effect-durable-agent 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/{compaction-63iEDHHl.js → compaction-D7WJa899.js} +3 -3
  2. package/dist/{compaction-63iEDHHl.js.map → compaction-D7WJa899.js.map} +1 -1
  3. package/dist/{delivery-2ZILvoRD.js → delivery-BoF-NZbZ.js} +3 -3
  4. package/dist/{delivery-2ZILvoRD.js.map → delivery-BoF-NZbZ.js.map} +1 -1
  5. package/dist/{delivery-D3MxW4wg.d.ts → delivery-v42MAMEP.d.ts} +153 -10
  6. package/dist/domain/command-queues.d.ts +1 -1
  7. package/dist/domain/message-transcript.d.ts +1 -1
  8. package/dist/domain/model-usage.d.ts +1 -1
  9. package/dist/domain/model-usage.js +1 -1
  10. package/dist/domain/reduced-state-schema.d.ts +2 -2
  11. package/dist/domain/reduced-state-schema.js +2 -2
  12. package/dist/domain/reduced-state.d.ts +2 -2
  13. package/dist/domain/reduced-state.js +3 -2
  14. package/dist/domain/reduced-state.js.map +1 -1
  15. package/dist/domain/run-scheduling.d.ts +1 -1
  16. package/dist/{durable-168Womqp.d.ts → durable-BXqwM70o.d.ts} +510 -3
  17. package/dist/{durable-D13w1Qr3.js → durable-Da57Rcml.js} +17 -3
  18. package/dist/durable-Da57Rcml.js.map +1 -0
  19. package/dist/{envelope-BCzKUq_z.js → envelope-BSI_Xh-f.js} +21 -5
  20. package/dist/envelope-BSI_Xh-f.js.map +1 -0
  21. package/dist/{envelope-Che6KatU.d.ts → envelope-CJnPfbjC.d.ts} +53 -6
  22. package/dist/{event-factory-_vF1bIJ7.js → event-factory-BUoBwqAy.js} +3 -3
  23. package/dist/{event-factory-_vF1bIJ7.js.map → event-factory-BUoBwqAy.js.map} +1 -1
  24. package/dist/{events-DwTARLMv.d.ts → events-AIIwZ6dS.d.ts} +3 -3
  25. package/dist/{in-memory-CeODnZhE.js → in-memory-E497WhtS.js} +3 -3
  26. package/dist/{in-memory-CeODnZhE.js.map → in-memory-E497WhtS.js.map} +1 -1
  27. package/dist/index.d.ts +5 -5
  28. package/dist/index.js +3 -3
  29. package/dist/{interpreter-DKGJ1sSx.js → interpreter-BwYN2PCC.js} +5 -4
  30. package/dist/interpreter-BwYN2PCC.js.map +1 -0
  31. package/dist/{model-resolver-DeBDK8XO.d.ts → model-resolver-O8Kn27GH.d.ts} +3 -3
  32. package/dist/{model-usage-0GeHwaaU.d.ts → model-usage-mttrPN0j.d.ts} +2 -2
  33. package/dist/{records--54mZEBx.js → records-D0ZIAOzd.js} +3 -3
  34. package/dist/{records--54mZEBx.js.map → records-D0ZIAOzd.js.map} +1 -1
  35. package/dist/{reduced-state-B1cvy8N_.d.ts → reduced-state-DB_iANjR.d.ts} +50549 -48726
  36. package/dist/{reduced-state-schema-B98exWxQ.d.ts → reduced-state-schema-B9TYxkP9.d.ts} +2 -2
  37. package/dist/{reducer-registry-DhGVzHBV.d.ts → reducer-registry-Bqn5B4JO.d.ts} +5 -5
  38. package/dist/{run-scheduling-wakeup-Mjic4tb_.d.ts → run-scheduling-wakeup-DX2zRAxd.d.ts} +2 -2
  39. package/dist/services/compaction.d.ts +1 -1
  40. package/dist/services/compaction.js +1 -1
  41. package/dist/services/decider.d.ts +2 -0
  42. package/dist/services/decider.js +97 -0
  43. package/dist/services/decider.js.map +1 -0
  44. package/dist/services/model-call.d.ts +1 -1
  45. package/dist/services/model-resolver.d.ts +1 -1
  46. package/dist/services/prompt-projector.d.ts +1 -1
  47. package/dist/services/reducer-registry.d.ts +1 -1
  48. package/dist/services/run-scheduler.d.ts +1 -1
  49. package/dist/services/run-scheduling-wakeup.d.ts +1 -1
  50. package/dist/services/runtime-layer.d.ts +13 -9
  51. package/dist/services/runtime-layer.js +10 -7
  52. package/dist/services/runtime-layer.js.map +1 -1
  53. package/dist/services/runtime.d.ts +1 -1
  54. package/dist/services/runtime.js +4 -3
  55. package/dist/services/runtime.js.map +1 -1
  56. package/dist/services/session-event-observer.d.ts +1 -1
  57. package/dist/services/session-query.d.ts +1 -1
  58. package/dist/services/session-query.js +3 -3
  59. package/dist/services/session-state.d.ts +2 -2
  60. package/dist/services/session-state.js +2 -1
  61. package/dist/services/session-store.d.ts +2 -2
  62. package/dist/services/session-store.js +32 -17
  63. package/dist/services/session-store.js.map +1 -1
  64. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  65. package/dist/services/sink-registry.d.ts +1 -1
  66. package/dist/services/sink-registry.js +1 -1
  67. package/dist/services/span-names.d.ts +1 -1
  68. package/dist/services/span-names.js +1 -0
  69. package/dist/services/span-names.js.map +1 -1
  70. package/dist/services/tool-registry.d.ts +1 -1
  71. package/dist/services/tool-registry.js.map +1 -1
  72. package/dist/services/tracing.d.ts +2 -2
  73. package/dist/session-admission-WE8J_0z9.js +138 -0
  74. package/dist/session-admission-WE8J_0z9.js.map +1 -0
  75. package/dist/{session-event-observer-DlP9ITB2.d.ts → session-event-observer-BWQUJTcN.d.ts} +3 -3
  76. package/dist/{session-state-BehvUVyq.js → session-state-BII-Jhf-.js} +171 -19
  77. package/dist/session-state-BII-Jhf-.js.map +1 -0
  78. package/dist/{session-store-BL6sfrnn.d.ts → session-store-DaSHeg8Q.d.ts} +25 -8
  79. package/dist/{sink-checkpoint-store-DvuHwvx_.d.ts → sink-checkpoint-store-CUvIVvlZ.d.ts} +2 -2
  80. package/dist/{sink-registry-DskRcyOS.js → sink-registry-AOjX5_A1.js} +34 -10
  81. package/dist/sink-registry-AOjX5_A1.js.map +1 -0
  82. package/dist/{subscription-DZNWFDTV.d.ts → subscription-BhwUmsl4.d.ts} +2 -2
  83. package/dist/{subscription-DmO3BcdT.js → subscription-D7U4Tziv.js} +3 -3
  84. package/dist/{subscription-DmO3BcdT.js.map → subscription-D7U4Tziv.js.map} +1 -1
  85. package/dist/testkit/layers.d.ts +13 -10
  86. package/dist/testkit/layers.js +16 -9
  87. package/dist/testkit/layers.js.map +1 -1
  88. package/dist/testkit/transcript.d.ts +10 -4
  89. package/dist/testkit/transcript.js +58 -7
  90. package/dist/testkit/transcript.js.map +1 -1
  91. package/dist/transcript.d.ts +5 -5
  92. package/dist/transcript.js +5 -5
  93. package/dist/types/events/durable.d.ts +2 -2
  94. package/dist/types/events/durable.js +2 -2
  95. package/dist/types/events.d.ts +4 -4
  96. package/dist/types/events.js +3 -3
  97. package/dist/websocket/events.d.ts +1 -1
  98. package/dist/websocket/events.js +1 -1
  99. package/dist/websocket.d.ts +3 -3
  100. package/dist/websocket.js +3 -3
  101. package/dist/{window-read-Brov9VdQ.d.ts → window-read-BELSkO-r.d.ts} +2 -2
  102. package/dist/{window-read-DPFAA1hM.js → window-read-FJTCDaSq.js} +3 -3
  103. package/dist/{window-read-DPFAA1hM.js.map → window-read-FJTCDaSq.js.map} +1 -1
  104. package/package.json +5 -1
  105. package/dist/durable-D13w1Qr3.js.map +0 -1
  106. package/dist/envelope-BCzKUq_z.js.map +0 -1
  107. package/dist/interpreter-DKGJ1sSx.js.map +0 -1
  108. package/dist/session-state-BehvUVyq.js.map +0 -1
  109. package/dist/sink-registry-DskRcyOS.js.map +0 -1
  110. package/dist/tool-registry-CHHUU9BN.d.ts +0 -87
@@ -1,8 +1,8 @@
1
1
  import { n as CommandIdempotencyKey } from "./commands-BUquEZVP.js";
2
2
  import { c as EventId, g as SessionId, h as SequenceNumber, l as InferenceId, n as CommandId, o as DurablePosition, p as RunId, r as CompactionId, v as SummaryId, y as ToolCallId } from "./core-BcimKMIv.js";
3
- import { t as DurableEventEnvelope } from "./envelope-Che6KatU.js";
4
- import { H as DecodedDurableEvent } from "./durable-168Womqp.js";
5
- import "./events-DwTARLMv.js";
3
+ import { o as EventNamespace, r as EventDedupeKey, s as EventType, t as DurableEventEnvelope } from "./envelope-CJnPfbjC.js";
4
+ import { W as DecodedDurableEvent } from "./durable-BXqwM70o.js";
5
+ import "./events-AIIwZ6dS.js";
6
6
  import { r as CompactionSummaryArtifact } from "./context-projection-Bezx3drD.js";
7
7
  import * as Context from "effect/Context";
8
8
  import * as Effect from "effect/Effect";
@@ -3191,6 +3191,7 @@ declare const DurableAppendEntry: Schema.Struct<{
3191
3191
  }>>;
3192
3192
  readonly payload: Schema.Unknown;
3193
3193
  readonly durability: Schema.Literal<"durable">;
3194
+ readonly dedupeKey: Schema.optionalKey<Schema.brand<Schema.String, "EventDedupeKey">>;
3194
3195
  }>;
3195
3196
  }>;
3196
3197
  type DurableAppendEntry = typeof DurableAppendEntry.Type;
@@ -3230,6 +3231,7 @@ declare const DurableAppendBatch: Schema.Struct<{
3230
3231
  }>>;
3231
3232
  readonly payload: Schema.Unknown;
3232
3233
  readonly durability: Schema.Literal<"durable">;
3234
+ readonly dedupeKey: Schema.optionalKey<Schema.brand<Schema.String, "EventDedupeKey">>;
3233
3235
  }>;
3234
3236
  }>>;
3235
3237
  }>;
@@ -3260,14 +3262,27 @@ interface FindCommandAdmissionInput {
3260
3262
  readonly commandId?: CommandId;
3261
3263
  readonly idempotencyKey?: CommandIdempotencyKey;
3262
3264
  }
3265
+ /** Indexed lookup of the one event a session log holds for a dedupe triple. */
3266
+ interface FindEventByDedupeKeyInput {
3267
+ readonly namespace: EventNamespace;
3268
+ readonly type: EventType;
3269
+ readonly dedupeKey: EventDedupeKey;
3270
+ }
3263
3271
  /** Semantic durable store contract for one EDA session. */
3264
3272
  interface EDASessionStoreShape {
3265
3273
  /**
3266
3274
  * Append durable logical events atomically, preserving input order.
3267
3275
  *
3268
- * Implementations must be idempotent by `eventId`: duplicates return the
3269
- * original committed position and do not advance the durable head. Live publish
3270
- * remains outside the store and is owned by `SessionState` after this succeeds.
3276
+ * Each entry, in order and inside the one append transaction, resolves to:
3277
+ * 1. the committed event with the same `eventId`, if one exists; else
3278
+ * 2. the committed event with the same `(namespace, type, dedupeKey)`, if the entry has a
3279
+ * `dedupeKey` and one exists; else
3280
+ * 3. a newly inserted event.
3281
+ *
3282
+ * An entry that resolves to an existing event (including one earlier in the same batch) returns
3283
+ * that event's own id, payload and position, writes nothing and does not advance the durable
3284
+ * head. First write wins. Live publish remains outside the store and is owned by
3285
+ * `SessionState` after this succeeds.
3271
3286
  */
3272
3287
  readonly append: (batch: DurableAppendBatch) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;
3273
3288
  /** Replay committed durable events with `seq > afterSeq`. */
@@ -3276,6 +3291,8 @@ interface EDASessionStoreShape {
3276
3291
  readonly loadCommittedEventsBySeq: (seqs: ReadonlyArray<SequenceNumber>) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;
3277
3292
  /** Lookup an admitted command without replaying the full journal. */
3278
3293
  readonly findCommandAdmission: (input: FindCommandAdmissionInput) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;
3294
+ /** Lookup the event committed for a `(namespace, type, dedupeKey)` triple. */
3295
+ readonly findEventByDedupeKey: (input: FindEventByDedupeKeyInput) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;
3279
3296
  /** Load one compacted summary artifact body by id, if it has been saved. */
3280
3297
  readonly loadSummaryArtifact: (summaryId: SummaryId) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;
3281
3298
  /** Load one framework or app reducer checkpoint, if it has been saved. */
@@ -3322,5 +3339,5 @@ declare const queryCommittedEvents: <E extends DurableEventEnvelope>(store: EDAS
3322
3339
  readonly limit?: number;
3323
3340
  }) => Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError>;
3324
3341
  //#endregion
3325
- export { TranscriptAssistantPart as $, TranscriptDefinition as A, TranscriptToolRecord as At, makeTranscriptDefinition as B, transcriptDecorationBufferLimit as Bt, TranscriptVersionMeta as C, TranscriptRecordView as Ct, TranscriptWindowSelector as D, TranscriptRunOutcome as Dt, TranscriptWindowLimits as E, TranscriptRunMember as Et, TranscriptMappingOperation as F, TranscriptVersion as Ft, DecorationBufferRecordId as G, AssistantRecordId as H, transcriptRecordId as Ht, TranscriptMappingTarget as I, UserRecordId as It, PendingTranscriptUserRecord as J, ImportAssistantRecordId as K, TranscriptMappings as L, isPendingTranscriptUserRecord as Lt, TranscriptListEntryKey as M, TranscriptUnknownRecord as Mt, TranscriptMappedEvent as N, TranscriptUserRecord as Nt, defaultTranscriptWindowLimits as O, TranscriptSessionContextRecord as Ot, TranscriptMapping as P, TranscriptUserState as Pt, TranscriptAssistantLifecycle as Q, TranscriptUserFallback as R, isTopLevelTranscriptRecord as Rt, TranscriptReadiness as S, TranscriptRecordKind as St, TranscriptWindow as T, TranscriptRunGroupRecord as Tt, CompactionRecordId as U, transcriptStoredInlineBodyLimit as Ut, transcriptMappingBounds as V, transcriptRecordEnvelopeFormat as Vt, ConsumedTranscriptUserRecord as W, SessionContextRecordId as X, RunGroupRecordId as Y, ToolRecordId as Z, EDATranscriptStoreShape as _, TranscriptPosition as _t, EDAReducerCheckpoint as a, TranscriptCompactionRecord as at, TranscriptActiveContent as b, TranscriptRecordFromEnvelope as bt, EDASessionStoreShape as c, TranscriptDecorationBufferRecord as ct, SaveReducerCheckpointInput as d, TranscriptDecorationKey as dt, TranscriptAssistantRecord as et, hasEDASessionStoreError as f, TranscriptDecorations as ft, EDATranscriptStore as g, TranscriptOrderKey as gt, selectCommittedEvent as h, TranscriptOrder as ht, EDAAppEvents as i, TranscriptClassification as it, TranscriptDefinitionError as j, TranscriptTopLevelRecord as jt, transcriptCursorOf as k, TranscriptToolLifecycle as kt, FindCommandAdmissionInput as l, TranscriptDecorationEntryId as lt, registerAppEvents as m, TranscriptLogIncarnation as mt, DurableAppendBatch as n, TranscriptBodySource as nt, EDASessionStore as o, TranscriptCursor as ot, queryCommittedEvents as p, TranscriptFieldPath as pt, InferenceAssistantRecordId as q, DurableAppendEntry as r, TranscriptBufferedDecoration as rt, EDASessionStoreError as s, TranscriptDecoration as st, CommittedDurableEvent as t, TranscriptBody as tt, InMemoryStoreOptions as u, TranscriptDecorationEntryKey as ut, TranscriptCursorMismatch as v, TranscriptRecord as vt, TranscriptVersionStatus as w, TranscriptRecordViewFromEnvelope as wt, TranscriptActivePart as x, TranscriptRecordId as xt, TranscriptMaintenanceConfig as y, TranscriptRecordEnvelope as yt, emptyTranscriptMappings as z, runGroupStatus as zt };
3326
- //# sourceMappingURL=session-store-BL6sfrnn.d.ts.map
3342
+ export { TranscriptAssistantLifecycle as $, transcriptCursorOf as A, TranscriptToolLifecycle as At, emptyTranscriptMappings as B, runGroupStatus as Bt, TranscriptReadiness as C, TranscriptRecordKind as Ct, TranscriptWindowLimits as D, TranscriptRunMember as Dt, TranscriptWindow as E, TranscriptRunGroupRecord as Et, TranscriptMapping as F, TranscriptUserState as Ft, ConsumedTranscriptUserRecord as G, transcriptMappingBounds as H, transcriptRecordEnvelopeFormat as Ht, TranscriptMappingOperation as I, TranscriptVersion as It, InferenceAssistantRecordId as J, DecorationBufferRecordId as K, TranscriptMappingTarget as L, UserRecordId as Lt, TranscriptDefinitionError as M, TranscriptTopLevelRecord as Mt, TranscriptListEntryKey as N, TranscriptUnknownRecord as Nt, TranscriptWindowSelector as O, TranscriptRunOutcome as Ot, TranscriptMappedEvent as P, TranscriptUserRecord as Pt, ToolRecordId as Q, TranscriptMappings as R, isPendingTranscriptUserRecord as Rt, TranscriptActivePart as S, TranscriptRecordId as St, TranscriptVersionStatus as T, TranscriptRecordViewFromEnvelope as Tt, AssistantRecordId as U, transcriptRecordId as Ut, makeTranscriptDefinition as V, transcriptDecorationBufferLimit as Vt, CompactionRecordId as W, transcriptStoredInlineBodyLimit as Wt, RunGroupRecordId as X, PendingTranscriptUserRecord as Y, SessionContextRecordId as Z, EDATranscriptStore as _, TranscriptOrderKey as _t, EDAReducerCheckpoint as a, TranscriptClassification as at, TranscriptMaintenanceConfig as b, TranscriptRecordEnvelope as bt, EDASessionStoreShape as c, TranscriptDecoration as ct, InMemoryStoreOptions as d, TranscriptDecorationEntryKey as dt, TranscriptAssistantPart as et, SaveReducerCheckpointInput as f, TranscriptDecorationKey as ft, selectCommittedEvent as g, TranscriptOrder as gt, registerAppEvents as h, TranscriptLogIncarnation as ht, EDAAppEvents as i, TranscriptBufferedDecoration as it, TranscriptDefinition as j, TranscriptToolRecord as jt, defaultTranscriptWindowLimits as k, TranscriptSessionContextRecord as kt, FindCommandAdmissionInput as l, TranscriptDecorationBufferRecord as lt, queryCommittedEvents as m, TranscriptFieldPath as mt, DurableAppendBatch as n, TranscriptBody as nt, EDASessionStore as o, TranscriptCompactionRecord as ot, hasEDASessionStoreError as p, TranscriptDecorations as pt, ImportAssistantRecordId as q, DurableAppendEntry as r, TranscriptBodySource as rt, EDASessionStoreError as s, TranscriptCursor as st, CommittedDurableEvent as t, TranscriptAssistantRecord as tt, FindEventByDedupeKeyInput as u, TranscriptDecorationEntryId as ut, EDATranscriptStoreShape as v, TranscriptPosition as vt, TranscriptVersionMeta as w, TranscriptRecordView as wt, TranscriptActiveContent as x, TranscriptRecordFromEnvelope as xt, TranscriptCursorMismatch as y, TranscriptRecord as yt, TranscriptUserFallback as z, isTopLevelTranscriptRecord as zt };
3343
+ //# sourceMappingURL=session-store-DaSHeg8Q.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { h as SequenceNumber } from "./core-BcimKMIv.js";
2
- import { s as EDASessionStoreError } from "./session-store-BL6sfrnn.js";
2
+ import { s as EDASessionStoreError } from "./session-store-DaSHeg8Q.js";
3
3
  import * as Context from "effect/Context";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as Layer from "effect/Layer";
@@ -36,4 +36,4 @@ declare class SinkCheckpointStore extends SinkCheckpointStore_base {
36
36
  }
37
37
  //#endregion
38
38
  export { StoredSinkCheckpoint as i, SinkCheckpointStore as n, SinkCheckpointStoreShape as r, EDASinkName as t };
39
- //# sourceMappingURL=sink-checkpoint-store-DvuHwvx_.d.ts.map
39
+ //# sourceMappingURL=sink-checkpoint-store-CUvIVvlZ.d.ts.map
@@ -1,7 +1,8 @@
1
1
  import { SequenceNumber } from "./types/core.js";
2
2
  import { foldReducedState, initialReducedState } from "./domain/reduced-state.js";
3
+ import { n as SessionCommandAdmissionConflict, o as makeAppEventAdmission, r as appEventConflict, t as RegisteredAppEvents } from "./session-admission-WE8J_0z9.js";
3
4
  import { EDASessionStore, EDASessionStoreError, selectCommittedEvent } from "./services/session-store.js";
4
- import { n as SessionContext, t as EventFactory } from "./event-factory-_vF1bIJ7.js";
5
+ import { n as SessionContext, t as EventFactory } from "./event-factory-BUoBwqAy.js";
5
6
  import { IdGenerator } from "./services/id-generator.js";
6
7
  import { annotateEdaSpan } from "./services/tracing.js";
7
8
  import { EDAKeepAlive } from "./services/keep-alive.js";
@@ -15,6 +16,7 @@ import * as Stream from "effect/Stream";
15
16
  import * as Cause from "effect/Cause";
16
17
  import * as Queue from "effect/Queue";
17
18
  import * as Ref from "effect/Ref";
19
+ import * as Result from "effect/Result";
18
20
  import * as Scope from "effect/Scope";
19
21
  import * as Semaphore from "effect/Semaphore";
20
22
  import * as SynchronizedRef from "effect/SynchronizedRef";
@@ -130,16 +132,26 @@ const makeSinkRegistry = (sinks) => Effect.gen(function* () {
130
132
  const ids = yield* IdGenerator;
131
133
  const reducerRegistry = yield* EDAReducerRegistry;
132
134
  const keepAlive = yield* EDAKeepAlive;
135
+ const appEventAdmission = makeAppEventAdmission(yield* RegisteredAppEvents);
133
136
  const started = yield* Ref.make(false);
134
137
  const hydrationGate = yield* Semaphore.make(1);
135
138
  const deliveries = [];
136
- const baseContext = (staged, publishEphemeral, scope, checkpoint) => ({
139
+ const baseContext = (sinkName, staged, publishEphemeral, scope, checkpoint) => ({
137
140
  sessionId: session.sessionId,
138
141
  checkpoint,
139
142
  events: eventFactory,
140
143
  makeEventId: ids.makeEventId,
141
144
  emitEphemeral: publishEphemeral,
142
- stageDurable: (event) => Effect.sync(() => staged.push(event)),
145
+ stageDurable: (event) => Effect.gen(function* () {
146
+ const admitted = appEventAdmission.admit(event);
147
+ if (Result.isFailure(admitted)) return yield* appEventConflict(admitted.failure);
148
+ if (event.dedupeKey === void 0) yield* Effect.logWarning("EDA sink staged a durable event without a dedupeKey", {
149
+ sink: sinkName,
150
+ namespace: event.namespace,
151
+ type: event.type
152
+ });
153
+ staged.push(admitted.success);
154
+ }),
143
155
  forkScoped: (effect) => effect.pipe(Effect.forkIn(scope), Effect.asVoid)
144
156
  });
145
157
  const makeSinkRunner = Effect.fnUntraced(function* (sink, { initialProjection, appendDurableBatch, publishEphemeral, scope }) {
@@ -205,7 +217,7 @@ const makeSinkRegistry = (sinks) => Effect.gen(function* () {
205
217
  events: eventsForSink,
206
218
  throughSeq
207
219
  };
208
- const context = baseContext(staged, publishEphemeral, scope, checkpoint);
220
+ const context = baseContext(sink.name, staged, publishEphemeral, scope, checkpoint);
209
221
  if ((yield* Effect.gen(function* () {
210
222
  if (sink.durable === void 0) return;
211
223
  if (sink.state === "none") return yield* sink.durable.process(rawBatch, context);
@@ -215,10 +227,15 @@ const makeSinkRegistry = (sinks) => Effect.gen(function* () {
215
227
  stateAfter: nextProjection.reduced,
216
228
  reducerStates: nextProjection.reducerStates
217
229
  }, context);
218
- }).pipe(Effect.as(true), Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logError("EDA durable sink violated its infallible contract", {
219
- cause: Cause.pretty(cause),
220
- sink: sink.name
221
- }).pipe(Effect.as(false))))) && staged.length > 0) {
230
+ }).pipe(Effect.as(true), Effect.catchCause((cause) => {
231
+ if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
232
+ const refusal = stagedEventRefusal(cause);
233
+ if (refusal !== void 0) return Effect.fail(refusal);
234
+ return Effect.logError("EDA durable sink violated its infallible contract", {
235
+ cause: Cause.pretty(cause),
236
+ sink: sink.name
237
+ }).pipe(Effect.as(false));
238
+ }))) && staged.length > 0) {
222
239
  yield* annotateEdaSpan({ "eda.sink.staged_events": staged.length });
223
240
  yield* appendDurableBatch(staged);
224
241
  }
@@ -243,7 +260,7 @@ const makeSinkRegistry = (sinks) => Effect.gen(function* () {
243
260
  const processEphemeral = Effect.fnUntraced(function* (event) {
244
261
  if (sink.ephemeral === void 0) return;
245
262
  if (sink.state !== "none") yield* ensureProjection();
246
- yield* sink.ephemeral.process(event, baseContext([], publishEphemeral, scope, checkpoint)).pipe(Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logError("EDA sink ephemeral projection failed", {
263
+ yield* sink.ephemeral.process(event, baseContext(sink.name, [], publishEphemeral, scope, checkpoint)).pipe(Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logError("EDA sink ephemeral projection failed", {
247
264
  cause: Cause.pretty(cause),
248
265
  sink: sink.name
249
266
  })));
@@ -298,6 +315,13 @@ const makeSinkRegistry = (sinks) => Effect.gen(function* () {
298
315
  }, { discard: true })
299
316
  };
300
317
  });
318
+ /** The `stageDurable` refusal a sink let escape, as a failure or (through `orDie`) a defect. */
319
+ const stagedEventRefusal = (cause) => {
320
+ for (const reason of cause.reasons) {
321
+ const value = Cause.isFailReason(reason) ? reason.error : Cause.isDieReason(reason) ? reason.defect : void 0;
322
+ if (value instanceof SessionCommandAdmissionConflict) return value;
323
+ }
324
+ };
301
325
  const makeSinkCheckpoint = (store, sinkName, checkpointRef) => ({
302
326
  get: (schema, initial) => SynchronizedRef.get(checkpointRef).pipe(Effect.flatMap((checkpoint) => {
303
327
  const serialized = serializedSinkState(checkpoint.payload);
@@ -342,4 +366,4 @@ const matchesInterest = (event, interests) => interests === void 0 || interests
342
366
  //#endregion
343
367
  export { EDASinkRegistry as n, EDASink as t };
344
368
 
345
- //# sourceMappingURL=sink-registry-DskRcyOS.js.map
369
+ //# sourceMappingURL=sink-registry-AOjX5_A1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sink-registry-AOjX5_A1.js","names":[],"sources":["../src/services/sink-inbox.ts","../src/services/sink-registry.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\n\n/** Durable payloads stay in the log; only bounded best-effort ephemeral work is retained. */\nconst ephemeralCapacity = 128;\nconst ephemeralByteCapacity = 256 * 1024;\n\n/** An ephemeral update could not be measured as a JSON wire value. */\nexport class SinkEphemeralEncodingError extends Schema.TaggedError<SinkEphemeralEncodingError>()(\n \"SinkEphemeralEncodingError\",\n { cause: Schema.Defect() },\n) {}\n\n/** One ordered step on a sink's serialized delivery lane. */\ntype SinkWork =\n | { readonly _tag: \"Durable\"; readonly throughSeq: SequenceNumber }\n | { readonly _tag: \"Ephemeral\"; readonly event: PositionedEvent };\n\n/**\n * Coalesces durable heads without losing ephemeral ordering barriers. Publication never\n * waits for delivery. Overflow drops the newest ephemeral update, never durable work.\n */\nexport const makeSinkInbox = Effect.fnUntraced(function* (initialHead: SequenceNumber) {\n const wake = yield* Effect.acquireRelease(Queue.sliding<void>(1), Queue.shutdown);\n let head = initialHead;\n const pending: Array<{ readonly event: PositionedEvent; readonly bytes: number }> = [];\n let pendingBytes = 0;\n\n const notify = (throughSeq: SequenceNumber) =>\n Effect.sync(() => {\n head = SequenceNumber.make(Math.max(head, throughSeq));\n Queue.offerUnsafe(wake, undefined);\n });\n\n const offerEphemeral = (event: PositionedEvent) =>\n Effect.try({\n try: () => {\n const bytes = new TextEncoder().encode(JSON.stringify(event)).byteLength;\n if (pending.length >= ephemeralCapacity || bytes > ephemeralByteCapacity - pendingBytes) {\n return false;\n }\n pending.push({ event, bytes });\n pendingBytes += bytes;\n Queue.offerUnsafe(wake, undefined);\n return true;\n },\n catch: (cause) => new SinkEphemeralEncodingError({ cause }),\n });\n\n const poll = (cursor: SequenceNumber): Effect.Effect<SinkWork | undefined> =>\n Effect.sync(() => {\n while (pending.length > 0) {\n const first = pending[0];\n if (first === undefined) break;\n if (first.event.position.seq > cursor) {\n return { _tag: \"Durable\", throughSeq: first.event.position.seq };\n }\n pending.shift();\n pendingBytes -= first.bytes;\n if (first.event.position.seq === cursor) {\n return { _tag: \"Ephemeral\", event: first.event };\n }\n }\n return cursor < head ? { _tag: \"Durable\", throughSeq: head } : undefined;\n });\n\n return { notify, offerEphemeral, poll, awaitWork: Queue.take(wake) };\n});\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { type DecodedDurableEvent } from \"../types/events/durable\";\nimport { selectCommittedEvent } from \"./session-store\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport { foldReducedState, initialReducedState, type ReducedState } from \"../domain/reduced-state\";\nimport { EDAReducerRegistry, type EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { EventId, SessionId, SequenceNumber } from \"../types/core\";\nimport type {\n DurableEventEnvelope,\n EphemeralEventEnvelope,\n PositionedEvent,\n} from \"../types/events\";\nimport type { EDASessionStoreShape } from \"./session-store\";\nimport { type CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport type { EventFactoryShape } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { makeSinkInbox } from \"./sink-inbox\";\nimport {\n appEventConflict,\n makeAppEventAdmission,\n RegisteredAppEvents,\n SessionCommandAdmissionConflict,\n type AdmittedAppEvent,\n} from \"./session-admission\";\nimport { SessionContext } from \"./session-context\";\nimport {\n EDASinkName,\n SinkCheckpointStore,\n type SinkCheckpointStoreShape,\n type StoredSinkCheckpoint,\n} from \"./sink-checkpoint-store\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Cursor-window input delivered to one durable sink drain. */\nexport interface EDASinkRawDurableBatch<E = DecodedDurableEvent> {\n /** All durable events replayed for this cursor window, including uninterested events. */\n readonly allEvents: ReadonlyArray<CommittedDurableEvent>;\n /** Events matching the sink's durable interests. */\n readonly events: ReadonlyArray<CommittedDurableEvent<E>>;\n /** Durable sequence through which the sink may advance after success. */\n readonly throughSeq: SequenceNumber;\n}\n\n/** Cursor window with framework and app projections, enabled by default. */\nexport interface EDASinkDurableBatch<E = DecodedDurableEvent> extends EDASinkRawDurableBatch<E> {\n /** Authoritative reduced state folded exactly through `throughSeq`. */\n readonly stateAfter: ReducedState;\n /** App-specific durable reducer states folded exactly through `throughSeq`. */\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\n/** Typed, sink-owned durable state stored independently from cursor advancement. */\nexport interface EDASinkCheckpoint {\n /** Decode current durable state, or return `initial` for a new or legacy cursor row. */\n readonly get: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n initial: State,\n ) => Effect.Effect<State, EDASessionStoreError>;\n /** Validate, encode, and durably save state without advancing the sink cursor. */\n readonly save: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/** Capabilities exposed to sink processors without granting raw store or bus access. */\nexport interface EDASinkContext {\n readonly sessionId: SessionId;\n /** Sink-owned checkpoint state, serialized with cursor commits and background writes. */\n readonly checkpoint: EDASinkCheckpoint;\n /**\n * Build a framework durable event. `stageDurable` accepts only the framework types app code may\n * write (`SessionConfigured`, `SystemMessageCommitted`, `AssistantMessageImported`).\n */\n readonly events: EventFactoryShape;\n /** Mint an app durable event id for staged custom events. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Publish a best-effort live-only event. */\n readonly emitEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n /**\n * Stage durable events; the runner commits them after the sink succeeds, in a transaction\n * separate from the cursor commit. A crash between the two redelivers the batch, so give each\n * staged event a `dedupeKey` derived from what caused it; one without a key logs a warning.\n *\n * An event the app event admission rules refuse fails with a `SessionCommandAdmissionConflict`\n * and is not staged: a framework lifecycle event (`framework_event`), a payload that is not\n * JSON-native (`payload_not_json`) or is over `maxAppEventBytes` (`event_too_large`), or one\n * the registered `appEvents` schema rejects (`invalid_event`). A sink that catches it keeps\n * what it staged besides. One that lets it escape `process` stops its runner before the batch\n * is acknowledged: nothing staged in that delivery commits, the cursor stays, and the next\n * runtime start redelivers the batch.\n */\n readonly stageDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n /** Fork background sink work into the session scope. */\n readonly forkScoped: (effect: Effect.Effect<unknown, unknown>) => Effect.Effect<void>;\n}\n\n/** `\"*\"` and omission select every fact; a schema selects and narrows matching envelopes. */\nexport type EDASinkInterests = \"*\" | Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\n/** Delivery policy shared by raw and projected durable consumers. */\ninterface EDADurableSinkOptions {\n readonly interests?: EDASinkInterests;\n readonly batchSize?: number;\n}\n\n/** Default durable consumer with framework and app projections at each cursor window. */\nexport interface EDAProjectedDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (\n batch: EDASinkDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n}\n\n/** Raw consumer that never hydrates, folds, or retains a session projection. */\nexport interface EDARawDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (\n batch: EDASinkRawDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n}\n\n/** Durable sink definition backed by a checkpoint and an app-owned delivery policy. */\nexport type EDADurableSinkDefinition = EDAProjectedDurableSinkDefinition;\n\n/** Best-effort live-only sink definition. */\nexport interface EDAEphemeralSinkDefinition {\n readonly interests?:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>;\n readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, never>;\n}\n\n/**\n * Named app integration hook with optional durable and ephemeral filters.\n *\n * Every sink runs on one serialized position-ordered lane. Sinks own retry and\n * terminal failure handling, so callbacks have no typed error channel except a\n * `stageDurable` refusal, which stops the runner without acknowledging the batch.\n * An unexpected defect is logged and skipped before the durable checkpoint\n * advances. Ephemeral callbacks are best-effort and are only processed after the\n * durable prefix at their anchor sequence has been projected.\n */\ninterface EDASinkOptions {\n readonly name: string;\n readonly ephemeral?: EDAEphemeralSinkDefinition;\n}\n\n/** Existing consumers receive framework and app projections unless explicitly opted out. */\nexport interface EDAProjectedSink extends EDASinkOptions {\n readonly state?: \"projected\";\n readonly durable?: EDAProjectedDurableSinkDefinition;\n}\n\n/** Raw consumers retain only their cursor and sink-owned checkpoint payload. */\nexport interface EDARawSink extends EDASinkOptions {\n readonly state: \"none\";\n readonly durable?: EDARawDurableSinkDefinition;\n}\n\n/** The outer discriminant preserves contextual callback typing for inline default sinks. */\nexport type EDASink = EDAProjectedSink | EDARawSink;\n\n/** Projected and raw overloads preserve contextual callback inference and literal names. */\nfunction makeSink<const Sink extends EDAProjectedSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDARawSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDASink>(sink: Sink): Sink;\nfunction makeSink(sink: EDASink): EDASink {\n return sink;\n}\n\n/** Convenience constructor preserving a sink's literal name/type information. */\nexport const EDASink = {\n make: makeSink,\n /** The live-event schema owns both subscription filtering and callback typing. */\n forEphemeralEvents: <E extends import(\"../types/events\").EventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n process: (event: PositionedEvent<E>, ctx: EDASinkContext) => Effect.Effect<void, never>,\n ): EDAEphemeralSinkDefinition => ({\n interests,\n process: (entry, ctx) =>\n Schema.is(interests)(entry.event)\n ? process({ position: entry.position, event: entry.event }, ctx)\n : Effect.void,\n }),\n /** One schema selects and narrows the facts delivered to a projected durable consumer. */\n forEvents: <E extends DurableEventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n sink: Omit<EDAProjectedSink, \"durable\"> & {\n readonly durable: {\n readonly batchSize?: number;\n readonly process: (\n batch: EDASinkDurableBatch<E>,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n };\n },\n ): EDAProjectedSink => ({\n ...sink,\n durable: {\n ...sink.durable,\n interests,\n process: (batch, ctx) =>\n sink.durable.process(\n {\n ...batch,\n events: batch.events.flatMap((entry) => {\n const selected = selectCommittedEvent(interests, entry);\n return selected === undefined ? [] : [selected];\n }),\n },\n ctx,\n ),\n },\n }),\n};\n\n/** Session-owned capabilities needed to start all registered sink runners. */\nexport interface EDASinkRunnerStartInput {\n readonly appendDurableBatch: (\n events: ReadonlyArray<DurableEventEnvelope>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Immutable framework and app projections at one common durable head. */\n readonly initialProjection: {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n };\n readonly publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n readonly scope: Scope.Scope;\n}\n\n/** Registry service coordinating durable checkpoints and live sink delivery. */\nexport interface EDASinkRegistryShape {\n readonly sinks: ReadonlyArray<EDASink>;\n /** Start long-lived sink runners. Safe to call once during session-state acquisition. */\n readonly startSinkRunners: (\n input: EDASinkRunnerStartInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Coalesced non-blocking nudge that the durable log head advanced. */\n readonly notifyDurableHeadAdvanced: (head: SequenceNumber) => Effect.Effect<void>;\n /** Best-effort non-blocking delivery to ephemeral sink workers. */\n readonly publishEphemeralToSinks: (event: PositionedEvent) => Effect.Effect<void>;\n}\n\n/** Registry and runner for app-provided EDA sinks. */\nexport class EDASinkRegistry extends Context.Service<EDASinkRegistry, EDASinkRegistryShape>()(\n \"@effect-durable-agent/EDASinkRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDASinkRegistry, {\n sinks: [],\n startSinkRunners: () => Effect.void,\n notifyDurableHeadAdvanced: () => Effect.void,\n publishEphemeralToSinks: () => Effect.void,\n } satisfies EDASinkRegistryShape);\n\n static readonly Live = (sinks: ReadonlyArray<EDASink>) =>\n Layer.effect(EDASinkRegistry, makeSinkRegistry(sinks));\n}\n\nconst defaultBatchSize = 100;\nconst sinkCheckpointFormatVersion = 1;\n\ninterface SinkProjection {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\ninterface SerializedSinkState {\n readonly formatVersion: typeof sinkCheckpointFormatVersion;\n readonly state: unknown;\n readonly updatedAtMs: number;\n}\n\nconst makeSinkRegistry = (sinks: ReadonlyArray<EDASink>) =>\n Effect.gen(function* () {\n const session = yield* SessionContext;\n const store = yield* EDASessionStore;\n const checkpointStore = yield* SinkCheckpointStore;\n const eventFactory = yield* EventFactory;\n const ids = yield* IdGenerator;\n const reducerRegistry = yield* EDAReducerRegistry;\n const keepAlive = yield* EDAKeepAlive;\n const appEventAdmission = makeAppEventAdmission(yield* RegisteredAppEvents);\n const started = yield* Ref.make(false);\n const hydrationGate = yield* Semaphore.make(1);\n const deliveries: Array<{\n readonly sink: EDASink;\n readonly inbox: Effect.Success<ReturnType<typeof makeSinkInbox>>;\n }> = [];\n\n const baseContext = (\n sinkName: string,\n staged: Array<AdmittedAppEvent>,\n publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>,\n scope: Scope.Scope,\n checkpoint: EDASinkCheckpoint,\n ): EDASinkContext => ({\n sessionId: session.sessionId,\n checkpoint,\n events: eventFactory,\n makeEventId: ids.makeEventId,\n emitEphemeral: publishEphemeral,\n stageDurable: (event) =>\n Effect.gen(function* () {\n const admitted = appEventAdmission.admit(event);\n if (Result.isFailure(admitted)) return yield* appEventConflict(admitted.failure);\n // Staged events and the cursor commit separately; only a key collapses a restaged event.\n if (event.dedupeKey === undefined) {\n yield* Effect.logWarning(\"EDA sink staged a durable event without a dedupeKey\", {\n sink: sinkName,\n namespace: event.namespace,\n type: event.type,\n });\n }\n staged.push(admitted.success);\n }),\n forkScoped: (effect) => effect.pipe(Effect.forkIn(scope), Effect.asVoid),\n });\n\n const makeSinkRunner = Effect.fnUntraced(function* (\n sink: EDASink,\n { initialProjection, appendDurableBatch, publishEphemeral, scope }: EDASinkRunnerStartInput,\n ) {\n // Long-lived fibers capture the head and capabilities, not the initial projection.\n const initialHead = initialProjection.reduced.lastSeq;\n const sinkName = EDASinkName.make(sink.name);\n const storedCheckpoint = yield* checkpointStore.load(sinkName);\n const checkpointRef = yield* SynchronizedRef.make(storedCheckpoint);\n const checkpoint = makeSinkCheckpoint(checkpointStore, sinkName, checkpointRef);\n const cursor = storedCheckpoint.afterSeq;\n const cursorRef = yield* Ref.make(cursor);\n if (cursor > initialHead) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} cursor exceeds session head`,\n });\n }\n // Keep only an exact projection seed; lagging workers reconstruct in their own scope.\n const state = yield* Ref.make<SinkProjection | undefined>(\n sink.state === \"none\"\n ? undefined\n : cursor === initialHead\n ? {\n reduced: initialProjection.reduced,\n reducerStates: initialProjection.reducerStates,\n }\n : cursor === 0\n ? { reduced: initialReducedState, reducerStates: reducerRegistry.initial }\n : undefined,\n );\n const inbox = yield* makeSinkInbox(initialHead).pipe(Scope.provide(scope));\n deliveries.push({ sink, inbox });\n const ensureProjection = Effect.fnUntraced(function* () {\n const existing = yield* Ref.get(state);\n if (existing !== undefined) return existing;\n const hydrated = yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((event) => event.position.seq <= cursor),\n Stream.chunks,\n Stream.runFold(\n (): SinkProjection => ({\n reduced: initialReducedState,\n reducerStates: reducerRegistry.initial,\n }),\n (current, page): SinkProjection => ({\n reduced: foldReducedState(current.reduced, page),\n reducerStates: reducerRegistry.reduce(current.reducerStates, page),\n }),\n ),\n Effect.withSpan(\"agent.sink.hydrate\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.through\": cursor,\n },\n }),\n hydrationGate.withPermits(1),\n );\n if (hydrated.reduced.lastSeq !== cursor) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not reconstruct its cursor`,\n });\n }\n yield* Ref.set(state, hydrated);\n return hydrated;\n });\n\n const processDurableBatch = Effect.fnUntraced(function* (\n allEvents: ReadonlyArray<CommittedDurableEvent>,\n ) {\n if (allEvents.length === 0) {\n return;\n }\n\n const currentCursor = yield* Ref.get(cursorRef);\n const fresh = allEvents.filter((entry) => entry.position.seq > currentCursor);\n if (fresh.length === 0) {\n return;\n }\n\n const durable = sink.durable;\n const last = fresh.at(-1);\n if (last === undefined) return;\n const throughSeq = last.position.seq;\n const nextProjection =\n sink.state === \"none\"\n ? undefined\n : yield* Effect.gen(function* () {\n const current = yield* ensureProjection();\n return {\n reduced: foldReducedState(current.reduced, fresh),\n reducerStates: reducerRegistry.reduce(current.reducerStates, fresh),\n };\n });\n const eventsForSink =\n durable === undefined ? [] : filterInterested(fresh, durable.interests);\n\n if (durable !== undefined && eventsForSink.length > 0) {\n yield* Effect.gen(function* () {\n const staged: Array<AdmittedAppEvent> = [];\n const rawBatch: EDASinkRawDurableBatch = {\n allEvents: fresh,\n events: eventsForSink,\n throughSeq,\n };\n const context = baseContext(sink.name, staged, publishEphemeral, scope, checkpoint);\n const delivery = Effect.gen(function* () {\n if (sink.durable === undefined) return;\n if (sink.state === \"none\") return yield* sink.durable.process(rawBatch, context);\n // The projected branch owns both construction and delivery of these fields.\n if (nextProjection === undefined)\n return yield* Effect.die(\"Projected sink missing its projection\");\n return yield* sink.durable.process(\n {\n ...rawBatch,\n stateAfter: nextProjection.reduced,\n reducerStates: nextProjection.reducerStates,\n },\n context,\n );\n });\n const completed = yield* delivery.pipe(\n Effect.as(true),\n Effect.catchCause((cause) => {\n if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);\n // Skipping would acknowledge a batch whose staged facts never commit: stop instead.\n const refusal = stagedEventRefusal(cause);\n if (refusal !== undefined) return Effect.fail(refusal);\n return Effect.logError(\"EDA durable sink violated its infallible contract\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }).pipe(Effect.as(false));\n }),\n );\n if (completed && staged.length > 0) {\n yield* annotateEdaSpan({ \"eda.sink.staged_events\": staged.length });\n yield* appendDurableBatch(staged);\n }\n }).pipe(\n Effect.withSpan(\"agent.sink.drain\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.sink.cursor.before\": currentCursor,\n \"eda.sink.events.read\": fresh.length,\n \"eda.sink.events.interested\": eventsForSink.length,\n \"eda.sink.cursor.after\": throughSeq,\n },\n }),\n );\n }\n\n yield* commitSinkCheckpoint(checkpointStore, sinkName, checkpointRef, throughSeq);\n yield* Ref.set(cursorRef, throughSeq);\n yield* Ref.set(state, nextProjection);\n });\n\n const drainDurablesThrough = Effect.fnUntraced(function* (targetHead: SequenceNumber) {\n const currentCursor = yield* Ref.get(cursorRef);\n if (currentCursor >= targetHead) return;\n const allEvents = yield* readCursorBatchThrough(\n store,\n currentCursor,\n targetHead,\n sink.durable?.batchSize,\n );\n if (allEvents.length === 0) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not read its durable backlog`,\n });\n }\n yield* processDurableBatch(allEvents);\n });\n\n const processEphemeral = Effect.fnUntraced(function* (event: PositionedEvent) {\n if (sink.ephemeral === undefined) return;\n if (sink.state !== \"none\") yield* ensureProjection();\n yield* sink.ephemeral\n .process(event, baseContext(sink.name, [], publishEphemeral, scope, checkpoint))\n .pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink ephemeral projection failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n });\n\n const runLoop = Effect.forever(\n Effect.gen(function* () {\n const currentCursor = yield* Ref.get(cursorRef);\n const work = yield* inbox.poll(currentCursor);\n if (work === undefined) {\n yield* inbox.awaitWork;\n return;\n }\n yield* keepAlive.withActiveWork(\n `sink:${sink.name}`,\n work._tag === \"Durable\"\n ? drainDurablesThrough(work.throughSeq)\n : processEphemeral(work.event),\n );\n yield* Effect.yieldNow;\n }),\n ).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink runner failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n\n return {\n runLoop,\n initialization:\n sink.state === \"none\"\n ? \"raw\"\n : cursor === initialHead\n ? \"reused\"\n : cursor > 0\n ? \"deferred\"\n : \"empty\",\n };\n });\n\n return {\n sinks,\n startSinkRunners: Effect.fnUntraced(function* (input: EDASinkRunnerStartInput) {\n const wasStarted = yield* Ref.getAndSet(started, true);\n if (wasStarted) {\n return;\n }\n const runners = yield* Effect.gen(function* () {\n const runners = yield* Effect.forEach(sinks, (sink) => makeSinkRunner(sink, input), {\n concurrency: 1,\n });\n yield* Effect.annotateCurrentSpan({\n \"eda.sinks.raw\": runners.filter((runner) => runner.initialization === \"raw\").length,\n \"eda.sinks.reused\": runners.filter((runner) => runner.initialization === \"reused\")\n .length,\n \"eda.sinks.deferred\": runners.filter((runner) => runner.initialization === \"deferred\")\n .length,\n \"eda.sinks.empty\": runners.filter((runner) => runner.initialization === \"empty\").length,\n });\n return runners;\n }).pipe(\n Effect.withSpan(\"agent.sinks.initialize\", {\n attributes: {\n sessionId: session.sessionId,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.head\": input.initialProjection.reduced.lastSeq,\n \"eda.sinks.count\": sinks.length,\n },\n }),\n );\n // Catch-up can append events. Register every inbox before starting any delivery fiber.\n yield* Effect.forEach(\n runners,\n (runner) => runner.runLoop.pipe(Effect.forkIn(input.scope)),\n {\n discard: true,\n },\n );\n }),\n notifyDurableHeadAdvanced: (head) =>\n Effect.forEach(deliveries, ({ inbox }) => inbox.notify(head), { discard: true }),\n publishEphemeralToSinks: (event) =>\n Effect.forEach(\n deliveries,\n ({ sink, inbox }) => {\n if (\n sink.ephemeral === undefined ||\n !matchesInterest(event.event, sink.ephemeral.interests)\n )\n return Effect.void;\n return Effect.gen(function* () {\n const accepted = yield* inbox.offerEphemeral(event);\n if (!accepted) {\n yield* Effect.logWarning(\"EDA sink ephemeral buffer full\", { sink: sink.name });\n }\n }).pipe(\n Effect.catchTag(\"SinkEphemeralEncodingError\", (error) =>\n Effect.logWarning(\"EDA sink ephemeral serialization failed\", {\n cause: error.cause,\n sink: sink.name,\n }),\n ),\n );\n },\n { discard: true },\n ),\n } satisfies EDASinkRegistryShape;\n });\n\n/** The `stageDurable` refusal a sink let escape, as a failure or (through `orDie`) a defect. */\nconst stagedEventRefusal = (\n cause: Cause.Cause<unknown>,\n): SessionCommandAdmissionConflict | undefined => {\n for (const reason of cause.reasons) {\n const value = Cause.isFailReason(reason)\n ? reason.error\n : Cause.isDieReason(reason)\n ? reason.defect\n : undefined;\n if (value instanceof SessionCommandAdmissionConflict) return value;\n }\n return undefined;\n};\n\nconst makeSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n): EDASinkCheckpoint => ({\n get: (schema, initial) =>\n SynchronizedRef.get(checkpointRef).pipe(\n Effect.flatMap((checkpoint) => {\n const serialized = serializedSinkState(checkpoint.payload);\n return serialized === undefined\n ? Effect.succeed(initial)\n : decodeSinkState(schema, serialized.state);\n }),\n ),\n save: (schema, state) =>\n encodeSinkState(schema, state).pipe(\n Effect.flatMap((encoded) => {\n const payload: SerializedSinkState = {\n formatVersion: sinkCheckpointFormatVersion,\n state: encoded,\n updatedAtMs: Date.now(),\n };\n return SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.saveState(sinkName, payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq: checkpoint.afterSeq,\n payload,\n },\n ] as const),\n ),\n );\n }),\n ),\n});\n\nconst commitSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n afterSeq: SequenceNumber,\n): Effect.Effect<void, EDASessionStoreError> =>\n SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.commit(sinkName, afterSeq, checkpoint.payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq,\n payload: checkpoint.payload,\n },\n ] as const),\n ),\n );\n\nconst serializedSinkState = (payload: unknown): SerializedSinkState | undefined => {\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n !(\"formatVersion\" in payload) ||\n payload.formatVersion !== sinkCheckpointFormatVersion ||\n !(\"state\" in payload) ||\n !(\"updatedAtMs\" in payload) ||\n typeof payload.updatedAtMs !== \"number\"\n ) {\n return undefined;\n }\n return {\n formatVersion: sinkCheckpointFormatVersion,\n state: payload.state,\n updatedAtMs: payload.updatedAtMs,\n };\n};\n\nconst decodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n encoded: unknown,\n): Effect.Effect<State, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(encoded),\n catch: (cause) => sinkCheckpointCodecError(\"decoding\", cause),\n });\n\nconst encodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n): Effect.Effect<unknown, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.encodeUnknownSync(schema)(state),\n catch: (cause) => sinkCheckpointCodecError(\"encoding\", cause),\n });\n\nconst sinkCheckpointCodecError = (operation: string, cause: unknown) =>\n new EDASessionStoreError({\n message:\n cause instanceof Error\n ? `${operation} sink checkpoint: ${cause.message}`\n : `${operation} sink checkpoint: ${String(cause)}`,\n });\n\nconst readCursorBatchThrough = (\n store: EDASessionStoreShape,\n afterSeq: SequenceNumber,\n throughSeq: SequenceNumber,\n batchSize = defaultBatchSize,\n) =>\n store.eventsAfter(afterSeq).pipe(\n Stream.takeWhile((event) => event.position.seq <= throughSeq),\n Stream.take(batchSize),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n\nconst filterInterested = (\n events: ReadonlyArray<CommittedDurableEvent>,\n interests: EDASinkInterests | undefined,\n): ReadonlyArray<CommittedDurableEvent> =>\n events.filter(\n (entry) =>\n interests === undefined ||\n interests === \"*\" ||\n selectCommittedEvent(interests, entry) !== undefined,\n );\n\nconst matchesInterest = (\n event: import(\"../types/events\").EventEnvelope,\n interests:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>\n | undefined,\n): boolean => interests === undefined || interests === \"*\" || Schema.is(interests)(event);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAQA,MAAM,oBAAoB;AAC1B,MAAM,wBAAwB;;AAG9B,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,OAAO,OAAO,OAAO,EAAE,CAC3B,CAAC,CAAC,CAAC;;;;;AAWH,MAAa,gBAAgB,OAAO,WAAW,WAAW,aAA6B;CACrF,MAAM,OAAO,OAAO,OAAO,eAAe,MAAM,QAAc,CAAC,GAAG,MAAM,QAAQ;CAChF,IAAI,OAAO;CACX,MAAM,UAA8E,CAAC;CACrF,IAAI,eAAe;CAEnB,MAAM,UAAU,eACd,OAAO,WAAW;EAChB,OAAO,eAAe,KAAK,KAAK,IAAI,MAAM,UAAU,CAAC;EACrD,MAAM,YAAY,MAAM,KAAA,CAAS;CACnC,CAAC;CAEH,MAAM,kBAAkB,UACtB,OAAO,IAAI;EACT,WAAW;GACT,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC,CAAC;GAC9D,IAAI,QAAQ,UAAU,qBAAqB,QAAQ,wBAAwB,cACzE,OAAO;GAET,QAAQ,KAAK;IAAE;IAAO;GAAM,CAAC;GAC7B,gBAAgB;GAChB,MAAM,YAAY,MAAM,KAAA,CAAS;GACjC,OAAO;EACT;EACA,QAAQ,UAAU,I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kBAAkB,MAAM,CAAC,CAAC,OAAO;CACnD,QAAQ,UAAU,yBAAyB,YAAY,KAAK;AAC9D,CAAC;AAEH,MAAM,mBACJ,QACA,UAEA,OAAO,IAAI;CACT,WAAW,OAAO,kBAAkB,MAAM,CAAC,CAAC,KAAK;CACjD,QAAQ,UAAU,yBAAyB,YAAY,KAAK;AAC9D,CAAC;AAEH,MAAM,4BAA4B,WAAmB,UACnD,IAAI,qBAAqB,EACvB,SACE,iBAAiB,QACb,GAAG,UAAU,oBAAoB,MAAM,YACvC,GAAG,UAAU,oBAAoB,OAAO,KAAK,IACrD,CAAC;AAEH,MAAM,0BACJ,OACA,UACA,YACA,YAAY,qBAEZ,MAAM,YAAY,QAAQ,CAAC,CAAC,KAC1B,OAAO,WAAW,UAAU,MAAM,SAAS,OAAO,UAAU,GAC5D,OAAO,KAAK,SAAS,GACrB,OAAO,YACP,OAAO,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAC3C;AAEF,MAAM,oBACJ,QACA,cAEA,OAAO,QACJ,UACC,cAAc,KAAA,KACd,cAAc,OACd,qBAAqB,WAAW,KAAK,MAAM,KAAA,CAC/C;AAEF,MAAM,mBACJ,OACA,cAIY,cAAc,KAAA,KAAa,cAAc,OAAO,OAAO,GAAG,SAAS,CAAC,CAAC,KAAK"}
@@ -1,5 +1,5 @@
1
1
  import { h as SequenceNumber } from "./core-BcimKMIv.js";
2
- import { E as TranscriptWindowLimits, T as TranscriptWindow, _ as EDATranscriptStoreShape, b as TranscriptActiveContent, ot as TranscriptCursor, s as EDASessionStoreError } from "./session-store-BL6sfrnn.js";
2
+ import { D as TranscriptWindowLimits, E as TranscriptWindow, s as EDASessionStoreError, st as TranscriptCursor, v as EDATranscriptStoreShape, x as TranscriptActiveContent } from "./session-store-DaSHeg8Q.js";
3
3
  import * as Effect from "effect/Effect";
4
4
  import * as Schema from "effect/Schema";
5
5
  //#region src/transcript/subscription.d.ts
@@ -963,4 +963,4 @@ declare const planTranscriptUpdate: (input: {
963
963
  declare const readTranscriptSubscription: (store: EDATranscriptStoreShape, base: TranscriptSubscriptionBase | undefined, request: TranscriptSubscriptionRequest, policy: TranscriptSubscriptionPolicy) => Effect.Effect<TranscriptSubscriptionRead, EDASessionStoreError>;
964
964
  //#endregion
965
965
  export { TranscriptSubscriptionRead as a, defaultTranscriptSubscriptionPolicy as c, transcriptCoverageOf as d, transcriptSubscriptionBaseOf as f, TranscriptSubscriptionPolicy as i, planTranscriptUpdate as l, TranscriptRequestId as n, TranscriptSubscriptionRequest as o, TranscriptSubscriptionBase as r, TranscriptUpdate as s, TranscriptCoverage as t, readTranscriptSubscription as u };
966
- //# sourceMappingURL=subscription-DZNWFDTV.d.ts.map
966
+ //# sourceMappingURL=subscription-BhwUmsl4.d.ts.map
@@ -1,6 +1,6 @@
1
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--54mZEBx.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
4
  import * as Effect from "effect/Effect";
5
5
  import * as Schema from "effect/Schema";
6
6
  import * as SchemaGetter from "effect/SchemaGetter";
@@ -502,4 +502,4 @@ const evictOldest = Effect.fnUntraced(function* (read, from, to, maxRecords) {
502
502
  //#endregion
503
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
504
 
505
- //# sourceMappingURL=subscription-DmO3BcdT.js.map
505
+ //# sourceMappingURL=subscription-D7U4Tziv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"subscription-DmO3BcdT.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,U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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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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,16 +1,15 @@
1
1
  import { g as SessionId } from "../core-BcimKMIv.js";
2
- import { t as DurableEventEnvelope } from "../envelope-Che6KatU.js";
3
- import "../events-DwTARLMv.js";
4
- import { c as EDASessionStoreShape, o as EDASessionStore, s as EDASessionStoreError } from "../session-store-BL6sfrnn.js";
5
- import { t as ModelResolver } from "../model-resolver-DeBDK8XO.js";
6
- import { r as EDAReducerRegistry, t as EDAReducer } from "../reducer-registry-DhGVzHBV.js";
7
- import { An as EDAPromptProjector, Ct as RunScheduler, En as SessionContext, Jt as EDASink, Q as EDASessionQuery, St as ToolExecutor, Tn as EventFactory, bt as InferenceRunner, dn as CompactionPolicy, en as EDASinkRegistry, ht as SessionState, mn as CompactionRunner, on as CompactionExecutor, rn as LiveEventBus, xt as InferenceRunnerStreamPart, yt as TurnRunner } from "../reduced-state-B1cvy8N_.js";
8
- import { a as ToolParamsSchema, i as EDAToolRegistryShape, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-CHHUU9BN.js";
2
+ import { t as DurableEventEnvelope } from "../envelope-CJnPfbjC.js";
3
+ import "../events-AIIwZ6dS.js";
4
+ import { c as EDASessionStoreShape, i as EDAAppEvents, o as EDASessionStore, s as EDASessionStoreError } from "../session-store-DaSHeg8Q.js";
5
+ import { t as ModelResolver } from "../model-resolver-O8Kn27GH.js";
6
+ import { r as EDAReducerRegistry, t as EDAReducer } from "../reducer-registry-Bqn5B4JO.js";
7
+ import { Bt as CompactionExecutor, Ft as EDASinkRegistry, Gt as CompactionPolicy, Jt as CompactionRunner, Ln as EDADecider, _n as EDASessionQuery, _t as InferenceRunnerStreamPart, an as EventFactory, ar as EDAPromptProjector, bn as LiveEventBus, cn as EDAToolRegistry, dt as SessionState, gt as InferenceRunner, ht as TurnRunner, kt as EDASink, ln as EDAToolRegistryShape, on as EDAModelToolkit, tr as SessionContext, un as ToolParamsSchema, vt as ToolExecutor, yt as RunScheduler } from "../reduced-state-DB_iANjR.js";
8
+ import { t as SessionEventObserver } from "../session-event-observer-BWQUJTcN.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 { t as SessionEventObserver } from "../session-event-observer-DlP9ITB2.js";
12
- import { n as SinkCheckpointStore } from "../sink-checkpoint-store-DvuHwvx_.js";
13
- import { t as RunSchedulingWakeup } from "../run-scheduling-wakeup-Mjic4tb_.js";
11
+ import { n as SinkCheckpointStore } from "../sink-checkpoint-store-CUvIVvlZ.js";
12
+ import { t as RunSchedulingWakeup } from "../run-scheduling-wakeup-DX2zRAxd.js";
14
13
  import * as Layer from "effect/Layer";
15
14
  import * as LanguageModel from "effect/ai/LanguageModel";
16
15
  import * as Stream from "effect/Stream";
@@ -98,6 +97,10 @@ interface EdaTestLayerOptions {
98
97
  readonly compactionExecutorLayer?: Layer.Layer<CompactionExecutor>;
99
98
  /** App-specific durable metadata reducers. */
100
99
  readonly reducers?: ReadonlyArray<EDAReducer>;
100
+ /** Application event union, registered on the store and checked at admission, as in hosts. */
101
+ readonly appEvents?: EDAAppEvents;
102
+ /** Deciders the runtime runs, as `makeEDARuntimeLayer` registers them. */
103
+ readonly deciders?: ReadonlyArray<EDADecider>;
101
104
  /** Override state-to-LLM context projection. */
102
105
  readonly promptProjectorLayer?: Layer.Layer<EDAPromptProjector>;
103
106
  /** App-provided EDA sinks. */