@buildanagent/sdk 0.1.0-alpha.1 → 0.1.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +424 -5
  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 +12 -2
  66. package/dist/testing/scripted-model.js +19 -2
  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 +23 -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,300 @@
1
+ /**
2
+ * The OpenTelemetry observer: projects a run's events onto GenAI spans. One `invoke_agent` span covers the run, a
3
+ * `chat` span covers each model call and an `execute_tool` span covers each tool call, both children of the run's
4
+ * span. The observer only watches, like every observer: a tracer that throws is reported as a `hook_error` event
5
+ * and never touches the run, and the run's own spans are still ended and forgotten.
6
+ *
7
+ * The observer writes to the tracer the caller passes and nowhere else. It imports nothing from OpenTelemetry, so
8
+ * `@opentelemetry/api` is the caller's dependency, and the trace context it needs comes in as options, not from an
9
+ * ambient context that Workers and other runtimes may not carry across `await`.
10
+ */
11
+ import { totalInput } from "@buildanagent/gateway";
12
+ import { GEN_AI_ATTRIBUTES as A, GEN_AI_OPERATIONS } from "./attributes.js";
13
+ import { inputMessagesJson, jsonValue, outputMessagesJson, resultParts, systemInstructionsJson } from "./content.js";
14
+ /** The `SpanKind` numbers of `@opentelemetry/api`. */
15
+ const SPAN_KIND_INTERNAL = 0;
16
+ const SPAN_KIND_CLIENT = 2;
17
+ /** `SpanStatusCode.ERROR` of `@opentelemetry/api`. */
18
+ const STATUS_ERROR = 2;
19
+ function millis(timestamp) {
20
+ const value = Date.parse(timestamp);
21
+ return Number.isNaN(value) ? undefined : value;
22
+ }
23
+ /** Marks a span failed. `message` is free text, so it goes in only when `withMessage`, which content capture sets. */
24
+ function failed(span, message, withMessage, errorType) {
25
+ if (errorType !== undefined)
26
+ span.setAttribute(A.errorType, errorType);
27
+ span.setStatus?.(withMessage ? { code: STATUS_ERROR, message } : { code: STATUS_ERROR });
28
+ }
29
+ /** The low-cardinality `error.type` of a thrown value: its `code`, then its `name`, then the conventions' `_OTHER`. */
30
+ function errorTypeOf(error) {
31
+ if (typeof error === "object" && error !== null) {
32
+ const { code, name } = error;
33
+ if (typeof code === "string" && code !== "")
34
+ return code;
35
+ if (typeof name === "string" && name !== "")
36
+ return name;
37
+ }
38
+ return "_OTHER";
39
+ }
40
+ /**
41
+ * Writes the usage attributes of one call or one run. Input counts every class, because the conventions' input
42
+ * tokens include cached tokens (D3). A usage the provider did not report writes nothing, since its counts are
43
+ * incomplete and zero would read as a measurement.
44
+ */
45
+ function setUsage(span, usage) {
46
+ if (usage.unreported === true)
47
+ return;
48
+ span.setAttribute(A.usageInputTokens, totalInput(usage));
49
+ span.setAttribute(A.usageOutputTokens, usage.output);
50
+ if (usage.cacheRead > 0)
51
+ span.setAttribute(A.usageCacheReadInputTokens, usage.cacheRead);
52
+ const cacheWrite = usage.cacheWrite["5m"] + usage.cacheWrite["1h"];
53
+ if (cacheWrite > 0)
54
+ span.setAttribute(A.usageCacheWriteInputTokens, cacheWrite);
55
+ if (usage.reasoning > 0)
56
+ span.setAttribute(A.usageReasoningOutputTokens, usage.reasoning);
57
+ }
58
+ /** The finish reason each stop reason of a model call reports; an aborted call is `interrupted`. */
59
+ const FINISH_REASONS = {
60
+ stop: "stop",
61
+ length: "length",
62
+ tool_calls: "tool_calls",
63
+ error: "error",
64
+ aborted: "interrupted",
65
+ };
66
+ /** Holds the open spans of each run and turns one event at a time into span calls. */
67
+ class Projection {
68
+ #options;
69
+ #tracer;
70
+ #captureContent;
71
+ #runs = new Map();
72
+ constructor(options) {
73
+ this.#options = options;
74
+ this.#tracer = options.tracer;
75
+ this.#captureContent = options.captureContent ?? false;
76
+ }
77
+ handle(event) {
78
+ if (event.type === "run_start") {
79
+ this.#startAgent(event);
80
+ return;
81
+ }
82
+ const spans = this.#runs.get(event.runId);
83
+ if (spans === undefined)
84
+ return;
85
+ switch (event.type) {
86
+ case "model_call_start":
87
+ this.#startModelCall(event, spans);
88
+ break;
89
+ case "model_call_end":
90
+ this.#endModelCall(event, spans);
91
+ break;
92
+ case "tool_call_start":
93
+ this.#startTool(event, spans);
94
+ break;
95
+ case "tool_call_end":
96
+ this.#endTool(event, spans);
97
+ break;
98
+ case "approval_request":
99
+ this.#pauseTool(event, spans);
100
+ break;
101
+ case "run_end":
102
+ this.#endRun(event, spans);
103
+ break;
104
+ default:
105
+ break;
106
+ }
107
+ }
108
+ #startAgent(event) {
109
+ const name = this.#options.agentName;
110
+ const agent = this.#tracer.startSpan(name === undefined ? GEN_AI_OPERATIONS.invokeAgent : `${GEN_AI_OPERATIONS.invokeAgent} ${name}`, {
111
+ kind: SPAN_KIND_INTERNAL,
112
+ attributes: {
113
+ [A.operationName]: GEN_AI_OPERATIONS.invokeAgent,
114
+ [A.providerName]: event.model.provider,
115
+ [A.requestModel]: event.model.id,
116
+ ...(name === undefined ? {} : { [A.agentName]: name }),
117
+ },
118
+ ...startTime(event),
119
+ }, this.#options.parentContext);
120
+ let childContext;
121
+ try {
122
+ childContext = this.#options.childContext(agent);
123
+ }
124
+ catch (error) {
125
+ // The run's span would otherwise stay open for ever, since the run is never registered to end it.
126
+ agent.end(millis(event.timestamp));
127
+ throw error;
128
+ }
129
+ this.#runs.set(event.runId, { agent, childContext, model: undefined, tools: new Map() });
130
+ }
131
+ #startModelCall(event, spans) {
132
+ const { model, context, options } = event.request;
133
+ const span = this.#tracer.startSpan(`${GEN_AI_OPERATIONS.chat} ${model.id}`, {
134
+ kind: SPAN_KIND_CLIENT,
135
+ attributes: {
136
+ [A.operationName]: GEN_AI_OPERATIONS.chat,
137
+ [A.providerName]: model.provider,
138
+ [A.requestModel]: model.id,
139
+ ...(options.maxOutputTokens === undefined ? {} : { [A.requestMaxTokens]: options.maxOutputTokens }),
140
+ ...(options.temperature === undefined ? {} : { [A.requestTemperature]: options.temperature }),
141
+ },
142
+ ...startTime(event),
143
+ }, spans.childContext);
144
+ // Registered before any content is written, so a throw below leaves a span the run's end can still close.
145
+ this.#replace(spans.model, event);
146
+ spans.model = span;
147
+ if (this.#captureContent) {
148
+ span.setAttribute(A.systemInstructions, systemInstructionsJson(context.system));
149
+ span.setAttribute(A.inputMessages, inputMessagesJson(context.messages));
150
+ }
151
+ }
152
+ #endModelCall(event, spans) {
153
+ const span = spans.model;
154
+ if (span === undefined)
155
+ return;
156
+ spans.model = undefined;
157
+ const { message } = event;
158
+ // No `gen_ai.response.model`: `message.model` is the model the request named, not the one the provider says
159
+ // answered, so writing it would claim a measurement the gateway does not make.
160
+ try {
161
+ span.setAttribute(A.responseFinishReasons, [FINISH_REASONS[message.stopReason]]);
162
+ setUsage(span, message.usage);
163
+ if (message.error !== undefined) {
164
+ const { kind, status } = message.error;
165
+ failed(span, message.error.message, this.#captureContent, status === undefined ? kind : String(status));
166
+ }
167
+ if (this.#captureContent)
168
+ span.setAttribute(A.outputMessages, outputMessagesJson(message.content));
169
+ }
170
+ finally {
171
+ span.end(millis(event.timestamp));
172
+ }
173
+ }
174
+ #startTool(event, spans) {
175
+ const span = this.#tracer.startSpan(`${GEN_AI_OPERATIONS.executeTool} ${event.tool}`, {
176
+ kind: SPAN_KIND_INTERNAL,
177
+ attributes: {
178
+ [A.operationName]: GEN_AI_OPERATIONS.executeTool,
179
+ [A.toolName]: event.tool,
180
+ [A.toolCallId]: event.callId,
181
+ [A.toolType]: "function",
182
+ },
183
+ ...startTime(event),
184
+ }, spans.childContext);
185
+ this.#replace(spans.tools.get(event.callId), event);
186
+ spans.tools.set(event.callId, span);
187
+ if (this.#captureContent)
188
+ span.setAttribute(A.toolCallArguments, jsonValue(event.input));
189
+ }
190
+ #endTool(event, spans) {
191
+ const span = spans.tools.get(event.callId);
192
+ if (span === undefined)
193
+ return;
194
+ spans.tools.delete(event.callId);
195
+ try {
196
+ if (event.result.isError === true)
197
+ failed(span, "the tool returned an error", true, "tool_error");
198
+ if (this.#captureContent) {
199
+ // A `beforeToolCall` gate may have replaced the model's input; the span records what the tool ran with.
200
+ if ("input" in event)
201
+ span.setAttribute(A.toolCallArguments, jsonValue(event.input));
202
+ span.setAttribute(A.toolCallResult, jsonValue(resultParts(event.result.content)));
203
+ }
204
+ }
205
+ finally {
206
+ span.end(millis(event.timestamp));
207
+ }
208
+ }
209
+ /**
210
+ * Ends the span of a call a gate paused. The call didn't fail, so the span carries no error; it records nothing of
211
+ * the signed request, whose signature and key id belong in the host's own store, not in telemetry.
212
+ */
213
+ #pauseTool(event, spans) {
214
+ const span = spans.tools.get(event.request.callId);
215
+ if (span === undefined)
216
+ return;
217
+ spans.tools.delete(event.request.callId);
218
+ span.end(millis(event.timestamp));
219
+ }
220
+ /** Ends a span that a new call with the same key is about to displace, so it is exported and not lost. */
221
+ #replace(open, event) {
222
+ if (open !== undefined)
223
+ this.#abort(open, "a new call started before this one finished", millis(event.timestamp));
224
+ }
225
+ /** Marks an unfinished span failed and ends it, even when marking it throws. */
226
+ #abort(span, message, end) {
227
+ try {
228
+ failed(span, message, true);
229
+ }
230
+ finally {
231
+ span.end(end);
232
+ }
233
+ }
234
+ #endRun(event, spans) {
235
+ const { result } = event;
236
+ this.#close(event.runId, spans, millis(event.timestamp), () => {
237
+ setUsage(spans.agent, result.usage);
238
+ if (result.stopReason === "error") {
239
+ failed(spans.agent, result.error.message, this.#captureContent, result.error.kind);
240
+ }
241
+ });
242
+ }
243
+ /** Ends a run that threw, as `OtelObserver.endRun` describes. */
244
+ abandon(runId, error) {
245
+ const spans = this.#runs.get(runId);
246
+ if (spans === undefined)
247
+ return;
248
+ const message = error instanceof Error ? error.message : String(error);
249
+ this.#close(runId, spans, undefined, () => {
250
+ failed(spans.agent, message, this.#captureContent, errorTypeOf(error));
251
+ });
252
+ }
253
+ /**
254
+ * Ends a run's open call spans as failed, marks its own span with `mark`, ends it and forgets the run. The run is
255
+ * forgotten and every span ended even when the tracer throws partway, so a failing tracer leaks nothing. The first
256
+ * error is rethrown after all of them have been tried.
257
+ */
258
+ #close(runId, spans, end, mark) {
259
+ this.#runs.delete(runId);
260
+ const open = [...(spans.model === undefined ? [] : [spans.model]), ...spans.tools.values()];
261
+ const errors = [];
262
+ const attempt = (step) => {
263
+ try {
264
+ step();
265
+ }
266
+ catch (error) {
267
+ errors.push(error);
268
+ }
269
+ };
270
+ for (const span of open)
271
+ attempt(() => this.#abort(span, "the run ended before this call finished", end));
272
+ attempt(mark);
273
+ attempt(() => spans.agent.end(end));
274
+ if (errors.length > 0)
275
+ throw errors[0];
276
+ }
277
+ }
278
+ /**
279
+ * Creates an observer that projects a run's events onto OpenTelemetry GenAI spans. Pass it in `run()`'s
280
+ * `observers`: an observer added later with `run.on()` misses `run_start`, so it records nothing for that run. One
281
+ * observer can serve many runs, because it keeps each run's spans apart by run id.
282
+ *
283
+ * Without `captureContent`, no span holds a prompt, a message, a tool argument, a tool result or an error message.
284
+ */
285
+ export function otelObserver(options) {
286
+ const projection = new Projection(options);
287
+ return Object.assign((event) => projection.handle(event), {
288
+ async flush() {
289
+ await options.forceFlush?.();
290
+ },
291
+ endRun(runId, error) {
292
+ projection.abandon(runId, error);
293
+ },
294
+ });
295
+ }
296
+ function startTime(event) {
297
+ const time = millis(event.timestamp);
298
+ return time === undefined ? {} : { startTime: time };
299
+ }
300
+ //# sourceMappingURL=observer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observer.js","sourceRoot":"","sources":["../../src/otel/observer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAyB,UAAU,EAAc,MAAM,uBAAuB,CAAC;AAGtF,OAAO,EAAE,iBAAiB,IAAI,CAAC,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC5E,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,kBAAkB,EAAE,WAAW,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAKrH,sDAAsD;AACtD,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,sDAAsD;AACtD,MAAM,YAAY,GAAG,CAAC,CAAC;AAkFvB,SAAS,MAAM,CAAC,SAAiB;IAC/B,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IACpC,OAAO,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC;AACjD,CAAC;AAED,sHAAsH;AACtH,SAAS,MAAM,CAAC,IAAc,EAAE,OAAe,EAAE,WAAoB,EAAE,SAAkB;IACvF,IAAI,SAAS,KAAK,SAAS;QAAE,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IACvE,IAAI,CAAC,SAAS,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;AAC3F,CAAC;AAED,uHAAuH;AACvH,SAAS,WAAW,CAAC,KAAc;IACjC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KACF,CAAC,CAAC;AACL,CAAC;AAED,SAAS,SAAS,CAAC,KAAiB;IAClC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IACrC,OAAO,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AACvD,CAAC","sourcesContent":["/**\n * The OpenTelemetry observer: projects a run's events onto GenAI spans. One `invoke_agent` span covers the run, a\n * `chat` span covers each model call and an `execute_tool` span covers each tool call, both children of the run's\n * span. The observer only watches, like every observer: a tracer that throws is reported as a `hook_error` event\n * and never touches the run, and the run's own spans are still ended and forgotten.\n *\n * The observer writes to the tracer the caller passes and nowhere else. It imports nothing from OpenTelemetry, so\n * `@opentelemetry/api` is the caller's dependency, and the trace context it needs comes in as options, not from an\n * ambient context that Workers and other runtimes may not carry across `await`.\n */\nimport { type AssistantMessage, totalInput, type Usage } from \"@buildanagent/gateway\";\nimport type { AgentEvent } from \"../events.js\";\nimport type { Observer } from \"../hooks.js\";\nimport { GEN_AI_ATTRIBUTES as A, GEN_AI_OPERATIONS } from \"./attributes.js\";\nimport { inputMessagesJson, jsonValue, outputMessagesJson, resultParts, systemInstructionsJson } from \"./content.js\";\n\n/** An attribute value a span accepts. */\nexport type AttributeValueLike = string | number | boolean | string[];\n\n/** The `SpanKind` numbers of `@opentelemetry/api`. */\nconst SPAN_KIND_INTERNAL = 0;\nconst SPAN_KIND_CLIENT = 2;\n/** `SpanStatusCode.ERROR` of `@opentelemetry/api`. */\nconst STATUS_ERROR = 2;\n\n/** What `startSpan` takes: the fields of `@opentelemetry/api`'s `SpanOptions` that the observer sets. */\nexport interface SpanOptionsLike {\n /** An OpenTelemetry `SpanKind` number: 0 is internal and 2 is client. */\n readonly kind?: number;\n readonly attributes?: Readonly<Record<string, AttributeValueLike>>;\n /** Start time in milliseconds since the Unix epoch. */\n readonly startTime?: number;\n}\n\n/** The span methods the observer calls. An OpenTelemetry `Span` has all of them. */\nexport interface SpanLike {\n setAttribute(name: string, value: AttributeValueLike): unknown;\n /** `code` 2 is `SpanStatusCode.ERROR`. */\n setStatus?(status: { readonly code: number; readonly message?: string }): unknown;\n /** `endTime` is in milliseconds since the Unix epoch. */\n end(endTime?: number): void;\n}\n\n/** The tracer method the observer calls. An OpenTelemetry `Tracer` has it, so a real tracer fits without a wrapper. */\nexport interface TracerLike {\n startSpan(name: string, options?: SpanOptionsLike, context?: unknown): SpanLike;\n}\n\n/** Options for `otelObserver()`. */\nexport interface OtelObserverOptions {\n /** The tracer that receives the spans. The observer exports nowhere else. */\n readonly tracer: TracerLike;\n /**\n * Whether to record content: the system prompt, the messages of each call, each tool's arguments and result, and\n * the message of each error as its span's status description. Off by default, because content can hold secrets\n * and personal data that a trace backend should not receive. An error's message can quote any of them, so with\n * content off a failed span gets only its error status and `error.type`.\n */\n readonly captureContent?: boolean;\n /** The agent's name: it names the `invoke_agent` span and sets `gen_ai.agent.name`. */\n readonly agentName?: string;\n /**\n * The context the run's span starts in, passed to the tracer as `startSpan`'s third argument: the caller's own\n * span, such as an incoming request's. Every run the observer serves starts in this one context, so when it\n * belongs to one request, create one observer for each request. Left out, the run's span starts in whatever the\n * tracer treats as its default, which for an OpenTelemetry tracer is the active context. A run that a tool starts\n * is another run to the observer, with the same `parentContext`: its span is not a child of the calling tool's\n * span, because events carry no parent run id.\n */\n readonly parentContext?: unknown;\n /**\n * Makes the context a child span starts in from the run's span, so the spans of model and tool calls are children\n * of the run's span in its trace. With OpenTelemetry's API, pass\n * `(span) => trace.setSpan(context.active(), span as Span)`. It is required because the observer imports nothing\n * from OpenTelemetry and so cannot build a context itself.\n */\n readonly childContext: (parent: SpanLike) => unknown;\n /**\n * Flushes the exporter behind the tracer, such as `() => provider.forceFlush()`. `flush()` on the observer calls\n * it, so a Worker can pass `observer.flush()` to `waitUntil` and keep its spans from dying with the request.\n */\n readonly forceFlush?: () => Promise<unknown>;\n}\n\n/** The observer `otelObserver()` returns: an `Observer` that can also flush its exporter and end a run that threw. */\nexport type OtelObserver = Observer & {\n /** Resolves once the exporter behind the tracer has flushed, or at once when `forceFlush` was not passed. */\n flush(): Promise<void>;\n /**\n * Ends the open spans of a run whose `result` rejected, as failed, and forgets the run. A run that throws, for a\n * programmer error such as a tool that returns a malformed result, sends no `run_end`, so without this call its\n * spans are never exported. `error.type` is the error's `code` when it has one, such as an `SdkError`'s, and its\n * `name` otherwise. It ends every span, then rethrows the first error a tracer threw. An unknown run id, or a run\n * that already ended, does nothing.\n */\n endRun(runId: string, error?: unknown): void;\n};\n\ninterface RunSpans {\n readonly agent: SpanLike;\n readonly childContext: unknown;\n model: SpanLike | undefined;\n readonly tools: Map<string, SpanLike>;\n}\n\nfunction millis(timestamp: string): number | undefined {\n const value = Date.parse(timestamp);\n return Number.isNaN(value) ? undefined : value;\n}\n\n/** Marks a span failed. `message` is free text, so it goes in only when `withMessage`, which content capture sets. */\nfunction failed(span: SpanLike, message: string, withMessage: boolean, errorType?: string): void {\n if (errorType !== undefined) span.setAttribute(A.errorType, errorType);\n span.setStatus?.(withMessage ? { code: STATUS_ERROR, message } : { code: STATUS_ERROR });\n}\n\n/** The low-cardinality `error.type` of a thrown value: its `code`, then its `name`, then the conventions' `_OTHER`. */\nfunction errorTypeOf(error: unknown): string {\n if (typeof error === \"object\" && error !== null) {\n const { code, name } = error as { code?: unknown; name?: unknown };\n if (typeof code === \"string\" && code !== \"\") return code;\n if (typeof name === \"string\" && name !== \"\") return name;\n }\n return \"_OTHER\";\n}\n\n/**\n * Writes the usage attributes of one call or one run. Input counts every class, because the conventions' input\n * tokens include cached tokens (D3). A usage the provider did not report writes nothing, since its counts are\n * incomplete and zero would read as a measurement.\n */\nfunction setUsage(span: SpanLike, usage: Usage): void {\n if (usage.unreported === true) return;\n span.setAttribute(A.usageInputTokens, totalInput(usage));\n span.setAttribute(A.usageOutputTokens, usage.output);\n if (usage.cacheRead > 0) span.setAttribute(A.usageCacheReadInputTokens, usage.cacheRead);\n const cacheWrite = usage.cacheWrite[\"5m\"] + usage.cacheWrite[\"1h\"];\n if (cacheWrite > 0) span.setAttribute(A.usageCacheWriteInputTokens, cacheWrite);\n if (usage.reasoning > 0) span.setAttribute(A.usageReasoningOutputTokens, usage.reasoning);\n}\n\n/** The finish reason each stop reason of a model call reports; an aborted call is `interrupted`. */\nconst FINISH_REASONS: Readonly<Record<AssistantMessage[\"stopReason\"], string>> = {\n stop: \"stop\",\n length: \"length\",\n tool_calls: \"tool_calls\",\n error: \"error\",\n aborted: \"interrupted\",\n};\n\n/** Holds the open spans of each run and turns one event at a time into span calls. */\nclass Projection {\n readonly #options: OtelObserverOptions;\n readonly #tracer: TracerLike;\n readonly #captureContent: boolean;\n readonly #runs = new Map<string, RunSpans>();\n\n constructor(options: OtelObserverOptions) {\n this.#options = options;\n this.#tracer = options.tracer;\n this.#captureContent = options.captureContent ?? false;\n }\n\n handle(event: AgentEvent): void {\n if (event.type === \"run_start\") {\n this.#startAgent(event);\n return;\n }\n const spans = this.#runs.get(event.runId);\n if (spans === undefined) return;\n switch (event.type) {\n case \"model_call_start\":\n this.#startModelCall(event, spans);\n break;\n case \"model_call_end\":\n this.#endModelCall(event, spans);\n break;\n case \"tool_call_start\":\n this.#startTool(event, spans);\n break;\n case \"tool_call_end\":\n this.#endTool(event, spans);\n break;\n case \"approval_request\":\n this.#pauseTool(event, spans);\n break;\n case \"run_end\":\n this.#endRun(event, spans);\n break;\n default:\n break;\n }\n }\n\n #startAgent(event: Extract<AgentEvent, { type: \"run_start\" }>): void {\n const name = this.#options.agentName;\n const agent = this.#tracer.startSpan(\n name === undefined ? GEN_AI_OPERATIONS.invokeAgent : `${GEN_AI_OPERATIONS.invokeAgent} ${name}`,\n {\n kind: SPAN_KIND_INTERNAL,\n attributes: {\n [A.operationName]: GEN_AI_OPERATIONS.invokeAgent,\n [A.providerName]: event.model.provider,\n [A.requestModel]: event.model.id,\n ...(name === undefined ? {} : { [A.agentName]: name }),\n },\n ...startTime(event),\n },\n this.#options.parentContext,\n );\n let childContext: unknown;\n try {\n childContext = this.#options.childContext(agent);\n } catch (error) {\n // The run's span would otherwise stay open for ever, since the run is never registered to end it.\n agent.end(millis(event.timestamp));\n throw error;\n }\n this.#runs.set(event.runId, { agent, childContext, model: undefined, tools: new Map() });\n }\n\n #startModelCall(event: Extract<AgentEvent, { type: \"model_call_start\" }>, spans: RunSpans): void {\n const { model, context, options } = event.request;\n const span = this.#tracer.startSpan(\n `${GEN_AI_OPERATIONS.chat} ${model.id}`,\n {\n kind: SPAN_KIND_CLIENT,\n attributes: {\n [A.operationName]: GEN_AI_OPERATIONS.chat,\n [A.providerName]: model.provider,\n [A.requestModel]: model.id,\n ...(options.maxOutputTokens === undefined ? {} : { [A.requestMaxTokens]: options.maxOutputTokens }),\n ...(options.temperature === undefined ? {} : { [A.requestTemperature]: options.temperature }),\n },\n ...startTime(event),\n },\n spans.childContext,\n );\n // Registered before any content is written, so a throw below leaves a span the run's end can still close.\n this.#replace(spans.model, event);\n spans.model = span;\n if (this.#captureContent) {\n span.setAttribute(A.systemInstructions, systemInstructionsJson(context.system));\n span.setAttribute(A.inputMessages, inputMessagesJson(context.messages));\n }\n }\n\n #endModelCall(event: Extract<AgentEvent, { type: \"model_call_end\" }>, spans: RunSpans): void {\n const span = spans.model;\n if (span === undefined) return;\n spans.model = undefined;\n const { message } = event;\n // No `gen_ai.response.model`: `message.model` is the model the request named, not the one the provider says\n // answered, so writing it would claim a measurement the gateway does not make.\n try {\n span.setAttribute(A.responseFinishReasons, [FINISH_REASONS[message.stopReason]]);\n setUsage(span, message.usage);\n if (message.error !== undefined) {\n const { kind, status } = message.error;\n failed(span, message.error.message, this.#captureContent, status === undefined ? kind : String(status));\n }\n if (this.#captureContent) span.setAttribute(A.outputMessages, outputMessagesJson(message.content));\n } finally {\n span.end(millis(event.timestamp));\n }\n }\n\n #startTool(event: Extract<AgentEvent, { type: \"tool_call_start\" }>, spans: RunSpans): void {\n const span = this.#tracer.startSpan(\n `${GEN_AI_OPERATIONS.executeTool} ${event.tool}`,\n {\n kind: SPAN_KIND_INTERNAL,\n attributes: {\n [A.operationName]: GEN_AI_OPERATIONS.executeTool,\n [A.toolName]: event.tool,\n [A.toolCallId]: event.callId,\n [A.toolType]: \"function\",\n },\n ...startTime(event),\n },\n spans.childContext,\n );\n this.#replace(spans.tools.get(event.callId), event);\n spans.tools.set(event.callId, span);\n if (this.#captureContent) span.setAttribute(A.toolCallArguments, jsonValue(event.input));\n }\n\n #endTool(event: Extract<AgentEvent, { type: \"tool_call_end\" }>, spans: RunSpans): void {\n const span = spans.tools.get(event.callId);\n if (span === undefined) return;\n spans.tools.delete(event.callId);\n try {\n if (event.result.isError === true) failed(span, \"the tool returned an error\", true, \"tool_error\");\n if (this.#captureContent) {\n // A `beforeToolCall` gate may have replaced the model's input; the span records what the tool ran with.\n if (\"input\" in event) span.setAttribute(A.toolCallArguments, jsonValue(event.input));\n span.setAttribute(A.toolCallResult, jsonValue(resultParts(event.result.content)));\n }\n } finally {\n span.end(millis(event.timestamp));\n }\n }\n\n /**\n * Ends the span of a call a gate paused. The call didn't fail, so the span carries no error; it records nothing of\n * the signed request, whose signature and key id belong in the host's own store, not in telemetry.\n */\n #pauseTool(event: Extract<AgentEvent, { type: \"approval_request\" }>, spans: RunSpans): void {\n const span = spans.tools.get(event.request.callId);\n if (span === undefined) return;\n spans.tools.delete(event.request.callId);\n span.end(millis(event.timestamp));\n }\n\n /** Ends a span that a new call with the same key is about to displace, so it is exported and not lost. */\n #replace(open: SpanLike | undefined, event: AgentEvent): void {\n if (open !== undefined) this.#abort(open, \"a new call started before this one finished\", millis(event.timestamp));\n }\n\n /** Marks an unfinished span failed and ends it, even when marking it throws. */\n #abort(span: SpanLike, message: string, end: number | undefined): void {\n try {\n failed(span, message, true);\n } finally {\n span.end(end);\n }\n }\n\n #endRun(event: Extract<AgentEvent, { type: \"run_end\" }>, spans: RunSpans): void {\n const { result } = event;\n this.#close(event.runId, spans, millis(event.timestamp), () => {\n setUsage(spans.agent, result.usage);\n if (result.stopReason === \"error\") {\n failed(spans.agent, result.error.message, this.#captureContent, result.error.kind);\n }\n });\n }\n\n /** Ends a run that threw, as `OtelObserver.endRun` describes. */\n abandon(runId: string, error: unknown): void {\n const spans = this.#runs.get(runId);\n if (spans === undefined) return;\n const message = error instanceof Error ? error.message : String(error);\n this.#close(runId, spans, undefined, () => {\n failed(spans.agent, message, this.#captureContent, errorTypeOf(error));\n });\n }\n\n /**\n * Ends a run's open call spans as failed, marks its own span with `mark`, ends it and forgets the run. The run is\n * forgotten and every span ended even when the tracer throws partway, so a failing tracer leaks nothing. The first\n * error is rethrown after all of them have been tried.\n */\n #close(runId: string, spans: RunSpans, end: number | undefined, mark: () => void): void {\n this.#runs.delete(runId);\n const open = [...(spans.model === undefined ? [] : [spans.model]), ...spans.tools.values()];\n const errors: unknown[] = [];\n const attempt = (step: () => void): void => {\n try {\n step();\n } catch (error) {\n errors.push(error);\n }\n };\n for (const span of open) attempt(() => this.#abort(span, \"the run ended before this call finished\", end));\n attempt(mark);\n attempt(() => spans.agent.end(end));\n if (errors.length > 0) throw errors[0];\n }\n}\n\n/**\n * Creates an observer that projects a run's events onto OpenTelemetry GenAI spans. Pass it in `run()`'s\n * `observers`: an observer added later with `run.on()` misses `run_start`, so it records nothing for that run. One\n * observer can serve many runs, because it keeps each run's spans apart by run id.\n *\n * Without `captureContent`, no span holds a prompt, a message, a tool argument, a tool result or an error message.\n */\nexport function otelObserver(options: OtelObserverOptions): OtelObserver {\n const projection = new Projection(options);\n return Object.assign((event: AgentEvent) => projection.handle(event), {\n async flush(): Promise<void> {\n await options.forceFlush?.();\n },\n endRun(runId: string, error?: unknown): void {\n projection.abandon(runId, error);\n },\n });\n}\n\nfunction startTime(event: AgentEvent): { readonly startTime?: number } {\n const time = millis(event.timestamp);\n return time === undefined ? {} : { startTime: time };\n}\n"]}
@@ -0,0 +1,61 @@
1
+ import type { Interceptors, MaybePromise } from "./hooks.js";
2
+ import { type PendingFields, type Resolution, type SignedPendingRequest, type SignPendingOptions } from "./vendor/agent-safety/pending.js";
3
+ import type { ApprovalSigner } from "./vendor/agent-safety/signer.js";
4
+ /** The fields of an approval request built outside a run: the call that waits, and why. */
5
+ export interface PendingRequestFields {
6
+ /** Always `"approval"`: a request built outside a run waits for allow or deny. */
7
+ readonly kind: "approval";
8
+ /** The id of the tool call that waits. */
9
+ readonly callId: string;
10
+ /** The tool's name. */
11
+ readonly tool: string;
12
+ /** The call's input. The request stores its `canonicalInputHash()`, never the input itself. */
13
+ readonly input: unknown;
14
+ /** The version of the policy that asked for the approval, if the host versions its policy. It is signed. */
15
+ readonly policyVersion?: string;
16
+ /** Why the call needs a person, as shown to the approver. It is not signed. */
17
+ readonly reason?: string;
18
+ }
19
+ /** The one call the SDK signs a pending request through, from the loop and from `createPendingRequest()`. */
20
+ export declare function signPause(fields: PendingFields, signer: ApprovalSigner, options: SignPendingOptions): Promise<SignedPendingRequest>;
21
+ /** True when `signer` has the shape of an `ApprovalSigner`; its key material is never read or reported. */
22
+ export declare function isSigner(signer: unknown): signer is ApprovalSigner;
23
+ /**
24
+ * Signs an approval request for a tool call outside a run, such as a call your own code wants to make, with the
25
+ * payload a run writes when a gate returns `ask`: for the same fields, id and signer, the two requests and their
26
+ * signatures are identical. Store the request, and check a person's answer against it before the call runs.
27
+ *
28
+ * `options.generateId` makes the request's id (default `crypto.randomUUID()`) and `options.now` its `createdAt`
29
+ * (default the current time). Rejects with an `SdkError` with code `invalid_run_options` for a `kind` other than
30
+ * `"approval"` or a signer that isn't an `ApprovalSigner`, and with a `SafetyError` with code `invalid_pending` for a
31
+ * blank field or `invalid_input` for an input with no canonical JSON form.
32
+ */
33
+ export declare function createPendingRequest(fields: PendingRequestFields, signer: ApprovalSigner, options?: SignPendingOptions): Promise<SignedPendingRequest>;
34
+ /** What a blocking approval handler receives besides the request: the input it signs, and the run's abort signal. */
35
+ export interface ApprovalDetails {
36
+ /** The input the request signs and the call runs with once allowed. Show the approver this input. */
37
+ readonly input: unknown;
38
+ /** Fires when the run is aborted; the call then doesn't run, whatever the handler answers. */
39
+ readonly signal: AbortSignal;
40
+ }
41
+ /** Answers one approval request while the run waits: return `{ requestId: request.id, decision }`. */
42
+ export type ApprovalHandler = (request: SignedPendingRequest, details: ApprovalDetails) => MaybePromise<Resolution>;
43
+ /** The blocking approval handler an interceptors object carries, if it carries one. */
44
+ export declare function blockingHandlerOf(interceptors: Interceptors): ApprovalHandler | undefined;
45
+ /** An interceptors object that carries `handler`, for `blockingApprovals()` and `composeInterceptors()`. */
46
+ export declare function withBlockingHandler(interceptors: Interceptors, handler: ApprovalHandler): Interceptors;
47
+ /**
48
+ * Answers approvals inside the run, for a host where the person answers while the process waits, such as a terminal.
49
+ * Join the result with your gate in `composeInterceptors()`, or spread it into your interceptors. When a gate returns
50
+ * `ask`, the run signs the pending request and emits `approval_request` first, so a crash while it waits still
51
+ * leaves a signed record to resume from. It then calls `handler` and waits for its answer. A `Resolution` with
52
+ * `decision: "allow"` runs the call with the input the request signs, and `"deny"` gives the model an error result
53
+ * with the reason. An answer that doesn't name the request, isn't allow or deny, or comes from a handler that throws
54
+ * denies the call and emits `hook_error`, whatever `onFailure` says, and an abort while the run waits denies it too.
55
+ * A question from `clarificationTool()` still ends the run `clarification_requested`.
56
+ *
57
+ * Use it only where the run and the person share a process. Anywhere else, let the run end `awaiting_approval` and
58
+ * resume it with `continueRun()`. Throws an `SdkError` with code `invalid_run_options` when `handler` isn't a
59
+ * function.
60
+ */
61
+ export declare function blockingApprovals(handler: ApprovalHandler): Interceptors;
package/dist/pauses.js ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Signed pauses (D5). The signers, the input hash and the pending record belong to the safety package; this file only
3
+ * holds the one path the SDK signs through, which the loop and `createPendingRequest()` both call, so a pause the loop
4
+ * writes and one built outside a run cannot drift apart.
5
+ */
6
+ import { SdkError } from "./errors.js";
7
+ import { signPending, } from "./vendor/agent-safety/pending.js";
8
+ /** The one call the SDK signs a pending request through, from the loop and from `createPendingRequest()`. */
9
+ export function signPause(fields, signer, options) {
10
+ return signPending(fields, signer, options);
11
+ }
12
+ /** True when `signer` has the shape of an `ApprovalSigner`; its key material is never read or reported. */
13
+ export function isSigner(signer) {
14
+ if (typeof signer !== "object" || signer === null)
15
+ return false;
16
+ const { keyId, sign, verify } = signer;
17
+ return typeof keyId === "string" && typeof sign === "function" && typeof verify === "function";
18
+ }
19
+ /**
20
+ * Signs an approval request for a tool call outside a run, such as a call your own code wants to make, with the
21
+ * payload a run writes when a gate returns `ask`: for the same fields, id and signer, the two requests and their
22
+ * signatures are identical. Store the request, and check a person's answer against it before the call runs.
23
+ *
24
+ * `options.generateId` makes the request's id (default `crypto.randomUUID()`) and `options.now` its `createdAt`
25
+ * (default the current time). Rejects with an `SdkError` with code `invalid_run_options` for a `kind` other than
26
+ * `"approval"` or a signer that isn't an `ApprovalSigner`, and with a `SafetyError` with code `invalid_pending` for a
27
+ * blank field or `invalid_input` for an input with no canonical JSON form.
28
+ */
29
+ export function createPendingRequest(fields, signer, options = {}) {
30
+ if (fields?.kind !== "approval") {
31
+ return Promise.reject(new SdkError("invalid_run_options", `createPendingRequest() signs approvals only, so kind must be "approval"`));
32
+ }
33
+ if (!isSigner(signer)) {
34
+ return Promise.reject(new SdkError("invalid_run_options", "createPendingRequest() needs an ApprovalSigner, such as hmacSigner()"));
35
+ }
36
+ const { kind, callId, tool, input, policyVersion, reason } = fields;
37
+ return signPause({
38
+ kind,
39
+ callId,
40
+ tool,
41
+ input,
42
+ ...(policyVersion === undefined ? {} : { policyVersion }),
43
+ ...(reason === undefined ? {} : { reason }),
44
+ }, signer, options);
45
+ }
46
+ // The handler travels on an interceptors object under this key, so it joins with `composeInterceptors()` and a
47
+ // spread, and the six hook moments stay as they are.
48
+ const BLOCKING_HANDLER = Symbol("buildanagent.sdk.blockingApprovals");
49
+ /** The blocking approval handler an interceptors object carries, if it carries one. */
50
+ export function blockingHandlerOf(interceptors) {
51
+ const handler = interceptors[BLOCKING_HANDLER];
52
+ if (handler === undefined)
53
+ return undefined;
54
+ if (typeof handler !== "function") {
55
+ throw new SdkError("invalid_run_options", "the blockingApprovals() handler must be a function");
56
+ }
57
+ return handler;
58
+ }
59
+ /** An interceptors object that carries `handler`, for `blockingApprovals()` and `composeInterceptors()`. */
60
+ export function withBlockingHandler(interceptors, handler) {
61
+ return { ...interceptors, [BLOCKING_HANDLER]: handler };
62
+ }
63
+ /**
64
+ * Answers approvals inside the run, for a host where the person answers while the process waits, such as a terminal.
65
+ * Join the result with your gate in `composeInterceptors()`, or spread it into your interceptors. When a gate returns
66
+ * `ask`, the run signs the pending request and emits `approval_request` first, so a crash while it waits still
67
+ * leaves a signed record to resume from. It then calls `handler` and waits for its answer. A `Resolution` with
68
+ * `decision: "allow"` runs the call with the input the request signs, and `"deny"` gives the model an error result
69
+ * with the reason. An answer that doesn't name the request, isn't allow or deny, or comes from a handler that throws
70
+ * denies the call and emits `hook_error`, whatever `onFailure` says, and an abort while the run waits denies it too.
71
+ * A question from `clarificationTool()` still ends the run `clarification_requested`.
72
+ *
73
+ * Use it only where the run and the person share a process. Anywhere else, let the run end `awaiting_approval` and
74
+ * resume it with `continueRun()`. Throws an `SdkError` with code `invalid_run_options` when `handler` isn't a
75
+ * function.
76
+ */
77
+ export function blockingApprovals(handler) {
78
+ if (typeof handler !== "function") {
79
+ throw new SdkError("invalid_run_options", "blockingApprovals() needs a function that answers each request");
80
+ }
81
+ return withBlockingHandler({}, handler);
82
+ }
83
+ //# sourceMappingURL=pauses.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pauses.js","sourceRoot":"","sources":["../src/pauses.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAKL,WAAW,GACZ,MAAM,kCAAkC,CAAC;AAmB1C,6GAA6G;AAC7G,MAAM,UAAU,SAAS,CACvB,MAAqB,EACrB,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KAC5C,EACD,MAAM,EACN,OAAO,CACR,CAAC;AACJ,CAAC;AAaD,+GAA+G;AAC/G,qDAAqD;AACrD,MAAM,gBAAgB,GAAG,MAAM,CAAC,oCAAoC,CAAC,CAAC;AAEtE,uFAAuF;AACvF,MAAM,UAAU,iBAAiB,CAAC,YAA0B;IAC1D,MAAM,OAAO,GAAa,YAAwC,CAAC,gBAAgB,CAAC,CAAC;IACrF,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC5C,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;QAClC,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,oDAAoD,CAAC,CAAC;IAClG,CAAC;IACD,OAAO,OAA0B,CAAC;AACpC,CAAC;AAED,4GAA4G;AAC5G,MAAM,UAAU,mBAAmB,CAAC,YAA0B,EAAE,OAAwB;IACtF,OAAO,EAAE,GAAG,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,EAAkB,CAAC;AAC1E,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAwB;IACxD,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;QAClC,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,gEAAgE,CAAC,CAAC;IAC9G,CAAC;IACD,OAAO,mBAAmB,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["/**\n * Signed pauses (D5). The signers, the input hash and the pending record belong to the safety package; this file only\n * holds the one path the SDK signs through, which the loop and `createPendingRequest()` both call, so a pause the loop\n * writes and one built outside a run cannot drift apart.\n */\nimport { SdkError } from \"./errors.js\";\nimport type { Interceptors, MaybePromise } from \"./hooks.js\";\nimport {\n type PendingFields,\n type Resolution,\n type SignedPendingRequest,\n type SignPendingOptions,\n signPending,\n} from \"./vendor/agent-safety/pending.js\";\nimport type { ApprovalSigner } from \"./vendor/agent-safety/signer.js\";\n\n/** The fields of an approval request built outside a run: the call that waits, and why. */\nexport interface PendingRequestFields {\n /** Always `\"approval\"`: a request built outside a run waits for allow or deny. */\n readonly kind: \"approval\";\n /** The id of the tool call that waits. */\n readonly callId: string;\n /** The tool's name. */\n readonly tool: string;\n /** The call's input. The request stores its `canonicalInputHash()`, never the input itself. */\n readonly input: unknown;\n /** The version of the policy that asked for the approval, if the host versions its policy. It is signed. */\n readonly policyVersion?: string;\n /** Why the call needs a person, as shown to the approver. It is not signed. */\n readonly reason?: string;\n}\n\n/** The one call the SDK signs a pending request through, from the loop and from `createPendingRequest()`. */\nexport function signPause(\n fields: PendingFields,\n signer: ApprovalSigner,\n options: SignPendingOptions,\n): Promise<SignedPendingRequest> {\n return signPending(fields, signer, options);\n}\n\n/** True when `signer` has the shape of an `ApprovalSigner`; its key material is never read or reported. */\nexport function isSigner(signer: unknown): signer is ApprovalSigner {\n if (typeof signer !== \"object\" || signer === null) return false;\n const { keyId, sign, verify } = signer as Partial<ApprovalSigner>;\n return typeof keyId === \"string\" && typeof sign === \"function\" && typeof verify === \"function\";\n}\n\n/**\n * Signs an approval request for a tool call outside a run, such as a call your own code wants to make, with the\n * payload a run writes when a gate returns `ask`: for the same fields, id and signer, the two requests and their\n * signatures are identical. Store the request, and check a person's answer against it before the call runs.\n *\n * `options.generateId` makes the request's id (default `crypto.randomUUID()`) and `options.now` its `createdAt`\n * (default the current time). Rejects with an `SdkError` with code `invalid_run_options` for a `kind` other than\n * `\"approval\"` or a signer that isn't an `ApprovalSigner`, and with a `SafetyError` with code `invalid_pending` for a\n * blank field or `invalid_input` for an input with no canonical JSON form.\n */\nexport function createPendingRequest(\n fields: PendingRequestFields,\n signer: ApprovalSigner,\n options: SignPendingOptions = {},\n): Promise<SignedPendingRequest> {\n if (fields?.kind !== \"approval\") {\n return Promise.reject(\n new SdkError(\"invalid_run_options\", `createPendingRequest() signs approvals only, so kind must be \"approval\"`),\n );\n }\n if (!isSigner(signer)) {\n return Promise.reject(\n new SdkError(\"invalid_run_options\", \"createPendingRequest() needs an ApprovalSigner, such as hmacSigner()\"),\n );\n }\n const { kind, callId, tool, input, policyVersion, reason } = fields;\n return signPause(\n {\n kind,\n callId,\n tool,\n input,\n ...(policyVersion === undefined ? {} : { policyVersion }),\n ...(reason === undefined ? {} : { reason }),\n },\n signer,\n options,\n );\n}\n\n/** What a blocking approval handler receives besides the request: the input it signs, and the run's abort signal. */\nexport interface ApprovalDetails {\n /** The input the request signs and the call runs with once allowed. Show the approver this input. */\n readonly input: unknown;\n /** Fires when the run is aborted; the call then doesn't run, whatever the handler answers. */\n readonly signal: AbortSignal;\n}\n\n/** Answers one approval request while the run waits: return `{ requestId: request.id, decision }`. */\nexport type ApprovalHandler = (request: SignedPendingRequest, details: ApprovalDetails) => MaybePromise<Resolution>;\n\n// The handler travels on an interceptors object under this key, so it joins with `composeInterceptors()` and a\n// spread, and the six hook moments stay as they are.\nconst BLOCKING_HANDLER = Symbol(\"buildanagent.sdk.blockingApprovals\");\n\n/** The blocking approval handler an interceptors object carries, if it carries one. */\nexport function blockingHandlerOf(interceptors: Interceptors): ApprovalHandler | undefined {\n const handler: unknown = (interceptors as Record<symbol, unknown>)[BLOCKING_HANDLER];\n if (handler === undefined) return undefined;\n if (typeof handler !== \"function\") {\n throw new SdkError(\"invalid_run_options\", \"the blockingApprovals() handler must be a function\");\n }\n return handler as ApprovalHandler;\n}\n\n/** An interceptors object that carries `handler`, for `blockingApprovals()` and `composeInterceptors()`. */\nexport function withBlockingHandler(interceptors: Interceptors, handler: ApprovalHandler): Interceptors {\n return { ...interceptors, [BLOCKING_HANDLER]: handler } as Interceptors;\n}\n\n/**\n * Answers approvals inside the run, for a host where the person answers while the process waits, such as a terminal.\n * Join the result with your gate in `composeInterceptors()`, or spread it into your interceptors. When a gate returns\n * `ask`, the run signs the pending request and emits `approval_request` first, so a crash while it waits still\n * leaves a signed record to resume from. It then calls `handler` and waits for its answer. A `Resolution` with\n * `decision: \"allow\"` runs the call with the input the request signs, and `\"deny\"` gives the model an error result\n * with the reason. An answer that doesn't name the request, isn't allow or deny, or comes from a handler that throws\n * denies the call and emits `hook_error`, whatever `onFailure` says, and an abort while the run waits denies it too.\n * A question from `clarificationTool()` still ends the run `clarification_requested`.\n *\n * Use it only where the run and the person share a process. Anywhere else, let the run end `awaiting_approval` and\n * resume it with `continueRun()`. Throws an `SdkError` with code `invalid_run_options` when `handler` isn't a\n * function.\n */\nexport function blockingApprovals(handler: ApprovalHandler): Interceptors {\n if (typeof handler !== \"function\") {\n throw new SdkError(\"invalid_run_options\", \"blockingApprovals() needs a function that answers each request\");\n }\n return withBlockingHandler({}, handler);\n}\n"]}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The default progress policy (D11): it ends a run with `no_progress` when the model keeps making the same failing
3
+ * call. Two rules fire it:
4
+ *
5
+ * - **Identical failures.** The latest calls are one tool with one canonical input hash, each returned an error, and
6
+ * there are `maxIdenticalFailures` of them in a row (3 by default).
7
+ * - **One key.** A tool's `progressKey()` gave `maxSameKeyCalls` calls (5 by default) the same key and none of them
8
+ * succeeded. A successful call with that key starts its count again; calls with other keys don't.
9
+ *
10
+ * The policy reads the transcript, so it holds no state a `continueRun()` would have to restore, and it counts only
11
+ * the calls the run itself made. The loop runs it after the caller's `shouldStop`, outside the hook runner, so a
12
+ * caller's hook that throws can't switch it off.
13
+ */
14
+ import type { Message } from "@buildanagent/gateway";
15
+ import type { AnyTool } from "./tools/pipeline.js";
16
+ /** The thresholds of the default progress policy. Pass `progress: false` to `run()` to turn the policy off. */
17
+ export interface ProgressPolicy {
18
+ /** How many identical failing calls in a row end the run. Default 3. */
19
+ readonly maxIdenticalFailures?: number;
20
+ /** How many calls with one `progressKey` and no success between them end the run. Default 5. */
21
+ readonly maxSameKeyCalls?: number;
22
+ }
23
+ /** The defaults, provisional until recorded runs retune them. The object is frozen, so no caller can change them. */
24
+ export declare const DEFAULT_PROGRESS: Readonly<Required<ProgressPolicy>>;
25
+ /** Checks a `progress` option and fills in its defaults. */
26
+ export declare function resolveProgress(progress: ProgressPolicy | false | undefined): Required<ProgressPolicy> | undefined;
27
+ /** The progress check the loop runs after each step: the reason the run is stuck, or `undefined`. */
28
+ export type ProgressCheck = (messages: readonly Message[]) => Promise<string | undefined>;
29
+ /**
30
+ * The default progress policy as a check over the transcript. `skip` is how many messages came before this run's
31
+ * own, so a run continued from a context that ended in a loop is not stopped by the old calls. The transcript only
32
+ * grows, so each call's hash and key are worked out once and kept by its place in it.
33
+ */
34
+ export declare function progressCheck(tools: readonly AnyTool[], policy: Required<ProgressPolicy>, skip: number): ProgressCheck;