@buildanagent/sdk 0.1.0-alpha.1 → 0.1.0-alpha.10
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 +424 -5
- package/dist/budget.d.ts +33 -0
- package/dist/budget.js +55 -0
- package/dist/budget.js.map +1 -0
- package/dist/compose.d.ts +26 -0
- package/dist/compose.js +157 -0
- package/dist/compose.js.map +1 -0
- package/dist/errors.d.ts +49 -0
- package/dist/errors.js +57 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +168 -0
- package/dist/events.js +32 -0
- package/dist/events.js.map +1 -0
- package/dist/freeze.d.ts +11 -0
- package/dist/freeze.js +42 -0
- package/dist/freeze.js.map +1 -0
- package/dist/hook-checks.d.ts +31 -0
- package/dist/hook-checks.js +130 -0
- package/dist/hook-checks.js.map +1 -0
- package/dist/hook-runner.d.ts +96 -0
- package/dist/hook-runner.js +372 -0
- package/dist/hook-runner.js.map +1 -0
- package/dist/hooks.d.ts +183 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +26 -3
- package/dist/index.js +21 -3
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +67 -0
- package/dist/loop.js +644 -0
- package/dist/loop.js.map +1 -0
- package/dist/observers.d.ts +31 -0
- package/dist/observers.js +98 -0
- package/dist/observers.js.map +1 -0
- package/dist/otel/attributes.d.ts +43 -0
- package/dist/otel/attributes.js +50 -0
- package/dist/otel/attributes.js.map +1 -0
- package/dist/otel/content.d.ts +17 -0
- package/dist/otel/content.js +48 -0
- package/dist/otel/content.js.map +1 -0
- package/dist/otel/index.d.ts +6 -2
- package/dist/otel/index.js +6 -2
- package/dist/otel/index.js.map +1 -1
- package/dist/otel/observer.d.ts +82 -0
- package/dist/otel/observer.js +300 -0
- package/dist/otel/observer.js.map +1 -0
- package/dist/pauses.d.ts +61 -0
- package/dist/pauses.js +83 -0
- package/dist/pauses.js.map +1 -0
- package/dist/progress.d.ts +34 -0
- package/dist/progress.js +139 -0
- package/dist/progress.js.map +1 -0
- package/dist/result.d.ts +134 -0
- package/dist/result.js +2 -0
- package/dist/result.js.map +1 -0
- package/dist/resume.d.ts +76 -0
- package/dist/resume.js +237 -0
- package/dist/resume.js.map +1 -0
- package/dist/run.d.ts +214 -0
- package/dist/run.js +327 -0
- package/dist/run.js.map +1 -0
- package/dist/steering.d.ts +52 -0
- package/dist/steering.js +104 -0
- package/dist/steering.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 +54 -0
- package/dist/tools/define.js +121 -0
- package/dist/tools/define.js.map +1 -0
- package/dist/tools/format-error.d.ts +13 -0
- package/dist/tools/format-error.js +66 -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 +111 -0
- package/dist/tools/pipeline.js +382 -0
- package/dist/tools/pipeline.js.map +1 -0
- 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/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 +196 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/vendor/agent-safety/bytes.d.ts +17 -0
- package/dist/vendor/agent-safety/bytes.js +59 -0
- package/dist/vendor/agent-safety/bytes.js.map +1 -0
- package/dist/vendor/agent-safety/errors.d.ts +22 -0
- package/dist/vendor/agent-safety/errors.js +22 -0
- package/dist/vendor/agent-safety/errors.js.map +1 -0
- package/dist/vendor/agent-safety/hash.d.ts +16 -0
- package/dist/vendor/agent-safety/hash.js +110 -0
- package/dist/vendor/agent-safety/hash.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/pending.d.ts +119 -0
- package/dist/vendor/agent-safety/pending.js +122 -0
- package/dist/vendor/agent-safety/pending.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/vendor/agent-safety/signer.d.ts +42 -0
- package/dist/vendor/agent-safety/signer.js +128 -0
- package/dist/vendor/agent-safety/signer.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 +13 -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,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGxD,OAAO,EAAkB,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAA2C,aAAa,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAExG,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAwB,aAAa,EAAE,MAAM,eAAe,CAAC;AAEpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAIrD,OAAO,EAAuB,eAAe,EAAE,MAAM,iCAAiC,CAAC;AACvF,OAAO,EAAE,WAAW,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AE,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AACvE,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,WAAW,CAAc,OAAgB,EAAE,OAA2B;IACpF,MAAM,MAAM,GAAG,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9E,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;IAC5C,OAAO,IAAI,SAAS,CAAI,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AACrH,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 } from \"@buildanagent/gateway\";\nimport { checkBudgetOption } from \"./budget.js\";\nimport { RunStoppedError, SdkError } from \"./errors.js\";\nimport type { AgentEvent, AgentEventBody } from \"./events.js\";\nimport type { CallOptions, Interceptors, Observer } from \"./hooks.js\";\nimport { type LoopSetup, runLoop } from \"./loop.js\";\nimport { ObserverBus } from \"./observers.js\";\nimport { blockingHandlerOf, isSigner } from \"./pauses.js\";\nimport { type ProgressCheck, type ProgressPolicy, progressCheck, resolveProgress } from \"./progress.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.js\";\nimport { resumeSetupOf } from \"./resume.js\";\nimport { type DeliveryReceipt, SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolContext, ToolDefinition } from \"./tools/types.js\";\nimport type { Recheck, Resolution } from \"./vendor/agent-safety/pending.js\";\nimport { type ApprovalSigner, ephemeralSigner } from \"./vendor/agent-safety/signer.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\n/** The step cap's default, counted in model calls. */\nconst DEFAULT_MAX_STEPS = 20;\n\n/** The depth cap's default (D11): a top-level run, its subagents and their subagents may run, and no deeper. */\nconst DEFAULT_MAX_DEPTH = 2;\n\n/** How long the run waits, by default, for an observer to catch up before it drops it. */\nconst DEFAULT_OBSERVER_TIMEOUT_MS = 10_000;\n/** The longest delay `setTimeout` accepts; a larger one fires at once on Node and workerd alike. */\nconst MAX_TIMER_MS = 2_147_483_647;\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 /**\n * The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent unless a\n * `beforeModelCall` interceptor names them in `activeTools`.\n */\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 /**\n * The most the run's model calls may cost, in USD. Before each call the run projects its cost with\n * `projectCallCost()` and, if the spend so far plus that projection would pass the cap, ends with\n * `stopReason: \"budget\"` without making the call. The cap counts the calls this run makes, not the cost of the\n * history a `continueRun()` starts from. A budgeted run on a model whose price is unknown ends `error` with\n * `error.kind: \"unknown_price\"` before its first call, because it could not tell what it spent. Without it, a run\n * has no cap.\n */\n readonly budgetUsd?: number;\n /**\n * The default progress policy: the run ends `no_progress` after 3 identical failing tool calls in a row, or after 5\n * calls to a tool with one `progressKey` and no success between them. It runs after your own `shouldStop`, whose\n * `{ continue }` can't keep a stuck run going. Pass numbers to change either threshold, or `false` to turn the\n * policy off.\n */\n readonly progress?: ProgressPolicy | false;\n /**\n * How deeply this run is nested inside other agents' tool calls. Default 0. A tool that starts a run of its own\n * passes `depth: ctx.depth + 1` and `maxDepth: ctx.maxDepth`; `run()` throws an `SdkError` with code\n * `max_depth_exceeded` when `depth` is above `maxDepth`, which the tool's caller reads as an error result.\n */\n readonly depth?: number;\n /** The deepest nesting allowed, which tools read as `ctx.maxDepth`. Default 2. */\n readonly maxDepth?: 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?: CallOptions;\n /**\n * The interceptors: hooks that can change the run at six moments. A run takes one object; join several with\n * `composeInterceptors()`. See `Interceptors` for the order and for what a failing hook does.\n */\n readonly interceptors?: Interceptors;\n /**\n * Observers, which receive every event from `run_start` on and can't change the run. Each observer sees the events in\n * order and waits for its own promises, but observers don't wait for each other. An observer that throws becomes a\n * `hook_error` event. The run waits for every observer to handle the last event before it settles, for at most\n * `observerTimeoutMs` each time it waits; an observer that hasn't caught up by then is removed and reported as a\n * `hook_error`.\n */\n readonly observers?: readonly Observer[];\n /**\n * The longest the run waits for its observers each time it waits for them: before `agent_settled`, before\n * `run_end` and before it settles. A number from 1 to 2147483647; the default is 10000. It bounds an observer whose promise never settles.\n */\n readonly observerTimeoutMs?: number;\n /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */\n readonly clock?: Clock;\n /**\n * Makes the run's id, then the id of each pending request the run signs. A request id that repeats the run's id or\n * an earlier request's id is replaced by `crypto.randomUUID()`, so a generator that always returns one id still\n * pauses every call; return a fresh id on every call to keep request ids deterministic. Defaults to\n * `crypto.randomUUID()`.\n */\n readonly idGenerator?: () => string;\n /**\n * Signs the pending request a run writes when a `beforeToolCall` gate returns `ask`. The default,\n * `ephemeralSigner()`, holds a random key that lives only in this process, so only this process can verify its\n * pauses: on a serverless host, or anywhere a pause may resume in another process, pass `hmacSigner()` over a key\n * ring you keep. A pause that can't be signed is never written unsigned; its call is blocked instead.\n */\n readonly signer?: ApprovalSigner;\n}\n\n/** What `continueRun()` takes besides the shared options: the answers to a paused context's requests. */\nexport interface ContinueOptions<S = unknown> extends RunOptions<S> {\n /**\n * A person's answer to each pending request of the context: `{ requestId, decision: \"allow\" | \"deny\" }` for an\n * approval, `{ requestId, answer }` for a question. Each is checked against its request and the input\n * `context.pendingInputs` holds for it, with the run's `signer`, before anything runs. A request no resolution\n * names still waits, and the run ends paused again without a model call.\n */\n readonly resolutions?: readonly Resolution[];\n /**\n * Runs current policy for each verified approval just before its call runs. It gets copies of the request and\n * input. Resolve to `\"allow\"` to run the call, or to `{ deny: reason }` to give the model an error result with that\n * reason instead. A `recheck` that throws or returns anything else denies the call. Without it, a verified approval\n * runs, so check policy before you resolve.\n */\n readonly recheck?: Recheck;\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\"`, unless a gate already paused a call\n * in the step, which ends it `awaiting_approval`, because that call's signed request still waits. Does nothing once\n * the run has its outcome and is ending, which is before `agent_settled`.\n */\n abort(reason?: string): void;\n /**\n * Adds an observer that receives the events from now on, in order, and returns the function that removes it. An\n * event that was queued for it but not yet handled is dropped when you remove it. Add it right after `run()` to\n * see every event but `run_start`, which `run()` emits before it returns; to see that one too, pass the observer\n * in the `observers` option.\n */\n on(observer: Observer): () => void;\n /**\n * Queues a user message that redirects the run. The run applies it at the next step boundary: after the model call\n * or tool batch in flight, never inside it, and before the next model call. The promise resolves with a\n * `DeliveryReceipt` once the message is in the transcript, and the run emits a `steer_applied` event for it. It\n * rejects with an `SdkError` whose code is `undelivered_message` when the run ends first, and with\n * `invalid_run_options` for a blank message or a block that isn't text or an image. Steers are applied in the\n * order they were sent.\n */\n steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;\n /**\n * Queues a user message that waits until the run would otherwise end. When the model has answered and no tool call\n * is left, the run applies every waiting follow-up as user messages and makes one more model call, so a follow-up\n * sent before the run ends extends it by one step. A steer that is waiting goes first. The run still ends, and the\n * follow-up rejects with `undelivered_message`, when another stop reason ends it: a `shouldStop` hook or progress\n * policy that stops it, its output tool, an abort or `maxSteps`. The receipt works as for `steer()`.\n */\n followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction checkObserver(observer: unknown): void {\n if (typeof observer !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `an observer must be a function, got ${typeof observer}`);\n }\n}\n\nconst HOOK_NAMES = [\n \"transformContext\",\n \"beforeModelCall\",\n \"afterModelCall\",\n \"beforeToolCall\",\n \"afterToolCall\",\n \"shouldStop\",\n] as const;\n\n/** Checks the interceptors option once, so a misspelt or mistyped hook fails at `run()` and not mid-run. */\nfunction checkInterceptors(interceptors: Interceptors): Interceptors {\n if (typeof interceptors !== \"object\" || interceptors === null) {\n throw new SdkError(\"invalid_run_options\", \"interceptors must be an object of hooks\");\n }\n for (const name of HOOK_NAMES) {\n const hook: unknown = interceptors[name];\n if (hook !== undefined && typeof hook !== \"function\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.${name} must be a function, got ${typeof hook}`);\n }\n }\n blockingHandlerOf(interceptors);\n const { onFailure } = interceptors;\n if (onFailure !== undefined && onFailure !== \"fail_closed\" && onFailure !== \"continue\") {\n throw new SdkError(\"invalid_run_options\", `interceptors.onFailure must be \"fail_closed\" or \"continue\"`);\n }\n return interceptors;\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 readonly #bus: ObserverBus;\n #waiters: (() => void)[] = [];\n #ended = false;\n /** Set once the loop has its outcome and starts to end the run, so `abort()` no longer does anything. */\n #settled = false;\n /** Set by `run_end`: nothing may follow it, so a late observer report is dropped. */\n #closed = false;\n readonly #steering: SteeringQueue;\n #failure: { readonly error: unknown } | undefined;\n #stepIndex = 0;\n\n constructor(setup: Omit<LoopSetup, \"signal\" | \"steering\">, signal: AbortSignal | undefined, watch: ObserverSetup) {\n this.id = setup.runId;\n this.#clock = setup.clock;\n this.#steering = new SteeringQueue(setup.runId);\n this.#bus = new ObserverBus((hook, error) => {\n if (!this.#closed) this.#push({ type: \"hook_error\", hook, error: messageOf(error) }, this.#stepIndex);\n }, watch.timeoutMs);\n const { observers } = watch;\n for (const observer of observers) this.#bus.add(observer);\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 // The loop starts after this turn, so an observer added with `run.on()` straight after `run()` sees every event\n // after `run_start`, and a `run.abort()` straight after it stops the run before its first model call.\n // The loop drains the observers only once it has its outcome (`finish()`), so the first drain is also where an\n // abort stops mattering: it could no longer change the outcome, only add an `abort` event after it.\n const drain = () => {\n this.#settled = true;\n return this.#bus.flush();\n };\n const loop = Promise.resolve().then(() =>\n runLoop({ ...setup, signal: this.#controller.signal, steering: this.#steering }, emit, drain),\n );\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.#settled || 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 on(observer: Observer): () => void {\n checkObserver(observer);\n return this.#bus.add(observer);\n }\n\n steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n return this.#steering.add(\"steer\", message);\n }\n\n followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n return this.#steering.add(\"follow_up\", message);\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 if (body.type === \"run_end\") this.#closed = true;\n const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };\n const event = { ...base, ...body } as AgentEvent;\n this.#events.push(event);\n this.#bus.deliver(event);\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 isCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\n/**\n * The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under\n * the same cap. Spread it into the nested `run()`; the nested run throws `max_depth_exceeded` when the tool was\n * already at `maxDepth`.\n */\nexport function nestedRunDepth(ctx: Pick<ToolContext, \"depth\" | \"maxDepth\">): { depth: number; maxDepth: number } {\n return { depth: ctx.depth + 1, maxDepth: ctx.maxDepth };\n}\n\n/** Checks `depth` and `maxDepth`, and refuses a run nested deeper than the cap allows (D11). */\nfunction depthsOf(options: RunOptions<unknown>): { depth: number; maxDepth: number } {\n const { depth = 0, maxDepth = DEFAULT_MAX_DEPTH } = options;\n if (!isCount(depth) || !isCount(maxDepth)) {\n throw new SdkError(\n \"invalid_run_options\",\n `depth and maxDepth must be whole numbers, 0 or more, got ${String(depth)} and ${String(maxDepth)}`,\n );\n }\n if (depth > maxDepth) {\n throw new SdkError(\"max_depth_exceeded\", `a run at depth ${depth} is deeper than maxDepth ${maxDepth} allows`);\n }\n return { depth, maxDepth };\n}\n\n/**\n * The default progress policy for this run, or `undefined` when `progress: false` turns it off. `skip` is the number\n * of messages before the run's own.\n */\nfunction progressOf(options: RunOptions<unknown>, tools: readonly AnyTool[], skip: number): ProgressCheck | undefined {\n const policy = resolveProgress(options.progress);\n return policy === undefined ? undefined : progressCheck(tools, policy, skip);\n}\n\nfunction setupOf(\n options: RunOptions<unknown>,\n context: Context,\n input: readonly Message[],\n): Omit<LoopSetup, \"signal\" | \"steering\"> {\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 signer = options.signer ?? ephemeralSigner();\n if (!isSigner(signer)) {\n throw new SdkError(\n \"invalid_run_options\",\n \"signer must be an ApprovalSigner, such as hmacSigner() or ephemeralSigner()\",\n );\n }\n const budgetUsd = checkBudgetOption(options.budgetUsd);\n const tools = toolsOf(options);\n const { depth, maxDepth } = depthsOf(options);\n const progress = progressOf(options, tools, context.messages.length + input.length);\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 const nextId = options.idGenerator ?? randomIds;\n return {\n runId: nextId(),\n nextId,\n signer,\n model: options.model,\n system: context.system,\n history: context.messages,\n input,\n tools,\n output: options.output as AnyTool | undefined,\n maxSteps,\n ...(budgetUsd === undefined ? {} : { budgetUsd }),\n depth,\n maxDepth,\n modelOptions: options.modelOptions ?? {},\n interceptors: checkInterceptors(options.interceptors ?? {}),\n ...(progress === undefined ? {} : { progress }),\n clock: options.clock ?? systemClock,\n };\n}\n\n/** The observers a run starts with, and how long it waits for them. */\ninterface ObserverSetup {\n readonly observers: readonly Observer[];\n readonly timeoutMs: number;\n}\n\nfunction observersOf(options: RunOptions<unknown>): ObserverSetup {\n const observers = options.observers ?? [];\n for (const observer of observers) checkObserver(observer);\n const timeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {\n throw new SdkError(\n \"invalid_run_options\",\n `observerTimeoutMs must be a number from 1 to ${MAX_TIMER_MS}, got ${timeoutMs}`,\n );\n }\n return { observers, timeoutMs };\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, observersOf(options));\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 * A context whose last response ended in an error asks the model again.\n *\n * A paused context resumes with `resolutions`. Before the first model call, each waiting call's stored request is\n * verified with the run's `signer` against its call and its input in `context.pendingInputs`, then:\n *\n * - a verified `allow` runs the call once, with the input its request signs and without `beforeToolCall`, after\n * `recheck` allows it;\n * - a verified `deny` gives the model an error result with the reason, and a verified `answer` reaches the model as\n * the call's result;\n * - a request no resolution names still waits;\n * - a request or resolution that fails its check runs nothing, emits `resolution_rejected`, and the call asks again\n * with a new approval request: the gate is asked as for a new call, and the call pauses even when the gate allows\n * it. A call to a tool the model isn't sent by default gets the unknown-tool error result instead.\n *\n * Settling the requests is not a step. When a call still waits, the run ends paused again without a model call, and\n * when none does and an approved call's result sets `terminate`, the run ends `done` without one.\n * Each request answers once per context, but the SDK can't see other processes: mark a request used in your store\n * before you resume it, so a second resume of the same stored context is refused there.\n *\n * Throws an `SdkError` with code `invalid_run_options` for a context it can't read, for a context whose last\n * assistant message has a call with no result and no pending request, for a pending request whose call doesn't wait\n * in the context, and for malformed `resolutions` or `recheck`, besides the options `run()` refuses.\n */\nexport function continueRun<S = unknown>(context: Context, options: ContinueOptions<S>): Run<S> {\n const resume = resumeSetupOf(context, options?.resolutions, options?.recheck);\n const setup = setupOf(options, context, []);\n return new RunHandle<S>(resume === undefined ? setup : { ...setup, resume }, options.signal, observersOf(options));\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"]}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Steering and follow-up (SDK plan §3.3). A caller queues a user message while a run goes on; the loop applies it
|
|
3
|
+
* only at a step boundary, so a running model call or tool batch is never cut. A steer is applied before the run's
|
|
4
|
+
* next model call. A follow-up waits until the run would otherwise end. Each queued message returns a receipt once
|
|
5
|
+
* it has entered the transcript.
|
|
6
|
+
*/
|
|
7
|
+
import type { ContentBlock } from "@buildanagent/gateway";
|
|
8
|
+
/** Whether a message steers the run now or follows up once it would otherwise end. */
|
|
9
|
+
export type DeliveryKind = "steer" | "follow_up";
|
|
10
|
+
/**
|
|
11
|
+
* Proof that a queued message entered the transcript. `id` is unique within the run, `message` is the content the
|
|
12
|
+
* run added as a user message, and `stepIndex` is the step at whose start the run added it. That step's model call is
|
|
13
|
+
* the first to see the message, unless the run ends before the call, which a budget stop or a failed hook can cause.
|
|
14
|
+
*/
|
|
15
|
+
export interface DeliveryReceipt {
|
|
16
|
+
readonly id: string;
|
|
17
|
+
readonly kind: DeliveryKind;
|
|
18
|
+
readonly message: readonly ContentBlock[];
|
|
19
|
+
readonly stepIndex: number;
|
|
20
|
+
}
|
|
21
|
+
/** A message the loop took from the queue, with the function that settles its receipt. */
|
|
22
|
+
export interface Delivery {
|
|
23
|
+
readonly kind: DeliveryKind;
|
|
24
|
+
readonly message: readonly ContentBlock[];
|
|
25
|
+
/** Settles the receipt once the message is in the transcript. */
|
|
26
|
+
readonly deliver: (stepIndex: number) => DeliveryReceipt;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The queue between a caller and the loop. The caller adds with `steer()` and `followUp()`; the loop takes with
|
|
30
|
+
* `take()` at a step boundary, and closes the queue when the run has its outcome.
|
|
31
|
+
*/
|
|
32
|
+
export declare class SteeringQueue {
|
|
33
|
+
#private;
|
|
34
|
+
constructor(runId: string);
|
|
35
|
+
/**
|
|
36
|
+
* Queues a message. The promise rejects, never throws, for an unusable message or a run that has ended. A caller who
|
|
37
|
+
* ignores the promise must not crash the process when the run ends first, so a rejection is always marked handled;
|
|
38
|
+
* a caller who awaits it still sees it.
|
|
39
|
+
*/
|
|
40
|
+
add(kind: DeliveryKind, message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;
|
|
41
|
+
/** True while a steer is waiting. */
|
|
42
|
+
hasSteers(): boolean;
|
|
43
|
+
/** True while any message is waiting. */
|
|
44
|
+
hasPending(): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Removes and returns the waiting steers, and the waiting follow-ups too when `withFollowUps` is set, all in the
|
|
47
|
+
* order they were sent.
|
|
48
|
+
*/
|
|
49
|
+
take(withFollowUps: boolean): Delivery[];
|
|
50
|
+
/** Ends the queue: every message still waiting is rejected, and later calls are too. */
|
|
51
|
+
close(): void;
|
|
52
|
+
}
|
package/dist/steering.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { SdkError } from "./errors.js";
|
|
2
|
+
/** A copy of one block of a steering message that holds only the block's own fields. */
|
|
3
|
+
function checkBlock(block) {
|
|
4
|
+
const candidate = block;
|
|
5
|
+
if (candidate?.type === "text" && typeof candidate.text === "string") {
|
|
6
|
+
// Providers refuse an empty text block, so it is refused here rather than failing the next model call.
|
|
7
|
+
if (candidate.text.trim().length === 0) {
|
|
8
|
+
throw new SdkError("invalid_run_options", "a steering message's text block must not be empty");
|
|
9
|
+
}
|
|
10
|
+
return { type: "text", text: candidate.text };
|
|
11
|
+
}
|
|
12
|
+
if (candidate?.type === "image" && typeof candidate.mediaType === "string" && typeof candidate.data === "string") {
|
|
13
|
+
return { type: "image", mediaType: candidate.mediaType, data: candidate.data };
|
|
14
|
+
}
|
|
15
|
+
throw new SdkError("invalid_run_options", "a steering message holds only text and image blocks");
|
|
16
|
+
}
|
|
17
|
+
/** The content of a steering message: a string that isn't blank, or a non-empty list of text and image blocks. */
|
|
18
|
+
function contentOf(message) {
|
|
19
|
+
if (typeof message === "string") {
|
|
20
|
+
if (message.trim().length === 0)
|
|
21
|
+
throw new SdkError("invalid_run_options", "a steering message must not be empty");
|
|
22
|
+
return [{ type: "text", text: message }];
|
|
23
|
+
}
|
|
24
|
+
if (!Array.isArray(message) || message.length === 0) {
|
|
25
|
+
throw new SdkError("invalid_run_options", "a steering message must be a string or a non-empty list of blocks");
|
|
26
|
+
}
|
|
27
|
+
return message.map(checkBlock);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The queue between a caller and the loop. The caller adds with `steer()` and `followUp()`; the loop takes with
|
|
31
|
+
* `take()` at a step boundary, and closes the queue when the run has its outcome.
|
|
32
|
+
*/
|
|
33
|
+
export class SteeringQueue {
|
|
34
|
+
#runId;
|
|
35
|
+
#queue = [];
|
|
36
|
+
#count = 0;
|
|
37
|
+
#closed = false;
|
|
38
|
+
constructor(runId) {
|
|
39
|
+
this.#runId = runId;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Queues a message. The promise rejects, never throws, for an unusable message or a run that has ended. A caller who
|
|
43
|
+
* ignores the promise must not crash the process when the run ends first, so a rejection is always marked handled;
|
|
44
|
+
* a caller who awaits it still sees it.
|
|
45
|
+
*/
|
|
46
|
+
add(kind, message) {
|
|
47
|
+
const receipt = this.#enqueue(kind, message);
|
|
48
|
+
receipt.catch(() => undefined);
|
|
49
|
+
return receipt;
|
|
50
|
+
}
|
|
51
|
+
#enqueue(kind, message) {
|
|
52
|
+
let content;
|
|
53
|
+
try {
|
|
54
|
+
content = contentOf(message);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
return Promise.reject(error);
|
|
58
|
+
}
|
|
59
|
+
if (this.#closed)
|
|
60
|
+
return Promise.reject(undelivered(kind));
|
|
61
|
+
this.#count += 1;
|
|
62
|
+
const id = `${this.#runId}:message-${this.#count}`;
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
this.#queue.push({ id, kind, message: content, resolve, reject });
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** True while a steer is waiting. */
|
|
68
|
+
hasSteers() {
|
|
69
|
+
return this.#queue.some((entry) => entry.kind === "steer");
|
|
70
|
+
}
|
|
71
|
+
/** True while any message is waiting. */
|
|
72
|
+
hasPending() {
|
|
73
|
+
return this.#queue.length > 0;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Removes and returns the waiting steers, and the waiting follow-ups too when `withFollowUps` is set, all in the
|
|
77
|
+
* order they were sent.
|
|
78
|
+
*/
|
|
79
|
+
take(withFollowUps) {
|
|
80
|
+
const taken = this.#queue.filter((entry) => withFollowUps || entry.kind === "steer");
|
|
81
|
+
this.#queue = this.#queue.filter((entry) => !taken.includes(entry));
|
|
82
|
+
return taken.map((entry) => ({
|
|
83
|
+
kind: entry.kind,
|
|
84
|
+
message: entry.message,
|
|
85
|
+
deliver: (stepIndex) => {
|
|
86
|
+
const receipt = { id: entry.id, kind: entry.kind, message: entry.message, stepIndex };
|
|
87
|
+
entry.resolve(receipt);
|
|
88
|
+
return receipt;
|
|
89
|
+
},
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
/** Ends the queue: every message still waiting is rejected, and later calls are too. */
|
|
93
|
+
close() {
|
|
94
|
+
this.#closed = true;
|
|
95
|
+
const waiting = this.#queue;
|
|
96
|
+
this.#queue = [];
|
|
97
|
+
for (const entry of waiting)
|
|
98
|
+
entry.reject(undelivered(entry.kind));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function undelivered(kind) {
|
|
102
|
+
return new SdkError("undelivered_message", `the ${kind === "steer" ? "steer" : "follow-up"} was not applied: the run ended before its next step boundary`);
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=steering.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"steering.js","sourceRoot":"","sources":["../src/steering.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAiCvC,wFAAwF;AACxF,SAAS,UAAU,CAAC,KAAc;IAChC,MAAM,SAAS,GAAG,KAAuF,CAAC;IAC1G,IAAI,SAAS,EAAE,IAAI,KAAK,MAAM,IAAI,OAAO,SAAS,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;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,CAAC,IAAkB;IACrC,OAAO,IAAI,QAAQ,CACjB,qBAAqB,EACrB,OAAO,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,+DAA+D,CAC/G,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Steering and follow-up (SDK plan §3.3). A caller queues a user message while a run goes on; the loop applies it\n * only at a step boundary, so a running model call or tool batch is never cut. A steer is applied before the run's\n * next model call. A follow-up waits until the run would otherwise end. Each queued message returns a receipt once\n * it has entered the transcript.\n */\nimport type { ContentBlock } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\n\n/** Whether a message steers the run now or follows up once it would otherwise end. */\nexport type DeliveryKind = \"steer\" | \"follow_up\";\n\n/**\n * Proof that a queued message entered the transcript. `id` is unique within the run, `message` is the content the\n * run added as a user message, and `stepIndex` is the step at whose start the run added it. That step's model call is\n * the first to see the message, unless the run ends before the call, which a budget stop or a failed hook can cause.\n */\nexport interface DeliveryReceipt {\n readonly id: string;\n readonly kind: DeliveryKind;\n readonly message: readonly ContentBlock[];\n readonly stepIndex: number;\n}\n\ninterface Queued {\n readonly id: string;\n readonly kind: DeliveryKind;\n readonly message: readonly ContentBlock[];\n readonly resolve: (receipt: DeliveryReceipt) => void;\n readonly reject: (error: unknown) => void;\n}\n\n/** A message the loop took from the queue, with the function that settles its receipt. */\nexport interface Delivery {\n readonly kind: DeliveryKind;\n readonly message: readonly ContentBlock[];\n /** Settles the receipt once the message is in the transcript. */\n readonly deliver: (stepIndex: number) => DeliveryReceipt;\n}\n\n/** A copy of one block of a steering message that holds only the block's own fields. */\nfunction checkBlock(block: unknown): ContentBlock {\n const candidate = block as { type?: unknown; text?: unknown; mediaType?: unknown; data?: unknown } | null;\n if (candidate?.type === \"text\" && typeof candidate.text === \"string\") {\n // Providers refuse an empty text block, so it is refused here rather than failing the next model call.\n if (candidate.text.trim().length === 0) {\n throw new SdkError(\"invalid_run_options\", \"a steering message's text block must not be empty\");\n }\n return { type: \"text\", text: candidate.text };\n }\n if (candidate?.type === \"image\" && typeof candidate.mediaType === \"string\" && typeof candidate.data === \"string\") {\n return { type: \"image\", mediaType: candidate.mediaType, data: candidate.data };\n }\n throw new SdkError(\"invalid_run_options\", \"a steering message holds only text and image blocks\");\n}\n\n/** The content of a steering message: a string that isn't blank, or a non-empty list of text and image blocks. */\nfunction contentOf(message: unknown): ContentBlock[] {\n if (typeof message === \"string\") {\n if (message.trim().length === 0) throw new SdkError(\"invalid_run_options\", \"a steering message must not be empty\");\n return [{ type: \"text\", text: message }];\n }\n if (!Array.isArray(message) || message.length === 0) {\n throw new SdkError(\"invalid_run_options\", \"a steering message must be a string or a non-empty list of blocks\");\n }\n return message.map(checkBlock);\n}\n\n/**\n * The queue between a caller and the loop. The caller adds with `steer()` and `followUp()`; the loop takes with\n * `take()` at a step boundary, and closes the queue when the run has its outcome.\n */\nexport class SteeringQueue {\n readonly #runId: string;\n #queue: Queued[] = [];\n #count = 0;\n #closed = false;\n\n constructor(runId: string) {\n this.#runId = runId;\n }\n\n /**\n * Queues a message. The promise rejects, never throws, for an unusable message or a run that has ended. A caller who\n * ignores the promise must not crash the process when the run ends first, so a rejection is always marked handled;\n * a caller who awaits it still sees it.\n */\n add(kind: DeliveryKind, message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n const receipt = this.#enqueue(kind, message);\n receipt.catch(() => undefined);\n return receipt;\n }\n\n #enqueue(kind: DeliveryKind, message: string | readonly ContentBlock[]): Promise<DeliveryReceipt> {\n let content: ContentBlock[];\n try {\n content = contentOf(message);\n } catch (error) {\n return Promise.reject(error);\n }\n if (this.#closed) return Promise.reject(undelivered(kind));\n this.#count += 1;\n const id = `${this.#runId}:message-${this.#count}`;\n return new Promise<DeliveryReceipt>((resolve, reject) => {\n this.#queue.push({ id, kind, message: content, resolve, reject });\n });\n }\n\n /** True while a steer is waiting. */\n hasSteers(): boolean {\n return this.#queue.some((entry) => entry.kind === \"steer\");\n }\n\n /** True while any message is waiting. */\n hasPending(): boolean {\n return this.#queue.length > 0;\n }\n\n /**\n * Removes and returns the waiting steers, and the waiting follow-ups too when `withFollowUps` is set, all in the\n * order they were sent.\n */\n take(withFollowUps: boolean): Delivery[] {\n const taken = this.#queue.filter((entry) => withFollowUps || entry.kind === \"steer\");\n this.#queue = this.#queue.filter((entry) => !taken.includes(entry));\n return taken.map((entry) => ({\n kind: entry.kind,\n message: entry.message,\n deliver: (stepIndex) => {\n const receipt: DeliveryReceipt = { id: entry.id, kind: entry.kind, message: entry.message, stepIndex };\n entry.resolve(receipt);\n return receipt;\n },\n }));\n }\n\n /** Ends the queue: every message still waiting is rejected, and later calls are too. */\n close(): void {\n this.#closed = true;\n const waiting = this.#queue;\n this.#queue = [];\n for (const entry of waiting) entry.reject(undelivered(entry.kind));\n }\n}\n\nfunction undelivered(kind: DeliveryKind): SdkError {\n return new SdkError(\n \"undelivered_message\",\n `the ${kind === \"steer\" ? \"steer\" : \"follow-up\"} was not applied: the run ended before its next step boundary`,\n );\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":"sc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AC;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;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,G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K 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 @@
|
|
|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C;QAAE,OAAO,KAAK,CAAC;IACrF,kHAAkH;IAClH,6BAA6B;IAC7B,IAAI,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5E,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,KAAK,KAAK,MAAM;QAAE,OAAO,IAAI,CAAC;IAClC,IAAI,KAAK,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IACpC,OAAO,KAAK,CAAC;AACf,CAAC;AAED,2GAA2G;AAC3G,MAAM,UAAU,WAAW,CAAC,KAAc,EAAE,MAAe;IACzD,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACvE,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,QAAQ;YACX,OAAO,YAAY,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrC,KAAK,OAAO;YACV,OAAO,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACpC,KAAK,QAAQ;YACX,OAAO,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACpC,KAAK,SAAS;YACZ,OAAO,YAAY,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACnC,KAAK,SAAS;YACZ,OAAO,aAAa,CAAC,KAAK,CAAC,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,54 @@
|
|
|
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, `executionMode` is neither `parallel` nor `sequential`, `resourceKey` or `progressKey` is not a function,
|
|
21
|
+
* a raw JSON Schema does not compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe
|
|
22
|
+
* itself as JSON Schema.
|
|
23
|
+
*/
|
|
24
|
+
export declare function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S>;
|
|
25
|
+
/** The options of `outputTool()`. */
|
|
26
|
+
export interface OutputToolOptions<S> {
|
|
27
|
+
readonly name: string;
|
|
28
|
+
/** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */
|
|
29
|
+
readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;
|
|
30
|
+
/** Defaults to a line asking the model to call the tool once, with its final answer. */
|
|
31
|
+
readonly description?: string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the
|
|
35
|
+
* validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model
|
|
36
|
+
* as an error result, so the model can correct the answer and call again.
|
|
37
|
+
*/
|
|
38
|
+
export declare function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S>;
|
|
39
|
+
/** The options of `clarificationTool()`. */
|
|
40
|
+
export interface ClarificationToolOptions {
|
|
41
|
+
/** Defaults to `ask_user`. */
|
|
42
|
+
readonly name?: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
|
|
46
|
+
* `clarification`: the run signs a clarification request for the call, which gets no result, and ends
|
|
47
|
+
* `clarification_requested`. Pass the user's answer to `continueRun()` as `{ requestId, answer }`, and the model reads
|
|
48
|
+
* the answer as the call's result.
|
|
49
|
+
*/
|
|
50
|
+
export declare function clarificationTool(options?: ClarificationToolOptions): ToolDefinition<{
|
|
51
|
+
question: string;
|
|
52
|
+
}, never>;
|
|
53
|
+
/** The tool as one model call sends it: its name, description and input JSON Schema. */
|
|
54
|
+
export declare function toWireTool(tool: ToolDefinition<unknown, unknown>): WireTool;
|