effect-agent 0.1.0-beta.93 → 0.1.0-beta.95

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 (146) hide show
  1. package/dist/{Agent-RklVROrm.mjs → Agent-CG_VMrtA.mjs} +2 -2
  2. package/dist/{Agent-RklVROrm.mjs.map → Agent-CG_VMrtA.mjs.map} +1 -1
  3. package/dist/{Agent-CN0EWRsR.d.mts → Agent-CM6JubNX.d.mts} +2 -2
  4. package/dist/{AgentPolicy-CetmQrf3.d.mts → AgentPolicy-BqDoSXO6.d.mts} +2 -2
  5. package/dist/{AgentRuntime-BPjQM1Nv.mjs → AgentRuntime-Cdvqw7l_.mjs} +88 -32
  6. package/dist/AgentRuntime-Cdvqw7l_.mjs.map +1 -0
  7. package/dist/{AgentRuntime-uxR_a4VM.d.mts → AgentRuntime-CufqQ4JM.d.mts} +8 -8
  8. package/dist/{ContextCompactor-Dxu5zhOL.d.mts → ContextCompactor-WwSIG_Z2.d.mts} +2 -2
  9. package/dist/{DurableAgentRuntime-CdrBuKZY.mjs → DurableAgentRuntime-BaGsWDHO.mjs} +9 -5
  10. package/dist/DurableAgentRuntime-BaGsWDHO.mjs.map +1 -0
  11. package/dist/{EventSource-c6GRTCsl.d.mts → EventSource-DVfX1GRH.d.mts} +3 -3
  12. package/dist/{Messaging-CkcIdt4I.d.mts → Messaging-QMYhp297.d.mts} +3 -3
  13. package/dist/{MessagingHost-CRk0kXzT.d.mts → MessagingHost-gAxs5gme.d.mts} +3 -3
  14. package/dist/{Output-D6SkedVx.d.mts → Output-CjocJzsl.d.mts} +2 -2
  15. package/dist/{PreparedInputAdmission-QzFbW2LQ.d.mts → PreparedInputAdmission-DoWaMC2R.d.mts} +4 -4
  16. package/dist/{Records-vFp_ZQ9Y.d.mts → Records-B84j3Jq_.d.mts} +21 -9
  17. package/dist/{Records-C9cezOEf.mjs → Records-CsEsSW2o.mjs} +5 -2
  18. package/dist/Records-CsEsSW2o.mjs.map +1 -0
  19. package/dist/{RunJournal-lwbrh2hZ.mjs → RunJournal-yYpUlTOE.mjs} +3 -2
  20. package/dist/RunJournal-yYpUlTOE.mjs.map +1 -0
  21. package/dist/{RunOptions-g1aigcKI.d.mts → RunOptions-CE-G3niT.d.mts} +14 -8
  22. package/dist/{Schedule-BkZvKyMw.d.mts → Schedule-DCYBfhgT.d.mts} +2 -2
  23. package/dist/{Scheduling-D0QqOoeT.mjs → Scheduling-CUuYc3-D.mjs} +3 -3
  24. package/dist/{Scheduling-D0QqOoeT.mjs.map → Scheduling-CUuYc3-D.mjs.map} +1 -1
  25. package/dist/{Subagent-CnTzCy8k.mjs → Subagent-Cbfzylz1.mjs} +3 -3
  26. package/dist/{Subagent-CnTzCy8k.mjs.map → Subagent-Cbfzylz1.mjs.map} +1 -1
  27. package/dist/{Subagent-DyfzHNdv.d.mts → Subagent-DscbtbNY.d.mts} +6 -6
  28. package/dist/{SubagentHost-CJUBQlcc.d.mts → SubagentHost-DaFMZnVR.d.mts} +4 -4
  29. package/dist/{Subscription-CKQ0KDHN.d.mts → Subscription-C8IHdmFk.d.mts} +4 -4
  30. package/dist/{SubscriptionInput-Cth8F_7b.d.mts → SubscriptionInput-DhM3jUW2.d.mts} +3 -3
  31. package/dist/{ToolResult-DmmgoChv.d.mts → ToolResult-BKdqWRff.d.mts} +20 -3
  32. package/dist/{Worker-CaPYykpe.d.mts → Worker--j87JI__.d.mts} +2 -2
  33. package/dist/capabilities/Approval.mjs +1 -1
  34. package/dist/capabilities/Commands.d.mts +1 -1
  35. package/dist/capabilities/Messaging.d.mts +2 -2
  36. package/dist/capabilities/ModelContext.mjs +1 -1
  37. package/dist/capabilities/RunHooks.d.mts +1 -1
  38. package/dist/capabilities/Subagent.d.mts +2 -2
  39. package/dist/capabilities/Subagent.mjs +1 -1
  40. package/dist/capabilities/ToolDiscovery.d.mts +19 -4
  41. package/dist/capabilities/ToolDiscovery.mjs +33 -14
  42. package/dist/capabilities/ToolDiscovery.mjs.map +1 -1
  43. package/dist/core/Agent.d.mts +1 -1
  44. package/dist/core/Agent.mjs +1 -1
  45. package/dist/core/AgentPolicy.d.mts +1 -1
  46. package/dist/core/Thread.mjs +1 -1
  47. package/dist/core/ToolResult.d.mts +2 -2
  48. package/dist/core/ToolResult.mjs +17 -1
  49. package/dist/core/ToolResult.mjs.map +1 -1
  50. package/dist/core/Worker.d.mts +1 -1
  51. package/dist/core/Worker.mjs +1 -1
  52. package/dist/durable/ActivityStore.d.mts +1 -1
  53. package/dist/durable/ActivityStore.mjs +1 -1
  54. package/dist/durable/Admin.d.mts +1 -1
  55. package/dist/durable/Admin.mjs +1 -1
  56. package/dist/durable/AgentRegistration.d.mts +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 +1 -1
  60. package/dist/durable/Digest.d.mts +1 -1
  61. package/dist/durable/Digest.mjs +1 -1
  62. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  63. package/dist/durable/DurableAgentRuntime.mjs +1 -1
  64. package/dist/durable/EventSource.d.mts +1 -1
  65. package/dist/durable/EventSource.mjs +1 -1
  66. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  67. package/dist/durable/GitHubWorkflowSource.mjs +1 -1
  68. package/dist/durable/MessageDelivery.d.mts +23 -23
  69. package/dist/durable/MessageDelivery.mjs +1 -1
  70. package/dist/durable/MessageDeliveryStoreConformance.d.mts +40 -40
  71. package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
  72. package/dist/durable/PersistentHistory.d.mts +1 -1
  73. package/dist/durable/PersistentHistory.mjs +2 -2
  74. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  75. package/dist/durable/Records.d.mts +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/RunJournal.d.mts +1 -1
  80. package/dist/durable/RunJournal.mjs +1 -1
  81. package/dist/durable/Schedule.d.mts +1 -1
  82. package/dist/durable/Schedule.mjs +1 -1
  83. package/dist/durable/ScheduleStoreConformance.d.mts +1 -1
  84. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  85. package/dist/durable/ScheduleTransition.d.mts +1 -1
  86. package/dist/durable/ScheduleTransition.mjs +1 -1
  87. package/dist/durable/Scheduling.d.mts +2 -2
  88. package/dist/durable/Scheduling.mjs +1 -1
  89. package/dist/durable/SqlStorageV2Upgrade.d.mts +2 -2
  90. package/dist/durable/SqlStorageV2Upgrade.mjs +1 -1
  91. package/dist/durable/SqlSubscriptionStore.d.mts +2 -2
  92. package/dist/durable/SqlSubscriptionStore.mjs +1 -1
  93. package/dist/durable/SubmissionLedger.d.mts +1 -1
  94. package/dist/durable/SubmissionLedger.mjs +1 -1
  95. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  96. package/dist/durable/SubmissionLedgerConformance.mjs +2 -2
  97. package/dist/durable/SubmissionStatus.d.mts +1 -1
  98. package/dist/durable/Subscription.d.mts +1 -1
  99. package/dist/durable/Subscription.mjs +1 -1
  100. package/dist/durable/SubscriptionInput.d.mts +1 -1
  101. package/dist/durable/SubscriptionInput.mjs +1 -1
  102. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  103. package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
  104. package/dist/durable/SubscriptionTools.d.mts +3 -3
  105. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  106. package/dist/durable/SubscriptionTransition.mjs +1 -1
  107. package/dist/durable/Subscriptions.d.mts +5 -5
  108. package/dist/durable/Subscriptions.mjs +2 -2
  109. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  110. package/dist/durable/ThreadContextHistory.mjs +1 -1
  111. package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
  112. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  113. package/dist/durable/ThreadInvariants.d.mts +1 -1
  114. package/dist/durable/ThreadInvariants.mjs +1 -1
  115. package/dist/durable/ThreadProjection.d.mts +1 -1
  116. package/dist/durable/ThreadProjection.mjs +1 -1
  117. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  118. package/dist/durable/ThreadStore.d.mts +1 -1
  119. package/dist/durable/ThreadStore.mjs +1 -1
  120. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  121. package/dist/durable/ThreadStoreConformance.mjs +1 -1
  122. package/dist/durable/ToolReconciler.mjs +1 -1
  123. package/dist/durable/WorkerHost.d.mts +4 -4
  124. package/dist/engine/AgentRuntime.d.mts +1 -1
  125. package/dist/engine/AgentRuntime.mjs +1 -1
  126. package/dist/engine/Compaction.d.mts +1 -1
  127. package/dist/engine/ContextCompactor.d.mts +1 -1
  128. package/dist/engine/MessagingHost.d.mts +1 -1
  129. package/dist/engine/Output.d.mts +1 -1
  130. package/dist/engine/RunOptions.d.mts +1 -1
  131. package/dist/engine/RunOptions.mjs.map +1 -1
  132. package/dist/engine/SubagentHost.d.mts +1 -1
  133. package/dist/index.d.mts +18 -18
  134. package/dist/index.mjs +8 -8
  135. package/package.json +1 -1
  136. package/src/capabilities/ToolDiscovery.ts +48 -18
  137. package/src/core/ToolResult.ts +20 -0
  138. package/src/durable/DurableAgentRuntime.ts +7 -0
  139. package/src/durable/Records.ts +3 -0
  140. package/src/durable/RunJournal.ts +5 -0
  141. package/src/engine/RunOptions.ts +9 -3
  142. package/src/engine/internal/agent-runtime.ts +254 -67
  143. package/dist/AgentRuntime-BPjQM1Nv.mjs.map +0 -1
  144. package/dist/DurableAgentRuntime-CdrBuKZY.mjs.map +0 -1
  145. package/dist/Records-C9cezOEf.mjs.map +0 -1
  146. package/dist/RunJournal-lwbrh2hZ.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
- import { O as PersistedJson } from "./Records-vFp_ZQ9Y.mjs";
2
- import { E as SubscriptionSourceError, b as SubscriptionRecord, i as EventSourceVersion, t as AcceptedEvent } from "./Subscription-CKQ0KDHN.mjs";
1
+ import { O as PersistedJson } from "./Records-B84j3Jq_.mjs";
2
+ import { E as SubscriptionSourceError, b as SubscriptionRecord, i as EventSourceVersion, t as AcceptedEvent } from "./Subscription-C8IHdmFk.mjs";
3
3
  import { Context, Effect, Schema, Scope } from "effect";
4
4
  declare namespace EventSource_d_exports {
5
5
  export { EventSource, EventSources, NormalizedEvent, makeEventSource };
@@ -48,4 +48,4 @@ declare const makeEventSource: <Event extends Schema.Top, Parameters extends Sch
48
48
  }) => Effect.Effect<EventSource, never, Exclude<R, Scope.Scope> | Exclude<Event["DecodingServices"], Scope.Scope> | Exclude<Event["EncodingServices"], Scope.Scope> | Exclude<Parameters["DecodingServices"], Scope.Scope> | Exclude<Parameters["EncodingServices"], Scope.Scope>>;
49
49
  //#endregion
50
50
  export { makeEventSource as a, NormalizedEvent as i, EventSource_d_exports as n, EventSources as r, EventSource as t };
51
- //# sourceMappingURL=EventSource-c6GRTCsl.d.mts.map
51
+ //# sourceMappingURL=EventSource-DVfX1GRH.d.mts.map
@@ -1,6 +1,6 @@
1
1
  import { a as Receipt, t as IdempotencyKey } from "./Receipt-BAHyigAF.mjs";
2
- import { r as AnyDefinition } from "./Agent-CN0EWRsR.mjs";
3
- import { _ as MessagingError, d as InboxPage, f as InputMessage, g as MessageStatus, h as MessageRef, m as MessageAdmission, p as MessageAddress, t as MessagingHost, u as InboxEntry, v as PeerName } from "./MessagingHost-CRk0kXzT.mjs";
2
+ import { r as AnyDefinition } from "./Agent-CM6JubNX.mjs";
3
+ import { _ as MessagingError, d as InboxPage, f as InputMessage, g as MessageStatus, h as MessageRef, m as MessageAdmission, p as MessageAddress, t as MessagingHost, u as InboxEntry, v as PeerName } from "./MessagingHost-gAxs5gme.mjs";
4
4
  import { Tool, Toolkit } from "effect/unstable/ai";
5
5
  import { Crypto, Effect, Schema } from "effect";
6
6
  declare namespace Messaging_d_exports {
@@ -487,4 +487,4 @@ declare const retryTool: <const Name extends string, Input extends Schema.Top>(d
487
487
  };
488
488
  //#endregion
489
489
  export { inspect as a, reply as c, retryTool as d, send as f, inboxTool as i, replyTool as l, Peer as n, inspectTool as o, sendTool as p, inbox as r, peer as s, Messaging_d_exports as t, retry as u };
490
- //# sourceMappingURL=Messaging-CkcIdt4I.d.mts.map
490
+ //# sourceMappingURL=Messaging-QMYhp297.d.mts.map
@@ -2,8 +2,8 @@ import { u as ThreadId } from "./Identifiers-CN2s30fF.mjs";
2
2
  import { s as SubagentExecutionFailure } from "./SubagentContract-DdT7Cqe6.mjs";
3
3
  import { a as Receipt, r as Principal, t as IdempotencyKey } from "./Receipt-BAHyigAF.mjs";
4
4
  import { r as Update } from "./AgentUpdates-DMJ-_xow.mjs";
5
- import { r as AnyDefinition } from "./Agent-CN0EWRsR.mjs";
6
- import { u as WorkerSource } from "./Worker-CaPYykpe.mjs";
5
+ import { r as AnyDefinition } from "./Agent-CM6JubNX.mjs";
6
+ import { u as WorkerSource } from "./Worker--j87JI__.mjs";
7
7
  import { Context, Effect, Schema } from "effect";
8
8
  //#region src/core/Messaging.d.ts
9
9
  /** Application-chosen fixed route name; it never authorizes a destination by itself. */
@@ -243,4 +243,4 @@ declare const PeerDeliveryLifetime: Context.Reference<number>;
243
243
  declare const PeerMessageCapacity: Context.Reference<number>;
244
244
  //#endregion
245
245
  export { MessagingError as _, PeerDeliveryLifetime as a, PeerTarget as c, InboxPage as d, InputMessage as f, MessageStatus as g, MessageRef as h, PeerAuthorizer as i, SendPeerMessage as l, MessageAdmission as m, MessagingHost_d_exports as n, PeerMessageCapacity as o, MessageAddress as p, PeerAuthorizationRequest as r, PeerRoutes as s, MessagingHost as t, InboxEntry as u, PeerName as v };
246
- //# sourceMappingURL=MessagingHost-CRk0kXzT.d.mts.map
246
+ //# sourceMappingURL=MessagingHost-gAxs5gme.d.mts.map
@@ -1,4 +1,4 @@
1
- import "./Agent-CN0EWRsR.mjs";
1
+ import "./Agent-CM6JubNX.mjs";
2
2
  import { Prompt } from "effect/unstable/ai";
3
3
  import { Schema } from "effect";
4
4
  //#region src/engine/internal/output-contract.d.ts
@@ -22,4 +22,4 @@ declare namespace Output_d_exports {
22
22
  }
23
23
  //#endregion
24
24
  export { textOutput as n, Output_d_exports as t };
25
- //# sourceMappingURL=Output-D6SkedVx.d.mts.map
25
+ //# sourceMappingURL=Output-CjocJzsl.d.mts.map
@@ -1,7 +1,7 @@
1
1
  import { a as Receipt } from "./Receipt-BAHyigAF.mjs";
2
- import { un as SubmissionStatus } from "./Records-vFp_ZQ9Y.mjs";
3
- import { H as ScheduledInputRefused, V as ScheduledInputFailure, j as ScheduleStorageError } from "./Schedule-BkZvKyMw.mjs";
4
- import { a as PreparedInput } from "./Subscription-CKQ0KDHN.mjs";
2
+ import { un as SubmissionStatus } from "./Records-B84j3Jq_.mjs";
3
+ import { H as ScheduledInputRefused, V as ScheduledInputFailure, j as ScheduleStorageError } from "./Schedule-DCYBfhgT.mjs";
4
+ import { a as PreparedInput } from "./Subscription-C8IHdmFk.mjs";
5
5
  import { Context, Effect } from "effect";
6
6
  declare namespace PreparedInputAdmission_d_exports {
7
7
  export { PreparedInputAdmission, admitPreparedInput };
@@ -35,4 +35,4 @@ declare const admitPreparedInput: <R>(submit: Effect.Effect<Receipt, ScheduledIn
35
35
  }, ScheduleStorageError, R>;
36
36
  //#endregion
37
37
  export { PreparedInputAdmission_d_exports as n, admitPreparedInput as r, PreparedInputAdmission as t };
38
- //# sourceMappingURL=PreparedInputAdmission-QzFbW2LQ.d.mts.map
38
+ //# sourceMappingURL=PreparedInputAdmission-DoWaMC2R.d.mts.map
@@ -7,15 +7,16 @@ import { l as RunUsageSummary, r as ModelCallUsage, s as RunTotals } from "./Usa
7
7
  import { a as ExhaustedLimit } from "./RunEvent-DIrzkjLr.mjs";
8
8
  import { t as ThreadHistory } from "./ThreadHistory-tS1KwxHR.mjs";
9
9
  import { a as AgentInputError } from "./AgentError-CggcAQ7V.mjs";
10
- import { t as AgentPolicy } from "./AgentPolicy-CetmQrf3.mjs";
11
- import { T as RunDispositionDeclaration, _ as InstructionSource, c as Definition, m as InputPromptSource, n as Any, r as AnyDefinition, v as ModelServices } from "./Agent-CN0EWRsR.mjs";
10
+ import { t as ToolParameterRejection } from "./ToolResult-BKdqWRff.mjs";
11
+ import { t as AgentPolicy } from "./AgentPolicy-BqDoSXO6.mjs";
12
+ import { T as RunDispositionDeclaration, _ as InstructionSource, c as Definition, m as InputPromptSource, n as Any, r as AnyDefinition, v as ModelServices } from "./Agent-CM6JubNX.mjs";
12
13
  import { t as RunPolicyUsage } from "./RunPolicyUsage-ClZxyR46.mjs";
13
- import { a as WorkerError } from "./Worker-CaPYykpe.mjs";
14
- import { G as RunToolAuthorization, O as RunCostEstimator, h as RunApprovalHook, x as RunContextPreparation } from "./RunOptions-g1aigcKI.mjs";
15
- import { _ as MessagingError, f as InputMessage, t as MessagingHost } from "./MessagingHost-CRk0kXzT.mjs";
16
- import "./Messaging-CkcIdt4I.mjs";
17
- import { c as WorkerReportPreparationFailure, i as SubagentHost, l as WorkerReporting } from "./SubagentHost-CJUBQlcc.mjs";
18
- import { p as RuntimeBinding, r as AgentCompletionProjectionRequirements, s as AgentRuntimeRequirements } from "./AgentRuntime-uxR_a4VM.mjs";
14
+ import { a as WorkerError } from "./Worker--j87JI__.mjs";
15
+ import { G as RunToolAuthorization, O as RunCostEstimator, h as RunApprovalHook, x as RunContextPreparation } from "./RunOptions-CE-G3niT.mjs";
16
+ import { _ as MessagingError, f as InputMessage, t as MessagingHost } from "./MessagingHost-gAxs5gme.mjs";
17
+ import "./Messaging-QMYhp297.mjs";
18
+ import { c as WorkerReportPreparationFailure, i as SubagentHost, l as WorkerReporting } from "./SubagentHost-DaFMZnVR.mjs";
19
+ import { p as RuntimeBinding, r as AgentCompletionProjectionRequirements, s as AgentRuntimeRequirements } from "./AgentRuntime-CufqQ4JM.mjs";
19
20
  import { n as DurableRuntimeFailpoint, r as DurableRuntimeFailpointError } from "./DurableFailpoint-Oinuuedm.mjs";
20
21
  import { o as OperationDenied } from "./OperationAuthorizer-TzcQtpX5.mjs";
21
22
  import { s as ToolReconciler } from "./ToolReconciler-DQVaJfpE.mjs";
@@ -2181,6 +2182,7 @@ declare const projectRunJournal: (records: readonly CanonicalRecordEnvelope[], r
2181
2182
  */
2182
2183
  declare const promptFromCanonicalRecords: (records: readonly CanonicalRecordEnvelope[]) => Effect.Effect<Prompt.Prompt, RunJournalError, never>;
2183
2184
  interface TurnCommitInput {
2185
+ readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined;
2184
2186
  readonly toolExposure?: Snapshot | undefined;
2185
2187
  readonly toolSelections?: ReadonlyMap<string, Selection> | undefined;
2186
2188
  readonly budgetRejectedCalls?: ReadonlySet<string>;
@@ -2936,6 +2938,16 @@ declare const ToolCallSettled_base: Schema.Class<ToolCallSettled, Schema.TaggedS
2936
2938
  declare class ToolCallSettled extends ToolCallSettled_base {}
2937
2939
  declare const ModelResponseRecorded_base: Schema.Class<ModelResponseRecorded, Schema.Struct<{
2938
2940
  readonly _tag: Schema.tag<"ModelResponseRecorded">;
2941
+ readonly toolParameterRejections: Schema.optionalKey<Schema.$Array<Schema.Struct<{
2942
+ readonly toolCallId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/ToolCallId">;
2943
+ readonly parameters: Schema.Codec<Schema.Json, Schema.Json, never, never>;
2944
+ readonly error: Schema.toEncoded<Schema.Struct<{
2945
+ readonly _tag: Schema.tag<"AiError">;
2946
+ readonly module: Schema.String;
2947
+ readonly method: Schema.String;
2948
+ readonly reason: typeof import("effect/unstable/ai/AiError").ToolParameterValidationError;
2949
+ }>>;
2950
+ }>>>;
2939
2951
  readonly toolExposure: Schema.optionalKey<typeof Snapshot>;
2940
2952
  readonly runId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/RunId">;
2941
2953
  readonly turnId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/TurnId">;
@@ -3585,4 +3597,4 @@ declare class CanonicalRecordEnvelope extends CanonicalRecordEnvelope_base {}
3585
3597
  declare const CURRENT_CANONICAL_SCHEMA_VERSION: 1;
3586
3598
  //#endregion
3587
3599
  export { ToolCallResolved as $, UnknownResolution as $a, ChildBudgetReservationSnapshot as $i, turnBatchId as $n, AwaitChildAdmissionResolution as $r, ThreadObservation as $t, ProducerId as A, ResolutionAbortSubmission as Aa, SettleJoinedWithHost as Ai, runCompletedRecordId as An, AgentRegistration_d_exports as Ar, DurableWorkerFailure as At, SettlementOutcome as B, SubmissionAdmissionFence as Ba, AdmissionNotAdmitted as Bi, subagentStartedBatchId as Bn, definitionDigestsEqual as Br, CheckpointRejected as Bt, ModelCompleted as C, RecoverySnapshot as Ca, RepairSubagentStartLink as Ci, markUnknownBatchId as Cn, RetryCommand as Cr, DurableRetryFailure as Ct, PeerMessagePrepared as D, RenewOwnershipRequest as Da, ResumeWaitingParent as Di, projectRunJournal as Dn, predictRecoveryDisposition as Dr, DurableSubmitFailure as Dt, ObservationOffset as E, ReleaseOwnershipRequest as Ea, ResumeSuspended as Ei, modelResponseRecordId as En, obligationSeverityOf as Er, DurableSubmitAgent as Et, RunCompleted as F, Settlement as Fa, AdmissionAdmitted as Fi, subagentJoinedRecordId as Fn, DurableBindingFailure as Fr, recoveryRepairRecordId as Ft, SubmissionSettled as G, SubmissionLookupById as Ga, ApprovalConflict as Gi, toolCallResolutionBatchId as Gn, digestDefinition as Gr, SaveCheckpointRequest as Gt, SubagentLineageRecorded as H, SubmissionLedgerFailure as Ha, AdmissionRequest as Hi, toolApprovalDecisionRecordId as Hn, Digest_d_exports as Hr, FencedAppendRequest as Ht, RunFailed as I, SettlementConflict as Ia, AdmissionConflict as Ii, subagentLineageBatchId as In, DurableWorkerBinding as Ir, threadCreatedBatchId as It, ThreadCreated as J, SubmissionState as Ja, ApprovalPendingSuspension as Ji, toolCallSettledRecordId as Jn, AppendReservedSettlement as Jr, ThreadCheckpoints as Jt, SubmissionSettledRecord as K, SubmissionLookupByKey as Ka, ApprovalDecisionCommand as Ki, toolCallResolvedRecordId as Kn, digestDefinitions as Kr, SaveRecoveryCheckpointRequest as Kt, RunPolicyUsageReserved as L, SettlementFinalization as La, AdmissionFence as Li, subagentLineageRecordId as Ln, ExecutableAgentBinding as Lr, threadCreatedRecordId as Lt, RecordId as M, ResolutionNeverHappened as Ma, AbortCommand as Mi, runStartedBatchId as Mn, AgentRegistration as Mr, RecoveryReport as Mt, Records_d_exports as N, ResolutionSafeToRetry as Na, AbortIntent as Ni, runStartedRecordId as Nn, BindingDigestMismatch as Nr, childReservationIdFor as Nt, PersistedJson as O, ReservedChildBudget as Oa, RevertJoining as Oi, projectRunJournalStream as On, recoveryDecisionMeaning as Or, DurableSubmitOptions as Ot, RepairAnnotated as P, RevertJoiningRequest as Pa, AbortIntentRequest as Pi, subagentJoinBatchId as Pn, BindingUnavailable as Pr, recoveryRepairBatchId as Pt, ToolCallResolution as Q, SuspensionSnapshot as Qa, ChildBudgetReservationRequest as Qi, turnApprovalsBatchId as Qn, AwaitApprovalDecision as Qr, ThreadNotMaterialized as Qt, RunStartedRecord as R, SettlementReservation as Ra, AdmissionGroup as Ri, subagentRequestedBatchId as Rn, ResolvedBinding as Rr, AppendConflict as Rt, MAX_PERSISTED_JSON_NODES as S, ParentLinkage as Sa, RepairReadiness as Si, compactionRecordId as Sn, RecoveryExplanation as Sr, DurableResolveFailure as St, ModelResponseRecorded as T, ReleaseChildBudgetRequest as Ta, ResumePendingToolBatch as Ti, modelResponseInterruptedRecordId as Tn, RetryRefused as Tr, DurableRuntimeConfigOptions as Tt, SubagentRequested as U, SubmissionLedger_d_exports as Ua, AdmissionResolution as Ui, toolApprovalRequestRecordId as Un, EMPTY_TAIL_DIGEST as Ur, LoadCheckpointRequest as Ut, SubagentJoined as V, SubmissionLedger as Va, AdmissionPolicyError as Vi, subagentStartedRecordId as Vn, DigestError as Vr, FenceRejected as Vt, SubagentStarted as W, SubmissionLookup as Wa, AdmissionResult as Wi, toolCallPreparedRecordId as Wn, digestCanonicalBatch as Wr, MAX_THREAD_EXPORT_RECORDS as Wt, ToolApprovalRequested as X, SuspensionOutcome as Xa, BeginChildBudgetReleaseRequest as Xi, toolStepSettledBatchId as Xn, ApplyJoinAccounting as Xr, ThreadExportRequest as Xt, ToolApprovalDecided as Y, SuspendRequest as Ya, AttachChildToReservationRequest as Yi, toolCallUnknownRecordId as Yn, ApplyInput as Yr, ThreadExport as Yt, ToolCallPrepared as Z, SuspensionReason as Za, ChildAttachmentSnapshot as Zi, toolStepSettledRecordId as Zn, ApplyUnknownResolutions as Zr, ThreadMaterialization as Zt, Digest as _, MarkUnknownRequest as _a, RecoveryEvidence as _i, TurnCommitInput as _n, ObligationReport as _r, DurableAwaitFailure as _t, BatchId as a, Claim as aa, CompleteMaterialization as ai, ThreadStore_d_exports as an, settlementFailureFromRecord as ao, turnResultsBatch as ar, WorkerInputCompleted as at, MAX_PERSISTED_JSON_COLLECTION_LENGTH as b, OwnershipSnapshot as ba, RepairInputMarker as bi, childThreadIdFor as bn, RECOVERY_DECISION_MEANINGS as br, DurableObserveOptions as bt, CanonicalRecord as c, DEFAULT_OWNERSHIP_LEASE_DURATION as ca, EnsureWaitingForChild as ci, PendingSubmission as cn, submissionInputBatchId as co, ExplainedEvidence as cr, WorkerOriginRecorded as ct, CanonicalSequence as d, JoiningClaim as da, NoAction as di, SubmissionStatus_d_exports as dn, submissionSettlementId as do, IntegrityCheck as dr, WorkerReportingIntent as dt, ChildReservationConflict as ea, AwaitChildSettlement as ei, ThreadRead as en, UnknownResolutionCommand as eo, turnCanonicalBatch as er, ToolCallSettled as et, CompactionCreated as f, LedgerCapabilities as fa, OpenDelegationCallEvidence as fi, JournalBoundary as fn, submissionSettlementRecordId as fo, IntegrityCheckName as fr, DurableAbortFailure as ft, DeploymentId as g, MarkReadyRequest as ga, RecoveryDecision as gi, RunJournal_d_exports as gn, ObligationEntry as gr, DurableApprovalResolver as gt, DefinitionDigests as h, MarkJoinedRequest as ha, PropagateChildAbort as hi, RunJournalUsage as hn, ObligationBlockedOn as hr, DurableApprovalFailure as ht, ApprovalDecision as i, ChildSettledOutcome as ia, CompleteChildAdmission as ii, ThreadStoreFailure as in, WaitingForChildSuspension as io, turnResponseBatchId as ir, WorkerAdmission as it, RecordEnvelope as j, ResolutionCompletedWithResult as ja, classifyRecovery as ji, runIdForSubmission as jn, AgentAttemptContext as jr, DurableWorkerRequirements as jt, ProducerEpoch as k, ReservedSettlement as ka, SettleAborted as ki, promptFromCanonicalRecords as kn, renderRecoveryExplanation as kr, DurableVerifyFailure as kt, CanonicalRecordEnvelope as l, InputAppliedMarker as la, FinalizeLedgerFromHistory as li, SettledSubmission as ln, submissionInputRecordId as lo, ExplainedSubmission as lr, WorkerReportPrepared as lt, DefinitionDigestInput as m, MarkInputAppliedRequest as ma, PendingApprovalEvidence as mi, RunJournalProjection as mn, IntegrityReport as mr, DurableAgentRuntime_d_exports as mt, AbortedSubmissionSettled as n, ChildReservationStatus as na, AwaitParentEstablishment as ni, ThreadStore as nn, UnknownResolutionIntent as no, turnPreparedBatchId as nr, ToolStepSettled as nt, CURRENT_CANONICAL_SCHEMA_VERSION as o, ClaimJoiningRequest as oa, DeclaredPendingBatchEvidence as oi, ThreadTail as on, submissionAbortBatchId as oo, turnResultsBatchId as or, WorkerInputRequested as ot, CompletedSubmissionSettled as p, LedgerError as pa, OpenToolCallEvidence as pi, RunJournalError as pn, IntegrityCheckStatus as pr, DurableAgentRuntime as pt, SubtreeBudgetReserved as q, SubmissionSnapshot as qa, ApprovalDecisionIntent as qi, toolCallResultBatchId as qn, digestJson as qr, ThreadCheckpoint as qt, AgentUpdateEmitted as r, ChildSettledNotification as ra, AwaitUnknownResolution as ri, ThreadStoreError as rn, WaitingChild as ro, turnResponseBatch as rr, UserInputRecorded as rt, CanonicalBatch as s, ClaimRequest as sa, DelegationAdmissionEvidence as si, ThreadTailRequest as sn, submissionAbortRecordId as so, Admin_d_exports as sr, WorkerOrigin as st, AbortRequested as t, ChildReservationId as ta, AwaitHostSettlement as ti, ThreadRecoveryCheckpoints as tn, UnknownResolutionConflict as to, turnIdForRun as tr, ToolCallUnknown as tt, CanonicalRecordPayload as u, JoinSnapshot as ua, MarkUnknown as ui, SubmissionStatus as un, submissionSettlementBatchId as uo, ExplainedUnknownCall as ur, WorkerReportRefused as ut, FailedSubmissionSettled as v, OwnershipLost as va, Recovery_d_exports as vi, approvalDecisionBatchId as vn, ObligationSeverity as vr, DurableExplainFailure as vt, ModelResponseInterrupted as w, RecoverySnapshotRequest as wa, ResumeFromTurnBoundary as wi, modelResponseInterruptedBatchId as wn, RetryRefusalReason as wr, DurableRuntimeConfig as wt, MAX_PERSISTED_JSON_DEPTH as x, OwnershipToken as xa, RepairJoinMarker as xi, compactionBatchId as xn, RecoveryDisposition as xr, DurableProgressFailure as xt, MAX_PERSISTED_JSON_BYTES as y, OwnershipRenewal as ya, ReleaseOrphanChildReservation as yi, childIdempotencyKeyFor as yn, ObligationThresholds as yr, DurableObligationFailure as yt, SettlementFailureDiagnostic as z, SettlementReservationSnapshot as za, AdmissionIndeterminate as zi, subagentRequestedRecordId as zn, compileRegistrations as zr, AppendResult as zt };
3588
- //# sourceMappingURL=Records-vFp_ZQ9Y.d.mts.map
3600
+ //# sourceMappingURL=Records-B84j3Jq_.d.mts.map
@@ -1,7 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { AgentId, AttemptId, DelegationId, ReceiptId, RunId, SettlementId, SubmissionId, ThreadId, ToolCallId, TurnId } from "./core/Identifiers.mjs";
2
3
  import { n as utf8ByteLength } from "./utf8-DchGZRBd.mjs";
4
+ import { ToolParameterRejection } from "./core/ToolResult.mjs";
3
5
  import { AgentPolicy } from "./core/AgentPolicy.mjs";
4
- import { AgentId, AttemptId, DelegationId, ReceiptId, RunId, SettlementId, SubmissionId, ThreadId, ToolCallId, TurnId } from "./core/Identifiers.mjs";
5
6
  import { IdempotencyKey, Principal } from "./core/Receipt.mjs";
6
7
  import { Update } from "./core/AgentUpdates.mjs";
7
8
  import { PolicyLimit } from "./core/AgentError.mjs";
@@ -256,6 +257,8 @@ var ToolCallSettled = class extends Schema.TaggedClass("@effect-agent/thread/Too
256
257
  * `messagesDigest` pins the exact encoded content.
257
258
  */
258
259
  const ModelResponseRecordedFields = Schema.Struct({
260
+ /** Explicit pre-execution failures, committed with the original arguments before any approval. */
261
+ toolParameterRejections: Schema.optionalKey(Schema.Array(ToolParameterRejection)),
259
262
  toolExposure: Schema.optionalKey(Snapshot),
260
263
  runId: RunId,
261
264
  turnId: TurnId,
@@ -796,4 +799,4 @@ const CURRENT_CANONICAL_SCHEMA_VERSION = 1;
796
799
  //#endregion
797
800
  export { ToolStepSettled as $, Records_exports as A, SubagentRequested as B, ObservationOffset as C, ProducerId as D, ProducerEpoch as E, RunStartedRecord as F, ThreadCreated as G, SubmissionSettled as H, SettlementFailureDiagnostic as I, ToolCallPrepared as J, ToolApprovalDecided as K, SettlementOutcome as L, RunCompleted as M, RunFailed as N, RecordEnvelope as O, RunPolicyUsageReserved as P, ToolCallUnknown as Q, SubagentJoined as R, ModelResponseRecorded as S, PersistedJson as T, SubmissionSettledRecord as U, SubagentStarted as V, SubtreeBudgetReserved as W, ToolCallResolved as X, ToolCallResolution as Y, ToolCallSettled as Z, MAX_PERSISTED_JSON_COLLECTION_LENGTH as _, CURRENT_CANONICAL_SCHEMA_VERSION as a, WorkerOriginRecorded as at, ModelCompleted as b, CanonicalRecordEnvelope as c, WorkerReportingIntent as ct, CompactionCreated as d, UserInputRecorded as et, DefinitionDigestInput as f, MAX_PERSISTED_JSON_BYTES as g, Digest as h, BatchId as i, WorkerOrigin as it, RepairAnnotated as j, RecordId as k, CanonicalRecordPayload as l, strictSchema as lt, DeploymentId as m, AgentUpdateEmitted as n, WorkerInputCompleted as nt, CanonicalBatch as o, WorkerReportPrepared as ot, DefinitionDigests as p, ToolApprovalRequested as q, ApprovalDecision as r, WorkerInputRequested as rt, CanonicalRecord as s, WorkerReportRefused as st, AbortRequested as t, WorkerAdmission as tt, CanonicalSequence as u, MAX_PERSISTED_JSON_DEPTH as v, PeerMessagePrepared as w, ModelResponseInterrupted as x, MAX_PERSISTED_JSON_NODES as y, SubagentLineageRecorded as z };
798
801
 
799
- //# sourceMappingURL=Records-C9cezOEf.mjs.map
802
+ //# sourceMappingURL=Records-CsEsSW2o.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Records-CsEsSW2o.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/** Digests make a replay-visible definition/configuration change explicit. */\nexport class DefinitionDigests extends Schema.Class<DefinitionDigests>(\n \"@effect-agent/thread/DefinitionDigests\",\n)({\n agent: Digest,\n model: Digest,\n tools: Digest,\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 clock and duration allowance for one logical Run, 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\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/**\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 /** 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 and are visible while recovering this Run, but later Runs omit\n * them from their model-facing history. 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}) {}\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 /** 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 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,KAAK,OAAO,MAAM,wBAAwB,MAAM,CAAC;;AAGzE,MAAa,WAAW,WAAW,UAAU;;AAI7C,MAAa,UAAU,WAAW,SAAS;;AAI3C,MAAa,eAAe,WAAW,cAAc;;AAIrD,MAAa,aAAa,WAAW,YAAY;;AAIjD,MAAa,SAAS,OAAO,OAAO,MAAM,OAAO,UAAU,gBAAgB,CAAC,CAAC,CAAC,KAC5E,OAAO,MAAM,6BAA6B,CAC5C;;AAKA,MAAa,oBAAoB,WAAW,mBAAmB;;AAI/D,MAAa,oBAAoB,OAAO,QAAQ,KAC9C,OAAO,MAAM,wCAAwC,CACvD;;AAKA,MAAa,gBAAgB,OAAO,QAAQ,KAC1C,OAAO,MAAM,oCAAoC,CACnD;AAIA,MAAM,cAAc,OAAO,OAAO,MAAM,OAAO,YAAY,KAAS,CAAC;AACrE,MAAM,cAAc,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC;;AAGvE,MAAM,uBAAuB,OAAO,eAAe,MAAM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,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 { M as RunCompleted, O as RecordEnvelope, S as ModelResponseRecorded, T as PersistedJson, Z as ToolCallSettled, d as CompactionCreated, i as BatchId, k as RecordId, o as CanonicalBatch } from "./Records-C9cezOEf.mjs";
7
+ import { M as RunCompleted, O as RecordEnvelope, S as ModelResponseRecorded, T as PersistedJson, Z as ToolCallSettled, d as CompactionCreated, i as BatchId, k as RecordId, o as CanonicalBatch } from "./Records-CsEsSW2o.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";
@@ -690,6 +690,7 @@ const modelResponseRecord = Effect.fn("RunJournal.modelResponseRecord")(function
690
690
  createdAt: input.createdAt,
691
691
  deploymentId: input.deploymentId,
692
692
  payload: ModelResponseRecorded.make({
693
+ ...input.toolParameterRejections === void 0 || input.toolParameterRejections.length === 0 ? {} : { toolParameterRejections: input.toolParameterRejections },
693
694
  ...input.toolExposure === void 0 ? {} : { toolExposure: input.toolExposure },
694
695
  runId: input.runId,
695
696
  turnId: input.turnId,
@@ -822,4 +823,4 @@ const turnResultsBatch = Effect.fn("RunJournal.turnResultsBatch")(function* (inp
822
823
  //#endregion
823
824
  export { toolCallResolutionBatchId as A, turnIdForRun as B, subagentRequestedBatchId as C, toolApprovalDecisionRecordId as D, subagentStartedRecordId as E, toolStepSettledBatchId as F, turnResultsBatchId as G, turnResponseBatch as H, toolStepSettledRecordId as I, makeJournalMetadata as K, turnApprovalsBatchId as L, toolCallResultBatchId as M, toolCallSettledRecordId as N, toolApprovalRequestRecordId as O, toolCallUnknownRecordId as P, turnBatchId as R, subagentLineageRecordId as S, subagentStartedBatchId as T, turnResponseBatchId as U, turnPreparedBatchId as V, turnResultsBatch as W, runStartedBatchId as _, childThreadIdFor as a, subagentJoinedRecordId as b, markUnknownBatchId as c, modelResponseRecordId as d, projectRunJournal as f, runIdForSubmission as g, runCompletedRecordId as h, childIdempotencyKeyFor as i, toolCallResolvedRecordId as j, toolCallPreparedRecordId as k, modelResponseInterruptedBatchId as l, promptFromCanonicalRecords as m, RunJournal_exports as n, compactionBatchId as o, projectRunJournalStream as p, approvalDecisionBatchId as r, compactionRecordId as s, RunJournalError as t, modelResponseInterruptedRecordId as u, runStartedRecordId as v, subagentRequestedRecordId as w, subagentLineageBatchId as x, subagentJoinBatchId as y, turnCanonicalBatch as z };
824
825
 
825
- //# sourceMappingURL=RunJournal-lwbrh2hZ.mjs.map
826
+ //# sourceMappingURL=RunJournal-yYpUlTOE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RunJournal-yYpUlTOE.mjs","names":[],"sources":["../src/durable/internal/journal-metadata.ts","../src/durable/RunJournal.ts"],"sourcesContent":["import { type RunId } from \"../../core/Identifiers.ts\";\nimport {\n type CanonicalRecordEnvelope,\n type CompactionCreated,\n type ToolCallSettled,\n} from \"../Records.ts\";\nimport { type JournalCheckpointSeed } from \"./journal-checkpoint.ts\";\n\n/** Metadata for one exact canonical prefix, including the same optional checkpoint seed. */\nexport interface JournalMetadata {\n readonly ownerRunId: RunId | undefined;\n readonly seed: JournalCheckpointSeed | undefined;\n readonly firstSequenceByRun: ReadonlyMap<string, number>;\n readonly lastResponseSequenceByRun: ReadonlyMap<string, number>;\n readonly terminalSequenceByRun: ReadonlyMap<string, number>;\n readonly settledSpans: ReadonlyArray<{ readonly from: number; readonly to: number }>;\n readonly settledToolCallRecordIds: ReadonlySet<string>;\n readonly settledById: ReadonlyMap<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >;\n readonly compactions: ReadonlyArray<{\n readonly payload: CompactionCreated;\n readonly sequence: number;\n }>;\n}\n\n/**\n * Attempt-local metadata collector. Feed every validated record exactly once, in canonical order,\n * including records omitted from the control view. A snapshot is independent of later suffix\n * additions and may only accompany a replay stream bounded at that same captured tail.\n */\nexport const makeJournalMetadata = (\n ownerRunId: RunId | undefined,\n seed?: JournalCheckpointSeed,\n) => {\n const firstSequenceByRun = new Map<string, number>();\n\n if (seed?.firstSequence !== undefined) firstSequenceByRun.set(seed.runId, seed.firstSequence);\n const lastResponseSequenceByRun = new Map<string, number>();\n const terminalSequenceByRun = new Map<string, number>();\n const settledSpans: Array<{ readonly from: number; readonly to: number }> = [];\n const settledToolCallRecordIds = new Set<string>();\n\n const settledById = new Map<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >();\n\n const compactions: Array<{ readonly payload: CompactionCreated; readonly sequence: number }> = [];\n\n return {\n add: (envelope: CanonicalRecordEnvelope): void => {\n const payload = envelope.record.payload;\n\n if (\n (payload._tag === \"RunCompleted\" ||\n payload._tag === \"RunFailed\" ||\n payload._tag === \"SubmissionSettled\") &&\n payload.runId !== undefined &&\n !terminalSequenceByRun.has(payload.runId)\n )\n terminalSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"CompactionCreated\") {\n compactions.push({ payload, sequence: envelope.sequence });\n\n return;\n }\n if (\n \"runId\" in payload &&\n typeof payload.runId === \"string\" &&\n !firstSequenceByRun.has(payload.runId)\n )\n firstSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"ModelResponseRecorded\") {\n lastResponseSequenceByRun.set(payload.runId, envelope.sequence);\n } else if (payload._tag === \"ToolCallSettled\") {\n settledToolCallRecordIds.add(envelope.record.recordId);\n if (payload.runId === ownerRunId)\n settledById.set(envelope.record.recordId, {\n isFailure: payload.isFailure,\n ...(payload.toolSelection === undefined\n ? {}\n : { toolSelection: payload.toolSelection }),\n ...(payload.budgetRejected === undefined\n ? {}\n : { budgetRejected: payload.budgetRejected }),\n });\n const from = lastResponseSequenceByRun.get(payload.runId);\n\n if (from !== undefined && from < envelope.sequence)\n settledSpans.push({ from, to: envelope.sequence });\n }\n },\n snapshot: (): JournalMetadata => ({\n ownerRunId,\n seed,\n firstSequenceByRun: new Map(firstSequenceByRun),\n lastResponseSequenceByRun: new Map(lastResponseSequenceByRun),\n terminalSequenceByRun: new Map(terminalSequenceByRun),\n settledSpans: [...settledSpans],\n settledToolCallRecordIds: new Set(settledToolCallRecordIds),\n settledById: new Map(settledById),\n compactions: [...compactions],\n }),\n };\n};\n","import { type Crypto, Effect, Schema, Stream, type DateTime } from \"effect\";\nimport { Prompt } from \"effect/unstable/ai\";\n\nimport { ThreadId, RunId, ToolCallId, TurnId, type SubmissionId } from \"../core/Identifiers.ts\";\nimport { type ExhaustedLimit } from \"../core/RunEvent.ts\";\nimport { RunPolicyUsage } from \"../core/RunPolicyUsage.ts\";\nimport { type Selection, type Snapshot } from \"../core/ToolExposure.ts\";\nimport type { ToolParameterRejection } from \"../core/ToolResult.ts\";\nimport { ModelCallUsage, summarizeModelUsage, type RunUsageSummary } from \"../core/Usage.ts\";\nimport {\n CLEARED_TOOL_RESULT,\n COMPACTION_SUMMARY_PREFIX,\n contextWindowId,\n contextWindowMessage,\n} from \"../engine/Compaction.ts\";\nimport { digestJson, type DigestError } from \"./Digest.ts\";\nimport { type JournalCheckpointSeed } from \"./internal/journal-checkpoint.ts\";\nimport { makeJournalMetadata, type JournalMetadata } from \"./internal/journal-metadata.ts\";\nimport {\n BatchId,\n CanonicalBatch,\n CompactionCreated,\n ModelResponseRecorded,\n PersistedJson,\n RecordEnvelope,\n RecordId,\n RunCompleted,\n ToolCallSettled,\n type CanonicalRecordEnvelope,\n type CanonicalSequence,\n type DeploymentId,\n type ProducerId,\n} from \"./Records.ts\";\nimport { IdempotencyKey } from \"./SubmissionLedger.ts\";\n\n/** A canonical record could not be projected into Run/Prompt state. */\nexport class RunJournalError extends Schema.TaggedError<RunJournalError>()(\"RunJournalError\", {\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n}) {}\n\nconst journalError = (message: string, cause?: unknown): RunJournalError =>\n cause === undefined\n ? RunJournalError.make({ message })\n : RunJournalError.make({ message, cause });\n\nconst decodeRunId = Schema.decodeSync(RunId);\nconst decodeTurnId = Schema.decodeSync(TurnId);\nconst decodeBatchId = Schema.decodeSync(BatchId);\nconst decodeRecordId = Schema.decodeSync(RecordId);\n\n/**\n * Deterministic Run identity pinned per Submission (plan §Coordinator flow). Every Attempt of one\n * Submission shares this Run identity, so canonical per-Turn records from different Attempts\n * belong to one logical Run.\n */\nexport const runIdForSubmission = (submissionId: SubmissionId): RunId =>\n decodeRunId(`run:${submissionId}`);\n\n/** Stable canonical clock identity shared by every Attempt of one Run. */\nexport const runStartedRecordId = (runId: RunId): RecordId => decodeRecordId(`run-start:${runId}`);\n\nexport const runStartedBatchId = (runId: RunId): BatchId => decodeBatchId(`run-start:${runId}`);\n\n/** Deterministic Turn identity: Attempt-independent for one (Run, canonical turn) pair. */\nexport const turnIdForRun = (runId: RunId, turn: number): TurnId =>\n decodeTurnId(`turn:${runId}:${turn}`);\n\n/** Deterministic batch identity of one committed canonical no-tool Turn (P4 single-batch shape). */\nexport const turnBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESPONSE commit (plan §2.1 commit 1):\n * the assistant response plus pending steering becomes canonical BEFORE approval preflight and\n * tool preparation, creating the durability §15 \"resume tool scheduling\" window.\n */\nexport const turnResponseBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-response:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESULTS commit (plan §2.1 commit 5):\n * every `ToolCallSettled` record of the Turn, in declaration order, model-visible atomically.\n */\nexport const turnResultsBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-results:${runId}:${turn}`);\n\n/**\n * Deterministic per-call late-settle batch identity used by the resolution path when one\n * recovered/resolved call settles outside its Turn's results batch. Record identity\n * (`tool-settled:{runId}:{turn}:{toolCallId}`) dedupes double-settles across both paths.\n */\nexport const toolCallResultBatchId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`turn-results:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Turn's `ToolCallPrepared` commit (plan §2.1 commit 3). */\nexport const turnPreparedBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-prepared:${runId}:${turn}`);\n\n/**\n * Deterministic identity of one pre-Turn compaction record (RUN-026,\n * RUN-026). Keyed by Run, Turn, and kind — the engine performs at most one\n * threshold compaction per Turn plus at most one overflow-forced summarize,\n * so a superseding Attempt that re-decides the same compaction replays the\n * batch identity instead of duplicating the record.\n */\nexport const compactionRecordId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): RecordId => decodeRecordId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic batch identity of one compaction append (same string as its record id). */\nexport const compactionBatchId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): BatchId => decodeBatchId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic canonical record identity of one Turn's `ModelResponseRecorded` record. */\nexport const modelResponseRecordId = (runId: RunId, turn: number): RecordId =>\n decodeRecordId(`model-response:${runId}:${turn}`);\n\n/** Terminal Tool completion marker committed atomically with its settled Tool result. */\nexport const runCompletedRecordId = (runId: RunId): RecordId =>\n decodeRecordId(`run-completed:${runId}`);\n\n/** Deterministic canonical record identity of one Turn's `ToolCallSettled` record. */\nexport const toolCallSettledRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-settled:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallPrepared` record. */\nexport const toolCallPreparedRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-prepared:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Turn's `ToolCallUnknown` marking append. */\nexport const markUnknownBatchId = (submissionId: SubmissionId, turn: number): BatchId =>\n decodeBatchId(`mark-unknown:${submissionId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallUnknown` record. */\nexport const toolCallUnknownRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-unknown:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's resolution append (DUR-017). */\nexport const toolCallResolutionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`resolve:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallResolved` record. */\nexport const toolCallResolvedRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`tool-resolved:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one accepted Durable Step result. The one-record batch reuses the\n * SAME string, so batch idempotency plus the epoch fence realize the durability §11\n * racing-writers rule: only the fenced winner's record commits; the loser replays it.\n * A versioned JSON tuple keeps separator characters in each identity component distinct.\n * Replay derives this key from the structured payload, including records with legacy IDs.\n */\nexport const toolStepSettledRecordId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): RecordId => decodeRecordId(JSON.stringify([\"step@2\", runId, toolCallId, stepName]));\n\n/** Deterministic batch identity of one Durable Step commit (same string as its record id). */\nexport const toolStepSettledBatchId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): BatchId => decodeBatchId(toolStepSettledRecordId(runId, toolCallId, stepName));\n\n/** Deterministic batch identity of one Turn's canonical approval-request append (plan §2.6). */\nexport const turnApprovalsBatchId = (runId: RunId, turn: number): BatchId =>\n decodeBatchId(`turn-approvals:${runId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalRequested` record. */\nexport const toolApprovalRequestRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`approval-request:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's canonical approval-decision append. */\nexport const approvalDecisionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => decodeBatchId(`approval-decision:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalDecided` record. */\nexport const toolApprovalDecisionRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => decodeRecordId(`approval-decision:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one superseded Attempt's `ModelResponseInterrupted` audit record\n * (durability §9). Keyed by the superseded epoch, so each interrupted ownership period is\n * recorded at most once; the one-record batch reuses the same string.\n */\nexport const modelResponseInterruptedRecordId = (runId: RunId, supersededEpoch: number): RecordId =>\n decodeRecordId(`interrupted:${runId}:${supersededEpoch}`);\n\n/** Deterministic batch identity of one `ModelResponseInterrupted` append (same string). */\nexport const modelResponseInterruptedBatchId = (runId: RunId, supersededEpoch: number): BatchId =>\n decodeBatchId(`interrupted:${runId}:${supersededEpoch}`);\n\nconst decodeThreadId = Schema.decodeSync(ThreadId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentRequested` record.\n * The one-record batch reuses the same string, so batch\n * idempotency plus the parent epoch fence make the request append exactly-once-canonical.\n */\nexport const subagentRequestedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-requested:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentRequested` append (same string). */\nexport const subagentRequestedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-requested:${runId}:${toolCallId}`);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentStarted` record.\n * Recovery's start-link repair appends the EXACT same record\n * under this identity, so a raced repair replays instead of duplicating (SUB-016/SUB-017).\n */\nexport const subagentStartedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-started:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentStarted` append (same string). */\nexport const subagentStartedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-started:${runId}:${toolCallId}`);\n\n/**\n * Deterministic batch identity of one parent Tool Call's atomic settlement join: the\n * `SubagentJoined` record plus the parent's `ToolCallSettled` record (its existing\n * `tool-settled:{runId}:{turn}:{toolCallId}` identity) commit as ONE canonical batch (SUB-019).\n */\nexport const subagentJoinBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n decodeBatchId(`subagent-join:${runId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one parent Tool Call's `SubagentJoined` record. */\nexport const subagentJoinedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n decodeRecordId(`subagent-joined:${runId}:${toolCallId}`);\n\n/**\n * Deterministic identity of one child Thread's `SubagentLineageRecorded` record.\n * Its own single-record batch reuses the same string so the generic\n * `thread-created:{cid}` batch identity is never contradicted.\n */\nexport const subagentLineageRecordId = (threadId: ThreadId): RecordId =>\n decodeRecordId(`subagent-lineage:${threadId}`);\n\n/** Deterministic batch identity of one `SubagentLineageRecorded` append (same string). */\nexport const subagentLineageBatchId = (threadId: ThreadId): BatchId =>\n decodeBatchId(`subagent-lineage:${threadId}`);\n\n/**\n * Deterministic intended child Thread identity: the\n * parent Submission and Tool Call pair addresses exactly one child Thread, so a replayed\n * establishment converges on the one existing child (SUB-016).\n */\nexport const childThreadIdFor = (\n parentSubmissionId: SubmissionId,\n toolCallId: ToolCallId,\n): ThreadId => decodeThreadId(`subagent:${parentSubmissionId}:${toolCallId}`);\n\n/**\n * Deterministic child admission idempotency key: scoped to\n * the parent Run and Tool Call identity, so duplicate admission attempts resolve through the\n * ledger's idempotency contract to one child Receipt (SUB-016, SUB-031). The ledger key is\n * bounded (256); coordinator-minted Run and Tool Call identities stay far below that bound.\n */\nexport const childIdempotencyKeyFor = (\n parentRunId: RunId,\n toolCallId: ToolCallId,\n): IdempotencyKey => decodeIdempotencyKey(`subagent:${parentRunId}:${toolCallId}`);\n\nconst decodePromptMessages = Effect.fn(\"RunJournal.decodePromptMessages\")(\n (messages: PersistedJson): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n Schema.decodeUnknownEffect(Prompt.Prompt)(messages).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical messages are not Schema-encoded Prompt messages\", cause),\n ),\n ),\n);\n\ninterface PendingSettledTool {\n readonly record: ToolCallSettled;\n /** RUN-026: a `clear-tool-results` compaction covers this record's sequence. */\n readonly cleared: boolean;\n}\n\nconst toolMessageFromSettled = Effect.fn(\"RunJournal.toolMessageFromSettled\")(\n (settled: ReadonlyArray<PendingSettledTool>): Effect.Effect<Prompt.Message, RunJournalError> =>\n Effect.try({\n try: () =>\n Prompt.makeMessage(\"tool\", {\n content: settled.map(({ record, cleared }) =>\n Prompt.makePart(\"tool-result\", {\n id: record.toolCallId,\n name: record.toolName,\n result: cleared ? CLEARED_TOOL_RESULT : record.result,\n isFailure: record.isFailure,\n providerExecuted: false,\n }),\n ),\n }),\n catch: (cause) => journalError(\"Unable to rebuild Tool message from ToolCallSettled\", cause),\n }),\n);\n\n/**\n * Pure canonical projection of one Run's durable execution state.\n *\n * Prompt reconstruction contract (D8):\n *\n * - `ModelResponseRecorded.messages` carries the Schema-encoded Prompt messages the Turn appended\n * to the model-visible prompt — for the Run's FIRST committed Turn that includes the evaluated\n * instruction and user-input messages, for later Turns only the assistant response messages.\n * Tool messages are excluded from `messages`.\n * - `ToolCallSettled` records (committed in the same per-Turn batch, in declaration order)\n * deterministically rebuild the Turn's single Tool message.\n * - `UserInputRecorded` records input, with a Submission identity only for durable admission. Its\n * Prompt-visible form (instructions + user message) becomes canonical inside the owning Run's\n * first `ModelResponseRecorded`. The projection consumes it only for Run correlation.\n * - Immediate retained history uses `ModelCompleted.messages` for the successful Run's exact\n * native Prompt suffix, including any input examples. It has no resumable Turn state.\n */\n/** Cumulative committed usage of the projected Run (RUN-023 resume re-seed). */\nexport interface RunJournalUsage {\n readonly modelCalls: number;\n /** Known accounting gaps retained across Attempts without changing numeric usage totals. */\n readonly unobservedModelCalls?: number | undefined;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly lastInputTokens: number;\n readonly lastOutputTokens: number;\n /** Cumulative persisted spend of the projected Run's committed calls (RUN-023). */\n readonly costMicrousd: number;\n /** Canonical per-call detail used for settlement aggregation and recovery. */\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n /** Detailed usage of retired records, grouped without retaining per-call payloads. */\n readonly summarizedModelUsage?: RunUsageSummary | undefined;\n}\n\nexport interface RunJournalProjection {\n readonly toolSelection?: Selection | undefined;\n readonly policyUsage: RunPolicyUsage;\n /** Canonical projection for the requested Run; may end at its resumable Tool declaration. */\n readonly prompt: Prompt.Prompt;\n /** Valid prior-Run history excluding the projected Run's records and orphan Tool batches. */\n readonly historyBefore: Prompt.Prompt;\n /** Number of canonical Turns already committed for the projected Run. */\n readonly committedTurns: number;\n /** Summed per-call usage of the projected Run's committed responses; zeros for records predating usage capture. */\n readonly usage: RunJournalUsage;\n /** Latest committed context window identity, retained across ownership changes. */\n readonly contextWindowId?: string | undefined;\n /** Canonical evaluated instructions and initial input for this Run, independent of the view. */\n readonly protectedContext?: Prompt.Prompt | undefined;\n /** Last successful singleton Tool awaiting possible context-control interpretation by the engine. */\n readonly pendingContextToolCallId?: string | undefined;\n}\n\ninterface ProjectedResponseUsage {\n readonly modelCalls: number;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd: number;\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n}\n\nconst projectedResponseUsage = (\n response: ModelResponseRecorded,\n): Effect.Effect<ProjectedResponseUsage, RunJournalError> =>\n Effect.gen(function* () {\n const calls = response.modelUsage;\n\n if (calls === undefined) {\n return {\n modelCalls: 1,\n inputTokens: response.inputTokens ?? 0,\n outputTokens: response.outputTokens ?? 0,\n costMicrousd: response.costMicrousd ?? 0,\n modelUsage: [],\n };\n }\n if (calls.length === 0) {\n return yield* journalError(\"A canonical modelUsage list must not be empty\");\n }\n\n const summary = yield* summarizeModelUsage(calls).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical model usage exceeds accounting bounds\", cause),\n ),\n );\n\n if (\n (response.inputTokens !== undefined && response.inputTokens !== summary.inputTokens.total) ||\n (response.outputTokens !== undefined &&\n response.outputTokens !== summary.outputTokens.total) ||\n (response.costMicrousd !== undefined && response.costMicrousd !== summary.costMicrousd)\n ) {\n return yield* journalError(\"Canonical detailed and aggregate model usage disagree\");\n }\n\n return {\n modelCalls: summary.modelCalls,\n inputTokens: summary.inputTokens.total,\n outputTokens: summary.outputTokens.total,\n costMicrousd: summary.costMicrousd,\n modelUsage: calls,\n };\n });\n\nconst addProjectedUsage = (\n field: string,\n left: number,\n right: number,\n): Effect.Effect<number, RunJournalError> =>\n Schema.decodeEffect(Schema.Natural)(left + right).pipe(\n Effect.mapError((cause) =>\n journalError(`Canonical projected usage exceeds safe-integer bounds at ${field}`, cause),\n ),\n );\n\ninterface FoldState {\n readonly all: Array<Prompt.Message>;\n readonly before: Array<Prompt.Message>;\n readonly pendingTools: Array<PendingSettledTool>;\n readonly pendingToolsForRun: boolean;\n readonly committedTurns: number;\n}\n\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\n\nconst declaredApplicationToolCallIds = (prompt: Prompt.Prompt): ReadonlyArray<string> => {\n const ids: Array<string> = [];\n\n for (const message of prompt.content) {\n if (message.role !== \"assistant\") continue;\n for (const part of message.content) {\n if (part.type === \"tool-call\" && !part.providerExecuted) ids.push(part.id);\n }\n }\n\n return ids;\n};\n\nconst withoutApplicationToolCallMessages = (prompt: Prompt.Prompt): ReadonlyArray<Prompt.Message> =>\n prompt.content.filter(\n (message) =>\n message.role !== \"assistant\" ||\n !message.content.some((part) => part.type === \"tool-call\" && !part.providerExecuted),\n );\n\n/**\n * Phase 5 audit tags that are prompt-transparent: they carry durability evidence (preparation,\n * unknown marking, resolution, Step results, approvals, interruption) but contribute nothing to\n * the model-visible Prompt, and — unlike the P4 tags — they do NOT split a contiguous\n * `ToolCallSettled` group into separate Tool messages, so a late-settled call's audit records\n * cannot change the replayed prompt shape.\n *\n * The four S2 Subagent lifecycle tags are prompt-transparent for the same reason (spec §5/§11):\n * the parent prompt never carries child transcript or establishment evidence — the joined child\n * result reaches the model exclusively through the paired `ToolCallSettled` record, and the\n * child-log lineage record is not model input.\n */\nconst PROMPT_TRANSPARENT_TAGS: ReadonlySet<string> = new Set([\n \"RunPolicyUsageReserved\",\n \"RunStarted\",\n \"ToolCallPrepared\",\n \"ToolCallUnknown\",\n \"ToolCallResolved\",\n \"ToolStepSettled\",\n \"ToolApprovalRequested\",\n \"ToolApprovalDecided\",\n \"ModelResponseInterrupted\",\n \"SubagentRequested\",\n \"SubagentStarted\",\n \"SubagentJoined\",\n \"SubagentLineageRecorded\",\n \"WorkerInputRequested\",\n \"WorkerOriginRecorded\",\n \"WorkerInputCompleted\",\n \"WorkerReportPrepared\",\n \"AgentUpdateEmitted\",\n \"WorkerReportRefused\",\n \"PeerMessagePrepared\",\n \"SubtreeBudgetReserved\",\n]);\n\n/**\n * Pure projection: rebuild one Run's resume state from canonical records (DUR-015). Canonical\n * order is authoritative; the fold projects each complete `ModelResponseRecorded` Turn and the\n * owning Run's resumable incomplete Tool Turn, while excluding incomplete Tool batches from prior\n * Runs. It flushes each contiguous group of valid `ToolCallSettled` records into one Tool message,\n * exactly mirroring the per-Turn commit shape produced by `turnCanonicalBatch` (no-tool Turns) and\n * by the\n * `turnResponseBatch`/`turnResultsBatch` split (tool-declaring Turns). The Phase 5 audit tags\n * are skipped transparently, so split-batch commits replay to the same prompt as P4 single-batch\n * commits.\n *\n * An incomplete application Tool turn remains visible while projecting its owning Run so active\n * recovery can resume the declared batch. It is not a valid model-visible Turn boundary for a\n * later Run: the orphan assistant Tool declaration and any partial Tool results from that Turn\n * are excluded, while preceding instruction/user messages in the response record remain history.\n */\n/** @internal Lightweight canonical boundaries collected without retaining record payloads. */\nexport interface JournalBoundary {\n readonly sequence: CanonicalSequence;\n readonly tag: \"ModelResponseRecorded\" | \"ToolCallSettled\";\n readonly promptLength: number;\n /** A declaration without all settled results requires terminal-prior-Run proof for coverage. */\n readonly incomplete?: true | undefined;\n /** The Run terminated after its last response and differs from the projection's owner. */\n readonly terminalPriorRun?: true | undefined;\n}\n\n/**\n * Reconstruct a fixed canonical prefix from a re-readable stream. The caller must keep the same\n * records visible on every traversal. The first collects compaction and settlement metadata;\n * rollovers additionally validate covered Tool batches before rebuilding Prompt and usage. Metadata and the\n * live Prompt remain resident; covered historical message/tool payloads do not. An uncompacted Prompt still grows\n * with its conversation, so hosts must configure an appropriate context compaction policy.\n * Prepared metadata must describe exactly this stream and seed through the same fixed tail;\n * it skips only the metadata scan, never covered-Tool validation or the canonical fold.\n * @internal\n */\nexport const projectRunJournalStream = Effect.fn(\"RunJournal.projectRunJournalStream\")(function* <\n E,\n R,\n>(\n records: Stream.Stream<CanonicalRecordEnvelope, E, R>,\n ownerRunId: RunId | undefined,\n onBoundary?: (boundary: JournalBoundary) => void,\n seed?: JournalCheckpointSeed,\n preparedMetadata?: JournalMetadata,\n): Effect.fn.Return<RunJournalProjection, RunJournalError | E, R> {\n if (seed !== undefined && seed.runId !== ownerRunId)\n return yield* journalError(\"Recovery checkpoint belongs to another Run\");\n\n let state: FoldState = {\n all: [],\n before: [],\n pendingTools: [],\n pendingToolsForRun: false,\n committedTurns: seed?.committedTurns ?? 0,\n };\n\n // RUN-026 pre-scan: the widest VALID compaction bounds govern the fold. A\n // valid record covers strictly below its own sequence and never splits a response from its\n // settled tool results. Pruning and rollovers may cover complete owner-Run batches;\n // a summarize record must carry its summary. Invalid records\n // are ignored fail-safe — the full history stays authoritative. Ties on\n // coversThrough resolve to the record appended later (higher sequence),\n // matching at-most-once replay intent.\n // One span per settled record, paired with its declaring response the same\n // way the fold pairs them: a settled belongs to the most recent\n // ModelResponseRecorded of its Run. A bound inside (response, settled)\n // would orphan the tool message from its declaring response. Orphaned\n // settleds (filtered later by the fold) still contribute spans —\n // over-invalidating is the fail-safe direction.\n if (\n preparedMetadata !== undefined &&\n (preparedMetadata.ownerRunId !== ownerRunId || preparedMetadata.seed !== seed)\n )\n return yield* journalError(\"Prepared journal metadata belongs to another replay\");\n\n let metadata = preparedMetadata;\n\n if (metadata === undefined) {\n const collected = makeJournalMetadata(ownerRunId, seed);\n\n yield* Stream.runForEach(records, (envelope) => Effect.sync(() => collected.add(envelope)));\n metadata = collected.snapshot();\n }\n\n const {\n firstSequenceByRun,\n lastResponseSequenceByRun,\n terminalSequenceByRun,\n settledSpans,\n settledToolCallRecordIds,\n settledById,\n compactions,\n } = metadata;\n\n const settledCoverage = compactions.reduce(\n (through, { payload }) =>\n payload.kind !== \"summarize\" ? Math.max(through, payload.coversThrough) : through,\n 0,\n );\n\n // Terminality changes only prompt coverage; it never settles or resolves the Tool Call.\n // Compare against the compaction's Run and sequence, independent of the replay's owner.\n const isTerminalPriorRun = (\n candidateRunId: RunId,\n compactionRunId: RunId | undefined,\n beforeSequence: number,\n ): boolean => {\n const terminal = terminalSequenceByRun.get(candidateRunId);\n\n return (\n candidateRunId !== compactionRunId &&\n terminal !== undefined &&\n terminal < beforeSequence &&\n terminal > (lastResponseSequenceByRun.get(candidateRunId) ?? 0)\n );\n };\n\n const incompleteResponseSequences: Array<{ readonly sequence: number; readonly runId: RunId }> =\n [];\n\n let ownerPrefixSequence = seed?.firstSequence ?? Number.POSITIVE_INFINITY;\n\n let protectedContext: Prompt.Prompt | undefined =\n seed?.protectedContext === undefined\n ? undefined\n : yield* decodePromptMessages(seed.protectedContext);\n\n if (settledCoverage > 0) {\n yield* Stream.runForEach(records, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (payload._tag !== \"ModelResponseRecorded\" || envelope.sequence > settledCoverage) return;\n const messages = yield* decodePromptMessages(payload.messages);\n const declared = declaredApplicationToolCallIds(messages);\n\n for (const id of declared) {\n const callId = yield* Schema.decodeEffect(ToolCallId)(id).pipe(\n Effect.mapError((cause) =>\n journalError(\"Failed to decode a declared Tool Call ID\", cause),\n ),\n );\n\n if (\n !settledToolCallRecordIds.has(\n toolCallSettledRecordId(payload.runId, payload.turn, callId),\n )\n ) {\n incompleteResponseSequences.push({ sequence: envelope.sequence, runId: payload.runId });\n break;\n }\n }\n if (\n payload.runId === ownerRunId &&\n payload.turn === 1 &&\n payload.runScopedPrefixLength !== undefined\n ) {\n ownerPrefixSequence = envelope.sequence;\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n }),\n );\n }\n\n const boundIsValid = (payload: CompactionCreated, ownSequence: number): boolean => {\n const { runId, coversThrough } = payload;\n\n if (coversThrough <= 0 || coversThrough >= ownSequence) return false;\n if (seed !== undefined && ownSequence === seed.compaction.sequence)\n return (\n seed.compaction.record.payload._tag === \"CompactionCreated\" &&\n Schema.toEquivalence(CompactionCreated)(payload, seed.compaction.record.payload)\n );\n const ownerFirst = firstSequenceByRun.get(runId);\n\n if (payload.kind === \"summarize\" && ownerFirst !== undefined && coversThrough >= ownerFirst)\n return false;\n if (\n payload.kind !== \"summarize\" &&\n incompleteResponseSequences.some(\n (response) =>\n response.sequence <= coversThrough &&\n !isTerminalPriorRun(response.runId, runId, ownSequence),\n )\n )\n return false;\n for (const span of settledSpans) {\n if (span.from <= coversThrough && coversThrough < span.to) return false;\n }\n\n return true;\n };\n\n let summarizeBound = 0;\n let replacement: CompactionCreated | undefined;\n let summarizeSequence = -1;\n let clearBound = 0;\n let latestWindowId: string | undefined = seed?.contextWindowId;\n let latestWindowSequence = seed?.throughSequence ?? -1;\n let rolloverCoveredThrough = 0;\n\n for (const { payload, sequence } of compactions) {\n if (!boundIsValid(payload, sequence)) continue;\n if (payload.kind === \"rollover\" && sequence > latestWindowSequence) {\n latestWindowId = contextWindowId(payload.runId, payload.turn);\n latestWindowSequence = sequence;\n }\n if (payload.kind === \"rollover\")\n rolloverCoveredThrough = Math.max(rolloverCoveredThrough, payload.coversThrough);\n if (payload.kind === \"summarize\" || payload.kind === \"rollover\") {\n if (payload.kind === \"summarize\" && payload.summary === undefined) continue;\n if (\n payload.coversThrough > summarizeBound ||\n (payload.coversThrough === summarizeBound && sequence > summarizeSequence)\n ) {\n summarizeBound = payload.coversThrough;\n summarizeSequence = sequence;\n replacement = payload;\n }\n } else if (payload.coversThrough > clearBound) {\n clearBound = payload.coversThrough;\n }\n }\n let summaryEmitted = false;\n\n const retainedPrefix =\n replacement?.kind === \"rollover\" &&\n replacement.runId === ownerRunId &&\n ownerPrefixSequence <= summarizeBound\n ? (protectedContext?.content ?? [])\n : [];\n\n const replacementLength = replacement === undefined ? 0 : retainedPrefix.length + 1;\n\n if (seed?.frontier !== undefined)\n onBoundary?.({ ...seed.frontier, promptLength: replacementLength });\n\n const emitSummary = () => {\n if (summaryEmitted || replacement === undefined) return;\n summaryEmitted = true;\n\n const message =\n replacement.kind === \"rollover\"\n ? contextWindowMessage(\n contextWindowId(replacement.runId, replacement.turn),\n replacement.handoff,\n )\n : Prompt.makeMessage(\"user\", {\n content: [\n Prompt.makePart(\"text\", {\n text: `${COMPACTION_SUMMARY_PREFIX}${replacement.summary}`,\n }),\n ],\n });\n\n state.all.push(...retainedPrefix, message);\n if (replacement.kind !== \"rollover\" || replacement.runId !== ownerRunId)\n state.before.push(message);\n };\n\n const modelUsage: Array<ModelCallUsage> = [];\n let unobservedModelCalls = seed?.unobservedModelCalls ?? 0;\n\n const usage = {\n modelCalls: seed?.modelCalls ?? 0,\n inputTokens: seed?.inputTokens ?? 0,\n outputTokens: seed?.outputTokens ?? 0,\n lastInputTokens: seed?.lastInputTokens ?? 0,\n lastOutputTokens: seed?.lastOutputTokens ?? 0,\n costMicrousd: seed?.costMicrousd ?? 0,\n modelUsage,\n ...(seed === undefined ? {} : { summarizedModelUsage: seed.summarizedModelUsage }),\n };\n\n let toolSelection = seed?.toolSelection;\n let usageTurn = seed?.committedTurns ?? 0;\n\n const incompleteToolTurns = new Set<string>();\n const incompleteToolCalls = new Set<string>();\n let pendingContextToolCallId: string | undefined;\n let ownerTerminated = false;\n\n const policyUsage = {\n committedTurns: seed?.policyUsage.committedTurns ?? 0,\n toolCalls: seed?.policyUsage.toolCalls ?? 0,\n programmaticToolCalls: seed?.policyUsage.programmaticToolCalls ?? 0,\n consecutiveToolFailures: seed?.policyUsage.consecutiveToolFailures ?? 0,\n finalizationUsed: seed?.policyUsage.finalizationUsed ?? false,\n };\n\n const accountResponse = Effect.fn(\"RunJournal.accountResponse\")(function* (\n envelope: CanonicalRecordEnvelope,\n payload: ModelResponseRecorded,\n messages: Prompt.Prompt,\n ) {\n const record = envelope.record;\n\n const declared = declaredApplicationToolCallIds(messages);\n const declaredRecordIds: Array<RecordId> = [];\n\n for (const id of declared) {\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(id),\n catch: (cause) => journalError(\"Failed to decode a declared Tool Call ID\", cause),\n });\n\n declaredRecordIds.push(toolCallSettledRecordId(payload.runId, payload.turn, toolCallId));\n }\n if (declaredRecordIds.some((recordId) => !settledToolCallRecordIds.has(recordId))) {\n incompleteToolTurns.add(envelope.record.recordId);\n for (const recordId of declaredRecordIds) incompleteToolCalls.add(recordId);\n }\n if (payload.runId !== ownerRunId) return;\n if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;\n if (payload.turn === 1 && payload.runScopedPrefixLength !== undefined) {\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n\n const responseUsage = yield* projectedResponseUsage(payload);\n\n unobservedModelCalls = yield* addProjectedUsage(\n \"unobservedModelCalls\",\n unobservedModelCalls,\n payload.unobservedModelCalls ?? 0,\n );\n\n usage.modelCalls = yield* addProjectedUsage(\n \"modelCalls\",\n usage.modelCalls,\n responseUsage.modelCalls,\n );\n usage.inputTokens = yield* addProjectedUsage(\n \"inputTokens\",\n usage.inputTokens,\n responseUsage.inputTokens,\n );\n usage.outputTokens = yield* addProjectedUsage(\n \"outputTokens\",\n usage.outputTokens,\n responseUsage.outputTokens,\n );\n usage.costMicrousd = yield* addProjectedUsage(\n \"costMicrousd\",\n usage.costMicrousd,\n responseUsage.costMicrousd,\n );\n usage.modelUsage.push(...responseUsage.modelUsage);\n if (payload.turn > usageTurn) {\n usageTurn = payload.turn;\n usage.lastInputTokens = responseUsage.inputTokens;\n usage.lastOutputTokens = responseUsage.outputTokens;\n }\n\n policyUsage.committedTurns = Math.max(policyUsage.committedTurns, payload.turn);\n\n const calls = messages.content.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.filter((part) => part.type === \"tool-call\")\n : [],\n );\n\n const candidate = calls.length === 1 ? calls[0] : undefined;\n\n const candidateResult =\n candidate === undefined\n ? undefined\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${candidate.id}`);\n\n pendingContextToolCallId =\n candidate !== undefined &&\n !candidate.providerExecuted &&\n candidateResult?.isFailure === false &&\n candidateResult.budgetRejected !== true &&\n envelope.sequence > rolloverCoveredThrough\n ? candidate.id\n : undefined;\n\n policyUsage.toolCalls += calls.length;\n if (payload.toolExposure !== undefined) toolSelection = payload.toolExposure.selection;\n if (incompleteToolTurns.has(record.recordId)) return;\n for (const call of calls) {\n const result = call.providerExecuted\n ? messages.content\n .flatMap((message) => (message.role === \"assistant\" ? message.content : []))\n .find(\n (part) => part.type === \"tool-result\" && part.providerExecuted && part.id === call.id,\n )\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${call.id}`);\n\n if (result === undefined || (\"budgetRejected\" in result && result.budgetRejected === true))\n continue;\n if (!(\"isFailure\" in result)) continue;\n if (!result.isFailure && \"toolSelection\" in result && result.toolSelection !== undefined)\n toolSelection = result.toolSelection;\n policyUsage.consecutiveToolFailures = result.isFailure\n ? policyUsage.consecutiveToolFailures + 1\n : 0;\n }\n });\n\n let pendingToolOrder = new Map<string, number>();\n\n const flushTools = Effect.fn(\"RunJournal.flushTools\")(function* (\n current: FoldState,\n ): Effect.fn.Return<FoldState, RunJournalError> {\n if (current.pendingTools.length === 0) return current;\n\n // Suspension can persist an ordinary sibling before a delegated call joins. Model context\n // still uses declaration order, matching the live interpreter's completed results batch.\n const ordered = current.pendingTools.toSorted(\n (left, right) =>\n (pendingToolOrder.get(left.record.toolCallId) ?? Number.MAX_SAFE_INTEGER) -\n (pendingToolOrder.get(right.record.toolCallId) ?? Number.MAX_SAFE_INTEGER),\n );\n\n const toolMessage = yield* toolMessageFromSettled(ordered);\n\n current.all.push(toolMessage);\n if (!current.pendingToolsForRun) current.before.push(toolMessage);\n\n return {\n ...current,\n pendingTools: [],\n pendingToolsForRun: false,\n };\n });\n\n yield* Stream.runForEach(records, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (\n ((payload._tag === \"RunCompleted\" || payload._tag === \"RunFailed\") &&\n payload.runId === ownerRunId) ||\n (payload._tag === \"SubmissionSettled\" &&\n runIdForSubmission(payload.submissionId) === ownerRunId)\n )\n ownerTerminated = true;\n\n if (payload._tag === \"RunPolicyUsageReserved\" && payload.runId === ownerRunId) {\n if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;\n if (\n payload.programmaticToolCalls < policyUsage.programmaticToolCalls ||\n (policyUsage.finalizationUsed && !payload.finalizationUsed)\n ) {\n return yield* journalError(\"Run policy reservations must be monotonic\");\n }\n policyUsage.programmaticToolCalls = payload.programmaticToolCalls;\n policyUsage.finalizationUsed = payload.finalizationUsed;\n }\n if (PROMPT_TRANSPARENT_TAGS.has(payload._tag)) return;\n // The compaction record governs the fold (pre-scan) and contributes no\n // message of its own; records at or below the summarize bound render as\n // the one summary message emitted at the covered/kept transition.\n if (payload._tag === \"CompactionCreated\") return;\n if (\n seed !== undefined &&\n envelope.sequence <= seed.throughSequence &&\n (payload._tag === \"ModelResponseRecorded\" || payload._tag === \"ToolCallSettled\")\n )\n return;\n if (envelope.sequence <= summarizeBound) {\n // Projecting an earlier Run after a later summary still accounts for its covered responses.\n if (payload._tag === \"ModelResponseRecorded\" && payload.runId === ownerRunId) {\n const messages = yield* decodePromptMessages(payload.messages);\n\n yield* accountResponse(envelope, payload, messages);\n state = { ...state, committedTurns: Math.max(state.committedTurns, payload.turn) };\n }\n if (payload._tag === \"ModelResponseRecorded\" || payload._tag === \"ToolCallSettled\") {\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: replacementLength,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolTurns.has(envelope.record.recordId) ||\n incompleteToolCalls.has(envelope.record.recordId)\n ? { incomplete: true }\n : {}),\n });\n }\n\n return;\n }\n emitSummary();\n if (payload._tag === \"ToolCallSettled\") {\n if (payload.runId !== ownerRunId && incompleteToolCalls.has(envelope.record.recordId)) {\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length + (state.pendingTools.length === 0 ? 0 : 1),\n incomplete: true,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n });\n\n return;\n }\n if (\n state.pendingTools.length > 0 &&\n state.pendingToolsForRun !== (payload.runId === ownerRunId)\n ) {\n state = yield* flushTools(state);\n }\n state.pendingTools.push({ record: payload, cleared: envelope.sequence <= clearBound });\n state = {\n ...state,\n pendingToolsForRun: payload.runId === ownerRunId,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length + 1,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n\n return;\n }\n state = yield* flushTools(state);\n if (payload._tag === \"ModelCompleted\" && payload.messages !== undefined) {\n const messages = yield* decodePromptMessages(payload.messages);\n\n for (const message of messages.content) {\n state.all.push(message);\n if (payload.runId !== ownerRunId) state.before.push(message);\n }\n\n return;\n }\n if (payload._tag !== \"ModelResponseRecorded\") return;\n const messages = yield* decodePromptMessages(payload.messages);\n const forRun = payload.runId === ownerRunId;\n\n pendingToolOrder = new Map(\n declaredApplicationToolCallIds(messages).map((id, index) => [id, index]),\n );\n\n yield* accountResponse(envelope, payload, messages);\n\n const modelVisible =\n !forRun && payload.runScopedPrefixLength !== undefined\n ? Prompt.fromMessages(messages.content.slice(payload.runScopedPrefixLength))\n : messages;\n\n const visibleMessages =\n !forRun && incompleteToolTurns.has(envelope.record.recordId)\n ? withoutApplicationToolCallMessages(modelVisible)\n : modelVisible.content;\n\n for (const message of visibleMessages) {\n state.all.push(message);\n if (!forRun) state.before.push(message);\n }\n state = {\n ...state,\n committedTurns: forRun\n ? Math.max(state.committedTurns, payload.turn)\n : state.committedTurns,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolTurns.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n }),\n );\n emitSummary();\n state = yield* flushTools(state);\n\n const validatedPolicyUsage = yield* Schema.decodeEffect(RunPolicyUsage)(policyUsage).pipe(\n Effect.mapError((cause) =>\n journalError(\"Run policy accounting exceeds its Schema bounds\", cause),\n ),\n );\n\n return {\n ...(toolSelection === undefined ? {} : { toolSelection }),\n policyUsage: validatedPolicyUsage,\n prompt: Prompt.fromMessages(state.all),\n historyBefore: Prompt.fromMessages(state.before),\n committedTurns: state.committedTurns,\n usage: unobservedModelCalls === 0 ? usage : { ...usage, unobservedModelCalls },\n ...(latestWindowId === undefined ? {} : { contextWindowId: latestWindowId }),\n ...(protectedContext === undefined ? {} : { protectedContext }),\n ...(ownerTerminated || pendingContextToolCallId === undefined\n ? {}\n : { pendingContextToolCallId }),\n };\n});\n\n/** Pure projection of one Run's durable recovery state from canonical records. */\nexport const projectRunJournal = Effect.fn(\"RunJournal.projectRunJournal\")(\n (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n runId: RunId,\n ): Effect.Effect<RunJournalProjection, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), runId),\n);\n\n/**\n * Pure valid-prompt projection from canonical records: `UserInputRecorded` +\n * `ModelResponseRecorded` + complete `ToolCallSettled` batches → the deterministic model-visible\n * Prompt (plan §Coordinator flow step 3).\n */\nexport const promptFromCanonicalRecords = Effect.fn(\"RunJournal.promptFromCanonicalRecords\")(\n (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n ): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), undefined).pipe(\n Effect.map((projection) => projection.prompt),\n ),\n);\n\n/** Everything one committed Turn contributes to its canonical batch. */\n/**\n * Staged usage is validated, never repaired: clamping negatives or truncating\n * fractions would under-record canonical usage, and NaN/Infinity must fail\n * typed instead of escaping as a record-construction defect (RUN-023).\n */\nconst validStagedUsage = (label: string, value: number): Effect.Effect<number, RunJournalError> =>\n Number.isSafeInteger(value) && value >= 0\n ? Effect.succeed(value)\n : Effect.fail(\n journalError(`Staged ${label} must be a non-negative safe integer, got ${String(value)}`),\n );\n\nexport interface TurnCommitInput {\n readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined;\n readonly toolExposure?: Snapshot | undefined;\n readonly toolSelections?: ReadonlyMap<string, Selection> | undefined;\n readonly budgetRejectedCalls?: ReadonlySet<string>;\n readonly runId: RunId;\n /** Canonical (Run-relative, Attempt-independent) Turn number; must be positive. */\n readonly turn: number;\n readonly turnId: TurnId;\n /**\n * The Prompt messages this Turn appended to official history, in order, including the Turn's\n * Tool message when application Tools ran. Tool messages become `ToolCallSettled` records; the\n * remaining messages become the Turn's `ModelResponseRecorded.messages`.\n */\n readonly appended: ReadonlyArray<Prompt.Message>;\n readonly producerId: ProducerId;\n readonly deploymentId: DeploymentId;\n readonly createdAt: DateTime.Utc;\n /** Leading instruction/wake messages that stay canonical but are hidden from later Runs. */\n readonly runScopedPrefixLength?: number | undefined;\n /** Terminal output committed atomically with this Turn's final canonical batch. */\n readonly runCompletion?:\n | {\n readonly output: PersistedJson;\n readonly runDisposition?: PersistedJson | undefined;\n readonly finishReason?: \"budget-exhausted\" | undefined;\n readonly exhausted?: ExhaustedLimit | undefined;\n }\n | undefined;\n /** Known missing-accounting invocations staged before this canonical response. */\n readonly unobservedModelCalls?: number | undefined;\n /** Per-call provider usage staged by the engine's `noteTurnUsage` (RUN-023). */\n readonly usage?:\n | {\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd?: number | undefined;\n readonly modelUsage?: ReadonlyArray<ModelCallUsage> | undefined;\n }\n | undefined;\n}\n\nconst decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);\nconst encodePrompt = Schema.encodeEffect(Prompt.Prompt);\nconst decodeModelUsage = Schema.decodeUnknownEffect(Schema.Array(ModelCallUsage));\n\nconst requireCanonicalTurn = (turn: number): Effect.Effect<void, RunJournalError> =>\n !Number.isInteger(turn) || turn <= 0\n ? Effect.fail(journalError(`Canonical turn number must be a positive integer: ${turn}`))\n : Effect.void;\n\ninterface SplitTurnMessages {\n readonly promptMessages: ReadonlyArray<Prompt.Message>;\n readonly toolParts: ReadonlyArray<Prompt.ToolResultPart>;\n}\n\nconst splitTurnMessages = (appended: ReadonlyArray<Prompt.Message>): SplitTurnMessages => {\n const promptMessages: Array<Prompt.Message> = [];\n const toolParts: Array<Prompt.ToolResultPart> = [];\n\n for (const message of appended) {\n if (message.role !== \"tool\") {\n promptMessages.push(message);\n continue;\n }\n for (const part of message.content) {\n if (part.type !== \"tool-result\") continue;\n toolParts.push(part);\n }\n }\n\n return { promptMessages, toolParts };\n};\n\nconst modelResponseRecord = Effect.fn(\"RunJournal.modelResponseRecord\")(function* (\n input: TurnCommitInput,\n promptMessages: ReadonlyArray<Prompt.Message>,\n): Effect.fn.Return<RecordEnvelope, RunJournalError | DigestError, Crypto.Crypto> {\n if (promptMessages.length === 0) {\n return yield* journalError(`Turn ${input.turn} appended no model-visible Prompt messages`);\n }\n const runScopedPrefixLength = input.runScopedPrefixLength;\n\n if (\n runScopedPrefixLength !== undefined &&\n (input.turn !== 1 ||\n !Number.isSafeInteger(runScopedPrefixLength) ||\n runScopedPrefixLength <= 0 ||\n runScopedPrefixLength >= promptMessages.length ||\n promptMessages\n .slice(0, runScopedPrefixLength)\n .some((message) => message.role !== \"system\" && message.role !== \"user\"))\n ) {\n return yield* journalError(\n \"Run-scoped Prompt provenance must identify a non-empty system/user prefix of Turn 1 before its assistant response\",\n );\n }\n\n const encodedMessages = yield* encodePrompt(Prompt.fromMessages([...promptMessages])).pipe(\n Effect.mapError((cause) => journalError(\"Turn Prompt messages failed to encode\", cause)),\n );\n\n const messages = yield* decodePersistedJson(encodedMessages).pipe(\n Effect.mapError((cause) =>\n journalError(\"Turn Prompt messages exceed canonical persistence bounds\", cause),\n ),\n );\n\n const messagesDigest = yield* digestJson(messages);\n\n const modelUsage =\n input.usage?.modelUsage === undefined\n ? undefined\n : yield* decodeModelUsage(input.usage.modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage failed to decode\", cause)),\n );\n\n if (modelUsage !== undefined) {\n if (modelUsage.length === 0) {\n return yield* journalError(\"Turn model usage must contain at least one completed call\");\n }\n\n const summary = yield* summarizeModelUsage(modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage exceeds accounting bounds\", cause)),\n );\n\n if (\n input.usage === undefined ||\n input.usage.inputTokens !== summary.inputTokens.total ||\n input.usage.outputTokens !== summary.outputTokens.total ||\n (input.usage.costMicrousd ?? 0) !== summary.costMicrousd\n ) {\n return yield* journalError(\"Turn detailed and aggregate model usage disagree\");\n }\n }\n\n return RecordEnvelope.make({\n recordId: modelResponseRecordId(input.runId, input.turn),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: ModelResponseRecorded.make({\n ...(input.toolParameterRejections === undefined || input.toolParameterRejections.length === 0\n ? {}\n : { toolParameterRejections: input.toolParameterRejections }),\n ...(input.toolExposure === undefined ? {} : { toolExposure: input.toolExposure }),\n runId: input.runId,\n turnId: input.turnId,\n turn: input.turn,\n messages,\n messagesDigest,\n ...(runScopedPrefixLength === undefined ? {} : { runScopedPrefixLength }),\n ...(modelUsage === undefined ? {} : { modelUsage }),\n ...(input.unobservedModelCalls === undefined || input.unobservedModelCalls === 0\n ? {}\n : {\n unobservedModelCalls: yield* validStagedUsage(\n \"unobservedModelCalls\",\n input.unobservedModelCalls,\n ),\n }),\n ...(input.usage === undefined\n ? {}\n : {\n inputTokens: yield* validStagedUsage(\"inputTokens\", input.usage.inputTokens),\n outputTokens: yield* validStagedUsage(\"outputTokens\", input.usage.outputTokens),\n // Written only when non-zero: absent re-seeds as zero, so the\n // no-estimator case stays byte-identical to pre-cost histories.\n ...(input.usage.costMicrousd === undefined || input.usage.costMicrousd === 0\n ? {}\n : {\n costMicrousd: yield* validStagedUsage(\"costMicrousd\", input.usage.costMicrousd),\n }),\n }),\n }),\n });\n});\n\nconst toolSettledRecords = Effect.fn(\"RunJournal.toolSettledRecords\")(function* (\n input: TurnCommitInput,\n toolParts: ReadonlyArray<Prompt.ToolResultPart>,\n): Effect.fn.Return<Array<RecordEnvelope>, RunJournalError> {\n const toolRecords: Array<RecordEnvelope> = [];\n\n for (const part of toolParts) {\n const result = yield* decodePersistedJson(part.result).pipe(\n Effect.mapError((cause) =>\n journalError(`Tool result ${part.id} exceeds canonical persistence bounds`, cause),\n ),\n );\n\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(part.id),\n catch: (cause) => journalError(`Invalid Tool Call ID ${part.id}`, cause),\n });\n\n toolRecords.push(\n RecordEnvelope.make({\n recordId: toolCallSettledRecordId(input.runId, input.turn, toolCallId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: ToolCallSettled.make({\n ...(input.toolSelections?.get(part.id) === undefined\n ? {}\n : { toolSelection: input.toolSelections.get(part.id) }),\n runId: input.runId,\n toolCallId,\n toolName: part.name,\n result,\n isFailure: part.isFailure,\n ...(input.budgetRejectedCalls?.has(part.id) === true ? { budgetRejected: true } : {}),\n }),\n }),\n );\n }\n\n return toolRecords;\n});\n\nconst runCompletionRecord = (input: TurnCommitInput): RecordEnvelope | undefined =>\n input.runCompletion === undefined\n ? undefined\n : RecordEnvelope.make({\n recordId: runCompletedRecordId(input.runId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: RunCompleted.make({\n runId: input.runId,\n output: input.runCompletion.output,\n ...(input.runCompletion.runDisposition === undefined\n ? {}\n : { runDisposition: input.runCompletion.runDisposition }),\n ...(input.runCompletion.finishReason === undefined\n ? {}\n : { finishReason: input.runCompletion.finishReason }),\n ...(input.runCompletion.exhausted === undefined\n ? {}\n : { exhausted: input.runCompletion.exhausted }),\n }),\n });\n\n/**\n * Pure per-Turn canonical batch builder (TurnCompleted seam fold, D6/D8): one\n * `ModelResponseRecorded` record plus one `ToolCallSettled` record per terminal Tool result, all\n * under the WP0-style deterministic identities, committed as ONE atomic batch. The same input\n * always yields byte-identical content, so an in-Attempt append retry is an honest batch replay.\n *\n * Phase 5 keeps this shape for Turns that declare no application Tool calls; their terminal\n * `RunCompleted` marker joins the response in this same atomic batch. Tool-declaring Turns split\n * into `turnResponseBatch` + `turnResultsBatch`.\n */\nexport const turnCanonicalBatch = Effect.fn(\"RunJournal.turnCanonicalBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {\n yield* requireCanonicalTurn(input.turn);\n const { promptMessages, toolParts } = splitTurnMessages(input.appended);\n const modelResponse = yield* modelResponseRecord(input, promptMessages);\n const toolRecords = yield* toolSettledRecords(input, toolParts);\n const completionRecord = runCompletionRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [modelResponse, ...toolRecords]\n : [modelResponse, ...toolRecords, completionRecord],\n });\n});\n\n/**\n * Commit 1 of a tool-declaring Turn: the Turn's `ModelResponseRecorded` record, including\n * provider results retained in assistant content before application Tools execute.\n * — pending steering plus the assistant response with its declared tool calls — under batch\n * identity `turn-response:{runId}:{turn}`. Committing the response before preparation creates\n * the provably-safe durability §15 window (\"after model item commit, before tool preparation →\n * resume tool scheduling\"): a crash there resumes the declared batch with no model re-invocation\n * and no Unknown. Tool messages in `appended` are ignored; the record identity is the same\n * `model-response:{runId}:{turn}` as the single-batch shape, so record-id assertions and the\n * prompt projection are unchanged.\n */\nexport const turnResponseBatch = Effect.fn(\"RunJournal.turnResponseBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {\n yield* requireCanonicalTurn(input.turn);\n const { promptMessages } = splitTurnMessages(input.appended);\n const modelResponse = yield* modelResponseRecord(input, promptMessages);\n\n return CanonicalBatch.make({\n batchId: turnResponseBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records: [modelResponse],\n });\n});\n\n/**\n * Commit 5 of a tool-declaring Turn (plan §2.1): the Turn's `ToolCallSettled` records in\n * declaration order under batch identity `turn-results:{runId}:{turn}` — the batch becomes\n * model-visible atomically. Non-tool messages in `appended` are ignored; a Turn without any\n * terminal Tool result has no results batch and fails typed.\n */\nexport const turnResultsBatch = Effect.fn(\"RunJournal.turnResultsBatch\")(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError> {\n yield* requireCanonicalTurn(input.turn);\n const { toolParts } = splitTurnMessages(input.appended);\n const toolRecords = yield* toolSettledRecords(input, toolParts);\n const first = toolRecords[0];\n\n if (first === undefined) {\n return yield* journalError(`Turn ${input.turn} has no terminal Tool results to commit`);\n }\n if (input.runCompletion !== undefined && toolRecords.length !== 1) {\n return yield* journalError(\"A terminal Tool completion requires exactly one settled result\");\n }\n const completionRecord = runCompletionRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnResultsBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [first, ...toolRecords.slice(1)]\n : [first, ...toolRecords.slice(1), completionRecord],\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAa,uBACX,YACA,SACG;CACH,MAAM,qCAAqB,IAAI,IAAoB;CAEnD,IAAI,MAAM,kBAAkB,KAAA,GAAW,mBAAmB,IAAI,KAAK,OAAO,KAAK,aAAa;CAC5F,MAAM,4CAA4B,IAAI,IAAoB;CAC1D,MAAM,wCAAwB,IAAI,IAAoB;CACtD,MAAM,eAAsE,CAAC;CAC7E,MAAM,2CAA2B,IAAI,IAAY;CAEjD,MAAM,8BAAc,IAAI,IAGtB;CAEF,MAAM,cAAyF,CAAC;CAEhG,OAAO;EACL,MAAM,aAA4C;GAChD,MAAM,UAAU,SAAS,OAAO;GAEhC,KACG,QAAQ,SAAS,kBAChB,QAAQ,SAAS,eACjB,QAAQ,SAAS,wBACnB,QAAQ,UAAU,KAAA,KAClB,C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