Skip to content

Commit c0eccec

Browse files
committed
fix(session): settle an approval whose delivery fails
A deliverer gives up waiting to observe a decision's acceptance only after it has handed the decision to the agent, so the reactor may still hold it, but a delivery that threw was never tracked for the rebuild settle. An interrupt then rebuilt with the call still parked and nothing to settle it, and the rebuilt agent answered it with "approval timed out" at the old deadline. A decision whose delivery throws is tracked like a handed-over one, whether it failed before or after the hand-over, since either way the call stays parked.
1 parent 0b3e4b7 commit c0eccec

4 files changed

Lines changed: 107 additions & 21 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,7 @@ tool call
411411
- **command** — Splits chained commands for security classification and derives command-shape approval scopes. Multi-segment chains only offer an exact-command persist pattern (a prefix like `npm *` must not cover `npm i && rm -rf /` later).
412412
- **auto-shell-policy** — Constrains `run_shell` even when auto mode would otherwise rubber-stamp it. Before matching, `expandShellSubjects` peels `bash`/`sh`/`zsh -c`, `xargs` utility tails, and transparent prefixes (`env`, `nice`, `timeout`, …) so rules see the real payload; an unparseable wrapper (variable expansion or command substitution) sets an opaque flag that forces `ask`. Effects: `deny` blocks outright (file mutations through ad-hoc tooling — output redirection, `tee`, `sed -i`/`perl -i`, interpreter inline programs or heredocs — which must instead go through `write_file`/`edit_file`); `ask` declines to auto-allow and falls through to the operator prompt (recursive `rm`, dependency installs and remote runners: npm/yarn/pnpm/bun, pip, cargo, go, brew, npx/bunx, …, force or uncontained `git worktree` ops, shell that references a sensitive path such as `.env` or a private key, and opaque wrappers). Contained non-force `git worktree add`/`remove`/`prune` and read-only `list` auto-allow (sibling destinations like `../corbits-dispatch-wts/…` included; absolute outside, `~`, globs, and credential basenames still ask). Deny beats ask when multiple subjects match. Quoted spans are stripped before pattern matching so a quoted `>` or install word in an argument is not flagged, and program names are matched only in command position. Adding a table category is a one-line rule append in `AUTO_SHELL_RULES`.
413413
- **gate** — Evaluates a call in order: catastrophic authorization denial, `skipPermissions`, then the normal tier, grant, and auto policies. Catastrophic commands remain denied under every mode. Skip mode, enabled for the process by `--dangerously-skip-permissions` or `--yolo` and persisted to the active settings source by TUI `/yolo` (machine-wide only for the default user-global source, not an explicit `--config` source), allows the call before normal policy evaluation. Therefore `--auto --yolo` behaves as yolo: auto-mode file-mutation asks and denials do not run. Otherwise, `allow`-tier passes; for `ask`-tier, the gate checks persisted approvals and then requests operator approval. Shell security classifies each chain segment (`||` / `&&` / `|` / `;` / newlines), but the operator is prompted once for the full command block — any unapproved segment fails the whole block, and execution always runs the unsplit original. Safe pipeline tails and pure shell no-ops (`true` / `false` / `:` and bare control-flow keywords stranded by chain-splitting) skip without a prompt. In a non-interactive run an unresolved `ask` becomes a denial. In auto mode: non-shell built-ins in `AUTO_ALLOWED_TOOLS` (writes/edits/deletes, `web_fetch`, `web_search`, `manage_tasks`, `spawn_agent`, `wait_agents`, …) auto-allow when not path-restricted; for `run_shell` the gate consults the auto-shell policy — a `deny` rule fails the call, an `ask` rule skips the auto-allow shortcut and proceeds to the normal approval flow, and anything unmatched is auto-allowed. Paths outside the workspace on path-arg tools are denied at authorize time (the same sandbox path-escape enforces at execution, so the gate does not show an Accept overlay that cannot succeed). Writes under the in-workspace session state root (legacy `.agent-state`) still ask under auto mode. Under process-only `--dangerously-skip-permissions` / `--yolo` or TUI `/yolo` persisted in the active settings source (machine-wide only for the default user-global source), the gate auto-allows those same cases, and pre-gate sandboxes (path-escape, shell session cwd retention, `list_dir` / `delete_file` workspace bounds) honor `getSkipPermissions()` live so outside-workspace access is not hard-denied after the gate already allowed it — without rebuilding the plugin stack. Static secret-guard denies for path-keyed tools and authorization hard blocks still apply. Sensitive shell references require approval in normal and auto modes, but skip mode allows them without approval after catastrophic authorization checks. Mutating MCP and unknown built-ins are not blanket-allowed outside skip. Newly granted scopes are appended in memory and persisted.
414-
- **Reactor-gated sessions (main session; `reactorGated: true`).** The gate's decision logic lives in one `decide()` used by both consumers: `evaluate()` (the middleware path below, still used by sub-agents) and `authorizeCall()`, which expresses the decision as the vendored reactor's before-tool authz effect (`src/permission/reactor-authorize.ts` bridges it into `env.authorize`). An `ask` there suspends the call as a reactor `PendingOperation` keyed by a correlationId (persisted through the context store's existing `pendingOperations`); `send()` settles as `suspended` and `src/session/approval-resume.ts` rebuilds the operator request from the approval snapshot, resolves it through the same `requestApproval` seam the TUI overlay uses, and delivers the decision to the reactor on the correlationId signal channel — an approved decision grants a one-shot bypass and the exact parked call re-dispatches; a rejected one answers it with an error result. Idle rebuild waits on three signals. `inFlight` occupancy keeps the TUI busy across the overlay until the correlated resume is accepted (`message.received` / `message.correlated`) or a generation bump `settleAll`s the waiter. The reactor's message-run bracket (`message.run.started` to `message.run.ended`) stays open while the parked run suspends and while the resumed tool and next inference execute, so a deferred reload (for example, MCP tools landing while the overlay is up) runs only after the run reaches `reply`, `wait`, or `done`. A decision delivered to a reactor that rehydrated the parked approval from disk resumes with no run open, so the TUI also holds rebuilds from that `message.correlated` until the reactor announces a terminal (`connector.reply`, a run end, the chat director's silent settle of a dropped approval, a fatal `reactor.error`, or `reactor.done`). Every agent build logs its reason (`initial`, `mcp-tools-changed`, `interrupt`, `session-rotation`). Delivery generation owns session identity: interrupt, `/clear`, and `/new` abort the outstanding overlay, skip minting a grant, drop the decision, and surface an operator notice rather than delivering the operator's decision into a rebuilt agent. A rebuild that keeps the session (interrupt, or an MCP tool-set reload) instead rejects each dropped approval its store still shows parked on the rebuilt agent, again on every such rebuild until the store shows the call closed, and the chat director commits that result without starting a turn. An operator decision handed to a reactor that closes before acting on it leaves its call parked the same way and is settled the same way. `/clear` and `/new` forget dropped approvals, since the new session never loads the old one's parked calls. Under reactor gating the middleware/MCP `gateToolCall` is an execution backstop, not a second copy of `env.authorize`: it consumes the `authorizeCall` verdict only when id, name, and arguments match, and does not re-decide. Deny still blocks and does not call `next`; an `ask` or `allow` skips the middleware prompt so an approved re-dispatch never re-asks. A reused `codex-proxy` id cannot apply an outer `shell` allow to an inner `run_shell` deny. Inner posix runs whose outer tool is not `run_shell` (Codex `apply_patch` proxy) never pass `env.authorize`, so `gateToolCall` decides on that cache miss and still blocks a deny. The headless denial and the stricter chained-command hard-deny are preserved as deny effects (upstream `block`s) decided inside the same `decide()`.
414+
- **Reactor-gated sessions (main session; `reactorGated: true`).** The gate's decision logic lives in one `decide()` used by both consumers: `evaluate()` (the middleware path below, still used by sub-agents) and `authorizeCall()`, which expresses the decision as the vendored reactor's before-tool authz effect (`src/permission/reactor-authorize.ts` bridges it into `env.authorize`). An `ask` there suspends the call as a reactor `PendingOperation` keyed by a correlationId (persisted through the context store's existing `pendingOperations`); `send()` settles as `suspended` and `src/session/approval-resume.ts` rebuilds the operator request from the approval snapshot, resolves it through the same `requestApproval` seam the TUI overlay uses, and delivers the decision to the reactor on the correlationId signal channel — an approved decision grants a one-shot bypass and the exact parked call re-dispatches; a rejected one answers it with an error result. Idle rebuild waits on three signals. `inFlight` occupancy keeps the TUI busy across the overlay until the correlated resume is accepted (`message.received` / `message.correlated`) or a generation bump `settleAll`s the waiter. The reactor's message-run bracket (`message.run.started` to `message.run.ended`) stays open while the parked run suspends and while the resumed tool and next inference execute, so a deferred reload (for example, MCP tools landing while the overlay is up) runs only after the run reaches `reply`, `wait`, or `done`. A decision delivered to a reactor that rehydrated the parked approval from disk resumes with no run open, so the TUI also holds rebuilds from that `message.correlated` until the reactor announces a terminal (`connector.reply`, a run end, the chat director's silent settle of a dropped approval, a fatal `reactor.error`, or `reactor.done`). Every agent build logs its reason (`initial`, `mcp-tools-changed`, `interrupt`, `session-rotation`). Delivery generation owns session identity: interrupt, `/clear`, and `/new` abort the outstanding overlay, skip minting a grant, drop the decision, and surface an operator notice rather than delivering the operator's decision into a rebuilt agent. A rebuild that keeps the session (interrupt, or an MCP tool-set reload) instead rejects each dropped approval its store still shows parked on the rebuilt agent, again on every such rebuild until the store shows the call closed, and the chat director commits that result without starting a turn. An operator decision handed to a reactor that closes before acting on it, or whose delivery fails or never sees its acceptance, leaves its call parked the same way and is settled the same way. `/clear` and `/new` forget dropped approvals, since the new session never loads the old one's parked calls. Under reactor gating the middleware/MCP `gateToolCall` is an execution backstop, not a second copy of `env.authorize`: it consumes the `authorizeCall` verdict only when id, name, and arguments match, and does not re-decide. Deny still blocks and does not call `next`; an `ask` or `allow` skips the middleware prompt so an approved re-dispatch never re-asks. A reused `codex-proxy` id cannot apply an outer `shell` allow to an inner `run_shell` deny. Inner posix runs whose outer tool is not `run_shell` (Codex `apply_patch` proxy) never pass `env.authorize`, so `gateToolCall` decides on that cache miss and still blocks a deny. The headless denial and the stricter chained-command hard-deny are preserved as deny effects (upstream `block`s) decided inside the same `decide()`.
415415
- **Approval resume identity.** Before opening the operator gate, resume captures the session generation and agent/store pair and resolves the correlation exactly once through `ContextStore.load().pendingOperations` to one approval operation's `suspendedCall.id`. Missing or duplicate mappings produce no gate or delivery; store errors propagate with registration cleanup. Every decision path first checks captured history for an exact-call approval timeout, and operator decisions check again after the gate. While the overlay is open, resume watches history for that exact-call timeout and aborts the overlay signal so the gate auto-denies, occupancy (`inFlight`) unsticks, and no late decision is delivered. Identical tool names and arguments never establish identity. Cancellation during lookup cannot deliver a rejection. This suppresses observed exact timeouts, not all expired correlations: the reactor removes correlation state before the queued timeout result publishes, and expiration can also race the final history check or TUI delivery queue. Atomic stale-decision admission remains reactor-owned work tracked separately in CL-8000.
416416
- **Worker reactor ownership.** `workerPermissionGate` is a reactor-gated view over the parent's live permission gate: grants and policy are shared, not copied or toggled. Worker posix plugins and inherited MCP tools are bound to that view at worker start, so they take the reactor-gated `gateToolCall` path because the view reports `isReactorGated()` — they do not close over the parent's middleware-gated `isReactorGated()`. Deny still blocks; ask/allow skip the middleware prompt. `authorizeCall` on the view never emits `ask` — unresolved approvals become denials that name the permission subject, without invoking an approval callback or suspending, even with an interactive parent; the parent can obtain a grant and retry. Worker control-plane tools (`submit_result`, `ask_director`, and nested fleet verbs other than `spawn_agent`) allow without a parent grant. Authorization and tool execution run under the same async-local worker identity and cwd. Fleet authority remains an independent restriction, not an alternative permission grant.
417417

‎e2e/reactor-approval-reload.test.ts‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ import {
2525
DROPPED_APPROVAL_SETTLED_EVENT,
2626
type DroppedApprovalCalls,
2727
} from "../src/agent/director.js";
28-
import { createQueuedApprovalDeliver } from "../src/tui/approval-delivery.js";
28+
import {
29+
ApprovalDeliveryTimeoutError,
30+
createApprovalDeliverer,
31+
createQueuedApprovalDeliver,
32+
} from "../src/tui/approval-delivery.js";
2933
import {
3034
createDeliveryGeneration,
3135
createSessionOperationQueue,
@@ -442,7 +446,12 @@ type InterruptPoint =
442446
/** After an approval, while it waits behind a busy session queue. */
443447
| "decision-queued"
444448
/** After the reactor accepted an approval, while its loop is busy. */
445-
| "decision-accepted";
449+
| "decision-accepted"
450+
/**
451+
* After an approval reached a busy loop but the deliverer gave up waiting
452+
* to observe its acceptance.
453+
*/
454+
| "acceptance-timed-out";
446455

447456
/**
448457
* Parks `call` on an ask, then interrupts at `opts.interruptWhile` (while
@@ -506,9 +515,20 @@ async function dropThenInterrupt(
506515
return queuedOp;
507516
},
508517
fatalBuildError: () => null,
509-
deliverer: {
510-
deliver: async (message) => live.session.agent.deliver(message),
511-
},
518+
deliverer:
519+
interruptWhile === "acceptance-timed-out"
520+
? createApprovalDeliverer({
521+
deliverToAgent: (message) => live.session.agent.deliver(message),
522+
acceptance: {
523+
wait: () => new Promise<void>(() => undefined),
524+
settle: () => undefined,
525+
abandon: () => undefined,
526+
},
527+
timeoutMs: 50,
528+
})
529+
: {
530+
deliver: async (message) => live.session.agent.deliver(message),
531+
},
512532
}),
513533
});
514534
claimFrom = resume;
@@ -530,7 +550,10 @@ async function dropThenInterrupt(
530550
ctx.approve();
531551
await queued;
532552
}
533-
if (interruptWhile === "decision-accepted") {
553+
if (
554+
interruptWhile === "decision-accepted" ||
555+
interruptWhile === "acceptance-timed-out"
556+
) {
534557
// A second message's held inference keeps the loop busy, so the close's
535558
// abort is served ahead of the accepted approval.
536559
void live.session.agent.send("Still there?").catch(() => undefined);
@@ -539,7 +562,12 @@ async function dropThenInterrupt(
539562
"second message's inference",
540563
);
541564
ctx.approve();
542-
expect(await handling).toBe(true);
565+
if (interruptWhile === "decision-accepted")
566+
expect(await handling).toBe(true);
567+
else
568+
await expect(handling).rejects.toBeInstanceOf(
569+
ApprovalDeliveryTimeoutError,
570+
);
543571
await waitFor(
544572
() => parkedEvents.some((e) => e.type === "message.correlated"),
545573
"approval accepted",
@@ -580,7 +608,8 @@ async function dropThenInterrupt(
580608
});
581609
releaseCallId?.();
582610
releaseBusy?.();
583-
expect(await handling).toBe(true);
611+
if (interruptWhile !== "acceptance-timed-out")
612+
expect(await handling).toBe(true);
584613
await awaitTail();
585614

586615
await waitFor(
@@ -1130,4 +1159,18 @@ describe("integration: an ask dropped by an interrupt, then settled on the rebui
11301159
},
11311160
20_000,
11321161
);
1162+
1163+
test.serial(
1164+
"an approval whose acceptance was never observed settles with no model turn",
1165+
async () => {
1166+
const reloaded = await dropThenInterrupt(
1167+
{ name: "run_shell", args: { command: CLOSED_PORT_PROBE } },
1168+
NATIVE_ANTHROPIC,
1169+
{ interruptWhile: "acceptance-timed-out" },
1170+
);
1171+
1172+
await expectSettledWithoutRunning(reloaded);
1173+
},
1174+
20_000,
1175+
);
11331176
});

‎src/session/approval-resume-interrupt.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,39 @@ describe("approval resume decisions a closing reactor never ran", () => {
480480
return { resume, oldAgentDelivered };
481481
}
482482

483+
test("an approval whose delivery failed before the hand-over is rejected on the rebuilt agent with no turn", async () => {
484+
const resume = createApprovalResume({
485+
resolveParkedCallId: () => "call-ask",
486+
getAgent: () => ({
487+
deliver: () => undefined,
488+
history: async () => [userTurn()],
489+
}),
490+
deliver: async () => {
491+
throw new Error("agent build failed");
492+
},
493+
gate: {
494+
resolveSuspended: async () => ({ allow: true }),
495+
} as unknown as PermissionGate,
496+
});
497+
await expect(resume.handle(SUSPENDED)).rejects.toThrow(
498+
"agent build failed",
499+
);
500+
expect(resume.status("corr-1")).toBe("idle");
501+
502+
await resume.prepareRebuild(parkedStore().storage);
503+
const rebuilt: InboundMessage[] = [];
504+
await resume.settleOn(
505+
{ deliver: (message) => rebuilt.push(message) },
506+
parkedStore().storage,
507+
);
508+
509+
expect(firstDeliveredContent(rebuilt)).toEqual({
510+
outcome: "rejected",
511+
message: APPROVAL_DROPPED_NOTICE,
512+
});
513+
expect(resume.droppedCalls.claim("call-ask")).toBe(true);
514+
});
515+
483516
test("an approval handed over but still parked in the rebuilt store is rejected there with no turn", async () => {
484517
const { resume, oldAgentDelivered } = handedOverResume();
485518
expect(await resume.handle(SUSPENDED)).toBe(true);

0 commit comments

Comments
 (0)