@aaac/runtime 0.1.22 → 0.1.24

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.
@@ -43,6 +43,34 @@ declare class InMemoryStore implements MemoryStore {
43
43
  delete(ref: MemoryRef): Promise<void>;
44
44
  }
45
45
 
46
+ /**
47
+ * Library Tool → SDK Function Tool conversion.
48
+ *
49
+ * Converts LibraryToolDefinition entries into SDK-native function tools
50
+ * that each adapter can register with its respective LLM SDK.
51
+ *
52
+ * Each adapter receives tools in its native format:
53
+ * - Claude Agent SDK: MCP tool via createSdkMcpServer + tool()
54
+ * - OpenAI Agents SDK: function tool object
55
+ * - Google ADK: FunctionDeclaration tool
56
+ */
57
+
58
+ /**
59
+ * Adapter-agnostic function tool descriptor. Adapters convert this
60
+ * into their SDK-specific tool format.
61
+ */
62
+ interface SdkFunctionTool {
63
+ name: string;
64
+ description: string;
65
+ inputSchema: Record<string, unknown>;
66
+ handler: (args: Record<string, unknown>) => Promise<string>;
67
+ }
68
+ /**
69
+ * Build adapter-agnostic function tool descriptors from a LibraryToolRegistry.
70
+ * Each tool's handler calls registry.execute() and serialises the result.
71
+ */
72
+ declare function buildSdkFunctionTools(registry: LibraryToolRegistry): SdkFunctionTool[];
73
+
46
74
  interface LibraryToolDefinition {
47
75
  toolId: string;
48
76
  description: string;
@@ -58,6 +86,12 @@ interface LibraryToolRegistry {
58
86
  execute(toolId: string, input: unknown): Promise<unknown>;
59
87
  }
60
88
  declare function createLibraryToolRegistry(): LibraryToolRegistry;
89
+ /**
90
+ * Create a LibraryToolRegistry backed by pre-built SdkFunctionTool handlers.
91
+ * Unlike createLibraryToolRegistry (which resolves tools via dynamic import),
92
+ * this variant delegates execute() directly to the tool's in-process handler.
93
+ */
94
+ declare function createRegistryFromSdkTools(tools: SdkFunctionTool[]): LibraryToolRegistry;
61
95
 
62
96
  /**
63
97
  * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions
@@ -198,6 +232,14 @@ declare function createModelResolver(options: ModelResolverOptions): ModelResolv
198
232
  * event-catalog.md §1.5, §2.2 / OBSERVABILITY_TASKS.md Phase 1 / architecture.md §6, §7
199
233
  */
200
234
 
235
+ /** Token usage metrics returned by LLM adapters after a query/session. */
236
+ interface TokenUsage {
237
+ inputTokens: number;
238
+ outputTokens: number;
239
+ totalTokens?: number;
240
+ cacheReadTokens?: number;
241
+ cacheCreationTokens?: number;
242
+ }
201
243
  /**
202
244
  * Minimal observer emit signature — structurally matches EventCollector.emit().
203
245
  * Pass `collector.emit.bind(collector)` to wire up the full observability pipeline.
@@ -296,7 +338,10 @@ interface InnerSpanOptions {
296
338
  * Returns the spanId emitted (= generated UUIDv7).
297
339
  * Returns undefined when observer is undefined (no-op).
298
340
  */
299
- declare function emitLlmTurnOpen(observer: ObserverEmitFn | undefined, parentSpanId: string | undefined, turnNumber: number, model?: string): string | undefined;
341
+ declare function emitLlmTurnOpen(observer: ObserverEmitFn | undefined, parentSpanId: string | undefined, turnNumber: number, model?: string, llmParams?: {
342
+ temperature?: number;
343
+ reasoningEffort?: string;
344
+ }): string | undefined;
300
345
  /**
301
346
  * Emit an agent.llm_turn close span.
302
347
  */
@@ -524,6 +569,12 @@ interface WorkflowRunOptions {
524
569
  * artifactsPath/cwd/policy actions).
525
570
  */
526
571
  toolchain?: RunToolchainChecksOptions;
572
+ /**
573
+ * In-process library tools to register with every task in this workflow.
574
+ * Passed through to each runTask() call. Adapters convert these to their
575
+ * native tool format (Claude MCP, OpenAI function tools, ADK tools).
576
+ */
577
+ libraryTools?: LibraryToolRegistry;
527
578
  }
528
579
  /** Typed handoff envelope for workflow input. */
529
580
  interface HandoffInput<TType extends string = string, TPayload = unknown> {
@@ -578,6 +629,11 @@ interface WorkflowInvocation<THandoffType extends string = string, TPayload = un
578
629
  * OBSERVATION ONLY — never changes the workflow outcome.
579
630
  */
580
631
  toolchain?: RunToolchainChecksOptions;
632
+ /**
633
+ * In-process library tools to register with every task in this workflow.
634
+ * Created once per execution and shared across all steps.
635
+ */
636
+ libraryTools?: LibraryToolRegistry;
581
637
  }
582
638
  interface StepResult {
583
639
  step_index: number;
@@ -963,6 +1019,8 @@ interface SdkAdapter {
963
1019
  sendExecution?(request: AgentExecutionRequest): Promise<string>;
964
1020
  /** Return the memory_ref produced by the last send/sendExecution call. */
965
1021
  getLastMemoryRef?(): MemoryRef | null;
1022
+ /** Return the token usage from the last send/sendExecution call. */
1023
+ getLastTokenUsage?(): TokenUsage | null;
966
1024
  /** Check if this adapter is compatible with the given compat tag. */
967
1025
  isCompatible?(compat: string): boolean;
968
1026
  }
@@ -1047,6 +1105,7 @@ interface TaskRunResult {
1047
1105
  outcome: TaskOutcome;
1048
1106
  follow_ups_used: number;
1049
1107
  retries_used: number;
1108
+ tokenUsage?: TokenUsage;
1050
1109
  }
1051
1110
  /**
1052
1111
  * Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.
@@ -1091,4 +1150,4 @@ declare function runTask(adapter: SdkAdapter, taskId: string, context: TaskConte
1091
1150
  libraryTools?: LibraryToolRegistry;
1092
1151
  }): Promise<TaskRunResult>;
1093
1152
 
1094
- export { type SplitPrompt as $, type AdapterSendOptions as A, type BoundResolveOptions as B, type CacheConfig as C, type DelegateStep as D, type EnvelopeParams as E, type HookContext as F, type GuardrailHooks as G, type HandoffInput as H, InMemoryStore as I, type InnerSpanOptions as J, type ModelAwareSdkAdapterFactory as K, type LibraryToolRegistry as L, type MemoryRef as M, type ModelClass as N, type ObserverEmitFn as O, type PromptBuilderOptions as P, type ModelMappingConfig as Q, type ResolvedComponent as R, type SdkAdapter as S, type TaskContext as T, type ModelResolver as U, type ModelResolverOptions as V, type WorkflowResult as W, type ReceiveSpec as X, type ResolvedModel as Y, type RetryDecision as Z, type SdkAdapterFactory as _, type AgentExecutionRequest as a, type TaskRunOptions as a0, type ToolchainCheckResult as a1, type ToolchainManifest as a2, ToolchainManifestSchema as a3, type WorkflowContractLike as a4, type WorkflowInvocation as a5, type WorkflowRunOptions as a6, type WorkflowStep as a7, buildCandidateAgents as a8, buildGateEvaluationPrompt as a9, getEffectiveGuardrailIds as aA, getGuardrailRulesForAgent as aB, getWarnings as aC, guardrailContextToRuleData as aD, hasBlockingViolation as aE, parseGateEvaluationResponse as aF, renderAgentSystemPrompt as aG, runTask as aH, runToolchainChecks as aI, runWorkflow as aJ, zodSchemaToPromptDescription as aK, zodSchemaToYamlExample as aL, buildPerAgentGuardrails as aa, buildRetryFollowUp as ab, buildSplitTaskPrompt as ac, buildTaskPrompt as ad, createExecutionEnvelope as ae, createGuardrailHooks as af, createGuardrailHooksForAgent as ag, createGuardrailHooksFromRules as ah, createLibraryToolRegistry as ai, createModelResolver as aj, deriveToolchainsForAgents as ak, emitIterationClose as al, emitIterationMetric as am, emitIterationOpen as an, emitLlmTurnClose as ao, emitLlmTurnOpen as ap, emitSessionClose as aq, emitSessionOpen as ar, emitSubagentClose as as, emitSubagentOpen as at, emitToolExecClose as au, emitToolExecOpen as av, emitToolchainClose as aw, emitToolchainOpen as ax, extractStructuredResult as ay, getBlockingViolations as az, type TaskOutcome as b, type AgentContractLike as c, type TaskContractLike as d, type WorkflowRegistries as e, type StepCompleteEvent as f, type StepResult as g, type GuardrailRuleData as h, type MemoryStore as i, type ArtifactBindingConfig as j, type RunToolchainChecksOptions as k, type TaskRunResult as l, type ResolvedToolchain as m, type LibraryToolDefinition as n, type HookResponse as o, type GuardrailCheckResult as p, type AdapterOrFactory as q, type AgentProgressEvent as r, BoundResolver as s, type CandidateAgent as t, type ConvergenceEnvelope as u, type ConvergenceEnvelopePayload as v, type EvaluateStep as w, type GateStep as x, type GuardrailCheckFunctions as y, type GuardrailRule as z };
1153
+ export { type RetryDecision as $, type AdapterSendOptions as A, type BoundResolveOptions as B, type CacheConfig as C, type DelegateStep as D, type EnvelopeParams as E, type GuardrailCheckFunctions as F, type GuardrailHooks as G, type HandoffInput as H, type GuardrailRule as I, type HookContext as J, InMemoryStore as K, type LibraryToolRegistry as L, type MemoryRef as M, type InnerSpanOptions as N, type ObserverEmitFn as O, type PromptBuilderOptions as P, type ModelAwareSdkAdapterFactory as Q, type ResolvedComponent as R, type SdkAdapter as S, type TokenUsage as T, type ModelClass as U, type ModelMappingConfig as V, type WorkflowResult as W, type ModelResolver as X, type ModelResolverOptions as Y, type ReceiveSpec as Z, type ResolvedModel as _, type AgentExecutionRequest as a, type SdkAdapterFactory as a0, type SplitPrompt as a1, type TaskRunOptions as a2, type ToolchainCheckResult as a3, type ToolchainManifest as a4, ToolchainManifestSchema as a5, type WorkflowContractLike as a6, type WorkflowInvocation as a7, type WorkflowRunOptions as a8, type WorkflowStep as a9, emitToolchainClose as aA, emitToolchainOpen as aB, extractStructuredResult as aC, getBlockingViolations as aD, getEffectiveGuardrailIds as aE, getGuardrailRulesForAgent as aF, getWarnings as aG, guardrailContextToRuleData as aH, hasBlockingViolation as aI, parseGateEvaluationResponse as aJ, renderAgentSystemPrompt as aK, runTask as aL, runToolchainChecks as aM, runWorkflow as aN, zodSchemaToPromptDescription as aO, zodSchemaToYamlExample as aP, buildCandidateAgents as aa, buildGateEvaluationPrompt as ab, buildPerAgentGuardrails as ac, buildRetryFollowUp as ad, buildSdkFunctionTools as ae, buildSplitTaskPrompt as af, buildTaskPrompt as ag, createExecutionEnvelope as ah, createGuardrailHooks as ai, createGuardrailHooksForAgent as aj, createGuardrailHooksFromRules as ak, createLibraryToolRegistry as al, createModelResolver as am, createRegistryFromSdkTools as an, deriveToolchainsForAgents as ao, emitIterationClose as ap, emitIterationMetric as aq, emitIterationOpen as ar, emitLlmTurnClose as as, emitLlmTurnOpen as at, emitSessionClose as au, emitSessionOpen as av, emitSubagentClose as aw, emitSubagentOpen as ax, emitToolExecClose as ay, emitToolExecOpen as az, type TaskContext as b, type TaskOutcome as c, type AgentContractLike as d, type TaskContractLike as e, type WorkflowRegistries as f, type StepCompleteEvent as g, type StepResult as h, type GuardrailRuleData as i, type MemoryStore as j, type SdkFunctionTool as k, type ArtifactBindingConfig as l, type RunToolchainChecksOptions as m, type TaskRunResult as n, type ResolvedToolchain as o, type LibraryToolDefinition as p, type HookResponse as q, type GuardrailCheckResult as r, type AdapterOrFactory as s, type AgentProgressEvent as t, BoundResolver as u, type CandidateAgent as v, type ConvergenceEnvelope as w, type ConvergenceEnvelopePayload as x, type EvaluateStep as y, type GateStep as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aaac/runtime",
3
- "version": "0.1.22",
3
+ "version": "0.1.24",
4
4
  "description": "Runtime SDK for the AaaC toolchain",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/observability-bridge.ts"],"sourcesContent":["/**\n * observability-bridge.ts\n *\n * Bridge between @aaac/runtime execution and @aaac/observability agent-axis spans.\n *\n * Responsibilities:\n * - Generate ExecutionEnvelope (run_id = UUIDv7) for every task/workflow execution\n * - Emit agent.session (open/close) for runWorkflow() — root run span\n * - Emit agent.subagent (open/close) for runTask() — handoff/task span\n * - Emit toolchain.execution (open/close) for toolchain tool invocations\n * - Observer is OPTIONAL — all emit* functions are no-ops when observer is undefined\n *\n * No circular dependency: @aaac/observability does NOT import @aaac/runtime.\n * Types (ExecutionEnvelope, EmitInput) are consumed from @aaac/observability.\n *\n * event-catalog.md §1.5, §2.2 / OBSERVABILITY_TASKS.md Phase 1 / architecture.md §6, §7\n */\n\nimport { generateId } from \"@aaac/observability\";\nimport type { ExecutionEnvelope, EmitInput, AttrValue } from \"@aaac/observability\";\n\n// ── Re-exports ────────────────────────────────────────────────────────────────\n\nexport type { ExecutionEnvelope } from \"@aaac/observability\";\n\n// ── ObserverEmitFn ────────────────────────────────────────────────────────────\n\n/**\n * Minimal observer emit signature — structurally matches EventCollector.emit().\n * Pass `collector.emit.bind(collector)` to wire up the full observability pipeline.\n * When undefined, all emission is a no-op.\n */\nexport type ObserverEmitFn = (event: EmitInput) => void;\n\n// ── Envelope creation ─────────────────────────────────────────────────────────\n\nexport interface EnvelopeParams {\n /** run_id of the parent execution (populated by workflow-runner for task spans). */\n parentRunId?: string;\n /** Component / agent identifier from the agent-contracts definition. */\n componentId?: string;\n /** Agent that issued this execution (handoff source). */\n fromAgent?: string;\n /** Agent that receives this execution (handoff target). */\n toAgent?: string;\n /** agent-contracts schema version. */\n contractVersion?: string;\n /** LLM adapter identifier (e.g. 'claude-agent-sdk'). */\n adapter?: string;\n /** LLM model identifier (e.g. 'claude-opus-4-5'). */\n model?: string;\n /** Task instance identifier within the run. */\n taskInstanceId?: string;\n}\n\n/**\n * Create an ExecutionEnvelope with a fresh UUIDv7 run_id and current timestamp.\n * Only defined fields are included — undefined values are omitted.\n */\nexport function createExecutionEnvelope(params: EnvelopeParams = {}): ExecutionEnvelope {\n const envelope: ExecutionEnvelope = {\n run_id: generateId(),\n timestamp: new Date().toISOString(),\n };\n if (params.parentRunId !== undefined) envelope.parent_run_id = params.parentRunId;\n if (params.componentId !== undefined) envelope.component_id = params.componentId;\n if (params.fromAgent !== undefined) envelope.from_agent = params.fromAgent;\n if (params.toAgent !== undefined) envelope.to_agent = params.toAgent;\n if (params.contractVersion !== undefined) envelope.contract_version = params.contractVersion;\n if (params.adapter !== undefined) envelope.adapter = params.adapter;\n if (params.model !== undefined) envelope.model = params.model;\n if (params.taskInstanceId !== undefined) envelope.task_instance_id = params.taskInstanceId;\n return envelope;\n}\n\n// ── attribute builder helpers ─────────────────────────────────────────────────\n\n/** Build attribute record; omits keys with undefined/empty-string values. */\nfunction attrs(base: Record<string, AttrValue | undefined>): Record<string, AttrValue> {\n const out: Record<string, AttrValue> = {};\n for (const [k, v] of Object.entries(base)) {\n if (v !== undefined && v !== \"\") out[k] = v;\n }\n return out;\n}\n\n/** Extract numeric token_usage fields into flat attributes. */\nfunction tokenAttrs(meta: Record<string, unknown>): Record<string, AttrValue> {\n const out: Record<string, AttrValue> = {};\n const tu = meta.token_usage;\n if (tu && typeof tu === \"object\") {\n const t = tu as Record<string, unknown>;\n if (typeof t.input_tokens === \"number\") out[\"token_usage.input\"] = t.input_tokens;\n if (typeof t.output_tokens === \"number\") out[\"token_usage.output\"] = t.output_tokens;\n if (typeof t.total_tokens === \"number\") out[\"token_usage.total\"] = t.total_tokens;\n if (typeof t.cache_read_input_tokens === \"number\") out[\"token_usage.cache_read\"] = t.cache_read_input_tokens;\n if (typeof t.cache_creation_input_tokens === \"number\") out[\"token_usage.cache_creation\"] = t.cache_creation_input_tokens;\n }\n if (typeof meta.cost_usd === \"number\") out[\"cost_usd\"] = meta.cost_usd;\n return out;\n}\n\n// ── agent.session ─────────────────────────────────────────────────────────────\n\n/**\n * Emit an agent.session open span (root workflow/session execution).\n *\n * Uses envelope.run_id as the spanId so that child agent.subagent spans can\n * reference it as parentSpanId for hierarchical correlation.\n *\n * Returns the spanId emitted (= envelope.run_id).\n * Returns undefined when observer is undefined (no-op).\n *\n * event-catalog.md §2.2 — required: agent.session_id; axis: agent\n */\nexport function emitSessionOpen(\n observer: ObserverEmitFn | undefined,\n envelope: ExecutionEnvelope,\n workflowId: string,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = envelope.run_id;\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.session\",\n lifecycle: \"open\",\n spanId,\n parentSpanId: envelope.parent_run_id,\n attributes: attrs({\n axis: \"agent\",\n \"agent.session_id\": envelope.run_id,\n \"agent.run_id\": envelope.run_id,\n \"workflow.id\": workflowId,\n \"agent.component_id\": envelope.component_id,\n \"agent.model\": envelope.model,\n adapter: envelope.adapter,\n contract_version: envelope.contract_version,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit an agent.session close span.\n *\n * `errorMessage` is set on the exception path (workflow body threw) so the\n * failure cause is recorded alongside the run status. Omitted on the normal path.\n *\n * event-catalog.md §2.2 — optional: agent.session.duration_ms, agent.status, agent.error\n */\nexport function emitSessionClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n envelope: ExecutionEnvelope,\n durationMs: number,\n status: string,\n errorMessage?: string,\n): void {\n if (!observer) return;\n\n const metaAttrs: Record<string, AttrValue> =\n envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.session\",\n lifecycle: \"close\",\n spanId,\n attributes: {\n ...attrs({\n axis: \"agent\",\n \"agent.session_id\": envelope.run_id,\n \"agent.session.duration_ms\": durationMs,\n \"agent.status\": status,\n \"agent.error\": errorMessage,\n }),\n ...metaAttrs,\n },\n });\n}\n\n// ── agent.subagent ────────────────────────────────────────────────────────────\n\n/**\n * Emit an agent.subagent open span (task/handoff execution).\n *\n * Uses envelope.run_id as the spanId and parentSpanId for hierarchical correlation\n * (typically the session span's run_id).\n *\n * Returns the spanId emitted (= envelope.run_id).\n * Returns undefined when observer is undefined (no-op).\n *\n * event-catalog.md §2.2 — required: agent.role; axis: agent\n */\nexport function emitSubagentOpen(\n observer: ObserverEmitFn | undefined,\n envelope: ExecutionEnvelope,\n parentSpanId: string | undefined,\n taskId: string,\n agentRole: string,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = envelope.run_id;\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.subagent\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"agent\",\n \"agent.role\": agentRole,\n \"agent.kind\": \"task\",\n \"task.id\": taskId,\n \"agent.run_id\": envelope.run_id,\n \"agent.parent_run_id\": envelope.parent_run_id,\n \"agent.model\": envelope.model,\n adapter: envelope.adapter,\n \"agent.component_id\": envelope.component_id,\n \"agent.from_agent\": envelope.from_agent,\n \"agent.to_agent\": envelope.to_agent,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit an agent.subagent close span.\n *\n * `errorMessage` records the failure cause on `agent.error` (parity with\n * emitSessionClose); it is omitted from the attributes when undefined.\n *\n * event-catalog.md §2.2 — optional: agent.duration_ms, agent.status, agent.error,\n * token_usage, cost_usd\n */\nexport function emitSubagentClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n envelope: ExecutionEnvelope,\n durationMs: number,\n status: string,\n agentRole: string,\n errorMessage?: string,\n): void {\n if (!observer) return;\n\n const metaAttrs: Record<string, AttrValue> =\n envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.subagent\",\n lifecycle: \"close\",\n spanId,\n attributes: {\n ...attrs({\n axis: \"agent\",\n \"agent.role\": agentRole,\n \"agent.status\": status,\n \"agent.duration_ms\": durationMs,\n \"agent.error\": errorMessage,\n }),\n ...metaAttrs,\n },\n });\n}\n\n// ── evaluate.iteration ────────────────────────────────────────────────────────\n\n/**\n * Emit an evaluate.iteration open span (one closed-loop iteration).\n *\n * Returns the spanId emitted (= generated UUIDv7).\n * Returns undefined when observer is undefined (no-op).\n */\nexport function emitIterationOpen(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n evaluateTaskId: string,\n loopTo: string,\n iterationNumber: number,\n maxIterations: number,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"evaluate.iteration\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"agent\",\n \"evaluate.task\": evaluateTaskId,\n \"evaluate.loop_to\": loopTo,\n \"evaluate.iteration\": iterationNumber,\n \"evaluate.max_iterations\": maxIterations,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit an evaluate.iteration close span.\n */\nexport function emitIterationClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n evaluateTaskId: string,\n iterationNumber: number,\n verdict: string,\n durationMs: number,\n feedbackInjected: boolean,\n): void {\n if (!observer) return;\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"evaluate.iteration\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"agent\",\n \"evaluate.task\": evaluateTaskId,\n \"evaluate.iteration\": iterationNumber,\n \"evaluate.verdict\": verdict,\n \"evaluate.duration_ms\": durationMs,\n \"evaluate.feedback_injected\": feedbackInjected,\n }),\n });\n}\n\n/**\n * Emit an evaluate.metric instant event when an evaluate step terminates.\n */\nexport function emitIterationMetric(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n evaluateTaskId: string,\n totalIterations: number,\n terminalOutcome: string,\n): void {\n if (!observer) return;\n\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"evaluate.metric\",\n lifecycle: \"instant\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"agent\",\n \"evaluate.task\": evaluateTaskId,\n \"evaluate.total_iterations\": totalIterations,\n \"evaluate.terminal_outcome\": terminalOutcome,\n }),\n });\n}\n\n// ── InnerSpanOptions (for adapter plumbing) ──────────────────────────────────\n\n/** Options forwarded from task-runner to adapters for inner turn-level spans. */\nexport interface InnerSpanOptions {\n observer?: ObserverEmitFn;\n parentSpanId?: string;\n}\n\n// ── agent.llm_turn ───────────────────────────────────────────────────────────\n\n/**\n * Emit an agent.llm_turn open span when a new LLM turn begins.\n *\n * Returns the spanId emitted (= generated UUIDv7).\n * Returns undefined when observer is undefined (no-op).\n */\nexport function emitLlmTurnOpen(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n turnNumber: number,\n model?: string,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.llm_turn\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"agent\",\n \"llm.turn_number\": turnNumber,\n \"llm.model\": model,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit an agent.llm_turn close span.\n */\nexport function emitLlmTurnClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n turnNumber: number,\n durationMs: number,\n tokenAttrs?: {\n inputTokens?: number;\n outputTokens?: number;\n cacheHitTokens?: number;\n toolCallsCount?: number;\n },\n): void {\n if (!observer) return;\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.llm_turn\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"agent\",\n \"llm.turn_number\": turnNumber,\n \"llm.duration_ms\": durationMs,\n \"llm.input_tokens\": tokenAttrs?.inputTokens,\n \"llm.output_tokens\": tokenAttrs?.outputTokens,\n \"llm.cache_hit_tokens\": tokenAttrs?.cacheHitTokens,\n \"llm.tool_calls_count\": tokenAttrs?.toolCallsCount,\n }),\n });\n}\n\n// ── agent.tool_exec ──────────────────────────────────────────────────────────\n\n/**\n * Emit an agent.tool_exec open span when a tool execution begins.\n *\n * Returns the spanId emitted (= generated UUIDv7).\n * Returns undefined when observer is undefined (no-op).\n */\nexport function emitToolExecOpen(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n toolName: string,\n inputSummary: string,\n turnNumber: number,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.tool_exec\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"agent\",\n \"tool.name\": toolName,\n \"tool.input_summary\": inputSummary,\n \"llm.turn_number\": turnNumber,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit an agent.tool_exec close span.\n */\nexport function emitToolExecClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n toolName: string,\n durationMs: number,\n): void {\n if (!observer) return;\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.tool_exec\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"agent\",\n \"tool.name\": toolName,\n \"tool.duration_ms\": durationMs,\n }),\n });\n}\n\n// ── toolchain.execution ──────────────────────────────────────────────────────\n\n/**\n * Emit a toolchain.execution open span when a toolchain tool is invoked.\n *\n * Returns the spanId emitted (= generated UUIDv7).\n * Returns undefined when observer is undefined (no-op).\n */\nexport function emitToolchainOpen(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n toolchainId: string,\n operation: string,\n artifactIds: string[],\n componentId?: string,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"toolchain.execution\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"toolchain\",\n \"toolchain.id\": toolchainId,\n \"toolchain.operation\": operation,\n \"toolchain.artifact_ids\": artifactIds.join(\",\"),\n \"agent.component_id\": componentId,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit a toolchain.execution close span.\n */\nexport function emitToolchainClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n toolchainId: string,\n operation: string,\n durationMs: number,\n status: \"success\" | \"failure\",\n errorMessage?: string,\n): void {\n if (!observer) return;\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"toolchain.execution\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"toolchain\",\n \"toolchain.id\": toolchainId,\n \"toolchain.operation\": operation,\n \"toolchain.status\": status,\n \"toolchain.duration_ms\": durationMs,\n ...(errorMessage ? { \"toolchain.error\": errorMessage } : {}),\n }),\n });\n}\n"],"mappings":";AAkBA,SAAS,kBAAkB;AAyCpB,SAAS,wBAAwB,SAAyB,CAAC,GAAsB;AACtF,QAAM,WAA8B;AAAA,IAClC,QAAQ,WAAW;AAAA,IACnB,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,EACpC;AACA,MAAI,OAAO,gBAAgB,OAAW,UAAS,gBAAgB,OAAO;AACtE,MAAI,OAAO,gBAAgB,OAAW,UAAS,eAAe,OAAO;AACrE,MAAI,OAAO,cAAc,OAAW,UAAS,aAAa,OAAO;AACjE,MAAI,OAAO,YAAY,OAAW,UAAS,WAAW,OAAO;AAC7D,MAAI,OAAO,oBAAoB,OAAW,UAAS,mBAAmB,OAAO;AAC7E,MAAI,OAAO,YAAY,OAAW,UAAS,UAAU,OAAO;AAC5D,MAAI,OAAO,UAAU,OAAW,UAAS,QAAQ,OAAO;AACxD,MAAI,OAAO,mBAAmB,OAAW,UAAS,mBAAmB,OAAO;AAC5E,S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