@buildanagent/sdk 0.1.0-alpha.0 → 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +425 -6
  2. package/dist/budget.d.ts +33 -0
  3. package/dist/budget.js +55 -0
  4. package/dist/budget.js.map +1 -0
  5. package/dist/compose.d.ts +26 -0
  6. package/dist/compose.js +157 -0
  7. package/dist/compose.js.map +1 -0
  8. package/dist/errors.d.ts +49 -0
  9. package/dist/errors.js +57 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/events.d.ts +168 -0
  12. package/dist/events.js +32 -0
  13. package/dist/events.js.map +1 -0
  14. package/dist/freeze.d.ts +11 -0
  15. package/dist/freeze.js +42 -0
  16. package/dist/freeze.js.map +1 -0
  17. package/dist/hook-checks.d.ts +31 -0
  18. package/dist/hook-checks.js +130 -0
  19. package/dist/hook-checks.js.map +1 -0
  20. package/dist/hook-runner.d.ts +96 -0
  21. package/dist/hook-runner.js +372 -0
  22. package/dist/hook-runner.js.map +1 -0
  23. package/dist/hooks.d.ts +183 -0
  24. package/dist/hooks.js +2 -0
  25. package/dist/hooks.js.map +1 -0
  26. package/dist/index.d.ts +26 -3
  27. package/dist/index.js +21 -3
  28. package/dist/index.js.map +1 -1
  29. package/dist/loop.d.ts +67 -0
  30. package/dist/loop.js +644 -0
  31. package/dist/loop.js.map +1 -0
  32. package/dist/observers.d.ts +31 -0
  33. package/dist/observers.js +98 -0
  34. package/dist/observers.js.map +1 -0
  35. package/dist/otel/attributes.d.ts +43 -0
  36. package/dist/otel/attributes.js +50 -0
  37. package/dist/otel/attributes.js.map +1 -0
  38. package/dist/otel/content.d.ts +17 -0
  39. package/dist/otel/content.js +48 -0
  40. package/dist/otel/content.js.map +1 -0
  41. package/dist/otel/index.d.ts +6 -2
  42. package/dist/otel/index.js +6 -2
  43. package/dist/otel/index.js.map +1 -1
  44. package/dist/otel/observer.d.ts +82 -0
  45. package/dist/otel/observer.js +300 -0
  46. package/dist/otel/observer.js.map +1 -0
  47. package/dist/pauses.d.ts +61 -0
  48. package/dist/pauses.js +83 -0
  49. package/dist/pauses.js.map +1 -0
  50. package/dist/progress.d.ts +34 -0
  51. package/dist/progress.js +139 -0
  52. package/dist/progress.js.map +1 -0
  53. package/dist/result.d.ts +134 -0
  54. package/dist/result.js +2 -0
  55. package/dist/result.js.map +1 -0
  56. package/dist/resume.d.ts +76 -0
  57. package/dist/resume.js +237 -0
  58. package/dist/resume.js.map +1 -0
  59. package/dist/run.d.ts +214 -0
  60. package/dist/run.js +327 -0
  61. package/dist/run.js.map +1 -0
  62. package/dist/steering.d.ts +52 -0
  63. package/dist/steering.js +104 -0
  64. package/dist/steering.js.map +1 -0
  65. package/dist/testing/scripted-model.d.ts +17 -2
  66. package/dist/testing/scripted-model.js +22 -4
  67. package/dist/testing/scripted-model.js.map +1 -1
  68. package/dist/tools/coerce.d.ts +15 -0
  69. package/dist/tools/coerce.js +93 -0
  70. package/dist/tools/coerce.js.map +1 -0
  71. package/dist/tools/define.d.ts +54 -0
  72. package/dist/tools/define.js +121 -0
  73. package/dist/tools/define.js.map +1 -0
  74. package/dist/tools/format-error.d.ts +13 -0
  75. package/dist/tools/format-error.js +66 -0
  76. package/dist/tools/format-error.js.map +1 -0
  77. package/dist/tools/outcome.d.ts +7 -0
  78. package/dist/tools/outcome.js +30 -0
  79. package/dist/tools/outcome.js.map +1 -0
  80. package/dist/tools/pipeline.d.ts +111 -0
  81. package/dist/tools/pipeline.js +382 -0
  82. package/dist/tools/pipeline.js.map +1 -0
  83. package/dist/tools/scheduler.d.ts +33 -0
  84. package/dist/tools/scheduler.js +51 -0
  85. package/dist/tools/scheduler.js.map +1 -0
  86. package/dist/tools/schema.d.ts +20 -0
  87. package/dist/tools/schema.js +100 -0
  88. package/dist/tools/schema.js.map +1 -0
  89. package/dist/tools/types.d.ts +196 -0
  90. package/dist/tools/types.js +2 -0
  91. package/dist/tools/types.js.map +1 -0
  92. package/dist/vendor/agent-safety/bytes.d.ts +17 -0
  93. package/dist/vendor/agent-safety/bytes.js +59 -0
  94. package/dist/vendor/agent-safety/bytes.js.map +1 -0
  95. package/dist/vendor/agent-safety/errors.d.ts +22 -0
  96. package/dist/vendor/agent-safety/errors.js +22 -0
  97. package/dist/vendor/agent-safety/errors.js.map +1 -0
  98. package/dist/vendor/agent-safety/hash.d.ts +16 -0
  99. package/dist/vendor/agent-safety/hash.js +110 -0
  100. package/dist/vendor/agent-safety/hash.js.map +1 -0
  101. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  102. package/dist/vendor/agent-safety/outcome.js +140 -0
  103. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  104. package/dist/vendor/agent-safety/pending.d.ts +119 -0
  105. package/dist/vendor/agent-safety/pending.js +122 -0
  106. package/dist/vendor/agent-safety/pending.js.map +1 -0
  107. package/dist/vendor/agent-safety/render.d.ts +40 -0
  108. package/dist/vendor/agent-safety/render.js +92 -0
  109. package/dist/vendor/agent-safety/render.js.map +1 -0
  110. package/dist/vendor/agent-safety/signer.d.ts +42 -0
  111. package/dist/vendor/agent-safety/signer.js +128 -0
  112. package/dist/vendor/agent-safety/signer.js.map +1 -0
  113. package/dist/version.d.ts +2 -0
  114. package/dist/version.js +8 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +13 -3
@@ -0,0 +1,139 @@
1
+ import { SdkError } from "./errors.js";
2
+ import { canonicalInputHash } from "./vendor/agent-safety/hash.js";
3
+ /** The defaults, provisional until recorded runs retune them. The object is frozen, so no caller can change them. */
4
+ export const DEFAULT_PROGRESS = Object.freeze({
5
+ maxIdenticalFailures: 3,
6
+ maxSameKeyCalls: 5,
7
+ });
8
+ /** Checks a `progress` option and fills in its defaults. */
9
+ export function resolveProgress(progress) {
10
+ if (progress === false)
11
+ return undefined;
12
+ const policy = { ...DEFAULT_PROGRESS, ...definedFields(progress ?? {}) };
13
+ for (const [name, value] of Object.entries(policy)) {
14
+ if (!Number.isInteger(value) || value < 1) {
15
+ throw new SdkError("invalid_run_options", `progress.${name} must be a positive integer, got ${String(value)}`);
16
+ }
17
+ }
18
+ return policy;
19
+ }
20
+ function definedFields(policy) {
21
+ return Object.fromEntries(Object.entries(policy).filter(([, value]) => value !== undefined));
22
+ }
23
+ function keyOf(tool, input) {
24
+ if (tool?.progressKey === undefined)
25
+ return undefined;
26
+ try {
27
+ const key = tool.progressKey(input);
28
+ return typeof key === "string" ? key : undefined;
29
+ }
30
+ catch {
31
+ // A key function that can't read the model's input leaves the call unkeyed, so only the identical-failure rule
32
+ // sees it.
33
+ return undefined;
34
+ }
35
+ }
36
+ /** The hash of a call's input, or a value no other call shares when the input has no canonical form. */
37
+ async function hashOf(position, input) {
38
+ try {
39
+ return await canonicalInputHash(input);
40
+ }
41
+ catch {
42
+ return `unhashable:${position}`;
43
+ }
44
+ }
45
+ /** The calls of one assistant message, each named by its place in the transcript. */
46
+ function callsOf(message, turn) {
47
+ const calls = [];
48
+ message.content.forEach((block, at) => {
49
+ if (block.type === "tool_call")
50
+ calls.push({ call: block, position: `${turn}:${at}`, turn });
51
+ });
52
+ return calls;
53
+ }
54
+ /** The unanswered call with `callId` in the newest turn, the first such call within it. */
55
+ function callFor(calls, callId) {
56
+ let best;
57
+ for (const pending of calls) {
58
+ if (pending.failed !== undefined || pending.call.callId !== callId)
59
+ continue;
60
+ if (best === undefined || pending.turn > best.turn)
61
+ best = pending;
62
+ }
63
+ return best;
64
+ }
65
+ /**
66
+ * The tool calls in `messages` that have a result, in the order the model made them. Call ids need not be unique:
67
+ * a provider may repeat one or send none, so a result goes to the unanswered call with its id in the newest turn,
68
+ * the first such call within it, the order the gateway pairs them in.
69
+ */
70
+ function resolvedCalls(messages) {
71
+ const calls = [];
72
+ messages.forEach((message, index) => {
73
+ if (message.role === "assistant")
74
+ calls.push(...callsOf(message, index));
75
+ if (message.role !== "tool")
76
+ return;
77
+ const pending = callFor(calls, message.callId);
78
+ if (pending !== undefined)
79
+ pending.failed = message.isError === true;
80
+ });
81
+ return calls.filter((pending) => pending.failed !== undefined);
82
+ }
83
+ /** The calls in `messages` that have a result, each with its input hash, key and outcome. */
84
+ async function attemptsOf(messages, tools, facts) {
85
+ const attempts = [];
86
+ for (const { call, position, failed } of resolvedCalls(messages)) {
87
+ let known = facts.get(position);
88
+ if (known === undefined) {
89
+ known = { hash: hashOf(position, call.input), key: keyOf(tools.get(call.name), call.input) };
90
+ facts.set(position, known);
91
+ }
92
+ attempts.push({ tool: call.name, hash: await known.hash, key: known.key, failed: failed === true });
93
+ }
94
+ return attempts;
95
+ }
96
+ /** The reason when the latest calls are `limit` identical failures, or `undefined`. */
97
+ function identicalFailures(attempts, limit) {
98
+ const last = attempts.at(-1);
99
+ if (last === undefined || !last.failed)
100
+ return undefined;
101
+ let streak = 0;
102
+ for (let i = attempts.length - 1; i >= 0; i--) {
103
+ const attempt = attempts[i];
104
+ if (attempt === undefined || !attempt.failed || attempt.tool !== last.tool || attempt.hash !== last.hash)
105
+ break;
106
+ streak += 1;
107
+ }
108
+ if (streak < limit)
109
+ return undefined;
110
+ return `the model made ${streak} identical failing calls to ${last.tool} in a row`;
111
+ }
112
+ /** The reason when some key has `limit` calls and no success since its first, or `undefined`. */
113
+ function repeatedKey(attempts, limit) {
114
+ const counts = new Map();
115
+ for (const { tool, key, failed } of attempts) {
116
+ if (key === undefined)
117
+ continue;
118
+ const id = JSON.stringify([tool, key]);
119
+ const count = failed ? (counts.get(id) ?? 0) + 1 : 0;
120
+ counts.set(id, count);
121
+ if (count >= limit)
122
+ return `the model called ${tool} ${count} times with the key ${JSON.stringify(key)} and none succeeded`;
123
+ }
124
+ return undefined;
125
+ }
126
+ /**
127
+ * The default progress policy as a check over the transcript. `skip` is how many messages came before this run's
128
+ * own, so a run continued from a context that ended in a loop is not stopped by the old calls. The transcript only
129
+ * grows, so each call's hash and key are worked out once and kept by its place in it.
130
+ */
131
+ export function progressCheck(tools, policy, skip) {
132
+ const byName = new Map(tools.map((tool) => [tool.name, tool]));
133
+ const facts = new Map();
134
+ return async (messages) => {
135
+ const attempts = await attemptsOf(messages.slice(skip), byName, facts);
136
+ return identicalFailures(attempts, policy.maxIdenticalFailures) ?? repeatedKey(attempts, policy.maxSameKeyCalls);
137
+ };
138
+ }
139
+ //# sourceMappingURL=progress.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"progress.js","sourceRoot":"","sources":["../src/progress.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAUnE,qHAAqH;AACrH,MAAM,CAAC,MAAM,gBAAgB,GAAuC,MAAM,CAAC,MAAM,CAAC;IAChF,oBAAoB,EAAE,CAAC;IACvB,eAAe,EAAE,CAAC;CACnB,CAAC,CAAC;AAEH,4DAA4D;AAC5D,MAAM,UAAU,eAAe,CAAC,QAA4C;IAC1E,IAAI,QAAQ,KAAK,KAAK;QAAE,OAAO,SAAS,CAAC;IACzC,MAAM,MAAM,GAAG,EAAE,GAAG,gBAAgB,EAAE,GAAG,aAAa,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,CAAC;IACzE,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACnD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,YAAY,IAAI,oCAAoC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACjH,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,aAAa,CAAC,MAAsB;IAC3C,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAA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,CAAC;QACvE,OAAO,iBAAiB,CAAC,QAAQ,EAAE,MAAM,CAAC,oBAAoB,CAAC,IAAI,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC;IACnH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The default progress policy (D11): it ends a run with `no_progress` when the model keeps making the same failing\n * call. Two rules fire it:\n *\n * - **Identical failures.** The latest calls are one tool with one canonical input hash, each returned an error, and\n * there are `maxIdenticalFailures` of them in a row (3 by default).\n * - **One key.** A tool's `progressKey()` gave `maxSameKeyCalls` calls (5 by default) the same key and none of them\n * succeeded. A successful call with that key starts its count again; calls with other keys don't.\n *\n * The policy reads the transcript, so it holds no state a `continueRun()` would have to restore, and it counts only\n * the calls the run itself made. The loop runs it after the caller's `shouldStop`, outside the hook runner, so a\n * caller's hook that throws can't switch it off.\n */\nimport type { AssistantMessage, Message } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\nimport { canonicalInputHash } from \"./vendor/agent-safety/hash.js\";\n\n/** The thresholds of the default progress policy. Pass `progress: false` to `run()` to turn the policy off. */\nexport interface ProgressPolicy {\n /** How many identical failing calls in a row end the run. Default 3. */\n readonly maxIdenticalFailures?: number;\n /** How many calls with one `progressKey` and no success between them end the run. Default 5. */\n readonly maxSameKeyCalls?: number;\n}\n\n/** The defaults, provisional until recorded runs retune them. The object is frozen, so no caller can change them. */\nexport const DEFAULT_PROGRESS: Readonly<Required<ProgressPolicy>> = Object.freeze({\n maxIdenticalFailures: 3,\n maxSameKeyCalls: 5,\n});\n\n/** Checks a `progress` option and fills in its defaults. */\nexport function resolveProgress(progress: ProgressPolicy | false | undefined): Required<ProgressPolicy> | undefined {\n if (progress === false) return undefined;\n const policy = { ...DEFAULT_PROGRESS, ...definedFields(progress ?? {}) };\n for (const [name, value] of Object.entries(policy)) {\n if (!Number.isInteger(value) || value < 1) {\n throw new SdkError(\"invalid_run_options\", `progress.${name} must be a positive integer, got ${String(value)}`);\n }\n }\n return policy;\n}\n\nfunction definedFields(policy: ProgressPolicy): ProgressPolicy {\n return Object.fromEntries(Object.entries(policy).filter(([, value]) => value !== undefined));\n}\n\n/** One tool call of the run, with the result it got. */\ninterface Attempt {\n readonly tool: string;\n readonly hash: string;\n readonly key: string | undefined;\n readonly failed: boolean;\n}\n\n/** What the policy works out once for each call: its input hash and its key. */\ninterface CallFacts {\n readonly hash: Promise<string>;\n readonly key: string | undefined;\n}\n\nfunction keyOf(tool: AnyTool | undefined, input: unknown): string | undefined {\n if (tool?.progressKey === undefined) return undefined;\n try {\n const key: unknown = tool.progressKey(input);\n return typeof key === \"string\" ? key : undefined;\n } catch {\n // A key function that can't read the model's input leaves the call unkeyed, so only the identical-failure rule\n // sees it.\n return undefined;\n }\n}\n\n/** The hash of a call's input, or a value no other call shares when the input has no canonical form. */\nasync function hashOf(position: string, input: unknown): Promise<string> {\n try {\n return await canonicalInputHash(input);\n } catch {\n return `unhashable:${position}`;\n }\n}\n\n/** A call waiting for its result, named by its place in the transcript. */\ninterface Pending {\n readonly call: ToolCall;\n readonly position: string;\n readonly turn: number;\n failed?: boolean;\n}\n\n/** The calls of one assistant message, each named by its place in the transcript. */\nfunction callsOf(message: AssistantMessage, turn: number): Pending[] {\n const calls: Pending[] = [];\n message.content.forEach((block, at) => {\n if (block.type === \"tool_call\") calls.push({ call: block, position: `${turn}:${at}`, turn });\n });\n return calls;\n}\n\n/** The unanswered call with `callId` in the newest turn, the first such call within it. */\nfunction callFor(calls: readonly Pending[], callId: string): Pending | undefined {\n let best: Pending | undefined;\n for (const pending of calls) {\n if (pending.failed !== undefined || pending.call.callId !== callId) continue;\n if (best === undefined || pending.turn > best.turn) best = pending;\n }\n return best;\n}\n\n/**\n * The tool calls in `messages` that have a result, in the order the model made them. Call ids need not be unique:\n * a provider may repeat one or send none, so a result goes to the unanswered call with its id in the newest turn,\n * the first such call within it, the order the gateway pairs them in.\n */\nfunction resolvedCalls(messages: readonly Message[]): Pending[] {\n const calls: Pending[] = [];\n messages.forEach((message, index) => {\n if (message.role === \"assistant\") calls.push(...callsOf(message, index));\n if (message.role !== \"tool\") return;\n const pending = callFor(calls, message.callId);\n if (pending !== undefined) pending.failed = message.isError === true;\n });\n return calls.filter((pending) => pending.failed !== undefined);\n}\n\n/** The calls in `messages` that have a result, each with its input hash, key and outcome. */\nasync function attemptsOf(\n messages: readonly Message[],\n tools: ReadonlyMap<string, AnyTool>,\n facts: Map<string, CallFacts>,\n): Promise<Attempt[]> {\n const attempts: Attempt[] = [];\n for (const { call, position, failed } of resolvedCalls(messages)) {\n let known = facts.get(position);\n if (known === undefined) {\n known = { hash: hashOf(position, call.input), key: keyOf(tools.get(call.name), call.input) };\n facts.set(position, known);\n }\n attempts.push({ tool: call.name, hash: await known.hash, key: known.key, failed: failed === true });\n }\n return attempts;\n}\n\n/** The reason when the latest calls are `limit` identical failures, or `undefined`. */\nfunction identicalFailures(attempts: readonly Attempt[], limit: number): string | undefined {\n const last = attempts.at(-1);\n if (last === undefined || !last.failed) return undefined;\n let streak = 0;\n for (let i = attempts.length - 1; i >= 0; i--) {\n const attempt = attempts[i];\n if (attempt === undefined || !attempt.failed || attempt.tool !== last.tool || attempt.hash !== last.hash) break;\n streak += 1;\n }\n if (streak < limit) return undefined;\n return `the model made ${streak} identical failing calls to ${last.tool} in a row`;\n}\n\n/** The reason when some key has `limit` calls and no success since its first, or `undefined`. */\nfunction repeatedKey(attempts: readonly Attempt[], limit: number): string | undefined {\n const counts = new Map<string, number>();\n for (const { tool, key, failed } of attempts) {\n if (key === undefined) continue;\n const id = JSON.stringify([tool, key]);\n const count = failed ? (counts.get(id) ?? 0) + 1 : 0;\n counts.set(id, count);\n if (count >= limit)\n return `the model called ${tool} ${count} times with the key ${JSON.stringify(key)} and none succeeded`;\n }\n return undefined;\n}\n\n/** The progress check the loop runs after each step: the reason the run is stuck, or `undefined`. */\nexport type ProgressCheck = (messages: readonly Message[]) => Promise<string | undefined>;\n\n/**\n * The default progress policy as a check over the transcript. `skip` is how many messages came before this run's\n * own, so a run continued from a context that ended in a loop is not stopped by the old calls. The transcript only\n * grows, so each call's hash and key are worked out once and kept by its place in it.\n */\nexport function progressCheck(\n tools: readonly AnyTool[],\n policy: Required<ProgressPolicy>,\n skip: number,\n): ProgressCheck {\n const byName = new Map(tools.map((tool) => [tool.name, tool]));\n const facts = new Map<string, CallFacts>();\n return async (messages) => {\n const attempts = await attemptsOf(messages.slice(skip), byName, facts);\n return identicalFailures(attempts, policy.maxIdenticalFailures) ?? repeatedKey(attempts, policy.maxSameKeyCalls);\n };\n}\n"]}
@@ -0,0 +1,134 @@
1
+ /**
2
+ * What a run returns: a union discriminated by `stopReason`, in which only the `done` variant carries `output`, so
3
+ * code that reads the output without checking the stop reason fails to compile (D10). Every variant carries the
4
+ * usage, the cost and a context the run can continue from.
5
+ */
6
+ import type { AssistantMessage, Cost, Message, Usage } from "@buildanagent/gateway";
7
+ import type { SignedPendingRequest } from "./vendor/agent-safety/pending.js";
8
+ /**
9
+ * A run's conversation as plain JSON: the system prompt, every message so far and, for a run that paused, the signed
10
+ * requests it waits on. Store it anywhere and pass it to `continueRun()` to go on from where the run stopped.
11
+ */
12
+ export interface Context {
13
+ readonly system: string;
14
+ readonly messages: readonly Message[];
15
+ /**
16
+ * The signed requests of a run that paused, `awaiting_approval` or `clarification_requested`: the same ones as
17
+ * `result.pending`. Each one's tool call is in `messages` without a result. Absent for every other stop reason.
18
+ * `continueRun()` refuses a context whose last assistant message has a call with no result and no request here.
19
+ */
20
+ readonly pending?: readonly SignedPendingRequest[];
21
+ /**
22
+ * The input each pending request signs, by request id: the input its call would run with once approved, after
23
+ * coercion, `repair` and any gate's replacement, which can differ from the call's arguments in `messages`. Show
24
+ * the approver this input, and check an answer against it. Absent when `pending` is.
25
+ */
26
+ readonly pendingInputs?: Readonly<Record<string, unknown>>;
27
+ }
28
+ /** Why a model call failed, copied from the failed message's `error`. */
29
+ export interface RunError {
30
+ /**
31
+ * `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or
32
+ * credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a
33
+ * rejected request. `hook`: an interceptor threw while the run fails closed, and `message` says which one.
34
+ * `unknown_price`: the run has a `budgetUsd`, but a price it needs is unknown, so it can't check the spend.
35
+ */
36
+ readonly kind: NonNullable<AssistantMessage["error"]>["kind"] | "hook" | "unknown_price";
37
+ readonly message: string;
38
+ /** The provider's HTTP status, when the failure came with one. */
39
+ readonly status?: number;
40
+ }
41
+ /** The fields every run result carries. */
42
+ export interface ResultBase {
43
+ /** The messages this run added: the input, if any, then every response and tool result, in order. */
44
+ readonly messages: readonly Message[];
45
+ /** The whole conversation, earlier history included, ready for `continueRun()`. */
46
+ readonly context: Context;
47
+ /** The tokens of every model call, summed. */
48
+ readonly usage: Usage;
49
+ /**
50
+ * The cost of every model call, summed. It is unknown if any call's cost is. A run that made no call costs an exact
51
+ * 0 with basis `provider`, so adding it to another cost keeps that cost's basis.
52
+ */
53
+ readonly cost: Cost;
54
+ /** How many model calls the run made. */
55
+ readonly steps: number;
56
+ }
57
+ /**
58
+ * A run that finished: the model answered without calling a tool, or an output tool accepted its answer. `output` is
59
+ * the accepted answer, and `undefined` when the run has no output tool, the model answered in text, or another tool
60
+ * ended the run with `terminate: true`. A text
61
+ * answer cut off at the output limit also ends `done`; its message's `stopReason` is then `"length"`.
62
+ */
63
+ export interface DoneResult<S> extends ResultBase {
64
+ readonly stopReason: "done";
65
+ readonly output: S | undefined;
66
+ }
67
+ /**
68
+ * A run that ended before it finished. `max_steps`: it made `maxSteps` model calls and the model still wanted to
69
+ * continue. `aborted`: it was aborted.
70
+ */
71
+ export interface EndedResult extends ResultBase {
72
+ readonly stopReason: "max_steps" | "aborted";
73
+ }
74
+ /**
75
+ * A run that stopped making progress. The default progress policy ends a run this way after 3 identical failing tool
76
+ * calls in a row, or after 5 failing calls to a tool with one `progressKey`; pass `progress` to `run()` to change the
77
+ * thresholds, or `progress: false` to turn the policy off. A `shouldStop` hook that returns `{ stop: "no_progress" }`
78
+ * ends a run this way too. `reason` says which rule or hook fired.
79
+ */
80
+ export interface NoProgressResult extends ResultBase {
81
+ readonly stopReason: "no_progress";
82
+ readonly reason: string;
83
+ }
84
+ /**
85
+ * A run that ended before a model call because that call could have taken the spend past `budgetUsd`. `spentUsd` is
86
+ * what the run's earlier calls cost, and `projectedUsd` the most the refused call could have cost.
87
+ */
88
+ export interface BudgetResult extends ResultBase {
89
+ readonly stopReason: "budget";
90
+ readonly reason: string;
91
+ readonly budgetUsd: number;
92
+ readonly spentUsd: number;
93
+ readonly projectedUsd: number;
94
+ }
95
+ /** A run that ended because a model call failed, or because an interceptor failed while the run fails closed. */
96
+ export interface ErrorResult extends ResultBase {
97
+ readonly stopReason: "error";
98
+ readonly error: RunError;
99
+ }
100
+ /**
101
+ * A run that stopped before it finished, because a `shouldStop` hook ended it. `stoppedBy` is the `reason` the hook
102
+ * gave, or `"hook"` when it returned `true`.
103
+ */
104
+ export interface StoppedResult extends ResultBase {
105
+ readonly stopReason: "stopped";
106
+ readonly stoppedBy: string;
107
+ }
108
+ /**
109
+ * A run that paused because a `beforeToolCall` gate returned `ask`. `pending` holds one signed request for each call
110
+ * that waits, in model order; `context.pending` holds the same requests and `context.pendingInputs` the input each
111
+ * one signs. Those calls did not run and have no result in the transcript; the step's other calls ran or were denied
112
+ * as usual. Each request's signature covers its id, kind, call id, tool, input hash and policy version, so store the
113
+ * requests and their inputs with the context, show them to a person, and pass each answer to `continueRun()` as a
114
+ * `Resolution`, which checks it against its request and input before the call runs. When a tool asked a question in
115
+ * the same step, its clarification request is in `pending` too.
116
+ */
117
+ export interface AwaitingApprovalResult extends ResultBase {
118
+ readonly stopReason: "awaiting_approval";
119
+ readonly pending: readonly SignedPendingRequest[];
120
+ }
121
+ /**
122
+ * A run that paused because a tool, such as one from `clarificationTool()`, asked the user a question and no call
123
+ * waits for an approval. `pending` holds one signed request of kind `clarification` for each question, in model
124
+ * order, with the question in `question`. The asking call has no result in the transcript. Pass the user's answer to
125
+ * `continueRun()` as `{ requestId, answer }`, and the model reads the answer as the call's result.
126
+ */
127
+ export interface ClarificationRequestedResult extends ResultBase {
128
+ readonly stopReason: "clarification_requested";
129
+ readonly pending: readonly SignedPendingRequest[];
130
+ }
131
+ /** What a run returns. Check `stopReason` before you read the fields of one variant. */
132
+ export type RunResult<S = unknown> = DoneResult<S> | AwaitingApprovalResult | ClarificationRequestedResult | BudgetResult | EndedResult | ErrorResult | NoProgressResult | StoppedResult;
133
+ /** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */
134
+ export type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;
package/dist/result.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=result.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result.js","sourceRoot":"","sources":["../src/result.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * What a run returns: a union discriminated by `stopReason`, in which only the `done` variant carries `output`, so\n * code that reads the output without checking the stop reason fails to compile (D10). Every variant carries the\n * usage, the cost and a context the run can continue from.\n */\nimport type { AssistantMessage, Cost, Message, Usage } from \"@buildanagent/gateway\";\nimport type { SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\n\n/**\n * A run's conversation as plain JSON: the system prompt, every message so far and, for a run that paused, the signed\n * requests it waits on. Store it anywhere and pass it to `continueRun()` to go on from where the run stopped.\n */\nexport interface Context {\n readonly system: string;\n readonly messages: readonly Message[];\n /**\n * The signed requests of a run that paused, `awaiting_approval` or `clarification_requested`: the same ones as\n * `result.pending`. Each one's tool call is in `messages` without a result. Absent for every other stop reason.\n * `continueRun()` refuses a context whose last assistant message has a call with no result and no request here.\n */\n readonly pending?: readonly SignedPendingRequest[];\n /**\n * The input each pending request signs, by request id: the input its call would run with once approved, after\n * coercion, `repair` and any gate's replacement, which can differ from the call's arguments in `messages`. Show\n * the approver this input, and check an answer against it. Absent when `pending` is.\n */\n readonly pendingInputs?: Readonly<Record<string, unknown>>;\n}\n\n/** Why a model call failed, copied from the failed message's `error`. */\nexport interface RunError {\n /**\n * `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or\n * credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a\n * rejected request. `hook`: an interceptor threw while the run fails closed, and `message` says which one.\n * `unknown_price`: the run has a `budgetUsd`, but a price it needs is unknown, so it can't check the spend.\n */\n readonly kind: NonNullable<AssistantMessage[\"error\"]>[\"kind\"] | \"hook\" | \"unknown_price\";\n readonly message: string;\n /** The provider's HTTP status, when the failure came with one. */\n readonly status?: number;\n}\n\n/** The fields every run result carries. */\nexport interface ResultBase {\n /** The messages this run added: the input, if any, then every response and tool result, in order. */\n readonly messages: readonly Message[];\n /** The whole conversation, earlier history included, ready for `continueRun()`. */\n readonly context: Context;\n /** The tokens of every model call, summed. */\n readonly usage: Usage;\n /**\n * The cost of every model call, summed. It is unknown if any call's cost is. A run that made no call costs an exact\n * 0 with basis `provider`, so adding it to another cost keeps that cost's basis.\n */\n readonly cost: Cost;\n /** How many model calls the run made. */\n readonly steps: number;\n}\n\n/**\n * A run that finished: the model answered without calling a tool, or an output tool accepted its answer. `output` is\n * the accepted answer, and `undefined` when the run has no output tool, the model answered in text, or another tool\n * ended the run with `terminate: true`. A text\n * answer cut off at the output limit also ends `done`; its message's `stopReason` is then `\"length\"`.\n */\nexport interface DoneResult<S> extends ResultBase {\n readonly stopReason: \"done\";\n readonly output: S | undefined;\n}\n\n/**\n * A run that ended before it finished. `max_steps`: it made `maxSteps` model calls and the model still wanted to\n * continue. `aborted`: it was aborted.\n */\nexport interface EndedResult extends ResultBase {\n readonly stopReason: \"max_steps\" | \"aborted\";\n}\n\n/**\n * A run that stopped making progress. The default progress policy ends a run this way after 3 identical failing tool\n * calls in a row, or after 5 failing calls to a tool with one `progressKey`; pass `progress` to `run()` to change the\n * thresholds, or `progress: false` to turn the policy off. A `shouldStop` hook that returns `{ stop: \"no_progress\" }`\n * ends a run this way too. `reason` says which rule or hook fired.\n */\nexport interface NoProgressResult extends ResultBase {\n readonly stopReason: \"no_progress\";\n readonly reason: string;\n}\n\n/**\n * A run that ended before a model call because that call could have taken the spend past `budgetUsd`. `spentUsd` is\n * what the run's earlier calls cost, and `projectedUsd` the most the refused call could have cost.\n */\nexport interface BudgetResult extends ResultBase {\n readonly stopReason: \"budget\";\n readonly reason: string;\n readonly budgetUsd: number;\n readonly spentUsd: number;\n readonly projectedUsd: number;\n}\n\n/** A run that ended because a model call failed, or because an interceptor failed while the run fails closed. */\nexport interface ErrorResult extends ResultBase {\n readonly stopReason: \"error\";\n readonly error: RunError;\n}\n\n/**\n * A run that stopped before it finished, because a `shouldStop` hook ended it. `stoppedBy` is the `reason` the hook\n * gave, or `\"hook\"` when it returned `true`.\n */\nexport interface StoppedResult extends ResultBase {\n readonly stopReason: \"stopped\";\n readonly stoppedBy: string;\n}\n\n/**\n * A run that paused because a `beforeToolCall` gate returned `ask`. `pending` holds one signed request for each call\n * that waits, in model order; `context.pending` holds the same requests and `context.pendingInputs` the input each\n * one signs. Those calls did not run and have no result in the transcript; the step's other calls ran or were denied\n * as usual. Each request's signature covers its id, kind, call id, tool, input hash and policy version, so store the\n * requests and their inputs with the context, show them to a person, and pass each answer to `continueRun()` as a\n * `Resolution`, which checks it against its request and input before the call runs. When a tool asked a question in\n * the same step, its clarification request is in `pending` too.\n */\nexport interface AwaitingApprovalResult extends ResultBase {\n readonly stopReason: \"awaiting_approval\";\n readonly pending: readonly SignedPendingRequest[];\n}\n\n/**\n * A run that paused because a tool, such as one from `clarificationTool()`, asked the user a question and no call\n * waits for an approval. `pending` holds one signed request of kind `clarification` for each question, in model\n * order, with the question in `question`. The asking call has no result in the transcript. Pass the user's answer to\n * `continueRun()` as `{ requestId, answer }`, and the model reads the answer as the call's result.\n */\nexport interface ClarificationRequestedResult extends ResultBase {\n readonly stopReason: \"clarification_requested\";\n readonly pending: readonly SignedPendingRequest[];\n}\n\n/** What a run returns. Check `stopReason` before you read the fields of one variant. */\nexport type RunResult<S = unknown> =\n | DoneResult<S>\n | AwaitingApprovalResult\n | ClarificationRequestedResult\n | BudgetResult\n | EndedResult\n | ErrorResult\n | NoProgressResult\n | StoppedResult;\n\n/** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */\nexport type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;\n"]}
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Resuming a paused context (D5; SDK plan §3.3). `continueRun()` first checks the context's shape and refuses one it
3
+ * can't resume safely, then, inside the run, checks every waiting call's stored request and its resolution before
4
+ * anything runs. The checks fail closed: a request or resolution that doesn't verify never runs its call, and the
5
+ * call asks again with a new request.
6
+ */
7
+ import type { AssistantMessage } from "@buildanagent/gateway";
8
+ import type { AgentEventBody } from "./events.js";
9
+ import type { ToolCall, ToolResult } from "./tools/types.js";
10
+ import { type Recheck, type Resolution, type SignedPendingRequest } from "./vendor/agent-safety/pending.js";
11
+ import type { ApprovalSigner } from "./vendor/agent-safety/signer.js";
12
+ /** A call of the context's last assistant message that has no result, and the stored request it waits on. */
13
+ export interface OpenCall {
14
+ readonly call: ToolCall;
15
+ /** The stored request, untrusted until its signature verifies. Only `id` and `callId` are known to be strings. */
16
+ readonly request: SignedPendingRequest;
17
+ }
18
+ /** What a run that resumes a paused context starts with, checked for shape when `continueRun()` is called. */
19
+ export interface ResumeSetup {
20
+ /** The assistant message whose calls wait, absent when none does. */
21
+ readonly message?: AssistantMessage;
22
+ /** The calls that wait, in model order. */
23
+ readonly open: readonly OpenCall[];
24
+ /** Each resolution, by the request id it names. */
25
+ readonly resolutions: ReadonlyMap<string, Resolution>;
26
+ /** The request ids that more than one resolution names. */
27
+ readonly replayed: ReadonlySet<string>;
28
+ /** The request ids of resolutions that name no request in the context. */
29
+ readonly unmatched: readonly string[];
30
+ /** The input each stored request signs, by request id. */
31
+ readonly inputs: Readonly<Record<string, unknown>>;
32
+ /** Runs current policy before an approved call runs. */
33
+ readonly recheck?: Recheck;
34
+ }
35
+ /** What the checks decided for one waiting call. */
36
+ export type Verdict =
37
+ /** A verified approval: the call runs with `call.input`, the input its request signs. */
38
+ {
39
+ readonly kind: "run";
40
+ readonly call: ToolCall;
41
+ }
42
+ /** A verified denial or answer, or an approval current policy now denies: the model reads `result`. */
43
+ | {
44
+ readonly kind: "result";
45
+ readonly call: ToolCall;
46
+ readonly result: ToolResult;
47
+ }
48
+ /** No resolution names the request, which verified: it still waits. */
49
+ | {
50
+ readonly kind: "wait";
51
+ readonly call: ToolCall;
52
+ readonly request: SignedPendingRequest;
53
+ readonly input: unknown;
54
+ }
55
+ /** The request or its resolution failed a check: the call asks again. */
56
+ | {
57
+ readonly kind: "reissue";
58
+ readonly call: ToolCall;
59
+ };
60
+ /**
61
+ * Checks a context and its resolutions before a run starts, and returns what the run needs to resume its waiting
62
+ * calls, or `undefined` when no call waits. Throws an `SdkError` with code `invalid_run_options` for a context it
63
+ * can't read, for a call of the last assistant message that has no result and no stored request, for a stored
64
+ * request whose call doesn't wait in the context, and for malformed resolutions or `recheck`.
65
+ */
66
+ export declare function resumeSetupOf(context: unknown, resolutions: unknown, recheck: unknown): ResumeSetup | undefined;
67
+ /** What the checks need from the run. */
68
+ export interface JudgeContext {
69
+ readonly signer: ApprovalSigner;
70
+ send(body: AgentEventBody): void;
71
+ }
72
+ /**
73
+ * Checks each waiting call's stored request and resolution, in model order, and decides what happens to the call.
74
+ * Nothing runs here: the run acts on the verdicts afterwards.
75
+ */
76
+ export declare function judgeOpenCalls(resume: ResumeSetup, ctx: JudgeContext): Promise<Verdict[]>;
package/dist/resume.js ADDED
@@ -0,0 +1,237 @@
1
+ import { SdkError } from "./errors.js";
2
+ import { denied, textOf } from "./hook-runner.js";
3
+ import { verifyResolution, } from "./vendor/agent-safety/pending.js";
4
+ function invalid(message) {
5
+ throw new SdkError("invalid_run_options", `continueRun() ${message}`);
6
+ }
7
+ function isObject(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9
+ }
10
+ function isFailedTurn(message) {
11
+ return message.role === "assistant" && (message.stopReason === "error" || message.stopReason === "aborted");
12
+ }
13
+ /**
14
+ * The calls of the last assistant message that no later tool message answers. A message that ended in an error or
15
+ * an abort has none: the gateway's replay pass drops it, and the run asks the model again.
16
+ */
17
+ function openCallsOf(messages) {
18
+ const index = messages.findLastIndex((message) => message.role === "assistant");
19
+ const message = messages[index];
20
+ if (message?.role !== "assistant" || isFailedTurn(message))
21
+ return undefined;
22
+ const answered = new Set();
23
+ for (const later of messages.slice(index + 1))
24
+ if (later.role === "tool")
25
+ answered.add(later.callId);
26
+ const calls = message.content.filter((block) => block.type === "tool_call" && !answered.has(block.callId));
27
+ return { message, calls };
28
+ }
29
+ /** Checks the context's shape, the minimum `continueRun()` needs to read it. */
30
+ function checkContext(context) {
31
+ if (!isObject(context))
32
+ invalid("needs a context object with system and messages");
33
+ if (typeof context.system !== "string")
34
+ invalid("needs a context whose system is a string");
35
+ if (!Array.isArray(context.messages) || !context.messages.every((m) => isObject(m) && typeof m.role === "string")) {
36
+ invalid("needs a context whose messages are a list of messages");
37
+ }
38
+ if (context.pending !== undefined && !Array.isArray(context.pending))
39
+ invalid("needs pending to be a list");
40
+ if (context.pendingInputs !== undefined && !isObject(context.pendingInputs)) {
41
+ invalid("needs pendingInputs to be an object of inputs by request id");
42
+ }
43
+ }
44
+ /** The stored requests by call id, after checking that each one is an object with a string `id` and `callId`. */
45
+ function requestsByCall(pending) {
46
+ const byCall = new Map();
47
+ const ids = new Set();
48
+ for (const request of pending) {
49
+ if (!isObject(request) || typeof request.id !== "string" || typeof request.callId !== "string") {
50
+ invalid("needs each pending request to be an object with a string id and callId");
51
+ }
52
+ if (ids.has(request.id))
53
+ invalid(`got two pending requests with the id ${JSON.stringify(request.id)}`);
54
+ if (byCall.has(request.callId))
55
+ invalid(`got two pending requests for the call ${JSON.stringify(request.callId)}`);
56
+ ids.add(request.id);
57
+ byCall.set(request.callId, request);
58
+ }
59
+ return byCall;
60
+ }
61
+ /** The resolutions by request id, with the ids more than one of them names. */
62
+ function resolutionsOf(resolutions) {
63
+ if (resolutions !== undefined && !Array.isArray(resolutions))
64
+ invalid("needs resolutions to be a list");
65
+ const byId = new Map();
66
+ const replayed = new Set();
67
+ for (const resolution of (resolutions ?? [])) {
68
+ if (!isObject(resolution) || typeof resolution.requestId !== "string") {
69
+ invalid("needs each resolution to be an object with a string requestId");
70
+ }
71
+ if (byId.has(resolution.requestId))
72
+ replayed.add(resolution.requestId);
73
+ byId.set(resolution.requestId, resolution);
74
+ }
75
+ return { byId, replayed };
76
+ }
77
+ /**
78
+ * Pairs each waiting call with its stored request, and refuses a call with none, two calls with one id, and a
79
+ * request whose call doesn't wait.
80
+ */
81
+ function matchOpenCalls(calls, byCall) {
82
+ const open = [];
83
+ for (const call of calls) {
84
+ const request = byCall.get(call.callId);
85
+ // The owner's rule (2026-11-19): a waiting call with no record is a lost pause, so it fails loudly here rather
86
+ // than reaching the model as "No result was recorded".
87
+ if (request === undefined) {
88
+ invalid(`can't resume the call ${JSON.stringify(call.callId)} to "${call.name}": it has no result and no pending ` +
89
+ "request, so its pause record was lost. Restore the context's pending and pendingInputs, or add a result");
90
+ }
91
+ if (open.some((entry) => entry.call.callId === call.callId)) {
92
+ invalid(`got two waiting calls with the id ${JSON.stringify(call.callId)}`);
93
+ }
94
+ open.push({ call, request });
95
+ }
96
+ for (const [callId, request] of byCall) {
97
+ if (!calls.some((call) => call.callId === callId)) {
98
+ invalid(`got the pending request ${JSON.stringify(request.id)}, whose call doesn't wait in this context. ` +
99
+ "Remove the request from pending and its input from pendingInputs, or restore the call without its result");
100
+ }
101
+ }
102
+ return open;
103
+ }
104
+ /**
105
+ * Checks a context and its resolutions before a run starts, and returns what the run needs to resume its waiting
106
+ * calls, or `undefined` when no call waits. Throws an `SdkError` with code `invalid_run_options` for a context it
107
+ * can't read, for a call of the last assistant message that has no result and no stored request, for a stored
108
+ * request whose call doesn't wait in the context, and for malformed resolutions or `recheck`.
109
+ */
110
+ export function resumeSetupOf(context, resolutions, recheck) {
111
+ checkContext(context);
112
+ if (recheck !== undefined && typeof recheck !== "function")
113
+ invalid("needs recheck to be a function");
114
+ const byCall = requestsByCall(context.pending ?? []);
115
+ const { byId, replayed } = resolutionsOf(resolutions);
116
+ const found = openCallsOf(context.messages);
117
+ const open = matchOpenCalls(found?.calls ?? [], byCall);
118
+ const known = new Set(open.map((entry) => entry.request.id));
119
+ const unmatched = [...byId.keys()].filter((id) => !known.has(id));
120
+ if (found === undefined || open.length === 0) {
121
+ // Resolutions that name no request are still reported, and nothing runs for them.
122
+ if (unmatched.length === 0)
123
+ return undefined;
124
+ return { open: [], resolutions: byId, replayed, unmatched, inputs: {} };
125
+ }
126
+ return {
127
+ message: found.message,
128
+ open,
129
+ resolutions: byId,
130
+ replayed,
131
+ unmatched,
132
+ inputs: (context.pendingInputs ?? {}),
133
+ ...(recheck === undefined ? {} : { recheck: recheck }),
134
+ };
135
+ }
136
+ /** A resolution of the request's own kind, to check a stored request that no resolution names. */
137
+ function probeOf(request) {
138
+ return request.kind === "clarification"
139
+ ? { requestId: request.id, answer: "" }
140
+ : { requestId: request.id, decision: "deny" };
141
+ }
142
+ function inputOf(inputs, id) {
143
+ return Object.hasOwn(inputs, id) ? inputs[id] : undefined;
144
+ }
145
+ /**
146
+ * Checks each waiting call's stored request and resolution, in model order, and decides what happens to the call.
147
+ * Nothing runs here: the run acts on the verdicts afterwards.
148
+ */
149
+ export async function judgeOpenCalls(resume, ctx) {
150
+ const reject = (requestId, callId, cause) => ctx.send({ type: "resolution_rejected", requestId, ...(callId === undefined ? {} : { callId }), cause });
151
+ for (const id of resume.unmatched)
152
+ reject(id, undefined, "unknown_request");
153
+ const verdicts = [];
154
+ for (const { call, request } of resume.open) {
155
+ if (resume.replayed.has(request.id)) {
156
+ reject(request.id, call.callId, "replayed");
157
+ verdicts.push({ kind: "reissue", call });
158
+ continue;
159
+ }
160
+ const input = inputOf(resume.inputs, request.id);
161
+ const resolution = resume.resolutions.get(request.id);
162
+ const cause = await failedCheck(request, resolution ?? probeOf(request), call, input, ctx.signer);
163
+ if (cause !== undefined) {
164
+ reject(request.id, call.callId, cause);
165
+ verdicts.push({ kind: "reissue", call });
166
+ }
167
+ else if (resolution === undefined) {
168
+ verdicts.push({ kind: "wait", call, request, input });
169
+ }
170
+ else {
171
+ verdicts.push(await verdictOf(call, request, resolution, input, resume.recheck, ctx));
172
+ }
173
+ }
174
+ return verdicts;
175
+ }
176
+ /** Why the request or its resolution failed `verifyResolution()`, or `undefined` when both passed. */
177
+ async function failedCheck(request, resolution, call, input, signer) {
178
+ try {
179
+ const check = await verifyResolution(request, resolution, {
180
+ signer,
181
+ call: { callId: call.callId, tool: call.name, input },
182
+ });
183
+ return check.ok ? undefined : check.cause;
184
+ }
185
+ catch {
186
+ // A custom signer whose verify() throws fails the check; its message may hold anything, so it isn't passed on.
187
+ return "error";
188
+ }
189
+ }
190
+ /** The verdict for a verified resolution. */
191
+ async function verdictOf(call, request, resolution, input, recheck, ctx) {
192
+ const by = textOf(resolution.by);
193
+ // The verified request's kind decides, never the resolution's fields: a resolution that carries both an `answer`
194
+ // and a `decision` passes the check for either kind, and an approval must never take a host's text as its result.
195
+ if (request.kind === "clarification") {
196
+ const result = {
197
+ content: [{ type: "text", text: resolution.answer }],
198
+ details: { requestId: request.id, ...(by === undefined ? {} : { by }) },
199
+ };
200
+ return { kind: "result", call, result };
201
+ }
202
+ const decision = resolution;
203
+ if (decision.decision === "deny") {
204
+ return { kind: "result", call, result: denied(call.name, textOf(decision.reason), request.id, by) };
205
+ }
206
+ const blocked = recheck === undefined ? undefined : await policyBlock(recheck, request, input, ctx);
207
+ if (blocked !== undefined) {
208
+ const text = `Tool call "${call.name}" was approved, but current policy now denies it: ${blocked}`;
209
+ const result = {
210
+ content: [{ type: "text", text }],
211
+ isError: true,
212
+ details: { decision: "deny", requestId: request.id, policy: true },
213
+ };
214
+ return { kind: "result", call, result };
215
+ }
216
+ // The approved call runs with the input its request signs, never the transcript's arguments.
217
+ return { kind: "run", call: { ...call, input } };
218
+ }
219
+ /** Why current policy blocks an approved call, or `undefined` when `recheck` allows it. Fails closed. */
220
+ async function policyBlock(recheck, request, input, ctx) {
221
+ let answer;
222
+ try {
223
+ // Copies, so a callback that edits what it is handed can't change the input the run executes after the check. A
224
+ // request or input that can't be copied fails the check closed.
225
+ answer = await recheck(structuredClone(request), structuredClone(input));
226
+ }
227
+ catch (error) {
228
+ ctx.send({ type: "hook_error", hook: "recheck", error: error instanceof Error ? error.message : String(error) });
229
+ return "the policy check failed";
230
+ }
231
+ if (answer === "allow")
232
+ return undefined;
233
+ if (isObject(answer) && typeof answer.deny === "string" && answer.deny !== "")
234
+ return answer.deny;
235
+ return "the policy check did not allow it";
236
+ }
237
+ //# sourceMappingURL=resume.js.map