HITL

Quickstart

Gate a refund tool, route large refunds to a person, approve one, and verify the audit trail.

Reading this on GitHub? The <include> tags below are filled in on docs.getviewport.com/hitl/quickstart; here, open the files they name in examples/python/refund-threshold and examples/ts/refund-threshold.

Status: Beta. Install from the registry:

npm install @viewportai/hitl        # TypeScript, Node 22 or later
pip install viewport-hitl           # Python 3.11 or later

To run the examples below, work from a clone. From source:

mkdir viewport && cd viewport
git clone https://github.com/viewportai/core.git
git -C core checkout ed0dabc   # the core version hitl 0.1.0 is tested against
git clone https://github.com/viewportai/hitl.git
(cd core && make setup-ts build-ts)
cd hitl && make setup build-ts

Python extras add optional pieces: slack (httpx), postgres (psycopg), sign (cryptography, for the Viewport Console channel's Ed25519 reviews), otel, and one per framework (langgraph, claude-agent-sdk, openai-agents, pydantic-ai); from the checkout, uv sync --inexact --project python --extra slack --extra sign installs some, and make setup installs all of them. In TypeScript the same pieces are subpath imports (@viewportai/hitl/slack, @viewportai/hitl/console, ...) with the frameworks as optional peer dependencies.

Run the examples

Run from a clone. You need uv (it provides Python 3.11+), git, make (on macOS: xcode-select --install), and for TypeScript Node 22.18 or later to build from source (the build tooling needs it; the runtime needs Node 22), with corepack. On Node 25 and later corepack is not bundled; make falls back to a pinned corepack from npm automatically (or run npm install -g corepack first). HITL builds against a core checkout next to it:

mkdir viewport && cd viewport
git clone https://github.com/viewportai/core.git
git -C core checkout ed0dabc   # the core version hitl 0.1.0 is tested against
git clone https://github.com/viewportai/hitl.git
(cd core && make setup-ts build-ts)
cd hitl && make setup build-ts

uv run --project python python examples/python/refund-threshold/main.py
(cd examples/ts/refund-threshold && node --experimental-strip-types --no-warnings main.ts)

This page walks through that example step by step. The blocks in steps 1 to 5 are excerpts of examples/python/refund-threshold/main.py and examples/ts/refund-threshold/main.ts; they build on each other and are not meant to run alone. The complete program at the end is the whole file.

1. Write the policy

Refunds up to $50 run on their own. Larger ones go to the support approver: the people listed in members, reached through the support-desk channel, with four hours to answer. Anything no rule mentions is denied.

policies/refunds.yaml
# Refunds up to $50 run on their own. Larger ones wait for someone on the support desk.
approvers:
  support:
    channel: support-desk
    members: ["desk:dana", "desk:omar"]
    timeout: 4h

rules:
  refunds: { allow: issue_refund }
  negative-refunds:
    deny: issue_refund
    when: { args: { amount: { lt: 0 } } }
    reason: A refund amount cannot be negative
  large-refunds:
    ask: issue_refund
    when: { args: { amount: { gt: 50 } } }
    approver: support
    reason: Refunds over $50 need a human

tests:
  - action: { tool: issue_refund, args: { order_id: A-1001, amount: 20 } }
    expect: allow
  - action: { tool: issue_refund, args: { order_id: A-1002, amount: 900 } }
    expect: { effect: ask, rules: [large-refunds] }
  - action: { tool: issue_refund, args: { order_id: A-1003, amount: -900 } }
    expect: { effect: deny, rules: [negative-refunds] }

The tests: block is checked by viewport-hitl test (see CLI).

2. Connect a channel

A channel shows an approval request to people and carries their answer back. Slack and signed webhooks ship with the package (Channels); here the support desk is your own channel, a few lines that turn each request into a ticket.

examples/python/refund-threshold/main.py (excerpt)
class SupportDesk:
    """Your own channel: every approval request becomes a ticket on the support desk."""

    name = "support-desk"

    def __init__(self) -> None:
        self.tickets: asyncio.Queue[hitl.ApprovalRequest] = asyncio.Queue()

    async def deliver(self, request: hitl.ApprovalRequest) -> str:
        self.tickets.put_nowait(request)
        return f"ticket-{self.tickets.qsize()}"
examples/ts/refund-threshold/main.ts (excerpt)
// Your own channel: every approval request becomes a ticket on the support desk.
const tickets: ApprovalRequest[] = [];
const supportDesk: Channel = {
  name: "support-desk",
  async deliver(request) {
    tickets.push(request);
    return { ref: `ticket-${tickets.length}` };
  },
};

3. Gate the tool

examples/python/refund-threshold/main.py (excerpt)
desk = SupportDesk()
gate = hitl.Gate(
    POLICY,
    channels=[desk],
    receipts=RECEIPTS,  # hash-chained JSONL audit log
    clock=FakeClock("2026-11-25T10:00:00Z"),
)


@gate
async def issue_refund(order_id: str, amount: float) -> str:
    """Refund an order."""
    return f"Refunded ${amount:g} on {order_id}"
examples/ts/refund-threshold/main.ts (excerpt)
const gate = new Gate(POLICY, {
  channels: [supportDesk],
  receipts: RECEIPTS, // hash-chained JSONL audit log
  clock: new FakeClock("2026-11-25T10:00:00Z"),
});

const issueRefund = gate.tool({
  name: "issue_refund",
  description: "Refund an order",
  input_schema: {
    type: "object",
    properties: { order_id: { type: "string" }, amount: { type: "number" } },
    required: ["order_id", "amount"],
  },
  execute: async ({ order_id, amount }) => `Refunded $${amount} on ${order_id}`,
});

The FakeClock keeps the example deterministic. Leave clock out in production.

4. Call it

A small refund is allowed by the policy and runs at once. Nobody is asked.

examples/python/refund-threshold/main.py (excerpt)
small = await issue_refund("A-1001", 20)  # policy allows it: runs now
examples/ts/refund-threshold/main.ts (excerpt)
const small = await issueRefund({ order_id: "A-1001", amount: 20 }); // policy allows it: runs now

A large refund waits. The ticket carries the approval id and the digest of the exact action under review; the person answering echoes the digest back, so an answer can never apply to different arguments. gate.respond records the answer, the waiting call wakes, re-checks the policy, consumes the approval and runs.

examples/python/refund-threshold/main.py (excerpt)
pending = asyncio.create_task(issue_refund("A-1002", 900))  # waits for the desk

ticket = await desk.tickets.get()  # approval_id, tool, args, reason, digest, ...
await gate.respond(ticket.approval_id, hitl.approve(by="desk:dana", digest=ticket.digest))

large = await pending
examples/ts/refund-threshold/main.ts (excerpt)
const pending = issueRefund({ order_id: "A-1002", amount: 900 }); // waits for the desk

const ticket = await nextTicket(); // { approval_id, tool, args, reason, digest, ... }
await gate.respond(ticket.approval_id, approve({ by: "desk:dana", digest: ticket.digest }));

const large = await pending;

5. Verify the receipts

Every decision, request, answer and execution was appended to the receipts file as a hash-chained entry. verify_receipts / verifyReceipts recomputes every digest and link. The count of 9 includes an operator_action entry the example appends before verifying (see Receipts).

examples/python/refund-threshold/main.py (excerpt)
result = await hitl.verify_receipts(hitl.FileReceipts(RECEIPTS).read())
print(f"receipts verified: {result.ok}, {result.count} entries")  # receipts verified: True, 9 entries
examples/ts/refund-threshold/main.ts (excerpt)
const result = await verifyReceipts(new FileReceipts(RECEIPTS).read());
console.log(`receipts verified: ${result.ok}, ${result.count} entries`); // receipts verified: true, 9 entries

The CLI does the same from a shell, and exits 1 at the first entry that was changed. The example prints receipts written to <path> and deletes its temporary folder at exit; run it with KEEP_RECEIPTS=1 to keep the file, then, from the clone:

uv run --project python viewport-hitl receipts verify <path>                               # Python
(cd examples/ts/refund-threshold && corepack pnpm exec viewport-hitl receipts verify <path>)   # TypeScript
ok: 9 receipts, head seq 9 sha256:...

From a package install the same command is viewport-hitl receipts verify <path> (Python) or npx @viewportai/hitl receipts verify <path> (TypeScript). The example then rewrites who approved the refund in a copy of the file, and both checks report that copy as broken.

The complete program

The whole example, which also checks its own outcome and tampers with a copy of the receipts to show verification fail. To run your own copy, make a new folder with the policy above saved as policies/refunds.yaml and this file as main.py or main.ts. From the viewport folder of Run the examples:

mkdir -p my-gate/policies && cd my-gate          # save policies/refunds.yaml and main.py / main.ts here
uv run --project ../hitl/python python main.py   # Python
npm init -y && npm pkg set type=module && npm install ../hitl/ts   # TypeScript: link the built package
node --experimental-strip-types --no-warnings main.ts
main.py
"""Refunds over $50 need a human. The agent's call waits while a person on the support desk approves it through
gate.respond, then every step is checked in the hash-chained receipts file, in code and with the CLI."""

from __future__ import annotations

import asyncio
import atexit
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

from viewportai import hitl
from viewportai.hitl.testing import FakeClock

POLICY = Path(__file__).parent / "policies" / "refunds.yaml"
SCRATCH = Path(tempfile.mkdtemp(prefix="hitl-refunds-"))
RECEIPTS = SCRATCH / "receipts.jsonl"
if not os.environ.get("KEEP_RECEIPTS"):  # KEEP_RECEIPTS=1 keeps the file to try the CLI on it
    atexit.register(shutil.rmtree, SCRATCH, ignore_errors=True)


# region desk
class SupportDesk:
    """Your own channel: every approval request becomes a ticket on the support desk."""

    name = "support-desk"

    def __init__(self) -> None:
        self.tickets: asyncio.Queue[hitl.ApprovalRequest] = asyncio.Queue()

    async def deliver(self, request: hitl.ApprovalRequest) -> str:
        self.tickets.put_nowait(request)
        return f"ticket-{self.tickets.qsize()}"
# endregion


# region gate
desk = SupportDesk()
gate = hitl.Gate(
    POLICY,
    channels=[desk],
    receipts=RECEIPTS,  # hash-chained JSONL audit log
    clock=FakeClock("2026-11-25T10:00:00Z"),
)


@gate
async def issue_refund(order_id: str, amount: float) -> str:
    """Refund an order."""
    return f"Refunded ${amount:g} on {order_id}"
# endregion


async def main() -> None:
    # region small
    small = await issue_refund("A-1001", 20)  # policy allows it: runs now
    # endregion
    assert small == "Refunded $20 on A-1001"
    assert desk.tickets.empty(), "a $20 refund never reaches a human"

    # region large
    pending = asyncio.create_task(issue_refund("A-1002", 900))  # waits for the desk

    ticket = await desk.tickets.get()  # approval_id, tool, args, reason, digest, ...
    await gate.respond(ticket.approval_id, hitl.approve(by="desk:dana", digest=ticket.digest))

    large = await pending
    # endregion
    assert ticket.reason == "Refunds over $50 need a human"
    assert ticket.args == {"order_id": "A-1002", "amount": 900}
    assert large == "Refunded $900 on A-1002"
    approval = await gate.get(ticket.approval_id)
    assert approval is not None
    assert approval.status == "approved"
    assert approval.decided_by == "desk:dana"
    assert approval.consumed_at, "the approval was used exactly once"

    # region operator
    # Things people do outside the gate go on the same chain: here a lead flags the refunded order for a follow-up.
    audit = hitl.ReceiptLog(hitl.FileReceipts(RECEIPTS))
    await audit.operator_action(action="order.flagged", target="A-1002", by="desk:omar")
    # endregion

    # region verify
    result = await hitl.verify_receipts(hitl.FileReceipts(RECEIPTS).read())
    print(f"receipts verified: {result.ok}, {result.count} entries")  # receipts verified: True, 9 entries
    # endregion
    assert (result.ok, result.count) == (True, 9)
    kinds = [json.loads(line)["kind"] for line in RECEIPTS.read_text().splitlines()]
    assert kinds == [
        *["decision", "executed"],  # $20: allowed by policy, then run
        *["decision", "approval_requested", "approval_response", "approval_decided"],  # $900: asked, answered
        *["decision", "executed"],  # re-checked at consume, then run
        "operator_action",  # the lead's flag
    ], kinds

    # The CLI checks the same file: exit 0 when the chain is intact.
    cli = [str(Path(sys.executable).parent / "viewport-hitl"), "receipts", "verify", str(RECEIPTS)]
    ok = await asyncio.to_thread(subprocess.run, cli, capture_output=True, check=False)
    assert ok.returncode == 0

    print(f"receipts written to {RECEIPTS}")

    # Rewrite history in a copy (someone else approved the $900 refund) and both checks fail on it.
    forged = SCRATCH / "tampered.jsonl"
    forged.write_text(RECEIPTS.read_text().replace('"by":"desk:dana"', '"by":"desk:omar"'))
    assert not (await hitl.verify_receipts(hitl.FileReceipts(forged).read())).ok
    cli[-1] = str(forged)
    tampered = await asyncio.to_thread(subprocess.run, cli, capture_output=True, text=True, check=False)
    assert tampered.returncode == 1
    assert "BROKEN at seq" in tampered.stderr + tampered.stdout

    print("refund-threshold: ok")


asyncio.run(main())
main.ts
// Refunds over $50 need a human. The agent's call waits while a person on the support desk approves it through
// gate.respond, then every step is checked in the hash-chained receipts file, in code and with the CLI.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
  type ApprovalRequest,
  approve,
  type Channel,
  FileReceipts,
  Gate,
  ReceiptLog,
  verifyReceipts,
} from "@viewportai/hitl";
import { FakeClock } from "@viewportai/hitl/testing";

const POLICY = join(import.meta.dirname, "policies/refunds.yaml");
const SCRATCH = mkdtempSync(join(tmpdir(), "hitl-refunds-"));
const RECEIPTS = join(SCRATCH, "receipts.jsonl");
// KEEP_RECEIPTS=1 keeps the file to try the CLI on it.
if (!process.env.KEEP_RECEIPTS) process.on("exit", () => rmSync(SCRATCH, { recursive: true, force: true }));

// #region desk
// Your own channel: every approval request becomes a ticket on the support desk.
const tickets: ApprovalRequest[] = [];
const supportDesk: Channel = {
  name: "support-desk",
  async deliver(request) {
    tickets.push(request);
    return { ref: `ticket-${tickets.length}` };
  },
};
// #endregion

// #region gate
const gate = new Gate(POLICY, {
  channels: [supportDesk],
  receipts: RECEIPTS, // hash-chained JSONL audit log
  clock: new FakeClock("2026-11-25T10:00:00Z"),
});

const issueRefund = gate.tool({
  name: "issue_refund",
  description: "Refund an order",
  input_schema: {
    type: "object",
    properties: { order_id: { type: "string" }, amount: { type: "number" } },
    required: ["order_id", "amount"],
  },
  execute: async ({ order_id, amount }) => `Refunded $${amount} on ${order_id}`,
});
// #endregion

// #region small
const small = await issueRefund({ order_id: "A-1001", amount: 20 }); // policy allows it: runs now
// #endregion
assert.equal(small, "Refunded $20 on A-1001");
assert.equal(tickets.length, 0, "a $20 refund never reaches a human");

// #region large
const pending = issueRefund({ order_id: "A-1002", amount: 900 }); // waits for the desk

const ticket = await nextTicket(); // { approval_id, tool, args, reason, digest, ... }
await gate.respond(ticket.approval_id, approve({ by: "desk:dana", digest: ticket.digest }));

const large = await pending;
// #endregion
assert.equal(ticket.reason, "Refunds over $50 need a human");
assert.deepEqual(ticket.args, { order_id: "A-1002", amount: 900 });
assert.equal(large, "Refunded $900 on A-1002");
const approval = await gate.get(ticket.approval_id);
assert.equal(approval?.status, "approved");
assert.equal(approval?.decided_by, "desk:dana");
assert.ok(approval?.consumed_at, "the approval was used exactly once");

// #region operator
// Things people do outside the gate go on the same chain: here a lead flags the refunded order for a follow-up.
const audit = new ReceiptLog(new FileReceipts(RECEIPTS));
await audit.operatorAction({ action: "order.flagged", target: "A-1002", by: "desk:omar" });
// #endregion

// #region verify
const result = await verifyReceipts(new FileReceipts(RECEIPTS).read());
console.log(`receipts verified: ${result.ok}, ${result.count} entries`); // receipts verified: true, 9 entries
// #endregion
assert.deepEqual([result.ok, result.count], [true, 9]);
const kinds = readFileSync(RECEIPTS, "utf8")
  .trim()
  .split("\n")
  .map((line) => JSON.parse(line).kind as string);
assert.deepEqual(kinds, [
  ...["decision", "executed"], // $20: allowed by policy, then run
  ...["decision", "approval_requested", "approval_response", "approval_decided"], // $900: asked, answered
  ...["decision", "executed"], // re-checked at consume, then run
  "operator_action", // the lead's flag
]);

// The CLI checks the same file: exit 0 when the chain is intact.
const bin = createRequire(import.meta.url)
  .resolve("@viewportai/hitl/package.json")
  .replace(/package\.json$/, "dist/bin.js");
const cli = (file: string) => {
  try {
    return {
      code: 0,
      out: execFileSync(process.execPath, [bin, "receipts", "verify", file], { encoding: "utf8", stdio: "pipe" }),
    };
  } catch (e) {
    const err = e as { status: number; stderr: string };
    return { code: err.status, out: err.stderr };
  }
};
assert.equal(cli(RECEIPTS).code, 0);

console.log(`receipts written to ${RECEIPTS}`);

// Rewrite history in a copy (someone else approved the $900 refund) and both checks fail on it.
const forged = join(SCRATCH, "tampered.jsonl");
writeFileSync(forged, readFileSync(RECEIPTS, "utf8").replace('"by":"desk:dana"', '"by":"desk:omar"'));
assert.equal((await verifyReceipts(new FileReceipts(forged).read())).ok, false);
const tampered = cli(forged);
assert.equal(tampered.code, 1);
assert.match(tampered.out, /BROKEN at seq/);

console.log("refund-threshold: ok");

async function nextTicket(): Promise<ApprovalRequest> {
  for (let i = 0; i < 1000; i++) {
    const t = tickets.shift();
    if (t) return t;
    await new Promise((r) => setImmediate(r));
  }
  throw new Error("no approval request reached the support desk");
}

Next

On this page