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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +425 -6
  2. package/dist/budget.d.ts +33 -0
  3. package/dist/budget.js +55 -0
  4. package/dist/budget.js.map +1 -0
  5. package/dist/compose.d.ts +26 -0
  6. package/dist/compose.js +157 -0
  7. package/dist/compose.js.map +1 -0
  8. package/dist/errors.d.ts +49 -0
  9. package/dist/errors.js +57 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/events.d.ts +168 -0
  12. package/dist/events.js +32 -0
  13. package/dist/events.js.map +1 -0
  14. package/dist/freeze.d.ts +11 -0
  15. package/dist/freeze.js +42 -0
  16. package/dist/freeze.js.map +1 -0
  17. package/dist/hook-checks.d.ts +31 -0
  18. package/dist/hook-checks.js +130 -0
  19. package/dist/hook-checks.js.map +1 -0
  20. package/dist/hook-runner.d.ts +96 -0
  21. package/dist/hook-runner.js +372 -0
  22. package/dist/hook-runner.js.map +1 -0
  23. package/dist/hooks.d.ts +183 -0
  24. package/dist/hooks.js +2 -0
  25. package/dist/hooks.js.map +1 -0
  26. package/dist/index.d.ts +26 -3
  27. package/dist/index.js +21 -3
  28. package/dist/index.js.map +1 -1
  29. package/dist/loop.d.ts +67 -0
  30. package/dist/loop.js +644 -0
  31. package/dist/loop.js.map +1 -0
  32. package/dist/observers.d.ts +31 -0
  33. package/dist/observers.js +98 -0
  34. package/dist/observers.js.map +1 -0
  35. package/dist/otel/attributes.d.ts +43 -0
  36. package/dist/otel/attributes.js +50 -0
  37. package/dist/otel/attributes.js.map +1 -0
  38. package/dist/otel/content.d.ts +17 -0
  39. package/dist/otel/content.js +48 -0
  40. package/dist/otel/content.js.map +1 -0
  41. package/dist/otel/index.d.ts +6 -2
  42. package/dist/otel/index.js +6 -2
  43. package/dist/otel/index.js.map +1 -1
  44. package/dist/otel/observer.d.ts +82 -0
  45. package/dist/otel/observer.js +300 -0
  46. package/dist/otel/observer.js.map +1 -0
  47. package/dist/pauses.d.ts +61 -0
  48. package/dist/pauses.js +83 -0
  49. package/dist/pauses.js.map +1 -0
  50. package/dist/progress.d.ts +34 -0
  51. package/dist/progress.js +139 -0
  52. package/dist/progress.js.map +1 -0
  53. package/dist/result.d.ts +134 -0
  54. package/dist/result.js +2 -0
  55. package/dist/result.js.map +1 -0
  56. package/dist/resume.d.ts +76 -0
  57. package/dist/resume.js +237 -0
  58. package/dist/resume.js.map +1 -0
  59. package/dist/run.d.ts +214 -0
  60. package/dist/run.js +327 -0
  61. package/dist/run.js.map +1 -0
  62. package/dist/steering.d.ts +52 -0
  63. package/dist/steering.js +104 -0
  64. package/dist/steering.js.map +1 -0
  65. package/dist/testing/scripted-model.d.ts +17 -2
  66. package/dist/testing/scripted-model.js +22 -4
  67. package/dist/testing/scripted-model.js.map +1 -1
  68. package/dist/tools/coerce.d.ts +15 -0
  69. package/dist/tools/coerce.js +93 -0
  70. package/dist/tools/coerce.js.map +1 -0
  71. package/dist/tools/define.d.ts +54 -0
  72. package/dist/tools/define.js +121 -0
  73. package/dist/tools/define.js.map +1 -0
  74. package/dist/tools/format-error.d.ts +13 -0
  75. package/dist/tools/format-error.js +66 -0
  76. package/dist/tools/format-error.js.map +1 -0
  77. package/dist/tools/outcome.d.ts +7 -0
  78. package/dist/tools/outcome.js +30 -0
  79. package/dist/tools/outcome.js.map +1 -0
  80. package/dist/tools/pipeline.d.ts +111 -0
  81. package/dist/tools/pipeline.js +382 -0
  82. package/dist/tools/pipeline.js.map +1 -0
  83. package/dist/tools/scheduler.d.ts +33 -0
  84. package/dist/tools/scheduler.js +51 -0
  85. package/dist/tools/scheduler.js.map +1 -0
  86. package/dist/tools/schema.d.ts +20 -0
  87. package/dist/tools/schema.js +100 -0
  88. package/dist/tools/schema.js.map +1 -0
  89. package/dist/tools/types.d.ts +196 -0
  90. package/dist/tools/types.js +2 -0
  91. package/dist/tools/types.js.map +1 -0
  92. package/dist/vendor/agent-safety/bytes.d.ts +17 -0
  93. package/dist/vendor/agent-safety/bytes.js +59 -0
  94. package/dist/vendor/agent-safety/bytes.js.map +1 -0
  95. package/dist/vendor/agent-safety/errors.d.ts +22 -0
  96. package/dist/vendor/agent-safety/errors.js +22 -0
  97. package/dist/vendor/agent-safety/errors.js.map +1 -0
  98. package/dist/vendor/agent-safety/hash.d.ts +16 -0
  99. package/dist/vendor/agent-safety/hash.js +110 -0
  100. package/dist/vendor/agent-safety/hash.js.map +1 -0
  101. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  102. package/dist/vendor/agent-safety/outcome.js +140 -0
  103. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  104. package/dist/vendor/agent-safety/pending.d.ts +119 -0
  105. package/dist/vendor/agent-safety/pending.js +122 -0
  106. package/dist/vendor/agent-safety/pending.js.map +1 -0
  107. package/dist/vendor/agent-safety/render.d.ts +40 -0
  108. package/dist/vendor/agent-safety/render.js +92 -0
  109. package/dist/vendor/agent-safety/render.js.map +1 -0
  110. package/dist/vendor/agent-safety/signer.d.ts +42 -0
  111. package/dist/vendor/agent-safety/signer.js +128 -0
  112. package/dist/vendor/agent-safety/signer.js.map +1 -0
  113. package/dist/version.d.ts +2 -0
  114. package/dist/version.js +8 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +13 -3
@@ -0,0 +1,157 @@
1
+ import { SdkError } from "./errors.js";
2
+ import { checkDecision, checkMessages, checkModelPatch, checkReplacement, checkResultPatch, checkStopDecision, } from "./hook-checks.js";
3
+ import { blockingHandlerOf, withBlockingHandler } from "./pauses.js";
4
+ function hooksOf(sets, name) {
5
+ return sets.flatMap((set) => (set[name] === undefined ? [] : [set[name]]));
6
+ }
7
+ // Each joined hook checks what every one of its hooks returns, as the run checks a hook used alone, so a hook's wrong
8
+ // return shape is never hidden by the hooks around it. The checks throw `invalid_hook_result`, which the run rethrows
9
+ // whatever `onFailure` says.
10
+ /** The fields of `patch` that are set: a field set to `undefined` doesn't erase what an earlier hook set. */
11
+ function definedFields(patch) {
12
+ return Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined));
13
+ }
14
+ /** Passes the messages through each `transformContext` in turn: the second sees the first's view. */
15
+ const transform = (hooks) => async (e) => {
16
+ let messages = e.messages;
17
+ for (const hook of hooks)
18
+ messages = checkMessages("transformContext", await hook({ ...e, messages }));
19
+ return messages;
20
+ };
21
+ /**
22
+ * Merges the patches in order: a later field wins, and each hook sees the system prompt, messages and options set
23
+ * before it. `context.tools` stays the list the run would send, because only the run can lower a tool it activates.
24
+ */
25
+ const before = (hooks) => async (e) => {
26
+ let event = e;
27
+ let merged;
28
+ for (const hook of hooks) {
29
+ const patch = checkModelPatch(await hook(event));
30
+ if (patch === undefined)
31
+ continue;
32
+ const fields = definedFields(patch);
33
+ merged = { ...merged, ...fields };
34
+ event = { ...event, context: contextAfter(event.context, fields), options: fields.options ?? event.options };
35
+ }
36
+ return merged;
37
+ };
38
+ function contextAfter(context, patch) {
39
+ return {
40
+ ...context,
41
+ system: patch.system ?? context.system,
42
+ messages: patch.messages === undefined ? context.messages : [...patch.messages],
43
+ };
44
+ }
45
+ /** Chains the replacements: each hook sees the message the one before it returned. */
46
+ const after = (hooks) => async (e) => {
47
+ let message = e.message;
48
+ for (const hook of hooks)
49
+ message = checkReplacement(await hook({ ...e, message })) ?? message;
50
+ return { message };
51
+ };
52
+ /**
53
+ * Asks each gate in turn and keeps the strictest answer: the first `deny` wins at once, an `ask` outranks an `allow`,
54
+ * and a replacement input from one gate is what the later gates see. The answer carries the last replacement, an
55
+ * `ask`'s included, so a pause signs the input the call would run with. A gate that throws makes the whole check fail.
56
+ */
57
+ const gate = (hooks) => async (e) => {
58
+ let input = e.input;
59
+ let asked;
60
+ for (const hook of hooks) {
61
+ const decision = checkDecision(await hook({ ...e, input }));
62
+ if (decision.decision === "deny")
63
+ return decision;
64
+ if (decision.decision === "ask")
65
+ asked ??= decision;
66
+ if (decision.input !== undefined)
67
+ input = decision.input;
68
+ }
69
+ const replaced = input === e.input ? {} : { input };
70
+ // An ask carries the input the later gates saw, so the pause is signed over the input the call would run with.
71
+ if (asked !== undefined)
72
+ return { ...asked, ...replaced };
73
+ return { decision: "allow", ...replaced };
74
+ };
75
+ /** Applies the patches in order: each hook sees the result with the earlier patches applied. */
76
+ const afterTool = (hooks) => async (e) => {
77
+ let result = e.result;
78
+ let merged;
79
+ for (const hook of hooks) {
80
+ const patch = checkResultPatch(await hook({ ...e, result }));
81
+ if (patch === undefined)
82
+ continue;
83
+ const fields = definedFields(patch);
84
+ merged = { ...merged, ...fields };
85
+ result = { ...result, ...fields };
86
+ }
87
+ return merged;
88
+ };
89
+ /** The first `stop` wins at once; otherwise the first `continue` stands; otherwise the run decides. */
90
+ const stop = (hooks) => async (e) => {
91
+ let keepGoing = false;
92
+ for (const hook of hooks) {
93
+ const decision = await hook(e);
94
+ checkStopDecision(decision);
95
+ if (typeof decision === "object" && "continue" in decision) {
96
+ if (keepGoing === false)
97
+ keepGoing = decision;
98
+ }
99
+ else if (decision !== false)
100
+ return decision;
101
+ }
102
+ return keepGoing;
103
+ };
104
+ /**
105
+ * Joins interceptor objects into one. For a moment that several objects define, the hooks run in the order given,
106
+ * and the result is:
107
+ *
108
+ * - `transformContext`: the messages pass through each hook in turn.
109
+ * - `beforeModelCall`: the patches are merged in order, a later field replacing an earlier one, and each hook sees
110
+ * the system prompt, messages and options the earlier ones set. A field left `undefined` keeps the earlier value.
111
+ * - `afterModelCall`: each hook sees the message the one before returned.
112
+ * - `beforeToolCall`: the strictest decision wins. The first `deny` ends the check, an `ask` beats `allow`, and an
113
+ * input one gate replaces is the input the next gate sees. When a gate asks, the `ask` carries the last
114
+ * replacement, so the pending request is signed over the input the call would run with.
115
+ * - `afterToolCall`: the patches are applied in order, each hook seeing the result so far.
116
+ * - `shouldStop`: the first `stop` wins; failing that, the first `continue`.
117
+ *
118
+ * Each hook's return value is checked as if the hook ran alone, so a wrong shape, such as a gate that returns nothing,
119
+ * throws an `SdkError` with code `invalid_hook_result` whatever the other hooks return. A hook that throws fails the
120
+ * moment it belongs to, because the joined hook is one function. The joined `onFailure` is
121
+ * `"continue"` only when every object sets it to `"continue"`; an object that leaves it unset counts as
122
+ * `"fail_closed"`. One lenient object therefore never loosens the others, and a join of a gate with a lenient audit
123
+ * hook fails closed. Set `"continue"` on all of them, and the gate then fails open too.
124
+ *
125
+ * An object from `blockingApprovals()` passes its handler on to the joined object. Joining two of them throws an
126
+ * `SdkError` with code `invalid_run_options`, because a request can have only one answer.
127
+ */
128
+ export function composeInterceptors(...sets) {
129
+ const lenient = sets.every((set) => (set.onFailure ?? "fail_closed") === "continue");
130
+ const hooks = {
131
+ transformContext: hooksOf(sets, "transformContext"),
132
+ beforeModelCall: hooksOf(sets, "beforeModelCall"),
133
+ afterModelCall: hooksOf(sets, "afterModelCall"),
134
+ beforeToolCall: hooksOf(sets, "beforeToolCall"),
135
+ afterToolCall: hooksOf(sets, "afterToolCall"),
136
+ shouldStop: hooksOf(sets, "shouldStop"),
137
+ };
138
+ const handlers = sets.flatMap((set) => {
139
+ const handler = blockingHandlerOf(set);
140
+ return handler === undefined ? [] : [handler];
141
+ });
142
+ if (handlers.length > 1) {
143
+ throw new SdkError("invalid_run_options", "composeInterceptors() can join only one blockingApprovals() object");
144
+ }
145
+ const joined = {
146
+ ...(hooks.transformContext.length === 0 ? {} : { transformContext: transform(hooks.transformContext) }),
147
+ ...(hooks.beforeModelCall.length === 0 ? {} : { beforeModelCall: before(hooks.beforeModelCall) }),
148
+ ...(hooks.afterModelCall.length === 0 ? {} : { afterModelCall: after(hooks.afterModelCall) }),
149
+ ...(hooks.beforeToolCall.length === 0 ? {} : { beforeToolCall: gate(hooks.beforeToolCall) }),
150
+ ...(hooks.afterToolCall.length === 0 ? {} : { afterToolCall: afterTool(hooks.afterToolCall) }),
151
+ ...(hooks.shouldStop.length === 0 ? {} : { shouldStop: stop(hooks.shouldStop) }),
152
+ onFailure: lenient && sets.length > 0 ? "continue" : "fail_closed",
153
+ };
154
+ const [handler] = handlers;
155
+ return handler === undefined ? joined : withBlockingHandler(joined, handler);
156
+ }
157
+ //# sourceMappingURL=compose.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.js","sourceRoot":"","sources":["../src/compose.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EACL,aAAa,EACb,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAU1B,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAIrE,SAAS,OAAO,CAAqD,IAA6B,EAAE,IAAO;IACzG,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAY,CAAC,CAAC,CAAC,CAAC;AACxF,CAAC;AAED,sHAAsH;AACtH,sHAAsH;AACtH,6BAA6B;AAE7B,6GAA6G;AAC7G,SAAS,aAAa,CAAmB,KAAQ;IAC/C,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAe,CAAC;AAC5G,CAAC;AAED,qGAAqG;AACrG,MAAM,SAAS,GACb,CAAC,KAA0C,EAA4B,EAAE,CACzE,KAAK,EAAE,CAAC,EAAE,EAAE;IACV,IAAI,QAAQ,GAAuB,CAAC,CAAC,QAAQ,CAAC;IAC9C,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,QAAQ,GAAG,aAAa,CAAC,kBAAkB,EAAE,MAAM,IAAI,CAAC,EAAE,GAA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AAC,CAAC,CAAC,EAAE,cAAc,EAAE,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,EAAE,CAAC;QAC7F,GAAG,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,EAAE,CAAC;QAC5F,GAAG,CAAC,KAAK,CAAC,aAAa,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,SAAS,CAAC,KAAK,CAAC,aAAa,CAAC,EAAE,CAAC;QAC9F,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC;QAChF,SAAS,EAAE,OAAO,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,aAAa;KACnE,CAAC;IACF,MAAM,CAAC,OAAO,CAAC,GAAG,QAAQ,CAAC;IAC3B,OAAO,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,mBAAmB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAC/E,CAAC","sourcesContent":["/**\n * `composeInterceptors()`: joins several interceptor objects into one, so a context policy, a permission pipeline and\n * an audit can each be written and tested alone. A run takes one `Interceptors` object, and the joined one is it.\n */\nimport type { Message, ModelContext } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport {\n checkDecision,\n checkMessages,\n checkModelPatch,\n checkReplacement,\n checkResultPatch,\n checkStopDecision,\n} from \"./hook-checks.js\";\nimport type {\n GateDecision,\n Interceptors,\n ModelCallEvent,\n ModelCallPatch,\n StepEvent,\n StopDecision,\n ToolResultPatch,\n} from \"./hooks.js\";\nimport { blockingHandlerOf, withBlockingHandler } from \"./pauses.js\";\n\ntype Hook<K extends keyof Interceptors> = NonNullable<Interceptors[K]>;\n\nfunction hooksOf<K extends Exclude<keyof Interceptors, \"onFailure\">>(sets: readonly Interceptors[], name: K) {\n return sets.flatMap((set) => (set[name] === undefined ? [] : [set[name] as Hook<K>]));\n}\n\n// Each joined hook checks what every one of its hooks returns, as the run checks a hook used alone, so a hook's wrong\n// return shape is never hidden by the hooks around it. The checks throw `invalid_hook_result`, which the run rethrows\n// whatever `onFailure` says.\n\n/** The fields of `patch` that are set: a field set to `undefined` doesn't erase what an earlier hook set. */\nfunction definedFields<T extends object>(patch: T): Partial<T> {\n return Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined)) as Partial<T>;\n}\n\n/** Passes the messages through each `transformContext` in turn: the second sees the first's view. */\nconst transform =\n (hooks: readonly Hook<\"transformContext\">[]): Hook<\"transformContext\"> =>\n async (e) => {\n let messages: readonly Message[] = e.messages;\n for (const hook of hooks) messages = checkMessages(\"transformContext\", await hook({ ...e, messages }));\n return messages;\n };\n\n/**\n * Merges the patches in order: a later field wins, and each hook sees the system prompt, messages and options set\n * before it. `context.tools` stays the list the run would send, because only the run can lower a tool it activates.\n */\nconst before =\n (hooks: readonly Hook<\"beforeModelCall\">[]): Hook<\"beforeModelCall\"> =>\n async (e) => {\n let event: ModelCallEvent = e;\n let merged: ModelCallPatch | undefined;\n for (const hook of hooks) {\n const patch = checkModelPatch(await hook(event));\n if (patch === undefined) continue;\n const fields = definedFields(patch);\n merged = { ...merged, ...fields };\n event = { ...event, context: contextAfter(event.context, fields), options: fields.options ?? event.options };\n }\n return merged;\n };\n\nfunction contextAfter(context: ModelContext, patch: ModelCallPatch): ModelContext {\n return {\n ...context,\n system: patch.system ?? context.system,\n messages: patch.messages === undefined ? context.messages : [...patch.messages],\n };\n}\n\n/** Chains the replacements: each hook sees the message the one before it returned. */\nconst after =\n (hooks: readonly Hook<\"afterModelCall\">[]): Hook<\"afterModelCall\"> =>\n async (e) => {\n let message = e.message;\n for (const hook of hooks) message = checkReplacement(await hook({ ...e, message })) ?? message;\n return { message };\n };\n\n/**\n * Asks each gate in turn and keeps the strictest answer: the first `deny` wins at once, an `ask` outranks an `allow`,\n * and a replacement input from one gate is what the later gates see. The answer carries the last replacement, an\n * `ask`'s included, so a pause signs the input the call would run with. A gate that throws makes the whole check fail.\n */\nconst gate =\n (hooks: readonly Hook<\"beforeToolCall\">[]): Hook<\"beforeToolCall\"> =>\n async (e) => {\n let input = e.input;\n let asked: GateDecision | undefined;\n for (const hook of hooks) {\n const decision = checkDecision(await hook({ ...e, input }));\n if (decision.decision === \"deny\") return decision;\n if (decision.decision === \"ask\") asked ??= decision;\n if (decision.input !== undefined) input = decision.input;\n }\n const replaced = input === e.input ? {} : { input };\n // An ask carries the input the later gates saw, so the pause is signed over the input the call would run with.\n if (asked !== undefined) return { ...asked, ...replaced };\n return { decision: \"allow\", ...replaced };\n };\n\n/** Applies the patches in order: each hook sees the result with the earlier patches applied. */\nconst afterTool =\n (hooks: readonly Hook<\"afterToolCall\">[]): Hook<\"afterToolCall\"> =>\n async (e) => {\n let result = e.result;\n let merged: ToolResultPatch | undefined;\n for (const hook of hooks) {\n const patch = checkResultPatch(await hook({ ...e, result }));\n if (patch === undefined) continue;\n const fields = definedFields(patch) as ToolResultPatch;\n merged = { ...merged, ...fields };\n result = { ...result, ...fields };\n }\n return merged;\n };\n\n/** The first `stop` wins at once; otherwise the first `continue` stands; otherwise the run decides. */\nconst stop =\n (hooks: readonly Hook<\"shouldStop\">[]): Hook<\"shouldStop\"> =>\n async (e: StepEvent) => {\n let keepGoing: StopDecision = false;\n for (const hook of hooks) {\n const decision = await hook(e);\n checkStopDecision(decision);\n if (typeof decision === \"object\" && \"continue\" in decision) {\n if (keepGoing === false) keepGoing = decision;\n } else if (decision !== false) return decision;\n }\n return keepGoing;\n };\n\n/**\n * Joins interceptor objects into one. For a moment that several objects define, the hooks run in the order given,\n * and the result is:\n *\n * - `transformContext`: the messages pass through each hook in turn.\n * - `beforeModelCall`: the patches are merged in order, a later field replacing an earlier one, and each hook sees\n * the system prompt, messages and options the earlier ones set. A field left `undefined` keeps the earlier value.\n * - `afterModelCall`: each hook sees the message the one before returned.\n * - `beforeToolCall`: the strictest decision wins. The first `deny` ends the check, an `ask` beats `allow`, and an\n * input one gate replaces is the input the next gate sees. When a gate asks, the `ask` carries the last\n * replacement, so the pending request is signed over the input the call would run with.\n * - `afterToolCall`: the patches are applied in order, each hook seeing the result so far.\n * - `shouldStop`: the first `stop` wins; failing that, the first `continue`.\n *\n * Each hook's return value is checked as if the hook ran alone, so a wrong shape, such as a gate that returns nothing,\n * throws an `SdkError` with code `invalid_hook_result` whatever the other hooks return. A hook that throws fails the\n * moment it belongs to, because the joined hook is one function. The joined `onFailure` is\n * `\"continue\"` only when every object sets it to `\"continue\"`; an object that leaves it unset counts as\n * `\"fail_closed\"`. One lenient object therefore never loosens the others, and a join of a gate with a lenient audit\n * hook fails closed. Set `\"continue\"` on all of them, and the gate then fails open too.\n *\n * An object from `blockingApprovals()` passes its handler on to the joined object. Joining two of them throws an\n * `SdkError` with code `invalid_run_options`, because a request can have only one answer.\n */\nexport function composeInterceptors(...sets: readonly Interceptors[]): Interceptors {\n const lenient = sets.every((set) => (set.onFailure ?? \"fail_closed\") === \"continue\");\n const hooks = {\n transformContext: hooksOf(sets, \"transformContext\"),\n beforeModelCall: hooksOf(sets, \"beforeModelCall\"),\n afterModelCall: hooksOf(sets, \"afterModelCall\"),\n beforeToolCall: hooksOf(sets, \"beforeToolCall\"),\n afterToolCall: hooksOf(sets, \"afterToolCall\"),\n shouldStop: hooksOf(sets, \"shouldStop\"),\n };\n const handlers = sets.flatMap((set) => {\n const handler = blockingHandlerOf(set);\n return handler === undefined ? [] : [handler];\n });\n if (handlers.length > 1) {\n throw new SdkError(\"invalid_run_options\", \"composeInterceptors() can join only one blockingApprovals() object\");\n }\n const joined: Interceptors = {\n ...(hooks.transformContext.length === 0 ? {} : { transformContext: transform(hooks.transformContext) }),\n ...(hooks.beforeModelCall.length === 0 ? {} : { beforeModelCall: before(hooks.beforeModelCall) }),\n ...(hooks.afterModelCall.length === 0 ? {} : { afterModelCall: after(hooks.afterModelCall) }),\n ...(hooks.beforeToolCall.length === 0 ? {} : { beforeToolCall: gate(hooks.beforeToolCall) }),\n ...(hooks.afterToolCall.length === 0 ? {} : { afterToolCall: afterTool(hooks.afterToolCall) }),\n ...(hooks.shouldStop.length === 0 ? {} : { shouldStop: stop(hooks.shouldStop) }),\n onFailure: lenient && sets.length > 0 ? \"continue\" : \"fail_closed\",\n };\n const [handler] = handlers;\n return handler === undefined ? joined : withBlockingHandler(joined, handler);\n}\n"]}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool
3
+ * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never
4
+ * thrown: the tool pipeline returns it to the model as an error result. Two subclasses keep their own names:
5
+ * `RunStoppedError`, which `runOrThrow()` throws for a run that did not finish, and the testing export's
6
+ * `UnexpectedModelCallError`.
7
+ */
8
+ import type { Context, UnfinishedResult } from "./result.js";
9
+ /** Why an `SdkError` was thrown. */
10
+ export type SdkErrorCode = "invalid_tool_definition" | "invalid_tool_result" | "invalid_run_options" | "invalid_model_stream" | "max_depth_exceeded" | "invalid_hook_result" | "hook_failed" | "run_stopped" | "undelivered_message" | "unexpected_model_call";
11
+ /**
12
+ * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,
13
+ * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's
14
+ * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an
15
+ * option it can't use, such as a model that isn't from `createModel()`, or `continueRun()` got a context it can't
16
+ * resume, such as one whose waiting call lost its pending request. `invalid_model_stream`: a model's stream ended
17
+ * without a final message. `max_depth_exceeded`: a tool started a run nested deeper than `maxDepth` allows.
18
+ * `invalid_hook_result`: an interceptor returned something its type does not allow, such as
19
+ * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor
20
+ * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
21
+ * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
22
+ * `RunStoppedError`).
23
+ * `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it
24
+ * could apply the message.
25
+ * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
26
+ * `UnexpectedModelCallError`).
27
+ */
28
+ export declare class SdkError extends Error {
29
+ readonly name: string;
30
+ readonly code: SdkErrorCode;
31
+ constructor(code: SdkErrorCode, message: string, options?: ErrorOptions);
32
+ }
33
+ /** True for an `SdkError`, including one from another copy of the package. */
34
+ export declare function isSdkError(error: unknown): error is SdkError;
35
+ /**
36
+ * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It
37
+ * carries the whole result, and the context to continue from: a paused run's context resumes with `continueRun()` and
38
+ * its resolutions. It is an `SdkError` with code `run_stopped`.
39
+ */
40
+ export declare class RunStoppedError extends SdkError {
41
+ readonly name = "RunStoppedError";
42
+ readonly stopReason: UnfinishedResult["stopReason"];
43
+ readonly result: UnfinishedResult;
44
+ /** The conversation so far, ready for `continueRun()`. */
45
+ readonly context: Context;
46
+ constructor(result: UnfinishedResult);
47
+ /** True for a `RunStoppedError`, including one from another copy of the package. Use it in place of `instanceof`. */
48
+ static isInstance(error: unknown): error is RunStoppedError;
49
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,57 @@
1
+ // A registered symbol, so the guard still works when two copies of the package are bundled.
2
+ const SDK_ERROR = Symbol.for("buildanagent.sdk.SdkError");
3
+ /**
4
+ * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,
5
+ * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's
6
+ * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an
7
+ * option it can't use, such as a model that isn't from `createModel()`, or `continueRun()` got a context it can't
8
+ * resume, such as one whose waiting call lost its pending request. `invalid_model_stream`: a model's stream ended
9
+ * without a final message. `max_depth_exceeded`: a tool started a run nested deeper than `maxDepth` allows.
10
+ * `invalid_hook_result`: an interceptor returned something its type does not allow, such as
11
+ * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor
12
+ * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,
13
+ * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a
14
+ * `RunStoppedError`).
15
+ * `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it
16
+ * could apply the message.
17
+ * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
18
+ * `UnexpectedModelCallError`).
19
+ */
20
+ export class SdkError extends Error {
21
+ name = "SdkError";
22
+ code;
23
+ constructor(code, message, options) {
24
+ super(message, options);
25
+ this.code = code;
26
+ Object.defineProperty(this, SDK_ERROR, { value: true });
27
+ }
28
+ }
29
+ /** True for an `SdkError`, including one from another copy of the package. */
30
+ export function isSdkError(error) {
31
+ return typeof error === "object" && error !== null && error[SDK_ERROR] === true;
32
+ }
33
+ const RUN_STOPPED_ERROR = Symbol.for("buildanagent.sdk.RunStoppedError");
34
+ /**
35
+ * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It
36
+ * carries the whole result, and the context to continue from: a paused run's context resumes with `continueRun()` and
37
+ * its resolutions. It is an `SdkError` with code `run_stopped`.
38
+ */
39
+ export class RunStoppedError extends SdkError {
40
+ name = "RunStoppedError";
41
+ stopReason;
42
+ result;
43
+ /** The conversation so far, ready for `continueRun()`. */
44
+ context;
45
+ constructor(result) {
46
+ super("run_stopped", `the run stopped with "${result.stopReason}" after ${result.steps} model calls`);
47
+ this.stopReason = result.stopReason;
48
+ this.result = result;
49
+ this.context = result.context;
50
+ Object.defineProperty(this, RUN_STOPPED_ERROR, { value: true });
51
+ }
52
+ /** True for a `RunStoppedError`, including one from another copy of the package. Use it in place of `instanceof`. */
53
+ static isInstance(error) {
54
+ return (typeof error === "object" && error !== null && error[RUN_STOPPED_ERROR] === true);
55
+ }
56
+ }
57
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAsBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAW,UAAU,CAAC;IACnC,IAAI,CAAe;IAE5B,YAAY,IAAkB,EAAE,OAAe,EAAE,OAAsB;QACrE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC;AAED,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;AAEzE;;;;GAIG;AACH,MAAM,OAAO,eAAgB,SAAQ,QAAQ;IACzB,IAAI,GAAG,iBAAiB,CAAC;IAClC,UAAU,CAAiC;IAC3C,MAAM,CAAmB;IAClC,0DAA0D;IACjD,OAAO,CAAU;IAE1B,YAAY,MAAwB;QAClC,KAAK,CAAC,aAAa,EAAE,yBAAyB,MAAM,CAAC,UAAU,WAAW,MAAM,CAAC,KAAK,cAAc,CAAC,CAAC;QACtG,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;IAED,qHAAqH;IACrH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,iBAAiB,CAAC,KAAK,IAAI,CAC9G,CAAC;IACJ,CAAC;CACF","sourcesContent":["/**\n * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool\n * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never\n * thrown: the tool pipeline returns it to the model as an error result. Two subclasses keep their own names:\n * `RunStoppedError`, which `runOrThrow()` throws for a run that did not finish, and the testing export's\n * `UnexpectedModelCallError`.\n */\nimport type { Context, UnfinishedResult } from \"./result.js\";\n\n/** Why an `SdkError` was thrown. */\nexport type SdkErrorCode =\n | \"invalid_tool_definition\"\n | \"invalid_tool_result\"\n | \"invalid_run_options\"\n | \"invalid_model_stream\"\n | \"max_depth_exceeded\"\n | \"invalid_hook_result\"\n | \"hook_failed\"\n | \"run_stopped\"\n | \"undelivered_message\"\n | \"unexpected_model_call\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SDK_ERROR = Symbol.for(\"buildanagent.sdk.SdkError\");\n\n/**\n * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema,\n * exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name. `invalid_tool_result`: a tool's\n * `execute` returned a malformed result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an\n * option it can't use, such as a model that isn't from `createModel()`, or `continueRun()` got a context it can't\n * resume, such as one whose waiting call lost its pending request. `invalid_model_stream`: a model's stream ended\n * without a final message. `max_depth_exceeded`: a tool started a run nested deeper than `maxDepth` allows.\n * `invalid_hook_result`: an interceptor returned something its type does not allow, such as\n * a gate that returned no decision, or a replacement input that fails the tool's schema. `hook_failed`: an interceptor\n * threw while the run fails closed. The run catches it and ends with an `error` result whose `error.kind` is `hook`,\n * so it never reaches your code. `run_stopped`: `runOrThrow()` was given a run that did not finish (a\n * `RunStoppedError`).\n * `undelivered_message`: `steer()` or `followUp()` was called on a run that had ended, or the run ended before it\n * could apply the message.\n * `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an\n * `UnexpectedModelCallError`).\n */\nexport class SdkError extends Error {\n override readonly name: string = \"SdkError\";\n readonly code: SdkErrorCode;\n\n constructor(code: SdkErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SDK_ERROR, { value: true });\n }\n}\n\n/** True for an `SdkError`, including one from another copy of the package. */\nexport function isSdkError(error: unknown): error is SdkError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SDK_ERROR] === true;\n}\n\nconst RUN_STOPPED_ERROR = Symbol.for(\"buildanagent.sdk.RunStoppedError\");\n\n/**\n * Thrown by `runOrThrow()` for a run that ended any way other than `done`, such as one that reached `maxSteps`. It\n * carries the whole result, and the context to continue from: a paused run's context resumes with `continueRun()` and\n * its resolutions. It is an `SdkError` with code `run_stopped`.\n */\nexport class RunStoppedError extends SdkError {\n override readonly name = \"RunStoppedError\";\n readonly stopReason: UnfinishedResult[\"stopReason\"];\n readonly result: UnfinishedResult;\n /** The conversation so far, ready for `continueRun()`. */\n readonly context: Context;\n\n constructor(result: UnfinishedResult) {\n super(\"run_stopped\", `the run stopped with \"${result.stopReason}\" after ${result.steps} model calls`);\n this.stopReason = result.stopReason;\n this.result = result;\n this.context = result.context;\n Object.defineProperty(this, RUN_STOPPED_ERROR, { value: true });\n }\n\n /** True for a `RunStoppedError`, including one from another copy of the package. Use it in place of `instanceof`. */\n static isInstance(error: unknown): error is RunStoppedError {\n return (\n typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[RUN_STOPPED_ERROR] === true\n );\n }\n}\n"]}
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The events a run streams: one closed union in two layers (agent-SDK guide §5). The delta layer streams each content
3
+ * block by its index; the item layer's end events (`model_call_end`, `tool_call_end`, `run_end`) carry the
4
+ * authoritative item, which a session log stores. `AGENT_EVENT_TYPES` lists the union at run time, so a test can
5
+ * check that the loop emits no type the union does not declare.
6
+ */
7
+ import type { AssistantMessage, ContentBlock, DumpedOptions, ModelContext, ModelRef } from "@buildanagent/gateway";
8
+ import type { RunError, RunResult } from "./result.js";
9
+ import type { DeliveryReceipt } from "./steering.js";
10
+ import type { ToolResult } from "./tools/types.js";
11
+ import type { RejectionCause, SignedPendingRequest } from "./vendor/agent-safety/pending.js";
12
+ /** The fields every event carries. `seq` counts the run's events from 0; `stepIndex` counts its model calls from 0. */
13
+ export interface EventBase {
14
+ readonly runId: string;
15
+ readonly seq: number;
16
+ readonly stepIndex: number;
17
+ /** When the event was emitted, from the run's clock, in ISO 8601. */
18
+ readonly timestamp: string;
19
+ }
20
+ /** One model call's request as the loop sends it: the model, the context and the options. */
21
+ export interface ModelCallRequest {
22
+ readonly model: ModelRef;
23
+ readonly context: ModelContext;
24
+ readonly options: DumpedOptions;
25
+ }
26
+ /**
27
+ * Why a `warning` event fired. `max_steps`: the run reached `maxSteps` and stopped. `model_warning`: the model call
28
+ * reported something that did not stop it, such as an option the provider would reject and the adapter dropped.
29
+ */
30
+ export type WarningCode = "max_steps" | "model_warning";
31
+ /**
32
+ * Why `continueRun()` refused a resolution or a stored request: one of `verifyResolution()`'s causes, `replayed` when
33
+ * two resolutions name one request, or `error` when the check itself threw, such as a signer whose `verify()` threw.
34
+ * `unknown_request` also covers a resolution that names no request in the context.
35
+ */
36
+ export type ResolutionRejectionCause = RejectionCause | "replayed" | "error";
37
+ /** The body of each event, without the fields of `EventBase`. */
38
+ export type AgentEventBody = {
39
+ readonly type: "run_start";
40
+ readonly sdkVersion: string;
41
+ readonly specVersion: "v1";
42
+ /** Reserved for a hash of the run's defaults; empty for now. */
43
+ readonly defaultsHash: string;
44
+ /** Reserved for the SDK's capability names; empty for now. */
45
+ readonly capabilities: readonly string[];
46
+ readonly model: ModelRef;
47
+ } | {
48
+ readonly type: "run_end";
49
+ readonly result: RunResult;
50
+ }
51
+ /** Fires once nothing is running any more, retries and tools included; `run_end` follows it. */
52
+ | {
53
+ readonly type: "agent_settled";
54
+ } | {
55
+ readonly type: "step_start";
56
+ } | {
57
+ readonly type: "step_end";
58
+ readonly stopCheck: "continue" | "stop";
59
+ } | {
60
+ readonly type: "model_call_start";
61
+ readonly request: ModelCallRequest;
62
+ } | {
63
+ readonly type: "model_call_end";
64
+ readonly message: AssistantMessage;
65
+ } | {
66
+ readonly type: "text_start" | "reasoning_start" | "tool_input_start";
67
+ readonly index: number;
68
+ } | {
69
+ readonly type: "text_delta" | "reasoning_delta" | "tool_input_delta";
70
+ readonly index: number;
71
+ readonly delta: string;
72
+ } | {
73
+ readonly type: "text_end" | "reasoning_end" | "tool_input_end";
74
+ readonly index: number;
75
+ readonly block: ContentBlock;
76
+ } | {
77
+ readonly type: "tool_call_start";
78
+ readonly callId: string;
79
+ readonly tool: string;
80
+ readonly input: unknown;
81
+ } | {
82
+ readonly type: "tool_call_update";
83
+ readonly callId: string;
84
+ readonly details: unknown;
85
+ }
86
+ /**
87
+ * `result` is what the model reads for the call, after `afterToolCall` has had its say. `input` is present only
88
+ * when a `beforeToolCall` gate replaced the model's input, and holds the input the gate gave the call instead.
89
+ */
90
+ | {
91
+ readonly type: "tool_call_end";
92
+ readonly callId: string;
93
+ readonly result: ToolResult;
94
+ readonly input?: unknown;
95
+ }
96
+ /** `transformContext` returned the messages for one model call: `before` messages in, `after` messages out. */
97
+ | {
98
+ readonly type: "context_transformed";
99
+ readonly before: number;
100
+ readonly after: number;
101
+ }
102
+ /** The model is retrying a failed request; `attempt` is 1 for the first retry. */
103
+ | {
104
+ readonly type: "retry";
105
+ readonly attempt: number;
106
+ readonly delayMs: number;
107
+ readonly error: string;
108
+ }
109
+ /**
110
+ * A queued steer or follow-up entered the transcript as a user message, at the start of the step named by
111
+ * `receipt.stepIndex`, before its model call. `receipt.kind` tells the two apart.
112
+ */
113
+ | {
114
+ readonly type: "steer_applied";
115
+ readonly receipt: DeliveryReceipt;
116
+ }
117
+ /**
118
+ * The run signed a pending request for a call that waits for a person; `request.kind` tells the two kinds apart.
119
+ * An `approval`: a gate returned `ask`. `input` is the input the request signs and the call would run with once
120
+ * approved: the model's input after coercion, `repair` and any gate's replacement, so show the approver this, not
121
+ * the model's raw arguments. It comes once every call of the step has been gated, after the call's
122
+ * `tool_call_start` and before any call of the step runs; under `blockingApprovals()` it comes before the run waits
123
+ * for the answer. A `clarification`: a tool asked the user `request.question`, and `input` is the input it ran
124
+ * with; it comes once every call of the step has its result. A waiting call gets no `tool_call_end`, and the run
125
+ * ends `awaiting_approval` or `clarification_requested` after the step.
126
+ */
127
+ | {
128
+ readonly type: "approval_request";
129
+ readonly request: SignedPendingRequest;
130
+ readonly input: unknown;
131
+ }
132
+ /**
133
+ * `continueRun()` refused a resolution, or a stored request it had to check: the call did not run, and unless the
134
+ * resolution named no request in the context, the call asks again with a new request, which an `approval_request`
135
+ * event follows. `requestId` is the id the resolution or the stored request gave, and `callId` the waiting call's,
136
+ * when there is one. It holds no signature and no key.
137
+ */
138
+ | {
139
+ readonly type: "resolution_rejected";
140
+ readonly requestId: string;
141
+ readonly callId?: string;
142
+ readonly cause: ResolutionRejectionCause;
143
+ }
144
+ /**
145
+ * An interceptor or an observer threw, or a pause could not be signed. `hook` names it (`beforeToolCall`,
146
+ * `observer`, `signer` and so on) and `error` is the thrown message; for `signer` it is a fixed text with the
147
+ * safety package's error code, never the signer's own message. The run goes on or fails by the interceptors'
148
+ * `onFailure` setting; a failed observer never affects it, and a call whose pause could not be signed is blocked.
149
+ */
150
+ | {
151
+ readonly type: "hook_error";
152
+ readonly hook: string;
153
+ readonly error: string;
154
+ } | {
155
+ readonly type: "warning";
156
+ readonly code: WarningCode;
157
+ readonly detail: string;
158
+ } | {
159
+ readonly type: "error";
160
+ readonly error: RunError;
161
+ } | {
162
+ readonly type: "abort";
163
+ readonly reason?: string;
164
+ };
165
+ /** One event of a run. Switch on `type`: the union is closed, so a `switch` over it can be exhaustive. */
166
+ export type AgentEvent = EventBase & AgentEventBody;
167
+ /** Every `AgentEvent` type. A run emits no type this list lacks. */
168
+ export declare const AGENT_EVENT_TYPES: readonly ["run_start", "step_start", "model_call_start", "retry", "text_start", "text_delta", "text_end", "reasoning_start", "reasoning_delta", "reasoning_end", "tool_input_start", "tool_input_delta", "tool_input_end", "warning", "model_call_end", "context_transformed", "hook_error", "steer_applied", "tool_call_start", "approval_request", "resolution_rejected", "tool_call_update", "tool_call_end", "step_end", "error", "abort", "agent_settled", "run_end"];
package/dist/events.js ADDED
@@ -0,0 +1,32 @@
1
+ /** Every `AgentEvent` type. A run emits no type this list lacks. */
2
+ export const AGENT_EVENT_TYPES = Object.freeze([
3
+ "run_start",
4
+ "step_start",
5
+ "model_call_start",
6
+ "retry",
7
+ "text_start",
8
+ "text_delta",
9
+ "text_end",
10
+ "reasoning_start",
11
+ "reasoning_delta",
12
+ "reasoning_end",
13
+ "tool_input_start",
14
+ "tool_input_delta",
15
+ "tool_input_end",
16
+ "warning",
17
+ "model_call_end",
18
+ "context_transformed",
19
+ "hook_error",
20
+ "steer_applied",
21
+ "tool_call_start",
22
+ "approval_request",
23
+ "resolution_rejected",
24
+ "tool_call_update",
25
+ "tool_call_end",
26
+ "step_end",
27
+ "error",
28
+ "abort",
29
+ "agent_settled",
30
+ "run_end",
31
+ ]);
32
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAiIA,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,eAAe;IACf,iBAAiB;IACjB,kBAAkB;IAClB,qBAAqB;IACrB,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 { DeliveryReceipt } from \"./steering.js\";\nimport type { ToolResult } from \"./tools/types.js\";\nimport type { RejectionCause, SignedPendingRequest } from \"./vendor/agent-safety/pending.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/**\n * Why `continueRun()` refused a resolution or a stored request: one of `verifyResolution()`'s causes, `replayed` when\n * two resolutions name one request, or `error` when the check itself threw, such as a signer whose `verify()` threw.\n * `unknown_request` also covers a resolution that names no request in the context.\n */\nexport type ResolutionRejectionCause = RejectionCause | \"replayed\" | \"error\";\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 * A queued steer or follow-up entered the transcript as a user message, at the start of the step named by\n * `receipt.stepIndex`, before its model call. `receipt.kind` tells the two apart.\n */\n | { readonly type: \"steer_applied\"; readonly receipt: DeliveryReceipt }\n /**\n * The run signed a pending request for a call that waits for a person; `request.kind` tells the two kinds apart.\n * An `approval`: a gate returned `ask`. `input` is the input the request signs and the call would run with once\n * approved: the model's input after coercion, `repair` and any gate's replacement, so show the approver this, not\n * the model's raw arguments. It comes once every call of the step has been gated, after the call's\n * `tool_call_start` and before any call of the step runs; under `blockingApprovals()` it comes before the run waits\n * for the answer. A `clarification`: a tool asked the user `request.question`, and `input` is the input it ran\n * with; it comes once every call of the step has its result. A waiting call gets no `tool_call_end`, and the run\n * ends `awaiting_approval` or `clarification_requested` after the step.\n */\n | { readonly type: \"approval_request\"; readonly request: SignedPendingRequest; readonly input: unknown }\n /**\n * `continueRun()` refused a resolution, or a stored request it had to check: the call did not run, and unless the\n * resolution named no request in the context, the call asks again with a new request, which an `approval_request`\n * event follows. `requestId` is the id the resolution or the stored request gave, and `callId` the waiting call's,\n * when there is one. It holds no signature and no key.\n */\n | {\n readonly type: \"resolution_rejected\";\n readonly requestId: string;\n readonly callId?: string;\n readonly cause: ResolutionRejectionCause;\n }\n /**\n * An interceptor or an observer threw, or a pause could not be signed. `hook` names it (`beforeToolCall`,\n * `observer`, `signer` and so on) and `error` is the thrown message; for `signer` it is a fixed text with the\n * safety package's error code, never the signer's own message. The run goes on or fails by the interceptors'\n * `onFailure` setting; a failed observer never affects it, and a call whose pause could not be signed is blocked.\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 \"steer_applied\",\n \"tool_call_start\",\n \"approval_request\",\n \"resolution_rejected\",\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"]}
@@ -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;