@tangle-network/agent-runtime 0.143.0 → 0.153.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +32 -0
  2. package/dist/{activation-mi8TgSLM.js → activation-Bbic0THc.js} +3 -3
  3. package/dist/{activation-mi8TgSLM.js.map → activation-Bbic0THc.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +3 -3
  6. package/dist/{analyst-loop-CvkmfhUB.js → analyst-loop-Bouu53-l.js} +2 -2
  7. package/dist/{analyst-loop-CvkmfhUB.js.map → analyst-loop-Bouu53-l.js.map} +1 -1
  8. package/dist/analyst-loop.js +1 -1
  9. package/dist/{authoring-DuyShLdw.js → authoring-CcVhJ1lP.js} +2 -2
  10. package/dist/{authoring-DuyShLdw.js.map → authoring-CcVhJ1lP.js.map} +1 -1
  11. package/dist/candidate-execution/index.js +4 -4
  12. package/dist/{candidate-execution-CD5PoNmC.js → candidate-execution-DYOB1juU.js} +4 -4
  13. package/dist/{candidate-execution-CD5PoNmC.js.map → candidate-execution-DYOB1juU.js.map} +1 -1
  14. package/dist/{conversation-1hNtDeMM.js → conversation-BHMwAiMo.js} +28 -13
  15. package/dist/{conversation-1hNtDeMM.js.map → conversation-BHMwAiMo.js.map} +1 -1
  16. package/dist/conversation.d.ts +1 -1
  17. package/dist/conversation.js +1 -1
  18. package/dist/durable.d.ts +102 -4
  19. package/dist/durable.js +259 -13
  20. package/dist/durable.js.map +1 -1
  21. package/dist/{environment-provider-DCBJ13VP.js → environment-provider-3eCszBEm.js} +218 -34
  22. package/dist/environment-provider-3eCszBEm.js.map +1 -0
  23. package/dist/{environment-provider-B8eZ85Ga.d.ts → environment-provider-DJG0yIYl.d.ts} +2 -2
  24. package/dist/environment-provider.d.ts +1 -1
  25. package/dist/environment-provider.js +1 -1
  26. package/dist/executable-spec-BUcUcEPk.js +73 -0
  27. package/dist/executable-spec-BUcUcEPk.js.map +1 -0
  28. package/dist/{graph-De_XEsfH.js → graph-CIh2HDmH.js} +4 -4
  29. package/dist/{graph-De_XEsfH.js.map → graph-CIh2HDmH.js.map} +1 -1
  30. package/dist/{improvement-cycle-Bi-Tf4QF.js → improvement-cycle-GCDSsTN6.js} +7 -7
  31. package/dist/{improvement-cycle-Bi-Tf4QF.js.map → improvement-cycle-GCDSsTN6.js.map} +1 -1
  32. package/dist/{index-C2caGomG.d.ts → index-DLn9WI-f.d.ts} +342 -505
  33. package/dist/{index-B8rKtH3U.d.ts → index-lMADJLfq.d.ts} +4 -4
  34. package/dist/{index-D4sLkOPY.d.ts → index-rxVSm9-z.d.ts} +6 -4
  35. package/dist/index.d.ts +7 -7
  36. package/dist/index.js +13 -13
  37. package/dist/intelligence.d.ts +4 -4
  38. package/dist/intelligence.js +6 -6
  39. package/dist/jsonl-file-CDfsCI5s.js +59 -0
  40. package/dist/jsonl-file-CDfsCI5s.js.map +1 -0
  41. package/dist/kernel.d.ts +6 -6
  42. package/dist/kernel.js +13 -13
  43. package/dist/{knowledge-CVE6Wk1i.js → knowledge-CaY53BW2.js} +10 -7
  44. package/dist/{knowledge-CVE6Wk1i.js.map → knowledge-CaY53BW2.js.map} +1 -1
  45. package/dist/knowledge.d.ts +1 -1
  46. package/dist/knowledge.js +1 -1
  47. package/dist/{loop-runner-bin-BoHdQqLm.d.ts → loop-runner-bin-BwPqxKhR.d.ts} +3 -3
  48. package/dist/{loop-runner-bin-DdaI1nLL.js → loop-runner-bin-Dw43kB_-.js} +4 -4
  49. package/dist/{loop-runner-bin-DdaI1nLL.js.map → loop-runner-bin-Dw43kB_-.js.map} +1 -1
  50. package/dist/loop-runner-bin.d.ts +1 -1
  51. package/dist/loop-runner-bin.js +1 -1
  52. package/dist/{materialization-P86EciBw.js → materialization-Dl9J8ek4.js} +279 -58
  53. package/dist/materialization-Dl9J8ek4.js.map +1 -0
  54. package/dist/mcp/bin.js +3 -3
  55. package/dist/mcp/index.d.ts +3 -3
  56. package/dist/mcp/index.js +6 -6
  57. package/dist/{model-policy-DgRJIJse.js → model-policy-Sw4ywhtL.js} +68 -6
  58. package/dist/model-policy-Sw4ywhtL.js.map +1 -0
  59. package/dist/{openai-tools-BiAWKjh6.js → openai-tools-C4XKuK4t.js} +2 -2
  60. package/dist/{openai-tools-BiAWKjh6.js.map → openai-tools-C4XKuK4t.js.map} +1 -1
  61. package/dist/{prepare-D3n7cA39.js → prepare-C5tI-H4o.js} +2 -2
  62. package/dist/{prepare-D3n7cA39.js.map → prepare-C5tI-H4o.js.map} +1 -1
  63. package/dist/primeintellect/index.d.ts +1 -1
  64. package/dist/profiles.js +1 -1
  65. package/dist/{protected-model-port-bq6bD9YX.js → protected-model-port-DHDKNeY7.js} +2 -2
  66. package/dist/{protected-model-port-bq6bD9YX.js.map → protected-model-port-DHDKNeY7.js.map} +1 -1
  67. package/dist/{redact-DexTuAiX.d.ts → redact-NAptmqKw.d.ts} +3 -3
  68. package/dist/{researcher-CiSY6Wzb.js → researcher-BMFFPwKb.js} +2 -2
  69. package/dist/{researcher-CiSY6Wzb.js.map → researcher-BMFFPwKb.js.map} +1 -1
  70. package/dist/{run-layout-Be_Z0dF8.js → run-layout-C2jgwsCq.js} +111 -6
  71. package/dist/run-layout-C2jgwsCq.js.map +1 -0
  72. package/dist/{runtime-BnqjbOGX.js → runtime--Jsq8JCC.js} +118 -97
  73. package/dist/runtime--Jsq8JCC.js.map +1 -0
  74. package/dist/{runtime-J6Toky8K.d.ts → runtime-B-5dp5Iz.d.ts} +214 -14
  75. package/dist/{sandbox-events-COwCWUVB.js → sandbox-events-BVjstFgb.js} +70 -3
  76. package/dist/sandbox-events-BVjstFgb.js.map +1 -0
  77. package/dist/{spawn-journal-D2HKUImC.js → spawn-journal-BLnveCRS.js} +34 -104
  78. package/dist/spawn-journal-BLnveCRS.js.map +1 -0
  79. package/dist/{stream-agent-turn-C1Vs_3B9.d.ts → stream-agent-turn-BGyszuPH.d.ts} +2 -2
  80. package/dist/{stream-agent-turn-CXRugSGO.js → stream-agent-turn-DYi8ymsU.js} +91 -16
  81. package/dist/stream-agent-turn-DYi8ymsU.js.map +1 -0
  82. package/dist/{structural-rollout-CJgj9YXH.js → structural-rollout-D7V-HgXJ.js} +30 -13
  83. package/dist/structural-rollout-D7V-HgXJ.js.map +1 -0
  84. package/dist/{supervise-hCgG6ROJ.js → supervise-k_8VOASb.js} +2499 -2171
  85. package/dist/supervise-k_8VOASb.js.map +1 -0
  86. package/dist/{supervisor-s8SfZYbW.js → supervisor-CMZsJ7Wn.js} +673 -446
  87. package/dist/supervisor-CMZsJ7Wn.js.map +1 -0
  88. package/dist/testing.d.ts +2 -2
  89. package/dist/testing.js +12 -12
  90. package/dist/{top-app-BMOSKK06.js → top-app-3rYfFPTW.js} +192 -147
  91. package/dist/top-app-3rYfFPTW.js.map +1 -0
  92. package/dist/tui/bin.js +1 -1
  93. package/dist/tui/index.d.ts +32 -5
  94. package/dist/tui/index.js +1 -1
  95. package/dist/{types-Df9vulGc.d.ts → types-BPQhQRrC.d.ts} +507 -10
  96. package/dist/{util-C1bv6yog.js → util-D6ZEuBMi.js} +71 -2
  97. package/dist/util-D6ZEuBMi.js.map +1 -0
  98. package/dist/{workspace-archive-C52LjkeN.js → workspace-archive-B9ui4rrR.js} +2 -2
  99. package/dist/{workspace-archive-C52LjkeN.js.map → workspace-archive-B9ui4rrR.js.map} +1 -1
  100. package/package.json +7 -7
  101. package/dist/environment-provider-DCBJ13VP.js.map +0 -1
  102. package/dist/materialization-P86EciBw.js.map +0 -1
  103. package/dist/model-policy-DgRJIJse.js.map +0 -1
  104. package/dist/retained-run-binding-Dp2e8xne.js +0 -268
  105. package/dist/retained-run-binding-Dp2e8xne.js.map +0 -1
  106. package/dist/run-layout-Be_Z0dF8.js.map +0 -1
  107. package/dist/runtime-BnqjbOGX.js.map +0 -1
  108. package/dist/sandbox-events-COwCWUVB.js.map +0 -1
  109. package/dist/spawn-journal-D2HKUImC.js.map +0 -1
  110. package/dist/stream-agent-turn-CXRugSGO.js.map +0 -1
  111. package/dist/structural-rollout-CJgj9YXH.js.map +0 -1
  112. package/dist/supervise-hCgG6ROJ.js.map +0 -1
  113. package/dist/supervisor-s8SfZYbW.js.map +0 -1
  114. package/dist/top-app-BMOSKK06.js.map +0 -1
  115. package/dist/util-C1bv6yog.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"durable.js","names":[],"sources":["../src/durable/chat-engine.ts","../src/durable/execution-handle.ts","../src/durable/observer-journal.ts","../src/durable/observer-projection.ts","../src/durable/supervise-pursuit.ts","../src/durable/supervision-discovery.ts"],"sourcesContent":["/**\n * `handleChatTurn` is a framework-neutral chat-turn HTTP orchestrator.\n * Owns the NDJSON `ChatStreamEvent` line protocol, the `session.run.*`\n * lifecycle vocabulary, and the persist / post-process / trace-flush\n * hook order. Returns a `ReadableStream` body the product hands to its\n * platform `Response`.\n *\n * Sandbox owns long-running execution, reconnect, and replay.\n * The producer this engine wraps already speaks that protocol; this\n * engine frames the events and orders product callbacks.\n *\n * Hooks (`ChatTurnHooks`):\n * - `produce`: build the backend event stream\n * - `persistAssistantMessage`: write the assistant turn to the product DB\n * - `onTurnComplete?`: post-process proposals, citations, and similar work\n * - `onEvent?`: send each event to another consumer\n * - `transformFinalText?`: transform text before persistence\n * - `traceFlush?`: let `waitUntil` keep the worker alive for export\n *\n * Framework neutrality: takes already-resolved values (`identity` tuple,\n * a `waitUntil`), never a `Request` or a `Context`. The product's thin\n * route adapter does auth + parse + access-control, then calls\n * `handleChatTurn(...)` and returns `result.body` as its platform `Response`.\n */\n\n/** The NDJSON line protocol every product chat client already speaks. */\nexport interface ChatStreamEvent {\n type: string\n data?: Record<string, unknown>\n}\n\n/** Identity of a chat turn. `tenantId` is the workspace id for workspace-\n * scoped products and the user id for session-scoped products. */\nexport interface ChatTurnIdentity {\n tenantId: string\n /** Thread / session id. */\n sessionId: string\n userId: string\n /** Monotonic 0-based turn index within the session. */\n turnIndex: number\n}\n\n/** The live side of a turn returned by the product's `produce` hook. */\nexport interface ChatTurnProducer<TEvent extends ChatStreamEvent = ChatStreamEvent> {\n /** The turn's event stream. Forwarded verbatim to the caller. */\n stream: AsyncGenerator<TEvent, void, unknown>\n /** The turn's final assistant text. Read once, after `stream` drains. */\n finalText(): string\n}\n\n/** Product callbacks invoked while one chat turn runs. */\nexport interface ChatTurnHooks {\n /** Build the backend stream. The engine forwards events verbatim and\n * reads `finalText()` once the stream drains. */\n produce(): ChatTurnProducer\n /** Persist the assistant message to the product's own store. Called\n * once, after drain, with the assembled (transform-applied) text. */\n persistAssistantMessage(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional post-processing for proposals, citations, or credit metering.\n * Errors are logged without failing a turn that already streamed. */\n onTurnComplete?(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional per-event side channel, such as a Durable Object broadcast.\n * Runs for every emitted event, including the lifecycle envelope.\n * Errors are logged without breaking the chat stream. */\n onEvent?(event: ChatStreamEvent): void | Promise<void>\n /** Optional pre-persist transform of the final text (e.g. PII\n * redaction). Affects only what is persisted; the live stream is\n * never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Optional trace flush. Handed to `waitUntil` so the worker stays alive\n * until export completes. */\n traceFlush?(): Promise<void>\n}\n\n/** Inputs for one streamed product chat turn. */\nexport interface RunChatTurnInput {\n identity: ChatTurnIdentity\n hooks: ChatTurnHooks\n /** Worker liveness hook. When omitted, trace flush is awaited inline\n * before the stream closes. */\n waitUntil?: (p: Promise<unknown>) => void\n /** Structured logger for swallowed hook errors. Defaults to\n * `console.error` so failures surface without product wiring. */\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** HTTP response values returned for one chat turn. */\nexport interface ChatTurnResult {\n /** NDJSON body to return as the platform `Response` body. */\n body: ReadableStream<Uint8Array>\n /** Content type for the response. */\n contentType: 'application/x-ndjson'\n}\n\nconst encoder = new TextEncoder()\n\nfunction encodeLine(event: ChatStreamEvent): Uint8Array {\n return encoder.encode(`${JSON.stringify(event)}\\n`)\n}\n\nfunction defaultLog(message: string, meta?: Record<string, unknown>): void {\n if (meta) console.error(message, meta)\n else console.error(message)\n}\n\n/**\n * Run one chat turn. Returns immediately with a `ReadableStream` body;\n * execution starts while the stream is constructed. Backend\n * failures surface as `error` + `session.run.failed` events.\n */\nexport function handleChatTurn(input: RunChatTurnInput): ChatTurnResult {\n const log = input.log ?? defaultLog\n const { identity, hooks } = input\n\n const body = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n const emit = async (event: ChatStreamEvent): Promise<void> => {\n controller.enqueue(encodeLine(event))\n if (hooks.onEvent) {\n try {\n await hooks.onEvent(event)\n } catch (err) {\n log('[chat-engine] onEvent hook threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n }\n\n try {\n await emit({\n type: 'session.run.started',\n data: {\n sessionId: identity.sessionId,\n tenantId: identity.tenantId,\n turnIndex: identity.turnIndex,\n },\n })\n\n const producer = hooks.produce()\n for await (const event of producer.stream) {\n await emit(event)\n }\n const rawFinal = producer.finalText()\n const finalText = hooks.transformFinalText\n ? await hooks.transformFinalText(rawFinal)\n : rawFinal\n\n await hooks.persistAssistantMessage({ identity, finalText })\n if (hooks.onTurnComplete) {\n try {\n await hooks.onTurnComplete({ identity, finalText })\n } catch (err) {\n log('[chat-engine] onTurnComplete threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n await emit({\n type: 'session.run.completed',\n data: { sessionId: identity.sessionId },\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n log('[chat-engine] turn failed', { error: message })\n await emit({ type: 'error', data: { message } })\n await emit({\n type: 'session.run.failed',\n data: { sessionId: identity.sessionId, message },\n })\n } finally {\n if (hooks.traceFlush) {\n const flush = hooks.traceFlush().catch((err) =>\n log('[chat-engine] traceFlush threw', {\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n if (input.waitUntil) input.waitUntil(flush)\n else await flush\n }\n controller.close()\n }\n },\n })\n\n return { body, contentType: 'application/x-ndjson' }\n}\n","/**\n * Derive a stable execution id from the run identity.\n * The same `(projectId, sessionId, turnIndex)` tuple yields the same id.\n *\n * Use the result as both `PromptOptions.executionId` and\n * `PromptOptions.turnId` on the first dispatch.\n * The execution id addresses the server-side execution for reconnect and\n * replay; the turn id makes a repeated dispatch idempotent.\n * An execution id alone does not make a repeated POST idempotent.\n *\n * Format is readable, not hashed: operators grepping orchestrator logs\n * for `gtm-agent:thread-abc:3` find the run without translating an\n * opaque id. Components are URL-encoded so delimiters inside caller ids\n * cannot collapse distinct tuples. The final id is limited to the\n * orchestrator replay route's 256-byte maximum. Execution ids are not a\n * secrecy boundary.\n *\n * Wire integration:\n * - Initial dispatch: pass the result as `executionId` and `turnId`.\n * - Stream replay: pass it as `executionId` with `lastEventId`.\n *\n * @throws `TypeError` when either string id is blank.\n * @throws `RangeError` when `turnIndex` is invalid or the result exceeds 256 bytes.\n */\nexport function deriveExecutionId(input: {\n projectId: string\n sessionId: string\n turnIndex: number\n}): string {\n if (input.projectId.trim().length === 0) {\n throw new TypeError('projectId must be a non-empty string')\n }\n if (input.sessionId.trim().length === 0) {\n throw new TypeError('sessionId must be a non-empty string')\n }\n if (!Number.isSafeInteger(input.turnIndex) || input.turnIndex < 0) {\n throw new RangeError('turnIndex must be a non-negative safe integer')\n }\n\n const executionId = [\n encodeURIComponent(input.projectId),\n encodeURIComponent(input.sessionId),\n String(input.turnIndex),\n ].join(':')\n if (executionId.length > 256) {\n throw new RangeError('derived execution id must not exceed 256 bytes')\n }\n return executionId\n}\n","import { createHash } from 'node:crypto'\nimport { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport {\n type RuntimeDecisionPoint,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { parseCommittedJsonLines, prepareJsonlAppend, writeAllBytes } from './jsonl-file'\n\nexport type ObserverRecordKind = 'event' | 'decision'\n\n/**\n * One immutable record in the observer plane. `sequence` is journal order, not\n * execution order; causal/runtime order remains available on the underlying event.\n * `previousDigest` + `digest` make deletion, reordering, or mutation detectable.\n */\nexport interface ObserverRecord {\n readonly schemaVersion: 1\n readonly pursuitId: string\n readonly sequence: number\n readonly kind: ObserverRecordKind\n readonly observedAt: number\n readonly previousDigest?: string\n readonly event?: RuntimeHookEvent\n readonly decision?: RuntimeDecisionPoint\n readonly digest: string\n}\n\nexport interface ObserverJournal {\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord>\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord>\n read(): Promise<readonly ObserverRecord[]>\n hooks(): RuntimeHooks\n}\n\ntype UnsignedObserverRecord = Omit<ObserverRecord, 'digest'>\n\n/**\n * Durable, append-only third-person history for one concrete Runtime execution.\n * It consumes Runtime's existing hook stream and does not participate in execution\n * decisions. A broken observer therefore cannot change what an agent is allowed to do.\n *\n * The write discipline deliberately matches `FileSpawnJournal`: serialized appends,\n * torn-tail recovery, short-write handling, and fsync before acknowledgement. One\n * execution owns one journal file; higher-level pursuit aggregation joins isolated\n * journals by `pursuitId` instead of making independent processes share a write head.\n */\nexport class FileObserverJournal implements ObserverJournal {\n readonly path: string\n readonly pursuitId: string\n private tail: Promise<void> = Promise.resolve()\n private initialized = false\n private sequence = 0\n private previousDigest: string | undefined\n private appendFailure: Error | undefined\n\n constructor(path: string, pursuitId: string) {\n const stableId = pursuitId.trim()\n if (stableId.length === 0) {\n throw new TypeError('FileObserverJournal: pursuitId must be non-empty')\n }\n this.path = resolve(path)\n this.pursuitId = stableId\n }\n\n hooks(): RuntimeHooks {\n return withPursuitContext(this.pursuitId, {\n onEvent: (event) => this.appendEvent(event).then(() => undefined),\n onDecisionPoint: (point) => this.appendDecision(point).then(() => undefined),\n })\n }\n\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord> {\n return this.enqueue('event', event)\n }\n\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord> {\n return this.enqueue('decision', point)\n }\n\n async read(): Promise<readonly ObserverRecord[]> {\n await this.tail\n this.assertComplete()\n let text: string\n try {\n text = await readFile(this.path, 'utf8')\n } catch (error) {\n if (isNoEnt(error)) return []\n throw error\n }\n return verifyObserverRecords(\n parseCommittedJsonLines<ObserverRecord>(text, this.path),\n this.pursuitId,\n )\n }\n\n private enqueue(\n kind: ObserverRecordKind,\n value: RuntimeHookEvent | RuntimeDecisionPoint,\n ): Promise<ObserverRecord> {\n if (value.pursuitId !== this.pursuitId) {\n return Promise.reject(\n new Error(\n `FileObserverJournal: ${kind} pursuitId ${String(value.pursuitId)} does not match ${this.pursuitId}`,\n ),\n )\n }\n\n let result: ObserverRecord | undefined\n const operation = this.tail.then(async () => {\n this.assertComplete()\n try {\n await this.initialize()\n } catch (error) {\n this.appendFailure ??= toError(error)\n throw error\n }\n\n const unsigned: UnsignedObserverRecord = {\n schemaVersion: 1,\n pursuitId: this.pursuitId,\n sequence: this.sequence + 1,\n kind,\n observedAt: Date.now(),\n ...(this.previousDigest ? { previousDigest: this.previousDigest } : {}),\n ...(kind === 'event'\n ? { event: value as RuntimeHookEvent }\n : { decision: value as RuntimeDecisionPoint }),\n }\n const record: ObserverRecord = Object.freeze({\n ...unsigned,\n digest: observerRecordDigest(unsigned),\n })\n try {\n await this.writeRecord(record)\n } catch (error) {\n this.appendFailure ??= toError(error)\n throw error\n }\n this.sequence = record.sequence\n this.previousDigest = record.digest\n result = record\n })\n this.tail = operation.then(\n () => undefined,\n () => undefined,\n )\n return operation.then(() => {\n if (!result) throw new Error('FileObserverJournal: append completed without a record')\n return result\n })\n }\n\n private async initialize(): Promise<void> {\n if (this.initialized) return\n const records = await this.readExistingUnsafe()\n const verified = verifyObserverRecords(records, this.pursuitId)\n const tail = verified.at(-1)\n this.sequence = tail?.sequence ?? 0\n this.previousDigest = tail?.digest\n // Only latch after recovery + verification succeed. A transient read error or\n // corruption must never leave an instance pretending it initialized cleanly.\n this.initialized = true\n }\n\n private async readExistingUnsafe(): Promise<ObserverRecord[]> {\n let text: string\n try {\n text = await readFile(this.path, 'utf8')\n } catch (error) {\n if (isNoEnt(error)) return []\n throw error\n }\n return parseCommittedJsonLines<ObserverRecord>(text, this.path)\n }\n\n private async writeRecord(record: ObserverRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const needsSeparator = await prepareJsonlAppend(this.path)\n const handle = await fs.open(this.path, 'a')\n try {\n await writeAllBytes(handle, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await handle.sync()\n } finally {\n await handle.close()\n }\n }\n\n private assertComplete(): void {\n if (!this.appendFailure) return\n throw new Error(\n 'FileObserverJournal: a prior durable append failed; observer completeness is unknown',\n { cause: this.appendFailure },\n )\n }\n}\n\n/** Verify identity, monotonic sequence, payload shape, and the complete digest chain. */\nexport function verifyObserverRecords(\n records: readonly ObserverRecord[],\n pursuitId?: string,\n): readonly ObserverRecord[] {\n let previousDigest: string | undefined\n let expectedSequence = 1\n for (const record of records) {\n if (record.schemaVersion !== 1) throw new Error('observer journal: unsupported schemaVersion')\n if (pursuitId !== undefined && record.pursuitId !== pursuitId) {\n throw new Error(`observer journal: pursuit identity mismatch at sequence ${record.sequence}`)\n }\n if (record.sequence !== expectedSequence) {\n throw new Error(\n `observer journal: non-contiguous sequence ${record.sequence}; expected ${expectedSequence}`,\n )\n }\n if (record.previousDigest !== previousDigest) {\n throw new Error(`observer journal: digest-chain break at sequence ${record.sequence}`)\n }\n if ((record.kind === 'event') === (record.event === undefined)) {\n throw new Error(`observer journal: invalid event payload at sequence ${record.sequence}`)\n }\n if ((record.kind === 'decision') === (record.decision === undefined)) {\n throw new Error(`observer journal: invalid decision payload at sequence ${record.sequence}`)\n }\n if (record.event !== undefined && record.event.pursuitId !== record.pursuitId) {\n throw new Error(\n `observer journal: nested event pursuit mismatch at sequence ${record.sequence}`,\n )\n }\n if (record.decision !== undefined && record.decision.pursuitId !== record.pursuitId) {\n throw new Error(\n `observer journal: nested decision pursuit mismatch at sequence ${record.sequence}`,\n )\n }\n const { digest, ...unsigned } = record\n const expected = observerRecordDigest(unsigned)\n if (digest !== expected) {\n throw new Error(`observer journal: digest mismatch at sequence ${record.sequence}`)\n }\n previousDigest = digest\n expectedSequence += 1\n }\n return Object.freeze([...records])\n}\n\n/** Compute the canonical SHA-256 digest for an unsigned observer record. */\nexport function observerRecordDigest(record: Omit<ObserverRecord, 'digest'>): string {\n return createHash('sha256').update(JSON.stringify(record)).digest('hex')\n}\n\n/** Build the canonical durable observer hook in one call. */\nexport function createFileObserverHooks(\n path: string,\n pursuitId: string,\n): {\n readonly journal: FileObserverJournal\n readonly hooks: RuntimeHooks\n} {\n const journal = new FileObserverJournal(path, pursuitId)\n return { journal, hooks: journal.hooks() }\n}\n\nfunction isNoEnt(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n","import type { RuntimeDecisionKind, RuntimeHookTarget } from '../runtime-hooks'\nimport { type ObserverRecord, verifyObserverRecords } from './observer-journal'\n\nexport type PursuitRunStatus = 'running' | 'done' | 'failed'\n\nexport interface PursuitRunProjection {\n readonly runId: string\n readonly status: PursuitRunStatus\n readonly settledAt?: number\n readonly error?: string\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly decisionCount: number\n readonly targets: Readonly<Record<string, number>>\n readonly decisions: Readonly<Record<string, number>>\n}\n\nexport type PursuitNodeStatus = 'running' | 'done' | 'down'\n\nexport interface PursuitNodeProjection {\n readonly id: string\n readonly parentId?: string\n /** Node ids are scoped to this concrete Runtime tree; `(runId,id)` is identity. */\n readonly runId: string\n readonly label?: string\n readonly runtime?: string\n readonly depth?: number\n readonly assignmentId?: string\n readonly identity?: unknown\n readonly budget?: unknown\n readonly status: PursuitNodeStatus\n readonly settledAt?: number\n readonly spent?: unknown\n readonly outRef?: string\n readonly score?: number\n readonly valid?: boolean\n readonly reason?: string\n readonly infra?: boolean\n readonly wait?: unknown\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n}\n\nexport interface PursuitProjection {\n readonly pursuitId: string\n /** Number of records in this concrete execution journal. */\n readonly sequence: number\n /** Digest-chain tip for this concrete execution journal. */\n readonly chainTip: string\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly runs: readonly PursuitRunProjection[]\n readonly nodes: readonly PursuitNodeProjection[]\n readonly eventCount: number\n readonly decisionCount: number\n}\n\ntype MutableRun = {\n runId: string\n status: PursuitRunStatus\n settledAt?: number\n error?: string\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n decisionCount: number\n targets: Record<string, number>\n decisions: Record<string, number>\n}\n\ntype MutableNode = {\n id: string\n parentId?: string\n runId: string\n label?: string\n runtime?: string\n depth?: number\n assignmentId?: string\n identity?: unknown\n budget?: unknown\n status: PursuitNodeStatus\n settledAt?: number\n spent?: unknown\n outRef?: string\n score?: number\n valid?: boolean\n reason?: string\n infra?: boolean\n wait?: unknown\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n}\n\n/**\n * Fold one append-only execution journal into a deterministic operator projection.\n *\n * This is intentionally a READ model, not another state machine: it does not own\n * execution, cannot steer agents, and can be rebuilt from the journal at any time.\n * Projection verifies the complete hash chain first, so an operator view can never\n * silently render a mutated or reordered observer history as trustworthy state.\n *\n * Topology comes only from Runtime's canonical `agent.spawn` facts. Terminal node\n * state comes only from `agent.child`; concrete run state comes only from the root\n * `agent.run` lifecycle emitted by `supervisePursuit`. Node identity is scoped to the\n * concrete Runtime run so independent trees may both contain `root:s0` without aliasing.\n */\nexport function projectPursuit(records: readonly ObserverRecord[]): PursuitProjection {\n if (records.length === 0) {\n throw new TypeError('projectPursuit: at least one observer record is required')\n }\n const pursuitId = records[0]!.pursuitId\n const verified = verifyObserverRecords(records, pursuitId)\n const runs = new Map<string, MutableRun>()\n const nodes = new Map<string, MutableNode>()\n let eventCount = 0\n let decisionCount = 0\n\n for (const record of verified) {\n const observed = record.event ?? record.decision\n if (!observed) throw new Error(`projectPursuit: record ${record.sequence} has no observation`)\n const run = getRun(runs, observed.runId, record)\n run.lastSequence = record.sequence\n run.lastObservedAt = record.observedAt\n\n if (record.event) {\n eventCount += 1\n run.eventCount += 1\n increment(run.targets, record.event.target)\n projectRunActivity(run, record)\n projectSpawnNode(nodes, record)\n projectNodeActivity(nodes, record)\n } else if (record.decision) {\n decisionCount += 1\n run.decisionCount += 1\n increment(run.decisions, record.decision.kind)\n }\n }\n\n const first = verified[0]!\n const last = verified.at(-1)!\n return Object.freeze({\n pursuitId,\n sequence: last.sequence,\n chainTip: last.digest,\n firstObservedAt: first.observedAt,\n lastObservedAt: last.observedAt,\n runs: Object.freeze(\n [...runs.values()]\n .sort((a, b) => a.firstSequence - b.firstSequence || a.runId.localeCompare(b.runId))\n .map(freezeRun),\n ),\n nodes: Object.freeze(\n [...nodes.values()]\n .sort(\n (a, b) =>\n a.firstSequence - b.firstSequence ||\n a.runId.localeCompare(b.runId) ||\n a.id.localeCompare(b.id),\n )\n .map(freezeNode),\n ),\n eventCount,\n decisionCount,\n })\n}\n\nfunction getRun(runs: Map<string, MutableRun>, runId: string, record: ObserverRecord): MutableRun {\n const existing = runs.get(runId)\n if (existing) return existing\n const created: MutableRun = {\n runId,\n status: 'running',\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 0,\n decisionCount: 0,\n targets: {},\n decisions: {},\n }\n runs.set(runId, created)\n return created\n}\n\nfunction projectRunActivity(run: MutableRun, record: ObserverRecord): void {\n const event = record.event\n if (event?.target !== 'agent.run') return\n const payload = objectRecord(event.payload)\n const status = stringField(payload, 'status')\n if (event.phase === 'after' || status === 'done') {\n run.status = 'done'\n run.settledAt = record.observedAt\n return\n }\n if (event.phase !== 'error' && status !== 'failed') return\n run.status = 'failed'\n run.settledAt = record.observedAt\n const error = stringField(payload, 'error')\n if (error) run.error = error\n}\n\nfunction nodeKey(runId: string, nodeId: string): string {\n return `${runId}\\u0000${nodeId}`\n}\n\nfunction projectSpawnNode(nodes: Map<string, MutableNode>, record: ObserverRecord): void {\n const event = record.event\n if (event?.target !== 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const childId = stringField(payload, 'childId')\n if (!childId) return\n const key = nodeKey(event.runId, childId)\n const existing = nodes.get(key)\n if (existing) {\n existing.lastSequence = record.sequence\n existing.lastObservedAt = record.observedAt\n existing.eventCount += 1\n return\n }\n const label = stringField(payload, 'label')\n const runtime = stringField(payload, 'runtime')\n const depth = numberField(payload, 'depth')\n const assignmentId = stringField(payload, 'assignmentId')\n nodes.set(key, {\n id: childId,\n ...(event.parentId ? { parentId: event.parentId } : {}),\n runId: event.runId,\n ...(label ? { label } : {}),\n ...(runtime ? { runtime } : {}),\n ...(depth !== undefined ? { depth } : {}),\n ...(assignmentId ? { assignmentId } : {}),\n ...(payload && Object.hasOwn(payload, 'identity') ? { identity: payload.identity } : {}),\n ...(payload && Object.hasOwn(payload, 'budget') ? { budget: payload.budget } : {}),\n status: 'running',\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 1,\n })\n}\n\nfunction projectNodeActivity(nodes: Map<string, MutableNode>, record: ObserverRecord): void {\n const event = record.event\n if (event === undefined) return\n if (event.target === 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const nodeId =\n stringField(payload, 'childId') ??\n stringField(payload, 'nodeId') ??\n stringField(payload, 'workerId')\n if (!nodeId) return\n const node = nodes.get(nodeKey(event.runId, nodeId))\n if (!node) return\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n node.eventCount += 1\n\n if (event.target !== 'agent.child') return\n const status = stringField(payload, 'status')\n if (status !== 'done' && status !== 'down') return\n node.status = status\n node.settledAt = record.observedAt\n if (payload && Object.hasOwn(payload, 'spent')) node.spent = payload.spent\n const outRef = stringField(payload, 'outRef')\n if (outRef) node.outRef = outRef\n const score = numberField(payload, 'score')\n if (score !== undefined) node.score = score\n const valid = booleanField(payload, 'valid')\n if (valid !== undefined) node.valid = valid\n const reason = stringField(payload, 'reason')\n if (reason) node.reason = reason\n const infra = booleanField(payload, 'infra')\n if (infra !== undefined) node.infra = infra\n if (payload && Object.hasOwn(payload, 'wait')) node.wait = payload.wait\n}\n\nfunction freezeRun(run: MutableRun): PursuitRunProjection {\n return Object.freeze({\n ...run,\n targets: Object.freeze({ ...run.targets }),\n decisions: Object.freeze({ ...run.decisions }),\n })\n}\n\nfunction freezeNode(node: MutableNode): PursuitNodeProjection {\n return Object.freeze({ ...node })\n}\n\nfunction increment(\n target: Record<string, number>,\n key: RuntimeHookTarget | RuntimeDecisionKind,\n): void {\n target[key] = (target[key] ?? 0) + 1\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\nfunction stringField(value: Record<string, unknown> | undefined, key: string): string | undefined {\n const field = value?.[key]\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction numberField(value: Record<string, unknown> | undefined, key: string): number | undefined {\n const field = value?.[key]\n return typeof field === 'number' && Number.isFinite(field) ? field : undefined\n}\n\nfunction booleanField(\n value: Record<string, unknown> | undefined,\n key: string,\n): boolean | undefined {\n const field = value?.[key]\n return typeof field === 'boolean' ? field : undefined\n}\n","import { resolve } from 'node:path'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport { composeRuntimeHooks, type RuntimeHookEvent, withPursuitContext } from '../runtime-hooks'\nimport { createFileObserverHooks } from './observer-journal'\nimport { type PursuitProjection, projectPursuit } from './observer-projection'\n\nexport interface SupervisePursuitOptions extends SuperviseOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /**\n * One concrete Runtime execution owns one durable directory and observer journal.\n * A pursuit spanning several runs reuses `pursuitId` across distinct `runDir`s;\n * Intelligence joins those isolated projections without a shared write head.\n */\n readonly runDir: string\n}\n\nexport interface SupervisedPursuitResult<Result> {\n readonly result: Result\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n}\n\n/** A failed Runtime execution whose complete third-person projection was retained. */\nexport class SupervisePursuitError extends Error {\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n\n constructor(cause: unknown, pursuit: PursuitProjection, observerPath: string) {\n super(`supervisePursuit: ${errorMessage(cause)}`, { cause })\n this.name = 'SupervisePursuitError'\n this.pursuit = pursuit\n this.observerPath = observerPath\n }\n}\n\n/**\n * One-call durable pursuit execution over the canonical `supervise()` kernel.\n *\n * This is an adapter, not a second executor: it composes a durable third-person\n * observer into Runtime's existing recursive hook stream and then rebuilds the\n * operator projection after the same `supervise()` call settles. Agents never\n * receive the observer path or projection and their behavior does not depend on it.\n *\n * Every concrete execution writes only inside its own `runDir`. Cross-run pursuit\n * aggregation is therefore lock-free at the observer layer: reuse `pursuitId` across\n * run directories and let Intelligence join the independently verified projections.\n */\nexport async function supervisePursuit(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n): Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>> {\n const pursuitId = opts.pursuitId.trim()\n if (pursuitId.length === 0) {\n throw new TypeError('supervisePursuit: pursuitId must be non-empty')\n }\n const runDir = opts.runDir.trim()\n if (runDir.length === 0) {\n throw new TypeError('supervisePursuit: runDir must be non-empty')\n }\n\n const observerPath = resolve(runDir, 'observer.jsonl')\n const { pursuitId: _pursuitId, hooks, ...superviseOptions } = opts\n const observer = createFileObserverHooks(observerPath, pursuitId)\n const runId = superviseOptions.runId ?? 'supervise'\n const now = superviseOptions.now ?? Date.now\n\n // Root lifecycle is an observer-plane fact, not something the manager has to\n // narrate about itself. This also makes a zero-spawn/single-agent run observable.\n await observer.journal.appendEvent(rootEvent(pursuitId, runId, 'before', now()))\n\n try {\n const result = await supervise(profile, task, {\n ...superviseOptions,\n // The observer runs first so a caller hook that throws cannot prevent the\n // canonical lifecycle fact from entering the durable journal.\n hooks: withPursuitContext(pursuitId, composeRuntimeHooks(observer.hooks, hooks)),\n })\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'after', now(), { status: 'done' }),\n )\n return Object.freeze({\n result,\n pursuit: projectPursuit(await observer.journal.read()),\n observerPath,\n })\n } catch (error) {\n let pursuit: PursuitProjection | undefined\n let observerError: unknown\n try {\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'error', now(), {\n status: 'failed',\n error: errorMessage(error),\n }),\n )\n pursuit = projectPursuit(await observer.journal.read())\n } catch (failure) {\n observerError = failure\n }\n if (observerError !== undefined || pursuit === undefined) {\n const causes = observerError === undefined ? [error] : [error, observerError]\n throw new Error(\n 'supervisePursuit: Runtime failed and durable observer completeness could not be proven',\n { cause: new AggregateError(causes) },\n )\n }\n throw new SupervisePursuitError(error, pursuit, observerPath)\n }\n}\n\nfunction rootEvent(\n pursuitId: string,\n runId: string,\n phase: 'before' | 'after' | 'error',\n timestamp: number,\n payload?: Record<string, unknown>,\n): RuntimeHookEvent {\n return Object.freeze({\n id: `${runId}:pursuit:${phase}:${timestamp}`,\n pursuitId,\n runId,\n target: 'agent.run',\n phase,\n timestamp,\n ...(payload ? { payload: Object.freeze({ ...payload }) } : {}),\n })\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import { resolve } from 'node:path'\nimport type { NodeId } from '../runtime/supervise/types'\nimport { parseCommittedJsonLines } from './jsonl-file'\n\nexport interface DurableCoordinationStreamIdentity {\n readonly runId: string\n /** Exact owner ids present in the side-log, sorted for deterministic display. */\n readonly ownerIds: readonly string[]\n /** Records written before owner-scoped coordination identities were introduced. */\n readonly unscopedRecords: number\n readonly recordCount: number\n}\n\n/**\n * Identities discoverable from one `supervise({ runDir })` directory without\n * already knowing the root node or coordination run id stored inside it.\n */\nexport interface DurableSupervisionDiscovery {\n readonly runDir: string\n readonly spawnJournalPath: string\n readonly coordinationLogPath: string\n readonly roots: readonly NodeId[]\n readonly coordinationStreams: readonly DurableCoordinationStreamIdentity[]\n}\n\ntype SpawnJournalIdentityRecord = {\n readonly kind?: unknown\n readonly root?: unknown\n readonly event?: unknown\n}\n\ntype CoordinationIdentityRecord = {\n readonly runId?: unknown\n readonly ownerId?: unknown\n}\n\n/**\n * Discover the stable identities recorded by Runtime's durable supervision\n * files. This is the developer-facing first step before calling\n * `FileSpawnJournal.loadTree(root)`, `loadSpawnForest(journal, root)`, or\n * `FileCoordinationLog.load(runId, ownerId)`.\n *\n * Missing files produce empty collections. A malformed committed JSONL record\n * still fails loud through the same parser used by the runtime; a torn final\n * append is ignored because it was never acknowledged as committed.\n */\nexport async function discoverDurableSupervisionRun(\n runDir: string,\n): Promise<DurableSupervisionDiscovery> {\n if (typeof runDir !== 'string' || runDir.trim().length === 0) {\n throw new TypeError('discoverDurableSupervisionRun: runDir must be a non-empty string')\n }\n\n const canonicalRunDir = resolve(runDir)\n const spawnJournalPath = `${canonicalRunDir}/spawn-journal.jsonl`\n const coordinationLogPath = `${canonicalRunDir}/coordination-log.jsonl`\n const [spawnText, coordinationText] = await Promise.all([\n readOptionalText(spawnJournalPath),\n readOptionalText(coordinationLogPath),\n ])\n\n const allRoots = new Set<NodeId>()\n const nestedRoots = new Set<NodeId>()\n if (spawnText !== undefined) {\n for (const record of parseCommittedJsonLines<SpawnJournalIdentityRecord>(\n spawnText,\n spawnJournalPath,\n )) {\n if (record.kind === 'begin') {\n if (typeof record.root !== 'string' || record.root.length === 0) {\n throw new Error(`${spawnJournalPath}: begin record has no non-empty string root identity`)\n }\n allRoots.add(record.root as NodeId)\n continue\n }\n if (record.kind !== 'event') continue\n const event = record.event\n if (!isRecord(event) || event.kind !== 'spawned') continue\n if (!Object.hasOwn(event, 'ownedTreeRoot')) continue\n if (typeof event.ownedTreeRoot !== 'string' || event.ownedTreeRoot.length === 0) {\n throw new Error(\n `${spawnJournalPath}: spawned event ownedTreeRoot must be a non-empty string when present`,\n )\n }\n nestedRoots.add(event.ownedTreeRoot as NodeId)\n }\n }\n\n const streams = new Map<\n string,\n { owners: Set<string>; unscopedRecords: number; recordCount: number }\n >()\n if (coordinationText !== undefined) {\n for (const record of parseCommittedJsonLines<CoordinationIdentityRecord>(\n coordinationText,\n coordinationLogPath,\n )) {\n if (typeof record.runId !== 'string' || record.runId.length === 0) {\n throw new Error(`${coordinationLogPath}: record has no non-empty string runId identity`)\n }\n const stream = streams.get(record.runId) ?? {\n owners: new Set<string>(),\n unscopedRecords: 0,\n recordCount: 0,\n }\n stream.recordCount += 1\n if (record.ownerId === undefined) {\n stream.unscopedRecords += 1\n } else if (typeof record.ownerId === 'string' && record.ownerId.length > 0) {\n stream.owners.add(record.ownerId)\n } else {\n throw new Error(`${coordinationLogPath}: ownerId must be a non-empty string when present`)\n }\n streams.set(record.runId, stream)\n }\n }\n\n const coordinationStreams = [...streams.entries()]\n .sort(([left], [right]) => compareText(left, right))\n .map(([runId, stream]) =>\n Object.freeze({\n runId,\n ownerIds: Object.freeze([...stream.owners].sort(compareText)),\n unscopedRecords: stream.unscopedRecords,\n recordCount: stream.recordCount,\n }),\n )\n\n return Object.freeze({\n runDir: canonicalRunDir,\n spawnJournalPath,\n coordinationLogPath,\n roots: Object.freeze([...allRoots].filter((root) => !nestedRoots.has(root)).sort(compareText)),\n coordinationStreams: Object.freeze(coordinationStreams),\n })\n}\n\nasync function readOptionalText(path: string): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n try {\n return await fs.readFile(path, 'utf8')\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction isNoEntError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";;;;;;;AA8FA,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAS,WAAW,OAAoC;CACtD,OAAO,QAAQ,OAAO,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;AACpD;AAEA,SAAS,WAAW,SAAiB,MAAsC;CACzE,IAAI,MAAM,QAAQ,MAAM,SAAS,IAAI;MAChC,QAAQ,MAAM,OAAO;AAC5B;;;;;;AAOA,SAAgB,eAAe,OAAyC;CACtE,MAAM,MAAM,MAAM,OAAO;CACzB,MAAM,EAAE,UAAU,UAAU;CA0E5B,OAAO;EAAE,MAAA,IAxEQ,eAA2B,EAC1C,OAAO,OAAO,eAAe;GAC3B,MAAM,OAAO,OAAO,UAA0C;IAC5D,WAAW,QAAQ,WAAW,KAAK,CAAC;IACpC,IAAI,MAAM,SACR,IAAI;KACF,MAAM,MAAM,QAAQ,KAAK;IAC3B,SAAS,KAAK;KACZ,IAAI,oCAAoC,EACtC,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;IACH;GAEJ;GAEA,IAAI;IACF,MAAM,KAAK;KACT,MAAM;KACN,MAAM;MACJ,WAAW,SAAS;MACpB,UAAU,SAAS;MACnB,WAAW,SAAS;KACtB;IACF,CAAC;IAED,MAAM,WAAW,MAAM,QAAQ;IAC/B,WAAW,MAAM,SAAS,SAAS,QACjC,MAAM,KAAK,KAAK;IAElB,MAAM,WAAW,SAAS,UAAU;IACpC,MAAM,YAAY,MAAM,qBACpB,MAAM,MAAM,mBAAmB,QAAQ,IACvC;IAEJ,MAAM,MAAM,wBAAwB;KAAE;KAAU;IAAU,CAAC;IAC3D,IAAI,MAAM,g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C;AACH;AAEA,eAAe,iBAAiB,MAA2C;CACzE,MAAM,KAAK,MAAM,OAAO;CACxB,IAAI;EACF,OAAO,MAAM,GAAG,SAAS,MAAM,MAAM;CACvC,SAAS,OAAO;EACd,IAAI,aAAa,KAAK,GAAG,OAAO,KAAA;EAChC,MAAM;CACR;AACF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,YAAY,MAAc,OAAuB;CACxD,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD;AAEA,SAAS,aAAa,OAAyB;CAC7C,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA4B,SAAS;AAE1C"}
1
+ {"version":3,"file":"durable.js","names":[],"sources":["../src/durable/chat-engine.ts","../src/durable/execution-handle.ts","../src/durable/observer-journal.ts","../src/durable/observer-projection.ts","../src/durable/supervise-pursuit.ts","../src/durable/supervision-discovery.ts"],"sourcesContent":["/**\n * `handleChatTurn` is a framework-neutral chat-turn HTTP orchestrator.\n * Owns the NDJSON `ChatStreamEvent` line protocol, the `session.run.*`\n * lifecycle vocabulary, and the persist / post-process / trace-flush\n * hook order. Returns a `ReadableStream` body the product hands to its\n * platform `Response`.\n *\n * Sandbox owns long-running execution, reconnect, and replay.\n * The producer this engine wraps already speaks that protocol; this\n * engine frames the events and orders product callbacks.\n *\n * Hooks (`ChatTurnHooks`):\n * - `produce`: build the backend event stream\n * - `persistAssistantMessage`: write the assistant turn to the product DB\n * - `onTurnComplete?`: post-process proposals, citations, and similar work\n * - `onEvent?`: send each event to another consumer\n * - `transformFinalText?`: transform text before persistence\n * - `traceFlush?`: let `waitUntil` keep the worker alive for export\n *\n * Framework neutrality: takes already-resolved values (`identity` tuple,\n * a `waitUntil`), never a `Request` or a `Context`. The product's thin\n * route adapter does auth + parse + access-control, then calls\n * `handleChatTurn(...)` and returns `result.body` as its platform `Response`.\n */\n\n/** The NDJSON line protocol every product chat client already speaks. */\nexport interface ChatStreamEvent {\n type: string\n data?: Record<string, unknown>\n}\n\n/** Identity of a chat turn. `tenantId` is the workspace id for workspace-\n * scoped products and the user id for session-scoped products. */\nexport interface ChatTurnIdentity {\n tenantId: string\n /** Thread / session id. */\n sessionId: string\n userId: string\n /** Monotonic 0-based turn index within the session. */\n turnIndex: number\n}\n\n/** The live side of a turn returned by the product's `produce` hook. */\nexport interface ChatTurnProducer<TEvent extends ChatStreamEvent = ChatStreamEvent> {\n /** The turn's event stream. Forwarded verbatim to the caller. */\n stream: AsyncGenerator<TEvent, void, unknown>\n /** The turn's final assistant text. Read once, after `stream` drains. */\n finalText(): string\n}\n\n/** Product callbacks invoked while one chat turn runs. */\nexport interface ChatTurnHooks {\n /** Build the backend stream. The engine forwards events verbatim and\n * reads `finalText()` once the stream drains. */\n produce(): ChatTurnProducer\n /** Persist the assistant message to the product's own store. Called\n * once, after drain, with the assembled (transform-applied) text. */\n persistAssistantMessage(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional post-processing for proposals, citations, or credit metering.\n * Errors are logged without failing a turn that already streamed. */\n onTurnComplete?(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional per-event side channel, such as a Durable Object broadcast.\n * Runs for every emitted event, including the lifecycle envelope.\n * Errors are logged without breaking the chat stream. */\n onEvent?(event: ChatStreamEvent): void | Promise<void>\n /** Optional pre-persist transform of the final text (e.g. PII\n * redaction). Affects only what is persisted; the live stream is\n * never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Optional trace flush. Handed to `waitUntil` so the worker stays alive\n * until export completes. */\n traceFlush?(): Promise<void>\n}\n\n/** Inputs for one streamed product chat turn. */\nexport interface RunChatTurnInput {\n identity: ChatTurnIdentity\n hooks: ChatTurnHooks\n /** Worker liveness hook. When omitted, trace flush is awaited inline\n * before the stream closes. */\n waitUntil?: (p: Promise<unknown>) => void\n /** Structured logger for swallowed hook errors. Defaults to\n * `console.error` so failures surface without product wiring. */\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** HTTP response values returned for one chat turn. */\nexport interface ChatTurnResult {\n /** NDJSON body to return as the platform `Response` body. */\n body: ReadableStream<Uint8Array>\n /** Content type for the response. */\n contentType: 'application/x-ndjson'\n}\n\nconst encoder = new TextEncoder()\n\nfunction encodeLine(event: ChatStreamEvent): Uint8Array {\n return encoder.encode(`${JSON.stringify(event)}\\n`)\n}\n\nfunction defaultLog(message: string, meta?: Record<string, unknown>): void {\n if (meta) console.error(message, meta)\n else console.error(message)\n}\n\n/**\n * Run one chat turn. Returns immediately with a `ReadableStream` body;\n * execution starts while the stream is constructed. Backend\n * failures surface as `error` + `session.run.failed` events.\n */\nexport function handleChatTurn(input: RunChatTurnInput): ChatTurnResult {\n const log = input.log ?? defaultLog\n const { identity, hooks } = input\n\n const body = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n const emit = async (event: ChatStreamEvent): Promise<void> => {\n controller.enqueue(encodeLine(event))\n if (hooks.onEvent) {\n try {\n await hooks.onEvent(event)\n } catch (err) {\n log('[chat-engine] onEvent hook threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n }\n\n try {\n await emit({\n type: 'session.run.started',\n data: {\n sessionId: identity.sessionId,\n tenantId: identity.tenantId,\n turnIndex: identity.turnIndex,\n },\n })\n\n const producer = hooks.produce()\n for await (const event of producer.stream) {\n await emit(event)\n }\n const rawFinal = producer.finalText()\n const finalText = hooks.transformFinalText\n ? await hooks.transformFinalText(rawFinal)\n : rawFinal\n\n await hooks.persistAssistantMessage({ identity, finalText })\n if (hooks.onTurnComplete) {\n try {\n await hooks.onTurnComplete({ identity, finalText })\n } catch (err) {\n log('[chat-engine] onTurnComplete threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n await emit({\n type: 'session.run.completed',\n data: { sessionId: identity.sessionId },\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n log('[chat-engine] turn failed', { error: message })\n await emit({ type: 'error', data: { message } })\n await emit({\n type: 'session.run.failed',\n data: { sessionId: identity.sessionId, message },\n })\n } finally {\n if (hooks.traceFlush) {\n const flush = hooks.traceFlush().catch((err) =>\n log('[chat-engine] traceFlush threw', {\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n if (input.waitUntil) input.waitUntil(flush)\n else await flush\n }\n controller.close()\n }\n },\n })\n\n return { body, contentType: 'application/x-ndjson' }\n}\n","/**\n * Derive a stable execution id from the run identity.\n * The same `(projectId, sessionId, turnIndex)` tuple yields the same id.\n *\n * Use the result as both `PromptOptions.executionId` and\n * `PromptOptions.turnId` on the first dispatch.\n * The execution id addresses the server-side execution for reconnect and\n * replay; the turn id makes a repeated dispatch idempotent.\n * An execution id alone does not make a repeated POST idempotent.\n *\n * Format is readable, not hashed: operators grepping orchestrator logs\n * for `gtm-agent:thread-abc:3` find the run without translating an\n * opaque id. Components are URL-encoded so delimiters inside caller ids\n * cannot collapse distinct tuples. The final id is limited to the\n * orchestrator replay route's 256-byte maximum. Execution ids are not a\n * secrecy boundary.\n *\n * Wire integration:\n * - Initial dispatch: pass the result as `executionId` and `turnId`.\n * - Stream replay: pass it as `executionId` with `lastEventId`.\n *\n * @throws `TypeError` when either string id is blank.\n * @throws `RangeError` when `turnIndex` is invalid or the result exceeds 256 bytes.\n */\nexport function deriveExecutionId(input: {\n projectId: string\n sessionId: string\n turnIndex: number\n}): string {\n if (input.projectId.trim().length === 0) {\n throw new TypeError('projectId must be a non-empty string')\n }\n if (input.sessionId.trim().length === 0) {\n throw new TypeError('sessionId must be a non-empty string')\n }\n if (!Number.isSafeInteger(input.turnIndex) || input.turnIndex < 0) {\n throw new RangeError('turnIndex must be a non-negative safe integer')\n }\n\n const executionId = [\n encodeURIComponent(input.projectId),\n encodeURIComponent(input.sessionId),\n String(input.turnIndex),\n ].join(':')\n if (executionId.length > 256) {\n throw new RangeError('derived execution id must not exceed 256 bytes')\n }\n return executionId\n}\n","import { createHash } from 'node:crypto'\nimport { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport {\n type RuntimeDecisionPoint,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { parseCommittedJsonLines, prepareJsonlAppend, writeAllBytes } from './jsonl-file'\n\nexport type ObserverRecordKind = 'event' | 'decision'\n\n/**\n * One immutable record in the observer plane. `sequence` is journal order, not\n * execution order; causal/runtime order remains available on the underlying event.\n * `previousDigest` + `digest` make deletion, reordering, or mutation detectable.\n */\nexport interface ObserverRecord {\n readonly schemaVersion: 1\n readonly pursuitId: string\n readonly sequence: number\n readonly kind: ObserverRecordKind\n readonly observedAt: number\n readonly previousDigest?: string\n readonly event?: RuntimeHookEvent\n readonly decision?: RuntimeDecisionPoint\n readonly digest: string\n}\n\nexport interface ObserverJournal {\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord>\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord>\n read(): Promise<readonly ObserverRecord[]>\n hooks(): RuntimeHooks\n}\n\ntype UnsignedObserverRecord = Omit<ObserverRecord, 'digest'>\n\n/**\n * Durable, append-only third-person history for one concrete Runtime execution.\n * It consumes Runtime's existing hook stream and does not participate in execution\n * decisions. A broken observer therefore cannot change what an agent is allowed to do.\n *\n * The write discipline deliberately matches `FileSpawnJournal`: serialized appends,\n * torn-tail recovery, short-write handling, and fsync before acknowledgement. One\n * execution owns one journal file; higher-level pursuit aggregation joins isolated\n * journals by `pursuitId` instead of making independent processes share a write head.\n */\nexport class FileObserverJournal implements ObserverJournal {\n readonly path: string\n readonly pursuitId: string\n private tail: Promise<void> = Promise.resolve()\n private initialized = false\n private sequence = 0\n private previousDigest: string | undefined\n private appendFailure: Error | undefined\n\n constructor(path: string, pursuitId: string) {\n const stableId = pursuitId.trim()\n if (stableId.length === 0) {\n throw new TypeError('FileObserverJournal: pursuitId must be non-empty')\n }\n this.path = resolve(path)\n this.pursuitId = stableId\n }\n\n hooks(): RuntimeHooks {\n return withPursuitContext(this.pursuitId, {\n onEvent: (event) => this.appendEvent(event).then(() => undefined),\n onDecisionPoint: (point) => this.appendDecision(point).then(() => undefined),\n })\n }\n\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord> {\n return this.enqueue('event', event)\n }\n\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord> {\n return this.enqueue('decision', point)\n }\n\n async read(): Promise<readonly ObserverRecord[]> {\n await this.tail\n this.assertComplete()\n let text: string\n try {\n text = await readFile(this.path, 'utf8')\n } catch (error) {\n if (isNoEnt(error)) return []\n throw error\n }\n return verifyObserverRecords(\n parseCommittedJsonLines<ObserverRecord>(text, this.path),\n this.pursuitId,\n )\n }\n\n private enqueue(\n kind: ObserverRecordKind,\n value: RuntimeHookEvent | RuntimeDecisionPoint,\n ): Promise<ObserverRecord> {\n if (value.pursuitId !== this.pursuitId) {\n return Promise.reject(\n new Error(\n `FileObserverJournal: ${kind} pursuitId ${String(value.pursuitId)} does not match ${this.pursuitId}`,\n ),\n )\n }\n\n let result: ObserverRecord | undefined\n const operation = this.tail.then(async () => {\n this.assertComplete()\n try {\n await this.initialize()\n } catch (error) {\n this.appendFailure ??= toError(error)\n throw error\n }\n\n const unsigned: UnsignedObserverRecord = {\n schemaVersion: 1,\n pursuitId: this.pursuitId,\n sequence: this.sequence + 1,\n kind,\n observedAt: Date.now(),\n ...(this.previousDigest ? { previousDigest: this.previousDigest } : {}),\n ...(kind === 'event'\n ? { event: value as RuntimeHookEvent }\n : { decision: value as RuntimeDecisionPoint }),\n }\n const record: ObserverRecord = Object.freeze({\n ...unsigned,\n digest: observerRecordDigest(unsigned),\n })\n try {\n await this.writeRecord(record)\n } catch (error) {\n this.appendFailure ??= toError(error)\n throw error\n }\n this.sequence = record.sequence\n this.previousDigest = record.digest\n result = record\n })\n this.tail = operation.then(\n () => undefined,\n () => undefined,\n )\n return operation.then(() => {\n if (!result) throw new Error('FileObserverJournal: append completed without a record')\n return result\n })\n }\n\n private async initialize(): Promise<void> {\n if (this.initialized) return\n const records = await this.readExistingUnsafe()\n const verified = verifyObserverRecords(records, this.pursuitId)\n const tail = verified.at(-1)\n this.sequence = tail?.sequence ?? 0\n this.previousDigest = tail?.digest\n // Only latch after recovery + verification succeed. A transient read error or\n // corruption must never leave an instance pretending it initialized cleanly.\n this.initialized = true\n }\n\n private async readExistingUnsafe(): Promise<ObserverRecord[]> {\n let text: string\n try {\n text = await readFile(this.path, 'utf8')\n } catch (error) {\n if (isNoEnt(error)) return []\n throw error\n }\n return parseCommittedJsonLines<ObserverRecord>(text, this.path)\n }\n\n private async writeRecord(record: ObserverRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const needsSeparator = await prepareJsonlAppend(this.path)\n const handle = await fs.open(this.path, 'a')\n try {\n await writeAllBytes(handle, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await handle.sync()\n } finally {\n await handle.close()\n }\n }\n\n private assertComplete(): void {\n if (!this.appendFailure) return\n throw new Error(\n 'FileObserverJournal: a prior durable append failed; observer completeness is unknown',\n { cause: this.appendFailure },\n )\n }\n}\n\n/** Verify identity, monotonic sequence, payload shape, and the complete digest chain. */\nexport function verifyObserverRecords(\n records: readonly ObserverRecord[],\n pursuitId?: string,\n): readonly ObserverRecord[] {\n let previousDigest: string | undefined\n let expectedSequence = 1\n for (const record of records) {\n if (record.schemaVersion !== 1) throw new Error('observer journal: unsupported schemaVersion')\n if (pursuitId !== undefined && record.pursuitId !== pursuitId) {\n throw new Error(`observer journal: pursuit identity mismatch at sequence ${record.sequence}`)\n }\n if (record.sequence !== expectedSequence) {\n throw new Error(\n `observer journal: non-contiguous sequence ${record.sequence}; expected ${expectedSequence}`,\n )\n }\n if (record.previousDigest !== previousDigest) {\n throw new Error(`observer journal: digest-chain break at sequence ${record.sequence}`)\n }\n if ((record.kind === 'event') === (record.event === undefined)) {\n throw new Error(`observer journal: invalid event payload at sequence ${record.sequence}`)\n }\n if ((record.kind === 'decision') === (record.decision === undefined)) {\n throw new Error(`observer journal: invalid decision payload at sequence ${record.sequence}`)\n }\n if (record.event !== undefined && record.event.pursuitId !== record.pursuitId) {\n throw new Error(\n `observer journal: nested event pursuit mismatch at sequence ${record.sequence}`,\n )\n }\n if (record.decision !== undefined && record.decision.pursuitId !== record.pursuitId) {\n throw new Error(\n `observer journal: nested decision pursuit mismatch at sequence ${record.sequence}`,\n )\n }\n const { digest, ...unsigned } = record\n const expected = observerRecordDigest(unsigned)\n if (digest !== expected) {\n throw new Error(`observer journal: digest mismatch at sequence ${record.sequence}`)\n }\n previousDigest = digest\n expectedSequence += 1\n }\n return Object.freeze([...records])\n}\n\n/** Compute the canonical SHA-256 digest for an unsigned observer record. */\nexport function observerRecordDigest(record: Omit<ObserverRecord, 'digest'>): string {\n return createHash('sha256').update(JSON.stringify(record)).digest('hex')\n}\n\n/** Build the canonical durable observer hook in one call. */\nexport function createFileObserverHooks(\n path: string,\n pursuitId: string,\n): {\n readonly journal: FileObserverJournal\n readonly hooks: RuntimeHooks\n} {\n const journal = new FileObserverJournal(path, pursuitId)\n return { journal, hooks: journal.hooks() }\n}\n\nfunction isNoEnt(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n","import type {\n ExecutionBindingReceipt,\n ProfileMaterializationReceipt,\n ProviderModelExecutionEvidence,\n Spend,\n SpendChannel,\n SpendGap,\n WorkerTraceEvidence,\n} from '../runtime/supervise/types'\nimport { addSpend, cloneSpend, zeroSpend } from '../runtime/util'\nimport type { RuntimeDecisionKind, RuntimeHookTarget } from '../runtime-hooks'\nimport { type ObserverRecord, verifyObserverRecords } from './observer-journal'\n\nexport type PursuitRunStatus = 'running' | 'done' | 'failed'\n\n/**\n * Where a node's dollar figure came from. `reported` = a provider billed all of it; `estimated` =\n * a model catalog priced all of it; `partial` = a provider billed part and a catalog priced the\n * rest; `unknown` = nothing priced it, so `usd` is a floor and never the cost.\n */\nexport type PursuitCostProvenance = 'reported' | 'estimated' | 'partial' | 'unknown'\n\n/**\n * One node's token usage by class. Cache and reasoning classes are absent when the provider did\n * not report them — absence is not zero. `tokensKnown` is `false` when work happened whose token\n * count no provider reported, which makes `input`/`output` a floor.\n */\nexport interface PursuitNodeUsage {\n readonly input: number\n readonly output: number\n readonly cacheRead?: number\n readonly cacheWrite?: number\n readonly reasoning?: number\n readonly tokensKnown: boolean\n}\n\n/** One node's dollar cost with the provenance that decides whether it may be compared or summed. */\nexport interface PursuitNodeCost {\n readonly usd: number\n readonly usdKnown: boolean\n /** The part of `usd` a model catalog priced because no provider receipt covered it. */\n readonly usdEstimated?: number\n readonly provenance: PursuitCostProvenance\n}\n\n/**\n * One node's clock. `wallMs` is `settledAt - startedAt` and is deliberately distinct from the\n * executor-reported `spent.ms` sums, which under-report and overlap across parallel children.\n * `firstTokenAt` stays absent unless a provider reports that instant; it is never inferred from\n * `firstOutputAt`, which is when the node first reported usage for a turn.\n */\nexport interface PursuitNodeTiming {\n readonly startedAt: number\n readonly firstOutputAt?: number\n readonly firstTokenAt?: number\n readonly settledAt?: number\n readonly wallMs?: number\n}\n\n/** Where and how a node's execution was placed, read off its execution-binding receipt. */\nexport type PursuitNodePlacement = Readonly<Record<string, string | number | boolean | null>>\n\n/**\n * One run's spend counted once, and each node's own share of it. `inclusive` and the entries of\n * `exclusiveByNode` are the two views a client needs to show a tree without double counting.\n */\nexport interface PursuitRunTotals {\n /**\n * The whole run counted once. A node's settled `spent` already contains the child work its own\n * nested tree reported, so summing only the run's top-level nodes plus every node's own\n * inference counts each model call exactly once.\n */\n readonly inclusive: Spend\n /**\n * Each node's own share: its reported spend and own inference minus what its direct children\n * reported. Keyed by node id, plus the run root when the root itself metered inference. The\n * entries sum to `inclusive` by construction.\n */\n readonly exclusiveByNode: Readonly<Record<string, Spend>>\n}\n\nexport interface PursuitRunProjection {\n readonly runId: string\n readonly status: PursuitRunStatus\n readonly settledAt?: number\n readonly error?: string\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly decisionCount: number\n readonly targets: Readonly<Record<string, number>>\n readonly decisions: Readonly<Record<string, number>>\n readonly totals: PursuitRunTotals\n /** The nodes whose accounting is incomplete. Present exactly when non-empty. */\n readonly spendGaps?: ReadonlyArray<SpendGap>\n}\n\nexport type PursuitNodeStatus = 'running' | 'done' | 'down'\n\nexport interface PursuitNodeProjection {\n readonly id: string\n readonly parentId?: string\n /** Node ids are scoped to this concrete Runtime tree; `(runId,id)` is identity. */\n readonly runId: string\n readonly label?: string\n /** The runner that executed this node — the executor's own name, not a harness guess. */\n readonly runtime?: string\n readonly depth?: number\n readonly assignmentId?: string\n readonly identity?: unknown\n readonly budget?: unknown\n readonly status: PursuitNodeStatus\n readonly settledAt?: number\n /** The child work this node reported at settlement. Absent until a terminal record lands. */\n readonly spent?: Spend\n /** This node's OWN inference, re-homed from its nested tree. Absent when it drove no turns. */\n readonly ownInference?: Spend\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly usage?: PursuitNodeUsage\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly cost?: PursuitNodeCost\n readonly timing?: PursuitNodeTiming\n /** The kernel-minted attempt this node's execution binding is keyed on. */\n readonly attemptId?: string\n /** The runner-native execution the node bound to: a request, session, run, process, or tree. */\n readonly execution?: { readonly kind: string; readonly id: string }\n /** The model the materialization receipt names, when the runner reported one. */\n readonly model?: string\n /** The concrete backend the profile materialized onto. */\n readonly backend?: string\n readonly placement?: PursuitNodePlacement\n /** Model-call identifiers this node's own turns reported, in order, deduplicated. */\n readonly modelCalls?: ReadonlyArray<string>\n readonly materialization?: ProfileMaterializationReceipt\n readonly executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n /** What the provider itself reported serving, and why it is unknown when it is. */\n readonly providerModel?: ProviderModelExecutionEvidence\n /** Content-addressed pointer to this node's persisted tool trace, or why there is none. */\n readonly trace?: WorkerTraceEvidence\n readonly outRef?: string\n readonly score?: number\n readonly valid?: boolean\n readonly reason?: string\n readonly infra?: boolean\n readonly restartCount?: number\n readonly wait?: unknown\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly turnCount: number\n}\n\nexport interface PursuitProjection {\n readonly pursuitId: string\n /** Number of records in this concrete execution journal. */\n readonly sequence: number\n /** Digest-chain tip for this concrete execution journal. */\n readonly chainTip: string\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly runs: readonly PursuitRunProjection[]\n readonly nodes: readonly PursuitNodeProjection[]\n readonly eventCount: number\n readonly decisionCount: number\n}\n\ntype MutableRun = {\n runId: string\n status: PursuitRunStatus\n settledAt?: number\n error?: string\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n decisionCount: number\n targets: Record<string, number>\n decisions: Record<string, number>\n /** Inference the run root drove itself, attributable to no spawned node. */\n rootInference?: Spend\n}\n\ntype MutableNode = {\n id: string\n parentId?: string\n runId: string\n label?: string\n runtime?: string\n depth?: number\n assignmentId?: string\n identity?: unknown\n budget?: unknown\n status: PursuitNodeStatus\n startedAt?: number\n settledAt?: number\n spent?: Spend\n ownInference?: Spend\n reasoningTokens?: number\n firstOutputAt?: number\n firstTokenAt?: number\n attemptId?: string\n execution?: { kind: string; id: string }\n model?: string\n backend?: string\n placement?: PursuitNodePlacement\n modelCalls: string[]\n materialization?: ProfileMaterializationReceipt\n executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n providerModel?: ProviderModelExecutionEvidence\n trace?: WorkerTraceEvidence\n outRef?: string\n score?: number\n valid?: boolean\n reason?: string\n infra?: boolean\n restartCount?: number\n wait?: unknown\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n turnCount: number\n}\n\n/**\n * Fold one append-only execution journal into a deterministic operator projection.\n *\n * This is intentionally a READ model, not another state machine: it does not own\n * execution, cannot steer agents, and can be rebuilt from the journal at any time.\n * Projection verifies the complete hash chain first, so an operator view can never\n * silently render a mutated or reordered observer history as trustworthy state.\n *\n * Topology comes only from Runtime's canonical `agent.spawn` facts. Terminal node\n * state comes only from `agent.child`; concrete run state comes only from the root\n * `agent.run` lifecycle emitted by `supervisePursuit`. Node identity is scoped to the\n * concrete Runtime run so independent trees may both contain `root:s0` without aliasing.\n *\n * Usage, cost and timing are reported at the class the runtime measured them at. A missing\n * class stays ABSENT and the run names the node in `spendGaps`; nothing here converts an\n * unmeasured channel into a zero, because a fabricated zero is indistinguishable from free work.\n */\nexport function projectPursuit(records: readonly ObserverRecord[]): PursuitProjection {\n if (records.length === 0) {\n throw new TypeError('projectPursuit: at least one observer record is required')\n }\n const pursuitId = records[0]!.pursuitId\n const verified = verifyObserverRecords(records, pursuitId)\n const runs = new Map<string, MutableRun>()\n const nodes = new Map<string, MutableNode>()\n let eventCount = 0\n let decisionCount = 0\n\n for (const record of verified) {\n const observed = record.event ?? record.decision\n if (!observed) throw new Error(`projectPursuit: record ${record.sequence} has no observation`)\n const run = getRun(runs, observed.runId, record)\n run.lastSequence = record.sequence\n run.lastObservedAt = record.observedAt\n\n if (record.event) {\n eventCount += 1\n run.eventCount += 1\n increment(run.targets, record.event.target)\n projectRunActivity(run, record)\n projectSpawnNode(nodes, record)\n projectNodeActivity(nodes, record)\n projectTurn(runs, nodes, record)\n } else if (record.decision) {\n decisionCount += 1\n run.decisionCount += 1\n increment(run.decisions, record.decision.kind)\n }\n }\n\n const byRun = new Map<string, MutableNode[]>()\n for (const node of nodes.values()) {\n const list = byRun.get(node.runId)\n if (list) list.push(node)\n else byRun.set(node.runId, [node])\n }\n\n const first = verified[0]!\n const last = verified.at(-1)!\n return Object.freeze({\n pursuitId,\n sequence: last.sequence,\n chainTip: last.digest,\n firstObservedAt: first.observedAt,\n lastObservedAt: last.observedAt,\n runs: Object.freeze(\n [...runs.values()]\n .sort((a, b) => a.firstSequence - b.firstSequence || a.runId.localeCompare(b.runId))\n .map((run) => freezeRun(run, byRun.get(run.runId) ?? [])),\n ),\n nodes: Object.freeze(\n [...nodes.values()]\n .sort(\n (a, b) =>\n a.firstSequence - b.firstSequence ||\n a.runId.localeCompare(b.runId) ||\n a.id.localeCompare(b.id),\n )\n .map(freezeNode),\n ),\n eventCount,\n decisionCount,\n })\n}\n\nfunction getRun(runs: Map<string, MutableRun>, runId: string, record: ObserverRecord): MutableRun {\n const existing = runs.get(runId)\n if (existing) return existing\n const created: MutableRun = {\n runId,\n status: 'running',\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 0,\n decisionCount: 0,\n targets: {},\n decisions: {},\n }\n runs.set(runId, created)\n return created\n}\n\nfunction projectRunActivity(run: MutableRun, record: ObserverRecord): void {\n const event = record.event\n if (event?.target !== 'agent.run') return\n const payload = objectRecord(event.payload)\n const status = stringField(payload, 'status')\n if (event.phase === 'after' || status === 'done') {\n run.status = 'done'\n run.settledAt = record.observedAt\n return\n }\n if (event.phase !== 'error' && status !== 'failed') return\n run.status = 'failed'\n run.settledAt = record.observedAt\n const error = stringField(payload, 'error')\n if (error) run.error = error\n}\n\nfunction nodeKey(runId: string, nodeId: string): string {\n return `${runId}\\u0000${nodeId}`\n}\n\nfunction projectSpawnNode(nodes: Map<string, MutableNode>, record: ObserverRecord): void {\n const event = record.event\n if (event?.target !== 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const childId = stringField(payload, 'childId')\n if (!childId) return\n const key = nodeKey(event.runId, childId)\n const existing = nodes.get(key)\n if (existing) {\n existing.lastSequence = record.sequence\n existing.lastObservedAt = record.observedAt\n existing.eventCount += 1\n return\n }\n const label = stringField(payload, 'label')\n const runtime = stringField(payload, 'runtime')\n const depth = numberField(payload, 'depth')\n const assignmentId = stringField(payload, 'assignmentId')\n const attemptId = stringField(payload, 'attemptId')\n const startedAt = numberField(payload, 'startedAt')\n nodes.set(key, {\n id: childId,\n ...(event.parentId ? { parentId: event.parentId } : {}),\n runId: event.runId,\n ...(label ? { label } : {}),\n ...(runtime ? { runtime } : {}),\n ...(depth !== undefined ? { depth } : {}),\n ...(assignmentId ? { assignmentId } : {}),\n ...(attemptId ? { attemptId } : {}),\n // A spawn that predates the `startedAt` fact falls back to when the record was observed:\n // the spawn event is emitted synchronously with the spawn, so the two agree to the ms.\n startedAt: startedAt ?? record.observedAt,\n ...(payload && Object.hasOwn(payload, 'identity') ? { identity: payload.identity } : {}),\n ...(payload && Object.hasOwn(payload, 'budget') ? { budget: payload.budget } : {}),\n status: 'running',\n modelCalls: [],\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 1,\n turnCount: 0,\n })\n}\n\nfunction projectNodeActivity(nodes: Map<string, MutableNode>, record: ObserverRecord): void {\n const event = record.event\n if (event === undefined) return\n if (event.target === 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const nodeId =\n stringField(payload, 'childId') ??\n stringField(payload, 'nodeId') ??\n stringField(payload, 'workerId')\n if (!nodeId) return\n const node = nodes.get(nodeKey(event.runId, nodeId))\n if (!node) return\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n node.eventCount += 1\n\n if (event.target !== 'agent.child') return\n const status = stringField(payload, 'status')\n if (status !== 'done' && status !== 'down') return\n node.status = status\n node.settledAt = numberField(payload, 'settledAt') ?? record.observedAt\n const startedAt = numberField(payload, 'startedAt')\n if (startedAt !== undefined) node.startedAt = startedAt\n if (payload && Object.hasOwn(payload, 'spent')) node.spent = spendField(payload, 'spent')\n const metered = spendField(payload, 'metered')\n if (metered)\n node.ownInference = node.ownInference ? addSpend(node.ownInference, metered) : metered\n const runtime = stringField(payload, 'runtime')\n if (runtime) node.runtime = runtime\n const outRef = stringField(payload, 'outRef')\n if (outRef) node.outRef = outRef\n const score = numberField(payload, 'score')\n if (score !== undefined) node.score = score\n const valid = booleanField(payload, 'valid')\n if (valid !== undefined) node.valid = valid\n const reason = stringField(payload, 'reason')\n if (reason) node.reason = reason\n const infra = booleanField(payload, 'infra')\n if (infra !== undefined) node.infra = infra\n const restartCount = numberField(payload, 'restartCount')\n if (restartCount !== undefined) node.restartCount = restartCount\n if (payload && Object.hasOwn(payload, 'wait')) node.wait = payload.wait\n attachSettlementEvidence(node, payload)\n}\n\n/**\n * Read the receipts a settlement carries. Each is taken as reported: an `unknown` receipt keeps\n * its `status` and `reason` so a client can show WHY a model or backend is missing instead of\n * showing nothing, and a receipt that never landed leaves every derived field absent.\n */\nfunction attachSettlementEvidence(\n node: MutableNode,\n payload: Record<string, unknown> | undefined,\n): void {\n const providerModel = payload?.providerModel as ProviderModelExecutionEvidence | undefined\n if (providerModel && typeof providerModel === 'object') node.providerModel = providerModel\n const trace = payload?.trace as WorkerTraceEvidence | undefined\n if (trace && typeof trace === 'object') node.trace = trace\n const bindings = payload?.executionBindings\n if (Array.isArray(bindings) && bindings.length > 0) {\n node.executionBindings = bindings as ReadonlyArray<ExecutionBindingReceipt>\n const known = bindings.find(\n (binding): binding is Extract<ExecutionBindingReceipt, { status: 'known' }> =>\n objectRecord(binding)?.status === 'known',\n )\n if (known) {\n node.placement = known.descriptor\n node.attemptId ??= known.attemptId\n }\n }\n const receipt = payload?.materialization as ProfileMaterializationReceipt | undefined\n if (!receipt || typeof receipt !== 'object') return\n node.materialization = receipt\n if (receipt.status !== 'known') return\n node.backend = receipt.backend\n if (receipt.model.status === 'known') node.model = receipt.model.id\n node.execution = { kind: receipt.execution.kind, id: receipt.execution.id }\n}\n\n/**\n * Fold one metered turn onto whoever drove it. `agent.turn` names its subject in `parentId` — the\n * node making the call — not in the payload, because the caller IS the subject. A turn the run\n * root drove belongs to no spawned node and lands on the run instead, so the run's totals stay\n * complete without inventing a node for the root.\n */\nfunction projectTurn(\n runs: Map<string, MutableRun>,\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n): void {\n const event = record.event\n if (event?.target !== 'agent.turn') return\n const payload = objectRecord(event.payload)\n const spend = spendField(payload, 'spend')\n const subject = event.parentId\n if (subject === undefined) return\n const node = nodes.get(nodeKey(event.runId, subject))\n if (!node) {\n if (!spend) return\n const run = runs.get(event.runId)\n if (!run) return\n run.rootInference = run.rootInference ? addSpend(run.rootInference, spend) : spend\n return\n }\n node.turnCount += 1\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n if (spend) {\n node.ownInference = node.ownInference ? addSpend(node.ownInference, spend) : spend\n node.firstOutputAt ??= record.observedAt\n }\n const reasoning = numberField(payload, 'reasoningTokens')\n if (reasoning !== undefined) node.reasoningTokens = (node.reasoningTokens ?? 0) + reasoning\n const firstTokenAt = numberField(payload, 'firstTokenAt')\n if (firstTokenAt !== undefined) node.firstTokenAt ??= firstTokenAt\n const model = stringField(payload, 'model')\n if (model) node.model ??= model\n const callId = stringField(payload, 'callId')\n if (callId && !node.modelCalls.includes(callId)) node.modelCalls.push(callId)\n}\n\n/**\n * A node's whole reported cost: the child work its settlement reported plus the inference it drove\n * itself. `undefined` when neither landed — the run's `spendGaps` then names the node, so an\n * unaccounted node is visible instead of reading as free.\n */\nfunction nodeTotal(node: MutableNode): Spend | undefined {\n if (node.spent && node.ownInference) return addSpend(node.spent, node.ownInference)\n if (node.spent) return cloneSpend(node.spent)\n if (node.ownInference) return cloneSpend(node.ownInference)\n return undefined\n}\n\n/**\n * The run counted once, and each node's own share of it.\n *\n * A settled node's `spent` already contains the child work its nested tree reported, so summing\n * every node would count a driver's descendants twice. Inclusive therefore sums only the run's\n * TOP-LEVEL nodes — those whose parent is not another node of this run — plus the root's own\n * turns. Exclusive subtracts each node's direct children from its own total, which telescopes:\n * the exclusive entries sum back to `inclusive` exactly.\n */\nfunction runTotals(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunTotals {\n const present = new Set(nodes.map((node) => node.id))\n const children = new Map<string, MutableNode[]>()\n for (const node of nodes) {\n if (node.parentId === undefined || !present.has(node.parentId)) continue\n const list = children.get(node.parentId)\n if (list) list.push(node)\n else children.set(node.parentId, [node])\n }\n const exclusiveByNode: Record<string, Spend> = {}\n let inclusive = run.rootInference ? cloneSpend(run.rootInference) : zeroSpend()\n if (run.rootInference) exclusiveByNode[run.runId] = cloneSpend(run.rootInference)\n for (const node of nodes) {\n const total = nodeTotal(node)\n if (total === undefined) continue\n if (node.parentId === undefined || !present.has(node.parentId)) {\n inclusive = addSpend(inclusive, total)\n }\n let exclusive = total\n for (const child of children.get(node.id) ?? []) {\n const childTotal = nodeTotal(child)\n if (childTotal !== undefined) exclusive = subtractSpend(exclusive, childTotal)\n }\n exclusiveByNode[node.id] = exclusive\n }\n return Object.freeze({\n inclusive: Object.freeze(inclusive),\n exclusiveByNode: Object.freeze(exclusiveByNode),\n })\n}\n\n/**\n * Remove a child's reported total from its parent's. Per channel, never below zero: a parent whose\n * executor reported less than its children did is a reporting gap, and a negative exclusive share\n * would be a fabricated number rather than a measurement.\n */\nfunction subtractSpend(a: Spend, b: Spend): Spend {\n const tokens = { ...a.tokens }\n tokens.input = Math.max(0, tokens.input - b.tokens.input)\n tokens.output = Math.max(0, tokens.output - b.tokens.output)\n if (a.tokens.cacheRead !== undefined)\n tokens.cacheRead = Math.max(0, a.tokens.cacheRead - (b.tokens.cacheRead ?? 0))\n if (a.tokens.cacheWrite !== undefined)\n tokens.cacheWrite = Math.max(0, a.tokens.cacheWrite - (b.tokens.cacheWrite ?? 0))\n if (a.tokens.freshInput !== undefined)\n tokens.freshInput = Math.max(0, a.tokens.freshInput - (b.tokens.freshInput ?? 0))\n return {\n iterations: Math.max(0, a.iterations - b.iterations),\n tokens,\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: Math.max(0, a.usd - b.usd),\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...(a.usdEstimated !== undefined\n ? { usdEstimated: Math.max(0, a.usdEstimated - (b.usdEstimated ?? 0)) }\n : {}),\n ms: Math.max(0, a.ms - b.ms),\n }\n}\n\n/** The nodes of one run whose accounting is incomplete, in the vocabulary the supervisor already\n * uses: `never-settled` = no terminal record, so every channel is unaccounted; `unreported` = a\n * record landed with a channel the provider did not report, so that channel is a floor. */\nfunction runSpendGaps(nodes: readonly MutableNode[]): SpendGap[] {\n const gaps: SpendGap[] = []\n for (const node of nodes) {\n const label = node.label\n if (node.status === 'running') {\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'never-settled',\n channels: ['tokens', 'usd'],\n })\n continue\n }\n const total = nodeTotal(node)\n const channels: SpendChannel[] = []\n if (total === undefined || total.tokensKnown === false) channels.push('tokens')\n if (total === undefined || total.usdKnown === false) channels.push('usd')\n if (channels.length === 0) continue\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'unreported',\n channels,\n })\n }\n return gaps\n}\n\nfunction usageOf(total: Spend, reasoning: number | undefined): PursuitNodeUsage {\n return {\n input: total.tokens.input,\n output: total.tokens.output,\n ...(total.tokens.cacheRead !== undefined ? { cacheRead: total.tokens.cacheRead } : {}),\n ...(total.tokens.cacheWrite !== undefined ? { cacheWrite: total.tokens.cacheWrite } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n tokensKnown: total.tokensKnown !== false && total.tokens.tokensKnown !== false,\n }\n}\n\nfunction costOf(total: Spend): PursuitNodeCost {\n const usdKnown = total.usdKnown !== false\n const estimated = total.usdEstimated\n const provenance: PursuitCostProvenance = usdKnown\n ? estimated === undefined || estimated === 0\n ? 'reported'\n : 'partial'\n : estimated === undefined\n ? 'unknown'\n : estimated >= total.usd\n ? 'estimated'\n : 'partial'\n return {\n usd: total.usd,\n usdKnown,\n ...(estimated !== undefined ? { usdEstimated: estimated } : {}),\n provenance,\n }\n}\n\nfunction timingOf(node: MutableNode): PursuitNodeTiming | undefined {\n if (node.startedAt === undefined) return undefined\n return {\n startedAt: node.startedAt,\n ...(node.firstOutputAt !== undefined ? { firstOutputAt: node.firstOutputAt } : {}),\n ...(node.firstTokenAt !== undefined ? { firstTokenAt: node.firstTokenAt } : {}),\n ...(node.settledAt !== undefined ? { settledAt: node.settledAt } : {}),\n ...(node.settledAt !== undefined\n ? { wallMs: Math.max(0, node.settledAt - node.startedAt) }\n : {}),\n }\n}\n\nfunction freezeRun(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunProjection {\n const gaps = runSpendGaps(nodes)\n const { rootInference: _rootInference, ...rest } = run\n return Object.freeze({\n ...rest,\n targets: Object.freeze({ ...run.targets }),\n decisions: Object.freeze({ ...run.decisions }),\n totals: runTotals(run, nodes),\n ...(gaps.length > 0 ? { spendGaps: Object.freeze(gaps) } : {}),\n })\n}\n\nfunction freezeNode(node: MutableNode): PursuitNodeProjection {\n const { modelCalls, reasoningTokens, startedAt: _startedAt, ...rest } = node\n const total = nodeTotal(node)\n const timing = timingOf(node)\n return Object.freeze({\n ...rest,\n ...(modelCalls.length > 0 ? { modelCalls: Object.freeze([...modelCalls]) } : {}),\n ...(total !== undefined ? { usage: usageOf(total, reasoningTokens), cost: costOf(total) } : {}),\n ...(timing !== undefined ? { timing } : {}),\n })\n}\n\nfunction increment(\n target: Record<string, number>,\n key: RuntimeHookTarget | RuntimeDecisionKind,\n): void {\n target[key] = (target[key] ?? 0) + 1\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\n/** Read a journaled `Spend` without trusting the wire: a record missing the conserved channels is\n * not a zero-cost turn, it is an unparseable one, and it must not enter a total. */\nfunction spendField(value: Record<string, unknown> | undefined, key: string): Spend | undefined {\n const field = objectRecord(value?.[key])\n if (!field) return undefined\n const tokens = objectRecord(field.tokens)\n if (typeof field.usd !== 'number' || !Number.isFinite(field.usd)) return undefined\n if (!tokens || typeof tokens.input !== 'number' || typeof tokens.output !== 'number') {\n return undefined\n }\n return cloneSpend(field as unknown as Spend)\n}\n\nfunction stringField(value: Record<string, unknown> | undefined, key: string): string | undefined {\n const field = value?.[key]\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction numberField(value: Record<string, unknown> | undefined, key: string): number | undefined {\n const field = value?.[key]\n return typeof field === 'number' && Number.isFinite(field) ? field : undefined\n}\n\nfunction booleanField(\n value: Record<string, unknown> | undefined,\n key: string,\n): boolean | undefined {\n const field = value?.[key]\n return typeof field === 'boolean' ? field : undefined\n}\n","import { resolve } from 'node:path'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport { composeRuntimeHooks, type RuntimeHookEvent, withPursuitContext } from '../runtime-hooks'\nimport { createFileObserverHooks } from './observer-journal'\nimport { type PursuitProjection, projectPursuit } from './observer-projection'\n\nexport interface SupervisePursuitOptions extends SuperviseOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /**\n * One concrete Runtime execution owns one durable directory and observer journal.\n * A pursuit spanning several runs reuses `pursuitId` across distinct `runDir`s;\n * Intelligence joins those isolated projections without a shared write head.\n */\n readonly runDir: string\n}\n\nexport interface SupervisedPursuitResult<Result> {\n readonly result: Result\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n}\n\n/** A failed Runtime execution whose complete third-person projection was retained. */\nexport class SupervisePursuitError extends Error {\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n\n constructor(cause: unknown, pursuit: PursuitProjection, observerPath: string) {\n super(`supervisePursuit: ${errorMessage(cause)}`, { cause })\n this.name = 'SupervisePursuitError'\n this.pursuit = pursuit\n this.observerPath = observerPath\n }\n}\n\n/**\n * One-call durable pursuit execution over the canonical `supervise()` kernel.\n *\n * This is an adapter, not a second executor: it composes a durable third-person\n * observer into Runtime's existing recursive hook stream and then rebuilds the\n * operator projection after the same `supervise()` call settles. Agents never\n * receive the observer path or projection and their behavior does not depend on it.\n *\n * Every concrete execution writes only inside its own `runDir`. Cross-run pursuit\n * aggregation is therefore lock-free at the observer layer: reuse `pursuitId` across\n * run directories and let Intelligence join the independently verified projections.\n */\nexport async function supervisePursuit(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n): Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>> {\n const pursuitId = opts.pursuitId.trim()\n if (pursuitId.length === 0) {\n throw new TypeError('supervisePursuit: pursuitId must be non-empty')\n }\n const runDir = opts.runDir.trim()\n if (runDir.length === 0) {\n throw new TypeError('supervisePursuit: runDir must be non-empty')\n }\n\n const observerPath = resolve(runDir, 'observer.jsonl')\n const { pursuitId: _pursuitId, hooks, ...superviseOptions } = opts\n const observer = createFileObserverHooks(observerPath, pursuitId)\n const runId = superviseOptions.runId ?? 'supervise'\n const now = superviseOptions.now ?? Date.now\n\n // Root lifecycle is an observer-plane fact, not something the manager has to\n // narrate about itself. This also makes a zero-spawn/single-agent run observable.\n await observer.journal.appendEvent(rootEvent(pursuitId, runId, 'before', now()))\n\n try {\n const result = await supervise(profile, task, {\n ...superviseOptions,\n // The observer runs first so a caller hook that throws cannot prevent the\n // canonical lifecycle fact from entering the durable journal.\n hooks: withPursuitContext(pursuitId, composeRuntimeHooks(observer.hooks, hooks)),\n })\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'after', now(), { status: 'done' }),\n )\n return Object.freeze({\n result,\n pursuit: projectPursuit(await observer.journal.read()),\n observerPath,\n })\n } catch (error) {\n let pursuit: PursuitProjection | undefined\n let observerError: unknown\n try {\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'error', now(), {\n status: 'failed',\n error: errorMessage(error),\n }),\n )\n pursuit = projectPursuit(await observer.journal.read())\n } catch (failure) {\n observerError = failure\n }\n if (observerError !== undefined || pursuit === undefined) {\n const causes = observerError === undefined ? [error] : [error, observerError]\n throw new Error(\n 'supervisePursuit: Runtime failed and durable observer completeness could not be proven',\n { cause: new AggregateError(causes) },\n )\n }\n throw new SupervisePursuitError(error, pursuit, observerPath)\n }\n}\n\nfunction rootEvent(\n pursuitId: string,\n runId: string,\n phase: 'before' | 'after' | 'error',\n timestamp: number,\n payload?: Record<string, unknown>,\n): RuntimeHookEvent {\n return Object.freeze({\n id: `${runId}:pursuit:${phase}:${timestamp}`,\n pursuitId,\n runId,\n target: 'agent.run',\n phase,\n timestamp,\n ...(payload ? { payload: Object.freeze({ ...payload }) } : {}),\n })\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import { resolve } from 'node:path'\nimport type { NodeId } from '../runtime/supervise/types'\nimport { isNoEntError, parseCommittedJsonLines } from './jsonl-file'\n\nexport interface DurableCoordinationStreamIdentity {\n readonly runId: string\n /** Exact owner ids present in the side-log, sorted for deterministic display. */\n readonly ownerIds: readonly string[]\n /** Records written before owner-scoped coordination identities were introduced. */\n readonly unscopedRecords: number\n readonly recordCount: number\n}\n\n/**\n * Identities discoverable from one `supervise({ runDir })` directory without\n * already knowing the root node or coordination run id stored inside it.\n */\nexport interface DurableSupervisionDiscovery {\n readonly runDir: string\n readonly spawnJournalPath: string\n readonly coordinationLogPath: string\n readonly roots: readonly NodeId[]\n readonly coordinationStreams: readonly DurableCoordinationStreamIdentity[]\n}\n\ntype SpawnJournalIdentityRecord = {\n readonly kind?: unknown\n readonly root?: unknown\n readonly event?: unknown\n}\n\ntype CoordinationIdentityRecord = {\n readonly runId?: unknown\n readonly ownerId?: unknown\n}\n\n/**\n * Discover the stable identities recorded by Runtime's durable supervision\n * files. This is the developer-facing first step before calling\n * `FileSpawnJournal.loadTree(root)`, `loadSpawnForest(journal, root)`, or\n * `FileCoordinationLog.load(runId, ownerId)`.\n *\n * Missing files produce empty collections. A malformed committed JSONL record\n * still fails loud through the same parser used by the runtime; a torn final\n * append is ignored because it was never acknowledged as committed.\n */\nexport async function discoverDurableSupervisionRun(\n runDir: string,\n): Promise<DurableSupervisionDiscovery> {\n if (typeof runDir !== 'string' || runDir.trim().length === 0) {\n throw new TypeError('discoverDurableSupervisionRun: runDir must be a non-empty string')\n }\n\n const canonicalRunDir = resolve(runDir)\n const spawnJournalPath = `${canonicalRunDir}/spawn-journal.jsonl`\n const coordinationLogPath = `${canonicalRunDir}/coordination-log.jsonl`\n const [spawnText, coordinationText] = await Promise.all([\n readOptionalText(spawnJournalPath),\n readOptionalText(coordinationLogPath),\n ])\n\n const allRoots = new Set<NodeId>()\n const nestedRoots = new Set<NodeId>()\n if (spawnText !== undefined) {\n for (const record of parseCommittedJsonLines<SpawnJournalIdentityRecord>(\n spawnText,\n spawnJournalPath,\n )) {\n if (record.kind === 'begin') {\n if (typeof record.root !== 'string' || record.root.length === 0) {\n throw new Error(`${spawnJournalPath}: begin record has no non-empty string root identity`)\n }\n allRoots.add(record.root as NodeId)\n continue\n }\n if (record.kind !== 'event') continue\n const event = record.event\n if (!isRecord(event) || event.kind !== 'spawned') continue\n if (!Object.hasOwn(event, 'ownedTreeRoot')) continue\n if (typeof event.ownedTreeRoot !== 'string' || event.ownedTreeRoot.length === 0) {\n throw new Error(\n `${spawnJournalPath}: spawned event ownedTreeRoot must be a non-empty string when present`,\n )\n }\n nestedRoots.add(event.ownedTreeRoot as NodeId)\n }\n }\n\n const streams = new Map<\n string,\n { owners: Set<string>; unscopedRecords: number; recordCount: number }\n >()\n if (coordinationText !== undefined) {\n for (const record of parseCommittedJsonLines<CoordinationIdentityRecord>(\n coordinationText,\n coordinationLogPath,\n )) {\n if (typeof record.runId !== 'string' || record.runId.length === 0) {\n throw new Error(`${coordinationLogPath}: record has no non-empty string runId identity`)\n }\n const stream = streams.get(record.runId) ?? {\n owners: new Set<string>(),\n unscopedRecords: 0,\n recordCount: 0,\n }\n stream.recordCount += 1\n if (record.ownerId === undefined) {\n stream.unscopedRecords += 1\n } else if (typeof record.ownerId === 'string' && record.ownerId.length > 0) {\n stream.owners.add(record.ownerId)\n } else {\n throw new Error(`${coordinationLogPath}: ownerId must be a non-empty string when present`)\n }\n streams.set(record.runId, stream)\n }\n }\n\n const coordinationStreams = [...streams.entries()]\n .sort(([left], [right]) => compareText(left, right))\n .map(([runId, stream]) =>\n Object.freeze({\n runId,\n ownerIds: Object.freeze([...stream.owners].sort(compareText)),\n unscopedRecords: stream.unscopedRecords,\n recordCount: stream.recordCount,\n }),\n )\n\n return Object.freeze({\n runDir: canonicalRunDir,\n spawnJournalPath,\n coordinationLogPath,\n roots: Object.freeze([...allRoots].filter((root) => !nestedRoots.has(root)).sort(compareText)),\n coordinationStreams: Object.freeze(coordinationStreams),\n })\n}\n\nasync function readOptionalText(path: string): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n try {\n return await fs.readFile(path, 'utf8')\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n"],"mappings":";;;;;;;;AA8FA,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAS,WAAW,OAAoC;CACtD,OAAO,QAAQ,OAAO,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;AACpD;AAEA,SAAS,WAAW,SAAiB,MAAsC;CACzE,IAAI,MAAM,QAAQ,MAAM,SAAS,IAAI;MAChC,QAAQ,MAAM,OAAO;AAC5B;;;;;;AAOA,SAAgB,eAAe,OAAyC;CACtE,MAAM,MAAM,MAAM,OAAO;CACzB,MAAM,EAAE,UAAU,UAAU;CA0E5B,OAAO;EAAE,MAAA,IAxEQ,eAA2B,EAC1C,OAAO,OAAO,eAAe;GAC3B,MAAM,OAAO,OAAO,UAA0C;IAC5D,WAAW,QAAQ,WAAW,KAAK,CAAC;IACpC,IAAI,MAAM,SACR,IAAI;KACF,MAAM,MAAM,QAAQ,KAAK;IAC3B,SAAS,KAAK;KACZ,IAAI,oC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