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

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 (94) hide show
  1. package/dist/{command-queues-C8muEqeQ.d.ts → command-queues-DdDB_aYM.d.ts} +11 -18
  2. package/dist/compaction-BgDr5VJy.js +473 -0
  3. package/dist/compaction-BgDr5VJy.js.map +1 -0
  4. package/dist/{compaction-D7W0-Ur1.d.ts → compaction-ch8z6G9x.d.ts} +26 -7
  5. package/dist/{context-projection-C43pyxn2.d.ts → context-projection-n6Rdup0N.d.ts} +2 -2
  6. package/dist/domain/command-queues.d.ts +1 -1
  7. package/dist/domain/context-projection.d.ts +1 -1
  8. package/dist/domain/message-transcript.d.ts +1 -1
  9. package/dist/domain/model-usage.d.ts +2 -0
  10. package/dist/domain/model-usage.js +59 -0
  11. package/dist/domain/model-usage.js.map +1 -0
  12. package/dist/domain/reduced-state-schema.d.ts +11 -17
  13. package/dist/domain/reduced-state-schema.js +6 -11
  14. package/dist/domain/reduced-state-schema.js.map +1 -1
  15. package/dist/domain/reduced-state.d.ts +3 -2
  16. package/dist/domain/reduced-state.js +3 -2
  17. package/dist/{durable-DsV9PxZC.js → durable-BGFvX7Mh.js} +17 -80
  18. package/dist/durable-BGFvX7Mh.js.map +1 -0
  19. package/dist/{durable-B7M6TD_0.d.ts → durable-br2C1bWK.d.ts} +247 -4
  20. package/dist/envelope-DkZyMIgp.d.ts +191 -0
  21. package/dist/envelope-DxQzo5rN.js +82 -0
  22. package/dist/envelope-DxQzo5rN.js.map +1 -0
  23. package/dist/{event-factory-tcpLgdMN.js → event-factory-DTFdy0Cb.js} +3 -2
  24. package/dist/{event-factory-tcpLgdMN.js.map → event-factory-DTFdy0Cb.js.map} +1 -1
  25. package/dist/{event-factory-CLJcyymV.d.ts → event-factory-Di1jwQvm.d.ts} +3 -3
  26. package/dist/{events-Bb9-Cu-7.d.ts → events-LZFNoESe.d.ts} +2 -188
  27. package/dist/index.d.ts +5 -4
  28. package/dist/index.js +4 -3
  29. package/dist/{message-transcript-DsKTT47f.d.ts → message-transcript-DQNlzxle.d.ts} +3 -3
  30. package/dist/model-resolver-BPPJAsuh.d.ts +18 -0
  31. package/dist/model-usage-CdBEkTwU.d.ts +55 -0
  32. package/dist/{prompt-projector-hqPh5-NI.d.ts → prompt-projector-f4ElyXCE.d.ts} +4 -4
  33. package/dist/{reduced-state-TMi7ISla.js → reduced-state-DF0-6mbR.js} +25 -30
  34. package/dist/reduced-state-DF0-6mbR.js.map +1 -0
  35. package/dist/{reducer-registry--vQFATXb.d.ts → reducer-registry-aFjz_ZLT.d.ts} +2 -2
  36. package/dist/run-scheduler-CAt7dF6C.js +21 -0
  37. package/dist/run-scheduler-CAt7dF6C.js.map +1 -0
  38. package/dist/run-scheduler-xkhZyto5.d.ts +44 -0
  39. package/dist/{runtime-DXvMCq-J.d.ts → runtime-DDSYP9jS.d.ts} +6 -6
  40. package/dist/services/compaction.d.ts +1 -1
  41. package/dist/services/compaction.js +1 -426
  42. package/dist/services/model-resolver.d.ts +2 -0
  43. package/dist/services/model-resolver.js +17 -0
  44. package/dist/services/model-resolver.js.map +1 -0
  45. package/dist/services/prompt-projector.d.ts +1 -1
  46. package/dist/services/reducer-registry.d.ts +1 -1
  47. package/dist/services/run-scheduler.d.ts +2 -0
  48. package/dist/services/run-scheduler.js +2 -0
  49. package/dist/services/runtime-layer.d.ts +17 -14
  50. package/dist/services/runtime-layer.js +10 -8
  51. package/dist/services/runtime-layer.js.map +1 -1
  52. package/dist/services/runtime.d.ts +1 -1
  53. package/dist/services/runtime.js +3 -2
  54. package/dist/services/runtime.js.map +1 -1
  55. package/dist/services/session-event-observer.d.ts +1 -1
  56. package/dist/services/session-query.d.ts +1 -1
  57. package/dist/services/session-query.js +3 -3
  58. package/dist/services/session-state.d.ts +1 -1
  59. package/dist/services/session-state.js +1 -1
  60. package/dist/services/session-store.d.ts +1 -1
  61. package/dist/services/session-store.js +2 -1
  62. package/dist/services/session-store.js.map +1 -1
  63. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  64. package/dist/services/sink-registry.d.ts +1 -1
  65. package/dist/services/sink-registry.js +1 -1
  66. package/dist/services/tool-registry.d.ts +1 -1
  67. package/dist/services/tracing.d.ts +1 -1
  68. package/dist/{session-event-observer-D_aoFnQs.d.ts → session-event-observer-DaFMKKNc.d.ts} +2 -2
  69. package/dist/{session-query-lUZQpMvM.d.ts → session-query-B72HY_0L.d.ts} +9 -9
  70. package/dist/{session-state-C4m0j6CJ.js → session-state-Bkc6u-Wr.js} +44 -39
  71. package/dist/session-state-Bkc6u-Wr.js.map +1 -0
  72. package/dist/{session-state-Bi3oEbJU.d.ts → session-state-C9YLSAso.d.ts} +16 -15
  73. package/dist/{session-store-ofm8FFxs.d.ts → session-store-Cpi_NwTR.d.ts} +3 -3
  74. package/dist/{sink-checkpoint-store-BQVbI9DQ.d.ts → sink-checkpoint-store-M7qIxoSH.d.ts} +2 -2
  75. package/dist/{sink-registry-CE-hL7cB.d.ts → sink-registry-Bl-vQES6.d.ts} +9 -9
  76. package/dist/{sink-registry-DH6uiEgP.js → sink-registry-NDgeyzO0.js} +4 -4
  77. package/dist/{sink-registry-DH6uiEgP.js.map → sink-registry-NDgeyzO0.js.map} +1 -1
  78. package/dist/testkit/layers.d.ts +19 -14
  79. package/dist/testkit/layers.js +12 -9
  80. package/dist/testkit/layers.js.map +1 -1
  81. package/dist/{tool-registry-ClHdr_G5.d.ts → tool-registry-BJaVNtw4.d.ts} +3 -3
  82. package/dist/types/events/durable.d.ts +2 -2
  83. package/dist/types/events/durable.js +2 -2
  84. package/dist/types/events.d.ts +4 -3
  85. package/dist/types/events.js +3 -2
  86. package/dist/types/events.js.map +1 -1
  87. package/dist/websocket.d.ts +63 -2
  88. package/dist/websocket.js +2 -1
  89. package/dist/websocket.js.map +1 -1
  90. package/package.json +15 -2
  91. package/dist/durable-DsV9PxZC.js.map +0 -1
  92. package/dist/reduced-state-TMi7ISla.js.map +0 -1
  93. package/dist/services/compaction.js.map +0 -1
  94. package/dist/session-state-C4m0j6CJ.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { u as UserMessageContent } from "./commands-Ce1ec6kH.js";
2
- import { i as ContextProjection } from "./context-projection-C43pyxn2.js";
3
- import { S as ReducedState, v as MessageRecord } from "./command-queues-C8muEqeQ.js";
2
+ import { i as ContextProjection } from "./context-projection-n6Rdup0N.js";
3
+ import { S as ReducedState, v as MessageRecord } from "./command-queues-DdDB_aYM.js";
4
4
  import * as Prompt from "effect/unstable/ai/Prompt";
5
5
 
6
6
  //#region src/domain/message-transcript.d.ts
@@ -29,4 +29,4 @@ declare const contextProjectionPromptWithUserContent: (state: PromptProjectionSt
29
29
  declare const contextProjectionPromptWithUserContents: (state: PromptProjectionState, context: ContextProjection | undefined, contents: ReadonlyArray<UserMessageContent>) => Prompt.Prompt;
30
30
  //#endregion
31
31
  export { durableMessageTranscript as a, contextProjectionPromptWithUserContents as i, contextProjectionPrompt as n, durableTranscriptPrompt as o, contextProjectionPromptWithUserContent as r, durableTranscriptPromptWithUserContent as s, DurableTranscriptMessage as t };
32
- //# sourceMappingURL=message-transcript-DsKTT47f.d.ts.map
32
+ //# sourceMappingURL=message-transcript-DQNlzxle.d.ts.map
@@ -0,0 +1,18 @@
1
+ import { l as ModelSelectionPayload } from "./envelope-DkZyMIgp.js";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+ import * as LanguageModel from "effect/unstable/ai/LanguageModel";
6
+
7
+ //#region src/services/model-resolver.d.ts
8
+ declare const ModelResolver_base: Context.ServiceClass<ModelResolver, "@effect-durable-agent/ModelResolver", {
9
+ readonly resolve: (selection: ModelSelectionPayload | undefined) => Effect.Effect<LanguageModel.Service>;
10
+ }>;
11
+ /** Resolves a recorded selection into an executable provider service at a model-call boundary. */
12
+ declare class ModelResolver extends ModelResolver_base {
13
+ /** Fixed provider implementation for deterministic tests and single-model hosts. */
14
+ static readonly Fixed: Layer.Layer<ModelResolver, never, LanguageModel.LanguageModel>;
15
+ }
16
+ //#endregion
17
+ export { ModelResolver as t };
18
+ //# sourceMappingURL=model-resolver-BPPJAsuh.d.ts.map
@@ -0,0 +1,55 @@
1
+ import { _ as UsagePayload } from "./envelope-DkZyMIgp.js";
2
+ import * as Schema from "effect/Schema";
3
+
4
+ //#region src/domain/model-usage.d.ts
5
+ /** Additive provider usage categories; reasoning and text are breakdowns of output. */
6
+ declare const TokenUsageTotals: Schema.Struct<{
7
+ readonly inputTokens: Schema.Int;
8
+ readonly cachedInputTokens: Schema.Int;
9
+ readonly cacheWriteInputTokens: Schema.Int;
10
+ readonly outputTokens: Schema.Int;
11
+ readonly textTokens: Schema.Int;
12
+ readonly reasoningTokens: Schema.Int;
13
+ }>;
14
+ type TokenUsageTotals = typeof TokenUsageTotals.Type;
15
+ /** Model attribution survives compaction. Plain records are required by Cloudflare RPC structured cloning. */
16
+ declare const ModelTokenUsage: Schema.Struct<{
17
+ readonly provider: Schema.NonEmptyString;
18
+ readonly modelId: Schema.NonEmptyString;
19
+ readonly usage: Schema.Struct<{
20
+ readonly inputTokens: Schema.Int;
21
+ readonly cachedInputTokens: Schema.Int;
22
+ readonly cacheWriteInputTokens: Schema.Int;
23
+ readonly outputTokens: Schema.Int;
24
+ readonly textTokens: Schema.Int;
25
+ readonly reasoningTokens: Schema.Int;
26
+ }>;
27
+ }>;
28
+ type ModelTokenUsage = typeof ModelTokenUsage.Type;
29
+ /** One bounded bucket per distinct model used by a session. Dollars belong to the host. */
30
+ declare const TokenConsumptionState: Schema.Struct<{
31
+ readonly byModel: Schema.$Array<Schema.Struct<{
32
+ readonly provider: Schema.NonEmptyString;
33
+ readonly modelId: Schema.NonEmptyString;
34
+ readonly usage: Schema.Struct<{
35
+ readonly inputTokens: Schema.Int;
36
+ readonly cachedInputTokens: Schema.Int;
37
+ readonly cacheWriteInputTokens: Schema.Int;
38
+ readonly outputTokens: Schema.Int;
39
+ readonly textTokens: Schema.Int;
40
+ readonly reasoningTokens: Schema.Int;
41
+ }>;
42
+ }>>;
43
+ }>;
44
+ type TokenConsumptionState = typeof TokenConsumptionState.Type;
45
+ declare const emptyTokenUsage: TokenUsageTotals;
46
+ /** Fold an observed call into its model bucket; omitted provider counters add no known usage. */
47
+ declare const addModelUsage: (state: TokenConsumptionState, model: {
48
+ readonly provider: string;
49
+ readonly modelId: string;
50
+ }, usage: UsagePayload | undefined) => TokenConsumptionState;
51
+ /** Totals are a derived display value, never an input to multi-model pricing. */
52
+ declare const totalTokenUsage: (state: TokenConsumptionState) => TokenUsageTotals;
53
+ //#endregion
54
+ export { emptyTokenUsage as a, addModelUsage as i, TokenConsumptionState as n, totalTokenUsage as o, TokenUsageTotals as r, ModelTokenUsage as t };
55
+ //# sourceMappingURL=model-usage-CdBEkTwU.d.ts.map
@@ -1,7 +1,7 @@
1
1
  import { h as SessionId } from "./core-CYT6DBaS.js";
2
- import { i as ContextProjection } from "./context-projection-C43pyxn2.js";
3
- import { S as ReducedState } from "./command-queues-C8muEqeQ.js";
4
- import { a as EDAReducerStateSnapshot } from "./reducer-registry--vQFATXb.js";
2
+ import { i as ContextProjection } from "./context-projection-n6Rdup0N.js";
3
+ import { S as ReducedState } from "./command-queues-DdDB_aYM.js";
4
+ import { a as EDAReducerStateSnapshot } from "./reducer-registry-aFjz_ZLT.js";
5
5
  import * as Context from "effect/Context";
6
6
  import * as Effect from "effect/Effect";
7
7
  import * as Layer from "effect/Layer";
@@ -36,4 +36,4 @@ declare class EDAPromptProjector extends EDAPromptProjector_base {
36
36
  }
37
37
  //#endregion
38
38
  export { buildEDAPrompt as a, EDAPromptProjectorShape as i, EDAPromptProjectionInput as n, EDAPromptProjector as r, EDAProjectedPromptContext as t };
39
- //# sourceMappingURL=prompt-projector-hqPh5-NI.d.ts.map
39
+ //# sourceMappingURL=prompt-projector-f4ElyXCE.d.ts.map
@@ -1,5 +1,7 @@
1
1
  import { ContextVersion, SequenceNumber } from "./types/core.js";
2
- import { $n as turnStoppedEventType, An as inferenceFailedEventType, Bn as steeringMessageQueuedEventType, Cn as compactionRequestedEventType, En as contextRebasedEventType, Fn as runCompletedEventType, Gn as toolCallCompletedEventType, Hn as stopTurnRequestedEventType, In as runFailedEventType, Jn as toolCallRejectedEventType, Kn as toolCallCreatedEventType, Ln as runInterruptedEventType, Mn as messageQueuePausedEventType, Nn as pendingMessagesPausedEventType, Pn as recoveryCompletedEventType, Qn as turnStartedEventType, Rn as runStartedEventType, Sn as compactionFailedEventType, Tn as contextProjectedEventType, Un as summaryCreatedEventType, Vn as stopTurnAppliedEventType, Wn as systemMessageCommittedEventType, Xn as turnCompletedEventType, Yn as toolCallStartedEventType, Zn as turnFailedEventType, _n as commandCancelledEventType, bn as commandStartedEventType, dn as assistantMessageImportedEventType, er as userMessageCancelledEventType, fn as assistantPartialCommittedEventType, gn as commandAdmittedEventType, hn as baseStateRequestedEventType, jn as inferenceStartedEventType, kn as inferenceCompletedEventType, mn as baseStateFailedEventType, nr as userMessagePromotedEventType, pn as baseStateCreatedEventType, qn as toolCallFailedEventType, rr as userMessageSubmittedEventType, tr as userMessageCommittedEventType, un as assistantMessageCommittedEventType, vn as commandCompletedEventType, wn as compactionStartedEventType, xn as compactionCompletedEventType, xr as effectDurableAgentNamespace, yn as commandFailedEventType, zn as steeringMessageCancelledEventType } from "./durable-DsV9PxZC.js";
2
+ import { _ as effectDurableAgentNamespace } from "./envelope-DxQzo5rN.js";
3
+ import { addModelUsage } from "./domain/model-usage.js";
4
+ import { $n as turnFailedEventType, An as inferenceCompletedEventType, Bn as sessionConfiguredEventType, Cn as compactionFailedEventType, Dn as contextRebasedEventType, En as contextProjectedEventType, Fn as recoveryCompletedEventType, Gn as summaryCreatedEventType, Hn as steeringMessageQueuedEventType, In as runCompletedEventType, Jn as toolCallCreatedEventType, Kn as systemMessageCommittedEventType, Ln as runFailedEventType, Mn as inferenceStartedEventType, Nn as messageQueuePausedEventType, Pn as pendingMessagesPausedEventType, Qn as turnCompletedEventType, Rn as runInterruptedEventType, Sn as compactionCompletedEventType, Tn as compactionStartedEventType, Un as stopTurnAppliedEventType, Vn as steeringMessageCancelledEventType, Wn as stopTurnRequestedEventType, Xn as toolCallRejectedEventType, Yn as toolCallFailedEventType, Zn as toolCallStartedEventType, _n as commandAdmittedEventType, ar as userMessageSubmittedEventType, bn as commandFailedEventType, dn as assistantMessageCommittedEventType, er as turnStartedEventType, fn as assistantMessageImportedEventType, gn as baseStateRequestedEventType, hn as baseStateFailedEventType, ir as userMessagePromotedEventType, jn as inferenceFailedEventType, mn as baseStateCreatedEventType, nr as userMessageCancelledEventType, pn as assistantPartialCommittedEventType, qn as toolCallCompletedEventType, rr as userMessageCommittedEventType, tr as turnStoppedEventType, vn as commandCancelledEventType, wn as compactionRequestedEventType, xn as commandStartedEventType, yn as commandCompletedEventType, zn as runStartedEventType } from "./durable-BGFvX7Mh.js";
3
5
  import { deriveCommandQueues, emptyCommandQueues } from "./domain/command-queues.js";
4
6
  //#region src/domain/assert-never.ts
5
7
  const formatNeverValue = (value) => {
@@ -15,6 +17,9 @@ const assertNeverError = (value, context) => /* @__PURE__ */ new Error(`Unhandle
15
17
  const assertNever = (value, context) => {
16
18
  throw assertNeverError(value, context);
17
19
  };
20
+ //#endregion
21
+ //#region src/domain/reduced-state.ts
22
+ const emptyTokenConsumptionState = { byModel: [] };
18
23
  /** Empty durable replay state before any session event has committed. */
19
24
  const initialReducedState = {
20
25
  lastSeq: SequenceNumber.make(0),
@@ -28,22 +33,17 @@ const initialReducedState = {
28
33
  stopRequests: /* @__PURE__ */ new Map(),
29
34
  compactions: /* @__PURE__ */ new Map(),
30
35
  context: { version: ContextVersion.make(0) },
31
- tokenConsumption: { total: {
32
- inputTokens: 0,
33
- cachedInputTokens: 0,
34
- outputTokens: 0,
35
- textTokens: 0,
36
- reasoningTokens: 0
37
- } },
36
+ tokenConsumption: emptyTokenConsumptionState,
38
37
  commandQueues: emptyCommandQueues
39
38
  };
40
39
  /** Reserved reducer checkpoint name for the framework-owned `ReducedState`. */
41
40
  const frameworkReducedStateReducerName = "_eda.framework.reduced-state";
42
41
  /** Schema version for the framework-owned `ReducedState` checkpoint payload. */
43
- const frameworkReducedStateReducerSchemaVersion = 5;
42
+ const frameworkReducedStateReducerSchemaVersion = 6;
44
43
  /** Encode the framework reducer state into a pointer-based JSON-safe checkpoint payload. */
45
44
  const encodeReducedStateCheckpoint = (state) => ({
46
45
  lastSeq: state.lastSeq,
46
+ ...state.modelSelection === void 0 ? {} : { modelSelection: state.modelSelection },
47
47
  commands: Array.from(state.commands.entries()).map(([commandId, record]) => [commandId, encodeCheckpointCommandRecord(record)]),
48
48
  runs: Array.from(state.runs.entries()),
49
49
  recoveryContinuations: Array.from(state.recoveryContinuations.entries()),
@@ -77,6 +77,7 @@ const decodeReducedStateCheckpoint = (payload, referencedEvents) => {
77
77
  const messages = decodeCheckpointMessageRecords(checkpoint.messages ?? [], eventsBySeq);
78
78
  return {
79
79
  lastSeq: SequenceNumber.make(Number(checkpoint.lastSeq ?? 0)),
80
+ ...checkpoint.modelSelection === void 0 ? {} : { modelSelection: checkpoint.modelSelection },
80
81
  commands,
81
82
  runs,
82
83
  recoveryContinuations: new Map(checkpoint.recoveryContinuations ?? []),
@@ -213,16 +214,11 @@ const reduceSingleCheckpointEvent = (eventsBySeq, seq, expectedType) => {
213
214
  };
214
215
  const committedEventMapBySeq = (events) => new Map(events.map((event) => [Number(event.position.seq), event]));
215
216
  const uniqueSequenceNumbers = (seqs) => Array.from(new Set(seqs.map((seq) => Number(seq)))).sort((left, right) => left - right).map((seq) => SequenceNumber.make(seq));
216
- const decodeTokenConsumptionState = (value) => ({ total: {
217
- inputTokens: nonNegativeNumber(value?.total?.inputTokens),
218
- cachedInputTokens: nonNegativeNumber(value?.total?.cachedInputTokens),
219
- outputTokens: nonNegativeNumber(value?.total?.outputTokens),
220
- textTokens: nonNegativeNumber(value?.total?.textTokens),
221
- reasoningTokens: nonNegativeNumber(value?.total?.reasoningTokens)
222
- } });
217
+ const decodeTokenConsumptionState = (value) => value ?? emptyTokenConsumptionState;
223
218
  /** Fold newly committed durable events into the canonical replay state. */
224
219
  const foldReducedState = (state, committed) => {
225
220
  let lastSeq = state.lastSeq;
221
+ let modelSelection = state.modelSelection;
226
222
  const commands = new Map(state.commands);
227
223
  const runs = new Map(state.runs);
228
224
  const recoveryContinuations = new Map(state.recoveryContinuations);
@@ -298,6 +294,7 @@ const foldReducedState = (state, committed) => {
298
294
  }
299
295
  case runStartedEventType: {
300
296
  const { runId, commandIds, trace } = payload;
297
+ modelSelection ??= payload.modelSelection;
301
298
  const terminal = runs.get(runId)?.terminal;
302
299
  runs.set(runId, {
303
300
  runId,
@@ -305,6 +302,7 @@ const foldReducedState = (state, committed) => {
305
302
  startedAtMs: eventCreatedAtMs,
306
303
  startedSeq: seq,
307
304
  trace,
305
+ modelSelection: payload.modelSelection,
308
306
  ...terminal === void 0 ? {} : { terminal }
309
307
  });
310
308
  break;
@@ -431,7 +429,10 @@ const foldReducedState = (state, committed) => {
431
429
  ...usage === void 0 ? {} : { usage }
432
430
  }
433
431
  }));
434
- if (!previouslyCompleted && inferences.get(inferenceId)?.terminal?._tag === "Completed") tokenConsumption = addTokenUsage(tokenConsumption, usage);
432
+ if (!previouslyCompleted && inferences.get(inferenceId)?.terminal?._tag === "Completed") {
433
+ const model = runs.get(payload.runId)?.modelSelection;
434
+ if (model !== void 0) tokenConsumption = addModelUsage(tokenConsumption, model, usage);
435
+ }
435
436
  break;
436
437
  }
437
438
  case inferenceFailedEventType: {
@@ -758,6 +759,7 @@ const foldReducedState = (state, committed) => {
758
759
  }
759
760
  case compactionCompletedEventType: {
760
761
  const { compactionId } = payload;
762
+ if (compactions.get(compactionId)?.terminal?._tag !== "Completed" && payload.modelSelection !== void 0) tokenConsumption = addModelUsage(tokenConsumption, payload.modelSelection, payload.usage);
761
763
  upsert(compactions, compactionId, { compactionId }, (record) => ({
762
764
  ...record,
763
765
  terminal: {
@@ -769,6 +771,7 @@ const foldReducedState = (state, committed) => {
769
771
  }
770
772
  case compactionFailedEventType: {
771
773
  const { compactionId, error } = payload;
774
+ if (payload.modelSelection !== void 0) tokenConsumption = addModelUsage(tokenConsumption, payload.modelSelection, payload.usage);
772
775
  upsert(compactions, compactionId, { compactionId }, (record) => ({
773
776
  ...record,
774
777
  terminal: {
@@ -789,6 +792,9 @@ const foldReducedState = (state, committed) => {
789
792
  });
790
793
  break;
791
794
  }
795
+ case sessionConfiguredEventType:
796
+ modelSelection ??= payload.modelSelection;
797
+ break;
792
798
  case baseStateRequestedEventType:
793
799
  case baseStateCreatedEventType:
794
800
  case baseStateFailedEventType: break;
@@ -797,6 +803,7 @@ const foldReducedState = (state, committed) => {
797
803
  }
798
804
  return {
799
805
  lastSeq,
806
+ ...modelSelection === void 0 ? {} : { modelSelection },
800
807
  commands,
801
808
  runs,
802
809
  recoveryContinuations,
@@ -817,18 +824,6 @@ const foldReducedState = (state, committed) => {
817
824
  };
818
825
  /** Fold committed events from genesis into a fresh `ReducedState`. */
819
826
  const reduceCommittedEvents = (committed) => foldReducedState(initialReducedState, committed);
820
- const addTokenUsage = (state, usage) => {
821
- if (usage === void 0) return state;
822
- return { total: {
823
- inputTokens: state.total.inputTokens + tokenCount(usage.inputTokens),
824
- cachedInputTokens: state.total.cachedInputTokens + tokenCount(usage.cachedInputTokens),
825
- outputTokens: state.total.outputTokens + tokenCount(usage.outputTokens),
826
- textTokens: state.total.textTokens + tokenCount(usage.textTokens),
827
- reasoningTokens: state.total.reasoningTokens + tokenCount(usage.reasoningTokens)
828
- } };
829
- };
830
- const tokenCount = (value) => nonNegativeNumber(value);
831
- const nonNegativeNumber = (value) => value === void 0 || !Number.isFinite(value) ? 0 : Math.max(0, Math.trunc(value));
832
827
  /** Drop runtime state made model-invisible by a context rebase; storage remains append-only. */
833
828
  const pruneForContextRebase = (maps, retainedFromContextSeq, currentSummaryId) => {
834
829
  for (const [messageId, message] of maps.messages) if (message._tag !== "System" && messagePruneSeq(message) < retainedFromContextSeq) maps.messages.delete(messageId);
@@ -923,4 +918,4 @@ const appliedFields = (record) => record?.appliedSeq === void 0 ? {} : {
923
918
  //#endregion
924
919
  export { encodeReducedStateCheckpoint as a, frameworkReducedStateReducerSchemaVersion as c, pendingStopCommand as d, reduceCommittedEvents as f, assertNeverError as h, decodeReducedStateCheckpoint as i, initialReducedState as l, assertNever as m, activeTurnIdentityForCommand as n, foldReducedState as o, reducedStateCheckpointEventSeqs as p, classifyRecoverableWork as r, frameworkReducedStateReducerName as s, activeCommand as t, pendingCommands as u };
925
920
 
926
- //# sourceMappingURL=reduced-state-TMi7ISla.js.map
921
+ //# sourceMappingURL=reduced-state-DF0-6mbR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reduced-state-DF0-6mbR.js","names":[],"sources":["../src/domain/assert-never.ts","../src/domain/reduced-state.ts"],"sourcesContent":["const formatNeverValue = (value: never): string => {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n};\n\n/** Build the defect used when an exhaustive switch receives an impossible value. */\nexport const assertNeverError = (value: never, context: string) =>\n new Error(`Unhandled ${context}: ${formatNeverValue(value)}`);\n\n/** Throw for impossible branches in pure code after TypeScript exhaustiveness checking. */\nexport const assertNever = (value: never, context: string): never => {\n throw assertNeverError(value, context);\n};\n","import type * as Prompt from \"effect/unstable/ai/Prompt\";\nimport { addModelUsage, TokenConsumptionState } from \"./model-usage\";\nexport { type TokenUsageTotals, TokenConsumptionState } from \"./model-usage\";\n\nimport { assertNever } from \"./assert-never\";\nimport { deriveCommandQueues, emptyCommandQueues, type CommandQueues } from \"./command-queues\";\nimport {\n InferenceId,\n CommandId,\n CompactionId,\n ContextVersion,\n MessageId,\n RunId,\n SequenceNumber,\n SummaryId,\n ToolCallId,\n TurnId,\n} from \"../types/core\";\nimport {\n assistantMessageCommittedEventType,\n assistantMessageImportedEventType,\n assistantPartialCommittedEventType,\n baseStateCreatedEventType,\n baseStateFailedEventType,\n baseStateRequestedEventType,\n commandAdmittedEventType,\n commandCancelledEventType,\n commandCompletedEventType,\n commandFailedEventType,\n commandStartedEventType,\n compactionCompletedEventType,\n compactionFailedEventType,\n compactionRequestedEventType,\n compactionStartedEventType,\n contextProjectedEventType,\n effectDurableAgentNamespace,\n contextRebasedEventType,\n inferenceCompletedEventType,\n inferenceFailedEventType,\n inferenceStartedEventType,\n runCompletedEventType,\n runFailedEventType,\n runInterruptedEventType,\n runStartedEventType,\n sessionConfiguredEventType,\n stopTurnAppliedEventType,\n stopTurnRequestedEventType,\n steeringMessageCancelledEventType,\n steeringMessageQueuedEventType,\n userMessageSubmittedEventType,\n userMessagePromotedEventType,\n userMessageCancelledEventType,\n messageQueuePausedEventType,\n pendingMessagesPausedEventType,\n recoveryCompletedEventType,\n summaryCreatedEventType,\n systemMessageCommittedEventType,\n toolCallCompletedEventType,\n toolCallCreatedEventType,\n toolCallFailedEventType,\n toolCallRejectedEventType,\n toolCallStartedEventType,\n turnCompletedEventType,\n turnFailedEventType,\n turnStartedEventType,\n turnStoppedEventType,\n userMessageCommittedEventType,\n} from \"../types/events\";\nimport { type EDACommand as EDACommandValue, type UserMessageContent } from \"../types/commands\";\nimport type {\n AssistantMessageContent,\n EDAEventTrace,\n EDARunTrace,\n FailurePayload,\n ProviderPartId,\n RecoveryContinuation,\n SystemPromptText,\n ToolName,\n UsagePayload,\n ModelSelectionPayload,\n} from \"../types/events\";\nimport type { CommittedDurableEvent } from \"../services/session-store\";\n\n/** Failure payload paired with the durable sequence that recorded it. */\nexport type LifecycleFailure = {\n readonly seq: SequenceNumber;\n readonly error: FailurePayload;\n};\n\n/** Terminal command state folded from command lifecycle events. */\nexport type CommandTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload }\n | { readonly _tag: \"Cancelled\"; readonly seq: SequenceNumber; readonly reason: string };\n\n/** Durable command lifecycle projection used for scheduling and recovery. */\nexport interface CommandRecord {\n readonly commandId: CommandId;\n readonly command?: EDACommandValue;\n readonly admittedSeq?: SequenceNumber;\n readonly admissionTrace?: EDAEventTrace;\n readonly startedSeq?: SequenceNumber;\n readonly terminal?: CommandTerminal;\n}\n\n/** Terminal run state folded from run lifecycle events. */\nexport type RunTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload }\n | { readonly _tag: \"Interrupted\"; readonly seq: SequenceNumber; readonly reason: string };\n\n/** Common wall-clock lifecycle timing folded from durable event envelopes. */\nexport interface LifecycleTiming {\n readonly startedAtMs?: number;\n readonly terminalAtMs?: number;\n readonly durationMs?: number;\n}\n\n/** Durable run lifecycle projection tying one run to its owning command ids. */\nexport interface RunRecord extends LifecycleTiming {\n readonly modelSelection?: ModelSelectionPayload;\n readonly runId: RunId;\n readonly commandIds: ReadonlyArray<CommandId>;\n readonly startedSeq: SequenceNumber;\n readonly trace: EDARunTrace;\n readonly terminal?: RunTerminal;\n}\n\n/** Terminal turn state folded from turn lifecycle events. */\nexport type TurnTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber; readonly usage?: UsagePayload }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload }\n | { readonly _tag: \"Stopped\"; readonly seq: SequenceNumber; readonly reason: string };\n\n/** Durable turn lifecycle projection nested under a run. */\nexport interface TurnRecord extends LifecycleTiming {\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly startedSeq: SequenceNumber;\n readonly terminal?: TurnTerminal;\n}\n\n/** Terminal inference state folded from inference lifecycle events. */\nexport type InferenceTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber; readonly usage?: UsagePayload }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload };\n\n/** Durable model-inference lifecycle projection nested under a turn. */\nexport interface InferenceRecord extends LifecycleTiming {\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly startedSeq: SequenceNumber;\n readonly terminal?: InferenceTerminal;\n}\n\n/** Durable decision produced after a model inference seals final tool calls. */\nexport type ToolDecision =\n | {\n readonly _tag: \"Created\";\n readonly seq: SequenceNumber;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly providerPartId: ProviderPartId;\n readonly toolName: ToolName;\n readonly params: unknown;\n readonly providerExecuted: boolean;\n readonly promptPart?: Prompt.ToolCallPart;\n }\n | {\n readonly _tag: \"Rejected\";\n readonly seq: SequenceNumber;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly providerPartId: ProviderPartId;\n readonly toolName: ToolName;\n readonly reason: \"unknown-tool\" | \"invalid-params\";\n readonly modelFeedback: string;\n readonly promptPart?: Prompt.ToolResultPart;\n };\n\n/** Terminal framework-owned tool-call execution state. */\nexport type ToolTerminal =\n | {\n readonly _tag: \"Completed\";\n readonly seq: SequenceNumber;\n readonly result: unknown;\n readonly promptPart?: Prompt.ToolResultPart;\n }\n | {\n readonly _tag: \"Failed\";\n readonly seq: SequenceNumber;\n readonly error: FailurePayload;\n readonly promptPart?: Prompt.ToolResultPart;\n };\n\n/** Durable tool-call projection from decision through execution terminal. */\nexport interface ToolCallRecord extends LifecycleTiming {\n readonly toolCallId: ToolCallId;\n readonly decision?: ToolDecision;\n readonly startedSeq?: SequenceNumber;\n readonly terminal?: ToolTerminal;\n}\n\n/** Durable message-like facts folded from the event log. */\nexport type MessageRecord =\n | {\n readonly _tag: \"System\";\n readonly messageId: MessageId;\n readonly content: SystemPromptText;\n readonly createdAtMs?: number;\n readonly seq: SequenceNumber;\n }\n | {\n readonly _tag: \"User\";\n readonly messageId: MessageId;\n readonly commandId: CommandId;\n readonly content: UserMessageContent;\n readonly createdAtMs?: number;\n readonly seq: SequenceNumber;\n /** Present for admission-time message entities; absent on legacy committed users. */\n readonly requestedDisposition?: \"queue\" | \"steer\";\n readonly disposition?: \"queue\" | \"steer\";\n readonly promotedSeq?: SequenceNumber;\n readonly pausedSeq?: SequenceNumber;\n readonly pausedByCommandId?: CommandId;\n readonly consumedSeq?: SequenceNumber;\n readonly consumedTurnId?: TurnId;\n readonly cancelledSeq?: SequenceNumber;\n readonly cancelledByCommandId?: CommandId;\n readonly cancellationReason?: string;\n }\n | {\n readonly _tag: \"Steering\";\n readonly messageId: MessageId;\n readonly commandId: CommandId;\n readonly runId: RunId;\n readonly content: UserMessageContent;\n readonly createdAtMs?: number;\n readonly seq: SequenceNumber;\n readonly promotedSeq?: SequenceNumber;\n readonly consumedSeq?: SequenceNumber;\n readonly consumedTurnId?: TurnId;\n readonly cancelledSeq?: SequenceNumber;\n readonly cancelledByCommandId?: CommandId;\n readonly cancellationReason?: string;\n readonly pausedSeq?: SequenceNumber;\n readonly pausedByCommandId?: CommandId;\n }\n | {\n readonly _tag: \"Assistant\";\n readonly messageId: MessageId;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n /** True when the assistant message originated outside this EDA session. */\n readonly imported?: true;\n readonly content: AssistantMessageContent;\n readonly createdAtMs?: number;\n readonly promptParts?: ReadonlyArray<Prompt.AssistantMessagePart>;\n readonly seq: SequenceNumber;\n }\n | {\n readonly _tag: \"AssistantPartial\";\n readonly messageId: MessageId;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly content: AssistantMessageContent;\n readonly createdAtMs?: number;\n readonly promptParts?: ReadonlyArray<Prompt.AssistantMessagePart>;\n readonly reason: string;\n readonly seq: SequenceNumber;\n };\n\n/** Terminal compaction state folded from compaction lifecycle events. */\nexport type CompactionTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload };\n\n/** Durable compaction lifecycle projection and its produced summary cursor. */\nexport interface CompactionRecord {\n readonly compactionId: CompactionId;\n readonly requestedSeq?: SequenceNumber;\n readonly startedSeq?: SequenceNumber;\n readonly summaryCreatedSeq?: SequenceNumber;\n readonly summaryId?: SummaryId;\n readonly sourceFromSeq?: SequenceNumber;\n readonly sourceToSeq?: SequenceNumber;\n readonly rebasedSeq?: SequenceNumber;\n readonly contextVersion?: ContextVersion;\n readonly terminal?: CompactionTerminal;\n}\n\n/** Current model-context version and summary selected by compaction. */\nexport interface ContextRecord {\n readonly version: ContextVersion;\n readonly currentSummaryId?: SummaryId;\n}\n\n/** Durable StopTurn request and the lifecycle boundary it eventually applied to. */\nexport interface StopRequestRecord {\n readonly commandId: CommandId;\n readonly requestedSeq: SequenceNumber;\n readonly requestedRunId?: RunId;\n readonly requestedTurnId?: TurnId;\n readonly appliedSeq?: SequenceNumber;\n readonly appliedRunId?: RunId;\n readonly appliedTurnId?: TurnId;\n readonly appliedInferenceId?: InferenceId;\n}\n\n/** Admitted command that has not yet crossed the `CommandStarted` boundary. */\nexport interface PendingCommand {\n /** Lifecycle ID for the admitted command. */\n readonly commandId: CommandId;\n /** Typed command payload admitted durably. */\n readonly command: EDACommandValue;\n /** Admission sequence used for deterministic FIFO/control ordering. */\n readonly admittedSeq: SequenceNumber;\n /** Trace context captured at the durable command admission boundary. */\n readonly admissionTrace?: EDAEventTrace;\n}\n\n/** Started command without a terminal command boundary, optionally tied to an open run. */\nexport interface ActiveCommandEvidence {\n readonly commandId: CommandId;\n readonly runId?: RunId;\n}\n\n/** Active run/turn/inference identity derived from unfinished lifecycle records. */\nexport type ActiveTurnIdentity = {\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId?: InferenceId;\n};\n\n/** Canonical durable replay product used by queries, recovery, and scheduling. */\nexport interface ReducedState {\n /** Session execution policy established by configuration or the first historical run. */\n readonly modelSelection?: ModelSelectionPayload;\n readonly lastSeq: SequenceNumber;\n readonly commands: ReadonlyMap<CommandId, CommandRecord>;\n readonly runs: ReadonlyMap<RunId, RunRecord>;\n /** Explicit startup-recovery links keyed by replacement physical run id. */\n readonly recoveryContinuations: ReadonlyMap<RunId, RecoveryContinuationRecord>;\n readonly turns: ReadonlyMap<TurnId, TurnRecord>;\n readonly inferences: ReadonlyMap<InferenceId, InferenceRecord>;\n readonly toolCalls: ReadonlyMap<ToolCallId, ToolCallRecord>;\n readonly messages: ReadonlyMap<MessageId, MessageRecord>;\n readonly stopRequests: ReadonlyMap<CommandId, StopRequestRecord>;\n readonly compactions: ReadonlyMap<CompactionId, CompactionRecord>;\n readonly context: ContextRecord;\n /** Rolling model-token usage totals derived from completed provider inferences. */\n readonly tokenConsumption: TokenConsumptionState;\n /** Materialized scheduler queues derived from the maps above after every fold. */\n readonly commandQueues: CommandQueues;\n}\n\n/** Durable recovery continuation plus the sequence of its completion barrier. */\nexport interface RecoveryContinuationRecord extends RecoveryContinuation {\n readonly seq: SequenceNumber;\n}\n\n/** Unfinished lifecycle records requiring deterministic startup recovery. */\nexport interface RecoverableWork {\n readonly activeCommands: ReadonlyArray<CommandRecord>;\n readonly activeRuns: ReadonlyArray<RunRecord>;\n readonly activeTurns: ReadonlyArray<TurnRecord>;\n readonly activeInferences: ReadonlyArray<InferenceRecord>;\n readonly openToolCalls: ReadonlyArray<ToolCallRecord>;\n readonly runningToolCalls: ReadonlyArray<ToolCallRecord>;\n readonly pendingStopRequests: ReadonlyArray<StopRequestRecord>;\n readonly openCompactions: ReadonlyArray<CompactionRecord>;\n}\n\nconst emptyTokenConsumptionState: TokenConsumptionState = {\n byModel: [],\n};\n\n/** Empty durable replay state before any session event has committed. */\nexport const initialReducedState: ReducedState = {\n lastSeq: SequenceNumber.make(0),\n commands: new Map(),\n runs: new Map(),\n recoveryContinuations: new Map(),\n turns: new Map(),\n inferences: new Map(),\n toolCalls: new Map(),\n messages: new Map(),\n stopRequests: new Map(),\n compactions: new Map(),\n context: { version: ContextVersion.make(0) },\n tokenConsumption: emptyTokenConsumptionState,\n commandQueues: emptyCommandQueues,\n};\n\n/** Reserved reducer checkpoint name for the framework-owned `ReducedState`. */\nexport const frameworkReducedStateReducerName = \"_eda.framework.reduced-state\";\n\n/** Schema version for the framework-owned `ReducedState` checkpoint payload. */\nexport const frameworkReducedStateReducerSchemaVersion = 6;\n\n/** JSON payload stored for the framework-owned reduced-state reducer checkpoint. */\nexport type ReducedStateCheckpointCommandRecord = Omit<CommandRecord, \"command\">;\n\ntype SystemMessageRecord = Extract<MessageRecord, { readonly _tag: \"System\" }>;\ntype UserMessageRecord = Extract<MessageRecord, { readonly _tag: \"User\" }>;\ntype SteeringMessageRecord = Extract<MessageRecord, { readonly _tag: \"Steering\" }>;\ntype AssistantMessageRecord = Extract<MessageRecord, { readonly _tag: \"Assistant\" }>;\ntype AssistantPartialMessageRecord = Extract<MessageRecord, { readonly _tag: \"AssistantPartial\" }>;\n\nexport type ReducedStateCheckpointMessageRecord =\n | Omit<SystemMessageRecord, \"content\">\n | Omit<UserMessageRecord, \"content\">\n | Omit<SteeringMessageRecord, \"content\">\n | Omit<AssistantMessageRecord, \"content\" | \"promptParts\">\n | Omit<AssistantPartialMessageRecord, \"content\" | \"promptParts\">;\n\ntype CreatedToolDecision = Extract<ToolDecision, { readonly _tag: \"Created\" }>;\ntype RejectedToolDecision = Extract<ToolDecision, { readonly _tag: \"Rejected\" }>;\ntype CompletedToolTerminal = Extract<ToolTerminal, { readonly _tag: \"Completed\" }>;\ntype FailedToolTerminal = Extract<ToolTerminal, { readonly _tag: \"Failed\" }>;\n\nexport type ReducedStateCheckpointToolDecision =\n | Omit<CreatedToolDecision, \"params\" | \"promptPart\">\n | Omit<RejectedToolDecision, \"promptPart\">;\n\nexport type ReducedStateCheckpointToolTerminal =\n | Omit<CompletedToolTerminal, \"result\" | \"promptPart\">\n | Omit<FailedToolTerminal, \"error\" | \"promptPart\">;\n\nexport interface ReducedStateCheckpointToolCallRecord extends Omit<\n ToolCallRecord,\n \"decision\" | \"terminal\"\n> {\n readonly decision?: ReducedStateCheckpointToolDecision;\n readonly terminal?: ReducedStateCheckpointToolTerminal;\n}\n\nexport interface ReducedStateCheckpointPayload {\n readonly modelSelection?: ModelSelectionPayload;\n readonly lastSeq: SequenceNumber;\n readonly commands: ReadonlyArray<readonly [CommandId, ReducedStateCheckpointCommandRecord]>;\n readonly runs: ReadonlyArray<readonly [RunId, RunRecord]>;\n readonly recoveryContinuations?: ReadonlyArray<readonly [RunId, RecoveryContinuationRecord]>;\n readonly turns: ReadonlyArray<readonly [TurnId, TurnRecord]>;\n readonly inferences: ReadonlyArray<readonly [InferenceId, InferenceRecord]>;\n readonly toolCalls: ReadonlyArray<readonly [ToolCallId, ReducedStateCheckpointToolCallRecord]>;\n readonly messages: ReadonlyArray<readonly [MessageId, ReducedStateCheckpointMessageRecord]>;\n readonly stopRequests: ReadonlyArray<readonly [CommandId, StopRequestRecord]>;\n readonly compactions: ReadonlyArray<readonly [CompactionId, CompactionRecord]>;\n readonly context: ContextRecord;\n readonly tokenConsumption?: TokenConsumptionState;\n}\n\n/** Encode the framework reducer state into a pointer-based JSON-safe checkpoint payload. */\nexport const encodeReducedStateCheckpoint = (\n state: ReducedState,\n): ReducedStateCheckpointPayload => ({\n lastSeq: state.lastSeq,\n ...(state.modelSelection === undefined ? {} : { modelSelection: state.modelSelection }),\n commands: Array.from(state.commands.entries()).map(([commandId, record]) => [\n commandId,\n encodeCheckpointCommandRecord(record),\n ]),\n runs: Array.from(state.runs.entries()),\n recoveryContinuations: Array.from(state.recoveryContinuations.entries()),\n turns: Array.from(state.turns.entries()),\n inferences: Array.from(state.inferences.entries()),\n toolCalls: Array.from(state.toolCalls.entries()).map(([toolCallId, record]) => [\n toolCallId,\n encodeCheckpointToolCallRecord(record),\n ]),\n messages: Array.from(state.messages.entries()).map(([messageId, record]) => [\n messageId,\n encodeCheckpointMessageRecord(record),\n ]),\n stopRequests: Array.from(state.stopRequests.entries()),\n compactions: Array.from(state.compactions.entries()),\n context: state.context,\n tokenConsumption: state.tokenConsumption,\n});\n\n/** Event-log positions required to hydrate a pointer-based framework checkpoint. */\nexport const reducedStateCheckpointEventSeqs = (\n payload: unknown,\n): ReadonlyArray<SequenceNumber> => {\n const checkpoint = payload as ReducedStateCheckpointPayload;\n const seqs: Array<SequenceNumber> = [];\n for (const [, record] of checkpoint.commands ?? []) {\n if (record.admittedSeq !== undefined) {\n seqs.push(record.admittedSeq);\n }\n }\n for (const [, record] of checkpoint.messages ?? []) {\n seqs.push(record.seq);\n }\n for (const [, record] of checkpoint.toolCalls ?? []) {\n if (record.decision !== undefined) {\n seqs.push(record.decision.seq);\n }\n if (\n record.terminal !== undefined &&\n (record.terminal._tag === \"Completed\" || record.terminal._tag === \"Failed\")\n ) {\n seqs.push(record.terminal.seq);\n }\n }\n return uniqueSequenceNumbers(seqs);\n};\n\n/** Decode the framework reducer checkpoint and rebuild derived scheduler queues. */\nexport const decodeReducedStateCheckpoint = (\n payload: unknown,\n referencedEvents: ReadonlyArray<CommittedDurableEvent>,\n): ReducedState => {\n const checkpoint = payload as ReducedStateCheckpointPayload;\n const eventsBySeq = committedEventMapBySeq(referencedEvents);\n const commands = decodeCheckpointCommandRecords(checkpoint.commands ?? [], eventsBySeq);\n const runs = new Map(checkpoint.runs ?? []);\n const messages = decodeCheckpointMessageRecords(checkpoint.messages ?? [], eventsBySeq);\n return {\n lastSeq: SequenceNumber.make(Number(checkpoint.lastSeq ?? 0)),\n ...(checkpoint.modelSelection === undefined\n ? {}\n : { modelSelection: checkpoint.modelSelection }),\n commands,\n runs,\n recoveryContinuations: new Map(checkpoint.recoveryContinuations ?? []),\n turns: new Map(checkpoint.turns ?? []),\n inferences: new Map(checkpoint.inferences ?? []),\n toolCalls: decodeCheckpointToolCallRecords(checkpoint.toolCalls ?? [], eventsBySeq),\n messages,\n stopRequests: new Map(checkpoint.stopRequests ?? []),\n compactions: new Map(checkpoint.compactions ?? []),\n context: checkpoint.context ?? { version: ContextVersion.make(0) },\n tokenConsumption: decodeTokenConsumptionState(checkpoint.tokenConsumption),\n commandQueues: deriveCommandQueues({ commands, runs, messages }),\n };\n};\n\nconst encodeCheckpointCommandRecord = (\n record: CommandRecord,\n): ReducedStateCheckpointCommandRecord => {\n const { command: _command, ...checkpoint } = record;\n return checkpoint;\n};\n\nconst encodeCheckpointMessageRecord = (\n record: MessageRecord,\n): ReducedStateCheckpointMessageRecord => {\n switch (record._tag) {\n case \"System\": {\n const { content: _content, ...checkpoint } = record;\n return checkpoint;\n }\n case \"User\": {\n const { content: _content, ...checkpoint } = record;\n return checkpoint;\n }\n case \"Steering\": {\n const { content: _content, ...checkpoint } = record;\n return checkpoint;\n }\n case \"Assistant\": {\n const { content: _content, promptParts: _promptParts, ...checkpoint } = record;\n return checkpoint;\n }\n case \"AssistantPartial\": {\n const { content: _content, promptParts: _promptParts, ...checkpoint } = record;\n return checkpoint;\n }\n default:\n return assertNever(record, \"checkpoint message record\");\n }\n};\n\nconst encodeCheckpointToolCallRecord = (\n record: ToolCallRecord,\n): ReducedStateCheckpointToolCallRecord => ({\n toolCallId: record.toolCallId,\n ...(record.decision === undefined\n ? {}\n : { decision: encodeCheckpointToolDecision(record.decision) }),\n ...(record.durationMs === undefined ? {} : { durationMs: record.durationMs }),\n ...(record.startedAtMs === undefined ? {} : { startedAtMs: record.startedAtMs }),\n ...(record.startedSeq === undefined ? {} : { startedSeq: record.startedSeq }),\n ...(record.terminalAtMs === undefined ? {} : { terminalAtMs: record.terminalAtMs }),\n ...(record.terminal === undefined\n ? {}\n : { terminal: encodeCheckpointToolTerminal(record.terminal) }),\n});\n\nconst encodeCheckpointToolDecision = (\n decision: ToolDecision,\n): ReducedStateCheckpointToolDecision => {\n switch (decision._tag) {\n case \"Created\": {\n const { params: _params, promptPart: _promptPart, ...checkpoint } = decision;\n return checkpoint;\n }\n case \"Rejected\": {\n const { promptPart: _promptPart, ...checkpoint } = decision;\n return checkpoint;\n }\n default:\n return assertNever(decision, \"checkpoint tool decision\");\n }\n};\n\nconst encodeCheckpointToolTerminal = (\n terminal: ToolTerminal,\n): ReducedStateCheckpointToolTerminal => {\n switch (terminal._tag) {\n case \"Completed\": {\n const { result: _result, promptPart: _promptPart, ...checkpoint } = terminal;\n return checkpoint;\n }\n case \"Failed\": {\n const { error: _error, promptPart: _promptPart, ...checkpoint } = terminal;\n return checkpoint;\n }\n default:\n return assertNever(terminal, \"checkpoint tool terminal\");\n }\n};\n\nconst decodeCheckpointCommandRecords = (\n records: ReducedStateCheckpointPayload[\"commands\"],\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ReadonlyMap<CommandId, CommandRecord> =>\n new Map(\n records.map(([commandId, record]) => {\n if (record.admittedSeq === undefined) {\n return [commandId, record];\n }\n const admitted = reduceSingleCheckpointEvent(\n eventsBySeq,\n record.admittedSeq,\n commandAdmittedEventType,\n ).commands.get(commandId);\n if (admitted?.command === undefined) {\n throw new Error(`Checkpoint command ${commandId} missing admission payload`);\n }\n return [commandId, { ...record, command: admitted.command }];\n }),\n );\n\nconst decodeCheckpointMessageRecords = (\n records: ReducedStateCheckpointPayload[\"messages\"],\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ReadonlyMap<MessageId, MessageRecord> =>\n new Map(\n records.map(([messageId, record]) => {\n const message = reduceSingleCheckpointEvent(\n eventsBySeq,\n record.seq,\n checkpointMessageEventType(record),\n ).messages.get(messageId);\n if (message === undefined) {\n throw new Error(`Checkpoint message ${messageId} missing message payload`);\n }\n return [messageId, { ...message, ...record } as MessageRecord];\n }),\n );\n\nconst decodeCheckpointToolCallRecords = (\n records: ReducedStateCheckpointPayload[\"toolCalls\"],\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ReadonlyMap<ToolCallId, ToolCallRecord> =>\n new Map(\n records.map(([toolCallId, record]) => [\n toolCallId,\n {\n toolCallId,\n ...(record.decision === undefined\n ? {}\n : { decision: decodeCheckpointToolDecision(toolCallId, record.decision, eventsBySeq) }),\n ...(record.durationMs === undefined ? {} : { durationMs: record.durationMs }),\n ...(record.startedAtMs === undefined ? {} : { startedAtMs: record.startedAtMs }),\n ...(record.startedSeq === undefined ? {} : { startedSeq: record.startedSeq }),\n ...(record.terminalAtMs === undefined ? {} : { terminalAtMs: record.terminalAtMs }),\n ...(record.terminal === undefined\n ? {}\n : { terminal: decodeCheckpointToolTerminal(toolCallId, record.terminal, eventsBySeq) }),\n },\n ]),\n );\n\nconst decodeCheckpointToolDecision = (\n toolCallId: ToolCallId,\n decision: ReducedStateCheckpointToolDecision,\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ToolDecision => {\n const hydrated = reduceSingleCheckpointEvent(\n eventsBySeq,\n decision.seq,\n decision._tag === \"Created\" ? toolCallCreatedEventType : toolCallRejectedEventType,\n ).toolCalls.get(toolCallId)?.decision;\n if (hydrated === undefined || hydrated._tag !== decision._tag) {\n throw new Error(`Checkpoint tool decision ${toolCallId} missing ${decision._tag} payload`);\n }\n return hydrated;\n};\n\nconst decodeCheckpointToolTerminal = (\n toolCallId: ToolCallId,\n terminal: ReducedStateCheckpointToolTerminal,\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ToolTerminal => {\n const hydrated = reduceSingleCheckpointEvent(\n eventsBySeq,\n terminal.seq,\n terminal._tag === \"Completed\" ? toolCallCompletedEventType : toolCallFailedEventType,\n ).toolCalls.get(toolCallId)?.terminal;\n if (hydrated === undefined || hydrated._tag !== terminal._tag) {\n throw new Error(`Checkpoint tool terminal ${toolCallId} missing ${terminal._tag} payload`);\n }\n return hydrated;\n};\n\nconst checkpointMessageEventType = (record: ReducedStateCheckpointMessageRecord) => {\n switch (record._tag) {\n case \"System\":\n return systemMessageCommittedEventType;\n case \"User\":\n return record.requestedDisposition === undefined\n ? userMessageCommittedEventType\n : userMessageSubmittedEventType;\n case \"Steering\":\n return steeringMessageQueuedEventType;\n case \"Assistant\":\n return record.imported === true\n ? assistantMessageImportedEventType\n : assistantMessageCommittedEventType;\n case \"AssistantPartial\":\n return assistantPartialCommittedEventType;\n default:\n return assertNever(record, \"checkpoint message type\");\n }\n};\n\nconst reduceSingleCheckpointEvent = (\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n seq: SequenceNumber,\n expectedType: string,\n): ReducedState => {\n const event = eventsBySeq.get(Number(seq));\n if (event === undefined) {\n throw new Error(`Checkpoint reference seq ${seq} is missing`);\n }\n if (event.event.type !== expectedType) {\n throw new Error(\n `Checkpoint reference seq ${seq} expected ${expectedType}; got ${event.event.type}`,\n );\n }\n return foldReducedState(initialReducedState, [event]);\n};\n\nconst committedEventMapBySeq = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<number, CommittedDurableEvent> =>\n new Map(events.map((event) => [Number(event.position.seq), event]));\n\nconst uniqueSequenceNumbers = (\n seqs: ReadonlyArray<SequenceNumber>,\n): ReadonlyArray<SequenceNumber> =>\n Array.from(new Set(seqs.map((seq) => Number(seq))))\n .sort((left, right) => left - right)\n .map((seq) => SequenceNumber.make(seq));\n\nconst decodeTokenConsumptionState = (\n value: TokenConsumptionState | undefined,\n): TokenConsumptionState => value ?? emptyTokenConsumptionState;\n\n/** Fold newly committed durable events into the canonical replay state. */\nexport const foldReducedState = (\n state: ReducedState,\n committed: ReadonlyArray<CommittedDurableEvent>,\n): ReducedState => {\n let lastSeq = state.lastSeq;\n let modelSelection = state.modelSelection;\n const commands = new Map(state.commands);\n const runs = new Map(state.runs);\n const recoveryContinuations = new Map(state.recoveryContinuations);\n const turns = new Map(state.turns);\n const inferences = new Map(state.inferences);\n const toolCalls = new Map(state.toolCalls);\n const messages = new Map(state.messages);\n const stopRequests = new Map(state.stopRequests);\n const compactions = new Map(state.compactions);\n let context = state.context;\n let tokenConsumption = state.tokenConsumption;\n\n for (const entry of committed) {\n lastSeq = entry.position.seq;\n const { event } = entry;\n if (event.namespace !== effectDurableAgentNamespace) {\n continue;\n }\n\n const payload = event.payload as any;\n const seq = entry.position.seq;\n const eventCreatedAtMs = Number(event.createdAtMs);\n\n switch (event.type) {\n case commandAdmittedEventType: {\n const { command } = payload;\n const commandId = requireAdmittedCommandId(command);\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n admittedSeq: seq,\n admissionTrace: event.trace,\n command,\n }));\n break;\n }\n case commandStartedEventType: {\n const { commandId } = payload;\n upsert(commands, commandId, { commandId }, (record) => ({ ...record, startedSeq: seq }));\n break;\n }\n case commandCompletedEventType: {\n const { commandId } = payload;\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n terminal: { _tag: \"Completed\", seq } as CommandTerminal,\n }));\n break;\n }\n case commandFailedEventType: {\n const { commandId, error } = payload;\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n terminal: { _tag: \"Failed\", seq, error } as CommandTerminal,\n }));\n break;\n }\n case commandCancelledEventType: {\n const { commandId, reason } = payload;\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n terminal: { _tag: \"Cancelled\", seq, reason } as CommandTerminal,\n }));\n break;\n }\n case runStartedEventType: {\n const { runId, commandIds, trace } = payload;\n modelSelection ??= payload.modelSelection;\n const terminal = runs.get(runId)?.terminal;\n runs.set(runId, {\n runId,\n commandIds,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n trace,\n modelSelection: payload.modelSelection,\n ...(terminal === undefined ? {} : { terminal }),\n });\n break;\n }\n case runCompletedEventType: {\n const { runId } = payload;\n updateExisting(runs, runId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Completed\", seq } as RunTerminal,\n }));\n break;\n }\n case runFailedEventType: {\n const { runId, error } = payload;\n updateExisting(runs, runId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Failed\", seq, error } as RunTerminal,\n }));\n break;\n }\n case runInterruptedEventType: {\n const { runId, reason } = payload;\n updateExisting(runs, runId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Interrupted\", seq, reason } as RunTerminal,\n }));\n break;\n }\n case turnStartedEventType: {\n const { runId, turnId, inputMessageIds } = payload;\n const terminal = turns.get(turnId)?.terminal;\n turns.set(turnId, {\n runId,\n turnId,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n ...(terminal === undefined ? {} : { terminal }),\n });\n for (const messageId of inputMessageIds ?? []) {\n const message = messages.get(messageId);\n if (message?._tag === \"Steering\" || message?._tag === \"User\") {\n messages.set(messageId, { ...message, consumedSeq: seq, consumedTurnId: turnId });\n }\n }\n break;\n }\n case turnCompletedEventType: {\n const { turnId, usage } = payload;\n updateExisting(turns, turnId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Completed\",\n seq,\n ...(usage === undefined ? {} : { usage }),\n } as TurnTerminal,\n }));\n break;\n }\n case turnFailedEventType: {\n const { turnId, error } = payload;\n updateExisting(turns, turnId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Failed\", seq, error } as TurnTerminal,\n }));\n break;\n }\n case turnStoppedEventType: {\n const { turnId, reason } = payload;\n updateExisting(turns, turnId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Stopped\", seq, reason } as TurnTerminal,\n }));\n break;\n }\n case inferenceStartedEventType: {\n const { runId, turnId, inferenceId } = payload;\n const terminal = inferences.get(inferenceId)?.terminal;\n inferences.set(inferenceId, {\n runId,\n turnId,\n inferenceId: inferenceId,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n ...(terminal === undefined ? {} : { terminal }),\n });\n break;\n }\n case inferenceCompletedEventType: {\n const { inferenceId, usage } = payload;\n const previouslyCompleted = inferences.get(inferenceId)?.terminal?._tag === \"Completed\";\n updateExisting(inferences, inferenceId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Completed\",\n seq,\n ...(usage === undefined ? {} : { usage }),\n } as InferenceTerminal,\n }));\n if (!previouslyCompleted && inferences.get(inferenceId)?.terminal?._tag === \"Completed\") {\n const model = runs.get(payload.runId)?.modelSelection;\n if (model !== undefined) tokenConsumption = addModelUsage(tokenConsumption, model, usage);\n }\n break;\n }\n case inferenceFailedEventType: {\n const { inferenceId, error } = payload;\n updateExisting(inferences, inferenceId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Failed\", seq, error } as InferenceTerminal,\n }));\n break;\n }\n case toolCallCreatedEventType: {\n const { runId, turnId, inferenceId, toolCallId, promptPart } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n decision: {\n _tag: \"Created\",\n seq,\n runId,\n turnId,\n inferenceId: inferenceId,\n providerPartId: promptPart.id,\n toolName: promptPart.name,\n params: promptPart.params,\n providerExecuted: promptPart.providerExecuted,\n promptPart,\n } as ToolDecision,\n }));\n break;\n }\n case toolCallRejectedEventType: {\n const { runId, turnId, inferenceId, toolCallId, promptPart } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n decision: {\n _tag: \"Rejected\",\n seq,\n runId,\n turnId,\n inferenceId: inferenceId,\n providerPartId: promptPart.id,\n toolName: promptPart.name,\n reason: promptPart.result.reason,\n modelFeedback: promptPart.result.modelFeedback,\n promptPart,\n } as ToolDecision,\n }));\n break;\n }\n case toolCallStartedEventType: {\n const { toolCallId } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n }));\n break;\n }\n case toolCallCompletedEventType: {\n const { toolCallId, promptPart } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Completed\",\n seq,\n result: promptPart.result,\n promptPart,\n } as ToolTerminal,\n }));\n break;\n }\n case toolCallFailedEventType: {\n const { toolCallId, promptPart, error } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Failed\",\n seq,\n error: error ?? promptPart.result,\n promptPart,\n } as ToolTerminal,\n }));\n break;\n }\n case systemMessageCommittedEventType: {\n const { messageId, content } = payload;\n messages.set(messageId, {\n _tag: \"System\",\n messageId,\n content,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case userMessageCommittedEventType: {\n const { commandId, messageId, content } = payload;\n messages.set(messageId, {\n _tag: \"User\",\n messageId,\n commandId,\n content,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case userMessageSubmittedEventType: {\n const { commandId, messageId, disposition: requestedDisposition, content } = payload;\n messages.set(messageId, {\n _tag: \"User\",\n messageId,\n commandId,\n content,\n requestedDisposition,\n disposition: requestedDisposition,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case userMessagePromotedEventType: {\n const { messageId } = payload;\n const message = messages.get(messageId);\n if (\n (message?._tag === \"User\" && message.disposition === \"queue\") ||\n (message?._tag === \"Steering\" && message.pausedByCommandId !== undefined)\n ) {\n const {\n pausedByCommandId: _pausedByCommandId,\n pausedSeq: _pausedSeq,\n ...unpausedMessage\n } = message;\n messages.set(messageId, {\n ...unpausedMessage,\n ...(message._tag === \"User\" ? { disposition: \"steer\" as const } : {}),\n promotedSeq: seq,\n });\n }\n break;\n }\n case userMessageCancelledEventType: {\n const { commandId, messageId, reason } = payload;\n const message = messages.get(messageId);\n if (message?._tag === \"User\" || message?._tag === \"Steering\") {\n messages.set(messageId, {\n ...message,\n cancelledSeq: seq,\n cancelledByCommandId: commandId,\n cancellationReason: reason,\n });\n }\n break;\n }\n case messageQueuePausedEventType:\n case pendingMessagesPausedEventType: {\n const messageIds = payload.messageIds;\n const interruptionCommandId =\n event.type === messageQueuePausedEventType\n ? payload.stopCommandId\n : payload.interruptionCommandId;\n for (const messageId of messageIds) {\n const message = messages.get(messageId);\n if (\n (message?._tag === \"User\" || message?._tag === \"Steering\") &&\n message.consumedSeq === undefined &&\n message.cancelledSeq === undefined\n ) {\n messages.set(messageId, {\n ...message,\n ...(message._tag === \"User\" ? { disposition: \"queue\" as const } : {}),\n pausedSeq: seq,\n pausedByCommandId: interruptionCommandId,\n });\n }\n }\n break;\n }\n case steeringMessageQueuedEventType: {\n const { commandId, messageId, runId, content } = payload;\n messages.set(messageId, {\n _tag: \"Steering\",\n messageId,\n commandId,\n runId,\n content,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case steeringMessageCancelledEventType: {\n const { messageId, reason } = payload;\n const message = messages.get(messageId);\n if (message?._tag === \"Steering\") {\n messages.set(messageId, { ...message, cancelledSeq: seq, cancellationReason: reason });\n }\n break;\n }\n case assistantMessageCommittedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts } = payload;\n messages.set(messageId, {\n _tag: \"Assistant\",\n messageId,\n runId,\n turnId,\n inferenceId: inferenceId,\n content: assistantContentFromPromptParts(promptParts),\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n promptParts,\n seq,\n });\n break;\n }\n case assistantMessageImportedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts } = payload;\n messages.set(messageId, {\n _tag: \"Assistant\",\n messageId,\n runId,\n turnId,\n inferenceId,\n imported: true,\n content: assistantContentFromPromptParts(promptParts),\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n promptParts,\n seq,\n });\n break;\n }\n case assistantPartialCommittedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts, reason } = payload;\n messages.set(messageId, {\n _tag: \"AssistantPartial\",\n messageId,\n runId,\n turnId,\n inferenceId: inferenceId,\n content: assistantContentFromPromptParts(promptParts),\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n promptParts,\n reason,\n seq,\n });\n break;\n }\n case stopTurnRequestedEventType: {\n const { commandId, runId, turnId } = payload;\n stopRequests.set(commandId, {\n commandId,\n requestedSeq: seq,\n ...(runId === undefined ? {} : { requestedRunId: runId }),\n ...(turnId === undefined ? {} : { requestedTurnId: turnId }),\n ...appliedFields(stopRequests.get(commandId)),\n });\n break;\n }\n case stopTurnAppliedEventType: {\n const { commandId, runId, turnId, inferenceId } = payload;\n const existing = stopRequests.get(commandId);\n stopRequests.set(commandId, {\n commandId,\n requestedSeq: existing?.requestedSeq ?? seq,\n ...(existing?.requestedRunId === undefined\n ? {}\n : { requestedRunId: existing.requestedRunId }),\n ...(existing?.requestedTurnId === undefined\n ? {}\n : { requestedTurnId: existing.requestedTurnId }),\n appliedSeq: seq,\n appliedRunId: runId,\n appliedTurnId: turnId,\n ...(inferenceId === undefined ? {} : { appliedInferenceId: inferenceId }),\n });\n break;\n }\n case contextProjectedEventType: {\n const { contextVersion } = payload;\n context = { ...context, version: contextVersion };\n break;\n }\n case compactionRequestedEventType: {\n const { compactionId, sourceFromSeq, sourceToSeq } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n requestedSeq: seq,\n sourceFromSeq,\n sourceToSeq,\n }));\n break;\n }\n case compactionStartedEventType: {\n const { compactionId } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n startedSeq: seq,\n }));\n break;\n }\n case summaryCreatedEventType: {\n const { compactionId, summaryId, sourceFromSeq, sourceToSeq } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n summaryCreatedSeq: seq,\n summaryId,\n sourceFromSeq,\n sourceToSeq,\n }));\n break;\n }\n case contextRebasedEventType: {\n const { compactionId, summaryId, contextVersion, retainedFromContextSeq } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n summaryId,\n rebasedSeq: seq,\n contextVersion,\n }));\n pruneForContextRebase(\n {\n commands,\n runs,\n recoveryContinuations,\n turns,\n inferences,\n toolCalls,\n messages,\n stopRequests,\n compactions,\n },\n retainedFromContextSeq,\n summaryId,\n );\n context = {\n version: contextVersion,\n currentSummaryId: summaryId,\n };\n break;\n }\n case compactionCompletedEventType: {\n const { compactionId } = payload;\n if (\n compactions.get(compactionId)?.terminal?._tag !== \"Completed\" &&\n payload.modelSelection !== undefined\n ) {\n tokenConsumption = addModelUsage(tokenConsumption, payload.modelSelection, payload.usage);\n }\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n terminal: { _tag: \"Completed\", seq } as CompactionTerminal,\n }));\n break;\n }\n case compactionFailedEventType: {\n const { compactionId, error } = payload;\n if (payload.modelSelection !== undefined) {\n tokenConsumption = addModelUsage(tokenConsumption, payload.modelSelection, payload.usage);\n }\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n terminal: { _tag: \"Failed\", seq, error } as CompactionTerminal,\n }));\n const failed = compactions.get(compactionId);\n if (failed?.summaryId === undefined || failed.summaryId !== context.currentSummaryId) {\n compactions.delete(compactionId);\n }\n break;\n }\n case recoveryCompletedEventType: {\n const { continuation } = payload;\n if (continuation !== undefined) {\n recoveryContinuations.set(continuation.replacementRunId, { ...continuation, seq });\n }\n break;\n }\n case sessionConfiguredEventType:\n modelSelection ??= payload.modelSelection;\n break;\n case baseStateRequestedEventType:\n case baseStateCreatedEventType:\n case baseStateFailedEventType:\n break;\n default:\n assertNever(event as never, \"reduced-state durable event\");\n }\n }\n\n return {\n lastSeq,\n ...(modelSelection === undefined ? {} : { modelSelection }),\n commands,\n runs,\n recoveryContinuations,\n turns,\n inferences,\n toolCalls,\n messages,\n stopRequests,\n compactions,\n context,\n tokenConsumption,\n commandQueues: deriveCommandQueues({ commands, runs, messages }),\n };\n};\n\n/** Fold committed events from genesis into a fresh `ReducedState`. */\nexport const reduceCommittedEvents = (committed: ReadonlyArray<CommittedDurableEvent>) =>\n foldReducedState(initialReducedState, committed);\n\ninterface MutableReplayMaps {\n readonly commands: Map<CommandId, CommandRecord>;\n readonly runs: Map<RunId, RunRecord>;\n readonly recoveryContinuations: Map<RunId, RecoveryContinuationRecord>;\n readonly turns: Map<TurnId, TurnRecord>;\n readonly inferences: Map<InferenceId, InferenceRecord>;\n readonly toolCalls: Map<ToolCallId, ToolCallRecord>;\n readonly messages: Map<MessageId, MessageRecord>;\n readonly stopRequests: Map<CommandId, StopRequestRecord>;\n readonly compactions: Map<CompactionId, CompactionRecord>;\n}\n\n/** Drop runtime state made model-invisible by a context rebase; storage remains append-only. */\nconst pruneForContextRebase = (\n maps: MutableReplayMaps,\n retainedFromContextSeq: SequenceNumber,\n currentSummaryId: SummaryId,\n): void => {\n for (const [messageId, message] of maps.messages) {\n if (message._tag !== \"System\" && messagePruneSeq(message) < retainedFromContextSeq) {\n maps.messages.delete(messageId);\n }\n }\n\n for (const [toolCallId, tool] of maps.toolCalls) {\n const terminalSeq = tool.terminal?.seq;\n if (terminalSeq !== undefined && terminalSeq < retainedFromContextSeq) {\n maps.toolCalls.delete(toolCallId);\n }\n }\n\n for (const [inferenceId, inference] of maps.inferences) {\n if (inference.terminal !== undefined && inference.terminal.seq < retainedFromContextSeq) {\n maps.inferences.delete(inferenceId);\n }\n }\n\n for (const [turnId, turn] of maps.turns) {\n if (turn.terminal !== undefined && turn.terminal.seq < retainedFromContextSeq) {\n maps.turns.delete(turnId);\n }\n }\n\n for (const [runId, run] of maps.runs) {\n if (run.terminal !== undefined && run.terminal.seq < retainedFromContextSeq) {\n maps.runs.delete(runId);\n }\n }\n\n for (const replacementRunId of maps.recoveryContinuations.keys()) {\n if (!maps.runs.has(replacementRunId)) {\n maps.recoveryContinuations.delete(replacementRunId);\n }\n }\n\n for (const [commandId, command] of maps.commands) {\n if (command.terminal !== undefined && command.terminal.seq < retainedFromContextSeq) {\n maps.commands.delete(commandId);\n }\n }\n\n for (const [commandId, request] of maps.stopRequests) {\n if (request.appliedSeq !== undefined && request.appliedSeq < retainedFromContextSeq) {\n maps.stopRequests.delete(commandId);\n }\n }\n\n for (const [compactionId, compaction] of maps.compactions) {\n if (compaction.terminal !== undefined && compaction.summaryId !== currentSummaryId) {\n maps.compactions.delete(compactionId);\n }\n }\n};\n\nconst messagePruneSeq = (message: Exclude<MessageRecord, { readonly _tag: \"System\" }>): number => {\n if (message._tag === \"Steering\") {\n return message.consumedSeq ?? message.cancelledSeq ?? Number.POSITIVE_INFINITY;\n }\n return message.seq;\n};\n\n/** Pending admitted commands in deterministic scheduler order. */\nexport const pendingCommands = (state: ReducedState): ReadonlyArray<PendingCommand> =>\n state.commandQueues.pendingCommands;\n\n/** First pending StopTurn control command, when one is waiting. */\nexport const pendingStopCommand = (state: ReducedState): PendingCommand | undefined =>\n state.commandQueues.activeControlCommands.find((command) => command.command._tag === \"StopTurn\");\n\n/** Currently active command evidence, if any unfinished command is blocking FIFO work. */\nexport const activeCommand = (state: ReducedState): ActiveCommandEvidence | undefined =>\n state.commandQueues.active;\n\n/** Active run/turn/inference identity owned by a specific active command. */\nexport const activeTurnIdentityForCommand = (\n state: ReducedState,\n commandId: CommandId,\n): ActiveTurnIdentity | undefined => {\n const run = findLast(Array.from(state.runs.values()), (candidate): candidate is RunRecord =>\n candidate.commandIds.includes(commandId),\n );\n if (run === undefined) {\n return undefined;\n }\n\n const turn = findLast(\n Array.from(state.turns.values()),\n (candidate): candidate is TurnRecord => candidate.runId === run.runId,\n );\n if (turn === undefined) {\n return undefined;\n }\n\n const inference = findLast(\n Array.from(state.inferences.values()),\n (candidate): candidate is InferenceRecord =>\n candidate.runId === run.runId && candidate.turnId === turn.turnId,\n );\n\n return {\n runId: run.runId,\n turnId: turn.turnId,\n ...(inference === undefined ? {} : { inferenceId: inference.inferenceId }),\n };\n};\n\n/** Classify unfinished durable lifecycles that recovery may need to repair. */\nexport const classifyRecoverableWork = (state: ReducedState): RecoverableWork => {\n const activeCommands = Array.from(state.commands.values()).filter(\n (command) => command.startedSeq !== undefined && command.terminal === undefined,\n );\n const activeRuns = Array.from(state.runs.values()).filter((run) => run.terminal === undefined);\n const activeTurns = Array.from(state.turns.values()).filter(\n (turn) => turn.terminal === undefined,\n );\n const activeInferences = Array.from(state.inferences.values()).filter(\n (inference) => inference.terminal === undefined,\n );\n const openToolCalls = Array.from(state.toolCalls.values()).filter(\n (tool) =>\n tool.decision?._tag === \"Created\" &&\n !tool.decision.providerExecuted &&\n tool.terminal === undefined,\n );\n const runningToolCalls = openToolCalls.filter((tool) => tool.startedSeq !== undefined);\n const pendingStopRequests = Array.from(state.stopRequests.values()).filter(\n (request) =>\n request.appliedSeq === undefined &&\n state.commands.get(request.commandId)?.terminal === undefined,\n );\n const openCompactions = Array.from(state.compactions.values()).filter(\n (compaction) => compaction.terminal === undefined,\n );\n\n return {\n activeCommands,\n activeRuns,\n activeTurns,\n activeInferences,\n openToolCalls,\n runningToolCalls,\n pendingStopRequests,\n openCompactions,\n };\n};\n\nconst assistantContentFromPromptParts = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart>,\n): AssistantMessageContent => {\n const text = promptParts\n .filter((part): part is Prompt.TextPart => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n const reasoning = promptParts\n .filter((part): part is Prompt.ReasoningPart => part.type === \"reasoning\")\n .map((part) => part.text)\n .join(\"\");\n return {\n text,\n ...(reasoning.length === 0 ? {} : { reasoning }),\n };\n};\n\nconst findLast = <A, B extends A>(\n items: ReadonlyArray<A>,\n predicate: (item: A) => item is B,\n): B | undefined => {\n for (let index = items.length - 1; index >= 0; index -= 1) {\n const item = items[index] as A;\n if (predicate(item)) {\n return item;\n }\n }\n return undefined;\n};\n\nconst requireAdmittedCommandId = (command: EDACommandValue): CommandId => {\n if (command.commandId !== undefined) {\n return command.commandId;\n }\n throw new Error(\"CommandAdmitted command is missing a framework commandId\");\n};\n\nconst terminalTiming = (\n record: Pick<LifecycleTiming, \"startedAtMs\">,\n terminalAtMs: number,\n): LifecycleTiming => ({\n terminalAtMs,\n ...(record.startedAtMs === undefined\n ? {}\n : { durationMs: Math.max(0, terminalAtMs - record.startedAtMs) }),\n});\n\nconst upsert = <K, V>(map: Map<K, V>, key: K, fallback: V, update: (record: V) => V) => {\n map.set(key, update(map.get(key) ?? fallback));\n};\n\nconst updateExisting = <K, V>(map: Map<K, V>, key: K, update: (record: V) => V) => {\n const record = map.get(key);\n if (record !== undefined) {\n map.set(key, update(record));\n }\n};\n\nconst appliedFields = (record: StopRequestRecord | undefined) =>\n record?.appliedSeq === undefined\n ? {}\n : {\n appliedSeq: record.appliedSeq,\n appliedRunId: record.appliedRunId,\n appliedTurnId: record.appliedTurnId,\n ...(record.appliedInferenceId === undefined\n ? {}\n : { appliedInferenceId: record.appliedInferenceId }),\n };\n"],"mappings":";;;;;;AAAA,MAAM,oBAAoB,UAAyB;CACjD,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;AAGA,MAAa,oBAAoB,OAAc,4BAC7C,IAAI,MAAM,aAAa,QAAQ,IAAI,iBAAiB,KAAK,GAAG;;AAG9D,MAAa,eAAe,OAAc,YAA2B;CACnE,MAAM,iBAAiB,OAAO,OAAO;AACvC;;;AC2WA,MAAM,6BAAoD,EACxD,SAAS,CAAC,EACZ;;AAGA,MAAa,sBAAoC;CAC/C,SAAS,eAAe,KAAK,CAAC;CAC9B,0BAAU,IAAI,IAAI;CAClB,sBAAM,IAAI,IAAI;CACd,uCAAuB,IAAI,IAAI;CAC/B,uBAAO,IAAI,IAAI;CACf,4BAAY,IAAI,IAAI;CACpB,2BAAW,IAAI,IAAI;CACnB,0BAAU,IAAI,IAAI;CAClB,8BAAc,IAAI,IAAI;CACtB,6BAAa,IAAI,IAAI;CACrB,SAAS,EAAE,SAAS,eAAe,KAAK,CAAC,EAAE;CAC3C,kBAAkB;CAClB,eAAe;AACjB;;AAGA,MAAa,mCAAmC;;AAGhD,MAAa,4CAA4C;;AAwDzD,MAAa,gCACX,WACmC;CACnC,SA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E;CACV,MAAM,YAAY,YACf,QAAQ,SAAuC,KAAK,SAAS,WAAW,EACxE,KAAK,SAAS,KAAK,IAAI,EACvB,KAAK,EAAE;CACV,OAAO;EACL;EACA,GAAI,UAAU,WAAW,IAAI,CAAC,IAAI,EAAE,UAAU;CAChD;AACF;AAEA,MAAM,YACJ,OACA,cACkB;CAClB,KAAK,IAAI,QAAQ,MAAM,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG;EACzD,MAAM,OAAO,MAAM;EACnB,IAAI,UAAU,IAAI,GAChB,OAAO;CAEX;AAEF;AAEA,MAAM,4BAA4B,YAAwC;CACxE,IAAI,QAAQ,cAAc,KAAA,GACxB,OAAO,QAAQ;CAEjB,MAAM,IAAI,MAAM,0DAA0D;AAC5E;AAEA,MAAM,kBACJ,QACA,kBACqB;CACrB;CACA,GAAI,OAAO,gBAAgB,KAAA,IACvB,CAAC,IACD,EAAE,YAAY,KAAK,IAAI,GAAG,eAAe,OAAO,WAAW,EAAE;AACnE;AAEA,MAAM,UAAgB,KAAgB,KAAQ,UAAa,WAA6B;CACtF,IAAI,IAAI,KAAK,OAAO,IAAI,IAAI,GAAG,KAAK,QAAQ,CAAC;AAC/C;AAEA,MAAM,kBAAwB,KAAgB,KAAQ,WAA6B;CACjF,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,IAAI,WAAW,KAAA,GACb,IAAI,IAAI,KAAK,OAAO,MAAM,CAAC;AAE/B;AAEA,MAAM,iBAAiB,WACrB,QAAQ,eAAe,KAAA,IACnB,CAAC,IACD;CACE,YAAY,OAAO;CACnB,cAAc,OAAO;CACrB,eAAe,OAAO;CACtB,GAAI,OAAO,uBAAuB,KAAA,IAC9B,CAAC,IACD,EAAE,oBAAoB,OAAO,mBAAmB;AACtD"}
@@ -1,4 +1,4 @@
1
- import { t as CommittedDurableEvent } from "./session-store-ofm8FFxs.js";
1
+ import { t as CommittedDurableEvent } from "./session-store-Cpi_NwTR.js";
2
2
  import * as Context from "effect/Context";
3
3
  import * as Layer from "effect/Layer";
4
4
  import * as Schema from "effect/Schema";
@@ -76,4 +76,4 @@ declare class EDAReducerRegistry extends EDAReducerRegistry_base {
76
76
  declare const getEDAReducerState: <State, Name extends string>(snapshot: EDAReducerStateSnapshot, reducer: EDAReducer<State, Name>) => State;
77
77
  //#endregion
78
78
  export { EDAReducerStateSnapshot as a, decodeReducerState as c, encodeReducerState as d, getEDAReducerState as f, EDAReducerRegistryShape as i, defineEDAReducerRegistry as l, EDAReducerDefinition as n, EDAReducersFor as o, reducerSchemaVersion as p, EDAReducerRegistry as r, EDATypedReducerRegistry as s, EDAReducer as t, edaReservedReducerNamePrefix as u };
79
- //# sourceMappingURL=reducer-registry--vQFATXb.d.ts.map
79
+ //# sourceMappingURL=reducer-registry-aFjz_ZLT.d.ts.map
@@ -0,0 +1,21 @@
1
+ import * as Context from "effect/Context";
2
+ import * as Effect from "effect/Effect";
3
+ import * as Layer from "effect/Layer";
4
+ import * as Schema from "effect/Schema";
5
+ //#region src/domain/run-scheduling.ts
6
+ /**
7
+ * Permission to start the selected run in this session's current runtime.
8
+ * Only immediate local execution is supported; this value is never persisted.
9
+ */
10
+ const LocalRunResolution = Schema.TaggedStruct("Local", {});
11
+ //#endregion
12
+ //#region src/services/run-scheduler.ts
13
+ /** Replaceable run-start integration, independent of persistence and host SDKs. */
14
+ var RunScheduler = class RunScheduler extends Context.Service()("@effect-durable-agent/RunScheduler") {
15
+ /** Preserve local execution without allocating IDs, issuing commands, or writing events. */
16
+ static Immediate = Layer.succeed(RunScheduler, { resolve: () => Effect.succeed(LocalRunResolution.make({})) });
17
+ };
18
+ //#endregion
19
+ export { LocalRunResolution as n, RunScheduler as t };
20
+
21
+ //# sourceMappingURL=run-scheduler-CAt7dF6C.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-scheduler-CAt7dF6C.js","names":[],"sources":["../src/domain/run-scheduling.ts","../src/services/run-scheduler.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport type { CommandId, SessionId } from \"../types/core\";\n\n/**\n * Identity of the admitted work selected by dispatch or recovery for a new run.\n * This is not a durable request identity: recovery can resolve the same command again.\n */\nexport interface RunSchedulingInput {\n readonly sessionId: SessionId;\n readonly commandId: CommandId;\n}\n\n/**\n * Permission to start the selected run in this session's current runtime.\n * Only immediate local execution is supported; this value is never persisted.\n */\nexport const LocalRunResolution = Schema.TaggedStruct(\"Local\", {});\nexport type LocalRunResolution = typeof LocalRunResolution.Type;\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { LocalRunResolution, type RunSchedulingInput } from \"../domain/run-scheduling\";\n\nexport { LocalRunResolution, type RunSchedulingInput } from \"../domain/run-scheduling\";\n\n/**\n * Run-start boundary called by SessionState after pure dispatch or recovery policy\n * selects work, before allocating its run ID or committing RunStarted.\n *\n * Resolution must finish promptly with local permission. It must not wait for an\n * external approval: the caller owns the serialized control loop. Deferred scheduling\n * needs a future durable protocol, not a suspended effect behind this interface.\n * Calls may repeat after a restart; command identity is not an exactly-once key.\n */\nexport interface RunSchedulerShape {\n readonly resolve: (input: RunSchedulingInput) => Effect.Effect<LocalRunResolution>;\n}\n\n/** Replaceable run-start integration, independent of persistence and host SDKs. */\nexport class RunScheduler extends Context.Service<RunScheduler, RunSchedulerShape>()(\n \"@effect-durable-agent/RunScheduler\",\n) {\n /** Preserve local execution without allocating IDs, issuing commands, or writing events. */\n static readonly Immediate = Layer.succeed(RunScheduler, {\n resolve: () => Effect.succeed(LocalRunResolution.make({})),\n });\n}\n"],"mappings":";;;;;;;;;AAiBA,MAAa,qBAAqB,OAAO,aAAa,SAAS,CAAC,CAAC;;;;ACKjE,IAAa,eAAb,MAAa,qBAAqB,QAAQ,QAAyC,EACjF,oCACF,EAAE;;CAEA,OAAgB,YAAY,MAAM,QAAQ,cAAc,EACtD,eAAe,OAAO,QAAQ,mBAAmB,KAAK,CAAC,CAAC,CAAC,EAC3D,CAAC;AACH"}
@@ -0,0 +1,44 @@
1
+ import { h as SessionId, n as CommandId } from "./core-CYT6DBaS.js";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+ import * as Schema from "effect/Schema";
6
+
7
+ //#region src/domain/run-scheduling.d.ts
8
+ /**
9
+ * Identity of the admitted work selected by dispatch or recovery for a new run.
10
+ * This is not a durable request identity: recovery can resolve the same command again.
11
+ */
12
+ interface RunSchedulingInput {
13
+ readonly sessionId: SessionId;
14
+ readonly commandId: CommandId;
15
+ }
16
+ /**
17
+ * Permission to start the selected run in this session's current runtime.
18
+ * Only immediate local execution is supported; this value is never persisted.
19
+ */
20
+ declare const LocalRunResolution: Schema.TaggedStruct<"Local", {}>;
21
+ type LocalRunResolution = typeof LocalRunResolution.Type;
22
+ //#endregion
23
+ //#region src/services/run-scheduler.d.ts
24
+ /**
25
+ * Run-start boundary called by SessionState after pure dispatch or recovery policy
26
+ * selects work, before allocating its run ID or committing RunStarted.
27
+ *
28
+ * Resolution must finish promptly with local permission. It must not wait for an
29
+ * external approval: the caller owns the serialized control loop. Deferred scheduling
30
+ * needs a future durable protocol, not a suspended effect behind this interface.
31
+ * Calls may repeat after a restart; command identity is not an exactly-once key.
32
+ */
33
+ interface RunSchedulerShape {
34
+ readonly resolve: (input: RunSchedulingInput) => Effect.Effect<LocalRunResolution>;
35
+ }
36
+ declare const RunScheduler_base: Context.ServiceClass<RunScheduler, "@effect-durable-agent/RunScheduler", RunSchedulerShape>;
37
+ /** Replaceable run-start integration, independent of persistence and host SDKs. */
38
+ declare class RunScheduler extends RunScheduler_base {
39
+ /** Preserve local execution without allocating IDs, issuing commands, or writing events. */
40
+ static readonly Immediate: Layer.Layer<RunScheduler, never, never>;
41
+ }
42
+ //#endregion
43
+ export { RunSchedulingInput as i, RunSchedulerShape as n, LocalRunResolution as r, RunScheduler as t };
44
+ //# sourceMappingURL=run-scheduler-xkhZyto5.d.ts.map
@@ -1,9 +1,9 @@
1
1
  import { m as SequenceNumber, n as CommandId } from "./core-CYT6DBaS.js";
2
2
  import { r as EDACommand } from "./commands-Ce1ec6kH.js";
3
- import { w as CommandFailedEvent, x as CommandCompletedEvent, y as CommandCancelledEvent } from "./durable-B7M6TD_0.js";
4
- import { t as CommittedDurableEvent } from "./session-store-ofm8FFxs.js";
5
- import { h as SessionState, r as SessionCommandAdmissionError, t as EDASubmittable } from "./session-state-Bi3oEbJU.js";
6
- import { n as EDASessionQuery, r as EDASessionQueryShape } from "./session-query-lUZQpMvM.js";
3
+ import { w as CommandFailedEvent, x as CommandCompletedEvent, y as CommandCancelledEvent } from "./durable-br2C1bWK.js";
4
+ import { t as CommittedDurableEvent } from "./session-store-Cpi_NwTR.js";
5
+ import { h as SessionState, r as SessionCommandAdmissionError, t as EDASubmittable } from "./session-state-C9YLSAso.js";
6
+ import { n as EDASessionQuery, r as EDASessionQueryShape } from "./session-query-B72HY_0L.js";
7
7
  import * as Context from "effect/Context";
8
8
  import * as Effect from "effect/Effect";
9
9
  import * as Layer from "effect/Layer";
@@ -56,8 +56,8 @@ interface EDARuntimeShape {
56
56
  declare const EDARuntime_base: Context.ServiceClass<EDARuntime, "@effect-durable-agent/EDARuntime", EDARuntimeShape>;
57
57
  /** Top-level public facade for one effect-durable-agent session runtime. */
58
58
  declare class EDARuntime extends EDARuntime_base {
59
- static readonly Live: (config: EDARuntimeConfig) => Layer.Layer<EDARuntime, SessionCommandAdmissionError, SessionState | EDASessionQuery>;
59
+ static readonly Live: (config: EDARuntimeConfig) => Layer.Layer<EDARuntime, SessionCommandAdmissionError, EDASessionQuery | SessionState>;
60
60
  }
61
61
  //#endregion
62
62
  export { EDARuntimeError as a, EDARuntimeConfig as i, EDACommandTerminalEvent as n, EDARuntimeShape as o, EDARuntime as r, EDARuntimeSubmit as s, CommittedCommandTerminalEvent as t };
63
- //# sourceMappingURL=runtime-DXvMCq-J.d.ts.map
63
+ //# sourceMappingURL=runtime-DDSYP9jS.d.ts.map
@@ -1,2 +1,2 @@
1
- import { _ as defaultCompactionRetainTailTokens, a as CompactionExecutorShape, c as CompactionPolicy, d as CompactionRunner, f as CompactionRunnerInput, g as defaultCompactionMinSummarizableTokens, h as defaultCompactionCharsPerToken, i as CompactionExecutorInput, l as CompactionPolicyInput, m as LanguageModelSummaryCompactionExecutorOptions, n as CompactionError, o as CompactionOutput, p as CompactionRunnerShape, r as CompactionExecutor, s as CompactionPlan, t as ApproximateTokenThresholdCompactionPolicyOptions, u as CompactionPolicyShape, v as defaultCompactionThresholdTokens } from "../compaction-D7W0-Ur1.js";
1
+ import { _ as defaultCompactionRetainTailTokens, a as CompactionExecutorShape, c as CompactionPolicy, d as CompactionRunner, f as CompactionRunnerInput, g as defaultCompactionMinSummarizableTokens, h as defaultCompactionCharsPerToken, i as CompactionExecutorInput, l as CompactionPolicyInput, m as LanguageModelSummaryCompactionExecutorOptions, n as CompactionError, o as CompactionOutput, p as CompactionRunnerShape, r as CompactionExecutor, s as CompactionPlan, t as ApproximateTokenThresholdCompactionPolicyOptions, u as CompactionPolicyShape, v as defaultCompactionThresholdTokens } from "../compaction-ch8z6G9x.js";
2
2
  export { ApproximateTokenThresholdCompactionPolicyOptions, CompactionError, CompactionExecutor, CompactionExecutorInput, CompactionExecutorShape, CompactionOutput, CompactionPlan, CompactionPolicy, CompactionPolicyInput, CompactionPolicyShape, CompactionRunner, CompactionRunnerInput, CompactionRunnerShape, LanguageModelSummaryCompactionExecutorOptions, defaultCompactionCharsPerToken, defaultCompactionMinSummarizableTokens, defaultCompactionRetainTailTokens, defaultCompactionThresholdTokens };