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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +5 -5
  2. package/dist/assert-never-CoyUpoRB.js +18 -0
  3. package/dist/assert-never-CoyUpoRB.js.map +1 -0
  4. package/dist/{commands-Ce1ec6kH.d.ts → commands-BUquEZVP.d.ts} +31 -12
  5. package/dist/{compaction-BgDr5VJy.js → compaction-D7WJa899.js} +63 -13
  6. package/dist/compaction-D7WJa899.js.map +1 -0
  7. package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-Bezx3drD.d.ts} +16 -40
  8. package/dist/{core-CYT6DBaS.d.ts → core-BcimKMIv.d.ts} +5 -3
  9. package/dist/delivery-B_LDTuIB.d.ts +3169 -0
  10. package/dist/delivery-BoF-NZbZ.js +507 -0
  11. package/dist/delivery-BoF-NZbZ.js.map +1 -0
  12. package/dist/domain/command-queues.d.ts +81 -2
  13. package/dist/domain/command-queues.js +1 -1
  14. package/dist/domain/command-queues.js.map +1 -1
  15. package/dist/domain/context-projection.d.ts +1 -1
  16. package/dist/domain/context-projection.js +1 -1
  17. package/dist/domain/context-projection.js.map +1 -1
  18. package/dist/domain/message-transcript.d.ts +36 -2
  19. package/dist/domain/message-transcript.js +10 -2
  20. package/dist/domain/message-transcript.js.map +1 -1
  21. package/dist/domain/model-usage.d.ts +1 -1
  22. package/dist/domain/model-usage.js +1 -1
  23. package/dist/domain/reduced-state-schema.d.ts +3 -992
  24. package/dist/domain/reduced-state-schema.js +126 -7
  25. package/dist/domain/reduced-state-schema.js.map +1 -1
  26. package/dist/domain/reduced-state.d.ts +2 -2
  27. package/dist/domain/reduced-state.js +937 -2
  28. package/dist/domain/reduced-state.js.map +1 -0
  29. package/dist/domain/run-scheduling.d.ts +2 -0
  30. package/dist/domain/run-scheduling.js +127 -0
  31. package/dist/domain/run-scheduling.js.map +1 -0
  32. package/dist/{durable-br2C1bWK.d.ts → durable-BXqwM70o.d.ts} +8983 -2800
  33. package/dist/{durable-BGFvX7Mh.js → durable-Da57Rcml.js} +243 -15
  34. package/dist/durable-Da57Rcml.js.map +1 -0
  35. package/dist/{envelope-DxQzo5rN.js → envelope-BSI_Xh-f.js} +31 -6
  36. package/dist/envelope-BSI_Xh-f.js.map +1 -0
  37. package/dist/{envelope-DkZyMIgp.d.ts → envelope-CJnPfbjC.d.ts} +121 -11
  38. package/dist/{event-factory-DTFdy0Cb.js → event-factory-BUoBwqAy.js} +7 -3
  39. package/dist/event-factory-BUoBwqAy.js.map +1 -0
  40. package/dist/{events-LZFNoESe.d.ts → events-AIIwZ6dS.d.ts} +139 -137
  41. package/dist/{id-generator-Ckl8_XWW.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
  42. package/dist/in-memory-E497WhtS.js +150 -0
  43. package/dist/in-memory-E497WhtS.js.map +1 -0
  44. package/dist/index.d.ts +8 -8
  45. package/dist/index.js +6 -6
  46. package/dist/interpreter-BwYN2PCC.js +1453 -0
  47. package/dist/interpreter-BwYN2PCC.js.map +1 -0
  48. package/dist/{keep-alive-Chl5SJxy.d.ts → keep-alive-_zFCUvt3.d.ts} +1 -2
  49. package/dist/{model-resolver-BPPJAsuh.d.ts → model-resolver-O8Kn27GH.d.ts} +11 -5
  50. package/dist/{model-usage-CdBEkTwU.d.ts → model-usage-mttrPN0j.d.ts} +2 -3
  51. package/dist/records-D0ZIAOzd.js +675 -0
  52. package/dist/records-D0ZIAOzd.js.map +1 -0
  53. package/dist/reduced-state-YbjpihEf.d.ts +52933 -0
  54. package/dist/reduced-state-schema-B9TYxkP9.d.ts +2338 -0
  55. package/dist/{reducer-registry-aFjz_ZLT.d.ts → reducer-registry-Bqn5B4JO.d.ts} +12 -6
  56. package/dist/run-scheduling-wakeup-DX2zRAxd.d.ts +24 -0
  57. package/dist/services/compaction.d.ts +2 -2
  58. package/dist/services/compaction.js +2 -2
  59. package/dist/services/decider.d.ts +2 -0
  60. package/dist/services/decider.js +97 -0
  61. package/dist/services/decider.js.map +1 -0
  62. package/dist/services/id-generator.d.ts +1 -1
  63. package/dist/services/id-generator.js +6 -12
  64. package/dist/services/id-generator.js.map +1 -1
  65. package/dist/services/keep-alive.d.ts +1 -1
  66. package/dist/services/keep-alive.js.map +1 -1
  67. package/dist/services/model-call.d.ts +15 -0
  68. package/dist/services/model-call.js +15 -0
  69. package/dist/services/model-call.js.map +1 -0
  70. package/dist/services/model-resolver.d.ts +1 -1
  71. package/dist/services/model-resolver.js +1 -1
  72. package/dist/services/model-resolver.js.map +1 -1
  73. package/dist/services/prompt-projector.d.ts +2 -2
  74. package/dist/services/prompt-projector.js +49 -5
  75. package/dist/services/prompt-projector.js.map +1 -1
  76. package/dist/services/reducer-registry.d.ts +1 -1
  77. package/dist/services/reducer-registry.js +19 -6
  78. package/dist/services/reducer-registry.js.map +1 -1
  79. package/dist/services/run-scheduler.d.ts +2 -2
  80. package/dist/services/run-scheduler.js +25 -2
  81. package/dist/services/run-scheduler.js.map +1 -0
  82. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  83. package/dist/services/run-scheduling-wakeup.js +13 -0
  84. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  85. package/dist/services/runtime-layer.d.ts +21 -33
  86. package/dist/services/runtime-layer.js +24 -16
  87. package/dist/services/runtime-layer.js.map +1 -1
  88. package/dist/services/runtime.d.ts +1 -1
  89. package/dist/services/runtime.js +32 -20
  90. package/dist/services/runtime.js.map +1 -1
  91. package/dist/services/session-event-observer.d.ts +1 -1
  92. package/dist/services/session-event-observer.js.map +1 -1
  93. package/dist/services/session-query.d.ts +1 -1
  94. package/dist/services/session-query.js +57 -10
  95. package/dist/services/session-query.js.map +1 -1
  96. package/dist/services/session-state.d.ts +2 -2
  97. package/dist/services/session-state.js +2 -1
  98. package/dist/services/session-store.d.ts +2 -2
  99. package/dist/services/session-store.js +143 -38
  100. package/dist/services/session-store.js.map +1 -1
  101. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  102. package/dist/services/sink-checkpoint-store.js +2 -1
  103. package/dist/services/sink-checkpoint-store.js.map +1 -1
  104. package/dist/services/sink-registry.d.ts +2 -2
  105. package/dist/services/sink-registry.js +1 -1
  106. package/dist/services/span-names.d.ts +1 -1
  107. package/dist/services/span-names.js +7 -1
  108. package/dist/services/span-names.js.map +1 -1
  109. package/dist/services/tool-registry.d.ts +2 -2
  110. package/dist/services/tool-registry.js +12 -3
  111. package/dist/services/tool-registry.js.map +1 -1
  112. package/dist/services/tracing.d.ts +3 -3
  113. package/dist/services/tracing.js +2 -2
  114. package/dist/services/tracing.js.map +1 -1
  115. package/dist/session-admission-WE8J_0z9.js +138 -0
  116. package/dist/session-admission-WE8J_0z9.js.map +1 -0
  117. package/dist/{session-event-observer-DaFMKKNc.d.ts → session-event-observer-BWQUJTcN.d.ts} +3 -3
  118. package/dist/{session-state-Bkc6u-Wr.js → session-state-D02LCVcC.js} +815 -170
  119. package/dist/session-state-D02LCVcC.js.map +1 -0
  120. package/dist/session-store-DaSHeg8Q.d.ts +3343 -0
  121. package/dist/{sink-checkpoint-store-M7qIxoSH.d.ts → sink-checkpoint-store-CUvIVvlZ.d.ts} +3 -4
  122. package/dist/sink-registry-AOjX5_A1.js +369 -0
  123. package/dist/sink-registry-AOjX5_A1.js.map +1 -0
  124. package/dist/subscription-BhwUmsl4.d.ts +966 -0
  125. package/dist/subscription-D7U4Tziv.js +505 -0
  126. package/dist/subscription-D7U4Tziv.js.map +1 -0
  127. package/dist/testkit/layers.d.ts +33 -23
  128. package/dist/testkit/layers.js +34 -19
  129. package/dist/testkit/layers.js.map +1 -1
  130. package/dist/testkit/transcript.d.ts +232 -0
  131. package/dist/testkit/transcript.js +1526 -0
  132. package/dist/testkit/transcript.js.map +1 -0
  133. package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
  134. package/dist/transcript.d.ts +101 -0
  135. package/dist/transcript.js +107 -0
  136. package/dist/transcript.js.map +1 -0
  137. package/dist/types/commands.d.ts +2 -2
  138. package/dist/types/commands.js +8 -3
  139. package/dist/types/commands.js.map +1 -1
  140. package/dist/types/core.d.ts +2 -2
  141. package/dist/types/core.js +3 -1
  142. package/dist/types/core.js.map +1 -1
  143. package/dist/types/events/durable.d.ts +2 -2
  144. package/dist/types/events/durable.js +2 -2
  145. package/dist/types/events.d.ts +5 -5
  146. package/dist/types/events.js +3 -3
  147. package/dist/types/tracing.d.ts +1 -1
  148. package/dist/types/tracing.js.map +1 -1
  149. package/dist/websocket/events.d.ts +2 -0
  150. package/dist/websocket/events.js +2 -0
  151. package/dist/websocket.d.ts +2123 -2552
  152. package/dist/websocket.js +628 -442
  153. package/dist/websocket.js.map +1 -1
  154. package/dist/window-read-BELSkO-r.d.ts +113 -0
  155. package/dist/window-read-FJTCDaSq.js +264 -0
  156. package/dist/window-read-FJTCDaSq.js.map +1 -0
  157. package/package.json +41 -13
  158. package/dist/command-queues-DdDB_aYM.d.ts +0 -462
  159. package/dist/compaction-BgDr5VJy.js.map +0 -1
  160. package/dist/compaction-ch8z6G9x.d.ts +0 -165
  161. package/dist/durable-BGFvX7Mh.js.map +0 -1
  162. package/dist/envelope-DxQzo5rN.js.map +0 -1
  163. package/dist/event-factory-DTFdy0Cb.js.map +0 -1
  164. package/dist/event-factory-Di1jwQvm.d.ts +0 -87
  165. package/dist/index-BVVgDSdq.d.ts +0 -1
  166. package/dist/message-transcript-DQNlzxle.d.ts +0 -32
  167. package/dist/prompt-projector-f4ElyXCE.d.ts +0 -39
  168. package/dist/reduced-state-DF0-6mbR.js +0 -921
  169. package/dist/reduced-state-DF0-6mbR.js.map +0 -1
  170. package/dist/run-scheduler-CAt7dF6C.js +0 -21
  171. package/dist/run-scheduler-CAt7dF6C.js.map +0 -1
  172. package/dist/run-scheduler-xkhZyto5.d.ts +0 -44
  173. package/dist/runtime-DDSYP9jS.d.ts +0 -63
  174. package/dist/session-query-B72HY_0L.d.ts +0 -45
  175. package/dist/session-state-Bkc6u-Wr.js.map +0 -1
  176. package/dist/session-state-C9YLSAso.d.ts +0 -862
  177. package/dist/session-store-Cpi_NwTR.d.ts +0 -206
  178. package/dist/sink-registry-Bl-vQES6.d.ts +0 -133
  179. package/dist/sink-registry-NDgeyzO0.js +0 -272
  180. package/dist/sink-registry-NDgeyzO0.js.map +0 -1
  181. package/dist/tool-registry-BJaVNtw4.d.ts +0 -51
@@ -0,0 +1,505 @@
1
+ import { SequenceNumber } from "./types/core.js";
2
+ import { d as NonNegativeInt } from "./envelope-BSI_Xh-f.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-D0ZIAOzd.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 served cut is consistent but behind the log: either the active version is no longer
65
+ * carried by this release and history is being rebuilt under the current definition (clients
66
+ * receive one replacement when it activates), or the active version is catching up to the head
67
+ * (a session re-enabled after it was disabled; clients receive a re-read when it gets there).
68
+ */
69
+ UpdatingHistory: {},
70
+ /**
71
+ * No version is servable yet and the build of the current definition can still finish; the
72
+ * window is empty.
73
+ */
74
+ Building: {},
75
+ /**
76
+ * Nothing can be served, and `error` says why; the window is empty. Either a stored row of the
77
+ * served version cannot be decoded by this release (nothing is served until a rebuild finishes,
78
+ * rather than a wrong view), or no version is active and the build of the current definition
79
+ * froze as failed, which is never retried (only a new definition repairs it).
80
+ */
81
+ Unreadable: { error: Schema.String },
82
+ /** A readiness this reader does not know; treated as degraded. */
83
+ Unknown: { readinessType: Schema.String }
84
+ });
85
+ const knownReadinessTags = /* @__PURE__ */ new Set([
86
+ "Ready",
87
+ "Degraded",
88
+ "UpdatingHistory",
89
+ "Building",
90
+ "Unreadable",
91
+ "Unknown"
92
+ ]);
93
+ 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), {
94
+ decode: SchemaGetter.transform((readiness) => ({
95
+ _tag: "Unknown",
96
+ readinessType: readiness._tag
97
+ })),
98
+ encode: SchemaGetter.transform((readiness) => ({ _tag: readiness.readinessType }))
99
+ }));
100
+ /**
101
+ * Whether the window is the current interpretation of the log. A readiness this reader does not
102
+ * know decodes as `Unknown` and is treated as degraded: it carries no live content. A malformed
103
+ * readiness with a known tag is a decode failure.
104
+ */
105
+ const TranscriptReadiness = Schema.Union([KnownReadiness, UnrecognizedReadiness]);
106
+ /**
107
+ * One live part of the inference streaming now.
108
+ *
109
+ * `id` is stable for the life of the part (`text:<providerPartId>`, `reasoning:<providerPartId>`,
110
+ * `tool:<toolCallId>`), so a client keys a streaming part by it and replaces it in place as it
111
+ * grows. `paramsText` is the tool-call parameter text streamed so far; it is speculative until
112
+ * the call is sealed into a tool record.
113
+ */
114
+ const TranscriptActivePart = Schema.Struct({
115
+ id: Schema.NonEmptyString,
116
+ part: TranscriptAssistantPart,
117
+ paramsText: Schema.optionalKey(Schema.String)
118
+ }).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"));
119
+ /**
120
+ * Accumulated parts of the inference streaming now, captured at the same publication boundary as
121
+ * the window. Owned by the live runtime; storage-level reads never include it.
122
+ */
123
+ const TranscriptActiveContent = Schema.Struct({
124
+ assistantId: InferenceAssistantRecordId,
125
+ parts: Schema.Array(TranscriptActivePart)
126
+ });
127
+ const recordUpdatedSeq = (record) => record.updatedSeq;
128
+ const recordPosition = (record) => "position" in record ? record.position : void 0;
129
+ /** Positioned history, which is served only as a top-level record and never as a dependency. */
130
+ const isHistoryRecord = (record) => record.kind === "unknown" ? record.position !== void 0 : isTopLevelTranscriptRecord(record);
131
+ /**
132
+ * One complete, consistent read of a transcript version.
133
+ *
134
+ * `records` are top-level records in transcript order; `dependencies` are the tools and run
135
+ * groups they reference, the session context, and every pending user record. Every record is
136
+ * projected through `throughSeq` and none is newer, which is what makes a cut complete. A client
137
+ * replaces, never merges, what a window covers.
138
+ */
139
+ const TranscriptWindow = Schema.Struct({
140
+ incarnation: TranscriptLogIncarnation,
141
+ version: TranscriptVersion,
142
+ throughSeq: SequenceNumber,
143
+ records: Schema.Array(TranscriptRecordViewFromEnvelope),
144
+ dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),
145
+ activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),
146
+ hasOlder: Schema.Boolean,
147
+ hasNewer: Schema.Boolean,
148
+ readiness: TranscriptReadiness
149
+ }).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) => {
150
+ const ids = [...window.records, ...window.dependencies].map((record) => record.id);
151
+ return new Set(ids).size === ids.length || "a record is served at most once";
152
+ }), Schema.makeFilter((window) => window.records.every((record, index) => {
153
+ const position = recordPosition(record);
154
+ if (position === void 0 || !isHistoryRecord(record)) return false;
155
+ const previous = index === 0 ? void 0 : window.records[index - 1];
156
+ const previousPosition = previous === void 0 ? void 0 : recordPosition(previous);
157
+ return previous === void 0 || previousPosition === void 0 || TranscriptOrder({
158
+ ...previousPosition,
159
+ recordId: previous.id
160
+ }, {
161
+ ...position,
162
+ recordId: record.id
163
+ }) < 0;
164
+ }) || "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"));
165
+ /** Paging cursor for one top-level record of a window. */
166
+ const transcriptCursorOf = (window, record) => {
167
+ const position = "position" in record ? record.position : void 0;
168
+ return position === void 0 ? void 0 : {
169
+ incarnation: window.incarnation,
170
+ version: window.version,
171
+ anchorSeq: position.anchorSeq,
172
+ ordinal: position.ordinal,
173
+ recordId: record.id
174
+ };
175
+ };
176
+ /** Health of one stored transcript version. A failed version is frozen at its last good cursor. */
177
+ const TranscriptVersionStatus = Schema.TaggedUnion({
178
+ Ok: {},
179
+ Failed: {
180
+ failedAtSeq: SequenceNumber,
181
+ error: Schema.String
182
+ }
183
+ });
184
+ /**
185
+ * Per-version maintenance state, one per version present in a session's storage.
186
+ *
187
+ * `cursor` is the last fully projected seq, committed together with that version's rows. At most
188
+ * one version is `active` (served) and at most one is `building` (catching up from the log).
189
+ */
190
+ const TranscriptVersionMeta = Schema.Struct({
191
+ version: TranscriptVersion,
192
+ role: Schema.Literals(["active", "building"]),
193
+ cursor: SequenceNumber,
194
+ status: TranscriptVersionStatus
195
+ }).check(Schema.makeFilter((meta) => meta.status._tag !== "Failed" || meta.status.failedAtSeq > meta.cursor || "a failed version is frozen before the seq that failed"));
196
+ //#endregion
197
+ //#region src/transcript/subscription.ts
198
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
199
+ /** Client-chosen correlation id echoed on the update that answers a request. */
200
+ const TranscriptRequestId = Schema.NonEmptyString.check(Schema.isMaxLength(64));
201
+ /**
202
+ * The contiguous span of top-level records a subscriber holds, both ends inclusive. Absent when
203
+ * the subscriber holds no top-level records (an empty session, or a window still building).
204
+ */
205
+ const TranscriptCoverage = Schema.Struct({
206
+ from: TranscriptCursor,
207
+ to: TranscriptCursor
208
+ });
209
+ /**
210
+ * What a subscriber holds after its last complete update: the cut it was read at and the span it
211
+ * covers. Every update is planned relative to this base, which is also persisted with the socket
212
+ * so a hibernated subscription resumes without volatile state.
213
+ *
214
+ * `tail` is true when the coverage reaches the newest record of its cut; new history then joins
215
+ * the coverage as it is committed. A subscriber that paged back past the tail sees `hasNewer`
216
+ * instead and pages forward to rejoin it.
217
+ */
218
+ const TranscriptSubscriptionBase = Schema.Struct({
219
+ incarnation: TranscriptLogIncarnation,
220
+ version: TranscriptVersion,
221
+ throughSeq: SequenceNumber,
222
+ coverage: Schema.optionalKey(TranscriptCoverage),
223
+ tail: Schema.Boolean
224
+ });
225
+ /**
226
+ * One ordered, complete change to a subscriber's window: the only way a live client's window
227
+ * changes.
228
+ *
229
+ * - `replace` discards everything the client holds and installs this window.
230
+ * - `patch` is relative to the client's previous complete update: `records` and `dependencies`
231
+ * carry every record that changed or newly entered the window, `dependencyIds` lists the
232
+ * complete dependency membership of the new cut (the client drops any other dependency), and
233
+ * the client drops top-level records outside `coverage`.
234
+ *
235
+ * Either way the client ends at exactly the window read at `throughSeq`: a complete cut. When
236
+ * present, `activeContent` replaces the client's active content completely (an empty array
237
+ * clears it); when absent, active content is unchanged. A degraded update carries no live
238
+ * content, and a client shows none while readiness is not `Ready`.
239
+ */
240
+ const TranscriptUpdate = Schema.Struct({
241
+ updateSeq: PositiveInt,
242
+ mode: Schema.Literals(["replace", "patch"]),
243
+ incarnation: TranscriptLogIncarnation,
244
+ version: TranscriptVersion,
245
+ throughSeq: SequenceNumber,
246
+ coverage: Schema.optionalKey(TranscriptCoverage),
247
+ hasOlder: Schema.Boolean,
248
+ hasNewer: Schema.Boolean,
249
+ readiness: TranscriptReadiness,
250
+ records: Schema.Array(TranscriptRecordViewFromEnvelope),
251
+ dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),
252
+ dependencyIds: Schema.Array(Schema.NonEmptyString),
253
+ activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),
254
+ requestId: Schema.optionalKey(TranscriptRequestId)
255
+ }).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) => {
256
+ const dependencyIds = new Set(update.dependencyIds);
257
+ return update.dependencies.every((record) => dependencyIds.has(record.id)) || "every sent dependency is a member of the cut";
258
+ }));
259
+ const defaultTranscriptSubscriptionPolicy = {
260
+ initialCount: 100,
261
+ maxPageCount: 100,
262
+ limits: {
263
+ maxRecords: 300,
264
+ maxBytes: 2097152,
265
+ maxInlineBodyBytes: 16384
266
+ }
267
+ };
268
+ const orderKey = (cursor) => ({
269
+ anchorSeq: cursor.anchorSeq,
270
+ ordinal: cursor.ordinal,
271
+ recordId: cursor.recordId
272
+ });
273
+ const sameCursor = (left, right) => left.incarnation === right.incarnation && left.version === right.version && TranscriptOrder(orderKey(left), orderKey(right)) === 0;
274
+ /**
275
+ * A cursor after every possible record of one version, so a `Range` ending at it reads from a
276
+ * point to the newest record. Never sent to clients.
277
+ */
278
+ const tailCursor = (from) => ({
279
+ incarnation: from.incarnation,
280
+ version: from.version,
281
+ anchorSeq: SequenceNumber.make(Number.MAX_SAFE_INTEGER),
282
+ ordinal: Number.MAX_SAFE_INTEGER,
283
+ recordId: "￿"
284
+ });
285
+ /** The span a window's top-level records cover, or `undefined` when it has none. */
286
+ const transcriptCoverageOf = (window) => {
287
+ const first = window.records[0];
288
+ const last = window.records[window.records.length - 1];
289
+ const from = first === void 0 ? void 0 : transcriptCursorOf(window, first);
290
+ const to = last === void 0 ? void 0 : transcriptCursorOf(window, last);
291
+ return from === void 0 || to === void 0 ? void 0 : {
292
+ from,
293
+ to
294
+ };
295
+ };
296
+ const withinCoverage = (coverage, record) => {
297
+ if (coverage === void 0 || !("position" in record) || record.position === void 0) return false;
298
+ const key = {
299
+ ...record.position,
300
+ recordId: record.id
301
+ };
302
+ return TranscriptOrder(orderKey(coverage.from), key) <= 0 && TranscriptOrder(key, orderKey(coverage.to)) <= 0;
303
+ };
304
+ /** The base a client holds after applying an update for `window`. */
305
+ const transcriptSubscriptionBaseOf = (window) => {
306
+ const coverage = transcriptCoverageOf(window);
307
+ return {
308
+ incarnation: window.incarnation,
309
+ version: window.version,
310
+ throughSeq: window.throughSeq,
311
+ ...coverage === void 0 ? {} : { coverage },
312
+ tail: !window.hasNewer
313
+ };
314
+ };
315
+ /**
316
+ * Plan the one update that moves a client from `patchBase` to `window`.
317
+ *
318
+ * A patch sends a top-level record when it changed after the base cut or was outside the base
319
+ * coverage. It sends a tool dependency when the tool changed or its assistant is sent, and any
320
+ * other dependency (run groups, session context, pending users) when it changed or any top-level
321
+ * record is sent. Everything else the client already holds unchanged from the base cut, because
322
+ * the base cut was itself complete. A different incarnation or version, or a base cut ahead of
323
+ * the window, makes the update a replacement.
324
+ */
325
+ const planTranscriptUpdate = (input) => {
326
+ const { window } = input;
327
+ const base = input.patchBase;
328
+ const patch = base !== void 0 && base.incarnation === window.incarnation && base.version === window.version && base.throughSeq <= window.throughSeq;
329
+ const records = patch ? window.records.filter((record) => record.updatedSeq > base.throughSeq || !withinCoverage(base.coverage, record)) : window.records;
330
+ const sentIds = new Set(records.map((record) => record.id));
331
+ const dependencies = patch ? window.dependencies.filter((record) => record.updatedSeq > base.throughSeq || (record.kind === "tool" ? sentIds.has(record.assistantId) : records.length > 0)) : window.dependencies;
332
+ const coverage = transcriptCoverageOf(window);
333
+ const activeContent = patch && !input.includeActiveContent ? void 0 : servedActiveContent(window, input.activeContent);
334
+ return {
335
+ updateSeq: input.updateSeq,
336
+ mode: patch ? "patch" : "replace",
337
+ incarnation: window.incarnation,
338
+ version: window.version,
339
+ throughSeq: window.throughSeq,
340
+ ...coverage === void 0 ? {} : { coverage },
341
+ hasOlder: window.hasOlder,
342
+ hasNewer: window.hasNewer,
343
+ readiness: window.readiness,
344
+ records,
345
+ dependencies,
346
+ dependencyIds: window.dependencies.map((record) => record.id),
347
+ ...activeContent === void 0 ? {} : { activeContent },
348
+ ...input.requestId === void 0 ? {} : { requestId: input.requestId }
349
+ };
350
+ };
351
+ /**
352
+ * Live content as served with a window: none on a degraded read, and never for an inference the
353
+ * window already shows as committed or failed, so a stale live part cannot override a terminal.
354
+ */
355
+ const servedActiveContent = (window, activeContent) => {
356
+ if (window.readiness._tag !== "Ready") return [];
357
+ const settled = new Set(window.records.flatMap((record) => record.kind === "assistant" && record.lifecycle._tag !== "Streaming" ? [record.id] : []));
358
+ return activeContent.filter((content) => !settled.has(content.assistantId));
359
+ };
360
+ /**
361
+ * Read the window that answers one request, at one cut.
362
+ *
363
+ * Helper reads (to find a page's far edge) may see other cuts; only the final read is served,
364
+ * so the update is always one synchronous read. Coverage stays within `limits.maxRecords`:
365
+ * paging back evicts the newest records, paging forward evicts the oldest, and a tail that
366
+ * outgrows the bound keeps its newest records. A cursor minted for another incarnation or version
367
+ * falls back to a replacement of the latest records.
368
+ */
369
+ const readTranscriptSubscription = (store, base, request, policy) => {
370
+ const read = (selector) => store.readTranscriptWindow(selector, policy.limits);
371
+ const latest = read({
372
+ _tag: "Latest",
373
+ count: Math.min(policy.initialCount, policy.limits.maxRecords)
374
+ }).pipe(Effect.map((window) => ({
375
+ window,
376
+ patchBase: void 0
377
+ })));
378
+ const readCoverage = Effect.fnUntraced(function* (coverage, tail, overflowToNewest) {
379
+ if (coverage === void 0) return yield* read({
380
+ _tag: "Latest",
381
+ count: Math.min(policy.initialCount, policy.limits.maxRecords)
382
+ });
383
+ if (!tail) return yield* read({
384
+ _tag: "Range",
385
+ ...coverage
386
+ });
387
+ const window = yield* read({
388
+ _tag: "Range",
389
+ from: coverage.from,
390
+ to: tailCursor(coverage.from)
391
+ });
392
+ return window.hasNewer && overflowToNewest ? yield* read({
393
+ _tag: "Latest",
394
+ count: Math.max(1, window.records.length)
395
+ }) : window;
396
+ });
397
+ return Effect.fnUntraced(function* () {
398
+ switch (request._tag) {
399
+ case "Subscribe": {
400
+ const count = Math.min(request.count ?? policy.initialCount, policy.limits.maxRecords);
401
+ if (request.range === void 0) return {
402
+ window: yield* read({
403
+ _tag: "Latest",
404
+ count
405
+ }),
406
+ patchBase: void 0
407
+ };
408
+ const claimed = {
409
+ incarnation: request.range.from.incarnation,
410
+ version: request.range.from.version,
411
+ throughSeq: request.since ?? SequenceNumber.make(0),
412
+ coverage: request.range,
413
+ tail: request.tail
414
+ };
415
+ return {
416
+ window: yield* readCoverage(request.range, request.tail, true),
417
+ patchBase: request.since === void 0 ? void 0 : claimed
418
+ };
419
+ }
420
+ case "Refresh":
421
+ if (base === void 0) return yield* latest;
422
+ return {
423
+ window: yield* readCoverage(base.coverage, base.tail, true),
424
+ patchBase: base
425
+ };
426
+ case "Page": {
427
+ const coverage = base?.coverage;
428
+ const edge = request.direction === "before" ? coverage?.from : coverage?.to;
429
+ if (base === void 0 || coverage === void 0 || edge === void 0) return base === void 0 ? yield* latest : {
430
+ window: yield* readCoverage(base.coverage, base.tail, true),
431
+ patchBase: base
432
+ };
433
+ if (!sameCursor(edge, request.cursor)) return {
434
+ window: yield* readCoverage(coverage, base.tail, true),
435
+ patchBase: base
436
+ };
437
+ const page = yield* read({
438
+ _tag: "Page",
439
+ direction: request.direction,
440
+ cursor: request.cursor,
441
+ count: Math.min(request.count, policy.maxPageCount, policy.limits.maxRecords)
442
+ });
443
+ const first = page.records[0];
444
+ const last = page.records[page.records.length - 1];
445
+ const pageFrom = first === void 0 ? void 0 : transcriptCursorOf(page, first);
446
+ const pageTo = last === void 0 ? void 0 : transcriptCursorOf(page, last);
447
+ if (pageFrom === void 0 || pageTo === void 0) return {
448
+ window: yield* readCoverage(coverage, base.tail, true),
449
+ patchBase: base
450
+ };
451
+ if (request.direction === "before") return {
452
+ window: yield* readCoverage({
453
+ from: pageFrom,
454
+ to: coverage.to
455
+ }, base.tail, false),
456
+ patchBase: base
457
+ };
458
+ const from = yield* evictOldest(read, coverage.from, pageTo, policy.limits.maxRecords);
459
+ return {
460
+ window: yield* readCoverage({
461
+ from,
462
+ to: pageTo
463
+ }, !page.hasNewer, false),
464
+ patchBase: base
465
+ };
466
+ }
467
+ case "Retain": {
468
+ const coverage = base?.coverage;
469
+ if (base === void 0 || coverage === void 0) return base === void 0 ? yield* latest : {
470
+ window: yield* readCoverage(base.coverage, base.tail, true),
471
+ patchBase: base
472
+ };
473
+ 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 ? {
474
+ from: request.from,
475
+ to: request.to
476
+ } : coverage;
477
+ const tail = base.tail && sameCursor(retained.to, coverage.to);
478
+ return {
479
+ window: yield* readCoverage(retained, tail, true),
480
+ patchBase: base
481
+ };
482
+ }
483
+ }
484
+ })().pipe(Effect.catchTag("TranscriptCursorMismatch", () => latest.pipe(Effect.catchTag("TranscriptCursorMismatch", Effect.die))));
485
+ };
486
+ /**
487
+ * The oldest cursor a span ending at `to` may start from without exceeding `maxRecords`: the
488
+ * current `from`, or later when the span would be over the bound.
489
+ */
490
+ const evictOldest = Effect.fnUntraced(function* (read, from, to, maxRecords) {
491
+ if (maxRecords <= 1) return to;
492
+ const before = yield* read({
493
+ _tag: "Page",
494
+ direction: "before",
495
+ cursor: to,
496
+ count: maxRecords - 1
497
+ });
498
+ const first = before.records[0];
499
+ const oldest = first === void 0 ? void 0 : transcriptCursorOf(before, first);
500
+ return oldest === void 0 || TranscriptOrder(orderKey(oldest), orderKey(from)) <= 0 ? from : oldest;
501
+ });
502
+ //#endregion
503
+ 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 };
504
+
505
+ //# sourceMappingURL=subscription-D7U4Tziv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription-D7U4Tziv.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 served cut is consistent but behind the log: either the active version is no longer\n * carried by this release and history is being rebuilt under the current definition (clients\n * receive one replacement when it activates), or the active version is catching up to the head\n * (a session re-enabled after it was disabled; clients receive a re-read when it gets there).\n */\n UpdatingHistory: {},\n /**\n * No version is servable yet and the build of the current definition can still finish; the\n * window is empty.\n */\n Building: {},\n /**\n * Nothing can be served, and `error` says why; the window is empty. Either a stored row of the\n * served version cannot be decoded by this release (nothing is served until a rebuild finishes,\n * rather than a wrong view), or no version is active and the build of the current definition\n * froze as failed, which is never retried (only a new definition repairs it).\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,gBAAgB,iBAAiB,MAAM,IAAI,GAAG,iBAAiB,MAAM,EAAE,CAAC,KAAK,KAC7E,qCACJ,CACF;AACF,CAAC;;;;;;AAQD,MAAa,yBAAyB,OAAO,OAAO;CAClD,YAAYA;CACZ,UAAUA;CACV,oBAAoB;AACtB,CAAC;;AAID,MAAa,gCAAwD;CACnE,YAAY;CACZ,UAAU;CACV,oBAAoB;AACtB;;;;;;;;AASA,MAAM,iBAAiB,OAAO,YAAY;;CAExC,OAAO,CAAC;;CAER,UAAU;EAAE,aAAa;EAAgB,OAAO,OAAO;CAAO;;;;;;;CAO9D,iBAAiB,CAAC;;;;;CAKlB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