@buildanagent/sdk 0.1.0-alpha.3 → 0.1.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +76 -6
  2. package/dist/compose.d.ts +22 -0
  3. package/dist/compose.js +137 -0
  4. package/dist/compose.js.map +1 -0
  5. package/dist/errors.d.ts +12 -7
  6. package/dist/errors.js +11 -6
  7. package/dist/errors.js.map +1 -1
  8. package/dist/events.d.ts +22 -2
  9. package/dist/events.js +2 -0
  10. package/dist/events.js.map +1 -1
  11. package/dist/freeze.d.ts +11 -0
  12. package/dist/freeze.js +42 -0
  13. package/dist/freeze.js.map +1 -0
  14. package/dist/hook-checks.d.ts +31 -0
  15. package/dist/hook-checks.js +113 -0
  16. package/dist/hook-checks.js.map +1 -0
  17. package/dist/hook-runner.d.ts +60 -0
  18. package/dist/hook-runner.js +169 -0
  19. package/dist/hook-runner.js.map +1 -0
  20. package/dist/hooks.d.ts +177 -0
  21. package/dist/hooks.js +2 -0
  22. package/dist/hooks.js.map +1 -0
  23. package/dist/index.d.ts +7 -4
  24. package/dist/index.js +4 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/loop.d.ts +18 -8
  27. package/dist/loop.js +191 -29
  28. package/dist/loop.js.map +1 -1
  29. package/dist/observers.d.ts +31 -0
  30. package/dist/observers.js +98 -0
  31. package/dist/observers.js.map +1 -0
  32. package/dist/result.d.ts +11 -5
  33. package/dist/result.js.map +1 -1
  34. package/dist/run.d.ts +34 -4
  35. package/dist/run.js +84 -7
  36. package/dist/run.js.map +1 -1
  37. package/dist/tools/define.d.ts +3 -2
  38. package/dist/tools/define.js +10 -2
  39. package/dist/tools/define.js.map +1 -1
  40. package/dist/tools/format-error.js +1 -0
  41. package/dist/tools/format-error.js.map +1 -1
  42. package/dist/tools/pipeline.d.ts +40 -7
  43. package/dist/tools/pipeline.js +196 -37
  44. package/dist/tools/pipeline.js.map +1 -1
  45. package/dist/tools/scheduler.d.ts +33 -0
  46. package/dist/tools/scheduler.js +51 -0
  47. package/dist/tools/scheduler.js.map +1 -0
  48. package/dist/tools/types.d.ts +41 -5
  49. package/dist/tools/types.js.map +1 -1
  50. package/package.json +2 -2
@@ -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":["../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,IAAI,OAAO,EAAE,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,SAAS,CAAC,KAAc;IAC/B,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACnC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACnG,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,IAAI,KAAK,CAAC,OAAO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M,EAAE,CAAC;IAC7C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,CAAC,YAAY,EAAE,yDAAyD,CAAC,CAAC;IACvG,MAAM,QAAQ,GAAG,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/** 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,SAAQ,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C;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"]}
@@ -0,0 +1,177 @@
1
+ /**
2
+ * The hook types: six interceptors that can change a run, and the observer that only watches it. Each interceptor
3
+ * takes one event object and returns a replacement, never mutating its input, because the event's data is frozen.
4
+ */
5
+ import type { AssistantMessage, ContentBlock, Message, Model, ModelCallOptions, ModelContext, ModelRef, Usage } from "@buildanagent/gateway";
6
+ import type { AgentEvent } from "./events.js";
7
+ import type { ToolResult } from "./tools/types.js";
8
+ /** A value or a promise of one: a hook may be a plain function or an `async` one. */
9
+ export type MaybePromise<T> = T | Promise<T>;
10
+ /**
11
+ * A value, or nothing: what a hook that may change something returns. `void` lets an `async` hook that has nothing
12
+ * to change simply end, where `undefined` would force it to return explicitly.
13
+ */
14
+ export type OrNothing<T> = T | void;
15
+ /** The options of one model call, without the abort signal, which the run supplies. */
16
+ export type CallOptions = Omit<ModelCallOptions, "signal">;
17
+ /** The fields every hook event carries. */
18
+ export interface HookEventBase {
19
+ /** The run's id. */
20
+ readonly runId: string;
21
+ /** The index of the model call the hook belongs to, counted from 0. */
22
+ readonly stepIndex: number;
23
+ /** The tool call's id, for the two tool hooks; absent for the others. */
24
+ readonly callId?: string;
25
+ /** The run's abort signal. Pass it on to any I/O the hook does. */
26
+ readonly signal: AbortSignal;
27
+ /** When the hook was called, from the run's clock, in ISO 8601. */
28
+ readonly timestamp: string;
29
+ }
30
+ /** What `transformContext` receives: the conversation as it stands before the model call. */
31
+ export interface ContextEvent extends HookEventBase {
32
+ /** The system prompt. */
33
+ readonly system: string;
34
+ /** The whole conversation so far, never a view an earlier call's transform returned. */
35
+ readonly messages: readonly Message[];
36
+ /** The model the run was started with. */
37
+ readonly model: ModelRef;
38
+ /** The previous model call's usage. Absent on the first call. */
39
+ readonly lastUsage?: Usage;
40
+ }
41
+ /** What `beforeModelCall` receives: the request about to be sent. */
42
+ export interface ModelCallEvent extends HookEventBase {
43
+ /** The request: the system prompt, the messages `transformContext` returned and the tools this call sends. */
44
+ readonly context: ModelContext;
45
+ /** The options of this call, without the abort signal. */
46
+ readonly options: CallOptions;
47
+ }
48
+ /** What `afterModelCall` receives: the model's finished response. */
49
+ export interface ModelResultEvent extends HookEventBase {
50
+ /** The response, including a failed one, whose `stopReason` is `"error"`. */
51
+ readonly message: AssistantMessage;
52
+ }
53
+ /** What `beforeToolCall` receives: a call whose input has passed the tool's schema. */
54
+ export interface ToolCallEvent extends HookEventBase {
55
+ readonly callId: string;
56
+ /** The tool's name. */
57
+ readonly tool: string;
58
+ /** The validated input. */
59
+ readonly input: unknown;
60
+ }
61
+ /** What `afterToolCall` receives: the result of a call that executed, before the model reads it. */
62
+ export interface ToolResultEvent extends ToolCallEvent {
63
+ readonly result: ToolResult;
64
+ }
65
+ /** What `shouldStop` receives, after a step's tool calls have their results. */
66
+ export interface StepEvent extends HookEventBase {
67
+ /** The whole conversation so far, including this step's response and tool results. */
68
+ readonly messages: readonly Message[];
69
+ /** This step's model response. */
70
+ readonly lastMessage: AssistantMessage;
71
+ }
72
+ /**
73
+ * Changes to one model call's request. Every field is optional, and a change applies to that call only; the next
74
+ * call starts again from the run's own settings.
75
+ */
76
+ export interface ModelCallPatch {
77
+ /** Replaces the system prompt for this call. */
78
+ readonly system?: string;
79
+ /** Replaces the messages sent for this call. The run's own transcript keeps its messages. */
80
+ readonly messages?: readonly Message[];
81
+ /**
82
+ * The names of the tools to send, as the complete list: a tool left out is not sent, and a tool whose `exposure`
83
+ * is `deferred` or `hidden` is sent when named. Tools always go out in definition order, whatever order this list
84
+ * is in. A name that matches no tool throws an `SdkError` with code `invalid_hook_result`. A call to a tool that
85
+ * was not sent gets the unknown-tool error.
86
+ */
87
+ readonly activeTools?: readonly string[];
88
+ /** Makes this call with another model. */
89
+ readonly model?: Model;
90
+ /** Replaces the options of this call. */
91
+ readonly options?: CallOptions;
92
+ }
93
+ /**
94
+ * What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the
95
+ * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` asks a
96
+ * person; until runs can pause, it blocks the call like `deny` with a message that says approval isn't available.
97
+ */
98
+ export type GateDecision = {
99
+ readonly decision: "allow";
100
+ readonly input?: unknown;
101
+ readonly reason?: string;
102
+ } | {
103
+ readonly decision: "deny";
104
+ readonly reason: string;
105
+ } | {
106
+ readonly decision: "ask";
107
+ readonly reason?: string;
108
+ readonly policyVersion?: string;
109
+ };
110
+ /**
111
+ * Changes to a tool's result. Each field present replaces the result's own. A replaced `outcome` is not available
112
+ * here: a write's outcome is rendered into `content` once, so replace `content` instead.
113
+ */
114
+ export type ToolResultPatch = Partial<Omit<ToolResult, "outcome">>;
115
+ /**
116
+ * What `shouldStop` decides. `true` or `{ stop: "hook" }` ends the run `stopped`, with the reason as `stoppedBy`
117
+ * (`"hook"` for `true`). `{ stop: "no_progress" }` ends it `no_progress`. `{ continue }` keeps a run going that the
118
+ * model ended by answering in text, adding the content as a user message. When the model's step called tools, the run goes on anyway and the content is
119
+ * not added, so a hook that must reach the model should return it after a text answer. `false` leaves the decision to the run.
120
+ */
121
+ export type StopDecision = boolean | {
122
+ readonly continue: string | readonly ContentBlock[];
123
+ } | {
124
+ readonly stop: "no_progress" | "hook";
125
+ readonly reason: string;
126
+ };
127
+ /**
128
+ * The six interceptors, in the order a step calls them: `transformContext`, `beforeModelCall`, the model call,
129
+ * `afterModelCall`, then for each tool call `beforeToolCall` and `afterToolCall`, and last `shouldStop`. A run takes
130
+ * one object; `composeInterceptors()` joins several. Each hook may be `async`.
131
+ */
132
+ export interface Interceptors {
133
+ /**
134
+ * Returns the messages to send for this model call, such as a masked or summarised view of a long conversation.
135
+ * The view reaches that call's request only: the next call's event, `result.messages` and `result.context` hold
136
+ * the full history. Each call emits a `context_transformed` event with the message counts.
137
+ */
138
+ readonly transformContext?: (e: ContextEvent) => MaybePromise<readonly Message[]>;
139
+ /** Changes the request about to be sent. Return nothing to leave it as it is. */
140
+ readonly beforeModelCall?: (e: ModelCallEvent) => MaybePromise<OrNothing<ModelCallPatch>>;
141
+ /**
142
+ * Replaces the model's response. The transcript and the `model_call_end` event hold the replacement, and its tool
143
+ * calls are the ones that run. The call's usage and cost stay those of the model's own response. If it throws
144
+ * while the run fails closed, both hold an empty stand-in with `stopReason: "error"` and that usage and cost.
145
+ */
146
+ readonly afterModelCall?: (e: ModelResultEvent) => MaybePromise<OrNothing<{
147
+ readonly message?: AssistantMessage;
148
+ }>>;
149
+ /**
150
+ * The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in
151
+ * model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and
152
+ * every registered tool is allowed. A gate that returns `ask` pauses the run once pauses exist; until then `ask`
153
+ * blocks the call. A gate that throws denies the call unless `onFailure` is `"continue"`. A gate must return a
154
+ * decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.
155
+ */
156
+ readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;
157
+ /**
158
+ * Replaces fields of a result before the model reads it, and before `tool_call_end` reports it. It runs for calls
159
+ * that executed, including ones whose `execute` threw, and not for calls that never ran, such as an unknown tool,
160
+ * invalid input or a denied call. Return nothing to keep the result.
161
+ */
162
+ readonly afterToolCall?: (e: ToolResultEvent) => MaybePromise<OrNothing<ToolResultPatch>>;
163
+ /** Ends the run, or keeps it going, after a step. It is not asked once the run has a stop reason of its own. */
164
+ readonly shouldStop?: (e: StepEvent) => MaybePromise<StopDecision>;
165
+ /**
166
+ * What a hook that throws does. `"fail_closed"` (the default) stops the unsafe thing: a failed `beforeToolCall`
167
+ * denies the call, a failed `afterToolCall` withholds the result, and a failed model-moment hook or `shouldStop`
168
+ * ends the run with `stopReason: "error"` and `error.kind: "hook"`. `"continue"` skips the failed hook and goes on
169
+ * as if it had returned nothing. Either way the run emits a `hook_error` event.
170
+ */
171
+ readonly onFailure?: "fail_closed" | "continue";
172
+ }
173
+ /**
174
+ * Watches a run: called with each event, in order, and never able to change the run. A promise it returns is waited
175
+ * for before the next event is delivered to it. A throw or a rejection becomes a `hook_error` event.
176
+ */
177
+ export type Observer = (event: AgentEvent) => MaybePromise<void>;
package/dist/hooks.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The hook types: six interceptors that can change a run, and the observer that only watches it. Each interceptor\n * takes one event object and returns a replacement, never mutating its input, because the event's data is frozen.\n */\nimport type {\n AssistantMessage,\n ContentBlock,\n Message,\n Model,\n ModelCallOptions,\n ModelContext,\n ModelRef,\n Usage,\n} from \"@buildanagent/gateway\";\nimport type { AgentEvent } from \"./events.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** A value or a promise of one: a hook may be a plain function or an `async` one. */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * A value, or nothing: what a hook that may change something returns. `void` lets an `async` hook that has nothing\n * to change simply end, where `undefined` would force it to return explicitly.\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: a hook's return type, where void lets a function return nothing\nexport type OrNothing<T> = T | void;\n\n/** The options of one model call, without the abort signal, which the run supplies. */\nexport type CallOptions = Omit<ModelCallOptions, \"signal\">;\n\n/** The fields every hook event carries. */\nexport interface HookEventBase {\n /** The run's id. */\n readonly runId: string;\n /** The index of the model call the hook belongs to, counted from 0. */\n readonly stepIndex: number;\n /** The tool call's id, for the two tool hooks; absent for the others. */\n readonly callId?: string;\n /** The run's abort signal. Pass it on to any I/O the hook does. */\n readonly signal: AbortSignal;\n /** When the hook was called, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** What `transformContext` receives: the conversation as it stands before the model call. */\nexport interface ContextEvent extends HookEventBase {\n /** The system prompt. */\n readonly system: string;\n /** The whole conversation so far, never a view an earlier call's transform returned. */\n readonly messages: readonly Message[];\n /** The model the run was started with. */\n readonly model: ModelRef;\n /** The previous model call's usage. Absent on the first call. */\n readonly lastUsage?: Usage;\n}\n\n/** What `beforeModelCall` receives: the request about to be sent. */\nexport interface ModelCallEvent extends HookEventBase {\n /** The request: the system prompt, the messages `transformContext` returned and the tools this call sends. */\n readonly context: ModelContext;\n /** The options of this call, without the abort signal. */\n readonly options: CallOptions;\n}\n\n/** What `afterModelCall` receives: the model's finished response. */\nexport interface ModelResultEvent extends HookEventBase {\n /** The response, including a failed one, whose `stopReason` is `\"error\"`. */\n readonly message: AssistantMessage;\n}\n\n/** What `beforeToolCall` receives: a call whose input has passed the tool's schema. */\nexport interface ToolCallEvent extends HookEventBase {\n readonly callId: string;\n /** The tool's name. */\n readonly tool: string;\n /** The validated input. */\n readonly input: unknown;\n}\n\n/** What `afterToolCall` receives: the result of a call that executed, before the model reads it. */\nexport interface ToolResultEvent extends ToolCallEvent {\n readonly result: ToolResult;\n}\n\n/** What `shouldStop` receives, after a step's tool calls have their results. */\nexport interface StepEvent extends HookEventBase {\n /** The whole conversation so far, including this step's response and tool results. */\n readonly messages: readonly Message[];\n /** This step's model response. */\n readonly lastMessage: AssistantMessage;\n}\n\n/**\n * Changes to one model call's request. Every field is optional, and a change applies to that call only; the next\n * call starts again from the run's own settings.\n */\nexport interface ModelCallPatch {\n /** Replaces the system prompt for this call. */\n readonly system?: string;\n /** Replaces the messages sent for this call. The run's own transcript keeps its messages. */\n readonly messages?: readonly Message[];\n /**\n * The names of the tools to send, as the complete list: a tool left out is not sent, and a tool whose `exposure`\n * is `deferred` or `hidden` is sent when named. Tools always go out in definition order, whatever order this list\n * is in. A name that matches no tool throws an `SdkError` with code `invalid_hook_result`. A call to a tool that\n * was not sent gets the unknown-tool error.\n */\n readonly activeTools?: readonly string[];\n /** Makes this call with another model. */\n readonly model?: Model;\n /** Replaces the options of this call. */\n readonly options?: CallOptions;\n}\n\n/**\n * What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the\n * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` asks a\n * person; until runs can pause, it blocks the call like `deny` with a message that says approval isn't available.\n */\nexport type GateDecision =\n | { readonly decision: \"allow\"; readonly input?: unknown; readonly reason?: string }\n | { readonly decision: \"deny\"; readonly reason: string }\n | { readonly decision: \"ask\"; readonly reason?: string; readonly policyVersion?: string };\n\n/**\n * Changes to a tool's result. Each field present replaces the result's own. A replaced `outcome` is not available\n * here: a write's outcome is rendered into `content` once, so replace `content` instead.\n */\nexport type ToolResultPatch = Partial<Omit<ToolResult, \"outcome\">>;\n\n/**\n * What `shouldStop` decides. `true` or `{ stop: \"hook\" }` ends the run `stopped`, with the reason as `stoppedBy`\n * (`\"hook\"` for `true`). `{ stop: \"no_progress\" }` ends it `no_progress`. `{ continue }` keeps a run going that the\n * model ended by answering in text, adding the content as a user message. When the model's step called tools, the run goes on anyway and the content is\n * not added, so a hook that must reach the model should return it after a text answer. `false` leaves the decision to the run.\n */\nexport type StopDecision =\n | boolean\n | { readonly continue: string | readonly ContentBlock[] }\n | { readonly stop: \"no_progress\" | \"hook\"; readonly reason: string };\n\n/**\n * The six interceptors, in the order a step calls them: `transformContext`, `beforeModelCall`, the model call,\n * `afterModelCall`, then for each tool call `beforeToolCall` and `afterToolCall`, and last `shouldStop`. A run takes\n * one object; `composeInterceptors()` joins several. Each hook may be `async`.\n */\nexport interface Interceptors {\n /**\n * Returns the messages to send for this model call, such as a masked or summarised view of a long conversation.\n * The view reaches that call's request only: the next call's event, `result.messages` and `result.context` hold\n * the full history. Each call emits a `context_transformed` event with the message counts.\n */\n readonly transformContext?: (e: ContextEvent) => MaybePromise<readonly Message[]>;\n /** Changes the request about to be sent. Return nothing to leave it as it is. */\n readonly beforeModelCall?: (e: ModelCallEvent) => MaybePromise<OrNothing<ModelCallPatch>>;\n /**\n * Replaces the model's response. The transcript and the `model_call_end` event hold the replacement, and its tool\n * calls are the ones that run. The call's usage and cost stay those of the model's own response. If it throws\n * while the run fails closed, both hold an empty stand-in with `stopReason: \"error\"` and that usage and cost.\n */\n readonly afterModelCall?: (e: ModelResultEvent) => MaybePromise<OrNothing<{ readonly message?: AssistantMessage }>>;\n /**\n * The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in\n * model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and\n * every registered tool is allowed. A gate that returns `ask` pauses the run once pauses exist; until then `ask`\n * blocks the call. A gate that throws denies the call unless `onFailure` is `\"continue\"`. A gate must return a\n * decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.\n */\n readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;\n /**\n * Replaces fields of a result before the model reads it, and before `tool_call_end` reports it. It runs for calls\n * that executed, including ones whose `execute` threw, and not for calls that never ran, such as an unknown tool,\n * invalid input or a denied call. Return nothing to keep the result.\n */\n readonly afterToolCall?: (e: ToolResultEvent) => MaybePromise<OrNothing<ToolResultPatch>>;\n /** Ends the run, or keeps it going, after a step. It is not asked once the run has a stop reason of its own. */\n readonly shouldStop?: (e: StepEvent) => MaybePromise<StopDecision>;\n /**\n * What a hook that throws does. `\"fail_closed\"` (the default) stops the unsafe thing: a failed `beforeToolCall`\n * denies the call, a failed `afterToolCall` withholds the result, and a failed model-moment hook or `shouldStop`\n * ends the run with `stopReason: \"error\"` and `error.kind: \"hook\"`. `\"continue\"` skips the failed hook and goes on\n * as if it had returned nothing. Either way the run emits a `hook_error` event.\n */\n readonly onFailure?: \"fail_closed\" | \"continue\";\n}\n\n/**\n * Watches a run: called with each event, in order, and never able to change the run. A promise it returns is waited\n * for before the next event is delivered to it. A throw or a rejection becomes a `hook_error` event.\n */\nexport type Observer = (event: AgentEvent) => MaybePromise<void>;\n"]}