@buildanagent/sdk 0.1.0-alpha.4 → 0.1.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +115 -7
  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 +22 -0
  6. package/dist/compose.js +137 -0
  7. package/dist/compose.js.map +1 -0
  8. package/dist/errors.d.ts +7 -2
  9. package/dist/errors.js +6 -1
  10. package/dist/errors.js.map +1 -1
  11. package/dist/events.d.ts +22 -2
  12. package/dist/events.js +2 -0
  13. package/dist/events.js.map +1 -1
  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 +113 -0
  19. package/dist/hook-checks.js.map +1 -0
  20. package/dist/hook-runner.d.ts +60 -0
  21. package/dist/hook-runner.js +169 -0
  22. package/dist/hook-runner.js.map +1 -0
  23. package/dist/hooks.d.ts +177 -0
  24. package/dist/hooks.js +2 -0
  25. package/dist/hooks.js.map +1 -0
  26. package/dist/index.d.ts +10 -4
  27. package/dist/index.js +9 -3
  28. package/dist/index.js.map +1 -1
  29. package/dist/loop.d.ts +26 -8
  30. package/dist/loop.js +241 -35
  31. package/dist/loop.js.map +1 -1
  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/progress.d.ts +34 -0
  36. package/dist/progress.js +139 -0
  37. package/dist/progress.js.map +1 -0
  38. package/dist/result.d.ts +28 -5
  39. package/dist/result.js.map +1 -1
  40. package/dist/run.d.ts +69 -5
  41. package/dist/run.js +125 -7
  42. package/dist/run.js.map +1 -1
  43. package/dist/tools/define.d.ts +3 -3
  44. package/dist/tools/define.js +6 -3
  45. package/dist/tools/define.js.map +1 -1
  46. package/dist/tools/pipeline.d.ts +29 -7
  47. package/dist/tools/pipeline.js +48 -14
  48. package/dist/tools/pipeline.js.map +1 -1
  49. package/dist/tools/types.d.ts +10 -2
  50. package/dist/tools/types.js.map +1 -1
  51. package/dist/vendor/agent-safety/hash.d.ts +16 -0
  52. package/dist/vendor/agent-safety/hash.js +109 -0
  53. package/dist/vendor/agent-safety/hash.js.map +1 -0
  54. package/package.json +2 -2
@@ -0,0 +1,177 @@
1
+ /**
2
+ * The hook types: six interceptors that can change a run, and the observer that only watches it. Each interceptor
3
+ * takes one event object and returns a replacement, never mutating its input, because the event's data is frozen.
4
+ */
5
+ import type { AssistantMessage, ContentBlock, Message, Model, ModelCallOptions, ModelContext, ModelRef, Usage } from "@buildanagent/gateway";
6
+ import type { AgentEvent } from "./events.js";
7
+ import type { ToolResult } from "./tools/types.js";
8
+ /** A value or a promise of one: a hook may be a plain function or an `async` one. */
9
+ export type MaybePromise<T> = T | Promise<T>;
10
+ /**
11
+ * A value, or nothing: what a hook that may change something returns. `void` lets an `async` hook that has nothing
12
+ * to change simply end, where `undefined` would force it to return explicitly.
13
+ */
14
+ export type OrNothing<T> = T | void;
15
+ /** The options of one model call, without the abort signal, which the run supplies. */
16
+ export type CallOptions = Omit<ModelCallOptions, "signal">;
17
+ /** The fields every hook event carries. */
18
+ export interface HookEventBase {
19
+ /** The run's id. */
20
+ readonly runId: string;
21
+ /** The index of the model call the hook belongs to, counted from 0. */
22
+ readonly stepIndex: number;
23
+ /** The tool call's id, for the two tool hooks; absent for the others. */
24
+ readonly callId?: string;
25
+ /** The run's abort signal. Pass it on to any I/O the hook does. */
26
+ readonly signal: AbortSignal;
27
+ /** When the hook was called, from the run's clock, in ISO 8601. */
28
+ readonly timestamp: string;
29
+ }
30
+ /** What `transformContext` receives: the conversation as it stands before the model call. */
31
+ export interface ContextEvent extends HookEventBase {
32
+ /** The system prompt. */
33
+ readonly system: string;
34
+ /** The whole conversation so far, never a view an earlier call's transform returned. */
35
+ readonly messages: readonly Message[];
36
+ /** The model the run was started with. */
37
+ readonly model: ModelRef;
38
+ /** The previous model call's usage. Absent on the first call. */
39
+ readonly lastUsage?: Usage;
40
+ }
41
+ /** What `beforeModelCall` receives: the request about to be sent. */
42
+ export interface ModelCallEvent extends HookEventBase {
43
+ /** The request: the system prompt, the messages `transformContext` returned and the tools this call sends. */
44
+ readonly context: ModelContext;
45
+ /** The options of this call, without the abort signal. */
46
+ readonly options: CallOptions;
47
+ }
48
+ /** What `afterModelCall` receives: the model's finished response. */
49
+ export interface ModelResultEvent extends HookEventBase {
50
+ /** The response, including a failed one, whose `stopReason` is `"error"`. */
51
+ readonly message: AssistantMessage;
52
+ }
53
+ /** What `beforeToolCall` receives: a call whose input has passed the tool's schema. */
54
+ export interface ToolCallEvent extends HookEventBase {
55
+ readonly callId: string;
56
+ /** The tool's name. */
57
+ readonly tool: string;
58
+ /** The validated input. */
59
+ readonly input: unknown;
60
+ }
61
+ /** What `afterToolCall` receives: the result of a call that executed, before the model reads it. */
62
+ export interface ToolResultEvent extends ToolCallEvent {
63
+ readonly result: ToolResult;
64
+ }
65
+ /** What `shouldStop` receives, after a step's tool calls have their results. */
66
+ export interface StepEvent extends HookEventBase {
67
+ /** The whole conversation so far, including this step's response and tool results. */
68
+ readonly messages: readonly Message[];
69
+ /** This step's model response. */
70
+ readonly lastMessage: AssistantMessage;
71
+ }
72
+ /**
73
+ * Changes to one model call's request. Every field is optional, and a change applies to that call only; the next
74
+ * call starts again from the run's own settings.
75
+ */
76
+ export interface ModelCallPatch {
77
+ /** Replaces the system prompt for this call. */
78
+ readonly system?: string;
79
+ /** Replaces the messages sent for this call. The run's own transcript keeps its messages. */
80
+ readonly messages?: readonly Message[];
81
+ /**
82
+ * The names of the tools to send, as the complete list: a tool left out is not sent, and a tool whose `exposure`
83
+ * is `deferred` or `hidden` is sent when named. Tools always go out in definition order, whatever order this list
84
+ * is in. A name that matches no tool throws an `SdkError` with code `invalid_hook_result`. A call to a tool that
85
+ * was not sent gets the unknown-tool error.
86
+ */
87
+ readonly activeTools?: readonly string[];
88
+ /** Makes this call with another model. */
89
+ readonly model?: Model;
90
+ /** Replaces the options of this call. */
91
+ readonly options?: CallOptions;
92
+ }
93
+ /**
94
+ * What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the
95
+ * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` asks a
96
+ * person; until runs can pause, it blocks the call like `deny` with a message that says approval isn't available.
97
+ */
98
+ export type GateDecision = {
99
+ readonly decision: "allow";
100
+ readonly input?: unknown;
101
+ readonly reason?: string;
102
+ } | {
103
+ readonly decision: "deny";
104
+ readonly reason: string;
105
+ } | {
106
+ readonly decision: "ask";
107
+ readonly reason?: string;
108
+ readonly policyVersion?: string;
109
+ };
110
+ /**
111
+ * Changes to a tool's result. Each field present replaces the result's own. A replaced `outcome` is not available
112
+ * here: a write's outcome is rendered into `content` once, so replace `content` instead.
113
+ */
114
+ export type ToolResultPatch = Partial<Omit<ToolResult, "outcome">>;
115
+ /**
116
+ * What `shouldStop` decides. `true` or `{ stop: "hook" }` ends the run `stopped`, with the reason as `stoppedBy`
117
+ * (`"hook"` for `true`). `{ stop: "no_progress" }` ends it `no_progress`. `{ continue }` keeps a run going that the
118
+ * model ended by answering in text, adding the content as a user message. When the model's step called tools, the run goes on anyway and the content is
119
+ * not added, so a hook that must reach the model should return it after a text answer. `false` leaves the decision to the run.
120
+ */
121
+ export type StopDecision = boolean | {
122
+ readonly continue: string | readonly ContentBlock[];
123
+ } | {
124
+ readonly stop: "no_progress" | "hook";
125
+ readonly reason: string;
126
+ };
127
+ /**
128
+ * The six interceptors, in the order a step calls them: `transformContext`, `beforeModelCall`, the model call,
129
+ * `afterModelCall`, then for each tool call `beforeToolCall` and `afterToolCall`, and last `shouldStop`. A run takes
130
+ * one object; `composeInterceptors()` joins several. Each hook may be `async`.
131
+ */
132
+ export interface Interceptors {
133
+ /**
134
+ * Returns the messages to send for this model call, such as a masked or summarised view of a long conversation.
135
+ * The view reaches that call's request only: the next call's event, `result.messages` and `result.context` hold
136
+ * the full history. Each call emits a `context_transformed` event with the message counts.
137
+ */
138
+ readonly transformContext?: (e: ContextEvent) => MaybePromise<readonly Message[]>;
139
+ /** Changes the request about to be sent. Return nothing to leave it as it is. */
140
+ readonly beforeModelCall?: (e: ModelCallEvent) => MaybePromise<OrNothing<ModelCallPatch>>;
141
+ /**
142
+ * Replaces the model's response. The transcript and the `model_call_end` event hold the replacement, and its tool
143
+ * calls are the ones that run. The call's usage and cost stay those of the model's own response. If it throws
144
+ * while the run fails closed, both hold an empty stand-in with `stopReason: "error"` and that usage and cost.
145
+ */
146
+ readonly afterModelCall?: (e: ModelResultEvent) => MaybePromise<OrNothing<{
147
+ readonly message?: AssistantMessage;
148
+ }>>;
149
+ /**
150
+ * The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in
151
+ * model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and
152
+ * every registered tool is allowed. A gate that returns `ask` pauses the run once pauses exist; until then `ask`
153
+ * blocks the call. A gate that throws denies the call unless `onFailure` is `"continue"`. A gate must return a
154
+ * decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.
155
+ */
156
+ readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;
157
+ /**
158
+ * Replaces fields of a result before the model reads it, and before `tool_call_end` reports it. It runs for calls
159
+ * that executed, including ones whose `execute` threw, and not for calls that never ran, such as an unknown tool,
160
+ * invalid input or a denied call. Return nothing to keep the result.
161
+ */
162
+ readonly afterToolCall?: (e: ToolResultEvent) => MaybePromise<OrNothing<ToolResultPatch>>;
163
+ /** Ends the run, or keeps it going, after a step. It is not asked once the run has a stop reason of its own. */
164
+ readonly shouldStop?: (e: StepEvent) => MaybePromise<StopDecision>;
165
+ /**
166
+ * What a hook that throws does. `"fail_closed"` (the default) stops the unsafe thing: a failed `beforeToolCall`
167
+ * denies the call, a failed `afterToolCall` withholds the result, and a failed model-moment hook or `shouldStop`
168
+ * ends the run with `stopReason: "error"` and `error.kind: "hook"`. `"continue"` skips the failed hook and goes on
169
+ * as if it had returned nothing. Either way the run emits a `hook_error` event.
170
+ */
171
+ readonly onFailure?: "fail_closed" | "continue";
172
+ }
173
+ /**
174
+ * Watches a run: called with each event, in order, and never able to change the run. A promise it returns is waited
175
+ * for before the next event is delivered to it. A throw or a rejection becomes a `hook_error` event.
176
+ */
177
+ export type Observer = (event: AgentEvent) => MaybePromise<void>;
package/dist/hooks.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The hook types: six interceptors that can change a run, and the observer that only watches it. Each interceptor\n * takes one event object and returns a replacement, never mutating its input, because the event's data is frozen.\n */\nimport type {\n AssistantMessage,\n ContentBlock,\n Message,\n Model,\n ModelCallOptions,\n ModelContext,\n ModelRef,\n Usage,\n} from \"@buildanagent/gateway\";\nimport type { AgentEvent } from \"./events.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** A value or a promise of one: a hook may be a plain function or an `async` one. */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * A value, or nothing: what a hook that may change something returns. `void` lets an `async` hook that has nothing\n * to change simply end, where `undefined` would force it to return explicitly.\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: a hook's return type, where void lets a function return nothing\nexport type OrNothing<T> = T | void;\n\n/** The options of one model call, without the abort signal, which the run supplies. */\nexport type CallOptions = Omit<ModelCallOptions, \"signal\">;\n\n/** The fields every hook event carries. */\nexport interface HookEventBase {\n /** The run's id. */\n readonly runId: string;\n /** The index of the model call the hook belongs to, counted from 0. */\n readonly stepIndex: number;\n /** The tool call's id, for the two tool hooks; absent for the others. */\n readonly callId?: string;\n /** The run's abort signal. Pass it on to any I/O the hook does. */\n readonly signal: AbortSignal;\n /** When the hook was called, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** What `transformContext` receives: the conversation as it stands before the model call. */\nexport interface ContextEvent extends HookEventBase {\n /** The system prompt. */\n readonly system: string;\n /** The whole conversation so far, never a view an earlier call's transform returned. */\n readonly messages: readonly Message[];\n /** The model the run was started with. */\n readonly model: ModelRef;\n /** The previous model call's usage. Absent on the first call. */\n readonly lastUsage?: Usage;\n}\n\n/** What `beforeModelCall` receives: the request about to be sent. */\nexport interface ModelCallEvent extends HookEventBase {\n /** The request: the system prompt, the messages `transformContext` returned and the tools this call sends. */\n readonly context: ModelContext;\n /** The options of this call, without the abort signal. */\n readonly options: CallOptions;\n}\n\n/** What `afterModelCall` receives: the model's finished response. */\nexport interface ModelResultEvent extends HookEventBase {\n /** The response, including a failed one, whose `stopReason` is `\"error\"`. */\n readonly message: AssistantMessage;\n}\n\n/** What `beforeToolCall` receives: a call whose input has passed the tool's schema. */\nexport interface ToolCallEvent extends HookEventBase {\n readonly callId: string;\n /** The tool's name. */\n readonly tool: string;\n /** The validated input. */\n readonly input: unknown;\n}\n\n/** What `afterToolCall` receives: the result of a call that executed, before the model reads it. */\nexport interface ToolResultEvent extends ToolCallEvent {\n readonly result: ToolResult;\n}\n\n/** What `shouldStop` receives, after a step's tool calls have their results. */\nexport interface StepEvent extends HookEventBase {\n /** The whole conversation so far, including this step's response and tool results. */\n readonly messages: readonly Message[];\n /** This step's model response. */\n readonly lastMessage: AssistantMessage;\n}\n\n/**\n * Changes to one model call's request. Every field is optional, and a change applies to that call only; the next\n * call starts again from the run's own settings.\n */\nexport interface ModelCallPatch {\n /** Replaces the system prompt for this call. */\n readonly system?: string;\n /** Replaces the messages sent for this call. The run's own transcript keeps its messages. */\n readonly messages?: readonly Message[];\n /**\n * The names of the tools to send, as the complete list: a tool left out is not sent, and a tool whose `exposure`\n * is `deferred` or `hidden` is sent when named. Tools always go out in definition order, whatever order this list\n * is in. A name that matches no tool throws an `SdkError` with code `invalid_hook_result`. A call to a tool that\n * was not sent gets the unknown-tool error.\n */\n readonly activeTools?: readonly string[];\n /** Makes this call with another model. */\n readonly model?: Model;\n /** Replaces the options of this call. */\n readonly options?: CallOptions;\n}\n\n/**\n * What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the\n * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` asks a\n * person; until runs can pause, it blocks the call like `deny` with a message that says approval isn't available.\n */\nexport type GateDecision =\n | { readonly decision: \"allow\"; readonly input?: unknown; readonly reason?: string }\n | { readonly decision: \"deny\"; readonly reason: string }\n | { readonly decision: \"ask\"; readonly reason?: string; readonly policyVersion?: string };\n\n/**\n * Changes to a tool's result. Each field present replaces the result's own. A replaced `outcome` is not available\n * here: a write's outcome is rendered into `content` once, so replace `content` instead.\n */\nexport type ToolResultPatch = Partial<Omit<ToolResult, \"outcome\">>;\n\n/**\n * What `shouldStop` decides. `true` or `{ stop: \"hook\" }` ends the run `stopped`, with the reason as `stoppedBy`\n * (`\"hook\"` for `true`). `{ stop: \"no_progress\" }` ends it `no_progress`. `{ continue }` keeps a run going that the\n * model ended by answering in text, adding the content as a user message. When the model's step called tools, the run goes on anyway and the content is\n * not added, so a hook that must reach the model should return it after a text answer. `false` leaves the decision to the run.\n */\nexport type StopDecision =\n | boolean\n | { readonly continue: string | readonly ContentBlock[] }\n | { readonly stop: \"no_progress\" | \"hook\"; readonly reason: string };\n\n/**\n * The six interceptors, in the order a step calls them: `transformContext`, `beforeModelCall`, the model call,\n * `afterModelCall`, then for each tool call `beforeToolCall` and `afterToolCall`, and last `shouldStop`. A run takes\n * one object; `composeInterceptors()` joins several. Each hook may be `async`.\n */\nexport interface Interceptors {\n /**\n * Returns the messages to send for this model call, such as a masked or summarised view of a long conversation.\n * The view reaches that call's request only: the next call's event, `result.messages` and `result.context` hold\n * the full history. Each call emits a `context_transformed` event with the message counts.\n */\n readonly transformContext?: (e: ContextEvent) => MaybePromise<readonly Message[]>;\n /** Changes the request about to be sent. Return nothing to leave it as it is. */\n readonly beforeModelCall?: (e: ModelCallEvent) => MaybePromise<OrNothing<ModelCallPatch>>;\n /**\n * Replaces the model's response. The transcript and the `model_call_end` event hold the replacement, and its tool\n * calls are the ones that run. The call's usage and cost stay those of the model's own response. If it throws\n * while the run fails closed, both hold an empty stand-in with `stopReason: \"error\"` and that usage and cost.\n */\n readonly afterModelCall?: (e: ModelResultEvent) => MaybePromise<OrNothing<{ readonly message?: AssistantMessage }>>;\n /**\n * The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in\n * model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and\n * every registered tool is allowed. A gate that returns `ask` pauses the run once pauses exist; until then `ask`\n * blocks the call. A gate that throws denies the call unless `onFailure` is `\"continue\"`. A gate must return a\n * decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.\n */\n readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;\n /**\n * Replaces fields of a result before the model reads it, and before `tool_call_end` reports it. It runs for calls\n * that executed, including ones whose `execute` threw, and not for calls that never ran, such as an unknown tool,\n * invalid input or a denied call. Return nothing to keep the result.\n */\n readonly afterToolCall?: (e: ToolResultEvent) => MaybePromise<OrNothing<ToolResultPatch>>;\n /** Ends the run, or keeps it going, after a step. It is not asked once the run has a stop reason of its own. */\n readonly shouldStop?: (e: StepEvent) => MaybePromise<StopDecision>;\n /**\n * What a hook that throws does. `\"fail_closed\"` (the default) stops the unsafe thing: a failed `beforeToolCall`\n * denies the call, a failed `afterToolCall` withholds the result, and a failed model-moment hook or `shouldStop`\n * ends the run with `stopReason: \"error\"` and `error.kind: \"hook\"`. `\"continue\"` skips the failed hook and goes on\n * as if it had returned nothing. Either way the run emits a `hook_error` event.\n */\n readonly onFailure?: \"fail_closed\" | \"continue\";\n}\n\n/**\n * Watches a run: called with each event, in order, and never able to change the run. A promise it returns is waited\n * for before the next event is delivered to it. A throw or a rejection becomes a `hook_error` event.\n */\nexport type Observer = (event: AgentEvent) => MaybePromise<void>;\n"]}
package/dist/index.d.ts CHANGED
@@ -1,12 +1,18 @@
1
1
  /**
2
2
  * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
3
- * `continueRun()`, `runOrThrow()`), its events and results, and the tools: their definitions, schemas, results and
4
- * write outcomes. Hooks, signed pauses and budgets are planned in the SDK plan §3.3.
3
+ * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
4
+ * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
5
+ * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. Signed pauses are
6
+ * planned in the SDK plan §3.3.
5
7
  */
8
+ export { projectCallCost } from "@buildanagent/gateway";
9
+ export { composeInterceptors } from "./compose.js";
6
10
  export { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from "./errors.js";
7
11
  export { AGENT_EVENT_TYPES, type AgentEvent, type AgentEventBody, type EventBase, type ModelCallRequest, type WarningCode, } from "./events.js";
8
- export type { Context, DoneResult, EndedResult, ErrorResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
9
- export { continueRun, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
12
+ export type { CallOptions, ContextEvent, GateDecision, HookEventBase, Interceptors, MaybePromise, ModelCallEvent, ModelCallPatch, ModelResultEvent, Observer, OrNothing, StepEvent, StopDecision, ToolCallEvent, ToolResultEvent, ToolResultPatch, } from "./hooks.js";
13
+ export { DEFAULT_PROGRESS, type ProgressPolicy } from "./progress.js";
14
+ export type { BudgetResult, Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
15
+ export { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
10
16
  export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
11
17
  export type { JsonSchema, SchemaIssue, ToolAnnotations, ToolContext, ToolDefinition, ToolEffect, ToolExecutionMode, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
12
18
  export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
package/dist/index.js CHANGED
@@ -1,11 +1,17 @@
1
1
  /**
2
2
  * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
3
- * `continueRun()`, `runOrThrow()`), its events and results, and the tools: their definitions, schemas, results and
4
- * write outcomes. Hooks, signed pauses and budgets are planned in the SDK plan §3.3.
3
+ * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
4
+ * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
5
+ * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. Signed pauses are
6
+ * planned in the SDK plan §3.3.
5
7
  */
8
+ // Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.
9
+ export { projectCallCost } from "@buildanagent/gateway";
10
+ export { composeInterceptors } from "./compose.js";
6
11
  export { isSdkError, RunStoppedError, SdkError } from "./errors.js";
7
12
  export { AGENT_EVENT_TYPES, } from "./events.js";
8
- export { continueRun, run, runOrThrow } from "./run.js";
13
+ export { DEFAULT_PROGRESS } from "./progress.js";
14
+ export { continueRun, nestedRunDepth, run, runOrThrow } from "./run.js";
9
15
  export { clarificationTool, defineTool, outputTool, } from "./tools/define.js";
10
16
  /** The package's name, `@buildanagent/sdk`. */
11
17
  export const SDK_PACKAGE = "@buildanagent/sdk";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACvF,OAAO,EACL,iBAAiB,GAMlB,MAAM,aAAa,CAAC;AAYrB,OAAO,EAAE,WAAW,EAA4C,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAClG,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAgB3B,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,\n * `continueRun()`, `runOrThrow()`), its events and results, and the tools: their definitions, schemas, results and\n * write outcomes. Hooks, signed pauses and budgets are planned in the SDK plan §3.3.\n */\nexport { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n AGENT_EVENT_TYPES,\n type AgentEvent,\n type AgentEventBody,\n type EventBase,\n type ModelCallRequest,\n type WarningCode,\n} from \"./events.js\";\nexport type {\n Context,\n DoneResult,\n EndedResult,\n ErrorResult,\n ResultBase,\n RunError,\n RunResult,\n StoppedResult,\n UnfinishedResult,\n} from \"./result.js\";\nexport { continueRun, type Run, type RunInput, type RunOptions, run, runOrThrow } from \"./run.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolAnnotations,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolExecutionMode,\n ToolExposure,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,sHAAsH;AACtH,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACvF,OAAO,EACL,iBAAiB,GAMlB,MAAM,aAAa,CAAC;AAmBrB,OAAO,EAAE,gBAAgB,EAAuB,MAAM,eAAe,CAAC;AActE,OAAO,EAAE,WAAW,EAAE,cAAc,EAA4C,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAClH,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAgB3B,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,\n * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write\n * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also\n * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. Signed pauses are\n * planned in the SDK plan §3.3.\n */\n// Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.\nexport { projectCallCost } from \"@buildanagent/gateway\";\nexport { composeInterceptors } from \"./compose.js\";\nexport { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n AGENT_EVENT_TYPES,\n type AgentEvent,\n type AgentEventBody,\n type EventBase,\n type ModelCallRequest,\n type WarningCode,\n} from \"./events.js\";\nexport type {\n CallOptions,\n ContextEvent,\n GateDecision,\n HookEventBase,\n Interceptors,\n MaybePromise,\n ModelCallEvent,\n ModelCallPatch,\n ModelResultEvent,\n Observer,\n OrNothing,\n StepEvent,\n StopDecision,\n ToolCallEvent,\n ToolResultEvent,\n ToolResultPatch,\n} from \"./hooks.js\";\nexport { DEFAULT_PROGRESS, type ProgressPolicy } from \"./progress.js\";\nexport type {\n BudgetResult,\n Context,\n DoneResult,\n EndedResult,\n ErrorResult,\n NoProgressResult,\n ResultBase,\n RunError,\n RunResult,\n StoppedResult,\n UnfinishedResult,\n} from \"./result.js\";\nexport { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from \"./run.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolAnnotations,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolExecutionMode,\n ToolExposure,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
package/dist/loop.d.ts CHANGED
@@ -2,13 +2,15 @@
2
2
  * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds
3
3
  * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.
4
4
  *
5
- * Each step runs transform → before → stream → after → tools → stop. The transform, before and after moments are
6
- * where the interceptors plug in (D6); until they exist the request is the transcript as it stands and the response
7
- * is kept unchanged. Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed
8
- * tool result, throws.
5
+ * Each step runs transform → before → stream → after → tools → stop. Those moments are where the interceptors
6
+ * plug in (D6); a run without interceptors sends the transcript as it stands and keeps each response unchanged.
7
+ * Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,
8
+ * throws.
9
9
  */
10
- import { type Message, type Model, type ModelCallOptions } from "@buildanagent/gateway";
10
+ import { type Message, type Model } from "@buildanagent/gateway";
11
11
  import type { AgentEventBody } from "./events.js";
12
+ import type { CallOptions, Interceptors } from "./hooks.js";
13
+ import type { ProgressCheck } from "./progress.js";
12
14
  import type { RunResult } from "./result.js";
13
15
  import type { Clock } from "./testing/determinism.js";
14
16
  import { type AnyTool } from "./tools/pipeline.js";
@@ -21,18 +23,34 @@ export interface LoopSetup {
21
23
  readonly history: readonly Message[];
22
24
  /** The messages the run starts by adding, such as the user's input. */
23
25
  readonly input: readonly Message[];
24
- /** The tools the model is sent, in definition order; only these can run. */
26
+ /**
27
+ * Every tool the run knows, in definition order. A request sends the ones whose exposure is `direct`, or the ones
28
+ * `activeTools` names, and only the tools a request sent can run.
29
+ */
25
30
  readonly tools: readonly AnyTool[];
26
31
  readonly output: AnyTool | undefined;
27
32
  readonly maxSteps: number;
28
- readonly modelOptions: Omit<ModelCallOptions, "signal">;
33
+ /** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */
34
+ readonly budgetUsd?: number;
35
+ /** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */
36
+ readonly depth: number;
37
+ readonly maxDepth: number;
38
+ readonly modelOptions: CallOptions;
39
+ readonly interceptors: Interceptors;
40
+ /** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */
41
+ readonly progress?: ProgressCheck;
29
42
  readonly signal: AbortSignal;
30
43
  readonly clock: Clock;
31
44
  }
32
45
  /** Sends one event; the run adds the `EventBase` fields. */
33
46
  export type Emit = (body: AgentEventBody, stepIndex: number) => void;
47
+ /**
48
+ * Resolves once every observer has handled the events sent so far. The loop calls it only once it has its outcome,
49
+ * and the run treats the first call as the point after which an abort no longer counts.
50
+ */
51
+ export type Drain = () => Promise<void>;
34
52
  /**
35
53
  * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results
36
54
  * already received are in the transcript.
37
55
  */
38
- export declare function runLoop(setup: LoopSetup, emit: Emit): Promise<RunResult>;
56
+ export declare function runLoop(setup: LoopSetup, emit: Emit, drain: Drain): Promise<RunResult>;