@buildanagent/sdk 0.1.0-alpha.1 → 0.1.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +424 -5
- package/dist/budget.d.ts +33 -0
- package/dist/budget.js +55 -0
- package/dist/budget.js.map +1 -0
- package/dist/compose.d.ts +26 -0
- package/dist/compose.js +157 -0
- package/dist/compose.js.map +1 -0
- package/dist/errors.d.ts +49 -0
- package/dist/errors.js +57 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +168 -0
- package/dist/events.js +32 -0
- package/dist/events.js.map +1 -0
- package/dist/freeze.d.ts +11 -0
- package/dist/freeze.js +42 -0
- package/dist/freeze.js.map +1 -0
- package/dist/hook-checks.d.ts +31 -0
- package/dist/hook-checks.js +130 -0
- package/dist/hook-checks.js.map +1 -0
- package/dist/hook-runner.d.ts +96 -0
- package/dist/hook-runner.js +372 -0
- package/dist/hook-runner.js.map +1 -0
- package/dist/hooks.d.ts +183 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +26 -3
- package/dist/index.js +21 -3
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +67 -0
- package/dist/loop.js +644 -0
- package/dist/loop.js.map +1 -0
- package/dist/observers.d.ts +31 -0
- package/dist/observers.js +98 -0
- package/dist/observers.js.map +1 -0
- package/dist/otel/attributes.d.ts +43 -0
- package/dist/otel/attributes.js +50 -0
- package/dist/otel/attributes.js.map +1 -0
- package/dist/otel/content.d.ts +17 -0
- package/dist/otel/content.js +48 -0
- package/dist/otel/content.js.map +1 -0
- package/dist/otel/index.d.ts +6 -2
- package/dist/otel/index.js +6 -2
- package/dist/otel/index.js.map +1 -1
- package/dist/otel/observer.d.ts +82 -0
- package/dist/otel/observer.js +300 -0
- package/dist/otel/observer.js.map +1 -0
- package/dist/pauses.d.ts +61 -0
- package/dist/pauses.js +83 -0
- package/dist/pauses.js.map +1 -0
- package/dist/progress.d.ts +34 -0
- package/dist/progress.js +139 -0
- package/dist/progress.js.map +1 -0
- package/dist/result.d.ts +134 -0
- package/dist/result.js +2 -0
- package/dist/result.js.map +1 -0
- package/dist/resume.d.ts +76 -0
- package/dist/resume.js +237 -0
- package/dist/resume.js.map +1 -0
- package/dist/run.d.ts +214 -0
- package/dist/run.js +327 -0
- package/dist/run.js.map +1 -0
- package/dist/steering.d.ts +52 -0
- package/dist/steering.js +104 -0
- package/dist/steering.js.map +1 -0
- package/dist/testing/scripted-model.d.ts +12 -2
- package/dist/testing/scripted-model.js +19 -2
- package/dist/testing/scripted-model.js.map +1 -1
- package/dist/tools/coerce.d.ts +15 -0
- package/dist/tools/coerce.js +93 -0
- package/dist/tools/coerce.js.map +1 -0
- package/dist/tools/define.d.ts +54 -0
- package/dist/tools/define.js +121 -0
- package/dist/tools/define.js.map +1 -0
- package/dist/tools/format-error.d.ts +13 -0
- package/dist/tools/format-error.js +66 -0
- package/dist/tools/format-error.js.map +1 -0
- package/dist/tools/outcome.d.ts +7 -0
- package/dist/tools/outcome.js +30 -0
- package/dist/tools/outcome.js.map +1 -0
- package/dist/tools/pipeline.d.ts +111 -0
- package/dist/tools/pipeline.js +382 -0
- package/dist/tools/pipeline.js.map +1 -0
- package/dist/tools/scheduler.d.ts +33 -0
- package/dist/tools/scheduler.js +51 -0
- package/dist/tools/scheduler.js.map +1 -0
- package/dist/tools/schema.d.ts +20 -0
- package/dist/tools/schema.js +100 -0
- package/dist/tools/schema.js.map +1 -0
- package/dist/tools/types.d.ts +196 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/vendor/agent-safety/bytes.d.ts +17 -0
- package/dist/vendor/agent-safety/bytes.js +59 -0
- package/dist/vendor/agent-safety/bytes.js.map +1 -0
- package/dist/vendor/agent-safety/errors.d.ts +23 -0
- package/dist/vendor/agent-safety/errors.js +22 -0
- package/dist/vendor/agent-safety/errors.js.map +1 -0
- package/dist/vendor/agent-safety/hash.d.ts +16 -0
- package/dist/vendor/agent-safety/hash.js +110 -0
- package/dist/vendor/agent-safety/hash.js.map +1 -0
- package/dist/vendor/agent-safety/outcome.d.ts +88 -0
- package/dist/vendor/agent-safety/outcome.js +140 -0
- package/dist/vendor/agent-safety/outcome.js.map +1 -0
- package/dist/vendor/agent-safety/pending.d.ts +119 -0
- package/dist/vendor/agent-safety/pending.js +122 -0
- package/dist/vendor/agent-safety/pending.js.map +1 -0
- package/dist/vendor/agent-safety/render.d.ts +40 -0
- package/dist/vendor/agent-safety/render.js +92 -0
- package/dist/vendor/agent-safety/render.js.map +1 -0
- package/dist/vendor/agent-safety/signer.d.ts +42 -0
- package/dist/vendor/agent-safety/signer.js +128 -0
- package/dist/vendor/agent-safety/signer.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +13 -3
package/dist/loop.js.map
ADDED
|
@@ -0,0 +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;AAI3D,OAAO,EAAE,cAAc,EAAkC,MAAM,aAAa,CAAC;AAG7E,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAsC,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAK5G;;;GAGG;AACH,MAAM,OAAO,GAAS,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,E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C,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,IAAI,OAAO,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS;YAAE,OAAO,GAAG,MAAM,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAC3G,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 { judgeOpenCalls, type ResumeSetup, type Verdict } from \"./resume.js\";\nimport type { SteeringQueue } from \"./steering.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { toWireTool } from \"./tools/define.js\";\nimport { type AnyTool, type PipelineContext, runToolCalls, type ToolCallResult } from \"./tools/pipeline.js\";\nimport type { ToolCall, ToolResult } from \"./tools/types.js\";\nimport type { SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\nimport type { ApprovalSigner } from \"./vendor/agent-safety/signer.js\";\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 /** The waiting calls of the context a `continueRun()` resumes, and their resolutions. */\n readonly resume?: ResumeSetup;\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\" | \"clarification_requested\";\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/** Records one call's result: the tool message the model reads, the output tool's answer and `tool_call_end`. */\nfunction recordResult(state: LoopState, entry: ToolCallResult): void {\n const { output } = state.setup;\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/** Holds a signed request for a person: in the run's pending list, by id in its inputs, and as `approval_request`. */\nfunction holdPause(state: LoopState, request: SignedPendingRequest, input: unknown): void {\n state.pending.push(request);\n state.pendingInputs[request.id] = input;\n state.send({ type: \"approval_request\", request, input });\n}\n\n/** True for a result that asks the user a question, which pauses its call instead of reaching the model. */\nfunction asksUser(result: ToolResult): boolean {\n return result.pause !== undefined && result.isError !== true;\n}\n\n/** The pipeline callbacks every tool batch of the run shares. `onResult` holds back a question for `askUser()`. */\nfunction pipelineOf(state: LoopState, asks: ToolCallResult[]): PipelineContext {\n const { runId, signal, clock, depth, maxDepth } = state.setup;\n return {\n runId,\n signal,\n clock,\n depth,\n maxDepth,\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 }) => holdPause(state, request, input),\n onResult: (entry) => {\n if (asksUser(entry.result)) asks.push(entry);\n else recordResult(state, entry);\n },\n };\n}\n\n/**\n * Signs a clarification request for each call whose tool asked the user a question, in model order. The call then\n * waits like a paused one, with no result; a question that can't be signed reaches the model as an error result.\n * Returns the batch's results with those error results in place.\n */\nasync function askUser(\n state: LoopState,\n results: readonly ToolCallResult[],\n asks: readonly ToolCallResult[],\n): Promise<ToolCallResult[]> {\n const replaced = new Map<ToolCallResult, ToolCallResult>();\n for (const entry of asks) {\n const question = entry.result.pause?.question;\n const outcome = await state.hooks.clarify(entry.call, entry.ranWith, question as string);\n if (\"paused\" in outcome) {\n holdPause(state, outcome.paused, outcome.input);\n } else if (\"blocked\" in outcome) {\n const blocked = { call: entry.call, result: outcome.blocked };\n recordResult(state, blocked);\n replaced.set(entry, blocked);\n }\n }\n return results.map((entry) => replaced.get(entry) ?? entry);\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 asks: ToolCallResult[] = [];\n const results = await runToolCalls(message, state.active, {\n ...pipelineOf(state, asks),\n ...state.hooks.pipelineHooks(),\n });\n return asks.length === 0 ? results : askUser(state, results, asks);\n}\n\n/**\n * The outcome of a run whose calls wait for a person. Its requests are put in the model's order of their calls, and\n * it ends `awaiting_approval` when any waits for an approval, or `clarification_requested` when all wait for answers.\n */\nfunction pausedOutcome(state: LoopState, message: AssistantMessage): Outcome {\n const order = callOrderOf(message);\n const pending = [...state.pending].sort((a, b) => order.indexOf(a.callId) - order.indexOf(b.callId));\n const approval = pending.some((request) => request.kind === \"approval\");\n return {\n stopReason: approval ? \"awaiting_approval\" : \"clarification_requested\",\n pending,\n pendingInputs: { ...state.pendingInputs },\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, including a question for the user, or a finished answer wins over an abort\n * that came too late to change it; otherwise an abort stops the run before the step cap does. A pause wins over a\n * finished answer too, because its call is still waiting. A text answer cut off at the output limit also counts as\n * 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) return pausedOutcome(state, message);\n const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);\n if (finished) return { stopReason: \"done\", output: state.output };\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\" || outcome.stopReason === \"clarification_requested\"\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/** The synthetic response that holds `calls`, so the pipeline runs them as one batch of the resumed message. */\nfunction batchOf(message: AssistantMessage, calls: readonly ToolCall[]): AssistantMessage {\n return { ...message, content: [...calls], stopReason: \"tool_calls\" };\n}\n\n/** The call ids of `message`'s tool calls, in model order. */\nfunction callOrderOf(message: AssistantMessage): string[] {\n return message.content.flatMap((block) => (block.type === \"tool_call\" ? [block.callId] : []));\n}\n\n/**\n * Puts the tool messages `list` gained from `from` on in the model's order of their calls, as a step records them.\n * A resume settles its calls by verdict, so without this a denial could come before an approval the model made first.\n */\nfunction inModelOrder(list: Message[], from: number, order: readonly string[]): void {\n const rank = (entry: Message) => (entry.role === \"tool\" ? order.indexOf(entry.callId) : order.length);\n const tail = list.splice(from).sort((a, b) => rank(a) - rank(b));\n list.push(...tail);\n}\n\n/**\n * Acts on the verdicts for a resumed context's waiting calls, before the run's first model call, which none of this\n * counts as, and records their results in the model's order. Returns the paused outcome when any call still waits,\n * and `done` when none does and an approved call's result ends the run, as `terminate` does in a step.\n */\nasync function resume(state: LoopState, setup: ResumeSetup): Promise<Outcome | undefined> {\n const { message } = setup;\n const from = { messages: state.messages.length, added: state.added.length };\n try {\n return await settle(state, setup);\n } finally {\n if (message !== undefined) {\n const order = callOrderOf(message);\n inModelOrder(state.messages, from.messages, order);\n inModelOrder(state.added, from.added, order);\n }\n }\n}\n\n/**\n * Verified answers and denials reach the model as results; verified approvals run, without the gate, with the input\n * their requests sign; requests that still wait stay pending; and calls whose checks failed ask again, through the\n * gate but never running.\n */\nasync function settle(state: LoopState, setup: ResumeSetup): Promise<Outcome | undefined> {\n const { signer } = state.setup;\n state.hooks.reserveRequestIds(setup.open.map((entry) => entry.request.id));\n const verdicts = await judgeOpenCalls(setup, { signer, send: (body) => state.send(body) });\n const of = <K extends Verdict[\"kind\"]>(kind: K) =>\n verdicts.filter((verdict): verdict is Extract<Verdict, { kind: K }> => verdict.kind === kind);\n for (const { call, result } of of(\"result\")) {\n state.send({ type: \"tool_call_start\", callId: call.callId, tool: call.name, input: call.input });\n recordResult(state, { call, result });\n }\n const asks: ToolCallResult[] = [];\n const { message } = setup;\n if (message === undefined) return undefined;\n const run = of(\"run\").map((verdict) => verdict.call);\n let ran: readonly ToolCallResult[] = [];\n if (run.length > 0) {\n const { after } = state.hooks.pipelineHooks();\n const ctx = { ...pipelineOf(state, asks), approved: true, ...(after === undefined ? {} : { after }) };\n // A verified request names its tool, and the run signed it only for a call to a tool its request had sent.\n const results = await runToolCalls(batchOf(message, run), state.setup.tools, ctx);\n ran = asks.length > 0 ? await askUser(state, results, asks) : results;\n }\n for (const { request, input } of of(\"wait\")) {\n state.pending.push(request);\n state.pendingInputs[request.id] = input;\n }\n const again = of(\"reissue\").map((verdict) => verdict.call);\n if (again.length > 0) {\n const ctx = { ...pipelineOf(state, asks), gate: state.hooks.reissueGate() };\n // Nothing verified these calls, so only the tools a request sends by default may ask again: a stored context\n // can't get a new signed request for a tool the model is never sent.\n await runToolCalls(batchOf(message, again), directTools(state.setup.tools), ctx);\n }\n if (state.pending.length > 0) return pausedOutcome(state, message);\n const ends = ran.some(({ result }) => result.terminate === true && !result.isError);\n return ends ? { stopReason: \"done\", output: state.output } : undefined;\n}\n\n/** `resume()`, with a hook that failed while the run fails closed ending the run as a step's failure would. */\nasync function resumeOrFail(state: LoopState, setup: ResumeSetup): Promise<Outcome | undefined> {\n try {\n return await resume(state, setup);\n } catch (error) {\n return failedOutcome(state, error);\n }\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 if (outcome === undefined && setup.resume !== undefined) outcome = await resumeOrFail(state, setup.resume);\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,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The observer channel: delivers each event to every subscriber, in order, without ever letting a subscriber change
|
|
3
|
+
* or break the run. Each subscriber has its own queue, so a slow one delays only itself, and the run waits for the
|
|
4
|
+
* queues to empty only where it must, before `agent_settled` and before the run ends, and then only for a bounded
|
|
5
|
+
* time.
|
|
6
|
+
*/
|
|
7
|
+
import type { AgentEvent } from "./events.js";
|
|
8
|
+
import type { Observer } from "./hooks.js";
|
|
9
|
+
/** The hook name a `hook_error` event gives for a failed observer. */
|
|
10
|
+
export declare const OBSERVER_HOOK = "observer";
|
|
11
|
+
/** What a failed observer turns into: the run reports it as a `hook_error` event. */
|
|
12
|
+
export type ReportFailure = (hook: string, error: unknown) => void;
|
|
13
|
+
/** Delivers events to observers. `deliver` and `flush` never throw and never reject. */
|
|
14
|
+
export declare class ObserverBus {
|
|
15
|
+
#private;
|
|
16
|
+
/** `timeoutMs` bounds how long `flush` waits for an observer before it drops it. */
|
|
17
|
+
constructor(report: ReportFailure, timeoutMs: number);
|
|
18
|
+
/** Starts delivering later events to `observer`, and returns the function that stops it. */
|
|
19
|
+
add(observer: Observer): () => void;
|
|
20
|
+
/**
|
|
21
|
+
* Queues `event` for every subscriber. They all get one frozen copy, so an observer can neither change the event
|
|
22
|
+
* the run and its iterators hold nor any message or result inside it.
|
|
23
|
+
*/
|
|
24
|
+
deliver(event: AgentEvent): void;
|
|
25
|
+
/**
|
|
26
|
+
* Resolves once every subscriber has handled every event delivered so far, including events its failures add. A
|
|
27
|
+
* subscriber that has not caught up within the timeout is dropped and reported, so an observer whose promise never
|
|
28
|
+
* settles can't hold the run open.
|
|
29
|
+
*/
|
|
30
|
+
flush(): Promise<void>;
|
|
31
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { frozenCopy } from "./freeze.js";
|
|
2
|
+
/** The hook name a `hook_error` event gives for a failed observer. */
|
|
3
|
+
export const OBSERVER_HOOK = "observer";
|
|
4
|
+
/** Delivers events to observers. `deliver` and `flush` never throw and never reject. */
|
|
5
|
+
export class ObserverBus {
|
|
6
|
+
#subscriptions = new Set();
|
|
7
|
+
#report;
|
|
8
|
+
#timeoutMs;
|
|
9
|
+
/** `timeoutMs` bounds how long `flush` waits for an observer before it drops it. */
|
|
10
|
+
constructor(report, timeoutMs) {
|
|
11
|
+
this.#report = report;
|
|
12
|
+
this.#timeoutMs = timeoutMs;
|
|
13
|
+
}
|
|
14
|
+
/** Starts delivering later events to `observer`, and returns the function that stops it. */
|
|
15
|
+
add(observer) {
|
|
16
|
+
const subscription = {
|
|
17
|
+
observer,
|
|
18
|
+
active: true,
|
|
19
|
+
tail: Promise.resolve(),
|
|
20
|
+
pending: 0,
|
|
21
|
+
current: undefined,
|
|
22
|
+
};
|
|
23
|
+
this.#subscriptions.add(subscription);
|
|
24
|
+
return () => this.#remove(subscription);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Queues `event` for every subscriber. They all get one frozen copy, so an observer can neither change the event
|
|
28
|
+
* the run and its iterators hold nor any message or result inside it.
|
|
29
|
+
*/
|
|
30
|
+
deliver(event) {
|
|
31
|
+
if (this.#subscriptions.size === 0)
|
|
32
|
+
return;
|
|
33
|
+
const frozen = frozenCopy(event);
|
|
34
|
+
for (const subscription of this.#subscriptions) {
|
|
35
|
+
subscription.pending += 1;
|
|
36
|
+
subscription.tail = subscription.tail.then(() => this.#call(subscription, frozen));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Resolves once every subscriber has handled every event delivered so far, including events its failures add. A
|
|
41
|
+
* subscriber that has not caught up within the timeout is dropped and reported, so an observer whose promise never
|
|
42
|
+
* settles can't hold the run open.
|
|
43
|
+
*/
|
|
44
|
+
async flush() {
|
|
45
|
+
let timer;
|
|
46
|
+
const expired = new Promise((resolve) => {
|
|
47
|
+
timer = setTimeout(() => resolve("expired"), this.#timeoutMs);
|
|
48
|
+
});
|
|
49
|
+
try {
|
|
50
|
+
let tails;
|
|
51
|
+
do {
|
|
52
|
+
tails = [...this.#subscriptions].map((subscription) => subscription.tail);
|
|
53
|
+
const outcome = await Promise.race([Promise.all(tails), expired]);
|
|
54
|
+
if (outcome === "expired") {
|
|
55
|
+
this.#dropLagging();
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
} while ([...this.#subscriptions].some((subscription, index) => subscription.tail !== tails[index]));
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
#dropLagging() {
|
|
65
|
+
const lagging = [...this.#subscriptions].filter((subscription) => subscription.pending > 0);
|
|
66
|
+
for (const subscription of lagging)
|
|
67
|
+
this.#remove(subscription);
|
|
68
|
+
for (const subscription of lagging) {
|
|
69
|
+
const what = subscription.current === undefined ? "its events" : `a ${subscription.current} event`;
|
|
70
|
+
this.#report(OBSERVER_HOOK, new Error(`an observer did not handle ${what} within ${this.#timeoutMs} ms, so it was removed`));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
#remove(subscription) {
|
|
74
|
+
subscription.active = false;
|
|
75
|
+
this.#subscriptions.delete(subscription);
|
|
76
|
+
}
|
|
77
|
+
async #call(subscription, event) {
|
|
78
|
+
try {
|
|
79
|
+
// An unsubscribe call stops events that are queued but not yet handled, too.
|
|
80
|
+
if (!subscription.active)
|
|
81
|
+
return;
|
|
82
|
+
subscription.current = event.type;
|
|
83
|
+
await subscription.observer(event);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
// A failure while handling `hook_error` or `run_end` is dropped: reporting the first would loop for ever, and
|
|
87
|
+
// nothing may follow the second.
|
|
88
|
+
if (subscription.active && event.type !== "hook_error" && event.type !== "run_end") {
|
|
89
|
+
this.#report(OBSERVER_HOOK, error);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
subscription.pending -= 1;
|
|
94
|
+
subscription.current = undefined;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=observers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"observers.js","sourceRoot":"","sources":["../src/observers.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,sEAAsE;AACtE,MAAM,CAAC,MAAM,aAAa,GAAG,UAAU,CAAC;AAexC,wFAAwF;AACxF,MAAM,OAAO,WAAW;IACb,cAAc,GAAG,IAAI,GAAG,EAAgB,CAAC;IACzC,OAAO,CAAgB;IACvB,UAA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AC,YAA0B;QAChC,YAAY,CAAC,MAAM,GAAG,KAAK,CAAC;QAC5B,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,YAA0B,EAAE,KAAiB;QACvD,IAAI,CAAC;YACH,6EAA6E;YAC7E,IAAI,CAAC,YAAY,CAAC,MAAM;gBAAE,OAAO;YACjC,YAAY,CAAC,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC;YAClC,MAAM,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACrC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,8GAA8G;YAC9G,iCAAiC;YACjC,IAAI,YAAY,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBACnF,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;YACrC,CAAC;QACH,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,OAAO,IAAI,CAAC,CAAC;YAC1B,YAAY,CAAC,OAAO,GAAG,SAAS,CAAC;QACnC,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * The observer channel: delivers each event to every subscriber, in order, without ever letting a subscriber change\n * or break the run. Each subscriber has its own queue, so a slow one delays only itself, and the run waits for the\n * queues to empty only where it must, before `agent_settled` and before the run ends, and then only for a bounded\n * time.\n */\nimport type { AgentEvent } from \"./events.js\";\nimport { frozenCopy } from \"./freeze.js\";\nimport type { Observer } from \"./hooks.js\";\n\n/** The hook name a `hook_error` event gives for a failed observer. */\nexport const OBSERVER_HOOK = \"observer\";\n\ninterface Subscription {\n readonly observer: Observer;\n active: boolean;\n tail: Promise<void>;\n /** The events queued for it and not yet handled. */\n pending: number;\n /** The type of the event it is handling, for the report when it is dropped. */\n current: AgentEvent[\"type\"] | undefined;\n}\n\n/** What a failed observer turns into: the run reports it as a `hook_error` event. */\nexport type ReportFailure = (hook: string, error: unknown) => void;\n\n/** Delivers events to observers. `deliver` and `flush` never throw and never reject. */\nexport class ObserverBus {\n readonly #subscriptions = new Set<Subscription>();\n readonly #report: ReportFailure;\n readonly #timeoutMs: number;\n\n /** `timeoutMs` bounds how long `flush` waits for an observer before it drops it. */\n constructor(report: ReportFailure, timeoutMs: number) {\n this.#report = report;\n this.#timeoutMs = timeoutMs;\n }\n\n /** Starts delivering later events to `observer`, and returns the function that stops it. */\n add(observer: Observer): () => void {\n const subscription: Subscription = {\n observer,\n active: true,\n tail: Promise.resolve(),\n pending: 0,\n current: undefined,\n };\n this.#subscriptions.add(subscription);\n return () => this.#remove(subscription);\n }\n\n /**\n * Queues `event` for every subscriber. They all get one frozen copy, so an observer can neither change the event\n * the run and its iterators hold nor any message or result inside it.\n */\n deliver(event: AgentEvent): void {\n if (this.#subscriptions.size === 0) return;\n const frozen = frozenCopy(event);\n for (const subscription of this.#subscriptions) {\n subscription.pending += 1;\n subscription.tail = subscription.tail.then(() => this.#call(subscription, frozen));\n }\n }\n\n /**\n * Resolves once every subscriber has handled every event delivered so far, including events its failures add. A\n * subscriber that has not caught up within the timeout is dropped and reported, so an observer whose promise never\n * settles can't hold the run open.\n */\n async flush(): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<\"expired\">((resolve) => {\n timer = setTimeout(() => resolve(\"expired\"), this.#timeoutMs);\n });\n try {\n let tails: Promise<void>[];\n do {\n tails = [...this.#subscriptions].map((subscription) => subscription.tail);\n const outcome = await Promise.race([Promise.all(tails), expired]);\n if (outcome === \"expired\") {\n this.#dropLagging();\n return;\n }\n } while ([...this.#subscriptions].some((subscription, index) => subscription.tail !== tails[index]));\n } finally {\n clearTimeout(timer);\n }\n }\n\n #dropLagging(): void {\n const lagging = [...this.#subscriptions].filter((subscription) => subscription.pending > 0);\n for (const subscription of lagging) this.#remove(subscription);\n for (const subscription of lagging) {\n const what = subscription.current === undefined ? \"its events\" : `a ${subscription.current} event`;\n this.#report(\n OBSERVER_HOOK,\n new Error(`an observer did not handle ${what} within ${this.#timeoutMs} ms, so it was removed`),\n );\n }\n }\n\n #remove(subscription: Subscription): void {\n subscription.active = false;\n this.#subscriptions.delete(subscription);\n }\n\n async #call(subscription: Subscription, event: AgentEvent): Promise<void> {\n try {\n // An unsubscribe call stops events that are queued but not yet handled, too.\n if (!subscription.active) return;\n subscription.current = event.type;\n await subscription.observer(event);\n } catch (error) {\n // A failure while handling `hook_error` or `run_end` is dropped: reporting the first would loop for ever, and\n // nothing may follow the second.\n if (subscription.active && event.type !== \"hook_error\" && event.type !== \"run_end\") {\n this.#report(OBSERVER_HOOK, error);\n }\n } finally {\n subscription.pending -= 1;\n subscription.current = undefined;\n }\n }\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
|
+
{"version":3,"file":"attributes.js","sourceRoot":"","sources":["../../src/otel/attributes.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,SAAkB,CAAC;AAEvD,kGAAkG;AAClG,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7C,aAAa,EAAE,uBAAuB;IACtC,YAAY,EAAE,sBAAsB;IACpC,SAAS,EAAE,mBAAmB;IAC9B,YAAY,EAAE,sBAAsB;IACpC,gBAAgB,EAAE,2BAA2B;IAC7C,kBAAkB,EAAE,4BAA4B;IAChD,qBAAqB,EAAE,gCAAgC;IACvD,gBAAgB,EAAE,2BAA2B;IAC7C,iBAAiB,EAAE,4BAA4B;IAC/C,yBAAyB,EAAE,sCAAsC;IACjE,0BAA0B,EAAE,uCAAuC;IACnE,0BAA0B,EAAE,sCAAsC;IAClE,QAAQ,EAAE,kBAAkB;IAC5B,QAAQ,EAAE,kBAAkB;IAC5B,UAAU,EAAE,qBAAqB;IACjC,SAAS,EAAE,YAAY;IACvB,yDAAyD;IACzD,kBAAkB,EAAE,4BAA4B;IAChD,aAAa,EAAE,uBAAuB;IACtC,cAAc,EAAE,wBAAwB;IACxC,iBAAiB,EAAE,4BAA4B;IAC/C,cAAc,EAAE,yBAAyB;CACjC,CAAC,CAAC;AAEZ,kGAAkG;AAClG,MAAM,CAAC,MAAM,yBAAyB,GAAsB,MAAM,CAAC,MAAM,CAAC;IACxE,iBAAiB,CAAC,kBAAkB;IACpC,iBAAiB,CAAC,aAAa;IAC/B,iBAAiB,CAAC,cAAc;IAChC,iBAAiB,CAAC,iBAAiB;IACnC,iBAAiB,CAAC,cAAc;CACjC,CAAC,CAAC;AAEH,8DAA8D;AAC9D,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7C,WAAW,EAAE,cAAc;IAC3B,IAAI,EAAE,MAAM;IACZ,WAAW,EAAE,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,KAAK,CAAC,IAAI,EAAE,CAAC;QACnB,KAAK,MAAM;YACT,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC;QAC/C,KAAK,WAAW;YACd,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC;QACpD,KAAK,OAAO;YACV,+EAA+E;YAC/E,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,CAAC,SAAS,EAAE,CAAC;QACzE,KAAK,WAAW;YACd,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;IAC7F,CAAC;AACH,CAAC;AAED,mHAAmH;AACnH,MAAM,UAAU,WAAW,CAAC,OAAgC;IAC1D,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,SAAS,CAAC,OAAgB;IACjC,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,MAAM;YACZ,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,oBAAoB,EAAE,EAAE,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;SACpG,CAAC;IACJ,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC;AACvE,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,iBAAiB,CAAC,QAA4B;IAC5D,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,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;
|