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

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