@buildanagent/harness 0.1.0-alpha.28 → 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.
Files changed (113) hide show
  1. package/README.md +152 -5
  2. package/dist/context/file-spill.d.ts +11 -1
  3. package/dist/context/file-spill.js +23 -8
  4. package/dist/context/file-spill.js.map +1 -1
  5. package/dist/context/spill.d.ts +5 -1
  6. package/dist/context/spill.js +6 -2
  7. package/dist/context/spill.js.map +1 -1
  8. package/dist/credentials/addresses.d.ts +11 -0
  9. package/dist/credentials/addresses.js +41 -2
  10. package/dist/credentials/addresses.js.map +1 -1
  11. package/dist/credentials/allowlist.d.ts +22 -2
  12. package/dist/credentials/allowlist.js +74 -17
  13. package/dist/credentials/allowlist.js.map +1 -1
  14. package/dist/credentials/egress-policy.d.ts +69 -0
  15. package/dist/credentials/egress-policy.js +170 -0
  16. package/dist/credentials/egress-policy.js.map +1 -0
  17. package/dist/credentials/egress-proxy.d.ts +13 -1
  18. package/dist/credentials/egress-proxy.js +179 -11
  19. package/dist/credentials/egress-proxy.js.map +1 -1
  20. package/dist/credentials/git-route.d.ts +68 -0
  21. package/dist/credentials/git-route.js +288 -0
  22. package/dist/credentials/git-route.js.map +1 -0
  23. package/dist/credentials/index.d.ts +5 -1
  24. package/dist/credentials/index.js +5 -1
  25. package/dist/credentials/index.js.map +1 -1
  26. package/dist/credentials/scrub.d.ts +7 -0
  27. package/dist/credentials/scrub.js +22 -0
  28. package/dist/credentials/scrub.js.map +1 -1
  29. package/dist/errors.d.ts +14 -7
  30. package/dist/errors.js +13 -6
  31. package/dist/errors.js.map +1 -1
  32. package/dist/sandbox/base.d.ts +11 -1
  33. package/dist/sandbox/base.js +14 -0
  34. package/dist/sandbox/base.js.map +1 -1
  35. package/dist/sandbox/docker/index.d.ts +8 -2
  36. package/dist/sandbox/docker/index.js +63 -14
  37. package/dist/sandbox/docker/index.js.map +1 -1
  38. package/dist/sandbox/errors.d.ts +30 -2
  39. package/dist/sandbox/errors.js +36 -1
  40. package/dist/sandbox/errors.js.map +1 -1
  41. package/dist/sandbox/escalation-table.d.ts +38 -0
  42. package/dist/sandbox/escalation-table.js +95 -0
  43. package/dist/sandbox/escalation-table.js.map +1 -0
  44. package/dist/sandbox/escalation.d.ts +191 -0
  45. package/dist/sandbox/escalation.js +370 -0
  46. package/dist/sandbox/escalation.js.map +1 -0
  47. package/dist/sandbox/host-files.d.ts +2 -0
  48. package/dist/sandbox/host-files.js +10 -0
  49. package/dist/sandbox/host-files.js.map +1 -1
  50. package/dist/sandbox/index.d.ts +9 -4
  51. package/dist/sandbox/index.js +8 -3
  52. package/dist/sandbox/index.js.map +1 -1
  53. package/dist/sandbox/policy.d.ts +49 -0
  54. package/dist/sandbox/policy.js +149 -0
  55. package/dist/sandbox/policy.js.map +1 -0
  56. package/dist/sandbox/process.js +1 -1
  57. package/dist/sandbox/process.js.map +1 -1
  58. package/dist/sandbox/srt/index.d.ts +5 -2
  59. package/dist/sandbox/srt/index.js +27 -8
  60. package/dist/sandbox/srt/index.js.map +1 -1
  61. package/dist/sandbox/srt/settings.d.ts +17 -5
  62. package/dist/sandbox/srt/settings.js +53 -0
  63. package/dist/sandbox/srt/settings.js.map +1 -1
  64. package/dist/sandbox/types.d.ts +41 -4
  65. package/dist/sandbox/types.js.map +1 -1
  66. package/dist/sandbox/widen.d.ts +10 -0
  67. package/dist/sandbox/widen.js +150 -0
  68. package/dist/sandbox/widen.js.map +1 -0
  69. package/dist/session/approvals.d.ts +30 -1
  70. package/dist/session/approvals.js +12 -4
  71. package/dist/session/approvals.js.map +1 -1
  72. package/dist/session/code-call.d.ts +15 -1
  73. package/dist/session/code-call.js +2 -1
  74. package/dist/session/code-call.js.map +1 -1
  75. package/dist/session/escalation-log.d.ts +65 -0
  76. package/dist/session/escalation-log.js +84 -0
  77. package/dist/session/escalation-log.js.map +1 -0
  78. package/dist/session/rebuild.js +12 -3
  79. package/dist/session/rebuild.js.map +1 -1
  80. package/dist/testing/fake-sandbox.d.ts +21 -3
  81. package/dist/testing/fake-sandbox.js +157 -8
  82. package/dist/testing/fake-sandbox.js.map +1 -1
  83. package/dist/testing/sandbox-conformance.js +108 -1
  84. package/dist/testing/sandbox-conformance.js.map +1 -1
  85. package/dist/tools/builtins/bash.d.ts +9 -0
  86. package/dist/tools/builtins/bash.js +75 -0
  87. package/dist/tools/builtins/bash.js.map +1 -0
  88. package/dist/tools/builtins/builtins.d.ts +38 -0
  89. package/dist/tools/builtins/builtins.js +48 -0
  90. package/dist/tools/builtins/builtins.js.map +1 -0
  91. package/dist/tools/builtins/descriptions.d.ts +69 -0
  92. package/dist/tools/builtins/descriptions.js +94 -0
  93. package/dist/tools/builtins/descriptions.js.map +1 -0
  94. package/dist/tools/builtins/fetch.d.ts +12 -0
  95. package/dist/tools/builtins/fetch.js +157 -0
  96. package/dist/tools/builtins/fetch.js.map +1 -0
  97. package/dist/tools/builtins/files.d.ts +27 -0
  98. package/dist/tools/builtins/files.js +274 -0
  99. package/dist/tools/builtins/files.js.map +1 -0
  100. package/dist/tools/builtins/paths.d.ts +30 -0
  101. package/dist/tools/builtins/paths.js +62 -0
  102. package/dist/tools/builtins/paths.js.map +1 -0
  103. package/dist/tools/builtins/results.d.ts +15 -0
  104. package/dist/tools/builtins/results.js +31 -0
  105. package/dist/tools/builtins/results.js.map +1 -0
  106. package/dist/tools/builtins/search.d.ts +18 -0
  107. package/dist/tools/builtins/search.js +217 -0
  108. package/dist/tools/builtins/search.js.map +1 -0
  109. package/dist/tools/index.d.ts +6 -2
  110. package/dist/tools/index.js +5 -2
  111. package/dist/tools/index.js.map +1 -1
  112. package/llms.txt +52 -0
  113. package/package.json +5 -5
@@ -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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"escalation.js","sourceRoot":"","sources":["../../src/sandbox/escalation.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EAIpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EAEZ,OAAO,GACR,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAW,eAAe,EAAE,IA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C,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;QAC1G,IAAI,OAAO,KAAK,SAAS;YAAE,SAAS;QACpC,KAAK,CAAC,IAAI,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAc,OAA6B;IACnE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IAC/C,MAAM,OAAO,GAAe;QAC1B,OAAO;QACP,MAAM;QACN,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,KAAK,EAAE,OAAO,CAAC,QAAQ,IAAI,EAAE;KAC9B,CAAC;IACF,OAAO;QACL,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,WAAW,EAAE,sBAAsB;QACnC,GAAG,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;QAC1D,OAAO,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC;QACjD,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,cAAc;YACzC,OAAO,eAAe,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC,CAAC;QACrG,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `escalation()`: what the host does when a sandbox denies a command. Under `never` the denial goes back to the caller\n * and nothing is written. Under `on-request`, and under `granular` where a rule allows it, the denial becomes a signed\n * `approval_requested` entry, and once a person or a hook allows it, the command runs once more under the policy\n * widened by exactly what the denial named. The widened policy is built here, on the host, from the signed record and\n * the verified answer; no tool input or model output reaches it, and it lasts for that one rerun.\n */\nimport {\n canonicalInputHash,\n createPendingRequest,\n type Resolution,\n type SignedPendingRequest,\n type ToolResult,\n verifyResolution,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport { HarnessError } from \"../errors.js\";\nimport type { Harness } from \"../harness.js\";\nimport {\n type Approvals,\n answersByRequest,\n approvalsBinding,\n checkAnswers,\n type QuorumPolicy,\n settled,\n} from \"../session/approvals.js\";\nimport { type Io, inCodeCallQueue, ioOf } from \"../session/code-call.js\";\nimport {\n ESCALATION_TOOL,\n type EscalationLogRecord,\n type EscalationRecord,\n escalationsOf,\n isEscalationRecord,\n waitingEscalations,\n} from \"../session/escalation-log.js\";\nimport { recordSessionStart } from \"../session/runner.js\";\nimport type { Session } from \"../session/session.js\";\nimport {\n ESCALATION_TRANSITIONS,\n type EscalationEvent,\n type EscalationState,\n type EscalationTransition,\n nextEscalationState,\n} from \"./escalation-table.js\";\nimport type {\n ApprovalPolicy,\n ExecResult,\n Sandbox,\n SandboxClient,\n SandboxDenial,\n SandboxPolicy,\n WorkspaceManifest,\n} from \"./types.js\";\nimport { widenPolicy } from \"./widen.js\";\n\n/**\n * One rule of a `granular` policy: a denial of `kind` for `tool` may be asked about (`on-request`) or goes back to the\n * caller (`never`). A rule with no `kind` or no `tool` matches every kind or every tool. The first rule that matches\n * decides, and a denial no rule matches goes back to the caller.\n */\nexport interface EscalationRule {\n /** The kind of denial the rule covers. Left out, every kind. */\n readonly kind?: SandboxDenial[\"kind\"];\n /** A tool's canonical name or alias, as the registry knows it. */\n readonly tool?: string;\n /** Whether a matching denial may become a request. */\n readonly escalate: \"on-request\" | \"never\";\n}\n\n/** The options of `escalation()`. */\nexport interface EscalationOptions<H = unknown> {\n /** When a denial may become a request: `on-request`, `granular` (by `granular`'s rules) or `never`. */\n readonly approvalPolicy: ApprovalPolicy;\n /**\n * The approvals from `createApprovals()`. The escalation signs with their harness's signer, decides the rerun with\n * their harness's permission pipeline, and lets their quorum policy decide each answer.\n */\n readonly approvals: Approvals<H>;\n /** The rules a `granular` policy needs, and that any other policy refuses. */\n readonly granular?: readonly EscalationRule[];\n}\n\n/** One command to run in a sandbox, for one tool call, and what the host provisions the sandbox with. */\nexport interface EscalationRun<H = unknown> {\n /** The tool the command runs for, which the permission pipeline decides again before a rerun. */\n readonly tool: string;\n /** That tool call's input, as the pipeline sees it. It is recorded, so it needs a canonical JSON form. */\n readonly input: unknown;\n /** Who chose the call. Default `model`. */\n readonly initiator?: \"model\" | \"code\";\n /** The tool call's own id, recorded for the approver to see. */\n readonly toolCallId?: string;\n /** The executable and its arguments, with no shell. */\n readonly command: readonly string[];\n /** The working directory, relative to the workspace root. */\n readonly cwd?: string;\n /** Stops the command, and its rerun, after this long, as `Sandbox.exec()` does. */\n readonly timeoutMs?: number;\n /** The most bytes of each output stream to keep, as `Sandbox.exec()` does. */\n readonly maxOutputBytes?: number;\n /** The command's whole environment, from `spawnEnv()`. It is never recorded. */\n readonly env: Readonly<Record<string, string>>;\n /** Aborts the command. */\n readonly signal: AbortSignal;\n /** The backend `run()` provisions from when it is given no `sandbox`. */\n readonly client: SandboxClient;\n /** The workspace. Its root is recorded, and a rerun needs the same root. */\n readonly manifest: WorkspaceManifest;\n /** The policy the command runs under. It is recorded, and a rerun widens this record of it. */\n readonly policy: SandboxPolicy;\n /** A sandbox already provisioned with `policy`. Left out, `run()` provisions one and disposes it. */\n readonly sandbox?: Sandbox;\n /** The caller's identity. A request binds a MAC of it, so only the same value can resolve it. */\n readonly hostContext?: H;\n /** The clock of the entries and the signed request. Default the system clock. */\n readonly clock?: Clock;\n /** Makes the escalation's id and the ids of its entries and request. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/** The options of `EscalationMachine.resolve()`: where the rerun runs, which the log does not hold. */\nexport interface EscalationResolveOptions<H = unknown> {\n /** The backend the rerun provisions a fresh sandbox from. */\n readonly client: SandboxClient;\n /** The workspace, whose root must be the recorded one. */\n readonly manifest: WorkspaceManifest;\n /** The rerun's whole environment, from `spawnEnv()`. */\n readonly env: Readonly<Record<string, string>>;\n /**\n * Aborts the call and its rerun. A signal aborted when `resolve()` is called writes nothing. One aborted later, but\n * before the answer is written, writes no answer and runs nothing, so the request still waits. One aborted after the\n * answer is written only reaches the rerun, as `Sandbox.exec()` takes a signal, and the approval is spent.\n */\n readonly signal: AbortSignal;\n /** The same host context the request was made with, when it bound one. */\n readonly hostContext?: H;\n /** Who asked. An approver equal to it is refused. */\n readonly requesterId?: string;\n /** The clock of the entries. Default the system clock. */\n readonly clock?: Clock;\n /** Makes the ids of the entries. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/**\n * How an escalation call ended. `states` is the path it took through the transition table in this call. `result` is a\n * tool result a tool can return to the model: the command's output, or why it did not run. The model reads it only\n * when nothing was written, as under `never`; once a request exists, the rebuilt context leaves it out and the host\n * reads it.\n *\n * - `ran`: the command finished without a denial. `rerun` is true when it was the approved rerun.\n * - `denied`: the command did not run to an end the caller can use: a denial that went back with no request, a refused\n * answer, the pipeline's deny, or a second denial on the rerun.\n * - `awaiting_approval`: `pending` waits for an answer through `resolve()`. `widened` is the policy the rerun would get.\n *\n * `escalationId` names the escalation once it has a request; a denial that went back with no request has none.\n * `denial` is what the backend refused, and `reason` is the sentence `result` carries.\n */\nexport type EscalationResult =\n | {\n readonly status: \"ran\";\n readonly exec: Extract<ExecResult, { exitCode: number }>;\n readonly rerun: boolean;\n readonly escalationId?: string;\n readonly states: readonly EscalationState[];\n readonly result: ToolResult<unknown>;\n }\n | {\n readonly status: \"denied\";\n readonly reason: string;\n readonly denial?: SandboxDenial;\n readonly rerun: boolean;\n readonly escalationId?: string;\n readonly states: readonly EscalationState[];\n readonly result: ToolResult<unknown>;\n }\n | {\n readonly status: \"awaiting_approval\";\n readonly escalationId: string;\n readonly pending: SignedPendingRequest;\n readonly denial: SandboxDenial;\n readonly widened: SandboxPolicy;\n readonly states: readonly EscalationState[];\n readonly result: ToolResult<unknown>;\n };\n\n/** An escalation that waits for an answer: its id, its signed request and the record the request signs. */\nexport interface PendingEscalation {\n /** The escalation's id, which its request names as its call id. */\n readonly escalationId: string;\n /** The signed request, to show the approver with the record. */\n readonly request: SignedPendingRequest;\n /** What the request signs: the tool and its input, the command, the workspace root, the policy and the denial. */\n readonly record: EscalationRecord;\n}\n\n/** The machine `escalation()` returns. */\nexport interface EscalationMachine<H = unknown> {\n /** The approval policy the machine was made with. */\n readonly approvalPolicy: ApprovalPolicy;\n /** The table every move follows. */\n readonly transitions: readonly EscalationTransition[];\n /**\n * Runs a command in the sandbox. A command the backend does not deny ends `ran`, and nothing is written. A denial\n * ends `denied`, with nothing written, unless the policy allows a request and the denial names one path or host that\n * can be widened; then a signed `approval_requested` entry is written and the call ends `awaiting_approval`.\n *\n * Writing a request appends to the session, so under `on-request` and `granular` call it from host code outside a\n * turn's tool step, as `invokeTool()` runs. Throws `invalid_escalation` for an input or host context with no\n * canonical JSON form, before anything is written.\n */\n run(session: Session, run: EscalationRun<H>): Promise<EscalationResult>;\n /**\n * The escalations of the session that wait for an answer. The quorum policy is asked about each one with the answers\n * written so far, and one it says has expired is left out. Listing writes nothing, so such an escalation stays in the\n * log until it is answered: `resolve()` then writes the policy's denial, and it never reruns.\n */\n pending(session: Session): Promise<PendingEscalation[]>;\n /**\n * Answers one waiting escalation. The answer is checked before anything is written: the signature under a key in the\n * ring, the bound host context, the call and the record. An allow must name its approver in `by`, and a classifier's\n * allow (`by: \"classifier:…\"`) never approves a rerun; both are refused with nothing written. `by` is not covered by\n * the request's signature, so the host sets it only after it has authenticated the approver. The answer is written,\n * the quorum policy decides the answer, and an allow then goes through the permission pipeline again, so a deny rule\n * added since the pause wins. The rerun runs once in a fresh sandbox under the recorded policy widened by exactly the\n * recorded denial, and that sandbox is disposed after it. A second denial is the rerun's result.\n *\n * It first settles every escalation a crash left open: a rerun that started and has no result is never run again.\n * Throws `approval_not_pending` for a request that does not wait, `approval_refused` for one that fails its check, an\n * allow with no `by` or a classifier's allow, `approver_is_requester`, and `invalid_escalation` for a workspace with\n * another root.\n */\n resolve(session: Session, resolution: Resolution, options: EscalationResolveOptions<H>): Promise<EscalationResult>;\n}\n\nconst POLICIES: readonly string[] = [\"on-request\", \"granular\", \"never\"];\nconst KINDS: readonly string[] = [\"filesystem_read\", \"filesystem_write\", \"network\"];\n// The characters of each output stream the log keeps of a rerun. Even at six bytes a character, as JSON escapes a\n// control character, two streams stay under the store's 64 KiB entry bound.\nconst STORED_CHARS = 4 * 1024;\n\nconst invalid = (message: string, cause?: unknown) =>\n new HarnessError(\"invalid_escalation\", message, cause === undefined ? {} : { cause });\n\nfunction checkRules(rules: unknown): void {\n if (!Array.isArray(rules) || rules.length === 0) {\n throw invalid(\"a granular approval policy needs a non-empty list of escalation rules\");\n }\n for (const rule of rules as EscalationRule[]) {\n const ok =\n (rule?.escalate === \"on-request\" || rule?.escalate === \"never\") &&\n (rule.kind === undefined || KINDS.includes(rule.kind)) &&\n (rule.tool === undefined || (typeof rule.tool === \"string\" && rule.tool !== \"\"));\n if (!ok) throw invalid(`an escalation rule is unusable: ${JSON.stringify(rule)}`);\n }\n}\n\n/** Checks the options and returns the harness and quorum policy the approvals were made with. */\nfunction bindingOf<H>(options: EscalationOptions<H>): { harness: Harness<H>; quorum: QuorumPolicy } {\n if (!POLICIES.includes(options?.approvalPolicy)) {\n throw invalid(`the approval policy must be on-request, granular or never, got ${String(options?.approvalPolicy)}`);\n }\n if (options.approvalPolicy === \"granular\") checkRules(options.granular);\n else if (options.granular !== undefined) throw invalid(\"escalation rules apply only to a granular approval policy\");\n const binding = options.approvals === undefined ? undefined : approvalsBinding(options.approvals);\n if (binding === undefined) throw invalid(\"escalation() needs the approvals createApprovals() made\");\n if (options.approvalPolicy !== \"never\") {\n if (binding.harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no escalation could be asked\");\n }\n if (binding.harness.pipeline === undefined) {\n throw invalid(\"the harness has no permission pipeline, so no rerun could be decided again\");\n }\n }\n return binding;\n}\n\nconst text = (body: string, isError: boolean, details?: unknown): ToolResult<unknown> => ({\n content: [{ type: \"text\", text: body }],\n isError,\n ...(details === undefined ? {} : { details }),\n});\n\n/** The moves of one call: each goes through the table, so an edge it does not list throws. */\ninterface Walker {\n readonly states: EscalationState[];\n step(event: EscalationEvent): void;\n /** The states so far and an error result with `body`, for a call that ends without the command's output. */\n end(body: string): { readonly states: readonly EscalationState[]; readonly result: ToolResult<unknown> };\n}\n\nfunction walker(start: EscalationState): Walker {\n const states: EscalationState[] = [start];\n return {\n states,\n step(event) {\n states.push(nextEscalationState(states.at(-1) as EscalationState, event));\n },\n end: (body) => ({ states, result: text(body, true) }),\n };\n}\n\nconst what = (denial: SandboxDenial): string =>\n `The sandbox refused a ${denial.kind.replace(\"_\", \" \")} of ${denial.target}: ${denial.reason}.`;\n\nfunction clip(value: string, most = STORED_CHARS): string {\n return value.length <= most ? value : `${value.slice(0, most)}\\n[output cut]`;\n}\n\nfunction execText(exec: Extract<ExecResult, { exitCode: number }>, keep: (value: string) => string): string {\n const signal = exec.signal === undefined ? \"\" : ` (${exec.signal})`;\n return [`exit code ${exec.exitCode}${signal}`, keep(exec.stdout), keep(exec.stderr)].join(\"\\n\");\n}\n\nconst ranResult = (exec: Extract<ExecResult, { exitCode: number }>, keep = (value: string) => value) =>\n text(execText(exec, keep), exec.exitCode !== 0, {\n exitCode: exec.exitCode,\n ...(exec.signal === undefined ? {} : { signal: exec.signal }),\n });\n\n/**\n * Where an escalation's result text came from. `command`: the rerun's output. `quoted`: a sentence of the harness's\n * that quotes text it did not write, such as a backend's denial, an error's message or an approver's reason. `fixed`:\n * one of the harness's own fixed sentences.\n */\ntype ResultSource = \"command\" | \"quoted\" | \"fixed\";\n\n/** Writes the escalation's result, which ends it: the model never reads it, and the host gets it back. */\nasync function writeResult(io: Io, id: string, result: ToolResult<unknown>, source: ResultSource): Promise<void> {\n const first = result.content[0];\n // The streams were clipped one by one already; this bounds the whole text, the exit line included.\n const body = first?.type === \"text\" ? clip(first.text, 2 * STORED_CHARS + 256) : \"\";\n await io.write(source === \"command\" ? \"tool\" : \"harness\", {\n type: \"tool_result\",\n callId: id,\n tool: ESCALATION_TOOL,\n content: [{ type: \"text\", text: body }],\n isError: result.isError === true,\n ...(result.details === undefined ? {} : { details: result.details }),\n // A command's output, a backend's message or a quoted reason can carry instructions an attacker wrote; only the\n // harness's fixed sentences can't.\n trust: source === \"fixed\" ? \"trusted\" : \"untrusted\",\n });\n}\n\nconst INTERRUPTED = \"The rerun stopped before its result was recorded, so it may have run. It is not run again.\";\nconst NEVER_RAN = \"The escalation stopped after its answer was written and before its rerun started, so it never ran.\";\n\n/** Settles each escalation a crash left open, by the crash rule: a started rerun is never run again. */\nasync function settleOpen(path: readonly EscalationLogRecord[], io: Io): Promise<void> {\n for (const record of path) {\n if (record.result !== undefined || !(record.answered || record.started)) continue;\n nextEscalationState(record.started ? \"rerun\" : \"requested\", \"settled\");\n await writeResult(io, record.id, text(record.started ? INTERRUPTED : NEVER_RAN, true), \"fixed\");\n }\n}\n\nasync function hashable(value: unknown, what: string): Promise<void> {\n try {\n await canonicalInputHash(value);\n } catch (error) {\n throw invalid(`the escalation's ${what} has no canonical JSON form`, error);\n }\n}\n\n/** The fields of `fields` that are set, so an optional field left out is not written as `undefined`. */\nfunction present<T extends object>(fields: T): Partial<T> {\n return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined)) as Partial<T>;\n}\n\n/** Runs one command in a sandbox provisioned for it, and disposes that sandbox whatever happens. */\nasync function execIn(\n where: { readonly client: SandboxClient; readonly manifest: WorkspaceManifest; readonly sandbox?: Sandbox },\n policy: SandboxPolicy,\n command: Pick<EscalationRecord, \"command\" | \"cwd\" | \"timeoutMs\" | \"maxOutputBytes\">,\n run: { readonly env: Readonly<Record<string, string>>; readonly signal: AbortSignal },\n): Promise<ExecResult> {\n const used = where.sandbox ?? (await where.client.provision(where.manifest, policy));\n const { cwd, timeoutMs, maxOutputBytes } = command;\n try {\n return await used.exec(command.command, {\n env: run.env,\n signal: run.signal,\n ...present({ cwd, timeoutMs, maxOutputBytes }),\n });\n } finally {\n // A sandbox the caller provisioned is the caller's to dispose.\n if (where.sandbox === undefined) await used.dispose();\n }\n}\n\n/** What every call of one machine shares: the harness, its quorum policy, the approval policy and its rules. */\ninterface Machine<H> {\n readonly harness: Harness<H>;\n readonly quorum: QuorumPolicy;\n readonly approvalPolicy: ApprovalPolicy;\n readonly rules: readonly EscalationRule[];\n}\n\nconst nameOf = <H>(machine: Machine<H>, tool: string): string =>\n machine.harness.registry.get(tool)?.canonicalName ?? tool;\n\n/** Why a denial goes back with no request, or `undefined` when the policy allows one. */\nfunction refusal<H>(machine: Machine<H>, denial: SandboxDenial, tool: string): string | undefined {\n if (machine.approvalPolicy === \"never\") return \"The approval policy is never, so no one was asked.\";\n if (machine.approvalPolicy !== \"granular\") return undefined;\n const rule = machine.rules.find(\n (each) =>\n (each.kind === undefined || each.kind === denial.kind) &&\n (each.tool === undefined || nameOf(machine, each.tool) === nameOf(machine, tool)),\n );\n return rule?.escalate === \"on-request\"\n ? undefined\n : \"No escalation rule lets the host ask about this, so no one was asked.\";\n}\n\n/** The record a request signs, from the run and the denial: the host's facts, never the tool's input alone. */\nfunction recordOf<H>(machine: Machine<H>, call: EscalationRun<H>, denial: SandboxDenial): EscalationRecord {\n const { toolCallId, cwd, timeoutMs, maxOutputBytes } = call;\n return {\n tool: nameOf(machine, call.tool),\n input: call.input,\n initiator: call.initiator ?? \"model\",\n command: [...call.command],\n ...present({ toolCallId, cwd, timeoutMs, maxOutputBytes }),\n root: call.manifest.root,\n policy: call.policy,\n denial: { kind: denial.kind, target: denial.target, reason: denial.reason },\n };\n}\n\n/** Writes the session's start if it lacks one, settles what a crash left open, then signs and writes the request. */\nasync function ask<H>(\n machine: Machine<H>,\n session: Session,\n call: EscalationRun<H>,\n asked: { readonly record: EscalationRecord; readonly widened: SandboxPolicy; readonly walk: Walker },\n): Promise<EscalationResult> {\n const { harness } = machine;\n const { record, widened, walk } = asked;\n const io = ioOf(session, call);\n const id = io.newId();\n await recordSessionStart(harness, (origin, body) => io.write(origin, body), harness.model, await session.path());\n await settleOpen([...escalationsOf(await session.path()).values()], io);\n const reason = what(record.denial);\n const pending = await createPendingRequest(\n {\n kind: \"approval\",\n callId: id,\n tool: ESCALATION_TOOL,\n input: record,\n reason,\n ...present({ app: call.hostContext }),\n },\n harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n { generateId: io.newId, now: () => new Date(io.clock.now()) },\n );\n await io.write(\"harness\", { type: \"approval_requested\", request: pending, input: record });\n walk.step(\"asked\");\n const body = `${reason} A person was asked to allow it once (request ${pending.id}).`;\n return { status: \"awaiting_approval\", escalationId: id, pending, denial: record.denial, widened, ...walk.end(body) };\n}\n\nasync function runCommand<H>(machine: Machine<H>, session: Session, call: EscalationRun<H>): Promise<EscalationResult> {\n if (typeof call?.tool !== \"string\" || call.tool === \"\") throw invalid(\"an escalation run needs the tool's name\");\n const walk = walker(\"sandboxed\");\n const exec = await execIn(call, call.policy, call, call);\n if (!(\"denied\" in exec)) {\n walk.step(\"ran\");\n return { status: \"ran\", exec, rerun: false, states: walk.states, result: ranResult(exec) };\n }\n walk.step(\"denied\");\n const denial = exec.denied;\n const widened = widenPolicy(call.policy, denial);\n const why =\n refusal(machine, denial, call.tool) ??\n (widened === undefined ? \"The policy can't be widened to that, so no one was asked.\" : undefined);\n if (why !== undefined || widened === undefined) {\n walk.step(\"returned\");\n const reason = `${what(denial)} ${why}`;\n return { status: \"denied\", reason, denial, rerun: false, ...walk.end(reason) };\n }\n const record = recordOf(machine, call, denial);\n await hashable(record, \"record\");\n if (call.hostContext !== undefined) await hashable(call.hostContext, \"host context\");\n return inCodeCallQueue(session, () => ask(machine, session, call, { record, widened, walk }));\n}\n\n/** What an answer resolves once it passed its checks: the escalation, its verified record and the rerun's policy. */\ninterface Checked {\n readonly found: EscalationLogRecord;\n readonly record: EscalationRecord;\n readonly widened: SandboxPolicy;\n}\n\n/** Checks an answer against the waiting request before anything is written, and returns the escalation it answers. */\nasync function check<H>(\n machine: Machine<H>,\n path: readonly EscalationLogRecord[],\n resolution: Resolution,\n options: EscalationResolveOptions<H>,\n): Promise<Checked> {\n const { harness } = machine;\n const waiting = path.filter((record) => record.result === undefined && !record.answered && !record.started);\n const byRequest = new Map(waiting.map((record) => [record.requested.request.id, record]));\n checkAnswers(harness, byRequest, [resolution], options.requesterId);\n const found = byRequest.get(resolution.requestId) as EscalationLogRecord;\n const refuse = (cause: string) =>\n new HarnessError(\n \"approval_refused\",\n `the request for escalation ${found.id} failed its check (${cause}), so nothing ran and nothing was written`,\n );\n if (\"decision\" in resolution && resolution.decision === \"allow\") {\n // `by` is not signed, so the guard holds only as far as the host sets it truthfully; an allow that names no one\n // is refused rather than read as a person's.\n const by = typeof resolution.by === \"string\" ? resolution.by.trim().toLowerCase() : \"\";\n if (by === \"\") throw refuse(\"an allow that names no approver does not cover a sandbox rerun\");\n if (by.startsWith(\"classifier:\")) throw refuse(\"a classifier's allow does not cover a sandbox rerun\");\n }\n const verified = await verifyResolution(found.requested.request, resolution, {\n signer: harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n call: { callId: found.id, tool: ESCALATION_TOOL, input: found.requested.input },\n ...present({ app: options.hostContext }),\n });\n if (!verified.ok) throw refuse(verified.cause);\n const record = found.requested.input;\n if (!isEscalationRecord(record)) throw refuse(\"malformed\");\n const widened = widenPolicy(record.policy, record.denial);\n if (widened === undefined) throw refuse(\"not_widenable\");\n if (options.manifest?.root !== record.root) {\n throw invalid(\"the rerun's workspace must have the root the escalation recorded\");\n }\n return { found, record, widened };\n}\n\n/** Decides the call again with the pipeline, which writes the `permission_decision` the rerun starts after. */\nasync function decideAgain<H>(machine: Machine<H>, io: Io, id: string, record: EscalationRecord, hostContext?: H) {\n // bindingOf() refused a harness without a pipeline for every policy that can ask.\n const pipeline = machine.harness.pipeline as NonNullable<Harness<H>[\"pipeline\"]>;\n return pipeline.decide(\n { callId: id, tool: record.tool, input: record.input, initiator: record.initiator },\n { session: { append: (entry) => io.write(\"harness\", entry) }, hostContext, entries: await io.session.path() },\n );\n}\n\n/** Ends an escalation that will not rerun: writes the reason as its result and returns the denial. */\nasync function refuseRerun(io: Io, checked: Checked, walk: Walker, reason: string): Promise<EscalationResult> {\n walk.step(\"refused\");\n const ended = walk.end(reason);\n await writeResult(io, checked.found.id, ended.result, \"quoted\");\n return {\n status: \"denied\",\n reason,\n denial: checked.record.denial,\n rerun: false,\n escalationId: checked.found.id,\n ...ended,\n };\n}\n\nasync function resolveQueued<H>(\n machine: Machine<H>,\n session: Session,\n resolution: Resolution,\n options: EscalationResolveOptions<H>,\n): Promise<EscalationResult> {\n options.signal?.throwIfAborted();\n const io = ioOf(session, options);\n await settleOpen([...escalationsOf(await session.path()).values()], io);\n const path = await session.path();\n const checked = await check(machine, [...escalationsOf(path).values()], resolution, options);\n const { found, record, widened } = checked;\n const walk = walker(\"requested\");\n const outcome = await settled(machine.quorum, [found.requested], answersByRequest(path), [{ resolution }]);\n // The check and the quorum policy may await, so an abort since the call began stops it here, before the answer is\n // written: once it is, the approval is spent, and an abort then can only stop the rerun.\n options.signal?.throwIfAborted();\n for (const entry of outcome.records) await io.write(\"user\", { type: \"approval_resolved\", ...entry });\n const answer = outcome.forRun[0];\n if (answer === undefined) {\n walk.step(\"waiting\");\n const body = `${what(record.denial)} The request waits for more answers.`;\n const pending = found.requested.request;\n return {\n status: \"awaiting_approval\",\n escalationId: found.id,\n pending,\n denial: record.denial,\n widened,\n ...walk.end(body),\n };\n }\n if (!(\"decision\" in answer) || answer.decision !== \"allow\") {\n const why = (\"reason\" in answer ? answer.reason : undefined) ?? \"denied\";\n return refuseRerun(io, checked, walk, `The rerun was not allowed: ${why}.`);\n }\n walk.step(\"allowed\");\n const decision = await decideAgain(machine, io, found.id, record, options.hostContext);\n // A person allowed the rerun, so a question the pipeline would ask again doesn't stop it; a deny does.\n if (decision.decision === \"deny\") {\n return refuseRerun(io, checked, walk, `The permission policy now denies the call: ${decision.reason}`);\n }\n walk.step(\"started\");\n return rerun(io, checked, options, walk);\n}\n\n/** Runs the one rerun in a fresh sandbox under the widened policy, and writes its result. */\nasync function rerun<H>(\n io: Io,\n checked: Checked,\n options: EscalationResolveOptions<H>,\n walk: Walker,\n): Promise<EscalationResult> {\n const id = checked.found.id;\n let exec: ExecResult;\n try {\n exec = await execIn(options, checked.widened, checked.record, options);\n } catch (error) {\n // The rerun started, so it gets a result and is never run again, and the caller still sees why it failed.\n const reason = `The rerun failed: ${error instanceof Error ? error.message : String(error)}`;\n await writeResult(io, id, text(reason, true), \"quoted\");\n throw error;\n }\n walk.step(\"ran\");\n if (\"denied\" in exec) {\n const reason = `${what(exec.denied)} This was the approved rerun, so no one is asked again.`;\n const ended = walk.end(reason);\n await writeResult(io, id, ended.result, \"quoted\");\n return { status: \"denied\", reason, denial: exec.denied, rerun: true, escalationId: id, ...ended };\n }\n await writeResult(\n io,\n id,\n ranResult(exec, (value) => clip(value)),\n \"command\",\n );\n return { status: \"ran\", exec, rerun: true, escalationId: id, states: walk.states, result: ranResult(exec) };\n}\n\n/** The escalations that wait, less the ones the quorum policy says have expired. It writes nothing. */\nasync function pendingOf<H>(machine: Machine<H>, session: Session): Promise<PendingEscalation[]> {\n const path = await session.path();\n const answers = answersByRequest(path);\n const found: PendingEscalation[] = [];\n for (const { id, requested } of waitingEscalations(path)) {\n if (!isEscalationRecord(requested.input)) continue;\n const verdict = await machine.quorum.evaluate(requested.request, answers.get(requested.request.id) ?? []);\n if (verdict === \"expired\") continue;\n found.push({ escalationId: id, request: requested.request, record: requested.input });\n }\n return found;\n}\n\n/**\n * Creates the escalation machine for a harness's approvals. Throws `invalid_escalation` for unusable options, and\n * `approval_unavailable` when a policy that can ask has a harness with no signer.\n */\nexport function escalation<H = unknown>(options: EscalationOptions<H>): EscalationMachine<H> {\n const { harness, quorum } = bindingOf(options);\n const machine: Machine<H> = {\n harness,\n quorum,\n approvalPolicy: options.approvalPolicy,\n rules: options.granular ?? [],\n };\n return {\n approvalPolicy: options.approvalPolicy,\n transitions: ESCALATION_TRANSITIONS,\n run: (session, call) => runCommand(machine, session, call),\n pending: (session) => pendingOf(machine, session),\n resolve(session, resolution, resolveOptions) {\n return inCodeCallQueue(session, () => resolveQueued(machine, session, resolution, resolveOptions));\n },\n };\n}\n"]}
@@ -61,3 +61,5 @@ export declare class HostFiles {
61
61
  readFile(path: string): Promise<Uint8Array>;
62
62
  writeFile(path: string, data: Uint8Array): Promise<void>;
63
63
  }
64
+ /** For each real path, the spellings in the request that resolved to it, so a read-back can answer in them. */
65
+ export declare function spellings(real: readonly string[], requested: readonly string[]): ReadonlyMap<string, readonly string[]>;
@@ -245,4 +245,14 @@ export class HostFiles {
245
245
  }
246
246
  }
247
247
  }
248
+ /** For each real path, the spellings in the request that resolved to it, so a read-back can answer in them. */
249
+ export function spellings(real, requested) {
250
+ const names = new Map();
251
+ real.forEach((path, index) => {
252
+ const spelling = requested[index];
253
+ if (spelling !== undefined)
254
+ names.set(path, [...(names.get(path) ?? []), spelling]);
255
+ });
256
+ return names;
257
+ }
248
258
  //# sourceMappingURL=host-files.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"host-files.js","sourceRoot":"","sources":["../../src/sandbox/host-files.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAIjD,gEAAgE;AAChE,MAAM,CAAC,MAAM,YAAY,GAAG,8BAA8B,CAAC;AAE3D,wFAAwF;AACxF,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAExC,gGAAgG;AAChG,MAAM,UAAU,MAAM,CAAC,OAAoB,EAAE,IAAY,EAAE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/B,CAAC;oBAAS,CAAC;gBACT,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;YACvB,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,kBAAkB,EAAE,IAAI,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * The file calls that backends with a bind-mounted workspace share. A backend that confines commands with a kernel\n * feature still reads and writes the workspace's files from the host, and this checks every path first: by its real\n * path, so a symlink that leads out of a root is refused, and again on the opened file through `/proc`, so a path swapped\n * for a link in between is caught. A hostile process could still win that race, which is why no backend that uses this\n * claims a `hostile_process` stop. It is Node-only and Linux-only, because it reads `/proc`.\n */\nimport { HarnessError, isHarnessError } from \"../errors.js\";\nimport { SandboxDeniedError } from \"./errors.js\";\nimport type { NodeModules } from \"./process.js\";\nimport type { ExecOptions, ExecResult, SandboxDenial } from \"./types.js\";\n\n// The `PATH` a backend's tools run with when the host has none.\nexport const DEFAULT_PATH = \"/usr/local/bin:/usr/bin:/bin\";\n\n// The most bytes a file call reads or writes, because the whole file is held in memory.\nconst MAX_FILE_BYTES = 64 * 1024 * 1024;\n\n/** Whether `path` is inside `root`, or is `root`. Both are absolute, with symlinks resolved. */\nexport function inside(modules: NodeModules, root: string, path: string): boolean {\n const relative = modules.path.relative(root, path);\n const climbs = relative === \"..\" || relative.startsWith(`..${modules.path.sep}`);\n return relative === \"\" || (!climbs && !modules.path.isAbsolute(relative));\n}\n\n/** The real path of `path`, or `path` itself when it doesn't exist. */\nexport async function realOrSelf(modules: NodeModules, path: string): Promise<string> {\n return modules.fs.realpath(path).catch(() => path);\n}\n\n/**\n * The real path of `path`, which may not exist: the real path of its deepest folder that does, then the rest as written.\n * A symlink on the way is followed, so a link that points out of a root shows as outside it.\n */\nexport async function realPathOfMissing(modules: NodeModules, path: string): Promise<string> {\n const rest: string[] = [];\n let at = path;\n for (;;) {\n try {\n return modules.path.join(await modules.fs.realpath(at), ...rest);\n } catch {\n const parent = modules.path.dirname(at);\n if (parent === at) return path;\n rest.unshift(modules.path.basename(at));\n at = parent;\n }\n }\n}\n\n/** The paths that exist, without repeats. */\nexport async function existing(modules: NodeModules, paths: readonly string[]): Promise<string[]> {\n const present = await Promise.all(\n paths.map((path) =>\n modules.fs.access(path).then(\n () => path,\n () => undefined,\n ),\n ),\n );\n return [...new Set(present.filter((path): path is string => path !== undefined))];\n}\n\n/**\n * The absolute folders of `path`, or a default when there are none. A relative folder would be searched from the\n * workspace, where the agent can write, so `srt` could start a program the agent planted.\n */\nexport function absolutePath(modules: NodeModules, path: string | undefined): string {\n const folders = (path ?? \"\").split(modules.path.delimiter).filter((folder) => modules.path.isAbsolute(folder));\n return folders.length === 0 ? DEFAULT_PATH : folders.join(modules.path.delimiter);\n}\n\n/** The first folder of `hostPath` that holds an executable called `name`, or `undefined`. */\nexport async function findOnPath(modules: NodeModules, hostPath: string, name: string): Promise<string | undefined> {\n const folders = hostPath.split(modules.path.delimiter).filter((folder) => folder !== \"\");\n for (const folder of folders) {\n const candidate = modules.path.join(folder, name);\n try {\n await modules.fs.access(candidate, modules.fs.constants.X_OK);\n return candidate;\n } catch {\n // Not in this folder.\n }\n }\n return undefined;\n}\n\n/** Throws unless every path is absolute and is not `/`. */\nexport function checkPaths(modules: NodeModules, paths: readonly string[], what: string): void {\n for (const path of paths) {\n if (!modules.path.isAbsolute(path) || modules.path.resolve(path) === \"/\") {\n throw new HarnessError(\n \"invalid_sandbox_options\",\n `${what} must be an absolute path other than /, not ${JSON.stringify(path)}`,\n );\n }\n }\n}\n\n/** The workspace manifest's root as a real path, or an error when it isn't an existing absolute folder. */\nexport async function workspaceRoot(modules: NodeModules, root: string): Promise<string> {\n if (!modules.path.isAbsolute(root)) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a workspace manifest's root must be an absolute path\");\n }\n const stats = await modules.fs.stat(root).catch(() => undefined);\n if (!stats?.isDirectory()) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a workspace manifest's root must be an existing folder\");\n }\n return modules.fs.realpath(root);\n}\n\n/** The real roots a sandbox enforces on file calls. */\nexport interface RealRoots {\n readonly read: readonly string[];\n readonly write: readonly string[];\n readonly denyWrite: readonly string[];\n}\n\n/** The working directory as a real path inside `root`, or the denial for one outside it. */\nexport async function workingDirectory(\n modules: NodeModules,\n root: string,\n options: ExecOptions,\n): Promise<{ cwd: string } | Extract<ExecResult, { denied: SandboxDenial }>> {\n const wanted = modules.path.resolve(root, options.cwd ?? \".\");\n const cwd = await realPathOfMissing(modules, wanted);\n if (!inside(modules, root, cwd)) {\n return {\n denied: { kind: \"filesystem_read\", target: wanted, reason: \"the working directory is outside the workspace\" },\n };\n }\n const stats = await modules.fs.stat(cwd).catch(() => undefined);\n if (!stats?.isDirectory()) {\n throw new HarnessError(\"invalid_sandbox_options\", `the working directory ${cwd} is not an existing folder`);\n }\n return { cwd };\n}\n\n// What a backend that bind-mounts the workspace keeps read-only inside it, which the file calls keep read-only too: the\n// shell start-up files, the editor and agent settings, and a repository's hooks and config.\nconst PROTECTED_PATHS =\n /^(\\.bash_profile|\\.bashrc|\\.zshrc|\\.zprofile|\\.profile|\\.gitconfig|\\.gitmodules|\\.ripgreprc|\\.mcp\\.json|\\.vscode|\\.idea|\\.claude)(\\/|$)|(^|\\/)\\.git\\/(hooks|config)(\\/|$)/;\n\n/** The paths at the top of a write root that a backend can mount read-only when they exist. */\nexport const PROTECTED_TOP_LEVEL: readonly string[] = [\n \".bash_profile\",\n \".bashrc\",\n \".zshrc\",\n \".zprofile\",\n \".profile\",\n \".gitconfig\",\n \".gitmodules\",\n \".ripgreprc\",\n \".mcp.json\",\n \".vscode\",\n \".idea\",\n \".claude\",\n \".git/hooks\",\n \".git/config\",\n];\n\n/** Whether `relative`, a path under a write root with `/` between the parts, is one the file calls keep read-only. */\nexport const isProtectedPath = (relative: string): boolean => PROTECTED_PATHS.test(relative);\n\n/** Reads and writes workspace files from the host, inside the roots. */\nexport class HostFiles {\n private readonly modules: NodeModules;\n private readonly root: string;\n private readonly roots: RealRoots;\n private readonly protectedPath: ((relative: string) => boolean) | undefined;\n\n /**\n * `protectedPath` tells whether a path, relative to its write root with `/` between the parts, is one the backend\n * keeps read-only besides the `denyWrite` folders.\n */\n constructor(modules: NodeModules, root: string, roots: RealRoots, protectedPath?: (relative: string) => boolean) {\n this.modules = modules;\n this.root = root;\n this.roots = roots;\n this.protectedPath = protectedPath;\n }\n\n /** The real path of `path` against the workspace, or a denial when it is outside every one of `roots`. */\n private async contain(\n path: string,\n roots: readonly string[],\n kind: SandboxDenial[\"kind\"],\n rule: string,\n ): Promise<string> {\n const { modules } = this;\n const real = await realPathOfMissing(modules, modules.path.resolve(this.root, path));\n if (roots.some((root) => inside(modules, root, real))) return real;\n throw new SandboxDeniedError({ kind, target: path, reason: rule });\n }\n\n /** Throws a denial when `real` is a path that stays read-only: a `denyWrite` folder or one the backend protects. */\n private refuseProtected(real: string, path: string): void {\n const { modules, roots } = this;\n const inDenied = roots.denyWrite.some((folder) => inside(modules, folder, real));\n const owner = roots.write.find((root) => inside(modules, root, real));\n const relative = owner === undefined ? \"\" : modules.path.relative(owner, real).split(modules.path.sep).join(\"/\");\n if (inDenied || this.protectedPath?.(relative) === true) {\n throw new SandboxDeniedError({\n kind: \"filesystem_write\",\n target: path,\n reason: \"the path is one the sandbox keeps read-only\",\n });\n }\n }\n\n /** The real path of the file that `handle` opened, or a denial unless it is inside one of `roots`. */\n private async checkOpened(\n handle: import(\"node:fs/promises\").FileHandle,\n roots: readonly string[],\n kind: SandboxDenial[\"kind\"],\n path: string,\n ): Promise<string> {\n const { modules } = this;\n const opened = await modules.fs.realpath(`/proc/self/fd/${handle.fd}`).catch(() => undefined);\n if (opened === undefined || !roots.some((root) => inside(modules, root, opened))) {\n throw new SandboxDeniedError({ kind, target: path, reason: \"the file opened is outside the roots\" });\n }\n return opened;\n }\n\n /** The error for a file call that the OS failed: a denial when it refused, a missing file, or an I/O error. */\n private fileFailure(error: unknown, kind: SandboxDenial[\"kind\"], path: string): unknown {\n if (isHarnessError(error)) return error;\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return new HarnessError(\"sandbox_not_found\", `no such file: ${path}`, { cause: error });\n if (code === \"EACCES\" || code === \"EPERM\" || code === \"EROFS\" || code === \"ELOOP\") {\n return new SandboxDeniedError({ kind, target: path, reason: \"the OS refused it\" });\n }\n return new HarnessError(\"sandbox_io_failed\", `the file call on ${path} failed: ${code ?? String(error)}`, {\n cause: error,\n });\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n const { modules, roots } = this;\n const readable = [...roots.read, ...roots.write];\n const target = await this.contain(path, readable, \"filesystem_read\", \"the path is outside the read roots\");\n const { O_RDONLY, O_NOFOLLOW, O_NONBLOCK } = modules.fs.constants;\n try {\n // Opened without blocking, so a pipe the agent made can't hold the call: only a regular file is read.\n const handle = await modules.fs.open(target, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);\n try {\n await this.checkOpened(handle, readable, \"filesystem_read\", path);\n const stats = await handle.stat();\n if (!stats.isFile()) {\n throw new HarnessError(\"sandbox_io_failed\", `the path ${target} is not a regular file`);\n }\n if (stats.size > MAX_FILE_BYTES) {\n throw new HarnessError(\"sandbox_io_failed\", `the file ${target} is larger than ${MAX_FILE_BYTES} bytes`);\n }\n const bytes = new Uint8Array(stats.size);\n const { bytesRead } = await handle.read(bytes, 0, stats.size, 0);\n return bytes.subarray(0, bytesRead);\n } finally {\n await handle.close();\n }\n } catch (error) {\n throw this.fileFailure(error, \"filesystem_read\", path);\n }\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n if (data.length > MAX_FILE_BYTES) {\n throw new HarnessError(\"sandbox_io_failed\", `a file larger than ${MAX_FILE_BYTES} bytes can't be written`);\n }\n const { modules, roots } = this;\n const rule = \"the path is outside the write roots\";\n const target = await this.contain(path, roots.write, \"filesystem_write\", rule);\n this.refuseProtected(target, path);\n const { O_WRONLY, O_CREAT, O_NOFOLLOW, O_NONBLOCK } = modules.fs.constants;\n try {\n await modules.fs.mkdir(modules.path.dirname(target), { recursive: true });\n // Opened without O_TRUNC, so a file that turns out to be outside the roots is not emptied before the check.\n const handle = await modules.fs.open(target, O_WRONLY | O_CREAT | O_NOFOLLOW | O_NONBLOCK, 0o666);\n try {\n this.refuseProtected(await this.checkOpened(handle, roots.write, \"filesystem_write\", path), path);\n if (!(await handle.stat()).isFile()) {\n throw new HarnessError(\"sandbox_io_failed\", `the path ${target} is not a regular file`);\n }\n await handle.truncate(0);\n await handle.writeFile(data);\n } finally {\n await handle.close();\n }\n } catch (error) {\n throw this.fileFailure(error, \"filesystem_write\", path);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"host-files.js","sourceRoot":"","sources":["../../src/sandbox/host-files.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAIjD,gEAAgE;AAChE,MAAM,CAAC,MAAM,YAAY,GAAG,8BAA8B,CAAC;AAE3D,wFAAwF;AACxF,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAExC,gGAAgG;AAChG,MAAM,UAAU,MAAM,CAAC,OAAoB,EAAE,IAAY,EAAE,IAAY;IACrE,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACnD,MAAM,MAAM,GAAG,QAAQ,KAAK,IAAI,IAAI,QAAQ,CAAC,UAAU,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;IACjF,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC;AAC5E,CAAC;AAED,uEAAuE;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,EAAE,KAAK,EAAE,EAAE;QAC3B,MAAM,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;QAClC,IAAI,QAAQ,KAAK,SAAS;YAAE,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;IACtF,CAAC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * The file calls that backends with a bind-mounted workspace share. A backend that confines commands with a kernel\n * feature still reads and writes the workspace's files from the host, and this checks every path first: by its real\n * path, so a symlink that leads out of a root is refused, and again on the opened file through `/proc`, so a path swapped\n * for a link in between is caught. A hostile process could still win that race, which is why no backend that uses this\n * claims a `hostile_process` stop. It is Node-only and Linux-only, because it reads `/proc`.\n */\nimport { HarnessError, isHarnessError } from \"../errors.js\";\nimport { SandboxDeniedError } from \"./errors.js\";\nimport type { NodeModules } from \"./process.js\";\nimport type { ExecOptions, ExecResult, SandboxDenial } from \"./types.js\";\n\n// The `PATH` a backend's tools run with when the host has none.\nexport const DEFAULT_PATH = \"/usr/local/bin:/usr/bin:/bin\";\n\n// The most bytes a file call reads or writes, because the whole file is held in memory.\nconst MAX_FILE_BYTES = 64 * 1024 * 1024;\n\n/** Whether `path` is inside `root`, or is `root`. Both are absolute, with symlinks resolved. */\nexport function inside(modules: NodeModules, root: string, path: string): boolean {\n const relative = modules.path.relative(root, path);\n const climbs = relative === \"..\" || relative.startsWith(`..${modules.path.sep}`);\n return relative === \"\" || (!climbs && !modules.path.isAbsolute(relative));\n}\n\n/** The real path of `path`, or `path` itself when it doesn't exist. */\nexport async function realOrSelf(modules: NodeModules, path: string): Promise<string> {\n return modules.fs.realpath(path).catch(() => path);\n}\n\n/**\n * The real path of `path`, which may not exist: the real path of its deepest folder that does, then the rest as written.\n * A symlink on the way is followed, so a link that points out of a root shows as outside it.\n */\nexport async function realPathOfMissing(modules: NodeModules, path: string): Promise<string> {\n const rest: string[] = [];\n let at = path;\n for (;;) {\n try {\n return modules.path.join(await modules.fs.realpath(at), ...rest);\n } catch {\n const parent = modules.path.dirname(at);\n if (parent === at) return path;\n rest.unshift(modules.path.basename(at));\n at = parent;\n }\n }\n}\n\n/** The paths that exist, without repeats. */\nexport async function existing(modules: NodeModules, paths: readonly string[]): Promise<string[]> {\n const present = await Promise.all(\n paths.map((path) =>\n modules.fs.access(path).then(\n () => path,\n () => undefined,\n ),\n ),\n );\n return [...new Set(present.filter((path): path is string => path !== undefined))];\n}\n\n/**\n * The absolute folders of `path`, or a default when there are none. A relative folder would be searched from the\n * workspace, where the agent can write, so `srt` could start a program the agent planted.\n */\nexport function absolutePath(modules: NodeModules, path: string | undefined): string {\n const folders = (path ?? \"\").split(modules.path.delimiter).filter((folder) => modules.path.isAbsolute(folder));\n return folders.length === 0 ? DEFAULT_PATH : folders.join(modules.path.delimiter);\n}\n\n/** The first folder of `hostPath` that holds an executable called `name`, or `undefined`. */\nexport async function findOnPath(modules: NodeModules, hostPath: string, name: string): Promise<string | undefined> {\n const folders = hostPath.split(modules.path.delimiter).filter((folder) => folder !== \"\");\n for (const folder of folders) {\n const candidate = modules.path.join(folder, name);\n try {\n await modules.fs.access(candidate, modules.fs.constants.X_OK);\n return candidate;\n } catch {\n // Not in this folder.\n }\n }\n return undefined;\n}\n\n/** Throws unless every path is absolute and is not `/`. */\nexport function checkPaths(modules: NodeModules, paths: readonly string[], what: string): void {\n for (const path of paths) {\n if (!modules.path.isAbsolute(path) || modules.path.resolve(path) === \"/\") {\n throw new HarnessError(\n \"invalid_sandbox_options\",\n `${what} must be an absolute path other than /, not ${JSON.stringify(path)}`,\n );\n }\n }\n}\n\n/** The workspace manifest's root as a real path, or an error when it isn't an existing absolute folder. */\nexport async function workspaceRoot(modules: NodeModules, root: string): Promise<string> {\n if (!modules.path.isAbsolute(root)) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a workspace manifest's root must be an absolute path\");\n }\n const stats = await modules.fs.stat(root).catch(() => undefined);\n if (!stats?.isDirectory()) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a workspace manifest's root must be an existing folder\");\n }\n return modules.fs.realpath(root);\n}\n\n/** The real roots a sandbox enforces on file calls. */\nexport interface RealRoots {\n readonly read: readonly string[];\n readonly write: readonly string[];\n readonly denyWrite: readonly string[];\n}\n\n/** The working directory as a real path inside `root`, or the denial for one outside it. */\nexport async function workingDirectory(\n modules: NodeModules,\n root: string,\n options: ExecOptions,\n): Promise<{ cwd: string } | Extract<ExecResult, { denied: SandboxDenial }>> {\n const wanted = modules.path.resolve(root, options.cwd ?? \".\");\n const cwd = await realPathOfMissing(modules, wanted);\n if (!inside(modules, root, cwd)) {\n return {\n denied: { kind: \"filesystem_read\", target: wanted, reason: \"the working directory is outside the workspace\" },\n };\n }\n const stats = await modules.fs.stat(cwd).catch(() => undefined);\n if (!stats?.isDirectory()) {\n throw new HarnessError(\"invalid_sandbox_options\", `the working directory ${cwd} is not an existing folder`);\n }\n return { cwd };\n}\n\n// What a backend that bind-mounts the workspace keeps read-only inside it, which the file calls keep read-only too: the\n// shell start-up files, the editor and agent settings, and a repository's hooks and config.\nconst PROTECTED_PATHS =\n /^(\\.bash_profile|\\.bashrc|\\.zshrc|\\.zprofile|\\.profile|\\.gitconfig|\\.gitmodules|\\.ripgreprc|\\.mcp\\.json|\\.vscode|\\.idea|\\.claude)(\\/|$)|(^|\\/)\\.git\\/(hooks|config)(\\/|$)/;\n\n/** The paths at the top of a write root that a backend can mount read-only when they exist. */\nexport const PROTECTED_TOP_LEVEL: readonly string[] = [\n \".bash_profile\",\n \".bashrc\",\n \".zshrc\",\n \".zprofile\",\n \".profile\",\n \".gitconfig\",\n \".gitmodules\",\n \".ripgreprc\",\n \".mcp.json\",\n \".vscode\",\n \".idea\",\n \".claude\",\n \".git/hooks\",\n \".git/config\",\n];\n\n/** Whether `relative`, a path under a write root with `/` between the parts, is one the file calls keep read-only. */\nexport const isProtectedPath = (relative: string): boolean => PROTECTED_PATHS.test(relative);\n\n/** Reads and writes workspace files from the host, inside the roots. */\nexport class HostFiles {\n private readonly modules: NodeModules;\n private readonly root: string;\n private readonly roots: RealRoots;\n private readonly protectedPath: ((relative: string) => boolean) | undefined;\n\n /**\n * `protectedPath` tells whether a path, relative to its write root with `/` between the parts, is one the backend\n * keeps read-only besides the `denyWrite` folders.\n */\n constructor(modules: NodeModules, root: string, roots: RealRoots, protectedPath?: (relative: string) => boolean) {\n this.modules = modules;\n this.root = root;\n this.roots = roots;\n this.protectedPath = protectedPath;\n }\n\n /** The real path of `path` against the workspace, or a denial when it is outside every one of `roots`. */\n private async contain(\n path: string,\n roots: readonly string[],\n kind: SandboxDenial[\"kind\"],\n rule: string,\n ): Promise<string> {\n const { modules } = this;\n const real = await realPathOfMissing(modules, modules.path.resolve(this.root, path));\n if (roots.some((root) => inside(modules, root, real))) return real;\n throw new SandboxDeniedError({ kind, target: path, reason: rule });\n }\n\n /** Throws a denial when `real` is a path that stays read-only: a `denyWrite` folder or one the backend protects. */\n private refuseProtected(real: string, path: string): void {\n const { modules, roots } = this;\n const inDenied = roots.denyWrite.some((folder) => inside(modules, folder, real));\n const owner = roots.write.find((root) => inside(modules, root, real));\n const relative = owner === undefined ? \"\" : modules.path.relative(owner, real).split(modules.path.sep).join(\"/\");\n if (inDenied || this.protectedPath?.(relative) === true) {\n throw new SandboxDeniedError({\n kind: \"filesystem_write\",\n target: path,\n reason: \"the path is one the sandbox keeps read-only\",\n });\n }\n }\n\n /** The real path of the file that `handle` opened, or a denial unless it is inside one of `roots`. */\n private async checkOpened(\n handle: import(\"node:fs/promises\").FileHandle,\n roots: readonly string[],\n kind: SandboxDenial[\"kind\"],\n path: string,\n ): Promise<string> {\n const { modules } = this;\n const opened = await modules.fs.realpath(`/proc/self/fd/${handle.fd}`).catch(() => undefined);\n if (opened === undefined || !roots.some((root) => inside(modules, root, opened))) {\n throw new SandboxDeniedError({ kind, target: path, reason: \"the file opened is outside the roots\" });\n }\n return opened;\n }\n\n /** The error for a file call that the OS failed: a denial when it refused, a missing file, or an I/O error. */\n private fileFailure(error: unknown, kind: SandboxDenial[\"kind\"], path: string): unknown {\n if (isHarnessError(error)) return error;\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return new HarnessError(\"sandbox_not_found\", `no such file: ${path}`, { cause: error });\n if (code === \"EACCES\" || code === \"EPERM\" || code === \"EROFS\" || code === \"ELOOP\") {\n return new SandboxDeniedError({ kind, target: path, reason: \"the OS refused it\" });\n }\n return new HarnessError(\"sandbox_io_failed\", `the file call on ${path} failed: ${code ?? String(error)}`, {\n cause: error,\n });\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n const { modules, roots } = this;\n const readable = [...roots.read, ...roots.write];\n const target = await this.contain(path, readable, \"filesystem_read\", \"the path is outside the read roots\");\n const { O_RDONLY, O_NOFOLLOW, O_NONBLOCK } = modules.fs.constants;\n try {\n // Opened without blocking, so a pipe the agent made can't hold the call: only a regular file is read.\n const handle = await modules.fs.open(target, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);\n try {\n await this.checkOpened(handle, readable, \"filesystem_read\", path);\n const stats = await handle.stat();\n if (!stats.isFile()) {\n throw new HarnessError(\"sandbox_io_failed\", `the path ${target} is not a regular file`);\n }\n if (stats.size > MAX_FILE_BYTES) {\n throw new HarnessError(\"sandbox_io_failed\", `the file ${target} is larger than ${MAX_FILE_BYTES} bytes`);\n }\n const bytes = new Uint8Array(stats.size);\n const { bytesRead } = await handle.read(bytes, 0, stats.size, 0);\n return bytes.subarray(0, bytesRead);\n } finally {\n await handle.close();\n }\n } catch (error) {\n throw this.fileFailure(error, \"filesystem_read\", path);\n }\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n if (data.length > MAX_FILE_BYTES) {\n throw new HarnessError(\"sandbox_io_failed\", `a file larger than ${MAX_FILE_BYTES} bytes can't be written`);\n }\n const { modules, roots } = this;\n const rule = \"the path is outside the write roots\";\n const target = await this.contain(path, roots.write, \"filesystem_write\", rule);\n this.refuseProtected(target, path);\n const { O_WRONLY, O_CREAT, O_NOFOLLOW, O_NONBLOCK } = modules.fs.constants;\n try {\n await modules.fs.mkdir(modules.path.dirname(target), { recursive: true });\n // Opened without O_TRUNC, so a file that turns out to be outside the roots is not emptied before the check.\n const handle = await modules.fs.open(target, O_WRONLY | O_CREAT | O_NOFOLLOW | O_NONBLOCK, 0o666);\n try {\n this.refuseProtected(await this.checkOpened(handle, roots.write, \"filesystem_write\", path), path);\n if (!(await handle.stat()).isFile()) {\n throw new HarnessError(\"sandbox_io_failed\", `the path ${target} is not a regular file`);\n }\n await handle.truncate(0);\n await handle.writeFile(data);\n } finally {\n await handle.close();\n }\n } catch (error) {\n throw this.fileFailure(error, \"filesystem_write\", path);\n }\n }\n}\n\n/** For each real path, the spellings in the request that resolved to it, so a read-back can answer in them. */\nexport function spellings(\n real: readonly string[],\n requested: readonly string[],\n): ReadonlyMap<string, readonly string[]> {\n const names = new Map<string, string[]>();\n real.forEach((path, index) => {\n const spelling = requested[index];\n if (spelling !== undefined) names.set(path, [...(names.get(path) ?? []), spelling]);\n });\n return names;\n}\n"]}