@buildanagent/sdk 0.1.0-alpha.4 → 0.1.0-alpha.6
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 +115 -7
- 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 +22 -0
- package/dist/compose.js +137 -0
- package/dist/compose.js.map +1 -0
- package/dist/errors.d.ts +7 -2
- package/dist/errors.js +6 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +22 -2
- package/dist/events.js +2 -0
- package/dist/events.js.map +1 -1
- 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 +113 -0
- package/dist/hook-checks.js.map +1 -0
- package/dist/hook-runner.d.ts +60 -0
- package/dist/hook-runner.js +169 -0
- package/dist/hook-runner.js.map +1 -0
- package/dist/hooks.d.ts +177 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +10 -4
- package/dist/index.js +9 -3
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +26 -8
- package/dist/loop.js +241 -35
- package/dist/loop.js.map +1 -1
- package/dist/observers.d.ts +31 -0
- package/dist/observers.js +98 -0
- package/dist/observers.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 +28 -5
- package/dist/result.js.map +1 -1
- package/dist/run.d.ts +69 -5
- package/dist/run.js +125 -7
- package/dist/run.js.map +1 -1
- package/dist/tools/define.d.ts +3 -3
- package/dist/tools/define.js +6 -3
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/pipeline.d.ts +29 -7
- package/dist/tools/pipeline.js +48 -14
- package/dist/tools/pipeline.js.map +1 -1
- package/dist/tools/types.d.ts +10 -2
- package/dist/tools/types.js.map +1 -1
- package/dist/vendor/agent-safety/hash.d.ts +16 -0
- package/dist/vendor/agent-safety/hash.js +109 -0
- package/dist/vendor/agent-safety/hash.js.map +1 -0
- package/package.json +2 -2
package/dist/events.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AA2FA,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7C,WAAW;IACX,YAAY;IACZ,kBAAkB;IAClB,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,iBAAiB;IACjB,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,gBAAgB;IAChB,SAAS;IACT,gBAAgB;IAChB,qBAAqB;IACrB,YAAY;IACZ,iBAAiB;IACjB,kBAAkB;IAClB,eAAe;IACf,UAAU;IACV,OAAO;IACP,OAAO;IACP,eAAe;IACf,SAAS;CACuC,CAAC,CAAC","sourcesContent":["/**\n * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content\n * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the\n * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can\n * check that the loop emits no type the union does not declare.\n */\nimport type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from \"@buildanagent/gateway\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */\nexport interface EventBase {\n readonly runId: string;\n readonly seq: number;\n readonly stepIndex: number;\n /** When the event was emitted, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** One model call's request as the loop sends it: the model, the context and the options. */\nexport interface ModelCallRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: DumpedOptions;\n}\n\n/**\n * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call\n * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.\n */\nexport type WarningCode = \"max_steps\" | \"model_warning\";\n\n/** The body of each event, without the fields of `EventBase`. */\nexport type AgentEventBody =\n | {\n readonly type: \"run_start\";\n readonly sdkVersion: string;\n readonly specVersion: \"v1\";\n /** Reserved for a hash of the run's defaults; empty for now. */\n readonly defaultsHash: string;\n /** Reserved for the SDK's capability names; empty for now. */\n readonly capabilities: readonly string[];\n readonly model: ModelRef;\n }\n | { readonly type: \"run_end\"; readonly result: RunResult }\n /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */\n | { readonly type: \"agent_settled\" }\n | { readonly type: \"step_start\" }\n | { readonly type: \"step_end\"; readonly stopCheck: \"continue\" | \"stop\" }\n | { readonly type: \"model_call_start\"; readonly request: ModelCallRequest }\n | { readonly type: \"model_call_end\"; readonly message: AssistantMessage }\n | { readonly type: \"text_start\" | \"reasoning_start\" | \"tool_input_start\"; readonly index: number }\n | {\n readonly type: \"text_delta\" | \"reasoning_delta\" | \"tool_input_delta\";\n readonly index: number;\n readonly delta: string;\n }\n | {\n readonly type: \"text_end\" | \"reasoning_end\" | \"tool_input_end\";\n readonly index: number;\n readonly block: ContentBlock;\n }\n | { readonly type: \"tool_call_start\"; readonly callId: string; readonly tool: string; readonly input: unknown }\n | { readonly type: \"tool_call_update\"; readonly callId: string; readonly details: unknown }\n /**\n * `result` is what the model reads for the call, after `afterToolCall` has had its say. `input` is present only\n * when a `beforeToolCall` gate replaced the model's input, and holds the input the gate gave the call instead.\n */\n | {\n readonly type: \"tool_call_end\";\n readonly callId: string;\n readonly result: ToolResult;\n readonly input?: unknown;\n }\n /** `transformContext` returned the messages for one model call: `before` messages in, `after` messages out. */\n | { readonly type: \"context_transformed\"; readonly before: number; readonly after: number }\n /** The model is retrying a failed request; `attempt` is 1 for the first retry. */\n | { readonly type: \"retry\"; readonly attempt: number; readonly delayMs: number; readonly error: string }\n /**\n * An interceptor or an observer threw. `hook` names it (`beforeToolCall`, `observer` and so on) and `error` is the\n * thrown message. The run goes on or fails by the interceptors' `onFailure` setting; a failed observer never\n * affects it.\n */\n | { readonly type: \"hook_error\"; readonly hook: string; readonly error: string }\n | { readonly type: \"warning\"; readonly code: WarningCode; readonly detail: string }\n | { readonly type: \"error\"; readonly error: RunError }\n | { readonly type: \"abort\"; readonly reason?: string };\n\n/** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */\nexport type AgentEvent = EventBase & AgentEventBody;\n\n/** Every `AgentEvent` type. A run emits no type this list lacks. */\nexport const AGENT_EVENT_TYPES = Object.freeze([\n \"run_start\",\n \"step_start\",\n \"model_call_start\",\n \"retry\",\n \"text_start\",\n \"text_delta\",\n \"text_end\",\n \"reasoning_start\",\n \"reasoning_delta\",\n \"reasoning_end\",\n \"tool_input_start\",\n \"tool_input_delta\",\n \"tool_input_end\",\n \"warning\",\n \"model_call_end\",\n \"context_transformed\",\n \"hook_error\",\n \"tool_call_start\",\n \"tool_call_update\",\n \"tool_call_end\",\n \"step_end\",\n \"error\",\n \"abort\",\n \"agent_settled\",\n \"run_end\",\n] as const satisfies readonly AgentEvent[\"type\"][]);\n"]}
|
package/dist/freeze.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Frozen copies of the data a hook receives, so a hook that mutates its input throws instead of changing the run's
|
|
3
|
+
* own transcript (agent-SDK guide §6, rule 2: a hook returns a replacement).
|
|
4
|
+
*/
|
|
5
|
+
/** A deep, frozen copy of the plain objects and arrays in `value`; other values are shared. */
|
|
6
|
+
export declare function frozenCopy<T>(value: T): T;
|
|
7
|
+
/**
|
|
8
|
+
* A deep, writable copy of the plain objects and arrays in `value`. A hook's event holds frozen copies, so an input a
|
|
9
|
+
* gate hands back from the event must be thawed before a tool runs with it, or a tool that edits its input throws.
|
|
10
|
+
*/
|
|
11
|
+
export declare function thawedCopy<T>(value: T): T;
|
package/dist/freeze.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Frozen copies of the data a hook receives, so a hook that mutates its input throws instead of changing the run's
|
|
3
|
+
* own transcript (agent-SDK guide §6, rule 2: a hook returns a replacement).
|
|
4
|
+
*/
|
|
5
|
+
function isPlain(value) {
|
|
6
|
+
const prototype = Object.getPrototypeOf(value);
|
|
7
|
+
return prototype === Object.prototype || prototype === null;
|
|
8
|
+
}
|
|
9
|
+
function copyOf(value, seen, freeze = true) {
|
|
10
|
+
if (typeof value !== "object" || value === null)
|
|
11
|
+
return value;
|
|
12
|
+
const known = seen.get(value);
|
|
13
|
+
if (known !== undefined)
|
|
14
|
+
return known;
|
|
15
|
+
if (Array.isArray(value)) {
|
|
16
|
+
const copy = [];
|
|
17
|
+
seen.set(value, copy);
|
|
18
|
+
for (const item of value)
|
|
19
|
+
copy.push(copyOf(item, seen, freeze));
|
|
20
|
+
return freeze ? Object.freeze(copy) : copy;
|
|
21
|
+
}
|
|
22
|
+
// A class instance, such as an `Error` in a result's details, is kept as it is: copying would lose its behaviour.
|
|
23
|
+
if (!isPlain(value))
|
|
24
|
+
return value;
|
|
25
|
+
const copy = {};
|
|
26
|
+
seen.set(value, copy);
|
|
27
|
+
for (const [key, item] of Object.entries(value))
|
|
28
|
+
copy[key] = copyOf(item, seen, freeze);
|
|
29
|
+
return freeze ? Object.freeze(copy) : copy;
|
|
30
|
+
}
|
|
31
|
+
/** A deep, frozen copy of the plain objects and arrays in `value`; other values are shared. */
|
|
32
|
+
export function frozenCopy(value) {
|
|
33
|
+
return copyOf(value, new WeakMap());
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A deep, writable copy of the plain objects and arrays in `value`. A hook's event holds frozen copies, so an input a
|
|
37
|
+
* gate hands back from the event must be thawed before a tool runs with it, or a tool that edits its input throws.
|
|
38
|
+
*/
|
|
39
|
+
export function thawedCopy(value) {
|
|
40
|
+
return copyOf(value, new WeakMap(), false);
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=freeze.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"freeze.js","sourceRoot":"","sources":["../src/freeze.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,SAAS,OAAO,CAAC,KAAa;IAC5B,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAC9D,CAAC;AAED,SAAS,MAAM,CAAC,KAAc,EAAE,IAA8B,EAAE,MAAM,GAAG,IAAI;IAC3E,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC9B,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IACtC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,GAAc,EAAE,CAAC;QAC3B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACtB,KAAK,MAAM,IAAI,IAAI,KAAK;YAAE,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;QAChE,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAC7C,CAAC;IACD,kHAAkH;IAClH,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAClC,MAAM,IAAI,GAA4B,EAAE,CAAC;IACzC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACtB,KAAK,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,IAAI,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IACxF,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC7C,CAAC;AAED,+FAA+F;AAC/F,MAAM,UAAU,UAAU,CAAI,KAAQ;IACpC,OAAO,MAAM,CAAC,KAAK,EAAE,IAAI,OAAO,EAAE,CAAM,CAAC;AAC3C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAI,KAAQ;IACpC,OAAO,MAAM,CAAC,KAAK,EAAE,IAAI,OAAO,EAAE,EAAE,KAAK,CAAM,CAAC;AAClD,CAAC","sourcesContent":["/**\n * Frozen copies of the data a hook receives, so a hook that mutates its input throws instead of changing the run's\n * own transcript (agent-SDK guide §6, rule 2: a hook returns a replacement).\n */\n\nfunction isPlain(value: object): boolean {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction copyOf(value: unknown, seen: WeakMap<object, unknown>, freeze = true): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const known = seen.get(value);\n if (known !== undefined) return known;\n if (Array.isArray(value)) {\n const copy: unknown[] = [];\n seen.set(value, copy);\n for (const item of value) copy.push(copyOf(item, seen, freeze));\n return freeze ? Object.freeze(copy) : copy;\n }\n // A class instance, such as an `Error` in a result's details, is kept as it is: copying would lose its behaviour.\n if (!isPlain(value)) return value;\n const copy: Record<string, unknown> = {};\n seen.set(value, copy);\n for (const [key, item] of Object.entries(value)) copy[key] = copyOf(item, seen, freeze);\n return freeze ? Object.freeze(copy) : copy;\n}\n\n/** A deep, frozen copy of the plain objects and arrays in `value`; other values are shared. */\nexport function frozenCopy<T>(value: T): T {\n return copyOf(value, new WeakMap()) as T;\n}\n\n/**\n * A deep, writable copy of the plain objects and arrays in `value`. A hook's event holds frozen copies, so an input a\n * gate hands back from the event must be thawed before a tool runs with it, or a tool that edits its input throws.\n */\nexport function thawedCopy<T>(value: T): T {\n return copyOf(value, new WeakMap(), false) as T;\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks on what an interceptor returned. A hook that returns the wrong shape is a programmer error, so each check
|
|
3
|
+
* throws an `SdkError` with code `invalid_hook_result` rather than failing closed: a typo in a gate must be loud.
|
|
4
|
+
*/
|
|
5
|
+
import type { AssistantMessage, ContentBlock, Message } from "@buildanagent/gateway";
|
|
6
|
+
import type { GateDecision, ModelCallPatch } from "./hooks.js";
|
|
7
|
+
/** Checks a list of messages and returns a copy of it. */
|
|
8
|
+
export declare function checkMessages(hook: string, value: unknown): Message[];
|
|
9
|
+
/** Checks `beforeModelCall`'s return value: nothing, or a patch of well-formed fields. */
|
|
10
|
+
export declare function checkModelPatch(value: unknown): ModelCallPatch | undefined;
|
|
11
|
+
/** Checks `afterModelCall`'s return value and returns the replacement message, if there is one. */
|
|
12
|
+
export declare function checkReplacement(value: unknown): AssistantMessage | undefined;
|
|
13
|
+
/** Checks `beforeToolCall`'s decision. */
|
|
14
|
+
export declare function checkDecision(value: unknown): GateDecision;
|
|
15
|
+
/** Checks `afterToolCall`'s patch. */
|
|
16
|
+
export declare function checkResultPatch(value: unknown): Record<string, unknown> | undefined;
|
|
17
|
+
/** What the run does after `shouldStop`. */
|
|
18
|
+
export type StopVerdict = {
|
|
19
|
+
readonly kind: "none";
|
|
20
|
+
} | {
|
|
21
|
+
readonly kind: "stop";
|
|
22
|
+
readonly stoppedBy: string;
|
|
23
|
+
} | {
|
|
24
|
+
readonly kind: "no_progress";
|
|
25
|
+
readonly reason: string;
|
|
26
|
+
} | {
|
|
27
|
+
readonly kind: "continue";
|
|
28
|
+
readonly content: ContentBlock[];
|
|
29
|
+
};
|
|
30
|
+
/** Checks `shouldStop`'s decision and turns it into a verdict. */
|
|
31
|
+
export declare function checkStopDecision(value: unknown): StopVerdict;
|
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+
/** Checks `beforeToolCall`'s decision. */
|
|
59
|
+
export function checkDecision(value) {
|
|
60
|
+
if (!isObject(value))
|
|
61
|
+
invalid("beforeToolCall", "must return a decision: allow, deny or ask");
|
|
62
|
+
const { decision, reason } = value;
|
|
63
|
+
if (decision !== "allow" && decision !== "deny" && decision !== "ask") {
|
|
64
|
+
invalid("beforeToolCall", `returned the decision ${JSON.stringify(decision)}; it must be allow, deny or ask`);
|
|
65
|
+
}
|
|
66
|
+
if (decision === "deny" && typeof reason !== "string")
|
|
67
|
+
invalid("beforeToolCall", "returned deny without a reason");
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
/** Checks `afterToolCall`'s patch. */
|
|
71
|
+
export function checkResultPatch(value) {
|
|
72
|
+
if (value === undefined)
|
|
73
|
+
return undefined;
|
|
74
|
+
if (!isObject(value))
|
|
75
|
+
invalid("afterToolCall", "must return a patch object or nothing");
|
|
76
|
+
if ("outcome" in value)
|
|
77
|
+
invalid("afterToolCall", "returned an outcome; replace content instead");
|
|
78
|
+
for (const flag of ["isError", "terminate"]) {
|
|
79
|
+
if (value[flag] !== undefined && typeof value[flag] !== "boolean") {
|
|
80
|
+
invalid("afterToolCall", `returned ${flag} that is not a boolean`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
// The continue content becomes a user message in the transcript, so a malformed block would fail a later request far
|
|
86
|
+
// from the hook that returned it.
|
|
87
|
+
function continueContent(value) {
|
|
88
|
+
if (typeof value === "string")
|
|
89
|
+
return [{ type: "text", text: value }];
|
|
90
|
+
if (!isContentList(value)) {
|
|
91
|
+
invalid("shouldStop", "returned a continue that is neither text nor a list of text and image blocks");
|
|
92
|
+
}
|
|
93
|
+
return [...value];
|
|
94
|
+
}
|
|
95
|
+
/** Checks `shouldStop`'s decision and turns it into a verdict. */
|
|
96
|
+
export function checkStopDecision(value) {
|
|
97
|
+
if (value === true)
|
|
98
|
+
return { kind: "stop", stoppedBy: "hook" };
|
|
99
|
+
if (value === false)
|
|
100
|
+
return { kind: "none" };
|
|
101
|
+
if (!isObject(value))
|
|
102
|
+
invalid("shouldStop", "must return a boolean, { continue } or { stop, reason }");
|
|
103
|
+
const decision = value;
|
|
104
|
+
if ("continue" in decision)
|
|
105
|
+
return { kind: "continue", content: continueContent(decision.continue) };
|
|
106
|
+
if (typeof decision.reason !== "string" || (decision.stop !== "hook" && decision.stop !== "no_progress")) {
|
|
107
|
+
invalid("shouldStop", 'returned a stop that is not { stop: "hook" | "no_progress", reason }');
|
|
108
|
+
}
|
|
109
|
+
return decision.stop === "hook"
|
|
110
|
+
? { kind: "stop", stoppedBy: decision.reason }
|
|
111
|
+
: { kind: "no_progress", reason: decision.reason };
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=hook-checks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hook-checks.js","sourceRoot":"","sources":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ACzG,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/** 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 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,60 @@
|
|
|
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
|
+
import type { AssistantMessage, Message, ModelContext, ModelRef, Usage } from "@buildanagent/gateway";
|
|
11
|
+
import { SdkError } from "./errors.js";
|
|
12
|
+
import type { AgentEventBody } from "./events.js";
|
|
13
|
+
import { type StopVerdict } from "./hook-checks.js";
|
|
14
|
+
import type { CallOptions, Interceptors, ModelCallPatch } from "./hooks.js";
|
|
15
|
+
import type { Clock } from "./testing/determinism.js";
|
|
16
|
+
import { type PipelineContext } from "./tools/pipeline.js";
|
|
17
|
+
/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */
|
|
18
|
+
export declare class HookFailure extends SdkError {
|
|
19
|
+
readonly name = "HookFailure";
|
|
20
|
+
readonly hook: string;
|
|
21
|
+
constructor(hook: string, cause: unknown);
|
|
22
|
+
}
|
|
23
|
+
/** What a run gives its hook runner. */
|
|
24
|
+
export interface HookRunnerSetup {
|
|
25
|
+
readonly interceptors: Interceptors;
|
|
26
|
+
readonly runId: string;
|
|
27
|
+
readonly signal: AbortSignal;
|
|
28
|
+
readonly clock: Clock;
|
|
29
|
+
/** The index of the model call in progress. */
|
|
30
|
+
stepIndex(): number;
|
|
31
|
+
send(body: AgentEventBody): void;
|
|
32
|
+
}
|
|
33
|
+
/** The pipeline hooks that the interceptors fill, left out when no interceptor needs them. */
|
|
34
|
+
export type PipelineHooks = Pick<PipelineContext, "gate" | "after">;
|
|
35
|
+
/** Runs one run's interceptors. */
|
|
36
|
+
export declare class HookRunner {
|
|
37
|
+
#private;
|
|
38
|
+
constructor(setup: HookRunnerSetup);
|
|
39
|
+
/** The gate and the after-hook, for the tool pipeline. */
|
|
40
|
+
pipelineHooks(): PipelineHooks;
|
|
41
|
+
/** The messages `transformContext` chose for this call, or undefined to send the transcript as it is. */
|
|
42
|
+
transformContext(input: {
|
|
43
|
+
system: string;
|
|
44
|
+
messages: readonly Message[];
|
|
45
|
+
model: ModelRef;
|
|
46
|
+
lastUsage: Usage | undefined;
|
|
47
|
+
}): Promise<Message[] | undefined>;
|
|
48
|
+
/** What `beforeModelCall` changed, if anything. */
|
|
49
|
+
beforeModelCall(input: {
|
|
50
|
+
context: ModelContext;
|
|
51
|
+
options: CallOptions;
|
|
52
|
+
}): Promise<ModelCallPatch | undefined>;
|
|
53
|
+
/** The response the run goes on with: `afterModelCall`'s replacement, or `message` itself. */
|
|
54
|
+
afterModelCall(message: AssistantMessage): Promise<AssistantMessage>;
|
|
55
|
+
/** What `shouldStop` decided. */
|
|
56
|
+
shouldStop(input: {
|
|
57
|
+
messages: readonly Message[];
|
|
58
|
+
lastMessage: AssistantMessage;
|
|
59
|
+
}): Promise<StopVerdict>;
|
|
60
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
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 { isContentList } from "./tools/pipeline.js";
|
|
5
|
+
/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */
|
|
6
|
+
export class HookFailure extends SdkError {
|
|
7
|
+
name = "HookFailure";
|
|
8
|
+
hook;
|
|
9
|
+
constructor(hook, cause) {
|
|
10
|
+
super("hook_failed", `the ${hook} hook failed: ${messageOf(cause)}`, { cause });
|
|
11
|
+
this.hook = hook;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function messageOf(error) {
|
|
15
|
+
return error instanceof Error ? error.message : String(error);
|
|
16
|
+
}
|
|
17
|
+
/** The result of a call after `afterToolCall` returned `patch`, checked to still be one the model can read. */
|
|
18
|
+
function mergeResult(tool, result, patch) {
|
|
19
|
+
if (patch === undefined)
|
|
20
|
+
return result;
|
|
21
|
+
const merged = { ...result, ...patch };
|
|
22
|
+
if (!isContentList(merged.content)) {
|
|
23
|
+
throw new SdkError("invalid_hook_result", `afterToolCall for "${tool}" returned content that is not a list of text and image blocks`);
|
|
24
|
+
}
|
|
25
|
+
return merged;
|
|
26
|
+
}
|
|
27
|
+
function blocked(text, details) {
|
|
28
|
+
return { content: [{ type: "text", text }], isError: true, details };
|
|
29
|
+
}
|
|
30
|
+
function gateOutcome(tool, decision) {
|
|
31
|
+
if (decision.decision === "allow")
|
|
32
|
+
return decision.input === undefined ? undefined : { input: thawedCopy(decision.input) };
|
|
33
|
+
if (decision.decision === "deny") {
|
|
34
|
+
return { blocked: blocked(`Tool call "${tool}" was denied: ${decision.reason}`, { decision: "deny" }) };
|
|
35
|
+
}
|
|
36
|
+
const why = decision.reason === undefined ? "" : ` (${decision.reason})`;
|
|
37
|
+
const text = `Tool call "${tool}" needs approval${why}, and this run can't ask for it, so it was not run.`;
|
|
38
|
+
return {
|
|
39
|
+
blocked: blocked(text, { decision: "ask", ...(decision.reason === undefined ? {} : { reason: decision.reason }) }),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/** Runs one run's interceptors. */
|
|
43
|
+
export class HookRunner {
|
|
44
|
+
#setup;
|
|
45
|
+
#hooks;
|
|
46
|
+
#continues;
|
|
47
|
+
constructor(setup) {
|
|
48
|
+
this.#setup = setup;
|
|
49
|
+
this.#hooks = setup.interceptors;
|
|
50
|
+
this.#continues = setup.interceptors.onFailure === "continue";
|
|
51
|
+
}
|
|
52
|
+
/** The gate and the after-hook, for the tool pipeline. */
|
|
53
|
+
pipelineHooks() {
|
|
54
|
+
return {
|
|
55
|
+
...(this.#hooks.beforeToolCall === undefined ? {} : { gate: (e) => this.#gate(e) }),
|
|
56
|
+
...(this.#hooks.afterToolCall === undefined ? {} : { after: (e) => this.#afterTool(e) }),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** The messages `transformContext` chose for this call, or undefined to send the transcript as it is. */
|
|
60
|
+
async transformContext(input) {
|
|
61
|
+
const hook = this.#hooks.transformContext;
|
|
62
|
+
if (hook === undefined)
|
|
63
|
+
return undefined;
|
|
64
|
+
const { lastUsage, ...rest } = input;
|
|
65
|
+
const event = this.#event({ ...rest, ...(lastUsage === undefined ? {} : { lastUsage }) });
|
|
66
|
+
const guarded = await this.#guard("transformContext", () => hook(event));
|
|
67
|
+
if (guarded.status !== "ok")
|
|
68
|
+
return undefined;
|
|
69
|
+
const messages = checkMessages("transformContext", guarded.value);
|
|
70
|
+
this.#setup.send({ type: "context_transformed", before: input.messages.length, after: messages.length });
|
|
71
|
+
return messages;
|
|
72
|
+
}
|
|
73
|
+
/** What `beforeModelCall` changed, if anything. */
|
|
74
|
+
async beforeModelCall(input) {
|
|
75
|
+
const hook = this.#hooks.beforeModelCall;
|
|
76
|
+
if (hook === undefined)
|
|
77
|
+
return undefined;
|
|
78
|
+
const event = this.#event(input);
|
|
79
|
+
const guarded = await this.#guard("beforeModelCall", () => hook(event));
|
|
80
|
+
return guarded.status === "ok" ? checkModelPatch(guarded.value) : undefined;
|
|
81
|
+
}
|
|
82
|
+
/** The response the run goes on with: `afterModelCall`'s replacement, or `message` itself. */
|
|
83
|
+
async afterModelCall(message) {
|
|
84
|
+
const hook = this.#hooks.afterModelCall;
|
|
85
|
+
if (hook === undefined)
|
|
86
|
+
return message;
|
|
87
|
+
const event = this.#event({ message });
|
|
88
|
+
const guarded = await this.#guard("afterModelCall", () => hook(event));
|
|
89
|
+
return (guarded.status === "ok" ? checkReplacement(guarded.value) : undefined) ?? message;
|
|
90
|
+
}
|
|
91
|
+
/** What `shouldStop` decided. */
|
|
92
|
+
async shouldStop(input) {
|
|
93
|
+
const hook = this.#hooks.shouldStop;
|
|
94
|
+
if (hook === undefined)
|
|
95
|
+
return { kind: "none" };
|
|
96
|
+
const event = this.#event(input);
|
|
97
|
+
const guarded = await this.#guard("shouldStop", () => hook(event));
|
|
98
|
+
return guarded.status === "ok" ? checkStopDecision(guarded.value) : { kind: "none" };
|
|
99
|
+
}
|
|
100
|
+
async #gate(input) {
|
|
101
|
+
const hook = this.#hooks.beforeToolCall;
|
|
102
|
+
if (hook === undefined)
|
|
103
|
+
return undefined;
|
|
104
|
+
const { call, tool } = input;
|
|
105
|
+
const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input }, call.callId);
|
|
106
|
+
const failed = (error) => ({
|
|
107
|
+
blocked: blocked(`Tool call "${tool.name}" was not run, because its permission check failed.`, {
|
|
108
|
+
hook: "beforeToolCall",
|
|
109
|
+
error: messageOf(error),
|
|
110
|
+
}),
|
|
111
|
+
});
|
|
112
|
+
const guarded = await this.#guard("beforeToolCall", () => hook(event), failed);
|
|
113
|
+
if (guarded.status === "skipped")
|
|
114
|
+
return undefined;
|
|
115
|
+
return guarded.status === "closed" ? guarded.value : gateOutcome(tool.name, checkDecision(guarded.value));
|
|
116
|
+
}
|
|
117
|
+
async #afterTool(input) {
|
|
118
|
+
const hook = this.#hooks.afterToolCall;
|
|
119
|
+
const { call, tool, result } = input;
|
|
120
|
+
if (hook === undefined)
|
|
121
|
+
return result;
|
|
122
|
+
const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input, result }, call.callId);
|
|
123
|
+
// The tool already ran, so the stand-in says so and keeps the write outcome: a model told only "withheld" would
|
|
124
|
+
// retry a write that was applied.
|
|
125
|
+
const withheld = (error) => ({
|
|
126
|
+
...blocked(`Tool call "${tool.name}" ran, but its result was withheld, because its result check failed.`, {
|
|
127
|
+
hook: "afterToolCall",
|
|
128
|
+
error: messageOf(error),
|
|
129
|
+
}),
|
|
130
|
+
...(result.outcome === undefined ? {} : { outcome: result.outcome }),
|
|
131
|
+
});
|
|
132
|
+
const guarded = await this.#guard("afterToolCall", () => hook(event), withheld);
|
|
133
|
+
if (guarded.status === "skipped")
|
|
134
|
+
return result;
|
|
135
|
+
return guarded.status === "closed"
|
|
136
|
+
? guarded.value
|
|
137
|
+
: mergeResult(tool.name, result, checkResultPatch(guarded.value));
|
|
138
|
+
}
|
|
139
|
+
#event(payload, callId) {
|
|
140
|
+
const { runId, signal, clock } = this.#setup;
|
|
141
|
+
return Object.freeze({
|
|
142
|
+
runId,
|
|
143
|
+
stepIndex: this.#setup.stepIndex(),
|
|
144
|
+
...(callId === undefined ? {} : { callId }),
|
|
145
|
+
signal,
|
|
146
|
+
timestamp: clock.now(),
|
|
147
|
+
...frozenCopy(payload),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/** Calls a hook under the failure policy. Without `closed`, a failure under `fail_closed` throws a `HookFailure`. */
|
|
151
|
+
async #guard(hook, call, closed) {
|
|
152
|
+
try {
|
|
153
|
+
return { status: "ok", value: await call() };
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
// A wrong return shape is a programmer error whatever the policy, even when a joined hook found it inside
|
|
157
|
+
// `composeInterceptors()`: skipping or closing on it would let a typo in a gate pass silently.
|
|
158
|
+
if (isSdkError(error) && error.code === "invalid_hook_result")
|
|
159
|
+
throw error;
|
|
160
|
+
this.#setup.send({ type: "hook_error", hook, error: messageOf(error) });
|
|
161
|
+
if (this.#continues)
|
|
162
|
+
return { status: "skipped" };
|
|
163
|
+
if (closed === undefined)
|
|
164
|
+
throw new HookFailure(hook, error);
|
|
165
|
+
return { status: "closed", value: closed(error) };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
//# sourceMappingURL=hook-runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hook-runner.js","sourceRoot":"","sources":["../src/hook-runner.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EACL,aAAa,EACb,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,GAElB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAkC,aAAa,EAAwB,MAAM,qBAAqB,CAAC;AAG1G,uHAAuH;AACvH,MAAM,OAAO,WAAY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ACpD,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Runs the interceptors for one run: builds each hook's frozen event, applies the failure policy, checks what the\n * hook returned and emits `hook_error` and `context_transformed`. The loop and the tool pipeline call it at each\n * moment and never look at the hooks themselves.\n *\n * Failure policy (D6): a hook that throws is reported as a `hook_error` event. Under `fail_closed`, the default, a\n * failed gate denies its call, a failed `afterToolCall` withholds the result, and any other failed hook throws a\n * `HookFailure`, which the loop turns into an `error` result. Under `continue` the failed hook is skipped.\n */\nimport type { AssistantMessage, Message, ModelContext, ModelRef, Usage } from \"@buildanagent/gateway\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport { frozenCopy, thawedCopy } from \"./freeze.js\";\nimport {\n checkDecision,\n checkMessages,\n checkModelPatch,\n checkReplacement,\n checkResultPatch,\n checkStopDecision,\n type StopVerdict,\n} from \"./hook-checks.js\";\nimport type { CallOptions, GateDecision, HookEventBase, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { type AnyTool, type GateOutcome, isContentList, type PipelineContext } from \"./tools/pipeline.js\";\nimport type { ToolCall, ToolResult } from \"./tools/types.js\";\n\n/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */\nexport class HookFailure extends SdkError {\n override readonly name = \"HookFailure\";\n readonly hook: string;\n\n constructor(hook: string, cause: unknown) {\n super(\"hook_failed\", `the ${hook} hook failed: ${messageOf(cause)}`, { cause });\n this.hook = hook;\n }\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** How a guarded hook call ended: it returned, it failed and the run skips it, or it failed and a result stands in. */\ntype Guarded<T, R> =\n | { readonly status: \"ok\"; readonly value: T }\n | { readonly status: \"skipped\" }\n | { readonly status: \"closed\"; readonly value: R };\n\n/** The result of a call after `afterToolCall` returned `patch`, checked to still be one the model can read. */\nfunction mergeResult(tool: string, result: ToolResult, patch: Record<string, unknown> | undefined): ToolResult {\n if (patch === undefined) return result;\n const merged = { ...result, ...patch } as ToolResult;\n if (!isContentList(merged.content)) {\n throw new SdkError(\n \"invalid_hook_result\",\n `afterToolCall for \"${tool}\" returned content that is not a list of text and image blocks`,\n );\n }\n return merged;\n}\n\n/** What a run gives its hook runner. */\nexport interface HookRunnerSetup {\n readonly interceptors: Interceptors;\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n /** The index of the model call in progress. */\n stepIndex(): number;\n send(body: AgentEventBody): void;\n}\n\nfunction blocked(text: string, details: Record<string, unknown>): ToolResult {\n return { content: [{ type: \"text\", text }], isError: true, details };\n}\n\n/** The pipeline hooks that the interceptors fill, left out when no interceptor needs them. */\nexport type PipelineHooks = Pick<PipelineContext, \"gate\" | \"after\">;\n\nfunction gateOutcome(tool: string, decision: GateDecision): GateOutcome | undefined {\n if (decision.decision === \"allow\")\n return decision.input === undefined ? undefined : { input: thawedCopy(decision.input) };\n if (decision.decision === \"deny\") {\n return { blocked: blocked(`Tool call \"${tool}\" was denied: ${decision.reason}`, { decision: \"deny\" }) };\n }\n const why = decision.reason === undefined ? \"\" : ` (${decision.reason})`;\n const text = `Tool call \"${tool}\" needs approval${why}, and this run can't ask for it, so it was not run.`;\n return {\n blocked: blocked(text, { decision: \"ask\", ...(decision.reason === undefined ? {} : { reason: decision.reason }) }),\n };\n}\n\n/** Runs one run's interceptors. */\nexport class HookRunner {\n readonly #setup: HookRunnerSetup;\n readonly #hooks: Interceptors;\n readonly #continues: boolean;\n\n constructor(setup: HookRunnerSetup) {\n this.#setup = setup;\n this.#hooks = setup.interceptors;\n this.#continues = setup.interceptors.onFailure === \"continue\";\n }\n\n /** The gate and the after-hook, for the tool pipeline. */\n pipelineHooks(): PipelineHooks {\n return {\n ...(this.#hooks.beforeToolCall === undefined ? {} : { gate: (e) => this.#gate(e) }),\n ...(this.#hooks.afterToolCall === undefined ? {} : { after: (e) => this.#afterTool(e) }),\n };\n }\n\n /** The messages `transformContext` chose for this call, or undefined to send the transcript as it is. */\n async transformContext(input: {\n system: string;\n messages: readonly Message[];\n model: ModelRef;\n lastUsage: Usage | undefined;\n }): Promise<Message[] | undefined> {\n const hook = this.#hooks.transformContext;\n if (hook === undefined) return undefined;\n const { lastUsage, ...rest } = input;\n const event = this.#event({ ...rest, ...(lastUsage === undefined ? {} : { lastUsage }) });\n const guarded = await this.#guard(\"transformContext\", () => hook(event));\n if (guarded.status !== \"ok\") return undefined;\n const messages = checkMessages(\"transformContext\", guarded.value);\n this.#setup.send({ type: \"context_transformed\", before: input.messages.length, after: messages.length });\n return messages;\n }\n\n /** What `beforeModelCall` changed, if anything. */\n async beforeModelCall(input: { context: ModelContext; options: CallOptions }): Promise<ModelCallPatch | undefined> {\n const hook = this.#hooks.beforeModelCall;\n if (hook === undefined) return undefined;\n const event = this.#event(input);\n const guarded = await this.#guard(\"beforeModelCall\", () => hook(event));\n return guarded.status === \"ok\" ? checkModelPatch(guarded.value) : undefined;\n }\n\n /** The response the run goes on with: `afterModelCall`'s replacement, or `message` itself. */\n async afterModelCall(message: AssistantMessage): Promise<AssistantMessage> {\n const hook = this.#hooks.afterModelCall;\n if (hook === undefined) return message;\n const event = this.#event({ message });\n const guarded = await this.#guard(\"afterModelCall\", () => hook(event));\n return (guarded.status === \"ok\" ? checkReplacement(guarded.value) : undefined) ?? message;\n }\n\n /** What `shouldStop` decided. */\n async shouldStop(input: { messages: readonly Message[]; lastMessage: AssistantMessage }): Promise<StopVerdict> {\n const hook = this.#hooks.shouldStop;\n if (hook === undefined) return { kind: \"none\" };\n const event = this.#event(input);\n const guarded = await this.#guard(\"shouldStop\", () => hook(event));\n return guarded.status === \"ok\" ? checkStopDecision(guarded.value) : { kind: \"none\" };\n }\n\n async #gate(input: { call: ToolCall; tool: AnyTool; input: unknown }): Promise<GateOutcome | undefined> {\n const hook = this.#hooks.beforeToolCall;\n if (hook === undefined) return undefined;\n const { call, tool } = input;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input }, call.callId);\n const failed = (error: unknown): GateOutcome => ({\n blocked: blocked(`Tool call \"${tool.name}\" was not run, because its permission check failed.`, {\n hook: \"beforeToolCall\",\n error: messageOf(error),\n }),\n });\n const guarded = await this.#guard(\"beforeToolCall\", () => hook(event), failed);\n if (guarded.status === \"skipped\") return undefined;\n return guarded.status === \"closed\" ? guarded.value : gateOutcome(tool.name, checkDecision(guarded.value));\n }\n\n async #afterTool(input: { call: ToolCall; tool: AnyTool; input: unknown; result: ToolResult }): Promise<ToolResult> {\n const hook = this.#hooks.afterToolCall;\n const { call, tool, result } = input;\n if (hook === undefined) return result;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input, result }, call.callId);\n // The tool already ran, so the stand-in says so and keeps the write outcome: a model told only \"withheld\" would\n // retry a write that was applied.\n const withheld = (error: unknown): ToolResult => ({\n ...blocked(`Tool call \"${tool.name}\" ran, but its result was withheld, because its result check failed.`, {\n hook: \"afterToolCall\",\n error: messageOf(error),\n }),\n ...(result.outcome === undefined ? {} : { outcome: result.outcome }),\n });\n const guarded = await this.#guard(\"afterToolCall\", () => hook(event), withheld);\n if (guarded.status === \"skipped\") return result;\n return guarded.status === \"closed\"\n ? guarded.value\n : mergeResult(tool.name, result, checkResultPatch(guarded.value));\n }\n\n #event<P extends object>(payload: P, callId?: string): Readonly<HookEventBase & P> {\n const { runId, signal, clock } = this.#setup;\n return Object.freeze({\n runId,\n stepIndex: this.#setup.stepIndex(),\n ...(callId === undefined ? {} : { callId }),\n signal,\n timestamp: clock.now(),\n ...frozenCopy(payload),\n }) as Readonly<HookEventBase & P>;\n }\n\n /** Calls a hook under the failure policy. Without `closed`, a failure under `fail_closed` throws a `HookFailure`. */\n async #guard<T, R = never>(\n hook: string,\n call: () => T | Promise<T>,\n closed?: (error: unknown) => R,\n ): Promise<Guarded<Awaited<T>, R>> {\n try {\n return { status: \"ok\", value: await call() };\n } catch (error) {\n // A wrong return shape is a programmer error whatever the policy, even when a joined hook found it inside\n // `composeInterceptors()`: skipping or closing on it would let a typo in a gate pass silently.\n if (isSdkError(error) && error.code === \"invalid_hook_result\") throw error;\n this.#setup.send({ type: \"hook_error\", hook, error: messageOf(error) });\n if (this.#continues) return { status: \"skipped\" };\n if (closed === undefined) throw new HookFailure(hook, error);\n return { status: \"closed\", value: closed(error) };\n }\n }\n}\n"]}
|