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

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 (143) hide show
  1. package/dist/{AgentRuntime-B64362Id.d.mts → AgentRuntime-BMzrJos6.d.mts} +2 -2
  2. package/dist/{AgentRuntime-Cdvqw7l_.mjs → AgentRuntime-BWOnNc0d.mjs} +78 -42
  3. package/dist/AgentRuntime-BWOnNc0d.mjs.map +1 -0
  4. package/dist/{DurableAgentRuntime-DbUvZHDZ.mjs → DurableAgentRuntime-BE_OjQjz.mjs} +471 -252
  5. package/dist/DurableAgentRuntime-BE_OjQjz.mjs.map +1 -0
  6. package/dist/{DurableFailpoint-DQJet828.d.mts → DurableFailpoint-mx3-nsxU.d.mts} +3 -3
  7. package/dist/{EventSource-D6PAAEyK.d.mts → EventSource-BZ73J0s5.d.mts} +3 -3
  8. package/dist/{PreparedInputAdmission-omMbwd--.d.mts → PreparedInputAdmission-BkeI-Xvr.d.mts} +4 -4
  9. package/dist/{Records-CV49DgQK.d.mts → Records-BIiRLqlz.d.mts} +92 -128
  10. package/dist/{Records-BAutSSnJ.mjs → Records-DR1xtbXY.mjs} +35 -8
  11. package/dist/Records-DR1xtbXY.mjs.map +1 -0
  12. package/dist/{RunJournal-DRRRZmG7.mjs → RunJournal-DNs3PM4K.mjs} +80 -23
  13. package/dist/RunJournal-DNs3PM4K.mjs.map +1 -0
  14. package/dist/{RunOptions-Clj8cLsp.d.mts → RunOptions-Bruk54SE.d.mts} +13 -4
  15. package/dist/{Schedule-DePbGfgd.d.mts → Schedule-BNFlluAl.d.mts} +2 -2
  16. package/dist/{Scheduling-C3QpYn0W.mjs → Scheduling-HFH0pST1.mjs} +2 -2
  17. package/dist/{Scheduling-C3QpYn0W.mjs.map → Scheduling-HFH0pST1.mjs.map} +1 -1
  18. package/dist/{Subagent-Cbfzylz1.mjs → Subagent-C2s8PFrd.mjs} +2 -2
  19. package/dist/{Subagent-Cbfzylz1.mjs.map → Subagent-C2s8PFrd.mjs.map} +1 -1
  20. package/dist/{Subagent-Bm1dRecN.d.mts → Subagent-m7ywTCe4.d.mts} +3 -3
  21. package/dist/{Subscription-BR_8Cxh3.d.mts → Subscription-BCQ3L9Zp.d.mts} +3 -3
  22. package/dist/{SubscriptionInput-B95sQbuk.d.mts → SubscriptionInput-Cqu4_RW3.d.mts} +3 -3
  23. package/dist/{ToolReconciler-DQVaJfpE.d.mts → ToolReconciler-BmVRAHKs.d.mts} +8 -4
  24. package/dist/agent-registration-cXpB8cBU.mjs +199 -0
  25. package/dist/agent-registration-cXpB8cBU.mjs.map +1 -0
  26. package/dist/capabilities/Commands.d.mts +1 -1
  27. package/dist/capabilities/RunHooks.d.mts +1 -1
  28. package/dist/capabilities/Subagent.d.mts +1 -1
  29. package/dist/capabilities/Subagent.mjs +1 -1
  30. package/dist/durable/ActivityStore.d.mts +1 -1
  31. package/dist/durable/ActivityStore.mjs +1 -1
  32. package/dist/durable/Admin.d.mts +1 -1
  33. package/dist/durable/Admin.mjs +12 -10
  34. package/dist/durable/Admin.mjs.map +1 -1
  35. package/dist/durable/AgentRegistration.d.mts +2 -2
  36. package/dist/durable/AgentRegistration.mjs +4 -8
  37. package/dist/durable/AgentRegistration.mjs.map +1 -1
  38. package/dist/durable/Certification.d.mts +2 -2
  39. package/dist/durable/CommittedActivity.d.mts +1 -1
  40. package/dist/durable/CommittedActivity.mjs +1 -1
  41. package/dist/durable/Digest.d.mts +1 -1
  42. package/dist/durable/Digest.mjs +1 -1
  43. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  44. package/dist/durable/DurableAgentRuntime.mjs +1 -1
  45. package/dist/durable/DurableFailpoint.d.mts +1 -1
  46. package/dist/durable/DurableFailpoint.mjs +2 -0
  47. package/dist/durable/DurableFailpoint.mjs.map +1 -1
  48. package/dist/durable/DurableFailpointTestControl.d.mts +1 -1
  49. package/dist/durable/EventSource.d.mts +1 -1
  50. package/dist/durable/EventSource.mjs +1 -1
  51. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  52. package/dist/durable/GitHubWorkflowSource.mjs +1 -1
  53. package/dist/durable/MessageDelivery.d.mts +3 -3
  54. package/dist/durable/MessageDelivery.mjs +1 -1
  55. package/dist/durable/MessageDeliveryStoreConformance.d.mts +39 -39
  56. package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
  57. package/dist/durable/PersistentHistory.d.mts +1 -1
  58. package/dist/durable/PersistentHistory.mjs +2 -2
  59. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  60. package/dist/durable/Records.d.mts +2 -2
  61. package/dist/durable/Records.mjs +2 -2
  62. package/dist/durable/Recovery.d.mts +1 -1
  63. package/dist/durable/Recovery.mjs +9 -9
  64. package/dist/durable/Recovery.mjs.map +1 -1
  65. package/dist/durable/RunJournal.d.mts +2 -2
  66. package/dist/durable/RunJournal.mjs +2 -2
  67. package/dist/durable/Schedule.d.mts +1 -1
  68. package/dist/durable/Schedule.mjs +1 -1
  69. package/dist/durable/ScheduleStoreConformance.d.mts +1 -1
  70. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  71. package/dist/durable/ScheduleTransition.d.mts +1 -1
  72. package/dist/durable/ScheduleTransition.mjs +1 -1
  73. package/dist/durable/Scheduling.d.mts +2 -2
  74. package/dist/durable/Scheduling.mjs +1 -1
  75. package/dist/durable/SqlStorageV2Upgrade.d.mts +2 -2
  76. package/dist/durable/SqlStorageV2Upgrade.mjs +1 -1
  77. package/dist/durable/SqlSubscriptionStore.d.mts +2 -2
  78. package/dist/durable/SqlSubscriptionStore.mjs +1 -1
  79. package/dist/durable/SubmissionLedger.d.mts +1 -1
  80. package/dist/durable/SubmissionLedger.mjs +14 -13
  81. package/dist/durable/SubmissionLedger.mjs.map +1 -1
  82. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  83. package/dist/durable/SubmissionLedgerConformance.mjs +9 -2
  84. package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -1
  85. package/dist/durable/SubmissionStatus.d.mts +1 -1
  86. package/dist/durable/Subscription.d.mts +1 -1
  87. package/dist/durable/Subscription.mjs +1 -1
  88. package/dist/durable/SubscriptionInput.d.mts +1 -1
  89. package/dist/durable/SubscriptionInput.mjs +2 -2
  90. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  91. package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
  92. package/dist/durable/SubscriptionTools.d.mts +3 -3
  93. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  94. package/dist/durable/SubscriptionTransition.mjs +1 -1
  95. package/dist/durable/Subscriptions.d.mts +5 -5
  96. package/dist/durable/Subscriptions.mjs +1 -1
  97. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  98. package/dist/durable/ThreadContextHistory.mjs +1 -1
  99. package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
  100. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  101. package/dist/durable/ThreadInvariants.d.mts +4 -2
  102. package/dist/durable/ThreadInvariants.mjs +49 -3
  103. package/dist/durable/ThreadInvariants.mjs.map +1 -1
  104. package/dist/durable/ThreadProjection.d.mts +1 -1
  105. package/dist/durable/ThreadProjection.mjs +1 -1
  106. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  107. package/dist/durable/ThreadStore.d.mts +1 -1
  108. package/dist/durable/ThreadStore.mjs +1 -1
  109. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  110. package/dist/durable/ThreadStoreConformance.mjs +1 -1
  111. package/dist/durable/ToolReconciler.d.mts +1 -1
  112. package/dist/durable/ToolReconciler.mjs +9 -5
  113. package/dist/durable/ToolReconciler.mjs.map +1 -1
  114. package/dist/durable/WorkerHost.d.mts +1 -1
  115. package/dist/engine/AgentRuntime.d.mts +1 -1
  116. package/dist/engine/AgentRuntime.mjs +1 -1
  117. package/dist/engine/RunOptions.d.mts +1 -1
  118. package/dist/engine/RunOptions.mjs.map +1 -1
  119. package/dist/index.d.mts +11 -11
  120. package/dist/index.mjs +6 -6
  121. package/package.json +1 -1
  122. package/src/durable/Admin.ts +20 -11
  123. package/src/durable/AgentRegistration.ts +1 -5
  124. package/src/durable/DurableAgentRuntime.ts +947 -464
  125. package/src/durable/DurableFailpoint.ts +2 -0
  126. package/src/durable/Records.ts +30 -5
  127. package/src/durable/Recovery.ts +8 -8
  128. package/src/durable/RunJournal.ts +128 -51
  129. package/src/durable/SubmissionLedger.ts +13 -12
  130. package/src/durable/SubmissionLedgerConformance.ts +13 -2
  131. package/src/durable/ThreadInvariants.ts +70 -5
  132. package/src/durable/ToolReconciler.ts +7 -3
  133. package/src/durable/internal/agent-registration.ts +65 -414
  134. package/src/durable/internal/messaging-host.ts +0 -2
  135. package/src/durable/internal/worker-host.ts +34 -96
  136. package/src/engine/RunOptions.ts +13 -3
  137. package/src/engine/internal/agent-runtime.ts +160 -106
  138. package/dist/AgentRuntime-Cdvqw7l_.mjs.map +0 -1
  139. package/dist/DurableAgentRuntime-DbUvZHDZ.mjs.map +0 -1
  140. package/dist/Records-BAutSSnJ.mjs.map +0 -1
  141. package/dist/RunJournal-DRRRZmG7.mjs.map +0 -1
  142. package/dist/agent-registration-CXGDwvJH.mjs +0 -379
  143. package/dist/agent-registration-CXGDwvJH.mjs.map +0 -1
@@ -78,7 +78,9 @@ var Records_exports = /* @__PURE__ */ __exportAll({
78
78
  ToolCallResolved: () => ToolCallResolved,
79
79
  ToolCallSettled: () => ToolCallSettled,
80
80
  ToolCallUnknown: () => ToolCallUnknown,
81
+ ToolOperation: () => ToolOperation,
81
82
  ToolStepSettled: () => ToolStepSettled,
83
+ ToolUnavailable: () => ToolUnavailable,
82
84
  UserInputRecorded: () => UserInputRecorded,
83
85
  WorkerAdmission: () => WorkerAdmission,
84
86
  WorkerInputCompleted: () => WorkerInputCompleted,
@@ -199,14 +201,14 @@ var DefinitionDigestInput = class extends Schema.Class("@effect-agent/thread/Def
199
201
  model: PersistedJson,
200
202
  tools: PersistedJson
201
203
  }) {};
202
- /** The contracts a retained Run may decode or execute, independent of its deployment. */
204
+ /** Admission-time operation fingerprints. Agent fingerprints remain immutable evidence only. */
203
205
  var ReplayContract = class extends Schema.Class("@effect-agent/thread/ReplayContract")({
204
206
  agent: Digest,
205
- /** Agent semantics and output/completion codecs; the saved input is checked separately. */
207
+ /** Retained for reading earlier admissions; never selects executable code. */
206
208
  agentBehavior: Schema.optionalKey(Digest),
207
209
  tools: Schema.Record(Schema.String, Digest)
208
210
  }) {};
209
- /** Digests identify admission exactly; replay contracts separately authorize continuation. */
211
+ /** Digests identify admission exactly; only an unfinished operation needs replay compatibility. */
210
212
  var DefinitionDigests = class extends Schema.Class("@effect-agent/thread/DefinitionDigests")({
211
213
  agent: Digest,
212
214
  model: Digest,
@@ -262,6 +264,24 @@ var ToolCallSettled = class extends Schema.TaggedClass("@effect-agent/thread/Too
262
264
  /** Explicit engine evidence, never inferred from Tool result data. */
263
265
  budgetRejected: Schema.optionalKey(Schema.Literal(true))
264
266
  }) {};
267
+ /** Compact execution evidence committed with a declaration, before any handler can start. */
268
+ var ToolOperation = class extends Schema.Class("@effect-agent/thread/ToolOperation")({
269
+ toolCallId: ToolCallId,
270
+ toolName: BoundedName,
271
+ executionClass: Schema.Literals([
272
+ "readonly",
273
+ "idempotent",
274
+ "uncertain"
275
+ ]),
276
+ executionKind: ToolExecutionKind,
277
+ replay: Digest
278
+ }) {};
279
+ /** A retired call's runtime result. Unavailable readonly work may already have been observed. */
280
+ var ToolUnavailable = class extends Schema.TaggedClass()("ToolUnavailable", {
281
+ toolName: BoundedName,
282
+ execution: Schema.Literals(["not-executed", "unavailable"]),
283
+ message: BoundedText
284
+ }) {};
265
285
  /**
266
286
  * One committed model Turn. `messages` carries the Schema-encoded Effect AI Prompt messages this
267
287
  * Turn appended (assistant response plus any tool-call declarations), committed atomically at the
@@ -269,6 +289,8 @@ var ToolCallSettled = class extends Schema.TaggedClass("@effect-agent/thread/Too
269
289
  * `messagesDigest` pins the exact encoded content.
270
290
  */
271
291
  const ModelResponseRecordedFields = Schema.Struct({
292
+ /** Original operation identity/semantics, independent of later Agent and toolbox changes. */
293
+ toolOperations: Schema.optionalKey(Schema.Array(ToolOperation)),
272
294
  /** Explicit pre-execution failures, committed with the original arguments before any approval. */
273
295
  toolParameterRejections: Schema.optionalKey(Schema.Array(ToolParameterRejection)),
274
296
  toolExposure: Schema.optionalKey(Snapshot),
@@ -279,8 +301,9 @@ const ModelResponseRecordedFields = Schema.Struct({
279
301
  messagesDigest: Digest,
280
302
  /**
281
303
  * Number of leading messages that belong only to this Run's evaluated instructions and wake
282
- * input. They remain canonical and are visible while recovering this Run, but later Runs omit
283
- * them from their model-facing history. Records without this field retain their full history.
304
+ * input. They remain canonical. Continuations replace the instruction messages with current
305
+ * instructions while retaining user input; later Runs also retain that original user intent.
306
+ * Records without this field retain their full history.
284
307
  */
285
308
  runScopedPrefixLength: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),
286
309
  /**
@@ -315,7 +338,9 @@ var ToolCallPrepared = class extends Schema.TaggedClass("@effect-agent/thread/To
315
338
  parameters: PersistedJson,
316
339
  parametersDigest: Digest,
317
340
  /** Absent legacy evidence grants no delegation replay authority. */
318
- executionKind: Schema.optionalKey(ToolExecutionKind)
341
+ executionKind: Schema.optionalKey(ToolExecutionKind),
342
+ executionClass: Schema.optionalKey(ToolOperation.fields.executionClass),
343
+ replay: Schema.optionalKey(Digest)
319
344
  }) {};
320
345
  /** Monotonic reservations charged before programmatic execution or grace finalization. */
321
346
  var RunPolicyUsageReserved = class extends Schema.TaggedClass()("RunPolicyUsageReserved", {
@@ -439,6 +464,8 @@ var RunFailed = class extends Schema.TaggedClass("@effect-agent/thread/RunFailed
439
464
  const RunCompletedFields = Schema.Struct({
440
465
  runId: RunId,
441
466
  output: PersistedJson,
467
+ /** Integrity of validated terminal values, independent of future application codecs. */
468
+ resultDigest: Schema.optionalKey(Digest),
442
469
  /** Application disposition captured with an ordinary completion. */
443
470
  runDisposition: Schema.optionalKey(PersistedJson),
444
471
  /** Honest soft-landing marker, present exactly when `exhausted` is present. */
@@ -810,6 +837,6 @@ var CanonicalRecordEnvelope = class extends Schema.Class("@effect-agent/thread/C
810
837
  }) {};
811
838
  const CURRENT_CANONICAL_SCHEMA_VERSION = 1;
812
839
  //#endregion
813
- export { ToolCallSettled as $, Records_exports as A, SubagentJoined as B, ObservationOffset as C, ProducerId as D, ProducerEpoch as E, RunFailed as F, SubmissionSettledRecord as G, SubagentRequested as H, RunPolicyUsageReserved as I, ToolApprovalDecided as J, SubtreeBudgetReserved as K, RunStartedRecord as L, ReplayContract as M, RunCompleted as N, RecordEnvelope as O, RunDurationExhausted as P, ToolCallResolved as Q, SettlementFailureDiagnostic as R, ModelResponseRecorded as S, PersistedJson as T, SubagentStarted as U, SubagentLineageRecorded as V, SubmissionSettled as W, ToolCallPrepared as X, ToolApprovalRequested as Y, ToolCallResolution as Z, MAX_PERSISTED_JSON_COLLECTION_LENGTH as _, CURRENT_CANONICAL_SCHEMA_VERSION as a, WorkerInputRequested as at, ModelCompleted as b, CanonicalRecordEnvelope as c, WorkerReportPrepared as ct, CompactionCreated as d, strictSchema as dt, ToolCallUnknown as et, DefinitionDigestInput as f, MAX_PERSISTED_JSON_BYTES as g, Digest as h, BatchId as i, WorkerInputCompleted as it, RepairAnnotated as j, RecordId as k, CanonicalRecordPayload as l, WorkerReportRefused as lt, DeploymentId as m, AgentUpdateEmitted as n, UserInputRecorded as nt, CanonicalBatch as o, WorkerOrigin as ot, DefinitionDigests as p, ThreadCreated as q, ApprovalDecision as r, WorkerAdmission as rt, CanonicalRecord as s, WorkerOriginRecorded as st, AbortRequested as t, ToolStepSettled as tt, CanonicalSequence as u, WorkerReportingIntent as ut, MAX_PERSISTED_JSON_DEPTH as v, PeerMessagePrepared as w, ModelResponseInterrupted as x, MAX_PERSISTED_JSON_NODES as y, SettlementOutcome as z };
840
+ export { ToolCallSettled as $, Records_exports as A, SubagentJoined as B, ObservationOffset as C, ProducerId as D, ProducerEpoch as E, RunFailed as F, SubmissionSettledRecord as G, SubagentRequested as H, RunPolicyUsageReserved as I, ToolApprovalDecided as J, SubtreeBudgetReserved as K, RunStartedRecord as L, ReplayContract as M, RunCompleted as N, RecordEnvelope as O, RunDurationExhausted as P, ToolCallResolved as Q, SettlementFailureDiagnostic as R, ModelResponseRecorded as S, PersistedJson as T, SubagentStarted as U, SubagentLineageRecorded as V, SubmissionSettled as W, ToolCallPrepared as X, ToolApprovalRequested as Y, ToolCallResolution as Z, MAX_PERSISTED_JSON_COLLECTION_LENGTH as _, CURRENT_CANONICAL_SCHEMA_VERSION as a, WorkerAdmission as at, ModelCompleted as b, CanonicalRecordEnvelope as c, WorkerOrigin as ct, CompactionCreated as d, WorkerReportRefused as dt, ToolCallUnknown as et, DefinitionDigestInput as f, WorkerReportingIntent as ft, MAX_PERSISTED_JSON_BYTES as g, Digest as h, BatchId as i, UserInputRecorded as it, RepairAnnotated as j, RecordId as k, CanonicalRecordPayload as l, WorkerOriginRecorded as lt, DeploymentId as m, AgentUpdateEmitted as n, ToolStepSettled as nt, CanonicalBatch as o, WorkerInputCompleted as ot, DefinitionDigests as p, strictSchema as pt, ThreadCreated as q, ApprovalDecision as r, ToolUnavailable as rt, CanonicalRecord as s, WorkerInputRequested as st, AbortRequested as t, ToolOperation as tt, CanonicalSequence as u, WorkerReportPrepared as ut, MAX_PERSISTED_JSON_DEPTH as v, PeerMessagePrepared as w, ModelResponseInterrupted as x, MAX_PERSISTED_JSON_NODES as y, SettlementOutcome as z };
814
841
 
815
- //# sourceMappingURL=Records-BAutSSnJ.mjs.map
842
+ //# sourceMappingURL=Records-DR1xtbXY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Records-DR1xtbXY.mjs","names":[],"sources":["../src/core/internal/strict-schema.ts","../src/durable/Records.ts"],"sourcesContent":["import { Schema, SchemaParser, SchemaTransformation } from \"effect\";\n\n/** Keep strict parsing on nested values even when an outer parser uses its defaults. */\nexport const strictSchema = <S extends Schema.Top>(schema: S) =>\n Schema.declareConstructor<S[\"Type\"], S[\"Encoded\"]>()(\n [schema],\n ([codec]) =>\n (value, _ast, options) =>\n SchemaParser.decodeUnknownEffect(codec)(value, { ...options, onExcessProperty: \"error\" }),\n {\n toCodecJson: ([codec]) =>\n Schema.link<S[\"Encoded\"]>()(codec, SchemaTransformation.passthrough()),\n },\n );\n","import { Option, Schema } from \"effect\";\nimport { Prompt } from \"effect/unstable/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 {\n AgentId,\n AttemptId,\n ThreadId,\n DelegationId,\n ReceiptId,\n RunId,\n SettlementId,\n SubmissionId,\n ToolCallId,\n TurnId,\n} from \"../core/Identifiers.ts\";\nimport { strictSchema } from \"../core/internal/strict-schema.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { IdempotencyKey, Principal } 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 } from \"../core/Worker.ts\";\nimport { ContextHandoff } from \"../engine/ContextWindow.ts\";\n\nconst identifier = <const Name extends string>(name: Name) =>\n Schema.NonEmptyString.pipe(Schema.brand(`@effect-agent/thread/${name}`));\n\n/** Stable identity of one canonical record. */\nexport const RecordId = identifier(\"RecordId\");\nexport type RecordId = typeof RecordId.Type;\n\n/** Stable idempotency identity of one atomic append. */\nexport const BatchId = identifier(\"BatchId\");\nexport type BatchId = typeof BatchId.Type;\n\n/** Identity of the deployment that produced a record. */\nexport const DeploymentId = identifier(\"DeploymentId\");\nexport type DeploymentId = typeof DeploymentId.Type;\n\n/** Identity of a fenced canonical-log producer. */\nexport const ProducerId = identifier(\"ProducerId\");\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 = identifier(\"ObservationOffset\");\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\n/** Monotonic fencing epoch for a Thread producer. */\nexport const ProducerEpoch = Schema.Natural.pipe(\n Schema.brand(\"@effect-agent/thread/ProducerEpoch\"),\n);\n\nexport type ProducerEpoch = typeof ProducerEpoch.Type;\n\nconst BoundedText = Schema.String.check(Schema.isMaxLength(64 * 1024));\nconst BoundedName = Schema.NonEmptyString.check(Schema.isMaxLength(256));\n\n/** Stable, non-empty failure classification carried by a failed durable Settlement. */\nconst SettlementFailureTag = Schema.NonEmptyString.check(Schema.isMaxLength(256));\n\n/** Diagnostic text is bounded independently from the broader persisted JSON envelope. */\nconst SettlementFailureMessage = Schema.String.check(Schema.isMaxLength(16 * 1024));\n\n/**\n * The complete generic diagnostic allowed on a failed durable Settlement. It deliberately has\n * no raw Cause, stack, provider payload, or application-specific fields; those values can carry\n * secrets and do not form a stable cross-process contract.\n */\nexport const SettlementFailureDiagnostic = Schema.Struct({\n errorTag: SettlementFailureTag,\n message: SettlementFailureMessage,\n}).pipe(\n strictSchema,\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\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\nconst isPersistedJson = (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 > MAX_PERSISTED_JSON_DEPTH || ++nodes > MAX_PERSISTED_JSON_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 > MAX_PERSISTED_JSON_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 > MAX_PERSISTED_JSON_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 return encoded !== undefined && utf8ByteLength(encoded) <= MAX_PERSISTED_JSON_BYTES;\n } catch {\n return false;\n }\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/** 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 may include the exact encoded Prompt suffix of the\n * successful Run; durable execution instead journals individual ModelResponseRecorded Turns.\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 }).check(\n Schema.makeFilter(\n (record) => record.messages === undefined || isPersistedPromptMessages(record.messages),\n { title: \"Retained Run messages are Schema-encoded Effect AI Prompt messages\" },\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/** 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 * `messagesDigest` pins the exact encoded content.\n */\nconst ModelResponseRecordedFields = Schema.Struct({\n /** Original operation identity/semantics, independent of later Agent and toolbox changes. */\n toolOperations: Schema.optionalKey(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 messagesDigest: Digest,\n /**\n * Number of leading messages that belong only to this Run's evaluated instructions and wake\n * input. They remain canonical. Continuations replace the instruction messages with current\n * instructions while retaining user input; later Runs also retain that original user intent.\n * Records without this field retain their full 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. Absent on legacy\n * records, whose aggregate totals below retain the old resume behavior.\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 compatibility fields used by older projections. */\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 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/**\n * One approved uncertain/idempotent ordinary Tool Call made durable BEFORE any handler starts\n * (durability §10). `parameters` is the Schema-encoded wire form of the declared call and\n * `parametersDigest` pins it; recovery that sees this record without a matching `ToolCallSettled`\n * (or `ToolCallUnknown` → `ToolCallResolved`) must reconcile or mark unknown, never silently\n * replay (DUR-009). Ordinary `readonly`-class Tools never produce this record. Delegation\n * classification is always prepared, including for a Tool annotated `readonly`.\n */\nexport class ToolCallPrepared extends Schema.TaggedClass<ToolCallPrepared>(\n \"@effect-agent/thread/ToolCallPrepared\",\n)(\"ToolCallPrepared\", {\n runId: RunId,\n turnId: TurnId,\n turn: TurnNumber,\n toolCallId: ToolCallId,\n toolName: BoundedName,\n parameters: PersistedJson,\n parametersDigest: Digest,\n /** Absent legacy evidence grants no delegation replay authority. */\n executionKind: Schema.optionalKey(ToolExecutionKind),\n executionClass: Schema.optionalKey(ToolOperation.fields.executionClass),\n replay: Schema.optionalKey(Digest),\n}) {}\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 prepared 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}) {}\n\n/** The two-valued approval decision family shared by canonical records and ledger intents. */\nexport const ApprovalDecision = Schema.Literals([\"approved\", \"denied\"]);\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 * First-class interruption audit (durability §9): appended by a superseding Attempt before it\n * re-invokes the model for a Turn whose prior owner died without a complete canonical response.\n * Duplicate provider cost is thereby possible AND observable in canonical history.\n */\nexport class ModelResponseInterrupted extends Schema.TaggedClass<ModelResponseInterrupted>(\n \"@effect-agent/thread/ModelResponseInterrupted\",\n)(\"ModelResponseInterrupted\", {\n runId: RunId,\n supersededEpoch: ProducerEpoch,\n attemptId: AttemptId,\n reason: BoundedText,\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 resultDigest: Schema.optionalKey(Digest),\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\"]);\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 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 digests pinning the verified child\n * result and the bounded projected parent result, 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 childResultDigest: Digest,\n projectedResultDigest: Digest,\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 /** Omitted preserves existing application-mapped reports. */\n mode: Schema.optionalKey(Schema.Literal(\"standard\")),\n sourceDigests: DefinitionDigests,\n destinationDelegationId: Schema.optionalKey(DelegationId),\n});\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 /** Omitted retains source-subtree funding; worker-run renews only for a new native Run. */\n budgetScope: Schema.optionalKey(WorkerBudgetScope),\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 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/** 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 },\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 \"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 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 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/**\n * Current private-development canonical payload family. Phase 5 adds the seven durable-Tool tags\n * (prepared/unknown/resolved/step/approval-request/approval-decision/interrupted) additively; S2\n * adds the four durable-Subagent tags (requested/started/joined/lineage) additively, so the\n * envelope keeps `schemaVersion: 1` (P4 precedent for additive payload tags).\n */\nexport const CanonicalRecordPayload = Schema.Union([\n ThreadCreated,\n UserInputRecorded,\n RunStartedRecord,\n RunDurationExhausted,\n RunPolicyUsageReserved,\n ModelCompleted,\n ModelResponseRecorded,\n ToolCallPrepared,\n ToolCallSettled,\n ToolCallUnknown,\n ToolCallResolved,\n ToolStepSettled,\n ToolApprovalRequested,\n ToolApprovalDecided,\n ModelResponseInterrupted,\n CompactionCreated,\n RunFailed,\n RunCompleted,\n AbortRequested,\n SubmissionSettledRecord,\n SubagentRequested,\n SubagentStarted,\n SubagentJoined,\n SubagentLineageRecorded,\n WorkerInputRequested,\n WorkerOriginRecorded,\n WorkerInputCompleted,\n WorkerReportPrepared,\n AgentUpdateEmitted,\n WorkerReportRefused,\n PeerMessagePrepared,\n SubtreeBudgetReserved,\n RepairAnnotated,\n]);\n\nexport type CanonicalRecordPayload = typeof CanonicalRecordPayload.Type;\n\n/**\n * Versioned record envelope stored in an atomic batch. Thread ordering is assigned only\n * when the batch is committed.\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\nexport const CURRENT_CANONICAL_SCHEMA_VERSION = 1 as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAGA,MAAa,gBAAsC,WACjD,OAAO,mBAA4C,CAAC,CAClD,CAAC,MAAM,IACN,CAAC,YACC,OAAO,MAAM,YACZ,aAAa,oBAAoB,KAAK,CAAC,CAAC,OAAO;CAAE,GAAG;CAAS,kBAAkB;AAAQ,CAAC,GAC5F,EACE,cAAc,CAAC,WACb,OAAO,KAAmB,CAAC,CAAC,OAAO,qBAAqB,YAAY,CAAC,EACzE,CACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACwBF,MAAM,cAAyC,SAC7C,OAAO,eAAe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C/B,eAAe,OAAO,QAAQ,CAAC;CAC/B,WAAW,OAAO;CAClB,cAAc;CACd,SAAS;AACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,kBAAkB;;AAI/B,IAAa,iBAAb,cAAoC,OAAO,MACzC,qCACF,CAAC,CAAC;CACA,SAAS;CACT,YAAY;CACZ,SAAS,OAAO,cAAc,cAAc,CAAC,CAAC,MAAM,OAAO,YAAY,GAAG,CAAC;AAC7E,CAAC,CAAC,CAAC,CAAC;;;;AAKJ,IAAa,0BAAb,cAA6C,OAAO,MAClD,8CACF,CAAC,CAAC;CACA,UAAU;CACV,SAAS;CACT,UAAU;CACV,QAAQ;CACR,QAAQ;AACV,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAa,mCAAmC"}
@@ -4,7 +4,7 @@ import { IdempotencyKey } from "./core/Receipt.mjs";
4
4
  import { ModelCallUsage, summarizeModelUsage } from "./core/Usage.mjs";
5
5
  import { f as contextWindowId, n as COMPACTION_SUMMARY_PREFIX, p as contextWindowMessage, t as CLEARED_TOOL_RESULT } from "./compaction-C2OTceKw.mjs";
6
6
  import { RunPolicyUsage } from "./core/RunPolicyUsage.mjs";
7
- import { $ as ToolCallSettled, N as RunCompleted, O as RecordEnvelope, S as ModelResponseRecorded, T as PersistedJson, d as CompactionCreated, i as BatchId, k as RecordId, o as CanonicalBatch } from "./Records-BAutSSnJ.mjs";
7
+ import { $ as ToolCallSettled, N as RunCompleted, O as RecordEnvelope, S as ModelResponseRecorded, T as PersistedJson, d as CompactionCreated, i as BatchId, k as RecordId, o as CanonicalBatch } from "./Records-DR1xtbXY.mjs";
8
8
  import { digestJson } from "./durable/Digest.mjs";
9
9
  import { Prompt } from "effect/unstable/ai";
10
10
  import { Effect, Schema, Stream } from "effect";
@@ -80,6 +80,7 @@ var RunJournal_exports = /* @__PURE__ */ __exportAll({
80
80
  projectRunJournalStream: () => projectRunJournalStream,
81
81
  promptFromCanonicalRecords: () => promptFromCanonicalRecords,
82
82
  runCompletedRecordId: () => runCompletedRecordId,
83
+ runCompletionDigest: () => runCompletionDigest,
83
84
  runDurationBatchId: () => runDurationBatchId,
84
85
  runDurationRecordId: () => runDurationRecordId,
85
86
  runIdForSubmission: () => runIdForSubmission,
@@ -305,7 +306,6 @@ const declaredApplicationToolCallIds = (prompt) => {
305
306
  }
306
307
  return ids;
307
308
  };
308
- const withoutApplicationToolCallMessages = (prompt) => prompt.content.filter((message) => message.role !== "assistant" || !message.content.some((part) => part.type === "tool-call" && !part.providerExecuted));
309
309
  /**
310
310
  * Phase 5 audit tags that are prompt-transparent: they carry durability evidence (preparation,
311
311
  * unknown marking, resolution, Step results, approvals, interruption) but contribute nothing to
@@ -515,6 +515,7 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
515
515
  policyUsage.consecutiveToolFailures = result.isFailure ? policyUsage.consecutiveToolFailures + 1 : 0;
516
516
  }
517
517
  });
518
+ const historicalResults = /* @__PURE__ */ new Map();
518
519
  let pendingToolOrder = /* @__PURE__ */ new Map();
519
520
  const flushTools = Effect.fn("RunJournal.flushTools")(function* (current) {
520
521
  if (current.pendingTools.length === 0) return current;
@@ -560,12 +561,27 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
560
561
  }
561
562
  emitSummary();
562
563
  if (payload._tag === "ToolCallSettled") {
563
- if (payload.runId !== ownerRunId && incompleteToolCalls.has(envelope.record.recordId)) {
564
+ if (payload.runId !== ownerRunId) {
565
+ const slot = historicalResults.get(envelope.record.recordId);
566
+ if (slot === void 0) return yield* journalError("Historical Tool result has no matching declaration");
567
+ const declared = slot.parts[slot.partIndex];
568
+ if (declared?.id !== payload.toolCallId || declared.name !== payload.toolName) return yield* journalError("Historical Tool result differs from its declaration");
569
+ slot.parts[slot.partIndex] = Prompt.makePart("tool-result", {
570
+ id: payload.toolCallId,
571
+ name: payload.toolName,
572
+ result: envelope.sequence <= clearBound ? CLEARED_TOOL_RESULT : payload.result,
573
+ isFailure: payload.isFailure,
574
+ providerExecuted: false
575
+ });
576
+ const message = Prompt.makeMessage("tool", { content: [...slot.parts] });
577
+ state.all[slot.allIndex] = message;
578
+ state.before[slot.beforeIndex] = message;
579
+ historicalResults.delete(envelope.record.recordId);
564
580
  onBoundary?.({
565
581
  sequence: envelope.sequence,
566
582
  tag: payload._tag,
567
- promptLength: state.all.length + (state.pendingTools.length === 0 ? 0 : 1),
568
- incomplete: true,
583
+ promptLength: state.all.length,
584
+ ...incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {},
569
585
  ...isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY) ? { terminalPriorRun: true } : {}
570
586
  });
571
587
  return;
@@ -602,12 +618,40 @@ const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(
602
618
  const forRun = payload.runId === ownerRunId;
603
619
  pendingToolOrder = new Map(declaredApplicationToolCallIds(messages).map((id, index) => [id, index]));
604
620
  yield* accountResponse(envelope, payload, messages);
605
- const modelVisible = !forRun && payload.runScopedPrefixLength !== void 0 ? Prompt.fromMessages(messages.content.slice(payload.runScopedPrefixLength)) : messages;
606
- const visibleMessages = !forRun && incompleteToolTurns.has(envelope.record.recordId) ? withoutApplicationToolCallMessages(modelVisible) : modelVisible.content;
621
+ const visibleMessages = forRun ? messages.content : messages.content.filter((message) => message.role !== "system");
607
622
  for (const message of visibleMessages) {
608
623
  state.all.push(message);
609
624
  if (!forRun) state.before.push(message);
610
625
  }
626
+ if (!forRun) {
627
+ const calls = messages.content.flatMap((message) => message.role === "assistant" ? message.content.filter((part) => part.type === "tool-call" && !part.providerExecuted) : []);
628
+ if (calls.length > 0) {
629
+ const parts = calls.map((call) => Prompt.makePart("tool-result", {
630
+ id: call.id,
631
+ name: call.name,
632
+ result: {
633
+ _tag: "ToolOutcomeUnknown",
634
+ message: "This earlier operation has no recorded outcome. It may have executed. Do not assume success or retry it; its original operation remains unresolved."
635
+ },
636
+ isFailure: true,
637
+ providerExecuted: false
638
+ }));
639
+ const allIndex = state.all.length;
640
+ const beforeIndex = state.before.length;
641
+ const message = Prompt.makeMessage("tool", { content: parts });
642
+ state.all.push(message);
643
+ state.before.push(message);
644
+ for (const [partIndex, call] of calls.entries()) {
645
+ const callId = yield* Schema.decodeEffect(ToolCallId)(call.id).pipe(Effect.mapError((cause) => journalError("Invalid historical Tool Call ID", cause)));
646
+ historicalResults.set(toolCallSettledRecordId(payload.runId, payload.turn, callId), {
647
+ allIndex,
648
+ beforeIndex,
649
+ parts,
650
+ partIndex
651
+ });
652
+ }
653
+ }
654
+ }
611
655
  state = {
612
656
  ...state,
613
657
  committedTurns: forRun ? Math.max(state.committedTurns, payload.turn) : state.committedTurns
@@ -695,6 +739,7 @@ const modelResponseRecord = Effect.fn("RunJournal.modelResponseRecord")(function
695
739
  createdAt: input.createdAt,
696
740
  deploymentId: input.deploymentId,
697
741
  payload: ModelResponseRecorded.make({
742
+ ...input.toolOperations === void 0 ? {} : { toolOperations: input.toolOperations },
698
743
  ...input.toolParameterRejections === void 0 || input.toolParameterRejections.length === 0 ? {} : { toolParameterRejections: input.toolParameterRejections },
699
744
  ...input.toolExposure === void 0 ? {} : { toolExposure: input.toolExposure },
700
745
  runId: input.runId,
@@ -740,19 +785,31 @@ const toolSettledRecords = Effect.fn("RunJournal.toolSettledRecords")(function*
740
785
  }
741
786
  return toolRecords;
742
787
  });
743
- const runCompletionRecord = (input) => input.runCompletion === void 0 ? void 0 : RecordEnvelope.make({
744
- recordId: runCompletedRecordId(input.runId),
745
- family: "thread",
746
- schemaVersion: 1,
747
- createdAt: input.createdAt,
748
- deploymentId: input.deploymentId,
749
- payload: RunCompleted.make({
788
+ /** Integrity of the original validated terminal values; never a current-code projection. */
789
+ const runCompletionDigest = (completion) => digestJson({
790
+ runId: completion.runId,
791
+ output: completion.output,
792
+ runDisposition: completion.runDisposition ?? null,
793
+ finishReason: completion.finishReason ?? null,
794
+ exhausted: completion.exhausted ?? null
795
+ });
796
+ const runCompletionRecord = Effect.fn("RunJournal.runCompletionRecord")(function* (input) {
797
+ if (input.runCompletion === void 0) return void 0;
798
+ const completion = {
750
799
  runId: input.runId,
751
- output: input.runCompletion.output,
752
- ...input.runCompletion.runDisposition === void 0 ? {} : { runDisposition: input.runCompletion.runDisposition },
753
- ...input.runCompletion.finishReason === void 0 ? {} : { finishReason: input.runCompletion.finishReason },
754
- ...input.runCompletion.exhausted === void 0 ? {} : { exhausted: input.runCompletion.exhausted }
755
- })
800
+ ...input.runCompletion
801
+ };
802
+ return RecordEnvelope.make({
803
+ recordId: runCompletedRecordId(input.runId),
804
+ family: "thread",
805
+ schemaVersion: 1,
806
+ createdAt: input.createdAt,
807
+ deploymentId: input.deploymentId,
808
+ payload: RunCompleted.make({
809
+ ...completion,
810
+ resultDigest: yield* runCompletionDigest(completion)
811
+ })
812
+ });
756
813
  });
757
814
  /**
758
815
  * Pure per-Turn canonical batch builder (TurnCompleted seam fold, D6/D8): one
@@ -769,7 +826,7 @@ const turnCanonicalBatch = Effect.fn("RunJournal.turnCanonicalBatch")(function*
769
826
  const { promptMessages, toolParts } = splitTurnMessages(input.appended);
770
827
  const modelResponse = yield* modelResponseRecord(input, promptMessages);
771
828
  const toolRecords = yield* toolSettledRecords(input, toolParts);
772
- const completionRecord = runCompletionRecord(input);
829
+ const completionRecord = yield* runCompletionRecord(input);
773
830
  return CanonicalBatch.make({
774
831
  batchId: turnBatchId(input.runId, input.turn),
775
832
  producerId: input.producerId,
@@ -814,7 +871,7 @@ const turnResultsBatch = Effect.fn("RunJournal.turnResultsBatch")(function* (inp
814
871
  const first = toolRecords[0];
815
872
  if (first === void 0) return yield* journalError(`Turn ${input.turn} has no terminal Tool results to commit`);
816
873
  if (input.runCompletion !== void 0 && toolRecords.length !== 1) return yield* journalError("A terminal Tool completion requires exactly one settled result");
817
- const completionRecord = runCompletionRecord(input);
874
+ const completionRecord = yield* runCompletionRecord(input);
818
875
  return CanonicalBatch.make({
819
876
  batchId: turnResultsBatchId(input.runId, input.turn),
820
877
  producerId: input.producerId,
@@ -826,6 +883,6 @@ const turnResultsBatch = Effect.fn("RunJournal.turnResultsBatch")(function* (inp
826
883
  });
827
884
  });
828
885
  //#endregion
829
- export { toolApprovalRequestRecordId as A, turnBatchId as B, subagentLineageBatchId as C, subagentStartedBatchId as D, subagentRequestedRecordId as E, toolCallSettledRecordId as F, turnResponseBatchId as G, turnIdForRun as H, toolCallUnknownRecordId as I, makeJournalMetadata as J, turnResultsBatch as K, toolStepSettledBatchId as L, toolCallResolutionBatchId as M, toolCallResolvedRecordId as N, subagentStartedRecordId as O, toolCallResultBatchId as P, toolStepSettledRecordId as R, subagentJoinedRecordId as S, subagentRequestedBatchId as T, turnPreparedBatchId as U, turnCanonicalBatch as V, turnResponseBatch as W, runDurationRecordId as _, childThreadIdFor as a, runStartedRecordId as b, markUnknownBatchId as c, modelResponseRecordId as d, projectRunJournal as f, runDurationBatchId as g, runCompletedRecordId as h, childIdempotencyKeyFor as i, toolCallPreparedRecordId as j, toolApprovalDecisionRecordId as k, modelResponseInterruptedBatchId as l, promptFromCanonicalRecords as m, RunJournal_exports as n, compactionBatchId as o, projectRunJournalStream as p, turnResultsBatchId as q, approvalDecisionBatchId as r, compactionRecordId as s, RunJournalError as t, modelResponseInterruptedRecordId as u, runIdForSubmission as v, subagentLineageRecordId as w, subagentJoinBatchId as x, runStartedBatchId as y, turnApprovalsBatchId as z };
886
+ export { toolApprovalDecisionRecordId as A, turnApprovalsBatchId as B, subagentJoinedRecordId as C, subagentRequestedRecordId as D, subagentRequestedBatchId as E, toolCallResultBatchId as F, turnResponseBatch as G, turnCanonicalBatch as H, toolCallSettledRecordId as I, turnResultsBatchId as J, turnResponseBatchId as K, toolCallUnknownRecordId as L, toolCallPreparedRecordId as M, toolCallResolutionBatchId as N, subagentStartedBatchId as O, toolCallResolvedRecordId as P, toolStepSettledBatchId as R, subagentJoinBatchId as S, subagentLineageRecordId as T, turnIdForRun as U, turnBatchId as V, turnPreparedBatchId as W, makeJournalMetadata as Y, runDurationBatchId as _, childThreadIdFor as a, runStartedBatchId as b, markUnknownBatchId as c, modelResponseRecordId as d, projectRunJournal as f, runCompletionDigest as g, runCompletedRecordId as h, childIdempotencyKeyFor as i, toolApprovalRequestRecordId as j, subagentStartedRecordId as k, modelResponseInterruptedBatchId as l, promptFromCanonicalRecords as m, RunJournal_exports as n, compactionBatchId as o, projectRunJournalStream as p, turnResultsBatch as q, approvalDecisionBatchId as r, compactionRecordId as s, RunJournalError as t, modelResponseInterruptedRecordId as u, runDurationRecordId as v, subagentLineageBatchId as w, runStartedRecordId as x, runIdForSubmission as y, toolStepSettledRecordId as z };
830
887
 
831
- //# sourceMappingURL=RunJournal-DRRRZmG7.mjs.map
888
+ //# sourceMappingURL=RunJournal-DNs3PM4K.mjs.map