effect-durable-agent 0.1.0-alpha.22 → 0.1.0-alpha.23

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 (56) hide show
  1. package/dist/domain/command-queues.d.ts +1 -1
  2. package/dist/domain/message-transcript.d.ts +1 -1
  3. package/dist/domain/reduced-state.d.ts +1 -1
  4. package/dist/domain/run-scheduling.d.ts +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/records-DWKEjuqb.js +675 -0
  7. package/dist/records-DWKEjuqb.js.map +1 -0
  8. package/dist/{reduced-state-PJdig48e.d.ts → reduced-state-B5WxKSM5.d.ts} +4206 -4206
  9. package/dist/{reducer-registry-BAbhZs6d.d.ts → reducer-registry-CPObI3cs.d.ts} +2 -2
  10. package/dist/{run-scheduling-wakeup-QLK87OqG.d.ts → run-scheduling-wakeup-B19JTeyq.d.ts} +2 -2
  11. package/dist/services/compaction.d.ts +1 -1
  12. package/dist/services/model-call.d.ts +1 -1
  13. package/dist/services/prompt-projector.d.ts +1 -1
  14. package/dist/services/reducer-registry.d.ts +1 -1
  15. package/dist/services/reducer-registry.js +1 -1
  16. package/dist/services/run-scheduler.d.ts +1 -1
  17. package/dist/services/run-scheduling-wakeup.d.ts +1 -1
  18. package/dist/services/runtime-layer.d.ts +6 -6
  19. package/dist/services/runtime-layer.js +3 -3
  20. package/dist/services/runtime.d.ts +1 -1
  21. package/dist/services/runtime.js +1 -1
  22. package/dist/services/session-query.d.ts +1 -1
  23. package/dist/services/session-query.js +2 -2
  24. package/dist/services/session-state.d.ts +1 -1
  25. package/dist/services/session-state.js +1 -1
  26. package/dist/services/session-store.d.ts +1 -1
  27. package/dist/services/session-store.js +1 -1
  28. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  29. package/dist/services/sink-registry.d.ts +1 -1
  30. package/dist/services/sink-registry.js +1 -1
  31. package/dist/services/tool-registry.d.ts +1 -1
  32. package/dist/{session-state-StlO5B2N.js → session-state-C6SyphC0.js} +3 -3
  33. package/dist/{session-state-StlO5B2N.js.map → session-state-C6SyphC0.js.map} +1 -1
  34. package/dist/{session-store-ByDjS03N.d.ts → session-store-CWYZ29CV.d.ts} +163 -45
  35. package/dist/{session-store-DcJjs4Fd.js → session-store-DuEhcqIC.js} +3 -2
  36. package/dist/{session-store-DcJjs4Fd.js.map → session-store-DuEhcqIC.js.map} +1 -1
  37. package/dist/{sink-checkpoint-store-BHb8YRTw.d.ts → sink-checkpoint-store-B8Ky5nfW.d.ts} +2 -2
  38. package/dist/{sink-registry-DEneTH8u.js → sink-registry-DtrssBxF.js} +2 -2
  39. package/dist/{sink-registry-DEneTH8u.js.map → sink-registry-DtrssBxF.js.map} +1 -1
  40. package/dist/subscription-DelB8L87.d.ts +958 -0
  41. package/dist/subscription-g5W0Ggqx.js +498 -0
  42. package/dist/subscription-g5W0Ggqx.js.map +1 -0
  43. package/dist/testkit/layers.d.ts +9 -6
  44. package/dist/testkit/layers.js +4 -4
  45. package/dist/testkit/layers.js.map +1 -1
  46. package/dist/{tool-registry-CxZ0iuYb.d.ts → tool-registry-B_WE2ZwK.d.ts} +2 -2
  47. package/dist/transcript.d.ts +44 -4
  48. package/dist/transcript.js +98 -170
  49. package/dist/transcript.js.map +1 -1
  50. package/dist/websocket.d.ts +2209 -2
  51. package/dist/websocket.js +704 -18
  52. package/dist/websocket.js.map +1 -1
  53. package/dist/{window-read-B8aF_hDq.js → window-read-BDayZf7O.js} +74 -683
  54. package/dist/window-read-BDayZf7O.js.map +1 -0
  55. package/package.json +1 -1
  56. package/dist/window-read-B8aF_hDq.js.map +0 -1
@@ -1,673 +1,14 @@
1
- import { CommandId, CompactionId, ContextVersion, EventId, InferenceId, MessageId, RunId, SequenceNumber, SummaryId, ToolCallId, TurnId } from "./types/core.js";
2
- import { _ as UsagePayload, f as ProviderPartId, g as UnixEpochMillis, h as ToolName, l as ModelSelectionPayload, p as SchemaVersion, s as FailurePayload, u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
3
- import { TokenConsumptionState, addModelUsage } from "./domain/model-usage.js";
4
- import { CommandIdempotencyKey, SubmitMessageDisposition } from "./types/commands.js";
5
- import { $n as pendingMessagesPausedEventType, An as baseStateCreatedEventType, Bn as compactionRequestedEventType, Cr as turnStartedEventType, Dn as assistantMessageCommittedEventType, Dr as userMessagePromotedEventType, Er as userMessageCommittedEventType, Fn as commandCompletedEventType, Hn as contextProjectedEventType, In as commandFailedEventType, Jn as inferenceCompletedEventType, Ln as commandStartedEventType, Mn as baseStateRequestedEventType, Nn as commandAdmittedEventType, On as assistantMessageImportedEventType, Or as userMessageSubmittedEventType, Pn as commandCancelledEventType, Qn as messageQueuePausedEventType, Rn as compactionCompletedEventType, Sr as turnFailedEventType, Tr as userMessageCancelledEventType, Un as contextRebasedEventType, Vn as compactionStartedEventType, Xn as inferenceStartedEventType, Yn as inferenceFailedEventType, Zn as interpretLegacyAttemptForReduction, _r as toolCallCreatedEventType, ar as runSchedulingGrantedEventType, br as toolCallStartedEventType, cr as runStartedEventType, dr as steeringMessageQueuedEventType, er as recoveryCompletedEventType, fr as stopTurnAppliedEventType, gr as toolCallCompletedEventType, hr as systemMessageCommittedEventType, ir as runSchedulingDeliveredEventType, jn as baseStateFailedEventType, kn as assistantPartialCommittedEventType, lr as sessionConfiguredEventType, mr as summaryCreatedEventType, nr as runFailedEventType, or as runSchedulingInvalidatedEventType, pr as stopTurnRequestedEventType, rr as runInterruptedEventType, sr as runSchedulingRequestedEventType, tn as ToolCallRejectionReason, tr as runCompletedEventType, ur as steeringMessageCancelledEventType, vr as toolCallFailedEventType, wr as turnStoppedEventType, xr as turnCompletedEventType, yr as toolCallRejectedEventType, zn as compactionFailedEventType } from "./durable-CD__3ztN.js";
1
+ import { CommandId, SequenceNumber } from "./types/core.js";
2
+ import { f as ProviderPartId, g as UnixEpochMillis, h as ToolName, l as ModelSelectionPayload, p as SchemaVersion, s as FailurePayload, u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
3
+ import { addModelUsage } from "./domain/model-usage.js";
4
+ import { CommandIdempotencyKey } from "./types/commands.js";
5
+ import { $n as pendingMessagesPausedEventType, An as baseStateCreatedEventType, Bn as compactionRequestedEventType, Cr as turnStartedEventType, Dn as assistantMessageCommittedEventType, Dr as userMessagePromotedEventType, Er as userMessageCommittedEventType, Fn as commandCompletedEventType, Hn as contextProjectedEventType, In as commandFailedEventType, Jn as inferenceCompletedEventType, Ln as commandStartedEventType, Mn as baseStateRequestedEventType, Nn as commandAdmittedEventType, On as assistantMessageImportedEventType, Or as userMessageSubmittedEventType, Pn as commandCancelledEventType, Qn as messageQueuePausedEventType, Rn as compactionCompletedEventType, Sr as turnFailedEventType, Tr as userMessageCancelledEventType, Un as contextRebasedEventType, Vn as compactionStartedEventType, Xn as inferenceStartedEventType, Yn as inferenceFailedEventType, Zn as interpretLegacyAttemptForReduction, _r as toolCallCreatedEventType, ar as runSchedulingGrantedEventType, br as toolCallStartedEventType, cr as runStartedEventType, dr as steeringMessageQueuedEventType, er as recoveryCompletedEventType, fr as stopTurnAppliedEventType, gr as toolCallCompletedEventType, hr as systemMessageCommittedEventType, ir as runSchedulingDeliveredEventType, jn as baseStateFailedEventType, kn as assistantPartialCommittedEventType, lr as sessionConfiguredEventType, mr as summaryCreatedEventType, nr as runFailedEventType, or as runSchedulingInvalidatedEventType, pr as stopTurnRequestedEventType, rr as runInterruptedEventType, sr as runSchedulingRequestedEventType, tr as runCompletedEventType, ur as steeringMessageCancelledEventType, vr as toolCallFailedEventType, wr as turnStoppedEventType, xr as turnCompletedEventType, yr as toolCallRejectedEventType, zn as compactionFailedEventType } from "./durable-CD__3ztN.js";
6
6
  import { t as assertNever } from "./assert-never-CoyUpoRB.js";
7
- import { JsonUserMessageContent } from "./domain/reduced-state-schema.js";
7
+ import { A as TranscriptRecordFromEnvelope, E as TranscriptOrder, H as TranscriptVersion, K as runGroupStatus, O as TranscriptRecord, S as TranscriptDecorationKey, W as isPendingTranscriptUserRecord, Y as transcriptRecordId, Z as sha256Hex, b as TranscriptDecorationEntryId, h as TranscriptClassification, w as TranscriptFieldPath } from "./records-DWKEjuqb.js";
8
8
  import * as Context from "effect/Context";
9
9
  import * as Effect from "effect/Effect";
10
10
  import * as Schema from "effect/Schema";
11
- import * as Order from "effect/Order";
12
- import * as SchemaTransformation from "effect/SchemaTransformation";
13
11
  import * as Result from "effect/Result";
14
- import * as SchemaGetter from "effect/SchemaGetter";
15
- //#region src/transcript/hash.ts
16
- /**
17
- * Synchronous hashing for transcript identities (versions and bounded record keys).
18
- */
19
- const roundConstants = new Uint32Array([
20
- 1116352408,
21
- 1899447441,
22
- 3049323471,
23
- 3921009573,
24
- 961987163,
25
- 1508970993,
26
- 2453635748,
27
- 2870763221,
28
- 3624381080,
29
- 310598401,
30
- 607225278,
31
- 1426881987,
32
- 1925078388,
33
- 2162078206,
34
- 2614888103,
35
- 3248222580,
36
- 3835390401,
37
- 4022224774,
38
- 264347078,
39
- 604807628,
40
- 770255983,
41
- 1249150122,
42
- 1555081692,
43
- 1996064986,
44
- 2554220882,
45
- 2821834349,
46
- 2952996808,
47
- 3210313671,
48
- 3336571891,
49
- 3584528711,
50
- 113926993,
51
- 338241895,
52
- 666307205,
53
- 773529912,
54
- 1294757372,
55
- 1396182291,
56
- 1695183700,
57
- 1986661051,
58
- 2177026350,
59
- 2456956037,
60
- 2730485921,
61
- 2820302411,
62
- 3259730800,
63
- 3345764771,
64
- 3516065817,
65
- 3600352804,
66
- 4094571909,
67
- 275423344,
68
- 430227734,
69
- 506948616,
70
- 659060556,
71
- 883997877,
72
- 958139571,
73
- 1322822218,
74
- 1537002063,
75
- 1747873779,
76
- 1955562222,
77
- 2024104815,
78
- 2227730452,
79
- 2361852424,
80
- 2428436474,
81
- 2756734187,
82
- 3204031479,
83
- 3329325298
84
- ]);
85
- const rotateRight = (value, bits) => value >>> bits | value << 32 - bits;
86
- const at = (words, index) => words[index] ?? 0;
87
- /** Lowercase hex SHA-256 of a string's UTF-8 bytes. */
88
- const sha256Hex = (input) => {
89
- const message = new TextEncoder().encode(input);
90
- const bitLength = message.length * 8;
91
- const paddedLength = Math.ceil((message.length + 9) / 64) * 64;
92
- const padded = new Uint8Array(paddedLength);
93
- padded.set(message);
94
- padded[message.length] = 128;
95
- const view = new DataView(padded.buffer);
96
- view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
97
- view.setUint32(paddedLength - 4, bitLength >>> 0);
98
- const hash = new Uint32Array([
99
- 1779033703,
100
- 3144134277,
101
- 1013904242,
102
- 2773480762,
103
- 1359893119,
104
- 2600822924,
105
- 528734635,
106
- 1541459225
107
- ]);
108
- const schedule = /* @__PURE__ */ new Uint32Array(64);
109
- for (let offset = 0; offset < paddedLength; offset += 64) {
110
- for (let index = 0; index < 16; index += 1) schedule[index] = view.getUint32(offset + index * 4);
111
- for (let index = 16; index < 64; index += 1) {
112
- const w15 = at(schedule, index - 15);
113
- const w2 = at(schedule, index - 2);
114
- const s0 = rotateRight(w15, 7) ^ rotateRight(w15, 18) ^ w15 >>> 3;
115
- const s1 = rotateRight(w2, 17) ^ rotateRight(w2, 19) ^ w2 >>> 10;
116
- schedule[index] = at(schedule, index - 16) + s0 + at(schedule, index - 7) + s1;
117
- }
118
- const working = Uint32Array.from(hash);
119
- for (let index = 0; index < 64; index += 1) {
120
- const [a, b, c, d, e, f, g, h] = Array.from(working);
121
- const s1 = rotateRight(e ?? 0, 6) ^ rotateRight(e ?? 0, 11) ^ rotateRight(e ?? 0, 25);
122
- const choice = (e ?? 0) & (f ?? 0) ^ ~(e ?? 0) & (g ?? 0);
123
- const t1 = (h ?? 0) + s1 + choice + at(roundConstants, index) + at(schedule, index);
124
- const s0 = rotateRight(a ?? 0, 2) ^ rotateRight(a ?? 0, 13) ^ rotateRight(a ?? 0, 22);
125
- const majority = (a ?? 0) & (b ?? 0) ^ (a ?? 0) & (c ?? 0) ^ (b ?? 0) & (c ?? 0);
126
- working.set([
127
- t1 + s0 + majority,
128
- a ?? 0,
129
- b ?? 0,
130
- c ?? 0,
131
- (d ?? 0) + t1,
132
- e ?? 0,
133
- f ?? 0,
134
- g ?? 0
135
- ]);
136
- }
137
- for (let index = 0; index < 8; index += 1) hash[index] = at(hash, index) + at(working, index);
138
- }
139
- return Array.from(hash, (word) => word.toString(16).padStart(8, "0")).join("");
140
- };
141
- //#endregion
142
- //#region src/transcript/records.ts
143
- /** One logical user submission across every lifecycle state: `user:<commandId>`. */
144
- const UserRecordId = Schema.TemplateLiteral(["user:", CommandId]);
145
- /** One model inference's visible output: `assistant:<inferenceId>`. */
146
- const InferenceAssistantRecordId = Schema.TemplateLiteral(["assistant:", InferenceId]);
147
- /** Assistant context imported from another transport, keyed by its import event: `import:<eventId>`. */
148
- const ImportAssistantRecordId = Schema.TemplateLiteral(["import:", EventId]);
149
- /** Either assistant identity; both are top-level assistant records. */
150
- const AssistantRecordId = Schema.Union([InferenceAssistantRecordId, ImportAssistantRecordId]);
151
- /** The marker a context rebase leaves in history: `compaction:<compactionId>`. */
152
- const CompactionRecordId = Schema.TemplateLiteral(["compaction:", CompactionId]);
153
- /** A framework tool call, a dependency of its assistant: `tool:<toolCallId>`. */
154
- const ToolRecordId = Schema.TemplateLiteral(["tool:", ToolCallId]);
155
- /**
156
- * A run plus every startup-recovery continuation of it: `run:<rootRunId>`.
157
- *
158
- * The id names the first run of the chain and never changes when a continuation joins.
159
- */
160
- const RunGroupRecordId = Schema.TemplateLiteral(["run:", RunId]);
161
- /** The session-context singleton. */
162
- const SessionContextRecordId = Schema.Literal("session");
163
- /**
164
- * Internal holding record for decorations whose target user record does not exist yet.
165
- *
166
- * Hosts append decoration events before the command they describe (Gia submits
167
- * `[author, attachments…, SubmitMessage]` in one batch), so the interpreter parks them under the
168
- * association key and merges them when the user record is created. Never served by a window read.
169
- */
170
- const DecorationBufferRecordId = Schema.TemplateLiteral([
171
- "decorations:",
172
- Schema.Literals(["command", "idempotencyKey"]),
173
- ":",
174
- Schema.NonEmptyString.check(Schema.isMaxLength(512))
175
- ]);
176
- /** Every transcript record identity this EDA release writes. */
177
- const TranscriptRecordId = Schema.Union([
178
- UserRecordId,
179
- AssistantRecordId,
180
- CompactionRecordId,
181
- ToolRecordId,
182
- RunGroupRecordId,
183
- SessionContextRecordId,
184
- DecorationBufferRecordId
185
- ]);
186
- /** Constructors for record identities; the only place identities are spelled. */
187
- const transcriptRecordId = {
188
- user: (commandId) => `user:${commandId}`,
189
- assistant: (inferenceId) => `assistant:${inferenceId}`,
190
- import: (eventId) => `import:${eventId}`,
191
- compaction: (compactionId) => `compaction:${compactionId}`,
192
- tool: (toolCallId) => `tool:${toolCallId}`,
193
- runGroup: (rootRunId) => `run:${rootRunId}`,
194
- session: "session",
195
- /**
196
- * Keys longer than 256 characters (caller-owned idempotency keys) are hashed to stay bounded;
197
- * keys starting with `#` are hashed too, so a literal key never collides with a hashed one.
198
- */
199
- decorationBuffer: (association, key) => `decorations:${association}:${key.length > 0 && key.length <= 256 && !key.startsWith("#") ? key : `#sha256:${sha256Hex(key)}`}`
200
- };
201
- /**
202
- * History position of a top-level record: the event that placed it and an ordinal among records
203
- * placed by that same event. Assigned once and never moved.
204
- */
205
- const TranscriptPosition = Schema.Struct({
206
- anchorSeq: SequenceNumber,
207
- ordinal: NonNegativeInt
208
- });
209
- /**
210
- * Adapter-owned identity of one physical event log. A wiped log gets a new incarnation, which
211
- * invalidates every cursor, chunk and body reference minted against the old one.
212
- */
213
- const TranscriptLogIncarnation = Schema.NonEmptyString.pipe(Schema.brand("TranscriptLogIncarnation"));
214
- /**
215
- * Identity of one transcript interpretation: a hash of the EDA semantic revision and the host's
216
- * canonical mapping data. Two sessions with equal versions interpret the same log identically.
217
- */
218
- const TranscriptVersion = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/)).pipe(Schema.brand("TranscriptVersion"));
219
- /**
220
- * Paging cursor: a point in the total order `(anchorSeq, ordinal, recordId)`.
221
- *
222
- * A cursor is meaningful only for the incarnation and version that minted it; readers reject
223
- * any other pairing rather than guess an equivalent point.
224
- */
225
- const TranscriptCursor = Schema.Struct({
226
- incarnation: TranscriptLogIncarnation,
227
- version: TranscriptVersion,
228
- anchorSeq: SequenceNumber,
229
- ordinal: NonNegativeInt,
230
- recordId: Schema.NonEmptyString
231
- });
232
- /** Total transcript order over top-level records. */
233
- const TranscriptOrder = Order.Struct({
234
- anchorSeq: Order.Number,
235
- ordinal: Order.Number,
236
- recordId: Order.String
237
- });
238
- /** A JSON path into an event payload; the empty path is the payload itself. */
239
- const TranscriptFieldPath = Schema.Array(Schema.Union([Schema.String, NonNegativeInt]));
240
- /** The immutable log location a body was read from. */
241
- const TranscriptBodySource = Schema.Struct({
242
- seq: SequenceNumber,
243
- path: TranscriptFieldPath
244
- });
245
- /**
246
- * Largest body a stored record holds inline, in canonical JSON bytes. Larger bodies are stored
247
- * as references, which keeps every stored row far below a Durable Object's 2 MB value limit no
248
- * matter how large an event payload is.
249
- */
250
- const transcriptStoredInlineBodyLimit = 65536;
251
- /**
252
- * A potentially large body (tool parameters and results).
253
- *
254
- * Stored records hold a body inline up to `transcriptStoredInlineBodyLimit` and as a reference
255
- * above it; a window read may also replace a smaller inline body with a reference. A reference
256
- * points at the body's immutable source in the append-only log, so it stays resolvable after
257
- * projection rows are rebuilt or deleted. The host authorizes reference resolution.
258
- */
259
- const TranscriptBody = Schema.TaggedUnion({
260
- Inline: {
261
- value: Schema.Json,
262
- source: TranscriptBodySource
263
- },
264
- Ref: {
265
- source: TranscriptBodySource,
266
- byteLength: NonNegativeInt
267
- }
268
- });
269
- /** Host-defined decoration name, as written by a mapping operation. */
270
- const TranscriptDecorationKey = Schema.String.check(Schema.isPattern(/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/));
271
- /** Key of one decoration list entry: an entry id or a host-assigned ordinal. */
272
- const TranscriptDecorationEntryKey = Schema.Union([Schema.String.check(Schema.isMaxLength(256)), NonNegativeInt]);
273
- /**
274
- * A host decoration value: a JSON scalar/object, or a keyed list whose entries are replaced by id
275
- * or ordinal. EDA treats the JSON as opaque; only the host gives it meaning.
276
- */
277
- const TranscriptDecoration = Schema.TaggedUnion({
278
- Value: { value: Schema.Json },
279
- List: { entries: Schema.Array(Schema.Struct({
280
- key: TranscriptDecorationEntryKey,
281
- value: Schema.Json
282
- })) }
283
- });
284
- /** Decorations of one record, keyed by host decoration name. */
285
- const TranscriptDecorations = Schema.Record(TranscriptDecorationKey, TranscriptDecoration);
286
- /** Host classification of a user record, such as an authenticated subagent notice. */
287
- const TranscriptClassification = TranscriptDecorationKey;
288
- const LifecycleTimingFields = {
289
- startedAtMs: Schema.optionalKey(UnixEpochMillis),
290
- terminalAtMs: Schema.optionalKey(UnixEpochMillis),
291
- durationMs: Schema.optionalKey(NonNegativeInt)
292
- };
293
- /**
294
- * Where a user submission is in its lifecycle.
295
- *
296
- * Only `Consumed` records are rendered in history. `Pending`, `Paused`, `Promoted` and `Steering`
297
- * are waiting to be read by the agent and are served as dependencies. `Cancelled` records stay
298
- * stored so their aliases resolve but are never rendered.
299
- */
300
- const TranscriptUserState = Schema.TaggedUnion({
301
- /** Admitted and queued for a later run. */
302
- Pending: {},
303
- /** Queued, but held because the user interrupted the run that would have read it. */
304
- Paused: { byCommandId: CommandId },
305
- /** Moved from the queue to steer the active run. */
306
- Promoted: {},
307
- /** Waiting to steer the active run. */
308
- Steering: {},
309
- /** Read by the agent; the record's position is the consumption point. */
310
- Consumed: {
311
- turnId: Schema.optionalKey(TurnId),
312
- runId: Schema.optionalKey(RunId)
313
- },
314
- /** Withdrawn before the agent read it, or withdrawn from the model context. */
315
- Cancelled: {
316
- reason: Schema.String,
317
- byCommandId: Schema.optionalKey(CommandId)
318
- }
319
- });
320
- const UserBodyFields = {
321
- commandId: CommandId,
322
- /** Every message id that has carried this submission; a replacement id joins as an alias. */
323
- messageIds: Schema.Array(MessageId),
324
- idempotencyKey: Schema.optionalKey(CommandIdempotencyKey),
325
- disposition: Schema.optionalKey(SubmitMessageDisposition),
326
- /**
327
- * JSON projection of the content: file bytes become data URLs, URLs become strings. Content is
328
- * inline; file data belongs in host attachments rather than message content.
329
- */
330
- content: JsonUserMessageContent,
331
- state: TranscriptUserState,
332
- /** Present when the submission arrived as steering for a specific run. */
333
- steering: Schema.optionalKey(Schema.Struct({ runId: RunId })),
334
- classification: Schema.optionalKey(TranscriptClassification),
335
- decorations: TranscriptDecorations,
336
- /** The first event that named this submission; pending users are served in this order. */
337
- submittedSeq: SequenceNumber,
338
- submittedAtMs: UnixEpochMillis,
339
- /** Present exactly when `position` is: the record was consumed at some point. */
340
- consumedAtMs: Schema.optionalKey(UnixEpochMillis)
341
- };
342
- /** Lifecycle of one assistant record. Imports are `Completed` from the start. */
343
- const TranscriptAssistantLifecycle = Schema.TaggedUnion({
344
- Streaming: {},
345
- Completed: {
346
- finishReason: Schema.optionalKey(Schema.String),
347
- usage: Schema.optionalKey(UsagePayload)
348
- },
349
- Failed: { error: FailurePayload }
350
- });
351
- /**
352
- * One ordered part of assistant output. Tool calls are references; their bodies live on the tool
353
- * dependency. Part types this release does not render are kept as `Unknown` so ordering survives.
354
- */
355
- const KnownAssistantPart = Schema.TaggedUnion({
356
- Text: { text: Schema.String },
357
- Reasoning: { text: Schema.String },
358
- ToolCall: {
359
- providerPartId: ProviderPartId,
360
- toolName: ToolName,
361
- providerExecuted: Schema.Boolean,
362
- /** The framework tool record, once the call has been sealed into one. */
363
- toolId: Schema.optionalKey(ToolRecordId)
364
- },
365
- /** Result of a provider-executed tool, which has no framework tool record. */
366
- ToolResult: {
367
- providerPartId: ProviderPartId,
368
- toolName: ToolName,
369
- isFailure: Schema.Boolean,
370
- result: TranscriptBody
371
- },
372
- Unknown: { partType: Schema.String }
373
- });
374
- /** A part whose tag or shape this reader does not know keeps its place as `Unknown`. */
375
- const knownAssistantPartTags = /* @__PURE__ */ new Set([
376
- "Text",
377
- "Reasoning",
378
- "ToolCall",
379
- "ToolResult",
380
- "Unknown"
381
- ]);
382
- const UnrecognizedAssistantPart = Schema.Struct({ _tag: Schema.String.check(Schema.makeFilter((tag) => !knownAssistantPartTags.has(tag) || "a known part tag must decode as that part")) }).pipe(Schema.decodeTo(Schema.toType(KnownAssistantPart.cases.Unknown), {
383
- decode: SchemaGetter.transform((part) => ({
384
- _tag: "Unknown",
385
- partType: part._tag
386
- })),
387
- encode: SchemaGetter.transform((part) => ({ _tag: part.partType }))
388
- }));
389
- /**
390
- * One ordered part of assistant output. A part tag this reader does not know decodes as
391
- * `Unknown`, keeping its place; a malformed part with a known tag is a decode failure.
392
- */
393
- const TranscriptAssistantPart = Schema.Union([KnownAssistantPart, UnrecognizedAssistantPart]);
394
- const AssistantBodyFields = {
395
- source: Schema.Literals(["inference", "import"]),
396
- inferenceId: InferenceId,
397
- runId: RunId,
398
- turnId: TurnId,
399
- /** Run group of the producing run; absent for imports and for runs the log never started. */
400
- runGroupId: Schema.optionalKey(RunGroupRecordId),
401
- messageId: Schema.optionalKey(MessageId),
402
- lifecycle: TranscriptAssistantLifecycle,
403
- parts: Schema.Array(TranscriptAssistantPart),
404
- /** Present when the visible parts were preserved from an interrupted or failed inference. */
405
- partial: Schema.optionalKey(Schema.Struct({ reason: Schema.String })),
406
- ...LifecycleTimingFields
407
- };
408
- const CompactionBodyFields = {
409
- compactionId: CompactionId,
410
- /** Reference to the summary artifact; the transcript never copies summary text. */
411
- summaryId: SummaryId,
412
- contextVersion: ContextVersion,
413
- retainedFromContextSeq: SequenceNumber,
414
- createdAtMs: UnixEpochMillis,
415
- /** Set by the first `CompactionCompleted`; later completions add no token usage. */
416
- completedAtMs: Schema.optionalKey(UnixEpochMillis)
417
- };
418
- /** Lifecycle of one framework tool call. The last terminal event wins. */
419
- const TranscriptToolLifecycle = Schema.TaggedUnion({
420
- Created: {},
421
- Running: {},
422
- Completed: { result: TranscriptBody },
423
- Failed: { error: FailurePayload },
424
- /** The call was not executable; terminal from creation. */
425
- Rejected: {
426
- reason: ToolCallRejectionReason,
427
- message: Schema.String,
428
- modelFeedback: Schema.String
429
- }
430
- });
431
- const ToolBodyFields = {
432
- toolCallId: ToolCallId,
433
- assistantId: InferenceAssistantRecordId,
434
- providerPartId: ProviderPartId,
435
- toolName: ToolName,
436
- providerExecuted: Schema.Boolean,
437
- /** Absent for a rejected call: a rejection records only the model-facing feedback. */
438
- params: Schema.optionalKey(TranscriptBody),
439
- lifecycle: TranscriptToolLifecycle,
440
- createdAtMs: UnixEpochMillis,
441
- ...LifecycleTimingFields
442
- };
443
- /** Outcome of one run inside a run group. */
444
- const TranscriptRunOutcome = Schema.TaggedUnion({
445
- Running: {},
446
- Completed: {},
447
- Failed: { error: FailurePayload },
448
- /** Stopped by the user or by a runtime restart; a continuation may follow. */
449
- Interrupted: { reason: Schema.String }
450
- });
451
- /** One run in a run group, in start order. */
452
- const TranscriptRunMember = Schema.Struct({
453
- runId: RunId,
454
- commandIds: Schema.Array(CommandId),
455
- modelSelection: ModelSelectionPayload,
456
- outcome: TranscriptRunOutcome,
457
- /** The interrupted run this one continues, as recorded by startup recovery. */
458
- continuationOf: Schema.optionalKey(RunId),
459
- ...LifecycleTimingFields
460
- });
461
- const RunGroupBodyFields = {
462
- rootRunId: RunId,
463
- /** Every run of the chain in start order; the last member's outcome is the group's status. */
464
- runs: Schema.NonEmptyArray(TranscriptRunMember)
465
- };
466
- const SessionContextBodyFields = {
467
- /** The run currently executing, if any. */
468
- activeRunId: Schema.optionalKey(RunId),
469
- /** The compaction currently in progress, if any. */
470
- activeCompactionId: Schema.optionalKey(CompactionId),
471
- /** Session execution policy: the first configured or started model, as the runtime reads it. */
472
- modelSelection: Schema.optionalKey(ModelSelectionPayload),
473
- /** Model of the most recently started run. */
474
- lastRunModelSelection: Schema.optionalKey(ModelSelectionPayload),
475
- tokenUsage: TokenConsumptionState,
476
- decorations: TranscriptDecorations
477
- };
478
- /** One decoration operation parked until its target exists, in arrival order. */
479
- const TranscriptBufferedDecoration = Schema.Struct({
480
- seq: SequenceNumber,
481
- mapping: TranscriptDecorationKey,
482
- /** Operation index within the mapping. */
483
- operation: NonNegativeInt,
484
- value: Schema.Json,
485
- entryKey: Schema.optionalKey(TranscriptDecorationEntryKey)
486
- });
487
- /**
488
- * Operations one decoration buffer keeps. Later operations for the same key are dropped, as are
489
- * operations beyond the mapping bounds' decoration byte budget.
490
- */
491
- const transcriptDecorationBufferLimit = 32;
492
- const DecorationBufferBodyFields = { operations: Schema.Array(TranscriptBufferedDecoration).check(Schema.isMaxLength(32)) };
493
- const commonFields = (kind, id) => ({
494
- kind: Schema.tag(kind),
495
- id,
496
- /** The last event that contributed to this record. */
497
- updatedSeq: SequenceNumber
498
- });
499
- /**
500
- * User submission, top-level once consumed; waiting states are dependencies.
501
- *
502
- * A position is assigned once, when the agent first reads the submission, so a consumed record
503
- * always has one and a waiting record never does. A cancelled record keeps the position it was
504
- * consumed at, if any, and is never rendered.
505
- */
506
- const TranscriptUserRecord = Schema.Struct({
507
- ...commonFields("user", UserRecordId),
508
- position: Schema.optionalKey(TranscriptPosition),
509
- ...UserBodyFields
510
- }).check(Schema.makeFilter((user) => user.position === void 0 === (user.consumedAtMs === void 0) || "position and consumedAtMs are assigned together"), Schema.makeFilter((user) => user.id === `user:${user.commandId}` || "a user record id names its command"), Schema.makeFilter((user) => {
511
- switch (user.state._tag) {
512
- case "Consumed": return user.position !== void 0 || "a consumed user record has a position";
513
- case "Cancelled": return true;
514
- default: return user.position === void 0 || "a waiting user record has no position";
515
- }
516
- }));
517
- /** Assistant output of one inference or one import; top-level. */
518
- const TranscriptAssistantRecord = Schema.Struct({
519
- ...commonFields("assistant", AssistantRecordId),
520
- position: TranscriptPosition,
521
- ...AssistantBodyFields
522
- }).check(Schema.makeFilter((assistant) => (assistant.source === "import" ? assistant.id.startsWith("import:") : assistant.id === `assistant:${assistant.inferenceId}`) || "an assistant record id matches its source and inference"));
523
- /** Compaction marker; top-level. */
524
- const TranscriptCompactionRecord = Schema.Struct({
525
- ...commonFields("compaction", CompactionRecordId),
526
- position: TranscriptPosition,
527
- ...CompactionBodyFields
528
- }).check(Schema.makeFilter((compaction) => compaction.id === `compaction:${compaction.compactionId}` || "a compaction record id names its compaction"));
529
- /** Framework tool call; a dependency of its assistant record. */
530
- const TranscriptToolRecord = Schema.Struct({
531
- ...commonFields("tool", ToolRecordId),
532
- ...ToolBodyFields
533
- }).check(Schema.makeFilter((tool) => tool.id === `tool:${tool.toolCallId}` || "a tool record id names its tool call"));
534
- /** Run and its recovery continuations; a dependency of the records it produced. */
535
- const TranscriptRunGroupRecord = Schema.Struct({
536
- ...commonFields("runGroup", RunGroupRecordId),
537
- ...RunGroupBodyFields
538
- }).check(Schema.makeFilter((group) => group.id === `run:${group.rootRunId}` && group.runs[0].runId === group.rootRunId || "a run group is named by, and starts with, its root run"));
539
- /** A run group's status: the outcome of its latest run. */
540
- const runGroupStatus = (group) => (group.runs[group.runs.length - 1] ?? group.runs[0]).outcome;
541
- /** Session activity, model selection and token totals; a singleton dependency. */
542
- const TranscriptSessionContextRecord = Schema.Struct({
543
- ...commonFields("sessionContext", SessionContextRecordId),
544
- ...SessionContextBodyFields
545
- });
546
- /** Internal decoration holding record; stored, never served. */
547
- const TranscriptDecorationBufferRecord = Schema.Struct({
548
- ...commonFields("decorationBuffer", DecorationBufferRecordId),
549
- ...DecorationBufferBodyFields
550
- });
551
- /** Every record kind this EDA release stores. */
552
- const TranscriptRecord = Schema.Union([
553
- TranscriptUserRecord,
554
- TranscriptAssistantRecord,
555
- TranscriptCompactionRecord,
556
- TranscriptToolRecord,
557
- TranscriptRunGroupRecord,
558
- TranscriptSessionContextRecord,
559
- TranscriptDecorationBufferRecord
560
- ]);
561
- /**
562
- * A record this reader cannot interpret: a newer kind, or a body written by a newer EDA.
563
- *
564
- * It keeps the identity, position and revision so a client can hold its place and render a safe
565
- * placeholder. Storage readers do not produce it: an undecodable stored row makes a read
566
- * unavailable instead of wrong.
567
- */
568
- const TranscriptUnknownRecord = Schema.Struct({
569
- kind: Schema.tag("unknown"),
570
- originalKind: Schema.NonEmptyString,
571
- /** The envelope format it arrived in, kept so it re-encodes exactly as it was read. */
572
- format: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
573
- /** The uninterpreted body, kept so a relaying reader forwards it unchanged. */
574
- body: Schema.Record(Schema.String, Schema.Unknown),
575
- id: Schema.NonEmptyString,
576
- updatedSeq: SequenceNumber,
577
- position: Schema.optionalKey(TranscriptPosition)
578
- });
579
- /** Top-level kinds count toward a window's record limit and carry a position. */
580
- const isTopLevelTranscriptRecord = (record) => record.kind === "assistant" || record.kind === "compaction" || record.kind === "user" && record.state._tag === "Consumed" && record.position !== void 0;
581
- /** A user record still waiting for the agent; served as a dependency, never twice. */
582
- const isPendingTranscriptUserRecord = (record) => record.kind === "user" && (record.state._tag === "Pending" || record.state._tag === "Paused" || record.state._tag === "Promoted" || record.state._tag === "Steering");
583
- /**
584
- * Current stored-row envelope format. Readers accept every format up to this one.
585
- *
586
- * Bump it whenever a known kind gains a value an older reader of this format could not decode
587
- * (a new lifecycle or state tag, a new required field). Older readers then show such rows as
588
- * `unknown` records; without a bump, a strict older reader would reject the whole window.
589
- */
590
- const transcriptRecordEnvelopeFormat = 1;
591
- /**
592
- * Backward-readable row and wire shape for one record.
593
- *
594
- * Identity, kind, revision and position sit outside the kind-specific `body` so any reader can
595
- * place a record it cannot interpret.
596
- */
597
- const TranscriptRecordEnvelope = Schema.Struct({
598
- format: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
599
- kind: Schema.NonEmptyString,
600
- id: Schema.NonEmptyString,
601
- updatedSeq: SequenceNumber,
602
- position: Schema.optionalKey(TranscriptPosition),
603
- body: Schema.Record(Schema.String, Schema.Unknown)
604
- });
605
- const envelopeToFlat = (envelope) => {
606
- const { kind, id, updatedSeq, position, body } = envelope;
607
- const { kind: _kind, id: _id, updatedSeq: _updatedSeq, position: _position, ...fields } = body;
608
- return {
609
- ...fields,
610
- kind,
611
- id,
612
- updatedSeq,
613
- ...position === void 0 ? {} : { position }
614
- };
615
- };
616
- const flatToEnvelope = (record) => {
617
- const { kind, id, updatedSeq, position, ...body } = record;
618
- return Schema.decodeUnknownSync(TranscriptRecordEnvelope)({
619
- format: 1,
620
- kind,
621
- id,
622
- updatedSeq,
623
- ...position === void 0 ? {} : { position },
624
- body
625
- });
626
- };
627
- const FlatRecordFields = Schema.Record(Schema.String, Schema.Unknown);
628
- /** A known record stored or sent as its envelope. Decoding fails for anything this reader cannot interpret. */
629
- const TranscriptRecordFromEnvelope = TranscriptRecordEnvelope.check(Schema.makeFilter((envelope) => envelope.format <= 1 || `unsupported transcript record envelope format ${envelope.format}`)).pipe(Schema.decodeTo(FlatRecordFields, {
630
- decode: SchemaGetter.transform(envelopeToFlat),
631
- encode: SchemaGetter.transform(flatToEnvelope)
632
- }), Schema.decodeTo(TranscriptRecord, SchemaTransformation.passthroughSupertype()));
633
- const knownRecordKinds = /* @__PURE__ */ new Set([
634
- "user",
635
- "assistant",
636
- "compaction",
637
- "tool",
638
- "runGroup",
639
- "sessionContext",
640
- "decorationBuffer"
641
- ]);
642
- /**
643
- * Only a kind this reader does not know, or a newer envelope format, becomes `unknown`; a
644
- * malformed record of a known kind in a known format is a decode failure, never a placeholder.
645
- */
646
- const TranscriptUnknownRecordFromEnvelope = TranscriptRecordEnvelope.check(Schema.makeFilter((envelope) => !knownRecordKinds.has(envelope.kind) || envelope.format > 1 || `a ${envelope.kind} record in format ${envelope.format} must decode as that kind`)).pipe(Schema.decodeTo(TranscriptUnknownRecord, {
647
- decode: SchemaGetter.transform((envelope) => ({
648
- kind: "unknown",
649
- originalKind: envelope.kind,
650
- format: envelope.format,
651
- body: envelope.body,
652
- id: envelope.id,
653
- updatedSeq: envelope.updatedSeq,
654
- ...envelope.position === void 0 ? {} : { position: envelope.position }
655
- })),
656
- encode: SchemaGetter.transform((record) => Schema.decodeUnknownSync(TranscriptRecordEnvelope)({
657
- format: record.format,
658
- kind: record.originalKind,
659
- id: record.id,
660
- updatedSeq: record.updatedSeq,
661
- ...record.position === void 0 ? {} : { position: record.position },
662
- body: record.body
663
- }))
664
- }));
665
- /**
666
- * Wire codec for one record: a known record when this reader can interpret it, otherwise an
667
- * explicit unknown record that keeps its id and position.
668
- */
669
- const TranscriptRecordViewFromEnvelope = Schema.Union([TranscriptRecordFromEnvelope, TranscriptUnknownRecordFromEnvelope]);
670
- //#endregion
671
12
  //#region src/transcript/version.ts
672
13
  /**
673
14
  * EDA's transcript semantic revision.
@@ -680,8 +21,11 @@ const TranscriptRecordViewFromEnvelope = Schema.Union([TranscriptRecordFromEnvel
680
21
  *
681
22
  * A CI fingerprint over a fixed scenario corpus (added with the interpreter) fails when
682
23
  * interpretation output changes and this constant does not; re-record it together with the bump.
24
+ *
25
+ * History: 1 — the initial interpreter (0.1.0-alpha.22). 2 — submissions consumed by one turn are
26
+ * ordered by submission, as the prompt orders them, not by the turn's input list.
683
27
  */
684
- const transcriptSemanticRevision = 1;
28
+ const transcriptSemanticRevision = 2;
685
29
  /**
686
30
  * Deterministic JSON: object keys sorted by code unit, no whitespace. Only JSON values are
687
31
  * accepted, so equal data always produces equal bytes.
@@ -754,7 +98,16 @@ const TranscriptListEntryKey = Schema.TaggedUnion({
754
98
  /** A string id at this payload path (for example an attachment id). */
755
99
  Id: { path: MappingPath },
756
100
  /** A non-negative integer ordinal at this payload path; the list is kept in ordinal order. */
757
- Ordinal: { path: MappingPath }
101
+ Ordinal: { path: MappingPath },
102
+ /**
103
+ * An id and an ordinal; the list is kept in ordinal order. A new entry replaces every entry with
104
+ * the same id **or** the same ordinal, so an input retried with new ids, or in a different
105
+ * order, never leaves a stale duplicate (attachments and references keyed by both).
106
+ */
107
+ IdOrOrdinal: {
108
+ id: MappingPath,
109
+ ordinal: MappingPath
110
+ }
758
111
  });
759
112
  /** One declarative decoration operation. Every `from` path reads the authenticated event payload. */
760
113
  const TranscriptMappingOperation = Schema.TaggedUnion({
@@ -768,7 +121,7 @@ const TranscriptMappingOperation = Schema.TaggedUnion({
768
121
  from: MappingPath,
769
122
  to: TranscriptDecorationKey
770
123
  },
771
- /** Insert or replace one entry of a decoration list, keyed by id or by ordinal. */
124
+ /** Insert or replace one entry of a decoration list, keyed by id, ordinal, or either. */
772
125
  ReplaceListEntry: {
773
126
  from: MappingPath,
774
127
  to: TranscriptDecorationKey,
@@ -875,7 +228,7 @@ var TranscriptDefinition = class TranscriptDefinition {
875
228
  const mappings = yield* Schema.decodeUnknownEffect(TranscriptMappings)(input).pipe(Effect.mapError((error) => new TranscriptDefinitionError({ message: error.message })));
876
229
  const problems = validationProblems(mappings);
877
230
  if (problems.length > 0) return yield* new TranscriptDefinitionError({ message: problems.join("; ") });
878
- return new TranscriptDefinition(computeTranscriptVersion(1, Schema.encodeSync(TranscriptMappings)(mappings)), 1, mappings);
231
+ return new TranscriptDefinition(computeTranscriptVersion(2, Schema.encodeSync(TranscriptMappings)(mappings)), 2, mappings);
879
232
  });
880
233
  };
881
234
  /** Validate host mapping data and derive its transcript version; see `TranscriptDefinition.make`. */
@@ -984,21 +337,44 @@ const prepareOperation = (mapping, operation, index, payload) => {
984
337
  }
985
338
  case "ReplaceListEntry": {
986
339
  const value = boundedJson(extract(payload, operation.from));
987
- const entryKey = listEntryKey(operation.key, payload);
988
- return value === void 0 || entryKey === void 0 ? [] : [{
340
+ const entry = listEntryKey(operation.key, payload);
341
+ return value === void 0 || entry === void 0 ? [] : [{
989
342
  mapping,
990
343
  operation: index,
991
344
  value,
992
- entryKey
345
+ entryKey: entry.key,
346
+ ...entry.id === void 0 ? {} : { entryId: entry.id }
993
347
  }];
994
348
  }
995
349
  }
996
350
  };
351
+ const entryIdAt = (payload, path) => {
352
+ const value = extract(payload, path);
353
+ return typeof value === "string" && Schema.is(TranscriptDecorationEntryId)(value) ? value : void 0;
354
+ };
355
+ const ordinalAt = (payload, path) => {
356
+ const value = extract(payload, path);
357
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
358
+ };
359
+ /** The entry's list key, and its id when the list is keyed by id or ordinal. */
997
360
  const listEntryKey = (key, payload) => {
998
- const value = extract(payload, key.path);
999
361
  switch (key._tag) {
1000
- case "Id": return typeof value === "string" && value.length > 0 && Schema.is(TranscriptDecorationEntryKey)(value) ? value : void 0;
1001
- case "Ordinal": return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
362
+ case "Id": {
363
+ const id = entryIdAt(payload, key.path);
364
+ return id === void 0 ? void 0 : { key: id };
365
+ }
366
+ case "Ordinal": {
367
+ const ordinal = ordinalAt(payload, key.path);
368
+ return ordinal === void 0 ? void 0 : { key: ordinal };
369
+ }
370
+ case "IdOrOrdinal": {
371
+ const id = entryIdAt(payload, key.id);
372
+ const ordinal = ordinalAt(payload, key.ordinal);
373
+ return id === void 0 || ordinal === void 0 ? void 0 : {
374
+ key: ordinal,
375
+ id
376
+ };
377
+ }
1002
378
  }
1003
379
  };
1004
380
  const park = (batch, seq, association, key, prepared) => {
@@ -1098,7 +474,7 @@ const applyOperation = (definition, target, prepared) => {
1098
474
  }) : target;
1099
475
  case "ReplaceListEntry": {
1100
476
  if (prepared.entryKey === void 0) return target;
1101
- const list = replaceListEntry(target.decorations[operation.to], prepared.entryKey, prepared.value, operation.key._tag === "Ordinal");
477
+ const list = replaceListEntry(target.decorations[operation.to], prepared.entryKey, prepared.value, operation.key._tag !== "Id", operation.key._tag === "IdOrOrdinal" ? prepared.entryId : void 0);
1102
478
  return list === void 0 ? target : withDecoration(target, operation.to, list);
1103
479
  }
1104
480
  }
@@ -1110,8 +486,20 @@ const withDecoration = (target, key, decoration) => ({
1110
486
  [key]: decoration
1111
487
  }
1112
488
  });
1113
- const replaceListEntry = (existing, key, value, ordered) => {
489
+ const replaceListEntry = (existing, key, value, ordered, id) => {
1114
490
  const entries = existing?._tag === "List" ? existing.entries : [];
491
+ if (id !== void 0) {
492
+ const kept = entries.filter((entry) => entry.key !== key && entry.id !== id);
493
+ if (kept.length === entries.length && entries.length >= transcriptMappingBounds.maxListEntries) return;
494
+ return {
495
+ _tag: "List",
496
+ entries: [...kept, {
497
+ key,
498
+ value,
499
+ id
500
+ }].sort((left, right) => Number(left.key) - Number(right.key))
501
+ };
502
+ }
1115
503
  const index = entries.findIndex((entry) => entry.key === key);
1116
504
  if (index >= 0) return {
1117
505
  _tag: "List",
@@ -1435,15 +823,18 @@ const interpretEvent = (batch, entry, seq) => {
1435
823
  }
1436
824
  case turnStartedEventType: {
1437
825
  const { runId, turnId, inputMessageIds } = event.payload;
826
+ const consumed = /* @__PURE__ */ new Map();
1438
827
  for (const messageId of inputMessageIds ?? []) {
1439
828
  const user = userByMessage(batch, messageId);
1440
829
  if (user === void 0 || user.state._tag === "Consumed") continue;
1441
830
  if (user.state._tag === "Cancelled" && user.steering === void 0) continue;
1442
- batch.put(consume(batch, user, seq, at, {
1443
- runId,
1444
- turnId
1445
- }));
831
+ consumed.set(user.id, user);
1446
832
  }
833
+ const ordered = [...consumed.values()].sort((left, right) => left.submittedSeq - right.submittedSeq || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
834
+ for (const user of ordered) batch.put(consume(batch, user, seq, at, {
835
+ runId,
836
+ turnId
837
+ }));
1447
838
  return;
1448
839
  }
1449
840
  case assistantMessageCommittedEventType:
@@ -2168,6 +1559,6 @@ const withBodyRefs = (record, maxInlineBodyBytes) => {
2168
1559
  }
2169
1560
  };
2170
1561
  //#endregion
2171
- export { TranscriptRecordId as $, SessionContextRecordId as A, TranscriptCursor as B, transcriptSemanticRevision as C, ImportAssistantRecordId as D, DecorationBufferRecordId as E, TranscriptBody as F, TranscriptDecorations as G, TranscriptDecorationBufferRecord as H, TranscriptBodySource as I, TranscriptOrder as J, TranscriptFieldPath as K, TranscriptBufferedDecoration as L, TranscriptAssistantLifecycle as M, TranscriptAssistantPart as N, InferenceAssistantRecordId as O, TranscriptAssistantRecord as P, TranscriptRecordFromEnvelope as Q, TranscriptClassification as R, computeTranscriptVersion as S, CompactionRecordId as T, TranscriptDecorationEntryKey as U, TranscriptDecoration as V, TranscriptDecorationKey as W, TranscriptRecord as X, TranscriptPosition as Y, TranscriptRecordEnvelope as Z, TranscriptUserFallback as _, transcriptRecordId as _t, TranscriptCursorMismatch as a, TranscriptToolLifecycle as at, transcriptMappingBounds as b, TranscriptProjectionError as c, TranscriptUserRecord as ct, TranscriptListEntryKey as d, UserRecordId as dt, TranscriptRecordViewFromEnvelope as et, TranscriptMappedEvent as f, isPendingTranscriptUserRecord as ft, TranscriptMappings as g, transcriptRecordEnvelopeFormat as gt, TranscriptMappingTarget as h, transcriptDecorationBufferLimit as ht, EDATranscriptStore as i, TranscriptSessionContextRecord as it, ToolRecordId as j, RunGroupRecordId as k, TranscriptDefinition as l, TranscriptUserState as lt, TranscriptMappingOperation as m, runGroupStatus as mt, readTranscriptWindowFrom as n, TranscriptRunMember as nt, planTranscriptBatch as o, TranscriptToolRecord as ot, TranscriptMapping as p, isTopLevelTranscriptRecord as pt, TranscriptLogIncarnation as q, transcriptReadiness as r, TranscriptRunOutcome as rt, TranscriptAliasNamespace as s, TranscriptUnknownRecord as st, buildingTranscriptWindow as t, TranscriptRunGroupRecord as tt, TranscriptDefinitionError as u, TranscriptVersion as ut, emptyTranscriptMappings as v, transcriptStoredInlineBodyLimit as vt, AssistantRecordId as w, canonicalJson as x, makeTranscriptDefinition as y, TranscriptCompactionRecord as z };
1562
+ export { transcriptSemanticRevision as C, computeTranscriptVersion as S, TranscriptUserFallback as _, TranscriptCursorMismatch as a, transcriptMappingBounds as b, TranscriptProjectionError as c, TranscriptListEntryKey as d, TranscriptMappedEvent as f, TranscriptMappings as g, TranscriptMappingTarget as h, EDATranscriptStore as i, TranscriptDefinition as l, TranscriptMappingOperation as m, readTranscriptWindowFrom as n, planTranscriptBatch as o, TranscriptMapping as p, transcriptReadiness as r, TranscriptAliasNamespace as s, buildingTranscriptWindow as t, TranscriptDefinitionError as u, emptyTranscriptMappings as v, canonicalJson as x, makeTranscriptDefinition as y };
2172
1563
 
2173
- //# sourceMappingURL=window-read-B8aF_hDq.js.map
1564
+ //# sourceMappingURL=window-read-BDayZf7O.js.map