@buildanagent/sdk 0.1.0-alpha.2 → 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 +90 -8
- package/dist/errors.d.ts +27 -6
- package/dist/errors.js +30 -8
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +104 -0
- package/dist/events.js +27 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +8 -4
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +38 -0
- package/dist/loop.js +232 -0
- package/dist/loop.js.map +1 -0
- package/dist/result.d.ts +77 -0
- package/dist/result.js +2 -0
- package/dist/result.js.map +1 -0
- package/dist/run.d.ts +78 -0
- package/dist/run.js +165 -0
- package/dist/run.js.map +1 -0
- package/dist/testing/scripted-model.d.ts +12 -2
- package/dist/testing/scripted-model.js +19 -2
- package/dist/testing/scripted-model.js.map +1 -1
- package/dist/tools/define.d.ts +14 -4
- package/dist/tools/define.js +24 -4
- 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 +18 -5
- package/dist/tools/pipeline.js +160 -34
- 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 +47 -3
- package/dist/tools/types.js.map +1 -1
- package/dist/version.d.ts +2 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +2 -2
package/dist/run.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAExD,OAAO,EAAkB,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpD,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,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * `run()`, `continueRun()` and `runOrThrow()`, and the `Run` object they share (SDK plan §3.3; D10). A run streams\n * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the\n * non-streaming caller drive one loop.\n */\nimport type { ContentBlock, Message, Model, ModelCallOptions } from \"@buildanagent/gateway\";\nimport { RunStoppedError, SdkError } from \"./errors.js\";\nimport type { AgentEvent, AgentEventBody } from \"./events.js\";\nimport { type LoopSetup, runLoop } from \"./loop.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolDefinition } from \"./tools/types.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\n/** The step cap's default, counted in model calls. */\nconst DEFAULT_MAX_STEPS = 20;\n\nconst systemClock: Clock = { now: () => new Date().toISOString() };\nconst randomIds = (): string => globalThis.crypto.randomUUID();\n\n/** The options `run()` and `continueRun()` share. */\nexport interface RunOptions<S = unknown> {\n /** The model, from `createModel()`. */\n readonly model: Model;\n /** The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent. */\n readonly tools?: readonly ToolDefinition<unknown, unknown>[];\n /**\n * A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls\n * it with input that passes its schema, the run ends `done`, and `result.output` holds the validated answer.\n */\n readonly output?: ToolDefinition<S, S>;\n /**\n * The most model calls the run may make. Default 20. A run that reaches it while the model still wants to go on\n * ends with `stopReason: \"max_steps\"` and emits a `warning` event with `code: \"max_steps\"`.\n */\n readonly maxSteps?: number;\n /** Aborts the run, like `run.abort()`. */\n readonly signal?: AbortSignal;\n /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */\n readonly modelOptions?: Omit<ModelCallOptions, \"signal\">;\n /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */\n readonly clock?: Clock;\n /** Makes the run's id. Defaults to `crypto.randomUUID()`. */\n readonly idGenerator?: () => string;\n}\n\n/** What `run()` takes besides the shared options. */\nexport interface RunInput {\n /** The system prompt. */\n readonly system: string;\n /** The user's message that starts the run. */\n readonly input: string | readonly ContentBlock[];\n /** Earlier messages to send before `input`, such as a previous conversation. */\n readonly history?: readonly Message[];\n}\n\n/**\n * A run in progress. Iterate it to stream its events: each iteration starts from the run's first event, so you can\n * start iterating at any time. Await `result` for the outcome; it rejects only for a programmer error, such as a\n * tool that returns a malformed result, and iteration then throws the same error after the last event.\n */\nexport interface Run<S = unknown> extends AsyncIterable<AgentEvent> {\n /** The run's id, which every event carries. */\n readonly id: string;\n /** The outcome, once the run has stopped. */\n readonly result: Promise<RunResult<S>>;\n /**\n * Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started\n * get an error result instead. The run then ends with `stopReason: \"aborted\"`. Does nothing once the run has ended.\n */\n abort(reason?: string): void;\n}\n\nfunction reasonOf(reason: unknown): string | undefined {\n if (typeof reason === \"string\") return reason;\n return reason instanceof Error ? reason.message : undefined;\n}\n\nclass RunHandle<S> implements Run<S> {\n readonly id: string;\n readonly result: Promise<RunResult<S>>;\n readonly #events: AgentEvent[] = [];\n readonly #controller = new AbortController();\n readonly #clock: Clock;\n #waiters: (() => void)[] = [];\n #ended = false;\n #failure: { readonly error: unknown } | undefined;\n #stepIndex = 0;\n\n constructor(setup: Omit<LoopSetup, \"signal\">, signal: AbortSignal | undefined) {\n this.id = setup.runId;\n this.#clock = setup.clock;\n const emit = (body: AgentEventBody, stepIndex: number) => this.#push(body, stepIndex);\n const { model } = setup;\n const versions = { sdkVersion: SDK_VERSION, specVersion: \"v1\" as const, defaultsHash: \"\", capabilities: [] };\n emit({ type: \"run_start\", ...versions, model: model.ref }, 0);\n const forwardAbort = () => this.abort(reasonOf(signal?.reason));\n if (signal?.aborted) forwardAbort();\n else signal?.addEventListener(\"abort\", forwardAbort, { once: true });\n const loop = runLoop({ ...setup, signal: this.#controller.signal }, emit);\n // The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.\n this.result = loop as Promise<RunResult<S>>;\n // Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration\n // throws the same error.\n loop.then(\n () => this.#end(signal, forwardAbort, undefined),\n (error: unknown) => this.#end(signal, forwardAbort, { error }),\n );\n }\n\n abort(reason?: string): void {\n if (this.#ended || this.#controller.signal.aborted) return;\n this.#push(reason === undefined ? { type: \"abort\" } : { type: \"abort\", reason }, this.#stepIndex);\n this.#controller.abort(reason);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {\n let cursor = 0;\n return {\n next: async () => {\n while (cursor >= this.#events.length && !this.#ended) {\n await new Promise<void>((resolve) => this.#waiters.push(resolve));\n }\n const event = this.#events[cursor];\n if (event !== undefined) {\n cursor += 1;\n return { value: event, done: false };\n }\n if (this.#failure !== undefined) throw this.#failure.error;\n return { value: undefined, done: true };\n },\n };\n }\n\n #push(body: AgentEventBody, stepIndex: number): void {\n this.#stepIndex = stepIndex;\n const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };\n this.#events.push({ ...base, ...body });\n this.#wake();\n }\n\n #end(signal: AbortSignal | undefined, forwardAbort: () => void, failure: { readonly error: unknown } | undefined) {\n signal?.removeEventListener(\"abort\", forwardAbort);\n this.#failure = failure;\n this.#ended = true;\n this.#wake();\n }\n\n #wake(): void {\n const waiters = this.#waiters;\n this.#waiters = [];\n for (const wake of waiters) wake();\n }\n}\n\nfunction isModel(model: unknown): model is Model {\n const candidate = model as Partial<Model> | null;\n return (\n typeof candidate === \"object\" &&\n candidate !== null &&\n typeof candidate.stream === \"function\" &&\n typeof candidate.price === \"function\" &&\n typeof candidate.ref === \"object\"\n );\n}\n\n/** Every tool the run may send, the output tool last unless `tools` already holds it, after checking each one. */\nfunction toolsOf(options: RunOptions<unknown>): AnyTool[] {\n const tools = [...(options.tools ?? [])] as AnyTool[];\n const output = options.output as AnyTool | undefined;\n if (output !== undefined && !tools.includes(output)) tools.push(output);\n const names = new Set<string>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (names.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction setupOf(options: RunOptions<unknown>, context: Context, input: readonly Message[]): Omit<LoopSetup, \"signal\"> {\n if (!isModel(options.model)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"the model must come from createModel(), such as createModel({ adapter, id })\",\n );\n }\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n if (!Number.isInteger(maxSteps) || maxSteps < 1) {\n throw new SdkError(\"invalid_run_options\", `maxSteps must be a positive integer, got ${maxSteps}`);\n }\n const tools = toolsOf(options);\n if (options.output !== undefined && (options.output.exposure ?? \"direct\") !== \"direct\") {\n throw new SdkError(\n \"invalid_run_options\",\n `the output tool \"${options.output.name}\" must be sent to the model, so its exposure must be \"direct\"`,\n );\n }\n return {\n runId: (options.idGenerator ?? randomIds)(),\n model: options.model,\n system: context.system,\n history: context.messages,\n input,\n tools: tools.filter((tool) => (tool.exposure ?? \"direct\") === \"direct\"),\n output: options.output as AnyTool | undefined,\n maxSteps,\n modelOptions: options.modelOptions ?? {},\n clock: options.clock ?? systemClock,\n };\n}\n\n/**\n * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool\n * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an\n * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool\n * that isn't sent to the model, or two tools with one name.\n */\nexport function run<S = unknown>(options: RunOptions<S> & RunInput): Run<S> {\n const content = typeof options.input === \"string\" ? [{ type: \"text\" as const, text: options.input }] : options.input;\n const input: Message = { role: \"user\", content: [...content] };\n const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);\n return new RunHandle<S>(setup, options.signal);\n}\n\n/**\n * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like\n * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context\n * is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.\n */\nexport function continueRun<S = unknown>(context: Context, options: RunOptions<S>): Run<S> {\n return new RunHandle<S>(setupOf(options, context, []), options.signal);\n}\n\n/**\n * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that\n * carries the result and the context to continue from.\n */\nexport async function runOrThrow<S>(started: Run<S>): Promise<DoneResult<S>> {\n const result = await started.result;\n if (result.stopReason === \"done\") return result;\n throw new RunStoppedError(result);\n}\n"]}
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* It implements the gateway's `ModelAdapter` and imports nothing from the loop, so gateway tests can use it too.
|
|
13
13
|
*/
|
|
14
14
|
import { type AssistantMessage, type ContentBlock, type ModelAdapter, type ModelCaps, type ModelContext, type ModelEvent, type ModelRef, type StreamOptions, type Usage } from "@buildanagent/gateway";
|
|
15
|
+
import { SdkError } from "../errors.js";
|
|
15
16
|
/** One scripted model response. */
|
|
16
17
|
export interface AssistantScript {
|
|
17
18
|
content: ContentBlock[];
|
|
@@ -44,8 +45,13 @@ export interface ScriptedModelOptions {
|
|
|
44
45
|
/** The caps `createModel()` gives this model. Default: 200,000-token window, 32,000 output tokens, images, reasoning. */
|
|
45
46
|
caps?: ModelCaps;
|
|
46
47
|
}
|
|
47
|
-
|
|
48
|
+
/**
|
|
49
|
+
* Thrown when a `ScriptedModel` is called after its last scripted step. It is an `SdkError` with code
|
|
50
|
+
* `unexpected_model_call`, so `isSdkError()` recognises it too.
|
|
51
|
+
*/
|
|
52
|
+
export declare class UnexpectedModelCallError extends SdkError {
|
|
48
53
|
readonly name = "UnexpectedModelCallError";
|
|
54
|
+
constructor(message: string);
|
|
49
55
|
}
|
|
50
56
|
export declare class ScriptedModel implements ModelAdapter {
|
|
51
57
|
#private;
|
|
@@ -56,7 +62,11 @@ export declare class ScriptedModel implements ModelAdapter {
|
|
|
56
62
|
constructor(steps: ScriptStep[], options?: ScriptedModelOptions);
|
|
57
63
|
/** Every call so far, as frozen, detached snapshots. */
|
|
58
64
|
get calls(): readonly RecordedRequest[];
|
|
59
|
-
/**
|
|
65
|
+
/**
|
|
66
|
+
* Throws if any scripted step was never used, or if the model was called after its last step. Call it in test
|
|
67
|
+
* teardown: `createModel()` turns an over-run's `UnexpectedModelCallError` into a failed call, so a run reports it
|
|
68
|
+
* as an `error` result, and only this check makes the test fail.
|
|
69
|
+
*/
|
|
60
70
|
assertComplete(): void;
|
|
61
71
|
stream(model: ModelRef, context: ModelContext, options: StreamOptions): AsyncIterable<ModelEvent>;
|
|
62
72
|
}
|
|
@@ -12,9 +12,17 @@
|
|
|
12
12
|
* It implements the gateway's `ModelAdapter` and imports nothing from the loop, so gateway tests can use it too.
|
|
13
13
|
*/
|
|
14
14
|
import { emptyUsage, unreportedUsage, } from "@buildanagent/gateway";
|
|
15
|
+
import { SdkError } from "../errors.js";
|
|
15
16
|
const DEFAULT_CAPS = { contextWindow: 200_000, maxOutputTokens: 32_000, images: true, reasoning: true };
|
|
16
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Thrown when a `ScriptedModel` is called after its last scripted step. It is an `SdkError` with code
|
|
19
|
+
* `unexpected_model_call`, so `isSdkError()` recognises it too.
|
|
20
|
+
*/
|
|
21
|
+
export class UnexpectedModelCallError extends SdkError {
|
|
17
22
|
name = "UnexpectedModelCallError";
|
|
23
|
+
constructor(message) {
|
|
24
|
+
super("unexpected_model_call", message);
|
|
25
|
+
}
|
|
18
26
|
}
|
|
19
27
|
function deepFreeze(value) {
|
|
20
28
|
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
@@ -73,6 +81,7 @@ export class ScriptedModel {
|
|
|
73
81
|
#chunkSize;
|
|
74
82
|
#nextId;
|
|
75
83
|
#used = 0;
|
|
84
|
+
#overRuns = 0;
|
|
76
85
|
constructor(steps, options = {}) {
|
|
77
86
|
const chunkSize = options.chunkSize ?? 4;
|
|
78
87
|
if (!Number.isInteger(chunkSize) || chunkSize < 1)
|
|
@@ -89,8 +98,15 @@ export class ScriptedModel {
|
|
|
89
98
|
get calls() {
|
|
90
99
|
return this.#calls;
|
|
91
100
|
}
|
|
92
|
-
/**
|
|
101
|
+
/**
|
|
102
|
+
* Throws if any scripted step was never used, or if the model was called after its last step. Call it in test
|
|
103
|
+
* teardown: `createModel()` turns an over-run's `UnexpectedModelCallError` into a failed call, so a run reports it
|
|
104
|
+
* as an `error` result, and only this check makes the test fail.
|
|
105
|
+
*/
|
|
93
106
|
assertComplete() {
|
|
107
|
+
if (this.#overRuns > 0) {
|
|
108
|
+
throw new UnexpectedModelCallError(`ScriptedModel: called ${this.#overRuns} more time(s) than its ${this.#steps.length} scripted steps allow`);
|
|
109
|
+
}
|
|
94
110
|
const remaining = this.#steps.length - this.#used;
|
|
95
111
|
if (remaining > 0) {
|
|
96
112
|
throw new Error(`ScriptedModel: ${remaining} of ${this.#steps.length} scripted steps were never called`);
|
|
@@ -108,6 +124,7 @@ export class ScriptedModel {
|
|
|
108
124
|
}
|
|
109
125
|
// The error surfaces when the caller reads the stream, like any other stream failure, not when it calls stream().
|
|
110
126
|
#overRun(callNumber) {
|
|
127
|
+
this.#overRuns += 1;
|
|
111
128
|
const error = new UnexpectedModelCallError(`ScriptedModel: call ${callNumber} has no scripted step (the script has ${this.#steps.length})`);
|
|
112
129
|
return { [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) }) };
|
|
113
130
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scripted-model.js","sourceRoot":"","sources":["../../src/testing/scripted-model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAGL,UAAU,EAQV,eAAe,GAChB,MAAM,uBAAuB,CAAC;AAwC/B,MAAM,YAAY,GAAc,EAAE,aAAa,EAAE,OAAO,EAAE,eAAe,EAA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I,EAAE,GAAG,IAAI,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;QAC5C,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["/**\n * `ScriptedModel`: the strict scripted test model every loop, tool, hook and pause test drives\n * (SDK plan §3.3, §5.1; SDK decision 14; agent-SDK guide §8).\n *\n * - **Strict.** A call past the last step throws `UnexpectedModelCallError`; `assertComplete()` throws if steps remain.\n * - **Frozen snapshots.** Each request is cloned and deeply frozen when the call is made, so later mutation of the\n * caller's context never changes `calls`.\n * - **Realistic streams.** Text, reasoning and tool-input JSON arrive in chunks of `chunkSize` characters, and the\n * abort signal is checked between chunks.\n * - **Deterministic.** Chunk sizes and generated ids come only from the options, never `Math.random()` or `Date.now()`.\n *\n * It implements the gateway's `ModelAdapter` and imports nothing from the loop, so gateway tests can use it too.\n */\nimport {\n type AssistantMessage,\n type ContentBlock,\n emptyUsage,\n type ModelAdapter,\n type ModelCaps,\n type ModelContext,\n type ModelEvent,\n type ModelRef,\n type StreamOptions,\n type Usage,\n unreportedUsage,\n} from \"@buildanagent/gateway\";\n\n/** One scripted model response. */\nexport interface AssistantScript {\n content: ContentBlock[];\n /** Defaults to `\"tool_calls\"` when `content` has a tool call, else `\"stop\"`. Ignored when `error` is set. */\n stopReason?: \"stop\" | \"length\" | \"tool_calls\";\n /** Ends the stream with an `error` terminal (`stopReason: \"error\"`) after streaming `content`. */\n error?: NonNullable<AssistantMessage[\"error\"]>;\n /**\n * The token counts the response reports; counts left out are zero. Leave `usage` itself out to script a provider\n * that reports none: the message's usage is then `unreported`, and `createModel()` prices it as unknown. Pass\n * `usage: {}` for a response that reports zero tokens.\n */\n usage?: Partial<Omit<Usage, \"raw\">>;\n}\n\n/** A frozen, detached snapshot of one call: the model, the context and the serialisable options. */\nexport interface RecordedRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: Readonly<\n Pick<StreamOptions, \"maxOutputTokens\" | \"temperature\" | \"cacheRetention\" | \"providerOptions\">\n >;\n}\n\n/** A fixed response, or a responder that builds one from the recorded request. */\nexport type ScriptStep = AssistantScript | ((request: RecordedRequest) => AssistantScript | Promise<AssistantScript>);\n\nexport interface ScriptedModelOptions {\n /** Characters per delta. Default 4. */\n chunkSize?: number;\n /** Overrides the adapter's `api` and `provider` (`\"scripted\"` by default). */\n ref?: Partial<ModelRef>;\n /** Fills in missing tool-call ids. Default `call-1`, `call-2`, … */\n idGenerator?: () => string;\n /** The caps `createModel()` gives this model. Default: 200,000-token window, 32,000 output tokens, images, reasoning. */\n caps?: ModelCaps;\n}\n\nconst DEFAULT_CAPS: ModelCaps = { contextWindow: 200_000, maxOutputTokens: 32_000, images: true, reasoning: true };\n\nexport class UnexpectedModelCallError extends Error {\n override readonly name = \"UnexpectedModelCallError\";\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const key of Reflect.ownKeys(value)) deepFreeze((value as Record<PropertyKey, unknown>)[key]);\n }\n return value;\n}\n\nfunction chunks(text: string, size: number): string[] {\n if (text.length === 0) return [];\n const out: string[] = [];\n for (let i = 0; i < text.length; i += size) out.push(text.slice(i, i + size));\n return out;\n}\n\n/** What one stream has built so far. */\ninterface RunState {\n readonly model: ModelRef;\n readonly content: ContentBlock[];\n readonly usage: Usage;\n}\n\n/** The serialisable stream options, with omitted ones left out rather than set to `undefined`. */\nfunction recordedOptions(options: StreamOptions): RecordedRequest[\"options\"] {\n const recorded: { -readonly [K in keyof RecordedRequest[\"options\"]]: RecordedRequest[\"options\"][K] } = {};\n if (options.maxOutputTokens !== undefined) recorded.maxOutputTokens = options.maxOutputTokens;\n if (options.temperature !== undefined) recorded.temperature = options.temperature;\n if (options.cacheRetention !== undefined) recorded.cacheRetention = options.cacheRetention;\n if (options.providerOptions !== undefined) recorded.providerOptions = options.providerOptions;\n return recorded;\n}\n\nfunction messageOf(\n run: RunState,\n stopReason: AssistantMessage[\"stopReason\"],\n error?: NonNullable<AssistantMessage[\"error\"]>,\n): AssistantMessage {\n return {\n role: \"assistant\",\n content: [...run.content],\n model: run.model,\n stopReason,\n ...(error === undefined ? {} : { error }),\n usage: run.usage,\n cost: { total: null, basis: \"unknown\", currency: \"USD\" },\n };\n}\n\n/** The terminal event once every block has streamed: an error if the script set one, else done. */\nfunction terminal(run: RunState, script: AssistantScript): ModelEvent {\n if (script.error) return { type: \"error\", message: messageOf(run, \"error\", script.error) };\n const stopReason = script.stopReason ?? (run.content.some((b) => b.type === \"tool_call\") ? \"tool_calls\" : \"stop\");\n return { type: \"done\", message: messageOf(run, stopReason) };\n}\n\nexport class ScriptedModel implements ModelAdapter {\n readonly specificationVersion = \"v1\" as const;\n readonly api: string;\n readonly provider: string;\n readonly defaultCaps: ModelCaps;\n readonly #steps: ScriptStep[];\n readonly #calls: RecordedRequest[] = [];\n readonly #chunkSize: number;\n readonly #nextId: () => string;\n #used = 0;\n\n constructor(steps: ScriptStep[], options: ScriptedModelOptions = {}) {\n const chunkSize = options.chunkSize ?? 4;\n if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(\"chunkSize must be a positive integer\");\n this.#steps = [...steps];\n this.#chunkSize = chunkSize;\n this.api = options.ref?.api ?? \"scripted\";\n this.provider = options.ref?.provider ?? \"scripted\";\n this.defaultCaps = { ...(options.caps ?? DEFAULT_CAPS) };\n let n = 0;\n this.#nextId = options.idGenerator ?? (() => `call-${++n}`);\n }\n\n /** Every call so far, as frozen, detached snapshots. */\n get calls(): readonly RecordedRequest[] {\n return this.#calls;\n }\n\n /** Throws if any scripted step was never used. Call it in test teardown. */\n assertComplete(): void {\n const remaining = this.#steps.length - this.#used;\n if (remaining > 0) {\n throw new Error(`ScriptedModel: ${remaining} of ${this.#steps.length} scripted steps were never called`);\n }\n }\n\n stream(model: ModelRef, context: ModelContext, options: StreamOptions): AsyncIterable<ModelEvent> {\n const callNumber = this.#used + 1;\n const step = this.#steps[this.#used];\n if (step === undefined) return this.#overRun(callNumber);\n const request: RecordedRequest = deepFreeze(structuredClone({ model, context, options: recordedOptions(options) }));\n this.#calls.push(request);\n this.#used += 1;\n return this.#run(step, request, options.signal);\n }\n\n // The error surfaces when the caller reads the stream, like any other stream failure, not when it calls stream().\n #overRun(callNumber: number): AsyncIterable<ModelEvent> {\n const error = new UnexpectedModelCallError(\n `ScriptedModel: call ${callNumber} has no scripted step (the script has ${this.#steps.length})`,\n );\n return { [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) }) };\n }\n\n async *#run(step: ScriptStep, request: RecordedRequest, signal: AbortSignal | undefined): AsyncGenerator<ModelEvent> {\n const script = typeof step === \"function\" ? await step(request) : step;\n const usage = script.usage === undefined ? unreportedUsage() : { ...emptyUsage(), ...script.usage, raw: null };\n const run: RunState = { model: request.model, content: [], usage };\n yield { type: \"start\" };\n let index = 0;\n for (const scripted of script.content) {\n // Checked before the call id is drawn, so an abort leaves the id sequence and the image blocks untouched.\n if (signal?.aborted) {\n yield { type: \"error\", message: messageOf(run, \"aborted\") };\n return;\n }\n const block = this.#withCallId(scripted);\n if (block.type === \"image\") {\n run.content.push(block);\n continue;\n }\n const completed = yield* this.#streamBlock(block, index, run, signal);\n if (!completed) return;\n index += 1;\n }\n yield terminal(run, script);\n }\n\n #withCallId(scripted: ContentBlock): ContentBlock {\n if (scripted.type === \"tool_call\" && !scripted.callId) return { ...scripted, callId: this.#nextId() };\n return structuredClone(scripted);\n }\n\n /** Streams one text, reasoning or tool-call block in chunks; returns false after an abort ends the stream. */\n async *#streamBlock(\n block: Exclude<ContentBlock, { type: \"image\" }>,\n index: number,\n run: RunState,\n signal: AbortSignal | undefined,\n ): AsyncGenerator<ModelEvent, boolean> {\n const kind = block.type === \"tool_call\" ? \"tool_input\" : block.type;\n const text = block.type === \"tool_call\" ? JSON.stringify(block.input ?? {}) : block.text;\n yield { type: `${kind}_start`, index };\n let partial = \"\";\n for (const delta of chunks(text, this.#chunkSize)) {\n if (signal?.aborted) {\n // An aborted stream keeps the text streamed so far, but never a partial tool call.\n if (block.type !== \"tool_call\" && partial) run.content.push({ ...block, text: partial });\n yield { type: \"error\", message: messageOf(run, \"aborted\") };\n return false;\n }\n partial += delta;\n yield { type: `${kind}_delta`, index, delta };\n }\n run.content.push(block);\n yield { type: `${kind}_end`, index, block };\n return true;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"scripted-model.js","sourceRoot":"","sources":["../../src/testing/scripted-model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAGL,UAAU,EAQV,eAAe,GAChB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAwCxC,MAAM,YAAY,GAAc,EAAE,aAAa,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAEnH;;;GAGG;AACH,MAAM,OAAO,wBAAyB,SAAQ,QAAQ;IAClC,IAAI,GAAG,0BAA0B,CAAC;IAEpD,YAAY,OAAe;QACzB,KAAK,CAAC,uBAAuB,EAAE,OAAO,CAAC,CAAC;IAC1C,CAAC;CACF;AAED,SAAS,UAAU,CAAI,KAAQ;IAC7B,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAClE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACrB,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC;YAAE,UAAU,CAAE,KAAsC,CAAC,GAAG,CAAC,CAAC,CAAC;IACrG,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,MAAM,CAAC,IAAY,EAAE,IAAY;IACxC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACjC,MAAM,GAAG,GAAa,EAAE,CAAC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,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;QACzF,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,QAAQ,EAAE,KAAK,EAAE,CAAC;QACvC,IAAI,OAAO,GAAG,EAAE,CAAC;QACjB,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAClD,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;gBACpB,mFAAmF;gBACnF,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO;oBAAE,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;gBACzF,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,CAAC,GAAG,EAAE,SAAS,CAAC,EAAE,CAAC;gBAC5D,OAAO,KAAK,CAAC;YACf,CAAC;YACD,OAAO,IAAI,KAAK,CAAC;YACjB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;QAChD,CAAC;QACD,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;QAC5C,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["/**\n * `ScriptedModel`: the strict scripted test model every loop, tool, hook and pause test drives\n * (SDK plan §3.3, §5.1; SDK decision 14; agent-SDK guide §8).\n *\n * - **Strict.** A call past the last step throws `UnexpectedModelCallError`; `assertComplete()` throws if steps remain.\n * - **Frozen snapshots.** Each request is cloned and deeply frozen when the call is made, so later mutation of the\n * caller's context never changes `calls`.\n * - **Realistic streams.** Text, reasoning and tool-input JSON arrive in chunks of `chunkSize` characters, and the\n * abort signal is checked between chunks.\n * - **Deterministic.** Chunk sizes and generated ids come only from the options, never `Math.random()` or `Date.now()`.\n *\n * It implements the gateway's `ModelAdapter` and imports nothing from the loop, so gateway tests can use it too.\n */\nimport {\n type AssistantMessage,\n type ContentBlock,\n emptyUsage,\n type ModelAdapter,\n type ModelCaps,\n type ModelContext,\n type ModelEvent,\n type ModelRef,\n type StreamOptions,\n type Usage,\n unreportedUsage,\n} from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\n\n/** One scripted model response. */\nexport interface AssistantScript {\n content: ContentBlock[];\n /** Defaults to `\"tool_calls\"` when `content` has a tool call, else `\"stop\"`. Ignored when `error` is set. */\n stopReason?: \"stop\" | \"length\" | \"tool_calls\";\n /** Ends the stream with an `error` terminal (`stopReason: \"error\"`) after streaming `content`. */\n error?: NonNullable<AssistantMessage[\"error\"]>;\n /**\n * The token counts the response reports; counts left out are zero. Leave `usage` itself out to script a provider\n * that reports none: the message's usage is then `unreported`, and `createModel()` prices it as unknown. Pass\n * `usage: {}` for a response that reports zero tokens.\n */\n usage?: Partial<Omit<Usage, \"raw\">>;\n}\n\n/** A frozen, detached snapshot of one call: the model, the context and the serialisable options. */\nexport interface RecordedRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: Readonly<\n Pick<StreamOptions, \"maxOutputTokens\" | \"temperature\" | \"cacheRetention\" | \"providerOptions\">\n >;\n}\n\n/** A fixed response, or a responder that builds one from the recorded request. */\nexport type ScriptStep = AssistantScript | ((request: RecordedRequest) => AssistantScript | Promise<AssistantScript>);\n\nexport interface ScriptedModelOptions {\n /** Characters per delta. Default 4. */\n chunkSize?: number;\n /** Overrides the adapter's `api` and `provider` (`\"scripted\"` by default). */\n ref?: Partial<ModelRef>;\n /** Fills in missing tool-call ids. Default `call-1`, `call-2`, … */\n idGenerator?: () => string;\n /** The caps `createModel()` gives this model. Default: 200,000-token window, 32,000 output tokens, images, reasoning. */\n caps?: ModelCaps;\n}\n\nconst DEFAULT_CAPS: ModelCaps = { contextWindow: 200_000, maxOutputTokens: 32_000, images: true, reasoning: true };\n\n/**\n * Thrown when a `ScriptedModel` is called after its last scripted step. It is an `SdkError` with code\n * `unexpected_model_call`, so `isSdkError()` recognises it too.\n */\nexport class UnexpectedModelCallError extends SdkError {\n override readonly name = \"UnexpectedModelCallError\";\n\n constructor(message: string) {\n super(\"unexpected_model_call\", message);\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const key of Reflect.ownKeys(value)) deepFreeze((value as Record<PropertyKey, unknown>)[key]);\n }\n return value;\n}\n\nfunction chunks(text: string, size: number): string[] {\n if (text.length === 0) return [];\n const out: string[] = [];\n for (let i = 0; i < text.length; i += size) out.push(text.slice(i, i + size));\n return out;\n}\n\n/** What one stream has built so far. */\ninterface RunState {\n readonly model: ModelRef;\n readonly content: ContentBlock[];\n readonly usage: Usage;\n}\n\n/** The serialisable stream options, with omitted ones left out rather than set to `undefined`. */\nfunction recordedOptions(options: StreamOptions): RecordedRequest[\"options\"] {\n const recorded: { -readonly [K in keyof RecordedRequest[\"options\"]]: RecordedRequest[\"options\"][K] } = {};\n if (options.maxOutputTokens !== undefined) recorded.maxOutputTokens = options.maxOutputTokens;\n if (options.temperature !== undefined) recorded.temperature = options.temperature;\n if (options.cacheRetention !== undefined) recorded.cacheRetention = options.cacheRetention;\n if (options.providerOptions !== undefined) recorded.providerOptions = options.providerOptions;\n return recorded;\n}\n\nfunction messageOf(\n run: RunState,\n stopReason: AssistantMessage[\"stopReason\"],\n error?: NonNullable<AssistantMessage[\"error\"]>,\n): AssistantMessage {\n return {\n role: \"assistant\",\n content: [...run.content],\n model: run.model,\n stopReason,\n ...(error === undefined ? {} : { error }),\n usage: run.usage,\n cost: { total: null, basis: \"unknown\", currency: \"USD\" },\n };\n}\n\n/** The terminal event once every block has streamed: an error if the script set one, else done. */\nfunction terminal(run: RunState, script: AssistantScript): ModelEvent {\n if (script.error) return { type: \"error\", message: messageOf(run, \"error\", script.error) };\n const stopReason = script.stopReason ?? (run.content.some((b) => b.type === \"tool_call\") ? \"tool_calls\" : \"stop\");\n return { type: \"done\", message: messageOf(run, stopReason) };\n}\n\nexport class ScriptedModel implements ModelAdapter {\n readonly specificationVersion = \"v1\" as const;\n readonly api: string;\n readonly provider: string;\n readonly defaultCaps: ModelCaps;\n readonly #steps: ScriptStep[];\n readonly #calls: RecordedRequest[] = [];\n readonly #chunkSize: number;\n readonly #nextId: () => string;\n #used = 0;\n #overRuns = 0;\n\n constructor(steps: ScriptStep[], options: ScriptedModelOptions = {}) {\n const chunkSize = options.chunkSize ?? 4;\n if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(\"chunkSize must be a positive integer\");\n this.#steps = [...steps];\n this.#chunkSize = chunkSize;\n this.api = options.ref?.api ?? \"scripted\";\n this.provider = options.ref?.provider ?? \"scripted\";\n this.defaultCaps = { ...(options.caps ?? DEFAULT_CAPS) };\n let n = 0;\n this.#nextId = options.idGenerator ?? (() => `call-${++n}`);\n }\n\n /** Every call so far, as frozen, detached snapshots. */\n get calls(): readonly RecordedRequest[] {\n return this.#calls;\n }\n\n /**\n * Throws if any scripted step was never used, or if the model was called after its last step. Call it in test\n * teardown: `createModel()` turns an over-run's `UnexpectedModelCallError` into a failed call, so a run reports it\n * as an `error` result, and only this check makes the test fail.\n */\n assertComplete(): void {\n if (this.#overRuns > 0) {\n throw new UnexpectedModelCallError(\n `ScriptedModel: called ${this.#overRuns} more time(s) than its ${this.#steps.length} scripted steps allow`,\n );\n }\n const remaining = this.#steps.length - this.#used;\n if (remaining > 0) {\n throw new Error(`ScriptedModel: ${remaining} of ${this.#steps.length} scripted steps were never called`);\n }\n }\n\n stream(model: ModelRef, context: ModelContext, options: StreamOptions): AsyncIterable<ModelEvent> {\n const callNumber = this.#used + 1;\n const step = this.#steps[this.#used];\n if (step === undefined) return this.#overRun(callNumber);\n const request: RecordedRequest = deepFreeze(structuredClone({ model, context, options: recordedOptions(options) }));\n this.#calls.push(request);\n this.#used += 1;\n return this.#run(step, request, options.signal);\n }\n\n // The error surfaces when the caller reads the stream, like any other stream failure, not when it calls stream().\n #overRun(callNumber: number): AsyncIterable<ModelEvent> {\n this.#overRuns += 1;\n const error = new UnexpectedModelCallError(\n `ScriptedModel: call ${callNumber} has no scripted step (the script has ${this.#steps.length})`,\n );\n return { [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) }) };\n }\n\n async *#run(step: ScriptStep, request: RecordedRequest, signal: AbortSignal | undefined): AsyncGenerator<ModelEvent> {\n const script = typeof step === \"function\" ? await step(request) : step;\n const usage = script.usage === undefined ? unreportedUsage() : { ...emptyUsage(), ...script.usage, raw: null };\n const run: RunState = { model: request.model, content: [], usage };\n yield { type: \"start\" };\n let index = 0;\n for (const scripted of script.content) {\n // Checked before the call id is drawn, so an abort leaves the id sequence and the image blocks untouched.\n if (signal?.aborted) {\n yield { type: \"error\", message: messageOf(run, \"aborted\") };\n return;\n }\n const block = this.#withCallId(scripted);\n if (block.type === \"image\") {\n run.content.push(block);\n continue;\n }\n const completed = yield* this.#streamBlock(block, index, run, signal);\n if (!completed) return;\n index += 1;\n }\n yield terminal(run, script);\n }\n\n #withCallId(scripted: ContentBlock): ContentBlock {\n if (scripted.type === \"tool_call\" && !scripted.callId) return { ...scripted, callId: this.#nextId() };\n return structuredClone(scripted);\n }\n\n /** Streams one text, reasoning or tool-call block in chunks; returns false after an abort ends the stream. */\n async *#streamBlock(\n block: Exclude<ContentBlock, { type: \"image\" }>,\n index: number,\n run: RunState,\n signal: AbortSignal | undefined,\n ): AsyncGenerator<ModelEvent, boolean> {\n const kind = block.type === \"tool_call\" ? \"tool_input\" : block.type;\n const text = block.type === \"tool_call\" ? JSON.stringify(block.input ?? {}) : block.text;\n yield { type: `${kind}_start`, index };\n let partial = \"\";\n for (const delta of chunks(text, this.#chunkSize)) {\n if (signal?.aborted) {\n // An aborted stream keeps the text streamed so far, but never a partial tool call.\n if (block.type !== \"tool_call\" && partial) run.content.push({ ...block, text: partial });\n yield { type: \"error\", message: messageOf(run, \"aborted\") };\n return false;\n }\n partial += delta;\n yield { type: `${kind}_delta`, index, delta };\n }\n run.content.push(block);\n yield { type: `${kind}_end`, index, block };\n return true;\n }\n}\n"]}
|
package/dist/tools/define.d.ts
CHANGED
|
@@ -1,17 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,
|
|
3
|
+
* so a broken tool throws when it is defined rather than when the model first calls it.
|
|
4
|
+
*/
|
|
5
|
+
import { type WireTool } from "@buildanagent/gateway";
|
|
1
6
|
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
7
|
import { type PreparedSchema } from "./schema.js";
|
|
3
8
|
import type { ToolDefinition } from "./types.js";
|
|
4
9
|
/**
|
|
5
10
|
* Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
|
|
6
|
-
* `invalid_tool_definition`, for a bad name, a missing description or `execute`, or an unusable
|
|
11
|
+
* `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable
|
|
12
|
+
* schema.
|
|
7
13
|
*/
|
|
8
14
|
export declare function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema;
|
|
9
15
|
/**
|
|
10
16
|
* Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
|
|
11
17
|
*
|
|
12
18
|
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
13
|
-
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing,
|
|
14
|
-
*
|
|
19
|
+
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
|
|
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.
|
|
15
23
|
*/
|
|
16
24
|
export declare function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S>;
|
|
17
25
|
/** The options of `outputTool()`. */
|
|
@@ -35,8 +43,10 @@ export interface ClarificationToolOptions {
|
|
|
35
43
|
}
|
|
36
44
|
/**
|
|
37
45
|
* Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
|
|
38
|
-
* `clarification`,
|
|
46
|
+
* `clarification`, and a run that gets it ends with `stopReason: "stopped"` and `stoppedBy: "clarification"`.
|
|
39
47
|
*/
|
|
40
48
|
export declare function clarificationTool(options?: ClarificationToolOptions): ToolDefinition<{
|
|
41
49
|
question: string;
|
|
42
50
|
}, never>;
|
|
51
|
+
/** The tool as one model call sends it: its name, description and input JSON Schema. */
|
|
52
|
+
export declare function toWireTool(tool: ToolDefinition<unknown, unknown>): WireTool;
|
package/dist/tools/define.js
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
import { assertCanonicalName } from "@buildanagent/gateway";
|
|
6
6
|
import { SdkError } from "../errors.js";
|
|
7
7
|
import { prepareSchema } from "./schema.js";
|
|
8
|
+
const EXPOSURES = ["direct", "deferred", "hidden"];
|
|
9
|
+
const EXECUTION_MODES = ["parallel", "sequential"];
|
|
8
10
|
// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.
|
|
9
11
|
const prepared = new WeakMap();
|
|
10
12
|
function invalid(message, cause) {
|
|
@@ -23,7 +25,8 @@ function checkName(name) {
|
|
|
23
25
|
}
|
|
24
26
|
/**
|
|
25
27
|
* Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
|
|
26
|
-
* `invalid_tool_definition`, for a bad name, a missing description or `execute`, or an unusable
|
|
28
|
+
* `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable
|
|
29
|
+
* schema.
|
|
27
30
|
*/
|
|
28
31
|
export function preparedSchemaOf(tool) {
|
|
29
32
|
const known = prepared.get(tool);
|
|
@@ -34,6 +37,15 @@ export function preparedSchemaOf(tool) {
|
|
|
34
37
|
throw invalid(`tool "${name}": description must be a string`);
|
|
35
38
|
if (typeof tool.execute !== "function")
|
|
36
39
|
throw invalid(`tool "${name}": execute must be a function`);
|
|
40
|
+
if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {
|
|
41
|
+
throw invalid(`tool "${name}": exposure must be "direct", "deferred" or "hidden"`);
|
|
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
|
+
}
|
|
37
49
|
const schema = prepareSchema(name, tool.inputSchema);
|
|
38
50
|
prepared.set(tool, schema);
|
|
39
51
|
return schema;
|
|
@@ -42,8 +54,10 @@ export function preparedSchemaOf(tool) {
|
|
|
42
54
|
* Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
|
|
43
55
|
*
|
|
44
56
|
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
45
|
-
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing,
|
|
46
|
-
*
|
|
57
|
+
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
|
|
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.
|
|
47
61
|
*/
|
|
48
62
|
export function defineTool(definition) {
|
|
49
63
|
const tool = Object.freeze({ ...definition });
|
|
@@ -78,7 +92,7 @@ const CLARIFICATION_SCHEMA = Object.freeze({
|
|
|
78
92
|
});
|
|
79
93
|
/**
|
|
80
94
|
* Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
|
|
81
|
-
* `clarification`,
|
|
95
|
+
* `clarification`, and a run that gets it ends with `stopReason: "stopped"` and `stoppedBy: "clarification"`.
|
|
82
96
|
*/
|
|
83
97
|
export function clarificationTool(options = {}) {
|
|
84
98
|
return defineTool({
|
|
@@ -93,4 +107,10 @@ export function clarificationTool(options = {}) {
|
|
|
93
107
|
},
|
|
94
108
|
});
|
|
95
109
|
}
|
|
110
|
+
/** The tool as one model call sends it: its name, description and input JSON Schema. */
|
|
111
|
+
export function toWireTool(tool) {
|
|
112
|
+
const { jsonSchema } = preparedSchemaOf(tool);
|
|
113
|
+
// Adapters only read the schema; the cast drops the `readonly` that keeps our own code from changing it.
|
|
114
|
+
return { name: tool.name, description: tool.description, inputSchema: jsonSchema };
|
|
115
|
+
}
|
|
96
116
|
//# sourceMappingURL=define.js.map
|
package/dist/tools/define.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAuB,aAAa,EAAE,MAAM,aAAa,CAAC;AAGjE,+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,C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;gBACvE,KAAK,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,QAAQ,EAAE;aAC3C,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,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 } 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\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`, or an unusable 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 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, a raw JSON Schema does not\n * compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot 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`, which the run turns into a request for the user's answer.\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"]}
|
|
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,IAAI,CAAC;QACH,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,OAAO,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC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,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,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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,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,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IACrD,CAAC;IAAC,MAAM,CAAC;QACP,mGAAmG;QACnG,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IACD,IAAI,IAAI,CAAC,MAAM,IAAI,oB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AAI,+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,18 @@ 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>;
|
|
33
|
+
/** Called for each call of a message before its result is worked out, whether or not the call will run. */
|
|
34
|
+
onStart?(call: ToolCall): void;
|
|
22
35
|
/** Receives a tool's progress updates. */
|
|
23
36
|
onUpdate?(callId: string, details: unknown): void;
|
|
24
37
|
/**
|
|
@@ -44,9 +57,9 @@ export interface ToolCallResult {
|
|
|
44
57
|
*/
|
|
45
58
|
export declare function runToolCall(call: ToolCall, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolResult>;
|
|
46
59
|
/**
|
|
47
|
-
* Runs every tool call of an assistant message
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
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.
|
|
51
64
|
*/
|
|
52
65
|
export declare function runToolCalls(message: AssistantMessage, tools: readonly AnyTool[], ctx: PipelineContext): Promise<ToolCallResult[]>;
|