@buildanagent/sdk 0.1.0-alpha.1 → 0.1.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +424 -5
- package/dist/budget.d.ts +33 -0
- package/dist/budget.js +55 -0
- package/dist/budget.js.map +1 -0
- package/dist/compose.d.ts +26 -0
- package/dist/compose.js +157 -0
- package/dist/compose.js.map +1 -0
- package/dist/errors.d.ts +49 -0
- package/dist/errors.js +57 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +168 -0
- package/dist/events.js +32 -0
- package/dist/events.js.map +1 -0
- package/dist/freeze.d.ts +11 -0
- package/dist/freeze.js +42 -0
- package/dist/freeze.js.map +1 -0
- package/dist/hook-checks.d.ts +31 -0
- package/dist/hook-checks.js +130 -0
- package/dist/hook-checks.js.map +1 -0
- package/dist/hook-runner.d.ts +96 -0
- package/dist/hook-runner.js +372 -0
- package/dist/hook-runner.js.map +1 -0
- package/dist/hooks.d.ts +183 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +26 -3
- package/dist/index.js +21 -3
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +67 -0
- package/dist/loop.js +644 -0
- package/dist/loop.js.map +1 -0
- package/dist/observers.d.ts +31 -0
- package/dist/observers.js +98 -0
- package/dist/observers.js.map +1 -0
- package/dist/otel/attributes.d.ts +43 -0
- package/dist/otel/attributes.js +50 -0
- package/dist/otel/attributes.js.map +1 -0
- package/dist/otel/content.d.ts +17 -0
- package/dist/otel/content.js +48 -0
- package/dist/otel/content.js.map +1 -0
- package/dist/otel/index.d.ts +6 -2
- package/dist/otel/index.js +6 -2
- package/dist/otel/index.js.map +1 -1
- package/dist/otel/observer.d.ts +82 -0
- package/dist/otel/observer.js +300 -0
- package/dist/otel/observer.js.map +1 -0
- package/dist/pauses.d.ts +61 -0
- package/dist/pauses.js +83 -0
- package/dist/pauses.js.map +1 -0
- package/dist/progress.d.ts +34 -0
- package/dist/progress.js +139 -0
- package/dist/progress.js.map +1 -0
- package/dist/result.d.ts +134 -0
- package/dist/result.js +2 -0
- package/dist/result.js.map +1 -0
- package/dist/resume.d.ts +76 -0
- package/dist/resume.js +237 -0
- package/dist/resume.js.map +1 -0
- package/dist/run.d.ts +214 -0
- package/dist/run.js +327 -0
- package/dist/run.js.map +1 -0
- package/dist/steering.d.ts +52 -0
- package/dist/steering.js +104 -0
- package/dist/steering.js.map +1 -0
- package/dist/testing/scripted-model.d.ts +12 -2
- package/dist/testing/scripted-model.js +19 -2
- package/dist/testing/scripted-model.js.map +1 -1
- package/dist/tools/coerce.d.ts +15 -0
- package/dist/tools/coerce.js +93 -0
- package/dist/tools/coerce.js.map +1 -0
- package/dist/tools/define.d.ts +54 -0
- package/dist/tools/define.js +121 -0
- package/dist/tools/define.js.map +1 -0
- package/dist/tools/format-error.d.ts +13 -0
- package/dist/tools/format-error.js +66 -0
- package/dist/tools/format-error.js.map +1 -0
- package/dist/tools/outcome.d.ts +7 -0
- package/dist/tools/outcome.js +30 -0
- package/dist/tools/outcome.js.map +1 -0
- package/dist/tools/pipeline.d.ts +111 -0
- package/dist/tools/pipeline.js +382 -0
- package/dist/tools/pipeline.js.map +1 -0
- package/dist/tools/scheduler.d.ts +33 -0
- package/dist/tools/scheduler.js +51 -0
- package/dist/tools/scheduler.js.map +1 -0
- package/dist/tools/schema.d.ts +20 -0
- package/dist/tools/schema.js +100 -0
- package/dist/tools/schema.js.map +1 -0
- package/dist/tools/types.d.ts +196 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/vendor/agent-safety/bytes.d.ts +17 -0
- package/dist/vendor/agent-safety/bytes.js +59 -0
- package/dist/vendor/agent-safety/bytes.js.map +1 -0
- package/dist/vendor/agent-safety/errors.d.ts +23 -0
- package/dist/vendor/agent-safety/errors.js +22 -0
- package/dist/vendor/agent-safety/errors.js.map +1 -0
- package/dist/vendor/agent-safety/hash.d.ts +16 -0
- package/dist/vendor/agent-safety/hash.js +110 -0
- package/dist/vendor/agent-safety/hash.js.map +1 -0
- package/dist/vendor/agent-safety/outcome.d.ts +88 -0
- package/dist/vendor/agent-safety/outcome.js +140 -0
- package/dist/vendor/agent-safety/outcome.js.map +1 -0
- package/dist/vendor/agent-safety/pending.d.ts +119 -0
- package/dist/vendor/agent-safety/pending.js +122 -0
- package/dist/vendor/agent-safety/pending.js.map +1 -0
- package/dist/vendor/agent-safety/render.d.ts +40 -0
- package/dist/vendor/agent-safety/render.js +92 -0
- package/dist/vendor/agent-safety/render.js.map +1 -0
- package/dist/vendor/agent-safety/signer.d.ts +42 -0
- package/dist/vendor/agent-safety/signer.js +128 -0
- package/dist/vendor/agent-safety/signer.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +13 -3
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { SdkError } from "./errors.js";
|
|
2
|
+
import { isContentList } from "./tools/pipeline.js";
|
|
3
|
+
function invalid(hook, problem) {
|
|
4
|
+
throw new SdkError("invalid_hook_result", `${hook} ${problem}`);
|
|
5
|
+
}
|
|
6
|
+
function isObject(value) {
|
|
7
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
|
+
}
|
|
9
|
+
function isMessage(value) {
|
|
10
|
+
if (!isObject(value))
|
|
11
|
+
return false;
|
|
12
|
+
if (value.role === "tool")
|
|
13
|
+
return typeof value.callId === "string" && Array.isArray(value.content);
|
|
14
|
+
return (value.role === "user" || value.role === "assistant") && Array.isArray(value.content);
|
|
15
|
+
}
|
|
16
|
+
/** Checks a list of messages and returns a copy of it. */
|
|
17
|
+
export function checkMessages(hook, value) {
|
|
18
|
+
if (!Array.isArray(value) || !value.every(isMessage)) {
|
|
19
|
+
invalid(hook, "must return a list of messages, each with a role and content");
|
|
20
|
+
}
|
|
21
|
+
return [...value];
|
|
22
|
+
}
|
|
23
|
+
/** Checks `beforeModelCall`'s return value: nothing, or a patch of well-formed fields. */
|
|
24
|
+
export function checkModelPatch(value) {
|
|
25
|
+
if (value === undefined)
|
|
26
|
+
return undefined;
|
|
27
|
+
if (!isObject(value))
|
|
28
|
+
invalid("beforeModelCall", "must return a patch object or nothing");
|
|
29
|
+
const { system, messages, activeTools, model, options } = value;
|
|
30
|
+
if (system !== undefined && typeof system !== "string")
|
|
31
|
+
invalid("beforeModelCall", "returned a system that is not a string");
|
|
32
|
+
if (messages !== undefined)
|
|
33
|
+
checkMessages("beforeModelCall", messages);
|
|
34
|
+
if (activeTools !== undefined && !(Array.isArray(activeTools) && activeTools.every((n) => typeof n === "string"))) {
|
|
35
|
+
invalid("beforeModelCall", "returned activeTools that is not a list of tool names");
|
|
36
|
+
}
|
|
37
|
+
if (model !== undefined && typeof model?.stream !== "function") {
|
|
38
|
+
invalid("beforeModelCall", "returned a model that is not from createModel()");
|
|
39
|
+
}
|
|
40
|
+
if (options !== undefined && !isObject(options))
|
|
41
|
+
invalid("beforeModelCall", "returned options that are not an object");
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
/** Checks `afterModelCall`'s return value and returns the replacement message, if there is one. */
|
|
45
|
+
export function checkReplacement(value) {
|
|
46
|
+
if (value === undefined)
|
|
47
|
+
return undefined;
|
|
48
|
+
if (!isObject(value))
|
|
49
|
+
invalid("afterModelCall", "must return { message } or nothing");
|
|
50
|
+
const { message } = value;
|
|
51
|
+
if (message === undefined)
|
|
52
|
+
return undefined;
|
|
53
|
+
if (!isObject(message) || message.role !== "assistant" || !Array.isArray(message.content)) {
|
|
54
|
+
invalid("afterModelCall", "returned a message that is not an assistant message");
|
|
55
|
+
}
|
|
56
|
+
return message;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Checks the fields an `ask` adds, so a gate's own mistake is reported as one and not as a signer that failed.
|
|
60
|
+
* `policyVersion` is signed, so it must be a non-empty, well-formed string; `reason` is display text, which the pause
|
|
61
|
+
* leaves out when it is blank.
|
|
62
|
+
*/
|
|
63
|
+
function checkAsk(value) {
|
|
64
|
+
const { reason, policyVersion } = value;
|
|
65
|
+
if (reason !== undefined && typeof reason !== "string") {
|
|
66
|
+
invalid("beforeToolCall", "returned ask with a reason that is not a string");
|
|
67
|
+
}
|
|
68
|
+
if (policyVersion !== undefined &&
|
|
69
|
+
(typeof policyVersion !== "string" || policyVersion === "" || !policyVersion.isWellFormed())) {
|
|
70
|
+
invalid("beforeToolCall", "returned ask with a policyVersion that is not a non-empty, well-formed string");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Checks `beforeToolCall`'s decision. */
|
|
74
|
+
export function checkDecision(value) {
|
|
75
|
+
if (!isObject(value))
|
|
76
|
+
invalid("beforeToolCall", "must return a decision: allow, deny or ask");
|
|
77
|
+
const { decision, reason } = value;
|
|
78
|
+
if (decision !== "allow" && decision !== "deny" && decision !== "ask") {
|
|
79
|
+
invalid("beforeToolCall", `returned the decision ${JSON.stringify(decision)}; it must be allow, deny or ask`);
|
|
80
|
+
}
|
|
81
|
+
if (decision === "deny" && typeof reason !== "string")
|
|
82
|
+
invalid("beforeToolCall", "returned deny without a reason");
|
|
83
|
+
if (decision === "ask")
|
|
84
|
+
checkAsk(value);
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
/** Checks `afterToolCall`'s patch. */
|
|
88
|
+
export function checkResultPatch(value) {
|
|
89
|
+
if (value === undefined)
|
|
90
|
+
return undefined;
|
|
91
|
+
if (!isObject(value))
|
|
92
|
+
invalid("afterToolCall", "must return a patch object or nothing");
|
|
93
|
+
if ("outcome" in value)
|
|
94
|
+
invalid("afterToolCall", "returned an outcome; replace content instead");
|
|
95
|
+
for (const flag of ["isError", "terminate"]) {
|
|
96
|
+
if (value[flag] !== undefined && typeof value[flag] !== "boolean") {
|
|
97
|
+
invalid("afterToolCall", `returned ${flag} that is not a boolean`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
// The continue content becomes a user message in the transcript, so a malformed block would fail a later request far
|
|
103
|
+
// from the hook that returned it.
|
|
104
|
+
function continueContent(value) {
|
|
105
|
+
if (typeof value === "string")
|
|
106
|
+
return [{ type: "text", text: value }];
|
|
107
|
+
if (!isContentList(value)) {
|
|
108
|
+
invalid("shouldStop", "returned a continue that is neither text nor a list of text and image blocks");
|
|
109
|
+
}
|
|
110
|
+
return [...value];
|
|
111
|
+
}
|
|
112
|
+
/** Checks `shouldStop`'s decision and turns it into a verdict. */
|
|
113
|
+
export function checkStopDecision(value) {
|
|
114
|
+
if (value === true)
|
|
115
|
+
return { kind: "stop", stoppedBy: "hook" };
|
|
116
|
+
if (value === false)
|
|
117
|
+
return { kind: "none" };
|
|
118
|
+
if (!isObject(value))
|
|
119
|
+
invalid("shouldStop", "must return a boolean, { continue } or { stop, reason }");
|
|
120
|
+
const decision = value;
|
|
121
|
+
if ("continue" in decision)
|
|
122
|
+
return { kind: "continue", content: continueContent(decision.continue) };
|
|
123
|
+
if (typeof decision.reason !== "string" || (decision.stop !== "hook" && decision.stop !== "no_progress")) {
|
|
124
|
+
invalid("shouldStop", 'returned a stop that is not { stop: "hook" | "no_progress", reason }');
|
|
125
|
+
}
|
|
126
|
+
return decision.stop === "hook"
|
|
127
|
+
? { kind: "stop", stoppedBy: decision.reason }
|
|
128
|
+
: { kind: "no_progress", reason: decision.reason };
|
|
129
|
+
}
|
|
130
|
+
//# sourceMappingURL=hook-checks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hook-checks.js","sourceRoot":"","sources":["../src/hook-checks.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,SAAS,OAAO,CAAC,IAAY,EAAE,OAAe;IAC5C,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,GAAG,IAAI,IAA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KAAuC,CAAC;IACzD,IAAI,UAAU,IAAI,QAAQ;QAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;IACrG,IAAI,OAAO,QAAQ,CAAC,MAAM,KAAK,QAAQ,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,MAAM,IAAI,QAAQ,CAAC,IAAI,KAAK,aAAa,CAAC,EAAE,CAAC;QACzG,OAAO,CAAC,YAAY,EAAE,sEAAsE,CAAC,CAAC;IAChG,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,KAAK,MAAM;QAC7B,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,MAAM,EAAE;QAC9C,CAAC,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;AACvD,CAAC","sourcesContent":["/**\n * Checks on what an interceptor returned. A hook that returns the wrong shape is a programmer error, so each check\n * throws an `SdkError` with code `invalid_hook_result` rather than failing closed: a typo in a gate must be loud.\n */\nimport type { AssistantMessage, ContentBlock, Message, Model } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { GateDecision, ModelCallPatch, StopDecision } from \"./hooks.js\";\nimport { isContentList } from \"./tools/pipeline.js\";\n\nfunction invalid(hook: string, problem: string): never {\n throw new SdkError(\"invalid_hook_result\", `${hook} ${problem}`);\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isMessage(value: unknown): value is Message {\n if (!isObject(value)) return false;\n if (value.role === \"tool\") return typeof value.callId === \"string\" && Array.isArray(value.content);\n return (value.role === \"user\" || value.role === \"assistant\") && Array.isArray(value.content);\n}\n\n/** Checks a list of messages and returns a copy of it. */\nexport function checkMessages(hook: string, value: unknown): Message[] {\n if (!Array.isArray(value) || !value.every(isMessage)) {\n invalid(hook, \"must return a list of messages, each with a role and content\");\n }\n return [...value];\n}\n\n/** Checks `beforeModelCall`'s return value: nothing, or a patch of well-formed fields. */\nexport function checkModelPatch(value: unknown): ModelCallPatch | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) invalid(\"beforeModelCall\", \"must return a patch object or nothing\");\n const { system, messages, activeTools, model, options } = value;\n if (system !== undefined && typeof system !== \"string\")\n invalid(\"beforeModelCall\", \"returned a system that is not a string\");\n if (messages !== undefined) checkMessages(\"beforeModelCall\", messages);\n if (activeTools !== undefined && !(Array.isArray(activeTools) && activeTools.every((n) => typeof n === \"string\"))) {\n invalid(\"beforeModelCall\", \"returned activeTools that is not a list of tool names\");\n }\n if (model !== undefined && typeof (model as Partial<Model> | null)?.stream !== \"function\") {\n invalid(\"beforeModelCall\", \"returned a model that is not from createModel()\");\n }\n if (options !== undefined && !isObject(options))\n invalid(\"beforeModelCall\", \"returned options that are not an object\");\n return value as ModelCallPatch;\n}\n\n/** Checks `afterModelCall`'s return value and returns the replacement message, if there is one. */\nexport function checkReplacement(value: unknown): AssistantMessage | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) invalid(\"afterModelCall\", \"must return { message } or nothing\");\n const { message } = value;\n if (message === undefined) return undefined;\n if (!isObject(message) || message.role !== \"assistant\" || !Array.isArray(message.content)) {\n invalid(\"afterModelCall\", \"returned a message that is not an assistant message\");\n }\n return message as unknown as AssistantMessage;\n}\n\n/**\n * Checks the fields an `ask` adds, so a gate's own mistake is reported as one and not as a signer that failed.\n * `policyVersion` is signed, so it must be a non-empty, well-formed string; `reason` is display text, which the pause\n * leaves out when it is blank.\n */\nfunction checkAsk(value: Record<string, unknown>): void {\n const { reason, policyVersion } = value;\n if (reason !== undefined && typeof reason !== \"string\") {\n invalid(\"beforeToolCall\", \"returned ask with a reason that is not a string\");\n }\n if (\n policyVersion !== undefined &&\n (typeof policyVersion !== \"string\" || policyVersion === \"\" || !policyVersion.isWellFormed())\n ) {\n invalid(\"beforeToolCall\", \"returned ask with a policyVersion that is not a non-empty, well-formed string\");\n }\n}\n\n/** Checks `beforeToolCall`'s decision. */\nexport function checkDecision(value: unknown): GateDecision {\n if (!isObject(value)) invalid(\"beforeToolCall\", \"must return a decision: allow, deny or ask\");\n const { decision, reason } = value;\n if (decision !== \"allow\" && decision !== \"deny\" && decision !== \"ask\") {\n invalid(\"beforeToolCall\", `returned the decision ${JSON.stringify(decision)}; it must be allow, deny or ask`);\n }\n if (decision === \"deny\" && typeof reason !== \"string\") invalid(\"beforeToolCall\", \"returned deny without a reason\");\n if (decision === \"ask\") checkAsk(value);\n return value as unknown as GateDecision;\n}\n\n/** Checks `afterToolCall`'s patch. */\nexport function checkResultPatch(value: unknown): Record<string, unknown> | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) invalid(\"afterToolCall\", \"must return a patch object or nothing\");\n if (\"outcome\" in value) invalid(\"afterToolCall\", \"returned an outcome; replace content instead\");\n for (const flag of [\"isError\", \"terminate\"] as const) {\n if (value[flag] !== undefined && typeof value[flag] !== \"boolean\") {\n invalid(\"afterToolCall\", `returned ${flag} that is not a boolean`);\n }\n }\n return value;\n}\n\n/** What the run does after `shouldStop`. */\nexport type StopVerdict =\n | { readonly kind: \"none\" }\n | { readonly kind: \"stop\"; readonly stoppedBy: string }\n | { readonly kind: \"no_progress\"; readonly reason: string }\n | { readonly kind: \"continue\"; readonly content: ContentBlock[] };\n\n// The continue content becomes a user message in the transcript, so a malformed block would fail a later request far\n// from the hook that returned it.\nfunction continueContent(value: string | readonly ContentBlock[]): ContentBlock[] {\n if (typeof value === \"string\") return [{ type: \"text\", text: value }];\n if (!isContentList(value)) {\n invalid(\"shouldStop\", \"returned a continue that is neither text nor a list of text and image blocks\");\n }\n return [...value];\n}\n\n/** Checks `shouldStop`'s decision and turns it into a verdict. */\nexport function checkStopDecision(value: unknown): StopVerdict {\n if (value === true) return { kind: \"stop\", stoppedBy: \"hook\" };\n if (value === false) return { kind: \"none\" };\n if (!isObject(value)) invalid(\"shouldStop\", \"must return a boolean, { continue } or { stop, reason }\");\n const decision = value as Exclude<StopDecision, boolean>;\n if (\"continue\" in decision) return { kind: \"continue\", content: continueContent(decision.continue) };\n if (typeof decision.reason !== \"string\" || (decision.stop !== \"hook\" && decision.stop !== \"no_progress\")) {\n invalid(\"shouldStop\", 'returned a stop that is not { stop: \"hook\" | \"no_progress\", reason }');\n }\n return decision.stop === \"hook\"\n ? { kind: \"stop\", stoppedBy: decision.reason }\n : { kind: \"no_progress\", reason: decision.reason };\n}\n"]}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs the interceptors for one run: builds each hook's frozen event, applies the failure policy, checks what the
|
|
3
|
+
* hook returned and emits `hook_error` and `context_transformed`. The loop and the tool pipeline call it at each
|
|
4
|
+
* moment and never look at the hooks themselves.
|
|
5
|
+
*
|
|
6
|
+
* Failure policy (D6): a hook that throws is reported as a `hook_error` event. Under `fail_closed`, the default, a
|
|
7
|
+
* failed gate denies its call, a failed `afterToolCall` withholds the result, and any other failed hook throws a
|
|
8
|
+
* `HookFailure`, which the loop turns into an `error` result. Under `continue` the failed hook is skipped.
|
|
9
|
+
*
|
|
10
|
+
* A gate's `ask` pauses its call (D5): the runner signs a pending request through the one signing path, over the
|
|
11
|
+
* input the call would run with, and hands the request and that input to the pipeline, which reports the pause once
|
|
12
|
+
* every call of the step has been gated. Under `blockingApprovals()` the runner instead emits the request, waits for
|
|
13
|
+
* the handler's answer, checks it against the request, and allows or denies the call. A tool's clarification question
|
|
14
|
+
* is signed through the same path. A pause that can't be signed never pauses unsigned: the call is blocked instead,
|
|
15
|
+
* whatever `onFailure` says.
|
|
16
|
+
*/
|
|
17
|
+
import type { AssistantMessage, Message, ModelContext, ModelRef, Usage } from "@buildanagent/gateway";
|
|
18
|
+
import { SdkError } from "./errors.js";
|
|
19
|
+
import type { AgentEventBody } from "./events.js";
|
|
20
|
+
import { type StopVerdict } from "./hook-checks.js";
|
|
21
|
+
import type { CallOptions, Interceptors, ModelCallPatch } from "./hooks.js";
|
|
22
|
+
import type { Clock } from "./testing/determinism.js";
|
|
23
|
+
import { type GateOutcome, type PipelineContext } from "./tools/pipeline.js";
|
|
24
|
+
import type { ToolCall, ToolResult } from "./tools/types.js";
|
|
25
|
+
import type { ApprovalSigner } from "./vendor/agent-safety/signer.js";
|
|
26
|
+
/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */
|
|
27
|
+
export declare class HookFailure extends SdkError {
|
|
28
|
+
readonly name = "HookFailure";
|
|
29
|
+
readonly hook: string;
|
|
30
|
+
constructor(hook: string, cause: unknown);
|
|
31
|
+
}
|
|
32
|
+
/** What a run gives its hook runner. */
|
|
33
|
+
export interface HookRunnerSetup {
|
|
34
|
+
readonly interceptors: Interceptors;
|
|
35
|
+
readonly runId: string;
|
|
36
|
+
readonly signal: AbortSignal;
|
|
37
|
+
readonly clock: Clock;
|
|
38
|
+
/** The index of the model call in progress. */
|
|
39
|
+
stepIndex(): number;
|
|
40
|
+
send(body: AgentEventBody): void;
|
|
41
|
+
/** Signs the pending request a gate's `ask` writes. */
|
|
42
|
+
readonly signer: ApprovalSigner;
|
|
43
|
+
/** Makes each pending request's id. */
|
|
44
|
+
readonly nextId: () => string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A resolution's optional `reason` or `by`, kept only when it is a string. A resolution comes unchecked from the
|
|
48
|
+
* host's store or handler, so any other value is dropped rather than shown to the model as `null` or `[object Object]`.
|
|
49
|
+
*/
|
|
50
|
+
export declare function textOf(value: unknown): string | undefined;
|
|
51
|
+
/** The error result of a call a person denied, with their reason when they gave one. */
|
|
52
|
+
export declare function denied(tool: string, reason: string | undefined, requestId: string, by: string | undefined): ToolResult;
|
|
53
|
+
/** The pipeline hooks that the interceptors fill, left out when no interceptor needs them. */
|
|
54
|
+
export type PipelineHooks = Pick<PipelineContext, "gate" | "after">;
|
|
55
|
+
/** Runs one run's interceptors. */
|
|
56
|
+
export declare class HookRunner {
|
|
57
|
+
#private;
|
|
58
|
+
constructor(setup: HookRunnerSetup);
|
|
59
|
+
/**
|
|
60
|
+
* Marks request ids that already wait in the context a `continueRun()` started from, so a request this run signs
|
|
61
|
+
* never takes one of them.
|
|
62
|
+
*/
|
|
63
|
+
reserveRequestIds(ids: Iterable<string>): void;
|
|
64
|
+
/**
|
|
65
|
+
* The gate `continueRun()` puts in front of a call whose stored request failed its check: the run's own gate is
|
|
66
|
+
* asked as for a new call, but the call never runs. A deny still blocks it and an `ask` pauses it as usual, and an
|
|
67
|
+
* `allow`, or no gate at all, pauses it too, with a new request over the input the gate allowed.
|
|
68
|
+
*/
|
|
69
|
+
reissueGate(): NonNullable<PipelineContext["gate"]>;
|
|
70
|
+
/**
|
|
71
|
+
* Signs the clarification request of a call whose tool asked the user `question`, over the input the tool ran
|
|
72
|
+
* with. A question that can't be signed blocks the call, as an approval does.
|
|
73
|
+
*/
|
|
74
|
+
clarify(call: ToolCall, input: unknown, question: string): Promise<GateOutcome>;
|
|
75
|
+
/** The gate and the after-hook, for the tool pipeline. */
|
|
76
|
+
pipelineHooks(): PipelineHooks;
|
|
77
|
+
/** The messages `transformContext` chose for this call, or undefined to send the transcript as it is. */
|
|
78
|
+
transformContext(input: {
|
|
79
|
+
system: string;
|
|
80
|
+
messages: readonly Message[];
|
|
81
|
+
model: ModelRef;
|
|
82
|
+
lastUsage: Usage | undefined;
|
|
83
|
+
}): Promise<Message[] | undefined>;
|
|
84
|
+
/** What `beforeModelCall` changed, if anything. */
|
|
85
|
+
beforeModelCall(input: {
|
|
86
|
+
context: ModelContext;
|
|
87
|
+
options: CallOptions;
|
|
88
|
+
}): Promise<ModelCallPatch | undefined>;
|
|
89
|
+
/** The response the run goes on with: `afterModelCall`'s replacement, or `message` itself. */
|
|
90
|
+
afterModelCall(message: AssistantMessage): Promise<AssistantMessage>;
|
|
91
|
+
/** What `shouldStop` decided. */
|
|
92
|
+
shouldStop(input: {
|
|
93
|
+
messages: readonly Message[];
|
|
94
|
+
lastMessage: AssistantMessage;
|
|
95
|
+
}): Promise<StopVerdict>;
|
|
96
|
+
}
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { isSdkError, SdkError } from "./errors.js";
|
|
2
|
+
import { frozenCopy, thawedCopy } from "./freeze.js";
|
|
3
|
+
import { checkDecision, checkMessages, checkModelPatch, checkReplacement, checkResultPatch, checkStopDecision, } from "./hook-checks.js";
|
|
4
|
+
import { blockingHandlerOf, signPause } from "./pauses.js";
|
|
5
|
+
import { preparedSchemaOf } from "./tools/define.js";
|
|
6
|
+
import { isContentList } from "./tools/pipeline.js";
|
|
7
|
+
import { isSafetyError } from "./vendor/agent-safety/errors.js";
|
|
8
|
+
import { verifyResolution, } from "./vendor/agent-safety/pending.js";
|
|
9
|
+
/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */
|
|
10
|
+
export class HookFailure extends SdkError {
|
|
11
|
+
name = "HookFailure";
|
|
12
|
+
hook;
|
|
13
|
+
constructor(hook, cause) {
|
|
14
|
+
super("hook_failed", `the ${hook} hook failed: ${messageOf(cause)}`, { cause });
|
|
15
|
+
this.hook = hook;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function messageOf(error) {
|
|
19
|
+
return error instanceof Error ? error.message : String(error);
|
|
20
|
+
}
|
|
21
|
+
/** The result of a call after `afterToolCall` returned `patch`, checked to still be one the model can read. */
|
|
22
|
+
function mergeResult(tool, result, patch) {
|
|
23
|
+
if (patch === undefined)
|
|
24
|
+
return result;
|
|
25
|
+
const merged = { ...result, ...patch };
|
|
26
|
+
if (!isContentList(merged.content)) {
|
|
27
|
+
throw new SdkError("invalid_hook_result", `afterToolCall for "${tool}" returned content that is not a list of text and image blocks`);
|
|
28
|
+
}
|
|
29
|
+
return merged;
|
|
30
|
+
}
|
|
31
|
+
function blocked(text, details) {
|
|
32
|
+
return { content: [{ type: "text", text }], isError: true, details };
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* A resolution's optional `reason` or `by`, kept only when it is a string. A resolution comes unchecked from the
|
|
36
|
+
* host's store or handler, so any other value is dropped rather than shown to the model as `null` or `[object Object]`.
|
|
37
|
+
*/
|
|
38
|
+
export function textOf(value) {
|
|
39
|
+
return typeof value === "string" ? value : undefined;
|
|
40
|
+
}
|
|
41
|
+
/** The error result of a call a person denied, with their reason when they gave one. */
|
|
42
|
+
export function denied(tool, reason, requestId, by) {
|
|
43
|
+
const text = reason === undefined || reason === ""
|
|
44
|
+
? `Tool call "${tool}" was denied by the approver.`
|
|
45
|
+
: `Tool call "${tool}" was denied: ${reason}`;
|
|
46
|
+
return blocked(text, { decision: "deny", requestId, ...(by === undefined ? {} : { by }) });
|
|
47
|
+
}
|
|
48
|
+
function gateOutcome(tool, decision) {
|
|
49
|
+
if (decision.decision === "allow")
|
|
50
|
+
return decision.input === undefined ? undefined : { input: thawedCopy(decision.input) };
|
|
51
|
+
return { blocked: blocked(`Tool call "${tool}" was denied: ${decision.reason}`, { decision: "deny" }) };
|
|
52
|
+
}
|
|
53
|
+
const SAFETY_CODES = [
|
|
54
|
+
"invalid_outcome",
|
|
55
|
+
"invalid_input",
|
|
56
|
+
"invalid_key_ring",
|
|
57
|
+
"invalid_pending",
|
|
58
|
+
];
|
|
59
|
+
/**
|
|
60
|
+
* Why a pause could not be signed, as reports may show it: one of the safety package's error codes, or a fixed word.
|
|
61
|
+
* A custom signer's own text is never passed on, because nothing stops it from quoting key material, and that holds
|
|
62
|
+
* for a `code` too: any object can carry the safety error's marker, so only a known code is trusted.
|
|
63
|
+
*/
|
|
64
|
+
function unsignedCause(error) {
|
|
65
|
+
return isSafetyError(error) && SAFETY_CODES.includes(error.code) ? error.code : "signer_failed";
|
|
66
|
+
}
|
|
67
|
+
/** The reason a request carries when `continueRun()` asks again for a call whose earlier request failed its check. */
|
|
68
|
+
const REISSUED_REASON = "The earlier request for this call could not be verified, so it needs a new answer.";
|
|
69
|
+
/** Resolves to `ABORTED` once `signal` fires, or to what `promise` resolves to if that comes first. */
|
|
70
|
+
const ABORTED = Symbol("aborted");
|
|
71
|
+
async function unlessAborted(promise, signal) {
|
|
72
|
+
let stop;
|
|
73
|
+
const aborted = new Promise((resolve) => {
|
|
74
|
+
stop = () => resolve(ABORTED);
|
|
75
|
+
if (signal.aborted)
|
|
76
|
+
stop();
|
|
77
|
+
else
|
|
78
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
79
|
+
});
|
|
80
|
+
try {
|
|
81
|
+
return await Promise.race([promise, aborted]);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
if (stop !== undefined)
|
|
85
|
+
signal.removeEventListener("abort", stop);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** Runs one run's interceptors. */
|
|
89
|
+
export class HookRunner {
|
|
90
|
+
#setup;
|
|
91
|
+
#hooks;
|
|
92
|
+
#continues;
|
|
93
|
+
#requestIds = new Set();
|
|
94
|
+
#blocking;
|
|
95
|
+
constructor(setup) {
|
|
96
|
+
this.#setup = setup;
|
|
97
|
+
this.#hooks = setup.interceptors;
|
|
98
|
+
this.#continues = setup.interceptors.onFailure === "continue";
|
|
99
|
+
this.#blocking = blockingHandlerOf(setup.interceptors);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Marks request ids that already wait in the context a `continueRun()` started from, so a request this run signs
|
|
103
|
+
* never takes one of them.
|
|
104
|
+
*/
|
|
105
|
+
reserveRequestIds(ids) {
|
|
106
|
+
for (const id of ids)
|
|
107
|
+
this.#requestIds.add(id);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The gate `continueRun()` puts in front of a call whose stored request failed its check: the run's own gate is
|
|
111
|
+
* asked as for a new call, but the call never runs. A deny still blocks it and an `ask` pauses it as usual, and an
|
|
112
|
+
* `allow`, or no gate at all, pauses it too, with a new request over the input the gate allowed.
|
|
113
|
+
*/
|
|
114
|
+
reissueGate() {
|
|
115
|
+
return async (e) => {
|
|
116
|
+
// A call asked again never blocks on a handler: its new request is returned with the context.
|
|
117
|
+
const outcome = this.#hooks.beforeToolCall === undefined ? undefined : await this.#gate(e, false);
|
|
118
|
+
if (outcome !== undefined && ("blocked" in outcome || "paused" in outcome))
|
|
119
|
+
return outcome;
|
|
120
|
+
const input = outcome === undefined ? e.input : outcome.input;
|
|
121
|
+
return this.#sign(e.tool.name, { kind: "approval", callId: e.call.callId, tool: e.tool.name, input, reason: REISSUED_REASON }, input);
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Signs the clarification request of a call whose tool asked the user `question`, over the input the tool ran
|
|
126
|
+
* with. A question that can't be signed blocks the call, as an approval does.
|
|
127
|
+
*/
|
|
128
|
+
clarify(call, input, question) {
|
|
129
|
+
return this.#sign(call.name, { kind: "clarification", callId: call.callId, tool: call.name, input, question }, input);
|
|
130
|
+
}
|
|
131
|
+
/** The gate and the after-hook, for the tool pipeline. */
|
|
132
|
+
pipelineHooks() {
|
|
133
|
+
return {
|
|
134
|
+
...(this.#hooks.beforeToolCall === undefined ? {} : { gate: (e) => this.#gate(e) }),
|
|
135
|
+
...(this.#hooks.afterToolCall === undefined ? {} : { after: (e) => this.#afterTool(e) }),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/** The messages `transformContext` chose for this call, or undefined to send the transcript as it is. */
|
|
139
|
+
async transformContext(input) {
|
|
140
|
+
const hook = this.#hooks.transformContext;
|
|
141
|
+
if (hook === undefined)
|
|
142
|
+
return undefined;
|
|
143
|
+
const { lastUsage, ...rest } = input;
|
|
144
|
+
const event = this.#event({ ...rest, ...(lastUsage === undefined ? {} : { lastUsage }) });
|
|
145
|
+
const guarded = await this.#guard("transformContext", () => hook(event));
|
|
146
|
+
if (guarded.status !== "ok")
|
|
147
|
+
return undefined;
|
|
148
|
+
const messages = checkMessages("transformContext", guarded.value);
|
|
149
|
+
this.#setup.send({ type: "context_transformed", before: input.messages.length, after: messages.length });
|
|
150
|
+
return messages;
|
|
151
|
+
}
|
|
152
|
+
/** What `beforeModelCall` changed, if anything. */
|
|
153
|
+
async beforeModelCall(input) {
|
|
154
|
+
const hook = this.#hooks.beforeModelCall;
|
|
155
|
+
if (hook === undefined)
|
|
156
|
+
return undefined;
|
|
157
|
+
const event = this.#event(input);
|
|
158
|
+
const guarded = await this.#guard("beforeModelCall", () => hook(event));
|
|
159
|
+
return guarded.status === "ok" ? checkModelPatch(guarded.value) : undefined;
|
|
160
|
+
}
|
|
161
|
+
/** The response the run goes on with: `afterModelCall`'s replacement, or `message` itself. */
|
|
162
|
+
async afterModelCall(message) {
|
|
163
|
+
const hook = this.#hooks.afterModelCall;
|
|
164
|
+
if (hook === undefined)
|
|
165
|
+
return message;
|
|
166
|
+
const event = this.#event({ message });
|
|
167
|
+
const guarded = await this.#guard("afterModelCall", () => hook(event));
|
|
168
|
+
return (guarded.status === "ok" ? checkReplacement(guarded.value) : undefined) ?? message;
|
|
169
|
+
}
|
|
170
|
+
/** What `shouldStop` decided. */
|
|
171
|
+
async shouldStop(input) {
|
|
172
|
+
const hook = this.#hooks.shouldStop;
|
|
173
|
+
if (hook === undefined)
|
|
174
|
+
return { kind: "none" };
|
|
175
|
+
const event = this.#event(input);
|
|
176
|
+
const guarded = await this.#guard("shouldStop", () => hook(event));
|
|
177
|
+
return guarded.status === "ok" ? checkStopDecision(guarded.value) : { kind: "none" };
|
|
178
|
+
}
|
|
179
|
+
async #gate(input, block = true) {
|
|
180
|
+
const hook = this.#hooks.beforeToolCall;
|
|
181
|
+
if (hook === undefined)
|
|
182
|
+
return undefined;
|
|
183
|
+
const { call, tool } = input;
|
|
184
|
+
const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input }, call.callId);
|
|
185
|
+
const failed = (error) => ({
|
|
186
|
+
blocked: blocked(`Tool call "${tool.name}" was not run, because its permission check failed.`, {
|
|
187
|
+
hook: "beforeToolCall",
|
|
188
|
+
error: messageOf(error),
|
|
189
|
+
}),
|
|
190
|
+
});
|
|
191
|
+
const guarded = await this.#guard("beforeToolCall", () => hook(event), failed);
|
|
192
|
+
if (guarded.status === "skipped")
|
|
193
|
+
return undefined;
|
|
194
|
+
if (guarded.status === "closed")
|
|
195
|
+
return guarded.value;
|
|
196
|
+
const decision = checkDecision(guarded.value);
|
|
197
|
+
return decision.decision === "ask"
|
|
198
|
+
? this.#pause(call, tool, input.input, decision, block)
|
|
199
|
+
: gateOutcome(tool.name, decision);
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Signs the pending request for a call a gate asked about and returns it with the input it signs. That input is the
|
|
203
|
+
* one the call would run with: the checked input the gate saw, or the `ask`'s own replacement, which must pass the
|
|
204
|
+
* tool's schema like an `allow`'s. If signing fails, the call is blocked: a pause that no signature covers is never
|
|
205
|
+
* written. Under `blockingApprovals()`, the request is emitted and answered here instead.
|
|
206
|
+
*/
|
|
207
|
+
async #pause(call, tool, seen, decision, block) {
|
|
208
|
+
const { reason, policyVersion } = decision;
|
|
209
|
+
const input = thawedCopy(decision.input === undefined ? seen : await this.#replacement(tool, decision.input));
|
|
210
|
+
const fields = {
|
|
211
|
+
kind: "approval",
|
|
212
|
+
callId: call.callId,
|
|
213
|
+
tool: tool.name,
|
|
214
|
+
input,
|
|
215
|
+
...(policyVersion === undefined ? {} : { policyVersion }),
|
|
216
|
+
// Display text only, so a blank reason is left out rather than failing the signature.
|
|
217
|
+
...(reason === undefined || reason === "" ? {} : { reason }),
|
|
218
|
+
};
|
|
219
|
+
const outcome = await this.#sign(tool.name, fields, input);
|
|
220
|
+
if (!block || this.#blocking === undefined || !("paused" in outcome))
|
|
221
|
+
return outcome;
|
|
222
|
+
return this.#waitFor(this.#blocking, call, tool.name, outcome.paused, input, decision.input === undefined);
|
|
223
|
+
}
|
|
224
|
+
/** Signs one pending request through the one signing path, or blocks the call when it can't be signed. */
|
|
225
|
+
async #sign(tool, fields, input) {
|
|
226
|
+
const { signer, clock } = this.#setup;
|
|
227
|
+
let request;
|
|
228
|
+
try {
|
|
229
|
+
request = await signPause(fields, signer, {
|
|
230
|
+
generateId: () => this.#requestId(),
|
|
231
|
+
now: () => new Date(clock.now()),
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
return this.#unsigned(tool, unsignedCause(error));
|
|
236
|
+
}
|
|
237
|
+
// A resolution names its request by id, so two pending requests of one run must never share one.
|
|
238
|
+
if (this.#requestIds.has(request.id))
|
|
239
|
+
return this.#unsigned(tool, "duplicate_request_id");
|
|
240
|
+
this.#requestIds.add(request.id);
|
|
241
|
+
return { paused: request, input };
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* The blocking form of a pause: emit the signed request, wait for the handler, and check its answer against the
|
|
245
|
+
* request before the call may run. Every failure denies the call; nothing here lets it run unanswered.
|
|
246
|
+
*/
|
|
247
|
+
async #waitFor(handler, call, tool, request, input, unchanged) {
|
|
248
|
+
const { signal, signer } = this.#setup;
|
|
249
|
+
this.#setup.send({ type: "approval_request", request, input });
|
|
250
|
+
const refuse = (why, error) => {
|
|
251
|
+
this.#setup.send({ type: "hook_error", hook: "blockingApprovals", error });
|
|
252
|
+
return {
|
|
253
|
+
blocked: blocked(`Tool call "${tool}" was not run, because ${why}.`, {
|
|
254
|
+
decision: "ask",
|
|
255
|
+
requestId: request.id,
|
|
256
|
+
}),
|
|
257
|
+
};
|
|
258
|
+
};
|
|
259
|
+
let answer;
|
|
260
|
+
try {
|
|
261
|
+
answer = await unlessAborted(Promise.resolve(handler(request, Object.freeze({ input, signal }))), signal);
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
return refuse("its approval handler failed", messageOf(error));
|
|
265
|
+
}
|
|
266
|
+
if (answer === ABORTED) {
|
|
267
|
+
const text = `Tool call "${tool}" was not run, because the run was aborted while it waited for approval.`;
|
|
268
|
+
return { blocked: blocked(text, { decision: "ask", requestId: request.id }) };
|
|
269
|
+
}
|
|
270
|
+
let check;
|
|
271
|
+
try {
|
|
272
|
+
check = await verifyResolution(request, answer, {
|
|
273
|
+
signer,
|
|
274
|
+
call: { callId: call.callId, tool, input },
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
// A custom signer whose verify() throws fails the check; its message may hold anything, so it isn't passed on.
|
|
279
|
+
return refuse("its approval could not be verified", "the approval was refused (error)");
|
|
280
|
+
}
|
|
281
|
+
if (!check.ok)
|
|
282
|
+
return refuse("its approval could not be verified", `the approval was refused (${check.cause})`);
|
|
283
|
+
const resolution = check.resolution;
|
|
284
|
+
// An unchanged input is the checked one the gate saw, which the pipeline runs as it is; a replacement is passed on.
|
|
285
|
+
if ("decision" in resolution && resolution.decision === "allow")
|
|
286
|
+
return unchanged ? undefined : { input };
|
|
287
|
+
const reason = "reason" in resolution ? textOf(resolution.reason) : undefined;
|
|
288
|
+
return { blocked: denied(tool, reason, request.id, textOf(resolution.by)) };
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* The next request id from the run's `idGenerator`. A generator that repeats an id, such as one that always returns
|
|
292
|
+
* a session id, was enough for a run id alone, so a repeat of the run id or of an earlier request's id falls back to
|
|
293
|
+
* a random UUID instead of blocking the call.
|
|
294
|
+
*/
|
|
295
|
+
#requestId() {
|
|
296
|
+
const id = this.#setup.nextId();
|
|
297
|
+
return id === this.#setup.runId || this.#requestIds.has(id) ? globalThis.crypto.randomUUID() : id;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* An `ask`'s replacement input, checked against the tool's schema, because a call must never run with input its own
|
|
301
|
+
* tool would reject.
|
|
302
|
+
*/
|
|
303
|
+
async #replacement(tool, input) {
|
|
304
|
+
const checked = await preparedSchemaOf(tool).validate(input);
|
|
305
|
+
if (checked.ok)
|
|
306
|
+
return checked.value;
|
|
307
|
+
const issues = checked.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ");
|
|
308
|
+
throw new SdkError("invalid_hook_result", `beforeToolCall asked about tool "${tool.name}" with an input its schema rejects: ${issues}`);
|
|
309
|
+
}
|
|
310
|
+
/** Blocks a call whose pause could not be signed, and reports why without the signer's own message. */
|
|
311
|
+
#unsigned(tool, cause) {
|
|
312
|
+
this.#setup.send({
|
|
313
|
+
type: "hook_error",
|
|
314
|
+
hook: "signer",
|
|
315
|
+
error: `the approval request could not be signed (${cause})`,
|
|
316
|
+
});
|
|
317
|
+
const text = `Tool call "${tool}" needs approval, but its approval request could not be signed, so it was not run.`;
|
|
318
|
+
return { blocked: blocked(text, { decision: "ask", error: cause }) };
|
|
319
|
+
}
|
|
320
|
+
async #afterTool(input) {
|
|
321
|
+
const hook = this.#hooks.afterToolCall;
|
|
322
|
+
const { call, tool, result } = input;
|
|
323
|
+
if (hook === undefined)
|
|
324
|
+
return result;
|
|
325
|
+
const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input, result }, call.callId);
|
|
326
|
+
// The tool already ran, so the stand-in says so and keeps the write outcome: a model told only "withheld" would
|
|
327
|
+
// retry a write that was applied.
|
|
328
|
+
const withheld = (error) => ({
|
|
329
|
+
...blocked(`Tool call "${tool.name}" ran, but its result was withheld, because its result check failed.`, {
|
|
330
|
+
hook: "afterToolCall",
|
|
331
|
+
error: messageOf(error),
|
|
332
|
+
}),
|
|
333
|
+
...(result.outcome === undefined ? {} : { outcome: result.outcome }),
|
|
334
|
+
});
|
|
335
|
+
const guarded = await this.#guard("afterToolCall", () => hook(event), withheld);
|
|
336
|
+
if (guarded.status === "skipped")
|
|
337
|
+
return result;
|
|
338
|
+
return guarded.status === "closed"
|
|
339
|
+
? guarded.value
|
|
340
|
+
: mergeResult(tool.name, result, checkResultPatch(guarded.value));
|
|
341
|
+
}
|
|
342
|
+
#event(payload, callId) {
|
|
343
|
+
const { runId, signal, clock } = this.#setup;
|
|
344
|
+
return Object.freeze({
|
|
345
|
+
runId,
|
|
346
|
+
stepIndex: this.#setup.stepIndex(),
|
|
347
|
+
...(callId === undefined ? {} : { callId }),
|
|
348
|
+
signal,
|
|
349
|
+
timestamp: clock.now(),
|
|
350
|
+
...frozenCopy(payload),
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
/** Calls a hook under the failure policy. Without `closed`, a failure under `fail_closed` throws a `HookFailure`. */
|
|
354
|
+
async #guard(hook, call, closed) {
|
|
355
|
+
try {
|
|
356
|
+
return { status: "ok", value: await call() };
|
|
357
|
+
}
|
|
358
|
+
catch (error) {
|
|
359
|
+
// A wrong return shape is a programmer error whatever the policy, even when a joined hook found it inside
|
|
360
|
+
// `composeInterceptors()`: skipping or closing on it would let a typo in a gate pass silently.
|
|
361
|
+
if (isSdkError(error) && error.code === "invalid_hook_result")
|
|
362
|
+
throw error;
|
|
363
|
+
this.#setup.send({ type: "hook_error", hook, error: messageOf(error) });
|
|
364
|
+
if (this.#continues)
|
|
365
|
+
return { status: "skipped" };
|
|
366
|
+
if (closed === undefined)
|
|
367
|
+
throw new HookFailure(hook, error);
|
|
368
|
+
return { status: "closed", value: closed(error) };
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
//# sourceMappingURL=hook-runner.js.map
|