@tangle-network/agent-runtime 0.142.3 → 0.143.0

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 (77) hide show
  1. package/dist/{activation-o7JKmtxi.js → activation-mi8TgSLM.js} +2 -2
  2. package/dist/{activation-o7JKmtxi.js.map → activation-mi8TgSLM.js.map} +1 -1
  3. package/dist/agent.d.ts +2 -2
  4. package/dist/agent.js +3 -3
  5. package/dist/{analyst-loop-GcX0BY75.js → analyst-loop-CvkmfhUB.js} +2 -2
  6. package/dist/{analyst-loop-GcX0BY75.js.map → analyst-loop-CvkmfhUB.js.map} +1 -1
  7. package/dist/analyst-loop.d.ts +1 -1
  8. package/dist/analyst-loop.js +1 -1
  9. package/dist/{authoring-Bm1WlGPv.js → authoring-DuyShLdw.js} +2 -2
  10. package/dist/{authoring-Bm1WlGPv.js.map → authoring-DuyShLdw.js.map} +1 -1
  11. package/dist/{conversation-DXKJHyqB.js → conversation-1hNtDeMM.js} +3 -3
  12. package/dist/{conversation-DXKJHyqB.js.map → conversation-1hNtDeMM.js.map} +1 -1
  13. package/dist/conversation.d.ts +1 -1
  14. package/dist/conversation.js +1 -1
  15. package/dist/durable.d.ts +2 -2
  16. package/dist/durable.js +1 -1
  17. package/dist/{environment-provider-BicwCDK5.d.ts → environment-provider-B8eZ85Ga.d.ts} +3 -3
  18. package/dist/{environment-provider-DCEACNt9.js → environment-provider-DCBJ13VP.js} +2 -2
  19. package/dist/{environment-provider-DCEACNt9.js.map → environment-provider-DCBJ13VP.js.map} +1 -1
  20. package/dist/environment-provider.d.ts +1 -1
  21. package/dist/environment-provider.js +1 -1
  22. package/dist/{graph-DhrLuLOS.js → graph-De_XEsfH.js} +2 -2
  23. package/dist/{graph-DhrLuLOS.js.map → graph-De_XEsfH.js.map} +1 -1
  24. package/dist/{improvement-cycle-lcwlR6E2.js → improvement-cycle-Bi-Tf4QF.js} +5 -5
  25. package/dist/{improvement-cycle-lcwlR6E2.js.map → improvement-cycle-Bi-Tf4QF.js.map} +1 -1
  26. package/dist/{index-Bx3-tqG-.d.ts → index-B8rKtH3U.d.ts} +4 -4
  27. package/dist/{index-D_aH0F4C.d.ts → index-C2caGomG.d.ts} +12 -27
  28. package/dist/{index-CV1xRWy2.d.ts → index-D4sLkOPY.d.ts} +3 -3
  29. package/dist/index.d.ts +9 -9
  30. package/dist/index.js +9 -9
  31. package/dist/intelligence.d.ts +5 -5
  32. package/dist/intelligence.js +4 -4
  33. package/dist/kernel.d.ts +7 -7
  34. package/dist/kernel.js +10 -10
  35. package/dist/{knowledge-C9LlSJAR.js → knowledge-CVE6Wk1i.js} +3 -3
  36. package/dist/{knowledge-C9LlSJAR.js.map → knowledge-CVE6Wk1i.js.map} +1 -1
  37. package/dist/knowledge.d.ts +1 -1
  38. package/dist/knowledge.js +1 -1
  39. package/dist/{loop-runner-bin-CctBy5-X.d.ts → loop-runner-bin-BoHdQqLm.d.ts} +3 -3
  40. package/dist/{loop-runner-bin-DFo6Ss-1.js → loop-runner-bin-DdaI1nLL.js} +4 -4
  41. package/dist/{loop-runner-bin-DFo6Ss-1.js.map → loop-runner-bin-DdaI1nLL.js.map} +1 -1
  42. package/dist/loop-runner-bin.d.ts +1 -1
  43. package/dist/loop-runner-bin.js +1 -1
  44. package/dist/{materialization-CrdcfWXp.js → materialization-P86EciBw.js} +43 -2
  45. package/dist/materialization-P86EciBw.js.map +1 -0
  46. package/dist/mcp/bin.js +3 -3
  47. package/dist/mcp/index.d.ts +5 -5
  48. package/dist/mcp/index.js +4 -4
  49. package/dist/{openai-tools-CSm460sC.js → openai-tools-BiAWKjh6.js} +2 -2
  50. package/dist/{openai-tools-CSm460sC.js.map → openai-tools-BiAWKjh6.js.map} +1 -1
  51. package/dist/{openai-tools-t5-6h5bj.d.ts → openai-tools-z-whdYNC.d.ts} +2 -2
  52. package/dist/primeintellect/index.d.ts +1 -1
  53. package/dist/profiles.d.ts +1 -1
  54. package/dist/{redact-B0gDSTZO.d.ts → redact-DexTuAiX.d.ts} +3 -3
  55. package/dist/{runtime-DQs5xHdt.js → runtime-BnqjbOGX.js} +18 -12
  56. package/dist/{runtime-DQs5xHdt.js.map → runtime-BnqjbOGX.js.map} +1 -1
  57. package/dist/{runtime-htqI3fKL.d.ts → runtime-J6Toky8K.d.ts} +22 -10
  58. package/dist/{sandbox-events-BK-g19wx.js → sandbox-events-COwCWUVB.js} +6 -49
  59. package/dist/sandbox-events-COwCWUVB.js.map +1 -0
  60. package/dist/{stream-agent-turn-Dfy12OjG.d.ts → stream-agent-turn-C1Vs_3B9.d.ts} +6 -3
  61. package/dist/{stream-agent-turn-BMHUIuQS.js → stream-agent-turn-CXRugSGO.js} +55 -14
  62. package/dist/stream-agent-turn-CXRugSGO.js.map +1 -0
  63. package/dist/{structural-rollout-CzZKDkmA.js → structural-rollout-CJgj9YXH.js} +4 -4
  64. package/dist/{structural-rollout-CzZKDkmA.js.map → structural-rollout-CJgj9YXH.js.map} +1 -1
  65. package/dist/{supervise-BEs5MB91.js → supervise-hCgG6ROJ.js} +3 -3
  66. package/dist/{supervise-BEs5MB91.js.map → supervise-hCgG6ROJ.js.map} +1 -1
  67. package/dist/{supervisor-B_0ISTFG.js → supervisor-s8SfZYbW.js} +107 -43
  68. package/dist/supervisor-s8SfZYbW.js.map +1 -0
  69. package/dist/testing.d.ts +2 -2
  70. package/dist/testing.js +11 -11
  71. package/dist/{types-DZrBoBpN.d.ts → types-DeX8ibLc.d.ts} +4 -1
  72. package/dist/{types-_7w24mMg.d.ts → types-Df9vulGc.d.ts} +2 -2
  73. package/package.json +5 -5
  74. package/dist/materialization-CrdcfWXp.js.map +0 -1
  75. package/dist/sandbox-events-BK-g19wx.js.map +0 -1
  76. package/dist/stream-agent-turn-BMHUIuQS.js.map +0 -1
  77. package/dist/supervisor-B_0ISTFG.js.map +0 -1
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Ao as SupervisorAgentTestDeps, Cn as DriverAgentOptions, Gt as RunGraphTestOptions, Yt as runGraphWithTestBrain, bo as superviseWithTestBrain, vo as SuperviseTestOptions, wn as driverAgent, zo as supervisorAgentWithTestBrain } from "./index-D_aH0F4C.js";
2
- import { at as ToolLoopCallContext, ot as ToolLoopChat } from "./runtime-htqI3fKL.js";
1
+ import { Cn as DriverAgentOptions, Gt as RunGraphTestOptions, Lo as supervisorAgentWithTestBrain, Oo as SupervisorAgentTestDeps, Yt as runGraphWithTestBrain, go as SuperviseTestOptions, vo as superviseWithTestBrain, wn as driverAgent } from "./index-C2caGomG.js";
2
+ import { ot as ToolLoopCallContext, st as ToolLoopChat } from "./runtime-J6Toky8K.js";
3
3
  import { AgentImprovementProposal, AgentProfile, AgentProfileImprovementMeasuredComparison, SandboxSizePreset } from "@tangle-network/agent-interface";
4
4
  //#region src/testing/index.d.ts
5
5
  /** A proposal produced by Runtime's opaque profile-improvement path. */
package/dist/testing.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { $ as parseExactAgentProfile, K as applyExactAgentProfileDiff, rt as canonicalCandidateDigest$1, st as immutableCandidateValue } from "./prepare-D3n7cA39.js";
2
- import { f as verifyAgentImprovementProposal } from "./improvement-cycle-lcwlR6E2.js";
3
- import { c as supervisorAgentWithTestBrain, dt as driverAgent, r as superviseWithTestBrain } from "./supervise-BEs5MB91.js";
4
- import { i as runGraphWithTestBrain } from "./graph-DhrLuLOS.js";
2
+ import { f as verifyAgentImprovementProposal } from "./improvement-cycle-Bi-Tf4QF.js";
3
+ import { c as supervisorAgentWithTestBrain, dt as driverAgent, r as superviseWithTestBrain } from "./supervise-hCgG6ROJ.js";
4
+ import { i as runGraphWithTestBrain } from "./graph-De_XEsfH.js";
5
5
  import { SANDBOX_SIZE_PRESET_NAMES } from "@tangle-network/agent-interface";
6
6
  //#region src/testing/fixtures/agent-improvement-proposal.json
7
7
  var agent_improvement_proposal_default = {
8
8
  changedSurfaces: ["prompt"],
9
- digest: "sha256:b7013ba46d2e69b918f5b68fdb9598677be93996e65d59c7b5c8c55eb16e444a",
9
+ digest: "sha256:48c661298166f66507443e0eec2f7eb29606502ecf140f0f53711eb4575bd831",
10
10
  evaluation: {
11
11
  "decision": {
12
12
  "contributingChecks": [
@@ -4577,7 +4577,7 @@ var agent_improvement_proposal_default = {
4577
4577
  ],
4578
4578
  "metadata": {
4579
4579
  "fixture": "agent-improvement-proposal",
4580
- "runtimeVersion": "0.142.3"
4580
+ "runtimeVersion": "0.143.0"
4581
4581
  },
4582
4582
  "objectives": [
4583
4583
  {
@@ -4688,8 +4688,8 @@ var agent_improvement_proposal_default = {
4688
4688
  "baselineContentHash": "sha256:5c21ee53e513fc604cb09754e21c392b24a424da0ef37dbf8f1ee4a8a0b08f09",
4689
4689
  "candidateContentHash": "sha256:60fcbb1c728194bd51d7d19cb732d1c3f1881dce7e0a6266b41c8b98cfd65693",
4690
4690
  "kind": "agent-eval-loop",
4691
- "recordDigest": "sha256:67fda76a6a9508fc1573c8f00d215051bd4be078ac85db538530e0d20411680b",
4692
- "runId": "agent-runtime-0.142.3-proposal-fixture",
4691
+ "recordDigest": "sha256:37417d66cd978183738751bf0ba0bd7ccd05c69ac9e3ad9050e228681b488f9e",
4692
+ "runId": "agent-runtime-0.143.0-proposal-fixture",
4693
4693
  "schema": "agent-candidate-experiment"
4694
4694
  }
4695
4695
  },
@@ -4712,13 +4712,13 @@ var agent_improvement_proposal_default = {
4712
4712
  }],
4713
4713
  kind: "agent-improvement-proposal",
4714
4714
  proposedAt: "2026-07-10T01:00:00.000Z",
4715
- runId: "agent-runtime-0.142.3-proposal-fixture"
4715
+ runId: "agent-runtime-0.143.0-proposal-fixture"
4716
4716
  };
4717
4717
  //#endregion
4718
4718
  //#region src/testing/fixtures/agent-profile-improvement-proposal.json
4719
4719
  var agent_profile_improvement_proposal_default = {
4720
4720
  changedSurfaces: ["prompt", "skills"],
4721
- digest: "sha256:dd890bcb652aa108a8f0954fe0016853274cf96821f29dda07173738d1232d66",
4721
+ digest: "sha256:ac51cf5857d66e96b6cbdd2c9746ae1a44c95310bb89fb40cb947ebf0f8a0220",
4722
4722
  evaluation: {
4723
4723
  "decision": {
4724
4724
  "contributingChecks": [
@@ -6352,7 +6352,7 @@ var agent_profile_improvement_proposal_default = {
6352
6352
  ],
6353
6353
  "metadata": {
6354
6354
  "fixture": "agent-profile-improvement-proposal",
6355
- "runtimeVersion": "0.142.3"
6355
+ "runtimeVersion": "0.143.0"
6356
6356
  },
6357
6357
  "objectives": [
6358
6358
  {
@@ -6463,7 +6463,7 @@ var agent_profile_improvement_proposal_default = {
6463
6463
  "baselineContentHash": "sha256:21c495a37c418c10bde64fbaa188beddeed31f1f051ea60a6a6582a9ee0db704",
6464
6464
  "candidateContentHash": "sha256:103f77bc8481601eef1ad5fe6ba84a40dffabc3a44f421f8c8559121edab84e9",
6465
6465
  "kind": "agent-eval-loop",
6466
- "recordDigest": "sha256:b1c860be2dbc9e3a73bb296d76429f2554843a65d9c2e3c56a0072860e662de7",
6466
+ "recordDigest": "sha256:45a87e9da971b040445440e2daf2a2cac7aff32ab3b4fc828dd93a1d5a9a4fbf",
6467
6467
  "runId": "profile-improvement-1",
6468
6468
  "schema": "agent-profile-improvement-experiment"
6469
6469
  }
@@ -1,6 +1,7 @@
1
1
  import { l as RuntimeHooks } from "./runtime-hooks-Bj6wJHlH.js";
2
2
  import { AgentProfile, InputPart, RequestedInteractions, StreamEvent } from "@tangle-network/agent-interface";
3
3
  import { ControlBudget, ControlDecision, ControlEvalResult, ControlRunResult, ControlStep, DataAcquisitionPlan, DefaultVerdict, KnowledgeReadinessReport, KnowledgeRequirement, RunRecord, TraceStore, UserQuestion } from "@tangle-network/agent-eval";
4
+ import { AgentRunOutcome } from "@tangle-network/sandbox/runtime";
4
5
  import { CreateRequestOptions, CreateSandboxOptions, SandboxEvent, SandboxInstance } from "@tangle-network/sandbox";
5
6
  //#region src/types.d.ts
6
7
  /** @stable */
@@ -812,6 +813,8 @@ interface Iteration<Task, Output> {
812
813
  output?: Output;
813
814
  verdict?: DefaultVerdict;
814
815
  error?: Error;
816
+ /** Public Sandbox outcome settled after the complete event stream. */
817
+ sandboxOutcome?: AgentRunOutcome;
815
818
  /** Raw sandbox event stream collected for this iteration. Present on a failed iteration too,
816
819
  * holding the events received before the failure — including the one that reported it. */
817
820
  events: SandboxEvent[];
@@ -1228,4 +1231,4 @@ interface ExecCtx {
1228
1231
  }
1229
1232
  //#endregion
1230
1233
  export { OpenAIChatToolChoice as $, RuntimeRunCompleteInput as A, AgentBackendInput as B, MountRecorder as C, SelectionReceipt as D, SandboxClient as E, RuntimeRunRow as F, AgentTaskContext as G, AgentKnowledgeProvider as H, RuntimeRunStatus as I, AgentTaskStatus as J, AgentTaskRunResult as K, startRuntimeRun as L, RuntimeRunHandle as M, RuntimeRunOptions as N, ValidationCtx as O, RuntimeRunPersistenceAdapter as P, OpenAIChatTool as Q, AgentAdapter as R, MountManifestEntry as S, RunProvenance as T, AgentRuntimeEvent as U, AgentExecutionBackend as V, AgentRuntimeEventSink as W, KnowledgeReadinessDecision as X, BackendErrorDetail as Y, OpenAIChatResponseFormat as Z, LoopTeardownFailedPayload as _, Iteration as a, RuntimeStreamEvent as at, LoopTraceEvent as b, LoopIterationDispatchPayload as c, LoopLineageOptions as d, RunAgentTaskOptions as et, LoopPlanDescription as f, LoopStartedPayload as g, LoopSandboxPlacement as h, ExecCtx as i, RuntimeSessionStore as it, RuntimeRunCost as j, Validator as k, LoopIterationEndedPayload as l, LoopResult as m, DefaultVerdict as n, RuntimeCanonicalStreamEvent as nt, LoopDecisionPayload as o, LoopPlanPayload as p, AgentTaskSpec as q, Driver as r, RuntimeSession as rt, LoopEndedPayload as s, AgentRunSpec as t, RunAgentTaskStreamOptions as tt, LoopIterationStartedPayload as u, LoopTokenUsage as v, OutputAdapter as w, LoopWinner as x, LoopTraceEmitter as y, AgentBackendContext as z };
1231
- //# sourceMappingURL=types-DZrBoBpN.d.ts.map
1234
+ //# sourceMappingURL=types-DeX8ibLc.d.ts.map
@@ -1,4 +1,4 @@
1
- import { J as AgentTaskStatus, U as AgentRuntimeEvent, at as RuntimeStreamEvent, v as LoopTokenUsage, y as LoopTraceEmitter } from "./types-DZrBoBpN.js";
1
+ import { J as AgentTaskStatus, U as AgentRuntimeEvent, at as RuntimeStreamEvent, v as LoopTokenUsage, y as LoopTraceEmitter } from "./types-DeX8ibLc.js";
2
2
  import { l as RuntimeHooks } from "./runtime-hooks-Bj6wJHlH.js";
3
3
  import { AgentProfile, Sha256Digest } from "@tangle-network/agent-interface";
4
4
  import { ControlEvalResult, DefaultVerdict, KnowledgeReadinessReport, KnowledgeRequirement, ToolSpan } from "@tangle-network/agent-eval";
@@ -1933,4 +1933,4 @@ interface WidenGate<Out> {
1933
1933
  }
1934
1934
  //#endregion
1935
1935
  export { WaitOpts as $, WaitSpec as $t, ResumedWork as A, exportEvalRuns as At, SpawnOpts as B, RuntimeTelemetryOptions as Bt, NodeStatus as C, OtelSpan as Ct, Restart as D, buildRuntimeEventOtelSpans as Dt, ProviderModelExecutionEvidence as E, buildLoopSpanNodes as Et, Runtime as F, toOtelAttributes as Ft, SpendGap as G, sanitizeAgentRuntimeEvent as Gt, SpawnRejection as H, SanitizedKnowledgeRequirement as Ht, Scope as I, RuntimeEventCollector as It, Supervisor as J, PendingWait as Jt, SteerableRootHandle as K, sanitizeKnowledgeReadinessReport as Kt, Settled as L, RuntimeStreamEventCollector as Lt, RootMaterialization as M, loopEventToOtelSpan as Mt, RootProviderModelEvidence as N, padSpanId as Nt, ResultBlobStore as O, createOpenInferenceFileExporter as Ot, RootSignal as P, padTraceId as Pt, UsageEvent as Q, WaitRejection as Qt, SpawnEvent as R, RuntimeStreamEventSink as Rt, NodeSnapshot as S, OtelExporter as St, ProviderModelAttemptEvidence as T, buildLoopOtelSpans as Tt, Spend as U, createRuntimeEventCollector as Ut, SpawnPrior as V, SanitizedKnowledgeReadinessReport as Vt, SpendChannel as W, createRuntimeStreamEventCollector as Wt, TreeView as X, WaitProbe as Xt, SupervisorOpts as Y, WaitOutcome as Yt, UnknownMaterializationReason as Z, WaitProbeRegistry as Zt, MaterializedExecutionIdentity as _, ScopeProgressInput as _n, EvalRunsExportResult as _t, DefaultVerdict as a, waitUntil as an, readWorkerTraceContext as at, NodeExecutionIdentity as b, readWorkerProgress as bn, OtelAttribute as bt, ExecutorAccounting as c, ToolStepInput as cn, workerTraceSeamKey as ct, ExecutorFactory as d, decodeToolPart as dn, mergeTraceEnv as dt, createWaitProbes as en, WidenGate as et, ExecutorMaterialization as f, sandboxSessionTraceSource as fn, readTraceContextFromEnv as ft, Handle as g, ExecutorProgress as gn, EvalRunsExportConfig as gt, ExecutorResult as h, DEFAULT_STALL_AFTER_MS as hn, EvalRunGeneration as ht, Budget as i, validateWaitSpec as in, WorkerTraceSeamCarrier as it, RootHandle as j, generateSpanId as jt, ResumedKeyState as k, createOtelExporter as kt, ExecutorContext as l, TraceSource as ln, TraceContext as lt, ExecutorRegistry as m, ActivityNote as mn, EvalRunEvent as mt, AgentExecutionRef as n, pollFor as nn, WorkerTraceUnavailableReason as nt, ExecutionBindingReceipt as o, SessionMessageLike as on, workerTraceEnv as ot, ExecutorNodeContext as p, ActivityLog as pn, traceContextToEnv as pt, SupervisedResult as q, sanitizeRuntimeStreamEvent as qt, AgentSpec as r, timerAt as rn, WorkerTraceResolver as rt, Executor as s, SessionTraceBox as sn, workerTraceHeaders as st, Agent as t, isWaitOutcome as tn, WorkerTraceEvidence as tt, ExecutorExecutionBinding as u, createPushTraceSource as un, createPropagatingTraceEmitter as ut, MaterializedModelIdentity as v, WorkerProgress as vn, INTELLIGENCE_WIRE_VERSION as vt, ProfileMaterializationReceipt as w, RuntimeEventOtelOptions as wt, NodeId as x, OtelExportConfig as xt, NoWinnerError as y, createActivityLog as yn, LoopSpanNode as yt, SpawnJournal as z, RuntimeStreamEventSummary as zt };
1936
- //# sourceMappingURL=types-_7w24mMg.d.ts.map
1936
+ //# sourceMappingURL=types-Df9vulGc.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "0.142.3",
3
+ "version": "0.143.0",
4
4
  "description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
5
5
  "homepage": "https://github.com/tangle-network/agent-runtime#readme",
6
6
  "repository": {
@@ -119,8 +119,8 @@
119
119
  "@modelcontextprotocol/sdk": "1.30.0",
120
120
  "@biomejs/biome": "^2.5.5",
121
121
  "@tangle-network/agent-eval": ">=0.149.0 <0.150.0",
122
- "@tangle-network/agent-interface": "^1.1.0",
123
- "@tangle-network/sandbox": ">=0.29.0 <0.31.0",
122
+ "@tangle-network/agent-interface": "^1.3.0",
123
+ "@tangle-network/sandbox": ">=0.31.0 <0.32.0",
124
124
  "@types/node": "26.1.1",
125
125
  "@types/tar-stream": "3.1.4",
126
126
  "miniflare": "4.20260722.0",
@@ -141,8 +141,8 @@
141
141
  "license": "MIT",
142
142
  "peerDependencies": {
143
143
  "@tangle-network/agent-eval": ">=0.149.0 <0.150.0",
144
- "@tangle-network/agent-interface": "^1.1.0",
145
- "@tangle-network/sandbox": ">=0.29.0 <0.31.0"
144
+ "@tangle-network/agent-interface": "^1.3.0",
145
+ "@tangle-network/sandbox": ">=0.31.0 <0.32.0"
146
146
  },
147
147
  "peerDependenciesMeta": {
148
148
  "@tangle-network/sandbox": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"materialization-CrdcfWXp.js","names":[],"sources":["../src/runtime/supervise/executable-spec.ts","../src/runtime/supervise/materialization.ts"],"sourcesContent":["import { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { assertExecutableAgentProfile } from './model-policy'\nimport { detachedSnapshot } from './snapshot'\nimport type { AgentSpec } from './types'\n\n/**\n * Parse one untrusted profile into the exact immutable value execution may consume.\n *\n * Snapshotting before schema parsing reads caller-owned fields once. Snapshotting the parsed\n * result prevents downstream custom code from changing any identity or authority field.\n */\nexport function executableAgentProfileSnapshot(raw: unknown, context: string): AgentProfile {\n const input = detachedSnapshot(raw, `${context}: AgentProfile input`)\n const profile = agentProfileSchema.parse(input)\n assertExecutableAgentProfile(profile, context)\n return detachedSnapshot(profile, `${context}: parsed AgentProfile`)\n}\n\n/** Snapshot an executable spec while retaining trusted callbacks by reference. */\nexport function executableAgentSpecSnapshot(raw: AgentSpec, context: string): AgentSpec {\n const {\n profile: rawProfile,\n harness,\n execution: rawExecution,\n ...runtimeExtensions\n } = raw as AgentSpec & Readonly<Record<string, unknown>>\n const profile = executableAgentProfileSnapshot(rawProfile, context)\n const execution =\n rawExecution === undefined\n ? undefined\n : detachedSnapshot(rawExecution, `${context}: execution attribution`)\n return Object.freeze({\n ...runtimeExtensions,\n profile,\n harness,\n ...(execution === undefined ? {} : { execution }),\n }) as AgentSpec\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n ExecutionBindingReceipt,\n Executor,\n ExecutorExecutionBinding,\n ExecutorMaterialization,\n ProfileMaterializationReceipt,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n Runtime,\n UnknownMaterializationReason,\n} from './types'\n\ntype RuntimeOwnedExecutorMaterialization =\n | {\n readonly kind: 'known'\n readonly declaration: ExecutorMaterialization\n readonly binding?: ExecutorExecutionBinding\n }\n | {\n /** A Runtime-owned external executor whose exact launch is known, but whose remote\n * materializer has not yet returned its terminal acknowledgement. This private state lets\n * Runtime validate the planned authority before execution without presenting it as proof\n * that the remote process actually used that plan. */\n readonly kind: 'pending'\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | { readonly kind: 'deferred'; readonly runtime: Runtime }\n\ninterface RuntimeOwnedExecutorMaterializationRef {\n current: RuntimeOwnedExecutorMaterialization\n}\n\nconst runtimeOwnedExecutorMaterializations = new WeakMap<\n object,\n RuntimeOwnedExecutorMaterializationRef\n>()\nconst runtimeOwnedScopeOwners = new WeakMap<object, Runtime>()\nconst runtimeOwnedExecutorProviderEvidenceState = new WeakMap<\n object,\n {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n }\n>()\nconst runtimeOwnedDriveHarnessProviderEvidenceState = new WeakMap<\n object,\n ProviderModelExecutionEvidence\n>()\n\ninterface KnownReceiptInput {\n readonly authoredProfileDigest: Sha256Digest\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n}\n\ninterface UnknownReceiptInput {\n readonly authoredProfileDigest?: Sha256Digest\n readonly runtime: Runtime\n readonly reason: UnknownMaterializationReason\n}\n\nconst declarationKeys = new Set([\n 'effectiveProfile',\n 'backend',\n 'model',\n 'execution',\n 'materializer',\n 'plan',\n 'platformAttachments',\n])\n\n/**\n * Bind a declaration to a runtime-owned executor without putting an attestable method on the\n * public Executor interface. This module is not a package export: arbitrary caller executors stay\n * unknown even if they add a lookalike `materialization()` property.\n */\nexport function attestRuntimeOwnedExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding?: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n ...(binding === undefined\n ? {}\n : {\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n }),\n }),\n })\n ensureProviderEvidenceState(executor)\n return executor\n}\n\n/** Brand an external Runtime executor whose exact remote materialization is provable only after\n * its terminal protocol acknowledgement. The declaration is a planned authority check, never a\n * known receipt; callers must finalize this same object after validating the acknowledgement. */\nexport function attestRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'pending',\n runtime,\n declaration: detachedSnapshot(declaration, 'pending executor materialization'),\n binding: detachedSnapshot(binding, 'pending executor execution binding'),\n }),\n })\n return executor\n}\n\n/** Replace a private pending brand with terminally acknowledged evidence. A caller-owned executor\n * cannot enter this path because only this module can create the pending WeakMap entry. */\nexport function finalizeRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(executor as object)\n if (ref?.current.kind !== 'pending' || ref.current.runtime !== executor.runtime) {\n throw new ValidationError(\n 'executor materialization: terminal acknowledgement has no matching Runtime-owned pending executor',\n )\n }\n ref.current = Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n })\n return executor\n}\n\n/** Mark a runtime-owned orchestration executor whose exact leaf declaration is published through\n * its private nested Scope before the first backend inference. Arbitrary executors cannot opt in. */\nexport function attestRuntimeOwnedDeferredExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({ kind: 'deferred', runtime }),\n })\n return executor\n}\n\n/** Preserve the runtime-owned attestation when a trusted wrapper changes result semantics only. */\nexport function inheritRuntimeOwnedExecutorAttestation<In, Out>(\n source: Executor<In>,\n wrapper: Executor<Out>,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(source as object)\n if (ref !== undefined) {\n runtimeOwnedExecutorMaterializations.set(wrapper as object, ref)\n }\n const providerState = ensureProviderEvidenceState(source)\n runtimeOwnedExecutorProviderEvidenceState.set(wrapper as object, providerState)\n return wrapper\n}\n\nfunction ensureProviderEvidenceState<Out>(executor: Executor<Out>): {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n} {\n const existing = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (existing !== undefined) return existing\n const state = { attempts: [] }\n runtimeOwnedExecutorProviderEvidenceState.set(executor as object, state)\n return state\n}\n\n/** Read a declaration only when Runtime itself branded this exact executor object. */\nexport function runtimeOwnedExecutorMaterialization<Out>(\n executor: Executor<Out>,\n): ExecutorMaterialization | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.declaration : undefined\n}\n\n/** Read one attempt binding only from the private brand on this exact executor object. */\nexport function runtimeOwnedExecutorExecutionBinding<Out>(\n executor: Executor<Out>,\n): ExecutorExecutionBinding | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.binding : undefined\n}\n\n/** Read a planned external declaration only for Runtime's private pending brand. This is useful for\n * pre-execution authority checks, but must never be turned into a known durable receipt. */\nexport function runtimeOwnedPendingExecutorMaterialization<Out>(executor: Executor<Out>):\n | {\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'pending'\n ? {\n runtime: attestation.runtime,\n declaration: attestation.declaration,\n binding: attestation.binding,\n }\n : undefined\n}\n\n/** Read the expected leaf runtime only for a privately branded deferred orchestration executor. */\nexport function runtimeOwnedDeferredExecutorRuntime<Out>(\n executor: Executor<Out>,\n): Runtime | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'deferred' ? attestation.runtime : undefined\n}\n\n/** Propagate trust from a built-in driver adapter to the Agent and recursive executor it owns. */\nexport function attestRuntimeOwnedScopeOwner<T extends object>(owner: T, runtime: Runtime): T {\n runtimeOwnedScopeOwners.set(owner, runtime)\n return owner\n}\n\n/** Return a built-in scope owner's expected concrete leaf runtime; caller-owned functions/Agents\n * deliberately have no entry even if they add lookalike fields. */\nexport function runtimeOwnedScopeOwnerRuntime(owner: object): Runtime | undefined {\n return runtimeOwnedScopeOwners.get(owner)\n}\n\n/** Mark one provider inference attempt on a Runtime-owned executor. */\nexport function recordRuntimeOwnedProviderAttemptStart<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n state.attempts.push({ observations: [] })\n}\n\n/** Mark the current attempt as rejected before provider dispatch.\n *\n * The caller may use this only after consuming the Router-owned\n * `provider_dispatch: \"not_started\"` fact. Any other error stays an empty,\n * unknown attempt and must not be upgraded here.\n */\nexport function recordRuntimeOwnedProviderDispatchNotStarted<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider dispatch rejection arrived before an attempt started')\n }\n if (attempt.observations.length > 0 || attempt.identityConflict === true) {\n throw new ValidationError(\n 'provider dispatch rejection arrived after provider identity evidence was observed',\n )\n }\n attempt.providerDispatch = 'not_started'\n}\n\n/** Record a trusted served model on the current provider attempt. */\nexport function recordRuntimeOwnedProviderModel<Out>(executor: Executor<Out>, model: string): void {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n const attempt = state?.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider model observation arrived before an attempt started')\n }\n if (attempt.observations.at(-1) !== model) attempt.observations.push(model)\n}\n\n/** Convert process-local provider observations into a frozen, replayable evidence value. */\nexport function runtimeOwnedExecutorProviderEvidence<Out>(\n executor: Executor<Out>,\n): ProviderModelExecutionEvidence | undefined {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (state === undefined || state.attempts.length === 0) return undefined\n const attempts: ReadonlyArray<ProviderModelAttemptEvidence> = Object.freeze(\n state.attempts.map((attempt) =>\n Object.freeze({\n observations: Object.freeze([...attempt.observations]),\n ...(attempt.identityConflict ? { identityConflict: true } : {}),\n ...(attempt.providerDispatch === 'not_started'\n ? { providerDispatch: 'not_started' as const }\n : {}),\n }),\n ),\n )\n const models = Object.freeze([...new Set(attempts.flatMap((attempt) => attempt.observations))])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n return Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n )\n}\n\n/** Mark the current provider attempt unusable after conflicting served identity metadata. */\nexport function recordRuntimeOwnedProviderIdentityConflict<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider identity conflict arrived before an attempt started')\n }\n attempt.identityConflict = true\n}\n\n/** Attach one executor's provider evidence to a Runtime-owned root drive for final projection. */\nexport function recordRuntimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n evidence: ProviderModelExecutionEvidence | undefined,\n): void {\n if (evidence === undefined) return\n const prior = runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n if (prior === undefined) {\n runtimeOwnedDriveHarnessProviderEvidenceState.set(owner, evidence)\n return\n }\n const attempts = Object.freeze([...prior.attempts, ...evidence.attempts])\n const models = Object.freeze([...new Set([...prior.models, ...evidence.models])])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n runtimeOwnedDriveHarnessProviderEvidenceState.set(\n owner,\n Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n ),\n )\n}\n\n/** Read provider evidence recorded by a Runtime-owned root drive. */\nexport function runtimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n): ProviderModelExecutionEvidence | undefined {\n return runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n}\n\n/** Build one kernel-owned known receipt from a data-only executor declaration. */\nexport function knownMaterializationReceipt(\n input: KnownReceiptInput,\n): ProfileMaterializationReceipt {\n const declaration = detachedSnapshot(input.declaration, 'executor materialization')\n assertExactDeclaration(declaration)\n const effectiveProfile = agentProfileSchema.safeParse(declaration.effectiveProfile)\n if (!effectiveProfile.success) {\n throw new ValidationError('executor materialization: effectiveProfile must be an AgentProfile')\n }\n assertNonEmpty(declaration.backend, 'backend')\n assertNonEmpty(declaration.materializer, 'materializer')\n assertNonEmpty(declaration.execution?.kind, 'execution.kind')\n assertNonEmpty(declaration.execution?.id, 'execution.id')\n assertModel(declaration.model)\n\n let effectiveProfileDigest: Sha256Digest\n let materializationPlanDigest: Sha256Digest\n let platformAttachmentsDigest: Sha256Digest | undefined\n try {\n effectiveProfileDigest = canonicalAgentProfileDigest(effectiveProfile.data)\n materializationPlanDigest = canonicalCandidateDigest(jsonWireSnapshot(declaration.plan))\n platformAttachmentsDigest =\n declaration.platformAttachments === undefined\n ? undefined\n : canonicalCandidateDigest(jsonWireSnapshot(declaration.platformAttachments))\n } catch (error) {\n throw new ValidationError(\n 'executor materialization: profile, plan, and attachments must be finite RFC 8785 JSON',\n { cause: error },\n )\n }\n\n return Object.freeze({\n status: 'known' as const,\n authoredProfileDigest: input.authoredProfileDigest,\n effectiveProfileDigest,\n materializationPlanDigest,\n ...(platformAttachmentsDigest === undefined ? {} : { platformAttachmentsDigest }),\n runtime: input.runtime,\n backend: declaration.backend,\n model: declaration.model,\n execution: declaration.execution,\n materializer: declaration.materializer,\n })\n}\n\n/** Build an explicit unknown receipt without fabricating any executor-owned identity. */\nexport function unknownMaterializationReceipt(\n input: UnknownReceiptInput,\n): ProfileMaterializationReceipt {\n return Object.freeze({\n status: 'unknown' as const,\n ...(input.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: input.authoredProfileDigest }),\n runtime: input.runtime,\n reason: input.reason,\n })\n}\n\n/** Mint a process-unique attempt id before executor construction. */\nexport function newExecutionAttemptId(nodeId: string): string {\n return `${nodeId}:attempt:${randomUUID()}`\n}\n\n/** Build the immutable safe receipt for a full, transient execution binding. */\nexport function knownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n bindingInput: ExecutorExecutionBinding,\n): ExecutionBindingReceipt {\n const binding = detachedSnapshot(bindingInput, 'executor execution binding')\n assertNonEmpty(binding.attemptId, 'binding.attemptId')\n assertSafeDescriptor(binding.descriptor)\n let materializationReceiptDigest: Sha256Digest\n let bindingDigest: Sha256Digest\n try {\n materializationReceiptDigest = canonicalCandidateDigest(materialization)\n // Bind the exact JSON document a backend receives. Optional AgentProfile fields are represented\n // as `undefined` in memory but omitted by JSON transport; normalize that one distinction while\n // rejecting every non-finite/non-data value instead of silently coercing it.\n bindingDigest = canonicalCandidateDigest(jsonWireSnapshot(binding.binding))\n } catch (error) {\n throw new ValidationError('executor binding must be finite RFC 8785 JSON', { cause: error })\n }\n return Object.freeze({\n status: 'known' as const,\n attemptId: binding.attemptId,\n materializationReceiptDigest,\n bindingDigest,\n descriptor: binding.descriptor,\n })\n}\n\n/** Preserve an attempt boundary even when its caller-owned transport cannot be attested. */\nexport function unknownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n reason: UnknownMaterializationReason,\n): ExecutionBindingReceipt {\n assertNonEmpty(attemptId, 'binding.attemptId')\n return Object.freeze({\n status: 'unknown' as const,\n attemptId,\n materializationReceiptDigest: canonicalCandidateDigest(materialization),\n reason,\n })\n}\n\n/** Derive an authored-profile digest without turning non-canonical input into a fake identity. */\nexport function authoredProfileDigest(profile: unknown): Sha256Digest | undefined {\n try {\n return canonicalAgentProfileDigest(agentProfileSchema.parse(profile))\n } catch {\n return undefined\n }\n}\n\nfunction assertExactDeclaration(value: ExecutorMaterialization): void {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError('executor materialization: declaration must be an object')\n }\n const unknown = Object.keys(value).filter((key) => !declarationKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(\n `executor materialization: unknown declaration fields: ${unknown.sort().join(', ')}`,\n )\n }\n if (!Object.hasOwn(value, 'plan')) {\n throw new ValidationError('executor materialization: plan is required')\n }\n}\n\nfunction assertModel(model: ExecutorMaterialization['model']): void {\n if (typeof model !== 'object' || model === null || Array.isArray(model)) {\n throw new ValidationError('executor materialization: model must be a known/unknown identity')\n }\n const keys = Object.keys(model).sort()\n if (model.status === 'known') {\n if (keys.join(',') !== 'id,status') {\n throw new ValidationError('executor materialization: known model accepts only status and id')\n }\n assertNonEmpty(model.id, 'model.id')\n return\n }\n if (model.status === 'unknown') {\n if (keys.join(',') !== 'reason,status') {\n throw new ValidationError(\n 'executor materialization: unknown model accepts only status and reason',\n )\n }\n assertNonEmpty(model.reason, 'model.reason')\n return\n }\n throw new ValidationError('executor materialization: model.status must be known or unknown')\n}\n\nfunction assertNonEmpty(value: unknown, field: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`executor materialization: ${field} must be a non-empty string`)\n }\n}\n\nfunction assertSafeDescriptor(descriptor: ExecutorExecutionBinding['descriptor']): void {\n if (typeof descriptor !== 'object' || descriptor === null || Array.isArray(descriptor)) {\n throw new ValidationError('executor binding: descriptor must be an object')\n }\n for (const [key, value] of Object.entries(descriptor)) {\n if (/(url|uri|token|key|secret|bearer|credential|authorization)/i.test(key)) {\n throw new ValidationError(`executor binding: unsafe descriptor key ${JSON.stringify(key)}`)\n }\n if (\n value !== null &&\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} must be scalar`,\n )\n }\n if (typeof value === 'string' && (value.includes('://') || value.includes('@'))) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} contains transport or credential text`,\n )\n }\n }\n}\n\nfunction jsonWireSnapshot(value: unknown, path = '$'): unknown {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new ValidationError(`executor binding: ${path} must be finite`)\n }\n return value\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => {\n if (item === undefined) {\n throw new ValidationError(`executor binding: ${path}[${index}] cannot be undefined`)\n }\n return jsonWireSnapshot(item, `${path}[${index}]`)\n })\n }\n if (typeof value !== 'object' || value === null) {\n throw new ValidationError(`executor binding: ${path} must be JSON data`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new ValidationError(`executor binding: ${path} must be a plain object`)\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (item === undefined) continue\n out[key] = jsonWireSnapshot(item, `${path}.${key}`)\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,+BAA+B,KAAc,SAA+B;CAC1F,MAAM,QAAQ,iBAAiB,KAAK,GAAG,QAAQ,qBAAqB;CACpE,MAAM,UAAU,mBAAmB,MAAM,KAAK;CAC9C,6BAA6B,SAAS,OAAO;CAC7C,OAAO,iBAAiB,SAAS,GAAG,QAAQ,sBAAsB;AACpE;;AAGA,SAAgB,4BAA4B,KAAgB,SAA4B;CACtF,MAAM,EACJ,SAAS,YACT,SACA,WAAW,cACX,GAAG,sBACD;CACJ,MAAM,UAAU,+BAA+B,YAAY,OAAO;CAClE,MAAM,YACJ,iBAAiB,KAAA,IACb,KAAA,IACA,iBAAiB,cAAc,GAAG,QAAQ,wBAAwB;CACxE,OAAO,OAAO,OAAO;EACnB,GAAG;EACH;EACA;EACA,GAAI,cAAc,KAAA,IAAY,C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AAO,MAAM,KAAK,MAAM,UAAU;EAChC,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,gBAAgB,qBAAqB,KAAK,GAAG,MAAM,sBAAsB;EAErF,OAAO,iBAAiB,MAAM,GAAG,KAAK,GAAG,MAAM,EAAE;CACnD,CAAC;CAEH,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,MAAM,IAAI,gBAAgB,qBAAqB,KAAK,mBAAmB;CAEzE,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,IAAI,cAAc,OAAO,aAAa,cAAc,MAClD,MAAM,IAAI,gBAAgB,qBAAqB,KAAK,wBAAwB;CAE9E,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,KAAgC,GAAG;EAC1E,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI,OAAO,iBAAiB,MAAM,GAAG,KAAK,GAAG,KAAK;CACpD;CACA,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sandbox-events-BK-g19wx.js","names":[],"sources":["../src/runtime/timestamps.ts","../src/runtime/sandbox-transport-events.ts","../src/runtime/sandbox-events.ts"],"sourcesContent":["import { RuntimeEventEnvelopeSchema } from '@tangle-network/agent-interface'\n\nconst validTimestamp = '2026-01-01T00:00:00.000Z'\n\n/** Validate a timestamp with the public runtime envelope contract. */\nexport function assertRuntimeTimestamp(value: unknown, label: string): asserts value is string {\n try {\n RuntimeEventEnvelopeSchema.parse({\n runId: 'runtime',\n eventId: 'event',\n sequence: 0,\n occurredAt: value,\n receivedAt: validTimestamp,\n event: { type: 'status', status: 'processing' },\n })\n } catch (error) {\n throw new Error(`${label} must be a valid ISO timestamp`, { cause: error })\n }\n}\n\n/** Return whether a value satisfies the public runtime timestamp contract. */\nexport function isRuntimeTimestamp(value: unknown): value is string {\n try {\n assertRuntimeTimestamp(value, 'occurredAt')\n return true\n } catch {\n return false\n }\n}\n","import { CanonicalStreamEventSchema, type StreamEvent } from '@tangle-network/agent-interface'\nimport { assertRuntimeTimestamp } from './timestamps'\n\n/** Parse canonical payload fields without treating transport identity as event data. */\nexport function parseCanonicalTransportEvent(\n type: unknown,\n data: Record<string, unknown>,\n normalized: unknown,\n source: string,\n): StreamEvent | undefined {\n if (!isRecord(data)) {\n throw new Error(`${source} emitted a canonical event without an object payload`)\n }\n const outerType = String(type ?? '')\n if (normalized !== undefined) {\n if (\n typeof normalized === 'object' &&\n normalized !== null &&\n 'type' in normalized &&\n typeof normalized.type === 'string' &&\n normalized.type !== outerType\n ) {\n throw new Error(\n `${source} canonical event type \"${normalized.type}\" does not match transport type \"${outerType}\"`,\n )\n }\n const candidate = CanonicalStreamEventSchema.safeParse(normalized)\n if (!candidate.success) {\n throw new Error(`${source} emitted an invalid normalized canonical event`, {\n cause: candidate.error,\n })\n }\n return candidate.data\n }\n const {\n type: embeddedType,\n eventId: _eventId,\n cursor: _cursor,\n sequence: _sequence,\n occurredAt: _occurredAt,\n normalized: _normalized,\n ...payload\n } = data\n if (embeddedType !== undefined && embeddedType !== outerType) {\n throw new Error(\n `${source} canonical event type \"${String(embeddedType)}\" does not match transport type \"${outerType}\"`,\n )\n }\n const candidate = CanonicalStreamEventSchema.safeParse({ ...payload, type: outerType })\n return candidate.success ? candidate.data : undefined\n}\n\n/** Identity fields carried by either the transport envelope or its data payload. */\nexport interface TransportEventIdentity {\n readonly eventId?: string\n readonly cursor?: string\n readonly sequence?: number\n readonly occurredAt?: string\n}\n\n/** Extract shared event identity without privileging one provider wire shape. */\nexport function extractTransportEventIdentity(event: unknown): TransportEventIdentity {\n const record = isRecord(event) ? event : {}\n const data = isRecord(record.data) ? record.data : {}\n const providerEvent = isRecord(record.providerEvent) ? record.providerEvent : {}\n const providerData = isRecord(providerEvent.data) ? providerEvent.data : {}\n const eventId = canonicalEventId(record, data, providerEvent, providerData)\n const cursor = stableString(\n record.cursor ?? data.cursor ?? providerEvent.cursor ?? providerData.cursor,\n )\n const sequence = optionalSequence(\n record.sequence ?? data.sequence ?? providerEvent.sequence ?? providerData.sequence,\n )\n const occurredAt = optionalTimestamp(\n record.occurredAt ?? data.occurredAt ?? providerEvent.occurredAt ?? providerData.occurredAt,\n )\n return {\n ...(eventId === undefined ? {} : { eventId }),\n ...(cursor === undefined ? {} : { cursor }),\n ...(sequence === undefined ? {} : { sequence }),\n ...(occurredAt === undefined ? {} : { occurredAt }),\n }\n}\n\nfunction canonicalEventId(\n record: Record<string, unknown>,\n data: Record<string, unknown>,\n providerEvent: Record<string, unknown>,\n providerData: Record<string, unknown>,\n): string | undefined {\n const candidates = [\n ['data.eventId', data.eventId],\n ['providerEvent.eventId', providerEvent.eventId],\n ['providerData.eventId', providerData.eventId],\n ['record.eventId', record.eventId],\n ] as const\n const present = candidates.filter(([, value]) => value !== undefined)\n // `record.id` may be the provider's replay cursor, so use it only without a canonical field.\n if (present.length === 0) return stableString(record.id ?? providerEvent.id)\n\n const normalized = present.map(([source, value]) => {\n const eventId = stableString(value)\n if (eventId === undefined) throw new Error(`transport event ${source} must be a stable string`)\n return { source, eventId }\n })\n const first = normalized[0]!\n if (normalized.some((candidate) => candidate.eventId !== first.eventId)) {\n throw new Error('transport event canonical identities disagree')\n }\n return first.eventId\n}\n\nfunction stableString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 && value.trim() === value ? value : undefined\n}\n\nfunction finiteNonNegativeInteger(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nfunction optionalSequence(value: unknown): number | undefined {\n if (value === undefined) return undefined\n if (finiteNonNegativeInteger(value) === undefined) {\n throw new Error('transport event sequence must be a non-negative safe integer')\n }\n return value as number\n}\n\nfunction optionalTimestamp(value: unknown): string | undefined {\n if (value === undefined) return undefined\n assertRuntimeTimestamp(value, 'occurredAt')\n return value\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * Sandbox-event → runtime-event mapping.\n *\n * The sandbox SDK emits a polymorphic `SandboxEvent = { type, data, id? }`\n * whose `type` vocabulary is backend-determined (opencode, etc.) rather than\n * enumerated by the SDK. Two consumers project it:\n * - the loop kernel's cost ledger (`extractLlmCallEvent`) — sums usage off\n * every cost-bearing event, regardless of stream shape;\n * - the `AgentRuntime.act` streaming contract (`mapSandboxEvent`) — projects\n * incremental events to the `RuntimeStreamEvent` chat-UX vocabulary.\n *\n * Both live here so the empirically-observed `type` vocabulary has one home.\n */\n\nimport type { StreamEvent } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { RuntimeStreamEvent } from '../types'\nimport { parseCanonicalTransportEvent } from './sandbox-transport-events'\n\nconst CANONICAL_STREAM_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'message.part.updated',\n 'tool-heartbeat',\n 'tool-slow',\n 'model-processing',\n 'status',\n 'warning',\n 'raw',\n 'session.updated',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n])\n\n/** Decode one known Agent Interface event from a Sandbox event. */\nexport function canonicalStreamEventFromSandboxEvent(event: SandboxEvent): StreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n const normalized = data.normalized\n if (normalized === undefined && !CANONICAL_STREAM_EVENT_TYPES.has(type)) return undefined\n return parseCanonicalTransportEvent(type, data, normalized, 'sandbox')\n}\n\n/**\n * Forward a sandbox event to an optional observer without letting observer\n * behavior affect the run. The observer receives a defensive copy, synchronous\n * throws are swallowed, and returned promises are deliberately not awaited.\n */\nexport function notifySandboxEventObserver<Meta>(\n event: SandboxEvent,\n observer: ((event: SandboxEvent, meta: Meta) => void | PromiseLike<void>) | undefined,\n meta: Meta,\n): void {\n if (!observer) return\n try {\n const result = observer(cloneEventForObserver(event), meta)\n if (result && typeof result.then === 'function') {\n void result.then(undefined, () => {})\n }\n } catch {\n // Live observation is optional and must never interrupt the event stream.\n }\n}\n\nfunction cloneEventForObserver(event: SandboxEvent): SandboxEvent {\n try {\n return structuredClone(event)\n } catch {\n return copyPlainSpine(event, new WeakMap()) as SandboxEvent\n }\n}\n\nfunction copyPlainSpine(value: unknown, seen: WeakMap<object, unknown>): unknown {\n if (value === null || typeof value !== 'object') return value\n const existing = seen.get(value)\n if (existing !== undefined) return existing\n if (Array.isArray(value)) {\n const copy: unknown[] = []\n seen.set(value, copy)\n for (const item of value) copy.push(copyPlainSpine(item, seen))\n return copy\n }\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return {}\n const copy: Record<string, unknown> = {}\n seen.set(value, copy)\n for (const [key, child] of Object.entries(value)) {\n copy[key] = copyPlainSpine(child, seen)\n }\n return copy\n}\n\n/** Event types that settle one sandbox execution. A status or `success` flag is read as a\n * verdict on the whole execution only here; on any other event it describes that event. */\nconst TERMINAL_EVENT_TYPES: ReadonlySet<string> = new Set(['done', 'result', 'final'])\n\n/**\n * Return the terminal failure carried by one Sandbox event.\n *\n * Sandbox transports report execution failure in-band: commonly an `error`\n * event followed by a synthetic `done`. Treating the iterable as successfully\n * drained therefore turns a provider/configuration failure into a completed\n * empty artifact.\n *\n * The decoder reads a failure from exactly two places, so that a mid-stream\n * event describing its OWN failure cannot fail the execution: an `error`-typed\n * event, and a terminal event (`done`/`result`/`final`) whose `success` is\n * `false` or whose status is a failed one. A failing tool part therefore stays\n * a tool result, which is what {@link mapSandboxToolEvent} already projects it\n * to.\n */\nexport function sandboxEventFailure(event: SandboxEvent): string | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n const outcome = plainRecord(data.outcome)\n const status = firstString(\n data.status,\n outcome?.type,\n outcome?.status,\n plainRecord(data.result)?.status,\n )\n const terminal = TERMINAL_EVENT_TYPES.has(type)\n const terminalFailure =\n terminal && (data.success === false || (status !== undefined && TERMINAL_FAILURE.test(status)))\n if (type !== 'error' && !terminalFailure) return undefined\n\n return (\n describeSandboxError(data.error) ??\n describeSandboxError(outcome?.error) ??\n describeSandboxError(plainRecord(data.result)?.error) ??\n (typeof data.message === 'string' && data.message.length > 0 ? data.message : undefined) ??\n (status !== undefined\n ? `sandbox execution ended with status ${status}`\n : 'sandbox execution failed')\n )\n}\n\n/** Fail the live execution instead of allowing an in-band failure to become an empty success. */\nexport function assertSandboxEventSucceeded(event: SandboxEvent): void {\n const failure = sandboxEventFailure(event)\n if (failure !== undefined) throw new Error(`sandbox execution failed: ${failure}`)\n}\n\n/** The provider/model the platform reports it actually bound to a turn, when it reports one.\n * `source` is the platform's own account of where that choice came from — `environment` means\n * the platform chose, not the request. */\nexport interface SandboxServedBackend {\n readonly provider?: string\n readonly model?: string\n readonly source?: string\n}\n\n/**\n * Read the served execution identity off one Sandbox event.\n *\n * The platform reports `effectiveBackend` on `execution.started` and again on the terminal\n * event (`@tangle-network/sandbox`, `EffectiveBackend`). Absence returns `undefined`\n * and must stay unknown — a request is not a receipt, so nothing here may be inferred from\n * what was asked for.\n */\nexport function sandboxEventServedBackend(event: SandboxEvent): SandboxServedBackend | undefined {\n if (!event || typeof event !== 'object') return undefined\n const data = plainRecord(event.data)\n const served = plainRecord(data?.effectiveBackend)\n if (!served) return undefined\n const provider = firstString(served.provider)\n const model = firstString(served.model)\n const source = firstString(served.source)\n if (provider === undefined && model === undefined) return undefined\n return {\n ...(provider !== undefined ? { provider } : {}),\n ...(model !== undefined ? { model } : {}),\n ...(source !== undefined ? { source } : {}),\n }\n}\n\n/**\n * Fail the execution when the platform reports serving a model other than the exact one asked for.\n *\n * Measured motive (agent-runtime#892, live infrastructure 2026-08-17): 6 of 6 boxes whose profile\n * declared `zai-coding-plan/glm-5.2` reported\n * `{\"provider\":\"openai-compat\",\"model\":\"deepseek/deepseek-v4-flash\",\"source\":\"environment\"}`,\n * while the materialization receipt recorded the declared model as `status: \"known\"`. Sending\n * `backend.model` makes that substitution unlikely; only reading the report back makes it\n * detectable. A run that cannot say which model produced its evidence must not settle as one\n * that can.\n *\n * Silent when the platform reports no served model: unobserved stays unobserved.\n */\nexport function assertSandboxServedModel(\n event: SandboxEvent,\n expected: { readonly provider?: string; readonly model?: string } | undefined,\n): void {\n const wanted = expected?.model?.trim()\n if (!wanted) return\n const served = sandboxEventServedBackend(event)\n if (served?.model === undefined) return\n if (sameModelId(served.model, wanted, [served.provider, expected?.provider])) return\n const attribution = [\n served.provider !== undefined ? `provider ${JSON.stringify(served.provider)}` : undefined,\n served.source !== undefined ? `source ${JSON.stringify(served.source)}` : undefined,\n ].filter((part): part is string => part !== undefined)\n const detail = attribution.length > 0 ? ` (${attribution.join(', ')})` : ''\n throw new Error(\n `sandbox served model ${JSON.stringify(served.model)}${detail} instead of the exact profile model ${JSON.stringify(wanted)}`,\n )\n}\n\n/**\n * Do two model ids name the same model, allowing for routing prefixes?\n *\n * Either side may spell the model bare (`glm-5.2`), provider-qualified\n * (`zai-coding-plan/glm-5.2`), or route-qualified, and the platform reports the provider in its\n * own field rather than always in the id. So the comparison drops any known provider prefix and\n * then accepts a `/`-boundary suffix match: a longer route to the SAME leaf model is a routing\n * difference, not a substitution.\n *\n * What it deliberately does NOT absorb is a different leaf: `glm-5.2` against `glm-5.3` stays a\n * mismatch, which is the substitution measured directly against the provider API (a request for\n * `glm-5.2` was served `glm-5.3`). A version suffix is the whole difference between two\n * instruments, so nothing here may treat it as noise.\n */\nfunction sameModelId(\n served: string,\n wanted: string,\n providers: readonly (string | undefined)[],\n): boolean {\n const a = stripProviderPrefix(served, providers)\n const b = stripProviderPrefix(wanted, providers)\n return a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`)\n}\n\nfunction stripProviderPrefix(id: string, providers: readonly (string | undefined)[]): string {\n let out = id.trim().toLowerCase()\n for (const provider of providers) {\n const prefix = provider?.trim().toLowerCase()\n if (prefix && out.startsWith(`${prefix}/`)) out = out.slice(prefix.length + 1)\n }\n return out\n}\n\nfunction describeSandboxError(value: unknown): string | undefined {\n if (typeof value === 'string' && value.length > 0) return value\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const error = value as Record<string, unknown>\n return firstString(error.message, error.error, error.reason, error.code)\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n return values.find((value): value is string => typeof value === 'string' && value.length > 0)\n}\n\n/**\n * Extract a `RuntimeStreamEvent`-shaped `llm_call` from a sandbox event when\n * the event carries usage/cost data. Returns `undefined` for non-cost events\n * so the kernel can iterate the full stream without branching.\n *\n * Pure by contract: it never throws on a failed run. The terminal truth\n * boundary is {@link assertSandboxEventSucceeded}, applied by the two paths\n * that SETTLE an execution. Post-hoc readers — {@link sumSandboxUsage}, the\n * analyst trace store, the chat projection — must stay able to read a failed\n * turn's events, which is when reading them matters most.\n *\n * Canonical cost-carrying types observed in the wild:\n * - `llm_call` — `data: { model, tokensIn, tokensOut, costUsd, ... }`\n * - `message.completed` / `result` — `data: { usage: { inputTokens,\n * outputTokens, totalCostUsd? } }`\n * - `cost.usage` / `usage` — same shape under a dedicated type\n *\n * Numeric coercion is strict: `Number.isFinite` gates every accumulator write\n * so a sentinel `NaN` from a misbehaving backend cannot poison the ledger.\n */\nexport function extractLlmCallEvent(\n event: SandboxEvent,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'llm_call' || type === 'cost.usage' || type === 'usage') {\n return buildLlmCall(data, agentRunName)\n }\n if (type === 'message.completed' || type === 'result' || type === 'final') {\n const usage = data.usage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n return buildLlmCall({ ...usage, model: data.model ?? usage.model }, agentRunName)\n }\n // sandbox 0.4.0 terminal event: `data = { tokenUsage: { inputTokens, outputTokens,\n // reasoningTokens, cacheReadInputTokens }, totalCostUsd }`. Usage lives under\n // `tokenUsage` (not `usage`) and the cost is top-level — neither matched the\n // branches above, so an in-process loopDispatch run reported {0,0} and the\n // backend-integrity guard misread a real run as a stub. Reasoning tokens are\n // billed output (reasoning models), so they fold into the output count. The prompt-cache\n // counters are read off the SAME `tokenUsage` record rather than re-derived, because only\n // that record states what the provider billed.\n if (type === 'done') {\n const usage = data.tokenUsage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n const out = pickFiniteNumber(usage, ['outputTokens', 'completion_tokens', 'tokensOut'])\n const reasoning = pickFiniteNumber(usage, ['reasoningTokens'])\n const mergedOut =\n out !== undefined || reasoning !== undefined ? (out ?? 0) + (reasoning ?? 0) : undefined\n const cache = readPromptCacheUsage(usage)\n return buildLlmCall(\n {\n inputTokens: usage.inputTokens,\n outputTokens: mergedOut,\n totalCostUsd: data.totalCostUsd,\n model: data.model ?? usage.model,\n ...(cache !== undefined ? { promptCache: cache } : {}),\n },\n agentRunName,\n )\n }\n return undefined\n}\n\n/**\n * Sum the token usage + USD cost of a sandbox turn's events — the one honest way to meter an\n * `openSandboxRun` cell. Folds `extractLlmCallEvent` over the stream (which reads usage off EVERY backend\n * event shape), so a `runProfileMatrix` dispatch can report it to `ctx.cost`:\n *\n * receipt: (turn) => {\n * const u = sumSandboxUsage(turn.events)\n * return { model, inputTokens: u.input, outputTokens: u.output,\n * ...(u.tokensKnown === false ? { usageUnknown: true } : {}),\n * ...(u.usdKnown !== false && u.costUsd > 0 ? { actualCostUsd: u.costUsd } : {}),\n * ...(u.usdKnown === false ? { costUnknown: true } : {}),\n * ...(u.estimatedCostUsd !== undefined ? { estimatedCostUsd: u.estimatedCostUsd } : {}) }\n * }\n *\n * Without this a cell reads `{tokens:0, cost:0}` and the backend-integrity guard correctly aborts the\n * matrix as a stub. `agentRunName` is the fallback model label for cost-only events (default `'agent'`).\n */\nexport function sumSandboxUsage(\n events: readonly SandboxEvent[],\n agentRunName = 'agent',\n): {\n input: number\n output: number\n costUsd: number\n tokensKnown?: false\n usdKnown?: false\n estimatedCostUsd?: number\n} {\n let input = 0\n let output = 0\n let costUsd = 0\n let estimatedCostUsd = 0\n let sawEstimate = false\n let sawCall = false\n let tokensKnown = true\n let usdKnown = true\n for (const ev of events) {\n const call = extractLlmCallEvent(ev, agentRunName)\n if (!call) continue\n sawCall = true\n input += call.tokensIn ?? 0\n output += call.tokensOut ?? 0\n costUsd += call.costUsd ?? 0\n if (call.tokensKnown === false) tokensKnown = false\n if (call.usdKnown === false) usdKnown = false\n if (call.estimatedCostUsd !== undefined) {\n estimatedCostUsd += call.estimatedCostUsd\n sawEstimate = true\n }\n }\n return {\n input,\n output,\n costUsd,\n ...(sawCall && tokensKnown ? {} : { tokensKnown: false as const }),\n ...(sawCall && usdKnown ? {} : { usdKnown: false as const }),\n ...(sawEstimate ? { estimatedCostUsd } : {}),\n }\n}\n\nfunction buildLlmCall(\n data: Record<string, unknown>,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n const tokensIn = pickFiniteNumber(data, ['tokensIn', 'inputTokens', 'prompt_tokens'])\n const outputTokens = pickFiniteNumber(data, ['tokensOut', 'outputTokens', 'completion_tokens'])\n const reasoningTokens = pickFiniteNumber(data, ['reasoningTokens'])\n const tokensOut =\n outputTokens !== undefined || reasoningTokens !== undefined\n ? (outputTokens ?? 0) + (reasoningTokens ?? 0)\n : undefined\n const reportedCostUsd = pickFiniteNumber(data, ['costUsd', 'totalCostUsd', 'cost_usd', 'cost'])\n const explicitTokensKnown = data.tokensKnown ?? data.tokens_known\n const explicitCostKnown = data.costKnown ?? data.cost_known ?? data.usdKnown ?? data.usd_known\n const costProvenance = data.costProvenance ?? data.cost_provenance\n const explicitEstimate = pickFiniteNumber(data, ['estimatedCostUsd', 'estimated_cost_usd'])\n const catalogEstimate =\n costProvenance === 'catalog-estimate' ? (explicitEstimate ?? reportedCostUsd) : explicitEstimate\n const costUsd = costProvenance === 'catalog-estimate' ? undefined : reportedCostUsd\n const promptCache = readPromptCacheUsage(data)\n const tokensKnown =\n explicitTokensKnown !== false && tokensIn !== undefined && tokensOut !== undefined\n // Sandbox's canonical terminal `totalCostUsd` is already the provider-reported receipt. The\n // current SDK carries no provenance tag, so absence means the canonical receipt rather than\n // \"unknown\". Explicit estimates and explicit false-known markers remain unknown.\n const usdKnown =\n explicitCostKnown !== false &&\n costUsd !== undefined &&\n (costProvenance === undefined ||\n costProvenance === 'provider-receipt' ||\n costProvenance === 'billing-receipt')\n if (\n tokensIn === undefined &&\n tokensOut === undefined &&\n costUsd === undefined &&\n catalogEstimate === undefined &&\n promptCache === undefined &&\n explicitTokensKnown !== false &&\n explicitCostKnown !== false\n ) {\n return undefined\n }\n const model = typeof data.model === 'string' && data.model.length > 0 ? data.model : agentRunName\n const event: RuntimeStreamEvent & { type: 'llm_call' } = {\n type: 'llm_call',\n model,\n }\n if (tokensIn !== undefined) event.tokensIn = tokensIn\n if (tokensOut !== undefined) event.tokensOut = tokensOut\n if (!tokensKnown) event.tokensKnown = false\n if (costUsd !== undefined) event.costUsd = costUsd\n if (!usdKnown) event.usdKnown = false\n if (catalogEstimate !== undefined) event.estimatedCostUsd = catalogEstimate\n if (promptCache !== undefined) event.promptCache = promptCache\n return event\n}\n\n/**\n * Every wire spelling of a prompt-cache READ counter, in precedence order: the canonical name\n * first, then the spellings observed on the paths that reach this extractor — the sandbox terminal\n * `tokenUsage` record, the cli-bridge OpenAI-compatible usage object (which normalizes every\n * backend to Anthropic's `cache_read_input_tokens`), Anthropic verbatim, OpenAI's\n * `prompt_tokens_details.cached_tokens`, and DeepSeek's `prompt_cache_hit_tokens`.\n */\nconst PROMPT_CACHE_READ_KEYS = [\n 'readTokens',\n 'read_tokens',\n 'cacheReadInputTokens',\n 'cache_read_input_tokens',\n 'cacheRead',\n 'cache_read',\n 'cachedInputTokens',\n 'cachedTokens',\n 'cached_tokens',\n 'prompt_cache_hit_tokens',\n]\n\n/**\n * Every wire spelling of a prompt-cache WRITE counter. OpenAI reports no write counter at all, so\n * an OpenAI-shaped usage record matches nothing here and the write stays absent — which is the\n * point: absent is not zero.\n */\nconst PROMPT_CACHE_WRITE_KEYS = [\n 'writeTokens',\n 'write_tokens',\n 'cacheWriteInputTokens',\n 'cache_write_input_tokens',\n 'cacheCreationInputTokens',\n 'cache_creation_input_tokens',\n 'cacheWrite',\n 'cache_write',\n]\n\nconst PROMPT_CACHE_MISS_KEYS = ['missTokens', 'miss_tokens', 'prompt_cache_miss_tokens']\n\nconst PROMPT_CACHE_SAVINGS_KEYS = ['readSavingsUsd', 'read_savings_usd']\n\n/**\n * Read the provider's own prompt-cache accounting off one usage-bearing event payload, in the\n * `PromptCacheUsage` vocabulary the router, driver, and chat-client paths already speak.\n *\n * Two sources, one record. A payload that already carries a `promptCache` / `prompt_cache` object\n * is forwarded VERBATIM — those fields are the provider's own report, and an unrecognized one must\n * stay visible rather than be bucketed away. On top of that, flat provider counters are translated\n * to the canonical names, filling only the names the verbatim object did not already define.\n *\n * A counter the payload does not carry is left out. Defaulting it to zero would assert the provider\n * measured no cache, which is a different fact from a provider that reported nothing — and it is\n * the fact the budget reads to decide whether its charge is a measurement or a bound.\n */\nfunction readPromptCacheUsage(\n data: Record<string, unknown>,\n): Record<string, number | string> | undefined {\n const declared = finiteMetadata(data.promptCache ?? data.prompt_cache)\n const nested = plainRecord(data.promptCache) ?? plainRecord(data.prompt_cache)\n const details = plainRecord(data.prompt_tokens_details)\n const sources = [nested, data, details].filter(\n (s): s is Record<string, unknown> => s !== undefined,\n )\n\n const canonical: Record<string, number | string> = {}\n const readTokens = pickTokenCount(sources, PROMPT_CACHE_READ_KEYS)\n const writeTokens = pickTokenCount(sources, PROMPT_CACHE_WRITE_KEYS)\n const missTokens = pickTokenCount(sources, PROMPT_CACHE_MISS_KEYS)\n const readSavingsUsd = pickNonNegativeNumber(sources, PROMPT_CACHE_SAVINGS_KEYS)\n const status =\n nested !== undefined && typeof nested.status === 'string' ? nested.status : undefined\n if (readTokens !== undefined) canonical.readTokens = readTokens\n if (writeTokens !== undefined) canonical.writeTokens = writeTokens\n if (missTokens !== undefined) canonical.missTokens = missTokens\n if (readSavingsUsd !== undefined) canonical.readSavingsUsd = readSavingsUsd\n if (status !== undefined) canonical.status = status\n\n const merged = { ...canonical, ...declared }\n return Object.keys(merged).length > 0 ? merged : undefined\n}\n\nfunction plainRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\nfunction pickTokenCount(\n sources: readonly Record<string, unknown>[],\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n for (const source of sources) {\n const value = source[key]\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value\n }\n }\n return undefined\n}\n\nfunction pickNonNegativeNumber(\n sources: readonly Record<string, unknown>[],\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n for (const source of sources) {\n const value = source[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value\n }\n }\n return undefined\n}\n\nfunction finiteMetadata(value: unknown): Record<string, number | string> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const result: Record<string, number | string> = {}\n for (const [key, entry] of Object.entries(value)) {\n if ((typeof entry === 'number' && Number.isFinite(entry)) || typeof entry === 'string') {\n result[key] = entry\n }\n }\n return Object.keys(result).length > 0 ? result : undefined\n}\n\nfunction pickFiniteNumber(data: Record<string, unknown>, keys: string[]): number | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'number' && Number.isFinite(value)) return value\n }\n return undefined\n}\n\n/**\n * Cross-event state for {@link mapSandboxToolEvent}. Sandbox backends emit a\n * tool invocation as MANY `message.part.updated` frames on the same call id\n * (pending → running → completed), so faithful projection needs per-call\n * status memory: one `tool_call` on first sighting, at most one `tool_result`\n * on the terminal transition, nothing on intermediate re-frames. Create one\n * state per turn via {@link createSandboxToolPartState}.\n *\n * @experimental\n */\nexport interface SandboxToolPartState {\n /** Last seen status per tool call id. A terminal status is sticky — later\n * frames on a settled call project to nothing. */\n statusByCall: Map<string, string>\n /** Sequence for synthesized call ids when an event carries none. */\n seq: number\n}\n\n/**\n * Fresh per-turn {@link SandboxToolPartState} for {@link mapSandboxToolEvent} — an\n * empty call-status map so each turn projects tool frames independently.\n *\n * @experimental\n */\nexport function createSandboxToolPartState(): SandboxToolPartState {\n return { statusByCall: new Map(), seq: 0 }\n}\n\n/** Statuses that settle a tool call, or a whole execution, as a failure. One vocabulary for\n * both so a status never counts as failed in one projection and settled-fine in the other. */\nconst TERMINAL_FAILURE = /^(error|errored|failed|failure|cancelled|canceled|timeout|timed_out)$/i\n\n/**\n * Project one `SandboxEvent` onto the `tool_call` / `tool_result` variants of\n * `RuntimeStreamEvent` — the tool-part projection `mapSandboxEvent`\n * deliberately does NOT perform. Opt-in and additive: `mapSandboxEvent`'s\n * default vocabulary (text/reasoning deltas + `llm_call`) is unchanged;\n * consumers that need the tool surface (chat UIs rendering tool activity)\n * compose this projector alongside it — `streamAgentTurn` does exactly that\n * under its `preserveToolParts` option.\n *\n * Handled shapes (observed on the opencode / claude-code sandbox backends):\n * - `message.part.updated` with `part.type === 'tool'` — stateful: a\n * `tool_call` on the call id's first frame (args from `state.input` or\n * `state.metadata.input`), a `tool_result` when the status transitions to\n * `completed` (result from `state.output` / `metadata.output`) or to a\n * terminal failure (result is `{ error, status, output? }` — the error\n * surfaced in-band, never dropped).\n * - bare `tool*` event types (`tool.call`, `tool_result`, …) — stateless:\n * `*result*` types project to `tool_result`, the rest to `tool_call`.\n *\n * Returns `[]` for every non-tool event.\n *\n * @experimental\n */\nexport function mapSandboxToolEvent(\n event: SandboxEvent,\n state: SandboxToolPartState,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n if (!event || typeof event !== 'object') return []\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n if (String(part.type ?? '') !== 'tool') return []\n return projectToolPart(part, state, typeof event.id === 'string' ? event.id : undefined)\n }\n\n if (type.includes('tool')) {\n const callId =\n pickString(data, ['toolCallId', 'tool_use_id', 'id']) ??\n (typeof event.id === 'string' ? event.id : undefined) ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(data, ['name', 'toolName', 'tool']) ?? 'sandbox_tool'\n if (type.includes('result')) {\n return [\n {\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: data.output ?? data.result ?? data.content ?? data,\n },\n ]\n }\n return [\n { type: 'tool_call', toolName, toolCallId: callId, args: data.input ?? data.args ?? {} },\n ]\n }\n\n return []\n}\n\nfunction projectToolPart(\n part: Record<string, unknown>,\n state: SandboxToolPartState,\n eventId: string | undefined,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n const callId =\n pickString(part, ['callID', 'callId', 'toolCallId', 'id']) ??\n eventId ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(part, ['tool', 'toolName', 'name']) ?? 'sandbox_tool'\n const toolState =\n part.state && typeof part.state === 'object' ? (part.state as Record<string, unknown>) : {}\n const metadata =\n toolState.metadata && typeof toolState.metadata === 'object'\n ? (toolState.metadata as Record<string, unknown>)\n : {}\n const status = pickString(toolState, ['status']) ?? 'updated'\n\n const previous = state.statusByCall.get(callId)\n const settled =\n previous === 'completed' || (previous !== undefined && TERMINAL_FAILURE.test(previous))\n if (settled) return []\n\n const out: (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] = []\n if (previous === undefined) {\n out.push({\n type: 'tool_call',\n toolName,\n toolCallId: callId,\n args: toolState.input ?? metadata.input ?? {},\n })\n }\n state.statusByCall.set(callId, status)\n\n if (status === 'completed') {\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: toolState.output ?? metadata.output ?? '',\n })\n } else if (TERMINAL_FAILURE.test(status)) {\n const message =\n pickString(toolState, ['error', 'message']) ??\n pickString(metadata, ['error', 'message']) ??\n `sandbox tool ended with status ${status}`\n const output = toolState.output ?? metadata.output\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: { error: message, status, ...(output !== undefined ? { output } : {}) },\n })\n }\n return out\n}\n\nfunction pickString(data: Record<string, unknown>, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return undefined\n}\n\n/**\n * Project one `SandboxEvent` onto the `RuntimeStreamEvent` chat-UX vocabulary,\n * for runtimes that bridge a sandbox `streamPrompt` into the\n * `AgentRuntime.act` streaming contract. Returns `undefined` for events that\n * have no faithful projection — the raw stream is preserved separately for the\n * `OutputAdapter`, so an unmapped event never loses data.\n *\n * Mapped (the task-optional incremental variants — no synthesized task\n * lifecycle, no guessed tool-part shapes):\n * - `message.part.updated` text part → `text_delta`\n * - `message.part.updated` reasoning/thinking part → `reasoning_delta`\n * - cost-bearing events → `llm_call` (shared with the ledger extractor)\n *\n * Tool parts are deliberately NOT mapped here (unchanged default) — compose\n * {@link mapSandboxToolEvent} alongside when a consumer needs them.\n *\n * The opencode backend emits incremental text as\n * `{ type: 'message.part.updated', data: { part: { type, text }, delta } }`;\n * `delta` is the increment, `part.text` the running accumulation.\n */\nexport function mapSandboxEvent(\n event: SandboxEvent,\n opts: { agentRunName?: string } = {},\n): RuntimeStreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n const partType = String(part.type ?? '')\n const delta = typeof data.delta === 'string' ? data.delta : undefined\n const text = delta ?? (typeof part.text === 'string' ? part.text : undefined)\n if (text === undefined) return undefined\n if (partType === 'text') return { type: 'text_delta', text }\n if (partType === 'reasoning' || partType === 'thinking')\n return { type: 'reasoning_delta', text }\n return undefined\n }\n\n return extractLlmCallEvent(event, opts.agentRunName ?? 'agent')\n}\n\nexport {\n extractTransportEventIdentity,\n parseCanonicalTransportEvent,\n type TransportEventIdentity,\n} from './sandbox-transport-events'\n"],"mappings":";;AAEA,MAAM,iBAAiB;;AAGvB,SAAgB,uBAAuB,OAAgB,OAAwC;CAC7F,IAAI;EACF,2BAA2B,MAAM;GAC/B,OAAO;GACP,SAAS;GACT,UAAU;GACV,YAAY;GACZ,YAAY;GACZ,OAAO;IAAE,MAAM;IAAU,QAAQ;GAAa;EAChD,CAAC;CACH,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,MAAM,iCAAiC,EAAE,OAAO,MAAM,CAAC;CAC5E;AACF;;;;ACdA,SAAgB,6BACd,MACA,MACA,YACA,QACyB;CACzB,IAAI,CAAC,SAAS,IAAI,GAChB,MAAM,IAAI,MAAM,GAAG,OAAO,qDAAqD;CAEjF,MAAM,YAAY,OAAO,QAAQ,EAAE;CACnC,IAAI,eAAe,KAAA,GAAW;EAC5B,IACE,OAAO,eAAe,YACtB,eAAe,QACf,UAAU,cACV,OAAO,WAAW,SAAS,YAC3B,WAAW,SAAS,WAEpB,MAAM,IAAI,MACR,GAAG,OAAO,yBAAyB,WAAW,KAAK,mCAAmC,UAAU,EAClG;EAEF,MAAM,YAAY,2BAA2B,UAAU,UAAU;EACjE,IAAI,CAAC,UAAU,SACb,MAAM,IAAI,MAAM,GAAG,OAAO,iDAAiD,EACzE,OAAO,UAAU,MACnB,CAAC;EAEH,OAAO,UAAU;CACnB;CACA,MAAM,EACJ,MAAM,cACN,SAAS,UACT,QAAQ,SACR,UAAU,WACV,YAAY,aACZ,YAAY,aACZ,GAAG,YACD;CACJ,IAAI,iBAAiB,KAAA,KAAa,iBAAiB,WACjD,MAAM,IAAI,MACR,GAAG,OAAO,yBAAyB,OAAO,YAAY,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AAW,KAAK,OAAO,KAAA;EACnE,IAAI,SAAS,KAAA,GAAW,OAAO,KAAA;EAC/B,IAAI,aAAa,QAAQ,OAAO;GAAE,MAAM;GAAc;EAAK;EAC3D,IAAI,aAAa,eAAe,aAAa,YAC3C,OAAO;GAAE,MAAM;GAAmB;EAAK;EACzC;CACF;CAEA,OAAO,oBAAoB,OAAO,KAAK,gBAAgB,OAAO;AAChE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"stream-agent-turn-BMHUIuQS.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 { 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 mapSandboxEvent,\n mapSandboxToolEvent,\n} from './sandbox-events'\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 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}\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 model?: string\n stopReason?: string\n transportAttempts?: number\n result?: ExecutorResult<unknown>\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 }\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 for await (const event of abortableValues(inner, deadline.signal)) {\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 yield buildFinalEvent(\n task,\n session,\n acc,\n { status: 'completed', reason: 'turn completed' },\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 status: AgentTaskStatus = callerAborted ? 'aborted' : 'failed'\n const message = err instanceof Error ? err.message : String(err)\n const error: BackendErrorDetail =\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 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 }\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 for await (const event of abortableValues(stream, signal)) {\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}\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 throwIfAborted(signal)\n }\n result = executor.resultArtifact()\n } else {\n result = await awaitAbortable(run, signal)\n }\n acc.result = result\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}\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\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 (!Array.isArray(raw)) return []\n return raw.flatMap((entry) => {\n if (!entry || typeof entry !== 'object') return []\n const call = entry as Record<string, unknown>\n if (typeof call.name !== 'string') return []\n return [\n {\n ...(typeof call.id === 'string' ? { id: call.id } : {}),\n name: call.name,\n arguments:\n typeof call.arguments === 'string'\n ? call.arguments\n : JSON.stringify(call.arguments ?? {}),\n },\n ]\n })\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 (type !== 'result' && type !== 'done' && type !== 'final') 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.result\n ? {\n result: {\n outRef: acc.result.outRef,\n output: acc.result.out,\n ...(acc.result.verdict ? { verdict: acc.result.verdict } : {}),\n spent: acc.result.spent,\n },\n }\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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