@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":"rebuild.js","sourceRoot":"","sources":["../../src/session/rebuild.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAK5C,MAAM,OAAO,GAAG,CAAC,MAAwB,EAAkB,EAAE,CAC3D,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAE5E,+GAA+G;AAC/G,MAAM,cAAc;IACT,QAAQ,GAAc,EAAE,CAAC;IAClC,0EAA0E;IACjE,MAAM,GAAa,EAAE,CAAC;IAC/B,KAAK,CAAsB;IAClB,UAAU,CAAsB;IACzC,MAAM,CAA6D;IAEnE,YAAY,SAAS,GAAwB,IAAI,GAAG,EAAE;QACpD,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAED,4DAA4D;IAC5D,UAAU;QACR,IAAI,IAAI,CAAC,KAAK,EAAE,IAAI,KAAK,MAAM;YAAE,OAAO;QACxC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC1E,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;IACzB,CAAC;IAED,KAAK,CAAC,KAAY;QAChB,IAAI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IACD,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAC/B,MAAM,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,OAAO,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC;IACrF,MAAM,MAAM,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAClF,MAAM,OAAO,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IACvC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,CAAC;IAC3E,OAAO;QACL,OAAO,EAAE;YACP,MAAM;YACN,QAAQ;YACR,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;YAC9C,aAAa,EAAE,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;SAC3F;QACD,MAAM;KACP,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,SAAS,CAAC,IAA6B;IACrD,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Rebuilds the SDK's `Context` from a session's entries, so the log is the only state: any process can read the log\n * and go on with `continueRun()`. A message is the `message_block` entries that share a `messageId`, in `index` order;\n * an assistant message is closed by its `message_end` and takes its usage and cost from the `usage` entry right after\n * it. A `usage` entry anywhere else belongs to a call whose message was superseded, and builds no message. A code\n * call is the host's, not the model's, so its entries build no message either.\n */\n\nimport type { AssistantMessage, ContentBlock, Message } from \"@buildanagent/gateway\";\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Context, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\n\ntype Block = Extract<SessionEntry, { type: \"message_block\" }>;\ntype Pending = { role: \"user\" | \"assistant\"; id: string; blocks: Block[]; firstId: string };\n\nconst ordered = (blocks: readonly Block[]): ContentBlock[] =>\n [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);\n\n/** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */\nclass MessageBuilder {\n readonly messages: Message[] = [];\n /** The id of the first entry of each message, in step with `messages`. */\n readonly starts: string[] = [];\n #open: Pending | undefined;\n readonly #dropEmpty: ReadonlySet<string>;\n #ended: Extract<SessionEntry, { type: \"message_end\" }> | undefined;\n\n constructor(dropEmpty: ReadonlySet<string> = new Set()) {\n this.#dropEmpty = dropEmpty;\n }\n\n /** Closes the user message being built, if there is one. */\n #closeUser(): void {\n if (this.#open?.role !== \"user\") return;\n this.messages.push({ role: \"user\", content: ordered(this.#open.blocks) });\n this.starts.push(this.#open.firstId);\n this.#open = undefined;\n }\n\n block(entry: Block): void {\n this.#settleEnded(undefined);\n if (this.#open === undefined || this.#open.id !== entry.messageId || this.#open.role !== entry.role) {\n this.#closeUser();\n this.#open = { role: entry.role, id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#open.blocks.push(entry);\n }\n\n /** An assistant message with no usage entry after it still counts, with unknown cost. */\n #settleEnded(usage: Extract<SessionEntry, { type: \"usage\" }> | undefined): void {\n const end = this.#ended;\n const open = this.#open;\n if (end === undefined || open === undefined) return;\n this.#ended = undefined;\n this.#open = undefined;\n // A message whose signed reasoning was left out and that has nothing else would be an empty assistant turn.\n if (open.blocks.length === 0 && this.#dropEmpty.has(open.id)) return;\n const message: AssistantMessage = {\n role: \"assistant\",\n content: ordered(open.blocks),\n model: end.model,\n stopReason: end.stopReason,\n ...(end.error === undefined ? {} : { error: end.error }),\n usage: usage?.usage ?? EMPTY_USAGE,\n ...(usage?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: usage.lastAttemptUsage }),\n cost: usage?.cost ?? EMPTY_COST,\n };\n this.messages.push(message);\n this.starts.push(open.firstId);\n }\n\n end(entry: Extract<SessionEntry, { type: \"message_end\" }>): void {\n this.#settleEnded(undefined);\n if (this.#open?.role !== \"assistant\" || this.#open.id !== entry.messageId) {\n // A message with no blocks has no open message to close.\n this.#closeUser();\n this.#open = { role: \"assistant\", id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#ended = entry;\n }\n\n usage(entry: Extract<SessionEntry, { type: \"usage\" }>): void {\n if (entry.source === \"model_call\" && this.#ended !== undefined) this.#settleEnded(entry);\n }\n\n toolResult(entry: Extract<SessionEntry, { type: \"tool_result\" }>): void {\n this.#settleEnded(undefined);\n this.#closeUser();\n this.messages.push({ role: \"tool\", callId: entry.callId, content: entry.content, isError: entry.isError });\n this.starts.push(entry.id);\n }\n\n finish(): Message[] {\n this.#settleEnded(undefined);\n this.#closeUser();\n return this.messages;\n }\n}\n\n// A message with no usage entry, which a crash between the two writes leaves, has no usage anyone knows.\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n uncachedInput: 0,\n cacheRead: 0,\n cacheWrite: { \"5m\": 0, \"1h\": 0 },\n output: 0,\n reasoning: 0,\n raw: null,\n};\nconst EMPTY_COST: AssistantMessage[\"cost\"] = { total: null, basis: \"unknown\", currency: \"USD\" };\n\n/** A request that waits for a person, with the input its call would run with once approved. */\nexport interface PendingApproval {\n readonly request: SignedPendingRequest;\n readonly input: unknown;\n}\n\n/**\n * The requests on `path` that still wait: the latest request for each call of the last assistant message, while the call\n * has no result. A resolution does not end a wait, because the run that applies it may refuse it or never finish: only\n * the call's result does. A resume that started and died before the result is a crash, which `crashedResumes()` names,\n * and its requests do not wait.\n */\nexport function pendingApprovals(path: readonly SessionEntry[]): PendingApproval[] {\n const answered = new Set<string>();\n const latest = new Map<string, PendingApproval>();\n let lastMessage: string | undefined;\n let lastCalls = new Set<string>();\n for (const entry of path) {\n if (entry.type === \"tool_result\") answered.add(entry.callId);\n if (entry.type === \"approval_requested\")\n latest.set(entry.request.callId, { request: entry.request, input: entry.input });\n if (entry.type === \"message_block\" && entry.role === \"assistant\") {\n if (entry.messageId !== lastMessage) lastCalls = new Set();\n lastMessage = entry.messageId;\n if (entry.block.type === \"tool_call\") lastCalls.add(entry.block.callId);\n }\n }\n const crashed = crashedResumes(path);\n return [...latest.values()].filter(\n (entry) =>\n lastCalls.has(entry.request.callId) && !answered.has(entry.request.callId) && !crashed.has(entry.request.id),\n );\n}\n\n/**\n * The ids of the requests whose resume started and died: the log ends in a `continue` turn that has no end, after\n * allows were written for it. An approved call may have run, so it is settled as a crash and not asked again, even\n * when the run died before it reached that call.\n */\nexport function crashedResumes(path: readonly SessionEntry[]): Set<string> {\n const start = path.findLastIndex((entry) => entry.type === \"turn_start\");\n const turn = path[start];\n if (turn?.type !== \"turn_start\" || turn.mode !== \"continue\") return new Set();\n if (path.slice(start).some((entry) => entry.type === \"turn_end\")) return new Set();\n // Only the allows this run was given: a deny or an answer runs nothing, and an earlier run's answers are its own.\n const since = path.slice(0, start).findLastIndex((entry) => entry.type === \"turn_end\");\n return new Set(\n path.slice(since + 1, start).flatMap((entry) => {\n const answer = entry.type === \"approval_resolved\" && entry.quorum === undefined ? entry.resolution : undefined;\n return answer !== undefined && \"decision\" in answer && answer.decision === \"allow\" ? [answer.requestId] : [];\n }),\n );\n}\n\nconst isSignedReasoning = (entry: SessionEntry): boolean =>\n entry.type === \"message_block\" && entry.block.type === \"reasoning\" && entry.block.signature !== undefined;\n\n/** The user message that stands for the summarised span, so the model reads the summary where the span was. */\nexport function summaryMessage(summary: string): Message {\n return {\n role: \"user\",\n content: [\n { type: \"text\", text: `The earlier part of this conversation was summarized to save space:\\n\\n${summary}` },\n ],\n };\n}\n\n/**\n * The entries a context is built from, and whether a compaction applies. The latest `compaction` on the path replaces\n * everything before its `firstKeptEntryId`. The kept tail loses its signed reasoning, because a block that follows the\n * edited span would carry a signature the summary made stale; blocks written after the compaction are untouched.\n */\nexport function entriesAfterCompaction(path: readonly SessionEntry[]): {\n readonly entries: readonly SessionEntry[];\n readonly summary: string | undefined;\n /** The ids of messages that lost a signed reasoning block. */\n readonly stripped: ReadonlySet<string>;\n} {\n const at = path.findLastIndex((entry) => entry.type === \"compaction\");\n const compaction = path[at];\n if (compaction?.type !== \"compaction\") return { entries: path, summary: undefined, stripped: new Set() };\n const kept = path.findIndex((entry) => entry.id === compaction.firstKeptEntryId);\n if (kept < 0) {\n throw new HarnessError(\n \"entry_not_found\",\n `the compaction ${compaction.id} keeps from entry ${compaction.firstKeptEntryId}, which is not on this path`,\n );\n }\n // The messages that lose a block here are the only ones an empty result may drop.\n const stripped = new Set<string>();\n const entries = path.slice(kept).filter((entry, i) => {\n const drop = kept + i < at && isSignedReasoning(entry);\n if (drop && entry.type === \"message_block\") stripped.add(entry.messageId);\n return !drop;\n });\n return { entries: entries.filter((entry) => entry.type !== \"compaction\"), summary: compaction.summary, stripped };\n}\n\n/**\n * The context a path of entries stands for, with the id of the entry each message starts at (`null` for a summary).\n * `path` is a session's `path()`: the root to a HEAD, without `checkout` entries. The system prompt is the latest\n * `turn_start`'s, byte for byte, so a harness whose prompt changed later still rebuilds the conversation the model\n * saw. The latest compaction applies: its summary stands first, then the kept tail and what followed it.\n */\nexport function contextWithStarts(path: readonly SessionEntry[]): {\n readonly context: Context;\n readonly starts: readonly (string | null)[];\n} {\n const { entries, summary, stripped } = entriesAfterCompaction(path);\n const builder = new MessageBuilder(stripped);\n let system = \"\";\n for (const entry of path) if (entry.type === \"turn_start\") system = entry.system;\n // A code call's result answers no call the model made, so the model never reads it.\n const codeCalls = new Set(path.flatMap((entry) => (entry.type === \"code_call\" ? [entry.callId] : [])));\n for (const entry of entries) {\n if (entry.type === \"tool_result\" && codeCalls.has(entry.callId)) continue;\n switch (entry.type) {\n case \"message_block\":\n builder.block(entry);\n break;\n case \"message_end\":\n builder.end(entry);\n break;\n case \"usage\":\n builder.usage(entry);\n break;\n case \"tool_result\":\n builder.toolResult(entry);\n break;\n default:\n }\n }\n const built = builder.finish();\n const messages = summary === undefined ? built : [summaryMessage(summary), ...built];\n const starts = summary === undefined ? builder.starts : [null, ...builder.starts];\n const waiting = pendingApprovals(path);\n if (waiting.length === 0) return { context: { system, messages }, starts };\n return {\n context: {\n system,\n messages,\n pending: waiting.map((entry) => entry.request),\n pendingInputs: Object.fromEntries(waiting.map((entry) => [entry.request.id, entry.input])),\n },\n starts,\n };\n}\n\n/** The context a path of entries stands for. See `contextWithStarts()`. */\nexport function contextOf(path: readonly SessionEntry[]): Context {\n return contextWithStarts(path).context;\n}\n"]}
1
+ {"version":3,"file":"rebuild.js","sourceRoot":"","sources":["../../src/session/rebuild.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAKtD,MAAM,OAAO,GAAG,CAAC,MAAwB,EAAkB,EAAE,CAC3D,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAE5E,+GAA+G;AAC/G,MAAM,cAAc;IACT,QAAQ,GAAc,EAAE,CAAC;IAClC,0EAA0E;IACjE,MAAM,GAAa,EAAE,CAAC;IAC/B,KAAK,CAAsB;IAClB,UAAU,CAAsB;IACzC,MAAM,CAA6D;IAEnE,YAAY,SAAS,GAAwB,IAAI,GAAG,EAAE;QACpD,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAA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CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;YAC9C,aAAa,EAAE,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;SAC3F;QACD,MAAM;KACP,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,SAAS,CAAC,IAA6B;IACrD,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Rebuilds the SDK's `Context` from a session's entries, so the log is the only state: any process can read the log\n * and go on with `continueRun()`. A message is the `message_block` entries that share a `messageId`, in `index` order;\n * an assistant message is closed by its `message_end` and takes its usage and cost from the `usage` entry right after\n * it. A `usage` entry anywhere else belongs to a call whose message was superseded, and builds no message. A code\n * call is the host's, not the model's, so its entries build no message either.\n */\n\nimport type { AssistantMessage, ContentBlock, Message } from \"@buildanagent/gateway\";\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Context, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport { ESCALATION_TOOL } from \"./escalation-log.js\";\n\ntype Block = Extract<SessionEntry, { type: \"message_block\" }>;\ntype Pending = { role: \"user\" | \"assistant\"; id: string; blocks: Block[]; firstId: string };\n\nconst ordered = (blocks: readonly Block[]): ContentBlock[] =>\n [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);\n\n/** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */\nclass MessageBuilder {\n readonly messages: Message[] = [];\n /** The id of the first entry of each message, in step with `messages`. */\n readonly starts: string[] = [];\n #open: Pending | undefined;\n readonly #dropEmpty: ReadonlySet<string>;\n #ended: Extract<SessionEntry, { type: \"message_end\" }> | undefined;\n\n constructor(dropEmpty: ReadonlySet<string> = new Set()) {\n this.#dropEmpty = dropEmpty;\n }\n\n /** Closes the user message being built, if there is one. */\n #closeUser(): void {\n if (this.#open?.role !== \"user\") return;\n this.messages.push({ role: \"user\", content: ordered(this.#open.blocks) });\n this.starts.push(this.#open.firstId);\n this.#open = undefined;\n }\n\n block(entry: Block): void {\n this.#settleEnded(undefined);\n if (this.#open === undefined || this.#open.id !== entry.messageId || this.#open.role !== entry.role) {\n this.#closeUser();\n this.#open = { role: entry.role, id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#open.blocks.push(entry);\n }\n\n /** An assistant message with no usage entry after it still counts, with unknown cost. */\n #settleEnded(usage: Extract<SessionEntry, { type: \"usage\" }> | undefined): void {\n const end = this.#ended;\n const open = this.#open;\n if (end === undefined || open === undefined) return;\n this.#ended = undefined;\n this.#open = undefined;\n // A message whose signed reasoning was left out and that has nothing else would be an empty assistant turn.\n if (open.blocks.length === 0 && this.#dropEmpty.has(open.id)) return;\n const message: AssistantMessage = {\n role: \"assistant\",\n content: ordered(open.blocks),\n model: end.model,\n stopReason: end.stopReason,\n ...(end.error === undefined ? {} : { error: end.error }),\n usage: usage?.usage ?? EMPTY_USAGE,\n ...(usage?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: usage.lastAttemptUsage }),\n cost: usage?.cost ?? EMPTY_COST,\n };\n this.messages.push(message);\n this.starts.push(open.firstId);\n }\n\n end(entry: Extract<SessionEntry, { type: \"message_end\" }>): void {\n this.#settleEnded(undefined);\n if (this.#open?.role !== \"assistant\" || this.#open.id !== entry.messageId) {\n // A message with no blocks has no open message to close.\n this.#closeUser();\n this.#open = { role: \"assistant\", id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#ended = entry;\n }\n\n usage(entry: Extract<SessionEntry, { type: \"usage\" }>): void {\n if (entry.source === \"model_call\" && this.#ended !== undefined) this.#settleEnded(entry);\n }\n\n toolResult(entry: Extract<SessionEntry, { type: \"tool_result\" }>): void {\n this.#settleEnded(undefined);\n this.#closeUser();\n this.messages.push({ role: \"tool\", callId: entry.callId, content: entry.content, isError: entry.isError });\n this.starts.push(entry.id);\n }\n\n finish(): Message[] {\n this.#settleEnded(undefined);\n this.#closeUser();\n return this.messages;\n }\n}\n\n// A message with no usage entry, which a crash between the two writes leaves, has no usage anyone knows.\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n uncachedInput: 0,\n cacheRead: 0,\n cacheWrite: { \"5m\": 0, \"1h\": 0 },\n output: 0,\n reasoning: 0,\n raw: null,\n};\nconst EMPTY_COST: AssistantMessage[\"cost\"] = { total: null, basis: \"unknown\", currency: \"USD\" };\n\n/** A request that waits for a person, with the input its call would run with once approved. */\nexport interface PendingApproval {\n readonly request: SignedPendingRequest;\n readonly input: unknown;\n}\n\n/**\n * The requests on `path` that still wait: the latest request for each call of the last assistant message, while the call\n * has no result. A resolution does not end a wait, because the run that applies it may refuse it or never finish: only\n * the call's result does. A resume that started and died before the result is a crash, which `crashedResumes()` names,\n * and its requests do not wait.\n */\nexport function pendingApprovals(path: readonly SessionEntry[]): PendingApproval[] {\n const answered = new Set<string>();\n const latest = new Map<string, PendingApproval>();\n let lastMessage: string | undefined;\n let lastCalls = new Set<string>();\n for (const entry of path) {\n if (entry.type === \"tool_result\") answered.add(entry.callId);\n if (entry.type === \"approval_requested\")\n latest.set(entry.request.callId, { request: entry.request, input: entry.input });\n if (entry.type === \"message_block\" && entry.role === \"assistant\") {\n if (entry.messageId !== lastMessage) lastCalls = new Set();\n lastMessage = entry.messageId;\n if (entry.block.type === \"tool_call\") lastCalls.add(entry.block.callId);\n }\n }\n const crashed = crashedResumes(path);\n return [...latest.values()].filter(\n (entry) =>\n lastCalls.has(entry.request.callId) && !answered.has(entry.request.callId) && !crashed.has(entry.request.id),\n );\n}\n\n/**\n * The ids of the requests whose resume started and died: the log ends in a `continue` turn that has no end, after\n * allows were written for it. An approved call may have run, so it is settled as a crash and not asked again, even\n * when the run died before it reached that call.\n */\nexport function crashedResumes(path: readonly SessionEntry[]): Set<string> {\n const start = path.findLastIndex((entry) => entry.type === \"turn_start\");\n const turn = path[start];\n if (turn?.type !== \"turn_start\" || turn.mode !== \"continue\") return new Set();\n if (path.slice(start).some((entry) => entry.type === \"turn_end\")) return new Set();\n // Only the allows this run was given: a deny or an answer runs nothing, and an earlier run's answers are its own.\n const since = path.slice(0, start).findLastIndex((entry) => entry.type === \"turn_end\");\n return new Set(\n path.slice(since + 1, start).flatMap((entry) => {\n const answer = entry.type === \"approval_resolved\" && entry.quorum === undefined ? entry.resolution : undefined;\n return answer !== undefined && \"decision\" in answer && answer.decision === \"allow\" ? [answer.requestId] : [];\n }),\n );\n}\n\nconst isSignedReasoning = (entry: SessionEntry): boolean =>\n entry.type === \"message_block\" && entry.block.type === \"reasoning\" && entry.block.signature !== undefined;\n\n/** The user message that stands for the summarised span, so the model reads the summary where the span was. */\nexport function summaryMessage(summary: string): Message {\n return {\n role: \"user\",\n content: [\n { type: \"text\", text: `The earlier part of this conversation was summarized to save space:\\n\\n${summary}` },\n ],\n };\n}\n\n/**\n * The entries a context is built from, and whether a compaction applies. The latest `compaction` on the path replaces\n * everything before its `firstKeptEntryId`. The kept tail loses its signed reasoning, because a block that follows the\n * edited span would carry a signature the summary made stale; blocks written after the compaction are untouched.\n */\nexport function entriesAfterCompaction(path: readonly SessionEntry[]): {\n readonly entries: readonly SessionEntry[];\n readonly summary: string | undefined;\n /** The ids of messages that lost a signed reasoning block. */\n readonly stripped: ReadonlySet<string>;\n} {\n const at = path.findLastIndex((entry) => entry.type === \"compaction\");\n const compaction = path[at];\n if (compaction?.type !== \"compaction\") return { entries: path, summary: undefined, stripped: new Set() };\n const kept = path.findIndex((entry) => entry.id === compaction.firstKeptEntryId);\n if (kept < 0) {\n throw new HarnessError(\n \"entry_not_found\",\n `the compaction ${compaction.id} keeps from entry ${compaction.firstKeptEntryId}, which is not on this path`,\n );\n }\n // The messages that lose a block here are the only ones an empty result may drop.\n const stripped = new Set<string>();\n const entries = path.slice(kept).filter((entry, i) => {\n const drop = kept + i < at && isSignedReasoning(entry);\n if (drop && entry.type === \"message_block\") stripped.add(entry.messageId);\n return !drop;\n });\n return { entries: entries.filter((entry) => entry.type !== \"compaction\"), summary: compaction.summary, stripped };\n}\n\n/**\n * The context a path of entries stands for, with the id of the entry each message starts at (`null` for a summary).\n * `path` is a session's `path()`: the root to a HEAD, without `checkout` entries. The system prompt is the latest\n * `turn_start`'s, byte for byte, so a harness whose prompt changed later still rebuilds the conversation the model\n * saw. The latest compaction applies: its summary stands first, then the kept tail and what followed it.\n */\nexport function contextWithStarts(path: readonly SessionEntry[]): {\n readonly context: Context;\n readonly starts: readonly (string | null)[];\n} {\n const { entries, summary, stripped } = entriesAfterCompaction(path);\n const builder = new MessageBuilder(stripped);\n let system = \"\";\n for (const entry of path) if (entry.type === \"turn_start\") system = entry.system;\n // A code call's or a sandbox escalation's result answers no call the model made, so the model never reads it. Both\n // are known by their call ids, never by the result's tool name: the model can call a tool named `sandbox.escalation`,\n // and its error result must stay, or the rebuilt context would hold a tool call with no result.\n const hostCalls = new Set(\n path.flatMap((entry) => {\n if (entry.type === \"code_call\") return [entry.callId];\n if (entry.type === \"approval_requested\" && entry.request.tool === ESCALATION_TOOL) return [entry.request.callId];\n return [];\n }),\n );\n for (const entry of entries) {\n if (entry.type === \"tool_result\" && hostCalls.has(entry.callId)) continue;\n switch (entry.type) {\n case \"message_block\":\n builder.block(entry);\n break;\n case \"message_end\":\n builder.end(entry);\n break;\n case \"usage\":\n builder.usage(entry);\n break;\n case \"tool_result\":\n builder.toolResult(entry);\n break;\n default:\n }\n }\n const built = builder.finish();\n const messages = summary === undefined ? built : [summaryMessage(summary), ...built];\n const starts = summary === undefined ? builder.starts : [null, ...builder.starts];\n const waiting = pendingApprovals(path);\n if (waiting.length === 0) return { context: { system, messages }, starts };\n return {\n context: {\n system,\n messages,\n pending: waiting.map((entry) => entry.request),\n pendingInputs: Object.fromEntries(waiting.map((entry) => [entry.request.id, entry.input])),\n },\n starts,\n };\n}\n\n/** The context a path of entries stands for. See `contextWithStarts()`. */\nexport function contextOf(path: readonly SessionEntry[]): Context {\n return contextWithStarts(path).context;\n}\n"]}
package/llms.txt CHANGED
@@ -9,6 +9,7 @@ The sections of README.md and every public export, generated from this package's
9
9
  - [Install the alpha with `pnpm add @buildanagent/harness@alpha`](README.md#install-the-alpha-with-pnpm-add-buildanagentharnessalpha)
10
10
  - [The session log holds twenty-one entry types](README.md#the-session-log-holds-twenty-one-entry-types)
11
11
  - [A sandbox says what it stops, and the host decides what it may touch](README.md#a-sandbox-says-what-it-stops-and-the-host-decides-what-it-may-touch)
12
+ - [A denied command becomes a signed request, and an approved one reruns once](README.md#a-denied-command-becomes-a-signed-request-and-an-approved-one-reruns-once)
12
13
  - [The srt backend confines each command with Anthropic's OS sandbox](README.md#the-srt-backend-confines-each-command-with-anthropics-os-sandbox)
13
14
  - [The Docker backend runs each command in a locked-down container](README.md#the-docker-backend-runs-each-command-in-a-locked-down-container)
14
15
  - [A backend that claims a stop reads its policy back, and one that can't resume says so](README.md#a-backend-that-claims-a-stop-reads-its-policy-back-and-one-that-cant-resume-says-so)
@@ -275,13 +276,30 @@ The sections of README.md and every public export, generated from this package's
275
276
 
276
277
  - `type ApprovalPolicy`: When a denied action may be asked for again, which is the host's decision and never the sandbox's.
277
278
  - `confirmPolicy()`: Reads back the policy `sandbox` applied and compares it with `requested`.
279
+ - `escalation()`: Creates the escalation machine for a harness's approvals.
280
+ - `ESCALATION_EVENTS`: Every event.
281
+ - `ESCALATION_STATES`: Every state, in the order a command that escalates passes through them.
282
+ - `ESCALATION_TOOL`: The tool name an escalation's signed request carries.
283
+ - `ESCALATION_TRANSITIONS`: The legal edges.
284
+ - `type EscalationEvent`: What moves a command between states.
285
+ - `interface EscalationMachine`: The machine `escalation()` returns.
286
+ - `interface EscalationOptions`: The options of `escalation()`.
287
+ - `interface EscalationRecord`: What an escalation's request signs, as the input of its `approval_requested` entry: the call the command ran for, the command, the workspace root, the policy it ran under and the denial.
288
+ - `interface EscalationResolveOptions`: The options of `EscalationMachine.resolve()`: where the rerun runs, which the log does not hold.
289
+ - `type EscalationResult`: How an escalation call ended.
290
+ - `interface EscalationRule`: One rule of a `granular` policy: a denial of `kind` for `tool` may be asked about (`on-request`) or goes back to the caller (`never`).
291
+ - `interface EscalationRun`: One command to run in a sandbox, for one tool call, and what the host provisions the sandbox with.
292
+ - `type EscalationState`: Where a sandboxed command stands.
293
+ - `interface EscalationTransition`: One legal edge: from a state, on an event, to a state, and when the machine takes it.
278
294
  - `interface ExecOptions`: The options of `Sandbox.exec()`.
279
295
  - `type ExecResult`: What a command did: its exit status and output, or the denial that stopped it.
280
296
  - `hasCapability()`: Whether `client` lists `capability`.
297
+ - `nextEscalationState()`: The state `event` moves `from` to.
281
298
  - `NONE_SANDBOX_WARNING`: The warning written when a sandbox starts.
282
299
  - `noneSandbox()`: Builds the `none` backend.
283
300
  - `interface NoneSandboxOptions`: The options of `noneSandbox()`.
284
301
  - `pauseSandbox()`: Pauses `sandbox` until `resumeSandbox()` with its `id`, or throws `SandboxUnsupportedError`.
302
+ - `interface PendingEscalation`: An escalation that waits for an answer: its id, its signed request and the record the request signs.
285
303
  - `policyDifference()`: The first field in which `applied` differs from `requested`, or `undefined` when they hold the same entries.
286
304
  - `resumeSandbox()`: Reattaches to a sandbox by its id, or starts one from a snapshot's id, then confirms its policy as `provision()` does and sets the sandbox's `stops` to what the confirmed policy delivers.
287
305
  - `interface Sandbox`: A provisioned sandbox.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buildanagent/harness",
3
- "version": "0.1.0-alpha.29",
3
+ "version": "0.1.0-alpha.30",
4
4
  "description": "The buildanagent harness: the session log, context policy, tools, permissions, sandbox and credentials around the SDK's loop.",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "repository": {
@@ -103,10 +103,10 @@
103
103
  "@anthropic-ai/sandbox-runtime": "0.0.83",
104
104
  "@earendil-works/pi-schema": "1.5.2",
105
105
  "@modelcontextprotocol/client": "2.4.0",
106
- "@buildanagent/agent-safety": "0.1.0-alpha.29",
107
- "@buildanagent/gateway": "0.1.0-alpha.29",
108
- "@buildanagent/protocol": "0.1.0-alpha.29",
109
- "@buildanagent/sdk": "0.1.0-alpha.29"
106
+ "@buildanagent/agent-safety": "0.1.0-alpha.30",
107
+ "@buildanagent/protocol": "0.1.0-alpha.30",
108
+ "@buildanagent/sdk": "0.1.0-alpha.30",
109
+ "@buildanagent/gateway": "0.1.0-alpha.30"
110
110
  },
111
111
  "devDependencies": {
112
112
  "@modelcontextprotocol/server": "2.4.0",