effect-durable-agent 0.1.0-alpha.1

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 (140) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +21 -0
  4. package/README.md +305 -0
  5. package/SECURITY.md +8 -0
  6. package/dist/command-queues-CQ9cwRP7.d.ts +468 -0
  7. package/dist/commands-Ce1ec6kH.d.ts +104 -0
  8. package/dist/compaction-YayFKo_1.d.ts +144 -0
  9. package/dist/core-Hv3cFydL.d.ts +81 -0
  10. package/dist/domain/command-queues.d.ts +2 -0
  11. package/dist/domain/command-queues.js +97 -0
  12. package/dist/domain/command-queues.js.map +1 -0
  13. package/dist/domain/message-transcript.d.ts +2 -0
  14. package/dist/domain/message-transcript.js +111 -0
  15. package/dist/domain/message-transcript.js.map +1 -0
  16. package/dist/domain/reduced-state-schema.d.ts +996 -0
  17. package/dist/domain/reduced-state-schema.js +286 -0
  18. package/dist/domain/reduced-state-schema.js.map +1 -0
  19. package/dist/domain/reduced-state.d.ts +2 -0
  20. package/dist/domain/reduced-state.js +2 -0
  21. package/dist/durable-C3Rz7kg3.js +625 -0
  22. package/dist/durable-C3Rz7kg3.js.map +1 -0
  23. package/dist/durable-DlScwmCy.d.ts +7424 -0
  24. package/dist/durable-object-runtime-B7jwBY2R.js +1494 -0
  25. package/dist/durable-object-runtime-B7jwBY2R.js.map +1 -0
  26. package/dist/durable-object-runtime-pWv0ohlz.d.ts +257 -0
  27. package/dist/durable-object-storage-Czy7IPrh.d.ts +41 -0
  28. package/dist/events-Bb9-Cu-7.d.ts +918 -0
  29. package/dist/host/durable-object-runtime.d.ts +2 -0
  30. package/dist/host/durable-object-runtime.js +2 -0
  31. package/dist/host/durable-object-storage.d.ts +2 -0
  32. package/dist/host/durable-object-storage.js +0 -0
  33. package/dist/host/durable-object.d.ts +83 -0
  34. package/dist/host/durable-object.js +191 -0
  35. package/dist/host/durable-object.js.map +1 -0
  36. package/dist/host/websocket-wire.d.ts +2 -0
  37. package/dist/host/websocket-wire.js +88 -0
  38. package/dist/host/websocket-wire.js.map +1 -0
  39. package/dist/id-generator-C2Q15uZM.d.ts +33 -0
  40. package/dist/index-BVVgDSdq.d.ts +1 -0
  41. package/dist/index.d.ts +7 -0
  42. package/dist/index.js +7 -0
  43. package/dist/keep-alive-DYDsH6qN.d.ts +111 -0
  44. package/dist/keep-alive-p8dIcSVy.js +109 -0
  45. package/dist/keep-alive-p8dIcSVy.js.map +1 -0
  46. package/dist/message-transcript-BCHdHAe2.d.ts +32 -0
  47. package/dist/prompt-projector-9_02lk5-.d.ts +40 -0
  48. package/dist/reduced-state-C4nVVzz9.js +910 -0
  49. package/dist/reduced-state-C4nVVzz9.js.map +1 -0
  50. package/dist/reducer-registry-C0svUa63.d.ts +69 -0
  51. package/dist/runtime-C56FQxiL.d.ts +60 -0
  52. package/dist/services/compaction.d.ts +2 -0
  53. package/dist/services/compaction.js +426 -0
  54. package/dist/services/compaction.js.map +1 -0
  55. package/dist/services/id-generator.d.ts +2 -0
  56. package/dist/services/id-generator.js +56 -0
  57. package/dist/services/id-generator.js.map +1 -0
  58. package/dist/services/prompt-projector.d.ts +2 -0
  59. package/dist/services/prompt-projector.js +27 -0
  60. package/dist/services/prompt-projector.js.map +1 -0
  61. package/dist/services/reducer-registry.d.ts +2 -0
  62. package/dist/services/reducer-registry.js +71 -0
  63. package/dist/services/reducer-registry.js.map +1 -0
  64. package/dist/services/runtime.d.ts +2 -0
  65. package/dist/services/runtime.js +84 -0
  66. package/dist/services/runtime.js.map +1 -0
  67. package/dist/services/session-query.d.ts +2 -0
  68. package/dist/services/session-query.js +2 -0
  69. package/dist/services/session-store.d.ts +2 -0
  70. package/dist/services/session-store.js +2 -0
  71. package/dist/services/sink-registry.d.ts +2 -0
  72. package/dist/services/sink-registry.js +2 -0
  73. package/dist/services/span-names.d.ts +28 -0
  74. package/dist/services/span-names.js +42 -0
  75. package/dist/services/span-names.js.map +1 -0
  76. package/dist/services/tool-registry.d.ts +2 -0
  77. package/dist/services/tool-registry.js +46 -0
  78. package/dist/services/tool-registry.js.map +1 -0
  79. package/dist/services/tracing.d.ts +76 -0
  80. package/dist/services/tracing.js +116 -0
  81. package/dist/services/tracing.js.map +1 -0
  82. package/dist/session-query-DOc1KanA.js +2930 -0
  83. package/dist/session-query-DOc1KanA.js.map +1 -0
  84. package/dist/session-query-DlRo5Ufc.d.ts +769 -0
  85. package/dist/session-store-D2Ore1QC.d.ts +295 -0
  86. package/dist/session-store-pYxQW9qh.js +214 -0
  87. package/dist/session-store-pYxQW9qh.js.map +1 -0
  88. package/dist/sink-registry-CFC6xjsN.js +312 -0
  89. package/dist/sink-registry-CFC6xjsN.js.map +1 -0
  90. package/dist/sink-registry-CIU0LD3m.d.ts +158 -0
  91. package/dist/testkit/layers.d.ts +101 -0
  92. package/dist/testkit/layers.js +108 -0
  93. package/dist/testkit/layers.js.map +1 -0
  94. package/dist/tool-registry-CcnkAAQK.d.ts +51 -0
  95. package/dist/tracing-BXHAkxkx.d.ts +111 -0
  96. package/dist/types/commands.d.ts +2 -0
  97. package/dist/types/commands.js +60 -0
  98. package/dist/types/commands.js.map +1 -0
  99. package/dist/types/core.d.ts +2 -0
  100. package/dist/types/core.js +68 -0
  101. package/dist/types/core.js.map +1 -0
  102. package/dist/types/events/durable.d.ts +2 -0
  103. package/dist/types/events/durable.js +2 -0
  104. package/dist/types/events.d.ts +4 -0
  105. package/dist/types/events.js +90 -0
  106. package/dist/types/events.js.map +1 -0
  107. package/dist/types/tracing.d.ts +2 -0
  108. package/dist/types/tracing.js +99 -0
  109. package/dist/types/tracing.js.map +1 -0
  110. package/dist/websocket-wire-DvOu_6BJ.d.ts +16773 -0
  111. package/docs/assets/architecture.svg +106 -0
  112. package/docs/assets/event-sequence.svg +143 -0
  113. package/docs/assets/gcp-trace.png +0 -0
  114. package/docs/message-steering.md +831 -0
  115. package/docs/releasing.md +57 -0
  116. package/docs/spec.md +774 -0
  117. package/docs/subagents.md +725 -0
  118. package/docs/testing.md +64 -0
  119. package/docs/ui-projection.md +742 -0
  120. package/docs/websocket-protocol.md +613 -0
  121. package/examples/001-no-tools/README.md +65 -0
  122. package/examples/001-no-tools/worker.ts +79 -0
  123. package/examples/002-slack-bridge/README.md +134 -0
  124. package/examples/002-slack-bridge/events.ts +115 -0
  125. package/examples/002-slack-bridge/reducer.ts +216 -0
  126. package/examples/002-slack-bridge/scenario.test.ts +223 -0
  127. package/examples/002-slack-bridge/sinks.ts +109 -0
  128. package/examples/002-slack-bridge/worker.ts +140 -0
  129. package/examples/003-sandbox-lifecycle/README.md +78 -0
  130. package/examples/003-sandbox-lifecycle/events.ts +203 -0
  131. package/examples/003-sandbox-lifecycle/reducer.ts +305 -0
  132. package/examples/003-sandbox-lifecycle/scenario.test.ts +202 -0
  133. package/examples/_shared/event-id.ts +12 -0
  134. package/examples/_shared/http.ts +27 -0
  135. package/examples/_shared/openai.ts +33 -0
  136. package/package.json +181 -0
  137. package/testing/offline-trace/README.md +63 -0
  138. package/tooling/oxlint/index.mjs +15 -0
  139. package/tooling/oxlint/rules/effect-span-from-catalog.mjs +152 -0
  140. package/tooling/oxlint/rules/span-catalog-format.mjs +74 -0
@@ -0,0 +1,910 @@
1
+ import { ContextVersion, SequenceNumber } from "./types/core.js";
2
+ import { $n as userMessagePromotedEventType, An as pendingMessagesPausedEventType, Bn as summaryCreatedEventType, Cn as contextRebasedEventType, Dn as inferenceFailedEventType, En as inferenceCompletedEventType, Fn as runStartedEventType, Gn as toolCallRejectedEventType, Hn as toolCallCompletedEventType, In as steeringMessageCancelledEventType, Jn as turnFailedEventType, Kn as toolCallStartedEventType, Ln as steeringMessageQueuedEventType, Mn as runCompletedEventType, Nn as runFailedEventType, On as inferenceStartedEventType, Pn as runInterruptedEventType, Qn as userMessageCommittedEventType, Rn as stopTurnAppliedEventType, Sn as contextProjectedEventType, Un as toolCallCreatedEventType, Vn as systemMessageCommittedEventType, Wn as toolCallFailedEventType, Xn as turnStoppedEventType, Yn as turnStartedEventType, Zn as userMessageCancelledEventType, _n as commandStartedEventType, bn as compactionRequestedEventType, cn as assistantMessageCommittedEventType, dn as baseStateFailedEventType, er as userMessageSubmittedEventType, fn as baseStateRequestedEventType, gn as commandFailedEventType, hn as commandCompletedEventType, jn as recoveryCompletedEventType, kn as messageQueuePausedEventType, ln as assistantPartialCommittedEventType, mn as commandCancelledEventType, pn as commandAdmittedEventType, qn as turnCompletedEventType, un as baseStateCreatedEventType, vn as compactionCompletedEventType, vr as effectDurableAgentNamespace, xn as compactionStartedEventType, yn as compactionFailedEventType, zn as stopTurnRequestedEventType } from "./durable-C3Rz7kg3.js";
3
+ import { deriveCommandQueues, emptyCommandQueues } from "./domain/command-queues.js";
4
+ //#region src/domain/assert-never.ts
5
+ const formatNeverValue = (value) => {
6
+ try {
7
+ return JSON.stringify(value);
8
+ } catch {
9
+ return String(value);
10
+ }
11
+ };
12
+ /** Build the defect used when an exhaustive switch receives an impossible value. */
13
+ const assertNeverError = (value, context) => /* @__PURE__ */ new Error(`Unhandled ${context}: ${formatNeverValue(value)}`);
14
+ /** Throw for impossible branches in pure code after TypeScript exhaustiveness checking. */
15
+ const assertNever = (value, context) => {
16
+ throw assertNeverError(value, context);
17
+ };
18
+ /** Empty durable replay state before any session event has committed. */
19
+ const initialReducedState = {
20
+ lastSeq: SequenceNumber.make(0),
21
+ commands: /* @__PURE__ */ new Map(),
22
+ runs: /* @__PURE__ */ new Map(),
23
+ recoveryContinuations: /* @__PURE__ */ new Map(),
24
+ turns: /* @__PURE__ */ new Map(),
25
+ inferences: /* @__PURE__ */ new Map(),
26
+ toolCalls: /* @__PURE__ */ new Map(),
27
+ messages: /* @__PURE__ */ new Map(),
28
+ stopRequests: /* @__PURE__ */ new Map(),
29
+ compactions: /* @__PURE__ */ new Map(),
30
+ context: { version: ContextVersion.make(0) },
31
+ tokenConsumption: { total: {
32
+ inputTokens: 0,
33
+ cachedInputTokens: 0,
34
+ outputTokens: 0,
35
+ textTokens: 0,
36
+ reasoningTokens: 0
37
+ } },
38
+ commandQueues: emptyCommandQueues
39
+ };
40
+ /** Reserved reducer checkpoint name for the framework-owned `ReducedState`. */
41
+ const frameworkReducedStateReducerName = "_eda.framework.reduced-state";
42
+ /** Schema version for the framework-owned `ReducedState` checkpoint payload. */
43
+ const frameworkReducedStateReducerSchemaVersion = 4;
44
+ /** Encode the framework reducer state into a pointer-based JSON-safe checkpoint payload. */
45
+ const encodeReducedStateCheckpoint = (state) => ({
46
+ lastSeq: state.lastSeq,
47
+ commands: Array.from(state.commands.entries()).map(([commandId, record]) => [commandId, encodeCheckpointCommandRecord(record)]),
48
+ runs: Array.from(state.runs.entries()),
49
+ recoveryContinuations: Array.from(state.recoveryContinuations.entries()),
50
+ turns: Array.from(state.turns.entries()),
51
+ inferences: Array.from(state.inferences.entries()),
52
+ toolCalls: Array.from(state.toolCalls.entries()).map(([toolCallId, record]) => [toolCallId, encodeCheckpointToolCallRecord(record)]),
53
+ messages: Array.from(state.messages.entries()).map(([messageId, record]) => [messageId, encodeCheckpointMessageRecord(record)]),
54
+ stopRequests: Array.from(state.stopRequests.entries()),
55
+ compactions: Array.from(state.compactions.entries()),
56
+ context: state.context,
57
+ tokenConsumption: state.tokenConsumption
58
+ });
59
+ /** Event-log positions required to hydrate a pointer-based framework checkpoint. */
60
+ const reducedStateCheckpointEventSeqs = (payload) => {
61
+ const checkpoint = payload;
62
+ const seqs = [];
63
+ for (const [, record] of checkpoint.commands ?? []) if (record.admittedSeq !== void 0) seqs.push(record.admittedSeq);
64
+ for (const [, record] of checkpoint.messages ?? []) seqs.push(record.seq);
65
+ for (const [, record] of checkpoint.toolCalls ?? []) {
66
+ if (record.decision !== void 0) seqs.push(record.decision.seq);
67
+ if (record.terminal !== void 0 && (record.terminal._tag === "Completed" || record.terminal._tag === "Failed")) seqs.push(record.terminal.seq);
68
+ }
69
+ return uniqueSequenceNumbers(seqs);
70
+ };
71
+ /** Decode the framework reducer checkpoint and rebuild derived scheduler queues. */
72
+ const decodeReducedStateCheckpoint = (payload, referencedEvents) => {
73
+ const checkpoint = payload;
74
+ const eventsBySeq = committedEventMapBySeq(referencedEvents);
75
+ const commands = decodeCheckpointCommandRecords(checkpoint.commands ?? [], eventsBySeq);
76
+ const runs = new Map(checkpoint.runs ?? []);
77
+ const messages = decodeCheckpointMessageRecords(checkpoint.messages ?? [], eventsBySeq);
78
+ return {
79
+ lastSeq: SequenceNumber.make(Number(checkpoint.lastSeq ?? 0)),
80
+ commands,
81
+ runs,
82
+ recoveryContinuations: new Map(checkpoint.recoveryContinuations ?? []),
83
+ turns: new Map(checkpoint.turns ?? []),
84
+ inferences: new Map(checkpoint.inferences ?? []),
85
+ toolCalls: decodeCheckpointToolCallRecords(checkpoint.toolCalls ?? [], eventsBySeq),
86
+ messages,
87
+ stopRequests: new Map(checkpoint.stopRequests ?? []),
88
+ compactions: new Map(checkpoint.compactions ?? []),
89
+ context: checkpoint.context ?? { version: ContextVersion.make(0) },
90
+ tokenConsumption: decodeTokenConsumptionState(checkpoint.tokenConsumption),
91
+ commandQueues: deriveCommandQueues({
92
+ commands,
93
+ runs,
94
+ messages
95
+ })
96
+ };
97
+ };
98
+ const encodeCheckpointCommandRecord = (record) => {
99
+ const { command: _command, ...checkpoint } = record;
100
+ return checkpoint;
101
+ };
102
+ const encodeCheckpointMessageRecord = (record) => {
103
+ switch (record._tag) {
104
+ case "System": {
105
+ const { content: _content, ...checkpoint } = record;
106
+ return checkpoint;
107
+ }
108
+ case "User": {
109
+ const { content: _content, ...checkpoint } = record;
110
+ return checkpoint;
111
+ }
112
+ case "Steering": {
113
+ const { content: _content, ...checkpoint } = record;
114
+ return checkpoint;
115
+ }
116
+ case "Assistant": {
117
+ const { content: _content, promptParts: _promptParts, ...checkpoint } = record;
118
+ return checkpoint;
119
+ }
120
+ case "AssistantPartial": {
121
+ const { content: _content, promptParts: _promptParts, ...checkpoint } = record;
122
+ return checkpoint;
123
+ }
124
+ default: return assertNever(record, "checkpoint message record");
125
+ }
126
+ };
127
+ const encodeCheckpointToolCallRecord = (record) => ({
128
+ toolCallId: record.toolCallId,
129
+ ...record.decision === void 0 ? {} : { decision: encodeCheckpointToolDecision(record.decision) },
130
+ ...record.durationMs === void 0 ? {} : { durationMs: record.durationMs },
131
+ ...record.startedAtMs === void 0 ? {} : { startedAtMs: record.startedAtMs },
132
+ ...record.startedSeq === void 0 ? {} : { startedSeq: record.startedSeq },
133
+ ...record.terminalAtMs === void 0 ? {} : { terminalAtMs: record.terminalAtMs },
134
+ ...record.terminal === void 0 ? {} : { terminal: encodeCheckpointToolTerminal(record.terminal) }
135
+ });
136
+ const encodeCheckpointToolDecision = (decision) => {
137
+ switch (decision._tag) {
138
+ case "Created": {
139
+ const { params: _params, promptPart: _promptPart, ...checkpoint } = decision;
140
+ return checkpoint;
141
+ }
142
+ case "Rejected": {
143
+ const { promptPart: _promptPart, ...checkpoint } = decision;
144
+ return checkpoint;
145
+ }
146
+ default: return assertNever(decision, "checkpoint tool decision");
147
+ }
148
+ };
149
+ const encodeCheckpointToolTerminal = (terminal) => {
150
+ switch (terminal._tag) {
151
+ case "Completed": {
152
+ const { result: _result, promptPart: _promptPart, ...checkpoint } = terminal;
153
+ return checkpoint;
154
+ }
155
+ case "Failed": {
156
+ const { error: _error, promptPart: _promptPart, ...checkpoint } = terminal;
157
+ return checkpoint;
158
+ }
159
+ default: return assertNever(terminal, "checkpoint tool terminal");
160
+ }
161
+ };
162
+ const decodeCheckpointCommandRecords = (records, eventsBySeq) => new Map(records.map(([commandId, record]) => {
163
+ if (record.admittedSeq === void 0) return [commandId, record];
164
+ const admitted = reduceSingleCheckpointEvent(eventsBySeq, record.admittedSeq, commandAdmittedEventType).commands.get(commandId);
165
+ if (admitted?.command === void 0) throw new Error(`Checkpoint command ${commandId} missing admission payload`);
166
+ return [commandId, {
167
+ ...record,
168
+ command: admitted.command
169
+ }];
170
+ }));
171
+ const decodeCheckpointMessageRecords = (records, eventsBySeq) => new Map(records.map(([messageId, record]) => {
172
+ const message = reduceSingleCheckpointEvent(eventsBySeq, record.seq, checkpointMessageEventType(record)).messages.get(messageId);
173
+ if (message === void 0) throw new Error(`Checkpoint message ${messageId} missing message payload`);
174
+ return [messageId, {
175
+ ...message,
176
+ ...record
177
+ }];
178
+ }));
179
+ const decodeCheckpointToolCallRecords = (records, eventsBySeq) => new Map(records.map(([toolCallId, record]) => [toolCallId, {
180
+ toolCallId,
181
+ ...record.decision === void 0 ? {} : { decision: decodeCheckpointToolDecision(toolCallId, record.decision, eventsBySeq) },
182
+ ...record.durationMs === void 0 ? {} : { durationMs: record.durationMs },
183
+ ...record.startedAtMs === void 0 ? {} : { startedAtMs: record.startedAtMs },
184
+ ...record.startedSeq === void 0 ? {} : { startedSeq: record.startedSeq },
185
+ ...record.terminalAtMs === void 0 ? {} : { terminalAtMs: record.terminalAtMs },
186
+ ...record.terminal === void 0 ? {} : { terminal: decodeCheckpointToolTerminal(toolCallId, record.terminal, eventsBySeq) }
187
+ }]));
188
+ const decodeCheckpointToolDecision = (toolCallId, decision, eventsBySeq) => {
189
+ const hydrated = reduceSingleCheckpointEvent(eventsBySeq, decision.seq, decision._tag === "Created" ? toolCallCreatedEventType : toolCallRejectedEventType).toolCalls.get(toolCallId)?.decision;
190
+ if (hydrated === void 0 || hydrated._tag !== decision._tag) throw new Error(`Checkpoint tool decision ${toolCallId} missing ${decision._tag} payload`);
191
+ return hydrated;
192
+ };
193
+ const decodeCheckpointToolTerminal = (toolCallId, terminal, eventsBySeq) => {
194
+ const hydrated = reduceSingleCheckpointEvent(eventsBySeq, terminal.seq, terminal._tag === "Completed" ? toolCallCompletedEventType : toolCallFailedEventType).toolCalls.get(toolCallId)?.terminal;
195
+ if (hydrated === void 0 || hydrated._tag !== terminal._tag) throw new Error(`Checkpoint tool terminal ${toolCallId} missing ${terminal._tag} payload`);
196
+ return hydrated;
197
+ };
198
+ const checkpointMessageEventType = (record) => {
199
+ switch (record._tag) {
200
+ case "System": return systemMessageCommittedEventType;
201
+ case "User": return record.requestedDisposition === void 0 ? userMessageCommittedEventType : userMessageSubmittedEventType;
202
+ case "Steering": return steeringMessageQueuedEventType;
203
+ case "Assistant": return assistantMessageCommittedEventType;
204
+ case "AssistantPartial": return assistantPartialCommittedEventType;
205
+ default: return assertNever(record, "checkpoint message type");
206
+ }
207
+ };
208
+ const reduceSingleCheckpointEvent = (eventsBySeq, seq, expectedType) => {
209
+ const event = eventsBySeq.get(Number(seq));
210
+ if (event === void 0) throw new Error(`Checkpoint reference seq ${seq} is missing`);
211
+ if (event.event.type !== expectedType) throw new Error(`Checkpoint reference seq ${seq} expected ${expectedType}; got ${event.event.type}`);
212
+ return foldReducedState(initialReducedState, [event]);
213
+ };
214
+ const committedEventMapBySeq = (events) => new Map(events.map((event) => [Number(event.position.seq), event]));
215
+ 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
+ } });
223
+ /** Fold newly committed durable events into the canonical replay state. */
224
+ const foldReducedState = (state, committed) => {
225
+ let lastSeq = state.lastSeq;
226
+ const commands = new Map(state.commands);
227
+ const runs = new Map(state.runs);
228
+ const recoveryContinuations = new Map(state.recoveryContinuations);
229
+ const turns = new Map(state.turns);
230
+ const inferences = new Map(state.inferences);
231
+ const toolCalls = new Map(state.toolCalls);
232
+ const messages = new Map(state.messages);
233
+ const stopRequests = new Map(state.stopRequests);
234
+ const compactions = new Map(state.compactions);
235
+ let context = state.context;
236
+ let tokenConsumption = state.tokenConsumption;
237
+ for (const entry of committed) {
238
+ lastSeq = entry.position.seq;
239
+ const { event } = entry;
240
+ if (event.namespace !== effectDurableAgentNamespace) continue;
241
+ const payload = event.payload;
242
+ const seq = entry.position.seq;
243
+ const eventCreatedAtMs = Number(event.createdAtMs);
244
+ switch (event.type) {
245
+ case commandAdmittedEventType: {
246
+ const { command } = payload;
247
+ const commandId = requireAdmittedCommandId(command);
248
+ upsert(commands, commandId, { commandId }, (record) => ({
249
+ ...record,
250
+ admittedSeq: seq,
251
+ admissionTrace: event.trace,
252
+ command
253
+ }));
254
+ break;
255
+ }
256
+ case commandStartedEventType: {
257
+ const { commandId } = payload;
258
+ upsert(commands, commandId, { commandId }, (record) => ({
259
+ ...record,
260
+ startedSeq: seq
261
+ }));
262
+ break;
263
+ }
264
+ case commandCompletedEventType: {
265
+ const { commandId } = payload;
266
+ upsert(commands, commandId, { commandId }, (record) => ({
267
+ ...record,
268
+ terminal: {
269
+ _tag: "Completed",
270
+ seq
271
+ }
272
+ }));
273
+ break;
274
+ }
275
+ case commandFailedEventType: {
276
+ const { commandId, error } = payload;
277
+ upsert(commands, commandId, { commandId }, (record) => ({
278
+ ...record,
279
+ terminal: {
280
+ _tag: "Failed",
281
+ seq,
282
+ error
283
+ }
284
+ }));
285
+ break;
286
+ }
287
+ case commandCancelledEventType: {
288
+ const { commandId, reason } = payload;
289
+ upsert(commands, commandId, { commandId }, (record) => ({
290
+ ...record,
291
+ terminal: {
292
+ _tag: "Cancelled",
293
+ seq,
294
+ reason
295
+ }
296
+ }));
297
+ break;
298
+ }
299
+ case runStartedEventType: {
300
+ const { runId, commandIds, trace } = payload;
301
+ const terminal = runs.get(runId)?.terminal;
302
+ runs.set(runId, {
303
+ runId,
304
+ commandIds,
305
+ startedAtMs: eventCreatedAtMs,
306
+ startedSeq: seq,
307
+ trace,
308
+ ...terminal === void 0 ? {} : { terminal }
309
+ });
310
+ break;
311
+ }
312
+ case runCompletedEventType: {
313
+ const { runId } = payload;
314
+ updateExisting(runs, runId, (record) => ({
315
+ ...record,
316
+ ...terminalTiming(record, eventCreatedAtMs),
317
+ terminal: {
318
+ _tag: "Completed",
319
+ seq
320
+ }
321
+ }));
322
+ break;
323
+ }
324
+ case runFailedEventType: {
325
+ const { runId, error } = payload;
326
+ updateExisting(runs, runId, (record) => ({
327
+ ...record,
328
+ ...terminalTiming(record, eventCreatedAtMs),
329
+ terminal: {
330
+ _tag: "Failed",
331
+ seq,
332
+ error
333
+ }
334
+ }));
335
+ break;
336
+ }
337
+ case runInterruptedEventType: {
338
+ const { runId, reason } = payload;
339
+ updateExisting(runs, runId, (record) => ({
340
+ ...record,
341
+ ...terminalTiming(record, eventCreatedAtMs),
342
+ terminal: {
343
+ _tag: "Interrupted",
344
+ seq,
345
+ reason
346
+ }
347
+ }));
348
+ break;
349
+ }
350
+ case turnStartedEventType: {
351
+ const { runId, turnId, inputMessageIds } = payload;
352
+ const terminal = turns.get(turnId)?.terminal;
353
+ turns.set(turnId, {
354
+ runId,
355
+ turnId,
356
+ startedAtMs: eventCreatedAtMs,
357
+ startedSeq: seq,
358
+ ...terminal === void 0 ? {} : { terminal }
359
+ });
360
+ for (const messageId of inputMessageIds ?? []) {
361
+ const message = messages.get(messageId);
362
+ if (message?._tag === "Steering" || message?._tag === "User") messages.set(messageId, {
363
+ ...message,
364
+ consumedSeq: seq,
365
+ consumedTurnId: turnId
366
+ });
367
+ }
368
+ break;
369
+ }
370
+ case turnCompletedEventType: {
371
+ const { turnId, usage } = payload;
372
+ updateExisting(turns, turnId, (record) => ({
373
+ ...record,
374
+ ...terminalTiming(record, eventCreatedAtMs),
375
+ terminal: {
376
+ _tag: "Completed",
377
+ seq,
378
+ ...usage === void 0 ? {} : { usage }
379
+ }
380
+ }));
381
+ break;
382
+ }
383
+ case turnFailedEventType: {
384
+ const { turnId, error } = payload;
385
+ updateExisting(turns, turnId, (record) => ({
386
+ ...record,
387
+ ...terminalTiming(record, eventCreatedAtMs),
388
+ terminal: {
389
+ _tag: "Failed",
390
+ seq,
391
+ error
392
+ }
393
+ }));
394
+ break;
395
+ }
396
+ case turnStoppedEventType: {
397
+ const { turnId, reason } = payload;
398
+ updateExisting(turns, turnId, (record) => ({
399
+ ...record,
400
+ ...terminalTiming(record, eventCreatedAtMs),
401
+ terminal: {
402
+ _tag: "Stopped",
403
+ seq,
404
+ reason
405
+ }
406
+ }));
407
+ break;
408
+ }
409
+ case inferenceStartedEventType: {
410
+ const { runId, turnId, inferenceId } = payload;
411
+ const terminal = inferences.get(inferenceId)?.terminal;
412
+ inferences.set(inferenceId, {
413
+ runId,
414
+ turnId,
415
+ inferenceId,
416
+ startedAtMs: eventCreatedAtMs,
417
+ startedSeq: seq,
418
+ ...terminal === void 0 ? {} : { terminal }
419
+ });
420
+ break;
421
+ }
422
+ case inferenceCompletedEventType: {
423
+ const { inferenceId, usage } = payload;
424
+ const previouslyCompleted = inferences.get(inferenceId)?.terminal?._tag === "Completed";
425
+ updateExisting(inferences, inferenceId, (record) => ({
426
+ ...record,
427
+ ...terminalTiming(record, eventCreatedAtMs),
428
+ terminal: {
429
+ _tag: "Completed",
430
+ seq,
431
+ ...usage === void 0 ? {} : { usage }
432
+ }
433
+ }));
434
+ if (!previouslyCompleted && inferences.get(inferenceId)?.terminal?._tag === "Completed") tokenConsumption = addTokenUsage(tokenConsumption, usage);
435
+ break;
436
+ }
437
+ case inferenceFailedEventType: {
438
+ const { inferenceId, error } = payload;
439
+ updateExisting(inferences, inferenceId, (record) => ({
440
+ ...record,
441
+ ...terminalTiming(record, eventCreatedAtMs),
442
+ terminal: {
443
+ _tag: "Failed",
444
+ seq,
445
+ error
446
+ }
447
+ }));
448
+ break;
449
+ }
450
+ case toolCallCreatedEventType: {
451
+ const { runId, turnId, inferenceId, toolCallId, promptPart } = payload;
452
+ upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({
453
+ ...record,
454
+ decision: {
455
+ _tag: "Created",
456
+ seq,
457
+ runId,
458
+ turnId,
459
+ inferenceId,
460
+ providerPartId: promptPart.id,
461
+ toolName: promptPart.name,
462
+ params: promptPart.params,
463
+ providerExecuted: promptPart.providerExecuted,
464
+ promptPart
465
+ }
466
+ }));
467
+ break;
468
+ }
469
+ case toolCallRejectedEventType: {
470
+ const { runId, turnId, inferenceId, toolCallId, promptPart } = payload;
471
+ upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({
472
+ ...record,
473
+ decision: {
474
+ _tag: "Rejected",
475
+ seq,
476
+ runId,
477
+ turnId,
478
+ inferenceId,
479
+ providerPartId: promptPart.id,
480
+ toolName: promptPart.name,
481
+ reason: promptPart.result.reason,
482
+ modelFeedback: promptPart.result.modelFeedback,
483
+ promptPart
484
+ }
485
+ }));
486
+ break;
487
+ }
488
+ case toolCallStartedEventType: {
489
+ const { toolCallId } = payload;
490
+ upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({
491
+ ...record,
492
+ startedAtMs: eventCreatedAtMs,
493
+ startedSeq: seq
494
+ }));
495
+ break;
496
+ }
497
+ case toolCallCompletedEventType: {
498
+ const { toolCallId, promptPart } = payload;
499
+ upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({
500
+ ...record,
501
+ ...terminalTiming(record, eventCreatedAtMs),
502
+ terminal: {
503
+ _tag: "Completed",
504
+ seq,
505
+ result: promptPart.result,
506
+ promptPart
507
+ }
508
+ }));
509
+ break;
510
+ }
511
+ case toolCallFailedEventType: {
512
+ const { toolCallId, promptPart, error } = payload;
513
+ upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({
514
+ ...record,
515
+ ...terminalTiming(record, eventCreatedAtMs),
516
+ terminal: {
517
+ _tag: "Failed",
518
+ seq,
519
+ error: error ?? promptPart.result,
520
+ promptPart
521
+ }
522
+ }));
523
+ break;
524
+ }
525
+ case systemMessageCommittedEventType: {
526
+ const { messageId, content } = payload;
527
+ messages.set(messageId, {
528
+ _tag: "System",
529
+ messageId,
530
+ content,
531
+ ...Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {},
532
+ seq
533
+ });
534
+ break;
535
+ }
536
+ case userMessageCommittedEventType: {
537
+ const { commandId, messageId, content } = payload;
538
+ messages.set(messageId, {
539
+ _tag: "User",
540
+ messageId,
541
+ commandId,
542
+ content,
543
+ ...Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {},
544
+ seq
545
+ });
546
+ break;
547
+ }
548
+ case userMessageSubmittedEventType: {
549
+ const { commandId, messageId, disposition: requestedDisposition, content } = payload;
550
+ messages.set(messageId, {
551
+ _tag: "User",
552
+ messageId,
553
+ commandId,
554
+ content,
555
+ requestedDisposition,
556
+ disposition: requestedDisposition,
557
+ ...Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {},
558
+ seq
559
+ });
560
+ break;
561
+ }
562
+ case userMessagePromotedEventType: {
563
+ const { messageId } = payload;
564
+ const message = messages.get(messageId);
565
+ if (message?._tag === "User" && message.disposition === "queue" || message?._tag === "Steering" && message.pausedByCommandId !== void 0) {
566
+ const { pausedByCommandId: _pausedByCommandId, pausedSeq: _pausedSeq, ...unpausedMessage } = message;
567
+ messages.set(messageId, {
568
+ ...unpausedMessage,
569
+ ...message._tag === "User" ? { disposition: "steer" } : {},
570
+ promotedSeq: seq
571
+ });
572
+ }
573
+ break;
574
+ }
575
+ case userMessageCancelledEventType: {
576
+ const { commandId, messageId, reason } = payload;
577
+ const message = messages.get(messageId);
578
+ if (message?._tag === "User" || message?._tag === "Steering") messages.set(messageId, {
579
+ ...message,
580
+ cancelledSeq: seq,
581
+ cancelledByCommandId: commandId,
582
+ cancellationReason: reason
583
+ });
584
+ break;
585
+ }
586
+ case messageQueuePausedEventType:
587
+ case pendingMessagesPausedEventType: {
588
+ const messageIds = payload.messageIds;
589
+ const interruptionCommandId = event.type === messageQueuePausedEventType ? payload.stopCommandId : payload.interruptionCommandId;
590
+ for (const messageId of messageIds) {
591
+ const message = messages.get(messageId);
592
+ if ((message?._tag === "User" || message?._tag === "Steering") && message.consumedSeq === void 0 && message.cancelledSeq === void 0) messages.set(messageId, {
593
+ ...message,
594
+ ...message._tag === "User" ? { disposition: "queue" } : {},
595
+ pausedSeq: seq,
596
+ pausedByCommandId: interruptionCommandId
597
+ });
598
+ }
599
+ break;
600
+ }
601
+ case steeringMessageQueuedEventType: {
602
+ const { commandId, messageId, runId, content } = payload;
603
+ messages.set(messageId, {
604
+ _tag: "Steering",
605
+ messageId,
606
+ commandId,
607
+ runId,
608
+ content,
609
+ ...Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {},
610
+ seq
611
+ });
612
+ break;
613
+ }
614
+ case steeringMessageCancelledEventType: {
615
+ const { messageId, reason } = payload;
616
+ const message = messages.get(messageId);
617
+ if (message?._tag === "Steering") messages.set(messageId, {
618
+ ...message,
619
+ cancelledSeq: seq,
620
+ cancellationReason: reason
621
+ });
622
+ break;
623
+ }
624
+ case assistantMessageCommittedEventType: {
625
+ const { messageId, runId, turnId, inferenceId, promptParts } = payload;
626
+ messages.set(messageId, {
627
+ _tag: "Assistant",
628
+ messageId,
629
+ runId,
630
+ turnId,
631
+ inferenceId,
632
+ content: assistantContentFromPromptParts(promptParts),
633
+ ...Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {},
634
+ promptParts,
635
+ seq
636
+ });
637
+ break;
638
+ }
639
+ case assistantPartialCommittedEventType: {
640
+ const { messageId, runId, turnId, inferenceId, promptParts, reason } = payload;
641
+ messages.set(messageId, {
642
+ _tag: "AssistantPartial",
643
+ messageId,
644
+ runId,
645
+ turnId,
646
+ inferenceId,
647
+ content: assistantContentFromPromptParts(promptParts),
648
+ ...Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {},
649
+ promptParts,
650
+ reason,
651
+ seq
652
+ });
653
+ break;
654
+ }
655
+ case stopTurnRequestedEventType: {
656
+ const { commandId, runId, turnId } = payload;
657
+ stopRequests.set(commandId, {
658
+ commandId,
659
+ requestedSeq: seq,
660
+ ...runId === void 0 ? {} : { requestedRunId: runId },
661
+ ...turnId === void 0 ? {} : { requestedTurnId: turnId },
662
+ ...appliedFields(stopRequests.get(commandId))
663
+ });
664
+ break;
665
+ }
666
+ case stopTurnAppliedEventType: {
667
+ const { commandId, runId, turnId, inferenceId } = payload;
668
+ const existing = stopRequests.get(commandId);
669
+ stopRequests.set(commandId, {
670
+ commandId,
671
+ requestedSeq: existing?.requestedSeq ?? seq,
672
+ ...existing?.requestedRunId === void 0 ? {} : { requestedRunId: existing.requestedRunId },
673
+ ...existing?.requestedTurnId === void 0 ? {} : { requestedTurnId: existing.requestedTurnId },
674
+ appliedSeq: seq,
675
+ appliedRunId: runId,
676
+ appliedTurnId: turnId,
677
+ ...inferenceId === void 0 ? {} : { appliedInferenceId: inferenceId }
678
+ });
679
+ break;
680
+ }
681
+ case contextProjectedEventType: {
682
+ const { contextVersion } = payload;
683
+ context = {
684
+ ...context,
685
+ version: contextVersion
686
+ };
687
+ break;
688
+ }
689
+ case compactionRequestedEventType: {
690
+ const { compactionId, sourceFromSeq, sourceToSeq } = payload;
691
+ upsert(compactions, compactionId, { compactionId }, (record) => ({
692
+ ...record,
693
+ requestedSeq: seq,
694
+ sourceFromSeq,
695
+ sourceToSeq
696
+ }));
697
+ break;
698
+ }
699
+ case compactionStartedEventType: {
700
+ const { compactionId } = payload;
701
+ upsert(compactions, compactionId, { compactionId }, (record) => ({
702
+ ...record,
703
+ startedSeq: seq
704
+ }));
705
+ break;
706
+ }
707
+ case summaryCreatedEventType: {
708
+ const { compactionId, summaryId, sourceFromSeq, sourceToSeq } = payload;
709
+ upsert(compactions, compactionId, { compactionId }, (record) => ({
710
+ ...record,
711
+ summaryCreatedSeq: seq,
712
+ summaryId,
713
+ sourceFromSeq,
714
+ sourceToSeq
715
+ }));
716
+ break;
717
+ }
718
+ case contextRebasedEventType: {
719
+ const { compactionId, summaryId, contextVersion, retainedFromContextSeq } = payload;
720
+ upsert(compactions, compactionId, { compactionId }, (record) => ({
721
+ ...record,
722
+ summaryId,
723
+ rebasedSeq: seq,
724
+ contextVersion
725
+ }));
726
+ pruneForContextRebase({
727
+ commands,
728
+ runs,
729
+ recoveryContinuations,
730
+ turns,
731
+ inferences,
732
+ toolCalls,
733
+ messages,
734
+ stopRequests,
735
+ compactions
736
+ }, retainedFromContextSeq, summaryId);
737
+ context = {
738
+ version: contextVersion,
739
+ currentSummaryId: summaryId
740
+ };
741
+ break;
742
+ }
743
+ case compactionCompletedEventType: {
744
+ const { compactionId } = payload;
745
+ upsert(compactions, compactionId, { compactionId }, (record) => ({
746
+ ...record,
747
+ terminal: {
748
+ _tag: "Completed",
749
+ seq
750
+ }
751
+ }));
752
+ break;
753
+ }
754
+ case compactionFailedEventType: {
755
+ const { compactionId, error } = payload;
756
+ upsert(compactions, compactionId, { compactionId }, (record) => ({
757
+ ...record,
758
+ terminal: {
759
+ _tag: "Failed",
760
+ seq,
761
+ error
762
+ }
763
+ }));
764
+ const failed = compactions.get(compactionId);
765
+ if (failed?.summaryId === void 0 || failed.summaryId !== context.currentSummaryId) compactions.delete(compactionId);
766
+ break;
767
+ }
768
+ case recoveryCompletedEventType: {
769
+ const { continuation } = payload;
770
+ if (continuation !== void 0) recoveryContinuations.set(continuation.replacementRunId, {
771
+ ...continuation,
772
+ seq
773
+ });
774
+ break;
775
+ }
776
+ case baseStateRequestedEventType:
777
+ case baseStateCreatedEventType:
778
+ case baseStateFailedEventType: break;
779
+ default: assertNever(event, "reduced-state durable event");
780
+ }
781
+ }
782
+ return {
783
+ lastSeq,
784
+ commands,
785
+ runs,
786
+ recoveryContinuations,
787
+ turns,
788
+ inferences,
789
+ toolCalls,
790
+ messages,
791
+ stopRequests,
792
+ compactions,
793
+ context,
794
+ tokenConsumption,
795
+ commandQueues: deriveCommandQueues({
796
+ commands,
797
+ runs,
798
+ messages
799
+ })
800
+ };
801
+ };
802
+ /** Fold committed events from genesis into a fresh `ReducedState`. */
803
+ const reduceCommittedEvents = (committed) => foldReducedState(initialReducedState, committed);
804
+ const addTokenUsage = (state, usage) => {
805
+ if (usage === void 0) return state;
806
+ return { total: {
807
+ inputTokens: state.total.inputTokens + tokenCount(usage.inputTokens),
808
+ cachedInputTokens: state.total.cachedInputTokens + tokenCount(usage.cachedInputTokens),
809
+ outputTokens: state.total.outputTokens + tokenCount(usage.outputTokens),
810
+ textTokens: state.total.textTokens + tokenCount(usage.textTokens),
811
+ reasoningTokens: state.total.reasoningTokens + tokenCount(usage.reasoningTokens)
812
+ } };
813
+ };
814
+ const tokenCount = (value) => nonNegativeNumber(value);
815
+ const nonNegativeNumber = (value) => value === void 0 || !Number.isFinite(value) ? 0 : Math.max(0, Math.trunc(value));
816
+ /** Drop runtime state made model-invisible by a context rebase; storage remains append-only. */
817
+ const pruneForContextRebase = (maps, retainedFromContextSeq, currentSummaryId) => {
818
+ for (const [messageId, message] of maps.messages) if (message._tag !== "System" && messagePruneSeq(message) < retainedFromContextSeq) maps.messages.delete(messageId);
819
+ for (const [toolCallId, tool] of maps.toolCalls) {
820
+ const terminalSeq = tool.terminal?.seq;
821
+ if (terminalSeq !== void 0 && terminalSeq < retainedFromContextSeq) maps.toolCalls.delete(toolCallId);
822
+ }
823
+ for (const [inferenceId, inference] of maps.inferences) if (inference.terminal !== void 0 && inference.terminal.seq < retainedFromContextSeq) maps.inferences.delete(inferenceId);
824
+ for (const [turnId, turn] of maps.turns) if (turn.terminal !== void 0 && turn.terminal.seq < retainedFromContextSeq) maps.turns.delete(turnId);
825
+ for (const [runId, run] of maps.runs) if (run.terminal !== void 0 && run.terminal.seq < retainedFromContextSeq) maps.runs.delete(runId);
826
+ for (const replacementRunId of maps.recoveryContinuations.keys()) if (!maps.runs.has(replacementRunId)) maps.recoveryContinuations.delete(replacementRunId);
827
+ for (const [commandId, command] of maps.commands) if (command.terminal !== void 0 && command.terminal.seq < retainedFromContextSeq) maps.commands.delete(commandId);
828
+ for (const [commandId, request] of maps.stopRequests) if (request.appliedSeq !== void 0 && request.appliedSeq < retainedFromContextSeq) maps.stopRequests.delete(commandId);
829
+ for (const [compactionId, compaction] of maps.compactions) if (compaction.terminal !== void 0 && compaction.summaryId !== currentSummaryId) maps.compactions.delete(compactionId);
830
+ };
831
+ const messagePruneSeq = (message) => {
832
+ if (message._tag === "Steering") return message.consumedSeq ?? message.cancelledSeq ?? Number.POSITIVE_INFINITY;
833
+ return message.seq;
834
+ };
835
+ /** Pending admitted commands in deterministic scheduler order. */
836
+ const pendingCommands = (state) => state.commandQueues.pendingCommands;
837
+ /** First pending StopTurn control command, when one is waiting. */
838
+ const pendingStopCommand = (state) => state.commandQueues.activeControlCommands.find((command) => command.command._tag === "StopTurn");
839
+ /** Currently active command evidence, if any unfinished command is blocking FIFO work. */
840
+ const activeCommand = (state) => state.commandQueues.active;
841
+ /** Active run/turn/inference identity owned by a specific active command. */
842
+ const activeTurnIdentityForCommand = (state, commandId) => {
843
+ const run = findLast(Array.from(state.runs.values()), (candidate) => candidate.commandIds.includes(commandId));
844
+ if (run === void 0) return;
845
+ const turn = findLast(Array.from(state.turns.values()), (candidate) => candidate.runId === run.runId);
846
+ if (turn === void 0) return;
847
+ const inference = findLast(Array.from(state.inferences.values()), (candidate) => candidate.runId === run.runId && candidate.turnId === turn.turnId);
848
+ return {
849
+ runId: run.runId,
850
+ turnId: turn.turnId,
851
+ ...inference === void 0 ? {} : { inferenceId: inference.inferenceId }
852
+ };
853
+ };
854
+ /** Classify unfinished durable lifecycles that recovery may need to repair. */
855
+ const classifyRecoverableWork = (state) => {
856
+ const activeCommands = Array.from(state.commands.values()).filter((command) => command.startedSeq !== void 0 && command.terminal === void 0);
857
+ const activeRuns = Array.from(state.runs.values()).filter((run) => run.terminal === void 0);
858
+ const activeTurns = Array.from(state.turns.values()).filter((turn) => turn.terminal === void 0);
859
+ const activeInferences = Array.from(state.inferences.values()).filter((inference) => inference.terminal === void 0);
860
+ const openToolCalls = Array.from(state.toolCalls.values()).filter((tool) => tool.decision?._tag === "Created" && !tool.decision.providerExecuted && tool.terminal === void 0);
861
+ return {
862
+ activeCommands,
863
+ activeRuns,
864
+ activeTurns,
865
+ activeInferences,
866
+ openToolCalls,
867
+ runningToolCalls: openToolCalls.filter((tool) => tool.startedSeq !== void 0),
868
+ pendingStopRequests: Array.from(state.stopRequests.values()).filter((request) => request.appliedSeq === void 0 && state.commands.get(request.commandId)?.terminal === void 0),
869
+ openCompactions: Array.from(state.compactions.values()).filter((compaction) => compaction.terminal === void 0)
870
+ };
871
+ };
872
+ const assistantContentFromPromptParts = (promptParts) => {
873
+ const text = promptParts.filter((part) => part.type === "text").map((part) => part.text).join("");
874
+ const reasoning = promptParts.filter((part) => part.type === "reasoning").map((part) => part.text).join("");
875
+ return {
876
+ text,
877
+ ...reasoning.length === 0 ? {} : { reasoning }
878
+ };
879
+ };
880
+ const findLast = (items, predicate) => {
881
+ for (let index = items.length - 1; index >= 0; index -= 1) {
882
+ const item = items[index];
883
+ if (predicate(item)) return item;
884
+ }
885
+ };
886
+ const requireAdmittedCommandId = (command) => {
887
+ if (command.commandId !== void 0) return command.commandId;
888
+ throw new Error("CommandAdmitted command is missing a framework commandId");
889
+ };
890
+ const terminalTiming = (record, terminalAtMs) => ({
891
+ terminalAtMs,
892
+ ...record.startedAtMs === void 0 ? {} : { durationMs: Math.max(0, terminalAtMs - record.startedAtMs) }
893
+ });
894
+ const upsert = (map, key, fallback, update) => {
895
+ map.set(key, update(map.get(key) ?? fallback));
896
+ };
897
+ const updateExisting = (map, key, update) => {
898
+ const record = map.get(key);
899
+ if (record !== void 0) map.set(key, update(record));
900
+ };
901
+ const appliedFields = (record) => record?.appliedSeq === void 0 ? {} : {
902
+ appliedSeq: record.appliedSeq,
903
+ appliedRunId: record.appliedRunId,
904
+ appliedTurnId: record.appliedTurnId,
905
+ ...record.appliedInferenceId === void 0 ? {} : { appliedInferenceId: record.appliedInferenceId }
906
+ };
907
+ //#endregion
908
+ 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 };
909
+
910
+ //# sourceMappingURL=reduced-state-C4nVVzz9.js.map