effect-durable-agent 0.1.0-alpha.9 → 0.1.0

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 (176) hide show
  1. package/README.md +5 -5
  2. package/dist/assert-never-CoyUpoRB.js +18 -0
  3. package/dist/assert-never-CoyUpoRB.js.map +1 -0
  4. package/dist/{commands-Ce1ec6kH.d.ts → commands-BUquEZVP.d.ts} +31 -12
  5. package/dist/{compaction-BgDr5VJy.js → compaction-63iEDHHl.js} +63 -13
  6. package/dist/compaction-63iEDHHl.js.map +1 -0
  7. package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-Bezx3drD.d.ts} +16 -40
  8. package/dist/{core-CYT6DBaS.d.ts → core-BcimKMIv.d.ts} +5 -3
  9. package/dist/delivery-2ZILvoRD.js +507 -0
  10. package/dist/delivery-2ZILvoRD.js.map +1 -0
  11. package/dist/delivery-D3MxW4wg.d.ts +3026 -0
  12. package/dist/domain/command-queues.d.ts +81 -2
  13. package/dist/domain/command-queues.js +1 -1
  14. package/dist/domain/command-queues.js.map +1 -1
  15. package/dist/domain/context-projection.d.ts +1 -1
  16. package/dist/domain/context-projection.js +1 -1
  17. package/dist/domain/context-projection.js.map +1 -1
  18. package/dist/domain/message-transcript.d.ts +36 -2
  19. package/dist/domain/message-transcript.js +10 -2
  20. package/dist/domain/message-transcript.js.map +1 -1
  21. package/dist/domain/model-usage.d.ts +1 -1
  22. package/dist/domain/model-usage.js +1 -1
  23. package/dist/domain/reduced-state-schema.d.ts +3 -992
  24. package/dist/domain/reduced-state-schema.js +126 -7
  25. package/dist/domain/reduced-state-schema.js.map +1 -1
  26. package/dist/domain/reduced-state.d.ts +2 -2
  27. package/dist/domain/reduced-state.js +936 -2
  28. package/dist/domain/reduced-state.js.map +1 -0
  29. package/dist/domain/run-scheduling.d.ts +2 -0
  30. package/dist/domain/run-scheduling.js +127 -0
  31. package/dist/domain/run-scheduling.js.map +1 -0
  32. package/dist/{durable-br2C1bWK.d.ts → durable-168Womqp.d.ts} +8535 -2859
  33. package/dist/{durable-BGFvX7Mh.js → durable-D13w1Qr3.js} +229 -15
  34. package/dist/durable-D13w1Qr3.js.map +1 -0
  35. package/dist/{envelope-DxQzo5rN.js → envelope-BCzKUq_z.js} +12 -3
  36. package/dist/envelope-BCzKUq_z.js.map +1 -0
  37. package/dist/{envelope-DkZyMIgp.d.ts → envelope-Che6KatU.d.ts} +70 -7
  38. package/dist/{event-factory-DTFdy0Cb.js → event-factory-_vF1bIJ7.js} +7 -3
  39. package/dist/event-factory-_vF1bIJ7.js.map +1 -0
  40. package/dist/{events-LZFNoESe.d.ts → events-DwTARLMv.d.ts} +139 -137
  41. package/dist/{id-generator-Ckl8_XWW.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
  42. package/dist/in-memory-CeODnZhE.js +150 -0
  43. package/dist/in-memory-CeODnZhE.js.map +1 -0
  44. package/dist/index.d.ts +8 -8
  45. package/dist/index.js +6 -6
  46. package/dist/interpreter-DKGJ1sSx.js +1452 -0
  47. package/dist/interpreter-DKGJ1sSx.js.map +1 -0
  48. package/dist/{keep-alive-Chl5SJxy.d.ts → keep-alive-_zFCUvt3.d.ts} +1 -2
  49. package/dist/{model-resolver-BPPJAsuh.d.ts → model-resolver-DeBDK8XO.d.ts} +11 -5
  50. package/dist/{model-usage-CdBEkTwU.d.ts → model-usage-0GeHwaaU.d.ts} +2 -3
  51. package/dist/records--54mZEBx.js +675 -0
  52. package/dist/records--54mZEBx.js.map +1 -0
  53. package/dist/reduced-state-B1cvy8N_.d.ts +51110 -0
  54. package/dist/reduced-state-schema-B98exWxQ.d.ts +2338 -0
  55. package/dist/{reducer-registry-aFjz_ZLT.d.ts → reducer-registry-DhGVzHBV.d.ts} +12 -6
  56. package/dist/run-scheduling-wakeup-Mjic4tb_.d.ts +24 -0
  57. package/dist/services/compaction.d.ts +2 -2
  58. package/dist/services/compaction.js +2 -2
  59. package/dist/services/id-generator.d.ts +1 -1
  60. package/dist/services/id-generator.js +6 -12
  61. package/dist/services/id-generator.js.map +1 -1
  62. package/dist/services/keep-alive.d.ts +1 -1
  63. package/dist/services/keep-alive.js.map +1 -1
  64. package/dist/services/model-call.d.ts +15 -0
  65. package/dist/services/model-call.js +15 -0
  66. package/dist/services/model-call.js.map +1 -0
  67. package/dist/services/model-resolver.d.ts +1 -1
  68. package/dist/services/model-resolver.js +1 -1
  69. package/dist/services/model-resolver.js.map +1 -1
  70. package/dist/services/prompt-projector.d.ts +2 -2
  71. package/dist/services/prompt-projector.js +49 -5
  72. package/dist/services/prompt-projector.js.map +1 -1
  73. package/dist/services/reducer-registry.d.ts +1 -1
  74. package/dist/services/reducer-registry.js +19 -6
  75. package/dist/services/reducer-registry.js.map +1 -1
  76. package/dist/services/run-scheduler.d.ts +2 -2
  77. package/dist/services/run-scheduler.js +25 -2
  78. package/dist/services/run-scheduler.js.map +1 -0
  79. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  80. package/dist/services/run-scheduling-wakeup.js +13 -0
  81. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  82. package/dist/services/runtime-layer.d.ts +17 -33
  83. package/dist/services/runtime-layer.js +19 -14
  84. package/dist/services/runtime-layer.js.map +1 -1
  85. package/dist/services/runtime.d.ts +1 -1
  86. package/dist/services/runtime.js +31 -20
  87. package/dist/services/runtime.js.map +1 -1
  88. package/dist/services/session-event-observer.d.ts +1 -1
  89. package/dist/services/session-event-observer.js.map +1 -1
  90. package/dist/services/session-query.d.ts +1 -1
  91. package/dist/services/session-query.js +57 -10
  92. package/dist/services/session-query.js.map +1 -1
  93. package/dist/services/session-state.d.ts +1 -1
  94. package/dist/services/session-state.js +1 -1
  95. package/dist/services/session-store.d.ts +2 -2
  96. package/dist/services/session-store.js +127 -37
  97. package/dist/services/session-store.js.map +1 -1
  98. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  99. package/dist/services/sink-checkpoint-store.js +2 -1
  100. package/dist/services/sink-checkpoint-store.js.map +1 -1
  101. package/dist/services/sink-registry.d.ts +2 -2
  102. package/dist/services/sink-registry.js +1 -1
  103. package/dist/services/span-names.d.ts +1 -1
  104. package/dist/services/span-names.js +6 -1
  105. package/dist/services/span-names.js.map +1 -1
  106. package/dist/services/tool-registry.d.ts +2 -2
  107. package/dist/services/tool-registry.js +12 -3
  108. package/dist/services/tool-registry.js.map +1 -1
  109. package/dist/services/tracing.d.ts +3 -3
  110. package/dist/services/tracing.js +2 -2
  111. package/dist/services/tracing.js.map +1 -1
  112. package/dist/{session-event-observer-DaFMKKNc.d.ts → session-event-observer-DlP9ITB2.d.ts} +3 -3
  113. package/dist/{session-state-Bkc6u-Wr.js → session-state-BehvUVyq.js} +659 -164
  114. package/dist/session-state-BehvUVyq.js.map +1 -0
  115. package/dist/session-store-BL6sfrnn.d.ts +3326 -0
  116. package/dist/{sink-checkpoint-store-M7qIxoSH.d.ts → sink-checkpoint-store-DvuHwvx_.d.ts} +3 -4
  117. package/dist/sink-registry-DskRcyOS.js +345 -0
  118. package/dist/sink-registry-DskRcyOS.js.map +1 -0
  119. package/dist/subscription-DZNWFDTV.d.ts +966 -0
  120. package/dist/subscription-DmO3BcdT.js +505 -0
  121. package/dist/subscription-DmO3BcdT.js.map +1 -0
  122. package/dist/testkit/layers.d.ts +30 -23
  123. package/dist/testkit/layers.js +23 -15
  124. package/dist/testkit/layers.js.map +1 -1
  125. package/dist/testkit/transcript.d.ts +226 -0
  126. package/dist/testkit/transcript.js +1475 -0
  127. package/dist/testkit/transcript.js.map +1 -0
  128. package/dist/{tool-registry-BJaVNtw4.d.ts → tool-registry-CHHUU9BN.d.ts} +44 -8
  129. package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
  130. package/dist/transcript.d.ts +101 -0
  131. package/dist/transcript.js +107 -0
  132. package/dist/transcript.js.map +1 -0
  133. package/dist/types/commands.d.ts +2 -2
  134. package/dist/types/commands.js +8 -3
  135. package/dist/types/commands.js.map +1 -1
  136. package/dist/types/core.d.ts +2 -2
  137. package/dist/types/core.js +3 -1
  138. package/dist/types/core.js.map +1 -1
  139. package/dist/types/events/durable.d.ts +2 -2
  140. package/dist/types/events/durable.js +2 -2
  141. package/dist/types/events.d.ts +5 -5
  142. package/dist/types/events.js +3 -3
  143. package/dist/types/tracing.d.ts +1 -1
  144. package/dist/types/tracing.js.map +1 -1
  145. package/dist/websocket/events.d.ts +2 -0
  146. package/dist/websocket/events.js +2 -0
  147. package/dist/websocket.d.ts +2123 -2552
  148. package/dist/websocket.js +628 -442
  149. package/dist/websocket.js.map +1 -1
  150. package/dist/window-read-Brov9VdQ.d.ts +113 -0
  151. package/dist/window-read-DPFAA1hM.js +264 -0
  152. package/dist/window-read-DPFAA1hM.js.map +1 -0
  153. package/package.json +37 -13
  154. package/dist/command-queues-DdDB_aYM.d.ts +0 -462
  155. package/dist/compaction-BgDr5VJy.js.map +0 -1
  156. package/dist/compaction-ch8z6G9x.d.ts +0 -165
  157. package/dist/durable-BGFvX7Mh.js.map +0 -1
  158. package/dist/envelope-DxQzo5rN.js.map +0 -1
  159. package/dist/event-factory-DTFdy0Cb.js.map +0 -1
  160. package/dist/event-factory-Di1jwQvm.d.ts +0 -87
  161. package/dist/index-BVVgDSdq.d.ts +0 -1
  162. package/dist/message-transcript-DQNlzxle.d.ts +0 -32
  163. package/dist/prompt-projector-f4ElyXCE.d.ts +0 -39
  164. package/dist/reduced-state-DF0-6mbR.js +0 -921
  165. package/dist/reduced-state-DF0-6mbR.js.map +0 -1
  166. package/dist/run-scheduler-CAt7dF6C.js +0 -21
  167. package/dist/run-scheduler-CAt7dF6C.js.map +0 -1
  168. package/dist/run-scheduler-xkhZyto5.d.ts +0 -44
  169. package/dist/runtime-DDSYP9jS.d.ts +0 -63
  170. package/dist/session-query-B72HY_0L.d.ts +0 -45
  171. package/dist/session-state-Bkc6u-Wr.js.map +0 -1
  172. package/dist/session-state-C9YLSAso.d.ts +0 -862
  173. package/dist/session-store-Cpi_NwTR.d.ts +0 -206
  174. package/dist/sink-registry-Bl-vQES6.d.ts +0 -133
  175. package/dist/sink-registry-NDgeyzO0.js +0 -272
  176. package/dist/sink-registry-NDgeyzO0.js.map +0 -1
@@ -1,38 +1,43 @@
1
- import { t as RunScheduler } from "./run-scheduler-CAt7dF6C.js";
2
- import { ModelResolver } from "./services/model-resolver.js";
1
+ import { RunSchedulingWakeup } from "./services/run-scheduling-wakeup.js";
3
2
  import { CommandId, InferenceId, MessageId, Position, RunId, SequenceNumber, SubSequenceNumber, TurnId } from "./types/core.js";
3
+ import { canGrantRun, planRunSchedulingCancellation, planWaitingRunInterruption, runSchedulingInputMessageIds, waitingRunControl } from "./domain/run-scheduling.js";
4
+ import { RunScheduler } from "./services/run-scheduler.js";
5
+ import { ModelResolver } from "./services/model-resolver.js";
4
6
  import { makeEDARunTrace } from "./types/tracing.js";
5
- import { c as ModelSelectionPayload, d as ProviderPartId, l as NonNegativeInt, m as ToolName, p as SystemPromptText, s as FailurePayload, u as PositionedEvent } from "./envelope-DxQzo5rN.js";
7
+ import { d as PositionedEvent, f as ProviderPartId, h as ToolName, l as ModelSelectionPayload, m as SystemPromptText, s as FailurePayload, u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
6
8
  import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
7
- import { $n as turnFailedEventType, An as inferenceCompletedEventType, Jn as toolCallCreatedEventType, Xn as toolCallRejectedEventType, _n as commandAdmittedEventType, jn as inferenceFailedEventType } from "./durable-BGFvX7Mh.js";
8
- import { a as encodeReducedStateCheckpoint, h as assertNeverError, i as decodeReducedStateCheckpoint, l as initialReducedState, m as assertNever, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName } from "./reduced-state-DF0-6mbR.js";
9
+ import { Jn as inferenceCompletedEventType, Kt as ToolCallCreatedEvent, Sr as turnFailedEventType, Yn as inferenceFailedEventType, _ as CommandAdmittedEvent, _r as toolCallCreatedEventType, cn as TurnCompletedEvent, dn as TurnFailedEvent, hn as TurnStoppedEvent, pn as TurnStartedEvent, qn as durableEventEnvelope, yr as toolCallRejectedEventType } from "./durable-D13w1Qr3.js";
10
+ import { n as assertNeverError, t as assertNever } from "./assert-never-CoyUpoRB.js";
11
+ import { activeTurnIdentityForCommand, classifyRecoverableWork, decodeReducedStateCheckpoint, encodeReducedStateCheckpoint, foldReducedState, frameworkReducedStateReducerName, initialReducedState, reducedStateCheckpointEventSeqs } from "./domain/reduced-state.js";
9
12
  import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
10
- import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError } from "./services/session-store.js";
11
- import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-BgDr5VJy.js";
13
+ import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError, queryCommittedEvents } from "./services/session-store.js";
14
+ import { o as CompactionRunner, p as makeUsagePayload } from "./compaction-63iEDHHl.js";
15
+ import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
16
+ import { n as SessionContext, t as EventFactory } from "./event-factory-_vF1bIJ7.js";
17
+ import { EDAToolRegistry, toolRecoveryPolicy } from "./services/tool-registry.js";
12
18
  import { IdGenerator } from "./services/id-generator.js";
13
- import { n as SessionContext, t as EventFactory } from "./event-factory-DTFdy0Cb.js";
14
19
  import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
15
20
  import { EDAKeepAlive } from "./services/keep-alive.js";
16
- import { n as EDASinkRegistry, r as LiveEventBus } from "./sink-registry-NDgeyzO0.js";
17
- import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
21
+ import { SessionEventObserver } from "./services/session-event-observer.js";
18
22
  import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
19
- import { EDAToolRegistry } from "./services/tool-registry.js";
23
+ import { n as EDASinkRegistry } from "./sink-registry-DskRcyOS.js";
20
24
  import * as Context from "effect/Context";
21
25
  import * as Effect from "effect/Effect";
22
26
  import * as Layer from "effect/Layer";
23
27
  import * as Schema from "effect/Schema";
24
28
  import * as Stream from "effect/Stream";
25
- import * as Prompt from "effect/unstable/ai/Prompt";
29
+ import * as Prompt from "effect/ai/Prompt";
30
+ import * as Exit from "effect/Exit";
26
31
  import * as Cause from "effect/Cause";
27
32
  import * as Clock from "effect/Clock";
28
- import * as Exit from "effect/Exit";
29
33
  import * as Fiber from "effect/Fiber";
30
34
  import * as Queue from "effect/Queue";
31
35
  import * as Ref from "effect/Ref";
32
36
  import * as Scope from "effect/Scope";
33
37
  import * as Semaphore from "effect/Semaphore";
34
38
  import * as Option from "effect/Option";
35
- import * as Response from "effect/unstable/ai/Response";
39
+ import * as PubSub from "effect/PubSub";
40
+ import * as Response from "effect/ai/Response";
36
41
  //#region src/domain/dispatch-policy.ts
37
42
  /** Durable/runtime evidence for active work blocking new queued commands. */
38
43
  const DispatchActiveCommand = Schema.TaggedStruct("DispatchActiveCommand", {
@@ -110,6 +115,15 @@ const decideDispatch = (state) => {
110
115
  command: toCandidate(next)
111
116
  };
112
117
  };
118
+ /** Promotion must retain a live or pending execution owner when the original command is terminal. */
119
+ const promotionNeedsResumeCommand = (state, messageId) => {
120
+ if (state.commandQueues.active?.runId !== void 0) return false;
121
+ const target = state.messages.get(messageId);
122
+ if (target?._tag !== "User" && target?._tag !== "Steering") return false;
123
+ const waiting = state.runSchedulingRequest?.work;
124
+ if (waiting?._tag === "Recovery" && waiting.inputMessageIds.includes(messageId)) return false;
125
+ return !state.commandQueues.pendingCommands.some((pending) => pending.commandId === target.commandId || pending.command._tag === "ResumePendingMessages" && pending.command.messageIds.includes(messageId));
126
+ };
113
127
  const nextIdleCommand = (state) => {
114
128
  const pendingById = new Map(state.commandQueues.pendingCommands.map((command) => [command.commandId, command]));
115
129
  for (const message of state.commandQueues.pendingSteers) {
@@ -220,9 +234,9 @@ const planSessionRecovery = (state) => {
220
234
  const pendingMessageIds = new Set([...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId));
221
235
  const sourceMessageIds = continuationCommand?.command?._tag === "ResumePendingMessages" ? continuationCommand.command.messageIds.filter((messageId) => pendingMessageIds.has(messageId)) : continuationCommand === void 0 ? [] : [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].filter((message) => message.commandId === continuationCommand.commandId).map((message) => message.messageId);
222
236
  const eligibleSteerIds = continuationRun === void 0 ? [] : state.commandQueues.pendingSteers.filter((message) => message.targetRunId === void 0 || message.targetRunId === continuationRun.runId || continuationRun.commandIds.some((commandId) => state.runs.get(message.targetRunId)?.commandIds.includes(commandId) === true)).map((message) => message.messageId);
223
- const continuationInputMessageIds = Array.from(new Set([...sourceMessageIds, ...eligibleSteerIds]));
237
+ const continuationInputMessageIds = Array.from(/* @__PURE__ */ new Set([...sourceMessageIds, ...eligibleSteerIds]));
224
238
  const continuationInputIds = new Set(continuationInputMessageIds);
225
- const messageIdsToResume = state.commandQueues.pendingSteers.filter((message) => !pausedMessageIds.has(message.messageId) && !continuationInputIds.has(message.messageId) && !pendingCommandsById.has(message.commandId) && !resumeOwnedMessageIds.has(message.messageId)).map((message) => message.messageId);
239
+ const messageIdsToResume = state.commandQueues.pendingSteers.filter((message) => !pausedMessageIds.has(message.messageId) && !continuationInputIds.has(message.messageId) && !(state.runSchedulingRequest?.work._tag === "Recovery" && state.runSchedulingRequest.work.inputMessageIds.includes(message.messageId)) && !pendingCommandsById.has(message.commandId) && !resumeOwnedMessageIds.has(message.messageId)).map((message) => message.messageId);
226
240
  return {
227
241
  activeCommands: recoverable.activeCommands,
228
242
  activeRuns: recoverable.activeRuns,
@@ -248,6 +262,60 @@ const planRunFailure = (state) => ({ messageIdsToResume: state.commandQueues.pen
248
262
  /** Normal explicit Stop/Interrupt policy. This is not startup recovery. */
249
263
  const planUserInterruption = (state) => ({ messageIdsToPause: [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId) });
250
264
  //#endregion
265
+ //#region src/services/live-event-bus.ts
266
+ /** Conservative raw-delta cap for one open turn's live-only reconnect replay. */
267
+ const activeTurnEphemeralReplayCapacity = 4096;
268
+ /** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */
269
+ var LiveEventBus = class LiveEventBus extends Context.Service()("@effect-durable-agent/LiveEventBus") {
270
+ static Live = Layer.effect(LiveEventBus, Effect.gen(function* () {
271
+ const pubsub = yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown);
272
+ const activeTurnReplay = yield* Ref.make({
273
+ events: [],
274
+ overflowed: false
275
+ });
276
+ const observer = yield* SessionEventObserver;
277
+ return makeLiveBus(pubsub, activeTurnReplay, observer);
278
+ }));
279
+ /** Live bus for hosts that do not install an append-driven observer. */
280
+ static Noop = LiveEventBus.Live.pipe(Layer.provide(SessionEventObserver.Noop));
281
+ };
282
+ const makeLiveBus = (pubsub, activeTurnReplay, observer) => ({
283
+ publish: (event) => Effect.gen(function* () {
284
+ yield* updateActiveTurnReplay(activeTurnReplay, event);
285
+ yield* observer.onEvent(event);
286
+ return yield* PubSub.publish(pubsub, event);
287
+ }),
288
+ subscribeQueue: () => PubSub.subscribe(pubsub),
289
+ subscribe: () => Effect.map(PubSub.subscribe(pubsub), (subscription) => Stream.fromEffectRepeat(PubSub.take(subscription))),
290
+ activeTurnReplay: () => Ref.get(activeTurnReplay)
291
+ });
292
+ const updateActiveTurnReplay = (ref, event) => Ref.update(ref, (state) => nextActiveTurnReplay(state, event));
293
+ const nextActiveTurnReplay = (state, event) => {
294
+ if (Schema.is(TurnStartedEvent)(event.event)) return {
295
+ turnId: event.event.payload.turnId,
296
+ events: [],
297
+ overflowed: false
298
+ };
299
+ if (Schema.is(TurnCompletedEvent)(event.event) || Schema.is(TurnFailedEvent)(event.event) || Schema.is(TurnStoppedEvent)(event.event)) {
300
+ const turnId = event.event.payload.turnId;
301
+ return turnId === void 0 || state.turnId === void 0 || turnId === state.turnId ? {
302
+ events: [],
303
+ overflowed: false
304
+ } : state;
305
+ }
306
+ if (event.event.durability !== "ephemeral" || state.turnId === void 0) return state;
307
+ const events = [...state.events, event];
308
+ if (events.length <= 4096) return {
309
+ ...state,
310
+ events
311
+ };
312
+ return {
313
+ ...state,
314
+ events: events.slice(events.length - activeTurnEphemeralReplayCapacity),
315
+ overflowed: true
316
+ };
317
+ };
318
+ //#endregion
251
319
  //#region src/services/started-boundary-guard.ts
252
320
  /** Build a guard bound to the session's durable append boundary. */
253
321
  const makeStartedBoundaryGuard = (state) => (spec) => {
@@ -306,13 +374,14 @@ Schema.Union([
306
374
  ToolExecutionSkipped
307
375
  ]);
308
376
  /** Failure when tool execution receives a committed event that is not ToolCallCreated. */
309
- var ToolExecutionEventNotCreated = class extends Schema.TaggedErrorClass()("ToolExecutionEventNotCreated", { eventType: Schema.String }) {};
377
+ var ToolExecutionEventNotCreated = class extends Schema.TaggedError()("ToolExecutionEventNotCreated", { eventType: Schema.String }) {};
310
378
  /** Construct the live tool-executor implementation. */
311
379
  const makeLiveToolExecutor = Effect.gen(function* () {
312
380
  const events = yield* EventFactory;
313
381
  const ids = yield* IdGenerator;
314
382
  const registry = yield* EDAToolRegistry;
315
383
  const session = yield* SessionContext;
384
+ const store = yield* EDASessionStore;
316
385
  const failToolCall = (input, created, error) => Effect.gen(function* () {
317
386
  const event = yield* events.toolCallFailed({
318
387
  toolCallId: created.event.payload.toolCallId,
@@ -327,7 +396,8 @@ const makeLiveToolExecutor = Effect.gen(function* () {
327
396
  yield* annotateEdaSpan({
328
397
  "eda.tool_call.id": created.event.payload.toolCallId,
329
398
  "eda.tool.name": created.event.payload.promptPart.name,
330
- "eda.tool.provider_executed": created.event.payload.promptPart.providerExecuted
399
+ "eda.tool.provider_executed": created.event.payload.promptPart.providerExecuted,
400
+ ...input.resume === void 0 ? {} : { "eda.tool.attempt": input.resume.attempt }
331
401
  });
332
402
  if (created.event.payload.promptPart.providerExecuted) {
333
403
  const outcome = ToolExecutionSkipped.make({ reason: "provider-executed" });
@@ -338,13 +408,20 @@ const makeLiveToolExecutor = Effect.gen(function* () {
338
408
  };
339
409
  }
340
410
  const guarded = yield* makeStartedBoundaryGuard(input.eventSink)({
341
- start: events.toolCallStarted({ toolCallId: created.event.payload.toolCallId }),
411
+ start: events.toolCallStarted({
412
+ toolCallId: created.event.payload.toolCallId,
413
+ ...input.resume === void 0 ? {} : { attempt: input.resume.attempt }
414
+ }),
342
415
  body: () => Effect.gen(function* () {
343
416
  const handled = yield* registry.execute(created.event.payload.promptPart.name, created.event.payload.promptPart.params, {
344
417
  toolCallId: created.event.payload.toolCallId,
418
+ runId: created.event.payload.runId,
419
+ turnId: created.event.payload.turnId,
420
+ queryEvents: (schema, options) => queryCommittedEvents(store, schema, options),
345
421
  sessionId: session.sessionId,
346
422
  makeEventId: ids.makeEventId,
347
- emitDurable: input.eventSink.appendDurable
423
+ emitDurable: input.eventSink.appendDurable,
424
+ ...input.resume === void 0 ? {} : { recovery: input.resume }
348
425
  }).pipe(Effect.map((result) => ({
349
426
  _tag: "Succeeded",
350
427
  result
@@ -405,6 +482,7 @@ const toolCompletedPromptPart = (created, result) => ({
405
482
  id: created.event.payload.promptPart.id,
406
483
  name: created.event.payload.promptPart.name,
407
484
  isFailure: false,
485
+ providerExecuted: false,
408
486
  result
409
487
  }),
410
488
  id: created.event.payload.promptPart.id,
@@ -416,6 +494,7 @@ const toolFailedPromptPart = (created, error) => ({
416
494
  id: created.event.payload.promptPart.id,
417
495
  name: created.event.payload.promptPart.name,
418
496
  isFailure: true,
497
+ providerExecuted: false,
419
498
  result: error
420
499
  }),
421
500
  id: created.event.payload.promptPart.id,
@@ -597,7 +676,8 @@ const recordToolParamsEnd = (state, input) => {
597
676
  };
598
677
  const recordToolCall = (state, input) => {
599
678
  const draft = state.drafts.get(input.providerPartId);
600
- const decision = makeToolCallDecision(state, input, draft?.toolCallId ?? input.toolCallId);
679
+ const toolCallId = draft?.toolCallId ?? input.toolCallId;
680
+ const decision = makeToolCallDecision(state, input, toolCallId);
601
681
  const nextDraft = draft === void 0 ? void 0 : markDraft(draft, decision);
602
682
  const nextDrafts = nextDraft === void 0 ? state.drafts : new Map(state.drafts).set(input.providerPartId, nextDraft);
603
683
  return {
@@ -714,6 +794,7 @@ const toolRejectedPromptPart = (decision) => ({
714
794
  id: decision.providerPartId,
715
795
  name: decision.toolName,
716
796
  isFailure: true,
797
+ providerExecuted: false,
717
798
  result: {
718
799
  message: decision.error.message,
719
800
  reason: decision.reason,
@@ -751,7 +832,7 @@ const InferenceRunResult = Schema.Struct({
751
832
  partsRecorded: NonNegativeInt,
752
833
  terminal: InferenceRunTerminal
753
834
  });
754
- Schema.TaggedErrorClass()("UnsupportedInferencePart", {
835
+ Schema.TaggedError()("UnsupportedInferencePart", {
755
836
  partType: Schema.String,
756
837
  reason: Schema.String
757
838
  });
@@ -971,7 +1052,8 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
971
1052
  type: "error",
972
1053
  error: failurePayloadFromUnknown(/* @__PURE__ */ new Error("Provider stream ended without a finish part"))
973
1054
  });
974
- return yield* requireTerminal(yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []));
1055
+ const terminal = yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []);
1056
+ return yield* requireTerminal(terminal);
975
1057
  });
976
1058
  return { runInference: Effect.fn("agent.inference")(function* (input) {
977
1059
  const languageModel = yield* models.resolve(input.modelSelection);
@@ -995,8 +1077,9 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
995
1077
  });
996
1078
  const body = (started) => Effect.gen(function* () {
997
1079
  const toolkit = yield* toolRegistry.getModelToolkit();
1080
+ const prompt = models.preparePrompt?.(input.modelSelection, Prompt.make(input.prompt));
998
1081
  const state = yield* languageModel.streamText({
999
- prompt: input.prompt,
1082
+ prompt: prompt ?? input.prompt,
1000
1083
  disableToolCallResolution: true,
1001
1084
  ...toolkit === void 0 ? {} : { toolkit }
1002
1085
  }).pipe(Stream.map((part) => part)).pipe(Stream.catchIf(isProviderStreamFailure, (error) => Stream.make(makeProviderErrorPart(error))), Stream.runFoldEffect(() => initialState, (current, part) => recordPart(input.eventSink, current, part, (next) => Ref.set(stateRef, next)).pipe(Effect.tap((next) => Ref.set(stateRef, next)))));
@@ -1043,7 +1126,8 @@ var InferenceRunner = class InferenceRunner extends Context.Service()("@effect-d
1043
1126
  };
1044
1127
  const inferenceUsageAttributes = (terminal) => {
1045
1128
  if (terminal._tag !== "InferenceRunFinished") return {};
1046
- return usageAttributes((terminal.committed.find((entry) => entry.event.type === "InferenceCompleted")?.event.payload)?.usage);
1129
+ const completed = terminal.committed.find((entry) => entry.event.type === "InferenceCompleted");
1130
+ return usageAttributes(completed?.event.type === "InferenceCompleted" ? completed.event.payload.usage : void 0);
1047
1131
  };
1048
1132
  const initialRunInferenceState = (identity) => ({
1049
1133
  inference: initialInferenceState(identity),
@@ -1053,12 +1137,12 @@ const initialRunInferenceState = (identity) => ({
1053
1137
  });
1054
1138
  const recordResponseContext = (entries, part) => {
1055
1139
  switch (part.type) {
1056
- case "text-start": return upsertTextualResponseEntry(entries, "Text", part.id, "");
1057
- case "text-delta": return upsertTextualResponseEntry(entries, "Text", part.id, part.delta);
1058
- case "text-end": return entries;
1059
- case "reasoning-start": return upsertTextualResponseEntry(entries, "Reasoning", part.id, "");
1060
- case "reasoning-delta": return upsertTextualResponseEntry(entries, "Reasoning", part.id, part.delta);
1061
- case "reasoning-end": return entries;
1140
+ case "text-start":
1141
+ case "text-end": return upsertTextualResponseEntry(entries, "Text", part.id, "", part.metadata);
1142
+ case "text-delta": return upsertTextualResponseEntry(entries, "Text", part.id, part.delta, part.metadata);
1143
+ case "reasoning-start":
1144
+ case "reasoning-end": return upsertTextualResponseEntry(entries, "Reasoning", part.id, "", part.metadata);
1145
+ case "reasoning-delta": return upsertTextualResponseEntry(entries, "Reasoning", part.id, part.delta, part.metadata);
1062
1146
  case "tool-call": return part.providerExecuted ? entries : [...entries, {
1063
1147
  _tag: "ResponsePart",
1064
1148
  part
@@ -1076,24 +1160,50 @@ const recordResponseContext = (entries, part) => {
1076
1160
  default: throw assertNeverError(part, "response context part");
1077
1161
  }
1078
1162
  };
1079
- const upsertTextualResponseEntry = (entries, tag, providerPartId, delta) => {
1163
+ /**
1164
+ * Folds one textual stream part into its entry. Provider metadata from start, delta and end parts
1165
+ * is merged per provider so replay keeps signatures, item ids and encrypted reasoning.
1166
+ */
1167
+ const upsertTextualResponseEntry = (entries, tag, providerPartId, delta, metadata) => {
1080
1168
  const index = entries.findIndex((entry) => (entry._tag === "Text" || entry._tag === "Reasoning") && entry._tag === tag && entry.providerPartId === providerPartId);
1081
1169
  if (index === -1) return [...entries, {
1082
1170
  _tag: tag,
1083
1171
  providerPartId,
1084
- text: delta
1172
+ text: delta,
1173
+ metadata: metadata ?? {}
1085
1174
  }];
1086
1175
  const current = entries[index];
1087
1176
  if (current._tag !== tag) return entries;
1088
1177
  return entries.map((entry, entryIndex) => entryIndex === index ? {
1089
1178
  ...current,
1090
- text: `${current.text}${delta}`
1179
+ text: `${current.text}${delta}`,
1180
+ metadata: mergeProviderMetadata(current.metadata, metadata)
1091
1181
  } : entry);
1092
1182
  };
1183
+ const mergeProviderMetadata = (left, right) => {
1184
+ if (right === void 0) return left;
1185
+ const merged = { ...left };
1186
+ for (const [provider, value] of Object.entries(right)) {
1187
+ const previous = merged[provider];
1188
+ merged[provider] = isMetadataRecord(previous) && isMetadataRecord(value) ? {
1189
+ ...previous,
1190
+ ...value
1191
+ } : value;
1192
+ }
1193
+ return merged;
1194
+ };
1195
+ const isMetadataRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1196
+ const hasProviderMetadata = (metadata) => Object.keys(metadata).length > 0;
1093
1197
  const responseContextToParts = (entries) => entries.flatMap((entry) => {
1094
1198
  switch (entry._tag) {
1095
- case "Text": return entry.text.length === 0 ? [] : [Response.makePart("text", { text: entry.text })];
1096
- case "Reasoning": return entry.text.length === 0 ? [] : [Response.makePart("reasoning", { text: entry.text })];
1199
+ case "Text": return entry.text.length === 0 ? [] : [Response.makePart("text", {
1200
+ text: entry.text,
1201
+ metadata: entry.metadata
1202
+ })];
1203
+ case "Reasoning": return entry.text.length === 0 && !hasProviderMetadata(entry.metadata) ? [] : [Response.makePart("reasoning", {
1204
+ text: entry.text,
1205
+ metadata: entry.metadata
1206
+ })];
1097
1207
  case "ResponsePart": return [entry.part];
1098
1208
  default: throw assertNeverError(entry, "response context entry");
1099
1209
  }
@@ -1142,7 +1252,6 @@ const makeResponseMetadata = (part) => ({
1142
1252
  id: part.id,
1143
1253
  modelId: part.modelId,
1144
1254
  timestamp: part.timestamp,
1145
- request: part.request,
1146
1255
  metadata: part.metadata
1147
1256
  });
1148
1257
  const makeFinishMetadata = (part) => ({
@@ -1174,6 +1283,7 @@ const makeLiveTurnRunner = Effect.gen(function* () {
1174
1283
  const events = yield* EventFactory;
1175
1284
  const inferenceRunner = yield* InferenceRunner;
1176
1285
  const toolExecutor = yield* ToolExecutor;
1286
+ const toolRegistry = yield* EDAToolRegistry;
1177
1287
  const commitCompletedTurn = (input, inferenceCompleted) => Effect.gen(function* () {
1178
1288
  const usage = inferenceCompleted.event.payload.usage;
1179
1289
  const turnCompleted = yield* events.turnCompleted({
@@ -1292,55 +1402,66 @@ const makeLiveTurnRunner = Effect.gen(function* () {
1292
1402
  return Cause.hasInterruptsOnly(exit.cause) ? failRemainingOpen("interrupted") : Effect.void;
1293
1403
  });
1294
1404
  });
1295
- return { runTurn: Effect.fn("agent.turn")(function* (input) {
1296
- const turnIdentity = {
1297
- runId: input.runId,
1298
- turnId: input.turnId
1299
- };
1300
- const maxToolCallsPerRun = input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun$1;
1301
- yield* annotateEdaSpan({
1302
- "eda.run.id": input.runId,
1303
- "eda.turn.id": input.turnId,
1304
- "eda.model.provider": input.modelSelection?.provider,
1305
- "eda.model.id": input.modelSelection?.modelId,
1306
- "eda.tool.max_calls_per_run": maxToolCallsPerRun
1307
- });
1308
- const inferencesStarted = yield* Ref.make(0);
1309
- return yield* Effect.gen(function* () {
1310
- const inferenceId = yield* ids.makeInferenceId();
1311
- yield* Ref.update(inferencesStarted, (count) => count + 1);
1312
- const inference = yield* inferenceRunner.runInference({
1313
- ...turnIdentity,
1314
- inferenceId,
1315
- prompt: input.prompt,
1316
- eventSink: input.eventSink,
1317
- modelSelection: input.modelSelection
1318
- });
1319
- const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
1320
- return TurnRunResult.make({
1321
- started: input.started,
1322
- inference,
1323
- outcome
1324
- });
1325
- }).pipe(Effect.tap((result) => Effect.gen(function* () {
1405
+ return {
1406
+ toolRecoveryPolicy: (toolName) => toolRegistry.getModelToolkit().pipe(Effect.map((toolkit) => toolRecoveryPolicy(toolkit, toolName))),
1407
+ resumeToolCalls: ({ calls, eventSink }) => Effect.forEach(calls, ({ created, resume }) => toolExecutor.executeCreated({
1408
+ created,
1409
+ eventSink,
1410
+ resume
1411
+ }), {
1412
+ concurrency: maxToolExecutionConcurrency,
1413
+ discard: true
1414
+ }),
1415
+ runTurn: Effect.fn("agent.turn")(function* (input) {
1416
+ const turnIdentity = {
1417
+ runId: input.runId,
1418
+ turnId: input.turnId
1419
+ };
1420
+ const maxToolCallsPerRun = input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun$1;
1326
1421
  yield* annotateEdaSpan({
1327
- "eda.turn.outcome": result.outcome._tag,
1328
- "eda.inference.started_count": yield* Ref.get(inferencesStarted),
1329
- "eda.provider.parts_recorded": result.inference.partsRecorded,
1330
- ...turnUsageAttributes(result)
1422
+ "eda.run.id": input.runId,
1423
+ "eda.turn.id": input.turnId,
1424
+ "eda.model.provider": input.modelSelection?.provider,
1425
+ "eda.model.id": input.modelSelection?.modelId,
1426
+ "eda.tool.max_calls_per_run": maxToolCallsPerRun
1331
1427
  });
1332
- })), Effect.catchCause((cause) => {
1333
- if (hasEDASessionStoreError(cause) || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
1334
- return Effect.uninterruptible(Effect.gen(function* () {
1335
- const terminal = yield* events.turnFailed({
1428
+ const inferencesStarted = yield* Ref.make(0);
1429
+ return yield* Effect.gen(function* () {
1430
+ const inferenceId = yield* ids.makeInferenceId();
1431
+ yield* Ref.update(inferencesStarted, (count) => count + 1);
1432
+ const inference = yield* inferenceRunner.runInference({
1336
1433
  ...turnIdentity,
1337
- error: failurePayloadFromCause(cause)
1434
+ inferenceId,
1435
+ prompt: input.prompt,
1436
+ eventSink: input.eventSink,
1437
+ modelSelection: input.modelSelection
1438
+ });
1439
+ const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
1440
+ return TurnRunResult.make({
1441
+ started: input.started,
1442
+ inference,
1443
+ outcome
1444
+ });
1445
+ }).pipe(Effect.tap((result) => Effect.gen(function* () {
1446
+ yield* annotateEdaSpan({
1447
+ "eda.turn.outcome": result.outcome._tag,
1448
+ "eda.inference.started_count": yield* Ref.get(inferencesStarted),
1449
+ "eda.provider.parts_recorded": result.inference.partsRecorded,
1450
+ ...turnUsageAttributes(result)
1338
1451
  });
1339
- yield* input.eventSink.appendDurable(terminal);
1340
- return yield* Effect.failCause(cause);
1452
+ })), Effect.catchCause((cause) => {
1453
+ if (hasEDASessionStoreError(cause) || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
1454
+ return Effect.uninterruptible(Effect.gen(function* () {
1455
+ const terminal = yield* events.turnFailed({
1456
+ ...turnIdentity,
1457
+ error: failurePayloadFromCause(cause)
1458
+ });
1459
+ yield* input.eventSink.appendDurable(terminal);
1460
+ return yield* Effect.failCause(cause);
1461
+ }));
1341
1462
  }));
1342
- }));
1343
- }) };
1463
+ })
1464
+ };
1344
1465
  });
1345
1466
  /** Owns one turn: turn boundaries, inferences, tool handoff, and terminal turn events. */
1346
1467
  var TurnRunner = class TurnRunner extends Context.Service()("@effect-durable-agent/TurnRunner") {
@@ -1382,6 +1503,7 @@ const toolFailurePromptPartFromCreated = (created, result) => {
1382
1503
  id: created.event.payload.promptPart.id,
1383
1504
  name: created.event.payload.promptPart.name,
1384
1505
  isFailure: true,
1506
+ providerExecuted: false,
1385
1507
  result
1386
1508
  }),
1387
1509
  id: created.event.payload.promptPart.id,
@@ -1395,11 +1517,11 @@ const requireFrameworkCreatedToolCalls = (created) => Effect.gen(function* () {
1395
1517
  if (unsupported !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Provider-executed tool calls are unsupported: ${unsupported.event.payload.promptPart.name}`));
1396
1518
  return created;
1397
1519
  });
1398
- const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.payload.usage) : {};
1399
- const isInferenceCompleted = (committed) => committed.event.type === inferenceCompletedEventType;
1400
- const isInferenceFailed = (committed) => committed.event.type === inferenceFailedEventType;
1401
- const isToolCallCreated = (committed) => committed.event.type === toolCallCreatedEventType;
1402
- const isToolCallRejected = (committed) => committed.event.type === toolCallRejectedEventType;
1520
+ const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.type === "TurnCompleted" ? result.outcome.committed.event.payload.usage : void 0) : {};
1521
+ const isInferenceCompleted = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceCompletedEventType;
1522
+ const isInferenceFailed = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceFailedEventType;
1523
+ const isToolCallCreated = (committed) => committed.event.namespace === "effect-durable-agent" && Schema.is(ToolCallCreatedEvent)(committed.event);
1524
+ const isToolCallRejected = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === toolCallRejectedEventType;
1403
1525
  const isToolDecisionBoundary = (committed) => isToolCallCreated(committed) || isToolCallRejected(committed);
1404
1526
  const requireInferenceCompleted = (committed) => {
1405
1527
  const completed = committed.find(isInferenceCompleted);
@@ -1430,7 +1552,11 @@ const SessionCommandOutcome = Schema.Union([
1430
1552
  SessionCommandCancelled
1431
1553
  ]);
1432
1554
  /** Why a control drain stopped without starting more command work. */
1433
- const SessionNoRunnableReason = Schema.Literals(["active-command", "no-pending-command"]);
1555
+ const SessionNoRunnableReason = Schema.Literals([
1556
+ "active-command",
1557
+ "no-pending-command",
1558
+ "awaiting-run-authorization"
1559
+ ]);
1434
1560
  /** Session control result when no admitted command is runnable. */
1435
1561
  const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand", {
1436
1562
  reason: SessionNoRunnableReason,
@@ -1438,7 +1564,7 @@ const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand",
1438
1564
  });
1439
1565
  /** Control result when command execution was started in an active child scope. */
1440
1566
  const SessionForkedCommand = Schema.TaggedStruct("SessionForkedCommand", { commandId: CommandId });
1441
- var SessionCommandAdmissionConflict = class extends Schema.TaggedErrorClass()("SessionCommandAdmissionConflict", {
1567
+ var SessionCommandAdmissionConflict = class extends Schema.TaggedError()("SessionCommandAdmissionConflict", {
1442
1568
  code: Schema.Literals(["queue_paused", "paused_queue_changed"]),
1443
1569
  message: Schema.String,
1444
1570
  pausedMessageIds: Schema.Array(MessageId)
@@ -1457,6 +1583,7 @@ const toolCancelledPromptPartFromRecord = (tool, error) => {
1457
1583
  id: decision.providerPartId,
1458
1584
  name: decision.toolName,
1459
1585
  isFailure: true,
1586
+ providerExecuted: false,
1460
1587
  result: error
1461
1588
  }),
1462
1589
  id: decision.providerPartId,
@@ -1495,10 +1622,27 @@ const makeLiveSessionState = Effect.gen(function* () {
1495
1622
  const promptProjector = yield* EDAPromptProjector;
1496
1623
  const sessionContext = yield* SessionContext;
1497
1624
  const runScheduler = yield* RunScheduler;
1625
+ const schedulingWakeup = yield* RunSchedulingWakeup;
1498
1626
  const reducerRegistry = yield* EDAReducerRegistry;
1499
1627
  const sinkRegistry = yield* EDASinkRegistry;
1500
- const hydrated = yield* hydrateFrameworkReducedState(store);
1501
- const hydratedReducerStates = yield* hydrateAppReducerStates(store, reducerRegistry.reducers);
1628
+ const { hydrated, hydratedReducerStates } = yield* Effect.gen(function* () {
1629
+ const hydrated = yield* hydrateFrameworkReducedState(store);
1630
+ const hydratedReducerStates = yield* hydrateAppReducerStates(store, reducerRegistry.reducers);
1631
+ yield* Effect.annotateCurrentSpan({
1632
+ "eda.seq.head": hydrated.state.lastSeq,
1633
+ "eda.checkpoint.framework_seq": hydrated.checkpointSeq,
1634
+ ...hydratedReducerStates.checkpointSeq === void 0 ? {} : { "eda.checkpoint.app_min_seq": hydratedReducerStates.checkpointSeq }
1635
+ });
1636
+ return {
1637
+ hydrated,
1638
+ hydratedReducerStates
1639
+ };
1640
+ }).pipe(Effect.withSpan("agent.session.hydrate", { attributes: {
1641
+ sessionId: sessionContext.sessionId,
1642
+ "eda.session.id": sessionContext.sessionId,
1643
+ "eda.reducers.count": reducerRegistry.reducers.length
1644
+ } }));
1645
+ yield* schedulingWakeup.setPending(hydrated.state.runSchedulingRequest !== void 0 && hydrated.state.runSchedulingRequest.deliveredSeq === void 0);
1502
1646
  const startupRecoveryCheckpointSeq = hydratedReducerStates.checkpointSeq === void 0 ? hydrated.checkpointSeq : SequenceNumber.make(Math.min(hydrated.checkpointSeq, hydratedReducerStates.checkpointSeq));
1503
1647
  const state = yield* Ref.make({
1504
1648
  reduced: hydrated.state,
@@ -1509,6 +1653,16 @@ const makeLiveSessionState = Effect.gen(function* () {
1509
1653
  }
1510
1654
  });
1511
1655
  const gate = yield* Semaphore.make(1);
1656
+ const controlGate = yield* Semaphore.make(1);
1657
+ /**
1658
+ * Admission versus startup repair: recovery plans its repair batch from a snapshot and then
1659
+ * checks the result reached a fixed point, so no command may be admitted in between. Recovery
1660
+ * that finishes in the background (re-invoked tools) would otherwise race live admission.
1661
+ */
1662
+ const admissionGate = yield* Semaphore.make(1);
1663
+ /** Set while startup recovery finishes in the background holding the control gate. */
1664
+ const recoveringInBackground = yield* Ref.make(false);
1665
+ const deliveryGate = yield* Semaphore.make(1);
1512
1666
  const ingressSignals = yield* Queue.sliding(1);
1513
1667
  const reducerCheckpointSnapshots = yield* Queue.sliding(1);
1514
1668
  const executionState = yield* Ref.make({ _tag: "Idle" });
@@ -1536,7 +1690,7 @@ const makeLiveSessionState = Effect.gen(function* () {
1536
1690
  }));
1537
1691
  const buildReducerCheckpointSnapshot = (snapshot) => [{
1538
1692
  name: frameworkReducedStateReducerName,
1539
- schemaVersion: 6,
1693
+ schemaVersion: 7,
1540
1694
  throughSeq: snapshot.reduced.lastSeq,
1541
1695
  payload: encodeReducedStateCheckpoint(snapshot.reduced),
1542
1696
  updatedAtMs: snapshot.updatedAtMs
@@ -1577,7 +1731,10 @@ const makeLiveSessionState = Effect.gen(function* () {
1577
1731
  reducerStates: nextReducerStates,
1578
1732
  ephemeral: current.ephemeral
1579
1733
  });
1580
- for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make(entry));
1734
+ for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make({
1735
+ position: entry.position,
1736
+ event: durableEventEnvelope(entry.event)
1737
+ }));
1581
1738
  return { head: nextReduced.lastSeq };
1582
1739
  });
1583
1740
  const snapshot = () => Ref.get(state).pipe(Effect.map((state) => state.reduced));
@@ -1609,10 +1766,11 @@ const makeLiveSessionState = Effect.gen(function* () {
1609
1766
  const commitInitialSystemPrompt = (systemPrompt) => Effect.gen(function* () {
1610
1767
  if (systemPrompt === void 0) return;
1611
1768
  if ((yield* Ref.get(state)).reduced.lastSeq > SequenceNumber.make(0)) return;
1612
- yield* appendDurable(yield* events.systemMessageCommitted({
1769
+ const event = yield* events.systemMessageCommitted({
1613
1770
  messageId: yield* ids.makeMessageId(),
1614
1771
  content: systemPrompt
1615
- }));
1772
+ });
1773
+ yield* appendDurable(event);
1616
1774
  });
1617
1775
  const publishEphemeralCore = (event) => withAppendGate(Effect.gen(function* () {
1618
1776
  const current = yield* Ref.get(state);
@@ -1634,13 +1792,10 @@ const makeLiveSessionState = Effect.gen(function* () {
1634
1792
  }
1635
1793
  });
1636
1794
  yield* liveBus.publish(positioned);
1795
+ yield* sinkRegistry.publishEphemeralToSinks(positioned);
1637
1796
  return positioned;
1638
1797
  }));
1639
- const publishEphemeral = (event) => Effect.gen(function* () {
1640
- const positioned = yield* publishEphemeralCore(event);
1641
- yield* sinkRegistry.publishEphemeralToSinks(positioned, publishEphemeralCore);
1642
- return positioned;
1643
- });
1798
+ const publishEphemeral = publishEphemeralCore;
1644
1799
  const wakeAfterCommandAdmission = () => Queue.offer(ingressSignals, void 0);
1645
1800
  /** Use indexed store lookup for command idempotency instead of genesis replay. */
1646
1801
  const findExistingCommandAdmission = (command) => Effect.gen(function* () {
@@ -1661,8 +1816,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1661
1816
  }
1662
1817
  const existing = yield* findExistingCommandAdmission(command);
1663
1818
  if (existing !== void 0) {
1664
- rememberPreparedCommand(existing.event, preparedByIdempotencyKey, preparedByCommandId);
1665
- return [existing.event];
1819
+ rememberPreparedCommand(durableEventEnvelope(existing.event), preparedByIdempotencyKey, preparedByCommandId);
1820
+ return [durableEventEnvelope(existing.event)];
1666
1821
  }
1667
1822
  const commandId = command.commandId ?? (yield* ids.makeCommandId());
1668
1823
  const admitted = commandWithId(command, commandId);
@@ -1716,7 +1871,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1716
1871
  submitted
1717
1872
  ];
1718
1873
  });
1719
- const submitBatch = Effect.fn(function* (input) {
1874
+ const submitBatch = (input) => admissionGate.withPermits(1)(submitBatchAdmitted(input));
1875
+ const submitBatchAdmitted = Effect.fn(function* (input) {
1720
1876
  const commandCount = input.filter(isEDACommand).length;
1721
1877
  yield* annotateEdaSpan({
1722
1878
  "eda.command.submittable_count": input.length,
@@ -1726,7 +1882,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1726
1882
  const committed = yield* withAppendGate(Effect.gen(function* () {
1727
1883
  const preparedByIdempotencyKey = /* @__PURE__ */ new Map();
1728
1884
  const preparedByCommandId = /* @__PURE__ */ new Map();
1729
- return yield* commitDurableEntriesWithinGate((yield* Effect.forEach(input, (item) => isEDACommand(item) ? prepareCommandAdmission(item, preparedByIdempotencyKey, preparedByCommandId) : Effect.succeed([item]))).flat().map((event) => ({ event })));
1885
+ const durableEvents = (yield* Effect.forEach(input, (item) => isEDACommand(item) ? prepareCommandAdmission(item, preparedByIdempotencyKey, preparedByCommandId) : Effect.succeed([item]))).flat();
1886
+ return yield* commitDurableEntriesWithinGate(durableEvents.map((event) => ({ event })));
1730
1887
  }));
1731
1888
  yield* annotateEdaSpan(committedBatchAttributes(committed));
1732
1889
  if (commandCount > 0) yield* wakeAfterCommandAdmission();
@@ -1737,6 +1894,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1737
1894
  });
1738
1895
  const initialize = (input) => commitInitialSystemPrompt(input.systemPrompt);
1739
1896
  const sessionApi = {
1897
+ grantRun: (command, input) => grantRun(command, input),
1898
+ retryRunSchedulingDelivery: () => retryRunSchedulingDelivery(),
1740
1899
  initialize,
1741
1900
  submitBatch,
1742
1901
  admitCommand,
@@ -1778,9 +1937,11 @@ const makeLiveSessionState = Effect.gen(function* () {
1778
1937
  yield* requestCurrentReducerCheckpointSnapshot("startup-recovery-complete");
1779
1938
  });
1780
1939
  const maybeCompactAtBoundary = () => Effect.gen(function* () {
1781
- const current = yield* currentReduced();
1940
+ const data = yield* currentData();
1941
+ const current = data.reduced;
1782
1942
  const next = (yield* compactionRunner.maybeCompact({
1783
1943
  state: current,
1944
+ reducerStates: data.reducerStates,
1784
1945
  context: yield* contextProjectionFor(current),
1785
1946
  appendDurableEntries
1786
1947
  })).length === 0 ? current : yield* currentReduced();
@@ -1788,25 +1949,29 @@ const makeLiveSessionState = Effect.gen(function* () {
1788
1949
  return next;
1789
1950
  });
1790
1951
  const cancelCommand = (commandId, reason) => Effect.gen(function* () {
1791
- const committed = yield* appendDurable(yield* events.commandCancelled({
1952
+ const event = yield* events.commandCancelled({
1792
1953
  commandId,
1793
1954
  reason
1794
- }));
1955
+ });
1956
+ const committed = yield* appendDurable(event);
1795
1957
  return SessionCommandCancelled.make({ committed });
1796
1958
  });
1797
1959
  const failInterruptedTurnIfOpen = (active, reason) => Effect.gen(function* () {
1798
1960
  if ((yield* currentReduced()).turns.get(active.turnId)?.terminal !== void 0) return;
1799
- return yield* appendDurable(yield* events.turnFailed({
1961
+ const event = yield* events.turnFailed({
1800
1962
  runId: active.runId,
1801
1963
  turnId: active.turnId,
1802
1964
  error: interruptionFailure("turn", reason, {
1803
1965
  runId: active.runId,
1804
1966
  turnId: active.turnId
1805
1967
  })
1806
- }));
1968
+ });
1969
+ return yield* appendDurable(event);
1807
1970
  });
1808
1971
  const completeRunAndCommand = (commandId, runId) => Effect.gen(function* () {
1809
- const committed = yield* appendDurableBatch([yield* events.runCompleted({ runId }), yield* events.commandCompleted({ commandId })]);
1972
+ const runCompleted = yield* events.runCompleted({ runId });
1973
+ const commandCompleted = yield* events.commandCompleted({ commandId });
1974
+ const committed = yield* appendDurableBatch([runCompleted, commandCompleted]);
1810
1975
  return SessionCommandCompleted.make({ committed: committed.at(-1) });
1811
1976
  });
1812
1977
  const failRunAndCommandWithError = (commandId, runId, error) => Effect.gen(function* () {
@@ -1818,7 +1983,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1818
1983
  commandId,
1819
1984
  error
1820
1985
  });
1821
- const failurePlan = planRunFailure(yield* currentReduced());
1986
+ const current = yield* currentReduced();
1987
+ const failurePlan = planRunFailure(current);
1822
1988
  const resumeEvents = [];
1823
1989
  if (failurePlan.messageIdsToResume.length > 0) {
1824
1990
  const resumeCommandId = yield* ids.makeCommandId();
@@ -1836,23 +2002,27 @@ const makeLiveSessionState = Effect.gen(function* () {
1836
2002
  });
1837
2003
  const failRunAndCommand = (commandId, runId, turn) => Effect.gen(function* () {
1838
2004
  if (turn.outcome._tag !== "TurnRunFailed") return yield* Effect.die(/* @__PURE__ */ new Error("Cannot fail run from a completed turn"));
1839
- return yield* failRunAndCommandWithError(commandId, runId, (yield* requireTurnFailed(turn.outcome.committed)).event.payload.error);
2005
+ const failed = yield* requireTurnFailed(turn.outcome.committed);
2006
+ return yield* failRunAndCommandWithError(commandId, runId, failed.event.payload.error);
1840
2007
  });
1841
2008
  const interruptRunAndCommand = (active, reason) => Effect.gen(function* () {
1842
2009
  const failurePlan = planRunFailure(yield* currentReduced());
2010
+ const runFailed = yield* events.runFailed({
2011
+ runId: active.runId,
2012
+ error: interruptionFailure("run", reason, { runId: active.runId })
2013
+ });
2014
+ const commandCancelled = yield* events.commandCancelled({
2015
+ commandId: active.commandId,
2016
+ reason
2017
+ });
2018
+ const resume = failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
2019
+ commandId: yield* ids.makeCommandId(),
2020
+ messageIds: failurePlan.messageIdsToResume
2021
+ }) })];
1843
2022
  const committed = yield* appendDurableBatch([
1844
- yield* events.runFailed({
1845
- runId: active.runId,
1846
- error: interruptionFailure("run", reason, { runId: active.runId })
1847
- }),
1848
- yield* events.commandCancelled({
1849
- commandId: active.commandId,
1850
- reason
1851
- }),
1852
- ...failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
1853
- commandId: yield* ids.makeCommandId(),
1854
- messageIds: failurePlan.messageIdsToResume
1855
- }) })]
2023
+ runFailed,
2024
+ commandCancelled,
2025
+ ...resume
1856
2026
  ]);
1857
2027
  return SessionCommandCancelled.make({ committed: committed.at(-1) });
1858
2028
  });
@@ -1969,13 +2139,68 @@ const makeLiveSessionState = Effect.gen(function* () {
1969
2139
  });
1970
2140
  return SessionForkedCommand.make({ commandId: input.commandId });
1971
2141
  });
2142
+ const reconcileSchedulingWakeup = Effect.fnUntraced(function* () {
2143
+ const request = (yield* currentReduced()).runSchedulingRequest;
2144
+ yield* schedulingWakeup.setPending(request !== void 0 && request.deliveredSeq === void 0);
2145
+ });
2146
+ const retryRunSchedulingDelivery = Effect.fnUntraced(function* () {
2147
+ if (yield* Ref.get(recoveringInBackground)) return;
2148
+ yield* deliveryGate.withPermitsIfAvailable(1)(Effect.gen(function* () {
2149
+ const request = yield* controlGate.withPermits(1)(Effect.gen(function* () {
2150
+ const current = (yield* currentReduced()).runSchedulingRequest;
2151
+ yield* reconcileSchedulingWakeup();
2152
+ return current?.deliveredSeq === void 0 ? current : void 0;
2153
+ }));
2154
+ if (request === void 0) return;
2155
+ const delivered = yield* Effect.exit(keepAlive.withActiveWork("run-scheduling-delivery", runScheduler.deliver({
2156
+ sessionId: sessionContext.sessionId,
2157
+ request: {
2158
+ requestId: request.requestId,
2159
+ work: request.work
2160
+ }
2161
+ }).pipe(Effect.timeout("10 seconds"))));
2162
+ if (Exit.isFailure(delivered)) {
2163
+ if (Cause.hasInterruptsOnly(delivered.cause)) return yield* Effect.interrupt;
2164
+ yield* controlGate.withPermits(1)(reconcileSchedulingWakeup());
2165
+ yield* Effect.logWarning("Run authorization delivery will retry on the durable host wakeup", {
2166
+ requestId: request.requestId,
2167
+ cause: Cause.pretty(delivered.cause)
2168
+ });
2169
+ return;
2170
+ }
2171
+ yield* controlGate.withPermits(1)(Effect.gen(function* () {
2172
+ const current = (yield* currentReduced()).runSchedulingRequest;
2173
+ if (current?.requestId === request.requestId && current.deliveredSeq === void 0) yield* appendDurable(yield* events.runSchedulingDelivered({ requestId: request.requestId }));
2174
+ yield* reconcileSchedulingWakeup();
2175
+ }));
2176
+ }));
2177
+ });
2178
+ const forkSchedulingDelivery = () => retryRunSchedulingDelivery().pipe(Effect.catchCause((cause) => Effect.gen(function* () {
2179
+ yield* markFatalIfDurable(cause);
2180
+ yield* Effect.logError("Run authorization delivery worker failed", { cause: Cause.pretty(cause) });
2181
+ })), Effect.forkIn(runtimeScope), Effect.asVoid);
2182
+ const prepareRunSchedulingRequest = Effect.fnUntraced(function* (work) {
2183
+ yield* schedulingWakeup.setPending(true);
2184
+ return yield* events.runSchedulingRequested({
2185
+ requestId: yield* ids.makeRunRequestId(),
2186
+ work
2187
+ });
2188
+ });
2189
+ const deferRun = Effect.fnUntraced(function* (work) {
2190
+ yield* appendDurable(yield* prepareRunSchedulingRequest(work));
2191
+ yield* forkSchedulingDelivery();
2192
+ return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
2193
+ });
1972
2194
  const startSubmitCommand = Effect.fn(function* (command, input) {
1973
2195
  if (command.command._tag !== "SubmitMessage") return yield* Effect.die(/* @__PURE__ */ new Error("startSubmitCommand requires SubmitMessage"));
1974
2196
  const submit = command.command;
1975
2197
  const commandId = command.commandId;
1976
- yield* runScheduler.resolve({
2198
+ if ((yield* runScheduler.resolve({
1977
2199
  sessionId: sessionContext.sessionId,
1978
2200
  commandId
2201
+ }))._tag === "Deferred") return yield* deferRun({
2202
+ _tag: "Command",
2203
+ commandId
1979
2204
  });
1980
2205
  yield* annotateEdaSpan({
1981
2206
  "eda.command.id": commandId,
@@ -2006,13 +2231,14 @@ const makeLiveSessionState = Effect.gen(function* () {
2006
2231
  modelSelection: input.modelSelection,
2007
2232
  trace: activeRunTrace.runTrace
2008
2233
  });
2234
+ const startedEvents = yield* appendDurableBatch([
2235
+ commandStarted,
2236
+ ...userMessage === void 0 ? [] : [userMessage],
2237
+ runStarted
2238
+ ]);
2009
2239
  return yield* startTurn({
2010
2240
  commandId,
2011
- commandStarted: (yield* appendDurableBatch([
2012
- commandStarted,
2013
- ...userMessage === void 0 ? [] : [userMessage],
2014
- runStarted
2015
- ]))[0],
2241
+ commandStarted: startedEvents[0],
2016
2242
  inputMessageIds: [messageId],
2017
2243
  runId,
2018
2244
  modelSelection: input.modelSelection,
@@ -2030,9 +2256,12 @@ const makeLiveSessionState = Effect.gen(function* () {
2030
2256
  return (message?._tag === "User" || message?._tag === "Steering") && message.consumedSeq === void 0 && message.cancelledSeq === void 0 ? [message] : [];
2031
2257
  });
2032
2258
  if (pending.length === 0) return yield* processInactiveStopCommand(command);
2033
- yield* runScheduler.resolve({
2259
+ if ((yield* runScheduler.resolve({
2034
2260
  sessionId: sessionContext.sessionId,
2035
2261
  commandId: command.commandId
2262
+ }))._tag === "Deferred") return yield* deferRun({
2263
+ _tag: "Command",
2264
+ commandId: command.commandId
2036
2265
  });
2037
2266
  const commandStarted = yield* events.commandStarted({ commandId: command.commandId });
2038
2267
  const runId = yield* ids.makeRunId();
@@ -2043,12 +2272,13 @@ const makeLiveSessionState = Effect.gen(function* () {
2043
2272
  runId
2044
2273
  });
2045
2274
  return yield* closeRunTraceOnFailure(activeRunTrace, Effect.gen(function* () {
2046
- const started = yield* appendDurableBatch([commandStarted, yield* events.runStarted({
2275
+ const runStarted = yield* events.runStarted({
2047
2276
  runId,
2048
2277
  commandIds: [command.commandId, ...pending.map((message) => message.commandId)],
2049
2278
  modelSelection: input.modelSelection,
2050
2279
  trace: activeRunTrace.runTrace
2051
- })]);
2280
+ });
2281
+ const started = yield* appendDurableBatch([commandStarted, runStarted]);
2052
2282
  return yield* startTurn({
2053
2283
  commandId: command.commandId,
2054
2284
  commandStarted: started[0],
@@ -2061,6 +2291,108 @@ const makeLiveSessionState = Effect.gen(function* () {
2061
2291
  });
2062
2292
  }));
2063
2293
  });
2294
+ const grantRun = Effect.fn("agent.run.grant")(function* (grant, input) {
2295
+ yield* annotateEdaSpan({
2296
+ "eda.session.id": sessionContext.sessionId,
2297
+ "eda.run_request.id": grant.requestId
2298
+ });
2299
+ return yield* controlGate.withPermits(1)(keepAlive.withActiveWork("run-authorization-grant", Effect.gen(function* () {
2300
+ yield* failIfFatal;
2301
+ const initial = yield* currentReduced();
2302
+ if (!canGrantRun(initial, grant.requestId)) return { _tag: "Stale" };
2303
+ const request = initial.runSchedulingRequest;
2304
+ if (request === void 0) return { _tag: "Stale" };
2305
+ const command = initial.commands.get(request.work.commandId);
2306
+ if (command?.command === void 0) return { _tag: "Stale" };
2307
+ const admitted = command.command;
2308
+ const predecessor = request.work._tag === "Recovery" ? initial.runs.get(request.work.interruptedRunId) : void 0;
2309
+ const modelSelection = predecessor?.modelSelection ?? initial.modelSelection ?? input.modelSelection;
2310
+ const runId = yield* ids.makeRunId();
2311
+ const trace = yield* startRunTrace({
2312
+ commandId: command.commandId,
2313
+ admissionTrace: command.admissionTrace,
2314
+ modelSelection,
2315
+ runId
2316
+ });
2317
+ return yield* closeRunTraceOnFailure(trace, Effect.gen(function* () {
2318
+ const started = yield* withAppendGate(Effect.gen(function* () {
2319
+ const current = yield* currentReduced();
2320
+ if (!canGrantRun(current, grant.requestId)) return void 0;
2321
+ const inputMessageIds = [...runSchedulingInputMessageIds(current, request.work)];
2322
+ const batch = [];
2323
+ let commandStarted;
2324
+ if (request.work._tag === "Recovery") {
2325
+ if (command.startedSeq === void 0 || predecessor === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization requires its started command and predecessor"));
2326
+ [commandStarted] = yield* store.loadCommittedEventsBySeq([command.startedSeq]);
2327
+ if (commandStarted?.event.type !== "CommandStarted") return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization is missing CommandStarted"));
2328
+ } else {
2329
+ batch.push(yield* events.commandStarted({ commandId: command.commandId }));
2330
+ if (admitted._tag === "SubmitMessage" && inputMessageIds.length === 0) {
2331
+ const messageId = yield* ids.makeMessageId();
2332
+ batch.push(yield* events.userMessageCommitted({
2333
+ commandId: command.commandId,
2334
+ messageId,
2335
+ content: admitted.content
2336
+ }));
2337
+ inputMessageIds.push(messageId);
2338
+ }
2339
+ }
2340
+ batch.push(yield* events.runSchedulingGranted({
2341
+ requestId: request.requestId,
2342
+ runId
2343
+ }));
2344
+ const commandIds = predecessor?.commandIds ?? [command.commandId, ...admitted._tag === "ResumePendingMessages" ? inputMessageIds.flatMap((messageId) => {
2345
+ const message = current.messages.get(messageId);
2346
+ return message?._tag === "User" || message?._tag === "Steering" ? [message.commandId] : [];
2347
+ }) : []];
2348
+ batch.push(yield* events.runStarted({
2349
+ runId,
2350
+ commandIds,
2351
+ modelSelection,
2352
+ trace: trace.runTrace
2353
+ }));
2354
+ if (request.work._tag === "Recovery") batch.push(yield* events.recoveryCompleted({
2355
+ trigger: "runtime-restart",
2356
+ continuation: {
2357
+ commandId: command.commandId,
2358
+ interruptedRunId: request.work.interruptedRunId,
2359
+ replacementRunId: runId
2360
+ }
2361
+ }));
2362
+ const committed = yield* commitDurableEntriesWithinGate(batch.map((event) => ({ event })));
2363
+ commandStarted ??= committed[0];
2364
+ if (commandStarted === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Granted run must have CommandStarted"));
2365
+ return {
2366
+ commandStarted,
2367
+ inputMessageIds
2368
+ };
2369
+ }));
2370
+ if (started === void 0) {
2371
+ yield* Scope.close(trace.runScope, Exit.void);
2372
+ return { _tag: "Stale" };
2373
+ }
2374
+ yield* reconcileSchedulingWakeup();
2375
+ yield* startTurn({
2376
+ commandId: command.commandId,
2377
+ commandStarted: started.commandStarted,
2378
+ inputMessageIds: started.inputMessageIds,
2379
+ runId,
2380
+ modelSelection,
2381
+ ...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
2382
+ runScope: trace.runScope,
2383
+ runSpan: trace.runSpan
2384
+ });
2385
+ yield* wakeAfterCommandAdmission();
2386
+ return {
2387
+ _tag: "Granted",
2388
+ runId
2389
+ };
2390
+ }));
2391
+ })).pipe(Effect.catchCause((cause) => Effect.gen(function* () {
2392
+ yield* markFatalIfDurable(cause);
2393
+ return yield* Effect.failCause(cause);
2394
+ }))));
2395
+ });
2064
2396
  const processInactiveStopCommand = Effect.fn(function* (command) {
2065
2397
  const commandId = command.commandId;
2066
2398
  return (yield* startedBoundaryGuard({
@@ -2142,6 +2474,47 @@ const makeLiveSessionState = Effect.gen(function* () {
2142
2474
  turn: exit.value
2143
2475
  };
2144
2476
  });
2477
+ /**
2478
+ * Before failing what the dead runtime left open, re-invoke each started tool call whose tool
2479
+ * declares `ToolRecovery: "reinvoke"` and still has attempts left. Each commits its next start
2480
+ * before running, so a runtime that dies again mid-reinvocation spends that attempt. Calls that
2481
+ * finish here are terminal by the time recovery plans its batch; the rest are failed as before.
2482
+ */
2483
+ const plannedReinvocations = Effect.fnUntraced(function* (reduced) {
2484
+ const calls = [];
2485
+ for (const tool of planSessionRecovery(reduced).openToolCalls) {
2486
+ const decision = tool.decision;
2487
+ if (decision?._tag !== "Created" || decision.providerExecuted) continue;
2488
+ if (tool.startedSeq === void 0 || tool.startedAtMs === void 0) continue;
2489
+ const attempt = (tool.attempt ?? 1) + 1;
2490
+ if (attempt > 3) continue;
2491
+ if ((yield* turnRunner.toolRecoveryPolicy(decision.toolName)) !== "reinvoke") continue;
2492
+ calls.push({
2493
+ seq: decision.seq,
2494
+ resume: {
2495
+ attempt,
2496
+ firstStartedAtMs: tool.startedAtMs,
2497
+ firstStartedSeq: tool.startedSeq
2498
+ }
2499
+ });
2500
+ }
2501
+ return calls;
2502
+ });
2503
+ const resumeInterruptedToolCalls = Effect.fnUntraced(function* (calls) {
2504
+ yield* annotateEdaSpan({ "eda.recovery.reinvoked_tool_calls": calls.length });
2505
+ if (calls.length === 0) return;
2506
+ const created = yield* store.loadCommittedEventsBySeq(calls.map((call) => call.seq));
2507
+ yield* turnRunner.resumeToolCalls({
2508
+ calls: calls.flatMap((call) => {
2509
+ const event = created.find((entry) => entry.position.seq === call.seq);
2510
+ return event === void 0 ? [] : [{
2511
+ created: event,
2512
+ resume: call.resume
2513
+ }];
2514
+ }),
2515
+ eventSink: sessionApi
2516
+ }).pipe(Effect.catchTag("ToolExecutionEventNotCreated", (error) => Effect.die(error)));
2517
+ });
2145
2518
  const recoverSession = Effect.fnUntraced(function* (reduced, reason, input) {
2146
2519
  const plan = planSessionRecovery(reduced);
2147
2520
  input = {
@@ -2229,11 +2602,17 @@ const makeLiveSessionState = Effect.gen(function* () {
2229
2602
  commandId: yield* ids.makeCommandId(),
2230
2603
  messageIds: plan.messageIdsToResume
2231
2604
  }) }));
2232
- if (plan.continuation !== void 0) yield* runScheduler.resolve({
2605
+ const resolution = plan.continuation === void 0 ? void 0 : yield* runScheduler.resolve({
2233
2606
  sessionId: sessionContext.sessionId,
2234
2607
  commandId: plan.continuation.command.commandId
2235
2608
  });
2236
- const continuationRunId = plan.continuation === void 0 ? void 0 : yield* ids.makeRunId();
2609
+ if (plan.continuation !== void 0 && resolution?._tag === "Deferred") recoveryEvents.push(yield* prepareRunSchedulingRequest({
2610
+ _tag: "Recovery",
2611
+ commandId: plan.continuation.command.commandId,
2612
+ interruptedRunId: plan.continuation.run.runId,
2613
+ inputMessageIds: plan.continuation.inputMessageIds
2614
+ }));
2615
+ const continuationRunId = plan.continuation === void 0 || resolution?._tag === "Deferred" ? void 0 : yield* ids.makeRunId();
2237
2616
  const continuationRunTrace = plan.continuation === void 0 || continuationRunId === void 0 ? void 0 : yield* startRunTrace({
2238
2617
  admissionTrace: plan.continuation.command.admissionTrace,
2239
2618
  commandId: plan.continuation.command.commandId,
@@ -2256,6 +2635,7 @@ const makeLiveSessionState = Effect.gen(function* () {
2256
2635
  } }
2257
2636
  }));
2258
2637
  const committed = recoveryEvents.length === 0 ? [] : yield* appendDurableBatch(recoveryEvents);
2638
+ if (resolution?._tag === "Deferred") yield* forkSchedulingDelivery();
2259
2639
  const nextPlan = planSessionRecovery(yield* currentReduced());
2260
2640
  if (!(plan.continuation === void 0 || continuationRunId === void 0 ? isSessionRecoveryPlanEmpty(nextPlan) : nextPlan.activeCommands.length === 1 && nextPlan.activeCommands[0]?.commandId === plan.continuation.command.commandId && nextPlan.activeRuns.length === 1 && nextPlan.activeRuns[0]?.runId === continuationRunId && nextPlan.activeTurns.length === 0 && nextPlan.activeInferences.length === 0 && nextPlan.openToolCalls.length === 0 && nextPlan.pendingStopRequests.length === 0 && nextPlan.openCompactions.length === 0 && nextPlan.messageIdsToPause.length === 0 && nextPlan.messageIdsToResume.length === 0 && nextPlan.continuation?.inputMessageIds.length === plan.continuation.inputMessageIds.length && nextPlan.continuation.inputMessageIds.every((messageId) => plan.continuation?.inputMessageIds.includes(messageId)))) return yield* Effect.die(/* @__PURE__ */ new Error("Startup recovery did not reach a fixed point before live execution"));
2261
2641
  return {
@@ -2317,7 +2697,8 @@ const makeLiveSessionState = Effect.gen(function* () {
2317
2697
  return (yield* startedBoundaryGuard({
2318
2698
  start: events.commandStarted({ commandId }),
2319
2699
  body: (started) => Effect.gen(function* () {
2320
- const committed = yield* appendDurableBatch([yield* events.commandCompleted({ commandId })]);
2700
+ const completed = yield* events.commandCompleted({ commandId });
2701
+ const committed = yield* appendDurableBatch([completed]);
2321
2702
  return {
2322
2703
  started,
2323
2704
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -2334,13 +2715,14 @@ const makeLiveSessionState = Effect.gen(function* () {
2334
2715
  })).value;
2335
2716
  });
2336
2717
  const failControlCommand = (commandId, code, message) => Effect.gen(function* () {
2337
- const committed = yield* appendDurable(yield* events.commandFailed({
2718
+ const failed = yield* events.commandFailed({
2338
2719
  commandId,
2339
2720
  error: FailurePayload.make({
2340
2721
  code,
2341
2722
  message
2342
2723
  })
2343
- }));
2724
+ });
2725
+ const committed = yield* appendDurable(failed);
2344
2726
  return SessionCommandFailed.make({ committed });
2345
2727
  });
2346
2728
  const cancelPendingMessage = Effect.fn(function* (command) {
@@ -2366,12 +2748,30 @@ const makeLiveSessionState = Effect.gen(function* () {
2366
2748
  commandId: target.commandId,
2367
2749
  reason: "pending message cancelled"
2368
2750
  })] : [];
2751
+ const schedulingPlan = planRunSchedulingCancellation(current, target.messageId);
2752
+ const schedulingEvents = [];
2753
+ if (schedulingPlan !== void 0) {
2754
+ schedulingEvents.push(yield* events.runSchedulingInvalidated({
2755
+ requestId: schedulingPlan.requestId,
2756
+ reason: "message-cancelled"
2757
+ }));
2758
+ if (schedulingPlan.cancelCommandId !== void 0) schedulingEvents.push(yield* events.commandCancelled({
2759
+ commandId: schedulingPlan.cancelCommandId,
2760
+ reason: "pending recovery inputs cancelled"
2761
+ }));
2762
+ if (schedulingPlan.replacementWork !== void 0) schedulingEvents.push(yield* prepareRunSchedulingRequest(schedulingPlan.replacementWork));
2763
+ }
2369
2764
  const completed = yield* events.commandCompleted({ commandId: controlCommandId });
2370
2765
  const committed = yield* appendDurableBatch([
2371
2766
  cancelled,
2372
2767
  ...originCancelled,
2768
+ ...schedulingEvents,
2373
2769
  completed
2374
2770
  ]);
2771
+ if (schedulingEvents.length > 0) {
2772
+ yield* reconcileSchedulingWakeup();
2773
+ yield* forkSchedulingDelivery();
2774
+ }
2375
2775
  return {
2376
2776
  started,
2377
2777
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -2394,17 +2794,28 @@ const makeLiveSessionState = Effect.gen(function* () {
2394
2794
  return (yield* startedBoundaryGuard({
2395
2795
  start: events.commandStarted({ commandId: controlCommandId }),
2396
2796
  body: (started) => Effect.gen(function* () {
2397
- const target = (yield* currentReduced()).messages.get(promotion.messageId);
2797
+ const current = yield* currentReduced();
2798
+ const target = current.messages.get(promotion.messageId);
2398
2799
  if (target?._tag !== "User" && target?._tag !== "Steering" || (target._tag === "User" ? target.disposition !== "queue" : target.pausedByCommandId === void 0) || target.consumedSeq !== void 0 || target.cancelledSeq !== void 0) return {
2399
2800
  started,
2400
2801
  outcome: yield* failControlCommand(controlCommandId, "message_not_queue", "Message is no longer a pending queue message")
2401
2802
  };
2402
- const committed = yield* appendDurableBatch([yield* events.userMessagePromoted({
2803
+ const promoted = yield* events.userMessagePromoted({
2403
2804
  commandId: controlCommandId,
2404
2805
  messageId: target.messageId,
2405
2806
  from: "queue",
2406
2807
  to: "steer"
2407
- }), yield* events.commandCompleted({ commandId: controlCommandId })]);
2808
+ });
2809
+ const resumed = promotionNeedsResumeCommand(current, target.messageId) ? [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
2810
+ commandId: yield* ids.makeCommandId(),
2811
+ messageIds: [target.messageId]
2812
+ }) })] : [];
2813
+ const completed = yield* events.commandCompleted({ commandId: controlCommandId });
2814
+ const committed = yield* appendDurableBatch([
2815
+ promoted,
2816
+ ...resumed,
2817
+ completed
2818
+ ]);
2408
2819
  return {
2409
2820
  started,
2410
2821
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -2431,25 +2842,30 @@ const makeLiveSessionState = Effect.gen(function* () {
2431
2842
  return (yield* startedBoundaryGuard({
2432
2843
  start: events.commandStarted({ commandId: stopCommandId }),
2433
2844
  body: (started) => Effect.uninterruptible(Effect.gen(function* () {
2434
- const requested = activeTurnIdentityForCommand(yield* currentReduced(), active.commandId);
2435
- yield* appendDurable(yield* events.stopTurnRequested({
2845
+ const beforeStop = yield* currentReduced();
2846
+ const requested = activeTurnIdentityForCommand(beforeStop, active.commandId);
2847
+ const requestedEvent = yield* events.stopTurnRequested({
2436
2848
  commandId: stopCommandId,
2437
2849
  ...requested === void 0 ? {} : {
2438
2850
  runId: requested.runId,
2439
2851
  turnId: requested.turnId
2440
2852
  }
2441
- }));
2853
+ });
2854
+ yield* appendDurable(requestedEvent);
2442
2855
  yield* Scope.close(active.turnScope, Exit.interrupt());
2443
2856
  yield* Ref.set(executionState, { _tag: "Idle" });
2444
2857
  yield* appendUserInterruption(active, stopCommandId, "interrupted");
2445
2858
  yield* Scope.close(active.runScope, Exit.interrupt());
2446
- const applied = activeTurnIdentityForCommand(yield* currentReduced(), active.commandId);
2447
- const committed = yield* appendDurableBatch([yield* events.stopTurnApplied({
2859
+ const afterStop = yield* currentReduced();
2860
+ const applied = activeTurnIdentityForCommand(afterStop, active.commandId);
2861
+ const appliedEvent = yield* events.stopTurnApplied({
2448
2862
  commandId: stopCommandId,
2449
2863
  runId: active.runId,
2450
2864
  turnId: active.turnId,
2451
2865
  ...applied?.turnId === active.turnId && applied.inferenceId !== void 0 ? { inferenceId: applied.inferenceId } : {}
2452
- }), yield* events.commandCompleted({ commandId: stopCommandId })]);
2866
+ });
2867
+ const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
2868
+ const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
2453
2869
  return {
2454
2870
  started,
2455
2871
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -2476,19 +2892,22 @@ const makeLiveSessionState = Effect.gen(function* () {
2476
2892
  return (yield* startedBoundaryGuard({
2477
2893
  start: events.commandStarted({ commandId: stopCommandId }),
2478
2894
  body: (started) => Effect.uninterruptible(Effect.gen(function* () {
2479
- yield* appendDurable(yield* events.stopTurnRequested({
2895
+ const requestedEvent = yield* events.stopTurnRequested({
2480
2896
  commandId: stopCommandId,
2481
2897
  runId: active.runId,
2482
2898
  turnId: active.turnId
2483
- }));
2899
+ });
2900
+ yield* appendDurable(requestedEvent);
2484
2901
  yield* Ref.set(executionState, { _tag: "Idle" });
2485
2902
  yield* appendUserInterruption(active, stopCommandId, "interrupted");
2486
2903
  yield* Scope.close(active.runScope, Exit.interrupt());
2487
- const committed = yield* appendDurableBatch([yield* events.stopTurnApplied({
2904
+ const appliedEvent = yield* events.stopTurnApplied({
2488
2905
  commandId: stopCommandId,
2489
2906
  runId: active.runId,
2490
2907
  turnId: active.turnId
2491
- }), yield* events.commandCompleted({ commandId: stopCommandId })]);
2908
+ });
2909
+ const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
2910
+ const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
2492
2911
  return {
2493
2912
  started,
2494
2913
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -2570,6 +2989,32 @@ const makeLiveSessionState = Effect.gen(function* () {
2570
2989
  default: return yield* Effect.die(assertNeverError(turn.outcome, "turn outcome"));
2571
2990
  }
2572
2991
  });
2992
+ const interruptWaitingRun = Effect.fnUntraced(function* (control, reason) {
2993
+ const plan = planWaitingRunInterruption(yield* currentReduced(), control.commandId);
2994
+ if (plan === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Waiting interruption requires a current reservation"));
2995
+ const isStop = control.command._tag === "StopTurn";
2996
+ const batch = [];
2997
+ if (isStop) batch.push(yield* events.commandStarted({ commandId: control.commandId }));
2998
+ batch.push(yield* events.runSchedulingInvalidated({
2999
+ requestId: plan.requestId,
3000
+ reason
3001
+ }));
3002
+ const [firstMessageId, ...restMessageIds] = plan.messageIds;
3003
+ if (firstMessageId !== void 0) batch.push(yield* events.pendingMessagesPaused({
3004
+ interruptionCommandId: control.commandId,
3005
+ runRequestId: plan.requestId,
3006
+ messageIds: [firstMessageId, ...restMessageIds],
3007
+ reason: "user-interrupted"
3008
+ }));
3009
+ if (plan.cancelCommandId !== void 0) batch.push(yield* events.commandCancelled({
3010
+ commandId: plan.cancelCommandId,
3011
+ reason
3012
+ }));
3013
+ if (isStop) batch.push(yield* events.commandCompleted({ commandId: control.commandId }));
3014
+ const committed = yield* appendDurableBatch(batch);
3015
+ yield* reconcileSchedulingWakeup();
3016
+ return committed;
3017
+ });
2573
3018
  const drainOneReadyCommand = Effect.fnUntraced(function* (input) {
2574
3019
  const execution = yield* inspectExecutionState();
2575
3020
  const current = yield* currentReduced();
@@ -2629,6 +3074,28 @@ const makeLiveSessionState = Effect.gen(function* () {
2629
3074
  });
2630
3075
  }
2631
3076
  }
3077
+ if (current.runSchedulingRequest !== void 0) {
3078
+ const control = waitingRunControl(current);
3079
+ if (control === void 0) return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
3080
+ switch (control.command._tag) {
3081
+ case "CancelPendingMessage": return yield* cancelPendingMessage(control);
3082
+ case "PromotePendingMessage": return yield* promotePendingMessage(control);
3083
+ case "StopTurn": {
3084
+ const committed = yield* interruptWaitingRun(control, "stopped");
3085
+ const started = committed[0];
3086
+ const completed = committed.at(-1);
3087
+ if (started === void 0 || completed === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Stopping a waiting request must commit its control lifecycle"));
3088
+ return {
3089
+ started,
3090
+ outcome: SessionCommandCompleted.make({ committed: completed })
3091
+ };
3092
+ }
3093
+ case "SubmitMessage":
3094
+ yield* interruptWaitingRun(control, "interrupted");
3095
+ return yield* startSubmitCommand(control, input);
3096
+ default: return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
3097
+ }
3098
+ }
2632
3099
  const decision = decideDispatch(current);
2633
3100
  switch (decision._tag) {
2634
3101
  case "DispatchBlockedByActiveCommand":
@@ -2658,7 +3125,7 @@ const makeLiveSessionState = Effect.gen(function* () {
2658
3125
  yield* failIfFatal;
2659
3126
  const processed = [];
2660
3127
  while (true) {
2661
- const result = yield* withFatalRecording(drainOneReadyCommand(input));
3128
+ const result = yield* controlGate.withPermits(1)(withFatalRecording(drainOneReadyCommand(input)));
2662
3129
  if (isSessionNoRunnableCommand(result)) {
2663
3130
  yield* annotateEdaSpan({
2664
3131
  "eda.command.processed_count": processed.length,
@@ -2680,12 +3147,20 @@ const makeLiveSessionState = Effect.gen(function* () {
2680
3147
  "eda.model.id": input.modelSelection.modelId
2681
3148
  });
2682
3149
  yield* failIfFatal;
2683
- const initial = yield* currentReduced();
3150
+ const { initial, recovery } = yield* admissionGate.withPermits(1)(Effect.gen(function* () {
3151
+ const initial = yield* currentReduced();
3152
+ return {
3153
+ initial,
3154
+ recovery: yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, {
3155
+ ...input,
3156
+ modelSelection: initial.modelSelection ?? input.modelSelection
3157
+ }))
3158
+ };
3159
+ }));
2684
3160
  input = {
2685
3161
  ...input,
2686
3162
  modelSelection: initial.modelSelection ?? input.modelSelection
2687
3163
  };
2688
- const recovery = yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, input));
2689
3164
  yield* requestStartupRecoveryCheckpointIfNeeded();
2690
3165
  if (recovery.continuation !== void 0) yield* closeRunTraceOnFailure(recovery.continuation, withFatalRecording(resumeRecoveredCommand(recovery.continuation, input)));
2691
3166
  });
@@ -2722,12 +3197,32 @@ const makeLiveSessionState = Effect.gen(function* () {
2722
3197
  }
2723
3198
  });
2724
3199
  const start = Effect.fn(function* (input) {
2725
- yield* runStartupRecovery(input);
2726
- yield* runLiveControlLoop(input).pipe(Effect.forkIn(runtimeScope));
3200
+ const reinvocations = yield* plannedReinvocations(yield* currentReduced());
3201
+ if (reinvocations.length === 0) {
3202
+ yield* runStartupRecovery(input);
3203
+ yield* forkSchedulingDelivery();
3204
+ yield* runLiveControlLoop(input).pipe(Effect.forkIn(runtimeScope));
3205
+ return;
3206
+ }
3207
+ yield* controlGate.take(1);
3208
+ yield* Ref.set(recoveringInBackground, true);
3209
+ yield* Effect.gen(function* () {
3210
+ yield* annotateRunInput(input);
3211
+ yield* initialize(input);
3212
+ yield* keepAlive.withActiveWork("session-recovery", Effect.gen(function* () {
3213
+ yield* withFatalRecording(resumeInterruptedToolCalls(reinvocations));
3214
+ yield* runStartupRecoveryPass(input);
3215
+ }));
3216
+ }).pipe(Effect.ensuring(Ref.set(recoveringInBackground, false).pipe(Effect.andThen(controlGate.release(1)))), Effect.andThen(forkSchedulingDelivery()), Effect.andThen(runLiveControlLoop(input)), Effect.catchCause((cause) => Effect.gen(function* () {
3217
+ const message = `EDA background startup recovery failed: ${Cause.pretty(cause)}`;
3218
+ yield* markFatalIfDurable(cause);
3219
+ yield* Ref.update(fatalInvariantViolation, (current) => current ?? message);
3220
+ yield* Effect.logError(message);
3221
+ })), Effect.withSpan("agent.session.recover.tools"), Effect.forkIn(runtimeScope));
2727
3222
  });
2728
3223
  yield* sinkRegistry.startSinkRunners({
2729
3224
  appendDurableBatch,
2730
- initialHead: (yield* Ref.get(state)).reduced.lastSeq,
3225
+ initialProjection: yield* Ref.get(state),
2731
3226
  publishEphemeral: publishEphemeralCore,
2732
3227
  scope: runtimeScope
2733
3228
  });
@@ -2744,10 +3239,10 @@ const hydrateReducedStateCheckpoint = (store, checkpoint) => Effect.gen(function
2744
3239
  });
2745
3240
  const hydrateFrameworkReducedState = (store) => Effect.gen(function* () {
2746
3241
  const checkpoint = yield* store.loadReducerCheckpoint(frameworkReducedStateReducerName);
2747
- const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 6 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
2748
- const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 6 ? SequenceNumber.make(0) : checkpoint.throughSeq;
3242
+ const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
3243
+ const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? SequenceNumber.make(0) : checkpoint.throughSeq;
2749
3244
  return {
2750
- state: foldReducedState(checkpointState, yield* store.eventsAfter(checkpointSeq).pipe(Stream.runCollect, Effect.map((events) => Array.from(events)))),
3245
+ state: yield* store.eventsAfter(checkpointSeq).pipe(Stream.chunks, Stream.runFold(() => checkpointState, foldReducedState)),
2751
3246
  checkpointSeq
2752
3247
  };
2753
3248
  });
@@ -2757,10 +3252,10 @@ const hydrateAppReducerStates = (store, reducers) => Effect.gen(function* () {
2757
3252
  const schemaVersion = reducerSchemaVersion(reducer);
2758
3253
  const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? reducer.initial : decodeReducerState(reducer, checkpoint.payload);
2759
3254
  const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? SequenceNumber.make(0) : checkpoint.throughSeq;
2760
- const tail = yield* store.eventsAfter(checkpointSeq).pipe(Stream.runCollect, Effect.map((events) => Array.from(events)));
3255
+ const state = yield* store.eventsAfter(checkpointSeq).pipe(Stream.chunks, Stream.runFold(() => checkpointState, (current, page) => page.reduce(reducer.reduce, current)));
2761
3256
  return [
2762
3257
  reducer.name,
2763
- tail.reduce(reducer.reduce, checkpointState),
3258
+ state,
2764
3259
  checkpointSeq
2765
3260
  ];
2766
3261
  }));
@@ -2804,7 +3299,7 @@ const commandWithId = (command, commandId) => {
2804
3299
  }
2805
3300
  };
2806
3301
  const rememberPreparedCommand = (event, preparedByIdempotencyKey, preparedByCommandId) => {
2807
- if (event.type !== commandAdmittedEventType) return;
3302
+ if (!Schema.is(CommandAdmittedEvent)(event)) return;
2808
3303
  const command = event.payload.command;
2809
3304
  if (command?.idempotencyKey !== void 0) preparedByIdempotencyKey.set(command.idempotencyKey, event);
2810
3305
  if (command?.commandId !== void 0) preparedByCommandId.set(command.commandId, event);
@@ -2827,6 +3322,6 @@ const requireTurnFailed = (committed) => isTurnFailed(committed) ? Effect.succee
2827
3322
  const isTurnFailed = (committed) => committed.event.type === turnFailedEventType;
2828
3323
  const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag === "SessionNoRunnableCommand";
2829
3324
  //#endregion
2830
- export { SessionCommandOutcome as a, SessionNoRunnableReason as c, TurnRunner as d, InferenceRunner as f, SessionCommandFailed as i, SessionRunInput as l, SessionCommandCancelled as n, SessionForkedCommand as o, ToolExecutor as p, SessionCommandCompleted as r, SessionNoRunnableCommand as s, SessionCommandAdmissionConflict as t, SessionState as u };
3325
+ export { SessionCommandOutcome as a, SessionNoRunnableReason as c, TurnRunner as d, InferenceRunner as f, SessionCommandFailed as i, SessionRunInput as l, LiveEventBus as m, SessionCommandCancelled as n, SessionForkedCommand as o, ToolExecutor as p, SessionCommandCompleted as r, SessionNoRunnableCommand as s, SessionCommandAdmissionConflict as t, SessionState as u };
2831
3326
 
2832
- //# sourceMappingURL=session-state-Bkc6u-Wr.js.map
3327
+ //# sourceMappingURL=session-state-BehvUVyq.js.map