@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/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,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;AAM3D,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;AACH,MAAM,OAAO,GAAS,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAyDvE,wCAAwC;AACxC,MAAM,SAAS;IACJ,KAAK,CAAY;IACjB,IAAI,CAAO;IACX,QAAQ,CAAY;IACpB,KAAK,CAAY;IACjB,KAAK,CA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,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,IAAI,CAAC;QACH,OAAO,OAAO,KAAK,SAAS,EAAE,CAAC;YAC7B,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;QACpF,CAAC;IACH,CAAC;YAAS,CAAC;QACT,6GAA6G;QAC7G,6CAA6C;QAC7C,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,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 { SteeringQueue } from \"./steering.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 /** The messages a caller queued with `steer()` and `followUp()`, applied only at step boundaries. */\n readonly steering: SteeringQueue;\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 /** Set when the run was kept going to deliver a follow-up, so the next step boundary applies the follow-ups too. */\n releaseFollowUps = false;\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/**\n * Applies the queued messages before a model call: every steer, and the follow-ups too once the run was kept going to\n * deliver them. Each becomes a user message and a `steer_applied` event, in the order it was sent, and its receipt\n * resolves with the index of the step about to run.\n */\nfunction applySteering(state: LoopState): void {\n const { steering } = state.setup;\n const withFollowUps = state.releaseFollowUps;\n state.releaseFollowUps = false;\n for (const delivery of steering.take(withFollowUps)) {\n // A copy, so a caller who changes a receipt's message cannot change the transcript.\n state.append({ role: \"user\", content: delivery.message.map((block) => ({ ...block })) });\n state.send({ type: \"steer_applied\", receipt: delivery.deliver(state.stepIndex) });\n }\n}\n\n/**\n * Keeps a run that its model ended by answering going, when a message is waiting and the step cap leaves room for\n * one more call: a steer comes first, and follow-ups wait for the next time the run would end. Any other outcome\n * stands, as does a `stop` or `no_progress` verdict that `withVerdict` folded into `done`, and an abort that came\n * after the answer, which `stopCheck` lets the answer win over. The messages still waiting are rejected when the run\n * ends.\n */\nfunction withQueued(state: LoopState, outcome: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n const { steering, maxSteps, signal } = state.setup;\n if (outcome?.stopReason !== \"done\" || !steering.hasPending() || state.steps >= maxSteps) return outcome;\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || signal.aborted) return outcome;\n state.releaseFollowUps = !steering.hasSteers();\n return undefined;\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 const judged = await withProgress(state, verdict);\n const outcome = withVerdict(state, natural, judged);\n return endedByAnswer ? withQueued(state, outcome, judged) : outcome;\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 applySteering(state);\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 try {\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n } finally {\n // The run has its outcome, or threw for a programmer error, so a message still waiting can no longer reach a\n // model call, and its receipt must not hang.\n setup.steering.close();\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;AAM3D,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAgB,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAKtF,kEAAkE;AAClE,MAAM,aAAa,GAAG,eAAe,CAAC;AAEtC;;;GAGG;AACH,MAAM,OAAO,GAAS,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAkEvE,wCA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AE,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,IAAI,CAAC;QACH,OAAO,OAAO,KAAK,SAAS,EAAE,CAAC;YAC7B,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;QACpF,CAAC;IACH,CAAC;YAAS,CAAC;QACT,6GAA6G;QAC7G,6CAA6C;QAC7C,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,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 { SteeringQueue } from \"./steering.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\";\nimport type { SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\nimport type { ApprovalSigner } from \"./vendor/agent-safety/signer.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 /** The messages a caller queued with `steer()` and `followUp()`, applied only at step boundaries. */\n readonly steering: SteeringQueue;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n /** Signs the pending request of each call a gate asks about (D5). */\n readonly signer: ApprovalSigner;\n /** Makes each pending request's id. */\n readonly nextId: () => string;\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 readonly stopReason: \"awaiting_approval\";\n readonly pending: readonly SignedPendingRequest[];\n readonly pendingInputs: Readonly<Record<string, unknown>>;\n };\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 /** Set when the run was kept going to deliver a follow-up, so the next step boundary applies the follow-ups too. */\n releaseFollowUps = false;\n /** The signed requests of the calls that gates paused, in model order. */\n readonly pending: SignedPendingRequest[] = [];\n /**\n * The input each pending request signs, by request id. It has no prototype, because an id comes from the host's\n * `idGenerator` and `\"__proto__\"` must be stored as a key like any other.\n */\n readonly pendingInputs: Record<string, unknown> = Object.create(null);\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 signer: setup.signer,\n nextId: setup.nextId,\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 onPause: ({ request, input }) => {\n state.pending.push(request);\n state.pendingInputs[request.id] = input;\n state.send({ type: \"approval_request\", request, input });\n },\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 pause, a finished answer or a question for the user wins over an abort that came\n * too late to change it; otherwise an abort stops the run before the step cap does. A pause wins over a finished\n * answer too, because its call is still waiting. 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 // A paused call is still waiting, so the run can't count as finished, and the pause is signed and stored with the\n // context, so it outlasts an abort that came while the step's other calls ran.\n if (state.pending.length > 0) {\n return { stopReason: \"awaiting_approval\", pending: [...state.pending], pendingInputs: { ...state.pendingInputs } };\n }\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/**\n * Applies the queued messages before a model call: every steer, and the follow-ups too once the run was kept going to\n * deliver them. Each becomes a user message and a `steer_applied` event, in the order it was sent, and its receipt\n * resolves with the index of the step about to run.\n */\nfunction applySteering(state: LoopState): void {\n const { steering } = state.setup;\n const withFollowUps = state.releaseFollowUps;\n state.releaseFollowUps = false;\n for (const delivery of steering.take(withFollowUps)) {\n // A copy, so a caller who changes a receipt's message cannot change the transcript.\n state.append({ role: \"user\", content: delivery.message.map((block) => ({ ...block })) });\n state.send({ type: \"steer_applied\", receipt: delivery.deliver(state.stepIndex) });\n }\n}\n\n/**\n * Keeps a run that its model ended by answering going, when a message is waiting and the step cap leaves room for\n * one more call: a steer comes first, and follow-ups wait for the next time the run would end. Any other outcome\n * stands, as does a `stop` or `no_progress` verdict that `withVerdict` folded into `done`, and an abort that came\n * after the answer, which `stopCheck` lets the answer win over. The messages still waiting are rejected when the run\n * ends.\n */\nfunction withQueued(state: LoopState, outcome: Outcome | undefined, verdict: StopVerdict): Outcome | undefined {\n const { steering, maxSteps, signal } = state.setup;\n if (outcome?.stopReason !== \"done\" || !steering.hasPending() || state.steps >= maxSteps) return outcome;\n if (verdict.kind === \"stop\" || verdict.kind === \"no_progress\" || signal.aborted) return outcome;\n state.releaseFollowUps = !steering.hasSteers();\n return undefined;\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 const judged = await withProgress(state, verdict);\n const outcome = withVerdict(state, natural, judged);\n return endedByAnswer ? withQueued(state, outcome, judged) : outcome;\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 applySteering(state);\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 pending =\n outcome.stopReason === \"awaiting_approval\"\n ? { pending: [...outcome.pending], pendingInputs: { ...outcome.pendingInputs } }\n : {};\n const base = {\n messages: state.added,\n context: { system: state.setup.system, messages: state.messages, ...pending },\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 try {\n while (outcome === undefined) {\n outcome = setup.signal.aborted ? { stopReason: \"aborted\" } : await runStep(state);\n }\n } finally {\n // The run has its outcome, or threw for a programmer error, so a message still waiting can no longer reach a\n // model call, and its receipt must not hang.\n setup.steering.close();\n }\n return finish(state, outcome);\n}\n"]}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OpenTelemetry GenAI names the observer writes, in one place. The GenAI semantic conventions are at Development
|
|
3
|
+
* stability, so a rename upstream is a one-line change here, and the harness's log projection imports the same names.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* The commit of `open-telemetry/semantic-conventions-genai` whose attribute and span names this module follows. A
|
|
7
|
+
* harness that exports spans can stamp it on its resource, so a reader knows which revision of the conventions the
|
|
8
|
+
* names come from.
|
|
9
|
+
*/
|
|
10
|
+
export declare const SEMCONV_GENAI_COMMIT: "d28355d";
|
|
11
|
+
/** The `gen_ai.*` and `error.*` attribute names the observer writes, keyed by what each holds. */
|
|
12
|
+
export declare const GEN_AI_ATTRIBUTES: Readonly<{
|
|
13
|
+
readonly operationName: "gen_ai.operation.name";
|
|
14
|
+
readonly providerName: "gen_ai.provider.name";
|
|
15
|
+
readonly agentName: "gen_ai.agent.name";
|
|
16
|
+
readonly requestModel: "gen_ai.request.model";
|
|
17
|
+
readonly requestMaxTokens: "gen_ai.request.max_tokens";
|
|
18
|
+
readonly requestTemperature: "gen_ai.request.temperature";
|
|
19
|
+
readonly responseFinishReasons: "gen_ai.response.finish_reasons";
|
|
20
|
+
readonly usageInputTokens: "gen_ai.usage.input_tokens";
|
|
21
|
+
readonly usageOutputTokens: "gen_ai.usage.output_tokens";
|
|
22
|
+
readonly usageCacheReadInputTokens: "gen_ai.usage.cache_read.input_tokens";
|
|
23
|
+
readonly usageCacheWriteInputTokens: "gen_ai.usage.cache_write.input_tokens";
|
|
24
|
+
readonly usageReasoningOutputTokens: "gen_ai.usage.reasoning.output_tokens";
|
|
25
|
+
readonly toolName: "gen_ai.tool.name";
|
|
26
|
+
readonly toolType: "gen_ai.tool.type";
|
|
27
|
+
readonly toolCallId: "gen_ai.tool.call.id";
|
|
28
|
+
readonly errorType: "error.type";
|
|
29
|
+
/** Content: written only when `captureContent` is on. */
|
|
30
|
+
readonly systemInstructions: "gen_ai.system_instructions";
|
|
31
|
+
readonly inputMessages: "gen_ai.input.messages";
|
|
32
|
+
readonly outputMessages: "gen_ai.output.messages";
|
|
33
|
+
readonly toolCallArguments: "gen_ai.tool.call.arguments";
|
|
34
|
+
readonly toolCallResult: "gen_ai.tool.call.result";
|
|
35
|
+
}>;
|
|
36
|
+
/** The names of the attributes that hold content: what the model and the tools read and wrote. */
|
|
37
|
+
export declare const GEN_AI_CONTENT_ATTRIBUTES: readonly string[];
|
|
38
|
+
/** The `gen_ai.operation.name` values the observer writes. */
|
|
39
|
+
export declare const GEN_AI_OPERATIONS: Readonly<{
|
|
40
|
+
readonly invokeAgent: "invoke_agent";
|
|
41
|
+
readonly chat: "chat";
|
|
42
|
+
readonly executeTool: "execute_tool";
|
|
43
|
+
}>;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OpenTelemetry GenAI names the observer writes, in one place. The GenAI semantic conventions are at Development
|
|
3
|
+
* stability, so a rename upstream is a one-line change here, and the harness's log projection imports the same names.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* The commit of `open-telemetry/semantic-conventions-genai` whose attribute and span names this module follows. A
|
|
7
|
+
* harness that exports spans can stamp it on its resource, so a reader knows which revision of the conventions the
|
|
8
|
+
* names come from.
|
|
9
|
+
*/
|
|
10
|
+
export const SEMCONV_GENAI_COMMIT = "d28355d";
|
|
11
|
+
/** The `gen_ai.*` and `error.*` attribute names the observer writes, keyed by what each holds. */
|
|
12
|
+
export const GEN_AI_ATTRIBUTES = Object.freeze({
|
|
13
|
+
operationName: "gen_ai.operation.name",
|
|
14
|
+
providerName: "gen_ai.provider.name",
|
|
15
|
+
agentName: "gen_ai.agent.name",
|
|
16
|
+
requestModel: "gen_ai.request.model",
|
|
17
|
+
requestMaxTokens: "gen_ai.request.max_tokens",
|
|
18
|
+
requestTemperature: "gen_ai.request.temperature",
|
|
19
|
+
responseFinishReasons: "gen_ai.response.finish_reasons",
|
|
20
|
+
usageInputTokens: "gen_ai.usage.input_tokens",
|
|
21
|
+
usageOutputTokens: "gen_ai.usage.output_tokens",
|
|
22
|
+
usageCacheReadInputTokens: "gen_ai.usage.cache_read.input_tokens",
|
|
23
|
+
usageCacheWriteInputTokens: "gen_ai.usage.cache_write.input_tokens",
|
|
24
|
+
usageReasoningOutputTokens: "gen_ai.usage.reasoning.output_tokens",
|
|
25
|
+
toolName: "gen_ai.tool.name",
|
|
26
|
+
toolType: "gen_ai.tool.type",
|
|
27
|
+
toolCallId: "gen_ai.tool.call.id",
|
|
28
|
+
errorType: "error.type",
|
|
29
|
+
/** Content: written only when `captureContent` is on. */
|
|
30
|
+
systemInstructions: "gen_ai.system_instructions",
|
|
31
|
+
inputMessages: "gen_ai.input.messages",
|
|
32
|
+
outputMessages: "gen_ai.output.messages",
|
|
33
|
+
toolCallArguments: "gen_ai.tool.call.arguments",
|
|
34
|
+
toolCallResult: "gen_ai.tool.call.result",
|
|
35
|
+
});
|
|
36
|
+
/** The names of the attributes that hold content: what the model and the tools read and wrote. */
|
|
37
|
+
export const GEN_AI_CONTENT_ATTRIBUTES = Object.freeze([
|
|
38
|
+
GEN_AI_ATTRIBUTES.systemInstructions,
|
|
39
|
+
GEN_AI_ATTRIBUTES.inputMessages,
|
|
40
|
+
GEN_AI_ATTRIBUTES.outputMessages,
|
|
41
|
+
GEN_AI_ATTRIBUTES.toolCallArguments,
|
|
42
|
+
GEN_AI_ATTRIBUTES.toolCallResult,
|
|
43
|
+
]);
|
|
44
|
+
/** The `gen_ai.operation.name` values the observer writes. */
|
|
45
|
+
export const GEN_AI_OPERATIONS = Object.freeze({
|
|
46
|
+
invokeAgent: "invoke_agent",
|
|
47
|
+
chat: "chat",
|
|
48
|
+
executeTool: "execute_tool",
|
|
49
|
+
});
|
|
50
|
+
//# sourceMappingURL=attributes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|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,cAAc;CACnB,CAAC,CAAC","sourcesContent":["/**\n * The OpenTelemetry GenAI names the observer writes, in one place. The GenAI semantic conventions are at Development\n * stability, so a rename upstream is a one-line change here, and the harness's log projection imports the same names.\n */\n\n/**\n * The commit of `open-telemetry/semantic-conventions-genai` whose attribute and span names this module follows. A\n * harness that exports spans can stamp it on its resource, so a reader knows which revision of the conventions the\n * names come from.\n */\nexport const SEMCONV_GENAI_COMMIT = \"d28355d\" as const;\n\n/** The `gen_ai.*` and `error.*` attribute names the observer writes, keyed by what each holds. */\nexport const GEN_AI_ATTRIBUTES = Object.freeze({\n operationName: \"gen_ai.operation.name\",\n providerName: \"gen_ai.provider.name\",\n agentName: \"gen_ai.agent.name\",\n requestModel: \"gen_ai.request.model\",\n requestMaxTokens: \"gen_ai.request.max_tokens\",\n requestTemperature: \"gen_ai.request.temperature\",\n responseFinishReasons: \"gen_ai.response.finish_reasons\",\n usageInputTokens: \"gen_ai.usage.input_tokens\",\n usageOutputTokens: \"gen_ai.usage.output_tokens\",\n usageCacheReadInputTokens: \"gen_ai.usage.cache_read.input_tokens\",\n usageCacheWriteInputTokens: \"gen_ai.usage.cache_write.input_tokens\",\n usageReasoningOutputTokens: \"gen_ai.usage.reasoning.output_tokens\",\n toolName: \"gen_ai.tool.name\",\n toolType: \"gen_ai.tool.type\",\n toolCallId: \"gen_ai.tool.call.id\",\n errorType: \"error.type\",\n /** Content: written only when `captureContent` is on. */\n systemInstructions: \"gen_ai.system_instructions\",\n inputMessages: \"gen_ai.input.messages\",\n outputMessages: \"gen_ai.output.messages\",\n toolCallArguments: \"gen_ai.tool.call.arguments\",\n toolCallResult: \"gen_ai.tool.call.result\",\n} as const);\n\n/** The names of the attributes that hold content: what the model and the tools read and wrote. */\nexport const GEN_AI_CONTENT_ATTRIBUTES: readonly string[] = Object.freeze([\n GEN_AI_ATTRIBUTES.systemInstructions,\n GEN_AI_ATTRIBUTES.inputMessages,\n GEN_AI_ATTRIBUTES.outputMessages,\n GEN_AI_ATTRIBUTES.toolCallArguments,\n GEN_AI_ATTRIBUTES.toolCallResult,\n]);\n\n/** The `gen_ai.operation.name` values the observer writes. */\nexport const GEN_AI_OPERATIONS = Object.freeze({\n invokeAgent: \"invoke_agent\",\n chat: \"chat\",\n executeTool: \"execute_tool\",\n} as const);\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns the SDK's transcript into the JSON the GenAI conventions describe for content attributes: messages with
|
|
3
|
+
* typed `parts`. Only the observer reads this, and only when `captureContent` is on.
|
|
4
|
+
*/
|
|
5
|
+
import type { ContentBlock, Message, ModelContent } from "@buildanagent/gateway";
|
|
6
|
+
type Part = Readonly<Record<string, unknown>>;
|
|
7
|
+
/** The parts of a result's content, as the conventions' `gen_ai.tool.call.result` or a tool message holds them. */
|
|
8
|
+
export declare function resultParts(content: readonly ModelContent[]): readonly Part[];
|
|
9
|
+
/** `gen_ai.input.messages` for a call's messages, as a JSON string. */
|
|
10
|
+
export declare function inputMessagesJson(messages: readonly Message[]): string;
|
|
11
|
+
/** `gen_ai.output.messages` for the model's answer, as a JSON string. */
|
|
12
|
+
export declare function outputMessagesJson(content: readonly ContentBlock[]): string;
|
|
13
|
+
/** `gen_ai.system_instructions`: the system prompt as one text part. */
|
|
14
|
+
export declare function systemInstructionsJson(system: string): string;
|
|
15
|
+
/** A tool's arguments or result as a JSON string; a value JSON cannot hold becomes its string form. */
|
|
16
|
+
export declare function jsonValue(value: unknown): string;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
function blockPart(block) {
|
|
2
|
+
switch (block.type) {
|
|
3
|
+
case "text":
|
|
4
|
+
return { type: "text", content: block.text };
|
|
5
|
+
case "reasoning":
|
|
6
|
+
return { type: "reasoning", content: block.text };
|
|
7
|
+
case "image":
|
|
8
|
+
// The bytes would swamp a span, so the part keeps the type and drops the data.
|
|
9
|
+
return { type: "blob", modality: "image", mime_type: block.mediaType };
|
|
10
|
+
case "tool_call":
|
|
11
|
+
return { type: "tool_call", id: block.callId, name: block.name, arguments: block.input };
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** The parts of a result's content, as the conventions' `gen_ai.tool.call.result` or a tool message holds them. */
|
|
15
|
+
export function resultParts(content) {
|
|
16
|
+
return content.map(blockPart);
|
|
17
|
+
}
|
|
18
|
+
function messageOf(message) {
|
|
19
|
+
if (message.role === "tool") {
|
|
20
|
+
return {
|
|
21
|
+
role: "tool",
|
|
22
|
+
parts: [{ type: "tool_call_response", id: message.callId, response: resultParts(message.content) }],
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
return { role: message.role, parts: message.content.map(blockPart) };
|
|
26
|
+
}
|
|
27
|
+
/** `gen_ai.input.messages` for a call's messages, as a JSON string. */
|
|
28
|
+
export function inputMessagesJson(messages) {
|
|
29
|
+
return JSON.stringify(messages.map(messageOf));
|
|
30
|
+
}
|
|
31
|
+
/** `gen_ai.output.messages` for the model's answer, as a JSON string. */
|
|
32
|
+
export function outputMessagesJson(content) {
|
|
33
|
+
return JSON.stringify([{ role: "assistant", parts: content.map(blockPart) }]);
|
|
34
|
+
}
|
|
35
|
+
/** `gen_ai.system_instructions`: the system prompt as one text part. */
|
|
36
|
+
export function systemInstructionsJson(system) {
|
|
37
|
+
return JSON.stringify([{ type: "text", content: system }]);
|
|
38
|
+
}
|
|
39
|
+
/** A tool's arguments or result as a JSON string; a value JSON cannot hold becomes its string form. */
|
|
40
|
+
export function jsonValue(value) {
|
|
41
|
+
try {
|
|
42
|
+
return JSON.stringify(value) ?? String(value);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return String(value);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=content.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"content.js","sourceRoot":"","sources":["../../src/otel/content.ts"],"names":[],"mappings":"AAQA,SAAS,SAAS,CAAC,KAAmB;IACpC,QAAQ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AAG,CAAC,SAAS,CAAC,CAAC,CAAC;AACjD,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,kBAAkB,CAAC,OAAgC;IACjE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;AAChF,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,sBAAsB,CAAC,MAAc;IACnD,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;AAC7D,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;IAChD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Turns the SDK's transcript into the JSON the GenAI conventions describe for content attributes: messages with\n * typed `parts`. Only the observer reads this, and only when `captureContent` is on.\n */\nimport type { ContentBlock, Message, ModelContent } from \"@buildanagent/gateway\";\n\ntype Part = Readonly<Record<string, unknown>>;\n\nfunction blockPart(block: ContentBlock): Part {\n switch (block.type) {\n case \"text\":\n return { type: \"text\", content: block.text };\n case \"reasoning\":\n return { type: \"reasoning\", content: block.text };\n case \"image\":\n // The bytes would swamp a span, so the part keeps the type and drops the data.\n return { type: \"blob\", modality: \"image\", mime_type: block.mediaType };\n case \"tool_call\":\n return { type: \"tool_call\", id: block.callId, name: block.name, arguments: block.input };\n }\n}\n\n/** The parts of a result's content, as the conventions' `gen_ai.tool.call.result` or a tool message holds them. */\nexport function resultParts(content: readonly ModelContent[]): readonly Part[] {\n return content.map(blockPart);\n}\n\nfunction messageOf(message: Message): { readonly role: string; readonly parts: readonly Part[] } {\n if (message.role === \"tool\") {\n return {\n role: \"tool\",\n parts: [{ type: \"tool_call_response\", id: message.callId, response: resultParts(message.content) }],\n };\n }\n return { role: message.role, parts: message.content.map(blockPart) };\n}\n\n/** `gen_ai.input.messages` for a call's messages, as a JSON string. */\nexport function inputMessagesJson(messages: readonly Message[]): string {\n return JSON.stringify(messages.map(messageOf));\n}\n\n/** `gen_ai.output.messages` for the model's answer, as a JSON string. */\nexport function outputMessagesJson(content: readonly ContentBlock[]): string {\n return JSON.stringify([{ role: \"assistant\", parts: content.map(blockPart) }]);\n}\n\n/** `gen_ai.system_instructions`: the system prompt as one text part. */\nexport function systemInstructionsJson(system: string): string {\n return JSON.stringify([{ type: \"text\", content: system }]);\n}\n\n/** A tool's arguments or result as a JSON string; a value JSON cannot hold becomes its string form. */\nexport function jsonValue(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n"]}
|
package/dist/otel/index.d.ts
CHANGED
|
@@ -1,2 +1,6 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/sdk/otel`: the OpenTelemetry observer. `otelObserver()` projects a run's events onto `gen_ai.*`
|
|
3
|
+
* spans, with content off unless the caller turns it on, and exports only to the tracer the caller passes.
|
|
4
|
+
*/
|
|
5
|
+
export { GEN_AI_ATTRIBUTES, GEN_AI_CONTENT_ATTRIBUTES, GEN_AI_OPERATIONS, SEMCONV_GENAI_COMMIT, } from "./attributes.js";
|
|
6
|
+
export { type AttributeValueLike, type OtelObserver, type OtelObserverOptions, otelObserver, type SpanLike, type SpanOptionsLike, type TracerLike, } from "./observer.js";
|
package/dist/otel/index.js
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/sdk/otel`: the OpenTelemetry observer. `otelObserver()` projects a run's events onto `gen_ai.*`
|
|
3
|
+
* spans, with content off unless the caller turns it on, and exports only to the tracer the caller passes.
|
|
4
|
+
*/
|
|
5
|
+
export { GEN_AI_ATTRIBUTES, GEN_AI_CONTENT_ATTRIBUTES, GEN_AI_OPERATIONS, SEMCONV_GENAI_COMMIT, } from "./attributes.js";
|
|
6
|
+
export { otelObserver, } from "./observer.js";
|
|
3
7
|
//# sourceMappingURL=index.js.map
|
package/dist/otel/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/otel/index.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/otel/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAIL,YAAY,GAIb,MAAM,eAAe,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk/otel`: the OpenTelemetry observer. `otelObserver()` projects a run's events onto `gen_ai.*`\n * spans, with content off unless the caller turns it on, and exports only to the tracer the caller passes.\n */\nexport {\n GEN_AI_ATTRIBUTES,\n GEN_AI_CONTENT_ATTRIBUTES,\n GEN_AI_OPERATIONS,\n SEMCONV_GENAI_COMMIT,\n} from \"./attributes.js\";\nexport {\n type AttributeValueLike,\n type OtelObserver,\n type OtelObserverOptions,\n otelObserver,\n type SpanLike,\n type SpanOptionsLike,\n type TracerLike,\n} from \"./observer.js\";\n"]}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { Observer } from "../hooks.js";
|
|
2
|
+
/** An attribute value a span accepts. */
|
|
3
|
+
export type AttributeValueLike = string | number | boolean | string[];
|
|
4
|
+
/** What `startSpan` takes: the fields of `@opentelemetry/api`'s `SpanOptions` that the observer sets. */
|
|
5
|
+
export interface SpanOptionsLike {
|
|
6
|
+
/** An OpenTelemetry `SpanKind` number: 0 is internal and 2 is client. */
|
|
7
|
+
readonly kind?: number;
|
|
8
|
+
readonly attributes?: Readonly<Record<string, AttributeValueLike>>;
|
|
9
|
+
/** Start time in milliseconds since the Unix epoch. */
|
|
10
|
+
readonly startTime?: number;
|
|
11
|
+
}
|
|
12
|
+
/** The span methods the observer calls. An OpenTelemetry `Span` has all of them. */
|
|
13
|
+
export interface SpanLike {
|
|
14
|
+
setAttribute(name: string, value: AttributeValueLike): unknown;
|
|
15
|
+
/** `code` 2 is `SpanStatusCode.ERROR`. */
|
|
16
|
+
setStatus?(status: {
|
|
17
|
+
readonly code: number;
|
|
18
|
+
readonly message?: string;
|
|
19
|
+
}): unknown;
|
|
20
|
+
/** `endTime` is in milliseconds since the Unix epoch. */
|
|
21
|
+
end(endTime?: number): void;
|
|
22
|
+
}
|
|
23
|
+
/** The tracer method the observer calls. An OpenTelemetry `Tracer` has it, so a real tracer fits without a wrapper. */
|
|
24
|
+
export interface TracerLike {
|
|
25
|
+
startSpan(name: string, options?: SpanOptionsLike, context?: unknown): SpanLike;
|
|
26
|
+
}
|
|
27
|
+
/** Options for `otelObserver()`. */
|
|
28
|
+
export interface OtelObserverOptions {
|
|
29
|
+
/** The tracer that receives the spans. The observer exports nowhere else. */
|
|
30
|
+
readonly tracer: TracerLike;
|
|
31
|
+
/**
|
|
32
|
+
* Whether to record content: the system prompt, the messages of each call, each tool's arguments and result, and
|
|
33
|
+
* the message of each error as its span's status description. Off by default, because content can hold secrets
|
|
34
|
+
* and personal data that a trace backend should not receive. An error's message can quote any of them, so with
|
|
35
|
+
* content off a failed span gets only its error status and `error.type`.
|
|
36
|
+
*/
|
|
37
|
+
readonly captureContent?: boolean;
|
|
38
|
+
/** The agent's name: it names the `invoke_agent` span and sets `gen_ai.agent.name`. */
|
|
39
|
+
readonly agentName?: string;
|
|
40
|
+
/**
|
|
41
|
+
* The context the run's span starts in, passed to the tracer as `startSpan`'s third argument: the caller's own
|
|
42
|
+
* span, such as an incoming request's. Every run the observer serves starts in this one context, so when it
|
|
43
|
+
* belongs to one request, create one observer for each request. Left out, the run's span starts in whatever the
|
|
44
|
+
* tracer treats as its default, which for an OpenTelemetry tracer is the active context. A run that a tool starts
|
|
45
|
+
* is another run to the observer, with the same `parentContext`: its span is not a child of the calling tool's
|
|
46
|
+
* span, because events carry no parent run id.
|
|
47
|
+
*/
|
|
48
|
+
readonly parentContext?: unknown;
|
|
49
|
+
/**
|
|
50
|
+
* Makes the context a child span starts in from the run's span, so the spans of model and tool calls are children
|
|
51
|
+
* of the run's span in its trace. With OpenTelemetry's API, pass
|
|
52
|
+
* `(span) => trace.setSpan(context.active(), span as Span)`. It is required because the observer imports nothing
|
|
53
|
+
* from OpenTelemetry and so cannot build a context itself.
|
|
54
|
+
*/
|
|
55
|
+
readonly childContext: (parent: SpanLike) => unknown;
|
|
56
|
+
/**
|
|
57
|
+
* Flushes the exporter behind the tracer, such as `() => provider.forceFlush()`. `flush()` on the observer calls
|
|
58
|
+
* it, so a Worker can pass `observer.flush()` to `waitUntil` and keep its spans from dying with the request.
|
|
59
|
+
*/
|
|
60
|
+
readonly forceFlush?: () => Promise<unknown>;
|
|
61
|
+
}
|
|
62
|
+
/** The observer `otelObserver()` returns: an `Observer` that can also flush its exporter and end a run that threw. */
|
|
63
|
+
export type OtelObserver = Observer & {
|
|
64
|
+
/** Resolves once the exporter behind the tracer has flushed, or at once when `forceFlush` was not passed. */
|
|
65
|
+
flush(): Promise<void>;
|
|
66
|
+
/**
|
|
67
|
+
* Ends the open spans of a run whose `result` rejected, as failed, and forgets the run. A run that throws, for a
|
|
68
|
+
* programmer error such as a tool that returns a malformed result, sends no `run_end`, so without this call its
|
|
69
|
+
* spans are never exported. `error.type` is the error's `code` when it has one, such as an `SdkError`'s, and its
|
|
70
|
+
* `name` otherwise. It ends every span, then rethrows the first error a tracer threw. An unknown run id, or a run
|
|
71
|
+
* that already ended, does nothing.
|
|
72
|
+
*/
|
|
73
|
+
endRun(runId: string, error?: unknown): void;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Creates an observer that projects a run's events onto OpenTelemetry GenAI spans. Pass it in `run()`'s
|
|
77
|
+
* `observers`: an observer added later with `run.on()` misses `run_start`, so it records nothing for that run. One
|
|
78
|
+
* observer can serve many runs, because it keeps each run's spans apart by run id.
|
|
79
|
+
*
|
|
80
|
+
* Without `captureContent`, no span holds a prompt, a message, a tool argument, a tool result or an error message.
|
|
81
|
+
*/
|
|
82
|
+
export declare function otelObserver(options: OtelObserverOptions): OtelObserver;
|