@yielded/agent 0.1.0-beta.174 → 0.1.0-beta.176

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 (177) hide show
  1. package/dist/{Admin-BHmp2V9p.d.mts → Admin-DTDihBra.d.mts} +50 -13
  2. package/dist/{AgentRuntime-BD3ZHAMq.d.mts → AgentRuntime-CHDyRbSf.d.mts} +3 -3
  3. package/dist/{AgentRuntime-B6qZlD3f.mjs → AgentRuntime-DaDKMasp.mjs} +123 -114
  4. package/dist/AgentRuntime-DaDKMasp.mjs.map +1 -0
  5. package/dist/{Digest-EpeqWEdv.mjs → Digest-C3EODOee.mjs} +2 -2
  6. package/dist/{Digest-EpeqWEdv.mjs.map → Digest-C3EODOee.mjs.map} +1 -1
  7. package/dist/{DurableAgentRuntime-CBBjRNJN.mjs → DurableAgentRuntime-BJbuIqQq.mjs} +237 -114
  8. package/dist/DurableAgentRuntime-BJbuIqQq.mjs.map +1 -0
  9. package/dist/{EventSource-C9aaJaXT.d.mts → EventSource-Cc58uEso.d.mts} +2 -2
  10. package/dist/InMemory.d.mts +2 -2
  11. package/dist/{MessageDelivery-BGDm-c46.d.mts → MessageDelivery-ClHg7c0O.d.mts} +42 -42
  12. package/dist/{MessagingHost-CRUK4JBi.mjs → MessagingHost-CZCyrnvJ.mjs} +27 -26
  13. package/dist/MessagingHost-CZCyrnvJ.mjs.map +1 -0
  14. package/dist/{PreparedInputAdmission-BvDqlgiP.d.mts → PreparedInputAdmission-CjcX1OP0.d.mts} +3 -3
  15. package/dist/{Records-BiuJDWNe.mjs → Records-DzL4Kbtw.mjs} +2 -2
  16. package/dist/{Records-BiuJDWNe.mjs.map → Records-DzL4Kbtw.mjs.map} +1 -1
  17. package/dist/{RunContinuation-4ZATcVLB.mjs → RunContinuation-CWHuciup.mjs} +74 -40
  18. package/dist/RunContinuation-CWHuciup.mjs.map +1 -0
  19. package/dist/{RunContinuation-CTJ1jGrO.d.mts → RunContinuation-DSnUTSSb.d.mts} +11 -5
  20. package/dist/{RunJournal-CNZqA3Ge.mjs → RunJournal-DGblbFas.mjs} +86 -81
  21. package/dist/RunJournal-DGblbFas.mjs.map +1 -0
  22. package/dist/{RunStorage-BHjuuERI.mjs → RunStorage-BF2YgWkg.mjs} +44 -33
  23. package/dist/RunStorage-BF2YgWkg.mjs.map +1 -0
  24. package/dist/{Scheduling-NG8slKdI.mjs → Scheduling-07_dsGED.mjs} +3 -3
  25. package/dist/{Scheduling-NG8slKdI.mjs.map → Scheduling-07_dsGED.mjs.map} +1 -1
  26. package/dist/{Subagent-CTIpnzlB.mjs → Subagent-CexndZSp.mjs} +2 -2
  27. package/dist/{Subagent-CTIpnzlB.mjs.map → Subagent-CexndZSp.mjs.map} +1 -1
  28. package/dist/{Subagent-DKhZA72u.d.mts → Subagent-xhN_aD1r.d.mts} +3 -3
  29. package/dist/{Subscription-BNg9VCRl.d.mts → Subscription-DuC_PcGx.d.mts} +2 -2
  30. package/dist/{SubscriptionInput-BUoXv-_K.d.mts → SubscriptionInput-B1IeAEDi.d.mts} +2 -2
  31. package/dist/{Thread-dk-QiNml.d.mts → Thread-DzdJAY4J.d.mts} +4 -3
  32. package/dist/{ThreadHistory-ByxS8HU1.d.mts → ThreadHistory-KPPBJLJb.d.mts} +12 -2
  33. package/dist/{ThreadImport-CMgzttvr.d.mts → ThreadImport-D_Biid6w.d.mts} +42 -42
  34. package/dist/{ThreadImport-CodYoJoa.mjs → ThreadImport-ZgWxf7bB.mjs} +8 -8
  35. package/dist/{ThreadImport-CodYoJoa.mjs.map → ThreadImport-ZgWxf7bB.mjs.map} +1 -1
  36. package/dist/{ThreadStore-59uDGXul.mjs → ThreadStore-BC4V-mY-.mjs} +42 -23
  37. package/dist/ThreadStore-BC4V-mY-.mjs.map +1 -0
  38. package/dist/{ThreadTransfer-3jigUl3g.mjs → ThreadTransfer-S7FnTRHt.mjs} +4 -4
  39. package/dist/{ThreadTransfer-3jigUl3g.mjs.map → ThreadTransfer-S7FnTRHt.mjs.map} +1 -1
  40. package/dist/{WorkerAdmission-DDYJdOsU.mjs → WorkerAdmission-C47Vy_cK.mjs} +5 -5
  41. package/dist/{WorkerAdmission-DDYJdOsU.mjs.map → WorkerAdmission-C47Vy_cK.mjs.map} +1 -1
  42. package/dist/{agent-registration-DRbyhAu-.mjs → agent-registration-a6QYaG3h.mjs} +4 -4
  43. package/dist/{agent-registration-DRbyhAu-.mjs.map → agent-registration-a6QYaG3h.mjs.map} +1 -1
  44. package/dist/capabilities/Messaging.mjs +1 -1
  45. package/dist/capabilities/ModelContext.d.mts +1 -1
  46. package/dist/capabilities/RunHooks.d.mts +1 -1
  47. package/dist/capabilities/Subagent.d.mts +1 -1
  48. package/dist/capabilities/Subagent.mjs +1 -1
  49. package/dist/core/Thread.d.mts +2 -2
  50. package/dist/core/Thread.mjs +5 -3
  51. package/dist/core/Thread.mjs.map +1 -1
  52. package/dist/durable/ActivityStore.mjs +1 -1
  53. package/dist/durable/Admin.d.mts +1 -1
  54. package/dist/durable/Admin.mjs +1 -1
  55. package/dist/durable/AgentRegistration.d.mts +1 -1
  56. package/dist/durable/AgentRegistration.mjs +1 -1
  57. package/dist/durable/Certification.d.mts +1 -1
  58. package/dist/durable/CommittedActivity.d.mts +1 -1
  59. package/dist/durable/CommittedActivity.mjs +3 -3
  60. package/dist/durable/Digest.mjs +1 -1
  61. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  62. package/dist/durable/DurableAgentRuntime.mjs +2 -2
  63. package/dist/durable/EventSource.d.mts +1 -1
  64. package/dist/durable/EventSource.mjs +1 -1
  65. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  66. package/dist/durable/LifecyclePublication.d.mts +1 -1
  67. package/dist/durable/LifecyclePublication.mjs +2 -2
  68. package/dist/durable/MessageDelivery.d.mts +1 -1
  69. package/dist/durable/MessageDelivery.mjs +2 -2
  70. package/dist/durable/MessageDeliveryStoreConformance.d.mts +40 -40
  71. package/dist/durable/MessageDeliveryStoreConformance.mjs +2 -2
  72. package/dist/durable/PersistentHistory.d.mts +2 -2
  73. package/dist/durable/PersistentHistory.mjs +4 -4
  74. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  75. package/dist/durable/RecordFormat.mjs +1 -1
  76. package/dist/durable/Records.mjs +1 -1
  77. package/dist/durable/Recovery.d.mts +1 -1
  78. package/dist/durable/Recovery.mjs +1 -1
  79. package/dist/durable/RunContinuation.d.mts +2 -2
  80. package/dist/durable/RunContinuation.mjs +3 -3
  81. package/dist/durable/RunJournal.d.mts +2 -2
  82. package/dist/durable/RunJournal.mjs +2 -2
  83. package/dist/durable/RunStorage.d.mts +1 -1
  84. package/dist/durable/RunStorage.mjs +1 -1
  85. package/dist/durable/Schedule.mjs +1 -1
  86. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  87. package/dist/durable/ScheduleTransition.mjs +1 -1
  88. package/dist/durable/Scheduling.d.mts +1 -1
  89. package/dist/durable/Scheduling.mjs +1 -1
  90. package/dist/durable/SettlementPublisher.d.mts +1 -1
  91. package/dist/durable/SettlementPublisher.mjs +3 -3
  92. package/dist/durable/SqlMemoryStore.mjs +5 -3
  93. package/dist/durable/SqlMemoryStore.mjs.map +1 -1
  94. package/dist/durable/SubmissionLedger.d.mts +1 -1
  95. package/dist/durable/SubmissionLedger.mjs +7 -3
  96. package/dist/durable/SubmissionLedger.mjs.map +1 -1
  97. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  98. package/dist/durable/SubmissionLedgerConformance.mjs +6 -6
  99. package/dist/durable/SubmissionStatus.d.mts +1 -1
  100. package/dist/durable/Subscription.d.mts +1 -1
  101. package/dist/durable/Subscription.mjs +2 -2
  102. package/dist/durable/SubscriptionInput.d.mts +1 -1
  103. package/dist/durable/SubscriptionInput.mjs +2 -2
  104. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  105. package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
  106. package/dist/durable/SubscriptionTools.d.mts +2 -2
  107. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  108. package/dist/durable/SubscriptionTransition.mjs +1 -1
  109. package/dist/durable/Subscriptions.d.mts +5 -5
  110. package/dist/durable/Subscriptions.mjs +2 -2
  111. package/dist/durable/ThreadArchiveRange.d.mts +1 -1
  112. package/dist/durable/ThreadArchiveRange.mjs +1 -1
  113. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  114. package/dist/durable/ThreadContextHistory.mjs +2 -2
  115. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  116. package/dist/durable/ThreadImport.d.mts +1 -1
  117. package/dist/durable/ThreadImport.mjs +1 -1
  118. package/dist/durable/ThreadInvariants.d.mts +3 -3
  119. package/dist/durable/ThreadInvariants.mjs +4 -4
  120. package/dist/durable/ThreadProjection.mjs +1 -1
  121. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  122. package/dist/durable/ThreadReader.d.mts +1 -1
  123. package/dist/durable/ThreadReader.mjs +1 -1
  124. package/dist/durable/ThreadStore.d.mts +1 -1
  125. package/dist/durable/ThreadStore.mjs +2 -2
  126. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  127. package/dist/durable/ThreadStoreConformance.mjs +4 -4
  128. package/dist/durable/ThreadTransfer.d.mts +1 -1
  129. package/dist/durable/ThreadTransfer.mjs +1 -1
  130. package/dist/durable/ThreadWork.d.mts +2 -2
  131. package/dist/durable/ThreadWork.mjs +12 -6
  132. package/dist/durable/ThreadWork.mjs.map +1 -1
  133. package/dist/durable/ToolReconciler.mjs +1 -1
  134. package/dist/durable/WakeScheduler.mjs +23 -39
  135. package/dist/durable/WakeScheduler.mjs.map +1 -1
  136. package/dist/durable/WorkerAdmission.d.mts +68 -68
  137. package/dist/durable/WorkerAdmission.mjs +1 -1
  138. package/dist/durable/WorkerHost.d.mts +1 -1
  139. package/dist/engine/AgentRuntime.d.mts +1 -1
  140. package/dist/engine/AgentRuntime.mjs +1 -1
  141. package/dist/engine/MessagingHost.mjs +1 -1
  142. package/dist/engine/Output.mjs +1 -1
  143. package/dist/engine/ThreadHistory.d.mts +1 -1
  144. package/dist/engine/ThreadHistory.mjs +3 -2
  145. package/dist/engine/ThreadHistory.mjs.map +1 -1
  146. package/dist/index.d.mts +12 -12
  147. package/dist/index.mjs +13 -13
  148. package/dist/{output-contract-CMIhu4Cw.mjs → output-contract-DCnLYCdp.mjs} +12 -15
  149. package/dist/{output-contract-CMIhu4Cw.mjs.map → output-contract-DCnLYCdp.mjs.map} +1 -1
  150. package/dist/{run-context-reader-CC7ZD95F.d.mts → run-context-reader-DvTEq2RC.d.mts} +2 -2
  151. package/package.json +1 -1
  152. package/src/core/Thread.ts +143 -146
  153. package/src/durable/DurableAgentRuntime.ts +549 -260
  154. package/src/durable/RunContinuation.ts +115 -64
  155. package/src/durable/RunJournal.ts +107 -112
  156. package/src/durable/RunStorage.ts +90 -61
  157. package/src/durable/SqlMemoryStore.ts +8 -6
  158. package/src/durable/SubmissionLedger.ts +15 -0
  159. package/src/durable/ThreadStore.ts +48 -26
  160. package/src/durable/ThreadWork.ts +10 -0
  161. package/src/durable/WakeScheduler.ts +34 -66
  162. package/src/durable/internal/initial-context.ts +17 -2
  163. package/src/durable/internal/prompt-history-cache.ts +13 -8
  164. package/src/durable/internal/usage-totals.ts +28 -31
  165. package/src/engine/MessagingHost.ts +4 -2
  166. package/src/engine/ThreadHistory.ts +47 -48
  167. package/src/engine/internal/agent-runtime.ts +234 -202
  168. package/src/engine/internal/output-contract.ts +15 -15
  169. package/src/engine/internal/primitive-delta.ts +2 -3
  170. package/src/engine/internal/tool-telemetry.ts +3 -5
  171. package/dist/AgentRuntime-B6qZlD3f.mjs.map +0 -1
  172. package/dist/DurableAgentRuntime-CBBjRNJN.mjs.map +0 -1
  173. package/dist/MessagingHost-CRUK4JBi.mjs.map +0 -1
  174. package/dist/RunContinuation-4ZATcVLB.mjs.map +0 -1
  175. package/dist/RunJournal-CNZqA3Ge.mjs.map +0 -1
  176. package/dist/RunStorage-BHjuuERI.mjs.map +0 -1
  177. package/dist/ThreadStore-59uDGXul.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"Records-BiuJDWNe.mjs","names":[],"sources":["../src/durable/internal/history-prompt.ts","../src/durable/Records.ts"],"sourcesContent":["import { Effect, Schema, SchemaParser, SchemaTransformation } from \"effect\";\nimport { Prompt } from \"effect/ai\";\n\nfunction restorePart(part: Prompt.UserMessagePartEncoded): Prompt.UserMessagePart;\nfunction restorePart(part: Prompt.AssistantMessagePartEncoded): Prompt.AssistantMessagePart;\nfunction restorePart(part: Prompt.ToolMessagePartEncoded): Prompt.ToolMessagePart;\nfunction restorePart(part: Prompt.PartEncoded): Prompt.Part {\n switch (part.type) {\n case \"text\":\n return Prompt.textPart(part);\n case \"reasoning\":\n return Prompt.reasoningPart(part);\n case \"file\":\n return Prompt.filePart(part);\n case \"tool-call\":\n return Prompt.toolCallPart({ ...part, providerExecuted: part.providerExecuted ?? false });\n case \"tool-result\":\n return Prompt.toolResultPart({ ...part, providerExecuted: part.providerExecuted ?? false });\n case \"tool-approval-request\":\n return Prompt.toolApprovalRequestPart(part);\n case \"tool-approval-response\":\n return Prompt.toolApprovalResponsePart(part);\n }\n}\n\nconst restoreMessage = (message: Prompt.MessageEncoded): Prompt.Message => {\n switch (message.role) {\n case \"system\":\n return Prompt.makeMessage(\"system\", message);\n case \"user\":\n return Prompt.makeMessage(\"user\", {\n ...message,\n content:\n typeof message.content === \"string\"\n ? [Prompt.textPart({ text: message.content })]\n : message.content.map((part) => restorePart(part)),\n });\n case \"assistant\":\n return Prompt.makeMessage(\"assistant\", {\n ...message,\n content:\n typeof message.content === \"string\"\n ? [Prompt.textPart({ text: message.content })]\n : message.content.map((part) => restorePart(part)),\n });\n case \"tool\":\n return Prompt.makeMessage(\"tool\", {\n ...message,\n content: message.content.map((part) => restorePart(part)),\n });\n }\n};\n\n/**\n * Validate the upstream encoded history once, then restore native values with its constructors.\n * The canonical codec remains authoritative at append, import, recovery and explicit verification.\n */\nexport const HistoryPrompt = Schema.toEncoded(Prompt.Prompt).pipe(\n Schema.decodeTo(\n Schema.toType(Prompt.Prompt),\n SchemaTransformation.transformEffect({\n decode: (input) => Effect.succeed(Prompt.fromMessages(input.content.map(restoreMessage))),\n encode: SchemaParser.encodeEffect(Prompt.Prompt),\n }),\n ),\n);\n","import { Option, Schema, Struct } from \"effect\";\nimport { Prompt } from \"effect/ai\";\n\nimport { InputMessage } from \"../capabilities/Messaging.ts\";\nimport { PolicyLimit } from \"../core/AgentError.ts\";\nimport { AgentPolicy } from \"../core/AgentPolicy.ts\";\nimport { Update } from \"../core/AgentUpdates.ts\";\nimport * as FailureDiagnostic from \"../core/FailureDiagnostic.ts\";\nimport {\n AgentId,\n ThreadId,\n DelegationId,\n ReceiptId,\n RunId,\n SettlementId,\n SubmissionId,\n ToolCallId,\n TurnId,\n} from \"../core/Identifiers.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { IdempotencyKey, Principal, Receipt } from \"../core/Receipt.ts\";\nimport { ExhaustedLimit } from \"../core/RunEvent.ts\";\nimport { RunPolicyUsage } from \"../core/RunPolicyUsage.ts\";\nimport {\n DelegationDepth,\n SubagentBudgetReservation,\n SubagentGrant,\n SubagentParentLink,\n ToolExecutionKind,\n} from \"../core/SubagentContract.ts\";\nimport { Selection, Snapshot } from \"../core/ToolExposure.ts\";\nimport { ToolParameterRejection } from \"../core/ToolResult.ts\";\nimport { ModelCallUsage, RunUsageSummary, RunTotals } from \"../core/Usage.ts\";\nimport { WorkerBudgetScope, WorkerRef, WorkerSource, WorkerStop } from \"../core/Worker.ts\";\nimport { ContextHandoff } from \"../engine/ContextWindow.ts\";\nimport { HistoryPrompt } from \"./internal/history-prompt.ts\";\n\n/** Stable identity of one canonical record. */\nexport const RecordId = Schema.NonEmptyString.pipe(Schema.brand(\"@effect-agent/thread/RecordId\"));\n\nexport type RecordId = typeof RecordId.Type;\n\n/** Stable idempotency identity of one atomic append. */\nexport const BatchId = Schema.NonEmptyString.pipe(Schema.brand(\"@effect-agent/thread/BatchId\"));\n\nexport type BatchId = typeof BatchId.Type;\n\n/** Identity of the deployment that produced a record. */\nexport const DeploymentId = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/thread/DeploymentId\"),\n);\n\nexport type DeploymentId = typeof DeploymentId.Type;\n\n/** Identity of a canonical-log producer. */\nexport const ProducerId = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/thread/ProducerId\"),\n);\n\nexport type ProducerId = typeof ProducerId.Type;\n\n/** SHA-256 digest encoded as lowercase hexadecimal text. */\nexport const Digest = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/)).pipe(\n Schema.brand(\"@effect-agent/thread/Digest\"),\n);\n\nexport type Digest = typeof Digest.Type;\n\n/** Adapter-owned resume cursor. Callers must not parse or synthesize it. */\nexport const ObservationOffset = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/thread/ObservationOffset\"),\n);\n\nexport type ObservationOffset = typeof ObservationOffset.Type;\n\n/** Gap-free position in one Thread's canonical sequence. */\nexport const CanonicalSequence = Schema.Natural.pipe(\n Schema.brand(\"@effect-agent/thread/CanonicalSequence\"),\n);\n\nexport type CanonicalSequence = typeof CanonicalSequence.Type;\n\nconst BoundedText = Schema.String.check(Schema.isMaxLength(64 * 1024));\nconst BoundedName = Schema.NonEmptyString.check(Schema.isMaxLength(256));\n\n/**\n * Private failed-Settlement evidence. The summary remains the safe public projection; diagnostic\n * and context preserve structured causal evidence for authorized operators, never model context.\n * Optional fields allow reading supported Settlements written before causal capture was available.\n */\nexport const SettlementFailureDiagnostic = FailureDiagnostic.Failure.pipe(\n Schema.annotate({\n identifier: \"@effect-agent/thread/SettlementFailureDiagnostic\",\n }),\n);\n\nexport type SettlementFailureDiagnostic = typeof SettlementFailureDiagnostic.Type;\n\n/** Positive canonical (Run-relative, Attempt-independent) Turn number. */\nconst TurnNumber = Schema.Int.check(Schema.isGreaterThan(0));\n\nexport const MAX_PERSISTED_JSON_DEPTH = 64;\nexport const MAX_PERSISTED_JSON_COLLECTION_LENGTH = 4_096;\nexport const MAX_PERSISTED_JSON_NODES = 65_536;\nexport const MAX_PERSISTED_JSON_BYTES = 1024 * 1024;\n/** Whole record wire includes bounded payloads and their canonical envelope. */\nexport const MAX_CANONICAL_RECORD_BYTES = 4 * 1024 * 1024;\n\n/**\n * Iteratively preflights an unknown value before Schema's recursive JSON validation. This is the\n * one narrow `Schema.declare` exception in the persistence model: Effect v4's `Unknown.decodeTo`\n * preserves `unknown` as the encoded type, which would leak through every nested record codec.\n * Schema.Json still owns the accepted value shape after this resource preflight succeeds.\n */\nconst isJson = Schema.is(Schema.Json);\n// No Unicode flag: match surrogate code units so astral characters take the UTF-8 path too.\nconst nonAscii = /[\\u0080-\\uFFFF]/;\n\nconst boundedJson =\n (limits: { readonly depth: number; readonly nodes: number; readonly bytes: number }) =>\n (input: unknown): input is Schema.Json => {\n const pending: Array<\n | { readonly _tag: \"visit\"; readonly value: unknown; readonly depth: number }\n | { readonly _tag: \"leave\"; readonly value: object }\n > = [{ _tag: \"visit\", value: input, depth: 0 }];\n\n // Only ancestors indicate a cycle. Shared acyclic values serialize once per occurrence,\n // so revisit them and charge every occurrence against the same resource limits.\n const ancestors = new WeakSet<object>();\n let nodes = 0;\n let textUnits = 0;\n\n try {\n while (pending.length > 0) {\n const current = pending.pop();\n\n if (current === undefined) return false;\n if (current._tag === \"leave\") {\n ancestors.delete(current.value);\n continue;\n }\n if (current.depth > limits.depth || ++nodes > limits.nodes) {\n return false;\n }\n\n const value = current.value;\n\n if (value === null || typeof value === \"boolean\") continue;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) return false;\n continue;\n }\n if (typeof value === \"string\") {\n textUnits += value.length;\n if (textUnits > limits.bytes) return false;\n continue;\n }\n if (typeof value !== \"object\" || ancestors.has(value)) return false;\n ancestors.add(value);\n pending.push({ _tag: \"leave\", value });\n\n const entries = Array.isArray(value)\n ? Array.from(value, (entry, index) => [index, entry] as const)\n : Object.entries(value);\n\n if (entries.length > MAX_PERSISTED_JSON_COLLECTION_LENGTH) return false;\n for (const [key, entry] of entries) {\n textUnits += typeof key === \"string\" ? key.length : 0;\n if (textUnits > limits.bytes) return false;\n pending.push({ _tag: \"visit\", value: entry, depth: current.depth + 1 });\n }\n }\n\n if (!isJson(input)) return false;\n const encoded = JSON.stringify(input);\n\n // Escaping is already reflected in the serialized text. UTF-8 uses one to three bytes per\n // UTF-16 code unit; ASCII uses exactly one. Only ambiguous Unicode needs the exact count.\n return (\n encoded !== undefined &&\n encoded.length <= limits.bytes &&\n (encoded.length <= limits.bytes / 3 ||\n !nonAscii.test(encoded) ||\n utf8ByteLength(encoded) <= limits.bytes)\n );\n } catch {\n return false;\n }\n };\n\nconst isPersistedJson = boundedJson({\n depth: MAX_PERSISTED_JSON_DEPTH,\n nodes: MAX_PERSISTED_JSON_NODES,\n bytes: MAX_PERSISTED_JSON_BYTES,\n});\n\n/** Canonical JSON admitted to persisted records and checkpoints under explicit resource limits. */\nexport const PersistedJson = Schema.declare(isPersistedJson, {\n identifier: \"@effect-agent/thread/PersistedJson\",\n description: \"JSON bounded by canonical persistence depth, collection, node, and byte limits\",\n});\n\nexport type PersistedJson = typeof PersistedJson.Type;\n\n/** Whole record wire reserves room for the payload's envelope and additional bounded fields. */\nexport const RecordJson = Schema.declare(\n boundedJson({\n depth: MAX_PERSISTED_JSON_DEPTH + 4,\n nodes: MAX_PERSISTED_JSON_NODES * 4,\n bytes: MAX_CANONICAL_RECORD_BYTES,\n }),\n {\n identifier: \"@effect-agent/thread/RecordJson\",\n description: \"Canonical record JSON bounded by depth, collection, node, and 4 MiB byte limits\",\n },\n);\n\nexport type RecordJson = typeof RecordJson.Type;\n\n/** Schema-owned replay inputs whose individual definitions are incorporated into digests. */\nexport class DefinitionDigestInput extends Schema.Class<DefinitionDigestInput>(\n \"@effect-agent/thread/DefinitionDigestInput\",\n)({\n agent: PersistedJson,\n model: PersistedJson,\n tools: PersistedJson,\n}) {}\n\n/** Admission-time operation fingerprints. Agent fingerprints remain immutable evidence only. */\nexport class ReplayContract extends Schema.Class<ReplayContract>(\n \"@effect-agent/thread/ReplayContract\",\n)({\n agent: Digest,\n /** Retained for reading earlier admissions; never selects executable code. */\n agentBehavior: Schema.optionalKey(Digest),\n tools: Schema.Record(Schema.String, Digest),\n}) {}\n\n/** Digests identify admission exactly; only an unfinished operation needs replay compatibility. */\nexport class DefinitionDigests extends Schema.Class<DefinitionDigests>(\n \"@effect-agent/thread/DefinitionDigests\",\n)({\n agent: Digest,\n model: Digest,\n tools: Digest,\n replay: Schema.optionalKey(ReplayContract),\n}) {}\n\nexport class ThreadCreated extends Schema.TaggedClass<ThreadCreated>(\n \"@effect-agent/thread/ThreadCreated\",\n)(\"ThreadCreated\", {\n agentId: AgentId,\n definitions: DefinitionDigests,\n}) {}\n\n/**\n * One recorded Thread input. `submissionId` is present only for durably accepted work;\n * retained history has no admission or settlement obligation. `kind` identifies the input seam.\n */\nexport class UserInputRecorded extends Schema.TaggedClass<UserInputRecorded>(\n \"@effect-agent/thread/UserInputRecorded\",\n)(\"UserInputRecorded\", {\n submissionId: Schema.optionalKey(SubmissionId),\n kind: Schema.Literals([\"user\", \"steering\", \"follow-up\"]),\n runId: Schema.optionalKey(RunId),\n input: PersistedJson,\n messageAdmission: Schema.optionalKey(InputMessage),\n}) {}\n\n/** Immutable Run start and per-Attempt duration allowance, before any agent execution. */\nexport class RunStartedRecord extends Schema.TaggedClass<RunStartedRecord>(\n \"@effect-agent/thread/RunStartedRecord\",\n)(\"RunStarted\", {\n runId: RunId,\n /** Older private histories cannot prove programmatic accounting and must be reset. */\n policyAccountingVersion: Schema.Literal(1),\n maxDurationMillis: Schema.Finite.check(Schema.isGreaterThan(0)),\n}) {}\n\n/** An active Attempt exhausted its execution allowance; downtime alone never writes this. */\nexport class RunDurationExhausted extends Schema.TaggedClass<RunDurationExhausted>(\n \"@effect-agent/thread/RunDurationExhausted\",\n)(\"RunDurationExhausted\", { runId: RunId }) {}\n\nconst PersistedPromptMessages = Schema.toEncoded(Prompt.Prompt);\nconst isPersistedPromptMessages = Schema.is(PersistedPromptMessages);\n\n/**\n * Final model output. Immediate history records the successful Run's source messages for\n * recall and a full retained model-context snapshot for the next Run. Durable execution\n * instead journals individual ModelResponseRecorded Turns and exact context references.\n */\nexport class ModelCompleted extends Schema.TaggedClass<ModelCompleted>(\n \"@effect-agent/thread/ModelCompleted\",\n)(\n \"ModelCompleted\",\n Schema.Struct({\n runId: RunId,\n output: PersistedJson,\n messages: Schema.optionalKey(PersistedJson),\n history: Schema.optionalKey(PersistedJson),\n }).check(\n Schema.makeFilter(\n (record) =>\n (record.messages === undefined && record.history === undefined) ||\n (record.messages !== undefined &&\n record.history !== undefined &&\n isPersistedPromptMessages(record.messages) &&\n isPersistedPromptMessages(record.history)),\n { title: \"Retained source messages and model context are paired encoded Effect AI Prompts\" },\n ),\n ),\n) {}\n\nexport class ToolCallSettled extends Schema.TaggedClass<ToolCallSettled>(\n \"@effect-agent/thread/ToolCallSettled\",\n)(\"ToolCallSettled\", {\n toolSelection: Schema.optionalKey(Selection),\n runId: RunId,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n result: PersistedJson,\n isFailure: Schema.Boolean,\n /** Explicit engine evidence, never inferred from Tool result data. */\n budgetRejected: Schema.optionalKey(Schema.Literal(true)),\n}) {}\n\n/** Compact execution evidence committed with a declaration, before any handler can start. */\nexport class ToolOperation extends Schema.Class<ToolOperation>(\n \"@effect-agent/thread/ToolOperation\",\n)({\n toolCallId: ToolCallId,\n toolName: BoundedName,\n executionClass: Schema.Literals([\"readonly\", \"idempotent\", \"uncertain\"]),\n executionKind: ToolExecutionKind,\n replay: Digest,\n}) {}\n\n/** Derived recovery input from one committed response; never a separate canonical record. */\nexport class DeclaredToolCall extends Schema.Class<DeclaredToolCall>(\n \"@effect-agent/thread/DeclaredToolCall\",\n)({\n ...ToolOperation.fields,\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n parameters: PersistedJson,\n parametersDigest: Digest,\n}) {}\n\n/** A retired call's runtime result. Unavailable readonly work may already have been observed. */\nexport class ToolUnavailable extends Schema.TaggedClass<ToolUnavailable>()(\"ToolUnavailable\", {\n toolName: BoundedName,\n execution: Schema.Literals([\"not-executed\", \"unavailable\"]),\n message: BoundedText,\n}) {}\n\n/**\n * One committed model Turn. `messages` carries the Schema-encoded Effect AI Prompt messages this\n * Turn appended (assistant response plus any tool-call declarations), committed atomically at the\n * Turn boundary so a recovering Attempt can rebuild the next Prompt from canonical records alone.\n */\nconst ModelResponseRecordedFields = Schema.Struct({\n /** Original bound for each application result; replacement Bindings cannot enlarge it. */\n toolResultMaxBytes: Schema.Int.check(\n Schema.isBetween({ minimum: 256, maximum: MAX_PERSISTED_JSON_BYTES }),\n ),\n /** Maximum encoded selection metadata from the native catalog at declaration time. */\n toolSelectionMaxBytes: Schema.Natural.check(\n Schema.isLessThanOrEqualTo(MAX_CANONICAL_RECORD_BYTES),\n ),\n /** Exactly one entry per application call, including rejected calls; none for provider execution. */\n toolOperations: Schema.Array(ToolOperation),\n /** Explicit pre-execution failures, committed with the original arguments before any approval. */\n toolParameterRejections: Schema.optionalKey(Schema.Array(ToolParameterRejection)),\n toolExposure: Schema.optionalKey(Snapshot),\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n messages: PersistedJson,\n /**\n * Number of leading messages that belong only to this Run's evaluated instructions and wake\n * input. They remain canonical. An unfinished Run retains this exact evaluated prefix;\n * subsequent Runs retain its original user intent in conversation history.\n */\n runScopedPrefixLength: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n /**\n * Exact normalized usage for every model call staged into this Turn. A\n * summarizer and the Turn response are distinct entries. Unmetered responses can omit it.\n */\n modelUsage: Schema.optionalKey(Schema.Array(ModelCallUsage)),\n /** Observed invocations without retained accounting before this Turn committed. */\n unobservedModelCalls: Schema.optionalKey(Schema.Natural),\n /** Aggregate observed usage when per-call accounting is unavailable. */\n inputTokens: Schema.optionalKey(Schema.Natural),\n outputTokens: Schema.optionalKey(Schema.Natural),\n /** Estimated spend staged with the usage; recovery re-seeds the cost budget (RUN-023). */\n costMicrousd: Schema.optionalKey(Schema.Natural),\n}).check(\n Schema.makeFilter(\n (response) => {\n if (!isPersistedPromptMessages(response.messages)) return false;\n\n const declarations = response.messages.content.flatMap((message) =>\n message.role === \"assistant\" && typeof message.content !== \"string\"\n ? message.content.filter(\n (part) => part.type === \"tool-call\" && part.providerExecuted !== true,\n )\n : [],\n );\n\n if (declarations.length !== response.toolOperations.length) return false;\n const seen = new Set<string>();\n\n for (const operation of response.toolOperations) {\n if (\n seen.has(operation.toolCallId) ||\n !declarations.some(\n (call) =>\n call.type === \"tool-call\" &&\n call.id === operation.toolCallId &&\n call.name === operation.toolName,\n )\n )\n return false;\n seen.add(operation.toolCallId);\n }\n\n return declarations.every((call) => call.type === \"tool-call\" && seen.has(call.id));\n },\n { title: \"Every application Tool declaration has unique original operation evidence\" },\n ),\n Schema.makeFilter(\n (response) =>\n response.runScopedPrefixLength === undefined ||\n (isPersistedPromptMessages(response.messages) &&\n response.runScopedPrefixLength < response.messages.content.length &&\n response.messages.content\n .slice(0, response.runScopedPrefixLength)\n .every((message) => message.role === \"system\" || message.role === \"user\")),\n {\n title:\n \"Run-scoped Prompt prefix contains only instruction/wake messages and leaves one response\",\n },\n ),\n);\n\nexport class ModelResponseRecorded extends Schema.TaggedClass<ModelResponseRecorded>(\n \"@effect-agent/thread/ModelResponseRecorded\",\n)(\"ModelResponseRecorded\", ModelResponseRecordedFields) {}\n\n/** Monotonic reservations charged before programmatic execution or grace finalization. */\nexport class RunPolicyUsageReserved extends Schema.TaggedClass<RunPolicyUsageReserved>()(\n \"RunPolicyUsageReserved\",\n {\n runId: RunId,\n programmaticToolCalls: RunPolicyUsage.fields.programmaticToolCalls,\n finalizationUsed: RunPolicyUsage.fields.finalizationUsed,\n },\n) {}\n\n/**\n * A durable Unknown Outcome: the external effect of one declared ordinary Tool Call may have\n * happened but was not confirmed canonically (DUR-009/DUR-017). It is neither success nor\n * ordinary failure; automatic continuation stops until an authorized resolution arrives.\n */\nexport class ToolCallUnknown extends Schema.TaggedClass<ToolCallUnknown>(\n \"@effect-agent/thread/ToolCallUnknown\",\n)(\"ToolCallUnknown\", {\n runId: RunId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n reason: BoundedText,\n}) {}\n\n/** How one open/unknown Tool Call was authoritatively closed (DUR-017 resolution audit). */\nexport const ToolCallResolution = Schema.Literals([\n \"completed-with-result\",\n \"failed-with-error\",\n \"never-started\",\n \"safe-retry\",\n]);\n\nexport type ToolCallResolution = typeof ToolCallResolution.Type;\n\n/**\n * The canonical audit record closing one open or unknown Tool Call: reconciler-recovered supplier\n * truth or an authorized `resolveUnknown` command. `author`/`reason` make every resolution an\n * attributable decision (DUR-017); a `completed-with-result` resolution is accompanied by the\n * per-call `ToolCallSettled` record carrying the recovered result.\n */\nexport class ToolCallResolved extends Schema.TaggedClass<ToolCallResolved>(\n \"@effect-agent/thread/ToolCallResolved\",\n)(\"ToolCallResolved\", {\n runId: RunId,\n toolCallId: ToolCallId,\n resolution: ToolCallResolution,\n author: BoundedName,\n reason: BoundedText,\n}) {}\n\n/**\n * One accepted Durable Step result (durability §11): exactly-once-recorded while the Step's\n * external side effect stays honestly at-least-once-executed. Only success is recorded — a failing\n * Step body fails into the handler's error channel and re-executes on re-entry. `output` is the\n * Schema-encoded Step output; `outputDigest` pins it for replay-divergence detection.\n */\nexport class ToolStepSettled extends Schema.TaggedClass<ToolStepSettled>(\n \"@effect-agent/thread/ToolStepSettled\",\n)(\"ToolStepSettled\", {\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: BoundedName,\n output: PersistedJson,\n outputDigest: Digest,\n}) {}\n\n/**\n * A canonical approval request for one declared Tool Call (CAP-006, durability §8): with this\n * record durable, \"waiting for explicit approval\" is a safe suspension boundary — the resumed\n * Attempt replays the declared batch instead of re-invoking the model.\n */\nexport class ToolApprovalRequested extends Schema.TaggedClass<ToolApprovalRequested>(\n \"@effect-agent/thread/ToolApprovalRequested\",\n)(\"ToolApprovalRequested\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n parametersDigest: Digest,\n /** This request preceded every possible dispatch of the original response. */\n blocksInitialDispatch: Schema.Boolean,\n}) {}\n\n/** The two-valued approval decision family shared by canonical records and ledger intents. */\nexport const ApprovalDecision = Schema.Literals([\"approved\", \"denied\"]);\n\nexport type ApprovalDecision = typeof ApprovalDecision.Type;\n\n/**\n * The canonical decision for one requested approval. Appended by the deciding Attempt (policy\n * auto-decisions) or by the resuming Attempt after a durable `resolveApproval` intent; it is the\n * deterministic decision authority for every later Attempt of the same Run.\n */\nexport class ToolApprovalDecided extends Schema.TaggedClass<ToolApprovalDecided>(\n \"@effect-agent/thread/ToolApprovalDecided\",\n)(\"ToolApprovalDecided\", {\n runId: RunId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n decision: ApprovalDecision,\n resolver: BoundedName,\n reason: BoundedText,\n}) {}\n\n/**\n * A Run resumed inference without a retained response. One marker makes usage coverage\n * incomplete; it does not count missing provider calls or retain Attempt history.\n */\nexport class ModelResponseInterrupted extends Schema.TaggedClass<ModelResponseInterrupted>(\n \"@effect-agent/thread/ModelResponseInterrupted\",\n)(\"ModelResponseInterrupted\", {\n runId: RunId,\n}) {}\n\n/** Disposable call cancellation: no response or Tool declaration is canonical. */\nexport class ModelCallAborted extends Schema.TaggedClass<ModelCallAborted>()(\"ModelCallAborted\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n restart: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 2 })),\n reason: Schema.Literal(\"joined-input\"),\n modelUsage: Schema.Array(ModelCallUsage),\n unobservedModelCalls: Schema.Natural,\n}) {}\n\n/**\n * One engine-native compaction committed before the pre-Turn view changes (RUN-026).\n * `coversThrough` is a Thread record sequence: the projection\n * renders records at or below it as a summary (`summarize`), a fresh window (`rollover`), or with\n * cleared tool results (kind `clear-tool-results`), never erasing source\n * history. The record carries no digest by decision: it is appended by the\n * fenced owner into the very log it covers, and re-verifying a digest would\n * re-read the covered range on every wake — the O(history) work compaction\n * exists to remove. Host-supplied ContextCompactor decisions use this same commit path.\n * Summaries exceeding BoundedText are rejected before append, never truncated.\n * `summary` is present exactly for `summarize` records; the projection\n * treats a summarize record without one as invalid and ignores it fail-safe.\n */\nexport class CompactionCreated extends Schema.TaggedClass<CompactionCreated>(\n \"@effect-agent/thread/CompactionCreated\",\n)(\"CompactionCreated\", {\n runId: RunId,\n turn: TurnNumber,\n kind: Schema.Literals([\"clear-tool-results\", \"summarize\", \"rollover\"]),\n coversThrough: CanonicalSequence,\n summary: Schema.optionalKey(BoundedText),\n handoff: Schema.optionalKey(ContextHandoff),\n}) {}\n\nexport class RunFailed extends Schema.TaggedClass<RunFailed>(\"@effect-agent/thread/RunFailed\")(\n \"RunFailed\",\n {\n runId: RunId,\n failure: PersistedJson,\n },\n) {}\n\nconst RunCompletedFields = Schema.Struct({\n runId: RunId,\n output: PersistedJson,\n /** Integrity of validated terminal values, independent of future application codecs. */\n /** Application disposition captured with an ordinary completion. */\n runDisposition: Schema.optionalKey(PersistedJson),\n /** Honest soft-landing marker, present exactly when `exhausted` is present. */\n finishReason: Schema.optionalKey(Schema.Literal(\"budget-exhausted\")),\n /** Budget dimension paired with `finishReason` on a soft landing. */\n exhausted: Schema.optionalKey(ExhaustedLimit),\n}).check(\n Schema.makeFilter(\n (completed) =>\n (completed.finishReason === undefined) === (completed.exhausted === undefined) &&\n (completed.runDisposition === undefined || completed.finishReason === undefined),\n { title: \"Run completion metadata matches its terminal family\" },\n ),\n);\n\nexport class RunCompleted extends Schema.TaggedClass<RunCompleted>(\n \"@effect-agent/thread/RunCompleted\",\n)(\"RunCompleted\", RunCompletedFields) {}\n\nexport class RepairAnnotated extends Schema.TaggedClass<RepairAnnotated>(\n \"@effect-agent/thread/RepairAnnotated\",\n)(\"RepairAnnotated\", {\n reason: BoundedText,\n details: PersistedJson,\n}) {}\n\n/** Terminal outcome family for one accepted Submission (DUR-002). */\nexport const SettlementOutcome = Schema.Literals([\"completed\", \"failed\", \"aborted\"]);\n\nexport type SettlementOutcome = typeof SettlementOutcome.Type;\n\n/**\n * A durable abort command made canonical before the active worker is interrupted (DUR-012).\n * Repeating the same abort command is idempotent; abort never rewrites a prior terminal outcome.\n */\nexport class AbortRequested extends Schema.TaggedClass<AbortRequested>(\n \"@effect-agent/thread/AbortRequested\",\n)(\"AbortRequested\", {\n submissionId: SubmissionId,\n author: BoundedName,\n reason: BoundedText,\n}) {}\n\n/**\n * The single canonical settlement record owed to one accepted Submission (DUR-002, DUR-011).\n * Canonical history is the outcome authority: the ledger row is finalized from this record and\n * never the other way around (DUR-015).\n */\nconst RawSubmissionSettled = Schema.Struct({\n submissionId: SubmissionId,\n settlementId: SettlementId,\n receiptId: ReceiptId,\n outcome: SettlementOutcome,\n runId: Schema.optionalKey(RunId),\n /** Number of retained owning facts through this terminal commit, excluding mutable progress. */\n historyRecordCount: Schema.optionalKey(Schema.Natural),\n result: Schema.optionalKey(PersistedJson),\n /**\n * Application-defined, Schema-encoded disposition for an ordinary completed\n * Run. Absent for budget exhaustion and every non-completed or run-less\n * settlement; consumers decode it with the application definition's Schema.\n */\n runDisposition: Schema.optionalKey(PersistedJson),\n /**\n * Present only when a `completed` Run settled through the final-answer\n * exhaustion resolution (RUN-011, RUN-018): the durable log must be able to\n * distinguish honest-exhaustion completion from ordinary completion without\n * the live event stream. Absent for every ordinary settlement, keeping\n * existing histories and goldens byte-stable (additive, schemaVersion 1).\n */\n finishReason: Schema.optionalKey(Schema.Literal(\"budget-exhausted\")),\n /**\n * The dimension that bound a budget-exhausted completion (RUN-011,\n * RUN-025), carried verbatim from the live `RunCompleted` event so\n * consumers never reconstruct it from message text. Valid only alongside\n * `finishReason: \"budget-exhausted\"`; absent on histories persisted before\n * the dimension became durable (additive, schemaVersion 1).\n */\n exhausted: Schema.optionalKey(ExhaustedLimit),\n /**\n * The typed `AgentPolicyError.limit` of a `failed` hard-rail settlement\n * (RUN-011): which finite policy dimension failed the Run, preserved\n * alongside the bounded `{errorTag, message}` failure projection in\n * `result`. Absent for every non-policy failure and on histories persisted\n * before the limit became durable (additive, schemaVersion 1).\n */\n policyLimit: Schema.optionalKey(PolicyLimit),\n /** Canonical aggregate of all priced model calls made by this Run. */\n usageSummary: Schema.optionalKey(RunUsageSummary),\n /** Calls included in usageSummary but not in any ModelResponseRecorded, retained on failure. */\n uncommittedModelUsage: Schema.optionalKey(Schema.Array(ModelCallUsage)),\n});\n\nconst isPolicyFailureProjection = Schema.is(\n Schema.Struct({ errorTag: Schema.Literal(\"AgentPolicyError\") }),\n);\n\nconst decodeSettlementFailureDiagnostic = Schema.decodeUnknownOption(SettlementFailureDiagnostic, {\n onExcessProperty: \"error\",\n});\n\nconst hasValidSettlementFamily = (settled: typeof RawSubmissionSettled.Type): boolean =>\n (settled.finishReason === undefined || settled.outcome === \"completed\") &&\n (settled.finishReason === undefined) === (settled.exhausted === undefined) &&\n (settled.usageSummary === undefined || settled.runId !== undefined) &&\n (settled.uncommittedModelUsage === undefined ||\n (settled.runId !== undefined && settled.usageSummary !== undefined)) &&\n (settled.runDisposition === undefined ||\n (settled.outcome === \"completed\" &&\n settled.finishReason === undefined &&\n settled.runId !== undefined &&\n settled.result !== undefined)) &&\n (settled.outcome !== \"failed\" ||\n Option.isSome(decodeSettlementFailureDiagnostic(settled.result))) &&\n (settled.outcome !== \"aborted\" || settled.result === undefined) &&\n (settled.policyLimit === undefined ||\n (settled.outcome === \"failed\" && isPolicyFailureProjection(settled.result)));\n\nconst SubmissionSettledFields = RawSubmissionSettled.check(\n Schema.makeFilter(hasValidSettlementFamily, {\n title:\n \"failed settlements require a bounded diagnostic; aborted settlements carry no result; budget metadata must match its settlement family\",\n }),\n);\n\nexport class SubmissionSettled extends Schema.TaggedClass<SubmissionSettled>(\n \"@effect-agent/thread/SubmissionSettled\",\n)(\"SubmissionSettled\", SubmissionSettledFields) {}\n\n/** Canonical completed settlement; joined completion may legitimately carry no independent result. */\nexport type CompletedSubmissionSettled = SubmissionSettled & {\n readonly outcome: \"completed\";\n};\n\n/** Canonical failed settlement; its bounded diagnostic is required and typed. */\nexport type FailedSubmissionSettled = SubmissionSettled & {\n readonly outcome: \"failed\";\n readonly result: SettlementFailureDiagnostic;\n};\n\n/** Canonical aborted settlement; abort records intent rather than fabricating a terminal result. */\nexport type AbortedSubmissionSettled = SubmissionSettled & {\n readonly outcome: \"aborted\";\n readonly result?: never;\n};\n\nexport type SubmissionSettledRecord =\n | CompletedSubmissionSettled\n | FailedSubmissionSettled\n | AbortedSubmissionSettled;\n\n/**\n * Canonical-boundary view of `SubmissionSettled`: `finishReason` is valid\n * only on a `completed` outcome, `exhausted` only alongside\n * `finishReason: \"budget-exhausted\"`, every `failed` outcome requires the exact bounded\n * `SettlementFailureDiagnostic`, aborted outcomes carry no result, and `policyLimit` only occurs\n * on a `failed` outcome whose diagnostic carries the `AgentPolicyError` tag. `runDisposition`\n * occurs only on an ordinary completed settlement with a Run —\n * so a malformed persisted combination such as\n * `{ outcome: \"failed\", finishReason: \"budget-exhausted\" }` or a\n * `policyLimit` contradicting `result.errorTag` fails closed at decode\n * instead of becoming trusted audit history (STORE-006, RUN-011).\n */\nexport const SubmissionSettledRecord = SubmissionSettled.pipe(\n Schema.refine(\n (settled): settled is SubmissionSettledRecord => hasValidSettlementFamily(settled),\n {\n expected:\n \"failed settlements require a bounded diagnostic, aborted settlements carry no result, finishReason only occurs on completed settlements, exhausted only occurs with finishReason budget-exhausted, runDisposition only occurs on an ordinary completed settlement with a Run result, and policyLimit only occurs on a failed AgentPolicyError settlement\",\n },\n ),\n);\n\n/**\n * PARENT-log record of one durable child establishment request:\n * the exact parent Tool Call, delegation and target identity, the digests that pin the child's\n * Binding/input/grant, the fenced budget reservation, and the INTENDED child identity derived\n * deterministically from the parent Run and Tool Call pair (D4). `childInput` carries the\n * prepared child input in encoded form (D3) so recovery can complete child admission from this\n * record alone — no live delegation handler is required. `childPrincipal`/`childIdempotencyKey`\n * carry the ledger admission scope with the ledger's exact bounds; the layering keeps their\n * branded Schemas in the ledger port.\n */\nexport class SubagentRequested extends Schema.TaggedClass<SubagentRequested>(\n \"@effect-agent/thread/SubagentRequested\",\n)(\"SubagentRequested\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n delegationId: DelegationId,\n targetAgentId: AgentId,\n targetDigests: DefinitionDigests,\n childInput: PersistedJson,\n childInputDigest: Digest,\n grantDigest: Digest,\n reservationId: BoundedName,\n reservationDigest: Digest,\n childThreadId: ThreadId,\n childPrincipal: BoundedName,\n childIdempotencyKey: BoundedName,\n /** Effective invocation bound, already clamped to the delegation and child Definition. */\n toolCallAllowance: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n policy: Schema.optionalKey(Schema.toCodecJson(AgentPolicy)),\n budget: Schema.optionalKey(SubagentBudgetReservation),\n grant: Schema.optionalKey(SubagentGrant),\n depth: Schema.optionalKey(DelegationDepth),\n}) {}\n\n/**\n * PARENT-log record that the intended child exists as accepted work:\n * the full established child identity. It is appended only after the child Receipt\n * exists — SUB-017 holds by construction because `childReceiptId` is a required field.\n */\nexport class SubagentStarted extends Schema.TaggedClass<SubagentStarted>(\n \"@effect-agent/thread/SubagentStarted\",\n)(\"SubagentStarted\", {\n runId: RunId,\n toolCallId: ToolCallId,\n childThreadId: ThreadId,\n childSubmissionId: SubmissionId,\n childReceiptId: ReceiptId,\n childRunId: RunId,\n}) {}\n\n/**\n * PARENT-log record of one verified child settlement join:\n * the child's canonical Settlement identity and outcome, the child usage summary, and the FINAL\n * consumed/released accounting decision for the reservation. It commits in ONE atomic batch with\n * the parent `ToolCallSettled` record (SUB-019); `beginChildBudgetRelease` replays\n * `finalAccounting` from this record, so canonical history authorizes the release (DUR-015).\n */\nexport class SubagentJoined extends Schema.TaggedClass<SubagentJoined>(\n \"@effect-agent/thread/SubagentJoined\",\n)(\"SubagentJoined\", {\n runId: RunId,\n toolCallId: ToolCallId,\n childSubmissionId: SubmissionId,\n childSettlementId: SettlementId,\n childOutcome: SettlementOutcome,\n usageSummary: PersistedJson,\n usage: Schema.optionalKey(RunTotals),\n delegatedUsage: Schema.optionalKey(RunTotals),\n reservationId: BoundedName,\n finalAccounting: PersistedJson,\n}) {}\n\n/**\n * CHILD-log immutable lineage: the Parent Link plus the digests that pin\n * the child's definition, input, and authority grant. It is the first record after the child's\n * `ThreadCreated` (its own single-record batch, so the generic `thread-created:{cid}`\n * batch identity is never contradicted) and the join path verifies it fail-closed — a fabricated\n * child or parent identity fails Parent Link verification (SUB-004, D10).\n */\nexport class SubagentLineageRecorded extends Schema.TaggedClass<SubagentLineageRecorded>(\n \"@effect-agent/thread/SubagentLineageRecorded\",\n)(\"SubagentLineageRecorded\", {\n parentLink: SubagentParentLink,\n parentSubmissionId: SubmissionId,\n childDefinitionDigests: DefinitionDigests,\n childInputDigest: Digest,\n grantDigest: Digest,\n /** Copied from the canonical request before readiness; restored for every child Attempt. */\n toolCallAllowance: SubagentRequested.fields.toolCallAllowance,\n policy: SubagentRequested.fields.policy,\n budget: SubagentRequested.fields.budget,\n grant: SubagentRequested.fields.grant,\n}) {}\n\nexport const WorkerReportingIntent = Schema.Struct({\n /** Absent only in historical custom-report origins; these remain readable as evidence. */\n mode: Schema.optionalKey(Schema.Literal(\"standard\")),\n sourceDigests: DefinitionDigests,\n /** Historical custom destination evidence. New worker origins never write this field. */\n destinationDelegationId: Schema.optionalKey(DelegationId),\n /** Frozen by the sender before acceptance. Standard emission never reads the source runtime. */\n returnAddress: Schema.optionalKey(\n Schema.Struct({\n input: PersistedJson,\n principal: Principal,\n policy: Schema.toCodecJson(AgentPolicy),\n depth: Schema.Natural,\n grant: Schema.optionalKey(SubagentGrant),\n /** Encoded to bound recursive worker origins at the admission boundary. */\n workerAdmission: Schema.optionalKey(PersistedJson),\n }),\n ),\n}).check(\n Schema.makeFilter((value) => (value.mode === \"standard\") === (value.returnAddress !== undefined)),\n);\n\n/** Exact successful predecessor evidence; a locator alone grants no authority. */\nexport const WorkerContinuation = Schema.Struct({\n worker: WorkerRef,\n receipt: Receipt,\n settlementId: SettlementId,\n}).check(Schema.makeFilter((value) => value.worker.threadId === value.receipt.threadId));\n\nexport type WorkerContinuation = typeof WorkerContinuation.Type;\n\n/** Immutable worker Thread origin. Each input has its own digest and parameters separately. */\nexport const WorkerOrigin = Schema.Struct({\n worker: WorkerRef,\n source: WorkerSource,\n /** A new assignment may continue this completed, immutable predecessor. */\n continuationOf: Schema.optionalKey(WorkerContinuation),\n /** Frozen funding owner; worker-run renews only for a new native Run. */\n budgetScope: WorkerBudgetScope,\n /** Frozen at worker creation; older origins remain reusable. */\n lifecycle: Schema.optionalKey(Schema.Literal(\"assignment\")),\n targetDigests: DefinitionDigests,\n policy: Schema.toCodecJson(AgentPolicy),\n budget: SubagentBudgetReservation,\n grant: SubagentGrant,\n depth: DelegationDepth,\n toolCallAllowance: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n firstMessageId: IdempotencyKey,\n createdAtMillis: Schema.Natural,\n expiresAtMillis: Schema.Natural,\n /** Exact source registration owns projection; absence means reporting was not declared. */\n reporting: Schema.optionalKey(WorkerReportingIntent),\n}).check(Schema.makeFilter((value) => value.expiresAtMillis > value.createdAtMillis));\n\nexport type WorkerOrigin = typeof WorkerOrigin.Type;\n\n/** Frozen per-input metadata; it grants no attached-child or parent-abort semantics. */\nexport const WorkerAdmission = Schema.Struct({\n origin: WorkerOrigin,\n /** Run executing this handoff, independently of immutable lineage and subtree funding. */\n executionRunId: Schema.NullOr(RunId),\n messageId: IdempotencyKey,\n parameters: PersistedJson,\n createdAtMillis: Schema.Natural,\n /** Host-bound source input whose subtree funds this input; never chosen by a model. */\n sourceSubmissionId: Schema.optionalKey(SubmissionId),\n /** Enables routed receipt lookup when the delivery is owned by a reporting child. */\n deliveryPrincipal: Schema.optionalKey(Principal),\n /** Proven framework updates use a separate bounded input-capacity partition. */\n reportKind: Schema.optionalKey(Schema.Literal(\"update\")),\n});\n\nexport type WorkerAdmission = typeof WorkerAdmission.Type;\n\n/** Owner command retained before the destination inbox is sealed. */\nexport class WorkerStopRequested extends Schema.TaggedClass<WorkerStopRequested>()(\n \"WorkerStopRequested\",\n {\n command: WorkerStop,\n principal: Principal,\n sourceSubmissionId: Schema.optionalKey(SubmissionId),\n },\n) {}\n\n/** The named canonical obligation closed only after its owning state durably completes. */\nexport class WorkHandoffCompleted extends Schema.TaggedClass<WorkHandoffCompleted>()(\n \"WorkHandoffCompleted\",\n { preparationId: RecordId, ownerId: Schema.NonEmptyString.check(Schema.isMaxLength(4096)) },\n) {}\n\n/** Source-log capacity reservation, retained independently of the source Run's settlement. */\nexport class WorkerInputRequested extends Schema.TaggedClass<WorkerInputRequested>()(\n \"WorkerInputRequested\",\n { admission: WorkerAdmission, inputDigest: Digest },\n) {}\n\n/** Child-log origin, reconstructed from a retained delivery before the child becomes ready. */\nexport class WorkerOriginRecorded extends Schema.TaggedClass<WorkerOriginRecorded>()(\n \"WorkerOriginRecorded\",\n { origin: WorkerOrigin },\n) {}\n\n/** Canonical child completion acknowledgement releases only this input's active capacity. */\nexport class WorkerInputCompleted extends Schema.TaggedClass<WorkerInputCompleted>()(\n \"WorkerInputCompleted\",\n {\n messageId: IdempotencyKey,\n workerThreadId: ThreadId,\n submissionId: SubmissionId,\n receiptId: ReceiptId,\n settlementId: SettlementId,\n completedAtMillis: Schema.Natural,\n /** New acknowledgements prove that this input's external effects are resolved. */\n effectsResolved: Schema.optionalKey(Schema.Literal(true)),\n },\n) {}\n\n/**\n * Frozen report decision for one actual Run, shared by every joined Receipt. The envelope is\n * a Schema-encoded PreparedInput, validated before append and decoded again on recovery.\n * Keeping the encoded value here avoids a Records/PreparedInput schema dependency cycle.\n */\nexport class WorkerReportPrepared extends Schema.TaggedClass<WorkerReportPrepared>()(\n \"WorkerReportPrepared\",\n {\n runId: RunId,\n messageId: IdempotencyKey,\n envelope: PersistedJson,\n createdAtMillis: Schema.Natural,\n deadlineAtMillis: Schema.Natural,\n predecessor: Schema.optionalKey(IdempotencyKey),\n },\n) {}\n\n/** Accepted update and its optional frozen parent delivery are one atomic canonical fact. */\nexport class AgentUpdateEmitted extends Schema.TaggedClass<AgentUpdateEmitted>()(\n \"AgentUpdateEmitted\",\n {\n update: Update,\n definitions: DefinitionDigests,\n delivery: Schema.optionalKey(\n Schema.Struct({\n messageId: IdempotencyKey,\n envelope: PersistedJson,\n createdAtMillis: Schema.Natural,\n deadlineAtMillis: Schema.Natural,\n predecessor: Schema.optionalKey(IdempotencyKey),\n }),\n ),\n },\n) {}\n\n/** Permanent bounded report refusal. Application errors and raw Run dispositions stay private. */\nexport class WorkerReportRefused extends Schema.TaggedClass<WorkerReportRefused>()(\n \"WorkerReportRefused\",\n {\n runId: RunId,\n messageId: IdempotencyKey,\n reason: Schema.Literals([\n \"filtered\",\n \"declaration-unavailable\",\n \"destination\",\n \"projection\",\n \"input\",\n \"preparation\",\n \"timeout\",\n \"defect\",\n \"expired\",\n \"denied\",\n \"capacity\",\n ]),\n },\n) {}\n\n/** Frozen source proof of peer provenance, readable through routed canonical storage. */\nexport class PeerMessagePrepared extends Schema.TaggedClass<PeerMessagePrepared>()(\n \"PeerMessagePrepared\",\n {\n messageId: IdempotencyKey,\n source: WorkerSource,\n sourcePrincipal: Principal,\n operation: Schema.Literals([\"send\", \"reply\"]),\n deadlineAtMillis: Schema.Int.check(Schema.isGreaterThan(0)),\n encodedEnvelope: PersistedJson,\n },\n) {}\n\n/**\n * One disjoint subtree slice shared by attached and background children of a source input.\n * The source keeps its own execution ceiling; descendants spend only the remaining allocation.\n * Reservations include future descendant slots and never refund, including after interruption.\n * resultBytes reserves the terminal/projection result, not cumulative Tool output bytes.\n */\nexport class SubtreeBudgetReserved extends Schema.TaggedClass<SubtreeBudgetReserved>()(\n \"SubtreeBudgetReserved\",\n {\n reservationId: BoundedName,\n /** Run executing this reservation; null for host-owned follow-ups. Grants no authority. */\n executionRunId: Schema.NullOr(RunId),\n sourceSubmissionId: Schema.optionalKey(SubmissionId),\n childThreadId: ThreadId,\n lifetime: Schema.Literals([\"attached\", \"background\"]),\n depth: DelegationDepth,\n policy: Schema.toCodecJson(AgentPolicy),\n grant: SubagentGrant,\n budget: SubagentBudgetReservation,\n },\n) {}\n\n/** Fact identity; active-only references resolve inside their Run checkpoint. */\nexport const EvidenceReference = Schema.Struct({ recordId: RecordId });\nexport type EvidenceReference = typeof EvidenceReference.Type;\n\n/**\n * Receipt-free factual closure. The receiver's irreversible inbox seal precedes its exact-key\n * NotAdmitted observation; a refusal or an absent lookup alone cannot close reserved work.\n * Invocation and allocation charges remain with the original funding Run.\n */\nexport class WorkerInputRefused extends Schema.TaggedClass<WorkerInputRefused>()(\n \"WorkerInputRefused\",\n Schema.Struct({\n messageId: IdempotencyKey,\n workerThreadId: ThreadId,\n reservation: EvidenceReference,\n stop: EvidenceReference,\n deliveryVersion: Schema.Int.check(Schema.isGreaterThan(0)),\n envelopeDigest: Digest,\n receiver: Schema.Struct({\n threadId: ThreadId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n inputDigest: Digest,\n stopped: Schema.Literal(true),\n resolution: Schema.Literal(\"NotAdmitted\"),\n }),\n }).check(Schema.makeFilter((value) => value.receiver.threadId === value.workerThreadId)),\n) {}\n\nexport const MAX_RUN_CONTINUATION_BYTES = 8_192;\n/** Incremental record JSON per Turn, including progress and the first Turn's initial context. */\nexport const MAX_TURN_CANONICAL_BYTES = MAX_CANONICAL_RECORD_BYTES;\n/** Room retained for a bounded terminal failure and its atomic progress publication. */\nexport const RUN_TERMINAL_RESERVE_BYTES = 256 * 1024;\n/** Bounded closing facts remain publishable even after dispatch capacity is exhausted. */\nexport const MAX_RUN_TERMINAL_BYTES = 2 * MAX_CANONICAL_RECORD_BYTES + RUN_TERMINAL_RESERVE_BYTES;\nexport const RUN_TERMINAL_RESERVE_RECORDS = 4;\nexport const MAX_RUN_EVIDENCE_RECORDS = 16_384;\nexport const MAX_RUN_EVIDENCE_BYTES = 32 * 1024 * 1024;\nexport const MAX_RUN_RECOVERY_SUFFIX_RECORDS = 64;\nexport const MAX_RUN_RECOVERY_SUFFIX_BYTES = 2 * 1024 * 1024;\nexport const MAX_RUN_TOOL_CALL_IDENTITIES = 4_096;\n\nexport const ContextEvidenceReference = Schema.Struct({\n ...EvidenceReference.fields,\n sequence: CanonicalSequence,\n});\n\nexport class RunContextRecorded extends Schema.TaggedClass<RunContextRecorded>()(\n \"RunContextRecorded\",\n Schema.Struct({\n version: Schema.Literal(1),\n runId: RunId,\n /** Only evaluated instructions and this Run's input; prior history remains in its facts. */\n runScopedInput: PersistedJson,\n /** Inclusive range; historyThrough + 1 denotes an empty range. */\n historyFrom: CanonicalSequence.check(Schema.isGreaterThan(0)),\n /** Fixed prior-history boundary, immediately before the original accepted input. */\n historyThrough: CanonicalSequence,\n /** Facts below historyFrom still needed after summarize or rollover coverage. */\n retained: Schema.Array(ContextEvidenceReference).check(Schema.isMaxLength(4_096)),\n /** Pins the projected prior Prompt, not a second copy or a per-record manifest. */\n historyDigest: Digest,\n priorHistoryLength: Schema.Natural,\n contextWindowId: Schema.optionalKey(BoundedName),\n }).check(\n Schema.makeFilter(\n (context) =>\n context.historyFrom <= context.historyThrough + 1 &&\n context.retained.every(\n (ref, index) =>\n ref.sequence > (context.retained[index - 1]?.sequence ?? 0) &&\n ref.sequence < context.historyFrom,\n ),\n { title: \"Saved context retains an ordered prefix below its original history range\" },\n ),\n ),\n) {}\n\n/** Accumulated charges; replacement Attempts never replenish or charge these again. */\nexport const ContinuationAccounting = Schema.Struct({\n ...RunPolicyUsage.fields,\n modelRestarts: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 2 })),\n modelCalls: Schema.Natural,\n unobservedModelCalls: Schema.Natural,\n inputTokens: Schema.Natural,\n outputTokens: Schema.Natural,\n lastInputTokens: Schema.Natural,\n lastOutputTokens: Schema.Natural,\n costMicrousd: Schema.Natural,\n /** The last complete operation batch whose declaration-ordered failure streak was charged. */\n accountedToolTurn: Schema.Natural,\n});\n\nexport type ContinuationAccounting = typeof ContinuationAccounting.Type;\n\n/** Semantic execution boundaries, never engine stacks, fibers, or program counters. */\nexport const RunPosition = Schema.Literals([\n \"starting\",\n \"awaiting-model\",\n \"processing-operations\",\n \"waiting-approval\",\n \"waiting-dependency\",\n \"unknown\",\n \"settling\",\n \"settled\",\n]);\n\n/**\n * Current interpreter progress, replaced atomically with lastFact under the Thread fence.\n * lastFact is the exact accounted frontier of the same commit. References resolve within this\n * Thread's history or its authoritative active checkpoint. Results, operation declarations,\n * approvals and delivery obligations remain canonical; evaluated context and validated completion\n * belong to active state. Neither the checkpoint nor its revision grants execution authority.\n * Retired intermediate revisions are not historical verification evidence.\n */\nexport class RunContinuation extends Schema.TaggedClass<RunContinuation>()(\n \"RunContinuation\",\n Schema.Struct({\n version: Schema.Literal(1),\n runId: RunId,\n submissionId: SubmissionId,\n revision: Schema.Natural.check(Schema.isGreaterThan(0)),\n /** Number of this Run's non-continuation facts accounted for at the frontier. */\n recordCount: Schema.Natural.check(\n Schema.isLessThanOrEqualTo(MAX_RUN_EVIDENCE_RECORDS + RUN_TERMINAL_RESERVE_RECORDS),\n ),\n /** Cumulative committed owning fact bytes, excluding progress; deletion never refunds them. */\n recordBytes: Schema.Natural.check(\n Schema.isLessThanOrEqualTo(MAX_RUN_EVIDENCE_BYTES + MAX_RUN_TERMINAL_BYTES),\n ),\n /** Logical Turn whose incremental durable commit bytes are currently being charged. */\n turn: Schema.Natural,\n turnBytes: Schema.Natural.check(\n Schema.isLessThanOrEqualTo(MAX_TURN_CANONICAL_BYTES + MAX_RUN_TERMINAL_BYTES),\n ),\n /** Closing facts consume the terminal reserve, rather than reserving it again. */\n terminalBytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_RUN_TERMINAL_BYTES)),\n terminalRecords: Schema.Natural.check(Schema.isLessThanOrEqualTo(RUN_TERMINAL_RESERVE_RECORDS)),\n /** Conservative room for terminal usage grouping; derived only from canonical model usage. */\n terminalUsageBytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_RUN_EVIDENCE_BYTES)),\n originalInput: EvidenceReference,\n savedContext: Schema.optionalKey(EvidenceReference),\n latestResponse: Schema.optionalKey(EvidenceReference),\n terminal: Schema.optionalKey(EvidenceReference),\n lastFact: EvidenceReference,\n position: RunPosition,\n accounting: ContinuationAccounting,\n }),\n) {}\n\n/** Bump only when the meaning of an existing record changes, independently of SQL layout. */\nexport const CURRENT_RECORD_VERSION = 6;\nexport const CURRENT_RECORD_FORMAT = \"effect-agent/thread@6\";\n\n/** Durable fact and execution-command schemas. Unsupported controls fail before execution. */\nexport const KnownRecordPayload = Schema.Union([\n ThreadCreated,\n UserInputRecorded,\n RunStartedRecord,\n RunDurationExhausted,\n RunPolicyUsageReserved,\n ModelCompleted,\n ModelResponseRecorded,\n ToolCallSettled,\n ToolCallUnknown,\n ToolCallResolved,\n ToolStepSettled,\n ToolApprovalRequested,\n ToolApprovalDecided,\n ModelResponseInterrupted,\n ModelCallAborted,\n CompactionCreated,\n RunFailed,\n RunCompleted,\n AbortRequested,\n SubmissionSettledRecord,\n SubagentRequested,\n SubagentStarted,\n SubagentJoined,\n SubagentLineageRecorded,\n WorkerInputRequested,\n WorkerStopRequested,\n WorkHandoffCompleted,\n WorkerOriginRecorded,\n WorkerInputCompleted,\n WorkerInputRefused,\n WorkerReportPrepared,\n AgentUpdateEmitted,\n WorkerReportRefused,\n PeerMessagePrepared,\n SubtreeBudgetReserved,\n RepairAnnotated,\n RunContextRecorded,\n RunContinuation,\n]);\n\n/** This format accepts only understood facts; unknown control cannot grant permission. */\nexport const CanonicalRecordPayload = KnownRecordPayload;\n\nexport type CanonicalRecordPayload = typeof CanonicalRecordPayload.Type;\n\n/**\n * Versioned durable fact. Retained history acquires Thread ordering at its atomic commit;\n * active operational facts keep their identities without a canonical sequence.\n */\nexport class RecordEnvelope extends Schema.Class<RecordEnvelope>(\n \"@effect-agent/thread/RecordEnvelope\",\n)({\n recordId: RecordId,\n family: Schema.Literal(\"thread\"),\n schemaVersion: Schema.Literal(1),\n createdAt: Schema.DateTimeUtcFromString,\n deploymentId: DeploymentId,\n payload: CanonicalRecordPayload,\n}) {}\n\n/** Backward-compatible domain name for a canonical record. */\nexport const CanonicalRecord = RecordEnvelope;\nexport type CanonicalRecord = RecordEnvelope;\n\n/** One non-empty, bounded, idempotent atomic append unit. */\nexport class CanonicalBatch extends Schema.Class<CanonicalBatch>(\n \"@effect-agent/thread/CanonicalBatch\",\n)({\n batchId: BatchId,\n producerId: ProducerId,\n records: Schema.NonEmptyArray(RecordEnvelope).check(Schema.isMaxLength(256)),\n}) {}\n\n/**\n * A committed record with its Thread ordering and opaque resumable observation cursor.\n */\nexport class CanonicalRecordEnvelope extends Schema.Class<CanonicalRecordEnvelope>(\n \"@effect-agent/thread/CanonicalRecordEnvelope\",\n)({\n threadId: ThreadId,\n batchId: BatchId,\n sequence: CanonicalSequence,\n offset: ObservationOffset,\n record: RecordEnvelope,\n}) {}\n\n/** Read-only history of validated facts. Original inputs establish Run view boundaries. */\nexport const PromptRecordPayload = Schema.TaggedUnion({\n UserInputRecorded: {\n runId: UserInputRecorded.fields.runId,\n kind: UserInputRecorded.fields.kind,\n submissionId: UserInputRecorded.fields.submissionId,\n },\n ModelCompleted: {\n runId: RunId,\n history: Schema.optionalKey(HistoryPrompt),\n },\n ModelResponseRecorded: {\n runId: RunId,\n turn: TurnNumber,\n messages: HistoryPrompt,\n runScopedPrefixLength: ModelResponseRecorded.fields.runScopedPrefixLength,\n },\n ToolCallSettled: {\n runId: RunId,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n result: Schema.Json,\n isFailure: Schema.Boolean,\n },\n CompactionCreated: CompactionCreated.fields,\n RunCompleted: { runId: RunId },\n RunFailed: { runId: RunId },\n SubmissionSettled: {\n runId: Schema.optionalKey(RunId),\n submissionId: SubmissionId,\n outcome: SettlementOutcome,\n },\n});\n\n/** Native selections and the projection decoder share this single list of supported facts. */\nexport const PROMPT_EVIDENCE_TAGS: ReadonlyArray<keyof typeof PromptRecordPayload.cases> =\n Struct.keys(PromptRecordPayload.cases);\n\nexport const PromptRecord = Schema.Struct({ recordId: RecordId, payload: PromptRecordPayload });\nexport type PromptRecord = typeof PromptRecord.Type;\n\n/** Not integrity evidence: omitted canonical wire must be read through the full record port. */\nexport const PromptRecordEnvelope = Schema.Struct({\n threadId: ThreadId,\n sequence: CanonicalSequence,\n record: PromptRecord,\n});\n\nexport type PromptRecordEnvelope = typeof PromptRecordEnvelope.Type;\n\nexport const CURRENT_CANONICAL_SCHEMA_VERSION = 1 as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,SAAS,YAAY,MAAuC;CAC1D,QAAQ,KAAK,MAAb;EACE,KAAK,QACH,OAAO,OAAO,SAAS,IAAI;EAC7B,KAAK,aACH,OAAO,OAAO,cAAc,IAAI;EAClC,KAAK,QACH,OAAO,OAAO,SAAS,IAAI;EAC7B,KAAK,aACH,OAAO,OAAO,aAAa;GAAE,GAAG;GAAM,kBAAkB,KAAK,oBAAoB;EAAM,CAAC;EAC1F,KAAK,eACH,OAAO,OAAO,eAAe;GAAE,GAAG;GAAM,kBAAkB,KAAK,oBAAoB;EAAM,CAAC;EAC5F,KAAK,yBACH,OAAO,OAAO,wBAAwB,IAAI;EAC5C,KAAK,0BACH,OAAO,OAAO,yBAAyB,IAAI;CAC/C;AACF;AAEA,MAAM,kBAAkB,YAAmD;CACzE,QAAQ,QAAQ,MAAhB;EACE,KAAK,UACH,OAAO,OAAO,YAAY,UAAU,OAAO;EAC7C,KAAK,QACH,OAAO,OAAO,YAAY,QAAQ;GAChC,GAAG;GACH,SACE,OAAO,QAAQ,YAAY,WACvB,CAAC,OAAO,SAAS,EAAE,MAAM,QAAQ,QAAQ,CAAC,CA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,MAAM,kBAAkB,OAAO;EAC/B,cAAc,kBAAkB,OAAO;CACzC;CACA,gBAAgB;EACd,OAAO;EACP,SAAS,OAAO,YAAY,aAAa;CAC3C;CACA,uBAAuB;EACrB,OAAO;EACP,MAAM;EACN,UAAU;EACV,uBAAuB,sBAAsB,OAAO;CACtD;CACA,iBAAiB;EACf,OAAO;EACP,YAAY;EACZ,UAAU;EACV,QAAQ,OAAO;EACf,WAAW,OAAO;CACpB;CACA,mBAAmB,kBAAkB;CACrC,cAAc,EAAE,OAAO,MAAM;CAC7B,WAAW,EAAE,OAAO,MAAM;CAC1B,mBAAmB;EACjB,OAAO,OAAO,YAAY,KAAK;EAC/B,cAAc;EACd,SAAS;CACX;AACF,CAAC;;AAGD,MAAa,uBACX,OAAO,KAAK,oBAAoB,KAAK;AAEvC,MAAa,eAAe,OAAO,OAAO;CAAE,UAAU;CAAU,SAAS;AAAoB,CAAC;;AAI9F,MAAa,uBAAuB,OAAO,OAAO;CAChD,UAAU;CACV,UAAU;CACV,QAAQ;AACV,CAAC;AAID,MAAa,mCAAmC"}
1
+ {"version":3,"file":"Records-DzL4Kbtw.mjs","names":[],"sources":["../src/durable/internal/history-prompt.ts","../src/durable/Records.ts"],"sourcesContent":["import { Effect, Schema, SchemaParser, SchemaTransformation } from \"effect\";\nimport { Prompt } from \"effect/ai\";\n\nfunction restorePart(part: Prompt.UserMessagePartEncoded): Prompt.UserMessagePart;\nfunction restorePart(part: Prompt.AssistantMessagePartEncoded): Prompt.AssistantMessagePart;\nfunction restorePart(part: Prompt.ToolMessagePartEncoded): Prompt.ToolMessagePart;\nfunction restorePart(part: Prompt.PartEncoded): Prompt.Part {\n switch (part.type) {\n case \"text\":\n return Prompt.textPart(part);\n case \"reasoning\":\n return Prompt.reasoningPart(part);\n case \"file\":\n return Prompt.filePart(part);\n case \"tool-call\":\n return Prompt.toolCallPart({ ...part, providerExecuted: part.providerExecuted ?? false });\n case \"tool-result\":\n return Prompt.toolResultPart({ ...part, providerExecuted: part.providerExecuted ?? false });\n case \"tool-approval-request\":\n return Prompt.toolApprovalRequestPart(part);\n case \"tool-approval-response\":\n return Prompt.toolApprovalResponsePart(part);\n }\n}\n\nconst restoreMessage = (message: Prompt.MessageEncoded): Prompt.Message => {\n switch (message.role) {\n case \"system\":\n return Prompt.makeMessage(\"system\", message);\n case \"user\":\n return Prompt.makeMessage(\"user\", {\n ...message,\n content:\n typeof message.content === \"string\"\n ? [Prompt.textPart({ text: message.content })]\n : message.content.map((part) => restorePart(part)),\n });\n case \"assistant\":\n return Prompt.makeMessage(\"assistant\", {\n ...message,\n content:\n typeof message.content === \"string\"\n ? [Prompt.textPart({ text: message.content })]\n : message.content.map((part) => restorePart(part)),\n });\n case \"tool\":\n return Prompt.makeMessage(\"tool\", {\n ...message,\n content: message.content.map((part) => restorePart(part)),\n });\n }\n};\n\n/**\n * Validate the upstream encoded history once, then restore native values with its constructors.\n * The canonical codec remains authoritative at append, import, recovery and explicit verification.\n */\nexport const HistoryPrompt = Schema.toEncoded(Prompt.Prompt).pipe(\n Schema.decodeTo(\n Schema.toType(Prompt.Prompt),\n SchemaTransformation.transformEffect({\n decode: (input) => Effect.succeed(Prompt.fromMessages(input.content.map(restoreMessage))),\n encode: SchemaParser.encodeEffect(Prompt.Prompt),\n }),\n ),\n);\n","import { Option, Schema, Struct } from \"effect\";\nimport { Prompt } from \"effect/ai\";\n\nimport { InputMessage } from \"../capabilities/Messaging.ts\";\nimport { PolicyLimit } from \"../core/AgentError.ts\";\nimport { AgentPolicy } from \"../core/AgentPolicy.ts\";\nimport { Update } from \"../core/AgentUpdates.ts\";\nimport * as FailureDiagnostic from \"../core/FailureDiagnostic.ts\";\nimport {\n AgentId,\n ThreadId,\n DelegationId,\n ReceiptId,\n RunId,\n SettlementId,\n SubmissionId,\n ToolCallId,\n TurnId,\n} from \"../core/Identifiers.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { IdempotencyKey, Principal, Receipt } from \"../core/Receipt.ts\";\nimport { ExhaustedLimit } from \"../core/RunEvent.ts\";\nimport { RunPolicyUsage } from \"../core/RunPolicyUsage.ts\";\nimport {\n DelegationDepth,\n SubagentBudgetReservation,\n SubagentGrant,\n SubagentParentLink,\n ToolExecutionKind,\n} from \"../core/SubagentContract.ts\";\nimport { Selection, Snapshot } from \"../core/ToolExposure.ts\";\nimport { ToolParameterRejection } from \"../core/ToolResult.ts\";\nimport { ModelCallUsage, RunUsageSummary, RunTotals } from \"../core/Usage.ts\";\nimport { WorkerBudgetScope, WorkerRef, WorkerSource, WorkerStop } from \"../core/Worker.ts\";\nimport { ContextHandoff } from \"../engine/ContextWindow.ts\";\nimport { HistoryPrompt } from \"./internal/history-prompt.ts\";\n\n/** Stable identity of one canonical record. */\nexport const RecordId = Schema.NonEmptyString.pipe(Schema.brand(\"@effect-agent/thread/RecordId\"));\n\nexport type RecordId = typeof RecordId.Type;\n\n/** Stable idempotency identity of one atomic append. */\nexport const BatchId = Schema.NonEmptyString.pipe(Schema.brand(\"@effect-agent/thread/BatchId\"));\n\nexport type BatchId = typeof BatchId.Type;\n\n/** Identity of the deployment that produced a record. */\nexport const DeploymentId = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/thread/DeploymentId\"),\n);\n\nexport type DeploymentId = typeof DeploymentId.Type;\n\n/** Identity of a canonical-log producer. */\nexport const ProducerId = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/thread/ProducerId\"),\n);\n\nexport type ProducerId = typeof ProducerId.Type;\n\n/** SHA-256 digest encoded as lowercase hexadecimal text. */\nexport const Digest = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/)).pipe(\n Schema.brand(\"@effect-agent/thread/Digest\"),\n);\n\nexport type Digest = typeof Digest.Type;\n\n/** Adapter-owned resume cursor. Callers must not parse or synthesize it. */\nexport const ObservationOffset = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/thread/ObservationOffset\"),\n);\n\nexport type ObservationOffset = typeof ObservationOffset.Type;\n\n/** Gap-free position in one Thread's canonical sequence. */\nexport const CanonicalSequence = Schema.Natural.pipe(\n Schema.brand(\"@effect-agent/thread/CanonicalSequence\"),\n);\n\nexport type CanonicalSequence = typeof CanonicalSequence.Type;\n\nconst BoundedText = Schema.String.check(Schema.isMaxLength(64 * 1024));\nconst BoundedName = Schema.NonEmptyString.check(Schema.isMaxLength(256));\n\n/**\n * Private failed-Settlement evidence. The summary remains the safe public projection; diagnostic\n * and context preserve structured causal evidence for authorized operators, never model context.\n * Optional fields allow reading supported Settlements written before causal capture was available.\n */\nexport const SettlementFailureDiagnostic = FailureDiagnostic.Failure.pipe(\n Schema.annotate({\n identifier: \"@effect-agent/thread/SettlementFailureDiagnostic\",\n }),\n);\n\nexport type SettlementFailureDiagnostic = typeof SettlementFailureDiagnostic.Type;\n\n/** Positive canonical (Run-relative, Attempt-independent) Turn number. */\nconst TurnNumber = Schema.Int.check(Schema.isGreaterThan(0));\n\nexport const MAX_PERSISTED_JSON_DEPTH = 64;\nexport const MAX_PERSISTED_JSON_COLLECTION_LENGTH = 4_096;\nexport const MAX_PERSISTED_JSON_NODES = 65_536;\nexport const MAX_PERSISTED_JSON_BYTES = 1024 * 1024;\n/** Whole record wire includes bounded payloads and their canonical envelope. */\nexport const MAX_CANONICAL_RECORD_BYTES = 4 * 1024 * 1024;\n\n/**\n * Iteratively preflights an unknown value before Schema's recursive JSON validation. This is the\n * one narrow `Schema.declare` exception in the persistence model: Effect v4's `Unknown.decodeTo`\n * preserves `unknown` as the encoded type, which would leak through every nested record codec.\n * Schema.Json still owns the accepted value shape after this resource preflight succeeds.\n */\nconst isJson = Schema.is(Schema.Json);\n// No Unicode flag: match surrogate code units so astral characters take the UTF-8 path too.\nconst nonAscii = /[\\u0080-\\uFFFF]/;\n\nconst boundedJson =\n (limits: { readonly depth: number; readonly nodes: number; readonly bytes: number }) =>\n (input: unknown): input is Schema.Json => {\n const pending: Array<\n | { readonly _tag: \"visit\"; readonly value: unknown; readonly depth: number }\n | { readonly _tag: \"leave\"; readonly value: object }\n > = [{ _tag: \"visit\", value: input, depth: 0 }];\n\n // Only ancestors indicate a cycle. Shared acyclic values serialize once per occurrence,\n // so revisit them and charge every occurrence against the same resource limits.\n const ancestors = new WeakSet<object>();\n let nodes = 0;\n let textUnits = 0;\n\n try {\n while (pending.length > 0) {\n const current = pending.pop();\n\n if (current === undefined) return false;\n if (current._tag === \"leave\") {\n ancestors.delete(current.value);\n continue;\n }\n if (current.depth > limits.depth || ++nodes > limits.nodes) {\n return false;\n }\n\n const value = current.value;\n\n if (value === null || typeof value === \"boolean\") continue;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) return false;\n continue;\n }\n if (typeof value === \"string\") {\n textUnits += value.length;\n if (textUnits > limits.bytes) return false;\n continue;\n }\n if (typeof value !== \"object\" || ancestors.has(value)) return false;\n ancestors.add(value);\n pending.push({ _tag: \"leave\", value });\n\n const entries = Array.isArray(value)\n ? Array.from(value, (entry, index) => [index, entry] as const)\n : Object.entries(value);\n\n if (entries.length > MAX_PERSISTED_JSON_COLLECTION_LENGTH) return false;\n for (const [key, entry] of entries) {\n textUnits += typeof key === \"string\" ? key.length : 0;\n if (textUnits > limits.bytes) return false;\n pending.push({ _tag: \"visit\", value: entry, depth: current.depth + 1 });\n }\n }\n\n if (!isJson(input)) return false;\n const encoded = JSON.stringify(input);\n\n // Escaping is already reflected in the serialized text. UTF-8 uses one to three bytes per\n // UTF-16 code unit; ASCII uses exactly one. Only ambiguous Unicode needs the exact count.\n return (\n encoded !== undefined &&\n encoded.length <= limits.bytes &&\n (encoded.length <= limits.bytes / 3 ||\n !nonAscii.test(encoded) ||\n utf8ByteLength(encoded) <= limits.bytes)\n );\n } catch {\n return false;\n }\n };\n\nconst isPersistedJson = boundedJson({\n depth: MAX_PERSISTED_JSON_DEPTH,\n nodes: MAX_PERSISTED_JSON_NODES,\n bytes: MAX_PERSISTED_JSON_BYTES,\n});\n\n/** Canonical JSON admitted to persisted records and checkpoints under explicit resource limits. */\nexport const PersistedJson = Schema.declare(isPersistedJson, {\n identifier: \"@effect-agent/thread/PersistedJson\",\n description: \"JSON bounded by canonical persistence depth, collection, node, and byte limits\",\n});\n\nexport type PersistedJson = typeof PersistedJson.Type;\n\n/** Whole record wire reserves room for the payload's envelope and additional bounded fields. */\nexport const RecordJson = Schema.declare(\n boundedJson({\n depth: MAX_PERSISTED_JSON_DEPTH + 4,\n nodes: MAX_PERSISTED_JSON_NODES * 4,\n bytes: MAX_CANONICAL_RECORD_BYTES,\n }),\n {\n identifier: \"@effect-agent/thread/RecordJson\",\n description: \"Canonical record JSON bounded by depth, collection, node, and 4 MiB byte limits\",\n },\n);\n\nexport type RecordJson = typeof RecordJson.Type;\n\n/** Schema-owned replay inputs whose individual definitions are incorporated into digests. */\nexport class DefinitionDigestInput extends Schema.Class<DefinitionDigestInput>(\n \"@effect-agent/thread/DefinitionDigestInput\",\n)({\n agent: PersistedJson,\n model: PersistedJson,\n tools: PersistedJson,\n}) {}\n\n/** Admission-time operation fingerprints. Agent fingerprints remain immutable evidence only. */\nexport class ReplayContract extends Schema.Class<ReplayContract>(\n \"@effect-agent/thread/ReplayContract\",\n)({\n agent: Digest,\n /** Retained for reading earlier admissions; never selects executable code. */\n agentBehavior: Schema.optionalKey(Digest),\n tools: Schema.Record(Schema.String, Digest),\n}) {}\n\n/** Digests identify admission exactly; only an unfinished operation needs replay compatibility. */\nexport class DefinitionDigests extends Schema.Class<DefinitionDigests>(\n \"@effect-agent/thread/DefinitionDigests\",\n)({\n agent: Digest,\n model: Digest,\n tools: Digest,\n replay: Schema.optionalKey(ReplayContract),\n}) {}\n\nexport class ThreadCreated extends Schema.TaggedClass<ThreadCreated>(\n \"@effect-agent/thread/ThreadCreated\",\n)(\"ThreadCreated\", {\n agentId: AgentId,\n definitions: DefinitionDigests,\n}) {}\n\n/**\n * One recorded Thread input. `submissionId` is present only for durably accepted work;\n * retained history has no admission or settlement obligation. `kind` identifies the input seam.\n */\nexport class UserInputRecorded extends Schema.TaggedClass<UserInputRecorded>(\n \"@effect-agent/thread/UserInputRecorded\",\n)(\"UserInputRecorded\", {\n submissionId: Schema.optionalKey(SubmissionId),\n kind: Schema.Literals([\"user\", \"steering\", \"follow-up\"]),\n runId: Schema.optionalKey(RunId),\n input: PersistedJson,\n messageAdmission: Schema.optionalKey(InputMessage),\n}) {}\n\n/** Immutable Run start and per-Attempt duration allowance, before any agent execution. */\nexport class RunStartedRecord extends Schema.TaggedClass<RunStartedRecord>(\n \"@effect-agent/thread/RunStartedRecord\",\n)(\"RunStarted\", {\n runId: RunId,\n /** Older private histories cannot prove programmatic accounting and must be reset. */\n policyAccountingVersion: Schema.Literal(1),\n maxDurationMillis: Schema.Finite.check(Schema.isGreaterThan(0)),\n}) {}\n\n/** An active Attempt exhausted its execution allowance; downtime alone never writes this. */\nexport class RunDurationExhausted extends Schema.TaggedClass<RunDurationExhausted>(\n \"@effect-agent/thread/RunDurationExhausted\",\n)(\"RunDurationExhausted\", { runId: RunId }) {}\n\nconst PersistedPromptMessages = Schema.toEncoded(Prompt.Prompt);\nconst isPersistedPromptMessages = Schema.is(PersistedPromptMessages);\n\n/**\n * Final model output. Immediate history records the successful Run's source messages for\n * recall and a full retained model-context snapshot for the next Run. Durable execution\n * instead journals individual ModelResponseRecorded Turns and exact context references.\n */\nexport class ModelCompleted extends Schema.TaggedClass<ModelCompleted>(\n \"@effect-agent/thread/ModelCompleted\",\n)(\n \"ModelCompleted\",\n Schema.Struct({\n runId: RunId,\n output: PersistedJson,\n messages: Schema.optionalKey(PersistedJson),\n history: Schema.optionalKey(PersistedJson),\n }).check(\n Schema.makeFilter(\n (record) =>\n (record.messages === undefined && record.history === undefined) ||\n (record.messages !== undefined &&\n record.history !== undefined &&\n isPersistedPromptMessages(record.messages) &&\n isPersistedPromptMessages(record.history)),\n { title: \"Retained source messages and model context are paired encoded Effect AI Prompts\" },\n ),\n ),\n) {}\n\nexport class ToolCallSettled extends Schema.TaggedClass<ToolCallSettled>(\n \"@effect-agent/thread/ToolCallSettled\",\n)(\"ToolCallSettled\", {\n toolSelection: Schema.optionalKey(Selection),\n runId: RunId,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n result: PersistedJson,\n isFailure: Schema.Boolean,\n /** Explicit engine evidence, never inferred from Tool result data. */\n budgetRejected: Schema.optionalKey(Schema.Literal(true)),\n}) {}\n\n/** Compact execution evidence committed with a declaration, before any handler can start. */\nexport class ToolOperation extends Schema.Class<ToolOperation>(\n \"@effect-agent/thread/ToolOperation\",\n)({\n toolCallId: ToolCallId,\n toolName: BoundedName,\n executionClass: Schema.Literals([\"readonly\", \"idempotent\", \"uncertain\"]),\n executionKind: ToolExecutionKind,\n replay: Digest,\n}) {}\n\n/** Derived recovery input from one committed response; never a separate canonical record. */\nexport class DeclaredToolCall extends Schema.Class<DeclaredToolCall>(\n \"@effect-agent/thread/DeclaredToolCall\",\n)({\n ...ToolOperation.fields,\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n parameters: PersistedJson,\n parametersDigest: Digest,\n}) {}\n\n/** A retired call's runtime result. Unavailable readonly work may already have been observed. */\nexport class ToolUnavailable extends Schema.TaggedClass<ToolUnavailable>()(\"ToolUnavailable\", {\n toolName: BoundedName,\n execution: Schema.Literals([\"not-executed\", \"unavailable\"]),\n message: BoundedText,\n}) {}\n\n/**\n * One committed model Turn. `messages` carries the Schema-encoded Effect AI Prompt messages this\n * Turn appended (assistant response plus any tool-call declarations), committed atomically at the\n * Turn boundary so a recovering Attempt can rebuild the next Prompt from canonical records alone.\n */\nconst ModelResponseRecordedFields = Schema.Struct({\n /** Original bound for each application result; replacement Bindings cannot enlarge it. */\n toolResultMaxBytes: Schema.Int.check(\n Schema.isBetween({ minimum: 256, maximum: MAX_PERSISTED_JSON_BYTES }),\n ),\n /** Maximum encoded selection metadata from the native catalog at declaration time. */\n toolSelectionMaxBytes: Schema.Natural.check(\n Schema.isLessThanOrEqualTo(MAX_CANONICAL_RECORD_BYTES),\n ),\n /** Exactly one entry per application call, including rejected calls; none for provider execution. */\n toolOperations: Schema.Array(ToolOperation),\n /** Explicit pre-execution failures, committed with the original arguments before any approval. */\n toolParameterRejections: Schema.optionalKey(Schema.Array(ToolParameterRejection)),\n toolExposure: Schema.optionalKey(Snapshot),\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n messages: PersistedJson,\n /**\n * Number of leading messages that belong only to this Run's evaluated instructions and wake\n * input. They remain canonical. An unfinished Run retains this exact evaluated prefix;\n * subsequent Runs retain its original user intent in conversation history.\n */\n runScopedPrefixLength: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n /**\n * Exact normalized usage for every model call staged into this Turn. A\n * summarizer and the Turn response are distinct entries. Unmetered responses can omit it.\n */\n modelUsage: Schema.optionalKey(Schema.Array(ModelCallUsage)),\n /** Observed invocations without retained accounting before this Turn committed. */\n unobservedModelCalls: Schema.optionalKey(Schema.Natural),\n /** Aggregate observed usage when per-call accounting is unavailable. */\n inputTokens: Schema.optionalKey(Schema.Natural),\n outputTokens: Schema.optionalKey(Schema.Natural),\n /** Estimated spend staged with the usage; recovery re-seeds the cost budget (RUN-023). */\n costMicrousd: Schema.optionalKey(Schema.Natural),\n}).check(\n Schema.makeFilter(\n (response) => {\n if (!isPersistedPromptMessages(response.messages)) return false;\n\n const declarations = response.messages.content.flatMap((message) =>\n message.role === \"assistant\" && typeof message.content !== \"string\"\n ? message.content.filter(\n (part) => part.type === \"tool-call\" && part.providerExecuted !== true,\n )\n : [],\n );\n\n if (declarations.length !== response.toolOperations.length) return false;\n const seen = new Set<string>();\n\n for (const operation of response.toolOperations) {\n if (\n seen.has(operation.toolCallId) ||\n !declarations.some(\n (call) =>\n call.type === \"tool-call\" &&\n call.id === operation.toolCallId &&\n call.name === operation.toolName,\n )\n )\n return false;\n seen.add(operation.toolCallId);\n }\n\n return declarations.every((call) => call.type === \"tool-call\" && seen.has(call.id));\n },\n { title: \"Every application Tool declaration has unique original operation evidence\" },\n ),\n Schema.makeFilter(\n (response) =>\n response.runScopedPrefixLength === undefined ||\n (isPersistedPromptMessages(response.messages) &&\n response.runScopedPrefixLength < response.messages.content.length &&\n response.messages.content\n .slice(0, response.runScopedPrefixLength)\n .every((message) => message.role === \"system\" || message.role === \"user\")),\n {\n title:\n \"Run-scoped Prompt prefix contains only instruction/wake messages and leaves one response\",\n },\n ),\n);\n\nexport class ModelResponseRecorded extends Schema.TaggedClass<ModelResponseRecorded>(\n \"@effect-agent/thread/ModelResponseRecorded\",\n)(\"ModelResponseRecorded\", ModelResponseRecordedFields) {}\n\n/** Monotonic reservations charged before programmatic execution or grace finalization. */\nexport class RunPolicyUsageReserved extends Schema.TaggedClass<RunPolicyUsageReserved>()(\n \"RunPolicyUsageReserved\",\n {\n runId: RunId,\n programmaticToolCalls: RunPolicyUsage.fields.programmaticToolCalls,\n finalizationUsed: RunPolicyUsage.fields.finalizationUsed,\n },\n) {}\n\n/**\n * A durable Unknown Outcome: the external effect of one declared ordinary Tool Call may have\n * happened but was not confirmed canonically (DUR-009/DUR-017). It is neither success nor\n * ordinary failure; automatic continuation stops until an authorized resolution arrives.\n */\nexport class ToolCallUnknown extends Schema.TaggedClass<ToolCallUnknown>(\n \"@effect-agent/thread/ToolCallUnknown\",\n)(\"ToolCallUnknown\", {\n runId: RunId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n reason: BoundedText,\n}) {}\n\n/** How one open/unknown Tool Call was authoritatively closed (DUR-017 resolution audit). */\nexport const ToolCallResolution = Schema.Literals([\n \"completed-with-result\",\n \"failed-with-error\",\n \"never-started\",\n \"safe-retry\",\n]);\n\nexport type ToolCallResolution = typeof ToolCallResolution.Type;\n\n/**\n * The canonical audit record closing one open or unknown Tool Call: reconciler-recovered supplier\n * truth or an authorized `resolveUnknown` command. `author`/`reason` make every resolution an\n * attributable decision (DUR-017); a `completed-with-result` resolution is accompanied by the\n * per-call `ToolCallSettled` record carrying the recovered result.\n */\nexport class ToolCallResolved extends Schema.TaggedClass<ToolCallResolved>(\n \"@effect-agent/thread/ToolCallResolved\",\n)(\"ToolCallResolved\", {\n runId: RunId,\n toolCallId: ToolCallId,\n resolution: ToolCallResolution,\n author: BoundedName,\n reason: BoundedText,\n}) {}\n\n/**\n * One accepted Durable Step result (durability §11): exactly-once-recorded while the Step's\n * external side effect stays honestly at-least-once-executed. Only success is recorded — a failing\n * Step body fails into the handler's error channel and re-executes on re-entry. `output` is the\n * Schema-encoded Step output; `outputDigest` pins it for replay-divergence detection.\n */\nexport class ToolStepSettled extends Schema.TaggedClass<ToolStepSettled>(\n \"@effect-agent/thread/ToolStepSettled\",\n)(\"ToolStepSettled\", {\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: BoundedName,\n output: PersistedJson,\n outputDigest: Digest,\n}) {}\n\n/**\n * A canonical approval request for one declared Tool Call (CAP-006, durability §8): with this\n * record durable, \"waiting for explicit approval\" is a safe suspension boundary — the resumed\n * Attempt replays the declared batch instead of re-invoking the model.\n */\nexport class ToolApprovalRequested extends Schema.TaggedClass<ToolApprovalRequested>(\n \"@effect-agent/thread/ToolApprovalRequested\",\n)(\"ToolApprovalRequested\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n parametersDigest: Digest,\n /** This request preceded every possible dispatch of the original response. */\n blocksInitialDispatch: Schema.Boolean,\n}) {}\n\n/** The two-valued approval decision family shared by canonical records and ledger intents. */\nexport const ApprovalDecision = Schema.Literals([\"approved\", \"denied\"]);\n\nexport type ApprovalDecision = typeof ApprovalDecision.Type;\n\n/**\n * The canonical decision for one requested approval. Appended by the deciding Attempt (policy\n * auto-decisions) or by the resuming Attempt after a durable `resolveApproval` intent; it is the\n * deterministic decision authority for every later Attempt of the same Run.\n */\nexport class ToolApprovalDecided extends Schema.TaggedClass<ToolApprovalDecided>(\n \"@effect-agent/thread/ToolApprovalDecided\",\n)(\"ToolApprovalDecided\", {\n runId: RunId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n decision: ApprovalDecision,\n resolver: BoundedName,\n reason: BoundedText,\n}) {}\n\n/**\n * A Run resumed inference without a retained response. One marker makes usage coverage\n * incomplete; it does not count missing provider calls or retain Attempt history.\n */\nexport class ModelResponseInterrupted extends Schema.TaggedClass<ModelResponseInterrupted>(\n \"@effect-agent/thread/ModelResponseInterrupted\",\n)(\"ModelResponseInterrupted\", {\n runId: RunId,\n}) {}\n\n/** Disposable call cancellation: no response or Tool declaration is canonical. */\nexport class ModelCallAborted extends Schema.TaggedClass<ModelCallAborted>()(\"ModelCallAborted\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n restart: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 2 })),\n reason: Schema.Literal(\"joined-input\"),\n modelUsage: Schema.Array(ModelCallUsage),\n unobservedModelCalls: Schema.Natural,\n}) {}\n\n/**\n * One engine-native compaction committed before the pre-Turn view changes (RUN-026).\n * `coversThrough` is a Thread record sequence: the projection\n * renders records at or below it as a summary (`summarize`), a fresh window (`rollover`), or with\n * cleared tool results (kind `clear-tool-results`), never erasing source\n * history. The record carries no digest by decision: it is appended by the\n * fenced owner into the very log it covers, and re-verifying a digest would\n * re-read the covered range on every wake — the O(history) work compaction\n * exists to remove. Host-supplied ContextCompactor decisions use this same commit path.\n * Summaries exceeding BoundedText are rejected before append, never truncated.\n * `summary` is present exactly for `summarize` records; the projection\n * treats a summarize record without one as invalid and ignores it fail-safe.\n */\nexport class CompactionCreated extends Schema.TaggedClass<CompactionCreated>(\n \"@effect-agent/thread/CompactionCreated\",\n)(\"CompactionCreated\", {\n runId: RunId,\n turn: TurnNumber,\n kind: Schema.Literals([\"clear-tool-results\", \"summarize\", \"rollover\"]),\n coversThrough: CanonicalSequence,\n summary: Schema.optionalKey(BoundedText),\n handoff: Schema.optionalKey(ContextHandoff),\n}) {}\n\nexport class RunFailed extends Schema.TaggedClass<RunFailed>(\"@effect-agent/thread/RunFailed\")(\n \"RunFailed\",\n {\n runId: RunId,\n failure: PersistedJson,\n },\n) {}\n\nconst RunCompletedFields = Schema.Struct({\n runId: RunId,\n output: PersistedJson,\n /** Integrity of validated terminal values, independent of future application codecs. */\n /** Application disposition captured with an ordinary completion. */\n runDisposition: Schema.optionalKey(PersistedJson),\n /** Honest soft-landing marker, present exactly when `exhausted` is present. */\n finishReason: Schema.optionalKey(Schema.Literal(\"budget-exhausted\")),\n /** Budget dimension paired with `finishReason` on a soft landing. */\n exhausted: Schema.optionalKey(ExhaustedLimit),\n}).check(\n Schema.makeFilter(\n (completed) =>\n (completed.finishReason === undefined) === (completed.exhausted === undefined) &&\n (completed.runDisposition === undefined || completed.finishReason === undefined),\n { title: \"Run completion metadata matches its terminal family\" },\n ),\n);\n\nexport class RunCompleted extends Schema.TaggedClass<RunCompleted>(\n \"@effect-agent/thread/RunCompleted\",\n)(\"RunCompleted\", RunCompletedFields) {}\n\nexport class RepairAnnotated extends Schema.TaggedClass<RepairAnnotated>(\n \"@effect-agent/thread/RepairAnnotated\",\n)(\"RepairAnnotated\", {\n reason: BoundedText,\n details: PersistedJson,\n}) {}\n\n/** Terminal outcome family for one accepted Submission (DUR-002). */\nexport const SettlementOutcome = Schema.Literals([\"completed\", \"failed\", \"aborted\"]);\n\nexport type SettlementOutcome = typeof SettlementOutcome.Type;\n\n/**\n * A durable abort command made canonical before the active worker is interrupted (DUR-012).\n * Repeating the same abort command is idempotent; abort never rewrites a prior terminal outcome.\n */\nexport class AbortRequested extends Schema.TaggedClass<AbortRequested>(\n \"@effect-agent/thread/AbortRequested\",\n)(\"AbortRequested\", {\n submissionId: SubmissionId,\n author: BoundedName,\n reason: BoundedText,\n}) {}\n\n/**\n * The single canonical settlement record owed to one accepted Submission (DUR-002, DUR-011).\n * Canonical history is the outcome authority: the ledger row is finalized from this record and\n * never the other way around (DUR-015).\n */\nconst RawSubmissionSettled = Schema.Struct({\n submissionId: SubmissionId,\n settlementId: SettlementId,\n receiptId: ReceiptId,\n outcome: SettlementOutcome,\n runId: Schema.optionalKey(RunId),\n /** Number of retained owning facts through this terminal commit, excluding mutable progress. */\n historyRecordCount: Schema.optionalKey(Schema.Natural),\n result: Schema.optionalKey(PersistedJson),\n /**\n * Application-defined, Schema-encoded disposition for an ordinary completed\n * Run. Absent for budget exhaustion and every non-completed or run-less\n * settlement; consumers decode it with the application definition's Schema.\n */\n runDisposition: Schema.optionalKey(PersistedJson),\n /**\n * Present only when a `completed` Run settled through the final-answer\n * exhaustion resolution (RUN-011, RUN-018): the durable log must be able to\n * distinguish honest-exhaustion completion from ordinary completion without\n * the live event stream. Absent for every ordinary settlement, keeping\n * existing histories and goldens byte-stable (additive, schemaVersion 1).\n */\n finishReason: Schema.optionalKey(Schema.Literal(\"budget-exhausted\")),\n /**\n * The dimension that bound a budget-exhausted completion (RUN-011,\n * RUN-025), carried verbatim from the live `RunCompleted` event so\n * consumers never reconstruct it from message text. Valid only alongside\n * `finishReason: \"budget-exhausted\"`; absent on histories persisted before\n * the dimension became durable (additive, schemaVersion 1).\n */\n exhausted: Schema.optionalKey(ExhaustedLimit),\n /**\n * The typed `AgentPolicyError.limit` of a `failed` hard-rail settlement\n * (RUN-011): which finite policy dimension failed the Run, preserved\n * alongside the bounded `{errorTag, message}` failure projection in\n * `result`. Absent for every non-policy failure and on histories persisted\n * before the limit became durable (additive, schemaVersion 1).\n */\n policyLimit: Schema.optionalKey(PolicyLimit),\n /** Canonical aggregate of all priced model calls made by this Run. */\n usageSummary: Schema.optionalKey(RunUsageSummary),\n /** Calls included in usageSummary but not in any ModelResponseRecorded, retained on failure. */\n uncommittedModelUsage: Schema.optionalKey(Schema.Array(ModelCallUsage)),\n});\n\nconst isPolicyFailureProjection = Schema.is(\n Schema.Struct({ errorTag: Schema.Literal(\"AgentPolicyError\") }),\n);\n\nconst decodeSettlementFailureDiagnostic = Schema.decodeUnknownOption(SettlementFailureDiagnostic, {\n onExcessProperty: \"error\",\n});\n\nconst hasValidSettlementFamily = (settled: typeof RawSubmissionSettled.Type): boolean =>\n (settled.finishReason === undefined || settled.outcome === \"completed\") &&\n (settled.finishReason === undefined) === (settled.exhausted === undefined) &&\n (settled.usageSummary === undefined || settled.runId !== undefined) &&\n (settled.uncommittedModelUsage === undefined ||\n (settled.runId !== undefined && settled.usageSummary !== undefined)) &&\n (settled.runDisposition === undefined ||\n (settled.outcome === \"completed\" &&\n settled.finishReason === undefined &&\n settled.runId !== undefined &&\n settled.result !== undefined)) &&\n (settled.outcome !== \"failed\" ||\n Option.isSome(decodeSettlementFailureDiagnostic(settled.result))) &&\n (settled.outcome !== \"aborted\" || settled.result === undefined) &&\n (settled.policyLimit === undefined ||\n (settled.outcome === \"failed\" && isPolicyFailureProjection(settled.result)));\n\nconst SubmissionSettledFields = RawSubmissionSettled.check(\n Schema.makeFilter(hasValidSettlementFamily, {\n title:\n \"failed settlements require a bounded diagnostic; aborted settlements carry no result; budget metadata must match its settlement family\",\n }),\n);\n\nexport class SubmissionSettled extends Schema.TaggedClass<SubmissionSettled>(\n \"@effect-agent/thread/SubmissionSettled\",\n)(\"SubmissionSettled\", SubmissionSettledFields) {}\n\n/** Canonical completed settlement; joined completion may legitimately carry no independent result. */\nexport type CompletedSubmissionSettled = SubmissionSettled & {\n readonly outcome: \"completed\";\n};\n\n/** Canonical failed settlement; its bounded diagnostic is required and typed. */\nexport type FailedSubmissionSettled = SubmissionSettled & {\n readonly outcome: \"failed\";\n readonly result: SettlementFailureDiagnostic;\n};\n\n/** Canonical aborted settlement; abort records intent rather than fabricating a terminal result. */\nexport type AbortedSubmissionSettled = SubmissionSettled & {\n readonly outcome: \"aborted\";\n readonly result?: never;\n};\n\nexport type SubmissionSettledRecord =\n | CompletedSubmissionSettled\n | FailedSubmissionSettled\n | AbortedSubmissionSettled;\n\n/**\n * Canonical-boundary view of `SubmissionSettled`: `finishReason` is valid\n * only on a `completed` outcome, `exhausted` only alongside\n * `finishReason: \"budget-exhausted\"`, every `failed` outcome requires the exact bounded\n * `SettlementFailureDiagnostic`, aborted outcomes carry no result, and `policyLimit` only occurs\n * on a `failed` outcome whose diagnostic carries the `AgentPolicyError` tag. `runDisposition`\n * occurs only on an ordinary completed settlement with a Run —\n * so a malformed persisted combination such as\n * `{ outcome: \"failed\", finishReason: \"budget-exhausted\" }` or a\n * `policyLimit` contradicting `result.errorTag` fails closed at decode\n * instead of becoming trusted audit history (STORE-006, RUN-011).\n */\nexport const SubmissionSettledRecord = SubmissionSettled.pipe(\n Schema.refine(\n (settled): settled is SubmissionSettledRecord => hasValidSettlementFamily(settled),\n {\n expected:\n \"failed settlements require a bounded diagnostic, aborted settlements carry no result, finishReason only occurs on completed settlements, exhausted only occurs with finishReason budget-exhausted, runDisposition only occurs on an ordinary completed settlement with a Run result, and policyLimit only occurs on a failed AgentPolicyError settlement\",\n },\n ),\n);\n\n/**\n * PARENT-log record of one durable child establishment request:\n * the exact parent Tool Call, delegation and target identity, the digests that pin the child's\n * Binding/input/grant, the fenced budget reservation, and the INTENDED child identity derived\n * deterministically from the parent Run and Tool Call pair (D4). `childInput` carries the\n * prepared child input in encoded form (D3) so recovery can complete child admission from this\n * record alone — no live delegation handler is required. `childPrincipal`/`childIdempotencyKey`\n * carry the ledger admission scope with the ledger's exact bounds; the layering keeps their\n * branded Schemas in the ledger port.\n */\nexport class SubagentRequested extends Schema.TaggedClass<SubagentRequested>(\n \"@effect-agent/thread/SubagentRequested\",\n)(\"SubagentRequested\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n delegationId: DelegationId,\n targetAgentId: AgentId,\n targetDigests: DefinitionDigests,\n childInput: PersistedJson,\n childInputDigest: Digest,\n grantDigest: Digest,\n reservationId: BoundedName,\n reservationDigest: Digest,\n childThreadId: ThreadId,\n childPrincipal: BoundedName,\n childIdempotencyKey: BoundedName,\n /** Effective invocation bound, already clamped to the delegation and child Definition. */\n toolCallAllowance: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n policy: Schema.optionalKey(Schema.toCodecJson(AgentPolicy)),\n budget: Schema.optionalKey(SubagentBudgetReservation),\n grant: Schema.optionalKey(SubagentGrant),\n depth: Schema.optionalKey(DelegationDepth),\n}) {}\n\n/**\n * PARENT-log record that the intended child exists as accepted work:\n * the full established child identity. It is appended only after the child Receipt\n * exists — SUB-017 holds by construction because `childReceiptId` is a required field.\n */\nexport class SubagentStarted extends Schema.TaggedClass<SubagentStarted>(\n \"@effect-agent/thread/SubagentStarted\",\n)(\"SubagentStarted\", {\n runId: RunId,\n toolCallId: ToolCallId,\n childThreadId: ThreadId,\n childSubmissionId: SubmissionId,\n childReceiptId: ReceiptId,\n childRunId: RunId,\n}) {}\n\n/**\n * PARENT-log record of one verified child settlement join:\n * the child's canonical Settlement identity and outcome, the child usage summary, and the FINAL\n * consumed/released accounting decision for the reservation. It commits in ONE atomic batch with\n * the parent `ToolCallSettled` record (SUB-019); `beginChildBudgetRelease` replays\n * `finalAccounting` from this record, so canonical history authorizes the release (DUR-015).\n */\nexport class SubagentJoined extends Schema.TaggedClass<SubagentJoined>(\n \"@effect-agent/thread/SubagentJoined\",\n)(\"SubagentJoined\", {\n runId: RunId,\n toolCallId: ToolCallId,\n childSubmissionId: SubmissionId,\n childSettlementId: SettlementId,\n childOutcome: SettlementOutcome,\n usageSummary: PersistedJson,\n usage: Schema.optionalKey(RunTotals),\n delegatedUsage: Schema.optionalKey(RunTotals),\n reservationId: BoundedName,\n finalAccounting: PersistedJson,\n}) {}\n\n/**\n * CHILD-log immutable lineage: the Parent Link plus the digests that pin\n * the child's definition, input, and authority grant. It is the first record after the child's\n * `ThreadCreated` (its own single-record batch, so the generic `thread-created:{cid}`\n * batch identity is never contradicted) and the join path verifies it fail-closed — a fabricated\n * child or parent identity fails Parent Link verification (SUB-004, D10).\n */\nexport class SubagentLineageRecorded extends Schema.TaggedClass<SubagentLineageRecorded>(\n \"@effect-agent/thread/SubagentLineageRecorded\",\n)(\"SubagentLineageRecorded\", {\n parentLink: SubagentParentLink,\n parentSubmissionId: SubmissionId,\n childDefinitionDigests: DefinitionDigests,\n childInputDigest: Digest,\n grantDigest: Digest,\n /** Copied from the canonical request before readiness; restored for every child Attempt. */\n toolCallAllowance: SubagentRequested.fields.toolCallAllowance,\n policy: SubagentRequested.fields.policy,\n budget: SubagentRequested.fields.budget,\n grant: SubagentRequested.fields.grant,\n}) {}\n\nexport const WorkerReportingIntent = Schema.Struct({\n /** Absent only in historical custom-report origins; these remain readable as evidence. */\n mode: Schema.optionalKey(Schema.Literal(\"standard\")),\n sourceDigests: DefinitionDigests,\n /** Historical custom destination evidence. New worker origins never write this field. */\n destinationDelegationId: Schema.optionalKey(DelegationId),\n /** Frozen by the sender before acceptance. Standard emission never reads the source runtime. */\n returnAddress: Schema.optionalKey(\n Schema.Struct({\n input: PersistedJson,\n principal: Principal,\n policy: Schema.toCodecJson(AgentPolicy),\n depth: Schema.Natural,\n grant: Schema.optionalKey(SubagentGrant),\n /** Encoded to bound recursive worker origins at the admission boundary. */\n workerAdmission: Schema.optionalKey(PersistedJson),\n }),\n ),\n}).check(\n Schema.makeFilter((value) => (value.mode === \"standard\") === (value.returnAddress !== undefined)),\n);\n\n/** Exact successful predecessor evidence; a locator alone grants no authority. */\nexport const WorkerContinuation = Schema.Struct({\n worker: WorkerRef,\n receipt: Receipt,\n settlementId: SettlementId,\n}).check(Schema.makeFilter((value) => value.worker.threadId === value.receipt.threadId));\n\nexport type WorkerContinuation = typeof WorkerContinuation.Type;\n\n/** Immutable worker Thread origin. Each input has its own digest and parameters separately. */\nexport const WorkerOrigin = Schema.Struct({\n worker: WorkerRef,\n source: WorkerSource,\n /** A new assignment may continue this completed, immutable predecessor. */\n continuationOf: Schema.optionalKey(WorkerContinuation),\n /** Frozen funding owner; worker-run renews only for a new native Run. */\n budgetScope: WorkerBudgetScope,\n /** Frozen at worker creation; older origins remain reusable. */\n lifecycle: Schema.optionalKey(Schema.Literal(\"assignment\")),\n targetDigests: DefinitionDigests,\n policy: Schema.toCodecJson(AgentPolicy),\n budget: SubagentBudgetReservation,\n grant: SubagentGrant,\n depth: DelegationDepth,\n toolCallAllowance: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n firstMessageId: IdempotencyKey,\n createdAtMillis: Schema.Natural,\n expiresAtMillis: Schema.Natural,\n /** Exact source registration owns projection; absence means reporting was not declared. */\n reporting: Schema.optionalKey(WorkerReportingIntent),\n}).check(Schema.makeFilter((value) => value.expiresAtMillis > value.createdAtMillis));\n\nexport type WorkerOrigin = typeof WorkerOrigin.Type;\n\n/** Frozen per-input metadata; it grants no attached-child or parent-abort semantics. */\nexport const WorkerAdmission = Schema.Struct({\n origin: WorkerOrigin,\n /** Run executing this handoff, independently of immutable lineage and subtree funding. */\n executionRunId: Schema.NullOr(RunId),\n messageId: IdempotencyKey,\n parameters: PersistedJson,\n createdAtMillis: Schema.Natural,\n /** Host-bound source input whose subtree funds this input; never chosen by a model. */\n sourceSubmissionId: Schema.optionalKey(SubmissionId),\n /** Enables routed receipt lookup when the delivery is owned by a reporting child. */\n deliveryPrincipal: Schema.optionalKey(Principal),\n /** Proven framework updates use a separate bounded input-capacity partition. */\n reportKind: Schema.optionalKey(Schema.Literal(\"update\")),\n});\n\nexport type WorkerAdmission = typeof WorkerAdmission.Type;\n\n/** Owner command retained before the destination inbox is sealed. */\nexport class WorkerStopRequested extends Schema.TaggedClass<WorkerStopRequested>()(\n \"WorkerStopRequested\",\n {\n command: WorkerStop,\n principal: Principal,\n sourceSubmissionId: Schema.optionalKey(SubmissionId),\n },\n) {}\n\n/** The named canonical obligation closed only after its owning state durably completes. */\nexport class WorkHandoffCompleted extends Schema.TaggedClass<WorkHandoffCompleted>()(\n \"WorkHandoffCompleted\",\n { preparationId: RecordId, ownerId: Schema.NonEmptyString.check(Schema.isMaxLength(4096)) },\n) {}\n\n/** Source-log capacity reservation, retained independently of the source Run's settlement. */\nexport class WorkerInputRequested extends Schema.TaggedClass<WorkerInputRequested>()(\n \"WorkerInputRequested\",\n { admission: WorkerAdmission, inputDigest: Digest },\n) {}\n\n/** Child-log origin, reconstructed from a retained delivery before the child becomes ready. */\nexport class WorkerOriginRecorded extends Schema.TaggedClass<WorkerOriginRecorded>()(\n \"WorkerOriginRecorded\",\n { origin: WorkerOrigin },\n) {}\n\n/** Canonical child completion acknowledgement releases only this input's active capacity. */\nexport class WorkerInputCompleted extends Schema.TaggedClass<WorkerInputCompleted>()(\n \"WorkerInputCompleted\",\n {\n messageId: IdempotencyKey,\n workerThreadId: ThreadId,\n submissionId: SubmissionId,\n receiptId: ReceiptId,\n settlementId: SettlementId,\n completedAtMillis: Schema.Natural,\n /** New acknowledgements prove that this input's external effects are resolved. */\n effectsResolved: Schema.optionalKey(Schema.Literal(true)),\n },\n) {}\n\n/**\n * Frozen report decision for one actual Run, shared by every joined Receipt. The envelope is\n * a Schema-encoded PreparedInput, validated before append and decoded again on recovery.\n * Keeping the encoded value here avoids a Records/PreparedInput schema dependency cycle.\n */\nexport class WorkerReportPrepared extends Schema.TaggedClass<WorkerReportPrepared>()(\n \"WorkerReportPrepared\",\n {\n runId: RunId,\n messageId: IdempotencyKey,\n envelope: PersistedJson,\n createdAtMillis: Schema.Natural,\n deadlineAtMillis: Schema.Natural,\n predecessor: Schema.optionalKey(IdempotencyKey),\n },\n) {}\n\n/** Accepted update and its optional frozen parent delivery are one atomic canonical fact. */\nexport class AgentUpdateEmitted extends Schema.TaggedClass<AgentUpdateEmitted>()(\n \"AgentUpdateEmitted\",\n {\n update: Update,\n definitions: DefinitionDigests,\n delivery: Schema.optionalKey(\n Schema.Struct({\n messageId: IdempotencyKey,\n envelope: PersistedJson,\n createdAtMillis: Schema.Natural,\n deadlineAtMillis: Schema.Natural,\n predecessor: Schema.optionalKey(IdempotencyKey),\n }),\n ),\n },\n) {}\n\n/** Permanent bounded report refusal. Application errors and raw Run dispositions stay private. */\nexport class WorkerReportRefused extends Schema.TaggedClass<WorkerReportRefused>()(\n \"WorkerReportRefused\",\n {\n runId: RunId,\n messageId: IdempotencyKey,\n reason: Schema.Literals([\n \"filtered\",\n \"declaration-unavailable\",\n \"destination\",\n \"projection\",\n \"input\",\n \"preparation\",\n \"timeout\",\n \"defect\",\n \"expired\",\n \"denied\",\n \"capacity\",\n ]),\n },\n) {}\n\n/** Frozen source proof of peer provenance, readable through routed canonical storage. */\nexport class PeerMessagePrepared extends Schema.TaggedClass<PeerMessagePrepared>()(\n \"PeerMessagePrepared\",\n {\n messageId: IdempotencyKey,\n source: WorkerSource,\n sourcePrincipal: Principal,\n operation: Schema.Literals([\"send\", \"reply\"]),\n deadlineAtMillis: Schema.Int.check(Schema.isGreaterThan(0)),\n encodedEnvelope: PersistedJson,\n },\n) {}\n\n/**\n * One disjoint subtree slice shared by attached and background children of a source input.\n * The source keeps its own execution ceiling; descendants spend only the remaining allocation.\n * Reservations include future descendant slots and never refund, including after interruption.\n * resultBytes reserves the terminal/projection result, not cumulative Tool output bytes.\n */\nexport class SubtreeBudgetReserved extends Schema.TaggedClass<SubtreeBudgetReserved>()(\n \"SubtreeBudgetReserved\",\n {\n reservationId: BoundedName,\n /** Run executing this reservation; null for host-owned follow-ups. Grants no authority. */\n executionRunId: Schema.NullOr(RunId),\n sourceSubmissionId: Schema.optionalKey(SubmissionId),\n childThreadId: ThreadId,\n lifetime: Schema.Literals([\"attached\", \"background\"]),\n depth: DelegationDepth,\n policy: Schema.toCodecJson(AgentPolicy),\n grant: SubagentGrant,\n budget: SubagentBudgetReservation,\n },\n) {}\n\n/** Fact identity; active-only references resolve inside their Run checkpoint. */\nexport const EvidenceReference = Schema.Struct({ recordId: RecordId });\nexport type EvidenceReference = typeof EvidenceReference.Type;\n\n/**\n * Receipt-free factual closure. The receiver's irreversible inbox seal precedes its exact-key\n * NotAdmitted observation; a refusal or an absent lookup alone cannot close reserved work.\n * Invocation and allocation charges remain with the original funding Run.\n */\nexport class WorkerInputRefused extends Schema.TaggedClass<WorkerInputRefused>()(\n \"WorkerInputRefused\",\n Schema.Struct({\n messageId: IdempotencyKey,\n workerThreadId: ThreadId,\n reservation: EvidenceReference,\n stop: EvidenceReference,\n deliveryVersion: Schema.Int.check(Schema.isGreaterThan(0)),\n envelopeDigest: Digest,\n receiver: Schema.Struct({\n threadId: ThreadId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n inputDigest: Digest,\n stopped: Schema.Literal(true),\n resolution: Schema.Literal(\"NotAdmitted\"),\n }),\n }).check(Schema.makeFilter((value) => value.receiver.threadId === value.workerThreadId)),\n) {}\n\nexport const MAX_RUN_CONTINUATION_BYTES = 8_192;\n/** Incremental record JSON per Turn, including progress and the first Turn's initial context. */\nexport const MAX_TURN_CANONICAL_BYTES = MAX_CANONICAL_RECORD_BYTES;\n/** Room retained for a bounded terminal failure and its atomic progress publication. */\nexport const RUN_TERMINAL_RESERVE_BYTES = 256 * 1024;\n/** Bounded closing facts remain publishable even after dispatch capacity is exhausted. */\nexport const MAX_RUN_TERMINAL_BYTES = 2 * MAX_CANONICAL_RECORD_BYTES + RUN_TERMINAL_RESERVE_BYTES;\nexport const RUN_TERMINAL_RESERVE_RECORDS = 4;\nexport const MAX_RUN_EVIDENCE_RECORDS = 16_384;\nexport const MAX_RUN_EVIDENCE_BYTES = 32 * 1024 * 1024;\nexport const MAX_RUN_RECOVERY_SUFFIX_RECORDS = 64;\nexport const MAX_RUN_RECOVERY_SUFFIX_BYTES = 2 * 1024 * 1024;\nexport const MAX_RUN_TOOL_CALL_IDENTITIES = 4_096;\n\nexport const ContextEvidenceReference = Schema.Struct({\n ...EvidenceReference.fields,\n sequence: CanonicalSequence,\n});\n\nexport class RunContextRecorded extends Schema.TaggedClass<RunContextRecorded>()(\n \"RunContextRecorded\",\n Schema.Struct({\n version: Schema.Literal(1),\n runId: RunId,\n /** Only evaluated instructions and this Run's input; prior history remains in its facts. */\n runScopedInput: PersistedJson,\n /** Inclusive range; historyThrough + 1 denotes an empty range. */\n historyFrom: CanonicalSequence.check(Schema.isGreaterThan(0)),\n /** Fixed prior-history boundary, immediately before the original accepted input. */\n historyThrough: CanonicalSequence,\n /** Facts below historyFrom still needed after summarize or rollover coverage. */\n retained: Schema.Array(ContextEvidenceReference).check(Schema.isMaxLength(4_096)),\n /** Pins the projected prior Prompt, not a second copy or a per-record manifest. */\n historyDigest: Digest,\n priorHistoryLength: Schema.Natural,\n contextWindowId: Schema.optionalKey(BoundedName),\n }).check(\n Schema.makeFilter(\n (context) =>\n context.historyFrom <= context.historyThrough + 1 &&\n context.retained.every(\n (ref, index) =>\n ref.sequence > (context.retained[index - 1]?.sequence ?? 0) &&\n ref.sequence < context.historyFrom,\n ),\n { title: \"Saved context retains an ordered prefix below its original history range\" },\n ),\n ),\n) {}\n\n/** Accumulated charges; replacement Attempts never replenish or charge these again. */\nexport const ContinuationAccounting = Schema.Struct({\n ...RunPolicyUsage.fields,\n modelRestarts: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 2 })),\n modelCalls: Schema.Natural,\n unobservedModelCalls: Schema.Natural,\n inputTokens: Schema.Natural,\n outputTokens: Schema.Natural,\n lastInputTokens: Schema.Natural,\n lastOutputTokens: Schema.Natural,\n costMicrousd: Schema.Natural,\n /** The last complete operation batch whose declaration-ordered failure streak was charged. */\n accountedToolTurn: Schema.Natural,\n});\n\nexport type ContinuationAccounting = typeof ContinuationAccounting.Type;\n\n/** Semantic execution boundaries, never engine stacks, fibers, or program counters. */\nexport const RunPosition = Schema.Literals([\n \"starting\",\n \"awaiting-model\",\n \"processing-operations\",\n \"waiting-approval\",\n \"waiting-dependency\",\n \"unknown\",\n \"settling\",\n \"settled\",\n]);\n\n/**\n * Current interpreter progress, replaced atomically with lastFact under the Thread fence.\n * lastFact is the exact accounted frontier of the same commit. References resolve within this\n * Thread's history or its authoritative active checkpoint. Results, operation declarations,\n * approvals and delivery obligations remain canonical; evaluated context and validated completion\n * belong to active state. Neither the checkpoint nor its revision grants execution authority.\n * Retired intermediate revisions are not historical verification evidence.\n */\nexport class RunContinuation extends Schema.TaggedClass<RunContinuation>()(\n \"RunContinuation\",\n Schema.Struct({\n version: Schema.Literal(1),\n runId: RunId,\n submissionId: SubmissionId,\n revision: Schema.Natural.check(Schema.isGreaterThan(0)),\n /** Number of this Run's non-continuation facts accounted for at the frontier. */\n recordCount: Schema.Natural.check(\n Schema.isLessThanOrEqualTo(MAX_RUN_EVIDENCE_RECORDS + RUN_TERMINAL_RESERVE_RECORDS),\n ),\n /** Cumulative committed owning fact bytes, excluding progress; deletion never refunds them. */\n recordBytes: Schema.Natural.check(\n Schema.isLessThanOrEqualTo(MAX_RUN_EVIDENCE_BYTES + MAX_RUN_TERMINAL_BYTES),\n ),\n /** Logical Turn whose incremental durable commit bytes are currently being charged. */\n turn: Schema.Natural,\n turnBytes: Schema.Natural.check(\n Schema.isLessThanOrEqualTo(MAX_TURN_CANONICAL_BYTES + MAX_RUN_TERMINAL_BYTES),\n ),\n /** Closing facts consume the terminal reserve, rather than reserving it again. */\n terminalBytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_RUN_TERMINAL_BYTES)),\n terminalRecords: Schema.Natural.check(Schema.isLessThanOrEqualTo(RUN_TERMINAL_RESERVE_RECORDS)),\n /** Conservative room for terminal usage grouping; derived only from canonical model usage. */\n terminalUsageBytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_RUN_EVIDENCE_BYTES)),\n originalInput: EvidenceReference,\n savedContext: Schema.optionalKey(EvidenceReference),\n latestResponse: Schema.optionalKey(EvidenceReference),\n terminal: Schema.optionalKey(EvidenceReference),\n lastFact: EvidenceReference,\n position: RunPosition,\n accounting: ContinuationAccounting,\n }),\n) {}\n\n/** Bump only when the meaning of an existing record changes, independently of SQL layout. */\nexport const CURRENT_RECORD_VERSION = 6;\nexport const CURRENT_RECORD_FORMAT = \"effect-agent/thread@6\";\n\n/** Durable fact and execution-command schemas. Unsupported controls fail before execution. */\nexport const KnownRecordPayload = Schema.Union([\n ThreadCreated,\n UserInputRecorded,\n RunStartedRecord,\n RunDurationExhausted,\n RunPolicyUsageReserved,\n ModelCompleted,\n ModelResponseRecorded,\n ToolCallSettled,\n ToolCallUnknown,\n ToolCallResolved,\n ToolStepSettled,\n ToolApprovalRequested,\n ToolApprovalDecided,\n ModelResponseInterrupted,\n ModelCallAborted,\n CompactionCreated,\n RunFailed,\n RunCompleted,\n AbortRequested,\n SubmissionSettledRecord,\n SubagentRequested,\n SubagentStarted,\n SubagentJoined,\n SubagentLineageRecorded,\n WorkerInputRequested,\n WorkerStopRequested,\n WorkHandoffCompleted,\n WorkerOriginRecorded,\n WorkerInputCompleted,\n WorkerInputRefused,\n WorkerReportPrepared,\n AgentUpdateEmitted,\n WorkerReportRefused,\n PeerMessagePrepared,\n SubtreeBudgetReserved,\n RepairAnnotated,\n RunContextRecorded,\n RunContinuation,\n]);\n\n/** This format accepts only understood facts; unknown control cannot grant permission. */\nexport const CanonicalRecordPayload = KnownRecordPayload;\n\nexport type CanonicalRecordPayload = typeof CanonicalRecordPayload.Type;\n\n/**\n * Versioned durable fact. Retained history acquires Thread ordering at its atomic commit;\n * active operational facts keep their identities without a canonical sequence.\n */\nexport class RecordEnvelope extends Schema.Class<RecordEnvelope>(\n \"@effect-agent/thread/RecordEnvelope\",\n)({\n recordId: RecordId,\n family: Schema.Literal(\"thread\"),\n schemaVersion: Schema.Literal(1),\n createdAt: Schema.DateTimeUtcFromString,\n deploymentId: DeploymentId,\n payload: CanonicalRecordPayload,\n}) {}\n\n/** Backward-compatible domain name for a canonical record. */\nexport const CanonicalRecord = RecordEnvelope;\nexport type CanonicalRecord = RecordEnvelope;\n\n/** One non-empty, bounded, idempotent atomic append unit. */\nexport class CanonicalBatch extends Schema.Class<CanonicalBatch>(\n \"@effect-agent/thread/CanonicalBatch\",\n)({\n batchId: BatchId,\n producerId: ProducerId,\n records: Schema.NonEmptyArray(RecordEnvelope).check(Schema.isMaxLength(256)),\n}) {}\n\n/**\n * A committed record with its Thread ordering and opaque resumable observation cursor.\n */\nexport class CanonicalRecordEnvelope extends Schema.Class<CanonicalRecordEnvelope>(\n \"@effect-agent/thread/CanonicalRecordEnvelope\",\n)({\n threadId: ThreadId,\n batchId: BatchId,\n sequence: CanonicalSequence,\n offset: ObservationOffset,\n record: RecordEnvelope,\n}) {}\n\n/** Read-only history of validated facts. Original inputs establish Run view boundaries. */\nexport const PromptRecordPayload = Schema.TaggedUnion({\n UserInputRecorded: {\n runId: UserInputRecorded.fields.runId,\n kind: UserInputRecorded.fields.kind,\n submissionId: UserInputRecorded.fields.submissionId,\n },\n ModelCompleted: {\n runId: RunId,\n history: Schema.optionalKey(HistoryPrompt),\n },\n ModelResponseRecorded: {\n runId: RunId,\n turn: TurnNumber,\n messages: HistoryPrompt,\n runScopedPrefixLength: ModelResponseRecorded.fields.runScopedPrefixLength,\n },\n ToolCallSettled: {\n runId: RunId,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n result: Schema.Json,\n isFailure: Schema.Boolean,\n },\n CompactionCreated: CompactionCreated.fields,\n RunCompleted: { runId: RunId },\n RunFailed: { runId: RunId },\n SubmissionSettled: {\n runId: Schema.optionalKey(RunId),\n submissionId: SubmissionId,\n outcome: SettlementOutcome,\n },\n});\n\n/** Native selections and the projection decoder share this single list of supported facts. */\nexport const PROMPT_EVIDENCE_TAGS: ReadonlyArray<keyof typeof PromptRecordPayload.cases> =\n Struct.keys(PromptRecordPayload.cases);\n\nexport const PromptRecord = Schema.Struct({ recordId: RecordId, payload: PromptRecordPayload });\nexport type PromptRecord = typeof PromptRecord.Type;\n\n/** Not integrity evidence: omitted canonical wire must be read through the full record port. */\nexport const PromptRecordEnvelope = Schema.Struct({\n threadId: ThreadId,\n sequence: CanonicalSequence,\n record: PromptRecord,\n});\n\nexport type PromptRecordEnvelope = typeof PromptRecordEnvelope.Type;\n\nexport const CURRENT_CANONICAL_SCHEMA_VERSION = 1 as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,SAAS,YAAY,MAAuC;CAC1D,QAAQ,KAAK,MAAb;EACE,KAAK,QACH,OAAO,OAAO,SAAS,IAAI;EAC7B,KAA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