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
@@ -0,0 +1,498 @@
1
+ import { SequenceNumber } from "./types/core.js";
2
+ import { u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
3
+ import { E as TranscriptOrder, G as isTopLevelTranscriptRecord, H as TranscriptVersion, M as TranscriptRecordViewFromEnvelope, T as TranscriptLogIncarnation, W as isPendingTranscriptUserRecord, _ as TranscriptCursor, a as InferenceAssistantRecordId, u as TranscriptAssistantPart } from "./records-DWKEjuqb.js";
4
+ import * as Effect from "effect/Effect";
5
+ import * as Schema from "effect/Schema";
6
+ import * as SchemaGetter from "effect/SchemaGetter";
7
+ //#region src/transcript/window.ts
8
+ const PositiveInt$1 = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
9
+ const orderKeyOfCursor = (cursor) => ({
10
+ anchorSeq: cursor.anchorSeq,
11
+ ordinal: cursor.ordinal,
12
+ recordId: cursor.recordId
13
+ });
14
+ /**
15
+ * Which slice of history to read.
16
+ *
17
+ * `Latest` serves first paint (SSR, CLIs); `Page` walks either direction from a cursor;
18
+ * `Range` re-reads exactly the span a client retains, inclusive of both ends, at one new cut.
19
+ */
20
+ const TranscriptWindowSelector = Schema.Union([
21
+ Schema.TaggedStruct("Latest", { count: PositiveInt$1 }),
22
+ Schema.TaggedStruct("Page", {
23
+ direction: Schema.Literals(["before", "after"]),
24
+ cursor: TranscriptCursor,
25
+ count: PositiveInt$1
26
+ }),
27
+ Schema.TaggedStruct("Range", {
28
+ from: TranscriptCursor,
29
+ to: TranscriptCursor
30
+ }).check(Schema.makeFilter((range) => range.from.incarnation === range.to.incarnation && range.from.version === range.to.version || "a range is scoped to one incarnation and version"), Schema.makeFilter((range) => TranscriptOrder(orderKeyOfCursor(range.from), orderKeyOfCursor(range.to)) <= 0 || "a range starts at or before its end"))
31
+ ]);
32
+ /**
33
+ * Bounds on one window. `maxRecords` caps top-level records (a selector's `count` is further
34
+ * capped by it); `maxBytes` caps the whole response, dependencies included; bodies above
35
+ * `maxInlineBodyBytes` are sent as references.
36
+ */
37
+ const TranscriptWindowLimits = Schema.Struct({
38
+ maxRecords: PositiveInt$1,
39
+ maxBytes: PositiveInt$1,
40
+ maxInlineBodyBytes: NonNegativeInt
41
+ });
42
+ /** Default bounds: the first window holds 100 top-level records (design decision 4). */
43
+ const defaultTranscriptWindowLimits = {
44
+ maxRecords: 100,
45
+ maxBytes: 1048576,
46
+ maxInlineBodyBytes: 16384
47
+ };
48
+ /**
49
+ * Whether the window is the current interpretation of the log, and if not, why its cut is
50
+ * behind.
51
+ *
52
+ * Every state other than `Ready` is a degraded read and obeys one rule: the response contains
53
+ * nothing newer than `throughSeq` — no newer pending users, session context or live content.
54
+ */
55
+ const KnownReadiness = Schema.TaggedUnion({
56
+ /** The active version is healthy and projected through the log head at read time. */
57
+ Ready: {},
58
+ /** The active version failed while projecting `failedAtSeq`; this is its last good cut. */
59
+ Degraded: {
60
+ failedAtSeq: SequenceNumber,
61
+ error: Schema.String
62
+ },
63
+ /**
64
+ * The active version is no longer carried by this release; history is being rebuilt under
65
+ * the current definition, and clients receive one replacement when it activates.
66
+ */
67
+ UpdatingHistory: {},
68
+ /** No version is servable yet; the window is empty. */
69
+ Building: {},
70
+ /**
71
+ * A stored row of the served version cannot be decoded by this release. Nothing is served
72
+ * until a rebuild finishes, rather than a wrong view; the window is empty.
73
+ */
74
+ Unreadable: { error: Schema.String },
75
+ /** A readiness this reader does not know; treated as degraded. */
76
+ Unknown: { readinessType: Schema.String }
77
+ });
78
+ const knownReadinessTags = /* @__PURE__ */ new Set([
79
+ "Ready",
80
+ "Degraded",
81
+ "UpdatingHistory",
82
+ "Building",
83
+ "Unreadable",
84
+ "Unknown"
85
+ ]);
86
+ const UnrecognizedReadiness = Schema.Struct({ _tag: Schema.String.check(Schema.makeFilter((tag) => !knownReadinessTags.has(tag) || "a known readiness must decode as that readiness")) }).pipe(Schema.decodeTo(Schema.toType(KnownReadiness.cases.Unknown), {
87
+ decode: SchemaGetter.transform((readiness) => ({
88
+ _tag: "Unknown",
89
+ readinessType: readiness._tag
90
+ })),
91
+ encode: SchemaGetter.transform((readiness) => ({ _tag: readiness.readinessType }))
92
+ }));
93
+ /**
94
+ * Whether the window is the current interpretation of the log. A readiness this reader does not
95
+ * know decodes as `Unknown` and is treated as degraded: it carries no live content. A malformed
96
+ * readiness with a known tag is a decode failure.
97
+ */
98
+ const TranscriptReadiness = Schema.Union([KnownReadiness, UnrecognizedReadiness]);
99
+ /**
100
+ * One live part of the inference streaming now.
101
+ *
102
+ * `id` is stable for the life of the part (`text:<providerPartId>`, `reasoning:<providerPartId>`,
103
+ * `tool:<toolCallId>`), so a client keys a streaming part by it and replaces it in place as it
104
+ * grows. `paramsText` is the tool-call parameter text streamed so far; it is speculative until
105
+ * the call is sealed into a tool record.
106
+ */
107
+ const TranscriptActivePart = Schema.Struct({
108
+ id: Schema.NonEmptyString,
109
+ part: TranscriptAssistantPart,
110
+ paramsText: Schema.optionalKey(Schema.String)
111
+ }).check(Schema.makeFilter((active) => (active.part._tag === "Text" ? active.id.startsWith("text:") : active.part._tag === "Reasoning" ? active.id.startsWith("reasoning:") : active.part._tag === "ToolCall" ? active.id.startsWith("tool:") : true) || "a live part's id names its kind"), Schema.makeFilter((active) => active.paramsText === void 0 || active.part._tag === "ToolCall" || "only a tool call streams parameter text"));
112
+ /**
113
+ * Accumulated parts of the inference streaming now, captured at the same publication boundary as
114
+ * the window. Owned by the live runtime; storage-level reads never include it.
115
+ */
116
+ const TranscriptActiveContent = Schema.Struct({
117
+ assistantId: InferenceAssistantRecordId,
118
+ parts: Schema.Array(TranscriptActivePart)
119
+ });
120
+ const recordUpdatedSeq = (record) => record.updatedSeq;
121
+ const recordPosition = (record) => "position" in record ? record.position : void 0;
122
+ /** Positioned history, which is served only as a top-level record and never as a dependency. */
123
+ const isHistoryRecord = (record) => record.kind === "unknown" ? record.position !== void 0 : isTopLevelTranscriptRecord(record);
124
+ /**
125
+ * One complete, consistent read of a transcript version.
126
+ *
127
+ * `records` are top-level records in transcript order; `dependencies` are the tools and run
128
+ * groups they reference, the session context, and every pending user record. Every record is
129
+ * projected through `throughSeq` and none is newer, which is what makes a cut complete. A client
130
+ * replaces, never merges, what a window covers.
131
+ */
132
+ const TranscriptWindow = Schema.Struct({
133
+ incarnation: TranscriptLogIncarnation,
134
+ version: TranscriptVersion,
135
+ throughSeq: SequenceNumber,
136
+ records: Schema.Array(TranscriptRecordViewFromEnvelope),
137
+ dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),
138
+ activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),
139
+ hasOlder: Schema.Boolean,
140
+ hasNewer: Schema.Boolean,
141
+ readiness: TranscriptReadiness
142
+ }).check(Schema.makeFilter((window) => [...window.records, ...window.dependencies].every((record) => recordUpdatedSeq(record) <= window.throughSeq) || "every record must be projected through throughSeq and none may be newer"), Schema.makeFilter((window) => window.readiness._tag === "Ready" || window.activeContent === void 0 || "a degraded read never attaches live content"), Schema.makeFilter((window) => window.readiness._tag !== "Degraded" || window.readiness.failedAtSeq > window.throughSeq || "a degraded cut ends before the seq that failed"), Schema.makeFilter((window) => [...window.records, ...window.dependencies].every((record) => record.kind !== "decorationBuffer" && (record.kind !== "unknown" || record.originalKind !== "decorationBuffer")) || "decoration buffers are never served"), Schema.makeFilter((window) => {
143
+ const ids = [...window.records, ...window.dependencies].map((record) => record.id);
144
+ return new Set(ids).size === ids.length || "a record is served at most once";
145
+ }), Schema.makeFilter((window) => window.records.every((record, index) => {
146
+ const position = recordPosition(record);
147
+ if (position === void 0 || !isHistoryRecord(record)) return false;
148
+ const previous = index === 0 ? void 0 : window.records[index - 1];
149
+ const previousPosition = previous === void 0 ? void 0 : recordPosition(previous);
150
+ return previous === void 0 || previousPosition === void 0 || TranscriptOrder({
151
+ ...previousPosition,
152
+ recordId: previous.id
153
+ }, {
154
+ ...position,
155
+ recordId: record.id
156
+ }) < 0;
157
+ }) || "records are positioned history records in transcript order"), Schema.makeFilter((window) => window.dependencies.every((record) => !isHistoryRecord(record)) || "dependencies never contain history records"), Schema.makeFilter((window) => window.dependencies.every((record) => record.kind !== "user" || isPendingTranscriptUserRecord(record)) || "the only user dependencies are pending users; cancelled users are never served"), Schema.makeFilter((window) => window.readiness._tag !== "Building" && window.readiness._tag !== "Unreadable" || window.records.length === 0 && window.dependencies.length === 0 && !window.hasOlder && !window.hasNewer || "a building or unreadable window is empty"));
158
+ /** Paging cursor for one top-level record of a window. */
159
+ const transcriptCursorOf = (window, record) => {
160
+ const position = "position" in record ? record.position : void 0;
161
+ return position === void 0 ? void 0 : {
162
+ incarnation: window.incarnation,
163
+ version: window.version,
164
+ anchorSeq: position.anchorSeq,
165
+ ordinal: position.ordinal,
166
+ recordId: record.id
167
+ };
168
+ };
169
+ /** Health of one stored transcript version. A failed version is frozen at its last good cursor. */
170
+ const TranscriptVersionStatus = Schema.TaggedUnion({
171
+ Ok: {},
172
+ Failed: {
173
+ failedAtSeq: SequenceNumber,
174
+ error: Schema.String
175
+ }
176
+ });
177
+ /**
178
+ * Per-version maintenance state, one per version present in a session's storage.
179
+ *
180
+ * `cursor` is the last fully projected seq, committed together with that version's rows. At most
181
+ * one version is `active` (served) and at most one is `building` (catching up from the log).
182
+ */
183
+ const TranscriptVersionMeta = Schema.Struct({
184
+ version: TranscriptVersion,
185
+ role: Schema.Literals(["active", "building"]),
186
+ cursor: SequenceNumber,
187
+ status: TranscriptVersionStatus
188
+ }).check(Schema.makeFilter((meta) => meta.status._tag !== "Failed" || meta.status.failedAtSeq > meta.cursor || "a failed version is frozen before the seq that failed"));
189
+ //#endregion
190
+ //#region src/transcript/subscription.ts
191
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
192
+ /** Client-chosen correlation id echoed on the update that answers a request. */
193
+ const TranscriptRequestId = Schema.NonEmptyString.check(Schema.isMaxLength(64));
194
+ /**
195
+ * The contiguous span of top-level records a subscriber holds, both ends inclusive. Absent when
196
+ * the subscriber holds no top-level records (an empty session, or a window still building).
197
+ */
198
+ const TranscriptCoverage = Schema.Struct({
199
+ from: TranscriptCursor,
200
+ to: TranscriptCursor
201
+ });
202
+ /**
203
+ * What a subscriber holds after its last complete update: the cut it was read at and the span it
204
+ * covers. Every update is planned relative to this base, which is also persisted with the socket
205
+ * so a hibernated subscription resumes without volatile state.
206
+ *
207
+ * `tail` is true when the coverage reaches the newest record of its cut; new history then joins
208
+ * the coverage as it is committed. A subscriber that paged back past the tail sees `hasNewer`
209
+ * instead and pages forward to rejoin it.
210
+ */
211
+ const TranscriptSubscriptionBase = Schema.Struct({
212
+ incarnation: TranscriptLogIncarnation,
213
+ version: TranscriptVersion,
214
+ throughSeq: SequenceNumber,
215
+ coverage: Schema.optionalKey(TranscriptCoverage),
216
+ tail: Schema.Boolean
217
+ });
218
+ /**
219
+ * One ordered, complete change to a subscriber's window: the only way a live client's window
220
+ * changes.
221
+ *
222
+ * - `replace` discards everything the client holds and installs this window.
223
+ * - `patch` is relative to the client's previous complete update: `records` and `dependencies`
224
+ * carry every record that changed or newly entered the window, `dependencyIds` lists the
225
+ * complete dependency membership of the new cut (the client drops any other dependency), and
226
+ * the client drops top-level records outside `coverage`.
227
+ *
228
+ * Either way the client ends at exactly the window read at `throughSeq`: a complete cut. When
229
+ * present, `activeContent` replaces the client's active content completely (an empty array
230
+ * clears it); when absent, active content is unchanged. A degraded update carries no live
231
+ * content, and a client shows none while readiness is not `Ready`.
232
+ */
233
+ const TranscriptUpdate = Schema.Struct({
234
+ updateSeq: PositiveInt,
235
+ mode: Schema.Literals(["replace", "patch"]),
236
+ incarnation: TranscriptLogIncarnation,
237
+ version: TranscriptVersion,
238
+ throughSeq: SequenceNumber,
239
+ coverage: Schema.optionalKey(TranscriptCoverage),
240
+ hasOlder: Schema.Boolean,
241
+ hasNewer: Schema.Boolean,
242
+ readiness: TranscriptReadiness,
243
+ records: Schema.Array(TranscriptRecordViewFromEnvelope),
244
+ dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),
245
+ dependencyIds: Schema.Array(Schema.NonEmptyString),
246
+ activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),
247
+ requestId: Schema.optionalKey(TranscriptRequestId)
248
+ }).check(Schema.makeFilter((update) => [...update.records, ...update.dependencies].every((record) => record.updatedSeq <= update.throughSeq) || "every record must be projected through throughSeq and none may be newer"), Schema.makeFilter((update) => update.readiness._tag === "Ready" || update.activeContent === void 0 || update.activeContent.length === 0 || "a degraded update never carries live content"), Schema.makeFilter((update) => {
249
+ const dependencyIds = new Set(update.dependencyIds);
250
+ return update.dependencies.every((record) => dependencyIds.has(record.id)) || "every sent dependency is a member of the cut";
251
+ }));
252
+ const defaultTranscriptSubscriptionPolicy = {
253
+ initialCount: 100,
254
+ maxPageCount: 100,
255
+ limits: {
256
+ maxRecords: 300,
257
+ maxBytes: 2097152,
258
+ maxInlineBodyBytes: 16384
259
+ }
260
+ };
261
+ const orderKey = (cursor) => ({
262
+ anchorSeq: cursor.anchorSeq,
263
+ ordinal: cursor.ordinal,
264
+ recordId: cursor.recordId
265
+ });
266
+ const sameCursor = (left, right) => left.incarnation === right.incarnation && left.version === right.version && TranscriptOrder(orderKey(left), orderKey(right)) === 0;
267
+ /**
268
+ * A cursor after every possible record of one version, so a `Range` ending at it reads from a
269
+ * point to the newest record. Never sent to clients.
270
+ */
271
+ const tailCursor = (from) => ({
272
+ incarnation: from.incarnation,
273
+ version: from.version,
274
+ anchorSeq: SequenceNumber.make(Number.MAX_SAFE_INTEGER),
275
+ ordinal: Number.MAX_SAFE_INTEGER,
276
+ recordId: "￿"
277
+ });
278
+ /** The span a window's top-level records cover, or `undefined` when it has none. */
279
+ const transcriptCoverageOf = (window) => {
280
+ const first = window.records[0];
281
+ const last = window.records[window.records.length - 1];
282
+ const from = first === void 0 ? void 0 : transcriptCursorOf(window, first);
283
+ const to = last === void 0 ? void 0 : transcriptCursorOf(window, last);
284
+ return from === void 0 || to === void 0 ? void 0 : {
285
+ from,
286
+ to
287
+ };
288
+ };
289
+ const withinCoverage = (coverage, record) => {
290
+ if (coverage === void 0 || !("position" in record) || record.position === void 0) return false;
291
+ const key = {
292
+ ...record.position,
293
+ recordId: record.id
294
+ };
295
+ return TranscriptOrder(orderKey(coverage.from), key) <= 0 && TranscriptOrder(key, orderKey(coverage.to)) <= 0;
296
+ };
297
+ /** The base a client holds after applying an update for `window`. */
298
+ const transcriptSubscriptionBaseOf = (window) => {
299
+ const coverage = transcriptCoverageOf(window);
300
+ return {
301
+ incarnation: window.incarnation,
302
+ version: window.version,
303
+ throughSeq: window.throughSeq,
304
+ ...coverage === void 0 ? {} : { coverage },
305
+ tail: !window.hasNewer
306
+ };
307
+ };
308
+ /**
309
+ * Plan the one update that moves a client from `patchBase` to `window`.
310
+ *
311
+ * A patch sends a top-level record when it changed after the base cut or was outside the base
312
+ * coverage. It sends a tool dependency when the tool changed or its assistant is sent, and any
313
+ * other dependency (run groups, session context, pending users) when it changed or any top-level
314
+ * record is sent. Everything else the client already holds unchanged from the base cut, because
315
+ * the base cut was itself complete. A different incarnation or version, or a base cut ahead of
316
+ * the window, makes the update a replacement.
317
+ */
318
+ const planTranscriptUpdate = (input) => {
319
+ const { window } = input;
320
+ const base = input.patchBase;
321
+ const patch = base !== void 0 && base.incarnation === window.incarnation && base.version === window.version && base.throughSeq <= window.throughSeq;
322
+ const records = patch ? window.records.filter((record) => record.updatedSeq > base.throughSeq || !withinCoverage(base.coverage, record)) : window.records;
323
+ const sentIds = new Set(records.map((record) => record.id));
324
+ const dependencies = patch ? window.dependencies.filter((record) => record.updatedSeq > base.throughSeq || (record.kind === "tool" ? sentIds.has(record.assistantId) : records.length > 0)) : window.dependencies;
325
+ const coverage = transcriptCoverageOf(window);
326
+ const activeContent = patch && !input.includeActiveContent ? void 0 : servedActiveContent(window, input.activeContent);
327
+ return {
328
+ updateSeq: input.updateSeq,
329
+ mode: patch ? "patch" : "replace",
330
+ incarnation: window.incarnation,
331
+ version: window.version,
332
+ throughSeq: window.throughSeq,
333
+ ...coverage === void 0 ? {} : { coverage },
334
+ hasOlder: window.hasOlder,
335
+ hasNewer: window.hasNewer,
336
+ readiness: window.readiness,
337
+ records,
338
+ dependencies,
339
+ dependencyIds: window.dependencies.map((record) => record.id),
340
+ ...activeContent === void 0 ? {} : { activeContent },
341
+ ...input.requestId === void 0 ? {} : { requestId: input.requestId }
342
+ };
343
+ };
344
+ /**
345
+ * Live content as served with a window: none on a degraded read, and never for an inference the
346
+ * window already shows as committed or failed, so a stale live part cannot override a terminal.
347
+ */
348
+ const servedActiveContent = (window, activeContent) => {
349
+ if (window.readiness._tag !== "Ready") return [];
350
+ const settled = new Set(window.records.flatMap((record) => record.kind === "assistant" && record.lifecycle._tag !== "Streaming" ? [record.id] : []));
351
+ return activeContent.filter((content) => !settled.has(content.assistantId));
352
+ };
353
+ /**
354
+ * Read the window that answers one request, at one cut.
355
+ *
356
+ * Helper reads (to find a page's far edge) may see other cuts; only the final read is served,
357
+ * so the update is always one synchronous read. Coverage stays within `limits.maxRecords`:
358
+ * paging back evicts the newest records, paging forward evicts the oldest, and a tail that
359
+ * outgrows the bound keeps its newest records. A cursor minted for another incarnation or version
360
+ * falls back to a replacement of the latest records.
361
+ */
362
+ const readTranscriptSubscription = (store, base, request, policy) => {
363
+ const read = (selector) => store.readTranscriptWindow(selector, policy.limits);
364
+ const latest = read({
365
+ _tag: "Latest",
366
+ count: Math.min(policy.initialCount, policy.limits.maxRecords)
367
+ }).pipe(Effect.map((window) => ({
368
+ window,
369
+ patchBase: void 0
370
+ })));
371
+ const readCoverage = Effect.fnUntraced(function* (coverage, tail, overflowToNewest) {
372
+ if (coverage === void 0) return yield* read({
373
+ _tag: "Latest",
374
+ count: Math.min(policy.initialCount, policy.limits.maxRecords)
375
+ });
376
+ if (!tail) return yield* read({
377
+ _tag: "Range",
378
+ ...coverage
379
+ });
380
+ const window = yield* read({
381
+ _tag: "Range",
382
+ from: coverage.from,
383
+ to: tailCursor(coverage.from)
384
+ });
385
+ return window.hasNewer && overflowToNewest ? yield* read({
386
+ _tag: "Latest",
387
+ count: Math.max(1, window.records.length)
388
+ }) : window;
389
+ });
390
+ return Effect.fnUntraced(function* () {
391
+ switch (request._tag) {
392
+ case "Subscribe": {
393
+ const count = Math.min(request.count ?? policy.initialCount, policy.limits.maxRecords);
394
+ if (request.range === void 0) return {
395
+ window: yield* read({
396
+ _tag: "Latest",
397
+ count
398
+ }),
399
+ patchBase: void 0
400
+ };
401
+ const claimed = {
402
+ incarnation: request.range.from.incarnation,
403
+ version: request.range.from.version,
404
+ throughSeq: request.since ?? SequenceNumber.make(0),
405
+ coverage: request.range,
406
+ tail: request.tail
407
+ };
408
+ return {
409
+ window: yield* readCoverage(request.range, request.tail, true),
410
+ patchBase: request.since === void 0 ? void 0 : claimed
411
+ };
412
+ }
413
+ case "Refresh":
414
+ if (base === void 0) return yield* latest;
415
+ return {
416
+ window: yield* readCoverage(base.coverage, base.tail, true),
417
+ patchBase: base
418
+ };
419
+ case "Page": {
420
+ const coverage = base?.coverage;
421
+ const edge = request.direction === "before" ? coverage?.from : coverage?.to;
422
+ if (base === void 0 || coverage === void 0 || edge === void 0) return base === void 0 ? yield* latest : {
423
+ window: yield* readCoverage(base.coverage, base.tail, true),
424
+ patchBase: base
425
+ };
426
+ if (!sameCursor(edge, request.cursor)) return {
427
+ window: yield* readCoverage(coverage, base.tail, true),
428
+ patchBase: base
429
+ };
430
+ const page = yield* read({
431
+ _tag: "Page",
432
+ direction: request.direction,
433
+ cursor: request.cursor,
434
+ count: Math.min(request.count, policy.maxPageCount, policy.limits.maxRecords)
435
+ });
436
+ const first = page.records[0];
437
+ const last = page.records[page.records.length - 1];
438
+ const pageFrom = first === void 0 ? void 0 : transcriptCursorOf(page, first);
439
+ const pageTo = last === void 0 ? void 0 : transcriptCursorOf(page, last);
440
+ if (pageFrom === void 0 || pageTo === void 0) return {
441
+ window: yield* readCoverage(coverage, base.tail, true),
442
+ patchBase: base
443
+ };
444
+ if (request.direction === "before") return {
445
+ window: yield* readCoverage({
446
+ from: pageFrom,
447
+ to: coverage.to
448
+ }, base.tail, false),
449
+ patchBase: base
450
+ };
451
+ const from = yield* evictOldest(read, coverage.from, pageTo, policy.limits.maxRecords);
452
+ return {
453
+ window: yield* readCoverage({
454
+ from,
455
+ to: pageTo
456
+ }, !page.hasNewer, false),
457
+ patchBase: base
458
+ };
459
+ }
460
+ case "Retain": {
461
+ const coverage = base?.coverage;
462
+ if (base === void 0 || coverage === void 0) return base === void 0 ? yield* latest : {
463
+ window: yield* readCoverage(base.coverage, base.tail, true),
464
+ patchBase: base
465
+ };
466
+ const retained = request.from.incarnation === base.incarnation && request.from.version === base.version && request.to.incarnation === base.incarnation && request.to.version === base.version && TranscriptOrder(orderKey(coverage.from), orderKey(request.from)) <= 0 && TranscriptOrder(orderKey(request.from), orderKey(request.to)) <= 0 && TranscriptOrder(orderKey(request.to), orderKey(coverage.to)) <= 0 ? {
467
+ from: request.from,
468
+ to: request.to
469
+ } : coverage;
470
+ const tail = base.tail && sameCursor(retained.to, coverage.to);
471
+ return {
472
+ window: yield* readCoverage(retained, tail, true),
473
+ patchBase: base
474
+ };
475
+ }
476
+ }
477
+ })().pipe(Effect.catchTag("TranscriptCursorMismatch", () => latest.pipe(Effect.catchTag("TranscriptCursorMismatch", Effect.die))));
478
+ };
479
+ /**
480
+ * The oldest cursor a span ending at `to` may start from without exceeding `maxRecords`: the
481
+ * current `from`, or later when the span would be over the bound.
482
+ */
483
+ const evictOldest = Effect.fnUntraced(function* (read, from, to, maxRecords) {
484
+ if (maxRecords <= 1) return to;
485
+ const before = yield* read({
486
+ _tag: "Page",
487
+ direction: "before",
488
+ cursor: to,
489
+ count: maxRecords - 1
490
+ });
491
+ const first = before.records[0];
492
+ const oldest = first === void 0 ? void 0 : transcriptCursorOf(before, first);
493
+ return oldest === void 0 || TranscriptOrder(orderKey(oldest), orderKey(from)) <= 0 ? from : oldest;
494
+ });
495
+ //#endregion
496
+ export { TranscriptWindowSelector as _, defaultTranscriptSubscriptionPolicy as a, transcriptCoverageOf as c, TranscriptActivePart as d, TranscriptReadiness as f, TranscriptWindowLimits as g, TranscriptWindow as h, TranscriptUpdate as i, transcriptSubscriptionBaseOf as l, TranscriptVersionStatus as m, TranscriptRequestId as n, planTranscriptUpdate as o, TranscriptVersionMeta as p, TranscriptSubscriptionBase as r, readTranscriptSubscription as s, TranscriptCoverage as t, TranscriptActiveContent as u, defaultTranscriptWindowLimits as v, transcriptCursorOf as y };
497
+
498
+ //# sourceMappingURL=subscription-g5W0Ggqx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription-g5W0Ggqx.js","names":["PositiveInt"],"sources":["../src/transcript/window.ts","../src/transcript/subscription.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { NonNegativeInt } from \"../types/events/envelope\";\nimport {\n InferenceAssistantRecordId,\n TranscriptAssistantPart,\n TranscriptCursor,\n TranscriptLogIncarnation,\n TranscriptOrder,\n TranscriptRecordViewFromEnvelope,\n isPendingTranscriptUserRecord,\n isTopLevelTranscriptRecord,\n TranscriptVersion,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n} from \"./records\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\n\nconst orderKeyOfCursor = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\n/**\n * Which slice of history to read.\n *\n * `Latest` serves first paint (SSR, CLIs); `Page` walks either direction from a cursor;\n * `Range` re-reads exactly the span a client retains, inclusive of both ends, at one new cut.\n */\nexport const TranscriptWindowSelector = Schema.Union([\n Schema.TaggedStruct(\"Latest\", { count: PositiveInt }),\n Schema.TaggedStruct(\"Page\", {\n direction: Schema.Literals([\"before\", \"after\"]),\n cursor: TranscriptCursor,\n count: PositiveInt,\n }),\n Schema.TaggedStruct(\"Range\", { from: TranscriptCursor, to: TranscriptCursor }).check(\n Schema.makeFilter(\n (range) =>\n (range.from.incarnation === range.to.incarnation &&\n range.from.version === range.to.version) ||\n \"a range is scoped to one incarnation and version\",\n ),\n Schema.makeFilter(\n (range) =>\n TranscriptOrder(orderKeyOfCursor(range.from), orderKeyOfCursor(range.to)) <= 0 ||\n \"a range starts at or before its end\",\n ),\n ),\n]);\nexport type TranscriptWindowSelector = typeof TranscriptWindowSelector.Type;\n\n/**\n * Bounds on one window. `maxRecords` caps top-level records (a selector's `count` is further\n * capped by it); `maxBytes` caps the whole response, dependencies included; bodies above\n * `maxInlineBodyBytes` are sent as references.\n */\nexport const TranscriptWindowLimits = Schema.Struct({\n maxRecords: PositiveInt,\n maxBytes: PositiveInt,\n maxInlineBodyBytes: NonNegativeInt,\n});\nexport type TranscriptWindowLimits = typeof TranscriptWindowLimits.Type;\n\n/** Default bounds: the first window holds 100 top-level records (design decision 4). */\nexport const defaultTranscriptWindowLimits: TranscriptWindowLimits = {\n maxRecords: 100,\n maxBytes: 1_048_576,\n maxInlineBodyBytes: 16_384,\n};\n\n/**\n * Whether the window is the current interpretation of the log, and if not, why its cut is\n * behind.\n *\n * Every state other than `Ready` is a degraded read and obeys one rule: the response contains\n * nothing newer than `throughSeq` — no newer pending users, session context or live content.\n */\nconst KnownReadiness = Schema.TaggedUnion({\n /** The active version is healthy and projected through the log head at read time. */\n Ready: {},\n /** The active version failed while projecting `failedAtSeq`; this is its last good cut. */\n Degraded: { failedAtSeq: SequenceNumber, error: Schema.String },\n /**\n * The active version is no longer carried by this release; history is being rebuilt under\n * the current definition, and clients receive one replacement when it activates.\n */\n UpdatingHistory: {},\n /** No version is servable yet; the window is empty. */\n Building: {},\n /**\n * A stored row of the served version cannot be decoded by this release. Nothing is served\n * until a rebuild finishes, rather than a wrong view; the window is empty.\n */\n Unreadable: { error: Schema.String },\n /** A readiness this reader does not know; treated as degraded. */\n Unknown: { readinessType: Schema.String },\n});\n\nconst knownReadinessTags: ReadonlySet<string> = new Set([\n \"Ready\",\n \"Degraded\",\n \"UpdatingHistory\",\n \"Building\",\n \"Unreadable\",\n \"Unknown\",\n]);\n\nconst UnrecognizedReadiness = Schema.Struct({\n _tag: Schema.String.check(\n Schema.makeFilter(\n (tag) => !knownReadinessTags.has(tag) || \"a known readiness must decode as that readiness\",\n ),\n ),\n}).pipe(\n Schema.decodeTo(Schema.toType(KnownReadiness.cases.Unknown), {\n decode: SchemaGetter.transform((readiness) => ({\n _tag: \"Unknown\" as const,\n readinessType: readiness._tag,\n })),\n encode: SchemaGetter.transform((readiness) => ({ _tag: readiness.readinessType })),\n }),\n);\n\n/**\n * Whether the window is the current interpretation of the log. A readiness this reader does not\n * know decodes as `Unknown` and is treated as degraded: it carries no live content. A malformed\n * readiness with a known tag is a decode failure.\n */\nexport const TranscriptReadiness = Schema.Union([KnownReadiness, UnrecognizedReadiness]);\nexport type TranscriptReadiness = typeof TranscriptReadiness.Type;\n\n/**\n * One live part of the inference streaming now.\n *\n * `id` is stable for the life of the part (`text:<providerPartId>`, `reasoning:<providerPartId>`,\n * `tool:<toolCallId>`), so a client keys a streaming part by it and replaces it in place as it\n * grows. `paramsText` is the tool-call parameter text streamed so far; it is speculative until\n * the call is sealed into a tool record.\n */\nexport const TranscriptActivePart = Schema.Struct({\n id: Schema.NonEmptyString,\n part: TranscriptAssistantPart,\n paramsText: Schema.optionalKey(Schema.String),\n}).check(\n Schema.makeFilter(\n (active) =>\n (active.part._tag === \"Text\"\n ? active.id.startsWith(\"text:\")\n : active.part._tag === \"Reasoning\"\n ? active.id.startsWith(\"reasoning:\")\n : active.part._tag === \"ToolCall\"\n ? active.id.startsWith(\"tool:\")\n : true) || \"a live part's id names its kind\",\n ),\n Schema.makeFilter(\n (active) =>\n active.paramsText === undefined ||\n active.part._tag === \"ToolCall\" ||\n \"only a tool call streams parameter text\",\n ),\n);\nexport type TranscriptActivePart = typeof TranscriptActivePart.Type;\n\n/**\n * Accumulated parts of the inference streaming now, captured at the same publication boundary as\n * the window. Owned by the live runtime; storage-level reads never include it.\n */\nexport const TranscriptActiveContent = Schema.Struct({\n assistantId: InferenceAssistantRecordId,\n parts: Schema.Array(TranscriptActivePart),\n});\nexport type TranscriptActiveContent = typeof TranscriptActiveContent.Type;\n\nconst recordUpdatedSeq = (record: TranscriptRecordView): number => record.updatedSeq;\n\nconst recordPosition = (record: TranscriptRecordView) =>\n \"position\" in record ? record.position : undefined;\n\n/** Positioned history, which is served only as a top-level record and never as a dependency. */\nconst isHistoryRecord = (record: TranscriptRecordView): boolean =>\n record.kind === \"unknown\" ? record.position !== undefined : isTopLevelTranscriptRecord(record);\n\n/**\n * One complete, consistent read of a transcript version.\n *\n * `records` are top-level records in transcript order; `dependencies` are the tools and run\n * groups they reference, the session context, and every pending user record. Every record is\n * projected through `throughSeq` and none is newer, which is what makes a cut complete. A client\n * replaces, never merges, what a window covers.\n */\nexport const TranscriptWindow = Schema.Struct({\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n records: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),\n activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),\n hasOlder: Schema.Boolean,\n hasNewer: Schema.Boolean,\n readiness: TranscriptReadiness,\n}).check(\n Schema.makeFilter(\n (window) =>\n [...window.records, ...window.dependencies].every(\n (record) => recordUpdatedSeq(record) <= window.throughSeq,\n ) || \"every record must be projected through throughSeq and none may be newer\",\n ),\n Schema.makeFilter(\n (window) =>\n window.readiness._tag === \"Ready\" ||\n window.activeContent === undefined ||\n \"a degraded read never attaches live content\",\n ),\n Schema.makeFilter(\n (window) =>\n window.readiness._tag !== \"Degraded\" ||\n window.readiness.failedAtSeq > window.throughSeq ||\n \"a degraded cut ends before the seq that failed\",\n ),\n Schema.makeFilter(\n (window) =>\n [...window.records, ...window.dependencies].every(\n (record) =>\n record.kind !== \"decorationBuffer\" &&\n (record.kind !== \"unknown\" || record.originalKind !== \"decorationBuffer\"),\n ) || \"decoration buffers are never served\",\n ),\n Schema.makeFilter((window) => {\n const ids = [...window.records, ...window.dependencies].map((record) => record.id);\n return new Set(ids).size === ids.length || \"a record is served at most once\";\n }),\n Schema.makeFilter(\n (window) =>\n window.records.every((record, index) => {\n const position = recordPosition(record);\n if (position === undefined || !isHistoryRecord(record)) return false;\n const previous = index === 0 ? undefined : window.records[index - 1];\n const previousPosition = previous === undefined ? undefined : recordPosition(previous);\n return (\n previous === undefined ||\n previousPosition === undefined ||\n TranscriptOrder(\n { ...previousPosition, recordId: previous.id },\n { ...position, recordId: record.id },\n ) < 0\n );\n }) || \"records are positioned history records in transcript order\",\n ),\n Schema.makeFilter(\n (window) =>\n window.dependencies.every((record) => !isHistoryRecord(record)) ||\n \"dependencies never contain history records\",\n ),\n Schema.makeFilter(\n (window) =>\n window.dependencies.every(\n (record) => record.kind !== \"user\" || isPendingTranscriptUserRecord(record),\n ) || \"the only user dependencies are pending users; cancelled users are never served\",\n ),\n Schema.makeFilter(\n (window) =>\n (window.readiness._tag !== \"Building\" && window.readiness._tag !== \"Unreadable\") ||\n (window.records.length === 0 &&\n window.dependencies.length === 0 &&\n !window.hasOlder &&\n !window.hasNewer) ||\n \"a building or unreadable window is empty\",\n ),\n);\nexport type TranscriptWindow = typeof TranscriptWindow.Type;\n\n/** Paging cursor for one top-level record of a window. */\nexport const transcriptCursorOf = (\n window: Pick<TranscriptWindow, \"incarnation\" | \"version\">,\n record: TranscriptRecordView,\n): TranscriptCursor | undefined => {\n const position = \"position\" in record ? record.position : undefined;\n return position === undefined\n ? undefined\n : {\n incarnation: window.incarnation,\n version: window.version,\n anchorSeq: position.anchorSeq,\n ordinal: position.ordinal,\n recordId: record.id,\n };\n};\n\n/** Health of one stored transcript version. A failed version is frozen at its last good cursor. */\nexport const TranscriptVersionStatus = Schema.TaggedUnion({\n Ok: {},\n Failed: { failedAtSeq: SequenceNumber, error: Schema.String },\n});\nexport type TranscriptVersionStatus = typeof TranscriptVersionStatus.Type;\n\n/**\n * Per-version maintenance state, one per version present in a session's storage.\n *\n * `cursor` is the last fully projected seq, committed together with that version's rows. At most\n * one version is `active` (served) and at most one is `building` (catching up from the log).\n */\nexport const TranscriptVersionMeta = Schema.Struct({\n version: TranscriptVersion,\n role: Schema.Literals([\"active\", \"building\"]),\n cursor: SequenceNumber,\n status: TranscriptVersionStatus,\n}).check(\n Schema.makeFilter(\n (meta) =>\n meta.status._tag !== \"Failed\" ||\n meta.status.failedAtSeq > meta.cursor ||\n \"a failed version is frozen before the seq that failed\",\n ),\n);\nexport type TranscriptVersionMeta = typeof TranscriptVersionMeta.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { EDASessionStoreError } from \"../services/session-store\";\nimport {\n TranscriptCursor,\n TranscriptLogIncarnation,\n TranscriptOrder,\n TranscriptRecordViewFromEnvelope,\n TranscriptVersion,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n} from \"./records\";\nimport type { EDATranscriptStoreShape, TranscriptCursorMismatch } from \"./store\";\nimport {\n TranscriptActiveContent,\n TranscriptReadiness,\n transcriptCursorOf,\n type TranscriptWindow,\n type TranscriptWindowLimits,\n type TranscriptWindowSelector,\n} from \"./window\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\n\n/** Client-chosen correlation id echoed on the update that answers a request. */\nexport const TranscriptRequestId = Schema.NonEmptyString.check(Schema.isMaxLength(64));\nexport type TranscriptRequestId = typeof TranscriptRequestId.Type;\n\n/**\n * The contiguous span of top-level records a subscriber holds, both ends inclusive. Absent when\n * the subscriber holds no top-level records (an empty session, or a window still building).\n */\nexport const TranscriptCoverage = Schema.Struct({\n from: TranscriptCursor,\n to: TranscriptCursor,\n});\nexport type TranscriptCoverage = typeof TranscriptCoverage.Type;\n\n/**\n * What a subscriber holds after its last complete update: the cut it was read at and the span it\n * covers. Every update is planned relative to this base, which is also persisted with the socket\n * so a hibernated subscription resumes without volatile state.\n *\n * `tail` is true when the coverage reaches the newest record of its cut; new history then joins\n * the coverage as it is committed. A subscriber that paged back past the tail sees `hasNewer`\n * instead and pages forward to rejoin it.\n */\nexport const TranscriptSubscriptionBase = Schema.Struct({\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n coverage: Schema.optionalKey(TranscriptCoverage),\n tail: Schema.Boolean,\n});\nexport type TranscriptSubscriptionBase = typeof TranscriptSubscriptionBase.Type;\n\n/**\n * One ordered, complete change to a subscriber's window: the only way a live client's window\n * changes.\n *\n * - `replace` discards everything the client holds and installs this window.\n * - `patch` is relative to the client's previous complete update: `records` and `dependencies`\n * carry every record that changed or newly entered the window, `dependencyIds` lists the\n * complete dependency membership of the new cut (the client drops any other dependency), and\n * the client drops top-level records outside `coverage`.\n *\n * Either way the client ends at exactly the window read at `throughSeq`: a complete cut. When\n * present, `activeContent` replaces the client's active content completely (an empty array\n * clears it); when absent, active content is unchanged. A degraded update carries no live\n * content, and a client shows none while readiness is not `Ready`.\n */\nexport const TranscriptUpdate = Schema.Struct({\n updateSeq: PositiveInt,\n mode: Schema.Literals([\"replace\", \"patch\"]),\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n coverage: Schema.optionalKey(TranscriptCoverage),\n hasOlder: Schema.Boolean,\n hasNewer: Schema.Boolean,\n readiness: TranscriptReadiness,\n records: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencyIds: Schema.Array(Schema.NonEmptyString),\n activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),\n requestId: Schema.optionalKey(TranscriptRequestId),\n}).check(\n Schema.makeFilter(\n (update) =>\n [...update.records, ...update.dependencies].every(\n (record) => record.updatedSeq <= update.throughSeq,\n ) || \"every record must be projected through throughSeq and none may be newer\",\n ),\n Schema.makeFilter(\n (update) =>\n update.readiness._tag === \"Ready\" ||\n update.activeContent === undefined ||\n update.activeContent.length === 0 ||\n \"a degraded update never carries live content\",\n ),\n Schema.makeFilter((update) => {\n const dependencyIds = new Set(update.dependencyIds);\n return (\n update.dependencies.every((record) => dependencyIds.has(record.id)) ||\n \"every sent dependency is a member of the cut\"\n );\n }),\n);\nexport type TranscriptUpdate = typeof TranscriptUpdate.Type;\n\n/** Bounds of one subscription. Retained coverage never exceeds `limits.maxRecords`. */\nexport interface TranscriptSubscriptionPolicy {\n /** Top-level records of a fresh subscription (design decision 4). */\n readonly initialCount: number;\n /** Largest page a client may request at once. */\n readonly maxPageCount: number;\n readonly limits: TranscriptWindowLimits;\n}\n\nexport const defaultTranscriptSubscriptionPolicy: TranscriptSubscriptionPolicy = {\n initialCount: 100,\n maxPageCount: 100,\n limits: { maxRecords: 300, maxBytes: 2 * 1_048_576, maxInlineBodyBytes: 16_384 },\n};\n\n/** A subscriber's request, decoded from its socket and handled strictly in arrival order. */\nexport type TranscriptSubscriptionRequest =\n /** Re-read the held coverage at a new cut, after committed changes. */\n | { readonly _tag: \"Refresh\" }\n /**\n * Start (or restart) a subscription. With `range` and `since` (what SSR rendered, or what a\n * reconnecting client last applied), the first update is a patch over that range; otherwise\n * it is a replacement of the latest `count` records.\n */\n | {\n readonly _tag: \"Subscribe\";\n readonly range?: TranscriptCoverage;\n readonly tail: boolean;\n readonly since?: SequenceNumber;\n readonly count?: number;\n }\n /** Extend the coverage by `count` records from its `before` or `after` edge. */\n | {\n readonly _tag: \"Page\";\n readonly direction: \"before\" | \"after\";\n readonly cursor: TranscriptCursor;\n readonly count: number;\n }\n /** Narrow the coverage to a span inside it, releasing the rest. */\n | { readonly _tag: \"Retain\"; readonly from: TranscriptCursor; readonly to: TranscriptCursor };\n\n/** One window read at a single cut, and the base the update for it is relative to. */\nexport interface TranscriptSubscriptionRead {\n readonly window: TranscriptWindow;\n /** What the client holds; `undefined` makes the update a replacement. */\n readonly patchBase: TranscriptSubscriptionBase | undefined;\n}\n\nconst orderKey = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\nconst sameCursor = (left: TranscriptCursor, right: TranscriptCursor): boolean =>\n left.incarnation === right.incarnation &&\n left.version === right.version &&\n TranscriptOrder(orderKey(left), orderKey(right)) === 0;\n\n/**\n * A cursor after every possible record of one version, so a `Range` ending at it reads from a\n * point to the newest record. Never sent to clients.\n */\nconst tailCursor = (from: TranscriptCursor): TranscriptCursor => ({\n incarnation: from.incarnation,\n version: from.version,\n anchorSeq: SequenceNumber.make(Number.MAX_SAFE_INTEGER),\n ordinal: Number.MAX_SAFE_INTEGER,\n recordId: \"￿\",\n});\n\n/** The span a window's top-level records cover, or `undefined` when it has none. */\nexport const transcriptCoverageOf = (window: TranscriptWindow): TranscriptCoverage | undefined => {\n const first = window.records[0];\n const last = window.records[window.records.length - 1];\n const from = first === undefined ? undefined : transcriptCursorOf(window, first);\n const to = last === undefined ? undefined : transcriptCursorOf(window, last);\n return from === undefined || to === undefined ? undefined : { from, to };\n};\n\nconst withinCoverage = (\n coverage: TranscriptCoverage | undefined,\n record: TranscriptRecordView,\n): boolean => {\n if (coverage === undefined || !(\"position\" in record) || record.position === undefined) {\n return false;\n }\n const key = { ...record.position, recordId: record.id };\n return (\n TranscriptOrder(orderKey(coverage.from), key) <= 0 &&\n TranscriptOrder(key, orderKey(coverage.to)) <= 0\n );\n};\n\n/** The base a client holds after applying an update for `window`. */\nexport const transcriptSubscriptionBaseOf = (\n window: TranscriptWindow,\n): TranscriptSubscriptionBase => {\n const coverage = transcriptCoverageOf(window);\n return {\n incarnation: window.incarnation,\n version: window.version,\n throughSeq: window.throughSeq,\n ...(coverage === undefined ? {} : { coverage }),\n tail: !window.hasNewer,\n };\n};\n\n/**\n * Plan the one update that moves a client from `patchBase` to `window`.\n *\n * A patch sends a top-level record when it changed after the base cut or was outside the base\n * coverage. It sends a tool dependency when the tool changed or its assistant is sent, and any\n * other dependency (run groups, session context, pending users) when it changed or any top-level\n * record is sent. Everything else the client already holds unchanged from the base cut, because\n * the base cut was itself complete. A different incarnation or version, or a base cut ahead of\n * the window, makes the update a replacement.\n */\nexport const planTranscriptUpdate = (input: {\n readonly patchBase: TranscriptSubscriptionBase | undefined;\n readonly window: TranscriptWindow;\n readonly updateSeq: number;\n /** The live content captured at the same publication boundary as `window`. */\n readonly activeContent: ReadonlyArray<TranscriptActiveContent>;\n /**\n * Whether the client's active content must be replaced. A replacement always carries it;\n * otherwise the caller sends it only when it changed since its last send.\n */\n readonly includeActiveContent: boolean;\n readonly requestId?: TranscriptRequestId;\n}): TranscriptUpdate => {\n const { window } = input;\n const base = input.patchBase;\n const patch =\n base !== undefined &&\n base.incarnation === window.incarnation &&\n base.version === window.version &&\n base.throughSeq <= window.throughSeq;\n const records = patch\n ? window.records.filter(\n (record) => record.updatedSeq > base.throughSeq || !withinCoverage(base.coverage, record),\n )\n : window.records;\n const sentIds = new Set(records.map((record) => record.id));\n const dependencies = patch\n ? window.dependencies.filter(\n (record) =>\n record.updatedSeq > base.throughSeq ||\n (record.kind === \"tool\" ? sentIds.has(record.assistantId) : records.length > 0),\n )\n : window.dependencies;\n const coverage = transcriptCoverageOf(window);\n const activeContent =\n patch && !input.includeActiveContent\n ? undefined\n : servedActiveContent(window, input.activeContent);\n return {\n updateSeq: input.updateSeq,\n mode: patch ? \"patch\" : \"replace\",\n incarnation: window.incarnation,\n version: window.version,\n throughSeq: window.throughSeq,\n ...(coverage === undefined ? {} : { coverage }),\n hasOlder: window.hasOlder,\n hasNewer: window.hasNewer,\n readiness: window.readiness,\n records,\n dependencies,\n dependencyIds: window.dependencies.map((record) => record.id),\n ...(activeContent === undefined ? {} : { activeContent }),\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n };\n};\n\n/**\n * Live content as served with a window: none on a degraded read, and never for an inference the\n * window already shows as committed or failed, so a stale live part cannot override a terminal.\n */\nconst servedActiveContent = (\n window: TranscriptWindow,\n activeContent: ReadonlyArray<TranscriptActiveContent>,\n): ReadonlyArray<TranscriptActiveContent> => {\n if (window.readiness._tag !== \"Ready\") return [];\n const settled = new Set(\n window.records.flatMap((record) =>\n record.kind === \"assistant\" && record.lifecycle._tag !== \"Streaming\" ? [record.id] : [],\n ),\n );\n return activeContent.filter((content) => !settled.has(content.assistantId));\n};\n\n/**\n * Read the window that answers one request, at one cut.\n *\n * Helper reads (to find a page's far edge) may see other cuts; only the final read is served,\n * so the update is always one synchronous read. Coverage stays within `limits.maxRecords`:\n * paging back evicts the newest records, paging forward evicts the oldest, and a tail that\n * outgrows the bound keeps its newest records. A cursor minted for another incarnation or version\n * falls back to a replacement of the latest records.\n */\nexport const readTranscriptSubscription = (\n store: EDATranscriptStoreShape,\n base: TranscriptSubscriptionBase | undefined,\n request: TranscriptSubscriptionRequest,\n policy: TranscriptSubscriptionPolicy,\n): Effect.Effect<TranscriptSubscriptionRead, EDASessionStoreError> => {\n const read = (selector: TranscriptWindowSelector) =>\n store.readTranscriptWindow(selector, policy.limits);\n const latest = read({\n _tag: \"Latest\",\n count: Math.min(policy.initialCount, policy.limits.maxRecords),\n }).pipe(Effect.map((window) => ({ window, patchBase: undefined })));\n\n const readCoverage = Effect.fnUntraced(function* (\n coverage: TranscriptCoverage | undefined,\n tail: boolean,\n overflowToNewest: boolean,\n ) {\n if (coverage === undefined) {\n return yield* read({\n _tag: \"Latest\",\n count: Math.min(policy.initialCount, policy.limits.maxRecords),\n });\n }\n if (!tail) return yield* read({ _tag: \"Range\", ...coverage });\n const window = yield* read({\n _tag: \"Range\",\n from: coverage.from,\n to: tailCursor(coverage.from),\n });\n // The span outgrew the bound: keep as many of its newest records as the Range read held.\n return window.hasNewer && overflowToNewest\n ? yield* read({ _tag: \"Latest\", count: Math.max(1, window.records.length) })\n : window;\n });\n\n const handle = Effect.fnUntraced(function* () {\n switch (request._tag) {\n case \"Subscribe\": {\n const count = Math.min(request.count ?? policy.initialCount, policy.limits.maxRecords);\n if (request.range === undefined) {\n const window = yield* read({ _tag: \"Latest\", count });\n return { window, patchBase: undefined };\n }\n const claimed: TranscriptSubscriptionBase = {\n incarnation: request.range.from.incarnation,\n version: request.range.from.version,\n throughSeq: request.since ?? SequenceNumber.make(0),\n coverage: request.range,\n tail: request.tail,\n };\n const window = yield* readCoverage(request.range, request.tail, true);\n return { window, patchBase: request.since === undefined ? undefined : claimed };\n }\n case \"Refresh\": {\n if (base === undefined) return yield* latest;\n const window = yield* readCoverage(base.coverage, base.tail, true);\n return { window, patchBase: base };\n }\n case \"Page\": {\n const coverage = base?.coverage;\n const edge = request.direction === \"before\" ? coverage?.from : coverage?.to;\n if (base === undefined || coverage === undefined || edge === undefined) {\n return base === undefined\n ? yield* latest\n : { window: yield* readCoverage(base.coverage, base.tail, true), patchBase: base };\n }\n if (!sameCursor(edge, request.cursor)) {\n return { window: yield* readCoverage(coverage, base.tail, true), patchBase: base };\n }\n const page = yield* read({\n _tag: \"Page\",\n direction: request.direction,\n cursor: request.cursor,\n count: Math.min(request.count, policy.maxPageCount, policy.limits.maxRecords),\n });\n const first = page.records[0];\n const last = page.records[page.records.length - 1];\n const pageFrom = first === undefined ? undefined : transcriptCursorOf(page, first);\n const pageTo = last === undefined ? undefined : transcriptCursorOf(page, last);\n if (pageFrom === undefined || pageTo === undefined) {\n return { window: yield* readCoverage(coverage, base.tail, true), patchBase: base };\n }\n if (request.direction === \"before\") {\n // A Range keeps its oldest records when it is over a bound, evicting the newest.\n const window = yield* readCoverage({ from: pageFrom, to: coverage.to }, base.tail, false);\n return { window, patchBase: base };\n }\n const from = yield* evictOldest(read, coverage.from, pageTo, policy.limits.maxRecords);\n const window = yield* readCoverage({ from, to: pageTo }, !page.hasNewer, false);\n return { window, patchBase: base };\n }\n case \"Retain\": {\n const coverage = base?.coverage;\n if (base === undefined || coverage === undefined) {\n return base === undefined\n ? yield* latest\n : { window: yield* readCoverage(base.coverage, base.tail, true), patchBase: base };\n }\n const inside =\n request.from.incarnation === base.incarnation &&\n request.from.version === base.version &&\n request.to.incarnation === base.incarnation &&\n request.to.version === base.version &&\n TranscriptOrder(orderKey(coverage.from), orderKey(request.from)) <= 0 &&\n TranscriptOrder(orderKey(request.from), orderKey(request.to)) <= 0 &&\n TranscriptOrder(orderKey(request.to), orderKey(coverage.to)) <= 0;\n const retained = inside ? { from: request.from, to: request.to } : coverage;\n const tail = base.tail && sameCursor(retained.to, coverage.to);\n return { window: yield* readCoverage(retained, tail, true), patchBase: base };\n }\n }\n });\n\n // A Latest read names no cursor, so it cannot mismatch.\n return handle().pipe(\n Effect.catchTag(\"TranscriptCursorMismatch\", () =>\n latest.pipe(Effect.catchTag(\"TranscriptCursorMismatch\", Effect.die)),\n ),\n );\n};\n\n/**\n * The oldest cursor a span ending at `to` may start from without exceeding `maxRecords`: the\n * current `from`, or later when the span would be over the bound.\n */\nconst evictOldest = Effect.fnUntraced(function* (\n read: (\n selector: TranscriptWindowSelector,\n ) => Effect.Effect<TranscriptWindow, EDASessionStoreError | TranscriptCursorMismatch>,\n from: TranscriptCursor,\n to: TranscriptCursor,\n maxRecords: number,\n) {\n if (maxRecords <= 1) return to;\n const before = yield* read({\n _tag: \"Page\",\n direction: \"before\",\n cursor: to,\n count: maxRecords - 1,\n });\n const first = before.records[0];\n const oldest = first === undefined ? undefined : transcriptCursorOf(before, first);\n return oldest === undefined || TranscriptOrder(orderKey(oldest), orderKey(from)) <= 0\n ? from\n : oldest;\n});\n"],"mappings":";;;;;;;AAmBA,MAAMA,gBAAc,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;AAErE,MAAM,oBAAoB,YAAkD;CAC1E,WAAW,OAAO;CAClB,SAAS,OAAO;CAChB,UAAU,OAAO;AACnB;;;;;;;AAQA,MAAa,2BAA2B,OAAO,MAAM;CACnD,OAAO,aAAa,UAAU,EAAE,OAAOA,cAAY,CAAC;CACpD,OAAO,aAAa,QAAQ;EAC1B,WAAW,OAAO,SAAS,CAAC,UAAU,OAAO,CAAC;EAC9C,QAAQ;EACR,OAAOA;CACT,CAAC;CACD,OAAO,aAAa,SAAS;EAAE,MAAM;EAAkB,IAAI;CAAiB,CAAC,CAAC,CAAC,MAC7E,OAAO,YACJ,UACE,MAAM,KAAK,gBAAgB,MAAM,GAAG,eACnC,MAAM,KAAK,YAAY,MAAM,GAAG,WAClC,kDACJ,GACA,OAAO,YACJ,UACC,gBAAg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AQ;KAAM,IAAI,QAAQ;IAAG,IAAI;IACnE,MAAM,OAAO,KAAK,QAAQ,WAAW,SAAS,IAAI,SAAS,EAAE;IAC7D,OAAO;KAAE,QAAQ,OAAO,aAAa,UAAU,MAAM,IAAI;KAAG,WAAW;IAAK;GAC9E;EACF;CACF,CAGY,CAAC,CAAC,CAAC,CAAC,KACd,OAAO,SAAS,kCACd,OAAO,KAAK,OAAO,SAAS,4BAA4B,OAAO,GAAG,CAAC,CACrE,CACF;AACF;;;;;AAMA,MAAM,cAAc,OAAO,WAAW,WACpC,MAGA,MACA,IACA,YACA;CACA,IAAI,cAAc,GAAG,OAAO;CAC5B,MAAM,SAAS,OAAO,KAAK;EACzB,MAAM;EACN,WAAW;EACX,QAAQ;EACR,OAAO,aAAa;CACtB,CAAC;CACD,MAAM,QAAQ,OAAO,QAAQ;CAC7B,MAAM,SAAS,UAAU,KAAA,IAAY,KAAA,IAAY,mBAAmB,QAAQ,KAAK;CACjF,OAAO,WAAW,KAAA,KAAa,gBAAgB,SAAS,MAAM,GAAG,SAAS,IAAI,CAAC,KAAK,IAChF,OACA;AACN,CAAC"}
@@ -1,15 +1,16 @@
1
1
  import { g as SessionId } from "../core-BcimKMIv.js";
2
2
  import { t as DurableEventEnvelope } from "../envelope-Che6KatU.js";
3
3
  import "../events-BWuvzVml.js";
4
- import { c as EDASessionStoreShape, o as EDASessionStore, s as EDASessionStoreError } from "../session-store-ByDjS03N.js";
4
+ import { c as EDASessionStoreShape, o as EDASessionStore, s as EDASessionStoreError } from "../session-store-CWYZ29CV.js";
5
5
  import { t as ModelResolver } from "../model-resolver-DUms5p6X.js";
6
- import { r as EDAReducerRegistry, t as EDAReducer } from "../reducer-registry-BAbhZs6d.js";
7
- import { $ as EDASessionQuery, At as InferenceRunnerStreamPart, Cn as CompactionRunner, Fn as SessionContext, Mt as RunScheduler, Ot as TurnRunner, Pn as EventFactory, bn as CompactionPolicy, fn as LiveEventBus, hn as CompactionExecutor, jt as ToolExecutor, kt as InferenceRunner, ln as EDASinkRegistry, rn as EDASink, wt as SessionState, zn as EDAPromptProjector } from "../reduced-state-PJdig48e.js";
8
- import { a as ToolParamsSchema, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-CxZ0iuYb.js";
6
+ import { r as EDAReducerRegistry, t as EDAReducer } from "../reducer-registry-CPObI3cs.js";
7
+ import { $ as EDASessionQuery, At as InferenceRunnerStreamPart, Cn as CompactionRunner, Fn as SessionContext, Mt as RunScheduler, Ot as TurnRunner, Pn as EventFactory, bn as CompactionPolicy, fn as LiveEventBus, hn as CompactionExecutor, jt as ToolExecutor, kt as InferenceRunner, ln as EDASinkRegistry, rn as EDASink, wt as SessionState, zn as EDAPromptProjector } from "../reduced-state-B5WxKSM5.js";
8
+ import { a as ToolParamsSchema, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-B_WE2ZwK.js";
9
9
  import { t as IdGenerator } from "../id-generator-BKGoKjt-.js";
10
10
  import { t as EDAKeepAlive } from "../keep-alive-_zFCUvt3.js";
11
- import { n as SinkCheckpointStore } from "../sink-checkpoint-store-BHb8YRTw.js";
12
- import { t as RunSchedulingWakeup } from "../run-scheduling-wakeup-QLK87OqG.js";
11
+ import { t as SessionEventObserver } from "../session-event-observer-BdZltdrK.js";
12
+ import { n as SinkCheckpointStore } from "../sink-checkpoint-store-B8Ky5nfW.js";
13
+ import { t as RunSchedulingWakeup } from "../run-scheduling-wakeup-B19JTeyq.js";
13
14
  import * as Layer from "effect/Layer";
14
15
  import * as LanguageModel from "effect/ai/LanguageModel";
15
16
  import * as Stream from "effect/Stream";
@@ -93,6 +94,8 @@ interface EdaTestLayerOptions {
93
94
  readonly promptProjectorLayer?: Layer.Layer<EDAPromptProjector>;
94
95
  /** App-provided EDA sinks. */
95
96
  readonly sinks?: ReadonlyArray<EDASink>;
97
+ /** Host publication observer, such as a WebSocket connection manager. */
98
+ readonly sessionEventObserverLayer?: Layer.Layer<SessionEventObserver>;
96
99
  }
97
100
  /**
98
101
  * One in-memory layer graph for the whole session runtime, exposing every