@tangle-network/agent-runtime 0.134.4 → 0.134.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-q9Zo4NRy.js → activation-BFGP4ZnG.js} +2 -2
- package/dist/{activation-q9Zo4NRy.js.map → activation-BFGP4ZnG.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/{authoring-CmzMOTKX.js → authoring-CM9sA8yD.js} +2 -2
- package/dist/{authoring-CmzMOTKX.js.map → authoring-CM9sA8yD.js.map} +1 -1
- package/dist/{conversation-DYVSghi8.js → conversation-DIUtiLkC.js} +2 -2
- package/dist/{conversation-DYVSghi8.js.map → conversation-DIUtiLkC.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/{environment-provider-DIRm41xB.d.ts → environment-provider-BIZMHOQw.d.ts} +2 -2
- package/dist/environment-provider.d.ts +1 -1
- package/dist/{graph-B0wXX8Pr.js → graph-ICXhoz8O.js} +3 -2
- package/dist/graph-ICXhoz8O.js.map +1 -0
- package/dist/{improvement-cycle-4dO93TTE.js → improvement-cycle-b9IYBOJw.js} +4 -4
- package/dist/{improvement-cycle-4dO93TTE.js.map → improvement-cycle-b9IYBOJw.js.map} +1 -1
- package/dist/{index-SWNlB0Hv.d.ts → index-0qU8jNOJ.d.ts} +13 -5
- package/dist/{index-7VFw3_z0.d.ts → index-DJ9qeOi3.d.ts} +4 -4
- package/dist/{index-BbdLlSh6.d.ts → index-RYbM0cUo.d.ts} +2 -2
- package/dist/index.d.ts +7 -7
- package/dist/index.js +9 -9
- package/dist/intelligence.d.ts +4 -4
- package/dist/intelligence.js +3 -3
- package/dist/kernel.d.ts +5 -5
- package/dist/kernel.js +7 -7
- package/dist/{knowledge-EDOC3wEs.js → knowledge-Dxa5L4sb.js} +3 -3
- package/dist/{knowledge-EDOC3wEs.js.map → knowledge-Dxa5L4sb.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-CoBcsxpe.js → loop-runner-bin-B7yytyZx.js} +3 -3
- package/dist/{loop-runner-bin-CoBcsxpe.js.map → loop-runner-bin-B7yytyZx.js.map} +1 -1
- package/dist/{loop-runner-bin-DXqzpr4i.d.ts → loop-runner-bin-W7MjoHUk.d.ts} +3 -3
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +3 -3
- package/dist/mcp/index.js +4 -4
- package/dist/{openai-tools-BQHlv-Ex.js → openai-tools-DYTkum5Z.js} +2 -2
- package/dist/{openai-tools-BQHlv-Ex.js.map → openai-tools-DYTkum5Z.js.map} +1 -1
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/{redact-DTVIFTeR.d.ts → redact-Bojh05mQ.d.ts} +3 -3
- package/dist/{runtime-C60zv0Q4.d.ts → runtime-DHrzFy2v.d.ts} +3 -3
- package/dist/{runtime-DJMlvPY7.js → runtime-DPhY69h0.js} +7 -7
- package/dist/{runtime-DJMlvPY7.js.map → runtime-DPhY69h0.js.map} +1 -1
- package/dist/{stream-agent-turn-BLuTjcvw.d.ts → stream-agent-turn-BEv31Log.d.ts} +2 -2
- package/dist/{stream-agent-turn-DYBpzMmq.js → stream-agent-turn-Q5ellSUu.js} +10 -1
- package/dist/stream-agent-turn-Q5ellSUu.js.map +1 -0
- package/dist/{structural-rollout-GX7EzxeM.js → structural-rollout-B4ITMlW-.js} +3 -3
- package/dist/{structural-rollout-GX7EzxeM.js.map → structural-rollout-B4ITMlW-.js.map} +1 -1
- package/dist/{supervise-7JtBc_eW.js → supervise-CR8zPmfT.js} +23 -2
- package/dist/{supervise-7JtBc_eW.js.map → supervise-CR8zPmfT.js.map} +1 -1
- package/dist/{supervisor-Bfh5Gq_P.js → supervisor-DEEGgN_S.js} +55 -5
- package/dist/supervisor-DEEGgN_S.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +11 -11
- package/dist/{types-CfQbuWgo.d.ts → types-C7UNjVce.d.ts} +10 -3
- package/package.json +1 -1
- package/dist/graph-B0wXX8Pr.js.map +0 -1
- package/dist/stream-agent-turn-DYBpzMmq.js.map +0 -1
- package/dist/supervisor-Bfh5Gq_P.js.map +0 -1
package/dist/testing.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Lt as RunGraphTestOptions, Vt as runGraphWithTestBrain, Ya as superviseWithTestBrain, ao as SupervisorAgentTestDeps, gn as driverAgent, hn as DriverAgentOptions, mo as supervisorAgentWithTestBrain, qa as SuperviseTestOptions } from "./index-
|
|
2
|
-
import { it as ToolLoopChat, rt as ToolLoopCallContext } from "./runtime-
|
|
1
|
+
import { Lt as RunGraphTestOptions, Vt as runGraphWithTestBrain, Ya as superviseWithTestBrain, ao as SupervisorAgentTestDeps, gn as driverAgent, hn as DriverAgentOptions, mo as supervisorAgentWithTestBrain, qa as SuperviseTestOptions } from "./index-0qU8jNOJ.js";
|
|
2
|
+
import { it as ToolLoopChat, rt as ToolLoopCallContext } from "./runtime-DHrzFy2v.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-Czki1LBy.js";
|
|
2
|
-
import { f as verifyAgentImprovementProposal } from "./improvement-cycle-
|
|
3
|
-
import { c as supervisorAgentWithTestBrain, dt as driverAgent, r as superviseWithTestBrain } from "./supervise-
|
|
4
|
-
import { i as runGraphWithTestBrain } from "./graph-
|
|
2
|
+
import { f as verifyAgentImprovementProposal } from "./improvement-cycle-b9IYBOJw.js";
|
|
3
|
+
import { c as supervisorAgentWithTestBrain, dt as driverAgent, r as superviseWithTestBrain } from "./supervise-CR8zPmfT.js";
|
|
4
|
+
import { i as runGraphWithTestBrain } from "./graph-ICXhoz8O.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:
|
|
9
|
+
digest: "sha256:22fcbe2d1ef35fd675a6ec99eb700212ba88c560cdaa300eed1a511998b0d251",
|
|
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.134.
|
|
4580
|
+
"runtimeVersion": "0.134.6"
|
|
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:
|
|
4692
|
-
"runId": "agent-runtime-0.134.
|
|
4691
|
+
"recordDigest": "sha256:63f648151f74e1e3b23e820d9e7ed62e3c557b056f0bc3d204e8d43c90e878b3",
|
|
4692
|
+
"runId": "agent-runtime-0.134.6-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.134.
|
|
4715
|
+
runId: "agent-runtime-0.134.6-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:
|
|
4721
|
+
digest: "sha256:1691096dda156769f0a27951baeef3bc162032a5a9c4272ebe3de0b223322414",
|
|
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.134.
|
|
6355
|
+
"runtimeVersion": "0.134.6"
|
|
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:
|
|
6466
|
+
"recordDigest": "sha256:1017d1b15c7355373b1703da39560b6b445590c790ae33989c3cb74ef10dea9b",
|
|
6467
6467
|
"runId": "profile-improvement-1",
|
|
6468
6468
|
"schema": "agent-profile-improvement-experiment"
|
|
6469
6469
|
}
|
|
@@ -1005,8 +1005,15 @@ interface ExecutorExecutionBinding {
|
|
|
1005
1005
|
readonly binding: unknown;
|
|
1006
1006
|
readonly descriptor: Readonly<Record<string, string | number | boolean | null>>;
|
|
1007
1007
|
}
|
|
1008
|
-
/** Why exact materialization evidence is unavailable for a node.
|
|
1009
|
-
|
|
1008
|
+
/** Why exact materialization evidence is unavailable for a node.
|
|
1009
|
+
*
|
|
1010
|
+
* `executor-receipt-pending` is an IN-FLIGHT value only. It states that a pending executor has
|
|
1011
|
+
* declared its plan and has not yet sent the terminal acknowledgement, so the answer can still
|
|
1012
|
+
* arrive. A terminal record must never carry it: the attempt is over and no receipt is coming.
|
|
1013
|
+
* A terminal attempt that ended before its acknowledgement records
|
|
1014
|
+
* `executor-failed-before-receipt` instead, which names the outcome rather than a wait that
|
|
1015
|
+
* already finished. */
|
|
1016
|
+
type UnknownMaterializationReason = 'executor-did-not-report' | 'executor-failed-before-receipt' | 'executor-receipt-pending' | 'invalid-executor-report' | 'root-agent-did-not-report';
|
|
1010
1017
|
/** What the kernel can prove about one node's actual execution plan. */
|
|
1011
1018
|
type ProfileMaterializationReceipt = {
|
|
1012
1019
|
readonly status: 'known';
|
|
@@ -1926,4 +1933,4 @@ interface WidenGate<Out> {
|
|
|
1926
1933
|
}
|
|
1927
1934
|
//#endregion
|
|
1928
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 };
|
|
1929
|
-
//# sourceMappingURL=types-
|
|
1936
|
+
//# sourceMappingURL=types-C7UNjVce.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-runtime",
|
|
3
|
-
"version": "0.134.
|
|
3
|
+
"version": "0.134.6",
|
|
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": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"graph-B0wXX8Pr.js","names":[],"sources":["../src/runtime/supervise/graph.ts"],"sourcesContent":["/**\n *\n * `runGraph` — agent graphs: profiles as nodes, registry-backed prompt directives as edges.\n *\n * A topology is PLAIN DATA an agent can author in a few lines: nodes are canonical\n * `AgentProfile`s (the ONLY way a node is described — no role-builder functions), edges are typed\n * values carrying versioned {@link PromptHandle} directives, `deliverable` (termination) and\n * `budget` (one conserved pool) are mandatory. Driver↔worker is the two-node cyclic instance;\n * \"agent 3 analyzes 1 and 2 and reports to 1\" is ONE edge, not a framework.\n *\n * NOT A SECOND SCHEDULER. `runGraph` is an interpretation layer over what already runs:\n * `supervise()` is the execution core — the same `supervisorAgent`/`driverAgent` machinery,\n * `makeWorkerAgent` seam, conserved-pool budget, and deliverable-gated settlement every\n * supervised run uses. (`runAgentRounds` is deliberately NOT the substrate here.) What the graph\n * layer ADDS is exactly what a bespoke driver loop never\n * had:\n *\n * 1. **Node pinning** — a spawn names a node (`profile.name` = node id) and the node's canonical\n * profile is what runs; a driver cannot smuggle capabilities into a worker it did not define.\n * 2. **Observable edges** — every delegates/analyzes traversal lands in an EDGE LEDGER\n * (`delivered | stripped | empty | unpropagated`, with byte counts), in memory on\n * the result AND as `edge` events in the run journal. The motivating incident: a filter\n * silently replaced 1,700-char steering with 241 chars of boilerplate for three rounds and\n * NO artifact said so — an unobservable edge cannot be trusted and its directive cannot be\n * optimized.\n * 3. **Directives as data** — edge text lives in the prompt registry (`<surface>/v<n>`), so every\n * edge is a versioned optimization target, never prose hardcoded in a builder function.\n * 4. **Per-edge traversal caps** — the cyclic-graph backstop. A delegates edge whose cap is\n * exhausted REFUSES further traversals (fail loud), so a cycle cannot spin the pool dry.\n * 5. **Continuity as data** — a delegates edge may declare `continuity: 'resume'`, so each spawn\n * after the node's first re-attaches to its latest SETTLED session (the spawn context hands\n * the executor seam `resume: { ofWorker, sequence }`; the kernel keeps identity, ordering,\n * ledger truth, and the one conserved pool). Every ledger row states how its hop continued:\n * `'fresh' | 'resume'` for spawns, `'steer'` for mid-run deliveries — fresh respawns, session\n * resumes, and live steers are all plain data, each a ledgered fact.\n *\n * ORACLES ARE ENVIRONMENT, NEVER WORKERS. Graders/verifiers must not be spawnable in the graph —\n * a delegates edge to them leaks the rubric. An `analyzes` edge names its analyst in one of two\n * forms: a LENS id from the environment's registry (a pure function over trace evidence), or the\n * id of a graph NODE — a tool-equipped analyst AGENT spawned on each matching settle with the\n * node's pinned profile, whose settle output IS the findings. Either way the oracle doctrine\n * holds: an analyst node can never be a delegates target (refused loudly), so no driver can hand\n * it work, and an id living in both the registry and the nodes is refused as ambiguous.\n *\n * @experimental\n */\n\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport type {\n AnalystRegistry,\n AnalyzeOnSettleRoute,\n ContinuityMode,\n CoordinationEvent,\n MakeWorkerAgent,\n WorkerWatchOptions,\n} from '../../mcp/tools/coordination'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport type { RouterTransportConfig } from '../router-client'\nimport type { ToolLoopChat } from '../tool-loop'\nimport type { DeliverableSpec } from './completion-gate'\nimport {\n formatPromptHandle,\n kernelPromptRegistry,\n type PromptHandle,\n type PromptRegistry,\n} from './prompt-registry'\nimport type { ExecutorConfig } from './runtime'\nimport {\n type SuperviseOptions,\n supervise,\n superviseWithTestBrain,\n workerFromBackend,\n} from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\n\n// ── The algebra ────────────────────────────────────────────────────────────────\n\n/** A graph node: an id and a canonical `AgentProfile`. The profile is the ONLY way a node is\n * described — its `prompt.systemPrompt` is the standing role (the 0.117 canonical resolution;\n * never a legacy top-level-only reduction), its tools/mcp/resources are its capabilities. */\nexport interface GraphNode {\n readonly id: NodeId\n readonly profile: AgentProfile\n}\n\nexport type GraphEdge =\n /** Work flows down. The delegation directive is DATA → versionable, sweepable, optimizable.\n * Each spawn of `to` by `from` — and each mid-run steer from `from` to a live `to` worker —\n * is one traversal. */\n | {\n readonly kind: 'delegates'\n readonly from: NodeId\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Cyclic-graph backstop: traversals beyond this REFUSE (fail loud). Default\n * {@link defaultEdgeTraversalCap}. */\n readonly maxTraversals?: number\n /** Default continuity for this edge's SPAWN traversals. `'resume'` makes every spawn after\n * the node's first re-attach to its most recent SETTLED worker: a NEW live worker whose\n * spawn context carries `resume: { ofWorker, sequence }` for the executor seam, spending\n * from the same conserved pool — the node's first spawn is effectively `'fresh'`, and a\n * spawn while a prior worker is still live refuses loudly (steer is the live channel).\n * The driver's per-call `spawn_agent` `continuity` argument overrides either way. Omit =\n * `'fresh'` (today's behavior, byte-identical). Caps count resumes exactly like fresh\n * spawns. */\n readonly continuity?: ContinuityMode\n }\n /** Findings flow anywhere: an analyst over N nodes' settled traces, delivered to ONE node.\n * With a LENS analyst the directive wraps the findings for the recipient; with a NODE analyst\n * the directive is the analyst agent's task and the findings are its settle output. */\n | {\n readonly kind: 'analyzes'\n /** The analyst REFERENCE, in one of two forms: a lens id resolved against\n * `RunGraphOptions.analysts` (environment), or the id of a graph NODE with no delegates\n * edge pointing at it — then each matching settle spawns that node's pinned profile as a\n * tool-equipped analyst WORKER (same spawn machinery, conserved budget, trace join) whose\n * task is this edge's directive plus the settled worker's trace evidence and whose settle\n * output is the findings. An id that is both a node and a registry lens is refused. */\n readonly analyst: string\n readonly over: ReadonlyArray<NodeId>\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Observability cap: traversals beyond this are LEDGERED as exhausted (`unpropagated`).\n * Only delegates caps refuse traversal — they are what close the spawn cycle. */\n readonly maxTraversals?: number\n }\n\nexport interface AgentGraph {\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n /** Termination is mandatory, not optional: the independent completion oracle. */\n readonly deliverable: DeliverableSpec<unknown>\n /** One conserved pool across the whole graph — cycles without conservation never terminate. */\n readonly budget: Budget\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated'\n\n/** How one ledgered hop CONTINUED: a spawn traversal stamps its effective spawn mode\n * (`'fresh'` | `'resume'`), and every mid-run delivery into an already-live recipient — a\n * driver steer leg and every analyzes delivery (routed steer or driver-destined finding) —\n * stamps `'steer'`. Zero ambiguity: every row carries exactly one of the three. */\nexport type TraversalContinuity = ContinuityMode | 'steer'\n\n/** One recorded edge traversal — the in-memory row; the journal twin is the `edge` SpawnEvent. */\nexport interface EdgeTraversal {\n /** Stable edge id: `delegates:<from>-><to>` or `analyzes:<analyst>:<over…>-><to>`. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes'\n readonly from: string\n readonly to: string\n /** The resolved directive reference (`<surface>/v<n>`). */\n readonly directive: string\n /** 1-based per-edge ordinal. */\n readonly traversal: number\n readonly outcome: EdgeDeliveryOutcome\n /** How this hop continued — see {@link TraversalContinuity}. */\n readonly continuity: TraversalContinuity\n /** Bytes of directive + payload that actually crossed the edge. */\n readonly bytes: number\n readonly reason?: string\n /** The concrete worker node id, once known. */\n readonly workerId?: string\n}\n\n/** Default per-edge traversal cap — the cyclic-graph backstop when an edge names none. */\nexport const defaultEdgeTraversalCap = 32\n\n/** A delegates edge exhausted its traversal cap and the run produced no winner: the cap, not the\n * task, ended it. Carries the full evidence so failing loud loses nothing. */\nexport class GraphEdgeCapError extends Error {\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly ledger: ReadonlyArray<EdgeTraversal>\n readonly result: SupervisedResult<unknown>\n constructor(\n exhaustedEdges: ReadonlyArray<string>,\n ledger: ReadonlyArray<EdgeTraversal>,\n result: SupervisedResult<unknown>,\n ) {\n super(\n `runGraph: edge traversal cap exhausted on ${exhaustedEdges.join(', ')} and the run ` +\n 'delivered no winner — the cap (the cyclic-graph backstop), not the task, ended this run. ' +\n 'Raise maxTraversals on the edge or fix the cycle; the full edge ledger and the ' +\n 'supervised result ride on this error.',\n )\n this.name = 'GraphEdgeCapError'\n this.exhaustedEdges = exhaustedEdges\n this.ledger = ledger\n this.result = result\n }\n}\n\n// ── Options / result ───────────────────────────────────────────────────────────\n\nexport interface RunGraphOptions {\n /** WHERE worker nodes run — the executor backend. Provide this OR `makeWorkerAgent`. */\n readonly backend?: ExecutorConfig\n /** Leaf-execution override (offline tests / advanced). `runGraph` still owns node pinning,\n * directive delivery, and the edge ledger AROUND this seam — only the leaf `act` is yours. */\n readonly makeWorkerAgent?: MakeWorkerAgent\n /** The driver brain's router substrate (`profile.harness` omitted or `cli-base`). */\n readonly router?: RouterTransportConfig\n /** Caller-side runtime hooks (telemetry, policy, product extensions). Composed AFTER the\n * graph's own spawn-binding hook on the SAME event stream — the graph never swallows the\n * seam supervise() exposes. */\n readonly hooks?: RuntimeHooks\n /** The analyst lens registry `analyzes` edges resolve against. ENVIRONMENT — needed only for\n * lens analysts; an analyzes edge naming a graph NODE as its analyst needs no registry. */\n readonly analysts?: AnalystRegistry\n /** Watch every worker's LIVE tool trace with the online detector panel and raise a `finding`\n * on the bus the moment one loops or error-storms — forwarded to `supervise()` verbatim (see\n * `SuperviseOptions.watchWorkers`). Online findings (`analyst: 'online:<detector>'`) are bus\n * events for the driver, not graph edges, so they are never ledgered as traversals. Omit =\n * off (no online watching, no extra events). */\n readonly watchWorkers?: WorkerWatchOptions\n /** Directive registry. Default: the seeded kernel registry (`kernelPromptRegistry()`). */\n readonly registry?: PromptRegistry\n /** The run journal the edge ledger and every spawn/settle ride. Default: in-memory. */\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly runId?: string\n /** Per-child budget reserved from the conserved pool on each spawn. */\n readonly perWorker?: Budget\n readonly maxTurns?: number\n readonly maxLiveWorkers?: number\n /** Product authority over every steer/answer instruction (the filter seam). `runGraph` observes\n * what it CHANGES: a narrowed instruction ledgers its steer traversal as `stripped`. */\n readonly authorizeMessage?: SuperviseOptions['authorizeMessage']\n readonly signal?: AbortSignal\n readonly now?: () => number\n readonly otel?: SuperviseOptions['otel']\n readonly stallAfterMs?: number\n readonly allowedModels?: readonly string[]\n}\n\nexport interface GraphResult<Out = unknown> {\n readonly result: SupervisedResult<Out>\n /** Every edge traversal, in occurrence order — the observable-edge contract. */\n readonly ledger: ReadonlyArray<EdgeTraversal>\n /** Edge ids whose traversal cap was hit — analyzes exhaustion included (observable here, never\n * a refusal). A DELEGATES cap paired with a `no-winner` result THROWS\n * ({@link GraphEdgeCapError}) instead of returning: only delegates caps refuse spawns, so only\n * they can have ended the run. A LIFECYCLE no-winner (`aborted` / `budget-exhausted`) returns\n * normally even with an exhausted delegates cap — the abort or the pool, not the cap, ended\n * that run, and the exhaustion stays observable here. */\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly runId: string\n}\n\n/** Test-only graph options, exported only through the package's explicit `/testing` entry. */\nexport interface RunGraphTestOptions extends RunGraphOptions {\n readonly brain: ToolLoopChat\n}\n\n// ── Validation ─────────────────────────────────────────────────────────────────\n\ninterface ValidatedGraph {\n readonly root: GraphNode\n readonly workers: ReadonlyMap<NodeId, GraphNode>\n readonly delegatesByWorker: ReadonlyMap<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>\n readonly analyzes: ReadonlyArray<Extract<GraphEdge, { kind: 'analyzes' }>>\n /** Nodes referenced as an analyzes edge's ANALYST (the analyst-agent form): reachable through\n * their analyzes edge (spawned on settle), never through a delegates edge. */\n readonly analystNodes: ReadonlyMap<NodeId, GraphNode>\n}\n\nfunction edgeId(edge: GraphEdge): string {\n return edge.kind === 'delegates'\n ? `delegates:${edge.from}->${edge.to}`\n : `analyzes:${edge.analyst}:${edge.over.join('+')}->${edge.to}`\n}\n\n/** Validate the graph and resolve every directive BEFORE any compute is spent — an invalid\n * topology or an unknown directive is a configuration fault, never a mid-run surprise. */\nfunction validateGraph(\n graph: AgentGraph,\n registry: PromptRegistry,\n analysts: AnalystRegistry | undefined,\n): ValidatedGraph {\n if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {\n throw new ValidationError('runGraph: graph.nodes must be a non-empty array')\n }\n if (!Array.isArray(graph.edges) || graph.edges.length === 0) {\n throw new ValidationError('runGraph: graph.edges must be a non-empty array')\n }\n if (typeof graph.deliverable?.check !== 'function') {\n throw new ValidationError('runGraph: graph.deliverable is mandatory (termination oracle)')\n }\n if (typeof graph.budget !== 'object' || graph.budget === null) {\n throw new ValidationError('runGraph: graph.budget is mandatory (the conserved pool)')\n }\n const byId = new Map<NodeId, GraphNode>()\n for (const node of graph.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError('runGraph: every node needs a non-empty string id')\n }\n if (byId.has(node.id)) throw new ValidationError(`runGraph: duplicate node id '${node.id}'`)\n const parsed = agentProfileSchema.safeParse(node.profile)\n if (!parsed.success) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has an invalid AgentProfile: ${parsed.error.message}`,\n )\n }\n // The profile NAME is the node identity everywhere downstream: node pinning resolves a\n // spawn's `profile.name` against node ids, and the coordination layer matches analyst\n // routes (`over`/`to`) against the settled worker's PROFILE NAME. A divergent name would\n // make every analyzes edge touching this node silently never match — refuse it up front.\n if (node.profile.name !== node.id) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has profile.name ${JSON.stringify(node.profile.name)} — ` +\n 'profile.name IS the node identity (node pinning and analyst routing match on it) and ' +\n 'must equal the node id',\n )\n }\n byId.set(node.id, node)\n }\n const requireNode = (id: NodeId, where: string): GraphNode => {\n const node = byId.get(id)\n if (!node) throw new ValidationError(`runGraph: ${where} references unknown node '${id}'`)\n return node\n }\n const delegates = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'delegates' }> => edge.kind === 'delegates',\n )\n const analyzes = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'analyzes' }> => edge.kind === 'analyzes',\n )\n if (delegates.length === 0) {\n throw new ValidationError('runGraph: at least one delegates edge is required (who spawns whom)')\n }\n for (const edge of graph.edges) registry.resolve(edge.directive)\n for (const edge of delegates) {\n requireNode(edge.from, edgeId(edge))\n requireNode(edge.to, edgeId(edge))\n if (edge.from === edge.to) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates to itself — the driver↔worker cycle is the ` +\n 'settle-return loop, not a self-edge',\n )\n }\n // The type admits only 'fresh' | 'resume', but a graph is plain data that often arrives\n // through JSON — refuse a nonsense mode here, never let it reach the spawn tool as a string.\n if (\n edge.continuity !== undefined &&\n edge.continuity !== 'fresh' &&\n edge.continuity !== 'resume'\n ) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} has invalid continuity ${JSON.stringify(edge.continuity)} — ` +\n \"a delegates edge's continuity is 'fresh' or 'resume'\",\n )\n }\n }\n // Root: the one node that delegates and is never delegated TO. P0 executes the star/2-node\n // cyclic family (one driver, N workers); nested driver graphs are the recorded P3 absorption.\n const delegatedTo = new Set(delegates.map((edge) => edge.to))\n const roots = [...new Set(delegates.map((edge) => edge.from))].filter(\n (id) => !delegatedTo.has(id),\n )\n if (roots.length !== 1) {\n throw new ValidationError(\n `runGraph: expected exactly ONE root (a node that delegates and is never delegated to), ` +\n `found ${roots.length === 0 ? 'none — delegates edges form a cycle with no entry' : roots.join(', ')}. ` +\n 'P0 executes driver↔worker(s); nested driver graphs are P3.',\n )\n }\n const root = requireNode(roots[0] as string, 'root resolution')\n for (const edge of delegates) {\n if (edge.from !== root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates from a non-root node — P0 executes one driver over ` +\n 'its workers (the 2-node cyclic case, star-generalized); deeper delegation is P3',\n )\n }\n }\n const analystIds = new Set<string>()\n const analystNodes = new Map<NodeId, GraphNode>()\n for (const edge of analyzes) {\n // Continuity is a delegates-edge axis ONLY: analysts (lens or node) are spawned by the\n // analyst-on-settle machinery, each run a fresh session over settled evidence — an analyzes\n // edge carrying continuity would silently mean nothing, so it is refused as data.\n if ((edge as { continuity?: unknown }).continuity !== undefined) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} carries continuity — analysts are spawned by the analyst ` +\n 'machinery (every analyst run is a fresh session over settled evidence), so ' +\n 'continuity is a delegates-edge axis only',\n )\n }\n // The runner's traversal ledger resolves a finding/steer back to its edge BY ANALYST ID\n // alone, so a second edge sharing an analyst would silently absorb the first edge's\n // traversals (last-registered wins). Multi-edge-per-analyst is not yet supported; refuse it\n // rather than mis-ledger it.\n if (analystIds.has(edge.analyst)) {\n throw new ValidationError(\n `runGraph: two analyzes edges share analyst '${edge.analyst}' — one analyzes edge per ` +\n 'analyst lens (traversals are ledgered by analyst id; a second edge would silently ' +\n \"absorb the first's). Register the lens under a second id for a second edge.\",\n )\n }\n analystIds.add(edge.analyst)\n // The analyst REFERENCE has two forms — a registry lens id or a graph node id — and the id\n // itself is what distinguishes them, so an id living in both is refused as ambiguous rather\n // than silently resolved by precedence.\n const analystNode = byId.get(edge.analyst)\n const inRegistry = analysts?.kinds.some((kind) => kind.id === edge.analyst) === true\n if (analystNode !== undefined && inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is BOTH a graph node and a lens in ` +\n 'the analysts registry — the id alone distinguishes the two analyst forms, so this is ' +\n 'ambiguous; rename the node or register the lens under another id',\n )\n }\n if (analystNode !== undefined) {\n // The analyst-AGENT form. Oracle doctrine holds structurally: the analyst node can never\n // receive work — not from the root (a delegates edge to it is refused) and not by being\n // the root (the root delegates by definition).\n if (analystNode.id === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names the ROOT as its analyst — the root is the driver; ` +\n 'give the analyst its own node with no delegates edge pointing at it',\n )\n }\n if (delegatedTo.has(analystNode.id)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names node '${edge.analyst}' as its analyst, but that node ` +\n 'is a delegates target — oracle doctrine: an analyst is never delegated to. An ' +\n 'analyst NODE is legal only with NO delegates edge pointing at it; give the analyst ' +\n 'its own delegates-free node or pass a lens id from RunGraphOptions.analysts.',\n )\n }\n analystNodes.set(analystNode.id, analystNode)\n } else if (!analysts) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is not a graph node, and no ` +\n 'RunGraphOptions.analysts registry was provided to resolve it as a lens',\n )\n } else if (!inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is neither a graph node nor in the ` +\n `analysts registry (known lenses: ${analysts.kinds.map((kind) => kind.id).join(', ') || 'none'})`,\n )\n }\n if (edge.over.length === 0) {\n throw new ValidationError(`runGraph: ${edgeId(edge)} must analyze at least one node`)\n }\n for (const over of edge.over) {\n requireNode(over, edgeId(edge))\n // Analysts observe SETTLED WORKERS, matched by profile name — the root drives and never\n // settles as a worker, so an edge over the root would silently never fire; refuse it.\n if (over === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes the ROOT — analysts observe settled workers, and ` +\n 'the root never settles as one, so this edge would silently never fire; list ' +\n 'delegates-target nodes only',\n )\n }\n }\n requireNode(edge.to, edgeId(edge))\n }\n // Second pass, once every analyst NODE is known: an analyst run's settlement is a FINDING,\n // never a worker settle, so an analyzes edge OVER an analyst node would silently never fire —\n // refuse it rather than let it rot unobserved.\n for (const edge of analyzes) {\n for (const over of edge.over) {\n if (analystNodes.has(over)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes '${over}', which is an analyst node — an analyst ` +\n 'run settles as a finding, never as a worker, so this edge would silently never ' +\n 'fire; analyst nodes are not analyzable',\n )\n }\n }\n }\n const workers = new Map<NodeId, GraphNode>()\n const delegatesByWorker = new Map<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>()\n for (const edge of delegates) {\n if (delegatesByWorker.has(edge.to)) {\n throw new ValidationError(\n `runGraph: node '${edge.to}' is the target of two delegates edges — one delegation ` +\n 'directive per worker node (version the directive instead of forking the edge)',\n )\n }\n delegatesByWorker.set(edge.to, edge)\n workers.set(edge.to, requireNode(edge.to, edgeId(edge)))\n }\n // Every non-root node must be reachable by SOME edge, or it can never run. A worker node is\n // reached by its delegates edge; an analyst node by its analyzes edge (spawned on settle).\n for (const node of graph.nodes) {\n if (node.id !== root.id && !workers.has(node.id) && !analystNodes.has(node.id)) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has no delegates edge to it — an unreachable node never runs`,\n )\n }\n }\n return { root, workers, delegatesByWorker, analyzes, analystNodes }\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\nconst byteLength = (text: string): number => Buffer.byteLength(text, 'utf8')\n\nfunction stringifyPayload(payload: unknown): string {\n if (typeof payload === 'string') return payload\n try {\n return JSON.stringify(payload) ?? String(payload)\n } catch {\n return String(payload)\n }\n}\n\n/**\n * Execute an {@link AgentGraph}. The root node becomes the supervisor (`supervise()` — the\n * execution core), each worker node is spawnable BY NODE ID (`spawn_agent` with\n * `profile: { name: '<node id>' }`; the node's canonical profile is pinned by the graph), each\n * delegates directive is appended to the worker profile's `prompt.instructions` per traversal,\n * and each analyzes edge becomes an analyst-on-settle route with a real DESTINATION. Every\n * traversal is ledgered and journaled.\n */\nexport function runGraph(graph: AgentGraph, opts: RunGraphOptions): Promise<GraphResult> {\n if ('brain' in opts) {\n throw new ValidationError(\n 'runGraph: direct brain injection is test-only; production execution derives the model call from the root AgentProfile',\n )\n }\n return runGraphInternal(graph, opts)\n}\n\n/** Deterministic scripted-brain path for graph tests. Not exported from Runtime's main entry. */\nexport function runGraphWithTestBrain(\n graph: AgentGraph,\n opts: RunGraphTestOptions,\n): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return runGraphInternal(graph, runtimeOptions, brain)\n}\n\nfunction runGraphInternal(\n graph: AgentGraph,\n opts: RunGraphOptions,\n testBrain?: ToolLoopChat,\n): Promise<GraphResult> {\n const registry = opts.registry ?? kernelPromptRegistry()\n const { root, workers, delegatesByWorker, analyzes, analystNodes } = validateGraph(\n graph,\n registry,\n opts.analysts,\n )\n if (!opts.backend && !opts.makeWorkerAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeWorkerAgent',\n )\n }\n const journal = opts.journal ?? new InMemorySpawnJournal()\n const blobs = opts.blobs ?? new InMemoryResultBlobStore()\n const runId =\n opts.runId ??\n `graph-${canonicalCandidateDigest(graph.nodes.map((n) => n.id)).slice('sha256:'.length, 'sha256:'.length + 12)}`\n const now = opts.now ?? Date.now\n\n // ── Ledger state ──\n const ledger: EdgeTraversal[] = []\n const journaled = new Set<EdgeTraversal>()\n const traversalCounts = new Map<string, number>()\n const exhausted = new Set<string>()\n // The subset of `exhausted` that REFUSED work. Only a delegates cap closes the spawn cycle, so\n // only it can be the reason a run ended winnerless — an analyzes cap refuses nothing.\n const exhaustedDelegates = new Set<string>()\n const journalWrites: Promise<void>[] = []\n let ledgerSeq = 0\n const appendJournal = (entry: EdgeTraversal, nodeIdForEvent: string): Promise<void> => {\n if (journaled.has(entry)) return Promise.resolve()\n journaled.add(entry)\n const write = journal.appendEvent(runId, {\n kind: 'edge',\n id: nodeIdForEvent,\n edge: { kind: entry.kind, from: entry.from, to: entry.to, directive: entry.directive },\n traversal: entry.traversal,\n outcome: entry.outcome,\n continuity: entry.continuity,\n bytes: entry.bytes,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n seq: ledgerSeq++,\n at: new Date(now()).toISOString(),\n })\n journalWrites.push(write)\n return write\n }\n const record = (entry: Omit<EdgeTraversal, 'traversal'>, journalNow: boolean): EdgeTraversal => {\n const count = (traversalCounts.get(entry.edge) ?? 0) + 1\n traversalCounts.set(entry.edge, count)\n const row: EdgeTraversal = { ...entry, traversal: count }\n ledger.push(row)\n if (journalNow) void appendJournal(row, row.workerId ?? `graph:${row.to}`)\n return row\n }\n\n // ── Node pinning + delegates spawn traversals (the makeWorkerAgent wrapper) ──\n const makeLeaf =\n opts.makeWorkerAgent ?? workerFromBackend(opts.backend as ExecutorConfig, graph.deliverable)\n const nodeByWorkerId = new Map<string, NodeId>()\n const pendingByAssignment = new Map<string, EdgeTraversal>()\n const graphWorker: MakeWorkerAgent = (authoredProfile, spawnContext) => {\n const requested =\n typeof (authoredProfile as { name?: unknown } | undefined)?.name === 'string'\n ? (authoredProfile as { name: string }).name\n : undefined\n // An analyst-AGENT run: the coordination settle hook — never the driver; the marker is\n // authored by the runtime, not accepted from model arguments — spawns the analyst NODE.\n // Pin the node's canonical profile; the analysis directive travels as the TASK (composed by\n // the coordination layer with the settled worker's trace evidence), so nothing is appended\n // to the profile's instructions here. Its traversal is ledgered on the finding/steer it\n // produces, exactly like a registry analyst's.\n if (spawnContext?.analyst !== undefined) {\n const analystNode = analystNodes.get(spawnContext.analyst)\n if (!analystNode || requested !== analystNode.id) {\n throw new ValidationError(\n `runGraph: analyst run for ${JSON.stringify(spawnContext.analyst)} does not name an ` +\n `analyst node of this graph (analyst nodes: ${[...analystNodes.keys()].join(', ') || 'none'})`,\n )\n }\n return makeLeaf(analystNode.profile, spawnContext)\n }\n const node = requested !== undefined ? workers.get(requested) : undefined\n if (!node) {\n throw new ValidationError(\n `runGraph: spawn_agent named profile ${JSON.stringify(requested)} which is not a worker ` +\n `node of this graph (nodes: ${[...workers.keys()].join(', ')}). Spawn by node id: ` +\n 'profile.name selects the node; the node profile itself is pinned by the graph.',\n )\n }\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const id = edgeId(edge)\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(id) ?? 0\n // The EFFECTIVE spawn mode the coordination layer resolved (per-call override, else this\n // edge's declared default, else fresh) — stamped on the row so the ledger states how each\n // hop continued, never how it was merely configured to.\n const spawnContinuity = spawnContext?.continuity ?? 'fresh'\n if (used >= cap) {\n exhausted.add(id)\n exhaustedDelegates.add(id)\n record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: 'unpropagated',\n continuity: spawnContinuity,\n bytes: 0,\n reason: `traversal-cap-exhausted (max ${cap})`,\n },\n true,\n )\n throw new ValidationError(\n `runGraph: delegates edge ${id} exhausted its traversal cap (${cap}) — the ` +\n 'cyclic-graph backstop refused this spawn',\n )\n }\n const directiveText = registry.resolve(edge.directive).text\n const taskText = stringifyPayload(spawnContext?.task)\n const bytes = byteLength(directiveText) + byteLength(taskText)\n const row = record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: bytes === 0 ? 'empty' : 'delivered',\n continuity: spawnContinuity,\n bytes,\n ...(bytes === 0 ? { reason: 'no directive text and no task payload' } : {}),\n },\n false,\n )\n if (spawnContext?.assignmentId !== undefined) {\n pendingByAssignment.set(spawnContext.assignmentId, row)\n } else {\n void appendJournal(row, `graph:${row.to}`)\n }\n // The delegation directive is a STANDING instruction of this traversal: appended to the\n // node's canonical prompt instructions, so the worker runs under node profile + edge\n // directive, and the driver-authored profile contributes ONLY the node selection.\n const pinned: AgentProfile =\n directiveText.length === 0\n ? node.profile\n : {\n ...node.profile,\n prompt: {\n ...(node.profile.prompt ?? {}),\n instructions: [\n ...((node.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n directiveText,\n ],\n },\n }\n return makeLeaf(pinned, spawnContext)\n }\n\n // ── Analyzes edges → analyst-on-settle routes with destinations ──\n // A LENS edge's directive wraps the findings for the recipient (so a driver-destined lens\n // route carries no directive — it becomes the driver brief below). A NODE edge's directive is\n // the analyst AGENT's task, so it always rides the route, wherever the findings go.\n const routes: Array<string | AnalyzeOnSettleRoute> = analyzes.map((edge) => {\n const analystNode = analystNodes.get(edge.analyst)\n if (analystNode) {\n return {\n kind: edge.analyst,\n over: edge.over,\n agent: analystNode.profile,\n directive: registry.resolve(edge.directive).text,\n ...(edge.to === root.id ? {} : { to: edge.to }),\n }\n }\n return edge.to === root.id\n ? { kind: edge.analyst, over: edge.over }\n : {\n kind: edge.analyst,\n over: edge.over,\n to: edge.to,\n directive: registry.resolve(edge.directive).text,\n }\n })\n // Driver-destined analyzes findings are standing knowledge for the ROOT: the findings arrive\n // as bus events. For a lens edge the directive tells the driver what to do with them; for a\n // node edge the directive already went to the analyst agent as its task.\n const driverAnalyzesBriefs = analyzes\n .filter((edge) => edge.to === root.id)\n .map((edge) =>\n analystNodes.has(edge.analyst)\n ? `Findings from analyst '${edge.analyst}' (a tool-equipped analyst agent node, over: ` +\n `${edge.over.join(', ')}) will arrive as finding events.`\n : `Findings from analyst '${edge.analyst}' (over: ${edge.over.join(', ')}) will arrive as ` +\n `finding events.\\n${registry.resolve(edge.directive).text}`,\n )\n\n // ── Edge continuity defaults, threaded to the spawn tool by node id (= profile name) ──\n const continuityByProfile: Record<string, ContinuityMode> = {}\n for (const [nodeId, edge] of delegatesByWorker) {\n if (edge.continuity !== undefined) continuityByProfile[nodeId] = edge.continuity\n }\n\n // ── The driver graph brief: which nodes it may spawn, by exact name ──\n const workerLines = [...workers.values()].map((node) => {\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const description =\n typeof node.profile.description === 'string' && node.profile.description.length > 0\n ? ` — ${node.profile.description}`\n : ''\n const continuityNote =\n edge.continuity === 'resume'\n ? \"; continuity: resume — each spawn after the first re-attaches to this node's latest \" +\n 'settled session (spawn again to continue it; steer while it is live)'\n : ''\n return `- '${node.id}'${description} (delegation cap: ${cap} traversals${continuityNote})`\n })\n const graphBrief = [\n 'AGENT GRAPH: you are the driver node of a fixed topology. You may spawn ONLY these worker',\n \"nodes, by EXACT name (spawn_agent with profile: { name: '<node id>' }; the node's full\",\n 'profile is pinned by the graph — any other profile fields you author are ignored):',\n ...workerLines,\n ...(driverAnalyzesBriefs.length > 0 ? ['', ...driverAnalyzesBriefs] : []),\n ].join('\\n')\n const rootProfile: AgentProfile = {\n ...root.profile,\n prompt: {\n ...(root.profile.prompt ?? {}),\n instructions: [\n ...((root.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n graphBrief,\n ],\n },\n }\n\n // ── Steer + finding observation (delegates steers, analyzes traversals) ──\n // The filter seam: when the caller's authorizeMessage NARROWS an instruction, the delivered\n // bytes differ from the composed bytes — that steer traversal is `stripped` (the VB incident:\n // authored steering silently replaced by boilerplate, byte-indistinguishable downstream).\n const strippedByDigest = new Map<string, { composedBytes: number }>()\n const authorizeMessage: SuperviseOptions['authorizeMessage'] | undefined = opts.authorizeMessage\n ? (input) => {\n const decision = (\n opts.authorizeMessage as NonNullable<SuperviseOptions['authorizeMessage']>\n )(input)\n if (decision.instruction !== input.instruction) {\n strippedByDigest.set(canonicalCandidateDigest(decision.instruction), {\n composedBytes: byteLength(input.instruction),\n })\n }\n return decision\n }\n : undefined\n\n const routedAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n const driverAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n for (const edge of analyzes) {\n ;(edge.to === root.id ? driverAnalyzesByAnalyst : routedAnalyzesByAnalyst).set(\n edge.analyst,\n edge,\n )\n }\n const analyzesCapReached = (edge: Extract<GraphEdge, { kind: 'analyzes' }>): boolean => {\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(edgeId(edge)) ?? 0\n if (used < cap) return false\n exhausted.add(edgeId(edge))\n return true\n }\n const ledgerAnalyzes = (\n edge: Extract<GraphEdge, { kind: 'analyzes' }>,\n outcome: EdgeDeliveryOutcome,\n bytes: number,\n reason: string | undefined,\n workerId: string | undefined,\n ): void => {\n const capped = analyzesCapReached(edge)\n record(\n {\n edge: edgeId(edge),\n kind: 'analyzes',\n from: edge.over.join('+'),\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: capped ? 'unpropagated' : outcome,\n // Every analyzes traversal is a mid-run delivery into an already-live recipient (a\n // routed steer leg, or the finding reaching the live driver) — never a spawn.\n continuity: 'steer',\n bytes,\n ...(capped\n ? {\n reason: `traversal-cap-exhausted (max ${edge.maxTraversals ?? defaultEdgeTraversalCap})`,\n }\n : reason !== undefined\n ? { reason }\n : {}),\n ...(workerId !== undefined ? { workerId } : {}),\n },\n true,\n )\n }\n\n const onCoordinationEvent = async (\n _context: unknown,\n _eventId: unknown,\n recordEnvelope: { readonly event: CoordinationEvent },\n ): Promise<void> => {\n const event = recordEnvelope.event\n if (event.type === 'finding') {\n // A routed edge's traversal is ledgered on its STEER (the delivery); the finding event is\n // its audit copy. A driver-destined edge's traversal IS the finding reaching the bus.\n const edge = driverAnalyzesByAnalyst.get(event.finding.analyst)\n if (!edge) return\n const sourceNode = nodeByWorkerId.get(event.finding.fromWorker)\n if (sourceNode === undefined || !edge.over.includes(sourceNode)) return\n // Absent findings (the analyst returned `undefined` — the producer omits the key so the\n // event stays digestable) contribute ZERO bytes, never the text \"undefined\".\n const findingsText =\n event.finding.findings === undefined ? '' : stringifyPayload(event.finding.findings)\n const directiveBytes = byteLength(registry.resolve(edge.directive).text)\n const empty = findingsText.length === 0\n ledgerAnalyzes(\n edge,\n empty ? 'empty' : 'delivered',\n directiveBytes + byteLength(findingsText),\n empty ? 'analyst returned no findings' : undefined,\n event.finding.fromWorker,\n )\n return\n }\n if (event.type === 'steer') {\n const down = event.down\n if (event.analyst !== undefined) {\n const edge = routedAnalyzesByAnalyst.get(event.analyst)\n if (!edge) return\n ledgerAnalyzes(\n edge,\n down.delivered ? 'delivered' : 'unpropagated',\n byteLength(down.instruction),\n down.delivered ? undefined : down.outcome,\n down.toWorker,\n )\n return\n }\n // A driver-authored steer to a live worker node is a delegates traversal too — the\n // mid-run leg of the same edge (the leg the motivating incident lost).\n const nodeId = nodeByWorkerId.get(down.toWorker)\n if (nodeId === undefined) return\n const edge = delegatesByWorker.get(nodeId)\n if (!edge) return\n const stripped = strippedByDigest.get(down.instructionDigest)\n record(\n {\n edge: edgeId(edge),\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: !down.delivered ? 'unpropagated' : stripped ? 'stripped' : 'delivered',\n // The mid-run leg of the edge: a delivery into the LIVE worker, never a spawn.\n continuity: 'steer',\n bytes: byteLength(down.instruction),\n ...(!down.delivered\n ? { reason: down.outcome }\n : stripped\n ? { reason: `authorization narrowed ${stripped.composedBytes} composed bytes` }\n : {}),\n workerId: down.toWorker,\n },\n true,\n )\n }\n }\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks = {\n onEvent: (event: {\n target?: string\n phase?: string\n payload?: unknown\n }): void | Promise<void> => {\n if (event.target !== 'agent.spawn' || event.phase !== 'after') return\n const payload = event.payload as { childId?: unknown; assignmentId?: unknown } | undefined\n if (typeof payload?.childId !== 'string' || typeof payload.assignmentId !== 'string') return\n const pending = pendingByAssignment.get(payload.assignmentId)\n if (!pending) return\n pendingByAssignment.delete(payload.assignmentId)\n const bound: EdgeTraversal = { ...pending, workerId: payload.childId }\n ledger[ledger.indexOf(pending)] = bound\n nodeByWorkerId.set(payload.childId, bound.to)\n return appendJournal(bound, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\n\n // Every configuration fault above throws SYNCHRONOUSLY (matching `supervise()`'s own\n // contract); only the run itself is asynchronous.\n const start = async (): Promise<GraphResult> => {\n const superviseOptions = {\n budget: graph.budget,\n deliverable: graph.deliverable,\n makeWorkerAgent: graphWorker,\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent,\n // Lens routes resolve against the registry; agent routes carry their own analyst profile,\n // so a graph whose only analysts are nodes needs no registry at all.\n ...(routes.length > 0\n ? { analyzeOnSettle: routes, ...(opts.analysts ? { analysts: opts.analysts } : {}) }\n : {}),\n ...(Object.keys(continuityByProfile).length > 0 ? { continuityByProfile } : {}),\n ...(opts.watchWorkers ? { watchWorkers: opts.watchWorkers } : {}),\n ...(opts.router ? { router: opts.router } : {}),\n ...(authorizeMessage ? { authorizeMessage } : {}),\n ...(opts.perWorker ? { perWorker: opts.perWorker } : {}),\n ...(opts.maxTurns !== undefined ? { maxTurns: opts.maxTurns } : {}),\n ...(opts.maxLiveWorkers !== undefined ? { maxLiveWorkers: opts.maxLiveWorkers } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.now ? { now: opts.now } : {}),\n ...(opts.otel ? { otel: opts.otel } : {}),\n ...(opts.stallAfterMs !== undefined ? { stallAfterMs: opts.stallAfterMs } : {}),\n ...(opts.allowedModels ? { allowedModels: opts.allowedModels } : {}),\n } satisfies SuperviseOptions\n const result =\n testBrain === undefined\n ? await supervise(rootProfile, graphTask(graph, root), superviseOptions)\n : await superviseWithTestBrain(rootProfile, graphTask(graph, root), {\n ...superviseOptions,\n brain: testBrain,\n })\n\n // A spawn row is PROVISIONAL until the `agent.spawn` hook (fired synchronously once a worker\n // exists) binds it to a live worker id. A row still unbound here means the factory ran but no\n // NEW worker went live: the spawn was refused after the factory (identity conflict, runtime\n // floor) or a keyed re-spawn deduplicated to an already-completed result (prepare() runs the\n // factory, no hook fires). Both state the same truth every unpropagated row states — the\n // directive never reached a live worker — so rewrite rather than mint a new outcome. Then\n // settle every journal write, so the ledger's journal twin is complete when this returns.\n for (const pending of pendingByAssignment.values()) {\n const refused: EdgeTraversal = {\n ...pending,\n outcome: 'unpropagated',\n bytes: 0,\n reason: `no-live-worker-bound (spawn refused after the factory, or a keyed re-spawn deduplicated to a completed result; ${pending.bytes} composed bytes never crossed)`,\n }\n ledger[ledger.indexOf(pending)] = refused\n await appendJournal(refused, `graph:${refused.to}`)\n }\n pendingByAssignment.clear()\n await Promise.all(journalWrites)\n\n const exhaustedEdges = Object.freeze([...exhausted])\n const frozenLedger = Object.freeze(ledger.map((row) => Object.freeze({ ...row })))\n // A LIFECYCLE ending (caller abort, exhausted budget) is its own complete explanation: the\n // cap did not end that run even when it was exhausted along the way, and blaming it would\n // misattribute the ending (and turn a caller-initiated abort into a throw). The exhaustion\n // stays observable in `exhaustedEdges` either way.\n const lifecycleEnded =\n result.kind === 'no-winner' &&\n (result.reason === 'aborted' || result.reason === 'budget-exhausted')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.size > 0) {\n // Fail LOUD: the backstop, not the task, ended this run. The evidence rides on the error.\n // Only DELEGATES caps refuse spawns, so only they can be the cause named here.\n throw new GraphEdgeCapError(Object.freeze([...exhaustedDelegates]), frozenLedger, result)\n }\n return { result, ledger: frozenLedger, exhaustedEdges, runId }\n }\n\n return start()\n}\n\n/** The root task: the graph's own framing. The deliverable (mandatory) is the termination; the\n * task names what the topology exists to produce. */\nfunction graphTask(graph: AgentGraph, root: GraphNode): string {\n const describe = graph.deliverable.describe\n return (\n describe ?? `Deliver the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AQ,IAAI,aAAa;EAE/B,MAAM,iBAAiB,OAAO,OAAO,CAAC,GAAG,SAAS,CAAC;EACnD,MAAM,eAAe,OAAO,OAAO,OAAO,KAAK,QAAQ,OAAO,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;EAKjF,MAAM,iBACJ,OAAO,SAAS,gBACf,OAAO,WAAW,aAAa,OAAO,WAAW;EACpD,IAAI,OAAO,SAAS,YAAY,CAAC,kBAAkB,mBAAmB,OAAO,GAG3E,MAAM,IAAI,kBAAkB,OAAO,OAAO,CAAC,GAAG,kBAAkB,CAAC,GAAG,cAAc,MAAM;EAE1F,OAAO;GAAE;GAAQ,QAAQ;GAAc;GAAgB;EAAM;CAC/D;CAEA,OAAO,MAAM;AACf;;;AAIA,SAAS,UAAU,OAAmB,MAAyB;CAE7D,OADiB,MAAM,YAAY,YAErB,wEAAwE,KAAK,GAAG;AAEhG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stream-agent-turn-DYBpzMmq.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 { 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 = input.message ?? input.messages?.at(-1)?.content ?? 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 { type AgentProfile, canonicalCandidateDigest } from '@tangle-network/agent-interface'\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 { createSandboxToolPartState, mapSandboxEvent, mapSandboxToolEvent } 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'\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\n/** One prompt or an exact OpenAI-compatible conversation carried as the turn input. */\nexport type AgentTurnInput =\n | string\n | { readonly messages: ReadonlyArray<Readonly<Record<string, unknown>>> }\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 (typeof input === 'string') return input\n for (let index = input.messages.length - 1; index >= 0; index -= 1) {\n const message = input.messages[index]\n if (message?.role === 'user' && typeof message.content === 'string') return message.content\n }\n return 'structured agent turn'\n}\n\nfunction turnBackendInput(task: AgentTaskSpec, input: AgentTurnInput): AgentBackendInput {\n if (typeof input === 'string') return { task, message: input }\n return {\n task,\n messages: input.messages.map((message) => ({ ...message })) as AgentBackendInput['messages'],\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 session = await startTurnSession(backend, task, input, deadline.signal, label)\n yield {\n type: 'backend_start',\n task,\n session,\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, session, input, deadline.signal, acc)\n : backend.kind === 'executor'\n ? driveExecutorTurn(\n executor!,\n task,\n session,\n input,\n deadline.signal,\n acc,\n materializedModel(materialization, profile!),\n )\n : driveBoxTurn(\n backend.box,\n turnIntent(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 inner) {\n yield event\n throwIfAborted(deadline.signal)\n }\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 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 await executor?.teardown('brutalKill').catch(() => undefined)\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 prompt: string,\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(prompt, callOptions)\n const toolParts = cfg.preserveToolParts ? createSandboxToolPartState() : undefined\n for await (const event of stream) {\n if (cfg.onRawEvent) await cfg.onRawEvent(event)\n const terminalText = terminalTextFromSandboxEvent(event)\n if (terminalText !== undefined) acc.terminalText = terminalText\n if (toolParts) {\n for (const toolEvent of mapSandboxToolEvent(event, toolParts)) yield toolEvent\n }\n const mapped = mapSandboxEvent(event, { agentRunName })\n if (!mapped) continue\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\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 backend.stream(backendInput, context)) {\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 = typeof input === 'string' ? input : { messages: input.messages }\n const run = executor.execute(taskValue, signal)\n let result: ExecutorResult<unknown>\n if (isAsyncIterable(run)) {\n for await (const _usage of run) {\n throwIfAborted(signal)\n }\n result = executor.resultArtifact()\n } else {\n result = await run\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 isAsyncIterable(value: unknown): value is AsyncIterable<UsageEvent> {\n return typeof value === 'object' && value !== null && Symbol.asyncIterator in value\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: true })\n }\n return {\n signal: controller.signal,\n dispose: () => {\n if (timer) clearTimeout(timer)\n callerSignal?.removeEventListener('abort', onCallerAbort)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqBA,SAAgB,kBACd,SACA,aACA,UACgB;CAChB,MAAM,MAAM,OAAO;CACnB,OAAO;EACL,IAAI,eAAe,OAAO,WAAW;EACrC;EACA,QAAQ;EACR,WAAW;EACX,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