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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/domain/command-queues.d.ts +1 -1
  2. package/dist/domain/message-transcript.d.ts +1 -1
  3. package/dist/domain/reduced-state.d.ts +1 -1
  4. package/dist/domain/run-scheduling.d.ts +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/records-DWKEjuqb.js +675 -0
  7. package/dist/records-DWKEjuqb.js.map +1 -0
  8. package/dist/{reduced-state-PJdig48e.d.ts → reduced-state-B5WxKSM5.d.ts} +4206 -4206
  9. package/dist/{reducer-registry-BAbhZs6d.d.ts → reducer-registry-CPObI3cs.d.ts} +2 -2
  10. package/dist/{run-scheduling-wakeup-QLK87OqG.d.ts → run-scheduling-wakeup-B19JTeyq.d.ts} +2 -2
  11. package/dist/services/compaction.d.ts +1 -1
  12. package/dist/services/model-call.d.ts +1 -1
  13. package/dist/services/prompt-projector.d.ts +1 -1
  14. package/dist/services/reducer-registry.d.ts +1 -1
  15. package/dist/services/reducer-registry.js +1 -1
  16. package/dist/services/run-scheduler.d.ts +1 -1
  17. package/dist/services/run-scheduling-wakeup.d.ts +1 -1
  18. package/dist/services/runtime-layer.d.ts +6 -6
  19. package/dist/services/runtime-layer.js +3 -3
  20. package/dist/services/runtime.d.ts +1 -1
  21. package/dist/services/runtime.js +1 -1
  22. package/dist/services/session-query.d.ts +1 -1
  23. package/dist/services/session-query.js +2 -2
  24. package/dist/services/session-state.d.ts +1 -1
  25. package/dist/services/session-state.js +1 -1
  26. package/dist/services/session-store.d.ts +1 -1
  27. package/dist/services/session-store.js +1 -1
  28. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  29. package/dist/services/sink-registry.d.ts +1 -1
  30. package/dist/services/sink-registry.js +1 -1
  31. package/dist/services/tool-registry.d.ts +1 -1
  32. package/dist/{session-state-StlO5B2N.js → session-state-C6SyphC0.js} +3 -3
  33. package/dist/{session-state-StlO5B2N.js.map → session-state-C6SyphC0.js.map} +1 -1
  34. package/dist/{session-store-ByDjS03N.d.ts → session-store-CWYZ29CV.d.ts} +163 -45
  35. package/dist/{session-store-DcJjs4Fd.js → session-store-DuEhcqIC.js} +3 -2
  36. package/dist/{session-store-DcJjs4Fd.js.map → session-store-DuEhcqIC.js.map} +1 -1
  37. package/dist/{sink-checkpoint-store-BHb8YRTw.d.ts → sink-checkpoint-store-B8Ky5nfW.d.ts} +2 -2
  38. package/dist/{sink-registry-DEneTH8u.js → sink-registry-DtrssBxF.js} +2 -2
  39. package/dist/{sink-registry-DEneTH8u.js.map → sink-registry-DtrssBxF.js.map} +1 -1
  40. package/dist/subscription-DelB8L87.d.ts +958 -0
  41. package/dist/subscription-g5W0Ggqx.js +498 -0
  42. package/dist/subscription-g5W0Ggqx.js.map +1 -0
  43. package/dist/testkit/layers.d.ts +9 -6
  44. package/dist/testkit/layers.js +4 -4
  45. package/dist/testkit/layers.js.map +1 -1
  46. package/dist/{tool-registry-CxZ0iuYb.d.ts → tool-registry-B_WE2ZwK.d.ts} +2 -2
  47. package/dist/transcript.d.ts +44 -4
  48. package/dist/transcript.js +98 -170
  49. package/dist/transcript.js.map +1 -1
  50. package/dist/websocket.d.ts +2209 -2
  51. package/dist/websocket.js +704 -18
  52. package/dist/websocket.js.map +1 -1
  53. package/dist/{window-read-B8aF_hDq.js → window-read-BDayZf7O.js} +74 -683
  54. package/dist/window-read-BDayZf7O.js.map +1 -0
  55. package/package.json +1 -1
  56. package/dist/window-read-B8aF_hDq.js.map +0 -1
package/dist/websocket.js CHANGED
@@ -2,24 +2,27 @@ import { Position, SequenceNumber } from "./types/core.js";
2
2
  import { d as PositionedEvent, g as UnixEpochMillis, i as EventEnvelope } from "./envelope-BCzKUq_z.js";
3
3
  import { U as EDADurableEvent } from "./durable-CD__3ztN.js";
4
4
  import { EDAEphemeralEvent } from "./types/events.js";
5
+ import { E as TranscriptOrder, _ as TranscriptCursor } from "./records-DWKEjuqb.js";
6
+ import { c as transcriptCoverageOf, i as TranscriptUpdate, n as TranscriptRequestId, r as TranscriptSubscriptionBase, t as TranscriptCoverage } from "./subscription-g5W0Ggqx.js";
5
7
  import * as Effect from "effect/Effect";
6
8
  import * as Schema from "effect/Schema";
9
+ import * as Exit from "effect/Exit";
7
10
  //#region src/websocket/protocol.ts
8
- const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
9
- const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
11
+ const PositiveInt$2 = Schema.Int.check(Schema.isGreaterThan(0));
12
+ const NonNegativeInt$2 = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
10
13
  /** Current EDA live-event WebSocket wire protocol version. */
11
14
  const EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION = 1;
12
15
  /** Flow-control policy announced by the server in the hello frame. */
13
16
  const EDAWebSocketWireFlowControl = Schema.Struct({
14
- ackTimeoutMs: PositiveInt,
17
+ ackTimeoutMs: PositiveInt$2,
15
18
  /** Deprecated: servers no longer send heartbeat frames. Kept so deployed clients can decode hello. */
16
- heartbeatIntervalMs: PositiveInt,
17
- maxFrameBytes: PositiveInt,
18
- maxFrameEvents: PositiveInt,
19
- maxInFlightFrames: PositiveInt,
19
+ heartbeatIntervalMs: PositiveInt$2,
20
+ maxFrameBytes: PositiveInt$2,
21
+ maxFrameEvents: PositiveInt$2,
22
+ maxInFlightFrames: PositiveInt$2,
20
23
  /** Suggested client-originated ping cadence; absent on servers that still send heartbeats. */
21
- pingIntervalMs: Schema.optionalKey(PositiveInt),
22
- subscriberBufferCapacityEvents: PositiveInt
24
+ pingIntervalMs: Schema.optionalKey(PositiveInt$2),
25
+ subscriberBufferCapacityEvents: PositiveInt$2
23
26
  });
24
27
  /**
25
28
  * Canonical client liveness ping message.
@@ -38,27 +41,35 @@ const EDAWebSocketWireHelloFrame = Schema.Struct({
38
41
  _tag: Schema.Literal("hello"),
39
42
  protocolVersion: Schema.Literal(1),
40
43
  subscriberId: Schema.NonEmptyString,
41
- resumeSeq: NonNegativeInt,
44
+ resumeSeq: NonNegativeInt$2,
42
45
  flowControl: EDAWebSocketWireFlowControl
43
46
  });
44
47
  const EDAWebSocketWireHeartbeatFrame = Schema.Struct({
45
48
  _tag: Schema.Literal("heartbeat"),
46
- serverTimeMs: NonNegativeInt,
47
- durableThroughSeq: NonNegativeInt
49
+ serverTimeMs: NonNegativeInt$2,
50
+ durableThroughSeq: NonNegativeInt$2
48
51
  });
49
52
  const EDAWebSocketWireLaggedFrame = Schema.Struct({
50
53
  _tag: Schema.Literal("lagged"),
51
- resumeSeq: NonNegativeInt,
54
+ resumeSeq: NonNegativeInt$2,
52
55
  reason: Schema.Literals(["buffer-overflow", "ack-timeout"])
53
56
  });
54
57
  const EDAWebSocketWireErrorFrame = Schema.Struct({
55
58
  _tag: Schema.Literal("error"),
56
59
  message: Schema.String
57
60
  });
61
+ /**
62
+ * Client acknowledgement. `frameId` is the transport receipt: it cumulatively frees flow-control
63
+ * capacity. On a transcript socket `appliedUpdateSeq` is the client's applied cut, the last
64
+ * transcript update it applied completely, and `durableThroughSeq` is that update's
65
+ * `throughSeq`; both advance only on complete updates, never on a partial chunked transfer.
66
+ * Raw event sockets ignore `appliedUpdateSeq`.
67
+ */
58
68
  const EDAWebSocketWireAckFrame = Schema.Struct({
59
69
  _tag: Schema.Literal("ack"),
60
- frameId: PositiveInt,
61
- durableThroughSeq: NonNegativeInt
70
+ frameId: PositiveInt$2,
71
+ durableThroughSeq: NonNegativeInt$2,
72
+ appliedUpdateSeq: Schema.optionalKey(NonNegativeInt$2)
62
73
  });
63
74
  const EDAWebSocketWireClientFrame = Schema.Union([EDAWebSocketWireAckFrame, EDAWebSocketWirePingFrame]);
64
75
  /** Complete framework-owned event union present on every EDA WebSocket. */
@@ -70,9 +81,9 @@ const makeEDAWebSocketDomainSchemas = (event) => {
70
81
  });
71
82
  const eventsFrame = Schema.Struct({
72
83
  _tag: Schema.Literal("events"),
73
- frameId: PositiveInt,
84
+ frameId: PositiveInt$2,
74
85
  events: Schema.NonEmptyArray(positionedEvent),
75
- durableThroughSeq: NonNegativeInt
86
+ durableThroughSeq: NonNegativeInt$2
76
87
  });
77
88
  return {
78
89
  event,
@@ -494,6 +505,681 @@ const protocolClose = (state, message) => ({
494
505
  }
495
506
  });
496
507
  //#endregion
497
- export { EDAFrameworkWebSocketEvent, EDAWebSocketAckFrame, EDAWebSocketClientFrame, EDAWebSocketDeliveryCheckpoint, EDAWebSocketErrorFrame, EDAWebSocketEventsFrame, EDAWebSocketFlowControl, EDAWebSocketHeartbeatFrame, EDAWebSocketHelloFrame, EDAWebSocketInFlightFrame, EDAWebSocketLaggedFrame, EDAWebSocketPingFrame, EDAWebSocketPongFrame, EDAWebSocketServerFrame, EDAWebSocketSuppressedRange, EDAWebSocketWireAckFrame, EDAWebSocketWireClientFrame, EDAWebSocketWireErrorFrame, EDAWebSocketWireFlowControl, EDAWebSocketWireHeartbeatFrame, EDAWebSocketWireHelloFrame, EDAWebSocketWireLaggedFrame, EDAWebSocketWirePingFrame, EDAWebSocketWirePongFrame, EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE, EDA_WEB_SOCKET_PROTOCOL_VERSION, EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION, EDA_WS_CLOSE_GOING_AWAY, EDA_WS_CLOSE_LAGGED, EDA_WS_CLOSE_PROTOCOL_ERROR, EDA_WS_CLOSE_SEND_FAILED, EDA_WS_CLOSE_UNSUPPORTED_DATA, FrameId, SubscriberId, SubscriberLagReason, checkpointWebSocketDeliveryState, decodeEDAWebSocketClientMessage, defaultEDAWebSocketFlowControl, deliveryHelloFrame, edaFrameworkWebSocketWireProtocol, encodeEDAWebSocketServerFrame, laggedCloseReason, makeEDAWebSocketWireProtocol, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent, onHostSuppressedFrame, restoreWebSocketDeliveryState };
508
+ //#region src/websocket/transcript.ts
509
+ const PositiveInt$1 = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
510
+ const NonNegativeInt$1 = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
511
+ /**
512
+ * Transcript protocol major. A change of meaning that an older client would misread bumps it;
513
+ * a client that sees another major performs one bounded reload.
514
+ */
515
+ const EDA_TRANSCRIPT_PROTOCOL_MAJOR = 1;
516
+ /** Additive wire revision within a major; older clients drop fields they do not know. */
517
+ const EDA_TRANSCRIPT_WIRE_VERSION = 1;
518
+ /**
519
+ * The small, stable envelope a client decodes before any version-specific schema, from the
520
+ * socket hello and from the host's SSR data. Its shape never changes; everything else may.
521
+ */
522
+ const EDATranscriptNegotiation = Schema.Struct({
523
+ protocolMajor: PositiveInt$1,
524
+ wireVersion: PositiveInt$1,
525
+ /** Optional features this server speaks; clients ignore names they do not know. */
526
+ capabilities: Schema.Array(Schema.String)
527
+ });
528
+ /** What this EDA release speaks. Hosts embed it in SSR data next to the transcript window. */
529
+ const edaTranscriptNegotiation = {
530
+ protocolMajor: 1,
531
+ wireVersion: 1,
532
+ capabilities: [
533
+ "window",
534
+ "page",
535
+ "retain",
536
+ "chunked-updates",
537
+ "active-content"
538
+ ]
539
+ };
540
+ /** Any value carrying the envelope under `negotiation`: a hello frame or SSR data. */
541
+ const NegotiationCarrier = Schema.Struct({ negotiation: EDATranscriptNegotiation });
542
+ const decodeNegotiationCarrier = Schema.decodeUnknownOption(NegotiationCarrier);
543
+ /**
544
+ * Decode only the negotiation envelope from an untrusted hello frame or SSR payload and compare
545
+ * it with this client's major. Run before decoding anything version-specific.
546
+ */
547
+ const negotiateEDATranscript = (carrier, localMajor = 1) => {
548
+ const decoded = decodeNegotiationCarrier(carrier);
549
+ if (decoded._tag === "None") return { _tag: "Undecodable" };
550
+ const remote = decoded.value.negotiation;
551
+ return remote.protocolMajor === localMajor ? {
552
+ _tag: "Compatible",
553
+ remote
554
+ } : {
555
+ _tag: "MajorMismatch",
556
+ remote
557
+ };
558
+ };
559
+ /** WebSocket close code: the server lost volatile transfer state; reconnect and resubscribe. */
560
+ const EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE = 4009;
561
+ /** First frame on a transcript socket: the event-socket hello plus the negotiation envelope. */
562
+ const EDATranscriptHelloFrame = Schema.Struct({
563
+ ...EDAWebSocketWireHelloFrame.fields,
564
+ negotiation: EDATranscriptNegotiation
565
+ });
566
+ /** A transcript update that fits one frame. */
567
+ const EDATranscriptUpdateFrame = Schema.Struct({
568
+ _tag: Schema.Literal("transcript"),
569
+ frameId: PositiveInt$1,
570
+ update: TranscriptUpdate
571
+ });
572
+ /**
573
+ * One slice of an update too large for a frame. `data` slices concatenated in `index` order are
574
+ * the JSON of one `TranscriptUpdate`; the client applies it only after slice `count - 1` (the
575
+ * completion marker) and discards a transfer that is interrupted.
576
+ */
577
+ const EDATranscriptChunkFrame = Schema.Struct({
578
+ _tag: Schema.Literal("transcript-chunk"),
579
+ frameId: PositiveInt$1,
580
+ updateSeq: PositiveInt$1,
581
+ index: NonNegativeInt$1,
582
+ count: PositiveInt$1,
583
+ data: Schema.String
584
+ }).check(Schema.makeFilter((chunk) => chunk.index < chunk.count || "chunk index out of range"));
585
+ /** Every server frame a transcript socket may carry. */
586
+ const EDATranscriptServerFrame = Schema.Union([
587
+ EDATranscriptHelloFrame,
588
+ EDATranscriptUpdateFrame,
589
+ EDATranscriptChunkFrame,
590
+ EDAWebSocketWirePongFrame,
591
+ EDAWebSocketWireLaggedFrame,
592
+ EDAWebSocketWireErrorFrame
593
+ ]);
594
+ /**
595
+ * Start or restart the subscription. After SSR, `range` is what the page rendered, `tail` its
596
+ * `!hasNewer`, and `since` its `throughSeq`; a reconnecting client sends what it last applied.
597
+ * Without `range` the server replies with the latest `count` records.
598
+ */
599
+ const EDATranscriptSubscribeFrame = Schema.Struct({
600
+ _tag: Schema.Literal("subscribe"),
601
+ requestId: Schema.optionalKey(TranscriptRequestId),
602
+ range: Schema.optionalKey(TranscriptCoverage),
603
+ tail: Schema.optionalKey(Schema.Boolean),
604
+ since: Schema.optionalKey(SequenceNumber),
605
+ count: Schema.optionalKey(PositiveInt$1)
606
+ });
607
+ /** Extend the coverage from its edge: `cursor` is the coverage's `from` (before) or `to` (after). */
608
+ const EDATranscriptPageFrame = Schema.Struct({
609
+ _tag: Schema.Literal("page"),
610
+ requestId: Schema.optionalKey(TranscriptRequestId),
611
+ direction: Schema.Literals(["before", "after"]),
612
+ cursor: TranscriptCursor,
613
+ count: PositiveInt$1
614
+ });
615
+ /** Narrow the coverage to a span inside it, so the server stops sending changes outside it. */
616
+ const EDATranscriptRetainFrame = Schema.Struct({
617
+ _tag: Schema.Literal("retain"),
618
+ requestId: Schema.optionalKey(TranscriptRequestId),
619
+ from: TranscriptCursor,
620
+ to: TranscriptCursor
621
+ });
622
+ /** A client request; each is answered by exactly one update, in arrival order. */
623
+ const EDATranscriptRequestFrame = Schema.Union([
624
+ EDATranscriptSubscribeFrame,
625
+ EDATranscriptPageFrame,
626
+ EDATranscriptRetainFrame
627
+ ]);
628
+ /** Every client frame a transcript socket accepts. */
629
+ const EDATranscriptClientFrame = Schema.Union([
630
+ EDAWebSocketWireAckFrame,
631
+ EDAWebSocketWirePingFrame,
632
+ EDATranscriptSubscribeFrame,
633
+ EDATranscriptPageFrame,
634
+ EDATranscriptRetainFrame
635
+ ]);
636
+ const encodeUpdate = Schema.encodeSync(TranscriptUpdate);
637
+ const encodeServerFrame = Schema.encodeSync(EDATranscriptServerFrame);
638
+ /** Serialize one update once; frames embed this text, chunks slice it. */
639
+ const encodeEDATranscriptUpdate = (update) => JSON.stringify(encodeUpdate(update));
640
+ /** Serialize a non-update server frame. */
641
+ const encodeEDATranscriptServerFrame = (frame) => JSON.stringify(encodeServerFrame(frame));
642
+ /** The single-frame form of an encoded update. */
643
+ const edaTranscriptUpdateFrameText = (frameId, encodedUpdate) => `{"_tag":"transcript","frameId":${frameId},"update":${encodedUpdate}}`;
644
+ /** One chunk frame of an encoded update. */
645
+ const edaTranscriptChunkFrameText = (input) => `{"_tag":"transcript-chunk","frameId":${input.frameId},"updateSeq":${input.updateSeq},"index":${input.index},"count":${input.count},"data":${JSON.stringify(input.data)}}`;
646
+ const textEncoder = new TextEncoder();
647
+ /** UTF-8 byte length of a string. */
648
+ const utf8ByteLength = (text) => textEncoder.encode(text).byteLength;
649
+ /** Bytes a chunk frame spends besides its data, with generous room for large numbers. */
650
+ const chunkFrameOverheadBytes = 160;
651
+ /** Control characters JSON writes as a two-byte escape (`\b`, `\t`, `\n`, `\f`, `\r`). */
652
+ const shortEscapes = /* @__PURE__ */ new Set([
653
+ 8,
654
+ 9,
655
+ 10,
656
+ 12,
657
+ 13
658
+ ]);
659
+ /** UTF-8 bytes one UTF-16 code unit costs inside a JSON string literal. */
660
+ const jsonStringUnitBytes = (code) => {
661
+ if (code === 34 || code === 92) return 2;
662
+ if (code < 32) return shortEscapes.has(code) ? 2 : 6;
663
+ if (code < 128) return 1;
664
+ if (code < 2048) return 2;
665
+ if (code >= 55296 && code <= 57343) return 6;
666
+ return 3;
667
+ };
668
+ /**
669
+ * Split an encoded update into chunk data that each fit a frame of `maxFrameBytes`, never
670
+ * splitting a surrogate pair.
671
+ */
672
+ const splitEDATranscriptUpdate = (encodedUpdate, maxFrameBytes) => {
673
+ const budget = Math.max(16, maxFrameBytes - chunkFrameOverheadBytes);
674
+ const chunks = [];
675
+ let start = 0;
676
+ let bytes = 0;
677
+ for (let index = 0; index < encodedUpdate.length; index += 1) {
678
+ const code = encodedUpdate.charCodeAt(index);
679
+ const pair = code >= 55296 && code <= 56319 && index + 1 < encodedUpdate.length ? encodedUpdate.charCodeAt(index + 1) : void 0;
680
+ const isPair = pair !== void 0 && pair >= 56320 && pair <= 57343;
681
+ const cost = isPair ? 4 : jsonStringUnitBytes(code);
682
+ if (bytes + cost > budget && index > start) {
683
+ chunks.push(encodedUpdate.slice(start, index));
684
+ start = index;
685
+ bytes = 0;
686
+ }
687
+ bytes += cost;
688
+ if (isPair) index += 1;
689
+ }
690
+ if (start < encodedUpdate.length || chunks.length === 0) chunks.push(encodedUpdate.slice(start));
691
+ return chunks;
692
+ };
693
+ //#endregion
694
+ //#region src/websocket/transcript-client.ts
695
+ /** A client that has rendered nothing yet. */
696
+ const emptyEDATranscriptClientState = {
697
+ window: void 0,
698
+ lastFrameId: 0,
699
+ appliedUpdateSeq: 0,
700
+ assembling: void 0
701
+ };
702
+ /** Seed a client from the window its page was server-rendered with. */
703
+ const edaTranscriptClientFromWindow = (window) => ({
704
+ ...emptyEDATranscriptClientState,
705
+ window: {
706
+ incarnation: window.incarnation,
707
+ version: window.version,
708
+ throughSeq: window.throughSeq,
709
+ coverage: transcriptCoverageOf(window),
710
+ hasOlder: window.hasOlder,
711
+ hasNewer: window.hasNewer,
712
+ readiness: window.readiness,
713
+ records: window.records,
714
+ dependencies: window.dependencies,
715
+ activeContent: window.activeContent ?? []
716
+ }
717
+ });
718
+ /**
719
+ * Prepare for a new socket: per-socket counters restart and any partial transfer is discarded.
720
+ * The applied window is kept; the next `subscribe` asks for changes since it.
721
+ */
722
+ const edaTranscriptClientReconnected = (state) => ({
723
+ ...emptyEDATranscriptClientState,
724
+ window: state.window
725
+ });
726
+ const decodeUpdateFrame = Schema.decodeUnknownExit(EDATranscriptUpdateFrame);
727
+ const decodeChunkFrame = Schema.decodeUnknownExit(EDATranscriptChunkFrame);
728
+ const decodeUpdate = Schema.decodeUnknownExit(TranscriptUpdate);
729
+ const peek = (value) => {
730
+ if (typeof value !== "object" || value === null) return {};
731
+ const tag = "_tag" in value && typeof value._tag === "string" ? value._tag : void 0;
732
+ const frameId = "frameId" in value && typeof value.frameId === "number" && Number.isInteger(value.frameId) ? value.frameId : void 0;
733
+ return {
734
+ ...tag === void 0 ? {} : { tag },
735
+ ...frameId === void 0 ? {} : { frameId }
736
+ };
737
+ };
738
+ /** Apply one server text message. Frames must arrive in frame-id order without gaps. */
739
+ const applyEDATranscriptServerMessage = (state, message) => {
740
+ let json;
741
+ try {
742
+ json = JSON.parse(message);
743
+ } catch {
744
+ return resubscribe(state, "malformed server message");
745
+ }
746
+ const { tag, frameId } = peek(json);
747
+ switch (tag) {
748
+ case "hello": return {
749
+ state,
750
+ outcome: {
751
+ _tag: "Hello",
752
+ negotiation: negotiateEDATranscript(json)
753
+ }
754
+ };
755
+ case "pong": return {
756
+ state,
757
+ outcome: { _tag: "Ignored" }
758
+ };
759
+ case "lagged":
760
+ case "error": return resubscribe(state, `server sent ${tag}`);
761
+ }
762
+ if (frameId === void 0) return {
763
+ state,
764
+ outcome: { _tag: "Ignored" }
765
+ };
766
+ if (frameId !== state.lastFrameId + 1) return resubscribe(state, "frame gap");
767
+ const received = {
768
+ ...state,
769
+ lastFrameId: frameId
770
+ };
771
+ if (tag === "transcript") {
772
+ const decoded = decodeUpdateFrame(json);
773
+ if (Exit.isFailure(decoded)) return resubscribe(state, "undecodable update");
774
+ if (received.assembling !== void 0) return resubscribe(state, "update interrupted a transfer");
775
+ return applyUpdate(received, decoded.value.update);
776
+ }
777
+ if (tag === "transcript-chunk") {
778
+ const decoded = decodeChunkFrame(json);
779
+ if (Exit.isFailure(decoded)) return resubscribe(state, "undecodable chunk");
780
+ const chunk = decoded.value;
781
+ const assembling = received.assembling ?? {
782
+ updateSeq: chunk.updateSeq,
783
+ count: chunk.count,
784
+ data: []
785
+ };
786
+ if (assembling.updateSeq !== chunk.updateSeq || assembling.count !== chunk.count || assembling.data.length !== chunk.index) return resubscribe(state, "interrupted chunked transfer");
787
+ const data = [...assembling.data, chunk.data];
788
+ if (data.length < chunk.count) {
789
+ const next = {
790
+ ...received,
791
+ assembling: {
792
+ ...assembling,
793
+ data
794
+ }
795
+ };
796
+ return {
797
+ state: next,
798
+ outcome: { _tag: "Partial" },
799
+ ack: ackOf(next)
800
+ };
801
+ }
802
+ let updateJson;
803
+ try {
804
+ updateJson = JSON.parse(data.join(""));
805
+ } catch {
806
+ return resubscribe(state, "malformed chunked update");
807
+ }
808
+ const update = decodeUpdate(updateJson);
809
+ if (Exit.isFailure(update) || update.value.updateSeq !== chunk.updateSeq) return resubscribe(state, "undecodable chunked update");
810
+ return applyUpdate({
811
+ ...received,
812
+ assembling: void 0
813
+ }, update.value);
814
+ }
815
+ return {
816
+ state: received,
817
+ outcome: { _tag: "Ignored" },
818
+ ack: ackOf(received)
819
+ };
820
+ };
821
+ const resubscribe = (state, reason) => ({
822
+ state: {
823
+ ...state,
824
+ assembling: void 0
825
+ },
826
+ outcome: {
827
+ _tag: "Resubscribe",
828
+ reason
829
+ }
830
+ });
831
+ const ackOf = (state) => ({
832
+ _tag: "ack",
833
+ frameId: state.lastFrameId,
834
+ durableThroughSeq: state.appliedUpdateSeq === 0 ? 0 : state.window?.throughSeq ?? 0,
835
+ appliedUpdateSeq: state.appliedUpdateSeq
836
+ });
837
+ const orderKeyOf = (record) => "position" in record && record.position !== void 0 ? {
838
+ ...record.position,
839
+ recordId: record.id
840
+ } : void 0;
841
+ const covered = (coverage, record) => {
842
+ const key = orderKeyOf(record);
843
+ return coverage !== void 0 && key !== void 0 && TranscriptOrder(coverage.from, key) <= 0 && TranscriptOrder(key, coverage.to) <= 0;
844
+ };
845
+ const applyUpdate = (state, update) => {
846
+ if (update.updateSeq !== state.appliedUpdateSeq + 1) return resubscribe(state, "update gap");
847
+ const previous = state.window;
848
+ if (update.mode === "patch" && (previous === void 0 || previous.incarnation !== update.incarnation || previous.version !== update.version)) return resubscribe(state, "patch without its base");
849
+ const base = update.mode === "patch" ? previous : void 0;
850
+ const topLevel = new Map((base?.records ?? []).map((record) => [record.id, record]));
851
+ for (const record of update.records) topLevel.set(record.id, record);
852
+ const records = [...topLevel.values()].filter((record) => covered(update.coverage, record)).sort((left, right) => {
853
+ const leftKey = orderKeyOf(left);
854
+ const rightKey = orderKeyOf(right);
855
+ return leftKey === void 0 || rightKey === void 0 ? 0 : TranscriptOrder(leftKey, rightKey);
856
+ });
857
+ const dependencyMap = new Map((base?.dependencies ?? []).map((record) => [record.id, record]));
858
+ for (const record of update.dependencies) dependencyMap.set(record.id, record);
859
+ const dependencies = update.dependencyIds.flatMap((id) => {
860
+ const record = dependencyMap.get(id);
861
+ return record === void 0 ? [] : [record];
862
+ });
863
+ if (dependencies.length !== update.dependencyIds.length) return resubscribe(state, "patch referenced a dependency the client does not hold");
864
+ const window = {
865
+ incarnation: update.incarnation,
866
+ version: update.version,
867
+ throughSeq: update.throughSeq,
868
+ coverage: update.coverage,
869
+ hasOlder: update.hasOlder,
870
+ hasNewer: update.hasNewer,
871
+ readiness: update.readiness,
872
+ records,
873
+ dependencies,
874
+ activeContent: update.readiness._tag !== "Ready" ? [] : update.activeContent ?? base?.activeContent ?? []
875
+ };
876
+ const next = {
877
+ ...state,
878
+ window,
879
+ appliedUpdateSeq: update.updateSeq,
880
+ assembling: void 0
881
+ };
882
+ return {
883
+ state: next,
884
+ outcome: {
885
+ _tag: "Applied",
886
+ updateSeq: update.updateSeq,
887
+ ...update.requestId === void 0 ? {} : { requestId: update.requestId }
888
+ },
889
+ ack: ackOf(next)
890
+ };
891
+ };
892
+ /**
893
+ * The request a client sends first on every socket: changes since the window it holds over the
894
+ * span it holds, or the latest `count` records when it holds none.
895
+ */
896
+ const edaTranscriptSubscribeRequest = (state, options) => {
897
+ const window = state.window;
898
+ const extra = {
899
+ ...options?.count === void 0 ? {} : { count: options.count },
900
+ ...options?.requestId === void 0 ? {} : { requestId: options.requestId }
901
+ };
902
+ return window?.coverage === void 0 ? {
903
+ _tag: "subscribe",
904
+ ...extra
905
+ } : {
906
+ _tag: "subscribe",
907
+ range: window.coverage,
908
+ tail: !window.hasNewer,
909
+ since: window.throughSeq,
910
+ ...extra
911
+ };
912
+ };
913
+ /** Page from the held coverage's edge, or `undefined` when there is nothing to page from. */
914
+ const edaTranscriptPageRequest = (state, direction, count, requestId) => {
915
+ const coverage = state.window?.coverage;
916
+ if (coverage === void 0) return void 0;
917
+ return {
918
+ _tag: "page",
919
+ direction,
920
+ cursor: direction === "before" ? coverage.from : coverage.to,
921
+ count,
922
+ ...requestId === void 0 ? {} : { requestId }
923
+ };
924
+ };
925
+ /**
926
+ * Keep only the top-level records from `fromIndex` to `toIndex` (inclusive) of the held window;
927
+ * the server confirms with an update whose coverage is the narrowed span.
928
+ */
929
+ const edaTranscriptRetainRequest = (state, fromIndex, toIndex, requestId) => {
930
+ const window = state.window;
931
+ const from = window?.records[fromIndex];
932
+ const to = window?.records[toIndex];
933
+ const fromKey = from === void 0 ? void 0 : orderKeyOf(from);
934
+ const toKey = to === void 0 ? void 0 : orderKeyOf(to);
935
+ if (window === void 0 || fromKey === void 0 || toKey === void 0) return void 0;
936
+ const scope = {
937
+ incarnation: window.incarnation,
938
+ version: window.version
939
+ };
940
+ return {
941
+ _tag: "retain",
942
+ from: {
943
+ ...scope,
944
+ ...fromKey,
945
+ anchorSeq: SequenceNumber.make(fromKey.anchorSeq)
946
+ },
947
+ to: {
948
+ ...scope,
949
+ ...toKey,
950
+ anchorSeq: SequenceNumber.make(toKey.anchorSeq)
951
+ },
952
+ ...requestId === void 0 ? {} : { requestId }
953
+ };
954
+ };
955
+ //#endregion
956
+ //#region src/websocket/transcript-delivery.ts
957
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
958
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
959
+ /** A chunked update whose frames are not all sent yet; its chunk data is volatile. */
960
+ const EDATranscriptTransfer = Schema.Struct({
961
+ updateSeq: PositiveInt,
962
+ throughSeq: SequenceNumber,
963
+ count: PositiveInt,
964
+ nextIndex: NonNegativeInt
965
+ });
966
+ /**
967
+ * Everything a transcript socket needs to resume after hibernation, persisted in its attachment
968
+ * before every send and after every applied ACK.
969
+ *
970
+ * Transport receipts (`inFlight`, `lastAckedFrameId`) bound frames in flight exactly as on an
971
+ * event socket. The applied cut (`appliedUpdateSeq`, `appliedThroughSeq`) is the last update the
972
+ * client applied completely. `subscription` is the base the next update is planned against, and
973
+ * `requests` are client requests not yet answered. A persisted `transfer` means chunk data was
974
+ * staged in memory; a socket restored with one cannot finish it and is closed.
975
+ */
976
+ const EDATranscriptDeliveryCheckpoint = Schema.Struct({
977
+ lastAckedFrameId: NonNegativeInt,
978
+ nextFrameId: PositiveInt,
979
+ inFlight: Schema.Array(Schema.Struct({
980
+ frameId: PositiveInt,
981
+ sentAtMs: Schema.Number
982
+ })),
983
+ nextUpdateSeq: PositiveInt,
984
+ completedUpdateSeq: NonNegativeInt,
985
+ completedThroughSeq: SequenceNumber,
986
+ appliedUpdateSeq: NonNegativeInt,
987
+ appliedThroughSeq: SequenceNumber,
988
+ transfer: Schema.optionalKey(EDATranscriptTransfer),
989
+ subscription: Schema.optionalKey(TranscriptSubscriptionBase),
990
+ requests: Schema.Array(EDATranscriptRequestFrame)
991
+ });
992
+ const defaultEDATranscriptDeliveryLimits = {
993
+ maxStagedBytes: 8388608,
994
+ maxPendingRequests: 4
995
+ };
996
+ /** Delivery state for a newly accepted transcript socket. */
997
+ const makeTranscriptDeliveryState = (policy) => ({
998
+ policy,
999
+ lastAckedFrameId: 0,
1000
+ nextFrameId: 1,
1001
+ inFlight: [],
1002
+ nextUpdateSeq: 1,
1003
+ completedUpdateSeq: 0,
1004
+ completedThroughSeq: SequenceNumber.make(0),
1005
+ appliedUpdateSeq: 0,
1006
+ appliedThroughSeq: SequenceNumber.make(0),
1007
+ requests: [],
1008
+ staged: []
1009
+ });
1010
+ /**
1011
+ * Restore a hibernated transcript socket. A socket that was mid-transfer lost its staged chunks
1012
+ * with the isolate and cannot resume: the caller closes it and the client resubscribes.
1013
+ */
1014
+ const restoreTranscriptDeliveryState = (policy, checkpoint) => checkpoint.transfer === void 0 ? {
1015
+ _tag: "Restored",
1016
+ state: {
1017
+ ...checkpoint,
1018
+ policy,
1019
+ staged: []
1020
+ }
1021
+ } : { _tag: "TransferLost" };
1022
+ /** The attachment-safe part of the state. */
1023
+ const checkpointTranscriptDelivery = (state) => ({
1024
+ lastAckedFrameId: state.lastAckedFrameId,
1025
+ nextFrameId: state.nextFrameId,
1026
+ inFlight: state.inFlight,
1027
+ nextUpdateSeq: state.nextUpdateSeq,
1028
+ completedUpdateSeq: state.completedUpdateSeq,
1029
+ completedThroughSeq: state.completedThroughSeq,
1030
+ appliedUpdateSeq: state.appliedUpdateSeq,
1031
+ appliedThroughSeq: state.appliedThroughSeq,
1032
+ ...state.transfer === void 0 ? {} : { transfer: state.transfer },
1033
+ ...state.subscription === void 0 ? {} : { subscription: state.subscription },
1034
+ requests: state.requests
1035
+ });
1036
+ /** Frames that may be sent before the client's next receipt. */
1037
+ const transcriptDeliveryCapacity = (state) => state.policy.maxInFlightFrames - state.inFlight.length;
1038
+ /** Lazily enforced ACK deadline: no resident timer, checked on each transition. */
1039
+ const transcriptAckTimedOut = (state, nowMs) => state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs);
1040
+ /**
1041
+ * Start sending one planned update, captured from its own snapshot.
1042
+ *
1043
+ * `subscription` becomes the base for the next update immediately: nothing else is sent until
1044
+ * this update's last frame is, so the client can only apply later updates on top of it. An
1045
+ * update within the frame limit is one frame; a larger one is chunked and as many chunks as
1046
+ * flow control allows are sent now, the rest staged.
1047
+ */
1048
+ const startTranscriptUpdate = (state, input, limits, nowMs) => {
1049
+ if (state.transfer !== void 0) throw new Error("A transcript update cannot start while another is being transferred");
1050
+ if (input.update.updateSeq !== state.nextUpdateSeq) throw new Error("A transcript update must carry the socket's next update seq");
1051
+ const updateSeq = input.update.updateSeq;
1052
+ const advanced = {
1053
+ ...state,
1054
+ nextUpdateSeq: updateSeq + 1,
1055
+ subscription: input.subscription
1056
+ };
1057
+ const single = edaTranscriptUpdateFrameText(state.nextFrameId, input.encodedUpdate);
1058
+ if (utf8ByteLength(single) <= state.policy.maxFrameBytes) return {
1059
+ _tag: "Sending",
1060
+ ...sendFrames({
1061
+ ...advanced,
1062
+ completedUpdateSeq: updateSeq,
1063
+ completedThroughSeq: input.update.throughSeq
1064
+ }, [single], nowMs)
1065
+ };
1066
+ const bytes = utf8ByteLength(input.encodedUpdate);
1067
+ if (bytes > limits.maxStagedBytes) return {
1068
+ _tag: "TooLarge",
1069
+ bytes
1070
+ };
1071
+ const chunks = splitEDATranscriptUpdate(input.encodedUpdate, state.policy.maxFrameBytes);
1072
+ return {
1073
+ _tag: "Sending",
1074
+ ...pumpTranscriptTransfer({
1075
+ ...advanced,
1076
+ transfer: {
1077
+ updateSeq,
1078
+ throughSeq: input.update.throughSeq,
1079
+ count: chunks.length,
1080
+ nextIndex: 0
1081
+ },
1082
+ staged: chunks
1083
+ }, nowMs)
1084
+ };
1085
+ };
1086
+ /** Send staged chunks of the transfer in progress while flow control allows. */
1087
+ const pumpTranscriptTransfer = (state, nowMs) => {
1088
+ let next = state;
1089
+ const frames = [];
1090
+ while (next.transfer !== void 0 && transcriptDeliveryCapacity(next) > 0) {
1091
+ const transfer = next.transfer;
1092
+ const [data, ...rest] = next.staged;
1093
+ if (data === void 0) break;
1094
+ const text = edaTranscriptChunkFrameText({
1095
+ frameId: next.nextFrameId,
1096
+ updateSeq: transfer.updateSeq,
1097
+ index: transfer.nextIndex,
1098
+ count: transfer.count,
1099
+ data
1100
+ });
1101
+ const nextIndex = transfer.nextIndex + 1;
1102
+ const done = nextIndex === transfer.count;
1103
+ const { transfer: _sent, ...withoutTransfer } = next;
1104
+ const sent = sendFrames(done ? {
1105
+ ...withoutTransfer,
1106
+ staged: [],
1107
+ completedUpdateSeq: transfer.updateSeq,
1108
+ completedThroughSeq: transfer.throughSeq
1109
+ } : {
1110
+ ...next,
1111
+ staged: rest,
1112
+ transfer: {
1113
+ ...transfer,
1114
+ nextIndex
1115
+ }
1116
+ }, [text], nowMs);
1117
+ next = sent.state;
1118
+ frames.push(...sent.frames);
1119
+ }
1120
+ return {
1121
+ state: next,
1122
+ frames
1123
+ };
1124
+ };
1125
+ const sendFrames = (state, texts, nowMs) => {
1126
+ const inFlight = texts.map((_, index) => ({
1127
+ frameId: state.nextFrameId + index,
1128
+ sentAtMs: nowMs
1129
+ }));
1130
+ return {
1131
+ state: {
1132
+ ...state,
1133
+ inFlight: [...state.inFlight, ...inFlight],
1134
+ nextFrameId: state.nextFrameId + texts.length
1135
+ },
1136
+ frames: texts
1137
+ };
1138
+ };
1139
+ /**
1140
+ * Apply one ACK. The receipt frees flow-control capacity cumulatively; the applied cut may only
1141
+ * name an update whose frames were all sent, and never moves backwards.
1142
+ */
1143
+ const onTranscriptAck = (state, ack) => {
1144
+ const appliedUpdateSeq = ack.appliedUpdateSeq ?? state.appliedUpdateSeq;
1145
+ const advancesApplied = appliedUpdateSeq > state.appliedUpdateSeq;
1146
+ if (ack.frameId <= state.lastAckedFrameId) return advancesApplied ? {
1147
+ _tag: "ProtocolError",
1148
+ message: "Duplicate ACK attempted to advance the applied cut"
1149
+ } : { _tag: "Ignored" };
1150
+ if (ack.frameId >= state.nextFrameId) return {
1151
+ _tag: "ProtocolError",
1152
+ message: "ACK referenced an unsent frame"
1153
+ };
1154
+ if (appliedUpdateSeq < state.appliedUpdateSeq) return {
1155
+ _tag: "ProtocolError",
1156
+ message: "ACK applied cut moved backwards"
1157
+ };
1158
+ if (appliedUpdateSeq > state.completedUpdateSeq) return {
1159
+ _tag: "ProtocolError",
1160
+ message: "ACK applied an incomplete update"
1161
+ };
1162
+ if (advancesApplied && appliedUpdateSeq === state.completedUpdateSeq && ack.durableThroughSeq !== state.completedThroughSeq) return {
1163
+ _tag: "ProtocolError",
1164
+ message: "ACK applied cut names another update's seq"
1165
+ };
1166
+ return {
1167
+ _tag: "Applied",
1168
+ state: {
1169
+ ...state,
1170
+ lastAckedFrameId: ack.frameId,
1171
+ inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),
1172
+ appliedUpdateSeq,
1173
+ appliedThroughSeq: advancesApplied ? SequenceNumber.make(ack.durableThroughSeq) : state.appliedThroughSeq
1174
+ }
1175
+ };
1176
+ };
1177
+ /** Queue one client request, or report that the client exceeded its request bound. */
1178
+ const enqueueTranscriptRequest = (state, request, limits) => state.requests.length >= limits.maxPendingRequests ? void 0 : {
1179
+ ...state,
1180
+ requests: [...state.requests, request]
1181
+ };
1182
+ //#endregion
1183
+ export { EDAFrameworkWebSocketEvent, EDATranscriptChunkFrame, EDATranscriptClientFrame, EDATranscriptDeliveryCheckpoint, EDATranscriptHelloFrame, EDATranscriptNegotiation, EDATranscriptPageFrame, EDATranscriptRequestFrame, EDATranscriptRetainFrame, EDATranscriptServerFrame, EDATranscriptSubscribeFrame, EDATranscriptTransfer, EDATranscriptUpdateFrame, EDAWebSocketAckFrame, EDAWebSocketClientFrame, EDAWebSocketDeliveryCheckpoint, EDAWebSocketErrorFrame, EDAWebSocketEventsFrame, EDAWebSocketFlowControl, EDAWebSocketHeartbeatFrame, EDAWebSocketHelloFrame, EDAWebSocketInFlightFrame, EDAWebSocketLaggedFrame, EDAWebSocketPingFrame, EDAWebSocketPongFrame, EDAWebSocketServerFrame, EDAWebSocketSuppressedRange, EDAWebSocketWireAckFrame, EDAWebSocketWireClientFrame, EDAWebSocketWireErrorFrame, EDAWebSocketWireFlowControl, EDAWebSocketWireHeartbeatFrame, EDAWebSocketWireHelloFrame, EDAWebSocketWireLaggedFrame, EDAWebSocketWirePingFrame, EDAWebSocketWirePongFrame, EDA_TRANSCRIPT_PROTOCOL_MAJOR, EDA_TRANSCRIPT_WIRE_VERSION, EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE, EDA_WEB_SOCKET_PROTOCOL_VERSION, EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION, EDA_WS_CLOSE_GOING_AWAY, EDA_WS_CLOSE_LAGGED, EDA_WS_CLOSE_PROTOCOL_ERROR, EDA_WS_CLOSE_SEND_FAILED, EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE, EDA_WS_CLOSE_UNSUPPORTED_DATA, FrameId, SubscriberId, SubscriberLagReason, applyEDATranscriptServerMessage, checkpointTranscriptDelivery, checkpointWebSocketDeliveryState, decodeEDAWebSocketClientMessage, defaultEDATranscriptDeliveryLimits, defaultEDAWebSocketFlowControl, deliveryHelloFrame, edaFrameworkWebSocketWireProtocol, edaTranscriptChunkFrameText, edaTranscriptClientFromWindow, edaTranscriptClientReconnected, edaTranscriptNegotiation, edaTranscriptPageRequest, edaTranscriptRetainRequest, edaTranscriptSubscribeRequest, edaTranscriptUpdateFrameText, emptyEDATranscriptClientState, encodeEDATranscriptServerFrame, encodeEDATranscriptUpdate, encodeEDAWebSocketServerFrame, enqueueTranscriptRequest, laggedCloseReason, makeEDAWebSocketWireProtocol, makeTranscriptDeliveryState, makeWebSocketDeliveryState, negotiateEDATranscript, onClientAck, onDurableEvents, onEphemeralEvent, onHostSuppressedFrame, onTranscriptAck, pumpTranscriptTransfer, restoreTranscriptDeliveryState, restoreWebSocketDeliveryState, splitEDATranscriptUpdate, startTranscriptUpdate, transcriptAckTimedOut, transcriptDeliveryCapacity, utf8ByteLength };
498
1184
 
499
1185
  //# sourceMappingURL=websocket.js.map