@tangle-network/agent-runtime 0.143.0 → 0.153.2

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.
Files changed (115) hide show
  1. package/README.md +32 -0
  2. package/dist/{activation-mi8TgSLM.js → activation-Bbic0THc.js} +3 -3
  3. package/dist/{activation-mi8TgSLM.js.map → activation-Bbic0THc.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +3 -3
  6. package/dist/{analyst-loop-CvkmfhUB.js → analyst-loop-Bouu53-l.js} +2 -2
  7. package/dist/{analyst-loop-CvkmfhUB.js.map → analyst-loop-Bouu53-l.js.map} +1 -1
  8. package/dist/analyst-loop.js +1 -1
  9. package/dist/{authoring-DuyShLdw.js → authoring-CcVhJ1lP.js} +2 -2
  10. package/dist/{authoring-DuyShLdw.js.map → authoring-CcVhJ1lP.js.map} +1 -1
  11. package/dist/candidate-execution/index.js +4 -4
  12. package/dist/{candidate-execution-CD5PoNmC.js → candidate-execution-DYOB1juU.js} +4 -4
  13. package/dist/{candidate-execution-CD5PoNmC.js.map → candidate-execution-DYOB1juU.js.map} +1 -1
  14. package/dist/{conversation-1hNtDeMM.js → conversation-BHMwAiMo.js} +28 -13
  15. package/dist/{conversation-1hNtDeMM.js.map → conversation-BHMwAiMo.js.map} +1 -1
  16. package/dist/conversation.d.ts +1 -1
  17. package/dist/conversation.js +1 -1
  18. package/dist/durable.d.ts +102 -4
  19. package/dist/durable.js +259 -13
  20. package/dist/durable.js.map +1 -1
  21. package/dist/{environment-provider-DCBJ13VP.js → environment-provider-3eCszBEm.js} +218 -34
  22. package/dist/environment-provider-3eCszBEm.js.map +1 -0
  23. package/dist/{environment-provider-B8eZ85Ga.d.ts → environment-provider-DJG0yIYl.d.ts} +2 -2
  24. package/dist/environment-provider.d.ts +1 -1
  25. package/dist/environment-provider.js +1 -1
  26. package/dist/executable-spec-BUcUcEPk.js +73 -0
  27. package/dist/executable-spec-BUcUcEPk.js.map +1 -0
  28. package/dist/{graph-De_XEsfH.js → graph-CIh2HDmH.js} +4 -4
  29. package/dist/{graph-De_XEsfH.js.map → graph-CIh2HDmH.js.map} +1 -1
  30. package/dist/{improvement-cycle-Bi-Tf4QF.js → improvement-cycle-GCDSsTN6.js} +7 -7
  31. package/dist/{improvement-cycle-Bi-Tf4QF.js.map → improvement-cycle-GCDSsTN6.js.map} +1 -1
  32. package/dist/{index-C2caGomG.d.ts → index-DLn9WI-f.d.ts} +342 -505
  33. package/dist/{index-B8rKtH3U.d.ts → index-lMADJLfq.d.ts} +4 -4
  34. package/dist/{index-D4sLkOPY.d.ts → index-rxVSm9-z.d.ts} +6 -4
  35. package/dist/index.d.ts +7 -7
  36. package/dist/index.js +13 -13
  37. package/dist/intelligence.d.ts +4 -4
  38. package/dist/intelligence.js +6 -6
  39. package/dist/jsonl-file-CDfsCI5s.js +59 -0
  40. package/dist/jsonl-file-CDfsCI5s.js.map +1 -0
  41. package/dist/kernel.d.ts +6 -6
  42. package/dist/kernel.js +13 -13
  43. package/dist/{knowledge-CVE6Wk1i.js → knowledge-CaY53BW2.js} +10 -7
  44. package/dist/{knowledge-CVE6Wk1i.js.map → knowledge-CaY53BW2.js.map} +1 -1
  45. package/dist/knowledge.d.ts +1 -1
  46. package/dist/knowledge.js +1 -1
  47. package/dist/{loop-runner-bin-BoHdQqLm.d.ts → loop-runner-bin-BwPqxKhR.d.ts} +3 -3
  48. package/dist/{loop-runner-bin-DdaI1nLL.js → loop-runner-bin-Dw43kB_-.js} +4 -4
  49. package/dist/{loop-runner-bin-DdaI1nLL.js.map → loop-runner-bin-Dw43kB_-.js.map} +1 -1
  50. package/dist/loop-runner-bin.d.ts +1 -1
  51. package/dist/loop-runner-bin.js +1 -1
  52. package/dist/{materialization-P86EciBw.js → materialization-Dl9J8ek4.js} +279 -58
  53. package/dist/materialization-Dl9J8ek4.js.map +1 -0
  54. package/dist/mcp/bin.js +3 -3
  55. package/dist/mcp/index.d.ts +3 -3
  56. package/dist/mcp/index.js +6 -6
  57. package/dist/{model-policy-DgRJIJse.js → model-policy-Sw4ywhtL.js} +68 -6
  58. package/dist/model-policy-Sw4ywhtL.js.map +1 -0
  59. package/dist/{openai-tools-BiAWKjh6.js → openai-tools-C4XKuK4t.js} +2 -2
  60. package/dist/{openai-tools-BiAWKjh6.js.map → openai-tools-C4XKuK4t.js.map} +1 -1
  61. package/dist/{prepare-D3n7cA39.js → prepare-C5tI-H4o.js} +2 -2
  62. package/dist/{prepare-D3n7cA39.js.map → prepare-C5tI-H4o.js.map} +1 -1
  63. package/dist/primeintellect/index.d.ts +1 -1
  64. package/dist/profiles.js +1 -1
  65. package/dist/{protected-model-port-bq6bD9YX.js → protected-model-port-DHDKNeY7.js} +2 -2
  66. package/dist/{protected-model-port-bq6bD9YX.js.map → protected-model-port-DHDKNeY7.js.map} +1 -1
  67. package/dist/{redact-DexTuAiX.d.ts → redact-NAptmqKw.d.ts} +3 -3
  68. package/dist/{researcher-CiSY6Wzb.js → researcher-BMFFPwKb.js} +2 -2
  69. package/dist/{researcher-CiSY6Wzb.js.map → researcher-BMFFPwKb.js.map} +1 -1
  70. package/dist/{run-layout-Be_Z0dF8.js → run-layout-C2jgwsCq.js} +111 -6
  71. package/dist/run-layout-C2jgwsCq.js.map +1 -0
  72. package/dist/{runtime-BnqjbOGX.js → runtime--Jsq8JCC.js} +118 -97
  73. package/dist/runtime--Jsq8JCC.js.map +1 -0
  74. package/dist/{runtime-J6Toky8K.d.ts → runtime-B-5dp5Iz.d.ts} +214 -14
  75. package/dist/{sandbox-events-COwCWUVB.js → sandbox-events-BVjstFgb.js} +70 -3
  76. package/dist/sandbox-events-BVjstFgb.js.map +1 -0
  77. package/dist/{spawn-journal-D2HKUImC.js → spawn-journal-BLnveCRS.js} +34 -104
  78. package/dist/spawn-journal-BLnveCRS.js.map +1 -0
  79. package/dist/{stream-agent-turn-C1Vs_3B9.d.ts → stream-agent-turn-BGyszuPH.d.ts} +2 -2
  80. package/dist/{stream-agent-turn-CXRugSGO.js → stream-agent-turn-DYi8ymsU.js} +91 -16
  81. package/dist/stream-agent-turn-DYi8ymsU.js.map +1 -0
  82. package/dist/{structural-rollout-CJgj9YXH.js → structural-rollout-D7V-HgXJ.js} +30 -13
  83. package/dist/structural-rollout-D7V-HgXJ.js.map +1 -0
  84. package/dist/{supervise-hCgG6ROJ.js → supervise-k_8VOASb.js} +2499 -2171
  85. package/dist/supervise-k_8VOASb.js.map +1 -0
  86. package/dist/{supervisor-s8SfZYbW.js → supervisor-CMZsJ7Wn.js} +673 -446
  87. package/dist/supervisor-CMZsJ7Wn.js.map +1 -0
  88. package/dist/testing.d.ts +2 -2
  89. package/dist/testing.js +12 -12
  90. package/dist/{top-app-BMOSKK06.js → top-app-3rYfFPTW.js} +192 -147
  91. package/dist/top-app-3rYfFPTW.js.map +1 -0
  92. package/dist/tui/bin.js +1 -1
  93. package/dist/tui/index.d.ts +32 -5
  94. package/dist/tui/index.js +1 -1
  95. package/dist/{types-Df9vulGc.d.ts → types-BPQhQRrC.d.ts} +507 -10
  96. package/dist/{util-C1bv6yog.js → util-D6ZEuBMi.js} +71 -2
  97. package/dist/util-D6ZEuBMi.js.map +1 -0
  98. package/dist/{workspace-archive-C52LjkeN.js → workspace-archive-B9ui4rrR.js} +2 -2
  99. package/dist/{workspace-archive-C52LjkeN.js.map → workspace-archive-B9ui4rrR.js.map} +1 -1
  100. package/package.json +7 -7
  101. package/dist/environment-provider-DCBJ13VP.js.map +0 -1
  102. package/dist/materialization-P86EciBw.js.map +0 -1
  103. package/dist/model-policy-DgRJIJse.js.map +0 -1
  104. package/dist/retained-run-binding-Dp2e8xne.js +0 -268
  105. package/dist/retained-run-binding-Dp2e8xne.js.map +0 -1
  106. package/dist/run-layout-Be_Z0dF8.js.map +0 -1
  107. package/dist/runtime-BnqjbOGX.js.map +0 -1
  108. package/dist/sandbox-events-COwCWUVB.js.map +0 -1
  109. package/dist/spawn-journal-D2HKUImC.js.map +0 -1
  110. package/dist/stream-agent-turn-CXRugSGO.js.map +0 -1
  111. package/dist/structural-rollout-CJgj9YXH.js.map +0 -1
  112. package/dist/supervise-hCgG6ROJ.js.map +0 -1
  113. package/dist/supervisor-s8SfZYbW.js.map +0 -1
  114. package/dist/top-app-BMOSKK06.js.map +0 -1
  115. package/dist/util-C1bv6yog.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-agent-turn-DYi8ymsU.js","names":["taskInput"],"sources":["../src/sessions.ts","../src/backends.ts","../src/runtime/stream-agent-turn.ts"],"sourcesContent":["/**\n *\n * Session helpers + an in-memory `RuntimeSessionStore` implementation suitable\n * for tests, scratch processes, and per-request scratch storage in serverless\n * runtimes. Durable stores (D1, postgres, Durable Objects) implement the same\n * interface from `./types`.\n *\n * @stable\n */\n\nimport { SessionMismatchError } from './errors'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n RuntimeSession,\n RuntimeSessionStore,\n RuntimeStreamEvent,\n} from './types'\n\n/** @internal */\nexport function newRuntimeSession(\n backend: string,\n requestedId?: string,\n metadata?: Record<string, unknown>,\n): RuntimeSession {\n const now = nowIso()\n return {\n id: requestedId || crypto.randomUUID(),\n backend,\n status: 'active',\n createdAt: now,\n updatedAt: now,\n metadata,\n }\n}\n\n/** @internal */\nexport function touchSession(session: RuntimeSession): RuntimeSession {\n return { ...session, updatedAt: nowIso() }\n}\n\n/** @internal */\nexport function nowIso(): string {\n return new Date().toISOString()\n}\n\ninterface StartOrResumeRuntimeSessionOptions<TInput extends AgentBackendInput> {\n backend: AgentExecutionBackend<TInput>\n input: TInput | (() => TInput)\n /** Smaller input used only when the backend can continue its native session. */\n continuationInput?: TInput | (() => TInput)\n context: Omit<AgentBackendContext, 'session'>\n store?: RuntimeSessionStore\n sessionId?: string\n resume?: boolean\n validateSession?: (session: RuntimeSession) => void\n}\n\ninterface RuntimeSessionCall<TInput extends AgentBackendInput> {\n session: RuntimeSession\n input: TInput\n resumed: boolean\n}\n\n/** Start or resume one backend session and persist its current identity. @internal */\nexport async function startOrResumeRuntimeSession<TInput extends AgentBackendInput>(\n options: StartOrResumeRuntimeSessionOptions<TInput>,\n): Promise<RuntimeSessionCall<TInput>> {\n const existing =\n options.resume && options.sessionId ? await options.store?.get(options.sessionId) : undefined\n if (!existing) {\n const input = resolveSessionInput(options.input)\n const session = options.backend.start\n ? await options.backend.start(input, {\n ...options.context,\n requestedSessionId: options.sessionId,\n })\n : newRuntimeSession(options.backend.kind, options.sessionId)\n assertSessionBackend(session, options.backend.kind)\n options.validateSession?.(session)\n await options.store?.put(session)\n return { session, input, resumed: false }\n }\n\n assertSessionBackend(existing, options.backend.kind)\n const continued = options.backend.resume !== undefined\n const input = resolveSessionInput(\n continued ? (options.continuationInput ?? options.input) : options.input,\n )\n const session = options.backend.resume\n ? await options.backend.resume(existing, input, options.context)\n : touchSession({ ...existing, status: 'active' })\n assertSessionBackend(session, options.backend.kind)\n options.validateSession?.(session)\n await options.store?.put(session)\n return { session, input, resumed: true }\n}\n\nfunction resolveSessionInput<TInput extends AgentBackendInput>(\n input: TInput | (() => TInput),\n): TInput {\n return typeof input === 'function' ? input() : input\n}\n\nfunction assertSessionBackend(session: RuntimeSession, backend: string): void {\n if (session.backend !== backend) throw new SessionMismatchError(session.backend, backend)\n}\n\n/** In-memory `RuntimeSessionStore` for single-process use and tests. @stable */\nexport class InMemoryRuntimeSessionStore implements RuntimeSessionStore {\n private readonly sessions = new Map<string, RuntimeSession>()\n private readonly events = new Map<string, RuntimeStreamEvent[]>()\n\n get(sessionId: string): RuntimeSession | undefined {\n return this.sessions.get(sessionId)\n }\n\n put(session: RuntimeSession): void {\n this.sessions.set(session.id, session)\n }\n\n appendEvent(sessionId: string, event: RuntimeStreamEvent): void {\n const existing = this.events.get(sessionId) ?? []\n existing.push(event)\n this.events.set(sessionId, existing)\n }\n\n listEvents(sessionId: string): RuntimeStreamEvent[] {\n return [...(this.events.get(sessionId) ?? [])]\n }\n}\n","/**\n * Provider-neutral backend adapters for `runAgentTaskStream`.\n *\n * Model inference is deliberately absent. Paid model work enters the Runtime executor with an\n * exact `AgentProfile`; these adapters only normalize a caller-owned iterable or sandbox stream.\n *\n * @stable\n */\n\nimport { providerMessageText } from './runtime/turn-input'\nimport { newRuntimeSession, nowIso, touchSession } from './sessions'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/** Wrap any custom async-iterable stream into a typed `AgentExecutionBackend`. @stable */\nexport function createIterableBackend<TInput extends AgentBackendInput>(options: {\n kind: string\n start?: AgentExecutionBackend<TInput>['start']\n resume?: AgentExecutionBackend<TInput>['resume']\n stream: AgentExecutionBackend<TInput>['stream']\n stop?: AgentExecutionBackend<TInput>['stop']\n}): AgentExecutionBackend<TInput> {\n return options\n}\n\n/** Build an `AgentExecutionBackend` backed by a sandbox/sidecar `streamPrompt` call. @stable */\nexport function createSandboxPromptBackend<\n TBox,\n TInput extends AgentBackendInput = AgentBackendInput,\n>(options: {\n kind?: string\n getBox(input: TInput, context: Omit<AgentBackendContext, 'session'>): Promise<TBox> | TBox\n streamPrompt(box: TBox, message: string, context: AgentBackendContext): AsyncIterable<unknown>\n mapEvent?: (event: unknown, context: AgentBackendContext) => RuntimeStreamEvent | undefined\n getSessionId?: (box: TBox, input: TInput) => string | undefined\n}): AgentExecutionBackend<TInput> {\n const kind = options.kind ?? 'sandbox'\n return {\n kind,\n async start(input, context) {\n const box = await options.getBox(input, context)\n return newRuntimeSession(\n kind,\n options.getSessionId?.(box, input) ?? context.requestedSessionId,\n { resumable: true },\n )\n },\n resume(session) {\n return touchSession({ ...session, status: 'active' })\n },\n async *stream(input, context) {\n const box = await options.getBox(input, context)\n const message =\n input.message ??\n input.messages?.at(-1)?.content ??\n providerMessageText(input.providerOptions) ??\n context.task.intent\n for await (const event of options.streamPrompt(box, message, context)) {\n const mapped = options.mapEvent?.(event, context) ?? mapCommonBackendEvent(event, context)\n if (mapped) yield mapped\n }\n },\n }\n}\n\n/** @internal */\nexport function normalizeBackendStreamEvent(\n event: RuntimeStreamEvent,\n task: AgentBackendContext['task'],\n session: RuntimeSession,\n): RuntimeStreamEvent {\n if (\n 'task' in event &&\n event.task &&\n 'session' in event &&\n event.session &&\n 'timestamp' in event &&\n event.timestamp\n ) {\n return event\n }\n return {\n ...event,\n task: 'task' in event && event.task ? event.task : task,\n session: 'session' in event && event.session ? event.session : session,\n timestamp: 'timestamp' in event && event.timestamp ? event.timestamp : nowIso(),\n } as RuntimeStreamEvent\n}\n\nfunction mapCommonBackendEvent(\n event: unknown,\n context: AgentBackendContext,\n): RuntimeStreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const record = event as Record<string, unknown>\n const type = String(record.type ?? '')\n const data =\n record.data && typeof record.data === 'object'\n ? (record.data as Record<string, unknown>)\n : record\n if (type === 'message.part.updated' || type === 'text_delta' || type === 'delta') {\n const part = data.part as Record<string, unknown> | undefined\n const partText =\n part !== undefined &&\n typeof part === 'object' &&\n (part.type === 'text' || part.type === undefined)\n ? stringValue(part.text)\n : undefined\n const text =\n stringValue(data.text) ?? stringValue(data.delta) ?? stringValue(record.text) ?? partText\n return text\n ? {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n if (type === 'reasoning_delta') {\n const text = stringValue(data.text) ?? stringValue(record.text)\n return text\n ? {\n type: 'reasoning_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n if (type === 'tool_call') {\n return {\n type: 'tool_call',\n task: context.task,\n session: context.session,\n toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? 'tool',\n toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),\n args: data.args ?? data.input ?? record.args,\n timestamp: nowIso(),\n }\n }\n if (type === 'tool_result') {\n return {\n type: 'tool_result',\n task: context.task,\n session: context.session,\n toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? 'tool',\n toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),\n result: data.result ?? data.output ?? record.result,\n timestamp: nowIso(),\n }\n }\n if (type === 'artifact') {\n const artifactId =\n stringValue(data.artifactId) ?? stringValue(data.id) ?? stringValue(record.artifactId)\n if (!artifactId) return undefined\n return {\n type: 'artifact',\n task: context.task,\n session: context.session,\n artifactId,\n name: stringValue(data.name) ?? stringValue(record.name),\n mimeType: stringValue(data.mimeType) ?? stringValue(record.mimeType),\n uri: stringValue(data.uri) ?? stringValue(record.uri),\n content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),\n metadata:\n data.metadata && typeof data.metadata === 'object'\n ? (data.metadata as Record<string, unknown>)\n : undefined,\n timestamp: nowIso(),\n }\n }\n if (type === 'proposal_created' || type === 'proposal' || type === 'filing') {\n const proposalId =\n stringValue(data.proposalId) ?? stringValue(data.id) ?? stringValue(record.proposalId)\n if (!proposalId) return undefined\n const status = stringValue(data.status) ?? stringValue(record.status)\n return {\n type: 'proposal_created',\n task: context.task,\n session: context.session,\n proposalId,\n title: stringValue(data.title) ?? stringValue(record.title) ?? proposalId,\n status:\n status === 'pending' || status === 'approved' || status === 'rejected' ? status : undefined,\n content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),\n timestamp: nowIso(),\n }\n }\n if (type === 'result' || type === 'final') {\n const text = stringValue(data.finalText) ?? stringValue(data.text) ?? stringValue(record.text)\n return text\n ? {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n return undefined\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n","/**\n * `streamAgentTurn` — the ONE run-a-turn event-stream contract over every\n * execution substrate: a sandbox box (`SandboxInstance.streamPrompt`), a\n * one-shot Runtime-owned `Executor` (cli-bridge / router / sandbox, via\n * `ExecutorFactory`), and an in-process `AgentExecutionBackend`.\n *\n * One function, one vocabulary: every backend kind yields the existing\n * `RuntimeStreamEvent` union incrementally and ALWAYS terminates with a\n * `final` event whose `text` is the turn's final text and whose\n * `metadata.tokenUsage` / `metadata.costUsd` / `metadata.model` carry the\n * turn's metered usage. `collectAgentTurn` drains a stream into that terminal\n * summary plus the full event list.\n *\n * This is a UNIFICATION seam, not a new stream parser — each kind is a thin\n * adapter over code that already exists and is already hardened:\n * - `box` — `mapSandboxEvent` + `extractLlmCallEvent` (sandbox-events.ts)\n * project the sandbox event stream; its requested profile is\n * explicitly recorded as unverified because the box already exists.\n * - `executor` — Runtime materializes the exact `AgentProfile`, records its\n * identity receipts, drives the executor once, and tears it\n * down after capturing the terminal artifact.\n * - `chat` — the backend's own `stream()` surface, normalized by\n * `normalizeBackendStreamEvent`; its requested profile is likewise\n * unverified because an arbitrary backend cannot attest its setup.\n *\n * Distinct from `openSandboxRun` (box-only, session resume over one persistent\n * artifact, raw `SandboxEvent` deliverables) and from `runAgentTaskStream`\n * (full task lifecycle: knowledge preflight, session store, resume). This is\n * the minimal turn primitive underneath both worlds: prompt in, one normalized\n * event stream out, terminal result+usage guaranteed on every non-thrown path.\n *\n * Stream envelope: `backend_start` → incremental events → (`backend_error` on\n * failure) → `final`. A caller-initiated abort terminates with\n * `final.status: 'aborted'`; an expired `timeoutMs` deadline with\n * `final.status: 'failed'` — so cancellation stays distinguishable from a\n * blown deadline.\n *\n * Mid-stream lifecycle work needs NO extra API: the generator is pull-based,\n * so the producer is suspended between yields and resumes only when the caller\n * pulls again. A consumer can therefore run arbitrary async work between\n * events — sync state on each `tool_result`, decide a no-op retry after\n * draining, run a pre-`done` flush when it receives `final` and BEFORE it\n * forwards its own terminal event downstream. The interleaving is guaranteed\n * (and locked by test): nothing is produced past the event the caller is\n * holding.\n *\n * @stable\n */\n\nimport { scoreKnowledgeReadiness } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n canonicalCandidateDigest,\n renderInputPartsAsText,\n} from '@tangle-network/agent-interface'\nimport type { AgentTurnInput } from '@tangle-network/agent-interface/environment-provider'\nimport type { PromptOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { type AgentRunOutcome, createAgentRunOutcomeTracker } from '@tangle-network/sandbox/runtime'\nimport { normalizeBackendStreamEvent } from '../backends'\nimport { BackendTransportError, ValidationError } from '../errors'\nimport { newRuntimeSession, nowIso } from '../sessions'\nimport type {\n AgentBackendInput,\n AgentExecutionBackend,\n AgentTaskSpec,\n AgentTaskStatus,\n BackendErrorDetail,\n RuntimeSession,\n RuntimeStreamEvent,\n} from '../types'\nimport { awaitAbortable } from './retained-run-binding'\nimport {\n canonicalStreamEventFromSandboxEvent,\n createSandboxToolPartState,\n isSandboxTerminalEvent,\n mapSandboxEvent,\n mapSandboxToolEvent,\n} from './sandbox-events'\nimport { projectSandboxOutcome, readSandboxOutcome } from './sandbox-outcome'\nimport { executableAgentProfileSnapshot } from './supervise/executable-spec'\nimport {\n authoredProfileDigest,\n knownExecutionBindingReceipt,\n knownMaterializationReceipt,\n runtimeOwnedExecutorExecutionBinding,\n runtimeOwnedExecutorMaterialization,\n runtimeOwnedPendingExecutorMaterialization,\n unknownExecutionBindingReceipt,\n unknownMaterializationReceipt,\n} from './supervise/materialization'\nimport {\n concreteModelId,\n profileBridgeWireModel,\n profileProviderModel,\n} from './supervise/model-policy'\nimport type {\n ExecutionBindingReceipt,\n Executor,\n ExecutorFactory,\n ExecutorProgressEvent,\n ExecutorResult,\n NodeExecutionIdentity,\n ProfileMaterializationReceipt,\n UsageEvent,\n} from './supervise/types'\nimport {\n promptFromAgentTurnInput,\n promptOptionsFromAgentTurnInput,\n providerMessageText,\n} from './turn-input'\n\n/**\n * The execution substrate one turn runs on — a closed discriminated union over\n * the three stream surfaces the runtime already owns.\n *\n * @stable\n */\nexport type AgentTurnBackend = {\n /** A Runtime-owned executor factory materialized from this exact canonical profile. */\n kind: 'executor'\n factory: ExecutorFactory<unknown>\n /** Exact canonical identity materialized by the executor. */\n profile: AgentProfile\n /** Model label stamped on cost-only `llm_call` events. Default `'agent'`. */\n agentRunName?: string\n}\n\n/** Lower-level observation adapters. They normalize an already-created execution surface but do\n * not bind an AgentProfile to it, so they are deliberately absent from the public kernel export. */\ntype ObservedAgentTurnBackend =\n | {\n /** A live sandbox box: the turn is one `box.streamPrompt(prompt)` call. */\n kind: 'box'\n box: SandboxInstance\n /**\n * Per-turn `PromptOptions` forwarded verbatim to `streamPrompt`\n * (`sessionId`, `turnId`, `model`, `backend` profile, `timeoutMs`, …).\n * The turn's derived abort signal (caller `signal` + `timeoutMs`\n * deadline) is always installed as `signal` — pass cancellation through\n * `StreamAgentTurnOptions`, not here.\n */\n options?: Omit<PromptOptions, 'signal'>\n /** Model label stamped on cost-only `llm_call` events. Default `'agent'`. */\n agentRunName?: string\n }\n | {\n /**\n * A caller-supplied in-process `AgentExecutionBackend`: the turn is one\n * `backend.stream()` call.\n */\n kind: 'chat'\n backend: AgentExecutionBackend\n }\n\nexport type { AgentTurnInput } from '@tangle-network/agent-interface/environment-provider'\n\n/** @stable */\nexport interface StreamAgentTurnOptions {\n /** Caller-initiated cancellation. Terminates the stream with `final.status: 'aborted'`. */\n signal?: AbortSignal\n /**\n * Wall-clock deadline for the whole turn in ms. An expired deadline aborts\n * the backend and terminates the stream with `final.status: 'failed'`\n * (a blown deadline is a turn failure, not a caller cancellation).\n */\n timeoutMs?: number\n /** Stable logical paid-call id, forwarded as the provider idempotency key and retained in evidence. */\n callId?: string\n /** Caller trace tag retained in evidence and forwarded when the transport supports it. */\n correlationId?: string\n /**\n * Opt-in tool-part projection for box and executor backends: sandbox tool\n * parts additionally surface in-stream as\n * `tool_call` / `tool_result` events (`mapSandboxToolEvent`), so a consumer\n * rendering tool activity needs no bespoke sandbox-event parser. Default\n * off — the stream vocabulary existing consumers see is unchanged. No-op\n * for the `chat` kind (its backend emits `RuntimeStreamEvent`s directly,\n * tool events included when the backend produces them).\n */\n preserveToolParts?: boolean\n /**\n * Raw-event tap for box-kind backends: called (and awaited) with every\n * unmapped `SandboxEvent` BEFORE it is projected, so a consumer can read\n * parts the chat-UX projection drops (part ids, step markers, custom\n * backend events) without forking the mapper. Purely observational — it\n * cannot alter the mapped stream. Never called for the `chat` kind, which\n * has no sandbox events.\n */\n onRawEvent?: (event: SandboxEvent) => void | Promise<void>\n}\n\nfunction turnIntent(input: AgentTurnInput): string {\n if (input.prompt !== undefined) return input.prompt\n if (input.parts !== undefined) return renderInputPartsAsText(input.parts)\n return providerMessageText(input.providerOptions) ?? 'structured agent turn'\n}\n\nfunction turnBackendInput(task: AgentTaskSpec, input: AgentTurnInput): AgentBackendInput {\n return {\n task,\n ...(input.prompt === undefined ? {} : { message: input.prompt }),\n ...(input.parts === undefined ? {} : { parts: structuredClone(input.parts) }),\n ...(input.interactions === undefined ? {} : { interactions: input.interactions }),\n ...(input.providerOptions === undefined\n ? {}\n : { providerOptions: structuredClone(input.providerOptions) }),\n }\n}\n\nfunction executorEvidence(\n executor: Executor<unknown>,\n profile: AgentProfile,\n attemptId: string,\n): {\n materialization: ProfileMaterializationReceipt\n executionBinding: ExecutionBindingReceipt\n} {\n const profileDigest = authoredProfileDigest(profile)\n const declaration = runtimeOwnedExecutorMaterialization(executor)\n if (!profileDigest || !declaration) {\n const materialization = unknownMaterializationReceipt({\n ...(profileDigest ? { authoredProfileDigest: profileDigest } : {}),\n runtime: executor.runtime,\n reason: declaration ? 'invalid-executor-report' : 'executor-did-not-report',\n })\n return {\n materialization,\n executionBinding: unknownExecutionBindingReceipt(\n materialization,\n attemptId,\n declaration ? 'invalid-executor-report' : 'executor-did-not-report',\n ),\n }\n }\n try {\n const materialization = knownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n declaration,\n })\n const binding = runtimeOwnedExecutorExecutionBinding(executor)\n if (!binding || binding.attemptId !== attemptId) throw new Error('executor attempt id mismatch')\n return {\n materialization,\n executionBinding: knownExecutionBindingReceipt(materialization, binding),\n }\n } catch {\n const materialization = unknownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n reason: 'invalid-executor-report',\n })\n return {\n materialization,\n executionBinding: unknownExecutionBindingReceipt(\n materialization,\n attemptId,\n 'invalid-executor-report',\n ),\n }\n }\n}\n\n/** Exact turns require the model-bearing profile to be the sole behavioral authority. Runtime\n * checks the trusted declaration before execution so a seam fallback cannot hide behind the same\n * profile digest. */\nfunction assertExactExecutorDeclaration(executor: Executor<unknown>, profile: AgentProfile): void {\n const profileModel = profileProviderModel(profile)\n if (!profileModel) {\n throw new ValidationError(\n 'streamAgentTurn: exact AgentProfile.model.default must name the concrete model',\n )\n }\n const declaration =\n runtimeOwnedExecutorMaterialization(executor) ??\n runtimeOwnedPendingExecutorMaterialization(executor)?.declaration\n if (!declaration) return\n if (declaration.model.status !== 'known') {\n throw new ValidationError(\n 'streamAgentTurn: exact executor did not materialize a known model identity',\n )\n }\n if (declaration.backend === 'router' || declaration.backend === 'router-tools') {\n const plan = declaration.plan as {\n configuredModel?: unknown\n configuredReasoningEffort?: unknown\n reasoningEffort?: unknown\n }\n if (declaration.model.id !== profileModel) {\n throw new ValidationError(\n 'streamAgentTurn: Router executor model differs from AgentProfile.model.default',\n )\n }\n if (\n plan.configuredModel !== null &&\n plan.configuredModel !== undefined &&\n concreteModelId(String(plan.configuredModel)) !== profileModel\n ) {\n throw new ValidationError(\n 'streamAgentTurn: configured Router model conflicts with AgentProfile.model.default',\n )\n }\n const expectedEffort = profile.model?.reasoningEffort ?? null\n if (\n plan.configuredReasoningEffort !== null &&\n plan.configuredReasoningEffort !== undefined &&\n plan.configuredReasoningEffort !== expectedEffort\n ) {\n throw new ValidationError(\n 'streamAgentTurn: configured Router reasoning conflicts with AgentProfile.model.reasoningEffort',\n )\n }\n if ((plan.reasoningEffort ?? null) !== expectedEffort) {\n throw new ValidationError(\n 'streamAgentTurn: Router reasoning effort must come from AgentProfile.model.reasoningEffort',\n )\n }\n }\n if (declaration.backend === 'bridge' || declaration.backend === 'bridge-worktree') {\n const expectedWireModel = profileBridgeWireModel(profile)\n if (!expectedWireModel || declaration.model.id !== expectedWireModel) {\n throw new ValidationError(\n 'streamAgentTurn: bridge executor model differs from the AgentProfile harness/provider/model wire id',\n )\n }\n const plan = declaration.plan as { configuredModel?: unknown }\n if (\n plan.configuredModel !== null &&\n plan.configuredModel !== undefined &&\n concreteModelId(String(plan.configuredModel)) !== expectedWireModel\n ) {\n throw new ValidationError(\n 'streamAgentTurn: configured bridge model conflicts with the AgentProfile harness/provider/model wire id',\n )\n }\n }\n}\n\nfunction turnProvenance(\n startedAt: number,\n timeoutMs: number | undefined,\n profileDigest: string | undefined,\n taskDigest: string,\n materialization: ProfileMaterializationReceipt | undefined,\n executionBinding: ExecutionBindingReceipt | undefined,\n correlation: Readonly<Record<string, string>>,\n): Record<string, unknown> {\n const endedAt = Date.now()\n return {\n ...(profileDigest\n ? {\n identity: {\n profileDigest,\n taskDigest,\n ...(Object.keys(correlation).length > 0 ? { correlation } : {}),\n },\n }\n : { taskDigest }),\n ...(materialization ? { materialization } : {}),\n ...(executionBinding ? { executionBindings: [executionBinding] } : {}),\n budget: { timeoutMs: timeoutMs ?? null },\n timing: {\n startedAt: new Date(startedAt).toISOString(),\n endedAt: new Date(endedAt).toISOString(),\n durationMs: endedAt - startedAt,\n },\n }\n}\n\n/**\n * Metered usage of one turn, summed over every cost-bearing event the backend\n * emitted. `input`/`output` are token counts and are accompanied by\n * `tokensKnown: false` when the backend did not report them. `costUsd`/`model`\n * are present only when the backend actually reported them.\n *\n * @stable\n */\nexport interface AgentTurnUsage {\n input: number\n output: number\n /** Present when a real turn ran but the provider did not report token usage. */\n tokensKnown?: false\n costUsd?: number\n /** Present when Runtime could not prove the full dollar amount. */\n usdKnown?: false\n /** Separately-labelled local/catalog estimate; never billed spend. */\n estimatedCostUsd?: number\n /** Provider-reported prompt-cache fields; absent fields remain unknown. */\n promptCache?: Readonly<Record<string, number | string>>\n /** Provider-reported reasoning-token subset of output, when available. */\n reasoningTokens?: number\n model?: string\n}\n\n/**\n * A drained turn: the terminal summary plus every event the stream yielded.\n * `status`/`error` mirror the terminal `final` event so a failed or aborted\n * turn stays inspectable without re-scanning `events`.\n *\n * @stable\n */\nexport interface CollectedAgentTurn {\n finalText: string\n /** Exact terminal artifact output from a Runtime-owned executor. */\n output?: unknown\n usage: AgentTurnUsage\n /** Exact underlying transport calls when the Runtime-owned executor reports them. */\n transportAttempts?: number\n toolCalls: Array<{ id?: string; name: string; arguments: string }>\n events: RuntimeStreamEvent[]\n status: AgentTaskStatus\n error?: BackendErrorDetail\n /** Public Sandbox outcome, when the turn ran through a Sandbox stream or executor. */\n sandboxOutcome?: AgentRunOutcome\n}\n\n/** Mutable per-turn accumulator threaded through the backend adapters. */\ninterface TurnAccumulator {\n /** Concatenated incremental text (`text_delta` events). */\n deltaText: string\n /** Final text read off a terminal `result`/`done`/`final` event, when the\n * backend emitted one. Preferred over `deltaText` for box streams, whose\n * `message.part.updated` fallback carries running accumulations. */\n terminalText?: string\n input: number\n output: number\n costUsd: number\n estimatedCostUsd: number\n sawEstimatedCost: boolean\n promptCache: Record<string, number | string>\n reasoningTokens?: number\n tokensKnown: boolean\n usdKnown: boolean\n sawLlmCall: boolean\n sawTokenUsage: boolean\n sawCostUsage: boolean\n model?: string\n stopReason?: string\n transportAttempts?: number\n result?: ExecutorResult<unknown>\n sandboxOutcome?: AgentRunOutcome\n}\n\n/**\n * Run ONE agent turn on any backend kind and stream its events. Yields the\n * `RuntimeStreamEvent` vocabulary incrementally and always ends with a `final`\n * event carrying the turn's text and usage (`metadata.tokenUsage`,\n * `metadata.costUsd?`, `metadata.model?`) — on success, failure, abort, and\n * timeout alike. The generator never throws; failures surface in-band as\n * `backend_error` + `final` with a typed `error` detail.\n *\n * @stable\n */\nexport async function* streamAgentTurn(\n backend: AgentTurnBackend,\n input: AgentTurnInput,\n opts: StreamAgentTurnOptions = {},\n): AsyncGenerator<RuntimeStreamEvent> {\n assertTurnTimeout(opts.timeoutMs)\n if ((backend as { kind?: unknown }).kind !== 'executor') {\n throw new ValidationError(\n \"streamAgentTurn: exact execution accepts only kind 'executor'; use Runtime-owned creation\",\n )\n }\n yield* streamAgentTurnInternal(backend, input, opts)\n}\n\n/** @internal Normalize a pre-created box/chat stream without asserting an AgentProfile identity. */\nexport async function* streamObservedAgentTurn(\n backend: ObservedAgentTurnBackend,\n input: AgentTurnInput,\n opts: StreamAgentTurnOptions = {},\n): AsyncGenerator<RuntimeStreamEvent> {\n assertTurnTimeout(opts.timeoutMs)\n yield* streamAgentTurnInternal(backend, input, opts)\n}\n\nfunction assertTurnTimeout(timeoutMs: number | undefined): void {\n if (timeoutMs === undefined) return\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647) {\n throw new ValidationError('streamAgentTurn: timeoutMs must be an integer from 1 to 2147483647')\n }\n}\n\nfunction assertTurnIdentity(value: string | undefined, field: string): void {\n if (value !== undefined && (typeof value !== 'string' || value.trim().length === 0)) {\n throw new ValidationError(`streamAgentTurn: ${field} must be a non-empty string`)\n }\n}\n\nasync function* streamAgentTurnInternal(\n backend: AgentTurnBackend | ObservedAgentTurnBackend,\n input: AgentTurnInput,\n opts: StreamAgentTurnOptions,\n): AsyncGenerator<RuntimeStreamEvent> {\n const label = backend.kind === 'chat' ? backend.backend.kind : backend.kind\n const profile =\n backend.kind === 'executor'\n ? executableAgentProfileSnapshot(backend.profile, 'streamAgentTurn')\n : undefined\n const profileDigest = profile ? authoredProfileDigest(profile) : undefined\n assertTurnIdentity(opts.callId, 'callId')\n assertTurnIdentity(opts.correlationId, 'correlationId')\n const correlation = {\n ...(opts.callId ? { callId: opts.callId } : {}),\n ...(opts.correlationId ? { correlationId: opts.correlationId } : {}),\n }\n const taskInput = input\n const taskDigest = canonicalCandidateDigest(taskInput)\n const task: AgentTaskSpec = {\n id: `turn-${crypto.randomUUID()}`,\n intent: turnIntent(input),\n ...(profileDigest\n ? {\n metadata: {\n identity: {\n profileDigest,\n taskDigest,\n ...(Object.keys(correlation).length > 0 ? { correlation } : {}),\n } satisfies NodeExecutionIdentity,\n },\n }\n : {}),\n }\n const acc: TurnAccumulator = {\n deltaText: '',\n input: 0,\n output: 0,\n costUsd: 0,\n estimatedCostUsd: 0,\n sawEstimatedCost: false,\n promptCache: {},\n tokensKnown: false,\n usdKnown: false,\n sawLlmCall: false,\n sawTokenUsage: false,\n sawCostUsage: false,\n }\n const deadline = deriveTurnSignal(opts.signal, opts.timeoutMs ?? 0)\n const startedAt = Date.now()\n\n let session: RuntimeSession | undefined\n let executor: Executor<unknown> | undefined\n let materialization: ProfileMaterializationReceipt | undefined\n let executionBinding: ExecutionBindingReceipt | undefined\n try {\n const nodeId = task.id\n const attemptId = `${nodeId}:attempt:${crypto.randomUUID()}`\n if (backend.kind === 'executor') {\n executor = backend.factory(\n { profile: profile!, harness: null },\n {\n signal: deadline.signal,\n seams: {},\n node: {\n rootId: nodeId,\n parentId: nodeId,\n nodeId,\n attemptId,\n identity: {\n profileDigest: profileDigest!,\n taskDigest,\n ...(Object.keys(correlation).length > 0 ? { correlation } : {}),\n },\n },\n },\n )\n assertExactExecutorDeclaration(executor, profile!)\n const pending = runtimeOwnedPendingExecutorMaterialization(executor)\n if (pending !== undefined) {\n if (pending.runtime !== executor.runtime || pending.binding.attemptId !== attemptId) {\n throw new ValidationError(\n 'streamAgentTurn: pending executor did not bind the kernel-minted attempt',\n )\n }\n if (authoredProfileDigest(pending.declaration.effectiveProfile) !== profileDigest) {\n throw new ValidationError(\n 'streamAgentTurn: pending executor changed the authored AgentProfile before execution',\n )\n }\n materialization = unknownMaterializationReceipt({\n authoredProfileDigest: profileDigest!,\n runtime: executor.runtime,\n reason: 'executor-receipt-pending',\n })\n executionBinding = unknownExecutionBindingReceipt(\n materialization,\n attemptId,\n 'executor-receipt-pending',\n )\n } else {\n ;({ materialization, executionBinding } = executorEvidence(executor, profile!, attemptId))\n assertExactExecutorEvidence(materialization, executionBinding)\n }\n } else {\n materialization = unknownMaterializationReceipt({\n runtime: backend.kind === 'box' ? 'sandbox' : label,\n reason: 'executor-did-not-report',\n })\n executionBinding = unknownExecutionBindingReceipt(\n materialization,\n attemptId,\n 'executor-did-not-report',\n )\n }\n const startedSession = await awaitAbortable(\n Promise.resolve().then(() => startTurnSession(backend, task, input, deadline.signal, label)),\n deadline.signal,\n )\n session = startedSession\n yield {\n type: 'backend_start',\n task,\n session: startedSession,\n backend: executor?.runtime ?? label,\n metadata: {\n ...(profileDigest\n ? {\n identity: {\n profileDigest,\n taskDigest,\n ...(Object.keys(correlation).length > 0 ? { correlation } : {}),\n },\n }\n : { taskDigest }),\n ...(materialization ? { materialization } : {}),\n ...(executionBinding ? { executionBindings: [executionBinding] } : {}),\n budget: { timeoutMs: opts.timeoutMs ?? null },\n timing: { startedAt: new Date(startedAt).toISOString() },\n },\n timestamp: nowIso(),\n }\n\n const inner =\n backend.kind === 'chat'\n ? driveChatTurn(backend.backend, task, startedSession, input, deadline.signal, acc)\n : backend.kind === 'executor'\n ? driveExecutorTurn(\n executor!,\n task,\n startedSession,\n input,\n deadline.signal,\n acc,\n materializedModel(materialization, profile!),\n )\n : driveBoxTurn(\n backend.box,\n input,\n deadline.signal,\n backend.agentRunName ?? 'agent',\n acc,\n {\n ...(backend.options ? { options: backend.options } : {}),\n preserveToolParts: opts.preserveToolParts === true,\n ...(opts.onRawEvent ? { onRawEvent: opts.onRawEvent } : {}),\n },\n )\n // One dedupe for every backend kind: a repeated provider `sourceEventId` is the same child\n // update, so the turn publishes it once whether it arrives live, on reconnect, or on replay.\n const seenChildTaskUpdates = new Set<string>()\n for await (const event of abortableValues(inner, deadline.signal)) {\n if (childTaskAlreadySeen(event, seenChildTaskUpdates)) {\n throwIfAborted(deadline.signal)\n continue\n }\n yield event\n throwIfAborted(deadline.signal)\n }\n // Some providers close their iterator instead of throwing after an abort\n // or deadline. Never turn that silent close into a successful completion.\n throwIfAborted(deadline.signal)\n\n if (backend.kind === 'executor') {\n ;({ materialization, executionBinding } = executorEvidence(executor!, profile!, attemptId))\n assertExactExecutorEvidence(materialization, executionBinding)\n }\n\n const terminalOutcome = acc.sandboxOutcome\n ? projectSandboxOutcome(acc.sandboxOutcome)\n : { status: 'completed' as const, reason: 'turn completed' }\n yield buildFinalEvent(\n task,\n session,\n acc,\n terminalOutcome,\n turnProvenance(\n startedAt,\n opts.timeoutMs,\n profileDigest,\n taskDigest,\n materialization,\n executionBinding,\n correlation,\n ),\n )\n } catch (err) {\n // The turn is over, so a pending receipt cannot still resolve. `backend_start` already\n // carried the pending value, where it was true; the final event must name the terminal\n // outcome instead of a wait that has ended.\n if (\n materialization?.status === 'unknown' &&\n materialization.reason === 'executor-receipt-pending' &&\n executionBinding?.status === 'unknown'\n ) {\n const terminal = unknownMaterializationReceipt({\n ...(materialization.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: materialization.authoredProfileDigest }),\n runtime: materialization.runtime,\n reason: 'executor-failed-before-receipt',\n })\n executionBinding = unknownExecutionBindingReceipt(\n terminal,\n executionBinding.attemptId,\n 'executor-failed-before-receipt',\n )\n materialization = terminal\n }\n const callerAborted = opts.signal?.aborted === true\n const sandboxProjection = acc.sandboxOutcome\n ? projectSandboxOutcome(acc.sandboxOutcome)\n : undefined\n const status: AgentTaskStatus = callerAborted\n ? 'aborted'\n : (sandboxProjection?.status ?? 'failed')\n const message = sandboxProjection?.reason ?? (err instanceof Error ? err.message : String(err))\n const error: BackendErrorDetail =\n sandboxProjection?.error ??\n (err instanceof BackendTransportError\n ? { kind: 'transport', message, status: err.status, body: err.body }\n : { kind: 'backend', message })\n yield {\n type: 'backend_error',\n task,\n ...(session ? { session } : {}),\n backend: label,\n message,\n recoverable: !callerAborted,\n error,\n timestamp: nowIso(),\n }\n yield buildFinalEvent(\n task,\n session,\n acc,\n { status, reason: message, error },\n turnProvenance(\n startedAt,\n opts.timeoutMs,\n profileDigest,\n taskDigest,\n materialization,\n executionBinding,\n correlation,\n ),\n )\n } finally {\n if (executor) {\n await awaitAbortable(\n Promise.resolve().then(() => executor!.teardown('brutalKill')),\n deadline.signal,\n ).catch(() => undefined)\n }\n deadline.dispose()\n }\n}\n\nfunction assertExactExecutorEvidence(\n materialization: ProfileMaterializationReceipt,\n executionBinding: ExecutionBindingReceipt,\n): void {\n if (materialization.status !== 'known' || executionBinding.status !== 'known') {\n throw new ValidationError(\n 'streamAgentTurn: exact profile execution requires terminally validated Runtime materialization and execution binding evidence',\n )\n }\n if (materialization.effectiveProfileDigest !== materialization.authoredProfileDigest) {\n throw new ValidationError(\n 'streamAgentTurn: executor changed the authored AgentProfile; exact turn execution refuses profile overlays',\n )\n }\n}\n\n/**\n * Drain a `streamAgentTurn` stream (or any `RuntimeStreamEvent` stream that\n * honors its terminal contract) into the turn summary plus the full event\n * list. Fail-loud: throws when the stream ends without a terminal `final`\n * event — a stream that violates the contract must not read as an empty turn.\n *\n * @stable\n */\nexport async function collectAgentTurn(\n stream: AsyncIterable<RuntimeStreamEvent>,\n): Promise<CollectedAgentTurn> {\n const events: RuntimeStreamEvent[] = []\n for await (const event of stream) events.push(event)\n const final = events.at(-1)\n if (final?.type !== 'final') {\n throw new Error(\n `collectAgentTurn: stream ended without a terminal 'final' event (last: ${final ? final.type : 'none'})`,\n )\n }\n const metadata = final.metadata ?? {}\n const resultMetadata =\n metadata.result && typeof metadata.result === 'object'\n ? (metadata.result as Record<string, unknown>)\n : undefined\n const sandboxOutcome =\n metadata.sandboxOutcome && typeof metadata.sandboxOutcome === 'object'\n ? (metadata.sandboxOutcome as AgentRunOutcome)\n : undefined\n const tokenUsage =\n metadata.tokenUsage && typeof metadata.tokenUsage === 'object'\n ? (metadata.tokenUsage as Record<string, unknown>)\n : {}\n const usage: AgentTurnUsage = {\n input: finiteNumber(tokenUsage.input) ?? 0,\n output: finiteNumber(tokenUsage.output) ?? 0,\n ...(metadata.tokensKnown === false ? { tokensKnown: false as const } : {}),\n }\n const costUsd = finiteNumber(metadata.costUsd)\n if (costUsd !== undefined) usage.costUsd = costUsd\n if (metadata.usdKnown === false) usage.usdKnown = false\n const estimatedCostUsd = finiteNumber(metadata.estimatedCostUsd)\n if (estimatedCostUsd !== undefined) usage.estimatedCostUsd = estimatedCostUsd\n if (metadata.promptCache && typeof metadata.promptCache === 'object') {\n usage.promptCache = metadata.promptCache as Record<string, number | string>\n }\n const reasoningTokens = finiteNumber(metadata.reasoningTokens)\n if (reasoningTokens !== undefined) usage.reasoningTokens = reasoningTokens\n if (typeof metadata.model === 'string' && metadata.model.length > 0) {\n usage.model = metadata.model\n }\n const transportAttempts = finiteNumber(metadata.transportAttempts)\n const toolCalls = events\n .filter((event) => event.type === 'tool_call')\n .map((event) => ({\n ...(event.toolCallId ? { id: event.toolCallId } : {}),\n name: event.toolName,\n arguments: typeof event.args === 'string' ? event.args : JSON.stringify(event.args ?? {}),\n }))\n return {\n finalText: final.text ?? '',\n ...(resultMetadata && 'output' in resultMetadata ? { output: resultMetadata.output } : {}),\n usage,\n ...(transportAttempts !== undefined ? { transportAttempts } : {}),\n toolCalls,\n events,\n status: final.status,\n ...(final.error ? { error: final.error } : {}),\n ...(sandboxOutcome ? { sandboxOutcome } : {}),\n }\n}\n\n/** Start the backend's session when it owns one (`chat` kind); mint a local\n * correlation session otherwise. Box/executor turns carry no server session\n * here — resume lives in `openSandboxRun`/`SandboxLineage`, not this primitive. */\nasync function startTurnSession(\n backend: AgentTurnBackend | ObservedAgentTurnBackend,\n task: AgentTaskSpec,\n input: AgentTurnInput,\n signal: AbortSignal,\n label: string,\n): Promise<RuntimeSession> {\n if (backend.kind === 'chat' && backend.backend.start) {\n return backend.backend.start(turnBackendInput(task, input), {\n task,\n knowledge: emptyReadiness(task),\n signal,\n })\n }\n return newRuntimeSession(label)\n}\n\n/** Box-drive configuration derived from the backend kind + turn options. */\ninterface BoxTurnConfig {\n /** Caller `PromptOptions` forwarded to `streamPrompt`; the turn's derived\n * signal is installed over any caller value. */\n options?: Omit<PromptOptions, 'signal'>\n /** Project tool parts to `tool_call`/`tool_result` (see `mapSandboxToolEvent`). */\n preserveToolParts: boolean\n /** Awaited raw-event tap, before projection. */\n onRawEvent?: (event: SandboxEvent) => void | Promise<void>\n}\n\n/**\n * One turn over a box: `box.streamPrompt` projected through the existing\n * `mapSandboxEvent` (text/reasoning deltas +\n * cost-bearing `llm_call`s), plus the opt-in `mapSandboxToolEvent` tool-part\n * projection. Usage accumulates off the mapped `llm_call` events — the same\n * fold `sumSandboxUsage` applies. Final text prefers the terminal\n * `result`/`done`/`final` payload over concatenated deltas, because the\n * sandbox `message.part.updated` fallback may carry running accumulations.\n */\nasync function* driveBoxTurn(\n box: SandboxInstance,\n input: AgentTurnInput,\n signal: AbortSignal,\n agentRunName: string,\n acc: TurnAccumulator,\n cfg: BoxTurnConfig,\n): AsyncGenerator<RuntimeStreamEvent> {\n const callOptions: PromptOptions = { ...(cfg.options ?? {}), signal }\n const stream = box.streamPrompt(promptFromAgentTurnInput(input), {\n ...callOptions,\n ...promptOptionsFromAgentTurnInput(input),\n signal,\n })\n const toolParts = cfg.preserveToolParts ? createSandboxToolPartState() : undefined\n const outcomeTracker = createAgentRunOutcomeTracker()\n for await (const event of abortableValues(stream, signal)) {\n outcomeTracker.observe(event)\n if (cfg.onRawEvent) {\n await awaitAbortable(\n Promise.resolve().then(() => cfg.onRawEvent!(event)),\n signal,\n )\n }\n const terminalText = terminalTextFromSandboxEvent(event)\n if (terminalText !== undefined) acc.terminalText = terminalText\n const canonical = canonicalStreamEventFromSandboxEvent(event)\n if (canonical) {\n yield canonical\n continue\n }\n\n if (toolParts) {\n for (const toolEvent of mapSandboxToolEvent(event, toolParts)) {\n yield toolEvent\n }\n }\n const mapped = mapSandboxEvent(event, { agentRunName })\n if (mapped) {\n // `mapSandboxEvent` stamps `agentRunName` as the model label when the\n // event carried none — a run label, not a reported model. Exclude it from\n // the terminal usage so `usage.model` is never a fabricated value.\n foldEvent(mapped, acc, agentRunName)\n yield mapped\n }\n\n // Unknown provider events stay available through onRawEvent. Do not copy\n // arbitrary provider payloads into the public stream.\n }\n acc.sandboxOutcome = outcomeTracker.finish()\n const projection = projectSandboxOutcome(acc.sandboxOutcome)\n if (projection.status === 'failed') {\n throw new Error(projection.reason)\n }\n}\n\n/** One turn over an in-process backend: its own `stream()` surface, projected\n * through the same `normalizeBackendStreamEvent` the task lifecycle applies. */\nasync function* driveChatTurn(\n backend: AgentExecutionBackend,\n task: AgentTaskSpec,\n session: RuntimeSession,\n input: AgentTurnInput,\n signal: AbortSignal,\n acc: TurnAccumulator,\n): AsyncGenerator<RuntimeStreamEvent> {\n const backendInput = turnBackendInput(task, input)\n const context = { task, knowledge: emptyReadiness(task), session, signal }\n for await (const raw of abortableValues(backend.stream(backendInput, context), signal)) {\n const event = normalizeBackendStreamEvent(raw, task, session)\n foldEvent(event, acc)\n yield event\n }\n}\n\nasync function* driveExecutorTurn(\n executor: Executor<unknown>,\n task: AgentTaskSpec,\n session: RuntimeSession,\n input: AgentTurnInput,\n signal: AbortSignal,\n acc: TurnAccumulator,\n declaredModel: string | undefined,\n): AsyncGenerator<RuntimeStreamEvent> {\n const taskValue = executorTaskValue(input)\n const run = executor.execute(taskValue, signal)\n let result: ExecutorResult<unknown>\n if (isAsyncIterable(run)) {\n for await (const usage of abortableValues(run, signal)) {\n if (usage.kind === 'progress') {\n const projected = executorProgressStreamEvent(usage.progress, task, session)\n foldEvent(projected, acc)\n yield projected\n throwIfAborted(signal)\n continue\n }\n foldUsageEvent(usage, acc)\n throwIfAborted(signal)\n }\n result = executor.resultArtifact()\n } else {\n result = await awaitAbortable(run, signal)\n }\n acc.result = result\n acc.sandboxOutcome = readSandboxOutcome(result.out)\n acc.terminalText = executorResultText(result.out)\n acc.input = result.spent.tokens.input\n acc.output = result.spent.tokens.output\n acc.costUsd = result.spent.usd\n const estimatedCostUsd = executorResultEstimatedCost(result.out)\n if (estimatedCostUsd !== undefined) {\n acc.estimatedCostUsd = estimatedCostUsd\n acc.sawEstimatedCost = true\n }\n Object.assign(acc.promptCache, executorResultPromptCache(result.out))\n acc.reasoningTokens = executorResultReasoningTokens(result.out)\n acc.tokensKnown = result.spent.tokensKnown !== false\n acc.usdKnown = result.spent.usdKnown !== false\n acc.sawLlmCall = true\n\n // Usage model identity is observational: the executor must report what answered. The profile's\n // declared model remains available in materialization evidence, but it is not fabricated into\n // `usage.model` when the provider/transport omitted an actual response model.\n const model = executorResultModel(result.out)\n if (model) acc.model = model\n acc.stopReason = executorResultStopReason(result.out)\n acc.transportAttempts = executorResultTransportAttempts(result.out)\n const latencyMs = result.spent.ms\n yield {\n type: 'llm_call',\n task,\n session,\n model: model ?? declaredModel ?? executor.runtime,\n ...(acc.tokensKnown ? { tokensIn: acc.input, tokensOut: acc.output } : {}),\n ...(acc.usdKnown ? { costUsd: acc.costUsd } : {}),\n ...(acc.tokensKnown ? {} : { tokensKnown: false }),\n ...(acc.usdKnown ? {} : { usdKnown: false }),\n ...(acc.sawEstimatedCost ? { estimatedCostUsd: acc.estimatedCostUsd } : {}),\n ...(Object.keys(acc.promptCache).length > 0 ? { promptCache: acc.promptCache } : {}),\n latencyMs,\n timestamp: nowIso(),\n }\n for (const call of executorResultToolCalls(result.out)) {\n yield {\n type: 'tool_call',\n task,\n session,\n toolName: call.name,\n ...(call.id ? { toolCallId: call.id } : {}),\n args: call.arguments,\n timestamp: nowIso(),\n }\n }\n yield {\n type: 'artifact',\n task,\n session,\n artifactId: result.outRef,\n name: 'agent-turn-result',\n metadata: {\n spend: result.spent,\n ...(result.verdict ? { verdict: result.verdict } : {}),\n },\n timestamp: nowIso(),\n }\n if (acc.sandboxOutcome && projectSandboxOutcome(acc.sandboxOutcome).status === 'failed') {\n throw new Error(projectSandboxOutcome(acc.sandboxOutcome).reason)\n }\n}\n\nfunction executorTaskValue(input: AgentTurnInput): unknown {\n const messages = input.providerOptions?.messages\n if (Array.isArray(messages)) {\n return { messages: structuredClone(messages) }\n }\n return {\n ...(input.prompt === undefined ? {} : { prompt: input.prompt }),\n ...(input.parts === undefined ? {} : { parts: structuredClone(input.parts) }),\n ...(input.interactions === undefined ? {} : { interactions: input.interactions }),\n }\n}\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<UsageEvent> {\n return typeof value === 'object' && value !== null && Symbol.asyncIterator in value\n}\n\n/**\n * Pull one provider iterator under Runtime's deadline.\n *\n * Providers still receive the signal for native cancellation, but correctness\n * does not depend on them observing it. A losing iterator is asked to close;\n * its late rejection is observed and cannot delay the terminal Runtime event.\n */\nasync function* abortableValues<T>(\n source: AsyncIterable<T>,\n signal: AbortSignal,\n): AsyncGenerator<T> {\n const iterator = source[Symbol.asyncIterator]()\n let completed = false\n try {\n for (;;) {\n const next = await awaitAbortable(\n Promise.resolve().then(() => iterator.next()),\n signal,\n )\n if (next.done) {\n completed = true\n return\n }\n yield next.value\n }\n } finally {\n if (!completed) {\n try {\n void Promise.resolve(iterator.return?.()).catch(() => undefined)\n } catch {\n // The Runtime deadline already owns the observable terminal result.\n }\n }\n }\n}\n\nfunction executorResultText(value: unknown): string {\n if (typeof value === 'string') return value\n if (!value || typeof value !== 'object') return ''\n const content = (value as Record<string, unknown>).content\n return typeof content === 'string' ? content : ''\n}\n\nfunction executorResultModel(value: unknown): string | undefined {\n if (!value || typeof value !== 'object') return undefined\n const model = (value as Record<string, unknown>).model\n return typeof model === 'string' && model.length > 0 ? model : undefined\n}\n\nfunction executorResultStopReason(value: unknown): string | undefined {\n if (!value || typeof value !== 'object') return undefined\n const reason = (value as Record<string, unknown>).finishReason\n return typeof reason === 'string' && reason.length > 0 ? reason : undefined\n}\n\nfunction executorResultTransportAttempts(value: unknown): number | undefined {\n if (!value || typeof value !== 'object') return undefined\n const attempts = (value as Record<string, unknown>).transportAttempts\n return typeof attempts === 'number' && Number.isSafeInteger(attempts) && attempts > 0\n ? attempts\n : undefined\n}\n\nfunction executorResultEstimatedCost(value: unknown): number | undefined {\n if (!value || typeof value !== 'object') return undefined\n return finiteNumber((value as Record<string, unknown>).estimatedCostUsd)\n}\n\nfunction executorResultPromptCache(value: unknown): Record<string, number | string> {\n if (!value || typeof value !== 'object') return {}\n const raw = (value as Record<string, unknown>).promptCache\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}\n const cache: Record<string, number | string> = {}\n for (const [key, entry] of Object.entries(raw)) {\n if ((typeof entry === 'number' && Number.isFinite(entry)) || typeof entry === 'string') {\n cache[key] = entry\n }\n }\n return cache\n}\n\nfunction executorResultReasoningTokens(value: unknown): number | undefined {\n if (!value || typeof value !== 'object') return undefined\n const count = (value as Record<string, unknown>).reasoningTokens\n return Number.isSafeInteger(count) && (count as number) >= 0 ? (count as number) : undefined\n}\n\n/**\n * Read the terminal tool calls an executor artifact published. Every Runtime-owned executor\n * reports `ExecutorToolCall[]`, so an artifact carrying any other shape is a defect in that\n * executor rather than a turn without tool calls: refuse it instead of dropping the calls.\n */\nfunction executorResultToolCalls(\n value: unknown,\n): Array<{ id?: string; name: string; arguments: string }> {\n if (!value || typeof value !== 'object') return []\n const raw = (value as Record<string, unknown>).toolCalls\n if (raw === undefined) return []\n if (!Array.isArray(raw)) {\n throw new ValidationError(\n `streamAgentTurn: executor artifact toolCalls must be an ExecutorToolCall array, received ${typeof raw}`,\n )\n }\n return raw.map((entry) => {\n const call = entry && typeof entry === 'object' ? (entry as Record<string, unknown>) : undefined\n if (!call || typeof call.name !== 'string' || call.name.length === 0) {\n throw new ValidationError(\n 'streamAgentTurn: executor artifact toolCalls entries require a non-empty name',\n )\n }\n return {\n ...(typeof call.id === 'string' ? { id: call.id } : {}),\n name: call.name,\n arguments:\n typeof call.arguments === 'string' ? call.arguments : JSON.stringify(call.arguments ?? {}),\n }\n })\n}\n\n/** Project one executor progress event onto the public turn vocabulary. */\nfunction executorProgressStreamEvent(\n progress: ExecutorProgressEvent,\n task: AgentTaskSpec,\n session: RuntimeSession,\n): RuntimeStreamEvent {\n const timestamp = nowIso()\n if (progress.kind === 'text_delta') {\n return { type: 'text_delta', task, session, text: progress.text, timestamp }\n }\n if (progress.kind === 'reasoning_delta') {\n return { type: 'reasoning_delta', task, session, text: progress.text, timestamp }\n }\n if (progress.kind === 'tool_call') {\n return {\n type: 'tool_call',\n task,\n session,\n toolName: progress.toolName,\n ...(progress.toolCallId === undefined ? {} : { toolCallId: progress.toolCallId }),\n ...(progress.args === undefined ? {} : { args: progress.args }),\n timestamp,\n }\n }\n if (progress.kind === 'tool_result') {\n return {\n type: 'tool_result',\n task,\n session,\n toolName: progress.toolName,\n ...(progress.toolCallId === undefined ? {} : { toolCallId: progress.toolCallId }),\n ...(progress.result === undefined ? {} : { result: progress.result }),\n timestamp,\n }\n }\n if (progress.kind === 'child_task') {\n return { ...progress.event, task, session, timestamp }\n }\n return { type: 'interaction', request: progress.request, task, session, timestamp }\n}\n\n/**\n * Drop a child-task update this turn already published. The provider's `sourceEventId` names one\n * exact update, so a reconnect or replay that repeats it must not add a second child.\n */\nfunction childTaskAlreadySeen(event: RuntimeStreamEvent, seen: Set<string>): boolean {\n if (event.type !== 'child-task') return false\n if (seen.has(event.sourceEventId)) return true\n seen.add(event.sourceEventId)\n return false\n}\n\n/** Fold one normalized executor usage event into the turn accumulator. */\nfunction foldUsageEvent(event: UsageEvent, acc: TurnAccumulator): void {\n if (event.kind === 'tokens') {\n const known = event.tokensKnown !== false\n acc.tokensKnown = acc.sawTokenUsage ? acc.tokensKnown && known : known\n acc.sawTokenUsage = true\n acc.input += event.input\n acc.output += event.output\n } else if (event.kind === 'cost') {\n const known = event.usdKnown\n acc.usdKnown = acc.sawCostUsage ? acc.usdKnown && known : known\n acc.sawCostUsage = true\n acc.costUsd += event.usd\n if (event.usdKnown === false && event.usdEstimated !== undefined) {\n acc.estimatedCostUsd += event.usdEstimated\n acc.sawEstimatedCost = true\n }\n }\n if (event.kind === 'tokens' || event.kind === 'cost') acc.sawLlmCall = true\n}\n\n/** Fold one normalized event into the turn accumulator (text + usage).\n * `fallbackModelLabel` — a mapper-stamped run label to exclude from\n * `usage.model` (it is not a backend-reported model). */\nfunction foldEvent(\n event: RuntimeStreamEvent,\n acc: TurnAccumulator,\n fallbackModelLabel?: string,\n): void {\n if (event.type === 'text_delta') {\n acc.deltaText += event.text\n return\n }\n if (event.type === 'llm_call') {\n const tokensReported =\n event.tokensKnown !== false && event.tokensIn !== undefined && event.tokensOut !== undefined\n const usdReported = event.usdKnown !== false && event.costUsd !== undefined\n if (!acc.sawLlmCall) {\n acc.tokensKnown = tokensReported\n acc.usdKnown = usdReported\n acc.sawLlmCall = true\n } else {\n acc.tokensKnown &&= tokensReported\n acc.usdKnown &&= usdReported\n }\n acc.input += event.tokensIn ?? 0\n acc.output += event.tokensOut ?? 0\n acc.costUsd += event.costUsd ?? 0\n if (event.estimatedCostUsd !== undefined) {\n acc.estimatedCostUsd += event.estimatedCostUsd\n acc.sawEstimatedCost = true\n }\n if (event.promptCache) Object.assign(acc.promptCache, event.promptCache)\n if (event.model && event.model !== fallbackModelLabel) acc.model = event.model\n }\n}\n\n/** Read the final text off a terminal sandbox event, when present. */\nfunction terminalTextFromSandboxEvent(event: SandboxEvent): string | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n if (!isSandboxTerminalEvent(type)) return undefined\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n for (const key of ['finalText', 'text', 'response', 'content']) {\n const value = data[key]\n if (typeof value === 'string') return value\n }\n return undefined\n}\n\nfunction buildFinalEvent(\n task: AgentTaskSpec,\n session: RuntimeSession | undefined,\n acc: TurnAccumulator,\n outcome: { status: AgentTaskStatus; reason: string; error?: BackendErrorDetail },\n provenance: Record<string, unknown>,\n): RuntimeStreamEvent {\n const finalText = acc.terminalText ?? acc.deltaText\n return {\n type: 'final',\n task,\n ...(session ? { session } : {}),\n status: outcome.status,\n reason: outcome.status === 'completed' ? (acc.stopReason ?? outcome.reason) : outcome.reason,\n ...(finalText ? { text: finalText } : {}),\n metadata: {\n tokenUsage: { input: acc.input, output: acc.output },\n ...(acc.tokensKnown ? {} : { tokensKnown: false }),\n ...(acc.usdKnown ? { costUsd: acc.costUsd } : { usdKnown: false }),\n ...(acc.sawEstimatedCost ? { estimatedCostUsd: acc.estimatedCostUsd } : {}),\n ...(Object.keys(acc.promptCache).length > 0 ? { promptCache: acc.promptCache } : {}),\n ...(acc.reasoningTokens !== undefined ? { reasoningTokens: acc.reasoningTokens } : {}),\n ...(acc.model ? { model: acc.model } : {}),\n ...(acc.stopReason ? { stopReason: acc.stopReason } : {}),\n ...(acc.transportAttempts !== undefined ? { transportAttempts: acc.transportAttempts } : {}),\n ...(acc.sandboxOutcome\n ? {\n sandboxOutcome: acc.sandboxOutcome,\n verdict: projectSandboxOutcome(acc.sandboxOutcome).verdict,\n }\n : {}),\n ...(acc.result\n ? {\n result: {\n outRef: acc.result.outRef,\n output: acc.result.out,\n ...(acc.sandboxOutcome\n ? { verdict: projectSandboxOutcome(acc.sandboxOutcome).verdict }\n : acc.result.verdict\n ? { verdict: acc.result.verdict }\n : {}),\n spent: acc.result.spent,\n },\n }\n : acc.sandboxOutcome\n ? { result: { verdict: projectSandboxOutcome(acc.sandboxOutcome).verdict } }\n : {}),\n ...provenance,\n },\n ...(outcome.error ? { error: outcome.error } : {}),\n timestamp: nowIso(),\n }\n}\n\nfunction materializedModel(\n receipt: ProfileMaterializationReceipt | undefined,\n profile: AgentProfile,\n): string | undefined {\n if (receipt?.status === 'known' && receipt.model.status === 'known') return receipt.model.id\n const fallback = profile.model?.default\n return typeof fallback === 'string' && fallback.length > 0 ? fallback : undefined\n}\n\n/** Minimal ready-by-construction readiness report for a requirement-free turn. */\nfunction emptyReadiness(task: AgentTaskSpec) {\n return scoreKnowledgeReadiness({ taskId: task.id, requirements: [] })\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (!signal.aborted) return\n throw signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason))\n}\n\n/**\n * Derive the turn's effective abort signal: fires when EITHER the caller's\n * signal aborts OR the `timeoutMs` deadline elapses. `dispose()` clears the\n * timer so a finished turn never leaks a pending timeout. `timeoutMs <= 0`\n * disables the deadline. Node-portable (no `AbortSignal.any`, which needs\n * >=20.3 — the package floor is >=20).\n */\nfunction deriveTurnSignal(\n callerSignal: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; dispose: () => void } {\n const controller = new AbortController()\n const timer =\n timeoutMs > 0\n ? setTimeout(\n () => controller.abort(new Error(`agent turn timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n : undefined\n if (timer && typeof (timer as { unref?: () => void }).unref === 'function') {\n ;(timer as { unref: () => void }).unref()\n }\n const onCallerAbort = () =>\n controller.abort(callerSignal?.reason ?? new Error('agent turn aborted'))\n if (callerSignal) {\n if (callerSignal.aborted) onCallerAbort()\n else callerSignal.addEventListener('abort', onCallerAbort, { once: true })\n }\n return {\n signal: controller.signal,\n dispose: () => {\n if (timer) clearTimeout(timer)\n callerSignal?.removeEventListener('abort', onCallerAbort)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,kBACd,SACA,aACA,UACgB;CAChB,MAAM,MAAM,OAAO;CACnB,OAAO;EACL,IAAI,eAAe,OAAO,WAAW;EACrC;EACA,QAAQ;EACR,WAAW;EACX,WAAW;EACX;CACF;AACF;;AAGA,SAAgB,aAAa,SAAyC;CACpE,OAAO;EAAE,GAAG;EAAS,WAAW,OAAO;CAAE;AAC3C;;AAGA,SAAgB,SAAiB;CAC/B,wBAAO,IAAI,KAAK,EAAA,CAAE,YAAY;AAChC;;AAqBA,eAAsB,4BACpB,SACqC;CACrC,MAAM,WACJ,QAAQ,UAAU,QAAQ,YAAY,MAAM,QAAQ,OAAO,IAAI,QAAQ,SAAS,IAAI,KAAA;CACtF,IAAI,CAAC,UAAU;EACb,MAAM,QAAQ,oBAAoB,QAAQ,KAAK;EAC/C,MAAM,UAAU,QAAQ,QAAQ,QAC5B,MAAM,QAAQ,QAAQ,MA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,OAAO;EACL,QAAQ,WAAW;EACnB,eAAe;GACb,IAAI,OAAO,aAAa,KAAK;GAC7B,cAAc,oBAAoB,SAAS,aAAa;EAC1D;CACF;AACF"}
@@ -1,8 +1,8 @@
1
- import { n as streamAgentTurn, t as collectAgentTurn } from "./stream-agent-turn-CXRugSGO.js";
2
- import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore } from "./spawn-journal-D2HKUImC.js";
3
- import { T as executableAgentProfileSnapshot } from "./materialization-P86EciBw.js";
4
- import { i as concreteModelId, s as profileModelExecutionSettings, t as assertExecutableAgentProfile } from "./model-policy-DgRJIJse.js";
5
- import { I as createExecutor, P as captureReusableExecutorConfig, l as withDriverExecutor, n as createSupervisor, yt as observedModelMatchesDeclared } from "./supervisor-s8SfZYbW.js";
1
+ import { n as streamAgentTurn, t as collectAgentTurn } from "./stream-agent-turn-DYi8ymsU.js";
2
+ import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore } from "./spawn-journal-BLnveCRS.js";
3
+ import { t as executableAgentProfileSnapshot } from "./executable-spec-BUcUcEPk.js";
4
+ import { c as profileModelExecutionSettings, i as concreteModelId, o as enforceTokenLimits, t as assertExecutableAgentProfile } from "./model-policy-Sw4ywhtL.js";
5
+ import { L as captureReusableExecutorConfig, l as withDriverExecutor, n as createSupervisor, wt as observedModelMatchesDeclared, z as createExecutor } from "./supervisor-CMZsJ7Wn.js";
6
6
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest } from "@tangle-network/agent-interface";
7
7
  import { costForTokenPricing, makeProposalFinding } from "@tangle-network/agent-eval";
8
8
  import { randomBytes } from "node:crypto";
@@ -281,21 +281,39 @@ function responseProfile(profile, req, context) {
281
281
  function assertProfileChatRequest(req, model, reasoningEffort, settings, context) {
282
282
  if (req.model !== void 0 && req.model !== model) throw new Error(`${context}: request model ${JSON.stringify(req.model)} conflicts with AgentProfile model ${JSON.stringify(model)}`);
283
283
  if (req.temperature !== void 0 && req.temperature !== settings.temperature) throw new Error(`${context}: request temperature conflicts with AgentProfile model metadata`);
284
- if (req.maxTokens !== void 0 && req.maxTokens !== settings.maxTokens) throw new Error(`${context}: request maxTokens conflicts with AgentProfile model metadata`);
284
+ if (req.maxTokens !== void 0) {
285
+ const applied = enforceTokenLimits(settings.tokenLimits, "router", context).applied;
286
+ if (req.maxTokens !== applied.maxTokens) throw new Error(`${context}: request maxTokens ${req.maxTokens} conflicts with AgentProfile.model.maxVisibleOutputTokens ${applied.maxTokens ?? "unset"}`);
287
+ }
285
288
  if (req.thinking !== void 0) {
286
289
  const expected = reasoningEffort === void 0 ? void 0 : reasoningEffort === "none" ? "disabled" : "enabled";
287
290
  if (req.thinking !== expected) throw new Error(`${context}: request thinking conflicts with AgentProfile.model.reasoningEffort`);
288
291
  }
289
292
  }
293
+ /**
294
+ * Which dollar fact a receipt carries, in the one order that never presents an estimate as a
295
+ * measurement: a provider receipt, else this runtime's own estimate, else the catalog rate the
296
+ * caller supplied, else an explicit refusal to state a cost.
297
+ *
298
+ * `pricing` is deliberately withheld on the unknown-usage path. A per-token rate applied to the
299
+ * zero token counts that path reports would produce a fabricated `$0`, which is the one thing
300
+ * `costUnknown` exists to prevent.
301
+ */
302
+ function costAttribution(usage, pricing) {
303
+ const actualCostUsd = usage.usdKnown === false ? void 0 : usage.costUsd;
304
+ if (actualCostUsd !== void 0) return { actualCostUsd };
305
+ if (usage.estimatedCostUsd !== void 0) return { estimatedCostUsd: usage.estimatedCostUsd };
306
+ if (pricing) return { customTokenPricing: pricing };
307
+ return { costUnknown: true };
308
+ }
290
309
  function optimizerReceipt(model, run, pricing) {
291
310
  const usage = run.turn.usage;
292
- const actualCostUsd = usage.usdKnown === false ? void 0 : usage.costUsd;
293
311
  if (usage.tokensKnown === false) return {
294
312
  model,
295
313
  inputTokens: 0,
296
314
  outputTokens: 0,
297
315
  usageUnknown: true,
298
- ...actualCostUsd !== void 0 ? { actualCostUsd } : usage.estimatedCostUsd !== void 0 ? { estimatedCostUsd: usage.estimatedCostUsd } : { costUnknown: true }
316
+ ...costAttribution(usage, void 0)
299
317
  };
300
318
  const cachedTokens = optimizerTokenCount(usage.promptCache?.readTokens, "cache read tokens");
301
319
  const cacheWriteTokens = optimizerTokenCount(usage.promptCache?.writeTokens, "cache write tokens");
@@ -308,21 +326,20 @@ function optimizerReceipt(model, run, pricing) {
308
326
  ...cachedTokens !== void 0 ? { cachedTokens } : {},
309
327
  ...cacheWriteTokens !== void 0 ? { cacheWriteTokens } : {},
310
328
  ...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
311
- ...actualCostUsd !== void 0 ? { actualCostUsd } : usage.estimatedCostUsd !== void 0 ? { estimatedCostUsd: usage.estimatedCostUsd } : pricing ? { customTokenPricing: pricing } : { costUnknown: true }
329
+ ...costAttribution(usage, pricing)
312
330
  };
313
331
  }
314
332
  /** Preserve the observed call totals when finer receipt classification is inconsistent. */
315
333
  function rawOptimizerReceipt(model, run, pricing) {
316
334
  const usage = run.turn.usage;
317
335
  const tokensKnown = usage.tokensKnown !== false;
318
- const actualCostUsd = usage.usdKnown === false ? void 0 : usage.costUsd;
319
336
  return {
320
337
  model,
321
338
  inputTokens: tokensKnown ? usage.input : 0,
322
339
  outputTokens: tokensKnown ? usage.output : 0,
323
340
  ...tokensKnown ? {} : { usageUnknown: true },
324
341
  ...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
325
- ...actualCostUsd !== void 0 ? { actualCostUsd } : usage.estimatedCostUsd !== void 0 ? { estimatedCostUsd: usage.estimatedCostUsd } : pricing ? { customTokenPricing: pricing } : { costUnknown: true }
342
+ ...costAttribution(usage, pricing)
326
343
  };
327
344
  }
328
345
  function optimizerReceiptModel(model, run) {
@@ -609,7 +626,7 @@ async function runShot(surface, _task, handle, tools, messages, opts, profileOve
609
626
  return {
610
627
  messages: out?.messages ?? messages,
611
628
  completions: out?.turns ?? 0,
612
- toolCalls: out?.toolCalls ?? 0,
629
+ toolCalls: out?.toolCalls?.length ?? 0,
613
630
  toolErrors,
614
631
  tokens: {
615
632
  input: turn.usage.input,
@@ -1673,4 +1690,4 @@ function structuralRollout(config = {}) {
1673
1690
  //#endregion
1674
1691
  export { observe as C, optimizerMethod as D, profileOptimizerModelCall as E, strategyAuthorMethod as O, defaultAnalystInstruction as S, profileChatClient as T, depthStrategy as _, defaultStructuralRolloutPolicy as a, sample as b, officialChecksFromMeta as c, selectBestIndex as d, structuralRollout as f, defineStrategy as g, breadthStrategy as h, defaultExtractCandidate as i, resolveEntrySymbol as l, adaptiveRefine as m, compareCheckOutcomes as n, filterAuthoredAsserts as o, visibleCheckScore as p, composeCheckSources as r, modelAuthoredChecks as s, canDisplace as t, sandboxCheckRunner as u, refine as v, renderReport as w, sampleThenRefine as x, runAgentic as y };
1675
1692
 
1676
- //# sourceMappingURL=structural-rollout-CJgj9YXH.js.map
1693
+ //# sourceMappingURL=structural-rollout-D7V-HgXJ.js.map