@buildanagent/sdk 0.1.0-alpha.5 → 0.1.0-alpha.6

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/dist/loop.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAEL,OAAO,EACP,QAAQ,EAGR,UAAU,GAQX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAI3D,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAgB,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAGtF,kEAAkE;AAClE,MAAM,aAAa,GAAG,eAAe,CAAC;AAEtC,uGAAuG;AACvG,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAE5B;;;GAGG;AACH,MAAM,OAAO,GAAS,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAyCvE,wCAAwC;AACxC,MAAM,SAAS;IACJ,KAAK,CAAY;IACjB,IAAI,CAAO;IACX,QAAQ,CAAY;IACpB,KAAK,CAAY;IACjB,KAAK,CAAQ;IACb,KAAK,CAAa;IAClB,KAAK,CAAiC;IAC/C,4FAA4F;IAC5F,MAAM,GAAuB,EAAE,CAAC;IAChC,KAAK,GAAG,CAAC,CAAC;IACV,SAAS,GAAG,CAAC,CAAC;IACd,KAAK,GAAU,UAAU,EAAE,CAAC;IAC5B,SAAS,CAAoB;IAC7B,IAAI,CAAmB;IACvB,MAAM,CAAU;IAEhB,YAAY,KAAgB,EAAE,IAAU,EAAE,KAAY;QACpD,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AC,CAAC;IACnH,CAAC;IACD,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO;QAAE,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;IACxF,MAAM,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC,CAAC;IACtC,MAAM,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACxC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;IACxC,MAAM,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,KAAgB,EAAE,IAAU,EAAE,KAAY;IACtE,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAChD,IAAI,OAA4B,CAAC;IACjC,OAAO,OAAO,KAAK,SAAS,EAAE,CAAC;QAC7B,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IACpF,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["/**\n * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds\n * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.\n *\n * Each step runs transform → before → stream → after → tools → stop. Those moments are where the interceptors\n * plug in (D6); a run without interceptors sends the transcript as it stands and keeps each response unchanged.\n * Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,\n * throws.\n */\nimport {\n type AssistantMessage,\n addCost,\n addUsage,\n type Cost,\n type DumpedOptions,\n emptyUsage,\n type GatewayEvent,\n type Message,\n type Model,\n type ModelContext,\n type StreamOptions,\n type Usage,\n type WireTool,\n} from \"@buildanagent/gateway\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport type { StopVerdict } from \"./hook-checks.js\";\nimport { HookFailure, HookRunner } from \"./hook-runner.js\";\nimport type { CallOptions, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\n\n/** The `stoppedBy` of a run that a clarification tool stopped. */\nconst CLARIFICATION = \"clarification\";\n\n// The depth cap's defaults (D11). Nested runs pass their own depth once the depth cap is configurable.\nconst TOP_LEVEL_DEPTH = 0;\nconst DEFAULT_MAX_DEPTH = 2;\n\n/**\n * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis\n * when it adds a provider cost, so the zero never turns a billed sum into an estimate.\n */\nconst NO_COST: Cost = { total: 0, basis: \"provider\", currency: \"USD\" };\n\n/** Everything one run needs, fixed when it starts. */\nexport interface LoopSetup {\n readonly runId: string;\n readonly model: Model;\n readonly system: string;\n /** The conversation before this run's own messages. */\n readonly history: readonly Message[];\n /** The messages the run starts by adding, such as the user's input. */\n readonly input: readonly Message[];\n /**\n * Every tool the run knows, in definition order. A request sends the ones whose exposure is `direct`, or the ones\n * `activeTools` names, and only the tools a request sent can run.\n */\n readonly tools: readonly AnyTool[];\n readonly output: AnyTool | undefined;\n readonly maxSteps: number;\n readonly modelOptions: CallOptions;\n readonly interceptors: Interceptors;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** Sends one event; the run adds the `EventBase` fields. */\nexport type Emit = (body: AgentEventBody, stepIndex: number) => void;\n\n/**\n * Resolves once every observer has handled the events sent so far. The loop calls it only once it has its outcome,\n * and the run treats the first call as the point after which an abort no longer counts.\n */\nexport type Drain = () => Promise<void>;\n\n/** How a run ended, before its usage, cost and messages are attached. */\ntype Outcome =\n | { readonly stopReason: \"done\"; readonly output: unknown }\n | { readonly stopReason: \"max_steps\" | \"aborted\" }\n | { readonly stopReason: \"error\"; readonly error: RunError }\n | { readonly stopReason: \"stopped\"; readonly stoppedBy: string }\n | { readonly stopReason: \"no_progress\"; readonly reason: string };\n\n/** What changes while a run goes on. */\nclass LoopState {\n readonly setup: LoopSetup;\n readonly emit: Emit;\n readonly messages: Message[];\n readonly added: Message[];\n readonly drain: Drain;\n readonly hooks: HookRunner;\n readonly #wire: ReadonlyMap<AnyTool, WireTool>;\n /** The tools the latest request sent; the tool calls of its response may run only these. */\n active: readonly AnyTool[] = [];\n steps = 0;\n stepIndex = 0;\n usage: Usage = emptyUsage();\n lastUsage: Usage | undefined;\n cost: Cost | undefined;\n output: unknown;\n\n constructor(setup: LoopSetup, emit: Emit, drain: Drain) {\n this.setup = setup;\n this.emit = emit;\n this.drain = drain;\n this.messages = [...setup.history, ...setup.input];\n this.added = [...setup.input];\n this.#wire = new Map(setup.tools.map((tool) => [tool, toWireTool(tool)]));\n this.hooks = new HookRunner({\n interceptors: setup.interceptors,\n runId: setup.runId,\n signal: setup.signal,\n clock: setup.clock,\n stepIndex: () => this.stepIndex,\n send: (body) => this.send(body),\n });\n }\n\n /** The wire form of each of `tools`, as a request sends them. */\n wireOf(tools: readonly AnyTool[]): WireTool[] {\n // Every tool of the run was lowered in the constructor, and a request names only the run's tools.\n return tools.map((tool) => this.#wire.get(tool) as WireTool);\n }\n\n send(body: AgentEventBody): void {\n this.emit(body, this.stepIndex);\n }\n\n append(message: Message): void {\n this.messages.push(message);\n this.added.push(message);\n }\n}\n\n/**\n * The stream options a request event records: everything but the payload hook, the abort signal and the caps, as the\n * gateway's own request dump leaves them out. An untyped caller may still pass a signal or caps in `modelOptions`.\n */\nfunction dumpedOptions(options: CallOptions): DumpedOptions {\n const { onPayload: _onPayload, signal: _signal, caps: _caps, ...rest } = options as StreamOptions;\n return rest;\n}\n\n/** Re-emits one model event as a run event, and returns the final message once the terminal event arrives. */\nfunction forward(state: LoopState, event: GatewayEvent): AssistantMessage | undefined {\n switch (event.type) {\n case \"done\":\n case \"error\":\n return event.message;\n case \"start\":\n return undefined;\n case \"retry\":\n state.send({ type: \"retry\", attempt: event.attempt, delayMs: event.delayMs, error: event.error });\n return undefined;\n case \"warning\":\n state.send({ type: \"warning\", code: \"model_warning\", detail: `${event.code}: ${event.message}` });\n return undefined;\n case \"text_start\":\n case \"reasoning_start\":\n case \"tool_input_start\":\n state.send({ type: event.type, index: event.index });\n return undefined;\n case \"text_delta\":\n case \"reasoning_delta\":\n case \"tool_input_delta\":\n state.send({ type: event.type, index: event.index, delta: event.delta });\n return undefined;\n default:\n state.send({ type: event.type, index: event.index, block: event.block });\n return undefined;\n }\n}\n\n/** One model call as it will be sent, after `transformContext` and `beforeModelCall`. */\ninterface Request {\n readonly model: Model;\n readonly context: ModelContext;\n readonly options: CallOptions;\n readonly active: readonly AnyTool[];\n}\n\n/** The tools a request sends unless `beforeModelCall` names others: the ones whose exposure is `direct`. */\nfunction directTools(tools: readonly AnyTool[]): AnyTool[] {\n return tools.filter((tool) => (tool.exposure ?? \"direct\") === \"direct\");\n}\n\n/** The tools `names` picks, in definition order whatever order `names` is in. */\nfunction toolsNamed(tools: readonly AnyTool[], names: readonly string[]): AnyTool[] {\n const unknown = names.filter((name) => !tools.some((tool) => tool.name === name));\n if (unknown.length > 0) {\n throw new SdkError(\"invalid_hook_result\", `activeTools names unknown tools: ${unknown.join(\", \")}`);\n }\n return tools.filter((tool) => names.includes(tool.name));\n}\n\nfunction patched(state: LoopState, request: Request, patch: ModelCallPatch): Request {\n const active = patch.activeTools === undefined ? request.active : toolsNamed(state.setup.tools, patch.activeTools);\n const { system, messages } = request.context;\n return {\n model: patch.model ?? request.model,\n options: patch.options ?? request.options,\n active,\n context: {\n system: patch.system ?? system,\n messages: patch.messages === undefined ? messages : [...patch.messages],\n tools: state.wireOf(active),\n },\n };\n}\n\n/**\n * Builds one call's request: the transcript, or the view `transformContext` returns for this call alone, then the\n * changes `beforeModelCall` asks for. The run's own transcript is never replaced by either.\n */\nasync function buildRequest(state: LoopState): Promise<Request> {\n const { model, system, modelOptions, tools } = state.setup;\n const view = await state.hooks.transformContext({\n system,\n messages: state.messages,\n model: model.ref,\n lastUsage: state.lastUsage,\n });\n const active = directTools(tools);\n const context = { system, messages: [...(view ?? state.messages)], tools: state.wireOf(active) };\n const request: Request = { model, context, options: modelOptions, active };\n const patch = await state.hooks.beforeModelCall({ context, options: modelOptions });\n return patch === undefined ? request : patched(state, request, patch);\n}\n\n/** Streams one request, re-emitting its events, and returns the model's final message. */\nasync function streamRequest(state: LoopState, request: Request): Promise<AssistantMessage> {\n const { model, context, options } = request;\n state.send({ type: \"model_call_start\", request: { model: model.ref, context, options: dumpedOptions(options) } });\n let message: AssistantMessage | undefined;\n for await (const event of model.stream(context, { ...options, signal: state.setup.signal })) {\n message = forward(state, event) ?? message;\n }\n if (message === undefined) {\n throw new SdkError(\"invalid_model_stream\", \"the model's stream ended without a done or error event\");\n }\n return message;\n}\n\n/** Adds a model call's response to the transcript and reports it. */\nfunction record(state: LoopState, message: AssistantMessage): void {\n state.append(message);\n state.send({ type: \"model_call_end\", message });\n}\n\n/**\n * What the transcript holds for a response whose `afterModelCall` failed while the run fails closed: no content, so a\n * check that crashed can't let the response through, but the call's usage and cost, which were billed. Its error stop\n * reason makes the replay pass skip it if the run is continued.\n */\nfunction withheld(original: AssistantMessage): AssistantMessage {\n const { model, usage, cost, lastAttemptUsage } = original;\n return {\n role: \"assistant\",\n content: [],\n model,\n stopReason: \"error\",\n error: { kind: \"fatal\", message: \"the response was withheld, because its afterModelCall check failed\" },\n usage,\n ...(lastAttemptUsage === undefined ? {} : { lastAttemptUsage }),\n cost,\n };\n}\n\n/**\n * Makes one model call, streams its events and records the response. The call's usage and cost are the model's own\n * message's, so an `afterModelCall` replacement changes what the run goes on with, never what it is billed. When\n * `afterModelCall` fails and the run fails closed, a withheld stand-in is recorded before the run ends, so the\n * transcript and `model_call_end` still account for the billed call and none of its tool calls run.\n */\nasync function callModel(state: LoopState): Promise<AssistantMessage> {\n const request = await buildRequest(state);\n state.active = request.active;\n const original = await streamRequest(state, request);\n state.steps += 1;\n state.usage = addUsage(state.usage, original.usage);\n state.lastUsage = original.usage;\n state.cost = state.cost === undefined ? original.cost : addCost(state.cost, original.cost);\n let message: AssistantMessage;\n try {\n message = await state.hooks.afterModelCall(original);\n } catch (error) {\n if (error instanceof HookFailure || (isSdkError(error) && error.code === \"invalid_hook_result\")) {\n record(state, withheld(original));\n }\n throw error;\n }\n record(state, message);\n return message;\n}\n\n/** The tool message the model reads for one call. */\nfunction toolMessage(entry: ToolCallResult): Message {\n return {\n role: \"tool\",\n callId: entry.call.callId,\n content: [...entry.result.content],\n isError: entry.result.isError === true,\n };\n}\n\n/** Runs the response's tool calls as the pipeline schedules them, recording each result in model order. */\nasync function runTools(state: LoopState, message: AssistantMessage): Promise<readonly ToolCallResult[]> {\n const { runId, signal, clock, output } = state.setup;\n return runToolCalls(message, state.active, {\n runId,\n signal,\n clock,\n depth: TOP_LEVEL_DEPTH,\n maxDepth: DEFAULT_MAX_DEPTH,\n ...state.hooks.pipelineHooks(),\n onStart: (call: ToolCall) =>\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input }),\n onUpdate: (callId, details) => state.send({ type: \"tool_call_update\", callId, details }),\n onResult: (entry) => {\n state.append(toolMessage(entry));\n if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {\n state.output = entry.result.structured;\n }\n const ranWith = \"input\" in entry ? { input: entry.input } : {};\n state.send({ type: \"tool_call_end\", callId: entry.call.callId, result: entry.result, ...ranWith });\n },\n });\n}\n\n/** The failed call's error as the run reports it. A message without one counts as `fatal`. */\nfunction runErrorOf(message: AssistantMessage): RunError {\n const error = message.error;\n if (error === undefined) return { kind: \"fatal\", message: \"the model call failed without an error description\" };\n return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };\n}\n\n/**\n * The stop check after one step. A finished answer, or a question for the user, wins over an abort that came too late\n * to change it; otherwise an abort stops the run before the step cap does. A text answer cut off at the output limit\n * also counts as finished: its message keeps `stopReason: \"length\"`.\n */\nfunction stopCheck(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Outcome | undefined {\n if (message.stopReason === \"error\") return { stopReason: \"error\", error: runErrorOf(message) };\n if (message.stopReason === \"aborted\") return { stopReason: \"aborted\" };\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\n // Until runs can pause for an answer, a clarification question stops the run, so the model never goes on as if the\n // user had been asked and answered.\n if (results.some(({ result }) => result.pause !== undefined && !result.isError)) {\n return { stopReason: \"stopped\", stoppedBy: CLARIFICATION };\n }\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n return undefined;\n}\n\n/**\n * What `shouldStop` changes about the stop check. A finished answer or an error stands whatever the hook says; the\n * hook can end a run that would go on, and can keep going a run the model ended by answering in text, until the\n * step cap.\n */\nfunction withVerdict(state: LoopState, natural: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n if (natural !== undefined && verdict.kind !== \"continue\") return natural;\n switch (verdict.kind) {\n case \"stop\":\n return { stopReason: \"stopped\", stoppedBy: verdict.stoppedBy };\n case \"no_progress\":\n return { stopReason: \"no_progress\", reason: verdict.reason };\n case \"continue\":\n if (natural === undefined) return undefined;\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n state.append({ role: \"user\", content: verdict.content });\n return undefined;\n default:\n return natural;\n }\n}\n\n/** The stop check after one step, then the `shouldStop` hook where it may change it. */\nasync function decide(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Promise<Outcome | undefined> {\n const natural = stopCheck(state, message, results);\n const endedByAnswer = natural?.stopReason === \"done\" && results.length === 0;\n if (natural !== undefined && !endedByAnswer) return natural;\n const verdict = await state.hooks.shouldStop({ messages: state.messages, lastMessage: message });\n return withVerdict(state, natural, verdict);\n}\n\n/** The outcome of a hook that failed while the run fails closed. A failure caused by an abort ends the run aborted. */\nfunction failedOutcome(state: LoopState, error: unknown): Outcome {\n if (!(error instanceof HookFailure)) throw error;\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n return { stopReason: \"error\", error: { kind: \"hook\", message: error.message } };\n}\n\nasync function runStep(state: LoopState): Promise<Outcome | undefined> {\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n let outcome: Outcome | undefined;\n try {\n const message = await callModel(state);\n const results = await runTools(state, message);\n outcome = await decide(state, message, results);\n } catch (error) {\n outcome = failedOutcome(state, error);\n }\n state.send({ type: \"step_end\", stopCheck: outcome === undefined ? \"continue\" : \"stop\" });\n return outcome;\n}\n\n/**\n * An aborted run's transcript ends with an assistant message whose `stopReason` is `\"aborted\"`. When tool results end\n * the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop\n * appends an empty one after them; the replay pass drops it before any request.\n */\nfunction closeAborted(state: LoopState): void {\n const last = state.messages.at(-1);\n if (last?.role === \"assistant\" && last.stopReason === \"aborted\") return;\n state.append({\n role: \"assistant\",\n content: [],\n model: state.setup.model.ref,\n stopReason: \"aborted\",\n usage: emptyUsage(),\n cost: { ...NO_COST },\n });\n}\n\nfunction resultOf(state: LoopState, outcome: Outcome): RunResult {\n const base = {\n messages: state.added,\n context: { system: state.setup.system, messages: state.messages },\n usage: state.usage,\n cost: state.cost ?? { ...NO_COST },\n steps: state.steps,\n };\n return { ...base, ...outcome } as RunResult;\n}\n\n/**\n * Ends the run: the settle event comes once every observer has seen what came before it, and `run_end` after that.\n * An observer's failure while handling `agent_settled` is reported between the two; one while handling `run_end` is\n * dropped, so `run_end` stays the last event. The result is returned only once observers have seen it.\n */\nasync function finish(state: LoopState, outcome: Outcome): Promise<RunResult> {\n if (outcome.stopReason === \"aborted\") closeAborted(state);\n if (outcome.stopReason === \"max_steps\") {\n state.send({ type: \"warning\", code: \"max_steps\", detail: `the run reached maxSteps (${state.setup.maxSteps})` });\n }\n if (outcome.stopReason === \"error\") state.send({ type: \"error\", error: outcome.error });\n await state.drain();\n state.send({ type: \"agent_settled\" });\n await state.drain();\n const result = resultOf(state, outcome);\n state.send({ type: \"run_end\", result });\n await state.drain();\n return result;\n}\n\n/**\n * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results\n * already received are in the transcript.\n */\nexport async function runLoop(setup: LoopSetup, emit: Emit, drain: Drain): Promise<RunResult> {\n const state = new LoopState(setup, emit, drain);\n let outcome: Outcome | undefined;\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n return finish(state, outcome);\n}\n"]}
1
+ {"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAEL,OAAO,EACP,QAAQ,EAGR,UAAU,EAKV,eAAe,GAIhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAK3D,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAgB,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAGtF,kEAAkE;AAClE,MAAM,aAAa,GAAG,eAAe,CAAC;AAEtC;;;GAGG;A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AO,CAAC,CAAC;IACxC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;IACxC,MAAM,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,KAAgB,EAAE,IAAU,EAAE,KAAY;IACtE,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAChD,uGAAuG;IACvG,MAAM,OAAO,GAAG,KAAK,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,iBAAiB,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC3F,IAAI,OAAO,GAAwB,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;IAC/G,OAAO,OAAO,KAAK,SAAS,EAAE,CAAC;QAC7B,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IACpF,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["/**\n * The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds\n * (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.\n *\n * Each step runs transform → before → stream → after → tools → stop. Those moments are where the interceptors\n * plug in (D6); a run without interceptors sends the transcript as it stands and keeps each response unchanged.\n * Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,\n * throws.\n */\nimport {\n type AssistantMessage,\n addCost,\n addUsage,\n type Cost,\n type DumpedOptions,\n emptyUsage,\n type GatewayEvent,\n type Message,\n type Model,\n type ModelContext,\n projectCallCost,\n type StreamOptions,\n type Usage,\n type WireTool,\n} from \"@buildanagent/gateway\";\nimport { checkBudget, unknownPriceError } from \"./budget.js\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport type { StopVerdict } from \"./hook-checks.js\";\nimport { HookFailure, HookRunner } from \"./hook-runner.js\";\nimport type { CallOptions, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport type { ProgressCheck } from \"./progress.js\";\nimport type { RunError, RunResult } from \"./result.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\n\n/** The `stoppedBy` of a run that a clarification tool stopped. */\nconst CLARIFICATION = \"clarification\";\n\n/**\n * The cost of no model call: an exact zero. Its basis is `provider` because `addCost()` keeps the other cost's basis\n * when it adds a provider cost, so the zero never turns a billed sum into an estimate.\n */\nconst NO_COST: Cost = { total: 0, basis: \"provider\", currency: \"USD\" };\n\n/** Everything one run needs, fixed when it starts. */\nexport interface LoopSetup {\n readonly runId: string;\n readonly model: Model;\n readonly system: string;\n /** The conversation before this run's own messages. */\n readonly history: readonly Message[];\n /** The messages the run starts by adding, such as the user's input. */\n readonly input: readonly Message[];\n /**\n * Every tool the run knows, in definition order. A request sends the ones whose exposure is `direct`, or the ones\n * `activeTools` names, and only the tools a request sent can run.\n */\n readonly tools: readonly AnyTool[];\n readonly output: AnyTool | undefined;\n readonly maxSteps: number;\n /** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */\n readonly budgetUsd?: number;\n /** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */\n readonly depth: number;\n readonly maxDepth: number;\n readonly modelOptions: CallOptions;\n readonly interceptors: Interceptors;\n /** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */\n readonly progress?: ProgressCheck;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** Sends one event; the run adds the `EventBase` fields. */\nexport type Emit = (body: AgentEventBody, stepIndex: number) => void;\n\n/**\n * Resolves once every observer has handled the events sent so far. The loop calls it only once it has its outcome,\n * and the run treats the first call as the point after which an abort no longer counts.\n */\nexport type Drain = () => Promise<void>;\n\n/** How a run ended, before its usage, cost and messages are attached. */\ntype Outcome =\n | { readonly stopReason: \"done\"; readonly output: unknown }\n | { readonly stopReason: \"max_steps\" | \"aborted\" }\n | {\n readonly stopReason: \"budget\";\n readonly reason: string;\n readonly budgetUsd: number;\n readonly spentUsd: number;\n readonly projectedUsd: number;\n }\n | { readonly stopReason: \"error\"; readonly error: RunError }\n | { readonly stopReason: \"stopped\"; readonly stoppedBy: string }\n | { readonly stopReason: \"no_progress\"; readonly reason: string };\n\n/** What changes while a run goes on. */\nclass LoopState {\n readonly setup: LoopSetup;\n readonly emit: Emit;\n readonly messages: Message[];\n readonly added: Message[];\n readonly drain: Drain;\n readonly hooks: HookRunner;\n readonly #wire: ReadonlyMap<AnyTool, WireTool>;\n /** The tools the latest request sent; the tool calls of its response may run only these. */\n active: readonly AnyTool[] = [];\n steps = 0;\n stepIndex = 0;\n usage: Usage = emptyUsage();\n lastUsage: Usage | undefined;\n cost: Cost | undefined;\n output: unknown;\n\n constructor(setup: LoopSetup, emit: Emit, drain: Drain) {\n this.setup = setup;\n this.emit = emit;\n this.drain = drain;\n this.messages = [...setup.history, ...setup.input];\n this.added = [...setup.input];\n this.#wire = new Map(setup.tools.map((tool) => [tool, toWireTool(tool)]));\n this.hooks = new HookRunner({\n interceptors: setup.interceptors,\n runId: setup.runId,\n signal: setup.signal,\n clock: setup.clock,\n stepIndex: () => this.stepIndex,\n send: (body) => this.send(body),\n });\n }\n\n /** The wire form of each of `tools`, as a request sends them. */\n wireOf(tools: readonly AnyTool[]): WireTool[] {\n // Every tool of the run was lowered in the constructor, and a request names only the run's tools.\n return tools.map((tool) => this.#wire.get(tool) as WireTool);\n }\n\n send(body: AgentEventBody): void {\n this.emit(body, this.stepIndex);\n }\n\n append(message: Message): void {\n this.messages.push(message);\n this.added.push(message);\n }\n}\n\n/**\n * The stream options a request event records: everything but the payload hook, the abort signal and the caps, as the\n * gateway's own request dump leaves them out. An untyped caller may still pass a signal or caps in `modelOptions`.\n */\nfunction dumpedOptions(options: CallOptions): DumpedOptions {\n const { onPayload: _onPayload, signal: _signal, caps: _caps, ...rest } = options as StreamOptions;\n return rest;\n}\n\n/** Re-emits one model event as a run event, and returns the final message once the terminal event arrives. */\nfunction forward(state: LoopState, event: GatewayEvent): AssistantMessage | undefined {\n switch (event.type) {\n case \"done\":\n case \"error\":\n return event.message;\n case \"start\":\n return undefined;\n case \"retry\":\n state.send({ type: \"retry\", attempt: event.attempt, delayMs: event.delayMs, error: event.error });\n return undefined;\n case \"warning\":\n state.send({ type: \"warning\", code: \"model_warning\", detail: `${event.code}: ${event.message}` });\n return undefined;\n case \"text_start\":\n case \"reasoning_start\":\n case \"tool_input_start\":\n state.send({ type: event.type, index: event.index });\n return undefined;\n case \"text_delta\":\n case \"reasoning_delta\":\n case \"tool_input_delta\":\n state.send({ type: event.type, index: event.index, delta: event.delta });\n return undefined;\n default:\n state.send({ type: event.type, index: event.index, block: event.block });\n return undefined;\n }\n}\n\n/** One model call as it will be sent, after `transformContext` and `beforeModelCall`. */\ninterface Request {\n readonly model: Model;\n readonly context: ModelContext;\n readonly options: CallOptions;\n readonly active: readonly AnyTool[];\n}\n\n/** The tools a request sends unless `beforeModelCall` names others: the ones whose exposure is `direct`. */\nfunction directTools(tools: readonly AnyTool[]): AnyTool[] {\n return tools.filter((tool) => (tool.exposure ?? \"direct\") === \"direct\");\n}\n\n/** The tools `names` picks, in definition order whatever order `names` is in. */\nfunction toolsNamed(tools: readonly AnyTool[], names: readonly string[]): AnyTool[] {\n const unknown = names.filter((name) => !tools.some((tool) => tool.name === name));\n if (unknown.length > 0) {\n throw new SdkError(\"invalid_hook_result\", `activeTools names unknown tools: ${unknown.join(\", \")}`);\n }\n return tools.filter((tool) => names.includes(tool.name));\n}\n\nfunction patched(state: LoopState, request: Request, patch: ModelCallPatch): Request {\n const active = patch.activeTools === undefined ? request.active : toolsNamed(state.setup.tools, patch.activeTools);\n const { system, messages } = request.context;\n return {\n model: patch.model ?? request.model,\n options: patch.options ?? request.options,\n active,\n context: {\n system: patch.system ?? system,\n messages: patch.messages === undefined ? messages : [...patch.messages],\n tools: state.wireOf(active),\n },\n };\n}\n\n/**\n * Builds one call's request: the transcript, or the view `transformContext` returns for this call alone, then the\n * changes `beforeModelCall` asks for. The run's own transcript is never replaced by either.\n */\nasync function buildRequest(state: LoopState): Promise<Request> {\n const { model, system, modelOptions, tools } = state.setup;\n const view = await state.hooks.transformContext({\n system,\n messages: state.messages,\n model: model.ref,\n lastUsage: state.lastUsage,\n });\n const active = directTools(tools);\n const context = { system, messages: [...(view ?? state.messages)], tools: state.wireOf(active) };\n const request: Request = { model, context, options: modelOptions, active };\n const patch = await state.hooks.beforeModelCall({ context, options: modelOptions });\n return patch === undefined ? request : patched(state, request, patch);\n}\n\n/** Streams one request, re-emitting its events, and returns the model's final message. */\nasync function streamRequest(state: LoopState, request: Request): Promise<AssistantMessage> {\n const { model, context, options } = request;\n state.send({ type: \"model_call_start\", request: { model: model.ref, context, options: dumpedOptions(options) } });\n let message: AssistantMessage | undefined;\n for await (const event of model.stream(context, { ...options, signal: state.setup.signal })) {\n message = forward(state, event) ?? message;\n }\n if (message === undefined) {\n throw new SdkError(\"invalid_model_stream\", \"the model's stream ended without a done or error event\");\n }\n return message;\n}\n\n/** Adds a model call's response to the transcript and reports it. */\nfunction record(state: LoopState, message: AssistantMessage): void {\n state.append(message);\n state.send({ type: \"model_call_end\", message });\n}\n\n/**\n * What the transcript holds for a response whose `afterModelCall` failed while the run fails closed: no content, so a\n * check that crashed can't let the response through, but the call's usage and cost, which were billed. Its error stop\n * reason makes the replay pass skip it if the run is continued.\n */\nfunction withheld(original: AssistantMessage): AssistantMessage {\n const { model, usage, cost, lastAttemptUsage } = original;\n return {\n role: \"assistant\",\n content: [],\n model,\n stopReason: \"error\",\n error: { kind: \"fatal\", message: \"the response was withheld, because its afterModelCall check failed\" },\n usage,\n ...(lastAttemptUsage === undefined ? {} : { lastAttemptUsage }),\n cost,\n };\n}\n\n/**\n * The budget check before a call (D9): the outcome that ends the run when the spend so far plus the call's projected\n * cost would pass `budgetUsd`, or `undefined` when the call may go out. It checks the request as it will be sent,\n * after the interceptors have changed it, and projects with the model the request names.\n */\nfunction budgetBlock(state: LoopState, request: Request): Outcome | undefined {\n const { budgetUsd } = state.setup;\n if (budgetUsd === undefined) return undefined;\n const projected = projectCallCost(request.model, request.context, request.options);\n const verdict = checkBudget(budgetUsd, state.cost, projected);\n switch (verdict.kind) {\n case \"allow\":\n return undefined;\n case \"unknown\":\n return { stopReason: \"error\", error: verdict.error };\n case \"exceeded\":\n return {\n stopReason: \"budget\",\n reason: verdict.reason,\n budgetUsd,\n spentUsd: verdict.spentUsd,\n projectedUsd: verdict.projectedUsd,\n };\n }\n}\n\n/**\n * Makes one model call, streams its events and records the response. The call's usage and cost are the model's own\n * message's, so an `afterModelCall` replacement changes what the run goes on with, never what it is billed. When\n * `afterModelCall` fails and the run fails closed, a withheld stand-in is recorded before the run ends, so the\n * transcript and `model_call_end` still account for the billed call and none of its tool calls run.\n */\nasync function callModel(state: LoopState): Promise<AssistantMessage | { readonly blocked: Outcome }> {\n const request = await buildRequest(state);\n const blocked = budgetBlock(state, request);\n if (blocked !== undefined) return { blocked };\n state.active = request.active;\n const original = await streamRequest(state, request);\n state.steps += 1;\n state.usage = addUsage(state.usage, original.usage);\n state.lastUsage = original.usage;\n state.cost = state.cost === undefined ? original.cost : addCost(state.cost, original.cost);\n let message: AssistantMessage;\n try {\n message = await state.hooks.afterModelCall(original);\n } catch (error) {\n if (error instanceof HookFailure || (isSdkError(error) && error.code === \"invalid_hook_result\")) {\n record(state, withheld(original));\n }\n throw error;\n }\n record(state, message);\n return message;\n}\n\n/** The tool message the model reads for one call. */\nfunction toolMessage(entry: ToolCallResult): Message {\n return {\n role: \"tool\",\n callId: entry.call.callId,\n content: [...entry.result.content],\n isError: entry.result.isError === true,\n };\n}\n\n/** Runs the response's tool calls as the pipeline schedules them, recording each result in model order. */\nasync function runTools(state: LoopState, message: AssistantMessage): Promise<readonly ToolCallResult[]> {\n const { runId, signal, clock, output } = state.setup;\n return runToolCalls(message, state.active, {\n runId,\n signal,\n clock,\n depth: state.setup.depth,\n maxDepth: state.setup.maxDepth,\n ...state.hooks.pipelineHooks(),\n onStart: (call: ToolCall) =>\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input }),\n onUpdate: (callId, details) => state.send({ type: \"tool_call_update\", callId, details }),\n onResult: (entry) => {\n state.append(toolMessage(entry));\n if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {\n state.output = entry.result.structured;\n }\n const ranWith = \"input\" in entry ? { input: entry.input } : {};\n state.send({ type: \"tool_call_end\", callId: entry.call.callId, result: entry.result, ...ranWith });\n },\n });\n}\n\n/** The failed call's error as the run reports it. A message without one counts as `fatal`. */\nfunction runErrorOf(message: AssistantMessage): RunError {\n const error = message.error;\n if (error === undefined) return { kind: \"fatal\", message: \"the model call failed without an error description\" };\n return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };\n}\n\n/**\n * The stop check after one step. A finished answer, or a question for the user, wins over an abort that came too late\n * to change it; otherwise an abort stops the run before the step cap does. A text answer cut off at the output limit\n * also counts as finished: its message keeps `stopReason: \"length\"`.\n */\nfunction stopCheck(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Outcome | undefined {\n if (message.stopReason === \"error\") return { stopReason: \"error\", error: runErrorOf(message) };\n if (message.stopReason === \"aborted\") return { stopReason: \"aborted\" };\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\n // Until runs can pause for an answer, a clarification question stops the run, so the model never goes on as if the\n // user had been asked and answered.\n if (results.some(({ result }) => result.pause !== undefined && !result.isError)) {\n return { stopReason: \"stopped\", stoppedBy: CLARIFICATION };\n }\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n return undefined;\n}\n\n/**\n * What `shouldStop` changes about the stop check. A finished answer or an error stands whatever the hook says; the\n * hook can end a run that would go on, and can keep going a run the model ended by answering in text, until the\n * step cap.\n */\nfunction withVerdict(state: LoopState, natural: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n if (natural !== undefined && verdict.kind !== \"continue\") return natural;\n switch (verdict.kind) {\n case \"stop\":\n return { stopReason: \"stopped\", stoppedBy: verdict.stoppedBy };\n case \"no_progress\":\n return { stopReason: \"no_progress\", reason: verdict.reason };\n case \"continue\":\n if (natural === undefined) return undefined;\n if (state.steps >= state.setup.maxSteps) return { stopReason: \"max_steps\" };\n state.append({ role: \"user\", content: verdict.content });\n return undefined;\n default:\n return natural;\n }\n}\n\n/** The stop check after one step, then the `shouldStop` hook where it may change it. */\nasync function decide(\n state: LoopState,\n message: AssistantMessage,\n results: readonly ToolCallResult[],\n): Promise<Outcome | undefined> {\n const natural = stopCheck(state, message, results);\n const endedByAnswer = natural?.stopReason === \"done\" && results.length === 0;\n if (natural !== undefined && !endedByAnswer) return natural;\n const verdict = await state.hooks.shouldStop({ messages: state.messages, lastMessage: message });\n return withVerdict(state, natural, await withProgress(state, verdict));\n}\n\n/**\n * The caller's verdict, unless the progress policy finds the run stuck. A caller's own stop stands, and a caller's\n * `{ continue }` or failed hook can't keep a stuck run going.\n */\nasync function withProgress(state: LoopState, verdict: StopVerdict): Promise<StopVerdict> {\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || state.setup.progress === undefined) return verdict;\n const reason = await state.setup.progress(state.messages);\n return reason === undefined ? verdict : { kind: \"no_progress\", reason };\n}\n\n/** The outcome of a hook that failed while the run fails closed. A failure caused by an abort ends the run aborted. */\nfunction failedOutcome(state: LoopState, error: unknown): Outcome {\n if (!(error instanceof HookFailure)) throw error;\n if (state.setup.signal.aborted) return { stopReason: \"aborted\" };\n return { stopReason: \"error\", error: { kind: \"hook\", message: error.message } };\n}\n\nasync function runStep(state: LoopState): Promise<Outcome | undefined> {\n state.stepIndex = state.steps;\n state.send({ type: \"step_start\" });\n let outcome: Outcome | undefined;\n try {\n const called = await callModel(state);\n if (\"blocked\" in called) {\n outcome = called.blocked;\n } else {\n const results = await runTools(state, called);\n outcome = await decide(state, called, results);\n }\n } catch (error) {\n outcome = failedOutcome(state, error);\n }\n state.send({ type: \"step_end\", stopCheck: outcome === undefined ? \"continue\" : \"stop\" });\n return outcome;\n}\n\n/**\n * An aborted run's transcript ends with an assistant message whose `stopReason` is `\"aborted\"`. When tool results end\n * the transcript, because the abort came while tools ran or cut off a response that held tool calls, the loop\n * appends an empty one after them; the replay pass drops it before any request.\n */\nfunction closeAborted(state: LoopState): void {\n const last = state.messages.at(-1);\n if (last?.role === \"assistant\" && last.stopReason === \"aborted\") return;\n state.append({\n role: \"assistant\",\n content: [],\n model: state.setup.model.ref,\n stopReason: \"aborted\",\n usage: emptyUsage(),\n cost: { ...NO_COST },\n });\n}\n\nfunction resultOf(state: LoopState, outcome: Outcome): RunResult {\n const base = {\n messages: state.added,\n context: { system: state.setup.system, messages: state.messages },\n usage: state.usage,\n cost: state.cost ?? { ...NO_COST },\n steps: state.steps,\n };\n return { ...base, ...outcome } as RunResult;\n}\n\n/**\n * Ends the run: the settle event comes once every observer has seen what came before it, and `run_end` after that.\n * An observer's failure while handling `agent_settled` is reported between the two; one while handling `run_end` is\n * dropped, so `run_end` stays the last event. The result is returned only once observers have seen it.\n */\nasync function finish(state: LoopState, outcome: Outcome): Promise<RunResult> {\n if (outcome.stopReason === \"aborted\") closeAborted(state);\n if (outcome.stopReason === \"max_steps\") {\n state.send({ type: \"warning\", code: \"max_steps\", detail: `the run reached maxSteps (${state.setup.maxSteps})` });\n }\n if (outcome.stopReason === \"error\") state.send({ type: \"error\", error: outcome.error });\n await state.drain();\n state.send({ type: \"agent_settled\" });\n await state.drain();\n const result = resultOf(state, outcome);\n state.send({ type: \"run_end\", result });\n await state.drain();\n return result;\n}\n\n/**\n * Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results\n * already received are in the transcript.\n */\nexport async function runLoop(setup: LoopSetup, emit: Emit, drain: Drain): Promise<RunResult> {\n const state = new LoopState(setup, emit, drain);\n // A budget needs a price to check against, so a model without one is refused before it is called (D4).\n const refused = setup.budgetUsd === undefined ? undefined : unknownPriceError(setup.model);\n let outcome: Outcome | undefined = refused === undefined ? undefined : { stopReason: \"error\", error: refused };\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n return finish(state, outcome);\n}\n"]}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The default progress policy (D11): it ends a run with `no_progress` when the model keeps making the same failing
3
+ * call. Two rules fire it:
4
+ *
5
+ * - **Identical failures.** The latest calls are one tool with one canonical input hash, each returned an error, and
6
+ * there are `maxIdenticalFailures` of them in a row (3 by default).
7
+ * - **One key.** A tool's `progressKey()` gave `maxSameKeyCalls` calls (5 by default) the same key and none of them
8
+ * succeeded. A successful call with that key starts its count again; calls with other keys don't.
9
+ *
10
+ * The policy reads the transcript, so it holds no state a `continueRun()` would have to restore, and it counts only
11
+ * the calls the run itself made. The loop runs it after the caller's `shouldStop`, outside the hook runner, so a
12
+ * caller's hook that throws can't switch it off.
13
+ */
14
+ import type { Message } from "@buildanagent/gateway";
15
+ import type { AnyTool } from "./tools/pipeline.js";
16
+ /** The thresholds of the default progress policy. Pass `progress: false` to `run()` to turn the policy off. */
17
+ export interface ProgressPolicy {
18
+ /** How many identical failing calls in a row end the run. Default 3. */
19
+ readonly maxIdenticalFailures?: number;
20
+ /** How many calls with one `progressKey` and no success between them end the run. Default 5. */
21
+ readonly maxSameKeyCalls?: number;
22
+ }
23
+ /** The defaults, provisional until recorded runs retune them. The object is frozen, so no caller can change them. */
24
+ export declare const DEFAULT_PROGRESS: Readonly<Required<ProgressPolicy>>;
25
+ /** Checks a `progress` option and fills in its defaults. */
26
+ export declare function resolveProgress(progress: ProgressPolicy | false | undefined): Required<ProgressPolicy> | undefined;
27
+ /** The progress check the loop runs after each step: the reason the run is stuck, or `undefined`. */
28
+ export type ProgressCheck = (messages: readonly Message[]) => Promise<string | undefined>;
29
+ /**
30
+ * The default progress policy as a check over the transcript. `skip` is how many messages came before this run's
31
+ * own, so a run continued from a context that ended in a loop is not stopped by the old calls. The transcript only
32
+ * grows, so each call's hash and key are worked out once and kept by its place in it.
33
+ */
34
+ export declare function progressCheck(tools: readonly AnyTool[], policy: Required<ProgressPolicy>, skip: number): ProgressCheck;
@@ -0,0 +1,139 @@
1
+ import { SdkError } from "./errors.js";
2
+ import { canonicalInputHash } from "./vendor/agent-safety/hash.js";
3
+ /** The defaults, provisional until recorded runs retune them. The object is frozen, so no caller can change them. */
4
+ export const DEFAULT_PROGRESS = Object.freeze({
5
+ maxIdenticalFailures: 3,
6
+ maxSameKeyCalls: 5,
7
+ });
8
+ /** Checks a `progress` option and fills in its defaults. */
9
+ export function resolveProgress(progress) {
10
+ if (progress === false)
11
+ return undefined;
12
+ const policy = { ...DEFAULT_PROGRESS, ...definedFields(progress ?? {}) };
13
+ for (const [name, value] of Object.entries(policy)) {
14
+ if (!Number.isInteger(value) || value < 1) {
15
+ throw new SdkError("invalid_run_options", `progress.${name} must be a positive integer, got ${String(value)}`);
16
+ }
17
+ }
18
+ return policy;
19
+ }
20
+ function definedFields(policy) {
21
+ return Object.fromEntries(Object.entries(policy).filter(([, value]) => value !== undefined));
22
+ }
23
+ function keyOf(tool, input) {
24
+ if (tool?.progressKey === undefined)
25
+ return undefined;
26
+ try {
27
+ const key = tool.progressKey(input);
28
+ return typeof key === "string" ? key : undefined;
29
+ }
30
+ catch {
31
+ // A key function that can't read the model's input leaves the call unkeyed, so only the identical-failure rule
32
+ // sees it.
33
+ return undefined;
34
+ }
35
+ }
36
+ /** The hash of a call's input, or a value no other call shares when the input has no canonical form. */
37
+ async function hashOf(position, input) {
38
+ try {
39
+ return await canonicalInputHash(input);
40
+ }
41
+ catch {
42
+ return `unhashable:${position}`;
43
+ }
44
+ }
45
+ /** The calls of one assistant message, each named by its place in the transcript. */
46
+ function callsOf(message, turn) {
47
+ const calls = [];
48
+ message.content.forEach((block, at) => {
49
+ if (block.type === "tool_call")
50
+ calls.push({ call: block, position: `${turn}:${at}`, turn });
51
+ });
52
+ return calls;
53
+ }
54
+ /** The unanswered call with `callId` in the newest turn, the first such call within it. */
55
+ function callFor(calls, callId) {
56
+ let best;
57
+ for (const pending of calls) {
58
+ if (pending.failed !== undefined || pending.call.callId !== callId)
59
+ continue;
60
+ if (best === undefined || pending.turn > best.turn)
61
+ best = pending;
62
+ }
63
+ return best;
64
+ }
65
+ /**
66
+ * The tool calls in `messages` that have a result, in the order the model made them. Call ids need not be unique:
67
+ * a provider may repeat one or send none, so a result goes to the unanswered call with its id in the newest turn,
68
+ * the first such call within it, the order the gateway pairs them in.
69
+ */
70
+ function resolvedCalls(messages) {
71
+ const calls = [];
72
+ messages.forEach((message, index) => {
73
+ if (message.role === "assistant")
74
+ calls.push(...callsOf(message, index));
75
+ if (message.role !== "tool")
76
+ return;
77
+ const pending = callFor(calls, message.callId);
78
+ if (pending !== undefined)
79
+ pending.failed = message.isError === true;
80
+ });
81
+ return calls.filter((pending) => pending.failed !== undefined);
82
+ }
83
+ /** The calls in `messages` that have a result, each with its input hash, key and outcome. */
84
+ async function attemptsOf(messages, tools, facts) {
85
+ const attempts = [];
86
+ for (const { call, position, failed } of resolvedCalls(messages)) {
87
+ let known = facts.get(position);
88
+ if (known === undefined) {
89
+ known = { hash: hashOf(position, call.input), key: keyOf(tools.get(call.name), call.input) };
90
+ facts.set(position, known);
91
+ }
92
+ attempts.push({ tool: call.name, hash: await known.hash, key: known.key, failed: failed === true });
93
+ }
94
+ return attempts;
95
+ }
96
+ /** The reason when the latest calls are `limit` identical failures, or `undefined`. */
97
+ function identicalFailures(attempts, limit) {
98
+ const last = attempts.at(-1);
99
+ if (last === undefined || !last.failed)
100
+ return undefined;
101
+ let streak = 0;
102
+ for (let i = attempts.length - 1; i >= 0; i--) {
103
+ const attempt = attempts[i];
104
+ if (attempt === undefined || !attempt.failed || attempt.tool !== last.tool || attempt.hash !== last.hash)
105
+ break;
106
+ streak += 1;
107
+ }
108
+ if (streak < limit)
109
+ return undefined;
110
+ return `the model made ${streak} identical failing calls to ${last.tool} in a row`;
111
+ }
112
+ /** The reason when some key has `limit` calls and no success since its first, or `undefined`. */
113
+ function repeatedKey(attempts, limit) {
114
+ const counts = new Map();
115
+ for (const { tool, key, failed } of attempts) {
116
+ if (key === undefined)
117
+ continue;
118
+ const id = JSON.stringify([tool, key]);
119
+ const count = failed ? (counts.get(id) ?? 0) + 1 : 0;
120
+ counts.set(id, count);
121
+ if (count >= limit)
122
+ return `the model called ${tool} ${count} times with the key ${JSON.stringify(key)} and none succeeded`;
123
+ }
124
+ return undefined;
125
+ }
126
+ /**
127
+ * The default progress policy as a check over the transcript. `skip` is how many messages came before this run's
128
+ * own, so a run continued from a context that ended in a loop is not stopped by the old calls. The transcript only
129
+ * grows, so each call's hash and key are worked out once and kept by its place in it.
130
+ */
131
+ export function progressCheck(tools, policy, skip) {
132
+ const byName = new Map(tools.map((tool) => [tool.name, tool]));
133
+ const facts = new Map();
134
+ return async (messages) => {
135
+ const attempts = await attemptsOf(messages.slice(skip), byName, facts);
136
+ return identicalFailures(attempts, policy.maxIdenticalFailures) ?? repeatedKey(attempts, policy.maxSameKeyCalls);
137
+ };
138
+ }
139
+ //# sourceMappingURL=progress.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"progress.js","sourceRoot":"","sources":["../src/progress.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,QAAQ,EA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,SAAS;QAChC,MAAM,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;QACvC,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACrD,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QACtB,IAAI,KAAK,IAAI,KAAK;YAChB,OAAO,oBAAoB,IAAI,IAAI,KAAK,uBAAuB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,qBAAqB,CAAC;IAC5G,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAKD;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAC3B,KAAyB,EACzB,MAAgC,EAChC,IAAY;IAEZ,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IAC/D,MAAM,KAAK,GAAG,IAAI,GAAG,EAAqB,CAAC;IAC3C,OAAO,KAAK,EAAE,QAAQ,EAAE,EAAE;QACxB,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;QACvE,OAAO,iBAAiB,CAAC,QAAQ,EAAE,MAAM,CAAC,oBAAoB,CAAC,IAAI,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC,eAAe,CAAC,CAAC;IACnH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The default progress policy (D11): it ends a run with `no_progress` when the model keeps making the same failing\n * call. Two rules fire it:\n *\n * - **Identical failures.** The latest calls are one tool with one canonical input hash, each returned an error, and\n * there are `maxIdenticalFailures` of them in a row (3 by default).\n * - **One key.** A tool's `progressKey()` gave `maxSameKeyCalls` calls (5 by default) the same key and none of them\n * succeeded. A successful call with that key starts its count again; calls with other keys don't.\n *\n * The policy reads the transcript, so it holds no state a `continueRun()` would have to restore, and it counts only\n * the calls the run itself made. The loop runs it after the caller's `shouldStop`, outside the hook runner, so a\n * caller's hook that throws can't switch it off.\n */\nimport type { AssistantMessage, Message } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { AnyTool } from \"./tools/pipeline.js\";\nimport type { ToolCall } from \"./tools/types.js\";\nimport { canonicalInputHash } from \"./vendor/agent-safety/hash.js\";\n\n/** The thresholds of the default progress policy. Pass `progress: false` to `run()` to turn the policy off. */\nexport interface ProgressPolicy {\n /** How many identical failing calls in a row end the run. Default 3. */\n readonly maxIdenticalFailures?: number;\n /** How many calls with one `progressKey` and no success between them end the run. Default 5. */\n readonly maxSameKeyCalls?: number;\n}\n\n/** The defaults, provisional until recorded runs retune them. The object is frozen, so no caller can change them. */\nexport const DEFAULT_PROGRESS: Readonly<Required<ProgressPolicy>> = Object.freeze({\n maxIdenticalFailures: 3,\n maxSameKeyCalls: 5,\n});\n\n/** Checks a `progress` option and fills in its defaults. */\nexport function resolveProgress(progress: ProgressPolicy | false | undefined): Required<ProgressPolicy> | undefined {\n if (progress === false) return undefined;\n const policy = { ...DEFAULT_PROGRESS, ...definedFields(progress ?? {}) };\n for (const [name, value] of Object.entries(policy)) {\n if (!Number.isInteger(value) || value < 1) {\n throw new SdkError(\"invalid_run_options\", `progress.${name} must be a positive integer, got ${String(value)}`);\n }\n }\n return policy;\n}\n\nfunction definedFields(policy: ProgressPolicy): ProgressPolicy {\n return Object.fromEntries(Object.entries(policy).filter(([, value]) => value !== undefined));\n}\n\n/** One tool call of the run, with the result it got. */\ninterface Attempt {\n readonly tool: string;\n readonly hash: string;\n readonly key: string | undefined;\n readonly failed: boolean;\n}\n\n/** What the policy works out once for each call: its input hash and its key. */\ninterface CallFacts {\n readonly hash: Promise<string>;\n readonly key: string | undefined;\n}\n\nfunction keyOf(tool: AnyTool | undefined, input: unknown): string | undefined {\n if (tool?.progressKey === undefined) return undefined;\n try {\n const key: unknown = tool.progressKey(input);\n return typeof key === \"string\" ? key : undefined;\n } catch {\n // A key function that can't read the model's input leaves the call unkeyed, so only the identical-failure rule\n // sees it.\n return undefined;\n }\n}\n\n/** The hash of a call's input, or a value no other call shares when the input has no canonical form. */\nasync function hashOf(position: string, input: unknown): Promise<string> {\n try {\n return await canonicalInputHash(input);\n } catch {\n return `unhashable:${position}`;\n }\n}\n\n/** A call waiting for its result, named by its place in the transcript. */\ninterface Pending {\n readonly call: ToolCall;\n readonly position: string;\n readonly turn: number;\n failed?: boolean;\n}\n\n/** The calls of one assistant message, each named by its place in the transcript. */\nfunction callsOf(message: AssistantMessage, turn: number): Pending[] {\n const calls: Pending[] = [];\n message.content.forEach((block, at) => {\n if (block.type === \"tool_call\") calls.push({ call: block, position: `${turn}:${at}`, turn });\n });\n return calls;\n}\n\n/** The unanswered call with `callId` in the newest turn, the first such call within it. */\nfunction callFor(calls: readonly Pending[], callId: string): Pending | undefined {\n let best: Pending | undefined;\n for (const pending of calls) {\n if (pending.failed !== undefined || pending.call.callId !== callId) continue;\n if (best === undefined || pending.turn > best.turn) best = pending;\n }\n return best;\n}\n\n/**\n * The tool calls in `messages` that have a result, in the order the model made them. Call ids need not be unique:\n * a provider may repeat one or send none, so a result goes to the unanswered call with its id in the newest turn,\n * the first such call within it, the order the gateway pairs them in.\n */\nfunction resolvedCalls(messages: readonly Message[]): Pending[] {\n const calls: Pending[] = [];\n messages.forEach((message, index) => {\n if (message.role === \"assistant\") calls.push(...callsOf(message, index));\n if (message.role !== \"tool\") return;\n const pending = callFor(calls, message.callId);\n if (pending !== undefined) pending.failed = message.isError === true;\n });\n return calls.filter((pending) => pending.failed !== undefined);\n}\n\n/** The calls in `messages` that have a result, each with its input hash, key and outcome. */\nasync function attemptsOf(\n messages: readonly Message[],\n tools: ReadonlyMap<string, AnyTool>,\n facts: Map<string, CallFacts>,\n): Promise<Attempt[]> {\n const attempts: Attempt[] = [];\n for (const { call, position, failed } of resolvedCalls(messages)) {\n let known = facts.get(position);\n if (known === undefined) {\n known = { hash: hashOf(position, call.input), key: keyOf(tools.get(call.name), call.input) };\n facts.set(position, known);\n }\n attempts.push({ tool: call.name, hash: await known.hash, key: known.key, failed: failed === true });\n }\n return attempts;\n}\n\n/** The reason when the latest calls are `limit` identical failures, or `undefined`. */\nfunction identicalFailures(attempts: readonly Attempt[], limit: number): string | undefined {\n const last = attempts.at(-1);\n if (last === undefined || !last.failed) return undefined;\n let streak = 0;\n for (let i = attempts.length - 1; i >= 0; i--) {\n const attempt = attempts[i];\n if (attempt === undefined || !attempt.failed || attempt.tool !== last.tool || attempt.hash !== last.hash) break;\n streak += 1;\n }\n if (streak < limit) return undefined;\n return `the model made ${streak} identical failing calls to ${last.tool} in a row`;\n}\n\n/** The reason when some key has `limit` calls and no success since its first, or `undefined`. */\nfunction repeatedKey(attempts: readonly Attempt[], limit: number): string | undefined {\n const counts = new Map<string, number>();\n for (const { tool, key, failed } of attempts) {\n if (key === undefined) continue;\n const id = JSON.stringify([tool, key]);\n const count = failed ? (counts.get(id) ?? 0) + 1 : 0;\n counts.set(id, count);\n if (count >= limit)\n return `the model called ${tool} ${count} times with the key ${JSON.stringify(key)} and none succeeded`;\n }\n return undefined;\n}\n\n/** The progress check the loop runs after each step: the reason the run is stuck, or `undefined`. */\nexport type ProgressCheck = (messages: readonly Message[]) => Promise<string | undefined>;\n\n/**\n * The default progress policy as a check over the transcript. `skip` is how many messages came before this run's\n * own, so a run continued from a context that ended in a loop is not stopped by the old calls. The transcript only\n * grows, so each call's hash and key are worked out once and kept by its place in it.\n */\nexport function progressCheck(\n tools: readonly AnyTool[],\n policy: Required<ProgressPolicy>,\n skip: number,\n): ProgressCheck {\n const byName = new Map(tools.map((tool) => [tool.name, tool]));\n const facts = new Map<string, CallFacts>();\n return async (messages) => {\n const attempts = await attemptsOf(messages.slice(skip), byName, facts);\n return identicalFailures(attempts, policy.maxIdenticalFailures) ?? repeatedKey(attempts, policy.maxSameKeyCalls);\n };\n}\n"]}
package/dist/result.d.ts CHANGED
@@ -18,8 +18,9 @@ export interface RunError {
18
18
  * `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or
19
19
  * credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a
20
20
  * rejected request. `hook`: an interceptor threw while the run fails closed, and `message` says which one.
21
+ * `unknown_price`: the run has a `budgetUsd`, but a price it needs is unknown, so it can't check the spend.
21
22
  */
22
- readonly kind: NonNullable<AssistantMessage["error"]>["kind"] | "hook";
23
+ readonly kind: NonNullable<AssistantMessage["error"]>["kind"] | "hook" | "unknown_price";
23
24
  readonly message: string;
24
25
  /** The provider's HTTP status, when the failure came with one. */
25
26
  readonly status?: number;
@@ -57,11 +58,27 @@ export interface DoneResult<S> extends ResultBase {
57
58
  export interface EndedResult extends ResultBase {
58
59
  readonly stopReason: "max_steps" | "aborted";
59
60
  }
60
- /** A run that a `shouldStop` hook ended with `{ stop: "no_progress" }`, which gave `reason`. */
61
+ /**
62
+ * A run that stopped making progress. The default progress policy ends a run this way after 3 identical failing tool
63
+ * calls in a row, or after 5 failing calls to a tool with one `progressKey`; pass `progress` to `run()` to change the
64
+ * thresholds, or `progress: false` to turn the policy off. A `shouldStop` hook that returns `{ stop: "no_progress" }`
65
+ * ends a run this way too. `reason` says which rule or hook fired.
66
+ */
61
67
  export interface NoProgressResult extends ResultBase {
62
68
  readonly stopReason: "no_progress";
63
69
  readonly reason: string;
64
70
  }
71
+ /**
72
+ * A run that ended before a model call because that call could have taken the spend past `budgetUsd`. `spentUsd` is
73
+ * what the run's earlier calls cost, and `projectedUsd` the most the refused call could have cost.
74
+ */
75
+ export interface BudgetResult extends ResultBase {
76
+ readonly stopReason: "budget";
77
+ readonly reason: string;
78
+ readonly budgetUsd: number;
79
+ readonly spentUsd: number;
80
+ readonly projectedUsd: number;
81
+ }
65
82
  /** A run that ended because a model call failed, or because an interceptor failed while the run fails closed. */
66
83
  export interface ErrorResult extends ResultBase {
67
84
  readonly stopReason: "error";
@@ -78,6 +95,6 @@ export interface StoppedResult extends ResultBase {
78
95
  readonly stoppedBy: string;
79
96
  }
80
97
  /** What a run returns. Check `stopReason` before you read the fields of one variant. */
81
- export type RunResult<S = unknown> = DoneResult<S> | EndedResult | ErrorResult | NoProgressResult | StoppedResult;
98
+ export type RunResult<S = unknown> = DoneResult<S> | BudgetResult | EndedResult | ErrorResult | NoProgressResult | StoppedResult;
82
99
  /** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */
83
100
  export type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;
@@ -1 +1 @@
1
- {"version":3,"file":"result.js","sourceRoot":"","sources":["../src/result.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * What a run returns: a union discriminated by `stopReason`, in which only the `done` variant carries `output`, so\n * code that reads the output without checking the stop reason fails to compile (D10). Every variant carries the\n * usage, the cost and a context the run can continue from.\n */\nimport type { AssistantMessage, Cost, Message, Usage } from \"@buildanagent/gateway\";\n\n/**\n * A run's conversation as plain JSON: the system prompt and every message so far. Store it anywhere and pass it to\n * `continueRun()` to go on from where the run stopped.\n */\nexport interface Context {\n readonly system: string;\n readonly messages: readonly Message[];\n}\n\n/** Why a model call failed, copied from the failed message's `error`. */\nexport interface RunError {\n /**\n * `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or\n * credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a\n * rejected request. `hook`: an interceptor threw while the run fails closed, and `message` says which one.\n */\n readonly kind: NonNullable<AssistantMessage[\"error\"]>[\"kind\"] | \"hook\";\n readonly message: string;\n /** The provider's HTTP status, when the failure came with one. */\n readonly status?: number;\n}\n\n/** The fields every run result carries. */\nexport interface ResultBase {\n /** The messages this run added: the input, if any, then every response and tool result, in order. */\n readonly messages: readonly Message[];\n /** The whole conversation, earlier history included, ready for `continueRun()`. */\n readonly context: Context;\n /** The tokens of every model call, summed. */\n readonly usage: Usage;\n /**\n * The cost of every model call, summed. It is unknown if any call's cost is. A run that made no call costs an exact\n * 0 with basis `provider`, so adding it to another cost keeps that cost's basis.\n */\n readonly cost: Cost;\n /** How many model calls the run made. */\n readonly steps: number;\n}\n\n/**\n * A run that finished: the model answered without calling a tool, or an output tool accepted its answer. `output` is\n * the accepted answer, and `undefined` when the run has no output tool, the model answered in text, or another tool\n * ended the run with `terminate: true`. A text\n * answer cut off at the output limit also ends `done`; its message's `stopReason` is then `\"length\"`.\n */\nexport interface DoneResult<S> extends ResultBase {\n readonly stopReason: \"done\";\n readonly output: S | undefined;\n}\n\n/**\n * A run that ended before it finished. `max_steps`: it made `maxSteps` model calls and the model still wanted to\n * continue. `aborted`: it was aborted.\n */\nexport interface EndedResult extends ResultBase {\n readonly stopReason: \"max_steps\" | \"aborted\";\n}\n\n/** A run that a `shouldStop` hook ended with `{ stop: \"no_progress\" }`, which gave `reason`. */\nexport interface NoProgressResult extends ResultBase {\n readonly stopReason: \"no_progress\";\n readonly reason: string;\n}\n\n/** A run that ended because a model call failed, or because an interceptor failed while the run fails closed. */\nexport interface ErrorResult extends ResultBase {\n readonly stopReason: \"error\";\n readonly error: RunError;\n}\n\n/**\n * A run that stopped before it finished, for a reason `stoppedBy` names. `clarification`: a tool from\n * `clarificationTool()` asked the user a question. Any other value is the `reason` a `shouldStop` hook gave, or\n * `\"hook\"` when it returned `true`. To go on, add the answer to `context` as a user message and pass the\n * context to `continueRun()`.\n */\nexport interface StoppedResult extends ResultBase {\n readonly stopReason: \"stopped\";\n readonly stoppedBy: string;\n}\n\n/** What a run returns. Check `stopReason` before you read the fields of one variant. */\nexport type RunResult<S = unknown> = DoneResult<S> | EndedResult | ErrorResult | NoProgressResult | StoppedResult;\n\n/** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */\nexport type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;\n"]}
1
+ {"version":3,"file":"result.js","sourceRoot":"","sources":["../src/result.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * What a run returns: a union discriminated by `stopReason`, in which only the `done` variant carries `output`, so\n * code that reads the output without checking the stop reason fails to compile (D10). Every variant carries the\n * usage, the cost and a context the run can continue from.\n */\nimport type { AssistantMessage, Cost, Message, Usage } from \"@buildanagent/gateway\";\n\n/**\n * A run's conversation as plain JSON: the system prompt and every message so far. Store it anywhere and pass it to\n * `continueRun()` to go on from where the run stopped.\n */\nexport interface Context {\n readonly system: string;\n readonly messages: readonly Message[];\n}\n\n/** Why a model call failed, copied from the failed message's `error`. */\nexport interface RunError {\n /**\n * `overflow`: the request was larger than the model's context window. `quota`: the account is out of quota or\n * credit. `retryable`: a temporary failure that outlasted the model's retries. `fatal`: any other failure, such as a\n * rejected request. `hook`: an interceptor threw while the run fails closed, and `message` says which one.\n * `unknown_price`: the run has a `budgetUsd`, but a price it needs is unknown, so it can't check the spend.\n */\n readonly kind: NonNullable<AssistantMessage[\"error\"]>[\"kind\"] | \"hook\" | \"unknown_price\";\n readonly message: string;\n /** The provider's HTTP status, when the failure came with one. */\n readonly status?: number;\n}\n\n/** The fields every run result carries. */\nexport interface ResultBase {\n /** The messages this run added: the input, if any, then every response and tool result, in order. */\n readonly messages: readonly Message[];\n /** The whole conversation, earlier history included, ready for `continueRun()`. */\n readonly context: Context;\n /** The tokens of every model call, summed. */\n readonly usage: Usage;\n /**\n * The cost of every model call, summed. It is unknown if any call's cost is. A run that made no call costs an exact\n * 0 with basis `provider`, so adding it to another cost keeps that cost's basis.\n */\n readonly cost: Cost;\n /** How many model calls the run made. */\n readonly steps: number;\n}\n\n/**\n * A run that finished: the model answered without calling a tool, or an output tool accepted its answer. `output` is\n * the accepted answer, and `undefined` when the run has no output tool, the model answered in text, or another tool\n * ended the run with `terminate: true`. A text\n * answer cut off at the output limit also ends `done`; its message's `stopReason` is then `\"length\"`.\n */\nexport interface DoneResult<S> extends ResultBase {\n readonly stopReason: \"done\";\n readonly output: S | undefined;\n}\n\n/**\n * A run that ended before it finished. `max_steps`: it made `maxSteps` model calls and the model still wanted to\n * continue. `aborted`: it was aborted.\n */\nexport interface EndedResult extends ResultBase {\n readonly stopReason: \"max_steps\" | \"aborted\";\n}\n\n/**\n * A run that stopped making progress. The default progress policy ends a run this way after 3 identical failing tool\n * calls in a row, or after 5 failing calls to a tool with one `progressKey`; pass `progress` to `run()` to change the\n * thresholds, or `progress: false` to turn the policy off. A `shouldStop` hook that returns `{ stop: \"no_progress\" }`\n * ends a run this way too. `reason` says which rule or hook fired.\n */\nexport interface NoProgressResult extends ResultBase {\n readonly stopReason: \"no_progress\";\n readonly reason: string;\n}\n\n/**\n * A run that ended before a model call because that call could have taken the spend past `budgetUsd`. `spentUsd` is\n * what the run's earlier calls cost, and `projectedUsd` the most the refused call could have cost.\n */\nexport interface BudgetResult extends ResultBase {\n readonly stopReason: \"budget\";\n readonly reason: string;\n readonly budgetUsd: number;\n readonly spentUsd: number;\n readonly projectedUsd: number;\n}\n\n/** A run that ended because a model call failed, or because an interceptor failed while the run fails closed. */\nexport interface ErrorResult extends ResultBase {\n readonly stopReason: \"error\";\n readonly error: RunError;\n}\n\n/**\n * A run that stopped before it finished, for a reason `stoppedBy` names. `clarification`: a tool from\n * `clarificationTool()` asked the user a question. Any other value is the `reason` a `shouldStop` hook gave, or\n * `\"hook\"` when it returned `true`. To go on, add the answer to `context` as a user message and pass the\n * context to `continueRun()`.\n */\nexport interface StoppedResult extends ResultBase {\n readonly stopReason: \"stopped\";\n readonly stoppedBy: string;\n}\n\n/** What a run returns. Check `stopReason` before you read the fields of one variant. */\nexport type RunResult<S = unknown> =\n | DoneResult<S>\n | BudgetResult\n | EndedResult\n | ErrorResult\n | NoProgressResult\n | StoppedResult;\n\n/** Every run result except `done`, which `runOrThrow()` turns into a `RunStoppedError`. */\nexport type UnfinishedResult = Exclude<RunResult, DoneResult<unknown>>;\n"]}
package/dist/run.d.ts CHANGED
@@ -6,9 +6,10 @@
6
6
  import type { ContentBlock, Message, Model } from "@buildanagent/gateway";
7
7
  import type { AgentEvent } from "./events.js";
8
8
  import type { CallOptions, Interceptors, Observer } from "./hooks.js";
9
+ import { type ProgressPolicy } from "./progress.js";
9
10
  import type { Context, DoneResult, RunResult } from "./result.js";
10
11
  import type { Clock } from "./testing/determinism.js";
11
- import type { ToolDefinition } from "./tools/types.js";
12
+ import type { ToolContext, ToolDefinition } from "./tools/types.js";
12
13
  /** The options `run()` and `continueRun()` share. */
13
14
  export interface RunOptions<S = unknown> {
14
15
  /** The model, from `createModel()`. */
@@ -28,6 +29,30 @@ export interface RunOptions<S = unknown> {
28
29
  * ends with `stopReason: "max_steps"` and emits a `warning` event with `code: "max_steps"`.
29
30
  */
30
31
  readonly maxSteps?: number;
32
+ /**
33
+ * The most the run's model calls may cost, in USD. Before each call the run projects its cost with
34
+ * `projectCallCost()` and, if the spend so far plus that projection would pass the cap, ends with
35
+ * `stopReason: "budget"` without making the call. The cap counts the calls this run makes, not the cost of the
36
+ * history a `continueRun()` starts from. A budgeted run on a model whose price is unknown ends `error` with
37
+ * `error.kind: "unknown_price"` before its first call, because it could not tell what it spent. Without it, a run
38
+ * has no cap.
39
+ */
40
+ readonly budgetUsd?: number;
41
+ /**
42
+ * The default progress policy: the run ends `no_progress` after 3 identical failing tool calls in a row, or after 5
43
+ * calls to a tool with one `progressKey` and no success between them. It runs after your own `shouldStop`, whose
44
+ * `{ continue }` can't keep a stuck run going. Pass numbers to change either threshold, or `false` to turn the
45
+ * policy off.
46
+ */
47
+ readonly progress?: ProgressPolicy | false;
48
+ /**
49
+ * How deeply this run is nested inside other agents' tool calls. Default 0. A tool that starts a run of its own
50
+ * passes `depth: ctx.depth + 1` and `maxDepth: ctx.maxDepth`; `run()` throws an `SdkError` with code
51
+ * `max_depth_exceeded` when `depth` is above `maxDepth`, which the tool's caller reads as an error result.
52
+ */
53
+ readonly depth?: number;
54
+ /** The deepest nesting allowed, which tools read as `ctx.maxDepth`. Default 2. */
55
+ readonly maxDepth?: number;
31
56
  /** Aborts the run, like `run.abort()`. */
32
57
  readonly signal?: AbortSignal;
33
58
  /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */
@@ -88,6 +113,15 @@ export interface Run<S = unknown> extends AsyncIterable<AgentEvent> {
88
113
  */
89
114
  on(observer: Observer): () => void;
90
115
  }
116
+ /**
117
+ * The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under
118
+ * the same cap. Spread it into the nested `run()`; the nested run throws `max_depth_exceeded` when the tool was
119
+ * already at `maxDepth`.
120
+ */
121
+ export declare function nestedRunDepth(ctx: Pick<ToolContext, "depth" | "maxDepth">): {
122
+ depth: number;
123
+ maxDepth: number;
124
+ };
91
125
  /**
92
126
  * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool
93
127
  * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an
package/dist/run.js CHANGED
@@ -1,10 +1,14 @@
1
+ import { checkBudgetOption } from "./budget.js";
1
2
  import { RunStoppedError, SdkError } from "./errors.js";
2
3
  import { runLoop } from "./loop.js";
3
4
  import { ObserverBus } from "./observers.js";
5
+ import { progressCheck, resolveProgress } from "./progress.js";
4
6
  import { preparedSchemaOf } from "./tools/define.js";
5
7
  import { SDK_VERSION } from "./version.js";
6
8
  /** The step cap's default, counted in model calls. */
7
9
  const DEFAULT_MAX_STEPS = 20;
10
+ /** The depth cap's default (D11): a top-level run, its subagents and their subagents may run, and no deeper. */
11
+ const DEFAULT_MAX_DEPTH = 2;
8
12
  /** How long the run waits, by default, for an observer to catch up before it drops it. */
9
13
  const DEFAULT_OBSERVER_TIMEOUT_MS = 10_000;
10
14
  /** The longest delay `setTimeout` accepts; a larger one fires at once on Node and workerd alike. */
@@ -173,6 +177,36 @@ function toolsOf(options) {
173
177
  }
174
178
  return tools;
175
179
  }
180
+ function isCount(value) {
181
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
182
+ }
183
+ /**
184
+ * The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under
185
+ * the same cap. Spread it into the nested `run()`; the nested run throws `max_depth_exceeded` when the tool was
186
+ * already at `maxDepth`.
187
+ */
188
+ export function nestedRunDepth(ctx) {
189
+ return { depth: ctx.depth + 1, maxDepth: ctx.maxDepth };
190
+ }
191
+ /** Checks `depth` and `maxDepth`, and refuses a run nested deeper than the cap allows (D11). */
192
+ function depthsOf(options) {
193
+ const { depth = 0, maxDepth = DEFAULT_MAX_DEPTH } = options;
194
+ if (!isCount(depth) || !isCount(maxDepth)) {
195
+ throw new SdkError("invalid_run_options", `depth and maxDepth must be whole numbers, 0 or more, got ${String(depth)} and ${String(maxDepth)}`);
196
+ }
197
+ if (depth > maxDepth) {
198
+ throw new SdkError("max_depth_exceeded", `a run at depth ${depth} is deeper than maxDepth ${maxDepth} allows`);
199
+ }
200
+ return { depth, maxDepth };
201
+ }
202
+ /**
203
+ * The default progress policy for this run, or `undefined` when `progress: false` turns it off. `skip` is the number
204
+ * of messages before the run's own.
205
+ */
206
+ function progressOf(options, tools, skip) {
207
+ const policy = resolveProgress(options.progress);
208
+ return policy === undefined ? undefined : progressCheck(tools, policy, skip);
209
+ }
176
210
  function setupOf(options, context, input) {
177
211
  if (!isModel(options.model)) {
178
212
  throw new SdkError("invalid_run_options", "the model must come from createModel(), such as createModel({ adapter, id })");
@@ -181,7 +215,10 @@ function setupOf(options, context, input) {
181
215
  if (!Number.isInteger(maxSteps) || maxSteps < 1) {
182
216
  throw new SdkError("invalid_run_options", `maxSteps must be a positive integer, got ${maxSteps}`);
183
217
  }
218
+ const budgetUsd = checkBudgetOption(options.budgetUsd);
184
219
  const tools = toolsOf(options);
220
+ const { depth, maxDepth } = depthsOf(options);
221
+ const progress = progressOf(options, tools, context.messages.length + input.length);
185
222
  if (options.output !== undefined && (options.output.exposure ?? "direct") !== "direct") {
186
223
  throw new SdkError("invalid_run_options", `the output tool "${options.output.name}" must be sent to the model, so its exposure must be "direct"`);
187
224
  }
@@ -194,8 +231,12 @@ function setupOf(options, context, input) {
194
231
  tools,
195
232
  output: options.output,
196
233
  maxSteps,
234
+ ...(budgetUsd === undefined ? {} : { budgetUsd }),
235
+ depth,
236
+ maxDepth,
197
237
  modelOptions: options.modelOptions ?? {},
198
238
  interceptors: checkInterceptors(options.interceptors ?? {}),
239
+ ...(progress === undefined ? {} : { progress }),
199
240
  clock: options.clock ?? systemClock,
200
241
  };
201
242
  }