Approvals
The approval lifecycle, wait and suspend modes, consume, edits, expiry and who may answer.
Code blocks on this page are excerpts of tested programs; each block's title names its file in examples/, where the complete program runs.
When the policy says ask, the gate creates an Approval: a durable record bound to the action digest, with one
requirement per approver the matched rules named. It delivers the request to each approver's channel and records
every answer as a Review.
Lifecycle
pending
┌───────────┬───┴──────────┬───────────────┐
every approver any deny deadline cancel(reason)
approved (a veto) passed
│ │ │ │
approved denied expired cancelled
│
consume: same digest, current policy, limits, used oncependingis the only open status. Single use is a field (consumed_at), not a status.- Every transition is a compare-and-set on the record's
version. Two simultaneous answers cannot both win: the loser getsconflictwith the current approval. gate.respond(approval_id, review)is idempotent by review id (a Slack action id, a webhook id). A repeat returnsduplicateand never counts twice.- One deny ends the approval, whatever the quorum.
- A review is
rejectedwhen its author is not a listed member (hitl.not_a_member), approves their own action (hitl.self_approval, through theidentitiesresolver you give the gate), or echoes a digest other than the one under review. - Channels always send the digest the reviewer saw. A review passed to
gate.respondwithoutdigestbinds to the action under review right now, so a host UI must pass the digest it showed: otherwise an answer given on a page opened before an edit would count for the edited action. - If an
identitiesresolver fails (throws, returns nothing, or times out), the review is rejected (hitl.identity_unavailable); without a resolver, raw ids are compared.
respond returns a value, never an exception for these outcomes: accepted, duplicate, conflict, rejected
or not_found.
Who may answer
members on an approver is either a list of identities (["slack:U01ABC"]) or { permission: "<name>" }, which
hands the decision to your app: give the gate a reviewer, reviewer=fn / { reviewer: fn }, called as
fn(approver, identity, approval) where approver is { name, permission, members }. It returns true or false, sync
or async.
- With a list, a review needs list membership and, when a reviewer is set, the reviewer's yes.
- With a permission, the reviewer decides. A permission without a reviewer is a
PolicyErrorwhen the gate is built, never a runtime allow. - A reviewer that throws or times out (
reviewer_timeout_ms/reviewerTimeoutMs, 5 s) rejects the review (hitl.not_a_member). - Self-approval, digest and expiry checks run first, inside the gate.
# Who may approve a large refund is your app's decision, not a list in YAML: the gate asks your reviewer whether a
# person holds the `refunds.approve` permission.
approvers:
finance:
channel: desk
members: { permission: refunds.approve }
rules:
refunds: { allow: issue_refund }
large-refunds:
ask: issue_refund
when: { args: { amount: { gt: 50 } } }
approver: finance
reason: Refunds over $50 need finance
# Your directory: who holds which permission. Reviewers answer through the desk channel as `desk:<user>`.
PERMISSIONS = {"desk:dana": {"refunds.approve"}, "desk:omar": set[str](), "desk:sam": {"refunds.approve"}}
async def reviewer(approver: hitl.ApproverRef, identity: str, approval: hitl.Approval) -> bool:
if identity == "desk:ghost":
raise ConnectionError("directory unavailable") # fails closed: the answer is rejected
return approver.permission in PERMISSIONS.get(identity, set())
gate = hitl.Gate(
POLICY,
channels=[desk],
reviewer=reviewer,
identities={"desk:sam": "person:sam", "user:sam": "person:sam"}, # one person, two ids
clock=FakeClock("2026-11-25T10:00:00Z"),
)// Your directory: who holds which permission. Reviewers answer through the desk channel as `desk:<user>`.
const PERMISSIONS: Record<string, string[]> = {
"desk:dana": ["refunds.approve"],
"desk:omar": [],
"desk:sam": ["refunds.approve"],
};
const reviewer: Reviewer = async (approver, identity) => {
if (identity === "desk:ghost") throw new Error("directory unavailable"); // fails closed: the answer is rejected
return (PERMISSIONS[identity] ?? []).includes(approver.permission ?? "");
};
const gate = new Gate(POLICY, {
channels: [desk],
reviewer,
identities: { "desk:sam": "person:sam", "user:sam": "person:sam" }, // one person, two ids
clock: new FakeClock("2026-11-25T10:00:00Z"),
});Dana holds the permission; Omar does not; the directory fails for a third; Sam holds it but the refund is his own:
action = {
"tool": "issue_refund",
"args": {"order_id": "A-1002", "amount": 900},
"call_id": "call_1",
"actor": {"id": "user:sam"}, # the agent acts for Sam
}
async with trace() as t:
pending = await gate.authorize(action, wait=False)
assert pending.approval is not None
approval_id = pending.approval.id
results = [
await gate.respond(approval_id, hitl.approve(by="desk:omar")), # no permission
await gate.respond(approval_id, hitl.approve(by="desk:ghost")), # the reviewer raises
await gate.respond(approval_id, hitl.approve(by="desk:sam")), # has it, but it is Sam's own refund
await gate.respond(approval_id, hitl.approve(by="desk:dana")), # has the permission
]
assert [f"{r.status} {r.code}" if r.code else r.status for r in results] == [
"rejected hitl.not_a_member",
"rejected hitl.not_a_member",
"rejected hitl.self_approval",
"accepted",
]
run = await gate.authorize(action, wait=False) # "approved"
await run.succeeded()const action = {
tool: "issue_refund",
args: { order_id: "A-1002", amount: 900 },
call_id: "call_1",
actor: { id: "user:sam" }, // the agent acts for Sam
};
const { events } = await trace(async () => {
const pending = await gate.authorize(action, { wait: false });
const id = pending.approval?.id as string;
const results = [
await gate.respond(id, approve({ by: "desk:omar" })), // no permission
await gate.respond(id, approve({ by: "desk:ghost" })), // the reviewer throws
await gate.respond(id, approve({ by: "desk:sam" })), // has the permission, but it is Sam's own refund
await gate.respond(id, approve({ by: "desk:dana" })), // has the permission
];
assert.deepEqual(
results.map((r) => ("code" in r ? `${r.status} ${r.code}` : r.status)),
["rejected hitl.not_a_member", "rejected hitl.not_a_member", "rejected hitl.self_approval", "accepted"],
);
const run = await gate.authorize(action, { wait: false }); // "approved"
await run.succeeded();
});# A permission with no reviewer configured is refused when the gate is built, never allowed at runtime.
try:
hitl.Gate(POLICY, channels=[desk])
raise AssertionError("a permission without a reviewer must not load")
except hitl.PolicyError as e:
print(f"permission without a reviewer: {e.code}") # permission without a reviewer: hitl.policy_invalid// A permission with no reviewer configured is refused when the gate is built, never allowed at runtime.
try {
new Gate(POLICY, { channels: [desk] });
assert.fail("a permission without a reviewer must not load");
} catch (e) {
assert.ok(e instanceof PolicyError);
console.log(`permission without a reviewer: ${e.code}`); // permission without a reviewer: hitl.policy_invalid
}Each review records which requirement it satisfied (eligible_for), so a person who belongs to two approvers is
counted where they were eligible.
Wait and suspend
Wait (the gate default): the call creates the approval, delivers it and waits for a terminal status. The answer can come from the same process or from another one through the shared store. The quickstart's refund waits while the support desk answers:
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 pendingconst 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;Suspend: authorize(action, wait=False) (or mode="suspend" on the gate) returns pending at once. Your host
saves its state and stops. After someone answers, the host asks again for the same action and the gate finds the
same approval by its idempotency key (adapter, scope, call id and action digest), so nothing is delivered twice and
nothing waits in memory. Suspend mode needs a call id or a caller key; without one the gate refuses to guess
(hitl.key_required). Each framework guide shows the native version of this.
action = {"tool": "send_wire", "args": {"to": "ACME-002", "amount": 9_000}, "call_id": "call_2"}
auth = await gate.authorize(action, wait=False) # returns "pending" at once
assert auth.approval is not None
approval_id = auth.approval.id
clock.advance(FOUR_HOURS) # nobody answered
swept = await gate.sweep() # optional: expiry is also applied lazily on every read
late = await gate.respond(approval_id, hitl.approve(by="pager:kim")) # too late: "conflict", already expired
retry = await gate.authorize(action, wait=False) # status "expired", never runsconst action = { tool: "send_wire", args: { to: "ACME-002", amount: 9_000 }, call_id: "call_2" };
const auth = await gate.authorize(action, { wait: false }); // returns "pending" at once
const id = auth.approval?.id as string;
clock.advance(FOUR_HOURS); // nobody answered
const swept = await gate.sweep(); // optional: expiry is also applied lazily on every read
const late = await gate.respond(id, approve({ by: "pager:kim" })); // too late: "conflict", already expired
const retry = await gate.authorize(action, { wait: false }); // status "expired", never runsConsume: the last check
Right before the side effect, the gate consumes the approval:
- The args about to run must digest to the approved action (or to the approver's edit).
- The current policy is evaluated again with fresh facts. A deny wins (the policy changed, a limit filled, a grant
was revoked); new requirements send the approval back to
pending. - Limits are reserved.
consumed_atis set by compare-and-set. A second consume fails withhitl.already_used.
Allowed actions go through steps 1 to 3 as well. In the marketing example the resumed call consumes the approval and sends; the example then repeats the same call and the gate refuses it, because the approval was used.
sent = await send_campaign.tool.execute(args, call)const sent = await sendCampaign({ campaign: "spring-sale", audience: "all-customers" }, call);Edits
A rule with edits: true lets an approver approve different arguments (edited_args). The edit is a new action:
the policy evaluates it, and the tool runs with exactly the edited arguments, never the proposed ones.
first = await gate.authorize(discount(40, "call_1"), wait=False) # "pending"
ticket = inbox.requests[-1]
await gate.respond(
ticket.approval_id,
hitl.approve(by="sales:ana", digest=ticket.digest, edited_args={"order_id": "A-7", "percent": 25}),
)
run = await gate.authorize(discount(40, "call_1"), wait=False) # "approved"
await apply_discount(run.args) # {"order_id": "A-7", "percent": 25}: the edited args, never the proposed ones
await run.succeeded()const first = await gate.authorize(discount(40, "call_1"), { wait: false }); // "pending"
const ticket = inbox.at(-1) as ApprovalRequest;
await gate.respond(
ticket.approval_id,
approve({ by: "sales:ana", digest: ticket.digest, edited_args: { order_id: "A-7", percent: 25 } }),
);
const run = await gate.authorize(discount(40, "call_1"), { wait: false }); // "approved"
await applyDiscount(run.args); // { order_id: "A-7", percent: 25 }: the edited args, never the proposed ones
await run.succeeded();Declared secrets are always masked. This is the guarantee: declare a field secret and it is masked in every
channel delivery and every persisted approval, whatever its shape (scalars by value, objects and arrays whole).
Declare it in the tool's input schema ("x-viewport-secret": true; "writeOnly": true and "format": "password"
count too, at any depth) or in the policy with a top-level secrets: mapping tool patterns to JSONPaths over the
action, for example secrets: { "payments_*": ["$.args.card.number", "$.args.cvv", "$.args.headers[*].value"] }
(unioned across policy files; an invalid path is a load error). Paths use a subset of JSONPath: $, names (.card,
['card number']), indexes ([0]) and wildcards ([*], .*); recursive descent (..) and filters ([?(...)])
are not supported. The schema walker follows local $refs, every allOf / anyOf / oneOf branch, if / then /
else, items, prefixItems, contains, additionalProperties, patternProperties, unevaluatedProperties and
dependentSchemas; a remote or broken $ref masks the whole field. Framework adapters pass the tool's own schema
(zod, Standard Schema, JSON Schema) for this, never to validate. A custom redact function sees the declared masking
and cannot undo it: the gate applies it again afterwards. It receives every other value unmasked (the default rules do
not run before or after it), and a value it copies to a new key is not masked again, so keep secrets out of whatever it
adds. Only redact: false turns redaction off.
Reasons never show a masked value. When a rule cannot decide or does not match on a value the request masks, the
reason names the path, the operator and the value's type instead: args.card: gt could not be decided on a string (value masked).
Heuristics are defence in depth (best effort). On top of declared secrets, the gate masks what looks secret. Keys are normalized before matching:
camelCase and PascalCase are split (accessToken, APIKey), everything is lowercased, and any run of -, .,
spaces or _ becomes one _ (x.api.key, Api Key):
- Under a secret key, only a secret-shaped string is masked: 1 to 512 characters, no control characters, none of
$ ` ; | & < > ( ) { } \ ' ", and no whitespace except one space after a leadingBearer,BasicorToken. Anything else (free text, a command, a number) is shown, so an agent can never hide text from the approver under a key that looks secret; declare a field secret to mask it whatever it holds. Objects and arrays under secret keys are walked, so a nestedAuthorizationheader is masked too. The full list (after normalization):access_token,api_key,apikey,auth_token,authorization,aws_secret_access_key,client_secret,cookie,cvc,cvv,db_password,encryption_key,id_token,master_key,otp,passcode,passphrase,passwd,password,pin,private_key,private_key_pem,proxy_authorization,refresh_token,secret,secret_key,security_token,session_token,set_cookie,signing_key,token,x_api_key,x_auth_token. - Keys ending in
_password,_secretor_tokenfollow the same secret-shaped rule. - Secrets carried as data are treated as keys too: a
[name, value]pair, a{ name | key, value }record (HAR headers, Kubernetes-style env lists), and aNAME=valuestring (DB_PASSWORD=hunter2keepsDB_PASSWORD=and masks the value). - Under any key, a string that is entirely a credential (
Bearer <token>,sk-...,ghp_...,AKIA..., a JWT, a private key block) is masked, and a URL likehttps://user:pass@hostmasks only its password. A string that merely contains something token-like is shown: an approver always sees the command or account an agent chose.
Every card (terminal, Slack, and the request payload webhooks and Console receive as hidden) says when anything is
masked: "2 values hidden: card.number, headers[0].value" (up to five paths, then "and N more").
A masked value reads [redacted hmac:<12 hex>], an HMAC under the gate's redaction key, so approvers can tell values
apart without anyone being able to guess a short secret from it. Markers never affect digests: approvals bind the
unredacted args.
The redaction key. In production, set VIEWPORT_REDACT_KEY (shared with Viewport core's recorded tool calls, so a secret
reads the same marker in a trajectory and in an approval) from a secret manager (at least 32 bytes with at
least 16 distinct byte values: hex: plus 64 hex characters, base64:..., or a string of 32 or more characters), or pass
redact_key / redactKey: the gate derives one key per tenant from it and stores nothing. Generate one with
openssl rand -hex 32 and set VIEWPORT_REDACT_KEY=hex:<output>; a patterned or repeated key is refused
(hitl.config_invalid). VIEWPORT_HITL_REDACT_KEY still works as a deprecated alias (with a warning); setting both to
different values is hitl.config_invalid. With a shared store
(SQLite, Postgres) and no key, the gate refuses to start (hitl.config_invalid) rather than fall back silently.
For development, redactKey: "store" (in code only; the environment cannot choose it) keeps a per-tenant key in the store
(hitl_secrets) and logs a warning: anyone who can read that table could brute-force low-entropy masked values.
rotate_redact_key / rotateRedactKey(tenant) replaces a stored key (other processes pick it up within a minute;
older markers keep their form). Markers are stable within a tenant by design, so approvers can tell equal values
apart; the flip side is that someone who can trigger approval requests in a tenant can test guesses online, one visible
approval request per guess. The in-memory store needs no key: it uses a random one for the process. A custom
redact function, or redact: false, needs no key. Pass your own redact function to replace the default, or redact=False / redact: false to opt
out.
When the request shown to approvers was redacted (the gate's redact hook changed the args), the request carries
redacted: true and edits are refused (hitl.edits_redacted, recorded on the receipt chain, the approval stays
open): an approver cannot rewrite fields they cannot see. A rule opts in with edits: redacted. The edit must then
give a real value for every masked field: an edit that still contains a redaction marker is refused
(hitl.edit_touches_redacted, the approval stays pending), so a marker never runs in place of the secret. In the
Console example, card numbers are redacted; refunds refuse edits and card updates opt in:
# Dana cannot see the card, so she may not rewrite a refund's args...
edit = fake.review(second.id, second.action_digest, "msg_edit", edited_args={"order_id": "A-8", "amount": 30})
refused_edit = json.loads((await webhooks.dispatch(edit)).body)
print(f"refund edit: {refused_edit['status']} ({refused_edit['code']})")
# refund edit: rejected (hitl.edits_redacted)
# ...unless the rule opts in with `edits: redacted`, as card updates do.
card = await ask("update_card", {"customer_id": "C-1", "card": "4111111111111111", "limit": 500}, "call_3")
lower_limit = {"customer_id": "C-1", "card": "4111111111111111", "limit": 300}
ok = fake.review(card.id, card.action_digest, "msg_edit_card", edited_args=lower_limit)
accepted = json.loads((await webhooks.dispatch(ok)).body)
print(f"card edit: {accepted['status']}, approval {accepted['approval_status']}")
# card edit: accepted, approval approved// Dana cannot see the card, so she may not rewrite a refund's args...
const edit = await fake.review(second.id, second.action_digest, "msg_edit", {
edited_args: { order_id: "A-8", amount: 30 },
});
const refusedEdit = await (await webhooks(edit)).json();
console.log(`refund edit: ${refusedEdit.status} (${refusedEdit.code})`); // refund edit: rejected (hitl.edits_redacted)
// ...unless the rule opts in with `edits: redacted`, as card updates do.
const card = await ask("update_card", { customer_id: "C-1", card: "4111111111111111", limit: 500 }, "call_3");
const lowerLimit = { customer_id: "C-1", card: "4111111111111111", limit: 300 };
const ok = await fake.review(card.id, card.action_digest, "msg_edit_card", { edited_args: lowerLimit });
const accepted = await (await webhooks(ok)).json();
console.log(`card edit: ${accepted.status}, approval ${accepted.approval_status}`); // card edit: accepted, approval approvedAn edit cannot escape the policy. If the edited arguments hit a deny rule, the approval is denied; if they need
another approver, it stays pending until that approver answers.
third = await gate.authorize(discount(20, "call_6", "t-7"), wait=False)
assert third.approval is not None
result = await gate.respond(
third.approval.id,
hitl.approve(by="sales:ana", edited_args={"order_id": "A-7", "percent": 80}), # an edit the policy denies
)
print(f"edit to 80%: review {result.status}, approval {result.approval and result.approval.status}")
# edit to 80%: review accepted, approval deniedconst third = await gate.authorize(discount(20, "call_6", "t-7"), { wait: false });
const result = await gate.respond(
third.approval?.id as string,
approve({ by: "sales:ana", edited_args: { order_id: "A-7", percent: 80 } }), // an edit the policy denies
);
console.log(`edit to 80%: review ${result.status}, approval ${"approval" in result && result.approval.status}`);
// edit to 80%: review accepted, approval deniedRedeem
Adapters with a native approval step use gate.redeem(action) as their execution-time check. It consumes an
approval that already exists for this exact action and never creates one: arguments changed after approval are
refused with hitl.not_approved, without a new pending approval and without notifying anyone. Allowed actions still
pass and reserve limits.
# An execution wrapper (what adapters install) redeems right before the side effect. It never creates an approval.
fourth = await gate.authorize(discount(30, "call_7", "t-8"), wait=False) # "pending"
assert fourth.approval is not None
await gate.respond(fourth.approval.id, hitl.approve(by="sales:ana", edited_args={"order_id": "A-7", "percent": 20}))
tampered = await gate.redeem(discount(45, "call_7", "t-8")) # args changed after approval
print(f"tampered args: {tampered.status} ({tampered.code})") # tampered args: denied (hitl.not_approved)
redeemed = await gate.redeem(discount(30, "call_7", "t-8")) # the call that was approved
print(f"approved call: {redeemed.status}, runs with {json.dumps(redeemed.args)}")
# approved call: approved, runs with {"order_id": "A-7", "percent": 20}// An execution wrapper (what adapters install) redeems right before the side effect. It never creates an approval.
const fourth = await gate.authorize(discount(30, "call_7", "t-8"), { wait: false }); // "pending"
await gate.respond(
fourth.approval?.id as string,
approve({ by: "sales:ana", edited_args: { order_id: "A-7", percent: 20 } }),
);
const tampered = await gate.redeem(discount(45, "call_7", "t-8")); // args changed after approval
console.log(`tampered args: ${tampered.status} (${tampered.code})`); // tampered args: denied (hitl.not_approved)
const redeemed = await gate.redeem(discount(30, "call_7", "t-8")); // the call that was approved
console.log(`approved call: ${redeemed.status}, runs with ${JSON.stringify(redeemed.args)}`);
// approved call: approved, runs with {"order_id":"A-7","percent":20}Events
Each gated action emits approval events to the ambient sink (or the gate's sink): allowed or denied at once,
pending when a call suspends (with approval_id, decision: ask, rules and reason), and the terminal status
when it resumes, under the same approval_id. One ask yields at most one pending and one terminal event. Viewport
Evals reads the same events from trajectories: "asked" means decision: ask. The trace around the answers above holds exactly
two:
approvals: list[Any] = [e for e in t.events if e.type == "approval"]
one_id = len({e.approval_id for e in approvals}) == 1
print(f"approval events: {[e.status for e in approvals]}, one approval_id: {one_id}")
# approval events: ['pending', 'approved'], one approval_id: Trueconst approvals = events.filter((e: Event) => e.type === "approval") as unknown as {
status: string;
approval_id?: string;
decision: string;
}[];
console.log(
`approval events: ${approvals.map((e) => e.status).join(", ")}, one approval_id: ${new Set(approvals.map((e) => e.approval_id)).size === 1}`,
); // approval events: pending, approved, one approval_id: trueExpiry
Each approval has a deadline: the rule's or approver's timeout, else the gate's default_timeout (1 hour). Past
it, the approval is expired and on_timeout applies (deny by default). Expiry is applied lazily whenever the
approval is read, and gate.sweep() expires overdue approvals in bulk. Every timed wait sleeps on the gate's clock,
so a FakeClock moves four hours in a test with no real waiting:
call = asyncio.create_task(send_wire("ACME-001", 25_000)) # waits on the clock, not on a timer
await until(lambda: clock.pending > 0) # the gate is asleep until the deadline
clock.advance(FOUR_HOURS)
try:
await call
except hitl.ActionDenied as refused:
print(f"wire {refused.status}: {refused.message}") # wire expired: The approval request expired
assert refused.status == "expired"
else:
raise AssertionError("an expired approval must refuse the transfer")const call = sendWire({ to: "ACME-001", amount: 25_000 }); // waits on the clock, not on a timer
await until(() => clock.pending > 0); // the gate is asleep until the deadline
clock.advance(FOUR_HOURS);
const refused = await call.catch((e: unknown) => e);
assert.ok(refused instanceof ActionDenied);
console.log(`wire ${refused.status}: ${refused.message}`); // wire expired: The approval request expiredAn approved but unused approval also has a use_by deadline (the approver's timeout from the decision). Consuming
after it asks again, with the new approval linked through superseded_by.