@buildanagent/sdk 0.1.0-alpha.7 → 0.1.0-alpha.9
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 +91 -4
- package/dist/compose.d.ts +2 -1
- package/dist/compose.js +10 -4
- package/dist/compose.js.map +1 -1
- package/dist/errors.d.ts +2 -1
- package/dist/errors.js +2 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +18 -4
- package/dist/events.js +1 -0
- package/dist/events.js.map +1 -1
- package/dist/hook-checks.js +17 -0
- package/dist/hook-checks.js.map +1 -1
- package/dist/hook-runner.d.ts +10 -0
- package/dist/hook-runner.js +86 -9
- package/dist/hook-runner.js.map +1 -1
- package/dist/hooks.d.ts +9 -4
- package/dist/hooks.js.map +1 -1
- package/dist/index.d.ts +9 -3
- package/dist/index.js +7 -2
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +5 -0
- package/dist/loop.js +26 -3
- package/dist/loop.js.map +1 -1
- 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 +32 -0
- package/dist/pauses.js +46 -0
- package/dist/pauses.js.map +1 -0
- package/dist/result.d.ts +27 -3
- package/dist/result.js.map +1 -1
- package/dist/run.d.ts +19 -3
- package/dist/run.js +17 -1
- package/dist/run.js.map +1 -1
- package/dist/tools/pipeline.d.ts +19 -3
- package/dist/tools/pipeline.js +24 -5
- package/dist/tools/pipeline.js.map +1 -1
- 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 +8 -4
- package/dist/vendor/agent-safety/errors.js +2 -2
- package/dist/vendor/agent-safety/errors.js.map +1 -1
- package/dist/vendor/agent-safety/hash.js +3 -2
- package/dist/vendor/agent-safety/hash.js.map +1 -1
- 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/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/package.json +4 -2
package/dist/run.js.map
CHANGED
|
@@ -1 +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,EAA2C,aAAa,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAExG,OAAO,EAAwB,aAAa,EAAE,MAAM,eAAe,CAAC;AAEpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAGrD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,sDAAsD;AACtD,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAE7B,gHAAgH;AAChH,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAE5B,0FAA0F;AAC1F,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAC3C,oGAAoG;AACpG,MAAM,YAAY,GAAG,aAAa,CAAC;AAEnC,MAAM,WAAW,GAAU,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC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, 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 { type ProgressCheck, type ProgressPolicy, progressCheck, resolveProgress } from \"./progress.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.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 { 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 /** 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 its\n * 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 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 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 return {\n runId: (options.idGenerator ?? randomIds)(),\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 */\nexport function continueRun<S = unknown>(context: Context, options: RunOptions<S>): Run<S> {\n return new RunHandle<S>(setupOf(options, context, []), 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"]}
|
|
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,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAA2C,aAAa,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAExG,OAAO,EAAwB,aAAa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,EAAE,OAAO,CAAC,OAAO,IAAI,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;IACrG,OAAO,IAAI,SAAS,CAAI,KAAK,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AACvE,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAc,OAAgB,EAAE,OAAsB;IAC/E,iHAAiH;IACjH,8GAA8G;IAC9G,IAAI,OAAO,EAAE,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACjE,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,gEAAgE,CAAC,CAAC;IAC9G,CAAC;IACD,OAAO,IAAI,SAAS,CAAI,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AAC/F,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 { isSigner } from \"./pauses.js\";\nimport { type ProgressCheck, type ProgressPolicy, progressCheck, resolveProgress } from \"./progress.js\";\nimport type { Context, DoneResult, RunResult } from \"./result.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 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 `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 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 * Throws an `SdkError` with code `invalid_run_options` for a context with `pending` requests, which this version\n * can't resume yet.\n */\nexport function continueRun<S = unknown>(context: Context, options: RunOptions<S>): Run<S> {\n // Resuming a pause needs its resolutions checked against their signed requests first. Until continueRun() can do\n // that, a paused context is refused, so a call that waits for a person is never silently dropped or answered.\n if (context?.pending !== undefined && context.pending.length > 0) {\n throw new SdkError(\"invalid_run_options\", \"continueRun() can't resume a context with pending requests yet\");\n }\n return new RunHandle<S>(setupOf(options, context, []), 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"]}
|
package/dist/tools/pipeline.d.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import type { AssistantMessage, ModelContent } from "@buildanagent/gateway";
|
|
12
12
|
import type { Clock } from "../testing/determinism.js";
|
|
13
|
+
import type { SignedPendingRequest } from "../vendor/agent-safety/pending.js";
|
|
13
14
|
import type { ToolCall, ToolDefinition, ToolResult } from "./types.js";
|
|
14
15
|
/** A tool of any input and structured type, as the pipeline holds it. */
|
|
15
16
|
export type AnyTool = ToolDefinition<unknown, unknown>;
|
|
@@ -22,9 +23,10 @@ export interface PipelineContext {
|
|
|
22
23
|
readonly clock: Clock;
|
|
23
24
|
/**
|
|
24
25
|
* The gate: asked once for each call that passed validation, one call at a time in model order, and before any call
|
|
25
|
-
* of the step executes. It returns `{ blocked }` to stop the call with that result, `{ input }` to
|
|
26
|
-
*
|
|
27
|
-
* is
|
|
26
|
+
* of the step executes. It returns `{ blocked }` to stop the call with that result, `{ paused, input }` to hold the
|
|
27
|
+
* call for a person with no result at all, with the signed request and the input it signs, `{ input }` to run it
|
|
28
|
+
* with another input, which must pass the tool's schema, or `undefined` to let it run as it is. Without a gate every
|
|
29
|
+
* call is allowed.
|
|
28
30
|
*/
|
|
29
31
|
gate?(e: {
|
|
30
32
|
readonly call: ToolCall;
|
|
@@ -51,6 +53,11 @@ export interface PipelineContext {
|
|
|
51
53
|
* in the same message throws.
|
|
52
54
|
*/
|
|
53
55
|
onResult?(entry: ToolCallResult): void;
|
|
56
|
+
/**
|
|
57
|
+
* Receives each call the gate paused, with its signed request and the input that request signs, in model order and
|
|
58
|
+
* only once every call of the message has been gated.
|
|
59
|
+
*/
|
|
60
|
+
onPause?(entry: PausedCall): void;
|
|
54
61
|
/**
|
|
55
62
|
* Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write
|
|
56
63
|
* may have happened even when its result then throws an `SdkError`.
|
|
@@ -60,9 +67,18 @@ export interface PipelineContext {
|
|
|
60
67
|
/** What a gate decides besides letting a call run unchanged. */
|
|
61
68
|
export type GateOutcome = {
|
|
62
69
|
readonly blocked: ToolResult;
|
|
70
|
+
} | {
|
|
71
|
+
readonly paused: SignedPendingRequest;
|
|
72
|
+
readonly input: unknown;
|
|
63
73
|
} | {
|
|
64
74
|
readonly input: unknown;
|
|
65
75
|
};
|
|
76
|
+
/** A tool call a gate paused: its signed request, and the input the request signs. */
|
|
77
|
+
export interface PausedCall {
|
|
78
|
+
readonly call: ToolCall;
|
|
79
|
+
readonly request: SignedPendingRequest;
|
|
80
|
+
readonly input: unknown;
|
|
81
|
+
}
|
|
66
82
|
/** One tool call and the result the model will read for it. */
|
|
67
83
|
export interface ToolCallResult {
|
|
68
84
|
readonly call: ToolCall;
|
package/dist/tools/pipeline.js
CHANGED
|
@@ -164,7 +164,7 @@ async function gateCall(call, tool, input, ctx) {
|
|
|
164
164
|
const outcome = await ctx.gate?.({ call, tool, input });
|
|
165
165
|
if (outcome === undefined)
|
|
166
166
|
return { input };
|
|
167
|
-
if ("blocked" in outcome)
|
|
167
|
+
if ("blocked" in outcome || "paused" in outcome)
|
|
168
168
|
return outcome;
|
|
169
169
|
const checked = await preparedSchemaOf(tool).validate(outcome.input);
|
|
170
170
|
if (!checked.ok) {
|
|
@@ -202,6 +202,8 @@ async function prepareCall(call, early, byName, ctx) {
|
|
|
202
202
|
const gated = await gateCall(call, tool, checked.input, ctx);
|
|
203
203
|
if ("blocked" in gated)
|
|
204
204
|
return { kind: "done", call, result: gated.blocked };
|
|
205
|
+
if ("paused" in gated)
|
|
206
|
+
return { kind: "paused", call, tool, request: gated.paused, input: gated.input };
|
|
205
207
|
const replaced = "replaced" in gated;
|
|
206
208
|
return { kind: "ready", call, tool, input: gated.input, replaced, key: resourceKeyOf(tool, gated.input) };
|
|
207
209
|
}
|
|
@@ -246,14 +248,20 @@ function start(prepared, sequential, ctx, batch) {
|
|
|
246
248
|
run: () => runReady(item, ctx, batch),
|
|
247
249
|
})), sequential);
|
|
248
250
|
const byItem = new Map(ready.map((item, index) => [item, scheduled[index]]));
|
|
249
|
-
return prepared.map((item) =>
|
|
250
|
-
|
|
251
|
+
return prepared.map((item) => {
|
|
252
|
+
if (item.kind === "paused")
|
|
253
|
+
return undefined;
|
|
254
|
+
if (item.kind === "done")
|
|
255
|
+
return Promise.resolve({ ok: true, value: item.result });
|
|
256
|
+
return byItem.get(item);
|
|
257
|
+
});
|
|
251
258
|
}
|
|
252
259
|
/**
|
|
253
260
|
* Runs the calls of one step. Each call is checked and gated one at a time, in model order, before any call executes.
|
|
254
261
|
* The calls that passed then start together, except that a call to a sequential tool makes the whole step run one
|
|
255
262
|
* call at a time, even when that call itself fails a check, and calls that share a `resourceKey` queue in model
|
|
256
|
-
* order. Results reach `ctx.onResult` in model order, each as soon as every result before it is in.
|
|
263
|
+
* order. Results reach `ctx.onResult` in model order, each as soon as every result before it is in. A call the gate
|
|
264
|
+
* paused gets no result and is left out; each one reaches `ctx.onPause`, in model order, once every call is gated.
|
|
257
265
|
*
|
|
258
266
|
* A programmer error (an `SdkError`) in one call fires the signal the other calls hold, waits for them to stop, and
|
|
259
267
|
* is then thrown, after every other call's result has been passed on: a call after the failing one may have run and
|
|
@@ -272,6 +280,7 @@ async function runCalls(calls, early, tools, ctx) {
|
|
|
272
280
|
catch (error) {
|
|
273
281
|
// None of these calls has executed, and none will. The first error is the one thrown, so a receiver that throws
|
|
274
282
|
// here must not hide it or stop the other calls from getting their results.
|
|
283
|
+
// A paused call gets a not-run result here too: the run is failing, so its pause is never reported or returned.
|
|
275
284
|
for (const item of prepared) {
|
|
276
285
|
const result = item.kind === "done" ? item.result : notRun(item.call, item.tool, "sibling_failed");
|
|
277
286
|
try {
|
|
@@ -283,6 +292,12 @@ async function runCalls(calls, early, tools, ctx) {
|
|
|
283
292
|
}
|
|
284
293
|
throw error;
|
|
285
294
|
}
|
|
295
|
+
// Reported only now, once every call has been gated, so a step that fails while its calls are checked never reports
|
|
296
|
+
// a pause and then gives the same call a result.
|
|
297
|
+
for (const item of prepared) {
|
|
298
|
+
if (item.kind === "paused")
|
|
299
|
+
ctx.onPause?.({ call: item.call, request: item.request, input: item.input });
|
|
300
|
+
}
|
|
286
301
|
const sequential = calls.some((call) => byName.get(call.name)?.executionMode === "sequential");
|
|
287
302
|
const { batch, release } = batchController(ctx.signal);
|
|
288
303
|
try {
|
|
@@ -300,6 +315,8 @@ async function deliver(prepared, running, ctx, batch) {
|
|
|
300
315
|
const results = [];
|
|
301
316
|
let failure;
|
|
302
317
|
for (const [index, pending] of running.entries()) {
|
|
318
|
+
if (pending === undefined)
|
|
319
|
+
continue;
|
|
303
320
|
const settled = await pending;
|
|
304
321
|
if (!settled.ok) {
|
|
305
322
|
failure ??= { error: settled.error };
|
|
@@ -327,8 +344,10 @@ async function deliver(prepared, running, ctx, batch) {
|
|
|
327
344
|
* an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.
|
|
328
345
|
*/
|
|
329
346
|
export async function runToolCall(call, tools, ctx) {
|
|
330
|
-
const { onStart: _start, onResult: _result, ...quiet } = ctx;
|
|
347
|
+
const { onStart: _start, onResult: _result, onPause: _pause, ...quiet } = ctx;
|
|
331
348
|
const [entry] = await runCalls([call], () => undefined, tools, quiet);
|
|
349
|
+
if (entry === undefined)
|
|
350
|
+
throw new SdkError("invalid_hook_result", `runToolCall() can't pause the call "${call.name}"`);
|
|
332
351
|
return entry.result;
|
|
333
352
|
}
|
|
334
353
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/tools/pipeline.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MA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C,CAAC;IAC/F,OAAO,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AACjF,CAAC","sourcesContent":["/**\n * The tool pipeline: the fixed steps every tool call runs (agent-SDK guide §4). Resolve the name, coerce, validate,\n * an optional `repair`, the gate, `execute`, the write outcome, then `afterToolCall`. A failure the model caused\n * becomes an error result and never throws; only a programmer error, such as a malformed tool result, throws an\n * `SdkError`.\n *\n * The gate runs after validation and `after` runs after `execute`. The run's interceptors fill them (`beforeToolCall`\n * and `afterToolCall`), and a pipeline without them allows every call and keeps every result. A step's calls are\n * checked and gated one at a time, in model order, and then scheduled together (see `runCalls`).\n */\nimport type { AssistantMessage, ModelContent } from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport { coerceValue } from \"./coerce.js\";\nimport { preparedSchemaOf } from \"./define.js\";\nimport { formatToolError, REDACTED_MESSAGE } from \"./format-error.js\";\nimport { withOutcome } from \"./outcome.js\";\nimport { type Settled, schedule } from \"./scheduler.js\";\nimport type { ToolCall, ToolDefinition, ToolFailure, ToolResult } from \"./types.js\";\n\n/** A tool of any input and structured type, as the pipeline holds it. */\nexport type AnyTool = ToolDefinition<unknown, unknown>;\n\n/** What the pipeline needs from the run around it. */\nexport interface PipelineContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly depth: number;\n readonly maxDepth: number;\n readonly clock: Clock;\n /**\n * The gate: asked once for each call that passed validation, one call at a time in model order, and before any call\n * of the step executes. It returns `{ blocked }` to stop the call with that result, `{ input }` to run it with\n * another input, which must pass the tool's schema, or `undefined` to let it run as it is. Without a gate every call\n * is allowed.\n */\n gate?(e: {\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n }): Promise<GateOutcome | undefined>;\n /**\n * Called with the result of each call that executed, and returns the result to use in its place. It runs inside the\n * call's own task, so a sibling is never left running while it works, and a programmer error it throws cancels the\n * siblings like one from `execute`.\n */\n after?(e: {\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n readonly result: ToolResult;\n }): Promise<ToolResult>;\n /** Called for each call of a message before its result is worked out, whether or not the call will run. */\n onStart?(call: ToolCall): void;\n /** Receives a tool's progress updates. */\n onUpdate?(callId: string, details: unknown): void;\n /**\n * Receives each call's result as soon as `runToolCalls` has it, so the run can record a write before a later call\n * in the same message throws.\n */\n onResult?(entry: ToolCallResult): void;\n /**\n * Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write\n * may have happened even when its result then throws an `SdkError`.\n */\n onExecuted?(call: ToolCall): void;\n}\n\n/** What a gate decides besides letting a call run unchanged. */\nexport type GateOutcome = { readonly blocked: ToolResult } | { readonly input: unknown };\n\n/** One tool call and the result the model will read for it. */\nexport interface ToolCallResult {\n readonly call: ToolCall;\n readonly result: ToolResult;\n /** The input the gate put in place of the model's, present only when the gate replaced it. */\n readonly input?: unknown;\n}\n\nfunction toolsByName(tools: readonly AnyTool[]): ReadonlyMap<string, AnyTool> {\n const byName = new Map<string, AnyTool>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (byName.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n byName.set(tool.name, tool);\n }\n return byName;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isModelContent(block: unknown): block is ModelContent {\n if (typeof block !== \"object\" || block === null) return false;\n const { type, text, mediaType, data } = block as Record<string, unknown>;\n if (type === \"text\") return typeof text === \"string\";\n return type === \"image\" && typeof mediaType === \"string\" && typeof data === \"string\";\n}\n\n/** True for a list of text and image blocks, the only content a tool result may carry. */\nexport function isContentList(content: unknown): content is readonly ModelContent[] {\n return Array.isArray(content) && content.every(isModelContent);\n}\n\ntype Formatted = { readonly content: readonly ModelContent[]; readonly error?: string };\n\n// A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so\n// the default text is used instead, and the formatter's error is kept in `details`.\nfunction formatted(failure: ToolFailure, tool: AnyTool | undefined): Formatted {\n const fallback = formatToolError(failure);\n if (tool?.formatError === undefined) return { content: fallback };\n let content: unknown;\n try {\n content = tool.formatError(failure);\n } catch (error) {\n return { content: fallback, error: errorMessage(error) };\n }\n if (isContentList(content)) return { content };\n return { content: fallback, error: \"formatError did not return a list of text and image blocks\" };\n}\n\nfunction failed(failure: ToolFailure, tool: AnyTool | undefined, details: Record<string, unknown> = {}): ToolResult {\n const { content, error: formatterError } = formatted(failure, tool);\n return {\n content,\n isError: true,\n details: { failure, ...details, ...(formatterError === undefined ? {} : { formatterError }) },\n };\n}\n\ntype Checked = { readonly ok: true; readonly input: unknown } | { readonly ok: false; readonly result: ToolResult };\n\n// Coerce, validate, and on failure give `repair` one chance. The model sees the issues of its own arguments, and\n// `details` keeps what repair returned.\nasync function checkInput(tool: AnyTool, call: ToolCall): Promise<Checked> {\n const schema = preparedSchemaOf(tool);\n const coerced = coerceValue(call.input, schema.jsonSchema);\n const first = await schema.validate(coerced);\n if (first.ok) return { ok: true, input: first.value };\n const failure: ToolFailure = {\n kind: \"invalid_input\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n issues: first.issues,\n };\n if (tool.repair === undefined) return { ok: false, result: failed(failure, tool) };\n let repaired: unknown;\n try {\n repaired = await tool.repair({ input: coerced, issues: first.issues });\n } catch (error) {\n return { ok: false, result: failed(failure, tool, { repairError: errorMessage(error) }) };\n }\n if (repaired === undefined) return { ok: false, result: failed(failure, tool) };\n const second = await schema.validate(coerceValue(repaired, schema.jsonSchema));\n if (second.ok) return { ok: true, input: second.value };\n return { ok: false, result: failed(failure, tool, { repaired, repairedIssues: second.issues }) };\n}\n\nfunction checkResult(tool: string, result: unknown): ToolResult {\n const content = (result as { content?: unknown } | null)?.content;\n if (typeof result !== \"object\" || result === null || !isContentList(content)) {\n throw new SdkError(\n \"invalid_tool_result\",\n `tool \"${tool}\" must return an object whose content is a list of text and image blocks`,\n );\n }\n return result as ToolResult;\n}\n\nasync function execute(tool: AnyTool, call: ToolCall, input: unknown, ctx: PipelineContext): Promise<ToolResult> {\n const context = {\n runId: ctx.runId,\n callId: call.callId,\n signal: ctx.signal,\n depth: ctx.depth,\n maxDepth: ctx.maxDepth,\n clock: ctx.clock,\n update: (details: unknown) => ctx.onUpdate?.(call.callId, details),\n };\n let result: unknown;\n try {\n result = await tool.execute(input, context);\n } catch (error) {\n ctx.onExecuted?.(call);\n const message = errorMessage(error);\n const redacted = tool.redactErrors === true;\n const failure: ToolFailure = {\n kind: \"execution_error\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n message: redacted ? REDACTED_MESSAGE : message,\n redacted,\n };\n return failed(failure, tool, { error: { name: error instanceof Error ? error.name : typeof error, message } });\n }\n ctx.onExecuted?.(call);\n return withOutcome(tool.name, checkResult(tool.name, result));\n}\n\ntype NotRunReason = Extract<ToolFailure, { kind: \"not_run\" }>[\"reason\"];\n\nfunction notRun(call: ToolCall, tool: AnyTool | undefined, reason: NotRunReason): ToolResult {\n return failed({ kind: \"not_run\", reason, tool: call.name, callId: call.callId, input: call.input }, tool);\n}\n\n// Why none of a message's calls may run, or undefined when they all may.\nfunction unrunnable(message: AssistantMessage, call: ToolCall, tools: readonly AnyTool[]): ToolResult | undefined {\n const tool = tools.find((candidate) => candidate.name === call.name);\n switch (message.stopReason) {\n case \"length\":\n return failed({ kind: \"truncated\", tool: call.name, callId: call.callId, input: call.input }, tool);\n case \"error\":\n return notRun(call, tool, \"response_error\");\n case \"aborted\":\n return notRun(call, tool, \"response_aborted\");\n default:\n return undefined;\n }\n}\n\n/** A call that passed every check before execution and now waits to be scheduled. */\ninterface Ready {\n readonly kind: \"ready\";\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n /** True when the gate replaced the model's input with `input`. */\n readonly replaced: boolean;\n readonly key: string | undefined;\n}\n\n/** A call whose result is already known: it failed a check, was gated or could not run. */\ninterface Done {\n readonly kind: \"done\";\n readonly call: ToolCall;\n readonly result: ToolResult;\n}\n\ntype Prepared = Ready | Done;\n\nfunction resourceKeyOf(tool: AnyTool, input: unknown): string | undefined {\n if (tool.resourceKey === undefined) return undefined;\n let key: unknown;\n try {\n key = tool.resourceKey(input);\n } catch (cause) {\n throw new SdkError(\"invalid_tool_definition\", `tool \"${tool.name}\": resourceKey threw: ${errorMessage(cause)}`, {\n cause,\n });\n }\n if (typeof key !== \"string\") {\n throw new SdkError(\"invalid_tool_definition\", `tool \"${tool.name}\": resourceKey must return a string`);\n }\n return key;\n}\n\n// Asks the gate about one call. A replacement input is checked against the tool's schema again, because the gate is\n// user code and a call must never run with input its own tool would have rejected.\nasync function gateCall(\n call: ToolCall,\n tool: AnyTool,\n input: unknown,\n ctx: PipelineContext,\n): Promise<{ readonly blocked: ToolResult } | { readonly input: unknown; readonly replaced?: true }> {\n const outcome = await ctx.gate?.({ call, tool, input });\n if (outcome === undefined) return { input };\n if (\"blocked\" in outcome) return outcome;\n const checked = await preparedSchemaOf(tool).validate(outcome.input);\n if (!checked.ok) {\n const issues = checked.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join(\"; \");\n throw new SdkError(\n \"invalid_hook_result\",\n `beforeToolCall replaced the input of tool \"${tool.name}\" with input its schema rejects: ${issues}`,\n );\n }\n return { input: checked.value, replaced: true };\n}\n\n// Everything that happens before execution, for one call: name, cancellation, input checks, resource key, and the\n// gate. A call that fails any of them is `Done` with the result the model reads.\nasync function prepareCall(\n call: ToolCall,\n early: ToolResult | undefined,\n byName: ReadonlyMap<string, AnyTool>,\n ctx: PipelineContext,\n): Promise<Prepared> {\n if (early !== undefined) return { kind: \"done\", call, result: early };\n const tool = byName.get(call.name);\n if (tool === undefined) {\n const availableTools = [...byName.keys()];\n const failure: ToolFailure = {\n kind: \"unknown_tool\",\n tool: call.name,\n callId: call.callId,\n input: call.input,\n availableTools,\n };\n return { kind: \"done\", call, result: failed(failure, undefined) };\n }\n // Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.\n if (ctx.signal.aborted) return { kind: \"done\", call, result: notRun(call, tool, \"run_aborted\") };\n const checked = await checkInput(tool, call);\n if (!checked.ok) return { kind: \"done\", call, result: checked.result };\n if (ctx.signal.aborted) return { kind: \"done\", call, result: notRun(call, tool, \"run_aborted\") };\n // Each call's gate settles before the next call's is asked, and every gate before any call executes.\n const gated = await gateCall(call, tool, checked.input, ctx);\n if (\"blocked\" in gated) return { kind: \"done\", call, result: gated.blocked };\n const replaced = \"replaced\" in gated;\n return { kind: \"ready\", call, tool, input: gated.input, replaced, key: resourceKeyOf(tool, gated.input) };\n}\n\n// Only a first-party tool's hint counts: an MCP server's annotations are claims by someone we don't control. A tool\n// with an `effect` changes the world whatever its hint says, so it always queues as a writer.\nfunction isTrustedReadOnly(tool: AnyTool): boolean {\n return tool.firstParty === true && tool.annotations?.readOnlyHint === true && tool.effect === undefined;\n}\n\n// Relays the run's cancellation to the signal the batch's tools receive, which a failing sibling can also fire.\nfunction batchController(runSignal: AbortSignal): { batch: AbortController; release(): void } {\n const batch = new AbortController();\n const relay = () => batch.abort(runSignal.reason);\n if (runSignal.aborted) relay();\n else runSignal.addEventListener(\"abort\", relay, { once: true });\n return { batch, release: () => runSignal.removeEventListener(\"abort\", relay) };\n}\n\n// Runs one ready call under the batch's signal. A programmer error cancels the siblings before it propagates; a\n// model-caused failure is an ordinary result and cancels nothing.\nasync function runReady(item: Ready, ctx: PipelineContext, batch: AbortController): Promise<ToolResult> {\n if (batch.signal.aborted) {\n return notRun(item.call, item.tool, ctx.signal.aborted ? \"run_aborted\" : \"sibling_failed\");\n }\n try {\n const result = await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });\n if (ctx.after === undefined) return result;\n return await ctx.after({ call: item.call, tool: item.tool, input: item.input, result });\n } catch (error) {\n batch.abort(error);\n throw error;\n }\n}\n\n// Starts every ready call by the scheduling rules and returns, in model order, the promise of each call's result.\nfunction start(\n prepared: readonly Prepared[],\n sequential: boolean,\n ctx: PipelineContext,\n batch: AbortController,\n): Promise<Settled<ToolResult>>[] {\n const ready = prepared.filter((item): item is Ready => item.kind === \"ready\");\n const scheduled = schedule(\n ready.map((item) => ({\n ...(item.key === undefined ? {} : { key: item.key }),\n readOnly: isTrustedReadOnly(item.tool),\n run: () => runReady(item, ctx, batch),\n })),\n sequential,\n );\n const byItem = new Map(ready.map((item, index) => [item, scheduled[index]]));\n return prepared.map(\n (item) =>\n (item.kind === \"done\" ? undefined : byItem.get(item)) ??\n Promise.resolve<Settled<ToolResult>>({ ok: true, value: (item as Done).result }),\n );\n}\n\n/**\n * Runs the calls of one step. Each call is checked and gated one at a time, in model order, before any call executes.\n * The calls that passed then start together, except that a call to a sequential tool makes the whole step run one\n * call at a time, even when that call itself fails a check, and calls that share a `resourceKey` queue in model\n * order. Results reach `ctx.onResult` in model order, each as soon as every result before it is in.\n *\n * A programmer error (an `SdkError`) in one call fires the signal the other calls hold, waits for them to stop, and\n * is then thrown, after every other call's result has been passed on: a call after the failing one may have run and\n * written. A programmer error while the calls are checked, such as a `resourceKey` that throws, is thrown after the\n * calls already checked get their results, so every call that started has one, except the call that failed.\n */\nasync function runCalls(\n calls: readonly ToolCall[],\n early: (call: ToolCall) => ToolResult | undefined,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const byName = toolsByName(tools);\n const prepared: Prepared[] = [];\n try {\n for (const call of calls) {\n ctx.onStart?.(call);\n prepared.push(await prepareCall(call, early(call), byName, ctx));\n }\n } catch (error) {\n // None of these calls has executed, and none will. The first error is the one thrown, so a receiver that throws\n // here must not hide it or stop the other calls from getting their results.\n for (const item of prepared) {\n const result = item.kind === \"done\" ? item.result : notRun(item.call, item.tool, \"sibling_failed\");\n try {\n ctx.onResult?.({ call: item.call, result });\n } catch {\n // Not rethrown: the error being handled is thrown below.\n }\n }\n throw error;\n }\n const sequential = calls.some((call) => byName.get(call.name)?.executionMode === \"sequential\");\n const { batch, release } = batchController(ctx.signal);\n try {\n return await deliver(prepared, start(prepared, sequential, ctx, batch), ctx, batch);\n } finally {\n release();\n }\n}\n\n// Passes each result on in model order, as soon as every result before it is in. A failed call has already cancelled\n// the others; the loop still waits for each of them and passes its result on, so none is left running and a write\n// that happened is recorded, and then the first error is thrown. A receiver that throws is a failed call too: it\n// cancels the siblings, and the results after it are still passed on.\nasync function deliver(\n prepared: readonly Prepared[],\n running: readonly Promise<Settled<ToolResult>>[],\n ctx: PipelineContext,\n batch: AbortController,\n): Promise<ToolCallResult[]> {\n const results: ToolCallResult[] = [];\n let failure: { readonly error: unknown } | undefined;\n for (const [index, pending] of running.entries()) {\n const settled = await pending;\n if (!settled.ok) {\n failure ??= { error: settled.error };\n continue;\n }\n const item = prepared[index] as Prepared;\n const replaced = item.kind === \"ready\" && item.replaced ? { input: item.input } : {};\n const entry: ToolCallResult = { call: item.call, result: settled.value, ...replaced };\n results.push(entry);\n try {\n ctx.onResult?.(entry);\n } catch (error) {\n failure ??= { error };\n batch.abort(error);\n }\n }\n if (failure !== undefined) throw failure.error;\n return results;\n}\n\n/**\n * Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure\n * the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws\n * an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.\n */\nexport async function runToolCall(\n call: ToolCall,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolResult> {\n const { onStart: _start, onResult: _result, ...quiet } = ctx;\n const [entry] = await runCalls([call], () => undefined, tools, quiet);\n return (entry as ToolCallResult).result;\n}\n\n/**\n * Runs every tool call of an assistant message and passes each result to `ctx.onResult` in model order. A message\n * that stopped at the output limit (`stopReason: \"length\"`) runs nothing: each of its calls gets an error asking the\n * model to re-issue it, because its arguments may be cut short. A message that ended in an error or was aborted also\n * runs nothing, because its calls may be partial. Otherwise the calls are scheduled as `runCalls` describes.\n */\nexport async function runToolCalls(\n message: AssistantMessage,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const calls = message.content.filter((block): block is ToolCall => block.type === \"tool_call\");\n return runCalls(calls, (call) => unrunnable(message, call, tools), tools, ctx);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/tools/pipeline.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAGxC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAgB,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AA8ExD,SAAS,WAAW,CAAC,KAAyB;IAC5C,MAAM,MAAM,GAAG,IAAI,GAAG,EAAmB,CAAC;IAC1C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,gBAAgB,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,QAAQ,CAAC,yBAAyB,EAAE,wBAAwB,IAAI,CAAC,IAAI,8BAA8B,CAAC,CAAC;QACjH,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,c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EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AACjF,CAAC","sourcesContent":["/**\n * The tool pipeline: the fixed steps every tool call runs (agent-SDK guide §4). Resolve the name, coerce, validate,\n * an optional `repair`, the gate, `execute`, the write outcome, then `afterToolCall`. A failure the model caused\n * becomes an error result and never throws; only a programmer error, such as a malformed tool result, throws an\n * `SdkError`.\n *\n * The gate runs after validation and `after` runs after `execute`. The run's interceptors fill them (`beforeToolCall`\n * and `afterToolCall`), and a pipeline without them allows every call and keeps every result. A step's calls are\n * checked and gated one at a time, in model order, and then scheduled together (see `runCalls`).\n */\nimport type { AssistantMessage, ModelContent } from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport type { SignedPendingRequest } from \"../vendor/agent-safety/pending.js\";\nimport { coerceValue } from \"./coerce.js\";\nimport { preparedSchemaOf } from \"./define.js\";\nimport { formatToolError, REDACTED_MESSAGE } from \"./format-error.js\";\nimport { withOutcome } from \"./outcome.js\";\nimport { type Settled, schedule } from \"./scheduler.js\";\nimport type { ToolCall, ToolDefinition, ToolFailure, ToolResult } from \"./types.js\";\n\n/** A tool of any input and structured type, as the pipeline holds it. */\nexport type AnyTool = ToolDefinition<unknown, unknown>;\n\n/** What the pipeline needs from the run around it. */\nexport interface PipelineContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly depth: number;\n readonly maxDepth: number;\n readonly clock: Clock;\n /**\n * The gate: asked once for each call that passed validation, one call at a time in model order, and before any call\n * of the step executes. It returns `{ blocked }` to stop the call with that result, `{ paused, input }` to hold the\n * call for a person with no result at all, with the signed request and the input it signs, `{ input }` to run it\n * with another input, which must pass the tool's schema, or `undefined` to let it run as it is. Without a gate every\n * call is allowed.\n */\n gate?(e: {\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n }): Promise<GateOutcome | undefined>;\n /**\n * Called with the result of each call that executed, and returns the result to use in its place. It runs inside the\n * call's own task, so a sibling is never left running while it works, and a programmer error it throws cancels the\n * siblings like one from `execute`.\n */\n after?(e: {\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n readonly result: ToolResult;\n }): Promise<ToolResult>;\n /** Called for each call of a message before its result is worked out, whether or not the call will run. */\n onStart?(call: ToolCall): void;\n /** Receives a tool's progress updates. */\n onUpdate?(callId: string, details: unknown): void;\n /**\n * Receives each call's result as soon as `runToolCalls` has it, so the run can record a write before a later call\n * in the same message throws.\n */\n onResult?(entry: ToolCallResult): void;\n /**\n * Receives each call the gate paused, with its signed request and the input that request signs, in model order and\n * only once every call of the message has been gated.\n */\n onPause?(entry: PausedCall): void;\n /**\n * Called as soon as a tool's `execute` returns or throws, before the result is checked, so the run knows a write\n * may have happened even when its result then throws an `SdkError`.\n */\n onExecuted?(call: ToolCall): void;\n}\n\n/** What a gate decides besides letting a call run unchanged. */\nexport type GateOutcome =\n | { readonly blocked: ToolResult }\n | { readonly paused: SignedPendingRequest; readonly input: unknown }\n | { readonly input: unknown };\n\n/** A tool call a gate paused: its signed request, and the input the request signs. */\nexport interface PausedCall {\n readonly call: ToolCall;\n readonly request: SignedPendingRequest;\n readonly input: unknown;\n}\n\n/** One tool call and the result the model will read for it. */\nexport interface ToolCallResult {\n readonly call: ToolCall;\n readonly result: ToolResult;\n /** The input the gate put in place of the model's, present only when the gate replaced it. */\n readonly input?: unknown;\n}\n\nfunction toolsByName(tools: readonly AnyTool[]): ReadonlyMap<string, AnyTool> {\n const byName = new Map<string, AnyTool>();\n for (const tool of tools) {\n preparedSchemaOf(tool);\n if (byName.has(tool.name)) {\n throw new SdkError(\"invalid_tool_definition\", `two tools are named \"${tool.name}\"; tool names must be unique`);\n }\n byName.set(tool.name, tool);\n }\n return byName;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isModelContent(block: unknown): block is ModelContent {\n if (typeof block !== \"object\" || block === null) return false;\n const { type, text, mediaType, data } = block as Record<string, unknown>;\n if (type === \"text\") return typeof text === \"string\";\n return type === \"image\" && typeof mediaType === \"string\" && typeof data === \"string\";\n}\n\n/** True for a list of text and image blocks, the only content a tool result may carry. */\nexport function isContentList(content: unknown): content is readonly ModelContent[] {\n return Array.isArray(content) && content.every(isModelContent);\n}\n\ntype Formatted = { readonly content: readonly ModelContent[]; readonly error?: string };\n\n// A formatter that throws, or returns something the model can't read, must not hide the failure from the model, so\n// the default text is used instead, and the formatter's error is kept in `details`.\nfunction formatted(failure: ToolFailure, tool: AnyTool | undefined): Formatted {\n const fallback = formatToolError(failure);\n if (tool?.formatError === undefined) return { content: fallback };\n let content: unknown;\n try {\n content = tool.formatError(failure);\n } catch (error) {\n return { content: fallback, error: errorMessage(error) };\n }\n if (isContentList(content)) return { content };\n return { content: fallback, error: \"formatError did not return a list of text and image blocks\" };\n}\n\nfunction failed(failure: ToolFailure, tool: AnyTool | undefined, details: Record<string, unknown> = {}): ToolResult {\n const { content, error: formatterError } = formatted(failure, tool);\n return {\n content,\n isError: true,\n details: { failure, ...details, ...(formatterError === undefined ? {} : { formatterError }) },\n };\n}\n\ntype Checked = { readonly ok: true; readonly input: unknown } | { readonly ok: false; readonly result: ToolResult };\n\n// Coerce, validate, and on failure give `repair` one chance. The model sees the issues of its own arguments, and\n// `details` keeps what repair returned.\nasync function checkInput(tool: AnyTool, call: ToolCall): Promise<Checked> {\n const schema = preparedSchemaOf(tool);\n const coerced = coerceValue(call.input, schema.jsonSchema);\n const first = await schema.validate(coerced);\n if (first.ok) return { ok: true, input: first.value };\n const failure: ToolFailure = {\n kind: \"invalid_input\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n issues: first.issues,\n };\n if (tool.repair === undefined) return { ok: false, result: failed(failure, tool) };\n let repaired: unknown;\n try {\n repaired = await tool.repair({ input: coerced, issues: first.issues });\n } catch (error) {\n return { ok: false, result: failed(failure, tool, { repairError: errorMessage(error) }) };\n }\n if (repaired === undefined) return { ok: false, result: failed(failure, tool) };\n const second = await schema.validate(coerceValue(repaired, schema.jsonSchema));\n if (second.ok) return { ok: true, input: second.value };\n return { ok: false, result: failed(failure, tool, { repaired, repairedIssues: second.issues }) };\n}\n\nfunction checkResult(tool: string, result: unknown): ToolResult {\n const content = (result as { content?: unknown } | null)?.content;\n if (typeof result !== \"object\" || result === null || !isContentList(content)) {\n throw new SdkError(\n \"invalid_tool_result\",\n `tool \"${tool}\" must return an object whose content is a list of text and image blocks`,\n );\n }\n return result as ToolResult;\n}\n\nasync function execute(tool: AnyTool, call: ToolCall, input: unknown, ctx: PipelineContext): Promise<ToolResult> {\n const context = {\n runId: ctx.runId,\n callId: call.callId,\n signal: ctx.signal,\n depth: ctx.depth,\n maxDepth: ctx.maxDepth,\n clock: ctx.clock,\n update: (details: unknown) => ctx.onUpdate?.(call.callId, details),\n };\n let result: unknown;\n try {\n result = await tool.execute(input, context);\n } catch (error) {\n ctx.onExecuted?.(call);\n const message = errorMessage(error);\n const redacted = tool.redactErrors === true;\n const failure: ToolFailure = {\n kind: \"execution_error\",\n tool: tool.name,\n callId: call.callId,\n input: call.input,\n message: redacted ? REDACTED_MESSAGE : message,\n redacted,\n };\n return failed(failure, tool, { error: { name: error instanceof Error ? error.name : typeof error, message } });\n }\n ctx.onExecuted?.(call);\n return withOutcome(tool.name, checkResult(tool.name, result));\n}\n\ntype NotRunReason = Extract<ToolFailure, { kind: \"not_run\" }>[\"reason\"];\n\nfunction notRun(call: ToolCall, tool: AnyTool | undefined, reason: NotRunReason): ToolResult {\n return failed({ kind: \"not_run\", reason, tool: call.name, callId: call.callId, input: call.input }, tool);\n}\n\n// Why none of a message's calls may run, or undefined when they all may.\nfunction unrunnable(message: AssistantMessage, call: ToolCall, tools: readonly AnyTool[]): ToolResult | undefined {\n const tool = tools.find((candidate) => candidate.name === call.name);\n switch (message.stopReason) {\n case \"length\":\n return failed({ kind: \"truncated\", tool: call.name, callId: call.callId, input: call.input }, tool);\n case \"error\":\n return notRun(call, tool, \"response_error\");\n case \"aborted\":\n return notRun(call, tool, \"response_aborted\");\n default:\n return undefined;\n }\n}\n\n/** A call that passed every check before execution and now waits to be scheduled. */\ninterface Ready {\n readonly kind: \"ready\";\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly input: unknown;\n /** True when the gate replaced the model's input with `input`. */\n readonly replaced: boolean;\n readonly key: string | undefined;\n}\n\n/** A call whose result is already known: it failed a check, was gated or could not run. */\ninterface Done {\n readonly kind: \"done\";\n readonly call: ToolCall;\n readonly result: ToolResult;\n}\n\n/** A call held for a person: it never runs in this step and gets no result, so the transcript leaves it open. */\ninterface Paused {\n readonly kind: \"paused\";\n readonly call: ToolCall;\n readonly tool: AnyTool;\n readonly request: SignedPendingRequest;\n /** The input the request signs, which the call would run with once approved. */\n readonly input: unknown;\n}\n\ntype Prepared = Ready | Done | Paused;\n\nfunction resourceKeyOf(tool: AnyTool, input: unknown): string | undefined {\n if (tool.resourceKey === undefined) return undefined;\n let key: unknown;\n try {\n key = tool.resourceKey(input);\n } catch (cause) {\n throw new SdkError(\"invalid_tool_definition\", `tool \"${tool.name}\": resourceKey threw: ${errorMessage(cause)}`, {\n cause,\n });\n }\n if (typeof key !== \"string\") {\n throw new SdkError(\"invalid_tool_definition\", `tool \"${tool.name}\": resourceKey must return a string`);\n }\n return key;\n}\n\n// Asks the gate about one call. A replacement input is checked against the tool's schema again, because the gate is\n// user code and a call must never run with input its own tool would have rejected.\nasync function gateCall(\n call: ToolCall,\n tool: AnyTool,\n input: unknown,\n ctx: PipelineContext,\n): Promise<\n | { readonly blocked: ToolResult }\n | { readonly paused: SignedPendingRequest; readonly input: unknown }\n | { readonly input: unknown; readonly replaced?: true }\n> {\n const outcome = await ctx.gate?.({ call, tool, input });\n if (outcome === undefined) return { input };\n if (\"blocked\" in outcome || \"paused\" in outcome) return outcome;\n const checked = await preparedSchemaOf(tool).validate(outcome.input);\n if (!checked.ok) {\n const issues = checked.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join(\"; \");\n throw new SdkError(\n \"invalid_hook_result\",\n `beforeToolCall replaced the input of tool \"${tool.name}\" with input its schema rejects: ${issues}`,\n );\n }\n return { input: checked.value, replaced: true };\n}\n\n// Everything that happens before execution, for one call: name, cancellation, input checks, resource key, and the\n// gate. A call that fails any of them is `Done` with the result the model reads.\nasync function prepareCall(\n call: ToolCall,\n early: ToolResult | undefined,\n byName: ReadonlyMap<string, AnyTool>,\n ctx: PipelineContext,\n): Promise<Prepared> {\n if (early !== undefined) return { kind: \"done\", call, result: early };\n const tool = byName.get(call.name);\n if (tool === undefined) {\n const availableTools = [...byName.keys()];\n const failure: ToolFailure = {\n kind: \"unknown_tool\",\n tool: call.name,\n callId: call.callId,\n input: call.input,\n availableTools,\n };\n return { kind: \"done\", call, result: failed(failure, undefined) };\n }\n // Checked before validation, so a cancelled run starts no `repair`, and again after, because `repair` may await.\n if (ctx.signal.aborted) return { kind: \"done\", call, result: notRun(call, tool, \"run_aborted\") };\n const checked = await checkInput(tool, call);\n if (!checked.ok) return { kind: \"done\", call, result: checked.result };\n if (ctx.signal.aborted) return { kind: \"done\", call, result: notRun(call, tool, \"run_aborted\") };\n // Each call's gate settles before the next call's is asked, and every gate before any call executes.\n const gated = await gateCall(call, tool, checked.input, ctx);\n if (\"blocked\" in gated) return { kind: \"done\", call, result: gated.blocked };\n if (\"paused\" in gated) return { kind: \"paused\", call, tool, request: gated.paused, input: gated.input };\n const replaced = \"replaced\" in gated;\n return { kind: \"ready\", call, tool, input: gated.input, replaced, key: resourceKeyOf(tool, gated.input) };\n}\n\n// Only a first-party tool's hint counts: an MCP server's annotations are claims by someone we don't control. A tool\n// with an `effect` changes the world whatever its hint says, so it always queues as a writer.\nfunction isTrustedReadOnly(tool: AnyTool): boolean {\n return tool.firstParty === true && tool.annotations?.readOnlyHint === true && tool.effect === undefined;\n}\n\n// Relays the run's cancellation to the signal the batch's tools receive, which a failing sibling can also fire.\nfunction batchController(runSignal: AbortSignal): { batch: AbortController; release(): void } {\n const batch = new AbortController();\n const relay = () => batch.abort(runSignal.reason);\n if (runSignal.aborted) relay();\n else runSignal.addEventListener(\"abort\", relay, { once: true });\n return { batch, release: () => runSignal.removeEventListener(\"abort\", relay) };\n}\n\n// Runs one ready call under the batch's signal. A programmer error cancels the siblings before it propagates; a\n// model-caused failure is an ordinary result and cancels nothing.\nasync function runReady(item: Ready, ctx: PipelineContext, batch: AbortController): Promise<ToolResult> {\n if (batch.signal.aborted) {\n return notRun(item.call, item.tool, ctx.signal.aborted ? \"run_aborted\" : \"sibling_failed\");\n }\n try {\n const result = await execute(item.tool, item.call, item.input, { ...ctx, signal: batch.signal });\n if (ctx.after === undefined) return result;\n return await ctx.after({ call: item.call, tool: item.tool, input: item.input, result });\n } catch (error) {\n batch.abort(error);\n throw error;\n }\n}\n\n// Starts every ready call by the scheduling rules and returns, in model order, the promise of each call's result.\nfunction start(\n prepared: readonly Prepared[],\n sequential: boolean,\n ctx: PipelineContext,\n batch: AbortController,\n): (Promise<Settled<ToolResult>> | undefined)[] {\n const ready = prepared.filter((item): item is Ready => item.kind === \"ready\");\n const scheduled = schedule(\n ready.map((item) => ({\n ...(item.key === undefined ? {} : { key: item.key }),\n readOnly: isTrustedReadOnly(item.tool),\n run: () => runReady(item, ctx, batch),\n })),\n sequential,\n );\n const byItem = new Map<Prepared, Promise<Settled<ToolResult>> | undefined>(\n ready.map((item, index) => [item, scheduled[index]]),\n );\n return prepared.map((item) => {\n if (item.kind === \"paused\") return undefined;\n if (item.kind === \"done\") return Promise.resolve<Settled<ToolResult>>({ ok: true, value: item.result });\n return byItem.get(item);\n });\n}\n\n/**\n * Runs the calls of one step. Each call is checked and gated one at a time, in model order, before any call executes.\n * The calls that passed then start together, except that a call to a sequential tool makes the whole step run one\n * call at a time, even when that call itself fails a check, and calls that share a `resourceKey` queue in model\n * order. Results reach `ctx.onResult` in model order, each as soon as every result before it is in. A call the gate\n * paused gets no result and is left out; each one reaches `ctx.onPause`, in model order, once every call is gated.\n *\n * A programmer error (an `SdkError`) in one call fires the signal the other calls hold, waits for them to stop, and\n * is then thrown, after every other call's result has been passed on: a call after the failing one may have run and\n * written. A programmer error while the calls are checked, such as a `resourceKey` that throws, is thrown after the\n * calls already checked get their results, so every call that started has one, except the call that failed.\n */\nasync function runCalls(\n calls: readonly ToolCall[],\n early: (call: ToolCall) => ToolResult | undefined,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const byName = toolsByName(tools);\n const prepared: Prepared[] = [];\n try {\n for (const call of calls) {\n ctx.onStart?.(call);\n prepared.push(await prepareCall(call, early(call), byName, ctx));\n }\n } catch (error) {\n // None of these calls has executed, and none will. The first error is the one thrown, so a receiver that throws\n // here must not hide it or stop the other calls from getting their results.\n // A paused call gets a not-run result here too: the run is failing, so its pause is never reported or returned.\n for (const item of prepared) {\n const result = item.kind === \"done\" ? item.result : notRun(item.call, item.tool, \"sibling_failed\");\n try {\n ctx.onResult?.({ call: item.call, result });\n } catch {\n // Not rethrown: the error being handled is thrown below.\n }\n }\n throw error;\n }\n // Reported only now, once every call has been gated, so a step that fails while its calls are checked never reports\n // a pause and then gives the same call a result.\n for (const item of prepared) {\n if (item.kind === \"paused\") ctx.onPause?.({ call: item.call, request: item.request, input: item.input });\n }\n const sequential = calls.some((call) => byName.get(call.name)?.executionMode === \"sequential\");\n const { batch, release } = batchController(ctx.signal);\n try {\n return await deliver(prepared, start(prepared, sequential, ctx, batch), ctx, batch);\n } finally {\n release();\n }\n}\n\n// Passes each result on in model order, as soon as every result before it is in. A failed call has already cancelled\n// the others; the loop still waits for each of them and passes its result on, so none is left running and a write\n// that happened is recorded, and then the first error is thrown. A receiver that throws is a failed call too: it\n// cancels the siblings, and the results after it are still passed on.\nasync function deliver(\n prepared: readonly Prepared[],\n running: readonly (Promise<Settled<ToolResult>> | undefined)[],\n ctx: PipelineContext,\n batch: AbortController,\n): Promise<ToolCallResult[]> {\n const results: ToolCallResult[] = [];\n let failure: { readonly error: unknown } | undefined;\n for (const [index, pending] of running.entries()) {\n if (pending === undefined) continue;\n const settled = await pending;\n if (!settled.ok) {\n failure ??= { error: settled.error };\n continue;\n }\n const item = prepared[index] as Prepared;\n const replaced = item.kind === \"ready\" && item.replaced ? { input: item.input } : {};\n const entry: ToolCallResult = { call: item.call, result: settled.value, ...replaced };\n results.push(entry);\n try {\n ctx.onResult?.(entry);\n } catch (error) {\n failure ??= { error };\n batch.abort(error);\n }\n }\n if (failure !== undefined) throw failure.error;\n return results;\n}\n\n/**\n * Runs one tool call through the pipeline and returns the result the model reads. It never throws for a failure\n * the model caused: an unknown tool, invalid input or a throwing `execute` each become an error result. It throws\n * an `SdkError` for a programmer error: a bad tool definition, two tools with one name, or a malformed result.\n */\nexport async function runToolCall(\n call: ToolCall,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolResult> {\n const { onStart: _start, onResult: _result, onPause: _pause, ...quiet } = ctx;\n const [entry] = await runCalls([call], () => undefined, tools, quiet);\n if (entry === undefined)\n throw new SdkError(\"invalid_hook_result\", `runToolCall() can't pause the call \"${call.name}\"`);\n return entry.result;\n}\n\n/**\n * Runs every tool call of an assistant message and passes each result to `ctx.onResult` in model order. A message\n * that stopped at the output limit (`stopReason: \"length\"`) runs nothing: each of its calls gets an error asking the\n * model to re-issue it, because its arguments may be cut short. A message that ended in an error or was aborted also\n * runs nothing, because its calls may be partial. Otherwise the calls are scheduled as `runCalls` describes.\n */\nexport async function runToolCalls(\n message: AssistantMessage,\n tools: readonly AnyTool[],\n ctx: PipelineContext,\n): Promise<ToolCallResult[]> {\n const calls = message.content.filter((block): block is ToolCall => block.type === \"tool_call\");\n return runCalls(calls, (call) => unrunnable(message, call, tools), tools, ctx);\n}\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Byte helpers for the signers: base64url without padding (RFC 4648 §5), and a comparison whose running time doesn't
|
|
3
|
+
* depend on where two byte strings first differ. Web-standard APIs only, so they run on every target.
|
|
4
|
+
*/
|
|
5
|
+
/** Encodes bytes as base64url with no padding. */
|
|
6
|
+
export declare function toBase64Url(bytes: Uint8Array): string;
|
|
7
|
+
/**
|
|
8
|
+
* Decodes unpadded base64url. Returns `undefined` for any text that isn't the canonical encoding of some bytes: a
|
|
9
|
+
* character outside the alphabet, padding, a length no encoding has, or unused low bits that aren't zero. Refusing a
|
|
10
|
+
* non-canonical form keeps one signature from having two spellings.
|
|
11
|
+
*/
|
|
12
|
+
export declare function fromBase64Url(text: string): Uint8Array | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* True when two byte strings are equal. It compares every byte, whatever the first difference, so the time it takes
|
|
15
|
+
* reveals only the lengths, which are public for a MAC.
|
|
16
|
+
*/
|
|
17
|
+
export declare function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Byte helpers for the signers: base64url without padding (RFC 4648 §5), and a comparison whose running time doesn't
|
|
3
|
+
* depend on where two byte strings first differ. Web-standard APIs only, so they run on every target.
|
|
4
|
+
*/
|
|
5
|
+
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
6
|
+
const VALUE = new Map([...ALPHABET].map((char, index) => [char, index]));
|
|
7
|
+
/** Encodes bytes as base64url with no padding. */
|
|
8
|
+
export function toBase64Url(bytes) {
|
|
9
|
+
let out = "";
|
|
10
|
+
for (let index = 0; index < bytes.length; index += 3) {
|
|
11
|
+
// Missing bytes of the last group count as zero; the characters they would fill are left off below.
|
|
12
|
+
const chunk = ((bytes[index] ?? 0) << 16) | ((bytes[index + 1] ?? 0) << 8) | (bytes[index + 2] ?? 0);
|
|
13
|
+
const chars = Math.min(4, Math.ceil(((bytes.length - index) * 8) / 6));
|
|
14
|
+
for (let shift = 0; shift < chars; shift++)
|
|
15
|
+
out += ALPHABET[(chunk >> (18 - 6 * shift)) & 63];
|
|
16
|
+
}
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Decodes unpadded base64url. Returns `undefined` for any text that isn't the canonical encoding of some bytes: a
|
|
21
|
+
* character outside the alphabet, padding, a length no encoding has, or unused low bits that aren't zero. Refusing a
|
|
22
|
+
* non-canonical form keeps one signature from having two spellings.
|
|
23
|
+
*/
|
|
24
|
+
export function fromBase64Url(text) {
|
|
25
|
+
if (text.length % 4 === 1)
|
|
26
|
+
return undefined;
|
|
27
|
+
const bytes = new Uint8Array(Math.floor((text.length * 6) / 8));
|
|
28
|
+
let buffer = 0;
|
|
29
|
+
let bits = 0;
|
|
30
|
+
let out = 0;
|
|
31
|
+
for (const char of text) {
|
|
32
|
+
const value = VALUE.get(char);
|
|
33
|
+
if (value === undefined)
|
|
34
|
+
return undefined;
|
|
35
|
+
buffer = ((buffer << 6) | value) & 0xffffff;
|
|
36
|
+
bits += 6;
|
|
37
|
+
if (bits >= 8) {
|
|
38
|
+
bits -= 8;
|
|
39
|
+
bytes[out++] = (buffer >> bits) & 0xff;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// The bits left over after the last whole byte must be zero, or two texts would decode to the same bytes.
|
|
43
|
+
if ((buffer & ((1 << bits) - 1)) !== 0)
|
|
44
|
+
return undefined;
|
|
45
|
+
return bytes;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* True when two byte strings are equal. It compares every byte, whatever the first difference, so the time it takes
|
|
49
|
+
* reveals only the lengths, which are public for a MAC.
|
|
50
|
+
*/
|
|
51
|
+
export function constantTimeEqual(a, b) {
|
|
52
|
+
if (a.length !== b.length)
|
|
53
|
+
return false;
|
|
54
|
+
let difference = 0;
|
|
55
|
+
for (let index = 0; index < a.length; index++)
|
|
56
|
+
difference |= (a[index] ?? 0) ^ (b[index] ?? 0);
|
|
57
|
+
return difference === 0;
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=b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I,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE;QAAE,UAAU,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IAC/F,OAAO,UAAU,KAAK,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * Byte helpers for the signers: base64url without padding (RFC 4648 §5), and a comparison whose running time doesn't\n * depend on where two byte strings first differ. Web-standard APIs only, so they run on every target.\n */\n\nconst ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\nconst VALUE = new Map([...ALPHABET].map((char, index) => [char, index]));\n\n/** Encodes bytes as base64url with no padding. */\nexport function toBase64Url(bytes: Uint8Array): string {\n let out = \"\";\n for (let index = 0; index < bytes.length; index += 3) {\n // Missing bytes of the last group count as zero; the characters they would fill are left off below.\n const chunk = ((bytes[index] ?? 0) << 16) | ((bytes[index + 1] ?? 0) << 8) | (bytes[index + 2] ?? 0);\n const chars = Math.min(4, Math.ceil(((bytes.length - index) * 8) / 6));\n for (let shift = 0; shift < chars; shift++) out += ALPHABET[(chunk >> (18 - 6 * shift)) & 63];\n }\n return out;\n}\n\n/**\n * Decodes unpadded base64url. Returns `undefined` for any text that isn't the canonical encoding of some bytes: a\n * character outside the alphabet, padding, a length no encoding has, or unused low bits that aren't zero. Refusing a\n * non-canonical form keeps one signature from having two spellings.\n */\nexport function fromBase64Url(text: string): Uint8Array | undefined {\n if (text.length % 4 === 1) return undefined;\n const bytes = new Uint8Array(Math.floor((text.length * 6) / 8));\n let buffer = 0;\n let bits = 0;\n let out = 0;\n for (const char of text) {\n const value = VALUE.get(char);\n if (value === undefined) return undefined;\n buffer = ((buffer << 6) | value) & 0xffffff;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes[out++] = (buffer >> bits) & 0xff;\n }\n }\n // The bits left over after the last whole byte must be zero, or two texts would decode to the same bytes.\n if ((buffer & ((1 << bits) - 1)) !== 0) return undefined;\n return bytes;\n}\n\n/**\n * True when two byte strings are equal. It compares every byte, whatever the first difference, so the time it takes\n * reveals only the lengths, which are public for a MAC.\n */\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let difference = 0;\n for (let index = 0; index < a.length; index++) difference |= (a[index] ?? 0) ^ (b[index] ?? 0);\n return difference === 0;\n}\n"]}
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason
|
|
3
|
-
*
|
|
2
|
+
* `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an
|
|
3
|
+
* input that has no canonical JSON form, or a key ring that can't sign.
|
|
4
4
|
*/
|
|
5
|
-
/**
|
|
6
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has
|
|
7
|
+
* no canonical JSON form, or a tool's context fails its `contextSchema`. `invalid_key_ring`: a signer's keys or key
|
|
8
|
+
* ids can't be used. `invalid_pending`: the fields of a pending request can't be signed.
|
|
9
|
+
*/
|
|
10
|
+
export type SafetyErrorCode = "invalid_outcome" | "invalid_input" | "invalid_key_ring" | "invalid_pending";
|
|
7
11
|
/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
|
|
8
12
|
export declare class SafetyError extends Error {
|
|
9
13
|
readonly name = "SafetyError";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason
|
|
3
|
-
*
|
|
2
|
+
* `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an
|
|
3
|
+
* input that has no canonical JSON form, or a key ring that can't sign.
|
|
4
4
|
*/
|
|
5
5
|
// A registered symbol, so the guard still works when two copies of the package are bundled.
|
|
6
6
|
const SAFETY_ERROR = Symbol.for("buildanagent.agent-safety.SafetyError");
|