Skip to content
pleach

Interrupts

Pause a turn for human approval — the `HumanInterrupt` envelope, response shapes, per-tool approval, and how interrupts compose with the stream.

An interrupt is a turn-level pause. A gated tool call waits inside the turn, the runtime emits a PendingInterrupt to the consumer, and the call proceeds only once a person decides.

See Stream events for interrupt.requested, interrupt.resolved and interrupt.timeout on the wire. See Durable pending interrupts for what a checkpoint keeps.

By default a paused turn does not survive a reload or a restart. A client that reloads records client_detached. After a restart the decision is still owed, but the turn does not continue. Durable gates are an experimental opt-in that parks the turn and serves the decision when the client re-submits the message.

Typical uses: approving a destructive tool call before it fires, reviewing a tool's result before the model reads it, and gating expensive operations behind a confirm step.

What gates a tool

Six settings decide whether a call waits for a person. Read them together: a tool can be gated by one and waived by another.

SettingWhere you set itWhat it gates
requiresApprovalThe tool definitionThat tool, under whatever name it's called by. Waits before the call runs.
interruptBeforeInterruptConfigThe tool names listed, matched exactly. Waits before the call runs.
interruptAfterInterruptConfigThe tool names listed, matched exactly. Holds the result until a decision, before the model reads it.
interruptOnInterruptConfigAny call your predicate returns true for. Decided per call, so no list can show it ahead of time.
approveFlaggedTools: falseInterruptConfigWaives requiresApproval only. Names in interruptBefore and interruptOn still gate.
durableGatesInterruptConfigNothing on its own. It changes how a gate the settings above raise waits: it parks the turn instead (experimental, opt-in).

A gated call fails closed. If no one can be asked, the predicate throws or the window closes unanswered, the call is refused, not run.

runtime.tools.listByApprovalRequired(bool) lists tools by this table. A tool counts as gated when its requiresApproval flag is set and not waived, or when interruptBefore or interruptAfter names it. runtime.tools.approvalCoverage() returns { gated, ungated, hasPredicateGate } by the same rule. The two return types, ApprovalListing and ApprovalCoverage, are exported from @pleach/core.

An interruptOn predicate decides per call, so it puts no tool in either list. When one is set, hasPredicateGate is true, and the lists don't tell the whole story. The lists read the interrupt config the runtime was built with. They can't see a gate your own tool executor raises.

How a pause works

Rules 1–4 apply to interrupts a node raises with config.interrupt(). Rules 5–10 describe how tool gates pause.

  1. Handle the non-answer. A node calls await config.interrupt(payload, opts) to pause where it stands. The call resolves with an InterruptOutcome and never throws.

    • status: "answered" carries approved (true for an approval or selection, false for a decline) and, for a question with an inputRequest, the chosen fields in value.
    • status: "unanswered" carries a reason: timeout, released, aborted, no-channel, subagent, deferred, invalid-payload or invalid-answer.

    Treat every unanswered outcome as no decision: never as approval, never as a choice. A stopped turn resolves a waiting interrupt as aborted at once, so put cleanup on config.abortSignal.

  2. Payloads must be strict JSON. A Date, Map, Set, BigInt, Symbol, function, undefined value, non-finite number, class instance, getter, cycle or sparse array resolves invalid-payload and is never shown. So does a payload over 16384 bytes of JSON. The card fields (subject, description, inputRequest) get the same check, and an inputRequest field named payload, __proto__, constructor or prototype is refused. What a person sees is a copy taken at the raise.

  3. An interrupt never re-runs the node. The node waits where it called config.interrupt(), so earlier work runs once and no model call is repeated or billed again. The wait lives in the process running the turn. If that process ends before a decision, the interrupt is released and nothing resumes it elsewhere. Put decision-dependent work after the await. opts.timeoutMs can shorten the decision window, never extend it.

  4. Raise in a stable order, within a bounded budget. If a throwing node is retried, its Nth config.interrupt() receives the earlier attempt's Nth outcome without asking again, when it asks the same question (same payload and card). A changed question is asked afresh. A refusal made before anything was raised (invalid-payload, subagent) is re-evaluated, not carried forward. Sort an unordered collection before raising in a loop over it. One run of a node makes at most 256 new raises across all attempts, and at most 8 may wait at once. Calls past either bound resolve no-channel.

  5. The call waits; nothing unwinds. A gated call awaits a decision inside the turn and is not re-run when the decision arrives. GraphInterrupt is exported as a standalone primitive, but the graph engine does not catch it. A node that throws it fails like any other thrown error, and the graph does not suspend.

  6. interruptBefore, interruptAfter and interruptOn are production gates. They name tool calls, not graph nodes. They pause plugin tools on createPleachRoute, createPleachAgent and createPleachRuntime, and calls made through runtime.executeTool on a SessionRuntime you construct. A tool served by your own tool executor is gated by that executor, which receives the onInterruptRequest bridge for the purpose.

  7. Gates fail closed. A throwing interruptOn predicate gates the call. A gated call is refused without running when:

    • it has no approval channel;
    • it runs inside a sub-agent, where nothing can answer it;
    • its request can't be raised;
    • its turn is stopped first.
  8. A decision window bounds the wait. An unanswered gate is released after 3 minutes by default; INTERRUPT_APPROVAL_TIMEOUT_MS changes it. The release is recorded as a policy decision (approval_window_expired). A turn that is stopped or disconnected while waiting records client_detached. Neither reads as the user's refusal.

  9. Only the turn's actor decides. A turn started with an actorId binds every gate it raises to that actor. See Who can decide.

  10. Payloads travel as JSON. A pending interrupt crosses a route body, an SSE frame and a checkpoint snapshot. Keep tool arguments to JSON-safe primitives, plain objects and arrays. Date, Map, Set, BigInt and functions lose information or fail.

A node reads the answer like this:

import type { InterruptOutcome } from "@pleach/core";

// Inside a node's execute(state, config):
const outcome: InterruptOutcome = await config.interrupt(
  { dataset: "assay-2026-10", rows: 1200 },
  { subject: "Run on this dataset?" },
);
if (outcome.status === "answered" && outcome.approved) {
  // go ahead
} else {
  // declined, or no decision: an "unanswered" outcome carries a reason
}
import {
  InterruptManager,
  InterruptScratchpad,
  GraphInterrupt,
} from "@pleach/core";
import type {
  HumanInterrupt,
  HumanResponse,
  PerToolApproval,
} from "@pleach/core";
Subpath@pleach/core/guestInterruptBus

Enabling interrupts

Pass InterruptConfig at runtime construction. It declares which tool calls pause the turn, by name (interruptBefore / interruptAfter) or by predicate (interruptOn):

import { SessionRuntime } from "@pleach/core";

const runtime = new SessionRuntime({
  storage: supabaseAdapter,
  userId:  "user_123",
  interrupt: {
    // Pause BEFORE these tools dispatch, for approval:
    interruptBefore: ["delete_file", "send_email", "execute_sql"],
    // Pause AFTER these tools complete, to review the result:
    interruptAfter: ["run_migration"],
    // Or gate dynamically on the tool call itself:
    interruptOn: (toolCall) => toolCall.name.startsWith("prod_"),
  },
});
InterruptConfig fieldTypePurpose
interruptBeforestring[]?Tool names that require approval before execution
interruptAfterstring[]?Tool names whose result waits for review before the model reads it
interruptOn(toolCall) => boolean ?Pause before execution when it returns true. It sees the call's arguments on both arguments and parameters

A tool named in both interruptBefore and interruptAfter pauses twice: once before it runs, once for its result. An approval the runtime already took covers the call's dispatch, never its result.

The same interrupt option is accepted by createPleachRoute, createPleachRuntime and createPleachAgent. On those three, the plugin-tool executor runs the gate itself, in front of each plugin tool's execute. For a multi-request HTTP deployment, pair it with a shared interruptResolver so the resolve request can settle a pause raised on the execute request.

Through createPleachRoutes or createPleachAgent, a gate pauses only on a turn that has a principal (your own resolveUserId). On any other turn the approval authority, on by default, refuses each gated call at once. See Who can decide.

A tool served by your own host executor (not a plugin tool) owns its own approval gate. When the interrupt config names such a tool, the plugin-tool executor logs one warning that its gate doesn't apply.

Reviewing a result: interruptAfter

interruptAfter pauses after a top-level plugin tool call runs, before its result reaches the model. The interrupt.requested envelope carries the result on toolCall.result. approvalMeta.gateType is "interrupt_after"; a before-pause reads "interrupt_before".

The call has already run, so a deny withholds its output but can't undo its side effects. Responding lists each decision's effect.

The reviewer sees a capped result. A result whose JSON is longer than 64,000 characters arrives as { truncated: true, chars, preview }, with the first 64,000 characters in preview. One that doesn't serialize arrives as { unserializable: true }. Approving still hands the model the full result. The result under review is never written into a checkpoint.

import { createPleachAgent, createInMemorySharedInterruptResolver } from "@pleach/core/quickstart";

const agent = createPleachAgent({
  context: process.env.OPENROUTER_API_KEY,
  db: myDurableStore,
  interrupt: { interruptBefore: ["code_exec", "fs_write"] },
  interruptResolver: createInMemorySharedInterruptResolver(),
});

createPleachRoute takes the same interrupt option. With it set, the route writes the turn's interrupt.requested, interrupt.resolved and interrupt.timeout frames into its streamed response body, so a body reader such as useChat sees the pause.

import { createPleachRoute } from "@pleach/core/quickstart";

export const POST = createPleachRoute({
  resolveUserId: (req) => myAuth.userIdFrom(req), // a verified credential
  interrupt: {
    interruptBefore: ["send_email"],
    interruptAfter: ["run_query"],
  },
});

The PendingInterrupt envelope

interrupt.requested carries a PendingInterrupt.

FieldTypeNotes
idstringThe id runtime.interrupts.resolve keys on
sessionIdstringThe session whose turn raised it
toolCallToolCallThe paused call. Its arguments (and parameters) are what it runs with if approved as is
toolCall.resultunknown?Present on an interruptAfter pause: the result under review
requestedAtDateWhen the pause was raised
status"pending" | "approved" | "rejected"
actorIdstring?The principal bound to decide it. See Who can decide
approvalMetaApprovalGateMeta?Gate provenance (label, risk, estimated cost), when recorded

Show toolCall.arguments in the approval UI, because that is what runs. When you fold the stream with applyStreamEvent, the call's tool part moves to approval-requested with those arguments as its input.

LangGraph-shaped types

HumanInterrupt, HumanResponse and PerToolApproval are exported so tooling that speaks LangGraph's interrupt() envelope can type its own payloads:

interface HumanInterrupt {
  action_request: {
    action: string;                      // e.g. "approve_tool_call"
    args:   Record<string, unknown>;     // tool args, context, justification
  };
  config: {
    allow_ignore:  boolean;              // skip + continue
    allow_respond: boolean;              // freeform response back to the LLM
    allow_edit:    boolean;              // user edits args before dispatch
    allow_accept:  boolean;              // approve as-is
  };
  description?: string;                  // human-readable why
}

They are types only. The runtime doesn't emit a HumanInterrupt, doesn't read its config flags, and decides on an ApprovalDecision (below), not a HumanResponse. If you build a HumanInterrupt for your own UI, disabling buttons whose config flag is false is your code's job.

Receiving an interrupt in the stream

for await (const event of runtime.executeMessage(sessionId, prompt, { actorId: userId })) {
  if (event.type === "interrupt.requested") {
    const decision = await showApprovalUI(event.interrupt);
    const receipt = runtime.interrupts.resolve(
      event.interrupt.id,
      decision,
      sessionId,           // settle it only if it is pending on this session
      { actorId: userId }, // the caller: must match the turn's actor
    );
    if (!receipt.handled) {
      // Not settled: unknown, already resolved, expired, another session's, or another actor's.
    }
  }
}

executeMessage yields interrupt.requested, interrupt.resolved and interrupt.timeout for approvals raised in the turn's own session, while the gated call waits. Each interrupt appears once, and another session's interrupts never appear. After runtime.interrupts.resolve, the next interrupt event is interrupt.resolved, then the turn continues from where it paused.

The waiting call emits tool.awaiting_approval with the same interrupt id, not tool.started. It gets tool.started only after an approving decision; a refused or expired call never does. createPleachRoute writes the waiting state to the event log as its own row. The runtime predicts the gate from its own approval settings: interruptBefore and tools that require approval. That holds on the graph's dispatch and on the client's own tool loop, which can announce a call before or after its gate is raised. If your own tool executor raises the gate, return true from expectsApproval(toolCall) in the interrupt config for that call, and its start is held too. A throw counts as true. Without it, that call still emits tool.started before its interrupt.requested.

If you also subscribe to the runtime's event bus and forward every stream event, you see each interrupt on both. Dedupe by interrupt id, or use createInterruptRelay, which already dedupes. A break out of the loop while a call waits returns once that wait ends; abort the turn to end it at once.

EventPayload
interrupt.requested{ interrupt: PendingInterrupt }
interrupt.resolved{ interruptId: string; decision: ApprovalDecision }
interrupt.timeout{ interruptId: string }

A gate whose decision window expires, or that a policy releases, arrives as interrupt.resolved with decision.approved: false, decision.decidedBy: "timeout-policy" and its decision.policyCode. Its durable row is interrupt.timeout. The stream's interrupt.timeout event fires only when the interrupt manager's own defaultTimeoutMs elapses.

runtime.interrupts.resolve is the canonical surface. The flat runtime.resolveInterrupt method remains callable but is @deprecated. See Facets for the facet migration, and runtime.interrupts.manager for direct access to the InterruptManager.

Responding

runtime.interrupts.resolve (and InterruptManager.resume, which it delegates to) consume an ApprovalDecision. The runtime branches on decision.approved:

interface ApprovalDecision {
  approved:           boolean;                  // approve or deny the paused call
  note?:              string;                   // optional freeform note
  modifiedArguments?: Record<string, unknown>;  // edited args, applied on approve
  acknowledgeIncompleteResult?: boolean;        // interruptAfter: approve a preview
}

On a pause before the call (interruptBefore, interruptOn):

IntentApprovalDecisionEffect
Approve as-is{ approved: true }Run the call with its original arguments
Approve with edits{ approved: true, modifiedArguments: {...} }Run it with the edits merged over the model's arguments
Deny{ approved: false }The call doesn't run. The model reads Tool call "<name>" was denied by user (plus : <note> when you pass one), and the turn continues

Edits are merged into a new object. An edit that sets __proto__, constructor or prototype is refused rather than applied in part.

When an edit is refused

resume checks an approval's edit before it settles anything. It refuses an approval whose modifiedArguments:

  • is not an object;
  • sets __proto__, constructor or prototype;
  • sets an argument the gated tool doesn't declare, when the tool's parameter schema names a closed set of arguments. A schema with no properties, or one that admits other keys with additionalProperties, names no closed set.

A key that only repeats the call's own value isn't an edit and is never refused. A refused decision settles nothing and records nothing. The interrupt stays pending, so the approver can answer again:

const receipt = runtime.interrupts.resolve(interruptId, {
  approved: true,
  modifiedArguments: { notAnArgument: 1 },
});
// receipt.handled       → false
// receipt.refused       → "edit_not_allowed"
// receipt.refusedReason → why, for the approver

refused and refusedReason are set only on a refusal. An unknown or already-resolved id also answers handled: false, with neither field. The HTTP route for a gate's decision answers a refusal with 422; a corrected POST then settles it. A 422 is not the 404 "Interrupt not pending" an unknown id gets.

{
  "error": "Edit not allowed",
  "interruptId": "…",
  "reason": "…"
}

On a pause after the call (interruptAfter), the call has already run, so a decision can only release or withhold its result:

IntentApprovalDecisionEffect
Approve{ approved: true }The result reaches the model unchanged
Deny{ approved: false }The result is withheld. The model reads the refusal text, marked that the call ran and its result was withheld
Approve with edits{ approved: true, modifiedArguments: {...} }Refused: an edit can't apply to a call that already ran, so the gate stays pending (see When an edit is refused). Edits that only repeat the arguments it ran with count as a plain approve
Approve a preview{ approved: true, acknowledgeIncompleteResult: true }The full result reaches the model, though the reviewer saw only a preview. See below

A preview needs an acknowledgement. When a result is too large to show whole (over 64,000 characters as JSON) or has no JSON form, the reviewer sees a marked preview instead: { truncated: true, chars, preview, requiresAcknowledgement: true } or { unserializable: true, requiresAcknowledgement: true }. A plain { approved: true } of a preview withholds the result, as a denial would. The model reads that the call ran and the approval didn't acknowledge the preview. Approve with acknowledgeIncompleteResult: true to hand the full result on anyway. The flag does nothing for a result shown in full, and it applies to interruptAfter only.

To tell a preview from a real result in your own review UI, use readIncompleteResultReview(toolCall.result). It returns { kind: "truncated", chars, preview } or { kind: "unserializable" } for a marked preview, and null for anything else. Release is still decided by the gate, not by your UI. It's exported from @pleach/core, and from @pleach/core/interrupt/incompleteResultReview for a browser component that shouldn't pull in the runtime.

import { readIncompleteResultReview } from "@pleach/core/interrupt/incompleteResultReview";

const review = readIncompleteResultReview(request.toolCall.result);
if (review !== null) {
  // Show the notice and an explicit "approve without the full result"
  // action that sends acknowledgeIncompleteResult: true.
}

An unanswered window or a stopped turn withholds the result the same way. A call named in interruptAfter whose result nobody could review (inside a sub-agent, with no approval channel, or once its turn has ended) is refused before it runs. If a reviewed call's tool throws, the model gets a generic failure, because the error text hasn't been reviewed either.

An approval-with-edit is approved: true plus modifiedArguments, not a separate response type. A payload that omits approved (for example an { type: "edit", args }-shaped object) leaves decision.approved === undefined, which the manager treats as a rejection.

const receipt = runtime.interrupts.resolve(interruptId, {
  approved: true,
  modifiedArguments: { ...originalArgs, dryRun: true },
});
// receipt.handled          → true when the pending interrupt was found and resolved
// receipt.resolvedDecision → echoes the decision payload on success
// receipt.interruptId      → always echoes the caller's argument

The resolve receipt

runtime.interrupts.resolve returns an InterruptResolveReceipt rather than a bare boolean. The receipt echoes the decision that was filed, so audit logs and plugin hooks can read it without re-querying the manager.

interface InterruptResolveReceipt {
  handled:           boolean;             // strict parity with the legacy boolean
  resolvedDecision?: ApprovalDecision;    // present when handled === true
  interruptId:       string;              // always echoes the argument
}

The receipt is always a truthy object, so callers that branched on the old boolean (if (result) ...) still behave correctly. Switch on receipt.handled for the original boolean semantics. The companion InterruptCancelReceipt (from runtime.interrupts.manager?.cancel(id)) and InterruptDestroyReceipt (from manager.destroy()) follow the same shape; see InterruptManager programmatic surface.

Who can decide

Breaking: the approval authority is on by default

createPleachRoutes and createPleachAgent build an approval authority unless you pass approvalAuthority: false. A paused call is then answered only by the turn's principal, presenting the one-time nonce the turn's own stream carried. A turn with no principal is headless: every gate it raises, interruptBefore tools included, is refused at once. Only your own resolveUserId names a principal; createPleachAgent without one uses the local identity, which does not count. To opt out, pass approvalAuthority: false.

The approval authority

With the authority on, a route-served approval works like this:

  1. The interrupt.requested frame on the turn's own response stream carries approvalNonce (64 hex characters) beside interrupt. The nonce is bound to the session, the interrupt and the turn's approver. Only that frame carries it.

  2. The resolve presents it in the request body:

    POST /sessions/:id/interrupts/:interruptId
    { "approved": true, "approvalNonce": "<the frame's approvalNonce>" }
  3. The request must come from the same user, as resolveUserId resolves it. A missing, wrong, reused or expired nonce, or another user, answers 404 {"error":"Interrupt not pending"}, exactly like an interrupt that isn't pending. Your resolver is never called and nothing is recorded.

  4. The nonce is spent when the resolve is accepted. A resolve your resolver doesn't settle (handled: false, or a refused edit) puts it back for the rightful answer.

  5. A nonce stays valid for 24 hours unless its interrupt ends sooner. An interrupt id raised again voids the earlier nonce.

A headless turn still writes the interrupt.requested frame, without a nonce. The runtime then settles the gate as { approved: false } with the note refused: nobody who can answer an approval is on this turn's stream, and the gated tool doesn't run.

Host setupTurn's approverA gated call
Your own resolveUserIdThe resolved userPauses; answered with the nonce
No resolveUserId (createPleachAgent falls back to the local identity)None: headlessRefused at once
approvalAuthority: falseNo nonce is issuedPauses; decided by the resolver alone
createPleachRoute on its ownNo authority unless you pass onePauses; no nonce

Opting out. approvalAuthority: false restores resolve-by-actor: no nonce is issued and no turn is refused. On createPleachAgent without resolveUserId, the install's local identity answers its turns' interrupts. A host interruptResolver receives each resolve with caller.approvalAuthority: "opted-out", so it can record that the answer wasn't bound to its turn's stream. A capability grant whose approver carries authority: "opted-out" records approval_authority: "opted-out" on its row.

Your own authority. createApprovalAuthority(options) from @pleach/core/quickstart builds one; pass it as approvalAuthority.

ApprovalAuthorityOptions fieldDefaultPurpose
approverOf(turn)The turn's principalWho may answer this turn's interrupts; undefined makes the turn headless
callerActorOf(caller, answering)caller.actorIdWho a resolve request acts as
ttlMs24 hHow long an unanswered nonce stays valid
maxPending4096Most nonces held at once; the oldest is dropped first
nonceStoreThis process onlyKeeps unanswered nonces across a restart. Requires approverKey
approverKey—The install's approver key, or a loader asked again until it gives a usable one

A single-user host that answers its own approvals gives the authority a fixed principal as both approver and answering actor. pleach dev does this with the person at the terminal. It honours PLEACH_DEV_INTERRUPT_BEFORE (comma-separated tool names) as its interruptBefore list, and it listens on 127.0.0.1 only, because every turn there is answered as that person.

import { createApprovalAuthority, createPleachRoutes } from "@pleach/core/quickstart";

const me = "operator@example.com";
const routes = createPleachRoutes({
  approvalAuthority: createApprovalAuthority({
    approverOf: () => me,
    callerActorOf: () => me,
  }),
});

Every request that reaches such a route answers as that person, so serve it only where nobody else can reach it.

Across a restart. Without a nonceStore, an unanswered nonce lives in the process that issued it. A resolve that reaches another process, or arrives after a restart, answers 404. An ApprovalNonceStore keeps the nonce and the approver only in hashed or keyed form, never in clear. Its remove(sessionId, interruptId) must answer synchronously with exactly true (it removed a record) or false (it held none), and only true spends the nonce. createApprovalAuthority throws APPROVAL_NONCE_STORE_REMOVE_UNANSWERED unless the store answers exactly false for a record nobody holds. While the approver key is unusable, no nonce is issued (the gated call is refused as on a headless turn) and none loaded from the store can be spent. See Approval nonces across a restart for the route-family options.

In the runtime: runtime.interrupts.resolve

runtime.interrupts.resolve(
  interruptId: string,
  decision: ApprovalDecision,
  sessionId?: string,
  caller?: { actorId?: string; requireActor?: boolean },
): InterruptResolveReceipt

Scoped to a session. Pass the session the caller was verified to own as sessionId. An interrupt pending on any other session answers handled: false, exactly like an unknown id. Omit it and the id alone decides.

A turn started with an actorId binds every gate it raises to that actor. createPleachRoute passes the non-empty resolveUserId value as the turn's actor, so only the user who sent the message can answer its approvals. Without resolveUserId, or when it returns an empty string, the turn carries no actor. Through createPleachRoutes or createPleachAgent such a turn is headless and its gates are refused, unless you pass approvalAuthority: false. Then, and on createPleachRoute on its own, its gates are scoped to the session only. Turns started through runtime.resume or runtime.resumeStream carry no actor either. The binding rides the pending entry (PendingInterrupt.actorId), listings, checkpoint snapshots and rehydration.

for await (const event of runtime.executeMessage(sessionId, prompt, { actorId: userId })) {
  // ...
}

// Later, from the request that carries the decision:
runtime.interrupts.resolve(interruptId, decision, sessionId, { actorId: userId });

resolve applies one rule, which interruptActorAdmits exports for your own listings:

  • A gate bound to an actor settles only when caller.actorId equals that actor. Any other caller, or one naming no actor, gets handled: false, exactly like an unknown id.
  • A gate with no actor settles for any caller, unless caller.requireActor is set. When the caller names an actor, the decision row records that caller as the person who decided. With no caller actor, the row names no person.
  • A refusal no person gave (nobody can be asked, the approver can't be named, or the answer couldn't be recorded) is written as a policy decision, never under the name of the person whose resolve triggered it.
  • A turn's stream shows only unbound interrupts and those bound to its own actor.

The createPleachRoutes interrupt route presents the request's resolveUserId value as the caller, so another user's resolve answers 404 "Interrupt not pending". With the approval authority on, the request must also present the nonce. Your resolver then receives the caller's actorId only, never the nonce.

A host that resolves a route's gates with its own runtime.interrupts.resolve call must pass { actorId } as the fourth argument, or the gate answers handled: false. With createInMemorySharedInterruptResolver, the onResolve(decision, caller) callback receives that caller. Pass it on to runtime.interrupts.resolve, and return the receipt (or false) so a refused caller leaves the registration in place for the rightful one.

An owner that can't be resolved is released at once. When a gate is raised while a turn runs whose owning session or principal the runtime can't tell, no scoped resolve could ever reach it. The bridge releases it immediately, unanswered, with policy code owner_unresolved and the note interrupt_owner_unresolved. The gated tool doesn't run.

Naming a reviewer: resolveGateReviewer

By default a gate is bound to the turn's own actor. Set resolveGateReviewer(request) in the interrupt config to bind it to someone else. The runtime's InterruptManager calls it once per raise, before the gate registers, so every gate raised through the manager is covered. The callback is synchronous and marked experimental.

interrupt: {
  interruptBefore: ["send_message"],
  resolveGateReviewer: ({ turnActorId, toolCall }) =>
    toolCall.name === "send_message" ? { reviewerId: supervisorOf(turnActorId) } : null,
}
The callback returnsThe gate
null, undefined, or no callbackBound to the turn's actor, as without the callback
{ reviewerId }Bound to reviewerId. If that is the same actor the call would be reviewed for, refused at once (self_review_refused)
{ reviewerId, selfReview: { reason } } with that same actorRefused (self_review_refused) unless the interrupt config sets allowSelfReview: true. With it, bound to that actor, with reason recorded on the interrupt.requested row
{ unavailable: true }, a throw, a promise, or anything it can't readRefused at once (reviewer_unresolved)

allowSelfReview is off by default, and only the boolean true turns it on. A refused gate is never left unbound and never registered. The runtime emits interrupt.requested, then interrupt.resolved with approved: false and the policy code, and the call doesn't run. The actor a call would be reviewed for is the turn's actor or the actor that raised the gate, checked disjunctively, so naming either one is a self-review. A reviewer named in a running turn that has no actor is refused too, since the runtime can't check it differs from the actor. Ids are compared exactly, with no trimming or case folding, so keep reviewerId and the turn's actor in one id space. The callback isn't asked about a "decision"-class request such as a plan choice, which belongs to the turn's own actor.

Binding only, for now

The callback decides who may answer and refuses a self-review. With the default approval authority, createPleachTurnRoutes still accepts an answer only from the turn's principal, using the turn's own nonce. No shipped route lets a named reviewer answer yet, so a gate bound to another reviewer ends unanswered as a policy release when its window closes. A host that raises gates through its own channel, without InterruptManager, isn't covered.

Released is not timed out

A gate can end unanswered two ways. Its window expires (policy code approval_window_expired or decision_window_expired), or a policy releases it before any window ran out:

Release policy codeWhy
client_detachedThe client stopped following the turn (it switched or reloaded the session, or its view unmounted), or the turn was stopped before a decision
bridge_capacity_evictedThe in-process approval bridge was full and released an older pending gate to make room
owner_unresolvedThe raising turn's owner could not be resolved (above)
headless_refusedNobody who can answer an approval was on the turn's stream
followup_auto_proceedA plan-choice question raised on a follow-up turn, one whose transcript already holds an earlier user message. See below
approval_unrecordedA person answered, but the answer couldn't be recorded, so the gate is released refused
self_review_refusedresolveGateReviewer named the same actor the call would be reviewed for — the turn's actor or the raiser's — with no self-review reason (above)
reviewer_unresolvedresolveGateReviewer threw, said no reviewer is available, or returned something unreadable (above)

Both kinds write the same durable interrupt.timeout row with hitl.kind: "no_answer" and decided_by: "policy". Outcome readers key on the policy code: hitlUnansweredOutcome(policyCode) returns "released" for the codes above and "timeout" otherwise. A consumer that switches exhaustively on HitlPolicyCode, or keys a Record<HitlPolicyCode, …>, must handle followup_auto_proceed. interruptProjection reports a released gate as resolution: "released", and a replay manifest records guards.hitlOutcome: "released". The model is told a policy released the approval, never that the user declined it.

A plan-choice question on a follow-up turn doesn't block the turn. The planner still raises the card, then settles it at once as { approved: false, decidedBy: "timeout-policy", policyCode: "followup_auto_proceed" } with the note "followup_auto_proceed". The turn continues as "let the assistant decide", and no window or timer is armed. A first turn keeps the full decision window. Because the user never answered, the runtime drops that decision instead of carrying it into the next turn's context. Where a decision record is narrated to the model, it reads as the assistant's choice, never the user's. @pleach/core exports both the note and the policy code.

Per-tool approval

The most common pattern. On the plugin-tool gate each gated call raises its own interrupt, so three gated calls in one round are three pending interrupts, each decided on its own. A queue UI lists them with runtime.interrupts.manager?.getPendingInterrupts() (or useChat().pendingInterrupts over the wire) and answers each by id:

function ApprovalQueue({ pending }: { pending: PendingInterrupt[] }) {
  return pending.map((p) => (
    <div key={p.id}>
      <h3>{p.toolCall.name}</h3>
      <pre>{JSON.stringify(p.toolCall.arguments, null, 2)}</pre>
      <button onClick={() => resolve(p.id, { approved: true })}>Approve</button>
      <button onClick={() => resolve(p.id, { approved: false })}>Reject</button>
      <button onClick={() => editThenResolve(p)}>Edit args</button>
    </div>
  ));
}

PerToolApproval (toolCallId, toolName, args, decision, editedArgs?) is an exported type for a UI that keeps its own queue state. The runtime doesn't produce or read it.

Example: a supervisor edits an advisory note before it publishes. An agent drafts a note for a client, and the tool that publishes it is gated. A supervisor changes the note's arguments and approves. Months later an examiner asks who approved the publication, and whether the text changed after approval.

  1. The runtime writes tool.awaiting_approval, then interrupt.requested. The request holds the call's arguments and the actor bound to decide.
  2. The supervisor edits and approves. The runtime writes interrupt.edited, which records two rows: the operator's arguments, then the effective arguments the tool received (Event log).
  3. tool.started is written only after that approving decision. A refused or unanswered gate never reaches it.
  4. Call getInterruptChain(client, chatId, toolCallId) from @pleach/core/query. It walks request to resolution and shows both argument sets (Query).

The chain names the supervisor only if your host passed an actor id. Without one, the row records a policy decision, not a person. Pleach records the decision. What a signature means, and the approver's own credential, are your firm's (Part 11 and ALCOA+).

Natural-language argument edits: rewriteToolArguments

rewriteToolArguments powers an edit box where the user types an instruction in prose and the runtime rewrites the paused call's arguments to match.

import { rewriteToolArguments } from "@pleach/core";

const result = await rewriteToolArguments(
  approval.toolName,
  approval.args,                 // the paused call's original arguments
  "make it a dry run and cap the limit at 10",  // the user's edit instruction
  { seam },                      // a ProviderSeam<"utility"> — the LLM that does the rewrite
);

runtime.interrupts.resolve(interruptId, {
  approved: true,
  modifiedArguments: result.args,
});

The rewrite runs on the utility call class, the cheapest rung in the family. It never throws. Every failure path resolves to the original arguments and a status you can branch on:

result.statusMeaningresult.args
successThe rewrite parsed and appliedThe rewritten arguments
fallback-no-modelNo seam was suppliedThe original arguments
fallback-empty-responseThe model returned nothingThe original arguments
fallback-parse-errorThe model's output didn't parse as JSONThe original arguments

A failed rewrite approves the call as-is rather than corrupting it. Override the prompt with a template (RewritePromptTemplate), or start from the exported DEFAULT_REWRITE_SYSTEM_PROMPT and DEFAULT_REWRITE_USER_MESSAGE.

React: useInterruptUI

@pleach/core/react ships useInterruptUI. It subscribes to the runtime's interrupt.{requested,resolved,timeout} events, tracks pending interrupts as React state, and routes each one to a caller-supplied handler component via renderActive(). Handlers are matched by interruptType (defaulting to the paused tool's name). The matched component receives the PendingInterrupt plus typed onResolve and onCancel callbacks.

import { useInterruptUI } from "@pleach/core/react";
import type { PendingInterrupt, SessionRuntime } from "@pleach/core";

// A handler renders one interrupt type. The plugin contract types
// `interrupt` as `unknown` (core stays React- and domain-free), so
// narrow it to `PendingInterrupt` to read the paused tool call.
function ApprovalHandler({
  interrupt,
  onResolve,
  onCancel,
}: {
  interrupt: unknown;
  onResolve: (decision: unknown) => void;
  onCancel: () => void;
}) {
  const { toolCall } = interrupt as PendingInterrupt;

  return (
    <Dialog open>
      <h2>Approve {toolCall.name}?</h2>
      <pre>{JSON.stringify(toolCall.arguments, null, 2)}</pre>
      {/* onResolve files an ApprovalDecision — approve as-is: */}
      <button onClick={() => onResolve({ approved: true })}>Approve</button>
      {/* approve with edited args: */}
      <button
        onClick={() =>
          onResolve({
            approved: true,
            modifiedArguments: { ...toolCall.arguments, dryRun: true },
          })
        }
      >
        Approve (dry run)
      </button>
      {/* onCancel rejects — shorthand for `{ approved: false }`: */}
      <button onClick={onCancel}>Reject</button>
    </Dialog>
  );
}

function ApprovalSurface({ runtime }: { runtime: SessionRuntime | null }) {
  const { renderActive } = useInterruptUI({
    runtime,
    handlers: [{ interruptType: "approvalRequired", component: ApprovalHandler }],
  });

  // Renders nothing until an interrupt arrives; accepts `runtime: null`.
  return <>{renderActive()}</>;
}

useInterruptUI owns the event wiring and resolve plumbing. onResolve forwards an ApprovalDecision to runtime.interrupts.resolve, and onCancel rejects the interrupt ({ approved: false }).

Per-tool dispatch configuration

When a batch of tool calls returns and some require approval, the runtime splits the batch so each tool is its own dispatch unit. This config drives the split:

interface PerToolDispatchConfig {
  alwaysInterrupt: string[];                 // names always paused
  neverInterrupt:  string[];                 // names always bypassed
  defaultBehavior: "interrupt" | "auto-approve";
}

A tool name in both lists resolves to neverInterrupt. Tools in neither list follow defaultBehavior. A single-tool batch short-circuits the dispatcher and runs as-is.

Programmatic envelope: InterruptRequest / InterruptDecision

The lower-level envelope the runtime publishes to the guest interrupt bus and that observer plugins consume. HumanInterrupt is the UI-shaped wrapper; InterruptRequest is the wire shape.

interface InterruptRequest {
  interruptId: string;
  toolCall: {
    id:           string;
    name:         string;
    parameters?:  Record<string, unknown>;
    arguments?:   Record<string, unknown>;
  };
  riskLevel: "low" | "medium" | "high";
}

interface InterruptDecision {
  approved:           boolean;
  note?:              string;                  // "always_allow" = session bypass
  modifiedArguments?: Record<string, unknown>; // edit action's new args
  acknowledgeIncompleteResult?: boolean;       // interruptAfter: approve a preview
}

Both shapes carry an index signature, so orchestrator-side variants with extra fields pass through unchanged.

Guest interrupt bus

A chat-scoped queue and decision store for sessions that pause on a server (for example a serverless function) and resolve on a browser. The package ships the bus interface and polling helpers; you wire the KV implementation.

import {
  setGuestInterruptStore,
  publishInterruptRequest,
  popInterruptRequest,
  recordInterruptDecision,
  waitForInterruptDecision,
  channelInterruptScope,
} from "@pleach/core/guestInterruptBus";

setGuestInterruptStore(myRedisBackedStore);

// Server stage:
await publishInterruptRequest(chatId, request);
const decision = await waitForInterruptDecision(request.interruptId, {
  timeoutMs: 5 * 60_000,
  intervalMs: 750,
});

// SSE endpoint:
const queued = await popInterruptRequest(chatId);

// Decision sink, for the chat the caller was authorized for:
const { accepted, reason } = await recordInterruptDecision(interruptId, decision, {
  scope: channelInterruptScope(chatId),
});

The GuestInterruptStore contract is get / setex / del / lpush / rpop / expire, which any Redis-shaped KV satisfies. Keys expire after 10 minutes.

Typed scopes. An interrupt id alone never authorizes a decision. Every active interrupt is marked with the scope that may decide it, and recordInterruptDecision accepts a decision only from a recorder presenting the same scope. A scope is an id plus the id space it belongs to.

HelperScopeMarked by
channelInterruptScope(chatId){ kind: "channel", id }: one chat's delivery queuepublishInterruptRequest
sessionInterruptScope(sessionId){ kind: "session", id }: a runtime sessionThe manager-backed bridge, for a gate raised under that session

Kind and id must both match, so a channel sink authorized for chat X never settles a gate raised for session X.

A bare-string scope no longer matches

A host that records with { scope: chatId } (a bare string) is refused with interrupt_scope_mismatch for every interrupt marked with a typed scope, and both publishInterruptRequest and the manager-backed bridge mark typed scopes. Pass channelInterruptScope(chatId) or sessionInterruptScope(sessionId). A bare string still matches only an interrupt marked with a bare string, and passing no scope matches only one marked unscoped: it is not a wildcard.

recordInterruptDecision(interruptId, decision, { scope, actor?, requireActor? }) returns { accepted, reason? }:

reasonWhy
interrupt_not_active_or_expiredThe id was never marked, already decided, or its TTL ran out
interrupt_scope_mismatchThe presented scope doesn't match the one the interrupt was marked with
interrupt_actor_mismatchThe interrupt is bound to an actor and actor isn't that actor, or requireActor is set and the interrupt has no actor

An accepted decision for an actor-bound interrupt is stored with the gate's actorId, and the waiting bridge applies only a decision that names it.

waitForInterruptDecision returns null on timeout or abort, and the caller picks the fail-safe. A null from a timeout means the user never decided in the window, so fail the turn closed (deny the gated action). A null from an abort means the user cancelled the parent turn, so let the abort propagate without surfacing a denial in the UI.

InterruptManager programmatic surface

The manager owns pending interrupts and the resolve-or-cancel plumbing.

MethodSignatureUse
shouldInterruptBefore(toolCall)booleanHonors interruptBefore list and interruptOn predicate
shouldInterruptAfter(toolCall)booleanHonors interruptAfter list
requestApproval(sessionId, toolCall, timeoutMs?)Promise<ApprovalDecision>Pause and emit interrupt.requested; resolves on resume
requestApprovalWithId(interruptId, sessionId, toolCall, timeoutMs?, …, actorId?)Promise<ApprovalDecision>Caller-supplied id, so an out-of-band resume from another request settles the same pending interrupt. The trailing optional arguments carry gate metadata and the bound actor
resume(interruptId, decision)InterruptResolveReceiptSubmit a decision; handled: false when the id is unknown
cancel(interruptId)InterruptCancelReceiptReject the pending promise with "Interrupt cancelled"; receipt echoes cancelled, toolCall, sessionId and state
destroy()InterruptDestroyReceiptTear down the manager; receipt carries cancelledCount and cancelledIds
getPendingInterrupts()PendingInterrupt[]Snapshot of every outstanding pause
getPendingInterrupt(id)PendingInterrupt | nullSingle lookup
snapshotPending()PendingInterruptSnapshot[]Serializable projection for checkpoints; see Durable pending interrupts
rehydrate(snapshots){ rehydratedIds, skippedIds }Re-register pending interrupts from a checkpoint after resume

Each receipt is a typed audit record. InterruptDecisionRecord captures the interrupt.requested to interrupt.resolved boundary on the audit ledger too; see Typed records.

The manager emits interrupt.timeout when its own defaultTimeoutMs fires (0, the default, arms no timer). The pending promise from requestApproval then rejects with the typed InterruptApprovalTimeoutError. Classify it with isInterruptApprovalTimeoutError(err) rather than matching the message. interrupt.timeout is a separate event from interrupt.resolved, so observability can tell a user no-op from a denial. That matters for the remedy: "approval expired, re-request" versus "approval denied, revise the plan".

The gate in front of plugin tools doesn't reject. When its decision window ends unanswered, it refuses the call with a policy decision (approval_window_expired), the tool doesn't run, and the turn continues with the refusal text as the call's result. Its durable row is interrupt.timeout with decided_by: "policy". A user's "Reject" writes interrupt.rejected with decided_by: "user".

Cross-request approval

requestApproval mints a fresh id and suits an in-process pause that resolves within one runtime lifetime. A durable, multi-request deployment needs the id up front, because the request that raises the interrupt and the request that resolves it are different processes.

requestApprovalWithId(interruptId, sessionId, toolCall, timeoutMs?) takes a caller-supplied id. Mint the id where you emit the interrupt to your remote client and persist it alongside the pending decision. An out-of-band resume(interruptId, decision) from any later request then settles the same promise. requestApproval is this method with a generated UUIDv7. A duplicate id that's still pending is rejected.

This is the seam a durable host wires into createPleachRoutes({ capabilities: { interruptResolver } }), so the route family resolves interrupts across requests. The option is interruptResolver on createPleachAgent, or capabilities.interruptResolver on createPleachRoutes. Pass createInMemorySharedInterruptResolver() for a process-local store, or your own store-backed DurableInterruptResolver. See the server route family for the option shape.

With the approval authority on (the default), the resolve must also spend the turn's nonce, and an authority holds its nonces in its own process unless it has a nonceStore. For a resolve in another process or after a restart, pass approvalNonceStore (with approverKey) to the default authority, or give your own authority a nonceStore. A resolver your authority already guards (authority.guardResolver(resolver)) names it (guardingAuthorityOf(resolver)), and the route family uses that authority. See Who can decide.

Durable pending interrupts

A pending interrupt is checkpointed when a checkpoint is written. The runtime stamps InterruptManager.snapshotPending() onto CheckpointMetadata.pendingInterrupts at each write: a user or assistant message, a finished tool call, a sub-agent result, a rollback and a new session. An approval owed at the last write is still owed after a restart or a time-travel restore.

Raising a gate also writes its own checkpoint. The write is stamped source: "interrupt" with writes: ["interrupt.requested"], and carries the pending interrupts, the pending tasks and the event-log cursor, so a gate raised since the last message is in a checkpoint rather than lost with the process.

Four limits on that write. It covers a gate the manager registered, so a refused gate isn't stamped. It needs a checkpointer; without one nothing is written. It is a probe, not a brake: it never throws, never delays the gate, and a write that fails is reported rather than retried. And nothing reads it to answer the gate, unless you opt in to durable gates. A resolve looks in memory only, so a restarted process still can't settle an owed gate — the checkpoint makes the gate recoverable state, not an answerable one. InterruptManager.rehydrate() stays explicit, and SessionRuntime doesn't call it for you.

The serialized shape is PendingInterruptSnapshot, exported from the root barrel:

import type { PendingInterruptSnapshot } from "@pleach/core";
FieldTypeNotes
idstringThe same id resolve keys on
sessionIdstringSession that owned the interrupt
toolCallToolCallThe paused tool call, without a result under interruptAfter review
requestedAtstringISO-8601, so a consumer can judge staleness
approvalMetaApprovalGateMeta?Gate provenance (label, risk, estimated cost), when recorded
actorIdstring?The bound actor, so a rehydrated gate is still decided only by its actor

Live resolve and reject callbacks and any armed timeout can't survive a process boundary, so they're excluded. So is a result under review (toolCall.result on an interruptAfter pause), which appears only on the live stream and in getPendingInterrupts().

After a resume, manager.rehydrate(metadata.pendingInterrupts) re-registers the entries. getPendingInterrupts() then reports them, and a late runtime.interrupts.resolve(id, decision) settles them. Rehydration is deliberately honest about what it can't restore:

  • No interrupt.requested re-emit, because the original process already recorded the request.
  • No timeout re-arm. The deadline may have passed during downtime, and auto-denying would manufacture a decision the user never made. Staleness is the consumer's call, and requestedAt is preserved for it.
  • The approved tool was never dispatched. Acting on a post-restart approval means re-driving the work with a fresh turn referencing the decision, not expecting the dead turn to continue.

Rehydration is idempotent. An id already pending, or a malformed snapshot entry, is skipped rather than overwritten, and the return value reports both sets.

A checkpoint is a copy of the pending list, and nothing in it marks a gate as decided later. Restoring a checkpoint written before a decision brings that gate back as owed, and it accepts a second decision. Check the decision rows on your event log before you act on an approval read from an older checkpoint.

Under the approval authority, a rehydrated gate is answerable over the route family only if its nonce survived too. The authority's nonceStore keeps unanswered nonces across a restart; without one the resolve answers 404.

Durable gates (experimental, opt-in)

InterruptConfig.durableGates is off by default. With it absent, every gate waits in the process, as described above. With it set, a gate your isDurable callback accepts parks its turn instead of waiting.

A durable gate behaves this way:

  1. The gate registers with no timer and is written to the raise checkpoint.
  2. The raise rejects with InterruptParkedError (carrying interruptId and messageId). The turn stops at its next boundary with no further model call. The stream ends with turn.completed and outcome gate-parked.
  3. A later decision on the gate is recorded in your GateReentryStore, keyed to the run: the session and the user message whose turn raised it.
  4. The client re-submits that same message. The new turn reaches the same gate and is served the recorded decision once.
const runtime = new SessionRuntime({
  interrupt: {
    durableGates: {
      isDurable: ({ toolCall }) => toolCall.name === "wire_transfer",
      windowMs: 15 * 60_000,
      store,       // your GateReentryStore
      subjectKeys, // read-side key access for the arguments digest
    },
  },
});

createInMemoryGateReentryStore is the reference store. It keeps decisions in process memory, so use your own store when decisions must outlive a restart.

The decision is served only when all of these hold:

  • Same run, tool, bound actor, request class and gate type.
  • The arguments match the recorded digest.
  • A person decided it inside the gate's window.
  • This caller wins the store's atomic consume.

Limits:

  • Not automatic resumption. Nothing continues the parked turn. The client must re-submit the message, and the turn runs again up to the gate.
  • Served once. A second retry of the same message, or a fork, raises a fresh gate.
  • Approval only on a call. A gate on a tool result review never parks, and neither does a gate with no finite window. Both wait in the process and log [Interrupt:durable-gate-downgraded].
  • No standing grant. The served decision never carries a grant or a result acknowledgement.
  • Expiry. A window that closed before the decision settles as a timeout-policy release with code durable_gate_expired. A late decision is never served.
  • Identical calls are numbered. Two calls with the same tool, bound actor and arguments in one batch get an occurrence number, from 0, in raise order within the turn. Each decision is served only to the call whose occurrence it was recorded for, so approving the second call never answers the first. Your store reads occurrence on a recorded decision and on the lookup. A record with none reads as 0. A malformed occurrence (negative, fractional or not a number) raises a fresh gate instead of being read as 0.
  • The reviewer is part of the record. A recorded reviewerRef is bound into the arguments digest. A store that swaps, adds or drops it makes the record unservable, and a store that digests without it fails closed.
  • Concurrent raises share one gate. Two raises of the same call and occurrence within one turn attach to the gate the first one parked, so the call doesn't park twice.
  • Retired records are written down. A record retired unserved, because it expired or was superseded, is listed in the retired field of the lookup's verdict. The runtime writes an interrupt.record_retired row for each, at audit severity. A database that applied the optional event-type constraint refuses that row until the constraint admits the type.
  • Retention is yours. The store must keep a record, and its consumed mark, at least until the gate's window ends.
  • A parked gate always has a window. ParkedGate.expiresAt is required. Every gate the manager parks has a finite window, and a stored marker without a parseable one is refused. On a recorded decision expiresAt stays optional, because a store may return it. A record without a window is malformed and never served.
  • Restore. A host that restores parked gates must call InterruptManager.rehydrate(snapshots, { sessionId }). Without that option the restored gates lose their parked marker and wait in the process.
  • Scope. Re-entry is pinned to the manager's tenant and to the gate's subject. multiTenant and multiSubject opt out.

Terminal writes to the event log

When the interrupt manager resolves an interrupt (approve, deny or edit), it writes a terminal event-log row carrying the resolution payload, including any edited args. That row is the boundary replay tools depend on. Replaying an interrupted turn from the event log re-establishes the same post-interrupt state without re-prompting the human.

For the row shape and the projections that fold these rows, see Event log and Event log projections.

Where to go next