effect-agent 0.1.0-beta.96 → 0.1.0-beta.97

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 (102) hide show
  1. package/dist/{DurableAgentRuntime-BGwGUIT-.mjs → DurableAgentRuntime-DbUvZHDZ.mjs} +34 -30
  2. package/dist/DurableAgentRuntime-DbUvZHDZ.mjs.map +1 -0
  3. package/dist/{EventSource-tCO_dAff.d.mts → EventSource-D6PAAEyK.d.mts} +3 -3
  4. package/dist/{PreparedInputAdmission-CFSddiT8.d.mts → PreparedInputAdmission-omMbwd--.d.mts} +4 -4
  5. package/dist/{Records-BEz5IFUu.mjs → Records-BAutSSnJ.mjs} +3 -1
  6. package/dist/Records-BAutSSnJ.mjs.map +1 -0
  7. package/dist/{Records-CMByd1eD.d.mts → Records-CV49DgQK.d.mts} +37 -9
  8. package/dist/{RunJournal-B_fxe57c.mjs → RunJournal-DRRRZmG7.mjs} +2 -2
  9. package/dist/{RunJournal-B_fxe57c.mjs.map → RunJournal-DRRRZmG7.mjs.map} +1 -1
  10. package/dist/{Schedule-BxCfnYr0.d.mts → Schedule-DePbGfgd.d.mts} +2 -2
  11. package/dist/{Scheduling-BW6BD_TP.mjs → Scheduling-C3QpYn0W.mjs} +2 -2
  12. package/dist/{Scheduling-BW6BD_TP.mjs.map → Scheduling-C3QpYn0W.mjs.map} +1 -1
  13. package/dist/{Subscription-CrTIQKZR.d.mts → Subscription-BR_8Cxh3.d.mts} +3 -3
  14. package/dist/{SubscriptionInput-BVOeFF1L.d.mts → SubscriptionInput-B95sQbuk.d.mts} +3 -3
  15. package/dist/{agent-registration-BTa5vmQF.mjs → agent-registration-CXGDwvJH.mjs} +151 -26
  16. package/dist/agent-registration-CXGDwvJH.mjs.map +1 -0
  17. package/dist/durable/ActivityStore.d.mts +1 -1
  18. package/dist/durable/ActivityStore.mjs +1 -1
  19. package/dist/durable/Admin.d.mts +1 -1
  20. package/dist/durable/Admin.mjs +1 -1
  21. package/dist/durable/AgentRegistration.d.mts +2 -2
  22. package/dist/durable/AgentRegistration.mjs +3 -2
  23. package/dist/durable/AgentRegistration.mjs.map +1 -1
  24. package/dist/durable/Certification.d.mts +1 -1
  25. package/dist/durable/CommittedActivity.d.mts +1 -1
  26. package/dist/durable/CommittedActivity.mjs +1 -1
  27. package/dist/durable/Digest.d.mts +1 -1
  28. package/dist/durable/Digest.mjs +1 -1
  29. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  30. package/dist/durable/DurableAgentRuntime.mjs +1 -1
  31. package/dist/durable/EventSource.d.mts +1 -1
  32. package/dist/durable/EventSource.mjs +1 -1
  33. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  34. package/dist/durable/GitHubWorkflowSource.mjs +1 -1
  35. package/dist/durable/MessageDelivery.d.mts +3 -3
  36. package/dist/durable/MessageDelivery.mjs +1 -1
  37. package/dist/durable/MessageDeliveryStoreConformance.d.mts +1 -1
  38. package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
  39. package/dist/durable/PersistentHistory.d.mts +1 -1
  40. package/dist/durable/PersistentHistory.mjs +2 -2
  41. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  42. package/dist/durable/Records.d.mts +1 -1
  43. package/dist/durable/Records.mjs +1 -1
  44. package/dist/durable/Recovery.d.mts +1 -1
  45. package/dist/durable/Recovery.mjs +1 -1
  46. package/dist/durable/RunJournal.d.mts +1 -1
  47. package/dist/durable/RunJournal.mjs +1 -1
  48. package/dist/durable/Schedule.d.mts +1 -1
  49. package/dist/durable/Schedule.mjs +1 -1
  50. package/dist/durable/ScheduleStoreConformance.d.mts +1 -1
  51. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  52. package/dist/durable/ScheduleTransition.d.mts +1 -1
  53. package/dist/durable/ScheduleTransition.mjs +1 -1
  54. package/dist/durable/Scheduling.d.mts +2 -2
  55. package/dist/durable/Scheduling.mjs +1 -1
  56. package/dist/durable/SqlStorageV2Upgrade.d.mts +2 -2
  57. package/dist/durable/SqlStorageV2Upgrade.mjs +1 -1
  58. package/dist/durable/SqlSubscriptionStore.d.mts +2 -2
  59. package/dist/durable/SqlSubscriptionStore.mjs +1 -1
  60. package/dist/durable/SubmissionLedger.d.mts +1 -1
  61. package/dist/durable/SubmissionLedger.mjs +1 -1
  62. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  63. package/dist/durable/SubmissionLedgerConformance.mjs +1 -1
  64. package/dist/durable/SubmissionStatus.d.mts +1 -1
  65. package/dist/durable/Subscription.d.mts +1 -1
  66. package/dist/durable/Subscription.mjs +1 -1
  67. package/dist/durable/SubscriptionInput.d.mts +1 -1
  68. package/dist/durable/SubscriptionInput.mjs +2 -2
  69. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  70. package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
  71. package/dist/durable/SubscriptionTools.d.mts +3 -3
  72. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  73. package/dist/durable/SubscriptionTransition.mjs +1 -1
  74. package/dist/durable/Subscriptions.d.mts +5 -5
  75. package/dist/durable/Subscriptions.mjs +1 -1
  76. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  77. package/dist/durable/ThreadContextHistory.mjs +1 -1
  78. package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
  79. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  80. package/dist/durable/ThreadInvariants.d.mts +1 -1
  81. package/dist/durable/ThreadInvariants.mjs +1 -1
  82. package/dist/durable/ThreadProjection.d.mts +1 -1
  83. package/dist/durable/ThreadProjection.mjs +1 -1
  84. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  85. package/dist/durable/ThreadStore.d.mts +1 -1
  86. package/dist/durable/ThreadStore.mjs +1 -1
  87. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  88. package/dist/durable/ThreadStoreConformance.mjs +1 -1
  89. package/dist/durable/ToolReconciler.mjs +1 -1
  90. package/dist/durable/WorkerHost.d.mts +1 -1
  91. package/dist/index.d.mts +6 -6
  92. package/dist/index.mjs +4 -4
  93. package/package.json +1 -1
  94. package/src/durable/AgentRegistration.ts +1 -0
  95. package/src/durable/DurableAgentRuntime.ts +3 -1
  96. package/src/durable/Records.ts +2 -0
  97. package/src/durable/internal/agent-registration.ts +274 -36
  98. package/src/durable/internal/messaging-host.ts +2 -5
  99. package/src/durable/internal/worker-host.ts +119 -85
  100. package/dist/DurableAgentRuntime-BGwGUIT-.mjs.map +0 -1
  101. package/dist/Records-BEz5IFUu.mjs.map +0 -1
  102. package/dist/agent-registration-BTa5vmQF.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"RunJournal-B_fxe57c.mjs","names":[],"sources":["../src/durable/internal/journal-metadata.ts","../src/durable/RunJournal.ts"],"sourcesContent":["import { type RunId } from \"../../core/Identifiers.ts\";\nimport {\n type CanonicalRecordEnvelope,\n type CompactionCreated,\n type ToolCallSettled,\n} from \"../Records.ts\";\nimport { type JournalCheckpointSeed } from \"./journal-checkpoint.ts\";\n\n/** Metadata for one exact canonical prefix, including the same optional checkpoint seed. */\nexport interface JournalMetadata {\n readonly ownerRunId: RunId | undefined;\n readonly seed: JournalCheckpointSeed | undefined;\n readonly firstSequenceByRun: ReadonlyMap<string, number>;\n readonly lastResponseSequenceByRun: ReadonlyMap<string, number>;\n readonly terminalSequenceByRun: ReadonlyMap<string, number>;\n readonly settledSpans: ReadonlyArray<{ readonly from: number; readonly to: number }>;\n readonly settledToolCallRecordIds: ReadonlySet<string>;\n readonly settledById: ReadonlyMap<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >;\n readonly compactions: ReadonlyArray<{\n readonly payload: CompactionCreated;\n readonly sequence: number;\n }>;\n}\n\n/**\n * Attempt-local metadata collector. Feed every validated record exactly once, in canonical order,\n * including records omitted from the control view. A snapshot is independent of later suffix\n * additions and may only accompany a replay stream bounded at that same captured tail.\n */\nexport const makeJournalMetadata = (\n ownerRunId: RunId | undefined,\n seed?: JournalCheckpointSeed,\n) => {\n const firstSequenceByRun = new Map<string, number>();\n\n if (seed?.firstSequence !== undefined) firstSequenceByRun.set(seed.runId, seed.firstSequence);\n const lastResponseSequenceByRun = new Map<string, number>();\n const terminalSequenceByRun = new Map<string, number>();\n const settledSpans: Array<{ readonly from: number; readonly to: number }> = [];\n const settledToolCallRecordIds = new Set<string>();\n\n const settledById = new Map<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >();\n\n const compactions: Array<{ readonly payload: CompactionCreated; readonly sequence: number }> = [];\n\n return {\n add: (envelope: CanonicalRecordEnvelope): void => {\n const payload = envelope.record.payload;\n\n if (\n (payload._tag === \"RunCompleted\" ||\n payload._tag === \"RunFailed\" ||\n payload._tag === \"SubmissionSettled\") &&\n payload.runId !== undefined &&\n !terminalSequenceByRun.has(payload.runId)\n )\n terminalSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"CompactionCreated\") {\n compactions.push({ payload, sequence: envelope.sequence });\n\n return;\n }\n if (\n \"runId\" in payload &&\n typeof payload.runId === \"string\" &&\n !firstSequenceByRun.has(payload.runId)\n )\n firstSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"ModelResponseRecorded\") {\n lastResponseSequenceByRun.set(payload.runId, envelope.sequence);\n } else if (payload._tag === \"ToolCallSettled\") {\n settledToolCallRecordIds.add(envelope.record.recordId);\n if (payload.runId === ownerRunId)\n settledById.set(envelope.record.recordId, {\n isFailure: payload.isFailure,\n ...(payload.toolSelection === undefined\n ? {}\n : { toolSelection: payload.toolSelection }),\n ...(payload.budgetRejected === undefined\n ? {}\n : { budgetRejected: payload.budgetRejected }),\n });\n const from = lastResponseSequenceByRun.get(payload.runId);\n\n if (from !== undefined && from < envelope.sequence)\n settledSpans.push({ from, to: envelope.sequence });\n }\n },\n snapshot: (): JournalMetadata => ({\n ownerRunId,\n seed,\n firstSequenceByRun: new Map(firstSequenceByRun),\n lastResponseSequenceByRun: new Map(lastResponseSequenceByRun),\n terminalSequenceByRun: new Map(terminalSequenceByRun),\n settledSpans: [...settledSpans],\n settledToolCallRecordIds: new Set(settledToolCallRecordIds),\n settledById: new Map(settledById),\n compactions: [...compactions],\n }),\n };\n};\n","import { type Crypto, Effect, Schema, Stream, type DateTime } from \"effect\";\nimport { Prompt } from \"effect/unstable/ai\";\n\nimport { ThreadId, RunId, ToolCallId, TurnId, type SubmissionId } from \"../core/Identifiers.ts\";\nimport { type ExhaustedLimit } from \"../core/RunEvent.ts\";\nimport { RunPolicyUsage } from \"../core/RunPolicyUsage.ts\";\nimport { type Selection, type Snapshot } from \"../core/ToolExposure.ts\";\nimport type { ToolParameterRejection } from \"../core/ToolResult.ts\";\nimport { ModelCallUsage, summarizeModelUsage, type RunUsageSummary } from \"../core/Usage.ts\";\nimport {\n CLEARED_TOOL_RESULT,\n COMPACTION_SUMMARY_PREFIX,\n contextWindowId,\n contextWindowMessage,\n} from \"../engine/Compaction.ts\";\nimport { digestJson, type DigestError } from \"./Digest.ts\";\nimport { type JournalCheckpointSeed } from \"./internal/journal-checkpoint.ts\";\nimport { makeJournalMetadata, type JournalMetadata } from \"./internal/journal-metadata.ts\";\nimport {\n BatchId,\n CanonicalBatch,\n CompactionCreated,\n ModelResponseRecorded,\n PersistedJson,\n RecordEnvelope,\n RecordId,\n RunCompleted,\n ToolCallSettled,\n type CanonicalRecordEnvelope,\n type CanonicalSequence,\n type DeploymentId,\n type ProducerId,\n} from \"./Records.ts\";\nimport { IdempotencyKey } from \"./SubmissionLedger.ts\";\n\n/** A canonical record could not be projected into Run/Prompt state. */\nexport class RunJournalError extends Schema.TaggedError<RunJournalError>()(\"RunJournalError\", {\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n}) {}\n\nconst journalError = (message: string, cause?: unknown): RunJournalError =>\n cause === undefined\n ? RunJournalError.make({ message })\n : RunJournalError.make({ message, cause });\n\nconst decodeRunId = Schema.decodeSync(RunId);\nconst decodeTurnId = Schema.decodeSync(TurnId);\nconst decodeBatchId = Schema.decodeSync(BatchId);\nconst decodeRecordId = Schema.decodeSync(RecordId);\n\n/**\n * Deterministic Run identity pinned per Submission (plan §Coordinator flow). Every Attempt of one\n * Submission shares this Run identity, so canonical per-Turn records from different Attempts\n * belong to one logical Run.\n */\nexport const runIdForSubmission = (submissionId: SubmissionId): RunId =>\n decodeRunId(`run:${submissionId}`);\n\n/** Stable canonical clock identity shared by every Attempt of one Run. */\nexport const runStartedRecordId = (runId: RunId): RecordId => decodeRecordId(`run-start:${runId}`);\n\nexport const runStartedBatchId = (runId: RunId): BatchId => decodeBatchId(`run-start:${runId}`);\n\nexport const runDurationRecordId = (runId: RunId): RecordId =>\n decodeRecordId(`run-duration:${runId}`);\n\nexport const runDurationBatchId = (runId: RunId): BatchId => decodeBatchId(`run-duration:${runId}`);\n\n/** Deterministic Turn identity: Attempt-independent for one (Run, canonical turn) pair. */\nexport const turnIdForRun = (runId: RunId, turn: number): TurnId =>\n decodeTurnId(`turn:${runId}:${turn}`);\n\n/** Deterministic batch identity of one committed canonical no-tool Turn (P4 single-batch shape). */\nexport const turnBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESPONSE commit (plan §2.1 commit 1):\n * the assistant response plus pending steering becomes canonical BEFORE approval preflight and\n * tool preparation, creating the durability §15 \"resume tool scheduling\" window.\n */\nexport const turnResponseBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-response:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESULTS commit (plan §2.1 commit 5):\n * every `ToolCallSettled` record of the Turn, in declaration order, model-visible atomically.\n */\nexport const turnResultsBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-results:${runId}:${turn}`);\n\n/**\n * Deterministic per-call late-settle batch identity used by the resolution path when one\n * recovered/resolved call settles outside its Turn's results batch. Record identity\n * (`tool-settled:{runId}:{turn}:{toolCallId}`) dedupes double-settles across both paths.\n */\nexport const toolCallResultBatchId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`turn-results:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Turn's `ToolCallPrepared` commit (plan §2.1 commit 3). */\nexport const turnPreparedBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-prepared:${runId}:${turn}`);\n\n/**\n * Deterministic identity of one pre-Turn compaction record (RUN-026,\n * RUN-026). Keyed by Run, Turn, and kind — the engine performs at most one\n * threshold compaction per Turn plus at most one overflow-forced summarize,\n * so a superseding Attempt that re-decides the same compaction replays the\n * batch identity instead of duplicating the record.\n */\nexport const compactionRecordId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): RecordId => decodeRecordId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic batch identity of one compaction append (same string as its record id). */\nexport const compactionBatchId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): BatchId => decodeBatchId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic canonical record identity of one Turn's `ModelResponseRecorded` record. */\nexport const modelResponseRecordId = (runId: RunId, turn: number): RecordId =>\n decodeRecordId(`model-response:${runId}:${turn}`);\n\n/** Terminal Tool completion marker committed atomically with its settled Tool result. */\nexport const runCompletedRecordId = (runId: RunId): RecordId =>\n decodeRecordId(`run-completed:${runId}`);\n\n/** Deterministic canonical record identity of one Turn's `ToolCallSettled` record. */\nexport const toolCallSettledRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-settled:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallPrepared` record. */\nexport const toolCallPreparedRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-prepared:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Turn's `ToolCallUnknown` marking append. */\nexport const markUnknownBatchId = (submissionId: SubmissionId, turn: number): BatchId =>\n decodeBatchId(`mark-unknown:${submissionId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallUnknown` record. */\nexport const toolCallUnknownRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-unknown:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's resolution append (DUR-017). */\nexport const toolCallResolutionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`resolve:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallResolved` record. */\nexport const toolCallResolvedRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-resolved:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one accepted Durable Step result. The one-record batch reuses the\n * SAME string, so batch idempotency plus the epoch fence realize the durability §11\n * racing-writers rule: only the fenced winner's record commits; the loser replays it.\n * A versioned JSON tuple keeps separator characters in each identity component distinct.\n * Replay derives this key from the structured payload, including records with legacy IDs.\n */\nexport const toolStepSettledRecordId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): RecordId => decodeRecordId(JSON.stringify([\"step@2\", runId, toolCallId, stepName]));\n\n/** Deterministic batch identity of one Durable Step commit (same string as its record id). */\nexport const toolStepSettledBatchId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): BatchId => decodeBatchId(toolStepSettledRecordId(runId, toolCallId, stepName));\n\n/** Deterministic batch identity of one Turn's canonical approval-request append (plan §2.6). */\nexport const turnApprovalsBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-approvals:${runId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalRequested` record. */\nexport const toolApprovalRequestRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`approval-request:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's canonical approval-decision append. */\nexport const approvalDecisionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`approval-decision:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalDecided` record. */\nexport const toolApprovalDecisionRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`approval-decision:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one superseded Attempt's `ModelResponseInterrupted` audit record\n * (durability §9). Keyed by the superseded epoch, so each interrupted ownership period is\n * recorded at most once; the one-record batch reuses the same string.\n */\nexport const modelResponseInterruptedRecordId = (runId: RunId, supersededEpoch: number): RecordId =>\n decodeRecordId(`interrupted:${runId}:${supersededEpoch}`);\n\n/** Deterministic batch identity of one `ModelResponseInterrupted` append (same string). */\nexport const modelResponseInterruptedBatchId = (runId: RunId, supersededEpoch: number): BatchId =>\n decodeBatchId(`interrupted:${runId}:${supersededEpoch}`);\n\nconst decodeThreadId = Schema.decodeSync(ThreadId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentRequested` record.\n * The one-record batch reuses the same string, so batch\n * idempotency plus the parent epoch fence make the request append exactly-once-canonical.\n */\nexport const subagentRequestedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-requested:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentRequested` append (same string). */\nexport const subagentRequestedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-requested:${runId}:${toolCallId}`);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentStarted` record.\n * Recovery's start-link repair appends the EXACT same record\n * under this identity, so a raced repair replays instead of duplicating (SUB-016/SUB-017).\n */\nexport const subagentStartedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-started:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentStarted` append (same string). */\nexport const subagentStartedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-started:${runId}:${toolCallId}`);\n\n/**\n * Deterministic batch identity of one parent Tool Call's atomic settlement join: the\n * `SubagentJoined` record plus the parent's `ToolCallSettled` record (its existing\n * `tool-settled:{runId}:{turn}:{toolCallId}` identity) commit as ONE canonical batch (SUB-019).\n */\nexport const subagentJoinBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-join:${runId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one parent Tool Call's `SubagentJoined` record. */\nexport const subagentJoinedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-joined:${runId}:${toolCallId}`);\n\n/**\n * Deterministic identity of one child Thread's `SubagentLineageRecorded` record.\n * Its own single-record batch reuses the same string so the generic\n * `thread-created:{cid}` batch identity is never contradicted.\n */\nexport const subagentLineageRecordId = (threadId: ThreadId): RecordId =>\n decodeRecordId(`subagent-lineage:${threadId}`);\n\n/** Deterministic batch identity of one `SubagentLineageRecorded` append (same string). */\nexport const subagentLineageBatchId = (threadId: ThreadId): BatchId =>\n decodeBatchId(`subagent-lineage:${threadId}`);\n\n/**\n * Deterministic intended child Thread identity: the\n * parent Submission and Tool Call pair addresses exactly one child Thread, so a replayed\n * establishment converges on the one existing child (SUB-016).\n */\nexport const childThreadIdFor = (\n parentSubmissionId: SubmissionId,\n toolCallId: ToolCallId,\n): ThreadId => decodeThreadId(`subagent:${parentSubmissionId}:${toolCallId}`);\n\n/**\n * Deterministic child admission idempotency key: scoped to\n * the parent Run and Tool Call identity, so duplicate admission attempts resolve through the\n * ledger's idempotency contract to one child Receipt (SUB-016, SUB-031). The ledger key is\n * bounded (256); coordinator-minted Run and Tool Call identities stay far below that bound.\n */\nexport const childIdempotencyKeyFor = (\n parentRunId: RunId,\n toolCallId: ToolCallId,\n): IdempotencyKey => decodeIdempotencyKey(`subagent:${parentRunId}:${toolCallId}`);\n\nconst decodePromptMessages = Effect.fn(\"RunJournal.decodePromptMessages\")(\n (messages: PersistedJson): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n Schema.decodeUnknownEffect(Prompt.Prompt)(messages).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical messages are not Schema-encoded Prompt messages\", cause),\n ),\n ),\n);\n\ninterface PendingSettledTool {\n readonly record: ToolCallSettled;\n /** RUN-026: a `clear-tool-results` compaction covers this record's sequence. */\n readonly cleared: boolean;\n}\n\nconst toolMessageFromSettled = Effect.fn(\"RunJournal.toolMessageFromSettled\")(\n (settled: ReadonlyArray<PendingSettledTool>): Effect.Effect<Prompt.Message, RunJournalError> =>\n Effect.try({\n try: () =>\n Prompt.makeMessage(\"tool\", {\n content: settled.map(({ record, cleared }) =>\n Prompt.makePart(\"tool-result\", {\n id: record.toolCallId,\n name: record.toolName,\n result: cleared ? CLEARED_TOOL_RESULT : record.result,\n isFailure: record.isFailure,\n providerExecuted: false,\n }),\n ),\n }),\n catch: (cause) => journalError(\"Unable to rebuild Tool message from ToolCallSettled\", cause),\n }),\n);\n\n/**\n * Pure canonical projection of one Run's durable execution state.\n *\n * Prompt reconstruction contract (D8):\n *\n * - `ModelResponseRecorded.messages` carries the Schema-encoded Prompt messages the Turn appended\n * to the model-visible prompt — for the Run's FIRST committed Turn that includes the evaluated\n * instruction and user-input messages, for later Turns only the assistant response messages.\n * Tool messages are excluded from `messages`.\n * - `ToolCallSettled` records (committed in the same per-Turn batch, in declaration order)\n * deterministically rebuild the Turn's single Tool message.\n * - `UserInputRecorded` records input, with a Submission identity only for durable admission. Its\n * Prompt-visible form (instructions + user message) becomes canonical inside the owning Run's\n * first `ModelResponseRecorded`. The projection consumes it only for Run correlation.\n * - Immediate retained history uses `ModelCompleted.messages` for the successful Run's exact\n * native Prompt suffix, including any input examples. It has no resumable Turn state.\n */\n/** Cumulative committed usage of the projected Run (RUN-023 resume re-seed). */\nexport interface RunJournalUsage {\n readonly modelCalls: number;\n /** Known accounting gaps retained across Attempts without changing numeric usage totals. */\n readonly unobservedModelCalls?: number | undefined;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly lastInputTokens: number;\n readonly lastOutputTokens: number;\n /** Cumulative persisted spend of the projected Run's committed calls (RUN-023). */\n readonly costMicrousd: number;\n /** Canonical per-call detail used for settlement aggregation and recovery. */\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n /** Detailed usage of retired records, grouped without retaining per-call payloads. */\n readonly summarizedModelUsage?: RunUsageSummary | undefined;\n}\n\nexport interface RunJournalProjection {\n readonly toolSelection?: Selection | undefined;\n readonly policyUsage: RunPolicyUsage;\n /** Canonical projection for the requested Run; may end at its resumable Tool declaration. */\n readonly prompt: Prompt.Prompt;\n /** Valid prior-Run history excluding the projected Run's records and orphan Tool batches. */\n readonly historyBefore: Prompt.Prompt;\n /** Number of canonical Turns already committed for the projected Run. */\n readonly committedTurns: number;\n /** Summed per-call usage of the projected Run's committed responses; zeros for records predating usage capture. */\n readonly usage: RunJournalUsage;\n /** Latest committed context window identity, retained across ownership changes. */\n readonly contextWindowId?: string | undefined;\n /** Canonical evaluated instructions and initial input for this Run, independent of the view. */\n readonly protectedContext?: Prompt.Prompt | undefined;\n /** Last successful singleton Tool awaiting possible context-control interpretation by the engine. */\n readonly pendingContextToolCallId?: string | undefined;\n}\n\ninterface ProjectedResponseUsage {\n readonly modelCalls: number;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd: number;\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n}\n\nconst projectedResponseUsage = (\n response: ModelResponseRecorded,\n): Effect.Effect<ProjectedResponseUsage, RunJournalError> =>\n Effect.gen(function* () {\n const calls = response.modelUsage;\n\n if (calls === undefined) {\n return {\n modelCalls: 1,\n inputTokens: response.inputTokens ?? 0,\n outputTokens: response.outputTokens ?? 0,\n costMicrousd: response.costMicrousd ?? 0,\n modelUsage: [],\n };\n }\n if (calls.length === 0) {\n return yield* journalError(\"A canonical modelUsage list must not be empty\");\n }\n\n const summary = yield* summarizeModelUsage(calls).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical model usage exceeds accounting bounds\", cause),\n ),\n );\n\n if (\n (response.inputTokens !== undefined && response.inputTokens !== summary.inputTokens.total) ||\n (response.outputTokens !== undefined &&\n response.outputTokens !== summary.outputTokens.total) ||\n (response.costMicrousd !== undefined && response.costMicrousd !== summary.costMicrousd)\n ) {\n return yield* journalError(\"Canonical detailed and aggregate model usage disagree\");\n }\n\n return {\n modelCalls: summary.modelCalls,\n inputTokens: summary.inputTokens.total,\n outputTokens: summary.outputTokens.total,\n costMicrousd: summary.costMicrousd,\n modelUsage: calls,\n };\n });\n\nconst addProjectedUsage = (\n field: string,\n left: number,\n right: number,\n): Effect.Effect<number, RunJournalError> =>\n Schema.decodeEffect(Schema.Natural)(left + right).pipe(\n Effect.mapError((cause) =>\n journalError(`Canonical projected usage exceeds safe-integer bounds at ${field}`, cause),\n ),\n );\n\ninterface FoldState {\n readonly all: Array<Prompt.Message>;\n readonly before: Array<Prompt.Message>;\n readonly pendingTools: Array<PendingSettledTool>;\n readonly pendingToolsForRun: boolean;\n readonly committedTurns: number;\n}\n\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\n\nconst declaredApplicationToolCallIds = (prompt: Prompt.Prompt): ReadonlyArray<string> => {\n const ids: Array<string> = [];\n\n for (const message of prompt.content) {\n if (message.role !== \"assistant\") continue;\n for (const part of message.content) {\n if (part.type === \"tool-call\" && !part.providerExecuted) ids.push(part.id);\n }\n }\n\n return ids;\n};\n\nconst withoutApplicationToolCallMessages = (prompt: Prompt.Prompt): ReadonlyArray<Prompt.Message> =>\n prompt.content.filter(\n (message) =>\n message.role !== \"assistant\" ||\n !message.content.some((part) => part.type === \"tool-call\" && !part.providerExecuted),\n );\n\n/**\n * Phase 5 audit tags that are prompt-transparent: they carry durability evidence (preparation,\n * unknown marking, resolution, Step results, approvals, interruption) but contribute nothing to\n * the model-visible Prompt, and — unlike the P4 tags — they do NOT split a contiguous\n * `ToolCallSettled` group into separate Tool messages, so a late-settled call's audit records\n * cannot change the replayed prompt shape.\n *\n * The four S2 Subagent lifecycle tags are prompt-transparent for the same reason (spec §5/§11):\n * the parent prompt never carries child transcript or establishment evidence — the joined child\n * result reaches the model exclusively through the paired `ToolCallSettled` record, and the\n * child-log lineage record is not model input.\n */\nconst PROMPT_TRANSPARENT_TAGS: ReadonlySet<string> = new Set([\n \"RunPolicyUsageReserved\",\n \"RunStarted\",\n \"RunDurationExhausted\",\n \"ToolCallPrepared\",\n \"ToolCallUnknown\",\n \"ToolCallResolved\",\n \"ToolStepSettled\",\n \"ToolApprovalRequested\",\n \"ToolApprovalDecided\",\n \"ModelResponseInterrupted\",\n \"SubagentRequested\",\n \"SubagentStarted\",\n \"SubagentJoined\",\n \"SubagentLineageRecorded\",\n \"WorkerInputRequested\",\n \"WorkerOriginRecorded\",\n \"WorkerInputCompleted\",\n \"WorkerReportPrepared\",\n \"AgentUpdateEmitted\",\n \"WorkerReportRefused\",\n \"PeerMessagePrepared\",\n \"SubtreeBudgetReserved\",\n]);\n\n/**\n * Pure projection: rebuild one Run's resume state from canonical records (DUR-015). Canonical\n * order is authoritative; the fold projects each complete `ModelResponseRecorded` Turn and the\n * owning Run's resumable incomplete Tool Turn, while excluding incomplete Tool batches from prior\n * Runs. It flushes each contiguous group of valid `ToolCallSettled` records into one Tool message,\n * exactly mirroring the per-Turn commit shape produced by `turnCanonicalBatch` (no-tool Turns) and\n * by the\n * `turnResponseBatch`/`turnResultsBatch` split (tool-declaring Turns). The Phase 5 audit tags\n * are skipped transparently, so split-batch commits replay to the same prompt as P4 single-batch\n * commits.\n *\n * An incomplete application Tool turn remains visible while projecting its owning Run so active\n * recovery can resume the declared batch. It is not a valid model-visible Turn boundary for a\n * later Run: the orphan assistant Tool declaration and any partial Tool results from that Turn\n * are excluded, while preceding instruction/user messages in the response record remain history.\n */\n/** @internal Lightweight canonical boundaries collected without retaining record payloads. */\nexport interface JournalBoundary {\n readonly sequence: CanonicalSequence;\n readonly tag: \"ModelResponseRecorded\" | \"ToolCallSettled\";\n readonly promptLength: number;\n /** A declaration without all settled results requires terminal-prior-Run proof for coverage. */\n readonly incomplete?: true | undefined;\n /** The Run terminated after its last response and differs from the projection's owner. */\n readonly terminalPriorRun?: true | undefined;\n}\n\n/**\n * Reconstruct a fixed canonical prefix from a re-readable stream. The caller must keep the same\n * records visible on every traversal. The first collects compaction and settlement metadata;\n * rollovers additionally validate covered Tool batches before rebuilding Prompt and usage. Metadata and the\n * live Prompt remain resident; covered historical message/tool payloads do not. An uncompacted Prompt still grows\n * with its conversation, so hosts must configure an appropriate context compaction policy.\n * Prepared metadata must describe exactly this stream and seed through the same fixed tail;\n * it skips only the metadata scan, never covered-Tool validation or the canonical fold.\n * @internal\n */\nexport const projectRunJournalStream = Effect.fn(\"RunJournal.projectRunJournalStream\")(function* <\n E,\n R,\n>(\n records: Stream.Stream<CanonicalRecordEnvelope, E, R>,\n ownerRunId: RunId | undefined,\n onBoundary?: (boundary: JournalBoundary) => void,\n seed?: JournalCheckpointSeed,\n preparedMetadata?: JournalMetadata,\n): Effect.fn.Return<RunJournalProjection, RunJournalError | E, R> {\n if (seed !== undefined && seed.runId !== ownerRunId)\n return yield* journalError(\"Recovery checkpoint belongs to another Run\");\n\n let state: FoldState = {\n all: [],\n before: [],\n pendingTools: [],\n pendingToolsForRun: false,\n committedTurns: seed?.committedTurns ?? 0,\n };\n\n // RUN-026 pre-scan: the widest VALID compaction bounds govern the fold. A\n // valid record covers strictly below its own sequence and never splits a response from its\n // settled tool results. Pruning and rollovers may cover complete owner-Run batches;\n // a summarize record must carry its summary. Invalid records\n // are ignored fail-safe — the full history stays authoritative. Ties on\n // coversThrough resolve to the record appended later (higher sequence),\n // matching at-most-once replay intent.\n // One span per settled record, paired with its declaring response the same\n // way the fold pairs them: a settled belongs to the most recent\n // ModelResponseRecorded of its Run. A bound inside (response, settled)\n // would orphan the tool message from its declaring response. Orphaned\n // settleds (filtered later by the fold) still contribute spans —\n // over-invalidating is the fail-safe direction.\n if (\n preparedMetadata !== undefined &&\n (preparedMetadata.ownerRunId !== ownerRunId || preparedMetadata.seed !== seed)\n )\n return yield* journalError(\"Prepared journal metadata belongs to another replay\");\n\n let metadata = preparedMetadata;\n\n if (metadata === undefined) {\n const collected = makeJournalMetadata(ownerRunId, seed);\n\n yield* Stream.runForEach(records, (envelope) => Effect.sync(() => collected.add(envelope)));\n metadata = collected.snapshot();\n }\n\n const {\n firstSequenceByRun,\n lastResponseSequenceByRun,\n terminalSequenceByRun,\n settledSpans,\n settledToolCallRecordIds,\n settledById,\n compactions,\n } = metadata;\n\n const settledCoverage = compactions.reduce(\n (through, { payload }) =>\n payload.kind !== \"summarize\" ? Math.max(through, payload.coversThrough) : through,\n 0,\n );\n\n // Terminality changes only prompt coverage; it never settles or resolves the Tool Call.\n // Compare against the compaction's Run and sequence, independent of the replay's owner.\n const isTerminalPriorRun = (\n candidateRunId: RunId,\n compactionRunId: RunId | undefined,\n beforeSequence: number,\n ): boolean => {\n const terminal = terminalSequenceByRun.get(candidateRunId);\n\n return (\n candidateRunId !== compactionRunId &&\n terminal !== undefined &&\n terminal < beforeSequence &&\n terminal > (lastResponseSequenceByRun.get(candidateRunId) ?? 0)\n );\n };\n\n const incompleteResponseSequences: Array<{ readonly sequence: number; readonly runId: RunId }> =\n [];\n\n let ownerPrefixSequence = seed?.firstSequence ?? Number.POSITIVE_INFINITY;\n\n let protectedContext: Prompt.Prompt | undefined =\n seed?.protectedContext === undefined\n ? undefined\n : yield* decodePromptMessages(seed.protectedContext);\n\n if (settledCoverage > 0) {\n yield* Stream.runForEach(records, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (payload._tag !== \"ModelResponseRecorded\" || envelope.sequence > settledCoverage) return;\n const messages = yield* decodePromptMessages(payload.messages);\n const declared = declaredApplicationToolCallIds(messages);\n\n for (const id of declared) {\n const callId = yield* Schema.decodeEffect(ToolCallId)(id).pipe(\n Effect.mapError((cause) =>\n journalError(\"Failed to decode a declared Tool Call ID\", cause),\n ),\n );\n\n if (\n !settledToolCallRecordIds.has(\n toolCallSettledRecordId(payload.runId, payload.turn, callId),\n )\n ) {\n incompleteResponseSequences.push({ sequence: envelope.sequence, runId: payload.runId });\n break;\n }\n }\n if (\n payload.runId === ownerRunId &&\n payload.turn === 1 &&\n payload.runScopedPrefixLength !== undefined\n ) {\n ownerPrefixSequence = envelope.sequence;\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n }),\n );\n }\n\n const boundIsValid = (payload: CompactionCreated, ownSequence: number): boolean => {\n const { runId, coversThrough } = payload;\n\n if (coversThrough <= 0 || coversThrough >= ownSequence) return false;\n if (seed !== undefined && ownSequence === seed.compaction.sequence)\n return (\n seed.compaction.record.payload._tag === \"CompactionCreated\" &&\n Schema.toEquivalence(CompactionCreated)(payload, seed.compaction.record.payload)\n );\n const ownerFirst = firstSequenceByRun.get(runId);\n\n if (payload.kind === \"summarize\" && ownerFirst !== undefined && coversThrough >= ownerFirst)\n return false;\n if (\n payload.kind !== \"summarize\" &&\n incompleteResponseSequences.some(\n (response) =>\n response.sequence <= coversThrough &&\n !isTerminalPriorRun(response.runId, runId, ownSequence),\n )\n )\n return false;\n for (const span of settledSpans) {\n if (span.from <= coversThrough && coversThrough < span.to) return false;\n }\n\n return true;\n };\n\n let summarizeBound = 0;\n let replacement: CompactionCreated | undefined;\n let summarizeSequence = -1;\n let clearBound = 0;\n let latestWindowId: string | undefined = seed?.contextWindowId;\n let latestWindowSequence = seed?.throughSequence ?? -1;\n let rolloverCoveredThrough = 0;\n\n for (const { payload, sequence } of compactions) {\n if (!boundIsValid(payload, sequence)) continue;\n if (payload.kind === \"rollover\" && sequence > latestWindowSequence) {\n latestWindowId = contextWindowId(payload.runId, payload.turn);\n latestWindowSequence = sequence;\n }\n if (payload.kind === \"rollover\")\n rolloverCoveredThrough = Math.max(rolloverCoveredThrough, payload.coversThrough);\n if (payload.kind === \"summarize\" || payload.kind === \"rollover\") {\n if (payload.kind === \"summarize\" && payload.summary === undefined) continue;\n if (\n payload.coversThrough > summarizeBound ||\n (payload.coversThrough === summarizeBound && sequence > summarizeSequence)\n ) {\n summarizeBound = payload.coversThrough;\n summarizeSequence = sequence;\n replacement = payload;\n }\n } else if (payload.coversThrough > clearBound) {\n clearBound = payload.coversThrough;\n }\n }\n let summaryEmitted = false;\n\n const retainedPrefix =\n replacement?.kind === \"rollover\" &&\n replacement.runId === ownerRunId &&\n ownerPrefixSequence <= summarizeBound\n ? (protectedContext?.content ?? [])\n : [];\n\n const replacementLength = replacement === undefined ? 0 : retainedPrefix.length + 1;\n\n if (seed?.frontier !== undefined)\n onBoundary?.({ ...seed.frontier, promptLength: replacementLength });\n\n const emitSummary = () => {\n if (summaryEmitted || replacement === undefined) return;\n summaryEmitted = true;\n\n const message =\n replacement.kind === \"rollover\"\n ? contextWindowMessage(\n contextWindowId(replacement.runId, replacement.turn),\n replacement.handoff,\n )\n : Prompt.makeMessage(\"user\", {\n content: [\n Prompt.makePart(\"text\", {\n text: `${COMPACTION_SUMMARY_PREFIX}${replacement.summary}`,\n }),\n ],\n });\n\n state.all.push(...retainedPrefix, message);\n if (replacement.kind !== \"rollover\" || replacement.runId !== ownerRunId)\n state.before.push(message);\n };\n\n const modelUsage: Array<ModelCallUsage> = [];\n let unobservedModelCalls = seed?.unobservedModelCalls ?? 0;\n\n const usage = {\n modelCalls: seed?.modelCalls ?? 0,\n inputTokens: seed?.inputTokens ?? 0,\n outputTokens: seed?.outputTokens ?? 0,\n lastInputTokens: seed?.lastInputTokens ?? 0,\n lastOutputTokens: seed?.lastOutputTokens ?? 0,\n costMicrousd: seed?.costMicrousd ?? 0,\n modelUsage,\n ...(seed === undefined ? {} : { summarizedModelUsage: seed.summarizedModelUsage }),\n };\n\n let toolSelection = seed?.toolSelection;\n let usageTurn = seed?.committedTurns ?? 0;\n\n const incompleteToolTurns = new Set<string>();\n const incompleteToolCalls = new Set<string>();\n let pendingContextToolCallId: string | undefined;\n let ownerTerminated = false;\n\n const policyUsage = {\n committedTurns: seed?.policyUsage.committedTurns ?? 0,\n toolCalls: seed?.policyUsage.toolCalls ?? 0,\n programmaticToolCalls: seed?.policyUsage.programmaticToolCalls ?? 0,\n consecutiveToolFailures: seed?.policyUsage.consecutiveToolFailures ?? 0,\n finalizationUsed: seed?.policyUsage.finalizationUsed ?? false,\n };\n\n const accountResponse = Effect.fn(\"RunJournal.accountResponse\")(function* (\n envelope: CanonicalRecordEnvelope,\n payload: ModelResponseRecorded,\n messages: Prompt.Prompt,\n ) {\n const record = envelope.record;\n\n const declared = declaredApplicationToolCallIds(messages);\n const declaredRecordIds: Array<RecordId> = [];\n\n for (const id of declared) {\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(id),\n catch: (cause) => journalError(\"Failed to decode a declared Tool Call ID\", cause),\n });\n\n declaredRecordIds.push(toolCallSettledRecordId(payload.runId, payload.turn, toolCallId));\n }\n if (declaredRecordIds.some((recordId) => !settledToolCallRecordIds.has(recordId))) {\n incompleteToolTurns.add(envelope.record.recordId);\n for (const recordId of declaredRecordIds) incompleteToolCalls.add(recordId);\n }\n if (payload.runId !== ownerRunId) return;\n if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;\n if (payload.turn === 1 && payload.runScopedPrefixLength !== undefined) {\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n\n const responseUsage = yield* projectedResponseUsage(payload);\n\n unobservedModelCalls = yield* addProjectedUsage(\n \"unobservedModelCalls\",\n unobservedModelCalls,\n payload.unobservedModelCalls ?? 0,\n );\n\n usage.modelCalls = yield* addProjectedUsage(\n \"modelCalls\",\n usage.modelCalls,\n responseUsage.modelCalls,\n );\n usage.inputTokens = yield* addProjectedUsage(\n \"inputTokens\",\n usage.inputTokens,\n responseUsage.inputTokens,\n );\n usage.outputTokens = yield* addProjectedUsage(\n \"outputTokens\",\n usage.outputTokens,\n responseUsage.outputTokens,\n );\n usage.costMicrousd = yield* addProjectedUsage(\n \"costMicrousd\",\n usage.costMicrousd,\n responseUsage.costMicrousd,\n );\n usage.modelUsage.push(...responseUsage.modelUsage);\n if (payload.turn > usageTurn) {\n usageTurn = payload.turn;\n usage.lastInputTokens = responseUsage.inputTokens;\n usage.lastOutputTokens = responseUsage.outputTokens;\n }\n\n policyUsage.committedTurns = Math.max(policyUsage.committedTurns, payload.turn);\n\n const calls = messages.content.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.filter((part) => part.type === \"tool-call\")\n : [],\n );\n\n const candidate = calls.length === 1 ? calls[0] : undefined;\n\n const candidateResult =\n candidate === undefined\n ? undefined\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${candidate.id}`);\n\n pendingContextToolCallId =\n candidate !== undefined &&\n !candidate.providerExecuted &&\n candidateResult?.isFailure === false &&\n candidateResult.budgetRejected !== true &&\n envelope.sequence > rolloverCoveredThrough\n ? candidate.id\n : undefined;\n\n policyUsage.toolCalls += calls.length;\n if (payload.toolExposure !== undefined) toolSelection = payload.toolExposure.selection;\n if (incompleteToolTurns.has(record.recordId)) return;\n for (const call of calls) {\n const result = call.providerExecuted\n ? messages.content\n .flatMap((message) => (message.role === \"assistant\" ? message.content : []))\n .find(\n (part) => part.type === \"tool-result\" && part.providerExecuted && part.id === call.id,\n )\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${call.id}`);\n\n if (result === undefined || (\"budgetRejected\" in result && result.budgetRejected === true))\n continue;\n if (!(\"isFailure\" in result)) continue;\n if (!result.isFailure && \"toolSelection\" in result && result.toolSelection !== undefined)\n toolSelection = result.toolSelection;\n policyUsage.consecutiveToolFailures = result.isFailure\n ? policyUsage.consecutiveToolFailures + 1\n : 0;\n }\n });\n\n let pendingToolOrder = new Map<string, number>();\n\n const flushTools = Effect.fn(\"RunJournal.flushTools\")(function* (\n current: FoldState,\n ): Effect.fn.Return<FoldState, RunJournalError> {\n if (current.pendingTools.length === 0) return current;\n\n // Suspension can persist an ordinary sibling before a delegated call joins. Model context\n // still uses declaration order, matching the live interpreter's completed results batch.\n const ordered = current.pendingTools.toSorted(\n (left, right) =>\n (pendingToolOrder.get(left.record.toolCallId) ?? Number.MAX_SAFE_INTEGER) -\n (pendingToolOrder.get(right.record.toolCallId) ?? Number.MAX_SAFE_INTEGER),\n );\n\n const toolMessage = yield* toolMessageFromSettled(ordered);\n\n current.all.push(toolMessage);\n if (!current.pendingToolsForRun) current.before.push(toolMessage);\n\n return {\n ...current,\n pendingTools: [],\n pendingToolsForRun: false,\n };\n });\n\n yield* Stream.runForEach(records, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (\n ((payload._tag === \"RunCompleted\" || payload._tag === \"RunFailed\") &&\n payload.runId === ownerRunId) ||\n (payload._tag === \"SubmissionSettled\" &&\n runIdForSubmission(payload.submissionId) === ownerRunId)\n )\n ownerTerminated = true;\n\n if (payload._tag === \"RunPolicyUsageReserved\" && payload.runId === ownerRunId) {\n if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;\n if (\n payload.programmaticToolCalls < policyUsage.programmaticToolCalls ||\n (policyUsage.finalizationUsed && !payload.finalizationUsed)\n ) {\n return yield* journalError(\"Run policy reservations must be monotonic\");\n }\n policyUsage.programmaticToolCalls = payload.programmaticToolCalls;\n policyUsage.finalizationUsed = payload.finalizationUsed;\n }\n if (PROMPT_TRANSPARENT_TAGS.has(payload._tag)) return;\n // The compaction record governs the fold (pre-scan) and contributes no\n // message of its own; records at or below the summarize bound render as\n // the one summary message emitted at the covered/kept transition.\n if (payload._tag === \"CompactionCreated\") return;\n if (\n seed !== undefined &&\n envelope.sequence <= seed.throughSequence &&\n (payload._tag === \"ModelResponseRecorded\" || payload._tag === \"ToolCallSettled\")\n )\n return;\n if (envelope.sequence <= summarizeBound) {\n // Projecting an earlier Run after a later summary still accounts for its covered responses.\n if (payload._tag === \"ModelResponseRecorded\" && payload.runId === ownerRunId) {\n const messages = yield* decodePromptMessages(payload.messages);\n\n yield* accountResponse(envelope, payload, messages);\n state = { ...state, committedTurns: Math.max(state.committedTurns, payload.turn) };\n }\n if (payload._tag === \"ModelResponseRecorded\" || payload._tag === \"ToolCallSettled\") {\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: replacementLength,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolTurns.has(envelope.record.recordId) ||\n incompleteToolCalls.has(envelope.record.recordId)\n ? { incomplete: true }\n : {}),\n });\n }\n\n return;\n }\n emitSummary();\n if (payload._tag === \"ToolCallSettled\") {\n if (payload.runId !== ownerRunId && incompleteToolCalls.has(envelope.record.recordId)) {\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length + (state.pendingTools.length === 0 ? 0 : 1),\n incomplete: true,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n });\n\n return;\n }\n if (\n state.pendingTools.length > 0 &&\n state.pendingToolsForRun !== (payload.runId === ownerRunId)\n ) {\n state = yield* flushTools(state);\n }\n state.pendingTools.push({ record: payload, cleared: envelope.sequence <= clearBound });\n state = {\n ...state,\n pendingToolsForRun: payload.runId === ownerRunId,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length + 1,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n\n return;\n }\n state = yield* flushTools(state);\n if (payload._tag === \"ModelCompleted\" && payload.messages !== undefined) {\n const messages = yield* decodePromptMessages(payload.messages);\n\n for (const message of messages.content) {\n state.all.push(message);\n if (payload.runId !== ownerRunId) state.before.push(message);\n }\n\n return;\n }\n if (payload._tag !== \"ModelResponseRecorded\") return;\n const messages = yield* decodePromptMessages(payload.messages);\n const forRun = payload.runId === ownerRunId;\n\n pendingToolOrder = new Map(\n declaredApplicationToolCallIds(messages).map((id, index) => [id, index]),\n );\n\n yield* accountResponse(envelope, payload, messages);\n\n const modelVisible =\n !forRun && payload.runScopedPrefixLength !== undefined\n ? Prompt.fromMessages(messages.content.slice(payload.runScopedPrefixLength))\n : messages;\n\n const visibleMessages =\n !forRun && incompleteToolTurns.has(envelope.record.recordId)\n ? withoutApplicationToolCallMessages(modelVisible)\n : modelVisible.content;\n\n for (const message of visibleMessages) {\n state.all.push(message);\n if (!forRun) state.before.push(message);\n }\n state = {\n ...state,\n committedTurns: forRun\n ? Math.max(state.committedTurns, payload.turn)\n : state.committedTurns,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolTurns.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n }),\n );\n emitSummary();\n state = yield* flushTools(state);\n\n const validatedPolicyUsage = yield* Schema.decodeEffect(RunPolicyUsage)(policyUsage).pipe(\n Effect.mapError((cause) =>\n journalError(\"Run policy accounting exceeds its Schema bounds\", cause),\n ),\n );\n\n return {\n ...(toolSelection === undefined ? {} : { toolSelection }),\n policyUsage: validatedPolicyUsage,\n prompt: Prompt.fromMessages(state.all),\n historyBefore: Prompt.fromMessages(state.before),\n committedTurns: state.committedTurns,\n usage: unobservedModelCalls === 0 ? usage : { ...usage, unobservedModelCalls },\n ...(latestWindowId === undefined ? {} : { contextWindowId: latestWindowId }),\n ...(protectedContext === undefined ? {} : { protectedContext }),\n ...(ownerTerminated || pendingContextToolCallId === undefined\n ? {}\n : { pendingContextToolCallId }),\n };\n});\n\n/** Pure projection of one Run's durable recovery state from canonical records. */\nexport const projectRunJournal = Effect.fn(\"RunJournal.projectRunJournal\")(\n (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n runId: RunId,\n ): Effect.Effect<RunJournalProjection, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), runId),\n);\n\n/**\n * Pure valid-prompt projection from canonical records: `UserInputRecorded` +\n * `ModelResponseRecorded` + complete `ToolCallSettled` batches → the deterministic model-visible\n * Prompt (plan §Coordinator flow step 3).\n */\nexport const promptFromCanonicalRecords = Effect.fn(\"RunJournal.promptFromCanonicalRecords\")(\n (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n ): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), undefined).pipe(\n Effect.map((projection) => projection.prompt),\n ),\n);\n\n/** Everything one committed Turn contributes to its canonical batch. */\n/**\n * Staged usage is validated, never repaired: clamping negatives or truncating\n * fractions would under-record canonical usage, and NaN/Infinity must fail\n * typed instead of escaping as a record-construction defect (RUN-023).\n */\nconst validStagedUsage = (label: string, value: number): Effect.Effect<number, RunJournalError> =>\n Number.isSafeInteger(value) && value >= 0\n ? Effect.succeed(value)\n : Effect.fail(\n journalError(`Staged ${label} must be a non-negative safe integer, got ${String(value)}`),\n );\n\nexport interface TurnCommitInput {\n readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined;\n readonly toolExposure?: Snapshot | undefined;\n readonly toolSelections?: ReadonlyMap<string, Selection> | undefined;\n readonly budgetRejectedCalls?: ReadonlySet<string>;\n readonly runId: RunId;\n /** Canonical (Run-relative, Attempt-independent) Turn number; must be positive. */\n readonly turn: number;\n readonly turnId: TurnId;\n /**\n * The Prompt messages this Turn appended to official history, in order, including the Turn's\n * Tool message when application Tools ran. Tool messages become `ToolCallSettled` records; the\n * remaining messages become the Turn's `ModelResponseRecorded.messages`.\n */\n readonly appended: ReadonlyArray<Prompt.Message>;\n readonly producerId: ProducerId;\n readonly deploymentId: DeploymentId;\n readonly createdAt: DateTime.Utc;\n /** Leading instruction/wake messages that stay canonical but are hidden from later Runs. */\n readonly runScopedPrefixLength?: number | undefined;\n /** Terminal output committed atomically with this Turn's final canonical batch. */\n readonly runCompletion?:\n | {\n readonly output: PersistedJson;\n readonly runDisposition?: PersistedJson | undefined;\n readonly finishReason?: \"budget-exhausted\" | undefined;\n readonly exhausted?: ExhaustedLimit | undefined;\n }\n | undefined;\n /** Known missing-accounting invocations staged before this canonical response. */\n readonly unobservedModelCalls?: number | undefined;\n /** Per-call provider usage staged by the engine's `noteTurnUsage` (RUN-023). */\n readonly usage?:\n | {\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd?: number | undefined;\n readonly modelUsage?: ReadonlyArray<ModelCallUsage> | undefined;\n }\n | undefined;\n}\n\nconst decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);\nconst encodePrompt = Schema.encodeEffect(Prompt.Prompt);\nconst decodeModelUsage = Schema.decodeUnknownEffect(Schema.Array(ModelCallUsage));\n\nconst requireCanonicalTurn = (turn: number): Effect.Effect<void, RunJournalError> =>\n !Number.isInteger(turn) || turn <= 0\n ? Effect.fail(journalError(`Canonical turn number must be a positive integer: ${turn}`))\n : Effect.void;\n\ninterface SplitTurnMessages {\n readonly promptMessages: ReadonlyArray<Prompt.Message>;\n readonly toolParts: ReadonlyArray<Prompt.ToolResultPart>;\n}\n\nconst splitTurnMessages = (appended: ReadonlyArray<Prompt.Message>): SplitTurnMessages => {\n const promptMessages: Array<Prompt.Message> = [];\n const toolParts: Array<Prompt.ToolResultPart> = [];\n\n for (const message of appended) {\n if (message.role !== \"tool\") {\n promptMessages.push(message);\n continue;\n }\n for (const part of message.content) {\n if (part.type !== \"tool-result\") continue;\n toolParts.push(part);\n }\n }\n\n return { promptMessages, toolParts };\n};\n\nconst modelResponseRecord = Effect.fn(\"RunJournal.modelResponseRecord\")(function* (\n input: TurnCommitInput,\n promptMessages: ReadonlyArray<Prompt.Message>,\n): Effect.fn.Return<RecordEnvelope, RunJournalError | DigestError, Crypto.Crypto> {\n if (promptMessages.length === 0) {\n return yield* journalError(`Turn ${input.turn} appended no model-visible Prompt messages`);\n }\n const runScopedPrefixLength = input.runScopedPrefixLength;\n\n if (\n runScopedPrefixLength !== undefined &&\n (input.turn !== 1 ||\n !Number.isSafeInteger(runScopedPrefixLength) ||\n runScopedPrefixLength <= 0 ||\n runScopedPrefixLength >= promptMessages.length ||\n promptMessages\n .slice(0, runScopedPrefixLength)\n .some((message) => message.role !== \"system\" && message.role !== \"user\"))\n ) {\n return yield* journalError(\n \"Run-scoped Prompt provenance must identify a non-empty system/user prefix of Turn 1 before its assistant response\",\n );\n }\n\n const encodedMessages = yield* encodePrompt(Prompt.fromMessages([...promptMessages])).pipe(\n Effect.mapError((cause) => journalError(\"Turn Prompt messages failed to encode\", cause)),\n );\n\n const messages = yield* decodePersistedJson(encodedMessages).pipe(\n Effect.mapError((cause) =>\n journalError(\"Turn Prompt messages exceed canonical persistence bounds\", cause),\n ),\n );\n\n const messagesDigest = yield* digestJson(messages);\n\n const modelUsage =\n input.usage?.modelUsage === undefined\n ? undefined\n : yield* decodeModelUsage(input.usage.modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage failed to decode\", cause)),\n );\n\n if (modelUsage !== undefined) {\n if (modelUsage.length === 0) {\n return yield* journalError(\"Turn model usage must contain at least one completed call\");\n }\n\n const summary = yield* summarizeModelUsage(modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage exceeds accounting bounds\", cause)),\n );\n\n if (\n input.usage === undefined ||\n input.usage.inputTokens !== summary.inputTokens.total ||\n input.usage.outputTokens !== summary.outputTokens.total ||\n (input.usage.costMicrousd ?? 0) !== summary.costMicrousd\n ) {\n return yield* journalError(\"Turn detailed and aggregate model usage disagree\");\n }\n }\n\n return RecordEnvelope.make({\n recordId: modelResponseRecordId(input.runId, input.turn),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: ModelResponseRecorded.make({\n ...(input.toolParameterRejections === undefined || input.toolParameterRejections.length === 0\n ? {}\n : { toolParameterRejections: input.toolParameterRejections }),\n ...(input.toolExposure === undefined ? {} : { toolExposure: input.toolExposure }),\n runId: input.runId,\n turnId: input.turnId,\n turn: input.turn,\n messages,\n messagesDigest,\n ...(runScopedPrefixLength === undefined ? {} : { runScopedPrefixLength }),\n ...(modelUsage === undefined ? {} : { modelUsage }),\n ...(input.unobservedModelCalls === undefined || input.unobservedModelCalls === 0\n ? {}\n : {\n unobservedModelCalls: yield* validStagedUsage(\n \"unobservedModelCalls\",\n input.unobservedModelCalls,\n ),\n }),\n ...(input.usage === undefined\n ? {}\n : {\n inputTokens: yield* validStagedUsage(\"inputTokens\", input.usage.inputTokens),\n outputTokens: yield* validStagedUsage(\"outputTokens\", input.usage.outputTokens),\n // Written only when non-zero: absent re-seeds as zero, so the\n // no-estimator case stays byte-identical to pre-cost histories.\n ...(input.usage.costMicrousd === undefined || input.usage.costMicrousd === 0\n ? {}\n : {\n costMicrousd: yield* validStagedUsage(\"costMicrousd\", input.usage.costMicrousd),\n }),\n }),\n }),\n });\n});\n\nconst toolSettledRecords = Effect.fn(\"RunJournal.toolSettledRecords\")(function* (\n input: TurnCommitInput,\n toolParts: ReadonlyArray<Prompt.ToolResultPart>,\n): Effect.fn.Return<Array<RecordEnvelope>, RunJournalError> {\n const toolRecords: Array<RecordEnvelope> = [];\n\n for (const part of toolParts) {\n const result = yield* decodePersistedJson(part.result).pipe(\n Effect.mapError((cause) =>\n journalError(`Tool result ${part.id} exceeds canonical persistence bounds`, cause),\n ),\n );\n\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(part.id),\n catch: (cause) => journalError(`Invalid Tool Call ID ${part.id}`, cause),\n });\n\n toolRecords.push(\n RecordEnvelope.make({\n recordId: toolCallSettledRecordId(input.runId, input.turn, toolCallId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: ToolCallSettled.make({\n ...(input.toolSelections?.get(part.id) === undefined\n ? {}\n : { toolSelection: input.toolSelections.get(part.id) }),\n runId: input.runId,\n toolCallId,\n toolName: part.name,\n result,\n isFailure: part.isFailure,\n ...(input.budgetRejectedCalls?.has(part.id) === true ? { budgetRejected: true } : {}),\n }),\n }),\n );\n }\n\n return toolRecords;\n});\n\nconst runCompletionRecord = (input: TurnCommitInput): RecordEnvelope | undefined =>\n input.runCompletion === undefined\n ? undefined\n : RecordEnvelope.make({\n recordId: runCompletedRecordId(input.runId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: RunCompleted.make({\n runId: input.runId,\n output: input.runCompletion.output,\n ...(input.runCompletion.runDisposition === undefined\n ? {}\n : { runDisposition: input.runCompletion.runDisposition }),\n ...(input.runCompletion.finishReason === undefined\n ? {}\n : { finishReason: input.runCompletion.finishReason }),\n ...(input.runCompletion.exhausted === undefined\n ? {}\n : { exhausted: input.runCompletion.exhausted }),\n }),\n });\n\n/**\n * Pure per-Turn canonical batch builder (TurnCompleted seam fold, D6/D8): one\n * `ModelResponseRecorded` record plus one `ToolCallSettled` record per terminal Tool result, all\n * under the WP0-style deterministic identities, committed as ONE atomic batch. The same input\n * always yields byte-identical content, so an in-Attempt append retry is an honest batch replay.\n *\n * Phase 5 keeps this shape for Turns that declare no application Tool calls; their terminal\n * `RunCompleted` marker joins the response in this same atomic batch. Tool-declaring Turns split\n * into `turnResponseBatch` + `turnResultsBatch`.\n */\nexport const turnCanonicalBatch = Effect.fn(\"RunJournal.turnCanonicalBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {\n yield* requireCanonicalTurn(input.turn);\n const { promptMessages, toolParts } = splitTurnMessages(input.appended);\n const modelResponse = yield* modelResponseRecord(input, promptMessages);\n const toolRecords = yield* toolSettledRecords(input, toolParts);\n const completionRecord = runCompletionRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [modelResponse, ...toolRecords]\n : [modelResponse, ...toolRecords, completionRecord],\n });\n});\n\n/**\n * Commit 1 of a tool-declaring Turn: the Turn's `ModelResponseRecorded` record, including\n * provider results retained in assistant content before application Tools execute.\n * — pending steering plus the assistant response with its declared tool calls — under batch\n * identity `turn-response:{runId}:{turn}`. Committing the response before preparation creates\n * the provably-safe durability §15 window (\"after model item commit, before tool preparation →\n * resume tool scheduling\"): a crash there resumes the declared batch with no model re-invocation\n * and no Unknown. Tool messages in `appended` are ignored; the record identity is the same\n * `model-response:{runId}:{turn}` as the single-batch shape, so record-id assertions and the\n * prompt projection are unchanged.\n */\nexport const turnResponseBatch = Effect.fn(\"RunJournal.turnResponseBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {\n yield* requireCanonicalTurn(input.turn);\n const { promptMessages } = splitTurnMessages(input.appended);\n const modelResponse = yield* modelResponseRecord(input, promptMessages);\n\n return CanonicalBatch.make({\n batchId: turnResponseBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records: [modelResponse],\n });\n});\n\n/**\n * Commit 5 of a tool-declaring Turn (plan §2.1): the Turn's `ToolCallSettled` records in\n * declaration order under batch identity `turn-results:{runId}:{turn}` — the batch becomes\n * model-visible atomically. Non-tool messages in `appended` are ignored; a Turn without any\n * terminal Tool result has no results batch and fails typed.\n */\nexport const turnResultsBatch = Effect.fn(\"RunJournal.turnResultsBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError> {\n yield* requireCanonicalTurn(input.turn);\n const { toolParts } = splitTurnMessages(input.appended);\n const toolRecords = yield* toolSettledRecords(input, toolParts);\n const first = toolRecords[0];\n\n if (first === undefined) {\n return yield* journalError(`Turn ${input.turn} has no terminal Tool results to commit`);\n }\n if (input.runCompletion !== undefined && toolRecords.length !== 1) {\n return yield* journalError(\"A terminal Tool completion requires exactly one settled result\");\n }\n const completionRecord = runCompletionRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnResultsBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [first, ...toolRecords.slice(1)]\n : [first, ...toolRecords.slice(1), completionRecord],\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAa,uBACX,YACA,SACG;CACH,MAAM,qCAAqB,IAAI,IAAoB;CAEnD,IAAI,MAAM,kBAAkB,KAAA,GAAW,mBAAmB,IAAI,KAAK,OAAO,KAAK,aAAa;CAC5F,MAAM,4CAA4B,IAAI,IAAoB;CAC1D,MAAM,wCAAwB,IAAI,IAAoB;CACtD,MAAM,eAAsE,CAAC;CAC7E,MAAM,2CAA2B,IAAI,IAAY;CAEjD,MAAM,8BAAc,IAAI,IAGtB;CAEF,MAAM,cAAyF,CAAC;CAEhG,OAAO;EACL,MAAM,aAA4C;GAChD,MAAM,UAAU,SAAS,OAAO;GAEhC,KACG,QAAQ,SAAS,kBAChB,QAAQ,SAAS,eACjB,QAAQ,SAAS,wBACnB,QAAQ,UAAU,KAAA,KAClB,CAAC,sBAAsB,IAAI,QAAQ,KAAK,GAExC,sBAAsB,IAAI,QAAQ,OAAO,SAAS,QAAQ;GAC5D,IAAI,QAAQ,SAAS,qBAAqB;IACxC,YAAY,KAAK;KAAE;KAAS,UAAU,SAAS;IAAS,CAAC;IAEzD;GACF;GACA,IACE,WAAW,WACX,OAAO,QAAQ,UAAU,YACzB,CAAC,mBAAmB,IAAI,QAAQ,KAAK,GAErC,mBAAmB,IAAI,QAAQ,OAAO,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CAE7F,MAAM,mBAAmB,oBAAoB,KAAK;CAElD,OAAO,eAAe,KAAK;EACzB,SAAS,mBAAmB,MAAM,OAAO,MAAM,IAAI;EACnD,YAAY,MAAM;EAClB,SACE,qBAAqB,KAAA,IACjB,CAAC,OAAO,GAAG,YAAY,MAAM,CAAC,CAAC,IAC/B;GAAC;GAAO,GAAG,YAAY,MAAM,CAAC;GAAG;EAAgB;CACzD,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"RunJournal-DRRRZmG7.mjs","names":[],"sources":["../src/durable/internal/journal-metadata.ts","../src/durable/RunJournal.ts"],"sourcesContent":["import { type RunId } from \"../../core/Identifiers.ts\";\nimport {\n type CanonicalRecordEnvelope,\n type CompactionCreated,\n type ToolCallSettled,\n} from \"../Records.ts\";\nimport { type JournalCheckpointSeed } from \"./journal-checkpoint.ts\";\n\n/** Metadata for one exact canonical prefix, including the same optional checkpoint seed. */\nexport interface JournalMetadata {\n readonly ownerRunId: RunId | undefined;\n readonly seed: JournalCheckpointSeed | undefined;\n readonly firstSequenceByRun: ReadonlyMap<string, number>;\n readonly lastResponseSequenceByRun: ReadonlyMap<string, number>;\n readonly terminalSequenceByRun: ReadonlyMap<string, number>;\n readonly settledSpans: ReadonlyArray<{ readonly from: number; readonly to: number }>;\n readonly settledToolCallRecordIds: ReadonlySet<string>;\n readonly settledById: ReadonlyMap<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >;\n readonly compactions: ReadonlyArray<{\n readonly payload: CompactionCreated;\n readonly sequence: number;\n }>;\n}\n\n/**\n * Attempt-local metadata collector. Feed every validated record exactly once, in canonical order,\n * including records omitted from the control view. A snapshot is independent of later suffix\n * additions and may only accompany a replay stream bounded at that same captured tail.\n */\nexport const makeJournalMetadata = (\n ownerRunId: RunId | undefined,\n seed?: JournalCheckpointSeed,\n) => {\n const firstSequenceByRun = new Map<string, number>();\n\n if (seed?.firstSequence !== undefined) firstSequenceByRun.set(seed.runId, seed.firstSequence);\n const lastResponseSequenceByRun = new Map<string, number>();\n const terminalSequenceByRun = new Map<string, number>();\n const settledSpans: Array<{ readonly from: number; readonly to: number }> = [];\n const settledToolCallRecordIds = new Set<string>();\n\n const settledById = new Map<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >();\n\n const compactions: Array<{ readonly payload: CompactionCreated; readonly sequence: number }> = [];\n\n return {\n add: (envelope: CanonicalRecordEnvelope): void => {\n const payload = envelope.record.payload;\n\n if (\n (payload._tag === \"RunCompleted\" ||\n payload._tag === \"RunFailed\" ||\n payload._tag === \"SubmissionSettled\") &&\n payload.runId !== undefined &&\n !terminalSequenceByRun.has(payload.runId)\n )\n terminalSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"CompactionCreated\") {\n compactions.push({ payload, sequence: envelope.sequence });\n\n return;\n }\n if (\n \"runId\" in payload &&\n typeof payload.runId === \"string\" &&\n !firstSequenceByRun.has(payload.runId)\n )\n firstSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"ModelResponseRecorded\") {\n lastResponseSequenceByRun.set(payload.runId, envelope.sequence);\n } else if (payload._tag === \"ToolCallSettled\") {\n settledToolCallRecordIds.add(envelope.record.recordId);\n if (payload.runId === ownerRunId)\n settledById.set(envelope.record.recordId, {\n isFailure: payload.isFailure,\n ...(payload.toolSelection === undefined\n ? {}\n : { toolSelection: payload.toolSelection }),\n ...(payload.budgetRejected === undefined\n ? {}\n : { budgetRejected: payload.budgetRejected }),\n });\n const from = lastResponseSequenceByRun.get(payload.runId);\n\n if (from !== undefined && from < envelope.sequence)\n settledSpans.push({ from, to: envelope.sequence });\n }\n },\n snapshot: (): JournalMetadata => ({\n ownerRunId,\n seed,\n firstSequenceByRun: new Map(firstSequenceByRun),\n lastResponseSequenceByRun: new Map(lastResponseSequenceByRun),\n terminalSequenceByRun: new Map(terminalSequenceByRun),\n settledSpans: [...settledSpans],\n settledToolCallRecordIds: new Set(settledToolCallRecordIds),\n settledById: new Map(settledById),\n compactions: [...compactions],\n }),\n };\n};\n","import { type Crypto, Effect, Schema, Stream, type DateTime } from \"effect\";\nimport { Prompt } from \"effect/unstable/ai\";\n\nimport { ThreadId, RunId, ToolCallId, TurnId, type SubmissionId } from \"../core/Identifiers.ts\";\nimport { type ExhaustedLimit } from \"../core/RunEvent.ts\";\nimport { RunPolicyUsage } from \"../core/RunPolicyUsage.ts\";\nimport { type Selection, type Snapshot } from \"../core/ToolExposure.ts\";\nimport type { ToolParameterRejection } from \"../core/ToolResult.ts\";\nimport { ModelCallUsage, summarizeModelUsage, type RunUsageSummary } from \"../core/Usage.ts\";\nimport {\n CLEARED_TOOL_RESULT,\n COMPACTION_SUMMARY_PREFIX,\n contextWindowId,\n contextWindowMessage,\n} from \"../engine/Compaction.ts\";\nimport { digestJson, type DigestError } from \"./Digest.ts\";\nimport { type JournalCheckpointSeed } from \"./internal/journal-checkpoint.ts\";\nimport { makeJournalMetadata, type JournalMetadata } from \"./internal/journal-metadata.ts\";\nimport {\n BatchId,\n CanonicalBatch,\n CompactionCreated,\n ModelResponseRecorded,\n PersistedJson,\n RecordEnvelope,\n RecordId,\n RunCompleted,\n ToolCallSettled,\n type CanonicalRecordEnvelope,\n type CanonicalSequence,\n type DeploymentId,\n type ProducerId,\n} from \"./Records.ts\";\nimport { IdempotencyKey } from \"./SubmissionLedger.ts\";\n\n/** A canonical record could not be projected into Run/Prompt state. */\nexport class RunJournalError extends Schema.TaggedError<RunJournalError>()(\"RunJournalError\", {\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n}) {}\n\nconst journalError = (message: string, cause?: unknown): RunJournalError =>\n cause === undefined\n ? RunJournalError.make({ message })\n : RunJournalError.make({ message, cause });\n\nconst decodeRunId = Schema.decodeSync(RunId);\nconst decodeTurnId = Schema.decodeSync(TurnId);\nconst decodeBatchId = Schema.decodeSync(BatchId);\nconst decodeRecordId = Schema.decodeSync(RecordId);\n\n/**\n * Deterministic Run identity pinned per Submission (plan §Coordinator flow). Every Attempt of one\n * Submission shares this Run identity, so canonical per-Turn records from different Attempts\n * belong to one logical Run.\n */\nexport const runIdForSubmission = (submissionId: SubmissionId): RunId =>\n decodeRunId(`run:${submissionId}`);\n\n/** Stable canonical clock identity shared by every Attempt of one Run. */\nexport const runStartedRecordId = (runId: RunId): RecordId => decodeRecordId(`run-start:${runId}`);\n\nexport const runStartedBatchId = (runId: RunId): BatchId => decodeBatchId(`run-start:${runId}`);\n\nexport const runDurationRecordId = (runId: RunId): RecordId =>\n decodeRecordId(`run-duration:${runId}`);\n\nexport const runDurationBatchId = (runId: RunId): BatchId => decodeBatchId(`run-duration:${runId}`);\n\n/** Deterministic Turn identity: Attempt-independent for one (Run, canonical turn) pair. */\nexport const turnIdForRun = (runId: RunId, turn: number): TurnId =>\n decodeTurnId(`turn:${runId}:${turn}`);\n\n/** Deterministic batch identity of one committed canonical no-tool Turn (P4 single-batch shape). */\nexport const turnBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESPONSE commit (plan §2.1 commit 1):\n * the assistant response plus pending steering becomes canonical BEFORE approval preflight and\n * tool preparation, creating the durability §15 \"resume tool scheduling\" window.\n */\nexport const turnResponseBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-response:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESULTS commit (plan §2.1 commit 5):\n * every `ToolCallSettled` record of the Turn, in declaration order, model-visible atomically.\n */\nexport const turnResultsBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-results:${runId}:${turn}`);\n\n/**\n * Deterministic per-call late-settle batch identity used by the resolution path when one\n * recovered/resolved call settles outside its Turn's results batch. Record identity\n * (`tool-settled:{runId}:{turn}:{toolCallId}`) dedupes double-settles across both paths.\n */\nexport const toolCallResultBatchId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`turn-results:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Turn's `ToolCallPrepared` commit (plan §2.1 commit 3). */\nexport const turnPreparedBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-prepared:${runId}:${turn}`);\n\n/**\n * Deterministic identity of one pre-Turn compaction record (RUN-026,\n * RUN-026). Keyed by Run, Turn, and kind — the engine performs at most one\n * threshold compaction per Turn plus at most one overflow-forced summarize,\n * so a superseding Attempt that re-decides the same compaction replays the\n * batch identity instead of duplicating the record.\n */\nexport const compactionRecordId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): RecordId => decodeRecordId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic batch identity of one compaction append (same string as its record id). */\nexport const compactionBatchId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): BatchId => decodeBatchId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic canonical record identity of one Turn's `ModelResponseRecorded` record. */\nexport const modelResponseRecordId = (runId: RunId, turn: number): RecordId =>\n decodeRecordId(`model-response:${runId}:${turn}`);\n\n/** Terminal Tool completion marker committed atomically with its settled Tool result. */\nexport const runCompletedRecordId = (runId: RunId): RecordId =>\n decodeRecordId(`run-completed:${runId}`);\n\n/** Deterministic canonical record identity of one Turn's `ToolCallSettled` record. */\nexport const toolCallSettledRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-settled:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallPrepared` record. */\nexport const toolCallPreparedRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-prepared:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Turn's `ToolCallUnknown` marking append. */\nexport const markUnknownBatchId = (submissionId: SubmissionId, turn: number): BatchId =>\n decodeBatchId(`mark-unknown:${submissionId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallUnknown` record. */\nexport const toolCallUnknownRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-unknown:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's resolution append (DUR-017). */\nexport const toolCallResolutionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`resolve:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallResolved` record. */\nexport const toolCallResolvedRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-resolved:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one accepted Durable Step result. The one-record batch reuses the\n * SAME string, so batch idempotency plus the epoch fence realize the durability §11\n * racing-writers rule: only the fenced winner's record commits; the loser replays it.\n * A versioned JSON tuple keeps separator characters in each identity component distinct.\n * Replay derives this key from the structured payload, including records with legacy IDs.\n */\nexport const toolStepSettledRecordId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): RecordId => decodeRecordId(JSON.stringify([\"step@2\", runId, toolCallId, stepName]));\n\n/** Deterministic batch identity of one Durable Step commit (same string as its record id). */\nexport const toolStepSettledBatchId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): BatchId => decodeBatchId(toolStepSettledRecordId(runId, toolCallId, stepName));\n\n/** Deterministic batch identity of one Turn's canonical approval-request append (plan §2.6). */\nexport const turnApprovalsBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-approvals:${runId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalRequested` record. */\nexport const toolApprovalRequestRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`approval-request:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's canonical approval-decision append. */\nexport const approvalDecisionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`approval-decision:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalDecided` record. */\nexport const toolApprovalDecisionRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`approval-decision:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one superseded Attempt's `ModelResponseInterrupted` audit record\n * (durability §9). Keyed by the superseded epoch, so each interrupted ownership period is\n * recorded at most once; the one-record batch reuses the same string.\n */\nexport const modelResponseInterruptedRecordId = (runId: RunId, supersededEpoch: number): RecordId =>\n decodeRecordId(`interrupted:${runId}:${supersededEpoch}`);\n\n/** Deterministic batch identity of one `ModelResponseInterrupted` append (same string). */\nexport const modelResponseInterruptedBatchId = (runId: RunId, supersededEpoch: number): BatchId =>\n decodeBatchId(`interrupted:${runId}:${supersededEpoch}`);\n\nconst decodeThreadId = Schema.decodeSync(ThreadId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentRequested` record.\n * The one-record batch reuses the same string, so batch\n * idempotency plus the parent epoch fence make the request append exactly-once-canonical.\n */\nexport const subagentRequestedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-requested:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentRequested` append (same string). */\nexport const subagentRequestedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-requested:${runId}:${toolCallId}`);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentStarted` record.\n * Recovery's start-link repair appends the EXACT same record\n * under this identity, so a raced repair replays instead of duplicating (SUB-016/SUB-017).\n */\nexport const subagentStartedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-started:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentStarted` append (same string). */\nexport const subagentStartedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-started:${runId}:${toolCallId}`);\n\n/**\n * Deterministic batch identity of one parent Tool Call's atomic settlement join: the\n * `SubagentJoined` record plus the parent's `ToolCallSettled` record (its existing\n * `tool-settled:{runId}:{turn}:{toolCallId}` identity) commit as ONE canonical batch (SUB-019).\n */\nexport const subagentJoinBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-join:${runId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one parent Tool Call's `SubagentJoined` record. */\nexport const subagentJoinedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-joined:${runId}:${toolCallId}`);\n\n/**\n * Deterministic identity of one child Thread's `SubagentLineageRecorded` record.\n * Its own single-record batch reuses the same string so the generic\n * `thread-created:{cid}` batch identity is never contradicted.\n */\nexport const subagentLineageRecordId = (threadId: ThreadId): RecordId =>\n decodeRecordId(`subagent-lineage:${threadId}`);\n\n/** Deterministic batch identity of one `SubagentLineageRecorded` append (same string). */\nexport const subagentLineageBatchId = (threadId: ThreadId): BatchId =>\n decodeBatchId(`subagent-lineage:${threadId}`);\n\n/**\n * Deterministic intended child Thread identity: the\n * parent Submission and Tool Call pair addresses exactly one child Thread, so a replayed\n * establishment converges on the one existing child (SUB-016).\n */\nexport const childThreadIdFor = (\n parentSubmissionId: SubmissionId,\n toolCallId: ToolCallId,\n): ThreadId => decodeThreadId(`subagent:${parentSubmissionId}:${toolCallId}`);\n\n/**\n * Deterministic child admission idempotency key: scoped to\n * the parent Run and Tool Call identity, so duplicate admission attempts resolve through the\n * ledger's idempotency contract to one child Receipt (SUB-016, SUB-031). The ledger key is\n * bounded (256); coordinator-minted Run and Tool Call identities stay far below that bound.\n */\nexport const childIdempotencyKeyFor = (\n parentRunId: RunId,\n toolCallId: ToolCallId,\n): IdempotencyKey => decodeIdempotencyKey(`subagent:${parentRunId}:${toolCallId}`);\n\nconst decodePromptMessages = Effect.fn(\"RunJournal.decodePromptMessages\")(\n (messages: PersistedJson): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n Schema.decodeUnknownEffect(Prompt.Prompt)(messages).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical messages are not Schema-encoded Prompt messages\", cause),\n ),\n ),\n);\n\ninterface PendingSettledTool {\n readonly record: ToolCallSettled;\n /** RUN-026: a `clear-tool-results` compaction covers this record's sequence. */\n readonly cleared: boolean;\n}\n\nconst toolMessageFromSettled = Effect.fn(\"RunJournal.toolMessageFromSettled\")(\n (settled: ReadonlyArray<PendingSettledTool>): Effect.Effect<Prompt.Message, RunJournalError> =>\n Effect.try({\n try: () =>\n Prompt.makeMessage(\"tool\", {\n content: settled.map(({ record, cleared }) =>\n Prompt.makePart(\"tool-result\", {\n id: record.toolCallId,\n name: record.toolName,\n result: cleared ? CLEARED_TOOL_RESULT : record.result,\n isFailure: record.isFailure,\n providerExecuted: false,\n }),\n ),\n }),\n catch: (cause) => journalError(\"Unable to rebuild Tool message from ToolCallSettled\", cause),\n }),\n);\n\n/**\n * Pure canonical projection of one Run's durable execution state.\n *\n * Prompt reconstruction contract (D8):\n *\n * - `ModelResponseRecorded.messages` carries the Schema-encoded Prompt messages the Turn appended\n * to the model-visible prompt — for the Run's FIRST committed Turn that includes the evaluated\n * instruction and user-input messages, for later Turns only the assistant response messages.\n * Tool messages are excluded from `messages`.\n * - `ToolCallSettled` records (committed in the same per-Turn batch, in declaration order)\n * deterministically rebuild the Turn's single Tool message.\n * - `UserInputRecorded` records input, with a Submission identity only for durable admission. Its\n * Prompt-visible form (instructions + user message) becomes canonical inside the owning Run's\n * first `ModelResponseRecorded`. The projection consumes it only for Run correlation.\n * - Immediate retained history uses `ModelCompleted.messages` for the successful Run's exact\n * native Prompt suffix, including any input examples. It has no resumable Turn state.\n */\n/** Cumulative committed usage of the projected Run (RUN-023 resume re-seed). */\nexport interface RunJournalUsage {\n readonly modelCalls: number;\n /** Known accounting gaps retained across Attempts without changing numeric usage totals. */\n readonly unobservedModelCalls?: number | undefined;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly lastInputTokens: number;\n readonly lastOutputTokens: number;\n /** Cumulative persisted spend of the projected Run's committed calls (RUN-023). */\n readonly costMicrousd: number;\n /** Canonical per-call detail used for settlement aggregation and recovery. */\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n /** Detailed usage of retired records, grouped without retaining per-call payloads. */\n readonly summarizedModelUsage?: RunUsageSummary | undefined;\n}\n\nexport interface RunJournalProjection {\n readonly toolSelection?: Selection | undefined;\n readonly policyUsage: RunPolicyUsage;\n /** Canonical projection for the requested Run; may end at its resumable Tool declaration. */\n readonly prompt: Prompt.Prompt;\n /** Valid prior-Run history excluding the projected Run's records and orphan Tool batches. */\n readonly historyBefore: Prompt.Prompt;\n /** Number of canonical Turns already committed for the projected Run. */\n readonly committedTurns: number;\n /** Summed per-call usage of the projected Run's committed responses; zeros for records predating usage capture. */\n readonly usage: RunJournalUsage;\n /** Latest committed context window identity, retained across ownership changes. */\n readonly contextWindowId?: string | undefined;\n /** Canonical evaluated instructions and initial input for this Run, independent of the view. */\n readonly protectedContext?: Prompt.Prompt | undefined;\n /** Last successful singleton Tool awaiting possible context-control interpretation by the engine. */\n readonly pendingContextToolCallId?: string | undefined;\n}\n\ninterface ProjectedResponseUsage {\n readonly modelCalls: number;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd: number;\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n}\n\nconst projectedResponseUsage = (\n response: ModelResponseRecorded,\n): Effect.Effect<ProjectedResponseUsage, RunJournalError> =>\n Effect.gen(function* () {\n const calls = response.modelUsage;\n\n if (calls === undefined) {\n return {\n modelCalls: 1,\n inputTokens: response.inputTokens ?? 0,\n outputTokens: response.outputTokens ?? 0,\n costMicrousd: response.costMicrousd ?? 0,\n modelUsage: [],\n };\n }\n if (calls.length === 0) {\n return yield* journalError(\"A canonical modelUsage list must not be empty\");\n }\n\n const summary = yield* summarizeModelUsage(calls).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical model usage exceeds accounting bounds\", cause),\n ),\n );\n\n if (\n (response.inputTokens !== undefined && response.inputTokens !== summary.inputTokens.total) ||\n (response.outputTokens !== undefined &&\n response.outputTokens !== summary.outputTokens.total) ||\n (response.costMicrousd !== undefined && response.costMicrousd !== summary.costMicrousd)\n ) {\n return yield* journalError(\"Canonical detailed and aggregate model usage disagree\");\n }\n\n return {\n modelCalls: summary.modelCalls,\n inputTokens: summary.inputTokens.total,\n outputTokens: summary.outputTokens.total,\n costMicrousd: summary.costMicrousd,\n modelUsage: calls,\n };\n });\n\nconst addProjectedUsage = (\n field: string,\n left: number,\n right: number,\n): Effect.Effect<number, RunJournalError> =>\n Schema.decodeEffect(Schema.Natural)(left + right).pipe(\n Effect.mapError((cause) =>\n journalError(`Canonical projected usage exceeds safe-integer bounds at ${field}`, cause),\n ),\n );\n\ninterface FoldState {\n readonly all: Array<Prompt.Message>;\n readonly before: Array<Prompt.Message>;\n readonly pendingTools: Array<PendingSettledTool>;\n readonly pendingToolsForRun: boolean;\n readonly committedTurns: number;\n}\n\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\n\nconst declaredApplicationToolCallIds = (prompt: Prompt.Prompt): ReadonlyArray<string> => {\n const ids: Array<string> = [];\n\n for (const message of prompt.content) {\n if (message.role !== \"assistant\") continue;\n for (const part of message.content) {\n if (part.type === \"tool-call\" && !part.providerExecuted) ids.push(part.id);\n }\n }\n\n return ids;\n};\n\nconst withoutApplicationToolCallMessages = (prompt: Prompt.Prompt): ReadonlyArray<Prompt.Message> =>\n prompt.content.filter(\n (message) =>\n message.role !== \"assistant\" ||\n !message.content.some((part) => part.type === \"tool-call\" && !part.providerExecuted),\n );\n\n/**\n * Phase 5 audit tags that are prompt-transparent: they carry durability evidence (preparation,\n * unknown marking, resolution, Step results, approvals, interruption) but contribute nothing to\n * the model-visible Prompt, and — unlike the P4 tags — they do NOT split a contiguous\n * `ToolCallSettled` group into separate Tool messages, so a late-settled call's audit records\n * cannot change the replayed prompt shape.\n *\n * The four S2 Subagent lifecycle tags are prompt-transparent for the same reason (spec §5/§11):\n * the parent prompt never carries child transcript or establishment evidence — the joined child\n * result reaches the model exclusively through the paired `ToolCallSettled` record, and the\n * child-log lineage record is not model input.\n */\nconst PROMPT_TRANSPARENT_TAGS: ReadonlySet<string> = new Set([\n \"RunPolicyUsageReserved\",\n \"RunStarted\",\n \"RunDurationExhausted\",\n \"ToolCallPrepared\",\n \"ToolCallUnknown\",\n \"ToolCallResolved\",\n \"ToolStepSettled\",\n \"ToolApprovalRequested\",\n \"ToolApprovalDecided\",\n \"ModelResponseInterrupted\",\n \"SubagentRequested\",\n \"SubagentStarted\",\n \"SubagentJoined\",\n \"SubagentLineageRecorded\",\n \"WorkerInputRequested\",\n \"WorkerOriginRecorded\",\n \"WorkerInputCompleted\",\n \"WorkerReportPrepared\",\n \"AgentUpdateEmitted\",\n \"WorkerReportRefused\",\n \"PeerMessagePrepared\",\n \"SubtreeBudgetReserved\",\n]);\n\n/**\n * Pure projection: rebuild one Run's resume state from canonical records (DUR-015). Canonical\n * order is authoritative; the fold projects each complete `ModelResponseRecorded` Turn and the\n * owning Run's resumable incomplete Tool Turn, while excluding incomplete Tool batches from prior\n * Runs. It flushes each contiguous group of valid `ToolCallSettled` records into one Tool message,\n * exactly mirroring the per-Turn commit shape produced by `turnCanonicalBatch` (no-tool Turns) and\n * by the\n * `turnResponseBatch`/`turnResultsBatch` split (tool-declaring Turns). The Phase 5 audit tags\n * are skipped transparently, so split-batch commits replay to the same prompt as P4 single-batch\n * commits.\n *\n * An incomplete application Tool turn remains visible while projecting its owning Run so active\n * recovery can resume the declared batch. It is not a valid model-visible Turn boundary for a\n * later Run: the orphan assistant Tool declaration and any partial Tool results from that Turn\n * are excluded, while preceding instruction/user messages in the response record remain history.\n */\n/** @internal Lightweight canonical boundaries collected without retaining record payloads. */\nexport interface JournalBoundary {\n readonly sequence: CanonicalSequence;\n readonly tag: \"ModelResponseRecorded\" | \"ToolCallSettled\";\n readonly promptLength: number;\n /** A declaration without all settled results requires terminal-prior-Run proof for coverage. */\n readonly incomplete?: true | undefined;\n /** The Run terminated after its last response and differs from the projection's owner. */\n readonly terminalPriorRun?: true | undefined;\n}\n\n/**\n * Reconstruct a fixed canonical prefix from a re-readable stream. The caller must keep the same\n * records visible on every traversal. The first collects compaction and settlement metadata;\n * rollovers additionally validate covered Tool batches before rebuilding Prompt and usage. Metadata and the\n * live Prompt remain resident; covered historical message/tool payloads do not. An uncompacted Prompt still grows\n * with its conversation, so hosts must configure an appropriate context compaction policy.\n * Prepared metadata must describe exactly this stream and seed through the same fixed tail;\n * it skips only the metadata scan, never covered-Tool validation or the canonical fold.\n * @internal\n */\nexport const projectRunJournalStream = Effect.fn(\"RunJournal.projectRunJournalStream\")(function* <\n E,\n R,\n>(\n records: Stream.Stream<CanonicalRecordEnvelope, E, R>,\n ownerRunId: RunId | undefined,\n onBoundary?: (boundary: JournalBoundary) => void,\n seed?: JournalCheckpointSeed,\n preparedMetadata?: JournalMetadata,\n): Effect.fn.Return<RunJournalProjection, RunJournalError | E, R> {\n if (seed !== undefined && seed.runId !== ownerRunId)\n return yield* journalError(\"Recovery checkpoint belongs to another Run\");\n\n let state: FoldState = {\n all: [],\n before: [],\n pendingTools: [],\n pendingToolsForRun: false,\n committedTurns: seed?.committedTurns ?? 0,\n };\n\n // RUN-026 pre-scan: the widest VALID compaction bounds govern the fold. A\n // valid record covers strictly below its own sequence and never splits a response from its\n // settled tool results. Pruning and rollovers may cover complete owner-Run batches;\n // a summarize record must carry its summary. Invalid records\n // are ignored fail-safe — the full history stays authoritative. Ties on\n // coversThrough resolve to the record appended later (higher sequence),\n // matching at-most-once replay intent.\n // One span per settled record, paired with its declaring response the same\n // way the fold pairs them: a settled belongs to the most recent\n // ModelResponseRecorded of its Run. A bound inside (response, settled)\n // would orphan the tool message from its declaring response. Orphaned\n // settleds (filtered later by the fold) still contribute spans —\n // over-invalidating is the fail-safe direction.\n if (\n preparedMetadata !== undefined &&\n (preparedMetadata.ownerRunId !== ownerRunId || preparedMetadata.seed !== seed)\n )\n return yield* journalError(\"Prepared journal metadata belongs to another replay\");\n\n let metadata = preparedMetadata;\n\n if (metadata === undefined) {\n const collected = makeJournalMetadata(ownerRunId, seed);\n\n yield* Stream.runForEach(records, (envelope) => Effect.sync(() => collected.add(envelope)));\n metadata = collected.snapshot();\n }\n\n const {\n firstSequenceByRun,\n lastResponseSequenceByRun,\n terminalSequenceByRun,\n settledSpans,\n settledToolCallRecordIds,\n settledById,\n compactions,\n } = metadata;\n\n const settledCoverage = compactions.reduce(\n (through, { payload }) =>\n payload.kind !== \"summarize\" ? Math.max(through, payload.coversThrough) : through,\n 0,\n );\n\n // Terminality changes only prompt coverage; it never settles or resolves the Tool Call.\n // Compare against the compaction's Run and sequence, independent of the replay's owner.\n const isTerminalPriorRun = (\n candidateRunId: RunId,\n compactionRunId: RunId | undefined,\n beforeSequence: number,\n ): boolean => {\n const terminal = terminalSequenceByRun.get(candidateRunId);\n\n return (\n candidateRunId !== compactionRunId &&\n terminal !== undefined &&\n terminal < beforeSequence &&\n terminal > (lastResponseSequenceByRun.get(candidateRunId) ?? 0)\n );\n };\n\n const incompleteResponseSequences: Array<{ readonly sequence: number; readonly runId: RunId }> =\n [];\n\n let ownerPrefixSequence = seed?.firstSequence ?? Number.POSITIVE_INFINITY;\n\n let protectedContext: Prompt.Prompt | undefined =\n seed?.protectedContext === undefined\n ? undefined\n : yield* decodePromptMessages(seed.protectedContext);\n\n if (settledCoverage > 0) {\n yield* Stream.runForEach(records, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (payload._tag !== \"ModelResponseRecorded\" || envelope.sequence > settledCoverage) return;\n const messages = yield* decodePromptMessages(payload.messages);\n const declared = declaredApplicationToolCallIds(messages);\n\n for (const id of declared) {\n const callId = yield* Schema.decodeEffect(ToolCallId)(id).pipe(\n Effect.mapError((cause) =>\n journalError(\"Failed to decode a declared Tool Call ID\", cause),\n ),\n );\n\n if (\n !settledToolCallRecordIds.has(\n toolCallSettledRecordId(payload.runId, payload.turn, callId),\n )\n ) {\n incompleteResponseSequences.push({ sequence: envelope.sequence, runId: payload.runId });\n break;\n }\n }\n if (\n payload.runId === ownerRunId &&\n payload.turn === 1 &&\n payload.runScopedPrefixLength !== undefined\n ) {\n ownerPrefixSequence = envelope.sequence;\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n }),\n );\n }\n\n const boundIsValid = (payload: CompactionCreated, ownSequence: number): boolean => {\n const { runId, coversThrough } = payload;\n\n if (coversThrough <= 0 || coversThrough >= ownSequence) return false;\n if (seed !== undefined && ownSequence === seed.compaction.sequence)\n return (\n seed.compaction.record.payload._tag === \"CompactionCreated\" &&\n Schema.toEquivalence(CompactionCreated)(payload, seed.compaction.record.payload)\n );\n const ownerFirst = firstSequenceByRun.get(runId);\n\n if (payload.kind === \"summarize\" && ownerFirst !== undefined && coversThrough >= ownerFirst)\n return false;\n if (\n payload.kind !== \"summarize\" &&\n incompleteResponseSequences.some(\n (response) =>\n response.sequence <= coversThrough &&\n !isTerminalPriorRun(response.runId, runId, ownSequence),\n )\n )\n return false;\n for (const span of settledSpans) {\n if (span.from <= coversThrough && coversThrough < span.to) return false;\n }\n\n return true;\n };\n\n let summarizeBound = 0;\n let replacement: CompactionCreated | undefined;\n let summarizeSequence = -1;\n let clearBound = 0;\n let latestWindowId: string | undefined = seed?.contextWindowId;\n let latestWindowSequence = seed?.throughSequence ?? -1;\n let rolloverCoveredThrough = 0;\n\n for (const { payload, sequence } of compactions) {\n if (!boundIsValid(payload, sequence)) continue;\n if (payload.kind === \"rollover\" && sequence > latestWindowSequence) {\n latestWindowId = contextWindowId(payload.runId, payload.turn);\n latestWindowSequence = sequence;\n }\n if (payload.kind === \"rollover\")\n rolloverCoveredThrough = Math.max(rolloverCoveredThrough, payload.coversThrough);\n if (payload.kind === \"summarize\" || payload.kind === \"rollover\") {\n if (payload.kind === \"summarize\" && payload.summary === undefined) continue;\n if (\n payload.coversThrough > summarizeBound ||\n (payload.coversThrough === summarizeBound && sequence > summarizeSequence)\n ) {\n summarizeBound = payload.coversThrough;\n summarizeSequence = sequence;\n replacement = payload;\n }\n } else if (payload.coversThrough > clearBound) {\n clearBound = payload.coversThrough;\n }\n }\n let summaryEmitted = false;\n\n const retainedPrefix =\n replacement?.kind === \"rollover\" &&\n replacement.runId === ownerRunId &&\n ownerPrefixSequence <= summarizeBound\n ? (protectedContext?.content ?? [])\n : [];\n\n const replacementLength = replacement === undefined ? 0 : retainedPrefix.length + 1;\n\n if (seed?.frontier !== undefined)\n onBoundary?.({ ...seed.frontier, promptLength: replacementLength });\n\n const emitSummary = () => {\n if (summaryEmitted || replacement === undefined) return;\n summaryEmitted = true;\n\n const message =\n replacement.kind === \"rollover\"\n ? contextWindowMessage(\n contextWindowId(replacement.runId, replacement.turn),\n replacement.handoff,\n )\n : Prompt.makeMessage(\"user\", {\n content: [\n Prompt.makePart(\"text\", {\n text: `${COMPACTION_SUMMARY_PREFIX}${replacement.summary}`,\n }),\n ],\n });\n\n state.all.push(...retainedPrefix, message);\n if (replacement.kind !== \"rollover\" || replacement.runId !== ownerRunId)\n state.before.push(message);\n };\n\n const modelUsage: Array<ModelCallUsage> = [];\n let unobservedModelCalls = seed?.unobservedModelCalls ?? 0;\n\n const usage = {\n modelCalls: seed?.modelCalls ?? 0,\n inputTokens: seed?.inputTokens ?? 0,\n outputTokens: seed?.outputTokens ?? 0,\n lastInputTokens: seed?.lastInputTokens ?? 0,\n lastOutputTokens: seed?.lastOutputTokens ?? 0,\n costMicrousd: seed?.costMicrousd ?? 0,\n modelUsage,\n ...(seed === undefined ? {} : { summarizedModelUsage: seed.summarizedModelUsage }),\n };\n\n let toolSelection = seed?.toolSelection;\n let usageTurn = seed?.committedTurns ?? 0;\n\n const incompleteToolTurns = new Set<string>();\n const incompleteToolCalls = new Set<string>();\n let pendingContextToolCallId: string | undefined;\n let ownerTerminated = false;\n\n const policyUsage = {\n committedTurns: seed?.policyUsage.committedTurns ?? 0,\n toolCalls: seed?.policyUsage.toolCalls ?? 0,\n programmaticToolCalls: seed?.policyUsage.programmaticToolCalls ?? 0,\n consecutiveToolFailures: seed?.policyUsage.consecutiveToolFailures ?? 0,\n finalizationUsed: seed?.policyUsage.finalizationUsed ?? false,\n };\n\n const accountResponse = Effect.fn(\"RunJournal.accountResponse\")(function* (\n envelope: CanonicalRecordEnvelope,\n payload: ModelResponseRecorded,\n messages: Prompt.Prompt,\n ) {\n const record = envelope.record;\n\n const declared = declaredApplicationToolCallIds(messages);\n const declaredRecordIds: Array<RecordId> = [];\n\n for (const id of declared) {\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(id),\n catch: (cause) => journalError(\"Failed to decode a declared Tool Call ID\", cause),\n });\n\n declaredRecordIds.push(toolCallSettledRecordId(payload.runId, payload.turn, toolCallId));\n }\n if (declaredRecordIds.some((recordId) => !settledToolCallRecordIds.has(recordId))) {\n incompleteToolTurns.add(envelope.record.recordId);\n for (const recordId of declaredRecordIds) incompleteToolCalls.add(recordId);\n }\n if (payload.runId !== ownerRunId) return;\n if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;\n if (payload.turn === 1 && payload.runScopedPrefixLength !== undefined) {\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n\n const responseUsage = yield* projectedResponseUsage(payload);\n\n unobservedModelCalls = yield* addProjectedUsage(\n \"unobservedModelCalls\",\n unobservedModelCalls,\n payload.unobservedModelCalls ?? 0,\n );\n\n usage.modelCalls = yield* addProjectedUsage(\n \"modelCalls\",\n usage.modelCalls,\n responseUsage.modelCalls,\n );\n usage.inputTokens = yield* addProjectedUsage(\n \"inputTokens\",\n usage.inputTokens,\n responseUsage.inputTokens,\n );\n usage.outputTokens = yield* addProjectedUsage(\n \"outputTokens\",\n usage.outputTokens,\n responseUsage.outputTokens,\n );\n usage.costMicrousd = yield* addProjectedUsage(\n \"costMicrousd\",\n usage.costMicrousd,\n responseUsage.costMicrousd,\n );\n usage.modelUsage.push(...responseUsage.modelUsage);\n if (payload.turn > usageTurn) {\n usageTurn = payload.turn;\n usage.lastInputTokens = responseUsage.inputTokens;\n usage.lastOutputTokens = responseUsage.outputTokens;\n }\n\n policyUsage.committedTurns = Math.max(policyUsage.committedTurns, payload.turn);\n\n const calls = messages.content.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.filter((part) => part.type === \"tool-call\")\n : [],\n );\n\n const candidate = calls.length === 1 ? calls[0] : undefined;\n\n const candidateResult =\n candidate === undefined\n ? undefined\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${candidate.id}`);\n\n pendingContextToolCallId =\n candidate !== undefined &&\n !candidate.providerExecuted &&\n candidateResult?.isFailure === false &&\n candidateResult.budgetRejected !== true &&\n envelope.sequence > rolloverCoveredThrough\n ? candidate.id\n : undefined;\n\n policyUsage.toolCalls += calls.length;\n if (payload.toolExposure !== undefined) toolSelection = payload.toolExposure.selection;\n if (incompleteToolTurns.has(record.recordId)) return;\n for (const call of calls) {\n const result = call.providerExecuted\n ? messages.content\n .flatMap((message) => (message.role === \"assistant\" ? message.content : []))\n .find(\n (part) => part.type === \"tool-result\" && part.providerExecuted && part.id === call.id,\n )\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${call.id}`);\n\n if (result === undefined || (\"budgetRejected\" in result && result.budgetRejected === true))\n continue;\n if (!(\"isFailure\" in result)) continue;\n if (!result.isFailure && \"toolSelection\" in result && result.toolSelection !== undefined)\n toolSelection = result.toolSelection;\n policyUsage.consecutiveToolFailures = result.isFailure\n ? policyUsage.consecutiveToolFailures + 1\n : 0;\n }\n });\n\n let pendingToolOrder = new Map<string, number>();\n\n const flushTools = Effect.fn(\"RunJournal.flushTools\")(function* (\n current: FoldState,\n ): Effect.fn.Return<FoldState, RunJournalError> {\n if (current.pendingTools.length === 0) return current;\n\n // Suspension can persist an ordinary sibling before a delegated call joins. Model context\n // still uses declaration order, matching the live interpreter's completed results batch.\n const ordered = current.pendingTools.toSorted(\n (left, right) =>\n (pendingToolOrder.get(left.record.toolCallId) ?? Number.MAX_SAFE_INTEGER) -\n (pendingToolOrder.get(right.record.toolCallId) ?? Number.MAX_SAFE_INTEGER),\n );\n\n const toolMessage = yield* toolMessageFromSettled(ordered);\n\n current.all.push(toolMessage);\n if (!current.pendingToolsForRun) current.before.push(toolMessage);\n\n return {\n ...current,\n pendingTools: [],\n pendingToolsForRun: false,\n };\n });\n\n yield* Stream.runForEach(records, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (\n ((payload._tag === \"RunCompleted\" || payload._tag === \"RunFailed\") &&\n payload.runId === ownerRunId) ||\n (payload._tag === \"SubmissionSettled\" &&\n runIdForSubmission(payload.submissionId) === ownerRunId)\n )\n ownerTerminated = true;\n\n if (payload._tag === \"RunPolicyUsageReserved\" && payload.runId === ownerRunId) {\n if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;\n if (\n payload.programmaticToolCalls < policyUsage.programmaticToolCalls ||\n (policyUsage.finalizationUsed && !payload.finalizationUsed)\n ) {\n return yield* journalError(\"Run policy reservations must be monotonic\");\n }\n policyUsage.programmaticToolCalls = payload.programmaticToolCalls;\n policyUsage.finalizationUsed = payload.finalizationUsed;\n }\n if (PROMPT_TRANSPARENT_TAGS.has(payload._tag)) return;\n // The compaction record governs the fold (pre-scan) and contributes no\n // message of its own; records at or below the summarize bound render as\n // the one summary message emitted at the covered/kept transition.\n if (payload._tag === \"CompactionCreated\") return;\n if (\n seed !== undefined &&\n envelope.sequence <= seed.throughSequence &&\n (payload._tag === \"ModelResponseRecorded\" || payload._tag === \"ToolCallSettled\")\n )\n return;\n if (envelope.sequence <= summarizeBound) {\n // Projecting an earlier Run after a later summary still accounts for its covered responses.\n if (payload._tag === \"ModelResponseRecorded\" && payload.runId === ownerRunId) {\n const messages = yield* decodePromptMessages(payload.messages);\n\n yield* accountResponse(envelope, payload, messages);\n state = { ...state, committedTurns: Math.max(state.committedTurns, payload.turn) };\n }\n if (payload._tag === \"ModelResponseRecorded\" || payload._tag === \"ToolCallSettled\") {\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: replacementLength,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolTurns.has(envelope.record.recordId) ||\n incompleteToolCalls.has(envelope.record.recordId)\n ? { incomplete: true }\n : {}),\n });\n }\n\n return;\n }\n emitSummary();\n if (payload._tag === \"ToolCallSettled\") {\n if (payload.runId !== ownerRunId && incompleteToolCalls.has(envelope.record.recordId)) {\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length + (state.pendingTools.length === 0 ? 0 : 1),\n incomplete: true,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n });\n\n return;\n }\n if (\n state.pendingTools.length > 0 &&\n state.pendingToolsForRun !== (payload.runId === ownerRunId)\n ) {\n state = yield* flushTools(state);\n }\n state.pendingTools.push({ record: payload, cleared: envelope.sequence <= clearBound });\n state = {\n ...state,\n pendingToolsForRun: payload.runId === ownerRunId,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length + 1,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n\n return;\n }\n state = yield* flushTools(state);\n if (payload._tag === \"ModelCompleted\" && payload.messages !== undefined) {\n const messages = yield* decodePromptMessages(payload.messages);\n\n for (const message of messages.content) {\n state.all.push(message);\n if (payload.runId !== ownerRunId) state.before.push(message);\n }\n\n return;\n }\n if (payload._tag !== \"ModelResponseRecorded\") return;\n const messages = yield* decodePromptMessages(payload.messages);\n const forRun = payload.runId === ownerRunId;\n\n pendingToolOrder = new Map(\n declaredApplicationToolCallIds(messages).map((id, index) => [id, index]),\n );\n\n yield* accountResponse(envelope, payload, messages);\n\n const modelVisible =\n !forRun && payload.runScopedPrefixLength !== undefined\n ? Prompt.fromMessages(messages.content.slice(payload.runScopedPrefixLength))\n : messages;\n\n const visibleMessages =\n !forRun && incompleteToolTurns.has(envelope.record.recordId)\n ? withoutApplicationToolCallMessages(modelVisible)\n : modelVisible.content;\n\n for (const message of visibleMessages) {\n state.all.push(message);\n if (!forRun) state.before.push(message);\n }\n state = {\n ...state,\n committedTurns: forRun\n ? Math.max(state.committedTurns, payload.turn)\n : state.committedTurns,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolTurns.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n }),\n );\n emitSummary();\n state = yield* flushTools(state);\n\n const validatedPolicyUsage = yield* Schema.decodeEffect(RunPolicyUsage)(policyUsage).pipe(\n Effect.mapError((cause) =>\n journalError(\"Run policy accounting exceeds its Schema bounds\", cause),\n ),\n );\n\n return {\n ...(toolSelection === undefined ? {} : { toolSelection }),\n policyUsage: validatedPolicyUsage,\n prompt: Prompt.fromMessages(state.all),\n historyBefore: Prompt.fromMessages(state.before),\n committedTurns: state.committedTurns,\n usage: unobservedModelCalls === 0 ? usage : { ...usage, unobservedModelCalls },\n ...(latestWindowId === undefined ? {} : { contextWindowId: latestWindowId }),\n ...(protectedContext === undefined ? {} : { protectedContext }),\n ...(ownerTerminated || pendingContextToolCallId === undefined\n ? {}\n : { pendingContextToolCallId }),\n };\n});\n\n/** Pure projection of one Run's durable recovery state from canonical records. */\nexport const projectRunJournal = Effect.fn(\"RunJournal.projectRunJournal\")(\n (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n runId: RunId,\n ): Effect.Effect<RunJournalProjection, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), runId),\n);\n\n/**\n * Pure valid-prompt projection from canonical records: `UserInputRecorded` +\n * `ModelResponseRecorded` + complete `ToolCallSettled` batches → the deterministic model-visible\n * Prompt (plan §Coordinator flow step 3).\n */\nexport const promptFromCanonicalRecords = Effect.fn(\"RunJournal.promptFromCanonicalRecords\")(\n (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n ): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), undefined).pipe(\n Effect.map((projection) => projection.prompt),\n ),\n);\n\n/** Everything one committed Turn contributes to its canonical batch. */\n/**\n * Staged usage is validated, never repaired: clamping negatives or truncating\n * fractions would under-record canonical usage, and NaN/Infinity must fail\n * typed instead of escaping as a record-construction defect (RUN-023).\n */\nconst validStagedUsage = (label: string, value: number): Effect.Effect<number, RunJournalError> =>\n Number.isSafeInteger(value) && value >= 0\n ? Effect.succeed(value)\n : Effect.fail(\n journalError(`Staged ${label} must be a non-negative safe integer, got ${String(value)}`),\n );\n\nexport interface TurnCommitInput {\n readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined;\n readonly toolExposure?: Snapshot | undefined;\n readonly toolSelections?: ReadonlyMap<string, Selection> | undefined;\n readonly budgetRejectedCalls?: ReadonlySet<string>;\n readonly runId: RunId;\n /** Canonical (Run-relative, Attempt-independent) Turn number; must be positive. */\n readonly turn: number;\n readonly turnId: TurnId;\n /**\n * The Prompt messages this Turn appended to official history, in order, including the Turn's\n * Tool message when application Tools ran. Tool messages become `ToolCallSettled` records; the\n * remaining messages become the Turn's `ModelResponseRecorded.messages`.\n */\n readonly appended: ReadonlyArray<Prompt.Message>;\n readonly producerId: ProducerId;\n readonly deploymentId: DeploymentId;\n readonly createdAt: DateTime.Utc;\n /** Leading instruction/wake messages that stay canonical but are hidden from later Runs. */\n readonly runScopedPrefixLength?: number | undefined;\n /** Terminal output committed atomically with this Turn's final canonical batch. */\n readonly runCompletion?:\n | {\n readonly output: PersistedJson;\n readonly runDisposition?: PersistedJson | undefined;\n readonly finishReason?: \"budget-exhausted\" | undefined;\n readonly exhausted?: ExhaustedLimit | undefined;\n }\n | undefined;\n /** Known missing-accounting invocations staged before this canonical response. */\n readonly unobservedModelCalls?: number | undefined;\n /** Per-call provider usage staged by the engine's `noteTurnUsage` (RUN-023). */\n readonly usage?:\n | {\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd?: number | undefined;\n readonly modelUsage?: ReadonlyArray<ModelCallUsage> | undefined;\n }\n | undefined;\n}\n\nconst decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);\nconst encodePrompt = Schema.encodeEffect(Prompt.Prompt);\nconst decodeModelUsage = Schema.decodeUnknownEffect(Schema.Array(ModelCallUsage));\n\nconst requireCanonicalTurn = (turn: number): Effect.Effect<void, RunJournalError> =>\n !Number.isInteger(turn) || turn <= 0\n ? Effect.fail(journalError(`Canonical turn number must be a positive integer: ${turn}`))\n : Effect.void;\n\ninterface SplitTurnMessages {\n readonly promptMessages: ReadonlyArray<Prompt.Message>;\n readonly toolParts: ReadonlyArray<Prompt.ToolResultPart>;\n}\n\nconst splitTurnMessages = (appended: ReadonlyArray<Prompt.Message>): SplitTurnMessages => {\n const promptMessages: Array<Prompt.Message> = [];\n const toolParts: Array<Prompt.ToolResultPart> = [];\n\n for (const message of appended) {\n if (message.role !== \"tool\") {\n promptMessages.push(message);\n continue;\n }\n for (const part of message.content) {\n if (part.type !== \"tool-result\") continue;\n toolParts.push(part);\n }\n }\n\n return { promptMessages, toolParts };\n};\n\nconst modelResponseRecord = Effect.fn(\"RunJournal.modelResponseRecord\")(function* (\n input: TurnCommitInput,\n promptMessages: ReadonlyArray<Prompt.Message>,\n): Effect.fn.Return<RecordEnvelope, RunJournalError | DigestError, Crypto.Crypto> {\n if (promptMessages.length === 0) {\n return yield* journalError(`Turn ${input.turn} appended no model-visible Prompt messages`);\n }\n const runScopedPrefixLength = input.runScopedPrefixLength;\n\n if (\n runScopedPrefixLength !== undefined &&\n (input.turn !== 1 ||\n !Number.isSafeInteger(runScopedPrefixLength) ||\n runScopedPrefixLength <= 0 ||\n runScopedPrefixLength >= promptMessages.length ||\n promptMessages\n .slice(0, runScopedPrefixLength)\n .some((message) => message.role !== \"system\" && message.role !== \"user\"))\n ) {\n return yield* journalError(\n \"Run-scoped Prompt provenance must identify a non-empty system/user prefix of Turn 1 before its assistant response\",\n );\n }\n\n const encodedMessages = yield* encodePrompt(Prompt.fromMessages([...promptMessages])).pipe(\n Effect.mapError((cause) => journalError(\"Turn Prompt messages failed to encode\", cause)),\n );\n\n const messages = yield* decodePersistedJson(encodedMessages).pipe(\n Effect.mapError((cause) =>\n journalError(\"Turn Prompt messages exceed canonical persistence bounds\", cause),\n ),\n );\n\n const messagesDigest = yield* digestJson(messages);\n\n const modelUsage =\n input.usage?.modelUsage === undefined\n ? undefined\n : yield* decodeModelUsage(input.usage.modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage failed to decode\", cause)),\n );\n\n if (modelUsage !== undefined) {\n if (modelUsage.length === 0) {\n return yield* journalError(\"Turn model usage must contain at least one completed call\");\n }\n\n const summary = yield* summarizeModelUsage(modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage exceeds accounting bounds\", cause)),\n );\n\n if (\n input.usage === undefined ||\n input.usage.inputTokens !== summary.inputTokens.total ||\n input.usage.outputTokens !== summary.outputTokens.total ||\n (input.usage.costMicrousd ?? 0) !== summary.costMicrousd\n ) {\n return yield* journalError(\"Turn detailed and aggregate model usage disagree\");\n }\n }\n\n return RecordEnvelope.make({\n recordId: modelResponseRecordId(input.runId, input.turn),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: ModelResponseRecorded.make({\n ...(input.toolParameterRejections === undefined || input.toolParameterRejections.length === 0\n ? {}\n : { toolParameterRejections: input.toolParameterRejections }),\n ...(input.toolExposure === undefined ? {} : { toolExposure: input.toolExposure }),\n runId: input.runId,\n turnId: input.turnId,\n turn: input.turn,\n messages,\n messagesDigest,\n ...(runScopedPrefixLength === undefined ? {} : { runScopedPrefixLength }),\n ...(modelUsage === undefined ? {} : { modelUsage }),\n ...(input.unobservedModelCalls === undefined || input.unobservedModelCalls === 0\n ? {}\n : {\n unobservedModelCalls: yield* validStagedUsage(\n \"unobservedModelCalls\",\n input.unobservedModelCalls,\n ),\n }),\n ...(input.usage === undefined\n ? {}\n : {\n inputTokens: yield* validStagedUsage(\"inputTokens\", input.usage.inputTokens),\n outputTokens: yield* validStagedUsage(\"outputTokens\", input.usage.outputTokens),\n // Written only when non-zero: absent re-seeds as zero, so the\n // no-estimator case stays byte-identical to pre-cost histories.\n ...(input.usage.costMicrousd === undefined || input.usage.costMicrousd === 0\n ? {}\n : {\n costMicrousd: yield* validStagedUsage(\"costMicrousd\", input.usage.costMicrousd),\n }),\n }),\n }),\n });\n});\n\nconst toolSettledRecords = Effect.fn(\"RunJournal.toolSettledRecords\")(function* (\n input: TurnCommitInput,\n toolParts: ReadonlyArray<Prompt.ToolResultPart>,\n): Effect.fn.Return<Array<RecordEnvelope>, RunJournalError> {\n const toolRecords: Array<RecordEnvelope> = [];\n\n for (const part of toolParts) {\n const result = yield* decodePersistedJson(part.result).pipe(\n Effect.mapError((cause) =>\n journalError(`Tool result ${part.id} exceeds canonical persistence bounds`, cause),\n ),\n );\n\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(part.id),\n catch: (cause) => journalError(`Invalid Tool Call ID ${part.id}`, cause),\n });\n\n toolRecords.push(\n RecordEnvelope.make({\n recordId: toolCallSettledRecordId(input.runId, input.turn, toolCallId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: ToolCallSettled.make({\n ...(input.toolSelections?.get(part.id) === undefined\n ? {}\n : { toolSelection: input.toolSelections.get(part.id) }),\n runId: input.runId,\n toolCallId,\n toolName: part.name,\n result,\n isFailure: part.isFailure,\n ...(input.budgetRejectedCalls?.has(part.id) === true ? { budgetRejected: true } : {}),\n }),\n }),\n );\n }\n\n return toolRecords;\n});\n\nconst runCompletionRecord = (input: TurnCommitInput): RecordEnvelope | undefined =>\n input.runCompletion === undefined\n ? undefined\n : RecordEnvelope.make({\n recordId: runCompletedRecordId(input.runId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: RunCompleted.make({\n runId: input.runId,\n output: input.runCompletion.output,\n ...(input.runCompletion.runDisposition === undefined\n ? {}\n : { runDisposition: input.runCompletion.runDisposition }),\n ...(input.runCompletion.finishReason === undefined\n ? {}\n : { finishReason: input.runCompletion.finishReason }),\n ...(input.runCompletion.exhausted === undefined\n ? {}\n : { exhausted: input.runCompletion.exhausted }),\n }),\n });\n\n/**\n * Pure per-Turn canonical batch builder (TurnCompleted seam fold, D6/D8): one\n * `ModelResponseRecorded` record plus one `ToolCallSettled` record per terminal Tool result, all\n * under the WP0-style deterministic identities, committed as ONE atomic batch. The same input\n * always yields byte-identical content, so an in-Attempt append retry is an honest batch replay.\n *\n * Phase 5 keeps this shape for Turns that declare no application Tool calls; their terminal\n * `RunCompleted` marker joins the response in this same atomic batch. Tool-declaring Turns split\n * into `turnResponseBatch` + `turnResultsBatch`.\n */\nexport const turnCanonicalBatch = Effect.fn(\"RunJournal.turnCanonicalBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {\n yield* requireCanonicalTurn(input.turn);\n const { promptMessages, toolParts } = splitTurnMessages(input.appended);\n const modelResponse = yield* modelResponseRecord(input, promptMessages);\n const toolRecords = yield* toolSettledRecords(input, toolParts);\n const completionRecord = runCompletionRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [modelResponse, ...toolRecords]\n : [modelResponse, ...toolRecords, completionRecord],\n });\n});\n\n/**\n * Commit 1 of a tool-declaring Turn: the Turn's `ModelResponseRecorded` record, including\n * provider results retained in assistant content before application Tools execute.\n * — pending steering plus the assistant response with its declared tool calls — under batch\n * identity `turn-response:{runId}:{turn}`. Committing the response before preparation creates\n * the provably-safe durability §15 window (\"after model item commit, before tool preparation →\n * resume tool scheduling\"): a crash there resumes the declared batch with no model re-invocation\n * and no Unknown. Tool messages in `appended` are ignored; the record identity is the same\n * `model-response:{runId}:{turn}` as the single-batch shape, so record-id assertions and the\n * prompt projection are unchanged.\n */\nexport const turnResponseBatch = Effect.fn(\"RunJournal.turnResponseBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {\n yield* requireCanonicalTurn(input.turn);\n const { promptMessages } = splitTurnMessages(input.appended);\n const modelResponse = yield* modelResponseRecord(input, promptMessages);\n\n return CanonicalBatch.make({\n batchId: turnResponseBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records: [modelResponse],\n });\n});\n\n/**\n * Commit 5 of a tool-declaring Turn (plan §2.1): the Turn's `ToolCallSettled` records in\n * declaration order under batch identity `turn-results:{runId}:{turn}` — the batch becomes\n * model-visible atomically. Non-tool messages in `appended` are ignored; a Turn without any\n * terminal Tool result has no results batch and fails typed.\n */\nexport const turnResultsBatch = Effect.fn(\"RunJournal.turnResultsBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError> {\n yield* requireCanonicalTurn(input.turn);\n const { toolParts } = splitTurnMessages(input.appended);\n const toolRecords = yield* toolSettledRecords(input, toolParts);\n const first = toolRecords[0];\n\n if (first === undefined) {\n return yield* journalError(`Turn ${input.turn} has no terminal Tool results to commit`);\n }\n if (input.runCompletion !== undefined && toolRecords.length !== 1) {\n return yield* journalError(\"A terminal Tool completion requires exactly one settled result\");\n }\n const completionRecord = runCompletionRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnResultsBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [first, ...toolRecords.slice(1)]\n : [first, ...toolRecords.slice(1), completionRecord],\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAa,uBACX,YACA,SACG;CACH,MAAM,qCAAqB,IAAI,IAAoB;CAEnD,IAAI,MAAM,kBAAkB,KAAA,GAAW,mBAAmB,IAAI,KAAK,OAAO,KAAK,aAAa;CAC5F,MAAM,4CAA4B,IAAI,IAAoB;CAC1D,MAAM,wCAAwB,IAAI,IAAoB;CACtD,MAAM,eAAsE,CAAC;CAC7E,MAAM,2CAA2B,IAAI,IAAY;CAEjD,MAAM,8BAAc,IAAI,IAGtB;CAEF,MAAM,cAAyF,CAAC;CAEhG,OAAO;EACL,MAAM,aAA4C;GAChD,MAAM,UAAU,SAAS,OAAO;GAEhC,KACG,QAAQ,SAAS,kBAChB,QAAQ,SAAS,eACjB,QAAQ,SAAS,wBACnB,QAAQ,UAAU,KAAA,KAClB,CAAC,sBAAsB,IAAI,QAAQ,KAAK,GAExC,sBAAsB,IAAI,QAAQ,OAAO,SAAS,QAAQ;GAC5D,IAAI,QAAQ,SAAS,qBAAqB;IACxC,YAAY,KAAK;KAAE;KAAS,UAAU,SAAS;IAAS,CAAC;IAEzD;GACF;GACA,IACE,WAAW,WACX,OAAO,QAAQ,UAAU,YACzB,CAAC,mBAAmB,IAAI,QAAQ,KAAK,GAErC,mBAAmB,IAAI,QAAQ,OAAO,SAAS,QAAQ;GACzD,IAAI,QAAQ,SAAS,yBACnB,0BAA0B,IAAI,QAAQ,OAAO,SAAS,QAAQ;QACzD,IAAI,QAAQ,SAAS,mBAAmB;IAC7C,yBA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E,qBAAqB,KAAA,IACjB,CAAC,OAAO,GAAG,YAAY,MAAM,CAAC,CAAC,IAC/B;GAAC;GAAO,GAAG,YAAY,MAAM,CAAC;GAAG;EAAgB;CACzD,CAAC;AACH,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { a as Receipt } from "./Receipt-BAHyigAF.mjs";
2
- import { _ as Digest, h as DefinitionDigests } from "./Records-CMByd1eD.mjs";
2
+ import { _ as Digest, h as DefinitionDigests } from "./Records-CV49DgQK.mjs";
3
3
  import { Context, Effect, Schema } from "effect";
4
4
  declare namespace Schedule_d_exports {
5
5
  export { ScheduleAuthorizationDecision, ScheduleAuthorizationError, ScheduleAuthorizer, ScheduleCapacityError, ScheduleChange, ScheduleConfiguration, ScheduleConflict, ScheduleDestination, ScheduleDueCursor, ScheduleFailpoint, ScheduleFailpointError, ScheduleId, ScheduleInstant, ScheduleKey, ScheduleManagementAuthorization, ScheduleManagementOperation, ScheduleNotFound, ScheduleOccurrenceAuthorization, ScheduleOwner, SchedulePage, SchedulePageRequest, SchedulePending, ScheduleRecord, ScheduleRefusal, ScheduleRetry, ScheduleRetryReason, ScheduleScope, ScheduleSkippedRange, ScheduleSnapshot, ScheduleSnapshotPage, ScheduleStorageError, ScheduleStore, ScheduleStoreFailure, ScheduleTiming, ScheduleTimingRequest, ScheduleValidationError, ScheduleWake, ScheduledEnvelope, ScheduledInputAdmission, ScheduledInputFailure, ScheduledInputRefused, ScheduledInputRetryable, SchedulingLimits, defaultSchedulingLimits };
@@ -839,4 +839,4 @@ declare const ScheduleFailpoint: Context.Reference<{
839
839
  }>;
840
840
  //#endregion
841
841
  export { ScheduleSnapshotPage as A, ScheduledInputAdmission as B, ScheduleRecord as C, ScheduleScope as D, ScheduleRetryReason as E, ScheduleTimingRequest as F, defaultSchedulingLimits as G, ScheduledInputRefused as H, ScheduleValidationError as I, ScheduleWake as L, ScheduleStore as M, ScheduleStoreFailure as N, ScheduleSkippedRange as O, ScheduleTiming as P, Schedule_d_exports as R, SchedulePending as S, ScheduleRetry as T, ScheduledInputRetryable as U, ScheduledInputFailure as V, SchedulingLimits as W, ScheduleNotFound as _, ScheduleChange as a, SchedulePage as b, ScheduleDestination as c, ScheduleFailpointError as d, ScheduleId as f, ScheduleManagementOperation as g, ScheduleManagementAuthorization as h, ScheduleCapacityError as i, ScheduleStorageError as j, ScheduleSnapshot as k, ScheduleDueCursor as l, ScheduleKey as m, ScheduleAuthorizationError as n, ScheduleConfiguration as o, ScheduleInstant as p, ScheduleAuthorizer as r, ScheduleConflict as s, ScheduleAuthorizationDecision as t, ScheduleFailpoint as u, ScheduleOccurrenceAuthorization as v, ScheduleRefusal as w, SchedulePageRequest as x, ScheduleOwner as y, ScheduledEnvelope as z };
842
- //# sourceMappingURL=Schedule-BxCfnYr0.d.mts.map
842
+ //# sourceMappingURL=Schedule-DePbGfgd.d.mts.map
@@ -2,7 +2,7 @@ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { ThreadId } from "./core/Identifiers.mjs";
3
3
  import { n as utf8ByteLength } from "./utf8-DchGZRBd.mjs";
4
4
  import { IdempotencyKey } from "./core/Receipt.mjs";
5
- import { T as PersistedJson, p as DefinitionDigests } from "./Records-BEz5IFUu.mjs";
5
+ import { T as PersistedJson, p as DefinitionDigests } from "./Records-BAutSSnJ.mjs";
6
6
  import { digestJson } from "./durable/Digest.mjs";
7
7
  import { ScheduleAuthorizer, ScheduleConflict, ScheduleDestination, ScheduleFailpoint, ScheduleInstant, ScheduleNotFound, ScheduleStorageError, ScheduleStore, ScheduleTimingRequest, ScheduleValidationError, ScheduleWake, ScheduledInputAdmission, SchedulingLimits, defaultSchedulingLimits } from "./durable/Schedule.mjs";
8
8
  import { admitPreparedInput } from "./durable/PreparedInputAdmission.mjs";
@@ -688,4 +688,4 @@ var ScheduleDriver = class ScheduleDriver extends Context.Service()("@effect-age
688
688
  //#endregion
689
689
  export { Scheduling_exports as i, ScheduleWakeNoop as n, Scheduling as r, ScheduleDriver as t };
690
690
 
691
- //# sourceMappingURL=Scheduling-BW6BD_TP.mjs.map
691
+ //# sourceMappingURL=Scheduling-C3QpYn0W.mjs.map