@buildanagent/sdk 0.1.0-alpha.3 → 0.1.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/dist/errors.d.ts +7 -6
- package/dist/errors.js +7 -6
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/loop.js +1 -1
- package/dist/loop.js.map +1 -1
- package/dist/tools/define.d.ts +3 -2
- package/dist/tools/define.js +10 -2
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/format-error.js +1 -0
- package/dist/tools/format-error.js.map +1 -1
- package/dist/tools/pipeline.d.ts +16 -5
- package/dist/tools/pipeline.js +160 -35
- package/dist/tools/pipeline.js.map +1 -1
- package/dist/tools/scheduler.d.ts +33 -0
- package/dist/tools/scheduler.js +51 -0
- package/dist/tools/scheduler.js.map +1 -0
- package/dist/tools/types.d.ts +39 -3
- package/dist/tools/types.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -34,7 +34,7 @@ for await (const event of started) {
|
|
|
34
34
|
const result = await started.result;
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
-
`model` comes from `createModel()` in the gateway, and a bare model id is a type error.
|
|
37
|
+
`model` comes from `createModel()` in the gateway, and a bare model id is a type error. A tool whose `exposure` is `"deferred"` or `"hidden"` is never sent to the model, and a call to it gets the unknown-tool error.
|
|
38
38
|
|
|
39
39
|
### Every run ends with a stop reason
|
|
40
40
|
|
|
@@ -161,11 +161,21 @@ The model reads the outcome first, as a sentence and as JSON, and then your cont
|
|
|
161
161
|
|
|
162
162
|
`clarificationTool()` gives the model a tool named `ask_user` that takes one `question`. Pass `{ name }` to call it something else. Once the model calls it, the run ends with `stopReason: "stopped"` and `stoppedBy: "clarification"`, and the question is the call's input in `result.messages`. To go on, add the user's answer to `result.context` as a user message and pass the context to `continueRun()`.
|
|
163
163
|
|
|
164
|
+
## A step's tool calls run in parallel
|
|
165
|
+
|
|
166
|
+
When the model asks for several tools in one response, the run checks them one at a time, in the order the model sent them, and then starts them all together. Results are added to the transcript in the model's order, whichever call finishes first, and a result is added as soon as every result before it is in. Three settings on a tool change the schedule:
|
|
167
|
+
|
|
168
|
+
- **`executionMode: "sequential"`** makes every call in that step run one at a time, in the model's order. Use it for a tool that depends on the calls around it. One call to a sequential tool is enough: its whole step runs in sequence, including calls to other tools, even when that call itself fails validation.
|
|
169
|
+
- **`resourceKey(input)`** returns a string that names what a call touches, such as a file path. Calls in one step with the same key never run at the same time, even when they come from different tools, and they run in the model's order. Calls with different keys, or no key, still run together.
|
|
170
|
+
- **`readOnlyHint`**, set in `annotations`, says that a tool changes nothing. It affects scheduling only when the tool is also `firstParty: true` and declares no `effect`. A read-only call doesn't wait for other read-only calls that share its key, though it still waits for a write before it, and a write waits for the reads before it. A tool from an MCP server stays `firstParty: false`, so its hint is ignored: the hint is a claim by whoever runs the server.
|
|
171
|
+
|
|
172
|
+
Every tool gets a `ctx.signal` that fires when the run is aborted. It also fires when a sibling call in the same step throws a programmer error, an `SdkError` such as a malformed result, because the run stops there. A call still waiting for its key never starts after the signal fires and gets an error result instead. The run waits for the other calls to return, passes on their results in the model's order (calls after the failing one that had already run included), and then throws, so pass the signal on to your own I/O. A sibling's error result, one the model can read and answer, such as invalid input or a tool that threw, cancels nothing.
|
|
173
|
+
|
|
164
174
|
## `SdkError` marks a mistake in your code
|
|
165
175
|
|
|
166
176
|
The SDK throws only for programmer errors, never for a failure the model caused. `isSdkError(error)` recognises the error, and its `code` says why:
|
|
167
177
|
|
|
168
|
-
- **`invalid_tool_definition`**: a tool's name, description, schema or
|
|
178
|
+
- **`invalid_tool_definition`**: a tool's name, description, schema, exposure, `executionMode` or `resourceKey` is unusable, or two tools share a name.
|
|
169
179
|
- **`invalid_tool_result`**: `execute` returned something other than a tool result, or an invalid outcome. A text block needs a string `text`, and an image block a string `mediaType` and `data`. The run's `result` rejects with this error, and iterating the run throws it after the last event.
|
|
170
180
|
- **`invalid_run_options`**: `run()` or `continueRun()` got a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, or an output tool whose `exposure` isn't `"direct"`.
|
|
171
181
|
- **`invalid_model_stream`**: a model's stream ended without a final message, which only a broken adapter does.
|
package/dist/errors.d.ts
CHANGED
|
@@ -9,12 +9,13 @@ import type { Context, UnfinishedResult } from "./result.js";
|
|
|
9
9
|
/** Why an `SdkError` was thrown. */
|
|
10
10
|
export type SdkErrorCode = "invalid_tool_definition" | "invalid_tool_result" | "invalid_run_options" | "invalid_model_stream" | "run_stopped" | "unexpected_model_call";
|
|
11
11
|
/**
|
|
12
|
-
* Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema
|
|
13
|
-
* exposure is unusable, or two tools share a name. `invalid_tool_result`: a tool's
|
|
14
|
-
* result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an
|
|
15
|
-
* model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended
|
|
16
|
-
* `run_stopped`: `runOrThrow()` was given a run that did not finish (a `RunStoppedError`).
|
|
17
|
-
* `ScriptedModel` was called more times than its script allows (an
|
|
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()`. `invalid_model_stream`: a model's stream ended
|
|
16
|
+
* without a final message. `run_stopped`: `runOrThrow()` was given a run that did not finish (a `RunStoppedError`).
|
|
17
|
+
* `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
|
|
18
|
+
* `UnexpectedModelCallError`).
|
|
18
19
|
*/
|
|
19
20
|
export declare class SdkError extends Error {
|
|
20
21
|
readonly name: string;
|
package/dist/errors.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
// A registered symbol, so the guard still works when two copies of the package are bundled.
|
|
2
2
|
const SDK_ERROR = Symbol.for("buildanagent.sdk.SdkError");
|
|
3
3
|
/**
|
|
4
|
-
* Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description, schema
|
|
5
|
-
* exposure is unusable, or two tools share a name. `invalid_tool_result`: a tool's
|
|
6
|
-
* result or write outcome. `invalid_run_options`: `run()` or `continueRun()` got an
|
|
7
|
-
* model that isn't from `createModel()`. `invalid_model_stream`: a model's stream ended
|
|
8
|
-
* `run_stopped`: `runOrThrow()` was given a run that did not finish (a `RunStoppedError`).
|
|
9
|
-
* `ScriptedModel` was called more times than its script allows (an
|
|
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()`. `invalid_model_stream`: a model's stream ended
|
|
8
|
+
* without a final message. `run_stopped`: `runOrThrow()` was given a run that did not finish (a `RunStoppedError`).
|
|
9
|
+
* `unexpected_model_call`: a `ScriptedModel` was called more times than its script allows (an
|
|
10
|
+
* `UnexpectedModelCallError`).
|
|
10
11
|
*/
|
|
11
12
|
export class SdkError extends Error {
|
|
12
13
|
name = "SdkError";
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAkBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAkBA,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,C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,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 | \"run_stopped\"\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()`. `invalid_model_stream`: a model's stream ended\n * without a final message. `run_stopped`: `runOrThrow()` was given a run that did not finish (a `RunStoppedError`).\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. 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"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export { AGENT_EVENT_TYPES, type AgentEvent, type AgentEventBody, type EventBase
|
|
|
8
8
|
export type { Context, DoneResult, EndedResult, ErrorResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
|
|
9
9
|
export { continueRun, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
|
|
10
10
|
export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
|
|
11
|
-
export type { JsonSchema, SchemaIssue, ToolContext, ToolDefinition, ToolEffect, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
|
|
11
|
+
export type { JsonSchema, SchemaIssue, ToolAnnotations, ToolContext, ToolDefinition, ToolEffect, ToolExecutionMode, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
|
|
12
12
|
export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
|
|
13
13
|
/** The package's name, `@buildanagent/sdk`. */
|
|
14
14
|
export declare 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;
|
|
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"]}
|
package/dist/loop.js
CHANGED
|
@@ -116,7 +116,7 @@ function toolMessage(entry) {
|
|
|
116
116
|
isError: entry.result.isError === true,
|
|
117
117
|
};
|
|
118
118
|
}
|
|
119
|
-
/** Runs the response's tool calls
|
|
119
|
+
/** Runs the response's tool calls as the pipeline schedules them, recording each result in model order. */
|
|
120
120
|
async function runTools(state, message) {
|
|
121
121
|
const { runId, signal, clock, tools, output } = state.setup;
|
|
122
122
|
return runToolCalls(message, tools, {
|
package/dist/loop.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAEL,OAAO,EACP,QAAQ,EAGR,UAAU,GASX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAIvC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAgB,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAGtF,kEAAkE;AAClE,MAAM,aAAa,GAA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OAAO,CAAC,UAAU,KAAK,SAAS;QAAE,YAAY,CAAC,KAAK,CAAC,CAAC;IAC1D,IAAI,OAAO,CAAC,UAAU,KAAK,WAAW,EAAE,CAAC;QACvC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,6BAA6B,KAAK,CAAC,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC,CAAC;IACnH,CAAC;IACD,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO;QAAE,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;IACxF,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC,CAAC;IACtC,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACxC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;IACxC,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,KAAgB,EAAE,IAAU;IACxD,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACzC,IAAI,OAA4B,CAAC;IACjC,OAAO,OAAO,KAAK,SAAS,EAAE,CAAC;QAC7B,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IACpF,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["/**\n * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds\n * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.\n *\n * Each step runs transform → before → stream → after → tools → stop. The transform, before and after moments are\n * where the interceptors plug in (D6); until they exist the request is the transcript as it stands and the response\n * is kept unchanged. Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed\n * tool result, throws.\n */\nimport {\n type AssistantMessage,\n addCost,\n addUsage,\n type Cost,\n type DumpedOptions,\n emptyUsage,\n type GatewayEvent,\n type Message,\n type Model,\n type ModelCallOptions,\n type ModelContext,\n type StreamOptions,\n type Usage,\n type WireTool,\n} from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\n\n/** The `stoppedBy` of a run that a clarification tool stopped. */\nconst CLARIFICATION = \"clarification\";\n\n// The depth cap's defaults (D11). Nested runs pass their own depth once the depth cap is configurable.\nconst TOP_LEVEL_DEPTH = 0;\nconst DEFAULT_MAX_DEPTH = 2;\n\n/**\n * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis\n * when it adds a provider cost, so the zero never turns a billed sum into an estimate.\n */\nconst NO_COST: Cost = { total: 0, basis: \"provider\", currency: \"USD\" };\n\n/** Everything one run needs, fixed when it starts. */\nexport interface LoopSetup {\n readonly runId: string;\n readonly model: Model;\n readonly system: string;\n /** The conversation before this run's own messages. */\n readonly history: readonly Message[];\n /** The messages the run starts by adding, such as the user's input. */\n readonly input: readonly Message[];\n /** The tools the model is sent, in definition order; only these can run. */\n readonly tools: readonly AnyTool[];\n readonly output: AnyTool | undefined;\n readonly maxSteps: number;\n readonly modelOptions: Omit<ModelCallOptions, \"signal\">;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** Sends one event; the run adds the `EventBase` fields. */\nexport type Emit = (body: AgentEventBody, stepIndex: number) => void;\n\n/** How a run ended, before its usage, cost and messages are attached. */\ntype Outcome =\n | { readonly stopReason: \"done\"; readonly output: unknown }\n | { readonly stopReason: \"max_steps\" | \"aborted\" }\n | { readonly stopReason: \"error\"; readonly error: RunError }\n | { readonly stopReason: \"stopped\"; readonly stoppedBy: string };\n\n/** What changes while a run goes on. */\nclass LoopState {\n readonly setup: LoopSetup;\n readonly emit: Emit;\n readonly messages: Message[];\n readonly added: Message[];\n readonly wireTools: WireTool[];\n steps = 0;\n stepIndex = 0;\n usage: Usage = emptyUsage();\n cost: Cost | undefined;\n output: unknown;\n\n constructor(setup: LoopSetup, emit: Emit) {\n this.setup = setup;\n this.emit = emit;\n this.messages = [...setup.history, ...setup.input];\n this.added = [...setup.input];\n this.wireTools = setup.tools.map(toWireTool);\n }\n\n send(body: AgentEventBody): void {\n this.emit(body, this.stepIndex);\n }\n\n append(message: Message): void {\n this.messages.push(message);\n this.added.push(message);\n }\n}\n\n/**\n * The stream options a request event records: everything but the payload hook, the abort signal and the caps, as the\n * gateway's own request dump leaves them out. An untyped caller may still pass a signal or caps in `modelOptions`.\n */\nfunction dumpedOptions(options: Omit<ModelCallOptions, \"signal\">): DumpedOptions {\n const { onPayload: _onPayload, signal: _signal, caps: _caps, ...rest } = options as StreamOptions;\n return rest;\n}\n\n/** Re-emits one model event as a run event, and returns the final message once the terminal event arrives. */\nfunction forward(state: LoopState, event: GatewayEvent): AssistantMessage | undefined {\n switch (event.type) {\n case \"done\":\n case \"error\":\n return event.message;\n case \"start\":\n return undefined;\n case \"retry\":\n state.send({ type: \"retry\", attempt: event.attempt, delayMs: event.delayMs, error: event.error });\n return undefined;\n case \"warning\":\n state.send({ type: \"warning\", code: \"model_warning\", detail: `${event.code}: ${event.message}` });\n return undefined;\n case \"text_start\":\n case \"reasoning_start\":\n case \"tool_input_start\":\n state.send({ type: event.type, index: event.index });\n return undefined;\n case \"text_delta\":\n case \"reasoning_delta\":\n case \"tool_input_delta\":\n state.send({ type: event.type, index: event.index, delta: event.delta });\n return undefined;\n default:\n state.send({ type: event.type, index: event.index, block: event.block });\n return undefined;\n }\n}\n\n/** Makes one model call, streams its events and records the response. */\nasync function callModel(state: LoopState): Promise<AssistantMessage> {\n const { model, system, modelOptions, signal } = state.setup;\n const context: ModelContext = { system, messages: [...state.messages], tools: state.wireTools };\n state.send({\n type: \"model_call_start\",\n request: { model: model.ref, context, options: dumpedOptions(modelOptions) },\n });\n let message: AssistantMessage | undefined;\n for await (const event of model.stream(context, { ...modelOptions, signal })) {\n message = forward(state, event) ?? message;\n }\n if (message === undefined) {\n throw new SdkError(\"invalid_model_stream\", \"the model's stream ended without a done or error event\");\n }\n state.steps += 1;\n state.usage = addUsage(state.usage, message.usage);\n state.cost = state.cost === undefined ? message.cost : addCost(state.cost, message.cost);\n state.append(message);\n state.send({ type: \"model_call_end\", message });\n return message;\n}\n\n/** The tool message the model reads for one call. */\nfunction toolMessage(entry: ToolCallResult): Message {\n return {\n role: \"tool\",\n callId: entry.call.callId,\n content: [...entry.result.content],\n isError: entry.result.isError === true,\n };\n}\n\n/** Runs the response's tool calls one at a time, recording each result as soon as it arrives. */\nasync function runTools(state: LoopState, message: AssistantMessage): Promise<readonly ToolCallResult[]> {\n const { runId, signal, clock, tools, output } = state.setup;\n return runToolCalls(message, tools, {\n runId,\n signal,\n clock,\n depth: TOP_LEVEL_DEPTH,\n maxDepth: DEFAULT_MAX_DEPTH,\n onStart: (call: ToolCall) =>\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input }),\n onUpdate: (callId, details) => state.send({ type: \"tool_call_update\", callId, details }),\n onResult: (entry) => {\n state.append(toolMessage(entry));\n if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {\n state.output = entry.result.structured;\n }\n state.send({ type: \"tool_call_end\", callId: entry.call.callId, result: entry.result });\n },\n });\n}\n\n/** The failed call's error as the run reports it. A message without one counts as `fatal`. */\nfunction runErrorOf(message: AssistantMessage): RunError {\n const error = message.error;\n if (error === undefined) return { kind: \"fatal\", message: \"the model call failed without an error description\" };\n return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };\n}\n\n/**\n * The stop check after one step. A finished answer, or a question for the user, wins over an abort that came too late\n * to change it; otherwise an abort stops the run before the step cap does. A text answer cut off at the output limit\n * also counts as finished: its message keeps `stopReason: \"length\"`.\n */\nfunction stopCheck(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Outcome | undefined {\n if (message.stopReason === \"error\") return { stopReason: \"error\", error: runErrorOf(message) };\n if (message.stopReason === \"aborted\") return { stopReason: \"aborted\" };\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\n // Until runs can pause for an answer, a clarification question stops the run, so the model never goes on as if the\n // user had been asked and answered.\n if (results.some(({ result }) => result.pause !== undefined && !result.isError)) {\n return { stopReason: \"stopped\", stoppedBy: CLARIFICATION };\n }\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n return undefined;\n}\n\nasync function runStep(state: LoopState): Promise<Outcome | undefined> {\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n const message = await callModel(state);\n const results = await runTools(state, message);\n const outcome = stopCheck(state, message, results);\n state.send({ type: \"step_end\", stopCheck: outcome === undefined ? \"continue\" : \"stop\" });\n return outcome;\n}\n\n/**\n * An aborted run's transcript ends with an assistant message whose `stopReason` is `\"aborted\"`. When tool results end\n * the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop\n * appends an empty one after them; the replay pass drops it before any request.\n */\nfunction closeAborted(state: LoopState): void {\n const last = state.messages.at(-1);\n if (last?.role === \"assistant\" && last.stopReason === \"aborted\") return;\n state.append({\n role: \"assistant\",\n content: [],\n model: state.setup.model.ref,\n stopReason: \"aborted\",\n usage: emptyUsage(),\n cost: { ...NO_COST },\n });\n}\n\nfunction resultOf(state: LoopState, outcome: Outcome): RunResult {\n const base = {\n messages: state.added,\n context: { system: state.setup.system, messages: state.messages },\n usage: state.usage,\n cost: state.cost ?? { ...NO_COST },\n steps: state.steps,\n };\n return { ...base, ...outcome } as RunResult;\n}\n\nfunction finish(state: LoopState, outcome: Outcome): RunResult {\n if (outcome.stopReason === \"aborted\") closeAborted(state);\n if (outcome.stopReason === \"max_steps\") {\n state.send({ type: \"warning\", code: \"max_steps\", detail: `the run reached maxSteps (${state.setup.maxSteps})` });\n }\n if (outcome.stopReason === \"error\") state.send({ type: \"error\", error: outcome.error });\n state.send({ type: \"agent_settled\" });\n const result = resultOf(state, outcome);\n state.send({ type: \"run_end\", result });\n return result;\n}\n\n/**\n * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results\n * already received are in the transcript.\n */\nexport async function runLoop(setup: LoopSetup, emit: Emit): Promise<RunResult> {\n const state = new LoopState(setup, emit);\n let outcome: Outcome | undefined;\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n return finish(state, outcome);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAEL,OAAO,EACP,QAAQ,EAGR,UAAU,GASX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAIvC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAgB,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAGtF,kEAAkE;AAClE,MAAM,aAAa,GAAG,eAAe,CAAC;AAEtC,uGAAuG;AACvG,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAE5B;;;GAGG;AACH,MAAM,OAAO,GAAS,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU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AE,WAAW,EAAE,MAAM,EAAE,6BAA6B,KAAK,CAAC,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC,CAAC;IACnH,CAAC;IACD,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO;QAAE,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;IACxF,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC,CAAC;IACtC,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACxC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;IACxC,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,KAAgB,EAAE,IAAU;IACxD,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACzC,IAAI,OAA4B,CAAC;IACjC,OAAO,OAAO,KAAK,SAAS,EAAE,CAAC;QAC7B,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IACpF,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["/**\n * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds\n * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.\n *\n * Each step runs transform → before → stream → after → tools → stop. The transform, before and after moments are\n * where the interceptors plug in (D6); until they exist the request is the transcript as it stands and the response\n * is kept unchanged. Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed\n * tool result, throws.\n */\nimport {\n type AssistantMessage,\n addCost,\n addUsage,\n type Cost,\n type DumpedOptions,\n emptyUsage,\n type GatewayEvent,\n type Message,\n type Model,\n type ModelCallOptions,\n type ModelContext,\n type StreamOptions,\n type Usage,\n type WireTool,\n} from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\n\n/** The `stoppedBy` of a run that a clarification tool stopped. */\nconst CLARIFICATION = \"clarification\";\n\n// The depth cap's defaults (D11). Nested runs pass their own depth once the depth cap is configurable.\nconst TOP_LEVEL_DEPTH = 0;\nconst DEFAULT_MAX_DEPTH = 2;\n\n/**\n * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis\n * when it adds a provider cost, so the zero never turns a billed sum into an estimate.\n */\nconst NO_COST: Cost = { total: 0, basis: \"provider\", currency: \"USD\" };\n\n/** Everything one run needs, fixed when it starts. */\nexport interface LoopSetup {\n readonly runId: string;\n readonly model: Model;\n readonly system: string;\n /** The conversation before this run's own messages. */\n readonly history: readonly Message[];\n /** The messages the run starts by adding, such as the user's input. */\n readonly input: readonly Message[];\n /** The tools the model is sent, in definition order; only these can run. */\n readonly tools: readonly AnyTool[];\n readonly output: AnyTool | undefined;\n readonly maxSteps: number;\n readonly modelOptions: Omit<ModelCallOptions, \"signal\">;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** Sends one event; the run adds the `EventBase` fields. */\nexport type Emit = (body: AgentEventBody, stepIndex: number) => void;\n\n/** How a run ended, before its usage, cost and messages are attached. */\ntype Outcome =\n | { readonly stopReason: \"done\"; readonly output: unknown }\n | { readonly stopReason: \"max_steps\" | \"aborted\" }\n | { readonly stopReason: \"error\"; readonly error: RunError }\n | { readonly stopReason: \"stopped\"; readonly stoppedBy: string };\n\n/** What changes while a run goes on. */\nclass LoopState {\n readonly setup: LoopSetup;\n readonly emit: Emit;\n readonly messages: Message[];\n readonly added: Message[];\n readonly wireTools: WireTool[];\n steps = 0;\n stepIndex = 0;\n usage: Usage = emptyUsage();\n cost: Cost | undefined;\n output: unknown;\n\n constructor(setup: LoopSetup, emit: Emit) {\n this.setup = setup;\n this.emit = emit;\n this.messages = [...setup.history, ...setup.input];\n this.added = [...setup.input];\n this.wireTools = setup.tools.map(toWireTool);\n }\n\n send(body: AgentEventBody): void {\n this.emit(body, this.stepIndex);\n }\n\n append(message: Message): void {\n this.messages.push(message);\n this.added.push(message);\n }\n}\n\n/**\n * The stream options a request event records: everything but the payload hook, the abort signal and the caps, as the\n * gateway's own request dump leaves them out. An untyped caller may still pass a signal or caps in `modelOptions`.\n */\nfunction dumpedOptions(options: Omit<ModelCallOptions, \"signal\">): DumpedOptions {\n const { onPayload: _onPayload, signal: _signal, caps: _caps, ...rest } = options as StreamOptions;\n return rest;\n}\n\n/** Re-emits one model event as a run event, and returns the final message once the terminal event arrives. */\nfunction forward(state: LoopState, event: GatewayEvent): AssistantMessage | undefined {\n switch (event.type) {\n case \"done\":\n case \"error\":\n return event.message;\n case \"start\":\n return undefined;\n case \"retry\":\n state.send({ type: \"retry\", attempt: event.attempt, delayMs: event.delayMs, error: event.error });\n return undefined;\n case \"warning\":\n state.send({ type: \"warning\", code: \"model_warning\", detail: `${event.code}: ${event.message}` });\n return undefined;\n case \"text_start\":\n case \"reasoning_start\":\n case \"tool_input_start\":\n state.send({ type: event.type, index: event.index });\n return undefined;\n case \"text_delta\":\n case \"reasoning_delta\":\n case \"tool_input_delta\":\n state.send({ type: event.type, index: event.index, delta: event.delta });\n return undefined;\n default:\n state.send({ type: event.type, index: event.index, block: event.block });\n return undefined;\n }\n}\n\n/** Makes one model call, streams its events and records the response. */\nasync function callModel(state: LoopState): Promise<AssistantMessage> {\n const { model, system, modelOptions, signal } = state.setup;\n const context: ModelContext = { system, messages: [...state.messages], tools: state.wireTools };\n state.send({\n type: \"model_call_start\",\n request: { model: model.ref, context, options: dumpedOptions(modelOptions) },\n });\n let message: AssistantMessage | undefined;\n for await (const event of model.stream(context, { ...modelOptions, signal })) {\n message = forward(state, event) ?? message;\n }\n if (message === undefined) {\n throw new SdkError(\"invalid_model_stream\", \"the model's stream ended without a done or error event\");\n }\n state.steps += 1;\n state.usage = addUsage(state.usage, message.usage);\n state.cost = state.cost === undefined ? message.cost : addCost(state.cost, message.cost);\n state.append(message);\n state.send({ type: \"model_call_end\", message });\n return message;\n}\n\n/** The tool message the model reads for one call. */\nfunction toolMessage(entry: ToolCallResult): Message {\n return {\n role: \"tool\",\n callId: entry.call.callId,\n content: [...entry.result.content],\n isError: entry.result.isError === true,\n };\n}\n\n/** Runs the response's tool calls as the pipeline schedules them, recording each result in model order. */\nasync function runTools(state: LoopState, message: AssistantMessage): Promise<readonly ToolCallResult[]> {\n const { runId, signal, clock, tools, output } = state.setup;\n return runToolCalls(message, tools, {\n runId,\n signal,\n clock,\n depth: TOP_LEVEL_DEPTH,\n maxDepth: DEFAULT_MAX_DEPTH,\n onStart: (call: ToolCall) =>\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input }),\n onUpdate: (callId, details) => state.send({ type: \"tool_call_update\", callId, details }),\n onResult: (entry) => {\n state.append(toolMessage(entry));\n if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {\n state.output = entry.result.structured;\n }\n state.send({ type: \"tool_call_end\", callId: entry.call.callId, result: entry.result });\n },\n });\n}\n\n/** The failed call's error as the run reports it. A message without one counts as `fatal`. */\nfunction runErrorOf(message: AssistantMessage): RunError {\n const error = message.error;\n if (error === undefined) return { kind: \"fatal\", message: \"the model call failed without an error description\" };\n return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };\n}\n\n/**\n * The stop check after one step. A finished answer, or a question for the user, wins over an abort that came too late\n * to change it; otherwise an abort stops the run before the step cap does. A text answer cut off at the output limit\n * also counts as finished: its message keeps `stopReason: \"length\"`.\n */\nfunction stopCheck(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Outcome | undefined {\n if (message.stopReason === \"error\") return { stopReason: \"error\", error: runErrorOf(message) };\n if (message.stopReason === \"aborted\") return { stopReason: \"aborted\" };\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\n // Until runs can pause for an answer, a clarification question stops the run, so the model never goes on as if the\n // user had been asked and answered.\n if (results.some(({ result }) => result.pause !== undefined && !result.isError)) {\n return { stopReason: \"stopped\", stoppedBy: CLARIFICATION };\n }\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n return undefined;\n}\n\nasync function runStep(state: LoopState): Promise<Outcome | undefined> {\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n const message = await callModel(state);\n const results = await runTools(state, message);\n const outcome = stopCheck(state, message, results);\n state.send({ type: \"step_end\", stopCheck: outcome === undefined ? \"continue\" : \"stop\" });\n return outcome;\n}\n\n/**\n * An aborted run's transcript ends with an assistant message whose `stopReason` is `\"aborted\"`. When tool results end\n * the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop\n * appends an empty one after them; the replay pass drops it before any request.\n */\nfunction closeAborted(state: LoopState): void {\n const last = state.messages.at(-1);\n if (last?.role === \"assistant\" && last.stopReason === \"aborted\") return;\n state.append({\n role: \"assistant\",\n content: [],\n model: state.setup.model.ref,\n stopReason: \"aborted\",\n usage: emptyUsage(),\n cost: { ...NO_COST },\n });\n}\n\nfunction resultOf(state: LoopState, outcome: Outcome): RunResult {\n const base = {\n messages: state.added,\n context: { system: state.setup.system, messages: state.messages },\n usage: state.usage,\n cost: state.cost ?? { ...NO_COST },\n steps: state.steps,\n };\n return { ...base, ...outcome } as RunResult;\n}\n\nfunction finish(state: LoopState, outcome: Outcome): RunResult {\n if (outcome.stopReason === \"aborted\") closeAborted(state);\n if (outcome.stopReason === \"max_steps\") {\n state.send({ type: \"warning\", code: \"max_steps\", detail: `the run reached maxSteps (${state.setup.maxSteps})` });\n }\n if (outcome.stopReason === \"error\") state.send({ type: \"error\", error: outcome.error });\n state.send({ type: \"agent_settled\" });\n const result = resultOf(state, outcome);\n state.send({ type: \"run_end\", result });\n return result;\n}\n\n/**\n * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results\n * already received are in the transcript.\n */\nexport async function runLoop(setup: LoopSetup, emit: Emit): Promise<RunResult> {\n const state = new LoopState(setup, emit);\n let outcome: Outcome | undefined;\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n return finish(state, outcome);\n}\n"]}
|
package/dist/tools/define.d.ts
CHANGED
|
@@ -17,8 +17,9 @@ export declare function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>)
|
|
|
17
17
|
*
|
|
18
18
|
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
19
19
|
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
|
|
20
|
-
* values,
|
|
21
|
-
* describe itself as JSON
|
|
20
|
+
* values, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` is not a function, a raw JSON Schema
|
|
21
|
+
* does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON
|
|
22
|
+
* Schema.
|
|
22
23
|
*/
|
|
23
24
|
export declare function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S>;
|
|
24
25
|
/** The options of `outputTool()`. */
|
package/dist/tools/define.js
CHANGED
|
@@ -6,6 +6,7 @@ import { assertCanonicalName } from "@buildanagent/gateway";
|
|
|
6
6
|
import { SdkError } from "../errors.js";
|
|
7
7
|
import { prepareSchema } from "./schema.js";
|
|
8
8
|
const EXPOSURES = ["direct", "deferred", "hidden"];
|
|
9
|
+
const EXECUTION_MODES = ["parallel", "sequential"];
|
|
9
10
|
// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.
|
|
10
11
|
const prepared = new WeakMap();
|
|
11
12
|
function invalid(message, cause) {
|
|
@@ -39,6 +40,12 @@ export function preparedSchemaOf(tool) {
|
|
|
39
40
|
if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {
|
|
40
41
|
throw invalid(`tool "${name}": exposure must be "direct", "deferred" or "hidden"`);
|
|
41
42
|
}
|
|
43
|
+
if (tool.executionMode !== undefined && !EXECUTION_MODES.includes(tool.executionMode)) {
|
|
44
|
+
throw invalid(`tool "${name}": executionMode must be "parallel" or "sequential"`);
|
|
45
|
+
}
|
|
46
|
+
if (tool.resourceKey !== undefined && typeof tool.resourceKey !== "function") {
|
|
47
|
+
throw invalid(`tool "${name}": resourceKey must be a function`);
|
|
48
|
+
}
|
|
42
49
|
const schema = prepareSchema(name, tool.inputSchema);
|
|
43
50
|
prepared.set(tool, schema);
|
|
44
51
|
return schema;
|
|
@@ -48,8 +55,9 @@ export function preparedSchemaOf(tool) {
|
|
|
48
55
|
*
|
|
49
56
|
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
50
57
|
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
|
|
51
|
-
* values,
|
|
52
|
-
* describe itself as JSON
|
|
58
|
+
* values, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` is not a function, a raw JSON Schema
|
|
59
|
+
* does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON
|
|
60
|
+
* Schema.
|
|
53
61
|
*/
|
|
54
62
|
export function defineTool(definition) {
|
|
55
63
|
const tool = Object.freeze({ ...definition });
|
package/dist/tools/define.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],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,CAAC,CAAC;AACL,CAAC;AAQD,MAAM,oBAAoB,GAAG,MAAM,CAAC,MAAM,CAAC;IACzC,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC;QACxB,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,EAAE,WAAW,EAAE,+BAA+B,EAAE,CAAC;KACxG,CAAC;IACF,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,UAAU,CAAC,CAAC;IACrC,oBAAoB,EAAE,KAAK;CAC5B,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAO,GAA6B,EAAE;IACtE,OAAO,UAAU,CAA8B;QAC7C,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,UAAU;QAChC,WAAW,EAAE,wEAAwE;QACrF,WAAW,EAAE,oBAAoB;QACjC,KAAK,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE;YACxB,OAAO;gBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,oCAAoC,EAAE,CAAC;gBACvE,KAAK,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,QAAQ,EAAE;aAC3C,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,UAAU,CAAC,IAAsC;IAC/D,MAAM,EAAE,UAAU,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAC9C,yGAAyG;IACzG,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,WAAW,EAAE,UAAqC,EAAE,CAAC;AAChH,CAAC","sourcesContent":["/**\n * `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,\n * so a broken tool throws when it is defined rather than when the model first calls it.\n */\nimport { assertCanonicalName, type WireTool } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { SdkError } from \"../errors.js\";\nimport { type PreparedSchema, prepareSchema } from \"./schema.js\";\nimport type { ToolDefinition, ToolResult } from \"./types.js\";\n\nconst EXPOSURES: readonly string[] = [\"direct\", \"deferred\", \"hidden\"];\n\n// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.\nconst prepared = new WeakMap<object, PreparedSchema>();\n\nfunction invalid(message: string, cause?: unknown): SdkError {\n return new SdkError(\"invalid_tool_definition\", message, cause === undefined ? {} : { cause });\n}\n\nfunction checkName(name: unknown): string {\n if (typeof name !== \"string\") throw invalid(\"a tool's name must be a string\");\n try {\n assertCanonicalName(name);\n } catch (cause) {\n throw invalid(cause instanceof Error ? cause.message : String(cause), cause);\n }\n return name;\n}\n\n/**\n * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code\n * `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable\n * schema.\n */\nexport function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema {\n const known = prepared.get(tool);\n if (known !== undefined) return known;\n const name = checkName(tool.name);\n if (typeof tool.description !== \"string\") throw invalid(`tool \"${name}\": description must be a string`);\n if (typeof tool.execute !== \"function\") throw invalid(`tool \"${name}\": execute must be a function`);\n if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {\n throw invalid(`tool \"${name}\": exposure must be \"direct\", \"deferred\" or \"hidden\"`);\n }\n const schema = prepareSchema(name, tool.inputSchema);\n prepared.set(tool, schema);\n return schema;\n}\n\n/**\n * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.\n *\n * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters\n * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three\n * values, a raw JSON Schema does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot\n * describe itself as JSON Schema.\n */\nexport function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S> {\n const tool = Object.freeze({ ...definition });\n // Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.\n preparedSchemaOf(tool as ToolDefinition<unknown, unknown>);\n return tool;\n}\n\n/** The options of `outputTool()`. */\nexport interface OutputToolOptions<S> {\n readonly name: string;\n /** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */\n readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;\n /** Defaults to a line asking the model to call the tool once, with its final answer. */\n readonly description?: string;\n}\n\nconst OUTPUT_DESCRIPTION = \"Submit your final answer as this tool's input. Call it once, when the task is done.\";\nconst OUTPUT_ACCEPTED = \"The final answer was accepted.\";\n\n/**\n * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the\n * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model\n * as an error result, so the model can correct the answer and call again.\n */\nexport function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S> {\n return defineTool<S, S>({\n name: options.name,\n description: options.description ?? OUTPUT_DESCRIPTION,\n inputSchema: options.schema,\n async execute(input): Promise<ToolResult<S>> {\n return { content: [{ type: \"text\", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };\n },\n });\n}\n\n/** The options of `clarificationTool()`. */\nexport interface ClarificationToolOptions {\n /** Defaults to `ask_user`. */\n readonly name?: string;\n}\n\nconst CLARIFICATION_SCHEMA = Object.freeze({\n type: \"object\",\n properties: Object.freeze({\n question: Object.freeze({ type: \"string\", minLength: 1, description: \"The question to ask the user.\" }),\n }),\n required: Object.freeze([\"question\"]),\n additionalProperties: false,\n});\n\n/**\n * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind\n * `clarification`, and a run that gets it ends with `stopReason: \"stopped\"` and `stoppedBy: \"clarification\"`.\n */\nexport function clarificationTool(options: ClarificationToolOptions = {}): ToolDefinition<{ question: string }, never> {\n return defineTool<{ question: string }, never>({\n name: options.name ?? \"ask_user\",\n description: \"Ask the user a question when you cannot continue without their answer.\",\n inputSchema: CLARIFICATION_SCHEMA,\n async execute({ question }) {\n return {\n content: [{ type: \"text\", text: \"The question was sent to the user.\" }],\n pause: { kind: \"clarification\", question },\n };\n },\n });\n}\n\n/** The tool as one model call sends it: its name, description and input JSON Schema. */\nexport function toWireTool(tool: ToolDefinition<unknown, unknown>): WireTool {\n const { jsonSchema } = preparedSchemaOf(tool);\n // Adapters only read the schema; the cast drops the `readonly` that keeps our own code from changing it.\n return { name: tool.name, description: tool.description, inputSchema: jsonSchema as Record<string, unknown> };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,mBAAmB,EAAiB,MAAM,uBAAuB,CAAC;AAE3E,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAuB,aAAa,EAAE,MAAM,aAAa,CAAC;AAGjE,MAAM,SAAS,GAAsB,CAAC,QAAQ,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC;AACtE,MAAM,eAAe,GAAsB,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;AAEtE,+FAA+F;AAC/F,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA0B,CAAC;AAEvD,SAAS,OAAO,CAAC,OAAe,EAAE,KAAe;IAC/C,OAAO,IAAI,QAAQ,CAAC,yBAAyB,EAAE,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;AAChG,CAAC;AAED,SAAS,SAAS,CAAC,IAAa;IAC9B,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,MAAM,OAAO,CAAC,gCAAgC,CAAC,CAAC;IAC9E,IAA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AAM,CAAC,MAAM,CAAC,CAAC,UAAU,CAAC,CAAC;IACrC,oBAAoB,EAAE,KAAK;CAC5B,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAO,GAA6B,EAAE;IACtE,OAAO,UAAU,CAA8B;QAC7C,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,UAAU;QAChC,WAAW,EAAE,wEAAwE;QACrF,WAAW,EAAE,oBAAoB;QACjC,KAAK,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE;YACxB,OAAO;gBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,oCAAoC,EAAE,CAAC;gBACvE,KAAK,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,QAAQ,EAAE;aAC3C,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,UAAU,CAAC,IAAsC;IAC/D,MAAM,EAAE,UAAU,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAC9C,yGAAyG;IACzG,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,WAAW,EAAE,UAAqC,EAAE,CAAC;AAChH,CAAC","sourcesContent":["/**\n * `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,\n * so a broken tool throws when it is defined rather than when the model first calls it.\n */\nimport { assertCanonicalName, type WireTool } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { SdkError } from \"../errors.js\";\nimport { type PreparedSchema, prepareSchema } from \"./schema.js\";\nimport type { ToolDefinition, ToolResult } from \"./types.js\";\n\nconst EXPOSURES: readonly string[] = [\"direct\", \"deferred\", \"hidden\"];\nconst EXECUTION_MODES: readonly string[] = [\"parallel\", \"sequential\"];\n\n// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.\nconst prepared = new WeakMap<object, PreparedSchema>();\n\nfunction invalid(message: string, cause?: unknown): SdkError {\n return new SdkError(\"invalid_tool_definition\", message, cause === undefined ? {} : { cause });\n}\n\nfunction checkName(name: unknown): string {\n if (typeof name !== \"string\") throw invalid(\"a tool's name must be a string\");\n try {\n assertCanonicalName(name);\n } catch (cause) {\n throw invalid(cause instanceof Error ? cause.message : String(cause), cause);\n }\n return name;\n}\n\n/**\n * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code\n * `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable\n * schema.\n */\nexport function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema {\n const known = prepared.get(tool);\n if (known !== undefined) return known;\n const name = checkName(tool.name);\n if (typeof tool.description !== \"string\") throw invalid(`tool \"${name}\": description must be a string`);\n if (typeof tool.execute !== \"function\") throw invalid(`tool \"${name}\": execute must be a function`);\n if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {\n throw invalid(`tool \"${name}\": exposure must be \"direct\", \"deferred\" or \"hidden\"`);\n }\n if (tool.executionMode !== undefined && !EXECUTION_MODES.includes(tool.executionMode)) {\n throw invalid(`tool \"${name}\": executionMode must be \"parallel\" or \"sequential\"`);\n }\n if (tool.resourceKey !== undefined && typeof tool.resourceKey !== \"function\") {\n throw invalid(`tool \"${name}\": resourceKey must be a function`);\n }\n const schema = prepareSchema(name, tool.inputSchema);\n prepared.set(tool, schema);\n return schema;\n}\n\n/**\n * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.\n *\n * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters\n * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three\n * values, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` is not a function, a raw JSON Schema\n * does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON\n * Schema.\n */\nexport function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S> {\n const tool = Object.freeze({ ...definition });\n // Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.\n preparedSchemaOf(tool as ToolDefinition<unknown, unknown>);\n return tool;\n}\n\n/** The options of `outputTool()`. */\nexport interface OutputToolOptions<S> {\n readonly name: string;\n /** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */\n readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;\n /** Defaults to a line asking the model to call the tool once, with its final answer. */\n readonly description?: string;\n}\n\nconst OUTPUT_DESCRIPTION = \"Submit your final answer as this tool's input. Call it once, when the task is done.\";\nconst OUTPUT_ACCEPTED = \"The final answer was accepted.\";\n\n/**\n * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the\n * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model\n * as an error result, so the model can correct the answer and call again.\n */\nexport function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S> {\n return defineTool<S, S>({\n name: options.name,\n description: options.description ?? OUTPUT_DESCRIPTION,\n inputSchema: options.schema,\n async execute(input): Promise<ToolResult<S>> {\n return { content: [{ type: \"text\", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };\n },\n });\n}\n\n/** The options of `clarificationTool()`. */\nexport interface ClarificationToolOptions {\n /** Defaults to `ask_user`. */\n readonly name?: string;\n}\n\nconst CLARIFICATION_SCHEMA = Object.freeze({\n type: \"object\",\n properties: Object.freeze({\n question: Object.freeze({ type: \"string\", minLength: 1, description: \"The question to ask the user.\" }),\n }),\n required: Object.freeze([\"question\"]),\n additionalProperties: false,\n});\n\n/**\n * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind\n * `clarification`, and a run that gets it ends with `stopReason: \"stopped\"` and `stoppedBy: \"clarification\"`.\n */\nexport function clarificationTool(options: ClarificationToolOptions = {}): ToolDefinition<{ question: string }, never> {\n return defineTool<{ question: string }, never>({\n name: options.name ?? \"ask_user\",\n description: \"Ask the user a question when you cannot continue without their answer.\",\n inputSchema: CLARIFICATION_SCHEMA,\n async execute({ question }) {\n return {\n content: [{ type: \"text\", text: \"The question was sent to the user.\" }],\n pause: { kind: \"clarification\", question },\n };\n },\n });\n}\n\n/** The tool as one model call sends it: its name, description and input JSON Schema. */\nexport function toWireTool(tool: ToolDefinition<unknown, unknown>): WireTool {\n const { jsonSchema } = preparedSchemaOf(tool);\n // Adapters only read the schema; the cast drops the `readonly` that keeps our own code from changing it.\n return { name: tool.name, description: tool.description, inputSchema: jsonSchema as Record<string, unknown> };\n}\n"]}
|
|
@@ -32,6 +32,7 @@ function showArguments(input) {
|
|
|
32
32
|
}
|
|
33
33
|
const NOT_RUN = {
|
|
34
34
|
run_aborted: (tool) => `Tool "${tool}" was not run, because the run was cancelled.`,
|
|
35
|
+
sibling_failed: (tool) => `Tool "${tool}" was not run, because another call in the same step failed with an error in the tool itself.`,
|
|
35
36
|
response_error: (tool) => `Tool "${tool}" was not run, because the response ended with an error before it was complete. Re-issue the ` +
|
|
36
37
|
"call if it is still needed.",
|
|
37
38
|
response_aborted: (tool) => `Tool "${tool}" was not run, because the response was stopped before it was complete. Re-issue the call if it ` +
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format-error.js","sourceRoot":"","sources":["../../src/tools/format-error.ts"],"names":[],"mappings":"AAQA,sDAAsD;AACtD,MAAM,CAAC,MAAM,iBAAiB,GAC5B,6GAA6G;IAC7G,yCAAyC,CAAC;AAE5C,sFAAsF;AACtF,MAAM,CAAC,MAAM,gBAAgB,GAAG,8BAA8B,CAAC;AAE/D,yGAAyG;AACzG,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAElC,qGAAqG;AACrG,SAAS,WAAW,CAAC,KAAc;IACjC,IAAI,CAAC;QACH,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IAAC,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,KAAK,CAAC,OAAO,EAAE,CAAC;AACvF,CAAC;AAED,SAAS,QAAQ,CAAC,OAAoB;IACpC,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;QACrB,KAAK,cAAc,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,OAAO,CAAC,cAAc,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC/F,OAAO,2BAA2B,OAAO,CAAC,IAAI,+BAA+B,KAAK,GAAG,CAAC;QACxF,CAAC;QACD,KAAK,eAAe;YAClB,OAAO,CAAC,2BAA2B,OAAO,CAAC,IAAI,gBAAgB,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAChH,KAAK,iBAAiB;YACpB,OAAO,SAAS,OAAO,CAAC,IAAI,aAAa,OAAO,CAAC,OAAO,EAAE,CAAC;QAC7D,KAAK,WAAW;YACd,OAAO,CACL,SAAS,OAAO,CAAC,IAAI,iFAAiF;gBACtG,mGAAmG,CACpG,CAAC;QACJ,KAAK,SAAS;YACZ,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED,uHAAuH;AACvH,MAAM,UAAU,eAAe,CAAC,OAAoB;IAClD,MAAM,IAAI,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,uBAAuB,aAAa,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,EAAE,iBAAiB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACtH,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;AAClC,CAAC","sourcesContent":["/**\n * The default error text the model reads for a failed tool call. Every message says what failed, shows the\n * arguments the model sent, and tells the model not to answer the failure with invented data, because agents have\n * been seen to \"make a mock implementation\" when a tool fails (agent-SDK guide §4).\n */\nimport type { ModelContent } from \"@buildanagent/gateway\";\nimport type { SchemaIssue, ToolFailure } from \"./types.js\";\n\n/** The line every default error message ends with. */\nexport const DO_NOT_SUBSTITUTE =\n \"Do not substitute a mock, a placeholder or invented data for this tool's result. Fix the call, try another \" +\n \"approach, or tell the user what failed.\";\n\n/** The fixed line a redacted error shows the model in place of the thrown message. */\nexport const REDACTED_MESSAGE = \"its error message is hidden.\";\n\n// Received arguments are shown up to this many characters, so one huge argument can't flood the context.\nconst MAX_ARGUMENTS_LENGTH = 2000;\n\n// `String()` can itself throw, on an object with no prototype, so the last resort is the object tag.\nfunction plainString(input: unknown): string {\n try {\n return String(input);\n } catch {\n return Object.prototype.toString.call(input);\n }\n}\n\nfunction showArguments(input: unknown): string {\n let text: string;\n try {\n text = JSON.stringify(input) ?? plainString(input);\n } catch {\n // Input from a test double or a tool bridge may hold a cycle or a bigint, which JSON can't encode.\n text = plainString(input);\n }\n if (text.length <= MAX_ARGUMENTS_LENGTH) return text;\n // Cut before a surrogate pair rather than through it, so the text stays valid UTF-16.\n const high = text.charCodeAt(MAX_ARGUMENTS_LENGTH - 1);\n const end = high >= 0xd800 && high <= 0xdbff ? MAX_ARGUMENTS_LENGTH - 1 : MAX_ARGUMENTS_LENGTH;\n return `${text.slice(0, end)}… (${text.length - end} more characters)`;\n}\n\nconst NOT_RUN = {\n run_aborted: (tool: string) => `Tool \"${tool}\" was not run, because the run was cancelled.`,\n response_error: (tool: string) =>\n `Tool \"${tool}\" was not run, because the response ended with an error before it was complete. Re-issue the ` +\n \"call if it is still needed.\",\n response_aborted: (tool: string) =>\n `Tool \"${tool}\" was not run, because the response was stopped before it was complete. Re-issue the call if it ` +\n \"is still needed.\",\n} as const;\n\nfunction issueLine(issue: SchemaIssue): string {\n return `- ${issue.path === \"\" ? \"(the whole input)\" : issue.path}: ${issue.message}`;\n}\n\nfunction describe(failure: ToolFailure): string {\n switch (failure.kind) {\n case \"unknown_tool\": {\n const tools = failure.availableTools.length === 0 ? \"none\" : failure.availableTools.join(\", \");\n return `There is no tool named \"${failure.tool}\". The available tools are: ${tools}.`;\n }\n case \"invalid_input\":\n return [`The arguments for tool \"${failure.tool}\" are invalid:`, ...failure.issues.map(issueLine)].join(\"\\n\");\n case \"execution_error\":\n return `Tool \"${failure.tool}\" failed: ${failure.message}`;\n case \"truncated\":\n return (\n `Tool \"${failure.tool}\" was not run, because the response was cut off at the output limit before the ` +\n \"call's arguments were complete. Re-issue the call with complete arguments, in a shorter response.\"\n );\n case \"not_run\":\n return NOT_RUN[failure.reason](failure.tool);\n }\n}\n\n/** The default content for a failed tool call: what failed, the received arguments, and the do-not-substitute line. */\nexport function formatToolError(failure: ToolFailure): ModelContent[] {\n const text = [describe(failure), `Received arguments: ${showArguments(failure.input)}`, DO_NOT_SUBSTITUTE].join(\"\\n\");\n return [{ type: \"text\", text }];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"format-error.js","sourceRoot":"","sources":["../../src/tools/format-error.ts"],"names":[],"mappings":"AAQA,sDAAsD;AACtD,MAAM,CAAC,MAAM,iBAAiB,GAC5B,6GAA6G;IAC7G,yCAAyC,CAAC;AAE5C,sFAAsF;AACtF,MAAM,CAAC,MAAM,gBAAgB,GAAG,8BAA8B,CAAC;AAE/D,yGAAyG;AACzG,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAElC,qGAAqG;AACrG,SAAS,WAAW,CAAC,KAAc;IACjC,IAAI,CAAC;QACH,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,IAAY,CAAC;IACjB,IAAI,CAAC;QACH,IAAI,GAAG,IAAI,C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AE,CAAC;YACpB,MAAM,KAAK,GAAG,OAAO,CAAC,cAAc,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC/F,OAAO,2BAA2B,OAAO,CAAC,IAAI,+BAA+B,KAAK,GAAG,CAAC;QACxF,CAAC;QACD,KAAK,eAAe;YAClB,OAAO,CAAC,2BAA2B,OAAO,CAAC,IAAI,gBAAgB,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAChH,KAAK,iBAAiB;YACpB,OAAO,SAAS,OAAO,CAAC,IAAI,aAAa,OAAO,CAAC,OAAO,EAAE,CAAC;QAC7D,KAAK,WAAW;YACd,OAAO,CACL,SAAS,OAAO,CAAC,IAAI,iFAAiF;gBACtG,mGAAmG,CACpG,CAAC;QACJ,KAAK,SAAS;YACZ,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED,uHAAuH;AACvH,MAAM,UAAU,eAAe,CAAC,OAAoB;IAClD,MAAM,IAAI,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,uBAAuB,aAAa,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,EAAE,iBAAiB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACtH,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;AAClC,CAAC","sourcesContent":["/**\n * The default error text the model reads for a failed tool call. Every message says what failed, shows the\n * arguments the model sent, and tells the model not to answer the failure with invented data, because agents have\n * been seen to \"make a mock implementation\" when a tool fails (agent-SDK guide §4).\n */\nimport type { ModelContent } from \"@buildanagent/gateway\";\nimport type { SchemaIssue, ToolFailure } from \"./types.js\";\n\n/** The line every default error message ends with. */\nexport const DO_NOT_SUBSTITUTE =\n \"Do not substitute a mock, a placeholder or invented data for this tool's result. Fix the call, try another \" +\n \"approach, or tell the user what failed.\";\n\n/** The fixed line a redacted error shows the model in place of the thrown message. */\nexport const REDACTED_MESSAGE = \"its error message is hidden.\";\n\n// Received arguments are shown up to this many characters, so one huge argument can't flood the context.\nconst MAX_ARGUMENTS_LENGTH = 2000;\n\n// `String()` can itself throw, on an object with no prototype, so the last resort is the object tag.\nfunction plainString(input: unknown): string {\n try {\n return String(input);\n } catch {\n return Object.prototype.toString.call(input);\n }\n}\n\nfunction showArguments(input: unknown): string {\n let text: string;\n try {\n text = JSON.stringify(input) ?? plainString(input);\n } catch {\n // Input from a test double or a tool bridge may hold a cycle or a bigint, which JSON can't encode.\n text = plainString(input);\n }\n if (text.length <= MAX_ARGUMENTS_LENGTH) return text;\n // Cut before a surrogate pair rather than through it, so the text stays valid UTF-16.\n const high = text.charCodeAt(MAX_ARGUMENTS_LENGTH - 1);\n const end = high >= 0xd800 && high <= 0xdbff ? MAX_ARGUMENTS_LENGTH - 1 : MAX_ARGUMENTS_LENGTH;\n return `${text.slice(0, end)}… (${text.length - end} more characters)`;\n}\n\nconst NOT_RUN = {\n run_aborted: (tool: string) => `Tool \"${tool}\" was not run, because the run was cancelled.`,\n sibling_failed: (tool: string) =>\n `Tool \"${tool}\" was not run, because another call in the same step failed with an error in the tool itself.`,\n response_error: (tool: string) =>\n `Tool \"${tool}\" was not run, because the response ended with an error before it was complete. Re-issue the ` +\n \"call if it is still needed.\",\n response_aborted: (tool: string) =>\n `Tool \"${tool}\" was not run, because the response was stopped before it was complete. Re-issue the call if it ` +\n \"is still needed.\",\n} as const;\n\nfunction issueLine(issue: SchemaIssue): string {\n return `- ${issue.path === \"\" ? \"(the whole input)\" : issue.path}: ${issue.message}`;\n}\n\nfunction describe(failure: ToolFailure): string {\n switch (failure.kind) {\n case \"unknown_tool\": {\n const tools = failure.availableTools.length === 0 ? \"none\" : failure.availableTools.join(\", \");\n return `There is no tool named \"${failure.tool}\". The available tools are: ${tools}.`;\n }\n case \"invalid_input\":\n return [`The arguments for tool \"${failure.tool}\" are invalid:`, ...failure.issues.map(issueLine)].join(\"\\n\");\n case \"execution_error\":\n return `Tool \"${failure.tool}\" failed: ${failure.message}`;\n case \"truncated\":\n return (\n `Tool \"${failure.tool}\" was not run, because the response was cut off at the output limit before the ` +\n \"call's arguments were complete. Re-issue the call with complete arguments, in a shorter response.\"\n );\n case \"not_run\":\n return NOT_RUN[failure.reason](failure.tool);\n }\n}\n\n/** The default content for a failed tool call: what failed, the received arguments, and the do-not-substitute line. */\nexport function formatToolError(failure: ToolFailure): ModelContent[] {\n const text = [describe(failure), `Received arguments: ${showArguments(failure.input)}`, DO_NOT_SUBSTITUTE].join(\"\\n\");\n return [{ type: \"text\", text }];\n}\n"]}
|
package/dist/tools/pipeline.d.ts
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* `SdkError`.
|
|
6
6
|
*
|
|
7
7
|
* The gate and `afterToolCall` steps hold their places in the order below, and the interceptors fill them in: until
|
|
8
|
-
* then every call is allowed and every result passes through unchanged.
|
|
8
|
+
* then every call is allowed and every result passes through unchanged. A step's calls are checked and gated one at a
|
|
9
|
+
* time, in model order, and then scheduled together (see `runCalls`).
|
|
9
10
|
*/
|
|
10
11
|
import type { AssistantMessage } from "@buildanagent/gateway";
|
|
11
12
|
import type { Clock } from "../testing/determinism.js";
|
|
@@ -19,6 +20,16 @@ export interface PipelineContext {
|
|
|
19
20
|
readonly depth: number;
|
|
20
21
|
readonly maxDepth: number;
|
|
21
22
|
readonly clock: Clock;
|
|
23
|
+
/**
|
|
24
|
+
* The gate: asked once for each call that passed validation, one call at a time in model order, and before any call
|
|
25
|
+
* of the step executes. It returns a result to block the call, or `undefined` to let it run. Without a gate every
|
|
26
|
+
* call is allowed.
|
|
27
|
+
*/
|
|
28
|
+
gate?(e: {
|
|
29
|
+
readonly call: ToolCall;
|
|
30
|
+
readonly tool: AnyTool;
|
|
31
|
+
readonly input: unknown;
|
|
32
|
+
}): Promise<ToolResult | undefined>;
|
|
22
33
|
/** Called for each call of a message before its result is worked out, whether or not the call will run. */
|
|
23
34
|
onStart?(call: ToolCall): void;
|
|
24
35
|
/** Receives a tool's progress updates. */
|
|
@@ -46,9 +57,9 @@ export interface ToolCallResult {
|
|
|
46
57
|
*/
|
|
47
58
|
export declare function runToolCall(call: ToolCall, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolResult>;
|
|
48
59
|
/**
|
|
49
|
-
* Runs every tool call of an assistant message
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
60
|
+
* Runs every tool call of an assistant message and passes each result to `ctx.onResult` in model order. A message
|
|
61
|
+
* that stopped at the output limit (`stopReason: "length"`) runs nothing: each of its calls gets an error asking the
|
|
62
|
+
* model to re-issue it, because its arguments may be cut short. A message that ended in an error or was aborted also
|
|
63
|
+
* runs nothing, because its calls may be partial. Otherwise the calls are scheduled as `runCalls` describes.
|
|
53
64
|
*/
|
|
54
65
|
export declare function runToolCalls(message: AssistantMessage, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolCallResult[]>;
|
package/dist/tools/pipeline.js
CHANGED
|
@@ -3,6 +3,7 @@ import { coerceValue } from "./coerce.js";
|
|
|
3
3
|
import { preparedSchemaOf } from "./define.js";
|
|
4
4
|
import { formatToolError, REDACTED_MESSAGE } from "./format-error.js";
|
|
5
5
|
import { withOutcome } from "./outcome.js";
|
|
6
|
+
import { schedule } from "./scheduler.js";
|
|
6
7
|
function toolsByName(tools) {
|
|
7
8
|
const byName = new Map();
|
|
8
9
|
for (const tool of tools) {
|
|
@@ -122,31 +123,6 @@ async function execute(tool, call, input, ctx) {
|
|
|
122
123
|
ctx.onExecuted?.(call);
|
|
123
124
|
return withOutcome(tool.name, checkResult(tool.name, result));
|
|
124
125
|
}
|
|
125
|
-
/**
|
|
126
|
-
* Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure
|
|
127
|
-
* the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws
|
|
128
|
-
* an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
|
|
129
|
-
*/
|
|
130
|
-
export async function runToolCall(call, tools, ctx) {
|
|
131
|
-
const byName = toolsByName(tools);
|
|
132
|
-
const tool = byName.get(call.name);
|
|
133
|
-
if (tool === undefined) {
|
|
134
|
-
const availableTools = [...byName.keys()];
|
|
135
|
-
return failed({ kind: "unknown_tool", tool: call.name, callId: call.callId, input: call.input, availableTools }, undefined);
|
|
136
|
-
}
|
|
137
|
-
// Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.
|
|
138
|
-
if (ctx.signal.aborted)
|
|
139
|
-
return notRun(call, tool, "run_aborted");
|
|
140
|
-
const checked = await checkInput(tool, call);
|
|
141
|
-
if (!checked.ok)
|
|
142
|
-
return checked.result;
|
|
143
|
-
if (ctx.signal.aborted)
|
|
144
|
-
return notRun(call, tool, "run_aborted");
|
|
145
|
-
// Gate: every call is allowed until the beforeToolCall interceptor exists.
|
|
146
|
-
const result = await execute(tool, call, checked.input, ctx);
|
|
147
|
-
// afterToolCall: the result passes through unchanged until that interceptor exists.
|
|
148
|
-
return result;
|
|
149
|
-
}
|
|
150
126
|
function notRun(call, tool, reason) {
|
|
151
127
|
return failed({ kind: "not_run", reason, tool: call.name, callId: call.callId, input: call.input }, tool);
|
|
152
128
|
}
|
|
@@ -164,22 +140,171 @@ function unrunnable(message, call, tools) {
|
|
|
164
140
|
return undefined;
|
|
165
141
|
}
|
|
166
142
|
}
|
|
143
|
+
function resourceKeyOf(tool, input) {
|
|
144
|
+
if (tool.resourceKey === undefined)
|
|
145
|
+
return undefined;
|
|
146
|
+
let key;
|
|
147
|
+
try {
|
|
148
|
+
key = tool.resourceKey(input);
|
|
149
|
+
}
|
|
150
|
+
catch (cause) {
|
|
151
|
+
throw new SdkError("invalid_tool_definition", `tool "${tool.name}": resourceKey threw: ${errorMessage(cause)}`, {
|
|
152
|
+
cause,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (typeof key !== "string") {
|
|
156
|
+
throw new SdkError("invalid_tool_definition", `tool "${tool.name}": resourceKey must return a string`);
|
|
157
|
+
}
|
|
158
|
+
return key;
|
|
159
|
+
}
|
|
160
|
+
// Everything that happens before execution, for one call: name, cancellation, input checks, resource key, and the
|
|
161
|
+
// gate. A call that fails any of them is `Done` with the result the model reads.
|
|
162
|
+
async function prepareCall(call, early, byName, ctx) {
|
|
163
|
+
if (early !== undefined)
|
|
164
|
+
return { kind: "done", call, result: early };
|
|
165
|
+
const tool = byName.get(call.name);
|
|
166
|
+
if (tool === undefined) {
|
|
167
|
+
const availableTools = [...byName.keys()];
|
|
168
|
+
const failure = {
|
|
169
|
+
kind: "unknown_tool",
|
|
170
|
+
tool: call.name,
|
|
171
|
+
callId: call.callId,
|
|
172
|
+
input: call.input,
|
|
173
|
+
availableTools,
|
|
174
|
+
};
|
|
175
|
+
return { kind: "done", call, result: failed(failure, undefined) };
|
|
176
|
+
}
|
|
177
|
+
// Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.
|
|
178
|
+
if (ctx.signal.aborted)
|
|
179
|
+
return { kind: "done", call, result: notRun(call, tool, "run_aborted") };
|
|
180
|
+
const checked = await checkInput(tool, call);
|
|
181
|
+
if (!checked.ok)
|
|
182
|
+
return { kind: "done", call, result: checked.result };
|
|
183
|
+
if (ctx.signal.aborted)
|
|
184
|
+
return { kind: "done", call, result: notRun(call, tool, "run_aborted") };
|
|
185
|
+
const key = resourceKeyOf(tool, checked.input);
|
|
186
|
+
// Each call's gate settles before the next call's is asked, and every gate before any call executes.
|
|
187
|
+
const blocked = await ctx.gate?.({ call, tool, input: checked.input });
|
|
188
|
+
if (blocked !== undefined)
|
|
189
|
+
return { kind: "done", call, result: blocked };
|
|
190
|
+
return { kind: "ready", call, tool, input: checked.input, key };
|
|
191
|
+
}
|
|
192
|
+
// Only a first-party tool's hint counts: an MCP server's annotations are claims by someone we don't control. A tool
|
|
193
|
+
// with an `effect` changes the world whatever its hint says, so it always queues as a writer.
|
|
194
|
+
function isTrustedReadOnly(tool) {
|
|
195
|
+
return tool.firstParty === true && tool.annotations?.readOnlyHint === true && tool.effect === undefined;
|
|
196
|
+
}
|
|
197
|
+
// Relays the run's cancellation to the signal the batch's tools receive, which a failing sibling can also fire.
|
|
198
|
+
function batchController(runSignal) {
|
|
199
|
+
const batch = new AbortController();
|
|
200
|
+
const relay = () => batch.abort(runSignal.reason);
|
|
201
|
+
if (runSignal.aborted)
|
|
202
|
+
relay();
|
|
203
|
+
else
|
|
204
|
+
runSignal.addEventListener("abort", relay, { once: true });
|
|
205
|
+
return { batch, release: () => runSignal.removeEventListener("abort", relay) };
|
|
206
|
+
}
|
|
207
|
+
// Runs one ready call under the batch's signal. A programmer error cancels the siblings before it propagates; a
|
|
208
|
+
// model-caused failure is an ordinary result and cancels nothing.
|
|
209
|
+
async function runReady(item, ctx, batch) {
|
|
210
|
+
if (batch.signal.aborted) {
|
|
211
|
+
return notRun(item.call, item.tool, ctx.signal.aborted ? "run_aborted" : "sibling_failed");
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
return await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
batch.abort(error);
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
// Starts every ready call by the scheduling rules and returns, in model order, the promise of each call's result.
|
|
222
|
+
function start(prepared, sequential, ctx, batch) {
|
|
223
|
+
const ready = prepared.filter((item) => item.kind === "ready");
|
|
224
|
+
const scheduled = schedule(ready.map((item) => ({
|
|
225
|
+
...(item.key === undefined ? {} : { key: item.key }),
|
|
226
|
+
readOnly: isTrustedReadOnly(item.tool),
|
|
227
|
+
run: () => runReady(item, ctx, batch),
|
|
228
|
+
})), sequential);
|
|
229
|
+
const byItem = new Map(ready.map((item, index) => [item, scheduled[index]]));
|
|
230
|
+
return prepared.map((item) => (item.kind === "done" ? undefined : byItem.get(item)) ??
|
|
231
|
+
Promise.resolve({ ok: true, value: item.result }));
|
|
232
|
+
}
|
|
167
233
|
/**
|
|
168
|
-
* Runs
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
234
|
+
* Runs the calls of one step. Each call is checked and gated one at a time, in model order, before any call executes.
|
|
235
|
+
* The calls that passed then start together, except that a call to a sequential tool makes the whole step run one
|
|
236
|
+
* call at a time, even when that call itself fails a check, and calls that share a `resourceKey` queue in model
|
|
237
|
+
* order. Results reach `ctx.onResult` in model order, each as soon as every result before it is in.
|
|
238
|
+
*
|
|
239
|
+
* A programmer error (an `SdkError`) in one call fires the signal the other calls hold, waits for them to stop, and
|
|
240
|
+
* is then thrown, after every other call's result has been passed on: a call after the failing one may have run and
|
|
241
|
+
* written. A programmer error while the calls are checked, such as a `resourceKey` that throws, is thrown after the
|
|
242
|
+
* calls already checked get their results, so every call that started has one, except the call that failed.
|
|
172
243
|
*/
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
244
|
+
async function runCalls(calls, early, tools, ctx) {
|
|
245
|
+
const byName = toolsByName(tools);
|
|
246
|
+
const prepared = [];
|
|
247
|
+
try {
|
|
248
|
+
for (const call of calls) {
|
|
249
|
+
ctx.onStart?.(call);
|
|
250
|
+
prepared.push(await prepareCall(call, early(call), byName, ctx));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
// None of these calls has executed, and none will.
|
|
255
|
+
for (const item of prepared) {
|
|
256
|
+
const result = item.kind === "done" ? item.result : notRun(item.call, item.tool, "sibling_failed");
|
|
257
|
+
ctx.onResult?.({ call: item.call, result });
|
|
258
|
+
}
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
const sequential = calls.some((call) => byName.get(call.name)?.executionMode === "sequential");
|
|
262
|
+
const { batch, release } = batchController(ctx.signal);
|
|
263
|
+
try {
|
|
264
|
+
return await deliver(prepared, start(prepared, sequential, ctx, batch), ctx);
|
|
265
|
+
}
|
|
266
|
+
finally {
|
|
267
|
+
release();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
// Passes each result on in model order, as soon as every result before it is in. A failed call has already cancelled
|
|
271
|
+
// the others; the loop still waits for each of them and passes its result on, so none is left running and a write
|
|
272
|
+
// that happened is recorded, and then the first error is thrown.
|
|
273
|
+
async function deliver(prepared, running, ctx) {
|
|
176
274
|
const results = [];
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const
|
|
275
|
+
let failure;
|
|
276
|
+
for (const [index, pending] of running.entries()) {
|
|
277
|
+
const settled = await pending;
|
|
278
|
+
if (!settled.ok) {
|
|
279
|
+
failure ??= { error: settled.error };
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
const entry = { call: prepared[index].call, result: settled.value };
|
|
180
283
|
results.push(entry);
|
|
181
284
|
ctx.onResult?.(entry);
|
|
182
285
|
}
|
|
286
|
+
if (failure !== undefined)
|
|
287
|
+
throw failure.error;
|
|
183
288
|
return results;
|
|
184
289
|
}
|
|
290
|
+
/**
|
|
291
|
+
* Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure
|
|
292
|
+
* the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws
|
|
293
|
+
* an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
|
|
294
|
+
*/
|
|
295
|
+
export async function runToolCall(call, tools, ctx) {
|
|
296
|
+
const { onStart: _start, onResult: _result, ...quiet } = ctx;
|
|
297
|
+
const [entry] = await runCalls([call], () => undefined, tools, quiet);
|
|
298
|
+
return entry.result;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Runs every tool call of an assistant message and passes each result to `ctx.onResult` in model order. A message
|
|
302
|
+
* that stopped at the output limit (`stopReason: "length"`) runs nothing: each of its calls gets an error asking the
|
|
303
|
+
* model to re-issue it, because its arguments may be cut short. A message that ended in an error or was aborted also
|
|
304
|
+
* runs nothing, because its calls may be partial. Otherwise the calls are scheduled as `runCalls` describes.
|
|
305
|
+
*/
|
|
306
|
+
export async function runToolCalls(message, tools, ctx) {
|
|
307
|
+
const calls = message.content.filter((block) => block.type === "tool_call");
|
|
308
|
+
return runCalls(calls, (call) => unrunnable(message, call, tools), tools, ctx);
|
|
309
|
+
}
|
|
185
310
|
//# sourceMappingURL=pipeline.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/tools/pipeline.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAmC3C,SAAS,WAAW,CAAC,KAAyB;IAC5C,MAAM,MAAM,GAAG,IAAI,GAAG,EAAmB,CAAC;IAC1C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,gBAAgB,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,QAAQ,CAAC,yBAAyB,EAAE,wBAAwB,IAAI,CAAC,IAAI,8BAA8B,CAAC,CAAC;QACjH,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,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K,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,GAAG,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC;QACpB,MAAM,KAAK,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,MAAM,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;QAC1G,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACpB,GAAG,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/**\n * The tool pipeline: the fixed steps every tool call runs (agent-SDK guide §4). Resolve the name, coerce, validate,\n * an optional `repair`, the gate, `execute`, the write outcome, then `afterToolCall`. A failure the model caused\n * becomes an error result and never throws; only a programmer error, such as a malformed tool result, throws an\n * `SdkError`.\n *\n * The gate and `afterToolCall` steps hold their places in the order below, and the interceptors fill them in: until\n * then every call is allowed and every result passes through unchanged. Calls run one at a time, in model order.\n */\nimport type { AssistantMessage, ModelContent } from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport { coerceValue } from \"./coerce.js\";\nimport { preparedSchemaOf } from \"./define.js\";\nimport { formatToolError, REDACTED_MESSAGE } from \"./format-error.js\";\nimport { withOutcome } from \"./outcome.js\";\nimport type { ToolCall, ToolDefinition, ToolFailure, ToolResult } from \"./types.js\";\n\n/** A tool of any input and structured type, as the pipeline holds it. */\nexport type AnyTool = ToolDefinition<unknown, unknown>;\n\n/** What the pipeline needs from the run around it. */\nexport interface PipelineContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly depth: number;\n readonly maxDepth: number;\n readonly clock: Clock;\n /** Called for each call of a message before its result is worked out, whether or not the call will run. */\n onStart?(call: ToolCall): void;\n /** Receives a tool's progress updates. */\n onUpdate?(callId: string, details: unknown): void;\n /**\n * Receives each call's result as soon as `runToolCalls` has it, so the run can record a write before a later call\n * in the same message throws.\n */\n onResult?(entry: ToolCallResult): void;\n /**\n * Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write\n * may have happened even when its result then throws an `SdkError`.\n */\n onExecuted?(call: ToolCall): void;\n}\n\n/** One tool call and the result the model will read for it. */\nexport interface ToolCallResult {\n readonly call: ToolCall;\n readonly result: ToolResult;\n}\n\nfunction toolsByName(tools: readonly AnyTool[]): ReadonlyMap<string, AnyTool> {\n const byName = new Map<string, AnyTool>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (byName.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n byName.set(tool.name, tool);\n }\n return byName;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isModelContent(block: unknown): block is ModelContent {\n if (typeof block !== \"object\" || block === null) return false;\n const { type, text, mediaType, data } = block as Record<string, unknown>;\n if (type === \"text\") return typeof text === \"string\";\n return type === \"image\" && typeof mediaType === \"string\" && typeof data === \"string\";\n}\n\nfunction isContentList(content: unknown): content is readonly ModelContent[] {\n return Array.isArray(content) && content.every(isModelContent);\n}\n\ntype Formatted = { readonly content: readonly ModelContent[]; readonly error?: string };\n\n// A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so\n// the default text is used instead, and the formatter's error is kept in `details`.\nfunction formatted(failure: ToolFailure, tool: AnyTool | undefined): Formatted {\n const fallback = formatToolError(failure);\n if (tool?.formatError === undefined) return { content: fallback };\n let content: unknown;\n try {\n content = tool.formatError(failure);\n } catch (error) {\n return { content: fallback, error: errorMessage(error) };\n }\n if (isContentList(content)) return { content };\n return { content: fallback, error: \"formatError did not return a list of text and image blocks\" };\n}\n\nfunction failed(failure: ToolFailure, tool: AnyTool | undefined, details: Record<string, unknown> = {}): ToolResult {\n const { content, error: formatterError } = formatted(failure, tool);\n return {\n content,\n isError: true,\n details: { failure, ...details, ...(formatterError === undefined ? {} : { formatterError }) },\n };\n}\n\ntype Checked = { readonly ok: true; readonly input: unknown } | { readonly ok: false; readonly result: ToolResult };\n\n// Coerce, validate, and on failure give `repair` one chance. The model sees the issues of its own arguments, and\n// `details` keeps what repair returned.\nasync function checkInput(tool: AnyTool, call: ToolCall): Promise<Checked> {\n const schema = preparedSchemaOf(tool);\n const coerced = coerceValue(call.input, schema.jsonSchema);\n const first = await schema.validate(coerced);\n if (first.ok) return { ok: true, input: first.value };\n const failure: ToolFailure = {\n kind: \"invalid_input\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n issues: first.issues,\n };\n if (tool.repair === undefined) return { ok: false, result: failed(failure, tool) };\n let repaired: unknown;\n try {\n repaired = await tool.repair({ input: coerced, issues: first.issues });\n } catch (error) {\n return { ok: false, result: failed(failure, tool, { repairError: errorMessage(error) }) };\n }\n if (repaired === undefined) return { ok: false, result: failed(failure, tool) };\n const second = await schema.validate(coerceValue(repaired, schema.jsonSchema));\n if (second.ok) return { ok: true, input: second.value };\n return { ok: false, result: failed(failure, tool, { repaired, repairedIssues: second.issues }) };\n}\n\nfunction checkResult(tool: string, result: unknown): ToolResult {\n const content = (result as { content?: unknown } | null)?.content;\n if (typeof result !== \"object\" || result === null || !isContentList(content)) {\n throw new SdkError(\n \"invalid_tool_result\",\n `tool \"${tool}\" must return an object whose content is a list of text and image blocks`,\n );\n }\n return result as ToolResult;\n}\n\nasync function execute(tool: AnyTool, call: ToolCall, input: unknown, ctx: PipelineContext): Promise<ToolResult> {\n const context = {\n runId: ctx.runId,\n callId: call.callId,\n signal: ctx.signal,\n depth: ctx.depth,\n maxDepth: ctx.maxDepth,\n clock: ctx.clock,\n update: (details: unknown) => ctx.onUpdate?.(call.callId, details),\n };\n let result: unknown;\n try {\n result = await tool.execute(input, context);\n } catch (error) {\n ctx.onExecuted?.(call);\n const message = errorMessage(error);\n const redacted = tool.redactErrors === true;\n const failure: ToolFailure = {\n kind: \"execution_error\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n message: redacted ? REDACTED_MESSAGE : message,\n redacted,\n };\n return failed(failure, tool, { error: { name: error instanceof Error ? error.name : typeof error, message } });\n }\n ctx.onExecuted?.(call);\n return withOutcome(tool.name, checkResult(tool.name, result));\n}\n\n/**\n * Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure\n * the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws\n * an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.\n */\nexport async function runToolCall(\n call: ToolCall,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolResult> {\n const byName = toolsByName(tools);\n const tool = byName.get(call.name);\n if (tool === undefined) {\n const availableTools = [...byName.keys()];\n return failed(\n { kind: \"unknown_tool\", tool: call.name, callId: call.callId, input: call.input, availableTools },\n undefined,\n );\n }\n // Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.\n if (ctx.signal.aborted) return notRun(call, tool, \"run_aborted\");\n const checked = await checkInput(tool, call);\n if (!checked.ok) return checked.result;\n if (ctx.signal.aborted) return notRun(call, tool, \"run_aborted\");\n // Gate: every call is allowed until the beforeToolCall interceptor exists.\n const result = await execute(tool, call, checked.input, ctx);\n // afterToolCall: the result passes through unchanged until that interceptor exists.\n return result;\n}\n\ntype NotRunReason = Extract<ToolFailure, { kind: \"not_run\" }>[\"reason\"];\n\nfunction notRun(call: ToolCall, tool: AnyTool | undefined, reason: NotRunReason): ToolResult {\n return failed({ kind: \"not_run\", reason, tool: call.name, callId: call.callId, input: call.input }, tool);\n}\n\n// Why none of a message's calls may run, or undefined when they all may.\nfunction unrunnable(message: AssistantMessage, call: ToolCall, tools: readonly AnyTool[]): ToolResult | undefined {\n const tool = tools.find((candidate) => candidate.name === call.name);\n switch (message.stopReason) {\n case \"length\":\n return failed({ kind: \"truncated\", tool: call.name, callId: call.callId, input: call.input }, tool);\n case \"error\":\n return notRun(call, tool, \"response_error\");\n case \"aborted\":\n return notRun(call, tool, \"response_aborted\");\n default:\n return undefined;\n }\n}\n\n/**\n * Runs every tool call of an assistant message, one at a time and in model order, and passes each result to\n * `ctx.onResult` as it arrives. A message that stopped at the output limit (`stopReason: \"length\"`) runs nothing:\n * each of its calls gets an error asking the model to re-issue it, because its arguments may be cut short. A message\n * that ended in an error or was aborted also runs nothing, because its calls may be partial.\n */\nexport async function runToolCalls(\n message: AssistantMessage,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const calls = message.content.filter((block): block is ToolCall => block.type === \"tool_call\");\n toolsByName(tools);\n const results: ToolCallResult[] = [];\n for (const call of calls) {\n ctx.onStart?.(call);\n const entry = { call, result: unrunnable(message, call, tools) ?? (await runToolCall(call, tools, ctx)) };\n results.push(entry);\n ctx.onResult?.(entry);\n }\n return results;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/tools/pipeline.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAgB,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AA6CxD,SAAS,WAAW,CAAC,KAAyB;IAC5C,MAAM,MAAM,GAAG,IAAI,GAAG,EAAmB,CAAC;IAC1C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,gBAAgB,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,QAAQ,CAAC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C,CAAC;IACtE,OAAQ,KAAwB,CAAC,MAAM,CAAC;AAC1C,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,OAAyB,EACzB,KAAyB,EACzB,GAAoB;IAEpB,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAqB,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;IAC/F,OAAO,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AACjF,CAAC","sourcesContent":["/**\n * The tool pipeline: the fixed steps every tool call runs (agent-SDK guide §4). Resolve the name, coerce, validate,\n * an optional `repair`, the gate, `execute`, the write outcome, then `afterToolCall`. A failure the model caused\n * becomes an error result and never throws; only a programmer error, such as a malformed tool result, throws an\n * `SdkError`.\n *\n * The gate and `afterToolCall` steps hold their places in the order below, and the interceptors fill them in: until\n * then every call is allowed and every result passes through unchanged. A step's calls are checked and gated one at a\n * time, in model order, and then scheduled together (see `runCalls`).\n */\nimport type { AssistantMessage, ModelContent } from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport { coerceValue } from \"./coerce.js\";\nimport { preparedSchemaOf } from \"./define.js\";\nimport { formatToolError, REDACTED_MESSAGE } from \"./format-error.js\";\nimport { withOutcome } from \"./outcome.js\";\nimport { type Settled, schedule } from \"./scheduler.js\";\nimport type { ToolCall, ToolDefinition, ToolFailure, ToolResult } from \"./types.js\";\n\n/** A tool of any input and structured type, as the pipeline holds it. */\nexport type AnyTool = ToolDefinition<unknown, unknown>;\n\n/** What the pipeline needs from the run around it. */\nexport interface PipelineContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly depth: number;\n readonly maxDepth: number;\n readonly clock: Clock;\n /**\n * The gate: asked once for each call that passed validation, one call at a time in model order, and before any call\n * of the step executes. It returns a result to block the call, or `undefined` to let it run. Without a gate every\n * call is allowed.\n */\n gate?(e: {\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n }): Promise<ToolResult | undefined>;\n /** Called for each call of a message before its result is worked out, whether or not the call will run. */\n onStart?(call: ToolCall): void;\n /** Receives a tool's progress updates. */\n onUpdate?(callId: string, details: unknown): void;\n /**\n * Receives each call's result as soon as `runToolCalls` has it, so the run can record a write before a later call\n * in the same message throws.\n */\n onResult?(entry: ToolCallResult): void;\n /**\n * Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write\n * may have happened even when its result then throws an `SdkError`.\n */\n onExecuted?(call: ToolCall): void;\n}\n\n/** One tool call and the result the model will read for it. */\nexport interface ToolCallResult {\n readonly call: ToolCall;\n readonly result: ToolResult;\n}\n\nfunction toolsByName(tools: readonly AnyTool[]): ReadonlyMap<string, AnyTool> {\n const byName = new Map<string, AnyTool>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (byName.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n byName.set(tool.name, tool);\n }\n return byName;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isModelContent(block: unknown): block is ModelContent {\n if (typeof block !== \"object\" || block === null) return false;\n const { type, text, mediaType, data } = block as Record<string, unknown>;\n if (type === \"text\") return typeof text === \"string\";\n return type === \"image\" && typeof mediaType === \"string\" && typeof data === \"string\";\n}\n\nfunction isContentList(content: unknown): content is readonly ModelContent[] {\n return Array.isArray(content) && content.every(isModelContent);\n}\n\ntype Formatted = { readonly content: readonly ModelContent[]; readonly error?: string };\n\n// A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so\n// the default text is used instead, and the formatter's error is kept in `details`.\nfunction formatted(failure: ToolFailure, tool: AnyTool | undefined): Formatted {\n const fallback = formatToolError(failure);\n if (tool?.formatError === undefined) return { content: fallback };\n let content: unknown;\n try {\n content = tool.formatError(failure);\n } catch (error) {\n return { content: fallback, error: errorMessage(error) };\n }\n if (isContentList(content)) return { content };\n return { content: fallback, error: \"formatError did not return a list of text and image blocks\" };\n}\n\nfunction failed(failure: ToolFailure, tool: AnyTool | undefined, details: Record<string, unknown> = {}): ToolResult {\n const { content, error: formatterError } = formatted(failure, tool);\n return {\n content,\n isError: true,\n details: { failure, ...details, ...(formatterError === undefined ? {} : { formatterError }) },\n };\n}\n\ntype Checked = { readonly ok: true; readonly input: unknown } | { readonly ok: false; readonly result: ToolResult };\n\n// Coerce, validate, and on failure give `repair` one chance. The model sees the issues of its own arguments, and\n// `details` keeps what repair returned.\nasync function checkInput(tool: AnyTool, call: ToolCall): Promise<Checked> {\n const schema = preparedSchemaOf(tool);\n const coerced = coerceValue(call.input, schema.jsonSchema);\n const first = await schema.validate(coerced);\n if (first.ok) return { ok: true, input: first.value };\n const failure: ToolFailure = {\n kind: \"invalid_input\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n issues: first.issues,\n };\n if (tool.repair === undefined) return { ok: false, result: failed(failure, tool) };\n let repaired: unknown;\n try {\n repaired = await tool.repair({ input: coerced, issues: first.issues });\n } catch (error) {\n return { ok: false, result: failed(failure, tool, { repairError: errorMessage(error) }) };\n }\n if (repaired === undefined) return { ok: false, result: failed(failure, tool) };\n const second = await schema.validate(coerceValue(repaired, schema.jsonSchema));\n if (second.ok) return { ok: true, input: second.value };\n return { ok: false, result: failed(failure, tool, { repaired, repairedIssues: second.issues }) };\n}\n\nfunction checkResult(tool: string, result: unknown): ToolResult {\n const content = (result as { content?: unknown } | null)?.content;\n if (typeof result !== \"object\" || result === null || !isContentList(content)) {\n throw new SdkError(\n \"invalid_tool_result\",\n `tool \"${tool}\" must return an object whose content is a list of text and image blocks`,\n );\n }\n return result as ToolResult;\n}\n\nasync function execute(tool: AnyTool, call: ToolCall, input: unknown, ctx: PipelineContext): Promise<ToolResult> {\n const context = {\n runId: ctx.runId,\n callId: call.callId,\n signal: ctx.signal,\n depth: ctx.depth,\n maxDepth: ctx.maxDepth,\n clock: ctx.clock,\n update: (details: unknown) => ctx.onUpdate?.(call.callId, details),\n };\n let result: unknown;\n try {\n result = await tool.execute(input, context);\n } catch (error) {\n ctx.onExecuted?.(call);\n const message = errorMessage(error);\n const redacted = tool.redactErrors === true;\n const failure: ToolFailure = {\n kind: \"execution_error\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n message: redacted ? REDACTED_MESSAGE : message,\n redacted,\n };\n return failed(failure, tool, { error: { name: error instanceof Error ? error.name : typeof error, message } });\n }\n ctx.onExecuted?.(call);\n return withOutcome(tool.name, checkResult(tool.name, result));\n}\n\ntype NotRunReason = Extract<ToolFailure, { kind: \"not_run\" }>[\"reason\"];\n\nfunction notRun(call: ToolCall, tool: AnyTool | undefined, reason: NotRunReason): ToolResult {\n return failed({ kind: \"not_run\", reason, tool: call.name, callId: call.callId, input: call.input }, tool);\n}\n\n// Why none of a message's calls may run, or undefined when they all may.\nfunction unrunnable(message: AssistantMessage, call: ToolCall, tools: readonly AnyTool[]): ToolResult | undefined {\n const tool = tools.find((candidate) => candidate.name === call.name);\n switch (message.stopReason) {\n case \"length\":\n return failed({ kind: \"truncated\", tool: call.name, callId: call.callId, input: call.input }, tool);\n case \"error\":\n return notRun(call, tool, \"response_error\");\n case \"aborted\":\n return notRun(call, tool, \"response_aborted\");\n default:\n return undefined;\n }\n}\n\n/** A call that passed every check before execution and now waits to be scheduled. */\ninterface Ready {\n readonly kind: \"ready\";\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n readonly key: string | undefined;\n}\n\n/** A call whose result is already known: it failed a check, was gated or could not run. */\ninterface Done {\n readonly kind: \"done\";\n readonly call: ToolCall;\n readonly result: ToolResult;\n}\n\ntype Prepared = Ready | Done;\n\nfunction resourceKeyOf(tool: AnyTool, input: unknown): string | undefined {\n if (tool.resourceKey === undefined) return undefined;\n let key: unknown;\n try {\n key = tool.resourceKey(input);\n } catch (cause) {\n throw new SdkError(\"invalid_tool_definition\", `tool \"${tool.name}\": resourceKey threw: ${errorMessage(cause)}`, {\n cause,\n });\n }\n if (typeof key !== \"string\") {\n throw new SdkError(\"invalid_tool_definition\", `tool \"${tool.name}\": resourceKey must return a string`);\n }\n return key;\n}\n\n// Everything that happens before execution, for one call: name, cancellation, input checks, resource key, and the\n// gate. A call that fails any of them is `Done` with the result the model reads.\nasync function prepareCall(\n call: ToolCall,\n early: ToolResult | undefined,\n byName: ReadonlyMap<string, AnyTool>,\n ctx: PipelineContext,\n): Promise<Prepared> {\n if (early !== undefined) return { kind: \"done\", call, result: early };\n const tool = byName.get(call.name);\n if (tool === undefined) {\n const availableTools = [...byName.keys()];\n const failure: ToolFailure = {\n kind: \"unknown_tool\",\n tool: call.name,\n callId: call.callId,\n input: call.input,\n availableTools,\n };\n return { kind: \"done\", call, result: failed(failure, undefined) };\n }\n // Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.\n if (ctx.signal.aborted) return { kind: \"done\", call, result: notRun(call, tool, \"run_aborted\") };\n const checked = await checkInput(tool, call);\n if (!checked.ok) return { kind: \"done\", call, result: checked.result };\n if (ctx.signal.aborted) return { kind: \"done\", call, result: notRun(call, tool, \"run_aborted\") };\n const key = resourceKeyOf(tool, checked.input);\n // Each call's gate settles before the next call's is asked, and every gate before any call executes.\n const blocked = await ctx.gate?.({ call, tool, input: checked.input });\n if (blocked !== undefined) return { kind: \"done\", call, result: blocked };\n return { kind: \"ready\", call, tool, input: checked.input, key };\n}\n\n// Only a first-party tool's hint counts: an MCP server's annotations are claims by someone we don't control. A tool\n// with an `effect` changes the world whatever its hint says, so it always queues as a writer.\nfunction isTrustedReadOnly(tool: AnyTool): boolean {\n return tool.firstParty === true && tool.annotations?.readOnlyHint === true && tool.effect === undefined;\n}\n\n// Relays the run's cancellation to the signal the batch's tools receive, which a failing sibling can also fire.\nfunction batchController(runSignal: AbortSignal): { batch: AbortController; release(): void } {\n const batch = new AbortController();\n const relay = () => batch.abort(runSignal.reason);\n if (runSignal.aborted) relay();\n else runSignal.addEventListener(\"abort\", relay, { once: true });\n return { batch, release: () => runSignal.removeEventListener(\"abort\", relay) };\n}\n\n// Runs one ready call under the batch's signal. A programmer error cancels the siblings before it propagates; a\n// model-caused failure is an ordinary result and cancels nothing.\nasync function runReady(item: Ready, ctx: PipelineContext, batch: AbortController): Promise<ToolResult> {\n if (batch.signal.aborted) {\n return notRun(item.call, item.tool, ctx.signal.aborted ? \"run_aborted\" : \"sibling_failed\");\n }\n try {\n return await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });\n } catch (error) {\n batch.abort(error);\n throw error;\n }\n}\n\n// Starts every ready call by the scheduling rules and returns, in model order, the promise of each call's result.\nfunction start(\n prepared: readonly Prepared[],\n sequential: boolean,\n ctx: PipelineContext,\n batch: AbortController,\n): Promise<Settled<ToolResult>>[] {\n const ready = prepared.filter((item): item is Ready => item.kind === \"ready\");\n const scheduled = schedule(\n ready.map((item) => ({\n ...(item.key === undefined ? {} : { key: item.key }),\n readOnly: isTrustedReadOnly(item.tool),\n run: () => runReady(item, ctx, batch),\n })),\n sequential,\n );\n const byItem = new Map(ready.map((item, index) => [item, scheduled[index]]));\n return prepared.map(\n (item) =>\n (item.kind === \"done\" ? undefined : byItem.get(item)) ??\n Promise.resolve<Settled<ToolResult>>({ ok: true, value: (item as Done).result }),\n );\n}\n\n/**\n * Runs the calls of one step. Each call is checked and gated one at a time, in model order, before any call executes.\n * The calls that passed then start together, except that a call to a sequential tool makes the whole step run one\n * call at a time, even when that call itself fails a check, and calls that share a `resourceKey` queue in model\n * order. Results reach `ctx.onResult` in model order, each as soon as every result before it is in.\n *\n * A programmer error (an `SdkError`) in one call fires the signal the other calls hold, waits for them to stop, and\n * is then thrown, after every other call's result has been passed on: a call after the failing one may have run and\n * written. A programmer error while the calls are checked, such as a `resourceKey` that throws, is thrown after the\n * calls already checked get their results, so every call that started has one, except the call that failed.\n */\nasync function runCalls(\n calls: readonly ToolCall[],\n early: (call: ToolCall) => ToolResult | undefined,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const byName = toolsByName(tools);\n const prepared: Prepared[] = [];\n try {\n for (const call of calls) {\n ctx.onStart?.(call);\n prepared.push(await prepareCall(call, early(call), byName, ctx));\n }\n } catch (error) {\n // None of these calls has executed, and none will.\n for (const item of prepared) {\n const result = item.kind === \"done\" ? item.result : notRun(item.call, item.tool, \"sibling_failed\");\n ctx.onResult?.({ call: item.call, result });\n }\n throw error;\n }\n const sequential = calls.some((call) => byName.get(call.name)?.executionMode === \"sequential\");\n const { batch, release } = batchController(ctx.signal);\n try {\n return await deliver(prepared, start(prepared, sequential, ctx, batch), ctx);\n } finally {\n release();\n }\n}\n\n// Passes each result on in model order, as soon as every result before it is in. A failed call has already cancelled\n// the others; the loop still waits for each of them and passes its result on, so none is left running and a write\n// that happened is recorded, and then the first error is thrown.\nasync function deliver(\n prepared: readonly Prepared[],\n running: readonly Promise<Settled<ToolResult>>[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const results: ToolCallResult[] = [];\n let failure: { readonly error: unknown } | undefined;\n for (const [index, pending] of running.entries()) {\n const settled = await pending;\n if (!settled.ok) {\n failure ??= { error: settled.error };\n continue;\n }\n const entry = { call: (prepared[index] as Prepared).call, result: settled.value };\n results.push(entry);\n ctx.onResult?.(entry);\n }\n if (failure !== undefined) throw failure.error;\n return results;\n}\n\n/**\n * Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure\n * the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws\n * an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.\n */\nexport async function runToolCall(\n call: ToolCall,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolResult> {\n const { onStart: _start, onResult: _result, ...quiet } = ctx;\n const [entry] = await runCalls([call], () => undefined, tools, quiet);\n return (entry as ToolCallResult).result;\n}\n\n/**\n * Runs every tool call of an assistant message and passes each result to `ctx.onResult` in model order. A message\n * that stopped at the output limit (`stopReason: \"length\"`) runs nothing: each of its calls gets an error asking the\n * model to re-issue it, because its arguments may be cut short. A message that ended in an error or was aborted also\n * runs nothing, because its calls may be partial. Otherwise the calls are scheduled as `runCalls` describes.\n */\nexport async function runToolCalls(\n message: AssistantMessage,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const calls = message.content.filter((block): block is ToolCall => block.type === \"tool_call\");\n return runCalls(calls, (call) => unrunnable(message, call, tools), tools, ctx);\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The step scheduler: decides when each tool call of one step starts (agent-SDK guide §4). It knows nothing about
|
|
3
|
+
* tools, only about tasks that may share a resource, so the rules can be tested without a model.
|
|
4
|
+
*
|
|
5
|
+
* - By default every task starts at once, in model order.
|
|
6
|
+
* - In a sequential batch, each task starts only after the one before it has settled.
|
|
7
|
+
* - Tasks with the same `key` never overlap and start in model order. A read-only task shares its key with other
|
|
8
|
+
* read-only tasks (a readers-writer lock), and waits only for the writers before it.
|
|
9
|
+
*
|
|
10
|
+
* The queues are built while the tasks are handed in, in model order, so the order never depends on how fast a task
|
|
11
|
+
* runs. No timers are used: a task waits on the promises of the tasks ahead of it.
|
|
12
|
+
*/
|
|
13
|
+
/** One unit of work for the scheduler. */
|
|
14
|
+
export interface Task<T> {
|
|
15
|
+
/** Tasks with the same key never overlap. A task without one is not queued behind anything. */
|
|
16
|
+
readonly key?: string;
|
|
17
|
+
/** A read-only task may overlap other read-only tasks with its key; any other task waits for all before it. */
|
|
18
|
+
readonly readOnly: boolean;
|
|
19
|
+
run(): Promise<T>;
|
|
20
|
+
}
|
|
21
|
+
/** How a task ended: the scheduler catches each task's error so that no rejection goes unobserved. */
|
|
22
|
+
export type Settled<T> = {
|
|
23
|
+
readonly ok: true;
|
|
24
|
+
readonly value: T;
|
|
25
|
+
} | {
|
|
26
|
+
readonly ok: false;
|
|
27
|
+
readonly error: unknown;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Starts `tasks` by the rules above and returns one promise per task, in the same order. A task's own rejection
|
|
31
|
+
* becomes a `Settled` value, so the promises never reject. With `sequential`, keys are moot: one task runs at a time.
|
|
32
|
+
*/
|
|
33
|
+
export declare function schedule<T>(tasks: readonly Task<T>[], sequential: boolean): Promise<Settled<T>>[];
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The step scheduler: decides when each tool call of one step starts (agent-SDK guide §4). It knows nothing about
|
|
3
|
+
* tools, only about tasks that may share a resource, so the rules can be tested without a model.
|
|
4
|
+
*
|
|
5
|
+
* - By default every task starts at once, in model order.
|
|
6
|
+
* - In a sequential batch, each task starts only after the one before it has settled.
|
|
7
|
+
* - Tasks with the same `key` never overlap and start in model order. A read-only task shares its key with other
|
|
8
|
+
* read-only tasks (a readers-writer lock), and waits only for the writers before it.
|
|
9
|
+
*
|
|
10
|
+
* The queues are built while the tasks are handed in, in model order, so the order never depends on how fast a task
|
|
11
|
+
* runs. No timers are used: a task waits on the promises of the tasks ahead of it.
|
|
12
|
+
*/
|
|
13
|
+
async function settle(task) {
|
|
14
|
+
try {
|
|
15
|
+
return { ok: true, value: await task.run() };
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
return { ok: false, error };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function inLane(lanes, key, task) {
|
|
22
|
+
const lane = lanes.get(key) ?? { writer: Promise.resolve(), readers: [] };
|
|
23
|
+
lanes.set(key, lane);
|
|
24
|
+
const ahead = task.readOnly ? [lane.writer] : [lane.writer, ...lane.readers];
|
|
25
|
+
const settled = Promise.all(ahead).then(() => settle(task));
|
|
26
|
+
if (task.readOnly) {
|
|
27
|
+
lane.readers.push(settled);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
lane.writer = settled;
|
|
31
|
+
lane.readers = [];
|
|
32
|
+
}
|
|
33
|
+
return settled;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Starts `tasks` by the rules above and returns one promise per task, in the same order. A task's own rejection
|
|
37
|
+
* becomes a `Settled` value, so the promises never reject. With `sequential`, keys are moot: one task runs at a time.
|
|
38
|
+
*/
|
|
39
|
+
export function schedule(tasks, sequential) {
|
|
40
|
+
const lanes = new Map();
|
|
41
|
+
let previous = Promise.resolve();
|
|
42
|
+
return tasks.map((task) => {
|
|
43
|
+
if (sequential) {
|
|
44
|
+
const settled = previous.then(() => settle(task));
|
|
45
|
+
previous = settled;
|
|
46
|
+
return settled;
|
|
47
|
+
}
|
|
48
|
+
return task.key === undefined ? settle(task) : inLane(lanes, task.key, task);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=scheduler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduler.js","sourceRoot":"","sources":["../../src/tools/scheduler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAcH,KAAK,UAAU,MAAM,CAAI,IAAa;IACpC,IAAI,CAAC;QACH,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;IAC/C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACH,CAAC;AAQD,SAAS,MAAM,CAAI,KAAwB,EAAE,GAAW,EAAE,IAAa;IACrE,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IAC1E,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC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: decides when each tool call of one step starts (agent-SDK guide §4). It knows nothing about\n * tools, only about tasks that may share a resource, so the rules can be tested without a model.\n *\n * - By default every task starts at once, in model order.\n * - In a sequential batch, each task starts only after the one before it has settled.\n * - Tasks with the same `key` never overlap and start in model order. A read-only task shares its key with other\n * read-only tasks (a readers-writer lock), and waits only for the writers before it.\n *\n * The queues are built while the tasks are handed in, in model order, so the order never depends on how fast a task\n * runs. No timers are used: a task waits on the promises of the tasks ahead of it.\n */\n\n/** One unit of work for the scheduler. */\nexport interface Task<T> {\n /** Tasks with the same key never overlap. A task without one is not queued behind anything. */\n readonly key?: string;\n /** A read-only task may overlap other read-only tasks with its key; any other task waits for all before it. */\n readonly readOnly: boolean;\n run(): Promise<T>;\n}\n\n/** How a task ended: the scheduler catches each task's error so that no rejection goes unobserved. */\nexport type Settled<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: unknown };\n\nasync function settle<T>(task: Task<T>): Promise<Settled<T>> {\n try {\n return { ok: true, value: await task.run() };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n// The tasks that currently hold or wait for one key: the last writer, and the readers queued since it.\ninterface Lane {\n writer: Promise<unknown>;\n readers: Promise<unknown>[];\n}\n\nfunction inLane<T>(lanes: Map<string, Lane>, key: string, task: Task<T>): Promise<Settled<T>> {\n const lane = lanes.get(key) ?? { writer: Promise.resolve(), readers: [] };\n lanes.set(key, lane);\n const ahead = task.readOnly ? [lane.writer] : [lane.writer, ...lane.readers];\n const settled = Promise.all(ahead).then(() => settle(task));\n if (task.readOnly) {\n lane.readers.push(settled);\n } else {\n lane.writer = settled;\n lane.readers = [];\n }\n return settled;\n}\n\n/**\n * Starts `tasks` by the rules above and returns one promise per task, in the same order. A task's own rejection\n * becomes a `Settled` value, so the promises never reject. With `sequential`, keys are moot: one task runs at a time.\n */\nexport function schedule<T>(tasks: readonly Task<T>[], sequential: boolean): Promise<Settled<T>>[] {\n const lanes = new Map<string, Lane>();\n let previous: Promise<unknown> = Promise.resolve();\n return tasks.map((task) => {\n if (sequential) {\n const settled = previous.then(() => settle(task));\n previous = settled;\n return settled;\n }\n return task.key === undefined ? settle(task) : inLane(lanes, task.key, task);\n });\n}\n"]}
|
package/dist/tools/types.d.ts
CHANGED
|
@@ -36,7 +36,7 @@ interface FailureBase {
|
|
|
36
36
|
* `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:
|
|
37
37
|
* the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the
|
|
38
38
|
* response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before
|
|
39
|
-
* the call started (`run_aborted`).
|
|
39
|
+
* the call started (`run_aborted`), or a sibling call in the same step threw a programmer error (`sibling_failed`).
|
|
40
40
|
*/
|
|
41
41
|
export type ToolFailure = (FailureBase & {
|
|
42
42
|
readonly kind: "unknown_tool";
|
|
@@ -52,7 +52,7 @@ export type ToolFailure = (FailureBase & {
|
|
|
52
52
|
readonly kind: "truncated";
|
|
53
53
|
}) | (FailureBase & {
|
|
54
54
|
readonly kind: "not_run";
|
|
55
|
-
readonly reason: "response_error" | "response_aborted" | "run_aborted";
|
|
55
|
+
readonly reason: "response_error" | "response_aborted" | "run_aborted" | "sibling_failed";
|
|
56
56
|
});
|
|
57
57
|
/**
|
|
58
58
|
* Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so
|
|
@@ -63,13 +63,29 @@ export interface ToolEffect<I> {
|
|
|
63
63
|
readonly kind: "write";
|
|
64
64
|
businessKey?(input: I): string;
|
|
65
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* What a tool says about itself, using the names of the Model Context Protocol's tool annotations. A hint comes from
|
|
68
|
+
* whoever wrote the tool, so the scheduler trusts it only for a tool marked `firstParty`.
|
|
69
|
+
*/
|
|
70
|
+
export interface ToolAnnotations {
|
|
71
|
+
/**
|
|
72
|
+
* The tool changes nothing. With `firstParty`, its calls that share a `resourceKey` run together, unless the tool
|
|
73
|
+
* also declares an `effect`, which wins.
|
|
74
|
+
*/
|
|
75
|
+
readonly readOnlyHint?: boolean;
|
|
76
|
+
}
|
|
77
|
+
/** How a tool's calls are scheduled within one step: `parallel` (the default) or `sequential`. */
|
|
78
|
+
export type ToolExecutionMode = "parallel" | "sequential";
|
|
66
79
|
/** Whether a tool is sent to the model: `direct`, `deferred` or `hidden`. */
|
|
67
80
|
export type ToolExposure = "direct" | "deferred" | "hidden";
|
|
68
81
|
/** What a tool's `execute` receives besides its input. */
|
|
69
82
|
export interface ToolContext {
|
|
70
83
|
readonly runId: string;
|
|
71
84
|
readonly callId: string;
|
|
72
|
-
/**
|
|
85
|
+
/**
|
|
86
|
+
* Fires when the run is aborted, and when a sibling call in the same step throws a programmer error, because the
|
|
87
|
+
* step is then abandoned. A sibling's error result, which the model reads and answers, never fires it.
|
|
88
|
+
*/
|
|
73
89
|
readonly signal: AbortSignal;
|
|
74
90
|
/** How deeply this run is nested inside other agents' tool calls; 0 for a top-level run. */
|
|
75
91
|
readonly depth: number;
|
|
@@ -124,6 +140,26 @@ export interface ToolDefinition<I = unknown, S = unknown> {
|
|
|
124
140
|
readonly exposure?: ToolExposure;
|
|
125
141
|
/** Marks a tool that changes the world. A tool without it counts as read-only. */
|
|
126
142
|
readonly effect?: ToolEffect<I>;
|
|
143
|
+
/**
|
|
144
|
+
* How this tool's calls are scheduled. A step's calls start together by default. A tool that sets `sequential`
|
|
145
|
+
* makes every call of its step run one at a time, in the order the model sent them, because it may depend on the
|
|
146
|
+
* calls around it.
|
|
147
|
+
*/
|
|
148
|
+
readonly executionMode?: ToolExecutionMode;
|
|
149
|
+
/**
|
|
150
|
+
* Names the resource a call touches, such as a file path. Calls in one step that return the same key never run at
|
|
151
|
+
* the same time, in any tool, and run in model order; calls with different keys run together. It must be
|
|
152
|
+
* deterministic and return a string, and it receives the validated input.
|
|
153
|
+
*/
|
|
154
|
+
resourceKey?(input: I): string;
|
|
155
|
+
/** Hints about the tool, such as `readOnlyHint`. They affect scheduling only when `firstParty` is true. */
|
|
156
|
+
readonly annotations?: ToolAnnotations;
|
|
157
|
+
/**
|
|
158
|
+
* True for a tool you wrote, false (the default) for one that came from a server you don't control, such as an MCP
|
|
159
|
+
* tool. Only a first-party tool's `readOnlyHint` changes how its calls are scheduled: read-only calls that share a
|
|
160
|
+
* `resourceKey` run together, and wait only for the writers before them. A tool with an `effect` is never read-only.
|
|
161
|
+
*/
|
|
162
|
+
readonly firstParty?: boolean;
|
|
127
163
|
/**
|
|
128
164
|
* Called once when the input fails its schema, with the coerced input and the issues. Return fixed input to
|
|
129
165
|
* validate again, or `undefined` to report the failure to the model.
|
package/dist/tools/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/tools/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The tool types: what a tool declares, what its `execute` receives and returns, and the failures the pipeline\n * reports to the model (SDK plan §3.3; agent-SDK guide §4).\n */\nimport type { ContentBlock, ModelContent } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport type { WriteOutcome } from \"../vendor/agent-safety/outcome.js\";\n\n/** A JSON Schema object, draft 2020-12 or draft 7, such as `{ type: \"object\", properties: { … } }`. */\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\n/**\n * A tool's input schema: a Standard Schema that can also describe itself as JSON Schema (Zod 4.2 or later, ArkType,\n * or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`), or a raw JSON Schema object. A raw schema whose `$schema` names draft 7 is checked as draft 7, and\n * any other as draft 2020-12.\n */\nexport type ToolSchema<I> = (StandardSchemaV1<unknown, I> & StandardJSONSchemaV1<unknown, I>) | JsonSchema;\n\n/**\n * One reason a tool input failed its schema. `path` is a JSON Pointer, such as `/items/0/sku`, or `\"\"` for the whole\n * input.\n */\nexport interface SchemaIssue {\n readonly path: string;\n readonly message: string;\n /** The JSON Schema keyword that failed, such as `required`, when the validator reports one. */\n readonly keyword?: string;\n}\n\n/** The fields every tool failure carries. `input` is the arguments the model sent. */\ninterface FailureBase {\n readonly tool: string;\n readonly callId: string;\n readonly input: unknown;\n}\n\n/**\n * A failed tool call, as the error formatter receives it. `unknown_tool`: the model named a tool that doesn't exist.\n * `invalid_input`: the arguments failed the schema, even after repair. `execution_error`: `execute` threw; with\n * `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:\n * the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the\n * response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before\n * the call started (`run_aborted`).\n */\nexport type ToolFailure =\n | (FailureBase & { readonly kind: \"unknown_tool\"; readonly availableTools: readonly string[] })\n | (FailureBase & { readonly kind: \"invalid_input\"; readonly issues: readonly SchemaIssue[] })\n | (FailureBase & { readonly kind: \"execution_error\"; readonly message: string; readonly redacted: boolean })\n | (FailureBase & { readonly kind: \"truncated\" })\n | (FailureBase & {\n readonly kind: \"not_run\";\n readonly reason: \"response_error\" | \"response_aborted\" | \"run_aborted\";\n });\n\n/**\n * Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so\n * a run that crashes mid-call may safely run it again. `businessKey` names the real-world operation, such as\n * `refund:<order id>`, so the same write is recognised across retries and sessions.\n */\nexport interface ToolEffect<I> {\n readonly kind: \"write\";\n businessKey?(input: I): string;\n}\n\n/** Whether a tool is sent to the model: `direct`, `deferred` or `hidden`. */\nexport type ToolExposure = \"direct\" | \"deferred\" | \"hidden\";\n\n/** What a tool's `execute` receives besides its input. */\nexport interface ToolContext {\n readonly runId: string;\n readonly callId: string;\n
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/tools/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The tool types: what a tool declares, what its `execute` receives and returns, and the failures the pipeline\n * reports to the model (SDK plan §3.3; agent-SDK guide §4).\n */\nimport type { ContentBlock, ModelContent } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport type { WriteOutcome } from \"../vendor/agent-safety/outcome.js\";\n\n/** A JSON Schema object, draft 2020-12 or draft 7, such as `{ type: \"object\", properties: { … } }`. */\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\n/**\n * A tool's input schema: a Standard Schema that can also describe itself as JSON Schema (Zod 4.2 or later, ArkType,\n * or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`), or a raw JSON Schema object. A raw schema whose `$schema` names draft 7 is checked as draft 7, and\n * any other as draft 2020-12.\n */\nexport type ToolSchema<I> = (StandardSchemaV1<unknown, I> & StandardJSONSchemaV1<unknown, I>) | JsonSchema;\n\n/**\n * One reason a tool input failed its schema. `path` is a JSON Pointer, such as `/items/0/sku`, or `\"\"` for the whole\n * input.\n */\nexport interface SchemaIssue {\n readonly path: string;\n readonly message: string;\n /** The JSON Schema keyword that failed, such as `required`, when the validator reports one. */\n readonly keyword?: string;\n}\n\n/** The fields every tool failure carries. `input` is the arguments the model sent. */\ninterface FailureBase {\n readonly tool: string;\n readonly callId: string;\n readonly input: unknown;\n}\n\n/**\n * A failed tool call, as the error formatter receives it. `unknown_tool`: the model named a tool that doesn't exist.\n * `invalid_input`: the arguments failed the schema, even after repair. `execution_error`: `execute` threw; with\n * `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:\n * the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the\n * response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before\n * the call started (`run_aborted`), or a sibling call in the same step threw a programmer error (`sibling_failed`).\n */\nexport type ToolFailure =\n | (FailureBase & { readonly kind: \"unknown_tool\"; readonly availableTools: readonly string[] })\n | (FailureBase & { readonly kind: \"invalid_input\"; readonly issues: readonly SchemaIssue[] })\n | (FailureBase & { readonly kind: \"execution_error\"; readonly message: string; readonly redacted: boolean })\n | (FailureBase & { readonly kind: \"truncated\" })\n | (FailureBase & {\n readonly kind: \"not_run\";\n readonly reason: \"response_error\" | \"response_aborted\" | \"run_aborted\" | \"sibling_failed\";\n });\n\n/**\n * Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so\n * a run that crashes mid-call may safely run it again. `businessKey` names the real-world operation, such as\n * `refund:<order id>`, so the same write is recognised across retries and sessions.\n */\nexport interface ToolEffect<I> {\n readonly kind: \"write\";\n businessKey?(input: I): string;\n}\n\n/**\n * What a tool says about itself, using the names of the Model Context Protocol's tool annotations. A hint comes from\n * whoever wrote the tool, so the scheduler trusts it only for a tool marked `firstParty`.\n */\nexport interface ToolAnnotations {\n /**\n * The tool changes nothing. With `firstParty`, its calls that share a `resourceKey` run together, unless the tool\n * also declares an `effect`, which wins.\n */\n readonly readOnlyHint?: boolean;\n}\n\n/** How a tool's calls are scheduled within one step: `parallel` (the default) or `sequential`. */\nexport type ToolExecutionMode = \"parallel\" | \"sequential\";\n\n/** Whether a tool is sent to the model: `direct`, `deferred` or `hidden`. */\nexport type ToolExposure = \"direct\" | \"deferred\" | \"hidden\";\n\n/** What a tool's `execute` receives besides its input. */\nexport interface ToolContext {\n readonly runId: string;\n readonly callId: string;\n /**\n * Fires when the run is aborted, and when a sibling call in the same step throws a programmer error, because the\n * step is then abandoned. A sibling's error result, which the model reads and answers, never fires it.\n */\n readonly signal: AbortSignal;\n /** How deeply this run is nested inside other agents' tool calls; 0 for a top-level run. */\n readonly depth: number;\n /** The deepest nesting allowed; a tool that starts another agent refuses at this depth. */\n readonly maxDepth: number;\n readonly clock: Clock;\n /** Reports progress for a user interface, such as rows processed so far. The model never sees it. */\n update(details: unknown): void;\n}\n\n/**\n * What a tool returns. `content` is what the model reads, `details` is for logs and user interfaces, and\n * `structured` is typed data for your code; only `content` reaches the model. `isError` marks a failure for the model.\n * `terminate` asks the run to end after this step. `pause` asks the user a question. `outcome` reports what a write\n * did: any kind except `applied` sets `isError`, and the model reads the outcome's sentence and fields before\n * `content`.\n */\nexport interface ToolResult<S = unknown> {\n readonly content: readonly ModelContent[];\n readonly details?: unknown;\n readonly structured?: S;\n readonly isError?: boolean;\n readonly terminate?: boolean;\n readonly pause?: { readonly kind: \"clarification\"; readonly question: string };\n readonly outcome?: WriteOutcome;\n}\n\n/**\n * A tool the model can call. `I` is the input `execute` receives after validation, and `S` the type of `structured`.\n *\n * Every call runs the same steps: the name is resolved, the input is coerced and validated, `repair` gets one chance\n * to fix invalid input, then `execute` runs. A failure the model caused, such as an unknown tool, invalid input or\n * a throwing `execute`, returns an error result to the model. A result that isn't a list of text and image blocks,\n * or that carries an invalid write outcome, throws an `SdkError` with code `invalid_tool_result`.\n */\nexport interface ToolDefinition<I = unknown, S = unknown> {\n /** 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. */\n readonly name: string;\n readonly description: string;\n /**\n * `function` (the default) runs in your process. The other kinds are for tools that a provider defines or runs:\n * `dynamic` tools have a schema known only at run time, such as one from an MCP server.\n */\n readonly kind?: \"function\" | \"dynamic\" | \"provider-local\" | \"provider-executed\";\n readonly inputSchema: ToolSchema<I>;\n /**\n * Whether the model is sent this tool. `direct` (the default) sends it with every model call. A `deferred` or\n * `hidden` tool is left out of every request, and a call the model makes to it anyway gets the unknown-tool error\n * result.\n */\n readonly exposure?: ToolExposure;\n /** Marks a tool that changes the world. A tool without it counts as read-only. */\n readonly effect?: ToolEffect<I>;\n /**\n * How this tool's calls are scheduled. A step's calls start together by default. A tool that sets `sequential`\n * makes every call of its step run one at a time, in the order the model sent them, because it may depend on the\n * calls around it.\n */\n readonly executionMode?: ToolExecutionMode;\n /**\n * Names the resource a call touches, such as a file path. Calls in one step that return the same key never run at\n * the same time, in any tool, and run in model order; calls with different keys run together. It must be\n * deterministic and return a string, and it receives the validated input.\n */\n resourceKey?(input: I): string;\n /** Hints about the tool, such as `readOnlyHint`. They affect scheduling only when `firstParty` is true. */\n readonly annotations?: ToolAnnotations;\n /**\n * True for a tool you wrote, false (the default) for one that came from a server you don't control, such as an MCP\n * tool. Only a first-party tool's `readOnlyHint` changes how its calls are scheduled: read-only calls that share a\n * `resourceKey` run together, and wait only for the writers before them. A tool with an `effect` is never read-only.\n */\n readonly firstParty?: boolean;\n /**\n * Called once when the input fails its schema, with the coerced input and the issues. Return fixed input to\n * validate again, or `undefined` to report the failure to the model.\n */\n repair?(e: { readonly input: unknown; readonly issues: readonly SchemaIssue[] }): Promise<unknown>;\n /**\n * Builds the content the model reads for a failed call, in place of the default text, which lists the issues and\n * the received arguments and tells the model not to substitute invented data. It runs synchronously; if it throws\n * or returns anything but a list of text and image blocks, the model reads the default text instead.\n */\n formatError?(failure: ToolFailure): readonly ModelContent[];\n /**\n * When true, an error thrown by `execute` reaches the model as a fixed line, and its message goes only to the\n * result's `details`. Default false.\n */\n readonly redactErrors?: boolean;\n execute(input: I, ctx: ToolContext): Promise<ToolResult<S>>;\n}\n\n/** A tool call block from an assistant message. */\nexport type ToolCall = Extract<ContentBlock, { type: \"tool_call\" }>;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buildanagent/sdk",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.4",
|
|
4
4
|
"description": "The buildanagent SDK: the agent loop, tools, hooks, signed pauses and budgets over the gateway.",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@earendil-works/pi-schema": "1.5.2",
|
|
39
39
|
"@standard-schema/spec": "1.1.0",
|
|
40
|
-
"@buildanagent/gateway": "0.1.0-alpha.
|
|
40
|
+
"@buildanagent/gateway": "0.1.0-alpha.4"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@cfworker/json-schema": "4.1.6",
|