@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.
- package/README.md +152 -5
- package/dist/context/file-spill.d.ts +11 -1
- package/dist/context/file-spill.js +23 -8
- package/dist/context/file-spill.js.map +1 -1
- package/dist/context/spill.d.ts +5 -1
- package/dist/context/spill.js +6 -2
- package/dist/context/spill.js.map +1 -1
- package/dist/credentials/addresses.d.ts +11 -0
- package/dist/credentials/addresses.js +41 -2
- package/dist/credentials/addresses.js.map +1 -1
- package/dist/credentials/allowlist.d.ts +22 -2
- package/dist/credentials/allowlist.js +74 -17
- package/dist/credentials/allowlist.js.map +1 -1
- package/dist/credentials/egress-policy.d.ts +69 -0
- package/dist/credentials/egress-policy.js +170 -0
- package/dist/credentials/egress-policy.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +13 -1
- package/dist/credentials/egress-proxy.js +179 -11
- package/dist/credentials/egress-proxy.js.map +1 -1
- package/dist/credentials/git-route.d.ts +68 -0
- package/dist/credentials/git-route.js +288 -0
- package/dist/credentials/git-route.js.map +1 -0
- package/dist/credentials/index.d.ts +5 -1
- package/dist/credentials/index.js +5 -1
- package/dist/credentials/index.js.map +1 -1
- package/dist/credentials/scrub.d.ts +7 -0
- package/dist/credentials/scrub.js +22 -0
- package/dist/credentials/scrub.js.map +1 -1
- package/dist/errors.d.ts +14 -7
- package/dist/errors.js +13 -6
- package/dist/errors.js.map +1 -1
- package/dist/sandbox/base.d.ts +11 -1
- package/dist/sandbox/base.js +14 -0
- package/dist/sandbox/base.js.map +1 -1
- package/dist/sandbox/docker/index.d.ts +8 -2
- package/dist/sandbox/docker/index.js +63 -14
- package/dist/sandbox/docker/index.js.map +1 -1
- package/dist/sandbox/errors.d.ts +30 -2
- package/dist/sandbox/errors.js +36 -1
- package/dist/sandbox/errors.js.map +1 -1
- package/dist/sandbox/escalation-table.d.ts +38 -0
- package/dist/sandbox/escalation-table.js +95 -0
- package/dist/sandbox/escalation-table.js.map +1 -0
- package/dist/sandbox/escalation.d.ts +191 -0
- package/dist/sandbox/escalation.js +370 -0
- package/dist/sandbox/escalation.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +2 -0
- package/dist/sandbox/host-files.js +10 -0
- package/dist/sandbox/host-files.js.map +1 -1
- package/dist/sandbox/index.d.ts +9 -4
- package/dist/sandbox/index.js +8 -3
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/policy.d.ts +49 -0
- package/dist/sandbox/policy.js +149 -0
- package/dist/sandbox/policy.js.map +1 -0
- package/dist/sandbox/process.js +1 -1
- package/dist/sandbox/process.js.map +1 -1
- package/dist/sandbox/srt/index.d.ts +5 -2
- package/dist/sandbox/srt/index.js +27 -8
- package/dist/sandbox/srt/index.js.map +1 -1
- package/dist/sandbox/srt/settings.d.ts +17 -5
- package/dist/sandbox/srt/settings.js +53 -0
- package/dist/sandbox/srt/settings.js.map +1 -1
- package/dist/sandbox/types.d.ts +41 -4
- package/dist/sandbox/types.js.map +1 -1
- package/dist/sandbox/widen.d.ts +10 -0
- package/dist/sandbox/widen.js +150 -0
- package/dist/sandbox/widen.js.map +1 -0
- package/dist/session/approvals.d.ts +30 -1
- package/dist/session/approvals.js +12 -4
- package/dist/session/approvals.js.map +1 -1
- package/dist/session/code-call.d.ts +15 -1
- package/dist/session/code-call.js +2 -1
- package/dist/session/code-call.js.map +1 -1
- package/dist/session/escalation-log.d.ts +65 -0
- package/dist/session/escalation-log.js +84 -0
- package/dist/session/escalation-log.js.map +1 -0
- package/dist/session/rebuild.js +12 -3
- package/dist/session/rebuild.js.map +1 -1
- package/dist/testing/fake-sandbox.d.ts +21 -3
- package/dist/testing/fake-sandbox.js +157 -8
- package/dist/testing/fake-sandbox.js.map +1 -1
- package/dist/testing/sandbox-conformance.js +108 -1
- package/dist/testing/sandbox-conformance.js.map +1 -1
- package/dist/tools/builtins/bash.d.ts +9 -0
- package/dist/tools/builtins/bash.js +75 -0
- package/dist/tools/builtins/bash.js.map +1 -0
- package/dist/tools/builtins/builtins.d.ts +38 -0
- package/dist/tools/builtins/builtins.js +48 -0
- package/dist/tools/builtins/builtins.js.map +1 -0
- package/dist/tools/builtins/descriptions.d.ts +69 -0
- package/dist/tools/builtins/descriptions.js +94 -0
- package/dist/tools/builtins/descriptions.js.map +1 -0
- package/dist/tools/builtins/fetch.d.ts +12 -0
- package/dist/tools/builtins/fetch.js +157 -0
- package/dist/tools/builtins/fetch.js.map +1 -0
- package/dist/tools/builtins/files.d.ts +27 -0
- package/dist/tools/builtins/files.js +274 -0
- package/dist/tools/builtins/files.js.map +1 -0
- package/dist/tools/builtins/paths.d.ts +30 -0
- package/dist/tools/builtins/paths.js +62 -0
- package/dist/tools/builtins/paths.js.map +1 -0
- package/dist/tools/builtins/results.d.ts +15 -0
- package/dist/tools/builtins/results.js +31 -0
- package/dist/tools/builtins/results.js.map +1 -0
- package/dist/tools/builtins/search.d.ts +18 -0
- package/dist/tools/builtins/search.js +217 -0
- package/dist/tools/builtins/search.js.map +1 -0
- package/dist/tools/index.d.ts +6 -2
- package/dist/tools/index.js +5 -2
- package/dist/tools/index.js.map +1 -1
- package/llms.txt +52 -0
- package/package.json +5 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"escalation-log.js","sourceRoot":"","sources":["../../src/session/escalation-log.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAE/C,8GAA8G;AAC9G,MAAM,CAAC,MAAM,eAAe,GAAG,oBAAoB,CAAC;AAgCpD,MAAM,SAAS,GAAG,CAAC,KAAc,EAAqB,EAAE,CACtD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC;AAE1E,SAAS,QAAQ,CAAC,KAAc;IAC9B,IAAI,O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M,EAAE,CAAC,CAAC,MAAM,CAC7C,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,IAAI,CAAC,MAAM,CAAC,OAAO,CAC/E,CAAC;AACJ,CAAC","sourcesContent":["/**\n * What the log says about each sandbox escalation: its latest signed request, whether its answer is final, whether its\n * rerun started, and its result. An escalation is keyed by the call id of its request, whose tool is\n * `ESCALATION_TOOL`. That name breaks the canonical tool-name rule, so no registered tool, and no call the model makes,\n * can carry it. A rerun that started and has no result is never run again: the crash rule a code call follows.\n */\nimport type { SessionEntry, ToolResultEntry } from \"@buildanagent/protocol\";\nimport type { SignedPendingRequest } from \"@buildanagent/sdk\";\nimport type { SandboxDenial, SandboxPolicy } from \"../sandbox/types.js\";\nimport { isDenial } from \"../sandbox/widen.js\";\n\n/** The tool name an escalation's signed request carries. It has a dot, so no registered tool can share it. */\nexport const ESCALATION_TOOL = \"sandbox.escalation\";\n\n/**\n * What an escalation's request signs, as the input of its `approval_requested` entry: the call the command ran for,\n * the command, the workspace root, the policy it ran under and the denial. The rerun's policy is built from `policy`\n * and `denial` alone, once the signature over this record verifies.\n */\nexport interface EscalationRecord {\n /** The tool the command ran for, which the permission pipeline decides again before the rerun. */\n readonly tool: string;\n /** That tool call's input, as the pipeline sees it. */\n readonly input: unknown;\n /** Who chose the call: the model, or the host's own code. */\n readonly initiator: \"model\" | \"code\";\n /** The tool call's own id, when the command ran for one. */\n readonly toolCallId?: string;\n /** The executable and its arguments. */\n readonly command: readonly string[];\n /** The working directory, relative to the workspace root. */\n readonly cwd?: string;\n /** The command's timeout, which the rerun keeps. */\n readonly timeoutMs?: number;\n /** The command's output cap, which the rerun keeps. */\n readonly maxOutputBytes?: number;\n /** The workspace root the sandbox was provisioned for. */\n readonly root: string;\n /** The policy the command ran under. */\n readonly policy: SandboxPolicy;\n /** What the backend refused. */\n readonly denial: SandboxDenial;\n}\n\nconst isStrings = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\nfunction isPolicy(value: unknown): value is SandboxPolicy {\n if (typeof value !== \"object\" || value === null) return false;\n const policy = value as Record<string, unknown>;\n const network = policy.network as Record<string, unknown> | undefined;\n return (\n isStrings(policy.readRoots) &&\n isStrings(policy.writeRoots) &&\n typeof network === \"object\" &&\n network !== null &&\n isStrings(network.allow) &&\n isStrings(network.deny)\n );\n}\n\nconst optional = (value: unknown, type: \"string\" | \"number\"): boolean => value === undefined || typeof value === type;\n\n/** True when `value` has the shape of an `EscalationRecord`. A record is checked after its signature verifies too. */\nexport function isEscalationRecord(value: unknown): value is EscalationRecord {\n if (typeof value !== \"object\" || value === null) return false;\n const record = value as Record<string, unknown>;\n return (\n typeof record.tool === \"string\" &&\n (record.initiator === \"model\" || record.initiator === \"code\") &&\n optional(record.toolCallId, \"string\") &&\n isStrings(record.command) &&\n record.command.length > 0 &&\n optional(record.cwd, \"string\") &&\n optional(record.timeoutMs, \"number\") &&\n optional(record.maxOutputBytes, \"number\") &&\n typeof record.root === \"string\" &&\n isPolicy(record.policy) &&\n isDenial(record.denial)\n );\n}\n\n/** One escalation as the log records it. */\nexport interface EscalationLogRecord {\n /** The escalation's id: its request's call id. */\n readonly id: string;\n /** The latest signed request and the record it signs, which a forged entry may not hold until it is checked. */\n readonly requested: { readonly request: SignedPendingRequest; readonly input: unknown };\n /** True once an answer is final: one no quorum still waits on, or the policy's refusal. */\n readonly answered: boolean;\n /**\n * True once the rerun started: after a final allow, the permission pipeline wrote a decision that is not a deny.\n * That entry is the last one before the rerun runs.\n */\n readonly started: boolean;\n /** The escalation's `tool_result` entry, once it has one. */\n readonly result?: SessionEntry & ToolResultEntry;\n}\n\ninterface Draft {\n id: string;\n requested: { request: SignedPendingRequest; input: unknown };\n answered: boolean;\n personAllowed: boolean;\n started: boolean;\n result?: SessionEntry & ToolResultEntry;\n}\n\n/** Folds a request: a later request for the same escalation replaces the earlier one and waits for its own answer. */\nfunction foldRequest(drafts: Map<string, Draft>, byRequest: Map<string, string>, entry: SessionEntry): void {\n if (entry.type !== \"approval_requested\") return;\n const id = entry.request.callId;\n const requested = { request: entry.request, input: entry.input };\n const draft = drafts.get(id);\n if (draft === undefined) drafts.set(id, { id, requested, answered: false, personAllowed: false, started: false });\n else Object.assign(draft, { requested, answered: false, personAllowed: false });\n byRequest.set(entry.request.id, id);\n}\n\n/** Folds an entry that names the escalation's id: the pipeline's decision, which starts the rerun, or its result. */\nfunction foldCall(draft: Draft, entry: SessionEntry): void {\n if (entry.type === \"permission_decision\") draft.started = entry.decision !== \"deny\" && draft.personAllowed;\n else if (entry.type === \"tool_result\") draft.result ??= entry;\n}\n\nfunction fold(drafts: Map<string, Draft>, byRequest: Map<string, string>, entry: SessionEntry): void {\n if (entry.type === \"approval_requested\" && entry.request.tool === ESCALATION_TOOL) {\n foldRequest(drafts, byRequest, entry);\n } else if (entry.type === \"approval_resolved\" && entry.quorum === undefined) {\n const draft = drafts.get(byRequest.get(entry.resolution.requestId) ?? \"\");\n if (draft === undefined) return;\n draft.answered = true;\n draft.personAllowed = \"decision\" in entry.resolution && entry.resolution.decision === \"allow\";\n } else if (\"callId\" in entry) {\n const draft = drafts.get(entry.callId);\n if (draft !== undefined) foldCall(draft, entry);\n }\n}\n\n/** Every escalation on `path`, by id, in the order they asked. */\nexport function escalationsOf(path: readonly SessionEntry[]): Map<string, EscalationLogRecord> {\n const drafts = new Map<string, Draft>();\n const byRequest = new Map<string, string>();\n for (const entry of path) fold(drafts, byRequest, entry);\n return drafts;\n}\n\n/** The escalations on `path` that wait for an answer: no final answer, no started rerun and no result. */\nexport function waitingEscalations(path: readonly SessionEntry[]): EscalationLogRecord[] {\n return [...escalationsOf(path).values()].filter(\n (record) => record.result === undefined && !record.answered && !record.started,\n );\n}\n"]}
|
package/dist/session/rebuild.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* call is the host's, not the model's, so its entries build no message either.
|
|
7
7
|
*/
|
|
8
8
|
import { HarnessError } from "../errors.js";
|
|
9
|
+
import { ESCALATION_TOOL } from "./escalation-log.js";
|
|
9
10
|
const ordered = (blocks) => [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);
|
|
10
11
|
/** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */
|
|
11
12
|
class MessageBuilder {
|
|
@@ -186,10 +187,18 @@ export function contextWithStarts(path) {
|
|
|
186
187
|
for (const entry of path)
|
|
187
188
|
if (entry.type === "turn_start")
|
|
188
189
|
system = entry.system;
|
|
189
|
-
// A code call's result answers no call the model made, so the model never reads it.
|
|
190
|
-
|
|
190
|
+
// A code call's or a sandbox escalation's result answers no call the model made, so the model never reads it. Both
|
|
191
|
+
// are known by their call ids, never by the result's tool name: the model can call a tool named `sandbox.escalation`,
|
|
192
|
+
// and its error result must stay, or the rebuilt context would hold a tool call with no result.
|
|
193
|
+
const hostCalls = new Set(path.flatMap((entry) => {
|
|
194
|
+
if (entry.type === "code_call")
|
|
195
|
+
return [entry.callId];
|
|
196
|
+
if (entry.type === "approval_requested" && entry.request.tool === ESCALATION_TOOL)
|
|
197
|
+
return [entry.request.callId];
|
|
198
|
+
return [];
|
|
199
|
+
}));
|
|
191
200
|
for (const entry of entries) {
|
|
192
|
-
if (entry.type === "tool_result" &&
|
|
201
|
+
if (entry.type === "tool_result" && hostCalls.has(entry.callId))
|
|
193
202
|
continue;
|
|
194
203
|
switch (entry.type) {
|
|
195
204
|
case "message_block":
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rebuild.js","sourceRoot":"","sources":["../../src/session/rebuild.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAK5C,MAAM,OAAO,GAAG,CAAC,MAAwB,EAAkB,EAAE,CAC3D,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC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AAM,KAAK,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,CAAC;IAC3E,OAAO;QACL,OAAO,EAAE;YACP,MAAM;YACN,QAAQ;YACR,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;YAC9C,aAAa,EAAE,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;SAC3F;QACD,MAAM;KACP,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,SAAS,CAAC,IAA6B;IACrD,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Rebuilds the SDK's `Context` from a session's entries, so the log is the only state: any process can read the log\n * and go on with `continueRun()`. A message is the `message_block` entries that share a `messageId`, in `index` order;\n * an assistant message is closed by its `message_end` and takes its usage and cost from the `usage` entry right after\n * it. A `usage` entry anywhere else belongs to a call whose message was superseded, and builds no message. A code\n * call is the host's, not the model's, so its entries build no message either.\n */\n\nimport type { AssistantMessage, ContentBlock, Message } from \"@buildanagent/gateway\";\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Context, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\n\ntype Block = Extract<SessionEntry, { type: \"message_block\" }>;\ntype Pending = { role: \"user\" | \"assistant\"; id: string; blocks: Block[]; firstId: string };\n\nconst ordered = (blocks: readonly Block[]): ContentBlock[] =>\n [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);\n\n/** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */\nclass MessageBuilder {\n readonly messages: Message[] = [];\n /** The id of the first entry of each message, in step with `messages`. */\n readonly starts: string[] = [];\n #open: Pending | undefined;\n readonly #dropEmpty: ReadonlySet<string>;\n #ended: Extract<SessionEntry, { type: \"message_end\" }> | undefined;\n\n constructor(dropEmpty: ReadonlySet<string> = new Set()) {\n this.#dropEmpty = dropEmpty;\n }\n\n /** Closes the user message being built, if there is one. */\n #closeUser(): void {\n if (this.#open?.role !== \"user\") return;\n this.messages.push({ role: \"user\", content: ordered(this.#open.blocks) });\n this.starts.push(this.#open.firstId);\n this.#open = undefined;\n }\n\n block(entry: Block): void {\n this.#settleEnded(undefined);\n if (this.#open === undefined || this.#open.id !== entry.messageId || this.#open.role !== entry.role) {\n this.#closeUser();\n this.#open = { role: entry.role, id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#open.blocks.push(entry);\n }\n\n /** An assistant message with no usage entry after it still counts, with unknown cost. */\n #settleEnded(usage: Extract<SessionEntry, { type: \"usage\" }> | undefined): void {\n const end = this.#ended;\n const open = this.#open;\n if (end === undefined || open === undefined) return;\n this.#ended = undefined;\n this.#open = undefined;\n // A message whose signed reasoning was left out and that has nothing else would be an empty assistant turn.\n if (open.blocks.length === 0 && this.#dropEmpty.has(open.id)) return;\n const message: AssistantMessage = {\n role: \"assistant\",\n content: ordered(open.blocks),\n model: end.model,\n stopReason: end.stopReason,\n ...(end.error === undefined ? {} : { error: end.error }),\n usage: usage?.usage ?? EMPTY_USAGE,\n ...(usage?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: usage.lastAttemptUsage }),\n cost: usage?.cost ?? EMPTY_COST,\n };\n this.messages.push(message);\n this.starts.push(open.firstId);\n }\n\n end(entry: Extract<SessionEntry, { type: \"message_end\" }>): void {\n this.#settleEnded(undefined);\n if (this.#open?.role !== \"assistant\" || this.#open.id !== entry.messageId) {\n // A message with no blocks has no open message to close.\n this.#closeUser();\n this.#open = { role: \"assistant\", id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#ended = entry;\n }\n\n usage(entry: Extract<SessionEntry, { type: \"usage\" }>): void {\n if (entry.source === \"model_call\" && this.#ended !== undefined) this.#settleEnded(entry);\n }\n\n toolResult(entry: Extract<SessionEntry, { type: \"tool_result\" }>): void {\n this.#settleEnded(undefined);\n this.#closeUser();\n this.messages.push({ role: \"tool\", callId: entry.callId, content: entry.content, isError: entry.isError });\n this.starts.push(entry.id);\n }\n\n finish(): Message[] {\n this.#settleEnded(undefined);\n this.#closeUser();\n return this.messages;\n }\n}\n\n// A message with no usage entry, which a crash between the two writes leaves, has no usage anyone knows.\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n uncachedInput: 0,\n cacheRead: 0,\n cacheWrite: { \"5m\": 0, \"1h\": 0 },\n output: 0,\n reasoning: 0,\n raw: null,\n};\nconst EMPTY_COST: AssistantMessage[\"cost\"] = { total: null, basis: \"unknown\", currency: \"USD\" };\n\n/** A request that waits for a person, with the input its call would run with once approved. */\nexport interface PendingApproval {\n readonly request: SignedPendingRequest;\n readonly input: unknown;\n}\n\n/**\n * The requests on `path` that still wait: the latest request for each call of the last assistant message, while the call\n * has no result. A resolution does not end a wait, because the run that applies it may refuse it or never finish: only\n * the call's result does. A resume that started and died before the result is a crash, which `crashedResumes()` names,\n * and its requests do not wait.\n */\nexport function pendingApprovals(path: readonly SessionEntry[]): PendingApproval[] {\n const answered = new Set<string>();\n const latest = new Map<string, PendingApproval>();\n let lastMessage: string | undefined;\n let lastCalls = new Set<string>();\n for (const entry of path) {\n if (entry.type === \"tool_result\") answered.add(entry.callId);\n if (entry.type === \"approval_requested\")\n latest.set(entry.request.callId, { request: entry.request, input: entry.input });\n if (entry.type === \"message_block\" && entry.role === \"assistant\") {\n if (entry.messageId !== lastMessage) lastCalls = new Set();\n lastMessage = entry.messageId;\n if (entry.block.type === \"tool_call\") lastCalls.add(entry.block.callId);\n }\n }\n const crashed = crashedResumes(path);\n return [...latest.values()].filter(\n (entry) =>\n lastCalls.has(entry.request.callId) && !answered.has(entry.request.callId) && !crashed.has(entry.request.id),\n );\n}\n\n/**\n * The ids of the requests whose resume started and died: the log ends in a `continue` turn that has no end, after\n * allows were written for it. An approved call may have run, so it is settled as a crash and not asked again, even\n * when the run died before it reached that call.\n */\nexport function crashedResumes(path: readonly SessionEntry[]): Set<string> {\n const start = path.findLastIndex((entry) => entry.type === \"turn_start\");\n const turn = path[start];\n if (turn?.type !== \"turn_start\" || turn.mode !== \"continue\") return new Set();\n if (path.slice(start).some((entry) => entry.type === \"turn_end\")) return new Set();\n // Only the allows this run was given: a deny or an answer runs nothing, and an earlier run's answers are its own.\n const since = path.slice(0, start).findLastIndex((entry) => entry.type === \"turn_end\");\n return new Set(\n path.slice(since + 1, start).flatMap((entry) => {\n const answer = entry.type === \"approval_resolved\" && entry.quorum === undefined ? entry.resolution : undefined;\n return answer !== undefined && \"decision\" in answer && answer.decision === \"allow\" ? [answer.requestId] : [];\n }),\n );\n}\n\nconst isSignedReasoning = (entry: SessionEntry): boolean =>\n entry.type === \"message_block\" && entry.block.type === \"reasoning\" && entry.block.signature !== undefined;\n\n/** The user message that stands for the summarised span, so the model reads the summary where the span was. */\nexport function summaryMessage(summary: string): Message {\n return {\n role: \"user\",\n content: [\n { type: \"text\", text: `The earlier part of this conversation was summarized to save space:\\n\\n${summary}` },\n ],\n };\n}\n\n/**\n * The entries a context is built from, and whether a compaction applies. The latest `compaction` on the path replaces\n * everything before its `firstKeptEntryId`. The kept tail loses its signed reasoning, because a block that follows the\n * edited span would carry a signature the summary made stale; blocks written after the compaction are untouched.\n */\nexport function entriesAfterCompaction(path: readonly SessionEntry[]): {\n readonly entries: readonly SessionEntry[];\n readonly summary: string | undefined;\n /** The ids of messages that lost a signed reasoning block. */\n readonly stripped: ReadonlySet<string>;\n} {\n const at = path.findLastIndex((entry) => entry.type === \"compaction\");\n const compaction = path[at];\n if (compaction?.type !== \"compaction\") return { entries: path, summary: undefined, stripped: new Set() };\n const kept = path.findIndex((entry) => entry.id === compaction.firstKeptEntryId);\n if (kept < 0) {\n throw new HarnessError(\n \"entry_not_found\",\n `the compaction ${compaction.id} keeps from entry ${compaction.firstKeptEntryId}, which is not on this path`,\n );\n }\n // The messages that lose a block here are the only ones an empty result may drop.\n const stripped = new Set<string>();\n const entries = path.slice(kept).filter((entry, i) => {\n const drop = kept + i < at && isSignedReasoning(entry);\n if (drop && entry.type === \"message_block\") stripped.add(entry.messageId);\n return !drop;\n });\n return { entries: entries.filter((entry) => entry.type !== \"compaction\"), summary: compaction.summary, stripped };\n}\n\n/**\n * The context a path of entries stands for, with the id of the entry each message starts at (`null` for a summary).\n * `path` is a session's `path()`: the root to a HEAD, without `checkout` entries. The system prompt is the latest\n * `turn_start`'s, byte for byte, so a harness whose prompt changed later still rebuilds the conversation the model\n * saw. The latest compaction applies: its summary stands first, then the kept tail and what followed it.\n */\nexport function contextWithStarts(path: readonly SessionEntry[]): {\n readonly context: Context;\n readonly starts: readonly (string | null)[];\n} {\n const { entries, summary, stripped } = entriesAfterCompaction(path);\n const builder = new MessageBuilder(stripped);\n let system = \"\";\n for (const entry of path) if (entry.type === \"turn_start\") system = entry.system;\n // A code call's result answers no call the model made, so the model never reads it.\n const codeCalls = new Set(path.flatMap((entry) => (entry.type === \"code_call\" ? [entry.callId] : [])));\n for (const entry of entries) {\n if (entry.type === \"tool_result\" && codeCalls.has(entry.callId)) continue;\n switch (entry.type) {\n case \"message_block\":\n builder.block(entry);\n break;\n case \"message_end\":\n builder.end(entry);\n break;\n case \"usage\":\n builder.usage(entry);\n break;\n case \"tool_result\":\n builder.toolResult(entry);\n break;\n default:\n }\n }\n const built = builder.finish();\n const messages = summary === undefined ? built : [summaryMessage(summary), ...built];\n const starts = summary === undefined ? builder.starts : [null, ...builder.starts];\n const waiting = pendingApprovals(path);\n if (waiting.length === 0) return { context: { system, messages }, starts };\n return {\n context: {\n system,\n messages,\n pending: waiting.map((entry) => entry.request),\n pendingInputs: Object.fromEntries(waiting.map((entry) => [entry.request.id, entry.input])),\n },\n starts,\n };\n}\n\n/** The context a path of entries stands for. See `contextWithStarts()`. */\nexport function contextOf(path: readonly SessionEntry[]): Context {\n return contextWithStarts(path).context;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rebuild.js","sourceRoot":"","sources":["../../src/session/rebuild.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAKtD,MAAM,OAAO,GAAG,CAAC,MAAwB,EAAkB,EAAE,CAC3D,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAE5E,+GAA+G;AAC/G,MAAM,cAAc;IACT,QAAQ,GAAc,EAAE,CAAC;IAClC,0EAA0E;IACjE,MAAM,GAAa,EAAE,CAAC;IAC/B,KAAK,CAAsB;IAClB,UAAU,CAAsB;IACzC,MAAM,CAA6D;IAEnE,YAAY,SAAS,GAAwB,IAAI,GAAG,EAAE;QACpD,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAED,4DAA4D;IAC5D,UAAU;QACR,IAAI,IAAI,CAAC,KAAK,EAAE,IAAI,KAAK,MAAM;YAAE,OAAO;QACxC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC1E,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;IACzB,CAAC;IAED,KAAK,CAAC,KAAY;QAChB,IAAI,CAAC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from a session's entries, so the log is the only state: any process can read the log\n * and go on with `continueRun()`. A message is the `message_block` entries that share a `messageId`, in `index` order;\n * an assistant message is closed by its `message_end` and takes its usage and cost from the `usage` entry right after\n * it. A `usage` entry anywhere else belongs to a call whose message was superseded, and builds no message. A code\n * call is the host's, not the model's, so its entries build no message either.\n */\n\nimport type { AssistantMessage, ContentBlock, Message } from \"@buildanagent/gateway\";\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Context, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport { ESCALATION_TOOL } from \"./escalation-log.js\";\n\ntype Block = Extract<SessionEntry, { type: \"message_block\" }>;\ntype Pending = { role: \"user\" | \"assistant\"; id: string; blocks: Block[]; firstId: string };\n\nconst ordered = (blocks: readonly Block[]): ContentBlock[] =>\n [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);\n\n/** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */\nclass MessageBuilder {\n readonly messages: Message[] = [];\n /** The id of the first entry of each message, in step with `messages`. */\n readonly starts: string[] = [];\n #open: Pending | undefined;\n readonly #dropEmpty: ReadonlySet<string>;\n #ended: Extract<SessionEntry, { type: \"message_end\" }> | undefined;\n\n constructor(dropEmpty: ReadonlySet<string> = new Set()) {\n this.#dropEmpty = dropEmpty;\n }\n\n /** Closes the user message being built, if there is one. */\n #closeUser(): void {\n if (this.#open?.role !== \"user\") return;\n this.messages.push({ role: \"user\", content: ordered(this.#open.blocks) });\n this.starts.push(this.#open.firstId);\n this.#open = undefined;\n }\n\n block(entry: Block): void {\n this.#settleEnded(undefined);\n if (this.#open === undefined || this.#open.id !== entry.messageId || this.#open.role !== entry.role) {\n this.#closeUser();\n this.#open = { role: entry.role, id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#open.blocks.push(entry);\n }\n\n /** An assistant message with no usage entry after it still counts, with unknown cost. */\n #settleEnded(usage: Extract<SessionEntry, { type: \"usage\" }> | undefined): void {\n const end = this.#ended;\n const open = this.#open;\n if (end === undefined || open === undefined) return;\n this.#ended = undefined;\n this.#open = undefined;\n // A message whose signed reasoning was left out and that has nothing else would be an empty assistant turn.\n if (open.blocks.length === 0 && this.#dropEmpty.has(open.id)) return;\n const message: AssistantMessage = {\n role: \"assistant\",\n content: ordered(open.blocks),\n model: end.model,\n stopReason: end.stopReason,\n ...(end.error === undefined ? {} : { error: end.error }),\n usage: usage?.usage ?? EMPTY_USAGE,\n ...(usage?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: usage.lastAttemptUsage }),\n cost: usage?.cost ?? EMPTY_COST,\n };\n this.messages.push(message);\n this.starts.push(open.firstId);\n }\n\n end(entry: Extract<SessionEntry, { type: \"message_end\" }>): void {\n this.#settleEnded(undefined);\n if (this.#open?.role !== \"assistant\" || this.#open.id !== entry.messageId) {\n // A message with no blocks has no open message to close.\n this.#closeUser();\n this.#open = { role: \"assistant\", id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#ended = entry;\n }\n\n usage(entry: Extract<SessionEntry, { type: \"usage\" }>): void {\n if (entry.source === \"model_call\" && this.#ended !== undefined) this.#settleEnded(entry);\n }\n\n toolResult(entry: Extract<SessionEntry, { type: \"tool_result\" }>): void {\n this.#settleEnded(undefined);\n this.#closeUser();\n this.messages.push({ role: \"tool\", callId: entry.callId, content: entry.content, isError: entry.isError });\n this.starts.push(entry.id);\n }\n\n finish(): Message[] {\n this.#settleEnded(undefined);\n this.#closeUser();\n return this.messages;\n }\n}\n\n// A message with no usage entry, which a crash between the two writes leaves, has no usage anyone knows.\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n uncachedInput: 0,\n cacheRead: 0,\n cacheWrite: { \"5m\": 0, \"1h\": 0 },\n output: 0,\n reasoning: 0,\n raw: null,\n};\nconst EMPTY_COST: AssistantMessage[\"cost\"] = { total: null, basis: \"unknown\", currency: \"USD\" };\n\n/** A request that waits for a person, with the input its call would run with once approved. */\nexport interface PendingApproval {\n readonly request: SignedPendingRequest;\n readonly input: unknown;\n}\n\n/**\n * The requests on `path` that still wait: the latest request for each call of the last assistant message, while the call\n * has no result. A resolution does not end a wait, because the run that applies it may refuse it or never finish: only\n * the call's result does. A resume that started and died before the result is a crash, which `crashedResumes()` names,\n * and its requests do not wait.\n */\nexport function pendingApprovals(path: readonly SessionEntry[]): PendingApproval[] {\n const answered = new Set<string>();\n const latest = new Map<string, PendingApproval>();\n let lastMessage: string | undefined;\n let lastCalls = new Set<string>();\n for (const entry of path) {\n if (entry.type === \"tool_result\") answered.add(entry.callId);\n if (entry.type === \"approval_requested\")\n latest.set(entry.request.callId, { request: entry.request, input: entry.input });\n if (entry.type === \"message_block\" && entry.role === \"assistant\") {\n if (entry.messageId !== lastMessage) lastCalls = new Set();\n lastMessage = entry.messageId;\n if (entry.block.type === \"tool_call\") lastCalls.add(entry.block.callId);\n }\n }\n const crashed = crashedResumes(path);\n return [...latest.values()].filter(\n (entry) =>\n lastCalls.has(entry.request.callId) && !answered.has(entry.request.callId) && !crashed.has(entry.request.id),\n );\n}\n\n/**\n * The ids of the requests whose resume started and died: the log ends in a `continue` turn that has no end, after\n * allows were written for it. An approved call may have run, so it is settled as a crash and not asked again, even\n * when the run died before it reached that call.\n */\nexport function crashedResumes(path: readonly SessionEntry[]): Set<string> {\n const start = path.findLastIndex((entry) => entry.type === \"turn_start\");\n const turn = path[start];\n if (turn?.type !== \"turn_start\" || turn.mode !== \"continue\") return new Set();\n if (path.slice(start).some((entry) => entry.type === \"turn_end\")) return new Set();\n // Only the allows this run was given: a deny or an answer runs nothing, and an earlier run's answers are its own.\n const since = path.slice(0, start).findLastIndex((entry) => entry.type === \"turn_end\");\n return new Set(\n path.slice(since + 1, start).flatMap((entry) => {\n const answer = entry.type === \"approval_resolved\" && entry.quorum === undefined ? entry.resolution : undefined;\n return answer !== undefined && \"decision\" in answer && answer.decision === \"allow\" ? [answer.requestId] : [];\n }),\n );\n}\n\nconst isSignedReasoning = (entry: SessionEntry): boolean =>\n entry.type === \"message_block\" && entry.block.type === \"reasoning\" && entry.block.signature !== undefined;\n\n/** The user message that stands for the summarised span, so the model reads the summary where the span was. */\nexport function summaryMessage(summary: string): Message {\n return {\n role: \"user\",\n content: [\n { type: \"text\", text: `The earlier part of this conversation was summarized to save space:\\n\\n${summary}` },\n ],\n };\n}\n\n/**\n * The entries a context is built from, and whether a compaction applies. The latest `compaction` on the path replaces\n * everything before its `firstKeptEntryId`. The kept tail loses its signed reasoning, because a block that follows the\n * edited span would carry a signature the summary made stale; blocks written after the compaction are untouched.\n */\nexport function entriesAfterCompaction(path: readonly SessionEntry[]): {\n readonly entries: readonly SessionEntry[];\n readonly summary: string | undefined;\n /** The ids of messages that lost a signed reasoning block. */\n readonly stripped: ReadonlySet<string>;\n} {\n const at = path.findLastIndex((entry) => entry.type === \"compaction\");\n const compaction = path[at];\n if (compaction?.type !== \"compaction\") return { entries: path, summary: undefined, stripped: new Set() };\n const kept = path.findIndex((entry) => entry.id === compaction.firstKeptEntryId);\n if (kept < 0) {\n throw new HarnessError(\n \"entry_not_found\",\n `the compaction ${compaction.id} keeps from entry ${compaction.firstKeptEntryId}, which is not on this path`,\n );\n }\n // The messages that lose a block here are the only ones an empty result may drop.\n const stripped = new Set<string>();\n const entries = path.slice(kept).filter((entry, i) => {\n const drop = kept + i < at && isSignedReasoning(entry);\n if (drop && entry.type === \"message_block\") stripped.add(entry.messageId);\n return !drop;\n });\n return { entries: entries.filter((entry) => entry.type !== \"compaction\"), summary: compaction.summary, stripped };\n}\n\n/**\n * The context a path of entries stands for, with the id of the entry each message starts at (`null` for a summary).\n * `path` is a session's `path()`: the root to a HEAD, without `checkout` entries. The system prompt is the latest\n * `turn_start`'s, byte for byte, so a harness whose prompt changed later still rebuilds the conversation the model\n * saw. The latest compaction applies: its summary stands first, then the kept tail and what followed it.\n */\nexport function contextWithStarts(path: readonly SessionEntry[]): {\n readonly context: Context;\n readonly starts: readonly (string | null)[];\n} {\n const { entries, summary, stripped } = entriesAfterCompaction(path);\n const builder = new MessageBuilder(stripped);\n let system = \"\";\n for (const entry of path) if (entry.type === \"turn_start\") system = entry.system;\n // A code call's or a sandbox escalation's result answers no call the model made, so the model never reads it. Both\n // are known by their call ids, never by the result's tool name: the model can call a tool named `sandbox.escalation`,\n // and its error result must stay, or the rebuilt context would hold a tool call with no result.\n const hostCalls = new Set(\n path.flatMap((entry) => {\n if (entry.type === \"code_call\") return [entry.callId];\n if (entry.type === \"approval_requested\" && entry.request.tool === ESCALATION_TOOL) return [entry.request.callId];\n return [];\n }),\n );\n for (const entry of entries) {\n if (entry.type === \"tool_result\" && hostCalls.has(entry.callId)) continue;\n switch (entry.type) {\n case \"message_block\":\n builder.block(entry);\n break;\n case \"message_end\":\n builder.end(entry);\n break;\n case \"usage\":\n builder.usage(entry);\n break;\n case \"tool_result\":\n builder.toolResult(entry);\n break;\n default:\n }\n }\n const built = builder.finish();\n const messages = summary === undefined ? built : [summaryMessage(summary), ...built];\n const starts = summary === undefined ? builder.starts : [null, ...builder.starts];\n const waiting = pendingApprovals(path);\n if (waiting.length === 0) return { context: { system, messages }, starts };\n return {\n context: {\n system,\n messages,\n pending: waiting.map((entry) => entry.request),\n pendingInputs: Object.fromEntries(waiting.map((entry) => [entry.request.id, entry.input])),\n },\n starts,\n };\n}\n\n/** The context a path of entries stands for. See `contextWithStarts()`. */\nexport function contextOf(path: readonly SessionEntry[]): Context {\n return contextWithStarts(path).context;\n}\n"]}
|
|
@@ -1,8 +1,15 @@
|
|
|
1
|
-
import type { SandboxClient } from "../sandbox/types.js";
|
|
1
|
+
import type { SandboxClient, SandboxPolicy, SandboxStop } from "../sandbox/types.js";
|
|
2
2
|
/** The options of `fakeSandbox()`. */
|
|
3
3
|
export interface FakeSandboxOptions {
|
|
4
4
|
/** Makes `provision()` throw `SandboxUnavailableError` with this reason, as a backend that can't start does. */
|
|
5
5
|
readonly unavailable?: string;
|
|
6
|
+
/**
|
|
7
|
+
* The policy the fake applies and reads back instead of the requested one, as a hosted provider's account-wide
|
|
8
|
+
* override would. `provision()` then throws `SandboxPolicyMismatchError` when the two differ.
|
|
9
|
+
*/
|
|
10
|
+
readonly applied?: (requested: SandboxPolicy) => SandboxPolicy;
|
|
11
|
+
/** The stops the fake claims. Defaults to `mistakes` and `exfiltration`, which its in-memory checks deliver. */
|
|
12
|
+
readonly stops?: readonly SandboxStop[];
|
|
6
13
|
}
|
|
7
14
|
/** One command the fake received, with what the caller passed. */
|
|
8
15
|
export interface RecordedExec {
|
|
@@ -24,11 +31,22 @@ export interface FakeSandboxClient extends SandboxClient {
|
|
|
24
31
|
* The commands the fake runs, in the form `[name, ...arguments]`: `echo` prints its arguments, `env` prints the
|
|
25
32
|
* environment it was given as `NAME=value` lines, `cat <path>` prints a file, `write <path> <text>` writes one,
|
|
26
33
|
* `true` and `false` exit with 0 and 1, `sleep <seconds>` waits and honours the timeout and the signal, and
|
|
27
|
-
* `net-probe <host>` reaches a host only if the policy allows it.
|
|
34
|
+
* `net-probe <host>` reaches a host only if the policy allows it. `find <dir>` lists the files under a folder, one per
|
|
35
|
+
* line or ending in NUL with `-print0`. When the command has `-prune`, it leaves out every folder named by a `-name`,
|
|
36
|
+
* the starting folder included. A `! -path <start>` exempts the starting folder. It exits with 0 and prints nothing for a folder
|
|
37
|
+
* with no files, and with 1 for a path that does not exist. `grep [-i] -e <pattern> -- <file>...` prints each
|
|
38
|
+
* matching line as `file:line:text`, reading the pattern as a JavaScript regular expression and skipping a file that
|
|
39
|
+
* holds a NUL byte. It exits with 1 when nothing matches, and with 2 after a missing file or a pattern it can't read,
|
|
40
|
+
* as grep does. A command that runs past its timeout exits with 124 and `timedOut: true`, and each stream keeps at
|
|
41
|
+
* most `maxOutputBytes`, with `truncated: true` when more was dropped.
|
|
42
|
+
* `bash -c <script>` and `sh -c <script>` split the script on whitespace and run its words as one of these commands,
|
|
43
|
+
* with no shell syntax. Any other command exits with 127.
|
|
28
44
|
*/
|
|
29
45
|
export declare const FAKE_COMMANDS: readonly string[];
|
|
30
46
|
/**
|
|
31
47
|
* Builds a fake backend with the tier `os` and the stops `mistakes` and `exfiltration`, because it enforces the
|
|
32
|
-
* policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none.
|
|
48
|
+
* policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none. It reads
|
|
49
|
+
* its policy back as a real backend does, so `provision()` throws `SandboxPolicyMismatchError` when `applied` changes
|
|
50
|
+
* the policy.
|
|
33
51
|
*/
|
|
34
52
|
export declare function fakeSandbox(options?: FakeSandboxOptions): FakeSandboxClient;
|
|
@@ -5,15 +5,40 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { HarnessError } from "../errors.js";
|
|
7
7
|
import { SandboxDeniedError, SandboxUnavailableError } from "../sandbox/errors.js";
|
|
8
|
+
import { confirmPolicy } from "../sandbox/policy.js";
|
|
8
9
|
/**
|
|
9
10
|
* The commands the fake runs, in the form `[name, ...arguments]`: `echo` prints its arguments, `env` prints the
|
|
10
11
|
* environment it was given as `NAME=value` lines, `cat <path>` prints a file, `write <path> <text>` writes one,
|
|
11
12
|
* `true` and `false` exit with 0 and 1, `sleep <seconds>` waits and honours the timeout and the signal, and
|
|
12
|
-
* `net-probe <host>` reaches a host only if the policy allows it.
|
|
13
|
+
* `net-probe <host>` reaches a host only if the policy allows it. `find <dir>` lists the files under a folder, one per
|
|
14
|
+
* line or ending in NUL with `-print0`. When the command has `-prune`, it leaves out every folder named by a `-name`,
|
|
15
|
+
* the starting folder included. A `! -path <start>` exempts the starting folder. It exits with 0 and prints nothing for a folder
|
|
16
|
+
* with no files, and with 1 for a path that does not exist. `grep [-i] -e <pattern> -- <file>...` prints each
|
|
17
|
+
* matching line as `file:line:text`, reading the pattern as a JavaScript regular expression and skipping a file that
|
|
18
|
+
* holds a NUL byte. It exits with 1 when nothing matches, and with 2 after a missing file or a pattern it can't read,
|
|
19
|
+
* as grep does. A command that runs past its timeout exits with 124 and `timedOut: true`, and each stream keeps at
|
|
20
|
+
* most `maxOutputBytes`, with `truncated: true` when more was dropped.
|
|
21
|
+
* `bash -c <script>` and `sh -c <script>` split the script on whitespace and run its words as one of these commands,
|
|
22
|
+
* with no shell syntax. Any other command exits with 127.
|
|
13
23
|
*/
|
|
14
|
-
export const FAKE_COMMANDS = [
|
|
24
|
+
export const FAKE_COMMANDS = [
|
|
25
|
+
"echo",
|
|
26
|
+
"env",
|
|
27
|
+
"cat",
|
|
28
|
+
"write",
|
|
29
|
+
"true",
|
|
30
|
+
"false",
|
|
31
|
+
"sleep",
|
|
32
|
+
"net-probe",
|
|
33
|
+
"find",
|
|
34
|
+
"grep",
|
|
35
|
+
"bash",
|
|
36
|
+
"sh",
|
|
37
|
+
];
|
|
15
38
|
const ENCODER = new TextEncoder();
|
|
16
39
|
const DECODER = new TextDecoder();
|
|
40
|
+
// What a real backend keeps of each stream when the caller names no cap.
|
|
41
|
+
const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
|
17
42
|
function normalize(path) {
|
|
18
43
|
const parts = [];
|
|
19
44
|
for (const part of path.split("/")) {
|
|
@@ -26,12 +51,41 @@ function normalize(path) {
|
|
|
26
51
|
}
|
|
27
52
|
return `/${parts.join("/")}`;
|
|
28
53
|
}
|
|
54
|
+
/** The lines of `text` that match, as `grep -n -H` prints them. */
|
|
55
|
+
function matchingLines(file, text, pattern) {
|
|
56
|
+
const lines = text.endsWith("\n") ? text.slice(0, -1).split("\n") : text.split("\n");
|
|
57
|
+
return lines.map((line, index) => (pattern.test(line) ? `${file}:${index + 1}:${line}\n` : "")).join("");
|
|
58
|
+
}
|
|
59
|
+
/** A `find -path` pattern with its backslash escapes removed, as the literal path it names. */
|
|
60
|
+
const literalOf = (pattern) => pattern?.replace(/\\(.)/g, "$1");
|
|
61
|
+
/** `text` cut to its first `bytes` UTF-8 bytes, never splitting a character, and whether anything was cut. */
|
|
62
|
+
function capped(text, bytes) {
|
|
63
|
+
const encoded = ENCODER.encode(text);
|
|
64
|
+
if (encoded.length <= bytes)
|
|
65
|
+
return { text, cut: false };
|
|
66
|
+
let end = bytes;
|
|
67
|
+
while (end > 0 && (encoded[end] & 0b1100_0000) === 0b1000_0000)
|
|
68
|
+
end -= 1;
|
|
69
|
+
return { text: DECODER.decode(encoded.subarray(0, end)), cut: true };
|
|
70
|
+
}
|
|
71
|
+
/** The pattern of a `grep` command's flags, or the result grep gives for a pattern it can't read. */
|
|
72
|
+
function patternOf(flags) {
|
|
73
|
+
const at = flags.indexOf("-e");
|
|
74
|
+
try {
|
|
75
|
+
return new RegExp(at < 0 ? "" : (flags[at + 1] ?? ""), flags.includes("-i") ? "i" : "");
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
// grep reports a pattern it can't read on standard error and exits with 2, before it reads any file.
|
|
79
|
+
return { exitCode: 2, stdout: "", stderr: `grep: ${error.message}\n` };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
29
82
|
const within = (path, root) => {
|
|
30
83
|
const base = normalize(root);
|
|
31
84
|
return base === "/" || path === base || path.startsWith(`${base}/`);
|
|
32
85
|
};
|
|
33
86
|
class FakeSandbox {
|
|
34
87
|
disposed = false;
|
|
88
|
+
stops = [];
|
|
35
89
|
// What ends each command still running, so `dispose()` can reject them as a real backend does.
|
|
36
90
|
running = new Set();
|
|
37
91
|
store = new Map();
|
|
@@ -48,6 +102,16 @@ class FakeSandbox {
|
|
|
48
102
|
if (this.disposed)
|
|
49
103
|
throw new HarnessError("sandbox_disposed", "the sandbox was disposed");
|
|
50
104
|
}
|
|
105
|
+
/** The policy the fake enforces, as a copy. */
|
|
106
|
+
async readBack() {
|
|
107
|
+
this.live();
|
|
108
|
+
const { readRoots, writeRoots, network } = this.policy;
|
|
109
|
+
return {
|
|
110
|
+
readRoots: [...readRoots],
|
|
111
|
+
writeRoots: [...writeRoots],
|
|
112
|
+
network: { allow: [...network.allow], deny: [...network.deny] },
|
|
113
|
+
};
|
|
114
|
+
}
|
|
51
115
|
/** The absolute path a name stands for: joined to the root, tidied of `.` and `..`, then followed through links. */
|
|
52
116
|
resolve(path, base = this.root) {
|
|
53
117
|
const tidy = normalize(path.startsWith("/") ? path : `${base}/${path}`);
|
|
@@ -109,7 +173,16 @@ class FakeSandbox {
|
|
|
109
173
|
return { denied: denial };
|
|
110
174
|
this.log.push({ command: [...command], cwd: options.cwd, env: { ...options.env }, timeoutMs: options.timeoutMs });
|
|
111
175
|
const [name = "", ...args] = command;
|
|
112
|
-
|
|
176
|
+
const result = await this.run(name, args, options);
|
|
177
|
+
if ("denied" in result)
|
|
178
|
+
return result;
|
|
179
|
+
// Each stream keeps at most `maxOutputBytes`, as a real backend's does.
|
|
180
|
+
const limit = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
|
181
|
+
const stdout = capped(result.stdout, limit);
|
|
182
|
+
const stderr = capped(result.stderr, limit);
|
|
183
|
+
if (!stdout.cut && !stderr.cut)
|
|
184
|
+
return result;
|
|
185
|
+
return { ...result, stdout: stdout.text, stderr: stderr.text, truncated: true };
|
|
113
186
|
}
|
|
114
187
|
async run(name, args, options) {
|
|
115
188
|
const ok = (stdout = "") => ({ exitCode: 0, stdout, stderr: "" });
|
|
@@ -135,6 +208,13 @@ class FakeSandbox {
|
|
|
135
208
|
}
|
|
136
209
|
case "sleep":
|
|
137
210
|
return this.sleep(Number(args[0] ?? 0) * 1000, options);
|
|
211
|
+
case "find":
|
|
212
|
+
return this.find(args);
|
|
213
|
+
case "grep":
|
|
214
|
+
return this.grep(args);
|
|
215
|
+
case "bash":
|
|
216
|
+
case "sh":
|
|
217
|
+
return this.shell(args, options);
|
|
138
218
|
default:
|
|
139
219
|
return { exitCode: 127, stdout: "", stderr: `command not found: ${name}\n` };
|
|
140
220
|
}
|
|
@@ -149,6 +229,69 @@ class FakeSandbox {
|
|
|
149
229
|
? { exitCode: 1, stdout: "", stderr: `no such file: ${target}\n` }
|
|
150
230
|
: { exitCode: 0, stdout: DECODER.decode(data), stderr: "" };
|
|
151
231
|
}
|
|
232
|
+
/** The script's words as one command, so a test can drive a shell tool without a shell. */
|
|
233
|
+
shell(args, options) {
|
|
234
|
+
if (args[0] !== "-c")
|
|
235
|
+
return Promise.resolve({ exitCode: 2, stdout: "", stderr: "the fake shell runs only -c\n" });
|
|
236
|
+
const [name = "", ...rest] = (args[1] ?? "").trim().split(/\s+/);
|
|
237
|
+
return this.run(name, rest, options);
|
|
238
|
+
}
|
|
239
|
+
/** Whether `path` is a folder: the root, a folder above it, or a folder that holds a file. */
|
|
240
|
+
isFolder(path) {
|
|
241
|
+
if (within(this.root, path))
|
|
242
|
+
return true;
|
|
243
|
+
const prefix = path === "/" ? "/" : `${path}/`;
|
|
244
|
+
return [...this.store.keys()].some((file) => file.startsWith(prefix));
|
|
245
|
+
}
|
|
246
|
+
find(args) {
|
|
247
|
+
const start = this.resolve(args[0] ?? ".");
|
|
248
|
+
const denial = this.readDenial(start);
|
|
249
|
+
if (denial)
|
|
250
|
+
return { denied: denial };
|
|
251
|
+
if (!this.store.has(start) && !this.isFolder(start)) {
|
|
252
|
+
return { exitCode: 1, stdout: "", stderr: `find: '${args[0] ?? "."}': No such file or directory\n` };
|
|
253
|
+
}
|
|
254
|
+
const named = args.flatMap((arg, index) => (arg === "-name" ? [args[index + 1] ?? ""] : []));
|
|
255
|
+
const pruned = new Set(args.includes("-prune") ? named : []);
|
|
256
|
+
// `! -path <start>` exempts the starting point from the prune, as it does for find; without it the prune tests
|
|
257
|
+
// the starting point's own name too, so a search that starts in a pruned folder finds nothing.
|
|
258
|
+
const exempt = args.some((arg, index) => arg === "!" && args[index + 1] === "-path" && literalOf(args[index + 2]) === start);
|
|
259
|
+
const ownName = start.split("/").at(-1) ?? "";
|
|
260
|
+
if (!exempt && ownName !== "" && pruned.has(ownName))
|
|
261
|
+
return { exitCode: 0, stdout: "", stderr: "" };
|
|
262
|
+
const files = [...this.store.keys()]
|
|
263
|
+
.filter((path) => path === start || path.startsWith(`${start === "/" ? "" : start}/`))
|
|
264
|
+
.filter((path) => !path
|
|
265
|
+
.slice(start.length)
|
|
266
|
+
.split("/")
|
|
267
|
+
.some((part) => pruned.has(part)))
|
|
268
|
+
.sort();
|
|
269
|
+
const end = args.includes("-print0") ? "\0" : "\n";
|
|
270
|
+
return { exitCode: 0, stdout: files.map((path) => `${path}${end}`).join(""), stderr: "" };
|
|
271
|
+
}
|
|
272
|
+
grep(args) {
|
|
273
|
+
const split = args.indexOf("--");
|
|
274
|
+
const flags = split < 0 ? args : args.slice(0, split);
|
|
275
|
+
const files = split < 0 ? [] : args.slice(split + 1);
|
|
276
|
+
const pattern = patternOf(flags);
|
|
277
|
+
if (!(pattern instanceof RegExp))
|
|
278
|
+
return pattern;
|
|
279
|
+
let stdout = "";
|
|
280
|
+
let stderr = "";
|
|
281
|
+
for (const file of files) {
|
|
282
|
+
const target = this.resolve(file);
|
|
283
|
+
const denial = this.readDenial(target);
|
|
284
|
+
if (denial)
|
|
285
|
+
return { denied: denial };
|
|
286
|
+
const data = this.store.get(target);
|
|
287
|
+
if (data === undefined)
|
|
288
|
+
stderr += `grep: ${file}: No such file or directory\n`;
|
|
289
|
+
else if (!data.includes(0))
|
|
290
|
+
stdout += matchingLines(file, DECODER.decode(data), pattern);
|
|
291
|
+
}
|
|
292
|
+
// grep exits with 2 after any error, even when other files matched.
|
|
293
|
+
return { exitCode: stderr !== "" ? 2 : stdout === "" ? 1 : 0, stdout, stderr };
|
|
294
|
+
}
|
|
152
295
|
writeCommand(path, text) {
|
|
153
296
|
const target = this.resolve(path);
|
|
154
297
|
const denial = this.writeDenial(target);
|
|
@@ -179,7 +322,9 @@ class FakeSandbox {
|
|
|
179
322
|
const stopAt = options.timeoutMs !== undefined && options.timeoutMs < ms ? options.timeoutMs : ms;
|
|
180
323
|
const timer = setTimeout(() => {
|
|
181
324
|
const timedOut = stopAt < ms;
|
|
182
|
-
done(
|
|
325
|
+
done(timedOut
|
|
326
|
+
? { exitCode: 124, stdout: "", stderr: `timed out after ${stopAt} ms\n`, timedOut: true }
|
|
327
|
+
: { exitCode: 0, stdout: "", stderr: "" });
|
|
183
328
|
}, stopAt);
|
|
184
329
|
options.signal.addEventListener("abort", aborted, { once: true });
|
|
185
330
|
});
|
|
@@ -193,14 +338,16 @@ class FakeSandbox {
|
|
|
193
338
|
}
|
|
194
339
|
/**
|
|
195
340
|
* Builds a fake backend with the tier `os` and the stops `mistakes` and `exfiltration`, because it enforces the
|
|
196
|
-
* policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none.
|
|
341
|
+
* policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none. It reads
|
|
342
|
+
* its policy back as a real backend does, so `provision()` throws `SandboxPolicyMismatchError` when `applied` changes
|
|
343
|
+
* the policy.
|
|
197
344
|
*/
|
|
198
345
|
export function fakeSandbox(options = {}) {
|
|
199
346
|
const execs = [];
|
|
200
347
|
let latest;
|
|
201
|
-
|
|
348
|
+
const client = {
|
|
202
349
|
tier: "os",
|
|
203
|
-
stops: ["mistakes", "exfiltration"],
|
|
350
|
+
stops: options.stops ?? ["mistakes", "exfiltration"],
|
|
204
351
|
execs,
|
|
205
352
|
files: () => latest?.store ?? new Map(),
|
|
206
353
|
symlink(link, target) {
|
|
@@ -209,7 +356,8 @@ export function fakeSandbox(options = {}) {
|
|
|
209
356
|
async provision(manifest, policy) {
|
|
210
357
|
if (options.unavailable !== undefined)
|
|
211
358
|
throw new SandboxUnavailableError("fake", options.unavailable);
|
|
212
|
-
const sandbox = new FakeSandbox(manifest.root, policy, execs);
|
|
359
|
+
const sandbox = new FakeSandbox(manifest.root, options.applied?.(policy) ?? policy, execs);
|
|
360
|
+
sandbox.stops = await confirmPolicy(client, sandbox, policy);
|
|
213
361
|
for (const [path, data] of Object.entries(manifest.files ?? {})) {
|
|
214
362
|
sandbox.seed(path, typeof data === "string" ? ENCODER.encode(data) : data);
|
|
215
363
|
}
|
|
@@ -217,5 +365,6 @@ export function fakeSandbox(options = {}) {
|
|
|
217
365
|
return sandbox;
|
|
218
366
|
},
|
|
219
367
|
};
|
|
368
|
+
return client;
|
|
220
369
|
}
|
|
221
370
|
//# sourceMappingURL=fake-sandbox.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fake-sandbox.js","sourceRoot":"","sources":["../../src/testing/fake-sandbox.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAmCnF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,aAAa,GAAsB,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;AAEvH,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,SAAS,CAAC,IAAY;IAC7B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACnC,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,GAAG;YAAE,SAAS;QAC1C,IAAI,IAAI,KAAK,IAAI;YAAE,KAAK,CAAC,GAAG,EAAE,CAAC;;YAC1B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AAC/B,CAAC;AAED,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,IAAY,EAAW,EAAE;IACrD,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC7B,OAAO,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC;AACtE,CAAC,CAAC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CACF;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,OAAO,GAAuB,EAAE;IAC1D,MAAM,KAAK,GAAmB,EAAE,CAAC;IACjC,IAAI,MAA+B,CAAC;IACpC,OAAO;QACL,IAAI,EAAE,IAAI;QACV,KAAK,EAAE,CAAC,UAAU,EAAE,cAAc,CAAC;QACnC,KAAK;QACL,KAAK,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;QACvC,OAAO,CAAC,IAAY,EAAE,MAAc;YAClC,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;QACxD,CAAC;QACD,KAAK,CAAC,SAAS,CAAC,QAA2B,EAAE,MAAqB;YAChE,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS;gBAAE,MAAM,IAAI,uBAAuB,CAAC,MAAM,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;YACtG,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;YAC9D,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC;gBAChE,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAC7E,CAAC;YACD,MAAM,GAAG,OAAO,CAAC;YACjB,OAAO,OAAO,CAAC;QACjB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `fakeSandbox()`: a sandbox in memory, for tests of the code that runs on one. It enforces the policy it is given, so\n * a test can see a denial, and it records every `exec`, but it confines no process and runs no program: it understands\n * a few commands, listed at `FAKE_COMMANDS`. It is portable, so a test can use it on every target.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { SandboxDeniedError, SandboxUnavailableError } from \"../sandbox/errors.js\";\nimport type {\n ExecOptions,\n ExecResult,\n Sandbox,\n SandboxClient,\n SandboxDenial,\n SandboxPolicy,\n WorkspaceManifest,\n} from \"../sandbox/types.js\";\n\n/** The options of `fakeSandbox()`. */\nexport interface FakeSandboxOptions {\n /** Makes `provision()` throw `SandboxUnavailableError` with this reason, as a backend that can't start does. */\n readonly unavailable?: string;\n}\n\n/** One command the fake received, with what the caller passed. */\nexport interface RecordedExec {\n readonly command: readonly string[];\n readonly cwd: string | undefined;\n readonly env: Readonly<Record<string, string>>;\n readonly timeoutMs: number | undefined;\n}\n\n/** A fake backend, and what it has seen. */\nexport interface FakeSandboxClient extends SandboxClient {\n /** Every command run through any sandbox this client provisioned, in order. */\n readonly execs: readonly RecordedExec[];\n /** The files of the latest sandbox, by absolute path. */\n files(): ReadonlyMap<string, Uint8Array>;\n /** Makes `link` an absolute path that stands for `target` in the latest sandbox, as a symlink does. */\n symlink(link: string, target: string): void;\n}\n\n/**\n * The commands the fake runs, in the form `[name, ...arguments]`: `echo` prints its arguments, `env` prints the\n * environment it was given as `NAME=value` lines, `cat <path>` prints a file, `write <path> <text>` writes one,\n * `true` and `false` exit with 0 and 1, `sleep <seconds>` waits and honours the timeout and the signal, and\n * `net-probe <host>` reaches a host only if the policy allows it. Any other command exits with 127.\n */\nexport const FAKE_COMMANDS: readonly string[] = [\"echo\", \"env\", \"cat\", \"write\", \"true\", \"false\", \"sleep\", \"net-probe\"];\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nfunction normalize(path: string): string {\n const parts: string[] = [];\n for (const part of path.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\n\nconst within = (path: string, root: string): boolean => {\n const base = normalize(root);\n return base === \"/\" || path === base || path.startsWith(`${base}/`);\n};\n\nclass FakeSandbox implements Sandbox {\n private disposed = false;\n // What ends each command still running, so `dispose()` can reject them as a real backend does.\n private readonly running = new Set<() => void>();\n readonly store = new Map<string, Uint8Array>();\n readonly links = new Map<string, string>();\n private readonly root: string;\n private readonly policy: SandboxPolicy;\n private readonly log: RecordedExec[];\n\n constructor(root: string, policy: SandboxPolicy, log: RecordedExec[]) {\n this.root = normalize(root);\n this.policy = policy;\n this.log = log;\n }\n\n private live(): void {\n if (this.disposed) throw new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\");\n }\n\n /** The absolute path a name stands for: joined to the root, tidied of `.` and `..`, then followed through links. */\n resolve(path: string, base = this.root): string {\n const tidy = normalize(path.startsWith(\"/\") ? path : `${base}/${path}`);\n for (const [link, target] of this.links) {\n if (tidy === link || tidy.startsWith(`${link}/`)) return normalize(`${target}${tidy.slice(link.length)}`);\n }\n return tidy;\n }\n\n private readDenial(path: string): SandboxDenial | undefined {\n const roots = [...this.policy.readRoots, ...this.policy.writeRoots];\n if (roots.some((root) => within(path, root))) return undefined;\n return { kind: \"filesystem_read\", target: path, reason: \"the path is outside the read roots\" };\n }\n\n private writeDenial(path: string): SandboxDenial | undefined {\n if (this.policy.writeRoots.some((root) => within(path, root))) return undefined;\n return { kind: \"filesystem_write\", target: path, reason: \"the path is outside the write roots\" };\n }\n\n private networkDenial(host: string): SandboxDenial | undefined {\n const { allow, deny } = this.policy.network;\n if (allow.includes(host) && !deny.includes(host)) return undefined;\n return { kind: \"network\", target: host, reason: \"the host is not on the network allowlist\" };\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n this.live();\n const target = this.resolve(path);\n const denial = this.readDenial(target);\n if (denial) throw new SandboxDeniedError(denial);\n const data = this.store.get(target);\n if (data === undefined) throw new HarnessError(\"sandbox_not_found\", `no such file: ${target}`);\n return data.slice();\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n this.live();\n const target = this.resolve(path);\n const denial = this.writeDenial(target);\n if (denial) throw new SandboxDeniedError(denial);\n this.store.set(target, data.slice());\n }\n\n /** Writes a file without a policy check, for the manifest's own files. */\n seed(path: string, data: Uint8Array): void {\n this.store.set(this.resolve(path), data.slice());\n }\n\n async exec(command: readonly string[], options: ExecOptions): Promise<ExecResult> {\n this.live();\n if (!Array.isArray(command) || command.length === 0) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a sandbox command is a non-empty list of strings\");\n }\n options.signal.throwIfAborted();\n const cwd = this.resolve(options.cwd ?? \".\");\n const denial = this.readDenial(cwd);\n if (denial) return { denied: denial };\n this.log.push({ command: [...command], cwd: options.cwd, env: { ...options.env }, timeoutMs: options.timeoutMs });\n const [name = \"\", ...args] = command;\n return this.run(name, args, options);\n }\n\n private async run(name: string, args: string[], options: ExecOptions): Promise<ExecResult> {\n const ok = (stdout = \"\"): ExecResult => ({ exitCode: 0, stdout, stderr: \"\" });\n switch (name) {\n case \"echo\":\n return ok(`${args.join(\" \")}\\n`);\n case \"env\":\n return ok(\n Object.entries(options.env)\n .map(([key, value]) => `${key}=${value}\\n`)\n .join(\"\"),\n );\n case \"true\":\n return ok();\n case \"false\":\n return { exitCode: 1, stdout: \"\", stderr: \"\" };\n case \"cat\":\n return this.cat(args[0] ?? \"\");\n case \"write\":\n return this.writeCommand(args[0] ?? \"\", args.slice(1).join(\" \"));\n case \"net-probe\": {\n const host = args[0] ?? \"\";\n const denial = this.networkDenial(host);\n return denial ? { denied: denial } : ok(`reached ${host}\\n`);\n }\n case \"sleep\":\n return this.sleep(Number(args[0] ?? 0) * 1000, options);\n default:\n return { exitCode: 127, stdout: \"\", stderr: `command not found: ${name}\\n` };\n }\n }\n\n private cat(path: string): ExecResult {\n const target = this.resolve(path);\n const denial = this.readDenial(target);\n if (denial) return { denied: denial };\n const data = this.store.get(target);\n return data === undefined\n ? { exitCode: 1, stdout: \"\", stderr: `no such file: ${target}\\n` }\n : { exitCode: 0, stdout: DECODER.decode(data), stderr: \"\" };\n }\n\n private writeCommand(path: string, text: string): ExecResult {\n const target = this.resolve(path);\n const denial = this.writeDenial(target);\n if (denial) return { denied: denial };\n this.store.set(target, ENCODER.encode(text));\n return { exitCode: 0, stdout: \"\", stderr: \"\" };\n }\n\n private sleep(ms: number, options: ExecOptions): Promise<ExecResult> {\n return new Promise((resolve, reject) => {\n const done = (result: ExecResult) => {\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", aborted);\n this.running.delete(disposed);\n resolve(result);\n };\n const aborted = () => {\n clearTimeout(timer);\n this.running.delete(disposed);\n reject(options.signal.reason);\n };\n const disposed = () => {\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", aborted);\n reject(new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\"));\n };\n this.running.add(disposed);\n const stopAt = options.timeoutMs !== undefined && options.timeoutMs < ms ? options.timeoutMs : ms;\n const timer = setTimeout(() => {\n const timedOut = stopAt < ms;\n done({ exitCode: timedOut ? 124 : 0, stdout: \"\", stderr: timedOut ? `timed out after ${stopAt} ms\\n` : \"\" });\n }, stopAt);\n options.signal.addEventListener(\"abort\", aborted, { once: true });\n });\n }\n\n async dispose(): Promise<void> {\n this.disposed = true;\n for (const stop of [...this.running]) stop();\n this.running.clear();\n }\n}\n\n/**\n * Builds a fake backend with the tier `os` and the stops `mistakes` and `exfiltration`, because it enforces the\n * policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none.\n */\nexport function fakeSandbox(options: FakeSandboxOptions = {}): FakeSandboxClient {\n const execs: RecordedExec[] = [];\n let latest: FakeSandbox | undefined;\n return {\n tier: \"os\",\n stops: [\"mistakes\", \"exfiltration\"],\n execs,\n files: () => latest?.store ?? new Map(),\n symlink(link: string, target: string) {\n latest?.links.set(normalize(link), normalize(target));\n },\n async provision(manifest: WorkspaceManifest, policy: SandboxPolicy) {\n if (options.unavailable !== undefined) throw new SandboxUnavailableError(\"fake\", options.unavailable);\n const sandbox = new FakeSandbox(manifest.root, policy, execs);\n for (const [path, data] of Object.entries(manifest.files ?? {})) {\n sandbox.seed(path, typeof data === \"string\" ? ENCODER.encode(data) : data);\n }\n latest = sandbox;\n return sandbox;\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fake-sandbox.js","sourceRoot":"","sources":["../../src/testing/fake-sandbox.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AA2CrD;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,aAAa,GAAsB;IAC9C,MAAM;IACN,KAAK;IACL,KAAK;IACL,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,WAAW;IACX,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;CACL,CAAC;AAEF,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,yEAAyE;AACzE,MAAM,wBAAwB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAEjD,SAAS,SAAS,CAAC,IAAY;IAC7B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACnC,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,GAAG;YAAE,SAAS;QAC1C,IAAI,IAAI,KAAK,IAAI;YAAE,KAAK,CAAC,GAAG,EAAE,CAAC;;YAC1B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AAC/B,CAAC;AAED,mEAAmE;AACnE,SAAS,aAAa,CAAC,IAAY,EAAE,I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IAAI,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,IAAI,MAAM,EAAE,KAAK,CAAC,CAAC;YAC3F,OAAO,CAAC,KAAK,GAAG,MAAM,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;YAC7D,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC;gBAChE,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAC7E,CAAC;YACD,MAAM,GAAG,OAAO,CAAC;YACjB,OAAO,OAAO,CAAC;QACjB,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * `fakeSandbox()`: a sandbox in memory, for tests of the code that runs on one. It enforces the policy it is given, so\n * a test can see a denial, and it records every `exec`, but it confines no process and runs no program: it understands\n * a few commands, listed at `FAKE_COMMANDS`. It is portable, so a test can use it on every target.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { SandboxDeniedError, SandboxUnavailableError } from \"../sandbox/errors.js\";\nimport { confirmPolicy } from \"../sandbox/policy.js\";\nimport type {\n ExecOptions,\n ExecResult,\n Sandbox,\n SandboxClient,\n SandboxDenial,\n SandboxPolicy,\n SandboxStop,\n WorkspaceManifest,\n} from \"../sandbox/types.js\";\n\n/** The options of `fakeSandbox()`. */\nexport interface FakeSandboxOptions {\n /** Makes `provision()` throw `SandboxUnavailableError` with this reason, as a backend that can't start does. */\n readonly unavailable?: string;\n /**\n * The policy the fake applies and reads back instead of the requested one, as a hosted provider's account-wide\n * override would. `provision()` then throws `SandboxPolicyMismatchError` when the two differ.\n */\n readonly applied?: (requested: SandboxPolicy) => SandboxPolicy;\n /** The stops the fake claims. Defaults to `mistakes` and `exfiltration`, which its in-memory checks deliver. */\n readonly stops?: readonly SandboxStop[];\n}\n\n/** One command the fake received, with what the caller passed. */\nexport interface RecordedExec {\n readonly command: readonly string[];\n readonly cwd: string | undefined;\n readonly env: Readonly<Record<string, string>>;\n readonly timeoutMs: number | undefined;\n}\n\n/** A fake backend, and what it has seen. */\nexport interface FakeSandboxClient extends SandboxClient {\n /** Every command run through any sandbox this client provisioned, in order. */\n readonly execs: readonly RecordedExec[];\n /** The files of the latest sandbox, by absolute path. */\n files(): ReadonlyMap<string, Uint8Array>;\n /** Makes `link` an absolute path that stands for `target` in the latest sandbox, as a symlink does. */\n symlink(link: string, target: string): void;\n}\n\n/**\n * The commands the fake runs, in the form `[name, ...arguments]`: `echo` prints its arguments, `env` prints the\n * environment it was given as `NAME=value` lines, `cat <path>` prints a file, `write <path> <text>` writes one,\n * `true` and `false` exit with 0 and 1, `sleep <seconds>` waits and honours the timeout and the signal, and\n * `net-probe <host>` reaches a host only if the policy allows it. `find <dir>` lists the files under a folder, one per\n * line or ending in NUL with `-print0`. When the command has `-prune`, it leaves out every folder named by a `-name`,\n * the starting folder included. A `! -path <start>` exempts the starting folder. It exits with 0 and prints nothing for a folder\n * with no files, and with 1 for a path that does not exist. `grep [-i] -e <pattern> -- <file>...` prints each\n * matching line as `file:line:text`, reading the pattern as a JavaScript regular expression and skipping a file that\n * holds a NUL byte. It exits with 1 when nothing matches, and with 2 after a missing file or a pattern it can't read,\n * as grep does. A command that runs past its timeout exits with 124 and `timedOut: true`, and each stream keeps at\n * most `maxOutputBytes`, with `truncated: true` when more was dropped.\n * `bash -c <script>` and `sh -c <script>` split the script on whitespace and run its words as one of these commands,\n * with no shell syntax. Any other command exits with 127.\n */\nexport const FAKE_COMMANDS: readonly string[] = [\n \"echo\",\n \"env\",\n \"cat\",\n \"write\",\n \"true\",\n \"false\",\n \"sleep\",\n \"net-probe\",\n \"find\",\n \"grep\",\n \"bash\",\n \"sh\",\n];\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n// What a real backend keeps of each stream when the caller names no cap.\nconst DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;\n\nfunction normalize(path: string): string {\n const parts: string[] = [];\n for (const part of path.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\n\n/** The lines of `text` that match, as `grep -n -H` prints them. */\nfunction matchingLines(file: string, text: string, pattern: RegExp): string {\n const lines = text.endsWith(\"\\n\") ? text.slice(0, -1).split(\"\\n\") : text.split(\"\\n\");\n return lines.map((line, index) => (pattern.test(line) ? `${file}:${index + 1}:${line}\\n` : \"\")).join(\"\");\n}\n\n/** A `find -path` pattern with its backslash escapes removed, as the literal path it names. */\nconst literalOf = (pattern: string | undefined): string | undefined => pattern?.replace(/\\\\(.)/g, \"$1\");\n\n/** `text` cut to its first `bytes` UTF-8 bytes, never splitting a character, and whether anything was cut. */\nfunction capped(text: string, bytes: number): { text: string; cut: boolean } {\n const encoded = ENCODER.encode(text);\n if (encoded.length <= bytes) return { text, cut: false };\n let end = bytes;\n while (end > 0 && ((encoded[end] as number) & 0b1100_0000) === 0b1000_0000) end -= 1;\n return { text: DECODER.decode(encoded.subarray(0, end)), cut: true };\n}\n\n/** The pattern of a `grep` command's flags, or the result grep gives for a pattern it can't read. */\nfunction patternOf(flags: readonly string[]): RegExp | ExecResult {\n const at = flags.indexOf(\"-e\");\n try {\n return new RegExp(at < 0 ? \"\" : (flags[at + 1] ?? \"\"), flags.includes(\"-i\") ? \"i\" : \"\");\n } catch (error) {\n // grep reports a pattern it can't read on standard error and exits with 2, before it reads any file.\n return { exitCode: 2, stdout: \"\", stderr: `grep: ${(error as Error).message}\\n` };\n }\n}\n\nconst within = (path: string, root: string): boolean => {\n const base = normalize(root);\n return base === \"/\" || path === base || path.startsWith(`${base}/`);\n};\n\nclass FakeSandbox implements Sandbox {\n private disposed = false;\n stops: readonly SandboxStop[] = [];\n // What ends each command still running, so `dispose()` can reject them as a real backend does.\n private readonly running = new Set<() => void>();\n readonly store = new Map<string, Uint8Array>();\n readonly links = new Map<string, string>();\n private readonly root: string;\n private readonly policy: SandboxPolicy;\n private readonly log: RecordedExec[];\n\n constructor(root: string, policy: SandboxPolicy, log: RecordedExec[]) {\n this.root = normalize(root);\n this.policy = policy;\n this.log = log;\n }\n\n private live(): void {\n if (this.disposed) throw new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\");\n }\n\n /** The policy the fake enforces, as a copy. */\n async readBack(): Promise<SandboxPolicy> {\n this.live();\n const { readRoots, writeRoots, network } = this.policy;\n return {\n readRoots: [...readRoots],\n writeRoots: [...writeRoots],\n network: { allow: [...network.allow], deny: [...network.deny] },\n };\n }\n\n /** The absolute path a name stands for: joined to the root, tidied of `.` and `..`, then followed through links. */\n resolve(path: string, base = this.root): string {\n const tidy = normalize(path.startsWith(\"/\") ? path : `${base}/${path}`);\n for (const [link, target] of this.links) {\n if (tidy === link || tidy.startsWith(`${link}/`)) return normalize(`${target}${tidy.slice(link.length)}`);\n }\n return tidy;\n }\n\n private readDenial(path: string): SandboxDenial | undefined {\n const roots = [...this.policy.readRoots, ...this.policy.writeRoots];\n if (roots.some((root) => within(path, root))) return undefined;\n return { kind: \"filesystem_read\", target: path, reason: \"the path is outside the read roots\" };\n }\n\n private writeDenial(path: string): SandboxDenial | undefined {\n if (this.policy.writeRoots.some((root) => within(path, root))) return undefined;\n return { kind: \"filesystem_write\", target: path, reason: \"the path is outside the write roots\" };\n }\n\n private networkDenial(host: string): SandboxDenial | undefined {\n const { allow, deny } = this.policy.network;\n if (allow.includes(host) && !deny.includes(host)) return undefined;\n return { kind: \"network\", target: host, reason: \"the host is not on the network allowlist\" };\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n this.live();\n const target = this.resolve(path);\n const denial = this.readDenial(target);\n if (denial) throw new SandboxDeniedError(denial);\n const data = this.store.get(target);\n if (data === undefined) throw new HarnessError(\"sandbox_not_found\", `no such file: ${target}`);\n return data.slice();\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n this.live();\n const target = this.resolve(path);\n const denial = this.writeDenial(target);\n if (denial) throw new SandboxDeniedError(denial);\n this.store.set(target, data.slice());\n }\n\n /** Writes a file without a policy check, for the manifest's own files. */\n seed(path: string, data: Uint8Array): void {\n this.store.set(this.resolve(path), data.slice());\n }\n\n async exec(command: readonly string[], options: ExecOptions): Promise<ExecResult> {\n this.live();\n if (!Array.isArray(command) || command.length === 0) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a sandbox command is a non-empty list of strings\");\n }\n options.signal.throwIfAborted();\n const cwd = this.resolve(options.cwd ?? \".\");\n const denial = this.readDenial(cwd);\n if (denial) return { denied: denial };\n this.log.push({ command: [...command], cwd: options.cwd, env: { ...options.env }, timeoutMs: options.timeoutMs });\n const [name = \"\", ...args] = command;\n const result = await this.run(name, args, options);\n if (\"denied\" in result) return result;\n // Each stream keeps at most `maxOutputBytes`, as a real backend's does.\n const limit = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n const stdout = capped(result.stdout, limit);\n const stderr = capped(result.stderr, limit);\n if (!stdout.cut && !stderr.cut) return result;\n return { ...result, stdout: stdout.text, stderr: stderr.text, truncated: true };\n }\n\n private async run(name: string, args: string[], options: ExecOptions): Promise<ExecResult> {\n const ok = (stdout = \"\"): ExecResult => ({ exitCode: 0, stdout, stderr: \"\" });\n switch (name) {\n case \"echo\":\n return ok(`${args.join(\" \")}\\n`);\n case \"env\":\n return ok(\n Object.entries(options.env)\n .map(([key, value]) => `${key}=${value}\\n`)\n .join(\"\"),\n );\n case \"true\":\n return ok();\n case \"false\":\n return { exitCode: 1, stdout: \"\", stderr: \"\" };\n case \"cat\":\n return this.cat(args[0] ?? \"\");\n case \"write\":\n return this.writeCommand(args[0] ?? \"\", args.slice(1).join(\" \"));\n case \"net-probe\": {\n const host = args[0] ?? \"\";\n const denial = this.networkDenial(host);\n return denial ? { denied: denial } : ok(`reached ${host}\\n`);\n }\n case \"sleep\":\n return this.sleep(Number(args[0] ?? 0) * 1000, options);\n case \"find\":\n return this.find(args);\n case \"grep\":\n return this.grep(args);\n case \"bash\":\n case \"sh\":\n return this.shell(args, options);\n default:\n return { exitCode: 127, stdout: \"\", stderr: `command not found: ${name}\\n` };\n }\n }\n\n private cat(path: string): ExecResult {\n const target = this.resolve(path);\n const denial = this.readDenial(target);\n if (denial) return { denied: denial };\n const data = this.store.get(target);\n return data === undefined\n ? { exitCode: 1, stdout: \"\", stderr: `no such file: ${target}\\n` }\n : { exitCode: 0, stdout: DECODER.decode(data), stderr: \"\" };\n }\n\n /** The script's words as one command, so a test can drive a shell tool without a shell. */\n private shell(args: string[], options: ExecOptions): Promise<ExecResult> {\n if (args[0] !== \"-c\") return Promise.resolve({ exitCode: 2, stdout: \"\", stderr: \"the fake shell runs only -c\\n\" });\n const [name = \"\", ...rest] = (args[1] ?? \"\").trim().split(/\\s+/);\n return this.run(name, rest, options);\n }\n\n /** Whether `path` is a folder: the root, a folder above it, or a folder that holds a file. */\n private isFolder(path: string): boolean {\n if (within(this.root, path)) return true;\n const prefix = path === \"/\" ? \"/\" : `${path}/`;\n return [...this.store.keys()].some((file) => file.startsWith(prefix));\n }\n\n private find(args: string[]): ExecResult {\n const start = this.resolve(args[0] ?? \".\");\n const denial = this.readDenial(start);\n if (denial) return { denied: denial };\n if (!this.store.has(start) && !this.isFolder(start)) {\n return { exitCode: 1, stdout: \"\", stderr: `find: '${args[0] ?? \".\"}': No such file or directory\\n` };\n }\n const named = args.flatMap((arg, index) => (arg === \"-name\" ? [args[index + 1] ?? \"\"] : []));\n const pruned = new Set(args.includes(\"-prune\") ? named : []);\n // `! -path <start>` exempts the starting point from the prune, as it does for find; without it the prune tests\n // the starting point's own name too, so a search that starts in a pruned folder finds nothing.\n const exempt = args.some(\n (arg, index) => arg === \"!\" && args[index + 1] === \"-path\" && literalOf(args[index + 2]) === start,\n );\n const ownName = start.split(\"/\").at(-1) ?? \"\";\n if (!exempt && ownName !== \"\" && pruned.has(ownName)) return { exitCode: 0, stdout: \"\", stderr: \"\" };\n const files = [...this.store.keys()]\n .filter((path) => path === start || path.startsWith(`${start === \"/\" ? \"\" : start}/`))\n .filter(\n (path) =>\n !path\n .slice(start.length)\n .split(\"/\")\n .some((part) => pruned.has(part)),\n )\n .sort();\n const end = args.includes(\"-print0\") ? \"\\0\" : \"\\n\";\n return { exitCode: 0, stdout: files.map((path) => `${path}${end}`).join(\"\"), stderr: \"\" };\n }\n\n private grep(args: string[]): ExecResult {\n const split = args.indexOf(\"--\");\n const flags = split < 0 ? args : args.slice(0, split);\n const files = split < 0 ? [] : args.slice(split + 1);\n const pattern = patternOf(flags);\n if (!(pattern instanceof RegExp)) return pattern;\n let stdout = \"\";\n let stderr = \"\";\n for (const file of files) {\n const target = this.resolve(file);\n const denial = this.readDenial(target);\n if (denial) return { denied: denial };\n const data = this.store.get(target);\n if (data === undefined) stderr += `grep: ${file}: No such file or directory\\n`;\n else if (!data.includes(0)) stdout += matchingLines(file, DECODER.decode(data), pattern);\n }\n // grep exits with 2 after any error, even when other files matched.\n return { exitCode: stderr !== \"\" ? 2 : stdout === \"\" ? 1 : 0, stdout, stderr };\n }\n\n private writeCommand(path: string, text: string): ExecResult {\n const target = this.resolve(path);\n const denial = this.writeDenial(target);\n if (denial) return { denied: denial };\n this.store.set(target, ENCODER.encode(text));\n return { exitCode: 0, stdout: \"\", stderr: \"\" };\n }\n\n private sleep(ms: number, options: ExecOptions): Promise<ExecResult> {\n return new Promise((resolve, reject) => {\n const done = (result: ExecResult) => {\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", aborted);\n this.running.delete(disposed);\n resolve(result);\n };\n const aborted = () => {\n clearTimeout(timer);\n this.running.delete(disposed);\n reject(options.signal.reason);\n };\n const disposed = () => {\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", aborted);\n reject(new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\"));\n };\n this.running.add(disposed);\n const stopAt = options.timeoutMs !== undefined && options.timeoutMs < ms ? options.timeoutMs : ms;\n const timer = setTimeout(() => {\n const timedOut = stopAt < ms;\n done(\n timedOut\n ? { exitCode: 124, stdout: \"\", stderr: `timed out after ${stopAt} ms\\n`, timedOut: true }\n : { exitCode: 0, stdout: \"\", stderr: \"\" },\n );\n }, stopAt);\n options.signal.addEventListener(\"abort\", aborted, { once: true });\n });\n }\n\n async dispose(): Promise<void> {\n this.disposed = true;\n for (const stop of [...this.running]) stop();\n this.running.clear();\n }\n}\n\n/**\n * Builds a fake backend with the tier `os` and the stops `mistakes` and `exfiltration`, because it enforces the\n * policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none. It reads\n * its policy back as a real backend does, so `provision()` throws `SandboxPolicyMismatchError` when `applied` changes\n * the policy.\n */\nexport function fakeSandbox(options: FakeSandboxOptions = {}): FakeSandboxClient {\n const execs: RecordedExec[] = [];\n let latest: FakeSandbox | undefined;\n const client: FakeSandboxClient = {\n tier: \"os\",\n stops: options.stops ?? [\"mistakes\", \"exfiltration\"],\n execs,\n files: () => latest?.store ?? new Map(),\n symlink(link: string, target: string) {\n latest?.links.set(normalize(link), normalize(target));\n },\n async provision(manifest: WorkspaceManifest, policy: SandboxPolicy) {\n if (options.unavailable !== undefined) throw new SandboxUnavailableError(\"fake\", options.unavailable);\n const sandbox = new FakeSandbox(manifest.root, options.applied?.(policy) ?? policy, execs);\n sandbox.stops = await confirmPolicy(client, sandbox, policy);\n for (const [path, data] of Object.entries(manifest.files ?? {})) {\n sandbox.seed(path, typeof data === \"string\" ? ENCODER.encode(data) : data);\n }\n latest = sandbox;\n return sandbox;\n },\n };\n return client;\n}\n"]}
|