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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"approvals.js","sourceRoot":"","sources":["../../src/session/approvals.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC1G,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAwB,MAAM,oBAAoB,CAAC;AAChG,OAAO,EAAwB,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACtE,OAAO,EAA6C,UAAU,EAAmB,MAAM,aAAa,CAAC;AAErG,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAejE,MAAM,MAAM,GAAG,CAAC,UAAsB,EAAW,EAAE,CAAC,UAAU,IAAI,UAAU,IAAI,UAAU,CAAC,QAAQ,KAAK,MAAM,CAAC;AAE/G,yHAAyH;AACzH,MAAM,CAAC,MAAM,aAAa,GAAiB;IACzC,QAAQ,CAAC,QAAQ,EAAE,WAAW;QAC5B,MAAM,MAAM,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAClC,IAAI,MAAM,KAAK,SAAS;YAAE,OAAO,SAAS,CAAC;QAC3C,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC;IAC7C,CAAC;CACF,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,MAAc;IACrC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,EAAE,CAAC;QAC5C,MAAM,IAAI,YAAY,CACpB,2BAA2B,EAC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,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAChF,MAAM,GAAG,GAAG,MAAM,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACvG,OAAO,cAAc,CACnB,OAAO,EACP,OAAO,EACP,IAAI,EACJ,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,EACvE,OAAO,CACR,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `createApprovals()`: the pause and resume of a call that waits for a person. A gate `ask` ends a turn\n * `awaiting_approval` with the signed request in the log, as an `approval_requested` entry written before the harness's\n * own observers hear of it, and a code call that asks writes the same entry. `pending()` reads the requests that still\n * wait, and `resolve()` answers them from any process that can open the session and load the key ring, because the log\n * holds everything the resume needs. A turn's answers resume the turn; a code call's answer runs the call with no model\n * step. An answer may also cover more than its own call (sticky and grouped answers), and a quorum policy may need\n * several answers before a call runs.\n */\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Resolution, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCallResult, Harness } from \"../harness.js\";\nimport type { ApprovalReuse } from \"../tools/types.js\";\nimport { checkCodeCallRequest, codeCallEffectKey, finishCodeCall, inCodeCallQueue } from \"./code-call.js\";\nimport { codeCallRequestIds, pendingCodeCalls, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { type PendingApproval, pendingApprovals } from \"./rebuild.js\";\nimport { type ResolutionRecord, type ResumeOptions, resumeTurn, type TurnResult } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { checkReuse, checkSticky, groupIdOf } from \"./sticky.js\";\n\n/** What a quorum policy says about one request: its answers are enough, not yet, a refusal, or too old. */\nexport type QuorumVerdict = \"met\" | \"pending\" | \"rejected\" | \"expired\";\n\n/**\n * Decides when a request has enough answers. `resolutions` are every answer written for the request so far, oldest\n * first. The policy keeps its own clock, so it can expire a request by age or because the policy changed. `met` runs\n * the call, `rejected` and `expired` turn it into a denial, and `pending` leaves it waiting.\n */\nexport interface QuorumPolicy {\n /** Decides one waiting request from every answer recorded for it so far, oldest first. */\n evaluate(request: SignedPendingRequest, resolutions: readonly Resolution[]): Promise<QuorumVerdict> | QuorumVerdict;\n}\n\nconst isDeny = (resolution: Resolution): boolean => \"decision\" in resolution && resolution.decision === \"deny\";\n\n/** The default policy: the latest answer decides. Any answer that is not a deny runs the call, and a deny refuses it. */\nexport const oneResolution: QuorumPolicy = {\n evaluate(_request, resolutions) {\n const latest = resolutions.at(-1);\n if (latest === undefined) return \"pending\";\n return isDeny(latest) ? \"rejected\" : \"met\";\n },\n};\n\n/**\n * A policy that needs `needed` allows from distinct approvers, named by `Resolution.by`. A deny as the latest answer\n * refuses the call, and the allows before it do not count. An allow with no `by` counts as one anonymous approver, so a\n * quorum above one needs the host to name them. Throws `invalid_permission_config` unless `needed` is a whole number\n * of at least one.\n */\nexport function quorumOf(needed: number): QuorumPolicy {\n if (!Number.isInteger(needed) || needed < 1) {\n throw new HarnessError(\n \"invalid_permission_config\",\n `a quorum needs a whole number of approvers of at least 1, got ${needed}`,\n );\n }\n return {\n evaluate(_request, resolutions) {\n if (resolutions.length === 0) return \"pending\";\n if (isDeny(resolutions.at(-1) as Resolution)) return \"rejected\";\n const approvers = new Set(\n resolutions.filter((resolution) => !isDeny(resolution)).map((resolution) => resolution.by ?? \"(unnamed)\"),\n );\n return approvers.size >= needed ? \"met\" : \"pending\";\n },\n };\n}\n\n/**\n * The settings a resume takes besides the answers: a turn's settings, and what the answers cover. A code call's\n * resolution reads `hostContext`, `signal`, `clock`, `newId`, `sticky`, `group` and `requesterId`, and ignores the\n * rest: it makes no model call, so `budgetUsd` and the model settings have nothing to apply to.\n */\nexport interface ResolveOptions<H = unknown> extends Omit<ResumeOptions<H>, \"resolutions\" | \"records\"> {\n /** Make each `allow` cover the same call again, for this run or for this session. */\n readonly sticky?: \"run\" | \"session\";\n /** For a shell tool, cover every command that starts with these words, not only the one approved. */\n readonly commandPrefix?: readonly string[];\n /** Apply each answer to every pending request of the step that has the same tool and the same input. */\n readonly group?: boolean;\n /** Who asked. An approver equal to it is refused: nobody approves their own request. */\n readonly requesterId?: string;\n}\n\n/** The options of `createApprovals()`. */\nexport interface ApprovalsOptions {\n /** When a request has enough answers. Default `oneResolution`. */\n readonly quorum?: QuorumPolicy;\n /** The secret values the host's credential store knows. A sticky allowance that covers one is refused. */\n readonly secrets?: () => readonly string[] | Promise<readonly string[]>;\n}\n\n/** The approvals of one harness. */\nexport interface Approvals<H = unknown> {\n /**\n * The requests of the session that still wait, each with the input its call would run with once approved: a paused\n * turn's, then the code calls', in the order they asked.\n */\n pending(session: Session): Promise<PendingApproval[]>;\n /**\n * Answers waiting requests and resumes the turn. Each answer is written as an `approval_resolved` entry first. The\n * quorum policy then decides each request: `met` goes to the SDK, which verifies the request's signature, call and\n * input, so a tampered request runs nothing and is asked again; `rejected` and `expired` become denials; `pending`\n * leaves the call waiting, and the turn ends `awaiting_approval` again. Each approved call goes through the permission\n * pipeline again, and a deny now turns the approval into a denial. Calling it with no answers evaluates the policy\n * for every request of a paused turn, which is how such a request expires. It leaves a code call's request waiting:\n * the policy decides that call when it is next answered, so a late allow for an expired call comes back `denied`.\n *\n * An answer to a code call's request resolves that call alone and returns a `CodeCallResult`. The request is checked\n * against its signature, the host context it binds and the call's recorded input before anything is written, and a\n * request that fails throws `approval_refused` and runs nothing. The answer is then written and the quorum policy\n * decides. `met` decides the call again with the pipeline, so a deny written since the pause wins, and then runs the\n * tool with `options.hostContext` and `options.signal`, with no model call; `rejected` and `expired` deny it; `pending`\n * returns `awaiting_approval`. A request whose call already has a result, or started before a crash, no longer waits,\n * so its tool runs at most once.\n *\n * Throws `approval_not_pending` for a request that does not wait, `approval_unavailable` without a signer,\n * `approver_is_requester` when an approver is the requester, `approval_reuse_refused` when a tool's `approvalReuse`\n * forbids a sticky or grouped answer, `sticky_refused` for an interpreter prefix or a secret, and `invalid_code_call`\n * for answers that name a code call together with any other request. The host fills `Resolution.by` only after it\n * has authenticated the approver; the harness trusts what it is given.\n */\n resolve(\n session: Session,\n resolutions: readonly Resolution[],\n options?: ResolveOptions<H>,\n ): Promise<TurnResult | CodeCallResult>;\n}\n\nconst decisionOf = (resolution: Resolution): \"allow\" | \"deny\" | undefined =>\n \"decision\" in resolution ? resolution.decision : undefined;\n\n/** Copies an answer to the other requests of its group, each with the same decision, reason and approver. */\nfunction expandGroup(\n resolutions: readonly Resolution[],\n groups: ReadonlyMap<string, string[]>,\n groupOf: ReadonlyMap<string, string>,\n): Resolution[] {\n const out = new Map<string, Resolution>(resolutions.map((resolution) => [resolution.requestId, resolution]));\n for (const resolution of resolutions) {\n for (const other of groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? []) {\n if (!out.has(other)) out.set(other, { ...resolution, requestId: other });\n }\n }\n return [...out.values()];\n}\n\n/** The answers already written for each request, oldest first. */\nfunction answersByRequest(path: readonly SessionEntry[]): Map<string, Resolution[]> {\n const answers = new Map<string, Resolution[]>();\n for (const entry of path) {\n if (entry.type === \"approval_resolved\") {\n answers.set(entry.resolution.requestId, [...(answers.get(entry.resolution.requestId) ?? []), entry.resolution]);\n }\n }\n return answers;\n}\n\n/** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */\nfunction checkAnswers<H>(\n harness: Harness<H>,\n waiting: ReadonlyMap<string, PendingApproval>,\n resolutions: readonly Resolution[],\n requesterId: string | undefined,\n): void {\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no approval can be checked\");\n }\n const named = new Set<string>();\n for (const resolution of resolutions) {\n if (named.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `request ${resolution.requestId} is answered twice in one resume`);\n }\n named.add(resolution.requestId);\n if (!waiting.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `no request ${resolution.requestId} is waiting in this session`);\n }\n if (requesterId !== undefined && resolution.by === requesterId) {\n throw new HarnessError(\"approver_is_requester\", `the approver ${resolution.by} is the one who asked`);\n }\n }\n}\n\n/** The synthetic denial for a request the policy refused or let expire, with the record that puts it in the log. */\nfunction denial(requestId: string, verdict: \"rejected\" | \"expired\"): ResolutionRecord {\n const reason = verdict === \"expired\" ? \"the approval expired\" : \"the approval was rejected\";\n return { resolution: { requestId, decision: \"deny\", reason, by: \"policy\" } };\n}\n\n/** An answer without what it would cover: a sticky allowance only takes effect once the quorum is met and the call runs. */\nconst plain = ({ resolution, groupId }: ResolutionRecord): ResolutionRecord => ({\n resolution,\n ...(groupId === undefined ? {} : { groupId }),\n});\n\n/** What the SDK is given for one request, and the entries to write for it, once the quorum policy has decided. */\nfunction outcomeOf(\n verdict: QuorumVerdict,\n requestId: string,\n answers: readonly Resolution[],\n fresh: readonly ResolutionRecord[],\n): { forRun?: Resolution; records: ResolutionRecord[] } {\n const latest = answers.at(-1);\n if (verdict === \"met\" && latest !== undefined) {\n const given = answers.findLast((answer) => !isDeny(answer)) ?? latest;\n // A verdict that flips with no new answer (a clock, a policy) still writes the answer the run is given, unmarked.\n return { forRun: given, records: fresh.length > 0 ? [...fresh] : [{ resolution: given }] };\n }\n if (verdict === \"rejected\" || verdict === \"expired\") {\n // A person's own deny is already in the log; a refusal or an expiry by the policy gets an entry of its own.\n if (verdict === \"rejected\" && latest !== undefined && isDeny(latest))\n return { forRun: latest, records: fresh.map(plain) };\n const refusal = denial(requestId, verdict);\n return { forRun: refusal.resolution, records: [...fresh.map(plain), refusal] };\n }\n return { records: fresh.map((record) => ({ ...plain(record), quorum: \"pending\" as const })) };\n}\n\n/**\n * What each waiting request gets once the quorum policy has looked at it: the answer the SDK applies for `met`, a denial\n * for `rejected` and `expired`, and nothing for `pending`, whose new answers are marked as waited on so a crash\n * of this resume never counts them as given. The records returned are the entries to write, denials by the policy\n * included, so the log tells an expiry from any other refusal.\n */\nasync function settled(\n policy: QuorumPolicy,\n waiting: readonly PendingApproval[],\n earlier: ReadonlyMap<string, Resolution[]>,\n records: readonly ResolutionRecord[],\n): Promise<{ forRun: Resolution[]; records: ResolutionRecord[] }> {\n const forRun: Resolution[] = [];\n const out: ResolutionRecord[] = [];\n for (const { request } of waiting) {\n const fresh = records.filter((record) => record.resolution.requestId === request.id);\n const answers = [...(earlier.get(request.id) ?? []), ...fresh.map((record) => record.resolution)];\n const outcome = outcomeOf(await policy.evaluate(request, answers), request.id, answers, fresh);\n if (outcome.forRun !== undefined) forRun.push(outcome.forRun);\n out.push(...outcome.records);\n }\n return { forRun, records: out };\n}\n\n/** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */\nexport function createApprovals<H = unknown>(harness: Harness<H>, settings: ApprovalsOptions = {}): Approvals<H> {\n const policy = settings.quorum ?? oneResolution;\n return {\n async pending(session) {\n const path = await session.path();\n return [...pendingApprovals(path), ...pendingCodeCalls(path).map(({ request, input }) => ({ request, input }))];\n },\n async resolve(session, resolutions, options = {}) {\n if (options.sticky !== undefined && settings.quorum !== undefined) {\n throw new HarnessError(\n \"sticky_refused\",\n \"a sticky allowance needs the default policy: one approver's click would otherwise skip the quorum on every later call\",\n );\n }\n const path = await session.path();\n const codeRequests = codeCallRequestIds(path);\n if (resolutions.some((resolution) => codeRequests.has(resolution.requestId))) {\n if (resolutions.length !== 1) {\n throw new HarnessError(\n \"invalid_code_call\",\n \"a code call's request is answered on its own, in a resolve() that answers nothing else\",\n );\n }\n const only = resolutions[0] as Resolution;\n return inCodeCallQueue(session, () => resolveCodeCall(harness, session, policy, settings, only, options));\n }\n const waiting = pendingApprovals(path);\n checkAnswers(\n harness,\n new Map(waiting.map((entry) => [entry.request.id, entry])),\n resolutions,\n options.requesterId,\n );\n const records = await recordsFor(harness, waiting, resolutions, options, await (settings.secrets?.() ?? []));\n const { forRun, records: toWrite } = await settled(policy, waiting, answersByRequest(path), records);\n return resumeTurn(session, harness, { ...options, resolutions: forRun, records: toWrite });\n },\n };\n}\n\nconst nameOf = <H>(harness: Harness<H>, tool: string): string => harness.registry.get(tool)?.canonicalName ?? tool;\nconst reuseOf = <H>(harness: Harness<H>, tool: string): ApprovalReuse =>\n harness.registry.get(tool)?.approvalReuse ?? \"both\";\n\n/** The group each waiting request belongs to: its requests, and the id each request's group has. */\nasync function groupsOf<H>(harness: Harness<H>, waiting: readonly PendingApproval[]) {\n const groups = new Map<string, string[]>();\n const groupOf = new Map<string, string>();\n for (const { request, input } of waiting) {\n const id = await groupIdOf(nameOf(harness, request.tool), input, request.inputHash);\n groupOf.set(request.id, id);\n groups.set(id, [...(groups.get(id) ?? []), request.id]);\n }\n return { groups, groupOf };\n}\n\n/** One entry to write: the answer, and, for an allow that is sticky, what it covers once the refusals have passed. */\nfunction recordOf<H>(\n harness: Harness<H>,\n pending: PendingApproval,\n resolution: Resolution,\n groupId: string | undefined,\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): ResolutionRecord {\n const grouped = groupId === undefined ? {} : { groupId };\n if (decisionOf(resolution) !== \"allow\" || options.sticky === undefined) return { resolution, ...grouped };\n const { request, input } = pending;\n checkReuse(request.tool, reuseOf(harness, request.tool), \"sticky\");\n checkSticky(input, options.commandPrefix, secrets);\n const match =\n options.commandPrefix === undefined\n ? { inputHash: request.inputHash }\n : { commandPrefix: [...options.commandPrefix] };\n const version = request.policyVersion === undefined ? {} : { policyVersion: request.policyVersion };\n return {\n resolution,\n sticky: options.sticky,\n allowance: { tool: nameOf(harness, request.tool), ...match, ...version },\n ...grouped,\n };\n}\n\n/** The entries to write: each answer, expanded to its group, with what it covers beyond its own call. */\nasync function recordsFor<H>(\n harness: Harness<H>,\n waiting: readonly PendingApproval[],\n resolutions: readonly Resolution[],\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): Promise<ResolutionRecord[]> {\n const { groups, groupOf } =\n options.group === true ? await groupsOf(harness, waiting) : { groups: new Map(), groupOf: new Map() };\n const expanded = options.group === true ? expandGroup(resolutions, groups, groupOf) : [...resolutions];\n const byId = new Map(waiting.map((entry) => [entry.request.id, entry]));\n // Only a group that really joins requests needs its tool to allow one answer for several calls.\n for (const resolution of expanded) {\n const members = groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? [];\n const tool = (byId.get(resolution.requestId) as PendingApproval).request.tool;\n if (members.length > 1) checkReuse(tool, reuseOf(harness, tool), \"group\");\n }\n return expanded.map((resolution) =>\n recordOf(\n harness,\n byId.get(resolution.requestId) as PendingApproval,\n resolution,\n groupOf.get(resolution.requestId),\n options,\n secrets,\n ),\n );\n}\n\n/**\n * Resolves one code call: the answer is checked against the call's signed request, written with what it covers, and\n * settled by the quorum policy, and the call then waits, is denied, or runs with no model step.\n */\nasync function resolveCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n policy: QuorumPolicy,\n settings: ApprovalsOptions,\n resolution: Resolution,\n options: ResolveOptions<H>,\n): Promise<CodeCallResult> {\n const path = await session.path();\n const waiting = pendingCodeCalls(path);\n checkAnswers(harness, new Map(waiting.map((entry) => [entry.request.id, entry])), [resolution], options.requesterId);\n const call = waiting.find((entry) => entry.request.id === resolution.requestId) as WaitingCodeCall;\n await checkCodeCallRequest(harness, call, resolution, options.hostContext);\n if (options.group === true) checkReuse(call.request.tool, reuseOf(harness, call.request.tool), \"group\");\n const record = recordOf(harness, call, resolution, undefined, options, await (settings.secrets?.() ?? []));\n const outcome = await settled(policy, [call], answersByRequest(path), [record]);\n const key = await codeCallEffectKey(session, harness, harness.registry.get(call.call.tool), call.call);\n return finishCodeCall(\n harness,\n session,\n call,\n { forRun: outcome.forRun[0], records: outcome.records, effectKey: key },\n options,\n );\n}\n"]}
1
+ {"version":3,"file":"approvals.js","source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,OAAO,CAAC,CAAC;IACxG,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC3G,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAChF,MAAM,GAAG,GAAG,MAAM,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACvG,OAAO,cAAc,CACnB,OAAO,EACP,OAAO,EACP,IAAI,EACJ,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,EACvE,OAAO,CACR,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `createApprovals()`: the pause and resume of a call that waits for a person. A gate `ask` ends a turn\n * `awaiting_approval` with the signed request in the log, as an `approval_requested` entry written before the harness's\n * own observers hear of it, and a code call that asks writes the same entry. `pending()` reads the requests that still\n * wait, and `resolve()` answers them from any process that can open the session and load the key ring, because the log\n * holds everything the resume needs. A turn's answers resume the turn; a code call's answer runs the call with no model\n * step. An answer may also cover more than its own call (sticky and grouped answers), and a quorum policy may need\n * several answers before a call runs.\n */\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Resolution, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCallResult, Harness } from \"../harness.js\";\nimport type { ApprovalReuse } from \"../tools/types.js\";\nimport { checkCodeCallRequest, codeCallEffectKey, finishCodeCall, inCodeCallQueue } from \"./code-call.js\";\nimport { codeCallRequestIds, pendingCodeCalls, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { type PendingApproval, pendingApprovals } from \"./rebuild.js\";\nimport { type ResolutionRecord, type ResumeOptions, resumeTurn, type TurnResult } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { checkReuse, checkSticky, groupIdOf } from \"./sticky.js\";\n\n/** What a quorum policy says about one request: its answers are enough, not yet, a refusal, or too old. */\nexport type QuorumVerdict = \"met\" | \"pending\" | \"rejected\" | \"expired\";\n\n/**\n * Decides when a request has enough answers. `resolutions` are every answer written for the request so far, oldest\n * first. The policy keeps its own clock, so it can expire a request by age or because the policy changed. `met` runs\n * the call, `rejected` and `expired` turn it into a denial, and `pending` leaves it waiting.\n */\nexport interface QuorumPolicy {\n /** Decides one waiting request from every answer recorded for it so far, oldest first. */\n evaluate(request: SignedPendingRequest, resolutions: readonly Resolution[]): Promise<QuorumVerdict> | QuorumVerdict;\n}\n\nconst isDeny = (resolution: Resolution): boolean => \"decision\" in resolution && resolution.decision === \"deny\";\n\n/** The default policy: the latest answer decides. Any answer that is not a deny runs the call, and a deny refuses it. */\nexport const oneResolution: QuorumPolicy = {\n evaluate(_request, resolutions) {\n const latest = resolutions.at(-1);\n if (latest === undefined) return \"pending\";\n return isDeny(latest) ? \"rejected\" : \"met\";\n },\n};\n\n/**\n * A policy that needs `needed` allows from distinct approvers, named by `Resolution.by`. A deny as the latest answer\n * refuses the call, and the allows before it do not count. An allow with no `by` counts as one anonymous approver, so a\n * quorum above one needs the host to name them. Throws `invalid_permission_config` unless `needed` is a whole number\n * of at least one.\n */\nexport function quorumOf(needed: number): QuorumPolicy {\n if (!Number.isInteger(needed) || needed < 1) {\n throw new HarnessError(\n \"invalid_permission_config\",\n `a quorum needs a whole number of approvers of at least 1, got ${needed}`,\n );\n }\n return {\n evaluate(_request, resolutions) {\n if (resolutions.length === 0) return \"pending\";\n if (isDeny(resolutions.at(-1) as Resolution)) return \"rejected\";\n const approvers = new Set(\n resolutions.filter((resolution) => !isDeny(resolution)).map((resolution) => resolution.by ?? \"(unnamed)\"),\n );\n return approvers.size >= needed ? \"met\" : \"pending\";\n },\n };\n}\n\n/**\n * The settings a resume takes besides the answers: a turn's settings, and what the answers cover. A code call's\n * resolution reads `hostContext`, `signal`, `clock`, `newId`, `sticky`, `group` and `requesterId`, and ignores the\n * rest: it makes no model call, so `budgetUsd` and the model settings have nothing to apply to.\n */\nexport interface ResolveOptions<H = unknown> extends Omit<ResumeOptions<H>, \"resolutions\" | \"records\"> {\n /** Make each `allow` cover the same call again, for this run or for this session. */\n readonly sticky?: \"run\" | \"session\";\n /** For a shell tool, cover every command that starts with these words, not only the one approved. */\n readonly commandPrefix?: readonly string[];\n /** Apply each answer to every pending request of the step that has the same tool and the same input. */\n readonly group?: boolean;\n /** Who asked. An approver equal to it is refused: nobody approves their own request. */\n readonly requesterId?: string;\n}\n\n/** The options of `createApprovals()`. */\nexport interface ApprovalsOptions {\n /** When a request has enough answers. Default `oneResolution`. */\n readonly quorum?: QuorumPolicy;\n /** The secret values the host's credential store knows. A sticky allowance that covers one is refused. */\n readonly secrets?: () => readonly string[] | Promise<readonly string[]>;\n}\n\n/** The approvals of one harness. */\nexport interface Approvals<H = unknown> {\n /**\n * The requests of the session that still wait, each with the input its call would run with once approved: a paused\n * turn's, then the code calls', in the order they asked.\n */\n pending(session: Session): Promise<PendingApproval[]>;\n /**\n * Answers waiting requests and resumes the turn. Each answer is written as an `approval_resolved` entry first. The\n * quorum policy then decides each request: `met` goes to the SDK, which verifies the request's signature, call and\n * input, so a tampered request runs nothing and is asked again; `rejected` and `expired` become denials; `pending`\n * leaves the call waiting, and the turn ends `awaiting_approval` again. Each approved call goes through the permission\n * pipeline again, and a deny now turns the approval into a denial. Calling it with no answers evaluates the policy\n * for every request of a paused turn, which is how such a request expires. It leaves a code call's request waiting:\n * the policy decides that call when it is next answered, so a late allow for an expired call comes back `denied`.\n *\n * An answer to a code call's request resolves that call alone and returns a `CodeCallResult`. The request is checked\n * against its signature, the host context it binds and the call's recorded input before anything is written, and a\n * request that fails throws `approval_refused` and runs nothing. The answer is then written and the quorum policy\n * decides. `met` decides the call again with the pipeline, so a deny written since the pause wins, and then runs the\n * tool with `options.hostContext` and `options.signal`, with no model call; `rejected` and `expired` deny it; `pending`\n * returns `awaiting_approval`. A request whose call already has a result, or started before a crash, no longer waits,\n * so its tool runs at most once.\n *\n * Throws `approval_not_pending` for a request that does not wait, `approval_unavailable` without a signer,\n * `approver_is_requester` when an approver is the requester, `approval_reuse_refused` when a tool's `approvalReuse`\n * forbids a sticky or grouped answer, `sticky_refused` for an interpreter prefix or a secret, and `invalid_code_call`\n * for answers that name a code call together with any other request. The host fills `Resolution.by` only after it\n * has authenticated the approver; the harness trusts what it is given.\n */\n resolve(\n session: Session,\n resolutions: readonly Resolution[],\n options?: ResolveOptions<H>,\n ): Promise<TurnResult | CodeCallResult>;\n}\n\nconst decisionOf = (resolution: Resolution): \"allow\" | \"deny\" | undefined =>\n \"decision\" in resolution ? resolution.decision : undefined;\n\n/** Copies an answer to the other requests of its group, each with the same decision, reason and approver. */\nfunction expandGroup(\n resolutions: readonly Resolution[],\n groups: ReadonlyMap<string, string[]>,\n groupOf: ReadonlyMap<string, string>,\n): Resolution[] {\n const out = new Map<string, Resolution>(resolutions.map((resolution) => [resolution.requestId, resolution]));\n for (const resolution of resolutions) {\n for (const other of groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? []) {\n if (!out.has(other)) out.set(other, { ...resolution, requestId: other });\n }\n }\n return [...out.values()];\n}\n\n/** The answers already written for each request, oldest first. */\nexport function answersByRequest(path: readonly SessionEntry[]): Map<string, Resolution[]> {\n const answers = new Map<string, Resolution[]>();\n for (const entry of path) {\n if (entry.type === \"approval_resolved\") {\n answers.set(entry.resolution.requestId, [...(answers.get(entry.resolution.requestId) ?? []), entry.resolution]);\n }\n }\n return answers;\n}\n\n/** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */\nexport function checkAnswers<H>(\n harness: Harness<H>,\n waiting: ReadonlyMap<string, unknown>,\n resolutions: readonly Resolution[],\n requesterId: string | undefined,\n): void {\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no approval can be checked\");\n }\n const named = new Set<string>();\n for (const resolution of resolutions) {\n if (named.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `request ${resolution.requestId} is answered twice in one resume`);\n }\n named.add(resolution.requestId);\n if (!waiting.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `no request ${resolution.requestId} is waiting in this session`);\n }\n if (requesterId !== undefined && resolution.by === requesterId) {\n throw new HarnessError(\"approver_is_requester\", `the approver ${resolution.by} is the one who asked`);\n }\n }\n}\n\n/** The synthetic denial for a request the policy refused or let expire, with the record that puts it in the log. */\nfunction denial(requestId: string, verdict: \"rejected\" | \"expired\"): ResolutionRecord {\n const reason = verdict === \"expired\" ? \"the approval expired\" : \"the approval was rejected\";\n return { resolution: { requestId, decision: \"deny\", reason, by: \"policy\" } };\n}\n\n/** An answer without what it would cover: a sticky allowance only takes effect once the quorum is met and the call runs. */\nconst plain = ({ resolution, groupId }: ResolutionRecord): ResolutionRecord => ({\n resolution,\n ...(groupId === undefined ? {} : { groupId }),\n});\n\n/** What the SDK is given for one request, and the entries to write for it, once the quorum policy has decided. */\nfunction outcomeOf(\n verdict: QuorumVerdict,\n requestId: string,\n answers: readonly Resolution[],\n fresh: readonly ResolutionRecord[],\n): { forRun?: Resolution; records: ResolutionRecord[] } {\n const latest = answers.at(-1);\n if (verdict === \"met\" && latest !== undefined) {\n const given = answers.findLast((answer) => !isDeny(answer)) ?? latest;\n // A verdict that flips with no new answer (a clock, a policy) still writes the answer the run is given, unmarked.\n return { forRun: given, records: fresh.length > 0 ? [...fresh] : [{ resolution: given }] };\n }\n if (verdict === \"rejected\" || verdict === \"expired\") {\n // A person's own deny is already in the log; a refusal or an expiry by the policy gets an entry of its own.\n if (verdict === \"rejected\" && latest !== undefined && isDeny(latest))\n return { forRun: latest, records: fresh.map(plain) };\n const refusal = denial(requestId, verdict);\n return { forRun: refusal.resolution, records: [...fresh.map(plain), refusal] };\n }\n return { records: fresh.map((record) => ({ ...plain(record), quorum: \"pending\" as const })) };\n}\n\n/**\n * What each waiting request gets once the quorum policy has looked at it: the answer the SDK applies for `met`, a denial\n * for `rejected` and `expired`, and nothing for `pending`, whose new answers are marked as waited on so a crash\n * of this resume never counts them as given. The records returned are the entries to write, denials by the policy\n * included, so the log tells an expiry from any other refusal.\n */\nexport async function settled(\n policy: QuorumPolicy,\n waiting: readonly Pick<PendingApproval, \"request\">[],\n earlier: ReadonlyMap<string, Resolution[]>,\n records: readonly ResolutionRecord[],\n): Promise<{ forRun: Resolution[]; records: ResolutionRecord[] }> {\n const forRun: Resolution[] = [];\n const out: ResolutionRecord[] = [];\n for (const { request } of waiting) {\n const fresh = records.filter((record) => record.resolution.requestId === request.id);\n const answers = [...(earlier.get(request.id) ?? []), ...fresh.map((record) => record.resolution)];\n const outcome = outcomeOf(await policy.evaluate(request, answers), request.id, answers, fresh);\n if (outcome.forRun !== undefined) forRun.push(outcome.forRun);\n out.push(...outcome.records);\n }\n return { forRun, records: out };\n}\n\n/** The harness and quorum policy each `Approvals` was made with, so a sandbox escalation shares them. */\nconst made = new WeakMap<object, { readonly harness: Harness<never>; readonly quorum: QuorumPolicy }>();\n\n/** The harness and quorum policy `approvals` was made with, or `undefined` for one `createApprovals()` did not make. */\nexport function approvalsBinding<H>(\n approvals: Approvals<H>,\n): { readonly harness: Harness<H>; readonly quorum: QuorumPolicy } | undefined {\n return made.get(approvals) as { readonly harness: Harness<H>; readonly quorum: QuorumPolicy } | undefined;\n}\n\n/** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */\nexport function createApprovals<H = unknown>(harness: Harness<H>, settings: ApprovalsOptions = {}): Approvals<H> {\n const policy = settings.quorum ?? oneResolution;\n const approvals: Approvals<H> = {\n async pending(session) {\n const path = await session.path();\n return [...pendingApprovals(path), ...pendingCodeCalls(path).map(({ request, input }) => ({ request, input }))];\n },\n async resolve(session, resolutions, options = {}) {\n if (options.sticky !== undefined && settings.quorum !== undefined) {\n throw new HarnessError(\n \"sticky_refused\",\n \"a sticky allowance needs the default policy: one approver's click would otherwise skip the quorum on every later call\",\n );\n }\n const path = await session.path();\n const codeRequests = codeCallRequestIds(path);\n if (resolutions.some((resolution) => codeRequests.has(resolution.requestId))) {\n if (resolutions.length !== 1) {\n throw new HarnessError(\n \"invalid_code_call\",\n \"a code call's request is answered on its own, in a resolve() that answers nothing else\",\n );\n }\n const only = resolutions[0] as Resolution;\n return inCodeCallQueue(session, () => resolveCodeCall(harness, session, policy, settings, only, options));\n }\n const waiting = pendingApprovals(path);\n checkAnswers(\n harness,\n new Map(waiting.map((entry) => [entry.request.id, entry])),\n resolutions,\n options.requesterId,\n );\n const records = await recordsFor(harness, waiting, resolutions, options, await (settings.secrets?.() ?? []));\n const { forRun, records: toWrite } = await settled(policy, waiting, answersByRequest(path), records);\n return resumeTurn(session, harness, { ...options, resolutions: forRun, records: toWrite });\n },\n };\n made.set(approvals, { harness: harness as Harness<never>, quorum: policy });\n return approvals;\n}\n\nconst nameOf = <H>(harness: Harness<H>, tool: string): string => harness.registry.get(tool)?.canonicalName ?? tool;\nconst reuseOf = <H>(harness: Harness<H>, tool: string): ApprovalReuse =>\n harness.registry.get(tool)?.approvalReuse ?? \"both\";\n\n/** The group each waiting request belongs to: its requests, and the id each request's group has. */\nasync function groupsOf<H>(harness: Harness<H>, waiting: readonly PendingApproval[]) {\n const groups = new Map<string, string[]>();\n const groupOf = new Map<string, string>();\n for (const { request, input } of waiting) {\n const id = await groupIdOf(nameOf(harness, request.tool), input, request.inputHash);\n groupOf.set(request.id, id);\n groups.set(id, [...(groups.get(id) ?? []), request.id]);\n }\n return { groups, groupOf };\n}\n\n/** One entry to write: the answer, and, for an allow that is sticky, what it covers once the refusals have passed. */\nfunction recordOf<H>(\n harness: Harness<H>,\n pending: PendingApproval,\n resolution: Resolution,\n groupId: string | undefined,\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): ResolutionRecord {\n const grouped = groupId === undefined ? {} : { groupId };\n if (decisionOf(resolution) !== \"allow\" || options.sticky === undefined) return { resolution, ...grouped };\n const { request, input } = pending;\n checkReuse(request.tool, reuseOf(harness, request.tool), \"sticky\");\n checkSticky(input, options.commandPrefix, secrets);\n const match =\n options.commandPrefix === undefined\n ? { inputHash: request.inputHash }\n : { commandPrefix: [...options.commandPrefix] };\n const version = request.policyVersion === undefined ? {} : { policyVersion: request.policyVersion };\n return {\n resolution,\n sticky: options.sticky,\n allowance: { tool: nameOf(harness, request.tool), ...match, ...version },\n ...grouped,\n };\n}\n\n/** The entries to write: each answer, expanded to its group, with what it covers beyond its own call. */\nasync function recordsFor<H>(\n harness: Harness<H>,\n waiting: readonly PendingApproval[],\n resolutions: readonly Resolution[],\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): Promise<ResolutionRecord[]> {\n const { groups, groupOf } =\n options.group === true ? await groupsOf(harness, waiting) : { groups: new Map(), groupOf: new Map() };\n const expanded = options.group === true ? expandGroup(resolutions, groups, groupOf) : [...resolutions];\n const byId = new Map(waiting.map((entry) => [entry.request.id, entry]));\n // Only a group that really joins requests needs its tool to allow one answer for several calls.\n for (const resolution of expanded) {\n const members = groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? [];\n const tool = (byId.get(resolution.requestId) as PendingApproval).request.tool;\n if (members.length > 1) checkReuse(tool, reuseOf(harness, tool), \"group\");\n }\n return expanded.map((resolution) =>\n recordOf(\n harness,\n byId.get(resolution.requestId) as PendingApproval,\n resolution,\n groupOf.get(resolution.requestId),\n options,\n secrets,\n ),\n );\n}\n\n/**\n * Resolves one code call: the answer is checked against the call's signed request, written with what it covers, and\n * settled by the quorum policy, and the call then waits, is denied, or runs with no model step.\n */\nasync function resolveCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n policy: QuorumPolicy,\n settings: ApprovalsOptions,\n resolution: Resolution,\n options: ResolveOptions<H>,\n): Promise<CodeCallResult> {\n const path = await session.path();\n const waiting = pendingCodeCalls(path);\n checkAnswers(harness, new Map(waiting.map((entry) => [entry.request.id, entry])), [resolution], options.requesterId);\n const call = waiting.find((entry) => entry.request.id === resolution.requestId) as WaitingCodeCall;\n await checkCodeCallRequest(harness, call, resolution, options.hostContext);\n if (options.group === true) checkReuse(call.request.tool, reuseOf(harness, call.request.tool), \"group\");\n const record = recordOf(harness, call, resolution, undefined, options, await (settings.secrets?.() ?? []));\n const outcome = await settled(policy, [call], answersByRequest(path), [record]);\n const key = await codeCallEffectKey(session, harness, harness.registry.get(call.call.tool), call.call);\n return finishCodeCall(\n harness,\n session,\n call,\n { forRun: outcome.forRun[0], records: outcome.records, effectKey: key },\n options,\n );\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { Origin, SessionEntry } from "@buildanagent/protocol";
1
2
  import { type Resolution } from "@buildanagent/sdk";
2
3
  import type { Clock } from "@buildanagent/sdk/testing";
3
4
  import type { CodeCall, CodeCallResult, Harness } from "../harness.js";
@@ -5,8 +6,19 @@ import type { RegisteredTool } from "../tools/types.js";
5
6
  import { type WaitingCodeCall } from "./code-call-log.js";
6
7
  import { type ResolutionRecord } from "./runner.js";
7
8
  import type { Session } from "./session.js";
9
+ import type { EntryInput } from "./store.js";
10
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
11
+ /** An entry to write, without the fields the writer fills in. */
12
+ export type Body = DistributiveOmit<EntryInput, "id" | "parentId" | "timestamp" | "origin">;
13
+ /** How a code call, or a sandbox escalation, writes: one entry at a time after the one before, with its ids and clock. */
14
+ export interface Io {
15
+ readonly session: Session;
16
+ write(origin: Origin, body: Body, id?: string): Promise<SessionEntry>;
17
+ readonly newId: () => string;
18
+ readonly clock: Clock;
19
+ }
8
20
  /** The settings both a call and its resolution take: where its ids and time come from. */
9
- interface IoOptions {
21
+ export interface IoOptions {
10
22
  readonly clock?: Clock;
11
23
  readonly newId?: () => string;
12
24
  }
@@ -15,6 +27,8 @@ interface RunOptions<H> extends IoOptions {
15
27
  readonly hostContext?: H;
16
28
  readonly signal?: AbortSignal;
17
29
  }
30
+ /** A writer for `session` with the given ids and clock, defaulting to random ids and the system clock. */
31
+ export declare function ioOf(session: Session, options: IoOptions): Io;
18
32
  /** Runs `task` after every code call of `session` that this process started before it. */
19
33
  export declare function inCodeCallQueue<T>(session: Session, task: () => Promise<T>): Promise<T>;
20
34
  /**
@@ -15,7 +15,8 @@ import { recordSessionStart } from "./runner.js";
15
15
  import { findSticky, stickyDecision } from "./sticky.js";
16
16
  // The SDK's default nesting cap, so a tool that starts an agent from a code call nests as it would in a run.
17
17
  const MAX_DEPTH = 2;
18
- function ioOf(session, options) {
18
+ /** A writer for `session` with the given ids and clock, defaulting to random ids and the system clock. */
19
+ export function ioOf(session, options) {
19
20
  const newId = options.newId ?? (() => globalThis.crypto.randomUUID());
20
21
  const clock = options.clock ?? { now: () => new Date().toISOString() };
21
22
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"code-call.js","sourceRoot":"","sources":["../../src/session/code-call.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAGpF,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EAIpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAI5C,OAAO,EAAuB,WAAW,EAAwB,MAAM,oBAAoB,CAAC;AAC5F,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,aAAa,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OAAO,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * Code-initiated tool calls: a side effect the host's own code chose, run through the same permission pipeline, signed\n * pause and log as a call the model makes, with no model step. The `code_call` entry is written before anything else\n * of the call, and its id is the call id, so the effect key is fixed before the tool can run and a resume finds it.\n * A call starts once its log holds the entry that clears it to run; one that started with no result is never rerun.\n */\nimport { effectKey, renderOutcome, writeOutcome } from \"@buildanagent/agent-safety\";\nimport type { ContentBlock } from \"@buildanagent/gateway\";\nimport type { CodeCallEntry, Origin, SessionEntry } from \"@buildanagent/protocol\";\nimport {\n canonicalInputHash,\n createPendingRequest,\n type Resolution,\n type ToolContext,\n type ToolResult,\n verifyResolution,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCall, CodeCallResult, Harness } from \"../harness.js\";\nimport type { Decision, PolicySession } from \"../permissions/types.js\";\nimport type { RegisteredTool } from \"../tools/types.js\";\nimport { type CodeCallRecord, codeCallsOf, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { writeCodeCallResult } from \"./code-call-result.js\";\nimport { effectScope } from \"./effect-scope.js\";\nimport { interruptedResult } from \"./resume.js\";\nimport { type ResolutionRecord, recordSessionStart } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { findSticky, stickyDecision } from \"./sticky.js\";\nimport type { EntryInput } from \"./store.js\";\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\ntype Body = DistributiveOmit<EntryInput, \"id\" | \"parentId\" | \"timestamp\" | \"origin\">;\n\n/** How a code call writes: one entry at a time after the one before, with its ids and clock. */\ninterface Io {\n readonly session: Session;\n write(origin: Origin, body: Body, id?: string): Promise<SessionEntry>;\n readonly newId: () => string;\n readonly clock: Clock;\n}\n\n/** The settings both a call and its resolution take: where its ids and time come from. */\ninterface IoOptions {\n readonly clock?: Clock;\n readonly newId?: () => string;\n}\n\n/** What running a code call needs besides the tool: its host context and its signal. */\ninterface RunOptions<H> extends IoOptions {\n readonly hostContext?: H;\n readonly signal?: AbortSignal;\n}\n\n// The SDK's default nesting cap, so a tool that starts an agent from a code call nests as it would in a run.\nconst MAX_DEPTH = 2;\n\nfunction ioOf(session: Session, options: IoOptions): Io {\n const newId = options.newId ?? (() => globalThis.crypto.randomUUID());\n const clock = options.clock ?? { now: () => new Date().toISOString() };\n return {\n session,\n newId,\n clock,\n async write(origin, body, id = newId()) {\n const entry = { ...body, id, parentId: session.head(), timestamp: clock.now(), origin } as EntryInput;\n const [stored] = await session.append([entry]);\n return stored as SessionEntry;\n },\n };\n}\n\nconst invalid = (message: string, cause?: unknown) =>\n new HarnessError(\"invalid_code_call\", message, cause === undefined ? {} : { cause });\n\nconst describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// One code call of a session runs at a time in a process: a second one would read the first one's open call as a crash.\n// Another process is kept out by the session's lock.\nconst queues = new WeakMap<Session, Promise<unknown>>();\n\n/** Runs `task` after every code call of `session` that this process started before it. */\nexport function inCodeCallQueue<T>(session: Session, task: () => Promise<T>): Promise<T> {\n const next = (queues.get(session) ?? Promise.resolve()).then(task, task);\n queues.set(\n session,\n next.catch(() => undefined),\n );\n return next;\n}\n\n/** The registered tool a code call names, refused when the registry lacks it or only a client can run it. */\nfunction toolFor<H>(harness: Harness<H>, name: string): RegisteredTool {\n const tool = harness.registry.get(name);\n if (tool === undefined) throw invalid(`no tool \"${name}\" is registered, so the code call can't run`);\n if (tool.pattern === \"client_request\") {\n throw invalid(`the tool \"${tool.canonicalName}\" runs on the client, which a code call has no way to reach`);\n }\n return tool;\n}\n\nasync function hashOf(value: unknown, what: string): Promise<string> {\n try {\n return await canonicalInputHash(value);\n } catch (error) {\n throw invalid(`the code call's ${what} has no canonical JSON form`, error);\n }\n}\n\n/**\n * The call's effect key: from the tool's business key when it declares one, and from the scope of `callId` otherwise.\n * A tool the registry no longer has gets the scope's key.\n */\nexport async function codeCallEffectKey<H>(\n session: Session,\n harness: Harness<H>,\n tool: RegisteredTool | undefined,\n call: { readonly callId: string; readonly input: unknown },\n): Promise<string> {\n const businessKey = tool?.definition.effect?.businessKey;\n try {\n return await effectKey(effectScope(session, harness, call.callId), businessKey?.(call.input));\n } catch (error) {\n throw invalid(`the effect key of the call to \"${tool?.canonicalName}\" could not be made`, error);\n }\n}\n\n/** Refuses a harness that can't decide or sign a code call, before anything is written. */\nfunction checkHarness<H>(harness: Harness<H>): void {\n if (harness.pipeline === undefined) {\n throw invalid(\"the harness has no permission pipeline, so no code call can be decided\");\n }\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so a code call could not ask anyone\");\n }\n}\n\n/**\n * Settles each code call a crash left open: writes the result it lacks. A call that started may have taken effect, so\n * it gets the result an interrupted model call gets. A call that never started never ran, so it gets an error that says\n * so: one that stopped before it could run or ask anyone, and one whose answer was written but which stopped, or was\n * refused, before it started. A call that asked and has no final answer still waits.\n */\nasync function settleCodeCalls<H>(path: readonly SessionEntry[], harness: Harness<H>, io: Io): Promise<void> {\n for (const { call, result, requested, answered, letRun } of codeCallsOf(path).values()) {\n if (result !== undefined || (requested !== undefined && !answered && !letRun)) continue;\n const body = letRun\n ? { origin: \"tool\" as const, ...interruptedResult(harness, call.tool) }\n : { origin: \"harness\" as const, ...notRun(answered ? NOT_RUN_ANSWERED : NOT_RUN_EARLY) };\n const { origin, ...fields } = body;\n await io.write(origin, { type: \"tool_result\", callId: call.callId, tool: call.tool, ...fields });\n }\n}\n\nconst NOT_RUN_EARLY = \"The code call stopped before it could run or ask anyone, so it never ran.\";\nconst NOT_RUN_ANSWERED = \"The code call stopped after its answer was written and before it could run, so it never ran.\";\n\nconst notRun = (text: string) => ({\n content: [{ type: \"text\" as const, text }],\n isError: true,\n trust: \"trusted\" as const,\n});\n\n/** Refuses a compensation that names no code call that ran, or that would share that call's effect key. */\nasync function checkCompensation<H>(\n session: Session,\n harness: Harness<H>,\n records: ReadonlyMap<string, CodeCallRecord>,\n compensated: string,\n ownKey: string,\n): Promise<void> {\n const target = records.get(compensated);\n // A denial is the harness's own result. A result from the tool, a crash's result, or a call let run that has no\n // result yet means the call ran or may have run.\n const ran = target?.result === undefined ? target?.letRun === true : target.result.origin === \"tool\";\n if (target === undefined || !ran) {\n throw invalid(`a compensation must name a code call that ran, and \"${compensated}\" names none`);\n }\n const theirs = await codeCallEffectKey(session, harness, harness.registry.get(target.call.tool), target.call);\n if (theirs === ownKey) {\n throw invalid(\"a compensation needs an effect key of its own, and this one has the key of the call it undoes\");\n }\n}\n\n/** Writes an error result for a call that does not run, and returns the denial. */\nasync function deny(io: Io, call: CodeCallEntry, reason: string): Promise<CodeCallResult> {\n const entry = await io.write(\"harness\", {\n type: \"tool_result\",\n callId: call.callId,\n tool: call.tool,\n ...notRun(reason),\n });\n return { status: \"denied\", callId: call.callId, reason, entryId: entry.id };\n}\n\n/** Decides the call with the pipeline, which writes its `permission_decision`, and keeps the policy version it used. */\nasync function decide<H>(\n harness: Harness<H>,\n session: Session,\n io: Io,\n call: CodeCallEntry,\n hostContext: H | undefined,\n): Promise<{ decision: Decision; policyVersion: string | undefined }> {\n let policyVersion: string | undefined;\n const policySession: PolicySession = {\n append(entry) {\n if (entry.type === \"permission_decision\") policyVersion = entry.policyVersion;\n return io.write(\"harness\", entry);\n },\n };\n // checkHarness() refused a harness without a pipeline before anything was written.\n const pipeline = harness.pipeline as NonNullable<Harness<H>[\"pipeline\"]>;\n const decision = await pipeline.decide(\n { callId: call.callId, tool: call.tool, input: call.input, initiator: \"code\" },\n { session: policySession, hostContext, entries: await session.path() },\n );\n return { decision, policyVersion: policyVersion === \"\" ? undefined : policyVersion };\n}\n\nconst isContentList = (content: unknown): content is ToolResult[\"content\"] =>\n Array.isArray(content) &&\n content.every(\n (block: Partial<ContentBlock> | null) =>\n (block?.type === \"text\" && typeof block.text === \"string\") ||\n (block?.type === \"image\" && typeof block.mediaType === \"string\" && typeof block.data === \"string\"),\n );\n\n/** A result with its write outcome's sentence in front of its content, as the model would read it. */\nfunction withOutcome(result: ToolResult<unknown>): ToolResult<unknown> {\n if (!isContentList(result?.content)) throw new TypeError(\"the tool returned content that is not text and images\");\n if (result.outcome === undefined) return result;\n const rendered = renderOutcome(result.outcome);\n return {\n ...result,\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n ...result.content,\n ],\n isError: result.isError === true || rendered.isError,\n };\n}\n\n/** The result of a tool that threw or returned something unusable: a write's outcome is unknown, since it may have run. */\nfunction thrownResult(tool: RegisteredTool, error: unknown): ToolResult<unknown> {\n const text = tool.definition.redactErrors === true ? \"The tool failed.\" : `The tool failed: ${describe(error)}`;\n if (tool.definition.effect?.kind !== \"write\") return { content: [{ type: \"text\", text }], isError: true };\n const rendered = renderOutcome(\n writeOutcome({\n kind: \"unknown\",\n operation: tool.canonicalName,\n retry: \"reconcile_first\",\n reason: \"WRITE_FAILED\",\n currentState: \"The tool failed before it returned, so the write may have taken effect.\",\n next: \"Check whether it took effect before you do anything else.\",\n }),\n );\n return {\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n { type: \"text\", text },\n ],\n isError: true,\n details: { outcome: rendered.payload },\n };\n}\n\n/**\n * Runs the tool through the harness's wrapper with the host context, and writes its result. The harness's interceptors\n * and observers belong to a turn's model step, so they don't run here; the pipeline already decided the call.\n */\nasync function runTool<H>(\n harness: Harness<H>,\n io: Io,\n tool: RegisteredTool,\n call: CodeCallEntry,\n options: RunOptions<H> & { readonly effectKey: string },\n): Promise<CodeCallResult> {\n const ctx: ToolContext<unknown> = {\n runId: call.callId,\n callId: call.callId,\n signal: options.signal ?? new AbortController().signal,\n depth: 0,\n maxDepth: MAX_DEPTH,\n clock: io.clock,\n app: options.hostContext,\n update: () => undefined,\n };\n let result: ToolResult<unknown>;\n // A wrapper that throws is recorded like a tool that throws, so the call that was let run still gets a result.\n try {\n const definition = harness.wrap === undefined ? tool.definition : harness.wrap(tool, options.hostContext as H);\n result = withOutcome(await definition.execute(call.input, ctx));\n } catch (error) {\n result = thrownResult(tool, error);\n }\n const writer = {\n session: io.session,\n now: io.clock.now,\n signal: ctx.signal,\n write: (body: Body) => io.write(\"tool\", body),\n };\n const entry = await writeCodeCallResult(harness, writer, tool, call, result);\n return { status: \"done\", callId: call.callId, result, entryId: entry.id, effectKey: options.effectKey };\n}\n\n/** Signs the request for a call the pipeline asks about, and writes it before anyone can hear of it. */\nasync function ask<H>(\n harness: Harness<H>,\n io: Io,\n call: CodeCallEntry,\n decision: { reason: string; policyVersion: string | undefined; hostContext: H | undefined; effectKey: string },\n): Promise<CodeCallResult> {\n const { reason, policyVersion, hostContext } = decision;\n const pending = await createPendingRequest(\n {\n kind: \"approval\",\n callId: call.callId,\n tool: call.tool,\n input: call.input,\n ...(policyVersion === undefined ? {} : { policyVersion }),\n ...(reason === \"\" ? {} : { reason }),\n ...(hostContext === undefined ? {} : { app: hostContext }),\n },\n // checkHarness() refused a harness without a signer before anything was written.\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: call.input });\n return { status: \"awaiting_approval\", callId: call.callId, pending, effectKey: decision.effectKey };\n}\n\n/** Checks everything a code call needs before its first entry, and returns its tool, input hash and effect key. */\nasync function prepare<H>(harness: Harness<H>, session: Session, call: CodeCall<H>, callId: string) {\n checkHarness(harness);\n const tool = toolFor(harness, call.tool);\n const inputHash = await hashOf(call.input, \"input\");\n if (call.hostContext !== undefined) await hashOf(call.hostContext, \"host context\");\n const key = await codeCallEffectKey(session, harness, tool, { callId, input: call.input });\n return { tool, inputHash, key };\n}\n\n/** `Harness.invokeTool()`: see its documentation. */\nexport async function invokeCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n call: CodeCall<H>,\n): Promise<CodeCallResult> {\n // Checked before the queue too, so an aborted call never waits behind another.\n call.signal?.throwIfAborted();\n return inCodeCallQueue(session, () => invokeQueued(harness, session, call));\n}\n\nasync function invokeQueued<H>(harness: Harness<H>, session: Session, call: CodeCall<H>): Promise<CodeCallResult> {\n const io = ioOf(session, call);\n const callId = io.newId();\n const { tool, inputHash, key } = await prepare(harness, session, call, callId);\n const path = await session.path();\n if (call.compensates !== undefined) {\n await checkCompensation(session, harness, codeCallsOf(path), call.compensates, key);\n }\n call.signal?.throwIfAborted();\n await recordSessionStart(harness, (origin, body) => io.write(origin, body), harness.model, path);\n await settleCodeCalls(await session.path(), harness, io);\n const entry: CodeCallEntry = {\n type: \"code_call\",\n callId,\n tool: tool.canonicalName,\n input: call.input,\n inputHash,\n ...(call.compensates === undefined ? {} : { compensates: call.compensates }),\n };\n await io.write(\"harness\", entry, callId);\n const { decision, policyVersion } = await decide(harness, session, io, entry, call.hostContext);\n if (decision.decision === \"deny\") return deny(io, entry, decision.reason);\n const run = { ...call, effectKey: key };\n if (decision.decision === \"allow\") return runTool(harness, io, tool, entry, run);\n const covered = await findSticky(await session.path(), { ...entry, policyVersion }, harness.registry);\n if (covered === undefined) {\n return ask(harness, io, entry, {\n reason: decision.reason,\n policyVersion,\n hostContext: call.hostContext,\n effectKey: key,\n });\n }\n await io.write(\"harness\", await stickyDecision(entry, covered, policyVersion));\n return runTool(harness, io, tool, entry, run);\n}\n\n/**\n * Checks a resolution against the waiting call's signed request before anything is written: the signature under a key\n * the signer holds, the host context the request binds, the call and tool, and the input, which must hash to the signed\n * hash in the `code_call` entry, in the `approval_requested` entry and in the request alike. Throws `approval_refused`\n * with the cause, which names no key, signature or input.\n */\nexport async function checkCodeCallRequest<H>(\n harness: Harness<H>,\n waiting: WaitingCodeCall,\n resolution: Resolution,\n hostContext: H | undefined,\n): Promise<void> {\n const { call, request, input } = waiting;\n const check = await verifyResolution(request, resolution, {\n signer: harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n call: { callId: call.callId, tool: call.tool, input: call.input },\n ...(hostContext === undefined ? {} : { app: hostContext }),\n });\n const cause = check.ok ? await inputCause(call, input) : check.cause;\n if (cause !== undefined) {\n throw new HarnessError(\n \"approval_refused\",\n `the request for code call ${call.callId} failed its check (${cause}), so nothing ran and nothing was written`,\n );\n }\n}\n\n/** `input_changed` unless the recorded input and the input shown to the approver both hash to the recorded hash. */\nasync function inputCause(call: CodeCallEntry, shown: unknown): Promise<\"input_changed\" | undefined> {\n const hash = async (value: unknown) => canonicalInputHash(value).catch(() => undefined);\n const [recorded, asked] = await Promise.all([hash(call.input), hash(shown)]);\n return recorded === call.inputHash && asked === call.inputHash ? undefined : \"input_changed\";\n}\n\n/** What the resolution of a code call is given: the answer the quorum settled on, if any, and the entries to write. */\nexport interface SettledCodeCall {\n readonly forRun: Resolution | undefined;\n readonly records: readonly ResolutionRecord[];\n readonly effectKey: string;\n}\n\n/**\n * Applies a code call's settled resolution: it writes the answers, then leaves the call waiting when the quorum still\n * waits, denies it for a person's or the policy's refusal, and otherwise decides it again with the pipeline, so a deny\n * written since the pause wins, and runs the tool itself, with no model step.\n */\nexport async function finishCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n waiting: WaitingCodeCall,\n settled: SettledCodeCall,\n options: RunOptions<H>,\n): Promise<CodeCallResult> {\n options.signal?.throwIfAborted();\n const io = ioOf(session, options);\n for (const record of settled.records) await io.write(\"user\", { type: \"approval_resolved\", ...record });\n const { call } = waiting;\n const { forRun, effectKey: key } = settled;\n if (forRun === undefined) {\n return { status: \"awaiting_approval\", callId: call.callId, pending: waiting.request, effectKey: key };\n }\n if (!(\"decision\" in forRun) || forRun.decision !== \"allow\") {\n return deny(io, call, (\"reason\" in forRun ? forRun.reason : undefined) ?? \"A person denied the call.\");\n }\n const tool = harness.registry.get(call.tool);\n if (tool?.canonicalName !== call.tool || tool.pattern !== \"in_process\") {\n return deny(io, call, `The tool \"${call.tool}\" is no longer registered for code calls, so the call did not run.`);\n }\n const { decision } = await decide(harness, session, io, call, options.hostContext);\n // A person approved the call, so a question the pipeline would ask again doesn't stop it; a deny does.\n if (decision.decision === \"deny\") return deny(io, call, decision.reason);\n return runTool(harness, io, tool, call, { ...options, effectKey: key });\n}\n"]}
1
+ {"version":3,"file":"code-call.js","sourceRoot":"","sources":["../../src/session/code-call.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAGpF,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EAIpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAI5C,OAAO,EAAuB,WAAW,EAAwB,MAAM,oBAAoB,CAAC;AAC5F,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAExE,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AA2BzD,6GAA6G;AAC7G,MAAM,SAAS,GAAG,CAAC,CAAC;AAEpB,0GAA0G;AAC1G,MAAM,UAAU,IAAI,CAAC,OAAgB,EAAE,OAAkB;IACvD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;IACtE,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC;IACvE,OAAO;QACL,OAAO;QACP,KA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AAK,OAAO,EAAE,CAAC;QAC3D,OAAO,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,QAAQ,IAAI,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,2BAA2B,CAAC,CAAC;IACzG,CAAC;IACD,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC7C,IAAI,IAAI,EAAE,aAAa,KAAK,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO,KAAK,YAAY,EAAE,CAAC;QACvE,OAAO,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,aAAa,IAAI,CAAC,IAAI,oEAAoE,CAAC,CAAC;IACpH,CAAC;IACD,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IACnF,uGAAuG;IACvG,IAAI,QAAQ,CAAC,QAAQ,KAAK,MAAM;QAAE,OAAO,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACzE,OAAO,OAAO,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * Code-initiated tool calls: a side effect the host's own code chose, run through the same permission pipeline, signed\n * pause and log as a call the model makes, with no model step. The `code_call` entry is written before anything else\n * of the call, and its id is the call id, so the effect key is fixed before the tool can run and a resume finds it.\n * A call starts once its log holds the entry that clears it to run; one that started with no result is never rerun.\n */\nimport { effectKey, renderOutcome, writeOutcome } from \"@buildanagent/agent-safety\";\nimport type { ContentBlock } from \"@buildanagent/gateway\";\nimport type { CodeCallEntry, Origin, SessionEntry } from \"@buildanagent/protocol\";\nimport {\n canonicalInputHash,\n createPendingRequest,\n type Resolution,\n type ToolContext,\n type ToolResult,\n verifyResolution,\n} from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCall, CodeCallResult, Harness } from \"../harness.js\";\nimport type { Decision, PolicySession } from \"../permissions/types.js\";\nimport type { RegisteredTool } from \"../tools/types.js\";\nimport { type CodeCallRecord, codeCallsOf, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { writeCodeCallResult } from \"./code-call-result.js\";\nimport { effectScope } from \"./effect-scope.js\";\nimport { interruptedResult } from \"./resume.js\";\nimport { type ResolutionRecord, recordSessionStart } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { findSticky, stickyDecision } from \"./sticky.js\";\nimport type { EntryInput } from \"./store.js\";\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n/** An entry to write, without the fields the writer fills in. */\nexport type Body = DistributiveOmit<EntryInput, \"id\" | \"parentId\" | \"timestamp\" | \"origin\">;\n\n/** How a code call, or a sandbox escalation, writes: one entry at a time after the one before, with its ids and clock. */\nexport interface Io {\n readonly session: Session;\n write(origin: Origin, body: Body, id?: string): Promise<SessionEntry>;\n readonly newId: () => string;\n readonly clock: Clock;\n}\n\n/** The settings both a call and its resolution take: where its ids and time come from. */\nexport interface IoOptions {\n readonly clock?: Clock;\n readonly newId?: () => string;\n}\n\n/** What running a code call needs besides the tool: its host context and its signal. */\ninterface RunOptions<H> extends IoOptions {\n readonly hostContext?: H;\n readonly signal?: AbortSignal;\n}\n\n// The SDK's default nesting cap, so a tool that starts an agent from a code call nests as it would in a run.\nconst MAX_DEPTH = 2;\n\n/** A writer for `session` with the given ids and clock, defaulting to random ids and the system clock. */\nexport function ioOf(session: Session, options: IoOptions): Io {\n const newId = options.newId ?? (() => globalThis.crypto.randomUUID());\n const clock = options.clock ?? { now: () => new Date().toISOString() };\n return {\n session,\n newId,\n clock,\n async write(origin, body, id = newId()) {\n const entry = { ...body, id, parentId: session.head(), timestamp: clock.now(), origin } as EntryInput;\n const [stored] = await session.append([entry]);\n return stored as SessionEntry;\n },\n };\n}\n\nconst invalid = (message: string, cause?: unknown) =>\n new HarnessError(\"invalid_code_call\", message, cause === undefined ? {} : { cause });\n\nconst describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n// One code call of a session runs at a time in a process: a second one would read the first one's open call as a crash.\n// Another process is kept out by the session's lock.\nconst queues = new WeakMap<Session, Promise<unknown>>();\n\n/** Runs `task` after every code call of `session` that this process started before it. */\nexport function inCodeCallQueue<T>(session: Session, task: () => Promise<T>): Promise<T> {\n const next = (queues.get(session) ?? Promise.resolve()).then(task, task);\n queues.set(\n session,\n next.catch(() => undefined),\n );\n return next;\n}\n\n/** The registered tool a code call names, refused when the registry lacks it or only a client can run it. */\nfunction toolFor<H>(harness: Harness<H>, name: string): RegisteredTool {\n const tool = harness.registry.get(name);\n if (tool === undefined) throw invalid(`no tool \"${name}\" is registered, so the code call can't run`);\n if (tool.pattern === \"client_request\") {\n throw invalid(`the tool \"${tool.canonicalName}\" runs on the client, which a code call has no way to reach`);\n }\n return tool;\n}\n\nasync function hashOf(value: unknown, what: string): Promise<string> {\n try {\n return await canonicalInputHash(value);\n } catch (error) {\n throw invalid(`the code call's ${what} has no canonical JSON form`, error);\n }\n}\n\n/**\n * The call's effect key: from the tool's business key when it declares one, and from the scope of `callId` otherwise.\n * A tool the registry no longer has gets the scope's key.\n */\nexport async function codeCallEffectKey<H>(\n session: Session,\n harness: Harness<H>,\n tool: RegisteredTool | undefined,\n call: { readonly callId: string; readonly input: unknown },\n): Promise<string> {\n const businessKey = tool?.definition.effect?.businessKey;\n try {\n return await effectKey(effectScope(session, harness, call.callId), businessKey?.(call.input));\n } catch (error) {\n throw invalid(`the effect key of the call to \"${tool?.canonicalName}\" could not be made`, error);\n }\n}\n\n/** Refuses a harness that can't decide or sign a code call, before anything is written. */\nfunction checkHarness<H>(harness: Harness<H>): void {\n if (harness.pipeline === undefined) {\n throw invalid(\"the harness has no permission pipeline, so no code call can be decided\");\n }\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so a code call could not ask anyone\");\n }\n}\n\n/**\n * Settles each code call a crash left open: writes the result it lacks. A call that started may have taken effect, so\n * it gets the result an interrupted model call gets. A call that never started never ran, so it gets an error that says\n * so: one that stopped before it could run or ask anyone, and one whose answer was written but which stopped, or was\n * refused, before it started. A call that asked and has no final answer still waits.\n */\nasync function settleCodeCalls<H>(path: readonly SessionEntry[], harness: Harness<H>, io: Io): Promise<void> {\n for (const { call, result, requested, answered, letRun } of codeCallsOf(path).values()) {\n if (result !== undefined || (requested !== undefined && !answered && !letRun)) continue;\n const body = letRun\n ? { origin: \"tool\" as const, ...interruptedResult(harness, call.tool) }\n : { origin: \"harness\" as const, ...notRun(answered ? NOT_RUN_ANSWERED : NOT_RUN_EARLY) };\n const { origin, ...fields } = body;\n await io.write(origin, { type: \"tool_result\", callId: call.callId, tool: call.tool, ...fields });\n }\n}\n\nconst NOT_RUN_EARLY = \"The code call stopped before it could run or ask anyone, so it never ran.\";\nconst NOT_RUN_ANSWERED = \"The code call stopped after its answer was written and before it could run, so it never ran.\";\n\nconst notRun = (text: string) => ({\n content: [{ type: \"text\" as const, text }],\n isError: true,\n trust: \"trusted\" as const,\n});\n\n/** Refuses a compensation that names no code call that ran, or that would share that call's effect key. */\nasync function checkCompensation<H>(\n session: Session,\n harness: Harness<H>,\n records: ReadonlyMap<string, CodeCallRecord>,\n compensated: string,\n ownKey: string,\n): Promise<void> {\n const target = records.get(compensated);\n // A denial is the harness's own result. A result from the tool, a crash's result, or a call let run that has no\n // result yet means the call ran or may have run.\n const ran = target?.result === undefined ? target?.letRun === true : target.result.origin === \"tool\";\n if (target === undefined || !ran) {\n throw invalid(`a compensation must name a code call that ran, and \"${compensated}\" names none`);\n }\n const theirs = await codeCallEffectKey(session, harness, harness.registry.get(target.call.tool), target.call);\n if (theirs === ownKey) {\n throw invalid(\"a compensation needs an effect key of its own, and this one has the key of the call it undoes\");\n }\n}\n\n/** Writes an error result for a call that does not run, and returns the denial. */\nasync function deny(io: Io, call: CodeCallEntry, reason: string): Promise<CodeCallResult> {\n const entry = await io.write(\"harness\", {\n type: \"tool_result\",\n callId: call.callId,\n tool: call.tool,\n ...notRun(reason),\n });\n return { status: \"denied\", callId: call.callId, reason, entryId: entry.id };\n}\n\n/** Decides the call with the pipeline, which writes its `permission_decision`, and keeps the policy version it used. */\nasync function decide<H>(\n harness: Harness<H>,\n session: Session,\n io: Io,\n call: CodeCallEntry,\n hostContext: H | undefined,\n): Promise<{ decision: Decision; policyVersion: string | undefined }> {\n let policyVersion: string | undefined;\n const policySession: PolicySession = {\n append(entry) {\n if (entry.type === \"permission_decision\") policyVersion = entry.policyVersion;\n return io.write(\"harness\", entry);\n },\n };\n // checkHarness() refused a harness without a pipeline before anything was written.\n const pipeline = harness.pipeline as NonNullable<Harness<H>[\"pipeline\"]>;\n const decision = await pipeline.decide(\n { callId: call.callId, tool: call.tool, input: call.input, initiator: \"code\" },\n { session: policySession, hostContext, entries: await session.path() },\n );\n return { decision, policyVersion: policyVersion === \"\" ? undefined : policyVersion };\n}\n\nconst isContentList = (content: unknown): content is ToolResult[\"content\"] =>\n Array.isArray(content) &&\n content.every(\n (block: Partial<ContentBlock> | null) =>\n (block?.type === \"text\" && typeof block.text === \"string\") ||\n (block?.type === \"image\" && typeof block.mediaType === \"string\" && typeof block.data === \"string\"),\n );\n\n/** A result with its write outcome's sentence in front of its content, as the model would read it. */\nfunction withOutcome(result: ToolResult<unknown>): ToolResult<unknown> {\n if (!isContentList(result?.content)) throw new TypeError(\"the tool returned content that is not text and images\");\n if (result.outcome === undefined) return result;\n const rendered = renderOutcome(result.outcome);\n return {\n ...result,\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n ...result.content,\n ],\n isError: result.isError === true || rendered.isError,\n };\n}\n\n/** The result of a tool that threw or returned something unusable: a write's outcome is unknown, since it may have run. */\nfunction thrownResult(tool: RegisteredTool, error: unknown): ToolResult<unknown> {\n const text = tool.definition.redactErrors === true ? \"The tool failed.\" : `The tool failed: ${describe(error)}`;\n if (tool.definition.effect?.kind !== \"write\") return { content: [{ type: \"text\", text }], isError: true };\n const rendered = renderOutcome(\n writeOutcome({\n kind: \"unknown\",\n operation: tool.canonicalName,\n retry: \"reconcile_first\",\n reason: \"WRITE_FAILED\",\n currentState: \"The tool failed before it returned, so the write may have taken effect.\",\n next: \"Check whether it took effect before you do anything else.\",\n }),\n );\n return {\n content: [\n { type: \"text\", text: rendered.text },\n { type: \"text\", text: JSON.stringify({ outcome: rendered.payload }) },\n { type: \"text\", text },\n ],\n isError: true,\n details: { outcome: rendered.payload },\n };\n}\n\n/**\n * Runs the tool through the harness's wrapper with the host context, and writes its result. The harness's interceptors\n * and observers belong to a turn's model step, so they don't run here; the pipeline already decided the call.\n */\nasync function runTool<H>(\n harness: Harness<H>,\n io: Io,\n tool: RegisteredTool,\n call: CodeCallEntry,\n options: RunOptions<H> & { readonly effectKey: string },\n): Promise<CodeCallResult> {\n const ctx: ToolContext<unknown> = {\n runId: call.callId,\n callId: call.callId,\n signal: options.signal ?? new AbortController().signal,\n depth: 0,\n maxDepth: MAX_DEPTH,\n clock: io.clock,\n app: options.hostContext,\n update: () => undefined,\n };\n let result: ToolResult<unknown>;\n // A wrapper that throws is recorded like a tool that throws, so the call that was let run still gets a result.\n try {\n const definition = harness.wrap === undefined ? tool.definition : harness.wrap(tool, options.hostContext as H);\n result = withOutcome(await definition.execute(call.input, ctx));\n } catch (error) {\n result = thrownResult(tool, error);\n }\n const writer = {\n session: io.session,\n now: io.clock.now,\n signal: ctx.signal,\n write: (body: Body) => io.write(\"tool\", body),\n };\n const entry = await writeCodeCallResult(harness, writer, tool, call, result);\n return { status: \"done\", callId: call.callId, result, entryId: entry.id, effectKey: options.effectKey };\n}\n\n/** Signs the request for a call the pipeline asks about, and writes it before anyone can hear of it. */\nasync function ask<H>(\n harness: Harness<H>,\n io: Io,\n call: CodeCallEntry,\n decision: { reason: string; policyVersion: string | undefined; hostContext: H | undefined; effectKey: string },\n): Promise<CodeCallResult> {\n const { reason, policyVersion, hostContext } = decision;\n const pending = await createPendingRequest(\n {\n kind: \"approval\",\n callId: call.callId,\n tool: call.tool,\n input: call.input,\n ...(policyVersion === undefined ? {} : { policyVersion }),\n ...(reason === \"\" ? {} : { reason }),\n ...(hostContext === undefined ? {} : { app: hostContext }),\n },\n // checkHarness() refused a harness without a signer before anything was written.\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: call.input });\n return { status: \"awaiting_approval\", callId: call.callId, pending, effectKey: decision.effectKey };\n}\n\n/** Checks everything a code call needs before its first entry, and returns its tool, input hash and effect key. */\nasync function prepare<H>(harness: Harness<H>, session: Session, call: CodeCall<H>, callId: string) {\n checkHarness(harness);\n const tool = toolFor(harness, call.tool);\n const inputHash = await hashOf(call.input, \"input\");\n if (call.hostContext !== undefined) await hashOf(call.hostContext, \"host context\");\n const key = await codeCallEffectKey(session, harness, tool, { callId, input: call.input });\n return { tool, inputHash, key };\n}\n\n/** `Harness.invokeTool()`: see its documentation. */\nexport async function invokeCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n call: CodeCall<H>,\n): Promise<CodeCallResult> {\n // Checked before the queue too, so an aborted call never waits behind another.\n call.signal?.throwIfAborted();\n return inCodeCallQueue(session, () => invokeQueued(harness, session, call));\n}\n\nasync function invokeQueued<H>(harness: Harness<H>, session: Session, call: CodeCall<H>): Promise<CodeCallResult> {\n const io = ioOf(session, call);\n const callId = io.newId();\n const { tool, inputHash, key } = await prepare(harness, session, call, callId);\n const path = await session.path();\n if (call.compensates !== undefined) {\n await checkCompensation(session, harness, codeCallsOf(path), call.compensates, key);\n }\n call.signal?.throwIfAborted();\n await recordSessionStart(harness, (origin, body) => io.write(origin, body), harness.model, path);\n await settleCodeCalls(await session.path(), harness, io);\n const entry: CodeCallEntry = {\n type: \"code_call\",\n callId,\n tool: tool.canonicalName,\n input: call.input,\n inputHash,\n ...(call.compensates === undefined ? {} : { compensates: call.compensates }),\n };\n await io.write(\"harness\", entry, callId);\n const { decision, policyVersion } = await decide(harness, session, io, entry, call.hostContext);\n if (decision.decision === \"deny\") return deny(io, entry, decision.reason);\n const run = { ...call, effectKey: key };\n if (decision.decision === \"allow\") return runTool(harness, io, tool, entry, run);\n const covered = await findSticky(await session.path(), { ...entry, policyVersion }, harness.registry);\n if (covered === undefined) {\n return ask(harness, io, entry, {\n reason: decision.reason,\n policyVersion,\n hostContext: call.hostContext,\n effectKey: key,\n });\n }\n await io.write(\"harness\", await stickyDecision(entry, covered, policyVersion));\n return runTool(harness, io, tool, entry, run);\n}\n\n/**\n * Checks a resolution against the waiting call's signed request before anything is written: the signature under a key\n * the signer holds, the host context the request binds, the call and tool, and the input, which must hash to the signed\n * hash in the `code_call` entry, in the `approval_requested` entry and in the request alike. Throws `approval_refused`\n * with the cause, which names no key, signature or input.\n */\nexport async function checkCodeCallRequest<H>(\n harness: Harness<H>,\n waiting: WaitingCodeCall,\n resolution: Resolution,\n hostContext: H | undefined,\n): Promise<void> {\n const { call, request, input } = waiting;\n const check = await verifyResolution(request, resolution, {\n signer: harness.signer as NonNullable<Harness<H>[\"signer\"]>,\n call: { callId: call.callId, tool: call.tool, input: call.input },\n ...(hostContext === undefined ? {} : { app: hostContext }),\n });\n const cause = check.ok ? await inputCause(call, input) : check.cause;\n if (cause !== undefined) {\n throw new HarnessError(\n \"approval_refused\",\n `the request for code call ${call.callId} failed its check (${cause}), so nothing ran and nothing was written`,\n );\n }\n}\n\n/** `input_changed` unless the recorded input and the input shown to the approver both hash to the recorded hash. */\nasync function inputCause(call: CodeCallEntry, shown: unknown): Promise<\"input_changed\" | undefined> {\n const hash = async (value: unknown) => canonicalInputHash(value).catch(() => undefined);\n const [recorded, asked] = await Promise.all([hash(call.input), hash(shown)]);\n return recorded === call.inputHash && asked === call.inputHash ? undefined : \"input_changed\";\n}\n\n/** What the resolution of a code call is given: the answer the quorum settled on, if any, and the entries to write. */\nexport interface SettledCodeCall {\n readonly forRun: Resolution | undefined;\n readonly records: readonly ResolutionRecord[];\n readonly effectKey: string;\n}\n\n/**\n * Applies a code call's settled resolution: it writes the answers, then leaves the call waiting when the quorum still\n * waits, denies it for a person's or the policy's refusal, and otherwise decides it again with the pipeline, so a deny\n * written since the pause wins, and runs the tool itself, with no model step.\n */\nexport async function finishCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n waiting: WaitingCodeCall,\n settled: SettledCodeCall,\n options: RunOptions<H>,\n): Promise<CodeCallResult> {\n options.signal?.throwIfAborted();\n const io = ioOf(session, options);\n for (const record of settled.records) await io.write(\"user\", { type: \"approval_resolved\", ...record });\n const { call } = waiting;\n const { forRun, effectKey: key } = settled;\n if (forRun === undefined) {\n return { status: \"awaiting_approval\", callId: call.callId, pending: waiting.request, effectKey: key };\n }\n if (!(\"decision\" in forRun) || forRun.decision !== \"allow\") {\n return deny(io, call, (\"reason\" in forRun ? forRun.reason : undefined) ?? \"A person denied the call.\");\n }\n const tool = harness.registry.get(call.tool);\n if (tool?.canonicalName !== call.tool || tool.pattern !== \"in_process\") {\n return deny(io, call, `The tool \"${call.tool}\" is no longer registered for code calls, so the call did not run.`);\n }\n const { decision } = await decide(harness, session, io, call, options.hostContext);\n // A person approved the call, so a question the pipeline would ask again doesn't stop it; a deny does.\n if (decision.decision === \"deny\") return deny(io, call, decision.reason);\n return runTool(harness, io, tool, call, { ...options, effectKey: key });\n}\n"]}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * What the log says about each sandbox escalation: its latest signed request, whether its answer is final, whether its
3
+ * rerun started, and its result. An escalation is keyed by the call id of its request, whose tool is
4
+ * `ESCALATION_TOOL`. That name breaks the canonical tool-name rule, so no registered tool, and no call the model makes,
5
+ * can carry it. A rerun that started and has no result is never run again: the crash rule a code call follows.
6
+ */
7
+ import type { SessionEntry, ToolResultEntry } from "@buildanagent/protocol";
8
+ import type { SignedPendingRequest } from "@buildanagent/sdk";
9
+ import type { SandboxDenial, SandboxPolicy } from "../sandbox/types.js";
10
+ /** The tool name an escalation's signed request carries. It has a dot, so no registered tool can share it. */
11
+ export declare const ESCALATION_TOOL = "sandbox.escalation";
12
+ /**
13
+ * What an escalation's request signs, as the input of its `approval_requested` entry: the call the command ran for,
14
+ * the command, the workspace root, the policy it ran under and the denial. The rerun's policy is built from `policy`
15
+ * and `denial` alone, once the signature over this record verifies.
16
+ */
17
+ export interface EscalationRecord {
18
+ /** The tool the command ran for, which the permission pipeline decides again before the rerun. */
19
+ readonly tool: string;
20
+ /** That tool call's input, as the pipeline sees it. */
21
+ readonly input: unknown;
22
+ /** Who chose the call: the model, or the host's own code. */
23
+ readonly initiator: "model" | "code";
24
+ /** The tool call's own id, when the command ran for one. */
25
+ readonly toolCallId?: string;
26
+ /** The executable and its arguments. */
27
+ readonly command: readonly string[];
28
+ /** The working directory, relative to the workspace root. */
29
+ readonly cwd?: string;
30
+ /** The command's timeout, which the rerun keeps. */
31
+ readonly timeoutMs?: number;
32
+ /** The command's output cap, which the rerun keeps. */
33
+ readonly maxOutputBytes?: number;
34
+ /** The workspace root the sandbox was provisioned for. */
35
+ readonly root: string;
36
+ /** The policy the command ran under. */
37
+ readonly policy: SandboxPolicy;
38
+ /** What the backend refused. */
39
+ readonly denial: SandboxDenial;
40
+ }
41
+ /** True when `value` has the shape of an `EscalationRecord`. A record is checked after its signature verifies too. */
42
+ export declare function isEscalationRecord(value: unknown): value is EscalationRecord;
43
+ /** One escalation as the log records it. */
44
+ export interface EscalationLogRecord {
45
+ /** The escalation's id: its request's call id. */
46
+ readonly id: string;
47
+ /** The latest signed request and the record it signs, which a forged entry may not hold until it is checked. */
48
+ readonly requested: {
49
+ readonly request: SignedPendingRequest;
50
+ readonly input: unknown;
51
+ };
52
+ /** True once an answer is final: one no quorum still waits on, or the policy's refusal. */
53
+ readonly answered: boolean;
54
+ /**
55
+ * True once the rerun started: after a final allow, the permission pipeline wrote a decision that is not a deny.
56
+ * That entry is the last one before the rerun runs.
57
+ */
58
+ readonly started: boolean;
59
+ /** The escalation's `tool_result` entry, once it has one. */
60
+ readonly result?: SessionEntry & ToolResultEntry;
61
+ }
62
+ /** Every escalation on `path`, by id, in the order they asked. */
63
+ export declare function escalationsOf(path: readonly SessionEntry[]): Map<string, EscalationLogRecord>;
64
+ /** The escalations on `path` that wait for an answer: no final answer, no started rerun and no result. */
65
+ export declare function waitingEscalations(path: readonly SessionEntry[]): EscalationLogRecord[];
@@ -0,0 +1,84 @@
1
+ import { isDenial } from "../sandbox/widen.js";
2
+ /** The tool name an escalation's signed request carries. It has a dot, so no registered tool can share it. */
3
+ export const ESCALATION_TOOL = "sandbox.escalation";
4
+ const isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
5
+ function isPolicy(value) {
6
+ if (typeof value !== "object" || value === null)
7
+ return false;
8
+ const policy = value;
9
+ const network = policy.network;
10
+ return (isStrings(policy.readRoots) &&
11
+ isStrings(policy.writeRoots) &&
12
+ typeof network === "object" &&
13
+ network !== null &&
14
+ isStrings(network.allow) &&
15
+ isStrings(network.deny));
16
+ }
17
+ const optional = (value, type) => value === undefined || typeof value === type;
18
+ /** True when `value` has the shape of an `EscalationRecord`. A record is checked after its signature verifies too. */
19
+ export function isEscalationRecord(value) {
20
+ if (typeof value !== "object" || value === null)
21
+ return false;
22
+ const record = value;
23
+ return (typeof record.tool === "string" &&
24
+ (record.initiator === "model" || record.initiator === "code") &&
25
+ optional(record.toolCallId, "string") &&
26
+ isStrings(record.command) &&
27
+ record.command.length > 0 &&
28
+ optional(record.cwd, "string") &&
29
+ optional(record.timeoutMs, "number") &&
30
+ optional(record.maxOutputBytes, "number") &&
31
+ typeof record.root === "string" &&
32
+ isPolicy(record.policy) &&
33
+ isDenial(record.denial));
34
+ }
35
+ /** Folds a request: a later request for the same escalation replaces the earlier one and waits for its own answer. */
36
+ function foldRequest(drafts, byRequest, entry) {
37
+ if (entry.type !== "approval_requested")
38
+ return;
39
+ const id = entry.request.callId;
40
+ const requested = { request: entry.request, input: entry.input };
41
+ const draft = drafts.get(id);
42
+ if (draft === undefined)
43
+ drafts.set(id, { id, requested, answered: false, personAllowed: false, started: false });
44
+ else
45
+ Object.assign(draft, { requested, answered: false, personAllowed: false });
46
+ byRequest.set(entry.request.id, id);
47
+ }
48
+ /** Folds an entry that names the escalation's id: the pipeline's decision, which starts the rerun, or its result. */
49
+ function foldCall(draft, entry) {
50
+ if (entry.type === "permission_decision")
51
+ draft.started = entry.decision !== "deny" && draft.personAllowed;
52
+ else if (entry.type === "tool_result")
53
+ draft.result ??= entry;
54
+ }
55
+ function fold(drafts, byRequest, entry) {
56
+ if (entry.type === "approval_requested" && entry.request.tool === ESCALATION_TOOL) {
57
+ foldRequest(drafts, byRequest, entry);
58
+ }
59
+ else if (entry.type === "approval_resolved" && entry.quorum === undefined) {
60
+ const draft = drafts.get(byRequest.get(entry.resolution.requestId) ?? "");
61
+ if (draft === undefined)
62
+ return;
63
+ draft.answered = true;
64
+ draft.personAllowed = "decision" in entry.resolution && entry.resolution.decision === "allow";
65
+ }
66
+ else if ("callId" in entry) {
67
+ const draft = drafts.get(entry.callId);
68
+ if (draft !== undefined)
69
+ foldCall(draft, entry);
70
+ }
71
+ }
72
+ /** Every escalation on `path`, by id, in the order they asked. */
73
+ export function escalationsOf(path) {
74
+ const drafts = new Map();
75
+ const byRequest = new Map();
76
+ for (const entry of path)
77
+ fold(drafts, byRequest, entry);
78
+ return drafts;
79
+ }
80
+ /** The escalations on `path` that wait for an answer: no final answer, no started rerun and no result. */
81
+ export function waitingEscalations(path) {
82
+ return [...escalationsOf(path).values()].filter((record) => record.result === undefined && !record.answered && !record.started);
83
+ }
84
+ //# sourceMappingURL=escalation-log.js.map
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AAK,EAAE,KAAK,CAAC,CAAC;IAClD,CAAC;AACH,CAAC;AAED,kEAAkE;AAClE,MAAM,UAAU,aAAa,CAAC,IAA6B;IACzD,MAAM,MAAM,GAAG,IAAI,GAAG,EAAiB,CAAC;IACxC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC5C,KAAK,MAAM,KAAK,IAAI,IAAI;QAAE,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IACzD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,0GAA0G;AAC1G,MAAM,UAAU,kBAAkB,CAAC,IAA6B;IAC9D,OAAO,CAAC,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC,MAAM,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"]}
@@ -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
- const codeCalls = new Set(path.flatMap((entry) => (entry.type === "code_call" ? [entry.callId] : [])));
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" && codeCalls.has(entry.callId))
201
+ if (entry.type === "tool_result" && hostCalls.has(entry.callId))
193
202
  continue;
194
203
  switch (entry.type) {
195
204
  case "message_block":