Answer HITL approvals
Route a Viewport HITL gate's approvals to Console's inbox with one environment variable.
A HITL gate sends Console each approval it needs a human for. Console answers with a review the gate verifies, and the gated tool runs with the approved args.
Register the gate
viewport-console sources add hitl --name refunds --reply-url http://127.0.0.1:3000/hitl/console
# VIEWPORT_HITL_CONSOLE_URL=http://hsrc_...:[email protected]:7071?k=whpk_... (shown once)--reply-url is where the gated app serves gate.webhooks(). It must end in the channel's name (console by
default). Console never sends to link-local or cloud metadata addresses, and sends to a private or shared range
(10/8, 172.16/12, 192.168/16, 100.64/10, fc00::/7) only with --allow-private, for a gate on your LAN or tailnet;
loopback needs nothing. The host is checked when the source is added, and every send resolves it once, checks the addresses and
connects to the one it checked (so a name cannot be re-pointed between the check and the connect); a name that does
not resolve fails that send and is retried. The printed URL
carries the source id, the delivery secret and Console's public review key. Without a running Console it names the
configured address (127.0.0.1:7071 by default), and the CLI says so: start Console on that port, not
--port 0, before the gate sends to it.
// An admin registers the gate once (`viewport-console sources add hitl --name refunds --reply-url ...`).
const added = await app.sources.add({ kind: "hitl", name: "refunds", reply_url: `${gateUrl}/hitl/console` });
const consoleUrl =
"console_url" in (added.credentials ?? {}) ? (added.credentials as { console_url: string }).console_url : "";
process.env.VIEWPORT_HITL_CONSOLE_URL = consoleUrl; // the one setting the gated app needs, shown onceUse the console channel
const gate = new Gate(
{ rules: { refunds: { ask: "issue_refund", reason: "Refunds need a human" } } },
{
channels: [consoleChannel()],
receipts: path.join(workdir, "gate-receipts.jsonl"),
// Runs before args are stored or delivered; digests still cover the real args. A `[redacted]` marker lets every
// card say which value is hidden.
redact: (args) => ({ ...(args as Record<string, unknown>), card: "[redacted]" }),
},
);
const issueRefund = gate.tool({
name: "issue_refund",
input_schema: {
type: "object",
properties: { order_id: { type: "string" }, amount: { type: "number" }, card: { type: "string" } },
required: ["order_id", "amount"],
},
execute: async ({ order_id, amount }) => `Refunded $${amount} on ${order_id}`,
});- The gate signs deliveries with the delivery secret (HMAC). Console verifies them.
- Console signs reviews with an Ed25519 key that never leaves Console. The gate holds only the public key, so something that reads the app's environment can deliver requests but cannot forge answers.
- Reviews carry
by: console:<user>. Every message has a checkedtype, and a replay is a duplicate. - Status flows both ways. Console asks the gate for each pending item's status every minute. When a review POST
never arrived, the gate's
sweep()pulls it from Console. - The gate's
redacthook, and HITL's default redaction, decide what Console shows. A masked item cannot be edited, because an edit replaces the whole args.
Answer and verify
const refund = issueRefund({ order_id: "A-1002", amount: 900, card: "4242 4242 4242 4242" }); // waits for a human
const { token } = await app.tokens.create("finance-bot", ["read", "approve"]);
const vc = await connect({ url: listening.url, token });
for await (const item of vc.inbox.watch()) {
// Answer only this gate's refund; any other item (another gate, daemon or tool) waits for a person.
if (item.source.id !== added.source.id || item.action.tool_name !== "issue_refund") continue;
console.log(
`${item.source.name}: ${item.action.tool_name}`,
JSON.stringify(item.action.args),
`(${item.reason?.text})`,
);
console.log("Hidden by the", item.hidden_by, item.hidden, "| edit offered:", item.can_edit);
assert.deepEqual(item.hidden, { count: 1, paths: ["card"] });
assert.equal(item.can_edit, false);
// Approving without seeing a value is an explicit choice: without acknowledgeHidden, Console refuses (409).
console.log("Answer:", (await item.approve({ acknowledgeHidden: true })).outcome);
break;
}
console.log("Tool result:", await refund);const consoleChain = await vc.receipts.verify();
const gateChain = await verifyReceipts(fileReceipts(path.join(workdir, "gate-receipts.jsonl")).read());
console.log(`Console chain: ${consoleChain.ok ? "verified" : "broken"} (${consoleChain.count} entries)`);
console.log(`Gate chain: ${gateChain.ok ? "verified" : "broken"} (${gateChain.count} entries)`);From Python
The Python gate uses the same channel (viewport-hitl[sign], hitl.console(...)). Mount gate.webhooks(), an ASGI
app, where --reply-url points. This example starts its own Console, registers the gate, and answers from the inbox
over the HTTP API, which is what the web UI's Approve button sends:
# Sign in with the link `serve` printed ("Sign in: http://127.0.0.1:<port>/login#t=..."), as the browser does.
login = http("POST", f"{base}/api/v1/login", {"token": sign_in.split("#t=")[1]}, {"origin": base})
auth = {"authorization": f"Bearer {login['session']}", "origin": base}
# Register the gate, as Settings > Sources does; Console answers at the gate's /hitl/console.
reply_url = f"http://127.0.0.1:{gate_port}/hitl/console"
source = {"kind": "hitl", "name": "refunds", "reply_url": reply_url}
console_url = http("POST", f"{base}/api/v1/sources", source, auth)["console_url"] # VIEWPORT_HITL_CONSOLE_URLgate = hitl.Gate(HERE / "policies" / "refunds.yaml", channels=[hitl.console(url=console_url)])
@gate
async def issue_refund(order_id: str, amount: float) -> str:
return f"Refunded ${amount:g} on {order_id}"
# Console's signed answers arrive at gate.webhooks(), an ASGI app: mount it in your app under /hitl.
app = gate.webhooks(base_path="/hitl")
webhooks = uvicorn.Server(uvicorn.Config(app, port=gate_port, log_level="warning"))items: list[dict[str, Any]] = []
deadline = asyncio.get_running_loop().time() + 20 # never hang `make examples`
while not items:
if asyncio.get_running_loop().time() > deadline:
raise TimeoutError("No pending approval reached Console's inbox within 20 s")
items = (await asyncio.to_thread(http, "GET", f"{base}/api/v1/inbox?status=pending", None, auth))["items"]
await asyncio.sleep(0.1)
item = items[0]
print(item["action"]["tool_name"], item["action"]["args"], item["reason"]["text"])
answer = {"answer": "approve", "digest": item["digest"]} # the digest of exactly what was shown
await asyncio.to_thread(http, "POST", f"{base}/api/v1/inbox/{item['key']}/answer", answer, auth)uv run --project examples/python python examples/python/gate-in-console/main.pyPlain webhook channel
Gates that use HITL's webhook channel work too: register with --webhook and configure the channel with the
printed URL and secret. On that path one shared secret signs both directions, so Console's by is an assertion
anyone holding the secret could make. Prefer the console channel.
HITL stores
To see every approval, including ones never delivered to Console, register the gate's store read-only:
{ kind: "hitl_store", path } for SQLite or { dsn } for Postgres (needs the optional pg package). Listing is
filtered by tenant in the store's own query. Answering still goes through a channel.
For Postgres, give Console its own database role that can only read. Grant SELECT on HITL's approval and receipt
tables and nothing else; in particular, grant nothing on hitl_secrets (the store's redaction keys). Console never
needs that key: redacted values arrive already masked ([redacted hmac:...]) and are shown as stored. For SQLite,
Console opens the file read-only.