@buildanagent/harness 0.1.0-alpha.29 → 0.1.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,191 @@
1
+ /**
2
+ * `escalation()`: what the host does when a sandbox denies a command. Under `never` the denial goes back to the caller
3
+ * and nothing is written. Under `on-request`, and under `granular` where a rule allows it, the denial becomes a signed
4
+ * `approval_requested` entry, and once a person or a hook allows it, the command runs once more under the policy
5
+ * widened by exactly what the denial named. The widened policy is built here, on the host, from the signed record and
6
+ * the verified answer; no tool input or model output reaches it, and it lasts for that one rerun.
7
+ */
8
+ import { type Resolution, type SignedPendingRequest, type ToolResult } from "@buildanagent/sdk";
9
+ import type { Clock } from "@buildanagent/sdk/testing";
10
+ import { type Approvals } from "../session/approvals.js";
11
+ import { type EscalationRecord } from "../session/escalation-log.js";
12
+ import type { Session } from "../session/session.js";
13
+ import { type EscalationState, type EscalationTransition } from "./escalation-table.js";
14
+ import type { ApprovalPolicy, ExecResult, Sandbox, SandboxClient, SandboxDenial, SandboxPolicy, WorkspaceManifest } from "./types.js";
15
+ /**
16
+ * One rule of a `granular` policy: a denial of `kind` for `tool` may be asked about (`on-request`) or goes back to the
17
+ * caller (`never`). A rule with no `kind` or no `tool` matches every kind or every tool. The first rule that matches
18
+ * decides, and a denial no rule matches goes back to the caller.
19
+ */
20
+ export interface EscalationRule {
21
+ /** The kind of denial the rule covers. Left out, every kind. */
22
+ readonly kind?: SandboxDenial["kind"];
23
+ /** A tool's canonical name or alias, as the registry knows it. */
24
+ readonly tool?: string;
25
+ /** Whether a matching denial may become a request. */
26
+ readonly escalate: "on-request" | "never";
27
+ }
28
+ /** The options of `escalation()`. */
29
+ export interface EscalationOptions<H = unknown> {
30
+ /** When a denial may become a request: `on-request`, `granular` (by `granular`'s rules) or `never`. */
31
+ readonly approvalPolicy: ApprovalPolicy;
32
+ /**
33
+ * The approvals from `createApprovals()`. The escalation signs with their harness's signer, decides the rerun with
34
+ * their harness's permission pipeline, and lets their quorum policy decide each answer.
35
+ */
36
+ readonly approvals: Approvals<H>;
37
+ /** The rules a `granular` policy needs, and that any other policy refuses. */
38
+ readonly granular?: readonly EscalationRule[];
39
+ }
40
+ /** One command to run in a sandbox, for one tool call, and what the host provisions the sandbox with. */
41
+ export interface EscalationRun<H = unknown> {
42
+ /** The tool the command runs for, which the permission pipeline decides again before a rerun. */
43
+ readonly tool: string;
44
+ /** That tool call's input, as the pipeline sees it. It is recorded, so it needs a canonical JSON form. */
45
+ readonly input: unknown;
46
+ /** Who chose the call. Default `model`. */
47
+ readonly initiator?: "model" | "code";
48
+ /** The tool call's own id, recorded for the approver to see. */
49
+ readonly toolCallId?: string;
50
+ /** The executable and its arguments, with no shell. */
51
+ readonly command: readonly string[];
52
+ /** The working directory, relative to the workspace root. */
53
+ readonly cwd?: string;
54
+ /** Stops the command, and its rerun, after this long, as `Sandbox.exec()` does. */
55
+ readonly timeoutMs?: number;
56
+ /** The most bytes of each output stream to keep, as `Sandbox.exec()` does. */
57
+ readonly maxOutputBytes?: number;
58
+ /** The command's whole environment, from `spawnEnv()`. It is never recorded. */
59
+ readonly env: Readonly<Record<string, string>>;
60
+ /** Aborts the command. */
61
+ readonly signal: AbortSignal;
62
+ /** The backend `run()` provisions from when it is given no `sandbox`. */
63
+ readonly client: SandboxClient;
64
+ /** The workspace. Its root is recorded, and a rerun needs the same root. */
65
+ readonly manifest: WorkspaceManifest;
66
+ /** The policy the command runs under. It is recorded, and a rerun widens this record of it. */
67
+ readonly policy: SandboxPolicy;
68
+ /** A sandbox already provisioned with `policy`. Left out, `run()` provisions one and disposes it. */
69
+ readonly sandbox?: Sandbox;
70
+ /** The caller's identity. A request binds a MAC of it, so only the same value can resolve it. */
71
+ readonly hostContext?: H;
72
+ /** The clock of the entries and the signed request. Default the system clock. */
73
+ readonly clock?: Clock;
74
+ /** Makes the escalation's id and the ids of its entries and request. Default `crypto.randomUUID()`. */
75
+ readonly newId?: () => string;
76
+ }
77
+ /** The options of `EscalationMachine.resolve()`: where the rerun runs, which the log does not hold. */
78
+ export interface EscalationResolveOptions<H = unknown> {
79
+ /** The backend the rerun provisions a fresh sandbox from. */
80
+ readonly client: SandboxClient;
81
+ /** The workspace, whose root must be the recorded one. */
82
+ readonly manifest: WorkspaceManifest;
83
+ /** The rerun's whole environment, from `spawnEnv()`. */
84
+ readonly env: Readonly<Record<string, string>>;
85
+ /**
86
+ * Aborts the call and its rerun. A signal aborted when `resolve()` is called writes nothing. One aborted later, but
87
+ * before the answer is written, writes no answer and runs nothing, so the request still waits. One aborted after the
88
+ * answer is written only reaches the rerun, as `Sandbox.exec()` takes a signal, and the approval is spent.
89
+ */
90
+ readonly signal: AbortSignal;
91
+ /** The same host context the request was made with, when it bound one. */
92
+ readonly hostContext?: H;
93
+ /** Who asked. An approver equal to it is refused. */
94
+ readonly requesterId?: string;
95
+ /** The clock of the entries. Default the system clock. */
96
+ readonly clock?: Clock;
97
+ /** Makes the ids of the entries. Default `crypto.randomUUID()`. */
98
+ readonly newId?: () => string;
99
+ }
100
+ /**
101
+ * How an escalation call ended. `states` is the path it took through the transition table in this call. `result` is a
102
+ * tool result a tool can return to the model: the command's output, or why it did not run. The model reads it only
103
+ * when nothing was written, as under `never`; once a request exists, the rebuilt context leaves it out and the host
104
+ * reads it.
105
+ *
106
+ * - `ran`: the command finished without a denial. `rerun` is true when it was the approved rerun.
107
+ * - `denied`: the command did not run to an end the caller can use: a denial that went back with no request, a refused
108
+ * answer, the pipeline's deny, or a second denial on the rerun.
109
+ * - `awaiting_approval`: `pending` waits for an answer through `resolve()`. `widened` is the policy the rerun would get.
110
+ *
111
+ * `escalationId` names the escalation once it has a request; a denial that went back with no request has none.
112
+ * `denial` is what the backend refused, and `reason` is the sentence `result` carries.
113
+ */
114
+ export type EscalationResult = {
115
+ readonly status: "ran";
116
+ readonly exec: Extract<ExecResult, {
117
+ exitCode: number;
118
+ }>;
119
+ readonly rerun: boolean;
120
+ readonly escalationId?: string;
121
+ readonly states: readonly EscalationState[];
122
+ readonly result: ToolResult<unknown>;
123
+ } | {
124
+ readonly status: "denied";
125
+ readonly reason: string;
126
+ readonly denial?: SandboxDenial;
127
+ readonly rerun: boolean;
128
+ readonly escalationId?: string;
129
+ readonly states: readonly EscalationState[];
130
+ readonly result: ToolResult<unknown>;
131
+ } | {
132
+ readonly status: "awaiting_approval";
133
+ readonly escalationId: string;
134
+ readonly pending: SignedPendingRequest;
135
+ readonly denial: SandboxDenial;
136
+ readonly widened: SandboxPolicy;
137
+ readonly states: readonly EscalationState[];
138
+ readonly result: ToolResult<unknown>;
139
+ };
140
+ /** An escalation that waits for an answer: its id, its signed request and the record the request signs. */
141
+ export interface PendingEscalation {
142
+ /** The escalation's id, which its request names as its call id. */
143
+ readonly escalationId: string;
144
+ /** The signed request, to show the approver with the record. */
145
+ readonly request: SignedPendingRequest;
146
+ /** What the request signs: the tool and its input, the command, the workspace root, the policy and the denial. */
147
+ readonly record: EscalationRecord;
148
+ }
149
+ /** The machine `escalation()` returns. */
150
+ export interface EscalationMachine<H = unknown> {
151
+ /** The approval policy the machine was made with. */
152
+ readonly approvalPolicy: ApprovalPolicy;
153
+ /** The table every move follows. */
154
+ readonly transitions: readonly EscalationTransition[];
155
+ /**
156
+ * Runs a command in the sandbox. A command the backend does not deny ends `ran`, and nothing is written. A denial
157
+ * ends `denied`, with nothing written, unless the policy allows a request and the denial names one path or host that
158
+ * can be widened; then a signed `approval_requested` entry is written and the call ends `awaiting_approval`.
159
+ *
160
+ * Writing a request appends to the session, so under `on-request` and `granular` call it from host code outside a
161
+ * turn's tool step, as `invokeTool()` runs. Throws `invalid_escalation` for an input or host context with no
162
+ * canonical JSON form, before anything is written.
163
+ */
164
+ run(session: Session, run: EscalationRun<H>): Promise<EscalationResult>;
165
+ /**
166
+ * The escalations of the session that wait for an answer. The quorum policy is asked about each one with the answers
167
+ * written so far, and one it says has expired is left out. Listing writes nothing, so such an escalation stays in the
168
+ * log until it is answered: `resolve()` then writes the policy's denial, and it never reruns.
169
+ */
170
+ pending(session: Session): Promise<PendingEscalation[]>;
171
+ /**
172
+ * Answers one waiting escalation. The answer is checked before anything is written: the signature under a key in the
173
+ * ring, the bound host context, the call and the record. An allow must name its approver in `by`, and a classifier's
174
+ * allow (`by: "classifier:…"`) never approves a rerun; both are refused with nothing written. `by` is not covered by
175
+ * the request's signature, so the host sets it only after it has authenticated the approver. The answer is written,
176
+ * the quorum policy decides the answer, and an allow then goes through the permission pipeline again, so a deny rule
177
+ * added since the pause wins. The rerun runs once in a fresh sandbox under the recorded policy widened by exactly the
178
+ * recorded denial, and that sandbox is disposed after it. A second denial is the rerun's result.
179
+ *
180
+ * It first settles every escalation a crash left open: a rerun that started and has no result is never run again.
181
+ * Throws `approval_not_pending` for a request that does not wait, `approval_refused` for one that fails its check, an
182
+ * allow with no `by` or a classifier's allow, `approver_is_requester`, and `invalid_escalation` for a workspace with
183
+ * another root.
184
+ */
185
+ resolve(session: Session, resolution: Resolution, options: EscalationResolveOptions<H>): Promise<EscalationResult>;
186
+ }
187
+ /**
188
+ * Creates the escalation machine for a harness's approvals. Throws `invalid_escalation` for unusable options, and
189
+ * `approval_unavailable` when a policy that can ask has a harness with no signer.
190
+ */
191
+ export declare function escalation<H = unknown>(options: EscalationOptions<H>): EscalationMachine<H>;
@@ -0,0 +1,370 @@
1
+ /**
2
+ * `escalation()`: what the host does when a sandbox denies a command. Under `never` the denial goes back to the caller
3
+ * and nothing is written. Under `on-request`, and under `granular` where a rule allows it, the denial becomes a signed
4
+ * `approval_requested` entry, and once a person or a hook allows it, the command runs once more under the policy
5
+ * widened by exactly what the denial named. The widened policy is built here, on the host, from the signed record and
6
+ * the verified answer; no tool input or model output reaches it, and it lasts for that one rerun.
7
+ */
8
+ import { canonicalInputHash, createPendingRequest, verifyResolution, } from "@buildanagent/sdk";
9
+ import { HarnessError } from "../errors.js";
10
+ import { answersByRequest, approvalsBinding, checkAnswers, settled, } from "../session/approvals.js";
11
+ import { inCodeCallQueue, ioOf } from "../session/code-call.js";
12
+ import { ESCALATION_TOOL, escalationsOf, isEscalationRecord, waitingEscalations, } from "../session/escalation-log.js";
13
+ import { recordSessionStart } from "../session/runner.js";
14
+ import { ESCALATION_TRANSITIONS, nextEscalationState, } from "./escalation-table.js";
15
+ import { widenPolicy } from "./widen.js";
16
+ const POLICIES = ["on-request", "granular", "never"];
17
+ const KINDS = ["filesystem_read", "filesystem_write", "network"];
18
+ // The characters of each output stream the log keeps of a rerun. Even at six bytes a character, as JSON escapes a
19
+ // control character, two streams stay under the store's 64 KiB entry bound.
20
+ const STORED_CHARS = 4 * 1024;
21
+ const invalid = (message, cause) => new HarnessError("invalid_escalation", message, cause === undefined ? {} : { cause });
22
+ function checkRules(rules) {
23
+ if (!Array.isArray(rules) || rules.length === 0) {
24
+ throw invalid("a granular approval policy needs a non-empty list of escalation rules");
25
+ }
26
+ for (const rule of rules) {
27
+ const ok = (rule?.escalate === "on-request" || rule?.escalate === "never") &&
28
+ (rule.kind === undefined || KINDS.includes(rule.kind)) &&
29
+ (rule.tool === undefined || (typeof rule.tool === "string" && rule.tool !== ""));
30
+ if (!ok)
31
+ throw invalid(`an escalation rule is unusable: ${JSON.stringify(rule)}`);
32
+ }
33
+ }
34
+ /** Checks the options and returns the harness and quorum policy the approvals were made with. */
35
+ function bindingOf(options) {
36
+ if (!POLICIES.includes(options?.approvalPolicy)) {
37
+ throw invalid(`the approval policy must be on-request, granular or never, got ${String(options?.approvalPolicy)}`);
38
+ }
39
+ if (options.approvalPolicy === "granular")
40
+ checkRules(options.granular);
41
+ else if (options.granular !== undefined)
42
+ throw invalid("escalation rules apply only to a granular approval policy");
43
+ const binding = options.approvals === undefined ? undefined : approvalsBinding(options.approvals);
44
+ if (binding === undefined)
45
+ throw invalid("escalation() needs the approvals createApprovals() made");
46
+ if (options.approvalPolicy !== "never") {
47
+ if (binding.harness.signer === undefined) {
48
+ throw new HarnessError("approval_unavailable", "the harness has no signer, so no escalation could be asked");
49
+ }
50
+ if (binding.harness.pipeline === undefined) {
51
+ throw invalid("the harness has no permission pipeline, so no rerun could be decided again");
52
+ }
53
+ }
54
+ return binding;
55
+ }
56
+ const text = (body, isError, details) => ({
57
+ content: [{ type: "text", text: body }],
58
+ isError,
59
+ ...(details === undefined ? {} : { details }),
60
+ });
61
+ function walker(start) {
62
+ const states = [start];
63
+ return {
64
+ states,
65
+ step(event) {
66
+ states.push(nextEscalationState(states.at(-1), event));
67
+ },
68
+ end: (body) => ({ states, result: text(body, true) }),
69
+ };
70
+ }
71
+ const what = (denial) => `The sandbox refused a ${denial.kind.replace("_", " ")} of ${denial.target}: ${denial.reason}.`;
72
+ function clip(value, most = STORED_CHARS) {
73
+ return value.length <= most ? value : `${value.slice(0, most)}\n[output cut]`;
74
+ }
75
+ function execText(exec, keep) {
76
+ const signal = exec.signal === undefined ? "" : ` (${exec.signal})`;
77
+ return [`exit code ${exec.exitCode}${signal}`, keep(exec.stdout), keep(exec.stderr)].join("\n");
78
+ }
79
+ const ranResult = (exec, keep = (value) => value) => text(execText(exec, keep), exec.exitCode !== 0, {
80
+ exitCode: exec.exitCode,
81
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
82
+ });
83
+ /** Writes the escalation's result, which ends it: the model never reads it, and the host gets it back. */
84
+ async function writeResult(io, id, result, source) {
85
+ const first = result.content[0];
86
+ // The streams were clipped one by one already; this bounds the whole text, the exit line included.
87
+ const body = first?.type === "text" ? clip(first.text, 2 * STORED_CHARS + 256) : "";
88
+ await io.write(source === "command" ? "tool" : "harness", {
89
+ type: "tool_result",
90
+ callId: id,
91
+ tool: ESCALATION_TOOL,
92
+ content: [{ type: "text", text: body }],
93
+ isError: result.isError === true,
94
+ ...(result.details === undefined ? {} : { details: result.details }),
95
+ // A command's output, a backend's message or a quoted reason can carry instructions an attacker wrote; only the
96
+ // harness's fixed sentences can't.
97
+ trust: source === "fixed" ? "trusted" : "untrusted",
98
+ });
99
+ }
100
+ const INTERRUPTED = "The rerun stopped before its result was recorded, so it may have run. It is not run again.";
101
+ const NEVER_RAN = "The escalation stopped after its answer was written and before its rerun started, so it never ran.";
102
+ /** Settles each escalation a crash left open, by the crash rule: a started rerun is never run again. */
103
+ async function settleOpen(path, io) {
104
+ for (const record of path) {
105
+ if (record.result !== undefined || !(record.answered || record.started))
106
+ continue;
107
+ nextEscalationState(record.started ? "rerun" : "requested", "settled");
108
+ await writeResult(io, record.id, text(record.started ? INTERRUPTED : NEVER_RAN, true), "fixed");
109
+ }
110
+ }
111
+ async function hashable(value, what) {
112
+ try {
113
+ await canonicalInputHash(value);
114
+ }
115
+ catch (error) {
116
+ throw invalid(`the escalation's ${what} has no canonical JSON form`, error);
117
+ }
118
+ }
119
+ /** The fields of `fields` that are set, so an optional field left out is not written as `undefined`. */
120
+ function present(fields) {
121
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
122
+ }
123
+ /** Runs one command in a sandbox provisioned for it, and disposes that sandbox whatever happens. */
124
+ async function execIn(where, policy, command, run) {
125
+ const used = where.sandbox ?? (await where.client.provision(where.manifest, policy));
126
+ const { cwd, timeoutMs, maxOutputBytes } = command;
127
+ try {
128
+ return await used.exec(command.command, {
129
+ env: run.env,
130
+ signal: run.signal,
131
+ ...present({ cwd, timeoutMs, maxOutputBytes }),
132
+ });
133
+ }
134
+ finally {
135
+ // A sandbox the caller provisioned is the caller's to dispose.
136
+ if (where.sandbox === undefined)
137
+ await used.dispose();
138
+ }
139
+ }
140
+ const nameOf = (machine, tool) => machine.harness.registry.get(tool)?.canonicalName ?? tool;
141
+ /** Why a denial goes back with no request, or `undefined` when the policy allows one. */
142
+ function refusal(machine, denial, tool) {
143
+ if (machine.approvalPolicy === "never")
144
+ return "The approval policy is never, so no one was asked.";
145
+ if (machine.approvalPolicy !== "granular")
146
+ return undefined;
147
+ const rule = machine.rules.find((each) => (each.kind === undefined || each.kind === denial.kind) &&
148
+ (each.tool === undefined || nameOf(machine, each.tool) === nameOf(machine, tool)));
149
+ return rule?.escalate === "on-request"
150
+ ? undefined
151
+ : "No escalation rule lets the host ask about this, so no one was asked.";
152
+ }
153
+ /** The record a request signs, from the run and the denial: the host's facts, never the tool's input alone. */
154
+ function recordOf(machine, call, denial) {
155
+ const { toolCallId, cwd, timeoutMs, maxOutputBytes } = call;
156
+ return {
157
+ tool: nameOf(machine, call.tool),
158
+ input: call.input,
159
+ initiator: call.initiator ?? "model",
160
+ command: [...call.command],
161
+ ...present({ toolCallId, cwd, timeoutMs, maxOutputBytes }),
162
+ root: call.manifest.root,
163
+ policy: call.policy,
164
+ denial: { kind: denial.kind, target: denial.target, reason: denial.reason },
165
+ };
166
+ }
167
+ /** Writes the session's start if it lacks one, settles what a crash left open, then signs and writes the request. */
168
+ async function ask(machine, session, call, asked) {
169
+ const { harness } = machine;
170
+ const { record, widened, walk } = asked;
171
+ const io = ioOf(session, call);
172
+ const id = io.newId();
173
+ await recordSessionStart(harness, (origin, body) => io.write(origin, body), harness.model, await session.path());
174
+ await settleOpen([...escalationsOf(await session.path()).values()], io);
175
+ const reason = what(record.denial);
176
+ const pending = await createPendingRequest({
177
+ kind: "approval",
178
+ callId: id,
179
+ tool: ESCALATION_TOOL,
180
+ input: record,
181
+ reason,
182
+ ...present({ app: call.hostContext }),
183
+ }, harness.signer, { generateId: io.newId, now: () => new Date(io.clock.now()) });
184
+ await io.write("harness", { type: "approval_requested", request: pending, input: record });
185
+ walk.step("asked");
186
+ const body = `${reason} A person was asked to allow it once (request ${pending.id}).`;
187
+ return { status: "awaiting_approval", escalationId: id, pending, denial: record.denial, widened, ...walk.end(body) };
188
+ }
189
+ async function runCommand(machine, session, call) {
190
+ if (typeof call?.tool !== "string" || call.tool === "")
191
+ throw invalid("an escalation run needs the tool's name");
192
+ const walk = walker("sandboxed");
193
+ const exec = await execIn(call, call.policy, call, call);
194
+ if (!("denied" in exec)) {
195
+ walk.step("ran");
196
+ return { status: "ran", exec, rerun: false, states: walk.states, result: ranResult(exec) };
197
+ }
198
+ walk.step("denied");
199
+ const denial = exec.denied;
200
+ const widened = widenPolicy(call.policy, denial);
201
+ const why = refusal(machine, denial, call.tool) ??
202
+ (widened === undefined ? "The policy can't be widened to that, so no one was asked." : undefined);
203
+ if (why !== undefined || widened === undefined) {
204
+ walk.step("returned");
205
+ const reason = `${what(denial)} ${why}`;
206
+ return { status: "denied", reason, denial, rerun: false, ...walk.end(reason) };
207
+ }
208
+ const record = recordOf(machine, call, denial);
209
+ await hashable(record, "record");
210
+ if (call.hostContext !== undefined)
211
+ await hashable(call.hostContext, "host context");
212
+ return inCodeCallQueue(session, () => ask(machine, session, call, { record, widened, walk }));
213
+ }
214
+ /** Checks an answer against the waiting request before anything is written, and returns the escalation it answers. */
215
+ async function check(machine, path, resolution, options) {
216
+ const { harness } = machine;
217
+ const waiting = path.filter((record) => record.result === undefined && !record.answered && !record.started);
218
+ const byRequest = new Map(waiting.map((record) => [record.requested.request.id, record]));
219
+ checkAnswers(harness, byRequest, [resolution], options.requesterId);
220
+ const found = byRequest.get(resolution.requestId);
221
+ const refuse = (cause) => new HarnessError("approval_refused", `the request for escalation ${found.id} failed its check (${cause}), so nothing ran and nothing was written`);
222
+ if ("decision" in resolution && resolution.decision === "allow") {
223
+ // `by` is not signed, so the guard holds only as far as the host sets it truthfully; an allow that names no one
224
+ // is refused rather than read as a person's.
225
+ const by = typeof resolution.by === "string" ? resolution.by.trim().toLowerCase() : "";
226
+ if (by === "")
227
+ throw refuse("an allow that names no approver does not cover a sandbox rerun");
228
+ if (by.startsWith("classifier:"))
229
+ throw refuse("a classifier's allow does not cover a sandbox rerun");
230
+ }
231
+ const verified = await verifyResolution(found.requested.request, resolution, {
232
+ signer: harness.signer,
233
+ call: { callId: found.id, tool: ESCALATION_TOOL, input: found.requested.input },
234
+ ...present({ app: options.hostContext }),
235
+ });
236
+ if (!verified.ok)
237
+ throw refuse(verified.cause);
238
+ const record = found.requested.input;
239
+ if (!isEscalationRecord(record))
240
+ throw refuse("malformed");
241
+ const widened = widenPolicy(record.policy, record.denial);
242
+ if (widened === undefined)
243
+ throw refuse("not_widenable");
244
+ if (options.manifest?.root !== record.root) {
245
+ throw invalid("the rerun's workspace must have the root the escalation recorded");
246
+ }
247
+ return { found, record, widened };
248
+ }
249
+ /** Decides the call again with the pipeline, which writes the `permission_decision` the rerun starts after. */
250
+ async function decideAgain(machine, io, id, record, hostContext) {
251
+ // bindingOf() refused a harness without a pipeline for every policy that can ask.
252
+ const pipeline = machine.harness.pipeline;
253
+ return pipeline.decide({ callId: id, tool: record.tool, input: record.input, initiator: record.initiator }, { session: { append: (entry) => io.write("harness", entry) }, hostContext, entries: await io.session.path() });
254
+ }
255
+ /** Ends an escalation that will not rerun: writes the reason as its result and returns the denial. */
256
+ async function refuseRerun(io, checked, walk, reason) {
257
+ walk.step("refused");
258
+ const ended = walk.end(reason);
259
+ await writeResult(io, checked.found.id, ended.result, "quoted");
260
+ return {
261
+ status: "denied",
262
+ reason,
263
+ denial: checked.record.denial,
264
+ rerun: false,
265
+ escalationId: checked.found.id,
266
+ ...ended,
267
+ };
268
+ }
269
+ async function resolveQueued(machine, session, resolution, options) {
270
+ options.signal?.throwIfAborted();
271
+ const io = ioOf(session, options);
272
+ await settleOpen([...escalationsOf(await session.path()).values()], io);
273
+ const path = await session.path();
274
+ const checked = await check(machine, [...escalationsOf(path).values()], resolution, options);
275
+ const { found, record, widened } = checked;
276
+ const walk = walker("requested");
277
+ const outcome = await settled(machine.quorum, [found.requested], answersByRequest(path), [{ resolution }]);
278
+ // The check and the quorum policy may await, so an abort since the call began stops it here, before the answer is
279
+ // written: once it is, the approval is spent, and an abort then can only stop the rerun.
280
+ options.signal?.throwIfAborted();
281
+ for (const entry of outcome.records)
282
+ await io.write("user", { type: "approval_resolved", ...entry });
283
+ const answer = outcome.forRun[0];
284
+ if (answer === undefined) {
285
+ walk.step("waiting");
286
+ const body = `${what(record.denial)} The request waits for more answers.`;
287
+ const pending = found.requested.request;
288
+ return {
289
+ status: "awaiting_approval",
290
+ escalationId: found.id,
291
+ pending,
292
+ denial: record.denial,
293
+ widened,
294
+ ...walk.end(body),
295
+ };
296
+ }
297
+ if (!("decision" in answer) || answer.decision !== "allow") {
298
+ const why = ("reason" in answer ? answer.reason : undefined) ?? "denied";
299
+ return refuseRerun(io, checked, walk, `The rerun was not allowed: ${why}.`);
300
+ }
301
+ walk.step("allowed");
302
+ const decision = await decideAgain(machine, io, found.id, record, options.hostContext);
303
+ // A person allowed the rerun, so a question the pipeline would ask again doesn't stop it; a deny does.
304
+ if (decision.decision === "deny") {
305
+ return refuseRerun(io, checked, walk, `The permission policy now denies the call: ${decision.reason}`);
306
+ }
307
+ walk.step("started");
308
+ return rerun(io, checked, options, walk);
309
+ }
310
+ /** Runs the one rerun in a fresh sandbox under the widened policy, and writes its result. */
311
+ async function rerun(io, checked, options, walk) {
312
+ const id = checked.found.id;
313
+ let exec;
314
+ try {
315
+ exec = await execIn(options, checked.widened, checked.record, options);
316
+ }
317
+ catch (error) {
318
+ // The rerun started, so it gets a result and is never run again, and the caller still sees why it failed.
319
+ const reason = `The rerun failed: ${error instanceof Error ? error.message : String(error)}`;
320
+ await writeResult(io, id, text(reason, true), "quoted");
321
+ throw error;
322
+ }
323
+ walk.step("ran");
324
+ if ("denied" in exec) {
325
+ const reason = `${what(exec.denied)} This was the approved rerun, so no one is asked again.`;
326
+ const ended = walk.end(reason);
327
+ await writeResult(io, id, ended.result, "quoted");
328
+ return { status: "denied", reason, denial: exec.denied, rerun: true, escalationId: id, ...ended };
329
+ }
330
+ await writeResult(io, id, ranResult(exec, (value) => clip(value)), "command");
331
+ return { status: "ran", exec, rerun: true, escalationId: id, states: walk.states, result: ranResult(exec) };
332
+ }
333
+ /** The escalations that wait, less the ones the quorum policy says have expired. It writes nothing. */
334
+ async function pendingOf(machine, session) {
335
+ const path = await session.path();
336
+ const answers = answersByRequest(path);
337
+ const found = [];
338
+ for (const { id, requested } of waitingEscalations(path)) {
339
+ if (!isEscalationRecord(requested.input))
340
+ continue;
341
+ const verdict = await machine.quorum.evaluate(requested.request, answers.get(requested.request.id) ?? []);
342
+ if (verdict === "expired")
343
+ continue;
344
+ found.push({ escalationId: id, request: requested.request, record: requested.input });
345
+ }
346
+ return found;
347
+ }
348
+ /**
349
+ * Creates the escalation machine for a harness's approvals. Throws `invalid_escalation` for unusable options, and
350
+ * `approval_unavailable` when a policy that can ask has a harness with no signer.
351
+ */
352
+ export function escalation(options) {
353
+ const { harness, quorum } = bindingOf(options);
354
+ const machine = {
355
+ harness,
356
+ quorum,
357
+ approvalPolicy: options.approvalPolicy,
358
+ rules: options.granular ?? [],
359
+ };
360
+ return {
361
+ approvalPolicy: options.approvalPolicy,
362
+ transitions: ESCALATION_TRANSITIONS,
363
+ run: (session, call) => runCommand(machine, session, call),
364
+ pending: (session) => pendingOf(machine, session),
365
+ resolve(session, resolution, resolveOptions) {
366
+ return inCodeCallQueue(session, () => resolveQueued(machine, session, resolution, resolveOptions));
367
+ },
368
+ };
369
+ }
370
+ //# sourceMappingURL=escalation.js.map