effect-durable-agent 0.1.0-alpha.1 → 0.1.0-alpha.10

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 (183) hide show
  1. package/README.md +140 -136
  2. package/dist/{command-queues-CQ9cwRP7.d.ts → command-queues-CQi4Xc7u.d.ts} +109 -21
  3. package/dist/{commands-Ce1ec6kH.d.ts → commands-p8venTWs.d.ts} +10 -2
  4. package/dist/compaction-0k8zCJgB.js +473 -0
  5. package/dist/compaction-0k8zCJgB.js.map +1 -0
  6. package/dist/{compaction-YayFKo_1.d.ts → compaction-BhLSSXJ-.d.ts} +28 -7
  7. package/dist/context-projection-mCuvcO2W.d.ts +140 -0
  8. package/dist/{core-Hv3cFydL.d.ts → core-C-6xHzRx.d.ts} +6 -3
  9. package/dist/domain/command-queues.d.ts +1 -1
  10. package/dist/domain/command-queues.js +1 -1
  11. package/dist/domain/command-queues.js.map +1 -1
  12. package/dist/domain/context-projection.d.ts +2 -0
  13. package/dist/domain/context-projection.js +32 -0
  14. package/dist/domain/context-projection.js.map +1 -0
  15. package/dist/domain/message-transcript.d.ts +1 -1
  16. package/dist/domain/model-usage.d.ts +2 -0
  17. package/dist/domain/model-usage.js +59 -0
  18. package/dist/domain/model-usage.js.map +1 -0
  19. package/dist/domain/reduced-state-schema.d.ts +14 -18
  20. package/dist/domain/reduced-state-schema.js +7 -11
  21. package/dist/domain/reduced-state-schema.js.map +1 -1
  22. package/dist/domain/reduced-state.d.ts +3 -2
  23. package/dist/domain/reduced-state.js +3 -2
  24. package/dist/domain/run-scheduling.d.ts +2 -0
  25. package/dist/domain/run-scheduling.js +127 -0
  26. package/dist/domain/run-scheduling.js.map +1 -0
  27. package/dist/{durable-C3Rz7kg3.js → durable-BPHVFVvV.js} +74 -83
  28. package/dist/durable-BPHVFVvV.js.map +1 -0
  29. package/dist/{durable-DlScwmCy.d.ts → durable-DeLCAvbw.d.ts} +1256 -104
  30. package/dist/envelope-DkZyMIgp.d.ts +191 -0
  31. package/dist/envelope-DxQzo5rN.js +82 -0
  32. package/dist/envelope-DxQzo5rN.js.map +1 -0
  33. package/dist/{keep-alive-DYDsH6qN.d.ts → event-factory-KaeDSfeP.d.ts} +11 -31
  34. package/dist/{keep-alive-p8dIcSVy.js → event-factory-QuC_UvyP.js} +8 -10
  35. package/dist/event-factory-QuC_UvyP.js.map +1 -0
  36. package/dist/{events-Bb9-Cu-7.d.ts → events-LZFNoESe.d.ts} +2 -188
  37. package/dist/{id-generator-C2Q15uZM.d.ts → id-generator--x6itQZ2.d.ts} +3 -2
  38. package/dist/index.d.ts +7 -6
  39. package/dist/index.js +5 -4
  40. package/dist/keep-alive-Chl5SJxy.d.ts +29 -0
  41. package/dist/{message-transcript-BCHdHAe2.d.ts → message-transcript-6PEzaEGn.d.ts} +4 -4
  42. package/dist/model-resolver-BPPJAsuh.d.ts +18 -0
  43. package/dist/model-usage-CdBEkTwU.d.ts +55 -0
  44. package/dist/{prompt-projector-9_02lk5-.d.ts → prompt-projector-CNhqUsEr.d.ts} +15 -16
  45. package/dist/{reduced-state-C4nVVzz9.js → reduced-state-Bz68V2H8.js} +65 -32
  46. package/dist/reduced-state-Bz68V2H8.js.map +1 -0
  47. package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-CCSzc4h8.d.ts} +16 -6
  48. package/dist/run-scheduler-DcS_okUH.d.ts +43 -0
  49. package/dist/run-scheduling-wakeup-CeHrvXie.d.ts +25 -0
  50. package/dist/{runtime-C56FQxiL.d.ts → runtime-WL_gKqxn.d.ts} +16 -7
  51. package/dist/services/compaction.d.ts +1 -1
  52. package/dist/services/compaction.js +1 -425
  53. package/dist/services/id-generator.d.ts +1 -1
  54. package/dist/services/id-generator.js +2 -1
  55. package/dist/services/id-generator.js.map +1 -1
  56. package/dist/services/keep-alive.d.ts +2 -0
  57. package/dist/services/keep-alive.js +13 -0
  58. package/dist/services/keep-alive.js.map +1 -0
  59. package/dist/services/model-resolver.d.ts +2 -0
  60. package/dist/services/model-resolver.js +17 -0
  61. package/dist/services/model-resolver.js.map +1 -0
  62. package/dist/services/prompt-projector.d.ts +2 -2
  63. package/dist/services/prompt-projector.js +20 -10
  64. package/dist/services/prompt-projector.js.map +1 -1
  65. package/dist/services/reducer-registry.d.ts +2 -2
  66. package/dist/services/reducer-registry.js +7 -3
  67. package/dist/services/reducer-registry.js.map +1 -1
  68. package/dist/services/run-scheduler.d.ts +3 -0
  69. package/dist/services/run-scheduler.js +25 -0
  70. package/dist/services/run-scheduler.js.map +1 -0
  71. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  72. package/dist/services/run-scheduling-wakeup.js +13 -0
  73. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  74. package/dist/services/runtime-layer.d.ts +67 -0
  75. package/dist/services/runtime-layer.js +47 -0
  76. package/dist/services/runtime-layer.js.map +1 -0
  77. package/dist/services/runtime.d.ts +1 -1
  78. package/dist/services/runtime.js +21 -14
  79. package/dist/services/runtime.js.map +1 -1
  80. package/dist/services/session-event-observer.d.ts +2 -0
  81. package/dist/services/session-event-observer.js +13 -0
  82. package/dist/services/session-event-observer.js.map +1 -0
  83. package/dist/services/session-query.d.ts +2 -2
  84. package/dist/services/session-query.js +140 -1
  85. package/dist/services/session-query.js.map +1 -0
  86. package/dist/services/session-state.d.ts +2 -0
  87. package/dist/services/session-state.js +2 -0
  88. package/dist/services/session-store.d.ts +2 -2
  89. package/dist/services/session-store.js +182 -2
  90. package/dist/services/session-store.js.map +1 -0
  91. package/dist/services/sink-checkpoint-store.d.ts +2 -0
  92. package/dist/services/sink-checkpoint-store.js +49 -0
  93. package/dist/services/sink-checkpoint-store.js.map +1 -0
  94. package/dist/services/sink-registry.d.ts +1 -1
  95. package/dist/services/sink-registry.js +1 -1
  96. package/dist/services/span-names.d.ts +1 -1
  97. package/dist/services/span-names.js +3 -0
  98. package/dist/services/span-names.js.map +1 -1
  99. package/dist/services/tool-registry.d.ts +1 -1
  100. package/dist/services/tracing.d.ts +1 -1
  101. package/dist/services/tracing.js +23 -2
  102. package/dist/services/tracing.js.map +1 -1
  103. package/dist/session-event-observer-DaFMKKNc.d.ts +24 -0
  104. package/dist/session-query-DfW_4KC0.d.ts +47 -0
  105. package/dist/{session-query-DOc1KanA.js → session-state-BIZ2SYaP.js} +350 -183
  106. package/dist/session-state-BIZ2SYaP.js.map +1 -0
  107. package/dist/{session-query-DlRo5Ufc.d.ts → session-state-BeR2rZRR.d.ts} +144 -46
  108. package/dist/{session-store-D2Ore1QC.d.ts → session-store-J_Un45kW.d.ts} +7 -96
  109. package/dist/sink-checkpoint-store-C9hUxfH0.d.ts +40 -0
  110. package/dist/{sink-registry-CFC6xjsN.js → sink-registry-Bbqhtdnx.js} +27 -67
  111. package/dist/sink-registry-Bbqhtdnx.js.map +1 -0
  112. package/dist/{sink-registry-CIU0LD3m.d.ts → sink-registry-DuDkNXjZ.d.ts} +24 -49
  113. package/dist/testkit/layers.d.ts +24 -14
  114. package/dist/testkit/layers.js +18 -11
  115. package/dist/testkit/layers.js.map +1 -1
  116. package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-BDmJe_Wr.d.ts} +4 -4
  117. package/dist/types/commands.d.ts +2 -2
  118. package/dist/types/commands.js +7 -2
  119. package/dist/types/commands.js.map +1 -1
  120. package/dist/types/core.d.ts +2 -2
  121. package/dist/types/core.js +4 -2
  122. package/dist/types/core.js.map +1 -1
  123. package/dist/types/events/durable.d.ts +2 -2
  124. package/dist/types/events/durable.js +2 -2
  125. package/dist/types/events.d.ts +4 -3
  126. package/dist/types/events.js +3 -2
  127. package/dist/types/events.js.map +1 -1
  128. package/dist/websocket.d.ts +2776 -0
  129. package/dist/websocket.js +498 -0
  130. package/dist/websocket.js.map +1 -0
  131. package/package.json +68 -43
  132. package/testing/offline-trace/README.md +2 -1
  133. package/CHANGELOG.md +0 -10
  134. package/CONTRIBUTING.md +0 -26
  135. package/SECURITY.md +0 -8
  136. package/dist/durable-C3Rz7kg3.js.map +0 -1
  137. package/dist/durable-object-runtime-B7jwBY2R.js +0 -1494
  138. package/dist/durable-object-runtime-B7jwBY2R.js.map +0 -1
  139. package/dist/durable-object-runtime-pWv0ohlz.d.ts +0 -257
  140. package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
  141. package/dist/host/durable-object-runtime.d.ts +0 -2
  142. package/dist/host/durable-object-runtime.js +0 -2
  143. package/dist/host/durable-object-storage.d.ts +0 -2
  144. package/dist/host/durable-object-storage.js +0 -0
  145. package/dist/host/durable-object.d.ts +0 -83
  146. package/dist/host/durable-object.js +0 -191
  147. package/dist/host/durable-object.js.map +0 -1
  148. package/dist/host/websocket-wire.d.ts +0 -2
  149. package/dist/host/websocket-wire.js +0 -88
  150. package/dist/host/websocket-wire.js.map +0 -1
  151. package/dist/keep-alive-p8dIcSVy.js.map +0 -1
  152. package/dist/reduced-state-C4nVVzz9.js.map +0 -1
  153. package/dist/services/compaction.js.map +0 -1
  154. package/dist/session-query-DOc1KanA.js.map +0 -1
  155. package/dist/session-store-pYxQW9qh.js +0 -214
  156. package/dist/session-store-pYxQW9qh.js.map +0 -1
  157. package/dist/sink-registry-CFC6xjsN.js.map +0 -1
  158. package/dist/websocket-wire-DvOu_6BJ.d.ts +0 -16773
  159. package/docs/assets/architecture.svg +0 -106
  160. package/docs/assets/event-sequence.svg +0 -143
  161. package/docs/assets/gcp-trace.png +0 -0
  162. package/docs/message-steering.md +0 -831
  163. package/docs/releasing.md +0 -57
  164. package/docs/spec.md +0 -774
  165. package/docs/subagents.md +0 -725
  166. package/docs/testing.md +0 -64
  167. package/docs/ui-projection.md +0 -742
  168. package/docs/websocket-protocol.md +0 -613
  169. package/examples/001-no-tools/README.md +0 -65
  170. package/examples/001-no-tools/worker.ts +0 -79
  171. package/examples/002-slack-bridge/README.md +0 -134
  172. package/examples/002-slack-bridge/events.ts +0 -115
  173. package/examples/002-slack-bridge/reducer.ts +0 -216
  174. package/examples/002-slack-bridge/scenario.test.ts +0 -223
  175. package/examples/002-slack-bridge/sinks.ts +0 -109
  176. package/examples/002-slack-bridge/worker.ts +0 -140
  177. package/examples/003-sandbox-lifecycle/README.md +0 -78
  178. package/examples/003-sandbox-lifecycle/events.ts +0 -203
  179. package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
  180. package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
  181. package/examples/_shared/event-id.ts +0 -12
  182. package/examples/_shared/http.ts +0 -27
  183. package/examples/_shared/openai.ts +0 -33
@@ -1,15 +1,21 @@
1
+ import { RunSchedulingWakeup } from "./services/run-scheduling-wakeup.js";
1
2
  import { CommandId, InferenceId, MessageId, Position, RunId, SequenceNumber, SubSequenceNumber, TurnId } from "./types/core.js";
2
- import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand, UserMessageContent } from "./types/commands.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";
3
6
  import { makeEDARunTrace } from "./types/tracing.js";
4
- import { Dn as inferenceFailedEventType, En as inferenceCompletedEventType, Gn as toolCallRejectedEventType, Jn as turnFailedEventType, Un as toolCallCreatedEventType, _r as UsagePayload, cr as FailurePayload, dr as PositionedEvent, fr as ProviderPartId, hr as ToolName, lr as ModelSelectionPayload, mr as SystemPromptText, pn as commandAdmittedEventType, ur as NonNegativeInt } from "./durable-C3Rz7kg3.js";
5
- 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-C4nVVzz9.js";
6
- import { a as EDASessionStoreError, c as hasEDASessionStoreError, f as ContextProjection, i as EDASessionStore, p as emptyContextProjection, t as CommittedDurableEvent } from "./session-store-pYxQW9qh.js";
7
- import { durableMessageTranscript } from "./domain/message-transcript.js";
7
+ 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";
8
+ import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
9
+ import { Bn as inferenceFailedEventType, En as commandAdmittedEventType, fr as turnFailedEventType, lr as toolCallRejectedEventType, sr as toolCallCreatedEventType, zn as inferenceCompletedEventType } from "./durable-BPHVFVvV.js";
10
+ 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-Bz68V2H8.js";
11
+ import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
12
+ import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError } from "./services/session-store.js";
13
+ import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-0k8zCJgB.js";
8
14
  import { IdGenerator } from "./services/id-generator.js";
9
- import { n as EventFactory, r as SessionContext, t as EDAKeepAlive } from "./keep-alive-p8dIcSVy.js";
15
+ import { n as SessionContext, t as EventFactory } from "./event-factory-QuC_UvyP.js";
10
16
  import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
11
- import { CompactionRunner } from "./services/compaction.js";
12
- import { i as LiveEventBus, n as EDASinkRegistry } from "./sink-registry-CFC6xjsN.js";
17
+ import { EDAKeepAlive } from "./services/keep-alive.js";
18
+ import { n as EDASinkRegistry, r as LiveEventBus } from "./sink-registry-Bbqhtdnx.js";
13
19
  import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
14
20
  import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
15
21
  import { EDAToolRegistry } from "./services/tool-registry.js";
@@ -27,9 +33,7 @@ import * as Queue from "effect/Queue";
27
33
  import * as Ref from "effect/Ref";
28
34
  import * as Scope from "effect/Scope";
29
35
  import * as Semaphore from "effect/Semaphore";
30
- import * as LanguageModel from "effect/unstable/ai/LanguageModel";
31
36
  import * as Option from "effect/Option";
32
- import * as PubSub from "effect/PubSub";
33
37
  import * as Response from "effect/unstable/ai/Response";
34
38
  //#region src/domain/dispatch-policy.ts
35
39
  /** Durable/runtime evidence for active work blocking new queued commands. */
@@ -108,6 +112,15 @@ const decideDispatch = (state) => {
108
112
  command: toCandidate(next)
109
113
  };
110
114
  };
115
+ /** Promotion must retain a live or pending execution owner when the original command is terminal. */
116
+ const promotionNeedsResumeCommand = (state, messageId) => {
117
+ if (state.commandQueues.active?.runId !== void 0) return false;
118
+ const target = state.messages.get(messageId);
119
+ if (target?._tag !== "User" && target?._tag !== "Steering") return false;
120
+ const waiting = state.runSchedulingRequest?.work;
121
+ if (waiting?._tag === "Recovery" && waiting.inputMessageIds.includes(messageId)) return false;
122
+ return !state.commandQueues.pendingCommands.some((pending) => pending.commandId === target.commandId || pending.command._tag === "ResumePendingMessages" && pending.command.messageIds.includes(messageId));
123
+ };
111
124
  const nextIdleCommand = (state) => {
112
125
  const pendingById = new Map(state.commandQueues.pendingCommands.map((command) => [command.commandId, command]));
113
126
  for (const message of state.commandQueues.pendingSteers) {
@@ -220,7 +233,7 @@ const planSessionRecovery = (state) => {
220
233
  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);
221
234
  const continuationInputMessageIds = Array.from(new Set([...sourceMessageIds, ...eligibleSteerIds]));
222
235
  const continuationInputIds = new Set(continuationInputMessageIds);
223
- 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);
236
+ 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);
224
237
  return {
225
238
  activeCommands: recoverable.activeCommands,
226
239
  activeRuns: recoverable.activeRuns,
@@ -757,7 +770,7 @@ Schema.TaggedErrorClass()("UnsupportedInferencePart", {
757
770
  const makeLiveInferenceRunner = Effect.gen(function* () {
758
771
  const ids = yield* IdGenerator;
759
772
  const events = yield* EventFactory;
760
- const languageModel = yield* LanguageModel.LanguageModel;
773
+ const models = yield* ModelResolver;
761
774
  const toolRegistry = yield* EDAToolRegistry;
762
775
  const recordPart = (eventSink, state, part, setLatestState) => Effect.gen(function* () {
763
776
  if (state.inference.phase === "sealed") {
@@ -972,6 +985,7 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
972
985
  return yield* requireTerminal(yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []));
973
986
  });
974
987
  return { runInference: Effect.fn("agent.inference")(function* (input) {
988
+ const languageModel = yield* models.resolve(input.modelSelection);
975
989
  const inferenceIdentity = {
976
990
  runId: input.runId,
977
991
  turnId: input.turnId,
@@ -1146,31 +1160,6 @@ const makeFinishMetadata = (part) => ({
1146
1160
  response: part.response,
1147
1161
  metadata: part.metadata
1148
1162
  });
1149
- const makeUsagePayload = (usage) => {
1150
- const uncachedInputTokens = nonNegativeInt(usage.inputTokens.uncached);
1151
- const cachedInputTokens = nonNegativeInt(usage.inputTokens.cacheRead);
1152
- const cacheWriteInputTokens = nonNegativeInt(usage.inputTokens.cacheWrite);
1153
- const inputTokens = nonNegativeInt(usage.inputTokens.total) ?? sumDefined([
1154
- uncachedInputTokens,
1155
- cachedInputTokens,
1156
- cacheWriteInputTokens
1157
- ]);
1158
- const textTokens = nonNegativeInt(usage.outputTokens.text);
1159
- const reasoningTokens = nonNegativeInt(usage.outputTokens.reasoning);
1160
- const outputTokens = nonNegativeInt(usage.outputTokens.total) ?? sumDefined([textTokens, reasoningTokens]);
1161
- return UsagePayload.make({
1162
- ...inputTokens === void 0 ? {} : { inputTokens },
1163
- ...cachedInputTokens === void 0 ? {} : { cachedInputTokens },
1164
- ...outputTokens === void 0 ? {} : { outputTokens },
1165
- ...textTokens === void 0 ? {} : { textTokens },
1166
- ...reasoningTokens === void 0 ? {} : { reasoningTokens }
1167
- });
1168
- };
1169
- const sumDefined = (values) => {
1170
- const present = values.filter((value) => value !== void 0);
1171
- return present.length === 0 ? void 0 : present.reduce((sum, value) => sum + value, 0);
1172
- };
1173
- const nonNegativeInt = (value) => value === void 0 || !Number.isFinite(value) ? void 0 : Math.max(0, Math.trunc(value));
1174
1163
  Schema.Struct({
1175
1164
  runId: RunId,
1176
1165
  turnId: TurnId
@@ -1431,7 +1420,10 @@ const requireInferenceFailed = (committed) => {
1431
1420
  const failed = committed.find(isInferenceFailed);
1432
1421
  return failed === void 0 ? Effect.die(/* @__PURE__ */ new Error("InferenceRunFailed did not include InferenceFailed")) : Effect.succeed(failed);
1433
1422
  };
1434
- Schema.Struct({
1423
+ //#endregion
1424
+ //#region src/services/session-state.ts
1425
+ /** Input for one session control pass or long-lived control process. */
1426
+ const SessionRunInput = Schema.Struct({
1435
1427
  modelSelection: ModelSelectionPayload,
1436
1428
  maxToolCallsPerRun: Schema.optionalKey(NonNegativeInt),
1437
1429
  systemPrompt: Schema.optionalKey(SystemPromptText)
@@ -1442,13 +1434,18 @@ const SessionCommandCompleted = Schema.TaggedStruct("SessionCommandCompleted", {
1442
1434
  const SessionCommandFailed = Schema.TaggedStruct("SessionCommandFailed", { committed: CommittedDurableEvent });
1443
1435
  /** Command outcome when command work was cancelled by stop, interrupt, or recovery. */
1444
1436
  const SessionCommandCancelled = Schema.TaggedStruct("SessionCommandCancelled", { committed: CommittedDurableEvent });
1445
- Schema.Union([
1437
+ /** Terminal command-processing variants returned from one control action. */
1438
+ const SessionCommandOutcome = Schema.Union([
1446
1439
  SessionCommandCompleted,
1447
1440
  SessionCommandFailed,
1448
1441
  SessionCommandCancelled
1449
1442
  ]);
1450
1443
  /** Why a control drain stopped without starting more command work. */
1451
- const SessionNoRunnableReason = Schema.Literals(["active-command", "no-pending-command"]);
1444
+ const SessionNoRunnableReason = Schema.Literals([
1445
+ "active-command",
1446
+ "no-pending-command",
1447
+ "awaiting-run-authorization"
1448
+ ]);
1452
1449
  /** Session control result when no admitted command is runnable. */
1453
1450
  const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand", {
1454
1451
  reason: SessionNoRunnableReason,
@@ -1512,10 +1509,13 @@ const makeLiveSessionState = Effect.gen(function* () {
1512
1509
  const compactionRunner = yield* CompactionRunner;
1513
1510
  const promptProjector = yield* EDAPromptProjector;
1514
1511
  const sessionContext = yield* SessionContext;
1512
+ const runScheduler = yield* RunScheduler;
1513
+ const schedulingWakeup = yield* RunSchedulingWakeup;
1515
1514
  const reducerRegistry = yield* EDAReducerRegistry;
1516
1515
  const sinkRegistry = yield* EDASinkRegistry;
1517
1516
  const hydrated = yield* hydrateFrameworkReducedState(store);
1518
1517
  const hydratedReducerStates = yield* hydrateAppReducerStates(store, reducerRegistry.reducers);
1518
+ yield* schedulingWakeup.setPending(hydrated.state.runSchedulingRequest !== void 0 && hydrated.state.runSchedulingRequest.deliveredSeq === void 0);
1519
1519
  const startupRecoveryCheckpointSeq = hydratedReducerStates.checkpointSeq === void 0 ? hydrated.checkpointSeq : SequenceNumber.make(Math.min(hydrated.checkpointSeq, hydratedReducerStates.checkpointSeq));
1520
1520
  const state = yield* Ref.make({
1521
1521
  reduced: hydrated.state,
@@ -1526,6 +1526,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1526
1526
  }
1527
1527
  });
1528
1528
  const gate = yield* Semaphore.make(1);
1529
+ const controlGate = yield* Semaphore.make(1);
1530
+ const deliveryGate = yield* Semaphore.make(1);
1529
1531
  const ingressSignals = yield* Queue.sliding(1);
1530
1532
  const reducerCheckpointSnapshots = yield* Queue.sliding(1);
1531
1533
  const executionState = yield* Ref.make({ _tag: "Idle" });
@@ -1553,7 +1555,7 @@ const makeLiveSessionState = Effect.gen(function* () {
1553
1555
  }));
1554
1556
  const buildReducerCheckpointSnapshot = (snapshot) => [{
1555
1557
  name: frameworkReducedStateReducerName,
1556
- schemaVersion: 4,
1558
+ schemaVersion: 7,
1557
1559
  throughSeq: snapshot.reduced.lastSeq,
1558
1560
  payload: encodeReducedStateCheckpoint(snapshot.reduced),
1559
1561
  updatedAtMs: snapshot.updatedAtMs
@@ -1754,6 +1756,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1754
1756
  });
1755
1757
  const initialize = (input) => commitInitialSystemPrompt(input.systemPrompt);
1756
1758
  const sessionApi = {
1759
+ grantRun: (command, input) => grantRun(command, input),
1760
+ retryRunSchedulingDelivery: () => retryRunSchedulingDelivery(),
1757
1761
  initialize,
1758
1762
  submitBatch,
1759
1763
  admitCommand,
@@ -1937,23 +1941,28 @@ const makeLiveSessionState = Effect.gen(function* () {
1937
1941
  });
1938
1942
  const closeRunTraceOnFailure = (trace, effect) => effect.pipe(Effect.onExit((exit) => Exit.isFailure(exit) ? Scope.close(trace.runScope, exit) : Effect.void));
1939
1943
  const startTurn = Effect.fn(function* (input) {
1940
- const inputMessageIds = input.promptInput.selectedUserMessages.map((message) => message.messageId);
1941
- const prompt = yield* buildEDAPrompt(promptProjector, input.promptInput);
1942
1944
  const turnId = yield* ids.makeTurnId();
1943
- const current = yield* currentReduced();
1945
+ const started = yield* appendDurable(yield* events.turnStarted({
1946
+ runId: input.runId,
1947
+ turnId,
1948
+ ...input.inputMessageIds.length === 0 ? {} : { inputMessageIds: input.inputMessageIds }
1949
+ }));
1950
+ const promptState = yield* currentData();
1951
+ const prompt = yield* buildEDAPrompt(promptProjector, {
1952
+ sessionId: sessionContext.sessionId,
1953
+ state: promptState.reduced,
1954
+ reducerStates: promptState.reducerStates,
1955
+ context: yield* contextProjectionFor(promptState.reduced)
1956
+ });
1957
+ const current = promptState.reduced;
1944
1958
  const remainingToolCalls = remainingToolCallsForRun(current, input.runId, input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun);
1945
1959
  const remainingToolRejectionCorrections = remainingToolRejectionCorrectionsForRun(current, input.runId, NonNegativeInt.make(maxToolRejectionCorrections));
1946
1960
  yield* annotateEdaSpan({
1947
1961
  "eda.command.id": input.commandId,
1948
1962
  "eda.run.id": input.runId,
1949
1963
  "eda.turn.id": turnId,
1950
- "eda.message.input_count": inputMessageIds.length
1964
+ "eda.message.input_count": input.inputMessageIds.length
1951
1965
  });
1952
- const started = yield* appendDurable(yield* events.turnStarted({
1953
- runId: input.runId,
1954
- turnId,
1955
- ...inputMessageIds.length === 0 ? {} : { inputMessageIds }
1956
- }));
1957
1966
  const turnScope = yield* Scope.fork(input.runScope, "sequential");
1958
1967
  const fiber = yield* keepAlive.withActiveWork(`turn:${turnId}`, turnRunner.runTurn({
1959
1968
  runId: input.runId,
@@ -1981,10 +1990,68 @@ const makeLiveSessionState = Effect.gen(function* () {
1981
1990
  });
1982
1991
  return SessionForkedCommand.make({ commandId: input.commandId });
1983
1992
  });
1993
+ const reconcileSchedulingWakeup = Effect.fnUntraced(function* () {
1994
+ const request = (yield* currentReduced()).runSchedulingRequest;
1995
+ yield* schedulingWakeup.setPending(request !== void 0 && request.deliveredSeq === void 0);
1996
+ });
1997
+ const retryRunSchedulingDelivery = Effect.fnUntraced(function* () {
1998
+ yield* deliveryGate.withPermitsIfAvailable(1)(Effect.gen(function* () {
1999
+ const request = yield* controlGate.withPermits(1)(Effect.gen(function* () {
2000
+ const current = (yield* currentReduced()).runSchedulingRequest;
2001
+ yield* reconcileSchedulingWakeup();
2002
+ return current?.deliveredSeq === void 0 ? current : void 0;
2003
+ }));
2004
+ if (request === void 0) return;
2005
+ const delivered = yield* Effect.exit(keepAlive.withActiveWork("run-scheduling-delivery", runScheduler.deliver({
2006
+ sessionId: sessionContext.sessionId,
2007
+ request: {
2008
+ requestId: request.requestId,
2009
+ work: request.work
2010
+ }
2011
+ }).pipe(Effect.timeout("10 seconds"))));
2012
+ if (Exit.isFailure(delivered)) {
2013
+ if (Cause.hasInterruptsOnly(delivered.cause)) return yield* Effect.interrupt;
2014
+ yield* controlGate.withPermits(1)(reconcileSchedulingWakeup());
2015
+ yield* Effect.logWarning("Run authorization delivery will retry on the durable host wakeup", {
2016
+ requestId: request.requestId,
2017
+ cause: Cause.pretty(delivered.cause)
2018
+ });
2019
+ return;
2020
+ }
2021
+ yield* controlGate.withPermits(1)(Effect.gen(function* () {
2022
+ const current = (yield* currentReduced()).runSchedulingRequest;
2023
+ if (current?.requestId === request.requestId && current.deliveredSeq === void 0) yield* appendDurable(yield* events.runSchedulingDelivered({ requestId: request.requestId }));
2024
+ yield* reconcileSchedulingWakeup();
2025
+ }));
2026
+ }));
2027
+ });
2028
+ const forkSchedulingDelivery = () => retryRunSchedulingDelivery().pipe(Effect.catchCause((cause) => Effect.gen(function* () {
2029
+ yield* markFatalIfDurable(cause);
2030
+ yield* Effect.logError("Run authorization delivery worker failed", { cause: Cause.pretty(cause) });
2031
+ })), Effect.forkIn(runtimeScope), Effect.asVoid);
2032
+ const prepareRunSchedulingRequest = Effect.fnUntraced(function* (work) {
2033
+ yield* schedulingWakeup.setPending(true);
2034
+ return yield* events.runSchedulingRequested({
2035
+ requestId: yield* ids.makeRunRequestId(),
2036
+ work
2037
+ });
2038
+ });
2039
+ const deferRun = Effect.fnUntraced(function* (work) {
2040
+ yield* appendDurable(yield* prepareRunSchedulingRequest(work));
2041
+ yield* forkSchedulingDelivery();
2042
+ return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
2043
+ });
1984
2044
  const startSubmitCommand = Effect.fn(function* (command, input) {
1985
2045
  if (command.command._tag !== "SubmitMessage") return yield* Effect.die(/* @__PURE__ */ new Error("startSubmitCommand requires SubmitMessage"));
1986
2046
  const submit = command.command;
1987
2047
  const commandId = command.commandId;
2048
+ if ((yield* runScheduler.resolve({
2049
+ sessionId: sessionContext.sessionId,
2050
+ commandId
2051
+ }))._tag === "Deferred") return yield* deferRun({
2052
+ _tag: "Command",
2053
+ commandId
2054
+ });
1988
2055
  yield* annotateEdaSpan({
1989
2056
  "eda.command.id": commandId,
1990
2057
  "eda.command.disposition": submit.disposition,
@@ -2014,30 +2081,17 @@ const makeLiveSessionState = Effect.gen(function* () {
2014
2081
  modelSelection: input.modelSelection,
2015
2082
  trace: activeRunTrace.runTrace
2016
2083
  });
2017
- const startedEvents = yield* appendDurableBatch([
2018
- commandStarted,
2019
- ...userMessage === void 0 ? [] : [userMessage],
2020
- runStarted
2021
- ]);
2022
- const selectedUserContent = submittedMessage === void 0 ? submit.content : Schema.decodeUnknownSync(UserMessageContent)(submittedMessage.content);
2023
- const promptState = yield* currentData();
2024
2084
  return yield* startTurn({
2025
2085
  commandId,
2026
- commandStarted: startedEvents[0],
2086
+ commandStarted: (yield* appendDurableBatch([
2087
+ commandStarted,
2088
+ ...userMessage === void 0 ? [] : [userMessage],
2089
+ runStarted
2090
+ ]))[0],
2091
+ inputMessageIds: [messageId],
2027
2092
  runId,
2028
2093
  modelSelection: input.modelSelection,
2029
2094
  ...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
2030
- promptInput: {
2031
- sessionId: sessionContext.sessionId,
2032
- state: promptState.reduced,
2033
- reducerStates: promptState.reducerStates,
2034
- context: yield* contextProjectionFor(promptState.reduced),
2035
- selectedUserMessages: [{
2036
- commandId,
2037
- content: selectedUserContent,
2038
- messageId
2039
- }]
2040
- },
2041
2095
  runScope: activeRunTrace.runScope,
2042
2096
  runSpan: activeRunTrace.runSpan
2043
2097
  });
@@ -2051,6 +2105,13 @@ const makeLiveSessionState = Effect.gen(function* () {
2051
2105
  return (message?._tag === "User" || message?._tag === "Steering") && message.consumedSeq === void 0 && message.cancelledSeq === void 0 ? [message] : [];
2052
2106
  });
2053
2107
  if (pending.length === 0) return yield* processInactiveStopCommand(command);
2108
+ if ((yield* runScheduler.resolve({
2109
+ sessionId: sessionContext.sessionId,
2110
+ commandId: command.commandId
2111
+ }))._tag === "Deferred") return yield* deferRun({
2112
+ _tag: "Command",
2113
+ commandId: command.commandId
2114
+ });
2054
2115
  const commandStarted = yield* events.commandStarted({ commandId: command.commandId });
2055
2116
  const runId = yield* ids.makeRunId();
2056
2117
  const activeRunTrace = yield* startRunTrace({
@@ -2069,25 +2130,117 @@ const makeLiveSessionState = Effect.gen(function* () {
2069
2130
  return yield* startTurn({
2070
2131
  commandId: command.commandId,
2071
2132
  commandStarted: started[0],
2133
+ inputMessageIds: pending.map((message) => message.messageId),
2072
2134
  runId,
2073
2135
  modelSelection: input.modelSelection,
2074
2136
  ...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
2075
- promptInput: {
2076
- sessionId: sessionContext.sessionId,
2077
- state: current.reduced,
2078
- reducerStates: current.reducerStates,
2079
- context: yield* contextProjectionFor(current.reduced),
2080
- selectedUserMessages: pending.map((message) => ({
2081
- commandId: message.commandId,
2082
- content: message.content,
2083
- messageId: message.messageId
2084
- }))
2085
- },
2086
2137
  runScope: activeRunTrace.runScope,
2087
2138
  runSpan: activeRunTrace.runSpan
2088
2139
  });
2089
2140
  }));
2090
2141
  });
2142
+ const grantRun = Effect.fn("agent.run.grant")(function* (grant, input) {
2143
+ yield* annotateEdaSpan({
2144
+ "eda.session.id": sessionContext.sessionId,
2145
+ "eda.run_request.id": grant.requestId
2146
+ });
2147
+ return yield* controlGate.withPermits(1)(keepAlive.withActiveWork("run-authorization-grant", Effect.gen(function* () {
2148
+ yield* failIfFatal;
2149
+ const initial = yield* currentReduced();
2150
+ if (!canGrantRun(initial, grant.requestId)) return { _tag: "Stale" };
2151
+ const request = initial.runSchedulingRequest;
2152
+ if (request === void 0) return { _tag: "Stale" };
2153
+ const command = initial.commands.get(request.work.commandId);
2154
+ if (command?.command === void 0) return { _tag: "Stale" };
2155
+ const admitted = command.command;
2156
+ const predecessor = request.work._tag === "Recovery" ? initial.runs.get(request.work.interruptedRunId) : void 0;
2157
+ const modelSelection = predecessor?.modelSelection ?? initial.modelSelection ?? input.modelSelection;
2158
+ const runId = yield* ids.makeRunId();
2159
+ const trace = yield* startRunTrace({
2160
+ commandId: command.commandId,
2161
+ admissionTrace: command.admissionTrace,
2162
+ modelSelection,
2163
+ runId
2164
+ });
2165
+ return yield* closeRunTraceOnFailure(trace, Effect.gen(function* () {
2166
+ const started = yield* withAppendGate(Effect.gen(function* () {
2167
+ const current = yield* currentReduced();
2168
+ if (!canGrantRun(current, grant.requestId)) return void 0;
2169
+ const inputMessageIds = [...runSchedulingInputMessageIds(current, request.work)];
2170
+ const batch = [];
2171
+ let commandStarted;
2172
+ if (request.work._tag === "Recovery") {
2173
+ if (command.startedSeq === void 0 || predecessor === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization requires its started command and predecessor"));
2174
+ [commandStarted] = yield* store.loadCommittedEventsBySeq([command.startedSeq]);
2175
+ if (commandStarted?.event.type !== "CommandStarted") return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization is missing CommandStarted"));
2176
+ } else {
2177
+ batch.push(yield* events.commandStarted({ commandId: command.commandId }));
2178
+ if (admitted._tag === "SubmitMessage" && inputMessageIds.length === 0) {
2179
+ const messageId = yield* ids.makeMessageId();
2180
+ batch.push(yield* events.userMessageCommitted({
2181
+ commandId: command.commandId,
2182
+ messageId,
2183
+ content: admitted.content
2184
+ }));
2185
+ inputMessageIds.push(messageId);
2186
+ }
2187
+ }
2188
+ batch.push(yield* events.runSchedulingGranted({
2189
+ requestId: request.requestId,
2190
+ runId
2191
+ }));
2192
+ const commandIds = predecessor?.commandIds ?? [command.commandId, ...admitted._tag === "ResumePendingMessages" ? inputMessageIds.flatMap((messageId) => {
2193
+ const message = current.messages.get(messageId);
2194
+ return message?._tag === "User" || message?._tag === "Steering" ? [message.commandId] : [];
2195
+ }) : []];
2196
+ batch.push(yield* events.runStarted({
2197
+ runId,
2198
+ commandIds,
2199
+ modelSelection,
2200
+ trace: trace.runTrace
2201
+ }));
2202
+ if (request.work._tag === "Recovery") batch.push(yield* events.recoveryCompleted({
2203
+ trigger: "runtime-restart",
2204
+ continuation: {
2205
+ commandId: command.commandId,
2206
+ interruptedRunId: request.work.interruptedRunId,
2207
+ replacementRunId: runId
2208
+ }
2209
+ }));
2210
+ const committed = yield* commitDurableEntriesWithinGate(batch.map((event) => ({ event })));
2211
+ commandStarted ??= committed[0];
2212
+ if (commandStarted === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Granted run must have CommandStarted"));
2213
+ return {
2214
+ commandStarted,
2215
+ inputMessageIds
2216
+ };
2217
+ }));
2218
+ if (started === void 0) {
2219
+ yield* Scope.close(trace.runScope, Exit.void);
2220
+ return { _tag: "Stale" };
2221
+ }
2222
+ yield* reconcileSchedulingWakeup();
2223
+ yield* startTurn({
2224
+ commandId: command.commandId,
2225
+ commandStarted: started.commandStarted,
2226
+ inputMessageIds: started.inputMessageIds,
2227
+ runId,
2228
+ modelSelection,
2229
+ ...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
2230
+ runScope: trace.runScope,
2231
+ runSpan: trace.runSpan
2232
+ });
2233
+ yield* wakeAfterCommandAdmission();
2234
+ return {
2235
+ _tag: "Granted",
2236
+ runId
2237
+ };
2238
+ }));
2239
+ })).pipe(Effect.catchCause((cause) => Effect.gen(function* () {
2240
+ yield* markFatalIfDurable(cause);
2241
+ return yield* Effect.failCause(cause);
2242
+ }))));
2243
+ });
2091
2244
  const processInactiveStopCommand = Effect.fn(function* (command) {
2092
2245
  const commandId = command.commandId;
2093
2246
  return (yield* startedBoundaryGuard({
@@ -2171,6 +2324,10 @@ const makeLiveSessionState = Effect.gen(function* () {
2171
2324
  });
2172
2325
  const recoverSession = Effect.fnUntraced(function* (reduced, reason, input) {
2173
2326
  const plan = planSessionRecovery(reduced);
2327
+ input = {
2328
+ ...input,
2329
+ modelSelection: plan.continuation?.run.modelSelection ?? input.modelSelection
2330
+ };
2174
2331
  yield* annotateEdaSpan({
2175
2332
  "eda.recovery.reason": reason,
2176
2333
  "eda.recovery.open_tool_calls": plan.openToolCalls.length,
@@ -2252,7 +2409,17 @@ const makeLiveSessionState = Effect.gen(function* () {
2252
2409
  commandId: yield* ids.makeCommandId(),
2253
2410
  messageIds: plan.messageIdsToResume
2254
2411
  }) }));
2255
- const continuationRunId = plan.continuation === void 0 ? void 0 : yield* ids.makeRunId();
2412
+ const resolution = plan.continuation === void 0 ? void 0 : yield* runScheduler.resolve({
2413
+ sessionId: sessionContext.sessionId,
2414
+ commandId: plan.continuation.command.commandId
2415
+ });
2416
+ if (plan.continuation !== void 0 && resolution?._tag === "Deferred") recoveryEvents.push(yield* prepareRunSchedulingRequest({
2417
+ _tag: "Recovery",
2418
+ commandId: plan.continuation.command.commandId,
2419
+ interruptedRunId: plan.continuation.run.runId,
2420
+ inputMessageIds: plan.continuation.inputMessageIds
2421
+ }));
2422
+ const continuationRunId = plan.continuation === void 0 || resolution?._tag === "Deferred" ? void 0 : yield* ids.makeRunId();
2256
2423
  const continuationRunTrace = plan.continuation === void 0 || continuationRunId === void 0 ? void 0 : yield* startRunTrace({
2257
2424
  admissionTrace: plan.continuation.command.admissionTrace,
2258
2425
  commandId: plan.continuation.command.commandId,
@@ -2275,6 +2442,7 @@ const makeLiveSessionState = Effect.gen(function* () {
2275
2442
  } }
2276
2443
  }));
2277
2444
  const committed = recoveryEvents.length === 0 ? [] : yield* appendDurableBatch(recoveryEvents);
2445
+ if (resolution?._tag === "Deferred") yield* forkSchedulingDelivery();
2278
2446
  const nextPlan = planSessionRecovery(yield* currentReduced());
2279
2447
  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"));
2280
2448
  return {
@@ -2282,6 +2450,7 @@ const makeLiveSessionState = Effect.gen(function* () {
2282
2450
  continuation: plan.continuation === void 0 || continuationRunId === void 0 || continuationRunTrace === void 0 ? void 0 : {
2283
2451
  command: plan.continuation.command,
2284
2452
  runId: continuationRunId,
2453
+ modelSelection: input.modelSelection,
2285
2454
  inputMessageIds: plan.continuation.inputMessageIds,
2286
2455
  runScope: continuationRunTrace.runScope,
2287
2456
  runSpan: continuationRunTrace.runSpan
@@ -2302,20 +2471,10 @@ const makeLiveSessionState = Effect.gen(function* () {
2302
2471
  yield* startTurn({
2303
2472
  commandId: continuation.command.commandId,
2304
2473
  commandStarted,
2474
+ inputMessageIds: pendingInputs.map((message) => message.messageId),
2305
2475
  runId: continuation.runId,
2306
- modelSelection: input.modelSelection,
2476
+ modelSelection: continuation.modelSelection,
2307
2477
  ...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
2308
- promptInput: {
2309
- sessionId: sessionContext.sessionId,
2310
- state: promptState.reduced,
2311
- reducerStates: promptState.reducerStates,
2312
- context: yield* contextProjectionFor(promptState.reduced),
2313
- selectedUserMessages: pendingInputs.map((message) => ({
2314
- commandId: message.commandId,
2315
- content: message.content,
2316
- messageId: message.messageId
2317
- }))
2318
- },
2319
2478
  runScope: continuation.runScope,
2320
2479
  runSpan: continuation.runSpan
2321
2480
  });
@@ -2394,12 +2553,30 @@ const makeLiveSessionState = Effect.gen(function* () {
2394
2553
  commandId: target.commandId,
2395
2554
  reason: "pending message cancelled"
2396
2555
  })] : [];
2556
+ const schedulingPlan = planRunSchedulingCancellation(current, target.messageId);
2557
+ const schedulingEvents = [];
2558
+ if (schedulingPlan !== void 0) {
2559
+ schedulingEvents.push(yield* events.runSchedulingInvalidated({
2560
+ requestId: schedulingPlan.requestId,
2561
+ reason: "message-cancelled"
2562
+ }));
2563
+ if (schedulingPlan.cancelCommandId !== void 0) schedulingEvents.push(yield* events.commandCancelled({
2564
+ commandId: schedulingPlan.cancelCommandId,
2565
+ reason: "pending recovery inputs cancelled"
2566
+ }));
2567
+ if (schedulingPlan.replacementWork !== void 0) schedulingEvents.push(yield* prepareRunSchedulingRequest(schedulingPlan.replacementWork));
2568
+ }
2397
2569
  const completed = yield* events.commandCompleted({ commandId: controlCommandId });
2398
2570
  const committed = yield* appendDurableBatch([
2399
2571
  cancelled,
2400
2572
  ...originCancelled,
2573
+ ...schedulingEvents,
2401
2574
  completed
2402
2575
  ]);
2576
+ if (schedulingEvents.length > 0) {
2577
+ yield* reconcileSchedulingWakeup();
2578
+ yield* forkSchedulingDelivery();
2579
+ }
2403
2580
  return {
2404
2581
  started,
2405
2582
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -2422,17 +2599,28 @@ const makeLiveSessionState = Effect.gen(function* () {
2422
2599
  return (yield* startedBoundaryGuard({
2423
2600
  start: events.commandStarted({ commandId: controlCommandId }),
2424
2601
  body: (started) => Effect.gen(function* () {
2425
- const target = (yield* currentReduced()).messages.get(promotion.messageId);
2602
+ const current = yield* currentReduced();
2603
+ const target = current.messages.get(promotion.messageId);
2426
2604
  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 {
2427
2605
  started,
2428
2606
  outcome: yield* failControlCommand(controlCommandId, "message_not_queue", "Message is no longer a pending queue message")
2429
2607
  };
2430
- const committed = yield* appendDurableBatch([yield* events.userMessagePromoted({
2608
+ const promoted = yield* events.userMessagePromoted({
2431
2609
  commandId: controlCommandId,
2432
2610
  messageId: target.messageId,
2433
2611
  from: "queue",
2434
2612
  to: "steer"
2435
- }), yield* events.commandCompleted({ commandId: controlCommandId })]);
2613
+ });
2614
+ const resumed = promotionNeedsResumeCommand(current, target.messageId) ? [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
2615
+ commandId: yield* ids.makeCommandId(),
2616
+ messageIds: [target.messageId]
2617
+ }) })] : [];
2618
+ const completed = yield* events.commandCompleted({ commandId: controlCommandId });
2619
+ const committed = yield* appendDurableBatch([
2620
+ promoted,
2621
+ ...resumed,
2622
+ completed
2623
+ ]);
2436
2624
  return {
2437
2625
  started,
2438
2626
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -2556,36 +2744,20 @@ const makeLiveSessionState = Effect.gen(function* () {
2556
2744
  case "ContinueWithSteering": return yield* startTurn({
2557
2745
  commandId: active.commandId,
2558
2746
  commandStarted: active.commandStarted,
2747
+ inputMessageIds: continuation.steerings.map((steering) => steering.messageId),
2559
2748
  runId: active.runId,
2560
2749
  modelSelection: active.modelSelection,
2561
2750
  ...active.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: active.maxToolCallsPerRun },
2562
- promptInput: {
2563
- sessionId: sessionContext.sessionId,
2564
- state: current,
2565
- reducerStates: (yield* currentData()).reducerStates,
2566
- context: yield* contextProjectionFor(current),
2567
- selectedUserMessages: continuation.steerings.map((steering) => ({
2568
- commandId: steering.commandId,
2569
- content: steering.content,
2570
- messageId: steering.messageId
2571
- }))
2572
- },
2573
2751
  runScope: active.runScope,
2574
2752
  runSpan: active.runSpan
2575
2753
  });
2576
2754
  case "ContinueWithToolFeedback": return yield* startTurn({
2577
2755
  commandId: active.commandId,
2578
2756
  commandStarted: active.commandStarted,
2757
+ inputMessageIds: [],
2579
2758
  runId: active.runId,
2580
2759
  modelSelection: active.modelSelection,
2581
2760
  ...active.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: active.maxToolCallsPerRun },
2582
- promptInput: {
2583
- sessionId: sessionContext.sessionId,
2584
- state: current,
2585
- reducerStates: (yield* currentData()).reducerStates,
2586
- context: yield* contextProjectionFor(current),
2587
- selectedUserMessages: []
2588
- },
2589
2761
  runScope: active.runScope,
2590
2762
  runSpan: active.runSpan
2591
2763
  });
@@ -2614,9 +2786,39 @@ const makeLiveSessionState = Effect.gen(function* () {
2614
2786
  default: return yield* Effect.die(assertNeverError(turn.outcome, "turn outcome"));
2615
2787
  }
2616
2788
  });
2789
+ const interruptWaitingRun = Effect.fnUntraced(function* (control, reason) {
2790
+ const plan = planWaitingRunInterruption(yield* currentReduced(), control.commandId);
2791
+ if (plan === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Waiting interruption requires a current reservation"));
2792
+ const isStop = control.command._tag === "StopTurn";
2793
+ const batch = [];
2794
+ if (isStop) batch.push(yield* events.commandStarted({ commandId: control.commandId }));
2795
+ batch.push(yield* events.runSchedulingInvalidated({
2796
+ requestId: plan.requestId,
2797
+ reason
2798
+ }));
2799
+ const [firstMessageId, ...restMessageIds] = plan.messageIds;
2800
+ if (firstMessageId !== void 0) batch.push(yield* events.pendingMessagesPaused({
2801
+ interruptionCommandId: control.commandId,
2802
+ runRequestId: plan.requestId,
2803
+ messageIds: [firstMessageId, ...restMessageIds],
2804
+ reason: "user-interrupted"
2805
+ }));
2806
+ if (plan.cancelCommandId !== void 0) batch.push(yield* events.commandCancelled({
2807
+ commandId: plan.cancelCommandId,
2808
+ reason
2809
+ }));
2810
+ if (isStop) batch.push(yield* events.commandCompleted({ commandId: control.commandId }));
2811
+ const committed = yield* appendDurableBatch(batch);
2812
+ yield* reconcileSchedulingWakeup();
2813
+ return committed;
2814
+ });
2617
2815
  const drainOneReadyCommand = Effect.fnUntraced(function* (input) {
2618
2816
  const execution = yield* inspectExecutionState();
2619
2817
  const current = yield* currentReduced();
2818
+ input = {
2819
+ ...input,
2820
+ modelSelection: current.modelSelection ?? input.modelSelection
2821
+ };
2620
2822
  if (execution?._tag === "FailedTurn") return execution.result;
2621
2823
  if (execution?._tag === "CompletedTurn") {
2622
2824
  const decision = decideDispatch(current);
@@ -2669,6 +2871,28 @@ const makeLiveSessionState = Effect.gen(function* () {
2669
2871
  });
2670
2872
  }
2671
2873
  }
2874
+ if (current.runSchedulingRequest !== void 0) {
2875
+ const control = waitingRunControl(current);
2876
+ if (control === void 0) return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
2877
+ switch (control.command._tag) {
2878
+ case "CancelPendingMessage": return yield* cancelPendingMessage(control);
2879
+ case "PromotePendingMessage": return yield* promotePendingMessage(control);
2880
+ case "StopTurn": {
2881
+ const committed = yield* interruptWaitingRun(control, "stopped");
2882
+ const started = committed[0];
2883
+ const completed = committed.at(-1);
2884
+ if (started === void 0 || completed === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Stopping a waiting request must commit its control lifecycle"));
2885
+ return {
2886
+ started,
2887
+ outcome: SessionCommandCompleted.make({ committed: completed })
2888
+ };
2889
+ }
2890
+ case "SubmitMessage":
2891
+ yield* interruptWaitingRun(control, "interrupted");
2892
+ return yield* startSubmitCommand(control, input);
2893
+ default: return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
2894
+ }
2895
+ }
2672
2896
  const decision = decideDispatch(current);
2673
2897
  switch (decision._tag) {
2674
2898
  case "DispatchBlockedByActiveCommand":
@@ -2698,7 +2922,7 @@ const makeLiveSessionState = Effect.gen(function* () {
2698
2922
  yield* failIfFatal;
2699
2923
  const processed = [];
2700
2924
  while (true) {
2701
- const result = yield* withFatalRecording(drainOneReadyCommand(input));
2925
+ const result = yield* controlGate.withPermits(1)(withFatalRecording(drainOneReadyCommand(input)));
2702
2926
  if (isSessionNoRunnableCommand(result)) {
2703
2927
  yield* annotateEdaSpan({
2704
2928
  "eda.command.processed_count": processed.length,
@@ -2720,7 +2944,12 @@ const makeLiveSessionState = Effect.gen(function* () {
2720
2944
  "eda.model.id": input.modelSelection.modelId
2721
2945
  });
2722
2946
  yield* failIfFatal;
2723
- const recovery = yield* withFatalRecording(recoverSession(yield* currentReduced(), startupRecoveryReason, input));
2947
+ const initial = yield* currentReduced();
2948
+ input = {
2949
+ ...input,
2950
+ modelSelection: initial.modelSelection ?? input.modelSelection
2951
+ };
2952
+ const recovery = yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, input));
2724
2953
  yield* requestStartupRecoveryCheckpointIfNeeded();
2725
2954
  if (recovery.continuation !== void 0) yield* closeRunTraceOnFailure(recovery.continuation, withFatalRecording(resumeRecoveredCommand(recovery.continuation, input)));
2726
2955
  });
@@ -2758,6 +2987,7 @@ const makeLiveSessionState = Effect.gen(function* () {
2758
2987
  });
2759
2988
  const start = Effect.fn(function* (input) {
2760
2989
  yield* runStartupRecovery(input);
2990
+ yield* forkSchedulingDelivery();
2761
2991
  yield* runLiveControlLoop(input).pipe(Effect.forkIn(runtimeScope));
2762
2992
  });
2763
2993
  yield* sinkRegistry.startSinkRunners({
@@ -2779,8 +3009,8 @@ const hydrateReducedStateCheckpoint = (store, checkpoint) => Effect.gen(function
2779
3009
  });
2780
3010
  const hydrateFrameworkReducedState = (store) => Effect.gen(function* () {
2781
3011
  const checkpoint = yield* store.loadReducerCheckpoint(frameworkReducedStateReducerName);
2782
- const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 4 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
2783
- const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 4 ? SequenceNumber.make(0) : checkpoint.throughSeq;
3012
+ const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
3013
+ const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? SequenceNumber.make(0) : checkpoint.throughSeq;
2784
3014
  return {
2785
3015
  state: foldReducedState(checkpointState, yield* store.eventsAfter(checkpointSeq).pipe(Stream.runCollect, Effect.map((events) => Array.from(events)))),
2786
3016
  checkpointSeq
@@ -2862,69 +3092,6 @@ const requireTurnFailed = (committed) => isTurnFailed(committed) ? Effect.succee
2862
3092
  const isTurnFailed = (committed) => committed.event.type === turnFailedEventType;
2863
3093
  const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag === "SessionNoRunnableCommand";
2864
3094
  //#endregion
2865
- //#region src/services/session-query.ts
2866
- /** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
2867
- var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-durable-agent/EDASessionQuery") {
2868
- static Live = Layer.effect(EDASessionQuery, Effect.gen(function* () {
2869
- const store = yield* EDASessionStore;
2870
- const liveBus = yield* LiveEventBus;
2871
- const sessionState = yield* SessionState;
2872
- const snapshot = Effect.gen(function* () {
2873
- const data = yield* sessionState.snapshotData();
2874
- return {
2875
- state: data.reduced,
2876
- reducerStates: data.reducerStates,
2877
- messages: durableMessageTranscript(data.reduced)
2878
- };
2879
- });
2880
- return {
2881
- snapshot: () => snapshot,
2882
- messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),
2883
- eventsAfter: (afterSeq) => Effect.gen(function* () {
2884
- const live = yield* liveBus.subscribeQueue();
2885
- const replayHead = (yield* sessionState.snapshot()).lastSeq;
2886
- const replay = yield* store.eventsAfter(afterSeq).pipe(Stream.filter((entry) => entry.position.seq <= replayHead), Stream.map((entry) => PositionedEvent.make({
2887
- position: entry.position,
2888
- event: entry.event
2889
- })), Stream.runCollect, Effect.map((events) => Array.from(events)));
2890
- const activeTurnReplay = yield* liveBus.activeTurnReplay();
2891
- const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter((event) => shouldEmitLiveEvent(event, replayHead));
2892
- const reconnectPrefix = Array.from(uniquePositionedEvents([
2893
- ...replay,
2894
- ...activeTurnReplay.events,
2895
- ...pendingLive
2896
- ])).sort(comparePositionedEvents);
2897
- yield* annotateEdaSpan({
2898
- "eda.seq.after": afterSeq,
2899
- "eda.seq.head": replayHead,
2900
- "eda.replay.events": replay.length,
2901
- "eda.live.active_turn_events": activeTurnReplay.events.length,
2902
- "eda.live.active_turn_overflowed": activeTurnReplay.overflowed,
2903
- "eda.live.buffered_events": pendingLive.length
2904
- });
2905
- const follow = Stream.fromEffectRepeat(PubSub.take(live)).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));
2906
- return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));
2907
- }).pipe(Effect.withSpan("agent.events.follow", { attributes: { "eda.seq.after": afterSeq } }))
2908
- };
2909
- }));
2910
- };
2911
- const shouldEmitLiveEvent = (event, replayHead) => event.event.durability === "ephemeral" || event.position.seq > replayHead;
2912
- const comparePositionedEvents = (left, right) => {
2913
- const seq = left.position.seq - right.position.seq;
2914
- return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;
2915
- };
2916
- const uniquePositionedEvents = (events) => {
2917
- const seen = /* @__PURE__ */ new Set();
2918
- const output = [];
2919
- for (const event of events) {
2920
- const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;
2921
- if (seen.has(key)) continue;
2922
- seen.add(key);
2923
- output.push(event);
2924
- }
2925
- return output;
2926
- };
2927
- //#endregion
2928
- export { ToolExecutor as a, InferenceRunner as i, SessionState as n, TurnRunner as r, EDASessionQuery as t };
3095
+ 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 };
2929
3096
 
2930
- //# sourceMappingURL=session-query-DOc1KanA.js.map
3097
+ //# sourceMappingURL=session-state-BIZ2SYaP.js.map