@buildanagent/sdk 0.1.0-alpha.1 → 0.1.0-alpha.3
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 +163 -5
- package/dist/errors.d.ts +39 -0
- package/dist/errors.js +47 -0
- package/dist/errors.js.map +1 -0
- 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 +11 -3
- package/dist/index.js +8 -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/coerce.d.ts +15 -0
- package/dist/tools/coerce.js +93 -0
- package/dist/tools/coerce.js.map +1 -0
- package/dist/tools/define.d.ts +51 -0
- package/dist/tools/define.js +108 -0
- package/dist/tools/define.js.map +1 -0
- package/dist/tools/format-error.d.ts +13 -0
- package/dist/tools/format-error.js +65 -0
- package/dist/tools/format-error.js.map +1 -0
- package/dist/tools/outcome.d.ts +7 -0
- package/dist/tools/outcome.js +30 -0
- package/dist/tools/outcome.js.map +1 -0
- package/dist/tools/pipeline.d.ts +54 -0
- package/dist/tools/pipeline.js +185 -0
- package/dist/tools/pipeline.js.map +1 -0
- package/dist/tools/schema.d.ts +20 -0
- package/dist/tools/schema.js +100 -0
- package/dist/tools/schema.js.map +1 -0
- package/dist/tools/types.d.ts +152 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/vendor/agent-safety/errors.d.ts +14 -0
- package/dist/vendor/agent-safety/errors.js +21 -0
- package/dist/vendor/agent-safety/errors.js.map +1 -0
- package/dist/vendor/agent-safety/outcome.d.ts +88 -0
- package/dist/vendor/agent-safety/outcome.js +140 -0
- package/dist/vendor/agent-safety/outcome.js.map +1 -0
- package/dist/vendor/agent-safety/render.d.ts +40 -0
- package/dist/vendor/agent-safety/render.js +92 -0
- package/dist/vendor/agent-safety/render.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +11 -3
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,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAGrD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,sDAAsD;AACtD,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAE7B,MAAM,WAAW,GAAU,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC;AACnE,MAAM,SAAS,GAAG,GAAW,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;AAuD/D,SAAS,QAAQ,CAAC,MAAe;IAC/B,IAAI,OAAO,MAAM,KAAK,QAAQ;QAAE,OAAO,MAAM,CAAC;IAC9C,OAAO,MAAM,YAAY,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9D,CAAC;AAED,MAAM,SAAS;IACJ,EAAE,CAAS;IACX,MAAM,CAAwB;IAC9B,OAAO,GAAiB,EAAE,CAAC;IAC3B,WAAW,GAAG,IAAI,eAAe,EAAE,CAAC;IACpC,MAAM,CAAQ;IACvB,QAAQ,GAAmB,EAAE,CAAC;IA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,CAAC,KAAK,CAAC,CAAC,CAAC;IACrG,OAAO,IAAI,SAAS,CAAI,KAAK,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;AACjD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAc,OAAgB,EAAE,OAAsB;IAC/E,OAAO,IAAI,SAAS,CAAI,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;AACzE,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAI,OAAe;IACjD,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC;IACpC,IAAI,MAAM,CAAC,UAAU,KAAK,MAAM;QAAE,OAAO,MAAM,CAAC;IAChD,MAAM,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,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAEnH,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAC/B,IAAI,GAAG,0BAA0B,CAAC;CACrD;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;IACzB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,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AAI,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\";\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;A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AAE,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"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coercion: the few conversions the pipeline makes to a model's tool arguments before validation (D7 keeps coercion
|
|
3
|
+
* our own step, not the validator's). The rules stay minimal and the SDK README lists them:
|
|
4
|
+
*
|
|
5
|
+
* 1. A string that holds JSON becomes the object or array it encodes, where the schema's `type` is `object` or
|
|
6
|
+
* `array`.
|
|
7
|
+
* 2. A string that holds a decimal number becomes that number, where the `type` is `number`, or `integer` when the
|
|
8
|
+
* number is whole. A whole number outside the safe integer range (beyond 2^53) stays a string.
|
|
9
|
+
* 3. The string `"true"` or `"false"` becomes a boolean, where the `type` is `boolean`.
|
|
10
|
+
*
|
|
11
|
+
* The rules reach nested values through `properties` and `items` only, and only where `type` is a single string.
|
|
12
|
+
* They never change a value that already has the schema's type, and they never modify the input.
|
|
13
|
+
*/
|
|
14
|
+
/** Applies the coercion rules to `value` under `schema`, returning `value` itself when no rule applies. */
|
|
15
|
+
export declare function coerceValue(value: unknown, schema: unknown): unknown;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coercion: the few conversions the pipeline makes to a model's tool arguments before validation (D7 keeps coercion
|
|
3
|
+
* our own step, not the validator's). The rules stay minimal and the SDK README lists them:
|
|
4
|
+
*
|
|
5
|
+
* 1. A string that holds JSON becomes the object or array it encodes, where the schema's `type` is `object` or
|
|
6
|
+
* `array`.
|
|
7
|
+
* 2. A string that holds a decimal number becomes that number, where the `type` is `number`, or `integer` when the
|
|
8
|
+
* number is whole. A whole number outside the safe integer range (beyond 2^53) stays a string.
|
|
9
|
+
* 3. The string `"true"` or `"false"` becomes a boolean, where the `type` is `boolean`.
|
|
10
|
+
*
|
|
11
|
+
* The rules reach nested values through `properties` and `items` only, and only where `type` is a single string.
|
|
12
|
+
* They never change a value that already has the schema's type, and they never modify the input.
|
|
13
|
+
*/
|
|
14
|
+
const DECIMAL = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
15
|
+
function isRecord(value) {
|
|
16
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
function parseJson(text) {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(text);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// Not JSON: the value stays a string, and validation reports it.
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function coerceObject(value, schema) {
|
|
28
|
+
const parsed = typeof value === "string" ? parseJson(value) : value;
|
|
29
|
+
const object = isRecord(parsed) ? parsed : undefined;
|
|
30
|
+
if (object === undefined)
|
|
31
|
+
return value;
|
|
32
|
+
const properties = isRecord(schema.properties) ? schema.properties : {};
|
|
33
|
+
let copy;
|
|
34
|
+
for (const [key, child] of Object.entries(properties)) {
|
|
35
|
+
if (!Object.hasOwn(object, key))
|
|
36
|
+
continue;
|
|
37
|
+
const coerced = coerceValue(object[key], child);
|
|
38
|
+
if (coerced === object[key])
|
|
39
|
+
continue;
|
|
40
|
+
copy ??= { ...object };
|
|
41
|
+
copy[key] = coerced;
|
|
42
|
+
}
|
|
43
|
+
return copy ?? object;
|
|
44
|
+
}
|
|
45
|
+
function coerceArray(value, schema) {
|
|
46
|
+
const parsed = typeof value === "string" ? parseJson(value) : value;
|
|
47
|
+
if (!Array.isArray(parsed))
|
|
48
|
+
return value;
|
|
49
|
+
if (!isRecord(schema.items))
|
|
50
|
+
return parsed;
|
|
51
|
+
const items = schema.items;
|
|
52
|
+
const coerced = parsed.map((item) => coerceValue(item, items));
|
|
53
|
+
return coerced.some((item, index) => item !== parsed[index]) ? coerced : parsed;
|
|
54
|
+
}
|
|
55
|
+
function coerceNumber(value, integer) {
|
|
56
|
+
if (typeof value !== "string" || !DECIMAL.test(value))
|
|
57
|
+
return value;
|
|
58
|
+
const number = Number(value);
|
|
59
|
+
if (!Number.isFinite(number) || (integer && !Number.isInteger(number)))
|
|
60
|
+
return value;
|
|
61
|
+
// A whole number past 2^53 would come out as a different number, such as another order's id, so it stays a string
|
|
62
|
+
// and validation reports it.
|
|
63
|
+
if (Number.isInteger(number) && !Number.isSafeInteger(number))
|
|
64
|
+
return value;
|
|
65
|
+
return number;
|
|
66
|
+
}
|
|
67
|
+
function coerceBoolean(value) {
|
|
68
|
+
if (value === "true")
|
|
69
|
+
return true;
|
|
70
|
+
if (value === "false")
|
|
71
|
+
return false;
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
/** Applies the coercion rules to `value` under `schema`, returning `value` itself when no rule applies. */
|
|
75
|
+
export function coerceValue(value, schema) {
|
|
76
|
+
if (!isRecord(schema) || typeof schema.type !== "string")
|
|
77
|
+
return value;
|
|
78
|
+
switch (schema.type) {
|
|
79
|
+
case "object":
|
|
80
|
+
return coerceObject(value, schema);
|
|
81
|
+
case "array":
|
|
82
|
+
return coerceArray(value, schema);
|
|
83
|
+
case "number":
|
|
84
|
+
return coerceNumber(value, false);
|
|
85
|
+
case "integer":
|
|
86
|
+
return coerceNumber(value, true);
|
|
87
|
+
case "boolean":
|
|
88
|
+
return coerceBoolean(value);
|
|
89
|
+
default:
|
|
90
|
+
return value;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=coerce.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coerce.js","sourceRoot":"","sources":["../../src/tools/coerce.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,MAAM,OAAO,GAAG,+CAA+C,CAAC;AAEhE,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,SAAS,CAAC,IAAY;IAC7B,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,iEAAiE;QACjE,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,SAAS,YAAY,CAAC,KAAc,EAAE,MAAc;IAClD,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACpE,MAAM,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;IACrD,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IACvC,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC;IACx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CAAC;QAC9B;YACE,OAAO,KAAK,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Coercion: the few conversions the pipeline makes to a model's tool arguments before validation (D7 keeps coercion\n * our own step, not the validator's). The rules stay minimal and the SDK README lists them:\n *\n * 1. A string that holds JSON becomes the object or array it encodes, where the schema's `type` is `object` or\n * `array`.\n * 2. A string that holds a decimal number becomes that number, where the `type` is `number`, or `integer` when the\n * number is whole. A whole number outside the safe integer range (beyond 2^53) stays a string.\n * 3. The string `\"true\"` or `\"false\"` becomes a boolean, where the `type` is `boolean`.\n *\n * The rules reach nested values through `properties` and `items` only, and only where `type` is a single string.\n * They never change a value that already has the schema's type, and they never modify the input.\n */\n\ntype Schema = Readonly<Record<string, unknown>>;\n\nconst DECIMAL = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n // Not JSON: the value stays a string, and validation reports it.\n return undefined;\n }\n}\n\nfunction coerceObject(value: unknown, schema: Schema): unknown {\n const parsed = typeof value === \"string\" ? parseJson(value) : value;\n const object = isRecord(parsed) ? parsed : undefined;\n if (object === undefined) return value;\n const properties = isRecord(schema.properties) ? schema.properties : {};\n let copy: Record<string, unknown> | undefined;\n for (const [key, child] of Object.entries(properties)) {\n if (!Object.hasOwn(object, key)) continue;\n const coerced = coerceValue(object[key], child);\n if (coerced === object[key]) continue;\n copy ??= { ...object };\n copy[key] = coerced;\n }\n return copy ?? object;\n}\n\nfunction coerceArray(value: unknown, schema: Schema): unknown {\n const parsed = typeof value === \"string\" ? parseJson(value) : value;\n if (!Array.isArray(parsed)) return value;\n if (!isRecord(schema.items)) return parsed;\n const items = schema.items;\n const coerced = parsed.map((item: unknown) => coerceValue(item, items));\n return coerced.some((item, index) => item !== parsed[index]) ? coerced : parsed;\n}\n\nfunction coerceNumber(value: unknown, integer: boolean): unknown {\n if (typeof value !== \"string\" || !DECIMAL.test(value)) return value;\n const number = Number(value);\n if (!Number.isFinite(number) || (integer && !Number.isInteger(number))) return value;\n // A whole number past 2^53 would come out as a different number, such as another order's id, so it stays a string\n // and validation reports it.\n if (Number.isInteger(number) && !Number.isSafeInteger(number)) return value;\n return number;\n}\n\nfunction coerceBoolean(value: unknown): unknown {\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n return value;\n}\n\n/** Applies the coercion rules to `value` under `schema`, returning `value` itself when no rule applies. */\nexport function coerceValue(value: unknown, schema: unknown): unknown {\n if (!isRecord(schema) || typeof schema.type !== \"string\") return value;\n switch (schema.type) {\n case \"object\":\n return coerceObject(value, schema);\n case \"array\":\n return coerceArray(value, schema);\n case \"number\":\n return coerceNumber(value, false);\n case \"integer\":\n return coerceNumber(value, true);\n case \"boolean\":\n return coerceBoolean(value);\n default:\n return value;\n }\n}\n"]}
|
|
@@ -0,0 +1,51 @@
|
|
|
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";
|
|
6
|
+
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
|
|
7
|
+
import { type PreparedSchema } from "./schema.js";
|
|
8
|
+
import type { ToolDefinition } from "./types.js";
|
|
9
|
+
/**
|
|
10
|
+
* Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
|
|
11
|
+
* `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable
|
|
12
|
+
* schema.
|
|
13
|
+
*/
|
|
14
|
+
export declare function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema;
|
|
15
|
+
/**
|
|
16
|
+
* Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
|
|
17
|
+
*
|
|
18
|
+
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
19
|
+
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
|
|
20
|
+
* values, a raw JSON Schema does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot
|
|
21
|
+
* describe itself as JSON Schema.
|
|
22
|
+
*/
|
|
23
|
+
export declare function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S>;
|
|
24
|
+
/** The options of `outputTool()`. */
|
|
25
|
+
export interface OutputToolOptions<S> {
|
|
26
|
+
readonly name: string;
|
|
27
|
+
/** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */
|
|
28
|
+
readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;
|
|
29
|
+
/** Defaults to a line asking the model to call the tool once, with its final answer. */
|
|
30
|
+
readonly description?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the
|
|
34
|
+
* validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model
|
|
35
|
+
* as an error result, so the model can correct the answer and call again.
|
|
36
|
+
*/
|
|
37
|
+
export declare function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S>;
|
|
38
|
+
/** The options of `clarificationTool()`. */
|
|
39
|
+
export interface ClarificationToolOptions {
|
|
40
|
+
/** Defaults to `ask_user`. */
|
|
41
|
+
readonly name?: string;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
|
|
45
|
+
* `clarification`, and a run that gets it ends with `stopReason: "stopped"` and `stoppedBy: "clarification"`.
|
|
46
|
+
*/
|
|
47
|
+
export declare function clarificationTool(options?: ClarificationToolOptions): ToolDefinition<{
|
|
48
|
+
question: string;
|
|
49
|
+
}, never>;
|
|
50
|
+
/** The tool as one model call sends it: its name, description and input JSON Schema. */
|
|
51
|
+
export declare function toWireTool(tool: ToolDefinition<unknown, unknown>): WireTool;
|
|
@@ -0,0 +1,108 @@
|
|
|
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 { assertCanonicalName } from "@buildanagent/gateway";
|
|
6
|
+
import { SdkError } from "../errors.js";
|
|
7
|
+
import { prepareSchema } from "./schema.js";
|
|
8
|
+
const EXPOSURES = ["direct", "deferred", "hidden"];
|
|
9
|
+
// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.
|
|
10
|
+
const prepared = new WeakMap();
|
|
11
|
+
function invalid(message, cause) {
|
|
12
|
+
return new SdkError("invalid_tool_definition", message, cause === undefined ? {} : { cause });
|
|
13
|
+
}
|
|
14
|
+
function checkName(name) {
|
|
15
|
+
if (typeof name !== "string")
|
|
16
|
+
throw invalid("a tool's name must be a string");
|
|
17
|
+
try {
|
|
18
|
+
assertCanonicalName(name);
|
|
19
|
+
}
|
|
20
|
+
catch (cause) {
|
|
21
|
+
throw invalid(cause instanceof Error ? cause.message : String(cause), cause);
|
|
22
|
+
}
|
|
23
|
+
return name;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
|
|
27
|
+
* `invalid_tool_definition`, for a bad name, a missing description or `execute`, an unknown exposure, or an unusable
|
|
28
|
+
* schema.
|
|
29
|
+
*/
|
|
30
|
+
export function preparedSchemaOf(tool) {
|
|
31
|
+
const known = prepared.get(tool);
|
|
32
|
+
if (known !== undefined)
|
|
33
|
+
return known;
|
|
34
|
+
const name = checkName(tool.name);
|
|
35
|
+
if (typeof tool.description !== "string")
|
|
36
|
+
throw invalid(`tool "${name}": description must be a string`);
|
|
37
|
+
if (typeof tool.execute !== "function")
|
|
38
|
+
throw invalid(`tool "${name}": execute must be a function`);
|
|
39
|
+
if (tool.exposure !== undefined && !EXPOSURES.includes(tool.exposure)) {
|
|
40
|
+
throw invalid(`tool "${name}": exposure must be "direct", "deferred" or "hidden"`);
|
|
41
|
+
}
|
|
42
|
+
const schema = prepareSchema(name, tool.inputSchema);
|
|
43
|
+
prepared.set(tool, schema);
|
|
44
|
+
return schema;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
|
|
48
|
+
*
|
|
49
|
+
* Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
|
|
50
|
+
* from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, `exposure` is not one of its three
|
|
51
|
+
* values, a raw JSON Schema does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot
|
|
52
|
+
* describe itself as JSON Schema.
|
|
53
|
+
*/
|
|
54
|
+
export function defineTool(definition) {
|
|
55
|
+
const tool = Object.freeze({ ...definition });
|
|
56
|
+
// Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.
|
|
57
|
+
preparedSchemaOf(tool);
|
|
58
|
+
return tool;
|
|
59
|
+
}
|
|
60
|
+
const OUTPUT_DESCRIPTION = "Submit your final answer as this tool's input. Call it once, when the task is done.";
|
|
61
|
+
const OUTPUT_ACCEPTED = "The final answer was accepted.";
|
|
62
|
+
/**
|
|
63
|
+
* Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the
|
|
64
|
+
* validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model
|
|
65
|
+
* as an error result, so the model can correct the answer and call again.
|
|
66
|
+
*/
|
|
67
|
+
export function outputTool(options) {
|
|
68
|
+
return defineTool({
|
|
69
|
+
name: options.name,
|
|
70
|
+
description: options.description ?? OUTPUT_DESCRIPTION,
|
|
71
|
+
inputSchema: options.schema,
|
|
72
|
+
async execute(input) {
|
|
73
|
+
return { content: [{ type: "text", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const CLARIFICATION_SCHEMA = Object.freeze({
|
|
78
|
+
type: "object",
|
|
79
|
+
properties: Object.freeze({
|
|
80
|
+
question: Object.freeze({ type: "string", minLength: 1, description: "The question to ask the user." }),
|
|
81
|
+
}),
|
|
82
|
+
required: Object.freeze(["question"]),
|
|
83
|
+
additionalProperties: false,
|
|
84
|
+
});
|
|
85
|
+
/**
|
|
86
|
+
* Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
|
|
87
|
+
* `clarification`, and a run that gets it ends with `stopReason: "stopped"` and `stoppedBy: "clarification"`.
|
|
88
|
+
*/
|
|
89
|
+
export function clarificationTool(options = {}) {
|
|
90
|
+
return defineTool({
|
|
91
|
+
name: options.name ?? "ask_user",
|
|
92
|
+
description: "Ask the user a question when you cannot continue without their answer.",
|
|
93
|
+
inputSchema: CLARIFICATION_SCHEMA,
|
|
94
|
+
async execute({ question }) {
|
|
95
|
+
return {
|
|
96
|
+
content: [{ type: "text", text: "The question was sent to the user." }],
|
|
97
|
+
pause: { kind: "clarification", question },
|
|
98
|
+
};
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
/** The tool as one model call sends it: its name, description and input JSON Schema. */
|
|
103
|
+
export function toWireTool(tool) {
|
|
104
|
+
const { jsonSchema } = preparedSchemaOf(tool);
|
|
105
|
+
// Adapters only read the schema; the cast drops the `readonly` that keeps our own code from changing it.
|
|
106
|
+
return { name: tool.name, description: tool.description, inputSchema: jsonSchema };
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=define.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAAA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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"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The default error text the model reads for a failed tool call. Every message says what failed, shows the
|
|
3
|
+
* arguments the model sent, and tells the model not to answer the failure with invented data, because agents have
|
|
4
|
+
* been seen to "make a mock implementation" when a tool fails (agent-SDK guide §4).
|
|
5
|
+
*/
|
|
6
|
+
import type { ModelContent } from "@buildanagent/gateway";
|
|
7
|
+
import type { ToolFailure } from "./types.js";
|
|
8
|
+
/** The line every default error message ends with. */
|
|
9
|
+
export declare const DO_NOT_SUBSTITUTE: string;
|
|
10
|
+
/** The fixed line a redacted error shows the model in place of the thrown message. */
|
|
11
|
+
export declare const REDACTED_MESSAGE = "its error message is hidden.";
|
|
12
|
+
/** The default content for a failed tool call: what failed, the received arguments, and the do-not-substitute line. */
|
|
13
|
+
export declare function formatToolError(failure: ToolFailure): ModelContent[];
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** The line every default error message ends with. */
|
|
2
|
+
export const DO_NOT_SUBSTITUTE = "Do not substitute a mock, a placeholder or invented data for this tool's result. Fix the call, try another " +
|
|
3
|
+
"approach, or tell the user what failed.";
|
|
4
|
+
/** The fixed line a redacted error shows the model in place of the thrown message. */
|
|
5
|
+
export const REDACTED_MESSAGE = "its error message is hidden.";
|
|
6
|
+
// Received arguments are shown up to this many characters, so one huge argument can't flood the context.
|
|
7
|
+
const MAX_ARGUMENTS_LENGTH = 2000;
|
|
8
|
+
// `String()` can itself throw, on an object with no prototype, so the last resort is the object tag.
|
|
9
|
+
function plainString(input) {
|
|
10
|
+
try {
|
|
11
|
+
return String(input);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return Object.prototype.toString.call(input);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function showArguments(input) {
|
|
18
|
+
let text;
|
|
19
|
+
try {
|
|
20
|
+
text = JSON.stringify(input) ?? plainString(input);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// Input from a test double or a tool bridge may hold a cycle or a bigint, which JSON can't encode.
|
|
24
|
+
text = plainString(input);
|
|
25
|
+
}
|
|
26
|
+
if (text.length <= MAX_ARGUMENTS_LENGTH)
|
|
27
|
+
return text;
|
|
28
|
+
// Cut before a surrogate pair rather than through it, so the text stays valid UTF-16.
|
|
29
|
+
const high = text.charCodeAt(MAX_ARGUMENTS_LENGTH - 1);
|
|
30
|
+
const end = high >= 0xd800 && high <= 0xdbff ? MAX_ARGUMENTS_LENGTH - 1 : MAX_ARGUMENTS_LENGTH;
|
|
31
|
+
return `${text.slice(0, end)}… (${text.length - end} more characters)`;
|
|
32
|
+
}
|
|
33
|
+
const NOT_RUN = {
|
|
34
|
+
run_aborted: (tool) => `Tool "${tool}" was not run, because the run was cancelled.`,
|
|
35
|
+
response_error: (tool) => `Tool "${tool}" was not run, because the response ended with an error before it was complete. Re-issue the ` +
|
|
36
|
+
"call if it is still needed.",
|
|
37
|
+
response_aborted: (tool) => `Tool "${tool}" was not run, because the response was stopped before it was complete. Re-issue the call if it ` +
|
|
38
|
+
"is still needed.",
|
|
39
|
+
};
|
|
40
|
+
function issueLine(issue) {
|
|
41
|
+
return `- ${issue.path === "" ? "(the whole input)" : issue.path}: ${issue.message}`;
|
|
42
|
+
}
|
|
43
|
+
function describe(failure) {
|
|
44
|
+
switch (failure.kind) {
|
|
45
|
+
case "unknown_tool": {
|
|
46
|
+
const tools = failure.availableTools.length === 0 ? "none" : failure.availableTools.join(", ");
|
|
47
|
+
return `There is no tool named "${failure.tool}". The available tools are: ${tools}.`;
|
|
48
|
+
}
|
|
49
|
+
case "invalid_input":
|
|
50
|
+
return [`The arguments for tool "${failure.tool}" are invalid:`, ...failure.issues.map(issueLine)].join("\n");
|
|
51
|
+
case "execution_error":
|
|
52
|
+
return `Tool "${failure.tool}" failed: ${failure.message}`;
|
|
53
|
+
case "truncated":
|
|
54
|
+
return (`Tool "${failure.tool}" was not run, because the response was cut off at the output limit before the ` +
|
|
55
|
+
"call's arguments were complete. Re-issue the call with complete arguments, in a shorter response.");
|
|
56
|
+
case "not_run":
|
|
57
|
+
return NOT_RUN[failure.reason](failure.tool);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** The default content for a failed tool call: what failed, the received arguments, and the do-not-substitute line. */
|
|
61
|
+
export function formatToolError(failure) {
|
|
62
|
+
const text = [describe(failure), `Received arguments: ${showArguments(failure.input)}`, DO_NOT_SUBSTITUTE].join("\n");
|
|
63
|
+
return [{ type: "text", text }];
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=format-error.js.map
|
|
@@ -0,0 +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,CA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AAC,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"]}
|