effect-durable-agent 0.1.0-alpha.1 → 0.1.0-alpha.3

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 (43) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/README.md +110 -108
  3. package/SECURITY.md +3 -4
  4. package/dist/{compaction-YayFKo_1.d.ts → compaction-1LSZR944.d.ts} +2 -2
  5. package/dist/{durable-object-runtime-pWv0ohlz.d.ts → durable-object-runtime-CiMKxGs6.d.ts} +7 -7
  6. package/dist/{durable-object-runtime-B7jwBY2R.js → durable-object-runtime-wKiqaAt2.js} +3 -3
  7. package/dist/durable-object-runtime-wKiqaAt2.js.map +1 -0
  8. package/dist/host/durable-object-runtime.d.ts +1 -1
  9. package/dist/host/durable-object-runtime.js +1 -1
  10. package/dist/host/durable-object.d.ts +3 -3
  11. package/dist/host/durable-object.js +1 -1
  12. package/dist/host/websocket-wire.d.ts +2 -2
  13. package/dist/host/websocket-wire.js +37 -20
  14. package/dist/host/websocket-wire.js.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/{prompt-projector-9_02lk5-.d.ts → prompt-projector-DimXJPOJ.d.ts} +12 -13
  17. package/dist/{runtime-C56FQxiL.d.ts → runtime-DcdPOEuE.d.ts} +2 -2
  18. package/dist/services/compaction.d.ts +1 -1
  19. package/dist/services/prompt-projector.d.ts +2 -2
  20. package/dist/services/prompt-projector.js +20 -10
  21. package/dist/services/prompt-projector.js.map +1 -1
  22. package/dist/services/runtime.d.ts +1 -1
  23. package/dist/services/runtime.js +1 -1
  24. package/dist/services/session-query.d.ts +1 -1
  25. package/dist/services/session-query.js +1 -1
  26. package/dist/services/sink-registry.d.ts +1 -1
  27. package/dist/{session-query-DOc1KanA.js → session-query-Cbf-e0rG.js} +26 -70
  28. package/dist/session-query-Cbf-e0rG.js.map +1 -0
  29. package/dist/{session-query-DlRo5Ufc.d.ts → session-query-hxfujxUH.d.ts} +9 -9
  30. package/dist/{sink-registry-CIU0LD3m.d.ts → sink-registry-BziFpxoE.d.ts} +2 -2
  31. package/dist/testkit/layers.d.ts +5 -5
  32. package/dist/testkit/layers.js +1 -1
  33. package/dist/websocket-wire-D3tLrhe2.d.ts +2172 -0
  34. package/docs/assets/architecture.svg +170 -60
  35. package/docs/assets/event-sequence.svg +68 -78
  36. package/docs/assets/hero.svg +33 -0
  37. package/docs/releasing.md +78 -39
  38. package/docs/spec.md +4 -1
  39. package/docs/websocket-protocol.md +31 -5
  40. package/package.json +1 -1
  41. package/dist/durable-object-runtime-B7jwBY2R.js.map +0 -1
  42. package/dist/session-query-DOc1KanA.js.map +0 -1
  43. package/dist/websocket-wire-DvOu_6BJ.d.ts +0 -16773
package/docs/releasing.md CHANGED
@@ -1,57 +1,96 @@
1
1
  # Releasing Effect Durable Agent
2
2
 
3
- Releases publish the public `effect-durable-agent` package from the standalone
4
- `advait/effect-durable-agent` repository.
3
+ Releases publish [`effect-durable-agent`](https://www.npmjs.com/package/effect-durable-agent) from
4
+ the public [`advait/effect-durable-agent`](https://github.com/advait/effect-durable-agent)
5
+ repository.
5
6
 
6
- ## One-time release setup
7
+ ## Current public baseline
7
8
 
8
- Before the first public release:
9
+ `0.1.0-alpha.1` was published interactively as the package bootstrap and is marked by the annotated
10
+ Git tag `v0.1.0-alpha.1`. Both the `alpha` and `latest` npm dist-tags currently resolve to that
11
+ version.
9
12
 
10
- 1. Make `advait/effect-durable-agent` public.
11
- 2. Confirm that the `CI` workflow passes on the default branch.
12
- 3. Protect the default branch and release tags as appropriate.
13
- 4. Confirm that `goguardian/gia` consumes this repository as a submodule pinned to an audited
14
- commit.
13
+ The bootstrap is complete and must not be repeated. In particular, do not create a GitHub release
14
+ for `v0.1.0-alpha.1`: publishing that release would run the npm workflow against a version that
15
+ already exists. The Git tag alone does not trigger the workflow.
15
16
 
16
- The package metadata and publishing workflow target this standalone repository.
17
+ ## One-time trusted-publisher setup
17
18
 
18
- ## Bootstrap the npm package
19
-
20
- npm requires a package to exist before it can be connected to a trusted publisher. The first
21
- release is therefore a one-time interactive bootstrap:
22
-
23
- ```bash
24
- pnpm install --frozen-lockfile
25
- pnpm run release:check
26
- npm publish
27
- ```
28
-
29
- The package metadata makes the scoped package public and publishes this prerelease under the
30
- `alpha` tag. This command requires an authenticated npm account with publishing rights and its
31
- configured two-factor authentication.
32
-
33
- After `0.1.0-alpha.1` exists, configure its npm trusted publisher:
19
+ Before publishing the next version, configure the package's trusted publisher in the npm package
20
+ settings:
34
21
 
35
22
  - Provider: GitHub Actions
36
23
  - Organization or user: `advait`
37
24
  - Repository: `effect-durable-agent`
38
25
  - Workflow filename: `publish.yml`
39
26
  - Allowed action: `npm publish`
40
- - Environment: leave blank unless the workflow is updated to use one
27
+ - Environment: leave blank unless `.github/workflows/publish.yml` is updated to use one
28
+
29
+ The workflow uses a GitHub-hosted runner, grants `id-token: write`, and runs a recent Node/npm pair.
30
+ Do not add an npm publishing token to the repository. npm uses the workflow's short-lived OIDC
31
+ identity and automatically attaches provenance because both the repository and package are public.
32
+
33
+ After one automated release succeeds, configure npm publishing access to require two-factor
34
+ authentication and disallow tokens, then revoke any automation tokens that are no longer needed.
35
+ See npm's [trusted publishing guide](https://docs.npmjs.com/trusted-publishers/) for the current
36
+ registry requirements.
41
37
 
42
- The workflow runs on a GitHub-hosted runner with the OIDC permissions and Node/npm versions required
43
- by npm trusted publishing. No npm token should be added to the repository. Trusted publishing
44
- automatically adds provenance when both the package and repository are public.
38
+ ## Release channels
45
39
 
46
- Keep prereleases on an explicit dist-tag such as `alpha` or `beta`. Change `publishConfig.tag` to
47
- `latest` only when publishing a stable release.
40
+ While the API is in alpha, `publishConfig.tag` remains `alpha` and consumers should install
41
+ `effect-durable-agent@alpha`. It is acceptable for `latest` to point to an alpha release, but an
42
+ alpha-tagged publish advances only `alpha`; it does not automatically move `latest`.
48
43
 
49
- ## Subsequent releases
44
+ If an alpha has been verified and should also become the default for unqualified installs, an
45
+ authenticated maintainer can move `latest` explicitly:
50
46
 
51
- 1. Update `package.json` to the intended version and refresh `pnpm-lock.yaml`.
52
- 2. Add release notes and run `pnpm run release:check`.
53
- 3. Merge the version change.
54
- 4. Create a GitHub release whose tag is exactly `v<package version>`.
55
- 5. Wait for the `Publish to npm` workflow and verify the version and provenance on npm.
47
+ ```bash
48
+ npm dist-tag add effect-durable-agent@0.1.0-alpha.2 latest
49
+ ```
56
50
 
57
- The workflow rejects a release tag that does not exactly match `package.json`.
51
+ Trusted publishing authorizes `npm publish`, not `npm dist-tag`, so changing a dist-tag is an
52
+ interactive maintainer operation and may require two-factor authentication. Always name the exact
53
+ version being promoted.
54
+
55
+ For the first stable release, remove the prerelease suffix and change `publishConfig.tag` to
56
+ `latest` in the version PR. Leave `alpha` pointing to the final alpha unless there is a deliberate
57
+ reason to move or remove it.
58
+
59
+ ## Release checklist
60
+
61
+ 1. Choose a new, never-before-published version.
62
+ 2. Update `package.json` and refresh `pnpm-lock.yaml`.
63
+ 3. Add the release notes to `CHANGELOG.md`.
64
+ 4. Run the complete release validation:
65
+
66
+ ```bash
67
+ pnpm install --frozen-lockfile
68
+ pnpm run release:check
69
+ ```
70
+
71
+ 5. Merge the version PR and confirm `CI` passes on `master`.
72
+ 6. Create a GitHub release targeting the merged commit. Its tag must be exactly
73
+ `v<package version>`; for example, `v0.1.0-alpha.2`.
74
+ 7. Wait for the `Publish to npm` workflow to pass. The workflow independently reruns the full
75
+ release check and rejects a tag that does not match `package.json`.
76
+ 8. Verify the registry metadata and dist-tags:
77
+
78
+ ```bash
79
+ npm view effect-durable-agent@0.1.0-alpha.2 name version repository.url dist.integrity --json
80
+ npm dist-tag ls effect-durable-agent
81
+ ```
82
+
83
+ 9. Install from the public registry in a clean consumer and run its typecheck and bundle. Do not
84
+ validate only against the repository or a local tarball.
85
+ 10. If desired for the alpha channel, move `latest` only after the registry install succeeds.
86
+ 11. Update downstream consumers, including the `goguardian/gia` submodule pin, in a separate PR.
87
+
88
+ ## Failure handling
89
+
90
+ - npm package versions are immutable. Never try to reuse a version after any successful publish;
91
+ increment the version and release again.
92
+ - If the workflow fails before publishing, fix the cause on `master` and create a release for the
93
+ corrected, incremented version. Do not move an existing release tag to a different commit.
94
+ - If only a dist-tag is wrong, correct the tag instead of republishing the package.
95
+ - Avoid unpublishing except for a genuine security or legal incident. Coordinate through the
96
+ process in [`SECURITY.md`](../SECURITY.md).
package/docs/spec.md CHANGED
@@ -499,7 +499,10 @@ Current extension points:
499
499
  Apps bind their custom durable-event union to the live protocol once with
500
500
  `makeEDAWebSocketWireProtocol({ appEvents })`. The binding automatically includes
501
501
  all framework durable and ephemeral events, configures strict host encoding, and
502
- exports the same event/frame schemas for browser or other WebSocket consumers.
502
+ exports explicit `domain` and `wire` event/frame schema surfaces. Apps pass the
503
+ binding's `host` adapter to the EDA host and share its `wire` schemas with browser
504
+ or other WebSocket consumers. Its typed `encodeServerFrame` accepts only the
505
+ app-bound domain frame type.
503
506
  Framework-only hosts reject unregistered app events rather than widening their
504
507
  payloads to `unknown`.
505
508
 
@@ -116,21 +116,47 @@ export const counterWebSocketProtocol = makeEDAWebSocketWireProtocol({
116
116
  appEvents: CounterIncrementedEvent,
117
117
  });
118
118
 
119
- export const CounterWebSocketServerFrame = counterWebSocketProtocol.serverFrame;
119
+ export const CounterWebSocketServerFrame = counterWebSocketProtocol.wire.serverFrame;
120
120
  export type CounterWebSocketServerFrame = typeof CounterWebSocketServerFrame.Type;
121
121
  ```
122
122
 
123
- `makeEDAWebSocketWireProtocol` automatically unions the app events with all EDA durable and ephemeral events. The returned value serves both boundaries:
123
+ `makeEDAWebSocketWireProtocol` automatically unions the app events with all EDA durable and ephemeral events. The returned value makes the two schema directions explicit:
124
124
 
125
- - Pass it to the EDA host as `webSocketProtocol` so outbound frames are encoded and validated against the app's exact event union.
126
- - Share its `serverFrame`, `eventsFrame`, and `positionedEvent` schemas with browser or other WebSocket consumers for decoding and type inference.
125
+ - `domain.event`, `domain.positionedEvent`, `domain.eventsFrame`, and `domain.serverFrame`
126
+ describe decoded in-memory values. Schema transformations have already run on their `Type` side.
127
+ - `wire.event`, `wire.positionedEvent`, `wire.eventsFrame`, and `wire.serverFrame` describe
128
+ the UTF-8 JSON representation. Browser and other external consumers decode with these schemas
129
+ when they need validated wire values without hydrating domain transformations.
130
+ - `wire.clientFrame` validates client-to-server ACK messages.
131
+ - `encodeServerFrame` accepts only the exact app-bound domain server-frame type and serializes it to
132
+ one JSON text message.
133
+ - `host` is the adapter passed as `webSocketProtocol` to the EDA host. It validates and encodes the
134
+ host's broad event envelope against the registered app/framework union at runtime.
127
135
 
128
- The exposed schemas describe the encoded JSON representation. Domain-only brands and transformations therefore do not leak into ordinary wire consumers, while every field is still derived from and checked by the domain event schemas. Switching on `event.type` narrows `event.payload` to that event's exact schema.
136
+ For example, a transformed message content field may be a prompt-part array in
137
+ `domain.serverFrame.Type` and a string in `wire.serverFrame.Type`. TypeScript rejects passing the
138
+ wire frame to `encodeServerFrame`; callers must decode external input through the domain schema
139
+ before treating it as an in-memory value. Both surfaces are derived from the same event schemas, so
140
+ there is still one logical contract rather than parallel hand-maintained models. Switching on
141
+ `event.type` narrows `event.payload` to that event's exact schema on either surface.
142
+
143
+ The EDA host binding is therefore explicit:
144
+
145
+ ```ts
146
+ const options = {
147
+ // Other host options omitted.
148
+ webSocketProtocol: counterWebSocketProtocol.host,
149
+ };
150
+ ```
129
151
 
130
152
  The app event union is the registration point: adding a custom event there changes the WebSocket union everywhere it is imported. Consumers that use an exhaustive event policy or `assertNever` then receive a TypeScript error until they explicitly apply or ignore the new event.
131
153
 
132
154
  Hosts without custom events use the strict framework-only protocol. The default host encoder does not accept an arbitrary `EventEnvelope`; an app event must be registered explicitly or outbound encoding fails. This prevents an omitted app binding from silently degrading payloads back to `unknown`.
133
155
 
156
+ This API separation does not change protocol version `1` or any serialized frame shape. It makes the
157
+ existing domain-to-wire transformation direction visible in TypeScript and tests it through a full
158
+ domain frame → JSON text → wire/domain decode round trip.
159
+
134
160
  ## 3. Schema sketch
135
161
 
136
162
  Frame variants are plain `Schema.Struct` values with literal `_tag` fields. Client and server protocols compose those variants with `Schema.Union`. This keeps the wire contract data-only; class constructors are reserved for domain values that benefit from behavior.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-durable-agent",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.3",
4
4
  "description": "A Redux-inspired state-management and durable execution layer for agentic applications on Cloudflare Durable Objects.",
5
5
  "keywords": [
6
6
  "agents",
@@ -1 +0,0 @@
1
- {"version":3,"file":"durable-object-runtime-B7jwBY2R.js","names":[],"sources":["../src/host/websocket-protocol.ts","../src/services/websocket-subscriber.ts","../src/host/durable-object-keepalive.ts","../src/host/durable-object-store.ts","../src/host/durable-object-sink-checkpoints.ts","../src/host/durable-object-runtime.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport {\n EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION,\n EDAWebSocketWireAckFrame,\n EDAWebSocketWireClientFrame,\n EDAWebSocketWireErrorFrame,\n EDAWebSocketWireFlowControl,\n EDAWebSocketWireHeartbeatFrame,\n EDAWebSocketWireHelloFrame,\n EDAWebSocketWireLaggedFrame,\n edaFrameworkWebSocketWireProtocol,\n type EDAWebSocketServerFrameEncoder,\n} from \"./websocket-wire\";\n\nimport { SequenceNumber, SessionId } from \"../types/core\";\nimport { PositionedEvent, UnixEpochMillis } from \"../types/events\";\nimport { EDATraceMetadata } from \"../types/tracing\";\n\n/** Current EDA live-event WebSocket protocol version. */\nexport const EDA_WEB_SOCKET_PROTOCOL_VERSION = EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION;\n\n/** WebSocket close code used when a subscriber cannot keep up with live delivery. */\nexport const EDA_WS_CLOSE_LAGGED = 4008;\n\n/** WebSocket close code used for normal host-driven shutdown. */\nexport const EDA_WS_CLOSE_GOING_AWAY = 1001;\n\n/** WebSocket close code used for malformed client protocol messages. */\nexport const EDA_WS_CLOSE_PROTOCOL_ERROR = 1002;\n\n/** WebSocket close code used when the host cannot send a frame. */\nexport const EDA_WS_CLOSE_SEND_FAILED = 1011;\n\n/** WebSocket close code used for unsupported binary messages. */\nexport const EDA_WS_CLOSE_UNSUPPORTED_DATA = 1003;\n\n/** Live subscriber identity persisted in WebSocket attachments. */\nexport const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand(\"SubscriberId\"));\nexport type SubscriberId = typeof SubscriberId.Type;\n\n/** Per-connection monotonically increasing server frame id. */\nexport const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(\n Schema.brand(\"FrameId\"),\n);\nexport type FrameId = typeof FrameId.Type;\n\n/** Flow-control policy announced by the server in the hello frame. */\nexport const EDAWebSocketFlowControl = EDAWebSocketWireFlowControl;\nexport type EDAWebSocketFlowControl = typeof EDAWebSocketFlowControl.Type;\n\n/** Default bounded policy sized for fast model deltas and large durable tool/message events. */\nexport const defaultEDAWebSocketFlowControl: EDAWebSocketFlowControl = {\n ackTimeoutMs: 30_000,\n heartbeatIntervalMs: 10_000,\n maxFrameBytes: 256 * 1024,\n maxFrameEvents: 1,\n maxInFlightFrames: 16,\n subscriberBufferCapacityEvents: 2_048,\n};\n\n/** First server frame; announces protocol and flow-control policy. */\nexport const EDAWebSocketHelloFrame = Schema.Struct({\n ...EDAWebSocketWireHelloFrame.fields,\n subscriberId: SubscriberId,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketHelloFrame = typeof EDAWebSocketHelloFrame.Type;\n\n/** Ordered positioned events delivered to the client. */\nexport const EDAWebSocketEventsFrame = Schema.Struct({\n _tag: Schema.Literal(\"events\"),\n frameId: FrameId,\n events: Schema.NonEmptyArray(PositionedEvent),\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketEventsFrame = typeof EDAWebSocketEventsFrame.Type;\n\n/** Idle server keepalive frame that clients may ignore and must not ACK. */\nexport const EDAWebSocketHeartbeatFrame = Schema.Struct({\n ...EDAWebSocketWireHeartbeatFrame.fields,\n serverTimeMs: UnixEpochMillis,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketHeartbeatFrame = typeof EDAWebSocketHeartbeatFrame.Type;\n\n/** Optional final frame sent before a lag-close. */\nexport const EDAWebSocketLaggedFrame = Schema.Struct({\n ...EDAWebSocketWireLaggedFrame.fields,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketLaggedFrame = typeof EDAWebSocketLaggedFrame.Type;\n\n/** Optional final frame sent before a protocol/internal close. */\nexport const EDAWebSocketErrorFrame = EDAWebSocketWireErrorFrame;\nexport type EDAWebSocketErrorFrame = typeof EDAWebSocketErrorFrame.Type;\n\n/** Server-to-client application frame union. */\nexport const EDAWebSocketServerFrame = Schema.Union([\n EDAWebSocketHelloFrame,\n EDAWebSocketEventsFrame,\n EDAWebSocketHeartbeatFrame,\n EDAWebSocketLaggedFrame,\n EDAWebSocketErrorFrame,\n]);\nexport type EDAWebSocketServerFrame = typeof EDAWebSocketServerFrame.Type;\n\n/** Client acknowledgement after applying a server frame. */\nexport const EDAWebSocketAckFrame = Schema.Struct({\n ...EDAWebSocketWireAckFrame.fields,\n frameId: FrameId,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketAckFrame = typeof EDAWebSocketAckFrame.Type;\n\n/** Client-to-server application frame union. */\nexport const EDAWebSocketClientFrame = Schema.Union([EDAWebSocketAckFrame]);\nexport type EDAWebSocketClientFrame = typeof EDAWebSocketClientFrame.Type;\n\n/** Small attachment persisted by Cloudflare for hibernating WebSockets. */\nexport const EDAWebSocketAttachment = Schema.Struct({\n kind: Schema.Literal(\"eda-events-v1\"),\n sessionId: SessionId,\n subscriberId: SubscriberId,\n lastAckedSeq: SequenceNumber,\n trace: EDATraceMetadata,\n});\nexport type EDAWebSocketAttachment = typeof EDAWebSocketAttachment.Type;\n\n/** Serialize a server frame for a text WebSocket message. */\nexport const encodeEDAWebSocketServerFrame = (\n frame: EDAWebSocketServerFrame,\n protocol?: EDAWebSocketServerFrameEncoder,\n): string => (protocol ?? edaFrameworkWebSocketWireProtocol).encodeServerFrame(frame);\n\n/** Decode an unknown attachment value from Cloudflare WebSocket hibernation storage. */\nexport const decodeEDAWebSocketAttachment = (\n input: unknown,\n): Effect.Effect<EDAWebSocketAttachment, unknown> =>\n Schema.decodeUnknownEffect(EDAWebSocketAttachment)(input);\n\n/** Decode an inbound text WebSocket message at the host boundary. */\nexport const decodeEDAWebSocketClientMessage = (\n input: string,\n): Effect.Effect<EDAWebSocketClientFrame, unknown> =>\n Effect.try({\n try: () => JSON.parse(input) as unknown,\n catch: (error) => error,\n }).pipe(\n Effect.flatMap((json) => Schema.decodeUnknownEffect(EDAWebSocketWireClientFrame)(json)),\n Effect.flatMap((frame) => Schema.decodeUnknownEffect(EDAWebSocketClientFrame)(frame)),\n );\n\n/** Short close reason that fits the WebSocket protocol reason limit. */\nexport const laggedCloseReason = (seq: SequenceNumber): string => `lag;seq=${seq}`;\n","import * as Clock from \"effect/Clock\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { EDARuntime } from \"./runtime\";\nimport { EDASessionStoreError } from \"./session-store\";\nimport { SequenceNumber } from \"../types/core\";\nimport { UnixEpochMillis, type PositionedEvent } from \"../types/events\";\nimport {\n EDA_WEB_SOCKET_PROTOCOL_VERSION,\n EDAWebSocketAckFrame,\n EDAWebSocketEventsFrame,\n EDAWebSocketFlowControl,\n EDAWebSocketHeartbeatFrame,\n EDAWebSocketHelloFrame,\n FrameId,\n SubscriberId,\n type EDAWebSocketClientFrame,\n type EDAWebSocketServerFrame,\n} from \"../host/websocket-protocol\";\n\n/** Slow subscriber reasons that intentionally close only the lagging socket. */\nexport const SubscriberLagReason = Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]);\nexport type SubscriberLagReason = typeof SubscriberLagReason.Type;\n\n/** The subscriber could not keep up with the bounded live-delivery policy. */\nexport class SubscriberLagged extends Schema.TaggedErrorClass<SubscriberLagged>()(\n \"SubscriberLagged\",\n {\n subscriberId: SubscriberId,\n lastAckedSeq: SequenceNumber,\n reason: SubscriberLagReason,\n },\n) {}\n\n/** The client sent a malformed or impossible protocol frame. */\nexport class SubscriberProtocolError extends Schema.TaggedErrorClass<SubscriberProtocolError>()(\n \"SubscriberProtocolError\",\n {\n subscriberId: SubscriberId,\n message: Schema.String,\n },\n) {}\n\n/** The host WebSocket boundary failed while sending a frame. */\nexport class SubscriberSendFailed extends Schema.TaggedErrorClass<SubscriberSendFailed>()(\n \"SubscriberSendFailed\",\n {\n subscriberId: SubscriberId,\n cause: Schema.Defect(),\n },\n) {}\n\n/** Expected error surface for one WebSocket subscriber workflow. */\nexport type EDAWebSocketSubscriberError =\n | SubscriberLagged\n | SubscriberProtocolError\n | SubscriberSendFailed\n | EDASessionStoreError;\n\n/** Transport boundary implemented by the Cloudflare WebSocket adapter or tests. */\nexport interface EDAWebSocketSubscriberTransport {\n readonly send: (frame: EDAWebSocketServerFrame) => Effect.Effect<void, SubscriberSendFailed>;\n readonly incoming: Queue.Queue<EDAWebSocketClientFrame>;\n readonly closed: Deferred.Deferred<void>;\n readonly persistAck: (seq: SequenceNumber) => Effect.Effect<void>;\n}\n\n/** Configuration for one scoped ACK-window subscriber workflow. */\nexport interface EDAWebSocketSubscriberInput {\n readonly subscriberId: SubscriberId;\n readonly resumeSeq: SequenceNumber;\n readonly policy: EDAWebSocketFlowControl;\n readonly transport: EDAWebSocketSubscriberTransport;\n}\n\ninterface SentFrame {\n readonly frameId: FrameId;\n readonly durableThroughSeq: SequenceNumber;\n readonly sentAtMs: number;\n}\n\n/** Run one scoped, ACK-gated live-event WebSocket subscriber. */\nexport const runWebSocketSubscriber = (\n input: EDAWebSocketSubscriberInput,\n): Effect.Effect<void, EDAWebSocketSubscriberError, EDARuntime | Scope.Scope> =>\n Effect.gen(function* () {\n const eda = yield* EDARuntime;\n const outbound = yield* Queue.dropping<PositionedEvent>(\n input.policy.subscriberBufferCapacityEvents,\n );\n const windowSignal = yield* Queue.sliding<void>(1);\n const timeoutFailure = yield* Deferred.make<never, SubscriberLagged>();\n const lastAckedSeq = yield* Ref.make(input.resumeSeq);\n const lastAckedFrameId = yield* Ref.make(0);\n const lastSentFrameId = yield* Ref.make(0);\n const lastSentDurableThroughSeq = yield* Ref.make(input.resumeSeq);\n const nextFrameId = yield* Ref.make(FrameId.make(1));\n const inFlight = yield* Ref.make<ReadonlyArray<SentFrame>>([]);\n\n yield* input.transport.send(\n EDAWebSocketHelloFrame.make({\n _tag: \"hello\",\n protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,\n subscriberId: input.subscriberId,\n resumeSeq: input.resumeSeq,\n flowControl: input.policy,\n }),\n );\n\n const events = yield* eda.eventsAfter(input.resumeSeq);\n // TODO(backpressure): this pump drains the replay/live stream into an intermediate queue ahead\n // of the ACK window. That bounded queue protects memory, but it still breaks end-to-end\n // backpressure from slow WebSocket clients to host-level paged durable replay.\n const pump = events.pipe(\n Stream.interruptWhen(Deferred.await(input.transport.closed)),\n Stream.runForEach((event) =>\n Queue.offer(outbound, event).pipe(\n Effect.flatMap((accepted) =>\n accepted\n ? Effect.void\n : Effect.gen(function* () {\n const seq = yield* Ref.get(lastAckedSeq);\n yield* new SubscriberLagged({\n subscriberId: input.subscriberId,\n lastAckedSeq: seq,\n reason: \"buffer-overflow\",\n });\n }),\n ),\n ),\n ),\n );\n\n const sender = sendLoop({\n inFlight,\n input,\n lastAckedSeq,\n lastSentDurableThroughSeq,\n lastSentFrameId,\n nextFrameId,\n outbound,\n timeoutFailure,\n windowSignal,\n });\n const ackLoop = receiveAcks({\n inFlight,\n input,\n lastAckedFrameId,\n lastAckedSeq,\n lastSentFrameId,\n windowSignal,\n });\n\n yield* Effect.raceFirst(\n Deferred.await(input.transport.closed),\n Effect.raceFirst(\n Deferred.await(timeoutFailure),\n Effect.raceFirst(pump, Effect.raceFirst(sender, ackLoop)),\n ),\n );\n });\n\nconst sendLoop = (input: {\n readonly inFlight: Ref.Ref<ReadonlyArray<SentFrame>>;\n readonly input: EDAWebSocketSubscriberInput;\n readonly lastAckedSeq: Ref.Ref<SequenceNumber>;\n readonly lastSentDurableThroughSeq: Ref.Ref<SequenceNumber>;\n readonly lastSentFrameId: Ref.Ref<number>;\n readonly nextFrameId: Ref.Ref<FrameId>;\n readonly outbound: Queue.Queue<PositionedEvent>;\n readonly timeoutFailure: Deferred.Deferred<never, SubscriberLagged>;\n readonly windowSignal: Queue.Queue<void>;\n}): Effect.Effect<\n void,\n SubscriberLagged | SubscriberProtocolError | SubscriberSendFailed,\n Scope.Scope\n> =>\n Effect.forever(\n Effect.gen(function* () {\n yield* waitForWindow(\n input.inFlight,\n input.windowSignal,\n input.input.policy.maxInFlightFrames,\n );\n const next = yield* takeNextOutboundOrHeartbeat(\n input.outbound,\n input.input.policy.heartbeatIntervalMs,\n );\n if (next._tag === \"heartbeat\") {\n yield* sendHeartbeat(input.input, input.lastSentDurableThroughSeq);\n return;\n }\n\n const event = next.event;\n const frameId = yield* Ref.get(input.nextFrameId);\n yield* Ref.set(input.nextFrameId, FrameId.make(frameId + 1));\n\n const previousSentDurableSeq = yield* Ref.get(input.lastSentDurableThroughSeq);\n const durableThroughSeq = durableThroughForFrame([event], previousSentDurableSeq);\n const frame = EDAWebSocketEventsFrame.make({\n _tag: \"events\",\n frameId,\n events: [event],\n durableThroughSeq,\n });\n const encodedBytes = encodedFrameBytes(frame);\n if (encodedBytes > input.input.policy.maxFrameBytes) {\n yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: `Encoded WebSocket frame exceeded maxFrameBytes (${encodedBytes} > ${input.input.policy.maxFrameBytes})`,\n });\n }\n\n const sentAtMs = yield* Clock.currentTimeMillis;\n const sent = { frameId, durableThroughSeq, sentAtMs } satisfies SentFrame;\n // Mark the frame in-flight before the synchronous host send so an immediate\n // client ACK cannot race ahead of our bookkeeping.\n yield* Ref.update(input.inFlight, (frames) => [...frames, sent]);\n yield* Ref.set(input.lastSentFrameId, frameId);\n yield* Ref.set(input.lastSentDurableThroughSeq, durableThroughSeq);\n yield* input.input.transport.send(frame);\n yield* startAckTimeout(\n input.input,\n input.inFlight,\n input.lastAckedSeq,\n input.timeoutFailure,\n sent,\n );\n }),\n );\n\nconst takeNextOutboundOrHeartbeat = (\n outbound: Queue.Queue<PositionedEvent>,\n heartbeatIntervalMs: number,\n): Effect.Effect<\n { readonly _tag: \"event\"; readonly event: PositionedEvent } | { readonly _tag: \"heartbeat\" }\n> =>\n Effect.raceFirst(\n Queue.take(outbound).pipe(Effect.map((event) => ({ _tag: \"event\", event }) as const)),\n Effect.sleep(`${heartbeatIntervalMs} millis`).pipe(Effect.as({ _tag: \"heartbeat\" } as const)),\n );\n\nconst sendHeartbeat = (\n input: EDAWebSocketSubscriberInput,\n lastSentDurableThroughSeq: Ref.Ref<SequenceNumber>,\n): Effect.Effect<void, SubscriberSendFailed> =>\n Effect.gen(function* () {\n const durableThroughSeq = yield* Ref.get(lastSentDurableThroughSeq);\n const serverTimeMs = yield* Clock.currentTimeMillis;\n yield* input.transport.send(\n EDAWebSocketHeartbeatFrame.make({\n _tag: \"heartbeat\",\n serverTimeMs: UnixEpochMillis.make(serverTimeMs),\n durableThroughSeq,\n }),\n );\n });\n\nconst receiveAcks = (input: {\n readonly inFlight: Ref.Ref<ReadonlyArray<SentFrame>>;\n readonly input: EDAWebSocketSubscriberInput;\n readonly lastAckedFrameId: Ref.Ref<number>;\n readonly lastAckedSeq: Ref.Ref<SequenceNumber>;\n readonly lastSentFrameId: Ref.Ref<number>;\n readonly windowSignal: Queue.Queue<void>;\n}): Effect.Effect<void, SubscriberProtocolError> =>\n Effect.forever(\n Effect.gen(function* () {\n const frame = yield* Queue.take(input.input.transport.incoming);\n if (frame._tag !== \"ack\") {\n yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: `Unsupported client frame ${(frame as { readonly _tag?: string })._tag ?? \"unknown\"}`,\n });\n }\n yield* applyAck(input, frame as EDAWebSocketAckFrame);\n }),\n );\n\nconst applyAck = (\n input: Parameters<typeof receiveAcks>[0],\n ack: EDAWebSocketAckFrame,\n): Effect.Effect<void, SubscriberProtocolError> =>\n Effect.gen(function* () {\n const lastAckedFrame = yield* Ref.get(input.lastAckedFrameId);\n const lastSentFrame = yield* Ref.get(input.lastSentFrameId);\n const currentSeq = yield* Ref.get(input.lastAckedSeq);\n\n if (ack.frameId <= lastAckedFrame) {\n if (ack.durableThroughSeq > currentSeq) {\n yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"Duplicate ACK attempted to advance durable seq\",\n });\n }\n return;\n }\n\n if (ack.frameId > lastSentFrame) {\n yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"ACK referenced an unsent frame\",\n });\n }\n\n if (ack.durableThroughSeq < currentSeq) {\n yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"ACK durable seq moved backwards\",\n });\n }\n\n const frames = yield* Ref.get(input.inFlight);\n const acknowledged = frames.filter((frame) => frame.frameId <= ack.frameId);\n if (acknowledged.length === 0) {\n yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"ACK referenced no in-flight frames\",\n });\n }\n const allowedDurableSeq = SequenceNumber.make(\n acknowledged.reduce<number>(\n (max, frame) => Math.max(max, frame.durableThroughSeq),\n currentSeq,\n ),\n );\n if (ack.durableThroughSeq > allowedDurableSeq) {\n yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"ACK durable seq exceeded sent frame boundary\",\n });\n }\n\n yield* Ref.update(input.inFlight, (frames) =>\n frames.filter((frame) => frame.frameId > ack.frameId),\n );\n yield* Ref.set(input.lastAckedFrameId, ack.frameId);\n yield* Ref.set(input.lastAckedSeq, ack.durableThroughSeq);\n yield* input.input.transport.persistAck(ack.durableThroughSeq);\n yield* Queue.offer(input.windowSignal, undefined);\n });\n\nconst waitForWindow = (\n inFlight: Ref.Ref<ReadonlyArray<SentFrame>>,\n windowSignal: Queue.Queue<void>,\n maxInFlightFrames: number,\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n while (true) {\n const frames = yield* Ref.get(inFlight);\n if (frames.length < maxInFlightFrames) {\n return;\n }\n yield* Queue.take(windowSignal);\n }\n });\n\nconst startAckTimeout = (\n input: EDAWebSocketSubscriberInput,\n inFlight: Ref.Ref<ReadonlyArray<SentFrame>>,\n lastAckedSeq: Ref.Ref<SequenceNumber>,\n timeoutFailure: Deferred.Deferred<never, SubscriberLagged>,\n sent: SentFrame,\n): Effect.Effect<void, never, Scope.Scope> =>\n Effect.gen(function* () {\n yield* Effect.sleep(`${input.policy.ackTimeoutMs} millis`);\n const stillInFlight = (yield* Ref.get(inFlight)).some(\n (frame) => frame.frameId === sent.frameId,\n );\n if (!stillInFlight) {\n return;\n }\n const seq = yield* Ref.get(lastAckedSeq);\n yield* Deferred.fail(\n timeoutFailure,\n new SubscriberLagged({\n subscriberId: input.subscriberId,\n lastAckedSeq: seq,\n reason: \"ack-timeout\",\n }),\n );\n }).pipe(Effect.forkScoped, Effect.asVoid);\n\nconst durableThroughForFrame = (\n events: ReadonlyArray<PositionedEvent>,\n previousSentDurableSeq: SequenceNumber,\n): SequenceNumber =>\n SequenceNumber.make(\n events.reduce<number>(\n (max, event) =>\n event.event.durability === \"durable\" ? Math.max(max, event.position.seq) : max,\n previousSentDurableSeq,\n ),\n );\n\nconst encodedFrameBytes = (frame: EDAWebSocketServerFrame): number =>\n new TextEncoder().encode(JSON.stringify(frame)).byteLength;\n","import * as Effect from \"effect/Effect\";\nimport type * as Fiber from \"effect/Fiber\";\n\n/** Default alarm cadence for keeping an active Durable Object warm. */\nexport const defaultDurableObjectKeepAliveIntervalMs = 30_000;\n\n/** Minimal Durable Object storage alarm surface needed by the EDA host keepalive. */\nexport interface DurableObjectAlarmStorage {\n readonly getAlarm: () => number | null | Promise<number | null>;\n readonly setAlarm: (scheduledTimeMs: number) => void | Promise<void>;\n readonly deleteAlarm: () => void | Promise<void>;\n}\n\n/** Optional host hook for background alarm writes started from synchronous observers. */\nexport interface DurableObjectBackgroundWaiter {\n readonly waitUntil: (promise: Promise<unknown>) => void;\n}\n\n/** Configuration for the in-memory active-work heartbeat. */\nexport interface DurableObjectKeepAliveOptions {\n /** Alarm interval while at least one host-tracked fiber is still unsettled. */\n readonly intervalMs?: number;\n /** Clock used for scheduling; tests can inject a deterministic clock. */\n readonly now?: () => number;\n /** Receives best-effort release/reschedule failures that cannot be awaited by the caller. */\n readonly onBackgroundError?: (error: unknown) => void;\n}\n\n/** Idempotent lease for one host-tracked active Effect fiber/root. */\nexport interface DurableObjectKeepAliveLease {\n readonly release: () => Promise<void>;\n}\n\n/**\n * Alarm-backed in-memory keepalive for a raw Durable Object host.\n *\n * The active lease count is intentionally not durable: if the object is evicted\n * or crashes, the fibers the leases represented are gone too, and normal EDA\n * durable recovery must explain any escaped lifecycle boundaries.\n */\nexport class DurableObjectKeepAlive {\n private readonly intervalMs: number;\n private readonly now: () => number;\n private readonly onBackgroundError: (error: unknown) => void;\n private activeLeases = 0;\n private scheduleTail: Promise<void> = Promise.resolve();\n private shutdownRequested = false;\n\n constructor(\n private readonly storage: DurableObjectAlarmStorage,\n private readonly background: DurableObjectBackgroundWaiter | undefined = undefined,\n options: DurableObjectKeepAliveOptions = {},\n ) {\n this.intervalMs = options.intervalMs ?? defaultDurableObjectKeepAliveIntervalMs;\n this.now = options.now ?? (() => Date.now());\n this.onBackgroundError = options.onBackgroundError ?? (() => undefined);\n }\n\n /** Number of active unsettled host roots currently holding the heartbeat. */\n get activeLeaseCount(): number {\n return this.activeLeases;\n }\n\n /** Acquire one active-work lease and arm the heartbeat if this is the first lease. */\n acquire(): Promise<DurableObjectKeepAliveLease> {\n if (this.shutdownRequested) {\n return Promise.reject(new Error(\"DurableObjectKeepAlive is shut down\"));\n }\n this.activeLeases += 1;\n let released = false;\n\n return this.reschedule().then(\n () => ({\n release: async () => {\n if (released) {\n return;\n }\n released = true;\n this.activeLeases = Math.max(0, this.activeLeases - 1);\n await this.reschedule();\n },\n }),\n async (error) => {\n released = true;\n this.activeLeases = Math.max(0, this.activeLeases - 1);\n await this.reschedule().catch(this.onBackgroundError);\n throw error;\n },\n );\n }\n\n /** Run a promise while holding a lease. Intended for host adapters, not EDA internals. */\n async runWhileActive<A>(fn: () => Promise<A>): Promise<A> {\n const lease = await this.acquire();\n try {\n return await fn();\n } finally {\n await lease.release();\n }\n }\n\n /**\n * Track an already-forked Effect fiber as active host work until it settles.\n *\n * Use this with `ManagedRuntime.runFork(...)` when the fiber needs an already\n * built runtime context. The returned lease can be released manually, but it\n * is normally released by the fiber observer.\n */\n async trackFiber<A, E>(fiber: Fiber.Fiber<A, E>): Promise<DurableObjectKeepAliveLease> {\n const lease = await this.acquire();\n fiber.addObserver(() => {\n this.waitUntil(\n lease.release().catch((error) => {\n this.onBackgroundError(error);\n }),\n );\n });\n\n if (fiber.pollUnsafe() !== undefined) {\n await lease.release();\n }\n\n return lease;\n }\n\n /**\n * Fork an Effect as host-tracked active work.\n *\n * This mirrors Effect's host-runner pattern: observe the root fiber and release\n * the alarm lease when it settles. It deliberately does not patch Effect\n * internals or try to classify runnable vs suspended fibers.\n */\n async fork<A, E>(effect: Effect.Effect<A, E>): Promise<Fiber.Fiber<A, E>> {\n const fiber = Effect.runFork(effect);\n await this.trackFiber(fiber);\n return fiber;\n }\n\n /** Handle the Durable Object `alarm()` callback and re-arm while work remains. */\n alarm(): Promise<void> {\n return this.reschedule();\n }\n\n /** Permanently stop the heartbeat and prevent later lease releases from re-arming it. */\n shutdown(): Promise<void> {\n this.shutdownRequested = true;\n this.activeLeases = 0;\n return this.reschedule();\n }\n\n private waitUntil(promise: Promise<unknown>): void {\n if (this.background !== undefined) {\n this.background.waitUntil(promise);\n return;\n }\n void promise;\n }\n\n private reschedule(): Promise<void> {\n this.scheduleTail = this.scheduleTail.catch(() => undefined).then(() => this.syncAlarm());\n return this.scheduleTail;\n }\n\n private async syncAlarm(): Promise<void> {\n if (this.shutdownRequested || this.activeLeases === 0) {\n await this.storage.deleteAlarm();\n return;\n }\n\n const desiredAt = this.now() + this.intervalMs;\n const currentAt = await this.storage.getAlarm();\n if (currentAt === null || currentAt > desiredAt) {\n await this.storage.setAlarm(desiredAt);\n }\n }\n}\n\n/** Hold a Durable Object heartbeat lease for the lifetime of an Effect. */\nexport const withDurableObjectKeepAlive =\n (keepAlive: DurableObjectKeepAlive) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Effect.acquireUseRelease(\n Effect.promise(() => keepAlive.acquire()),\n () => effect,\n (lease) => Effect.promise(() => lease.release()),\n );\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { SequenceNumber, SessionId, SummaryId, durablePosition } from \"../types/core\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n DurableEventEnvelope,\n assistantMessageCommittedEventType,\n assistantPartialCommittedEventType,\n commandAdmittedEventType,\n commandCancelledEventType,\n commandCompletedEventType,\n commandFailedEventType,\n commandStartedEventType,\n contextRebasedEventType,\n decodeUnknownEDADurableEventSync,\n effectDurableAgentNamespace,\n steeringMessageQueuedEventType,\n summaryCreatedEventType,\n systemMessageCommittedEventType,\n userMessageCommittedEventType,\n} from \"../types/events\";\nimport {\n CommittedDurableEvent,\n DurableAppendBatch,\n DurableAppendEntry,\n EDASessionStore,\n EDASessionStoreError,\n type EDAReducerCheckpoint,\n type EDASessionStoreShape,\n type SaveReducerCheckpointInput,\n durableObjectSerializedJsonHardCapBytes,\n} from \"../services/session-store\";\nimport { annotateEdaSpan, committedBatchAttributes } from \"../services/tracing\";\nimport type {\n DurableObjectSessionStorage,\n DurableObjectSessionStoreOptions,\n DurableObjectSqlStorage,\n} from \"./durable-object-storage\";\n\ninterface DurableObjectEventRow {\n readonly seq: number;\n readonly event_id: string;\n readonly namespace: string;\n readonly type: string;\n readonly schema_version: number;\n readonly created_at_ms: number;\n readonly trace_json: string;\n readonly fact_json: string;\n}\n\ninterface DurableObjectEventHeadRow {\n readonly head: number | null;\n}\n\ninterface DurableObjectEventPageCursor {\n readonly afterSeq: SequenceNumber;\n readonly throughSeq: SequenceNumber | undefined;\n}\n\ninterface DurableObjectMigrationRow {\n readonly version: number | null;\n}\n\ninterface DurableObjectMessagePayloadRow {\n readonly context_seq: number;\n readonly payload_json: string;\n}\n\ninterface DurableObjectSummaryPayloadRow {\n readonly payload_json: string;\n}\n\ninterface DurableObjectCommandLookupRow {\n readonly admitted_seq: number;\n}\n\ninterface DurableObjectCommandInputPayloadRow {\n readonly payload_json: string;\n}\n\ninterface DurableObjectReducerCheckpointRow {\n readonly reducer_name: string;\n readonly schema_version: number;\n readonly through_seq: number;\n readonly payload_json: string;\n readonly updated_at_ms: number;\n}\n\n/** Single squashed schema version for the current pre-release DO store. */\nconst durableObjectSessionStoreSchemaVersion = 1;\nconst jsonEncoder = new TextEncoder();\n\n/**\n * Bound one synchronous DO SQLite event-log read/decode to a small CPU and memory slice.\n *\n * A single logical event can already approach the per-row JSON hard cap, and logical decode may\n * touch sidecar rows. Sixteen rows keeps worst-case page memory materially below isolate limits\n * while still amortizing SQL cursor setup for normal small framework events. Revisit with page\n * duration/byte telemetry before increasing.\n */\nconst durableObjectEventReadPageRows = 16;\n\n/**\n * Durable Object SQLite-backed implementation of the semantic `EDASessionStore`.\n *\n * This adapter is the only place EDA framework storage code touches DO SQL. It\n * translates domain append intent into synchronous SQLite writes while keeping\n * `SessionState` and runners SQL-agnostic.\n */\nexport class DurableObjectSessionStore {\n /** Run the single squashed framework migration for the current pre-release schema. */\n static readonly migrate = (storage: DurableObjectSessionStorage) =>\n migrateDurableObjectSessionStore(storage);\n\n /** Build a session-scoped store after migrations have completed. */\n static readonly make = ({\n sessionId,\n storage,\n }: DurableObjectSessionStoreOptions): Effect.Effect<EDASessionStoreShape, EDASessionStoreError> =>\n Effect.gen(function* () {\n yield* DurableObjectSessionStore.migrate(storage);\n return makeDurableObjectSessionStore(sessionId, storage);\n });\n\n /** Layer constructor used by the Durable Object host runtime graph. */\n static readonly layer = (options: DurableObjectSessionStoreOptions) =>\n Layer.effect(EDASessionStore, DurableObjectSessionStore.make(options));\n}\n\n/**\n * Create all framework-owned tables in one idempotent startup step.\n *\n * The project is still pre-release, so this remains a squashed version-1 schema\n * rather than a chain of compatibility migrations.\n */\nconst migrateDurableObjectSessionStore = (storage: DurableObjectSessionStorage) =>\n Effect.try({\n try: () =>\n storage.transactionSync(() => {\n const { sql } = storage;\n sql.exec(`\n CREATE TABLE IF NOT EXISTS _eda_schema_migrations (\n id INTEGER PRIMARY KEY,\n applied_at TEXT NOT NULL DEFAULT (datetime('now'))\n )\n `);\n\n const currentVersion =\n sql\n .exec<DurableObjectMigrationRow>(\n \"SELECT COALESCE(MAX(id), 0) AS version FROM _eda_schema_migrations\",\n )\n .one().version ?? 0;\n\n if (currentVersion < durableObjectSessionStoreSchemaVersion) {\n sql.exec(`\n CREATE TABLE IF NOT EXISTS _eda_event_log (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n event_id TEXT NOT NULL UNIQUE,\n namespace TEXT NOT NULL,\n type TEXT NOT NULL,\n schema_version INTEGER NOT NULL,\n created_at_ms INTEGER NOT NULL,\n trace_json TEXT NOT NULL,\n fact_json TEXT NOT NULL\n )\n `);\n sql.exec(`\n CREATE INDEX IF NOT EXISTS _eda_event_log_namespace_type_seq_idx\n ON _eda_event_log(namespace, type, seq)\n `);\n\n sql.exec(`\n CREATE TABLE IF NOT EXISTS _eda_command_state (\n command_id TEXT PRIMARY KEY,\n admitted_seq INTEGER NOT NULL,\n status TEXT NOT NULL,\n idempotency_key TEXT,\n payload_json TEXT NOT NULL\n )\n `);\n sql.exec(`\n CREATE TABLE IF NOT EXISTS _eda_command_inputs (\n command_id TEXT PRIMARY KEY,\n admitted_seq INTEGER NOT NULL UNIQUE,\n payload_json TEXT NOT NULL\n )\n `);\n sql.exec(`\n CREATE INDEX IF NOT EXISTS _eda_command_state_status_seq_idx\n ON _eda_command_state(status, admitted_seq)\n `);\n sql.exec(`\n CREATE UNIQUE INDEX IF NOT EXISTS _eda_command_state_idempotency_idx\n ON _eda_command_state(idempotency_key) WHERE idempotency_key IS NOT NULL\n `);\n sql.exec(`\n CREATE TABLE IF NOT EXISTS _eda_context_messages (\n message_id TEXT PRIMARY KEY,\n context_seq INTEGER NOT NULL UNIQUE,\n payload_json TEXT NOT NULL\n )\n `);\n sql.exec(`\n CREATE INDEX IF NOT EXISTS _eda_context_messages_context_seq_idx\n ON _eda_context_messages(context_seq)\n `);\n sql.exec(`\n CREATE TABLE IF NOT EXISTS _eda_context_summaries (\n summary_id TEXT PRIMARY KEY,\n created_seq INTEGER NOT NULL UNIQUE,\n payload_json TEXT NOT NULL\n )\n `);\n sql.exec(`\n CREATE INDEX IF NOT EXISTS _eda_context_summaries_created_seq_idx\n ON _eda_context_summaries(created_seq)\n `);\n sql.exec(`\n CREATE TABLE IF NOT EXISTS _eda_reducer_checkpoints (\n reducer_name TEXT PRIMARY KEY,\n schema_version INTEGER NOT NULL,\n through_seq INTEGER NOT NULL,\n payload_json TEXT NOT NULL,\n updated_at_ms INTEGER NOT NULL\n )\n `);\n sql.exec(`\n CREATE TABLE IF NOT EXISTS _eda_sink_cursors (\n sink_name TEXT PRIMARY KEY,\n after_seq INTEGER NOT NULL,\n payload_json TEXT NOT NULL\n )\n `);\n sql.exec(\n \"INSERT INTO _eda_schema_migrations (id) VALUES (?)\",\n durableObjectSessionStoreSchemaVersion,\n );\n }\n }),\n catch: (error) => durableStoreError(\"migrating DurableObjectSessionStore\", error),\n });\n\n/**\n * Interpret the semantic store API with native DO SQLite.\n *\n * All writes that affect durable ordering happen inside `transactionSync`; replay\n * and lookup reads stay synchronous SQL wrapped in Effect boundaries.\n */\nconst makeDurableObjectSessionStore = (\n sessionId: SessionId,\n storage: DurableObjectSessionStorage,\n): EDASessionStoreShape => {\n const { sql } = storage;\n const ensureSession = (event: DurableEventEnvelope) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `DurableObjectSessionStore is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n };\n\n /**\n * Insert one append entry or return its existing idempotent event position.\n *\n * The event row is the sequence allocator. Artifact/projection writes happen\n * only for newly inserted events, preventing duplicate appends from advancing\n * body rows or metadata.\n */\n const insertOrRead = (entry: DurableAppendEntry): CommittedDurableEvent => {\n const { event } = entry;\n ensureSession(event);\n const existing = readCommittedByEventIdOptional(sql, sessionId, event.eventId);\n if (existing !== undefined) {\n return existing;\n }\n\n const encoded = encodeEventLogRow(event);\n sql.exec(\n `\n INSERT INTO _eda_event_log (\n event_id,\n namespace,\n type,\n schema_version,\n created_at_ms,\n trace_json,\n fact_json\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n encoded.eventId,\n encoded.namespace,\n encoded.type,\n encoded.schemaVersion,\n encoded.createdAtMs,\n encoded.traceJson,\n encoded.factJson,\n );\n const row = readEventLogRowByEventId(sql, event.eventId);\n applySynchronousProjections(sql, entry, SequenceNumber.make(row.seq), encoded.factJson);\n return rowToCommittedDurableEvent(sql, row, sessionId);\n };\n\n /** Execute an entire append batch as one synchronous SQLite transaction. */\n const append = (batch: DurableAppendBatch) =>\n Effect.try({\n try: () => storage.transactionSync(() => batch.entries.map(insertOrRead)),\n catch: (error) => durableStoreError(\"appending DurableObjectSessionStore batch\", error),\n }).pipe(Effect.tap((committed) => annotateEdaSpan(committedBatchAttributes(committed))));\n\n return {\n append,\n eventsAfter: (afterSeq) => makeCommittedEventStream(sql, sessionId, afterSeq),\n loadCommittedEventsBySeq: (seqs) =>\n Effect.try({\n try: () =>\n uniqueSequenceNumbers(seqs)\n .sort((left, right) => left - right)\n .map((seq) => readCommittedBySeq(sql, sessionId, seq)),\n catch: (error) =>\n durableStoreError(\"loading DurableObjectSessionStore events by seq\", error),\n }),\n findCommandAdmission: (input) =>\n Effect.try({\n try: () => {\n const row = findCommandAdmissionRow(sql, input.commandId, input.idempotencyKey);\n return row === undefined\n ? undefined\n : readCommittedBySeq(sql, sessionId, row.admitted_seq);\n },\n catch: (error) => durableStoreError(\"finding command admission\", error),\n }),\n loadSummaryArtifact: (summaryId) =>\n Effect.try({\n try: () => readSummaryPayloadOptional(sql, summaryId),\n catch: (error) => durableStoreError(\"loading DurableObjectSessionStore summary\", error),\n }),\n loadReducerCheckpoint: (name) =>\n Effect.try({\n try: () => readReducerCheckpoint(sql, name),\n catch: (error) =>\n durableStoreError(`loading DurableObjectSessionStore reducer checkpoint ${name}`, error),\n }),\n saveReducerCheckpoint: (checkpoint) =>\n Effect.try({\n try: () => writeReducerCheckpoint(sql, checkpoint),\n catch: (error) =>\n durableStoreError(\n `saving DurableObjectSessionStore reducer checkpoint ${checkpoint.name}`,\n error,\n ),\n }),\n saveReducerCheckpoints: (checkpoints) =>\n Effect.try({\n try: () =>\n storage.transactionSync(() =>\n checkpoints.forEach((checkpoint) => writeReducerCheckpoint(sql, checkpoint)),\n ),\n catch: (error) =>\n durableStoreError(\"saving DurableObjectSessionStore reducer checkpoints\", error),\n }),\n };\n};\n\nconst makeCommittedEventStream = (\n sql: DurableObjectSqlStorage,\n sessionId: SessionId,\n afterSeq: SequenceNumber,\n): Stream.Stream<CommittedDurableEvent, EDASessionStoreError> =>\n Stream.fromPull(\n Effect.sync(() => {\n let cursor: DurableObjectEventPageCursor = { afterSeq, throughSeq: undefined };\n let done = false;\n return Effect.gen(function* () {\n if (done) {\n return yield* Cause.done();\n }\n // DO SQLite is synchronous; yield between bounded pages so eager consumers do not\n // monopolize the isolate with one long replay/decode loop.\n yield* Effect.yieldNow;\n const page = yield* readCommittedEventPage(sql, sessionId, cursor);\n if (page.events.length === 0) {\n done = true;\n return yield* Cause.done();\n }\n if (Option.isSome(page.next)) {\n cursor = page.next.value;\n } else {\n done = true;\n }\n return page.events as readonly [CommittedDurableEvent, ...Array<CommittedDurableEvent>];\n });\n }),\n );\n\nconst readCommittedEventPage = (\n sql: DurableObjectSqlStorage,\n sessionId: SessionId,\n cursor: DurableObjectEventPageCursor,\n): Effect.Effect<\n {\n readonly events: ReadonlyArray<CommittedDurableEvent>;\n readonly next: Option.Option<DurableObjectEventPageCursor>;\n },\n EDASessionStoreError\n> =>\n Effect.try({\n try: () => {\n const throughSeq = cursor.throughSeq ?? readEventLogHead(sql);\n if (cursor.afterSeq >= throughSeq) {\n return { events: [], next: Option.none() };\n }\n\n const events = sql\n .exec<DurableObjectEventRow>(\n `\n SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json\n FROM _eda_event_log\n WHERE seq > ? AND seq <= ?\n ORDER BY seq ASC\n LIMIT ?\n `,\n cursor.afterSeq,\n throughSeq,\n durableObjectEventReadPageRows,\n )\n .toArray()\n .map((row) => rowToCommittedDurableEvent(sql, row, sessionId));\n const lastSeq = events.at(-1)?.position.seq ?? cursor.afterSeq;\n return {\n events,\n next:\n lastSeq < throughSeq\n ? Option.some({ afterSeq: lastSeq, throughSeq } satisfies DurableObjectEventPageCursor)\n : Option.none(),\n };\n },\n catch: (error) => durableStoreError(\"replaying DurableObjectSessionStore events\", error),\n });\n\nconst readEventLogHead = (sql: DurableObjectSqlStorage): SequenceNumber =>\n SequenceNumber.make(\n sql\n .exec<DurableObjectEventHeadRow>(\n `\n SELECT COALESCE(MAX(seq), 0) AS head\n FROM _eda_event_log\n `,\n )\n .one().head ?? 0,\n );\n\nconst uniqueSequenceNumbers = (seqs: ReadonlyArray<SequenceNumber>): Array<SequenceNumber> =>\n Array.from(new Set(seqs.map((seq) => Number(seq)))).map((seq) => SequenceNumber.make(seq));\n\nconst readEventLogRowByEventId = (\n sql: DurableObjectSqlStorage,\n eventId: DurableEventEnvelope[\"eventId\"],\n): DurableObjectEventRow =>\n sql\n .exec<DurableObjectEventRow>(\n `\n SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json\n FROM _eda_event_log\n WHERE event_id = ?\n `,\n eventId,\n )\n .one();\n\nconst readCommittedByEventIdOptional = (\n sql: DurableObjectSqlStorage,\n sessionId: SessionId,\n eventId: DurableEventEnvelope[\"eventId\"],\n): CommittedDurableEvent | undefined => {\n const row = sql\n .exec<DurableObjectEventRow>(\n `\n SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json\n FROM _eda_event_log\n WHERE event_id = ?\n `,\n eventId,\n )\n .toArray()[0];\n return row === undefined ? undefined : rowToCommittedDurableEvent(sql, row, sessionId);\n};\n\nconst readReducerCheckpoint = (\n sql: DurableObjectSqlStorage,\n name: string,\n): EDAReducerCheckpoint | undefined => {\n const row = sql\n .exec<DurableObjectReducerCheckpointRow>(\n `\n SELECT reducer_name, schema_version, through_seq, payload_json, updated_at_ms\n FROM _eda_reducer_checkpoints\n WHERE reducer_name = ?\n `,\n name,\n )\n .toArray()[0];\n return row === undefined\n ? undefined\n : {\n name: row.reducer_name,\n schemaVersion: row.schema_version,\n throughSeq: SequenceNumber.make(row.through_seq),\n payload: JSON.parse(row.payload_json),\n updatedAtMs: row.updated_at_ms,\n };\n};\n\nconst writeReducerCheckpoint = (\n sql: DurableObjectSqlStorage,\n checkpoint: SaveReducerCheckpointInput,\n): void => {\n sql.exec(\n `\n INSERT INTO _eda_reducer_checkpoints (\n reducer_name,\n schema_version,\n through_seq,\n payload_json,\n updated_at_ms\n ) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(reducer_name) DO UPDATE SET\n schema_version = excluded.schema_version,\n through_seq = excluded.through_seq,\n payload_json = excluded.payload_json,\n updated_at_ms = excluded.updated_at_ms\n `,\n checkpoint.name,\n checkpoint.schemaVersion,\n checkpoint.throughSeq,\n stringifyJsonForColumn(checkpoint.payload, \"_eda_reducer_checkpoints.payload_json\"),\n checkpoint.updatedAtMs,\n );\n};\n\nconst readMessagePayloadByContextSeq = (\n sql: DurableObjectSqlStorage,\n contextSeq: number,\n): DurableObjectMessagePayloadRow => {\n const message = sql\n .exec<DurableObjectMessagePayloadRow>(\n `\n SELECT context_seq, payload_json\n FROM _eda_context_messages\n WHERE context_seq = ?\n `,\n contextSeq,\n )\n .toArray()[0];\n if (message === undefined) {\n throw new Error(`Context message at seq ${contextSeq} missing from _eda_context_messages`);\n }\n return message;\n};\n\nconst readCommittedBySeq = (\n sql: DurableObjectSqlStorage,\n sessionId: SessionId,\n seq: number,\n): CommittedDurableEvent => {\n const row = sql\n .exec<DurableObjectEventRow>(\n `\n SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json\n FROM _eda_event_log\n WHERE seq = ?\n `,\n seq,\n )\n .one();\n return rowToCommittedDurableEvent(sql, row, sessionId);\n};\n\nconst rowToCommittedDurableEvent = (\n sql: DurableObjectSqlStorage,\n row: DurableObjectEventRow,\n sessionId: SessionId,\n): CommittedDurableEvent =>\n CommittedDurableEvent.make({\n position: durablePosition(SequenceNumber.make(row.seq)),\n event: decodeDurableEvent({\n namespace: row.namespace,\n type: row.type,\n schemaVersion: row.schema_version,\n durability: \"durable\",\n eventId: row.event_id,\n sessionId,\n createdAtMs: row.created_at_ms,\n trace: JSON.parse(row.trace_json),\n payload: readLogicalPayload(sql, row),\n }),\n });\n\nconst decodeDurableEvent = (input: unknown): DurableEventEnvelope => {\n const event = Schema.decodeUnknownSync(DurableEventEnvelope)(input);\n return event.namespace === effectDurableAgentNamespace\n ? decodeUnknownEDADurableEventSync(event)\n : event;\n};\n\ninterface EncodedEventLogRow {\n readonly eventId: string;\n readonly namespace: string;\n readonly type: string;\n readonly schemaVersion: number;\n readonly createdAtMs: number;\n readonly traceJson: string;\n readonly factJson: string;\n}\n\nconst encodeEventLogRow = (event: DurableEventEnvelope): EncodedEventLogRow => {\n const encoded = Schema.encodeSync(DurableEventEnvelope)(event);\n return {\n eventId: encoded.eventId,\n namespace: encoded.namespace,\n type: encoded.type,\n schemaVersion: encoded.schemaVersion,\n createdAtMs: encoded.createdAtMs,\n traceJson: stringifyJsonForColumn(encoded.trace, \"_eda_event_log.trace_json\"),\n factJson: stringifyJsonForColumn(\n eventLogFactPayload(encoded.namespace, encoded.type, encoded.payload),\n \"_eda_event_log.fact_json\",\n ),\n };\n};\n\nconst readLogicalPayload = (sql: DurableObjectSqlStorage, row: DurableObjectEventRow): unknown => {\n if (row.namespace !== effectDurableAgentNamespace) {\n return JSON.parse(row.fact_json);\n }\n if (row.type === commandAdmittedEventType) {\n const commandId = readCommandIdFromFact(row);\n const command = readCommandInputPayload(sql, commandId);\n return { command };\n }\n if (contextMessageEventTypes.has(row.type)) {\n return JSON.parse(readMessagePayloadByContextSeq(sql, row.seq).payload_json);\n }\n if (row.type === summaryCreatedEventType) {\n return {\n ...(JSON.parse(row.fact_json) as Record<string, unknown>),\n summary: readSummaryPayloadFromCreatedSeq(sql, row.seq),\n };\n }\n return JSON.parse(row.fact_json);\n};\n\nconst eventLogFactPayload = (namespace: string, type: string, payload: unknown): unknown => {\n if (\n namespace !== effectDurableAgentNamespace ||\n typeof payload !== \"object\" ||\n payload === null\n ) {\n return payload;\n }\n\n const record = payload as Record<string, unknown>;\n switch (type) {\n case commandAdmittedEventType:\n return { command: commandFact(record.command) };\n case systemMessageCommittedEventType:\n return pick(record, [\"messageId\"]);\n case userMessageCommittedEventType:\n return pick(record, [\"commandId\", \"messageId\"]);\n case steeringMessageQueuedEventType:\n return pick(record, [\"commandId\", \"messageId\", \"runId\"]);\n case assistantMessageCommittedEventType:\n return pick(record, [\"messageId\", \"runId\", \"turnId\", \"inferenceId\"]);\n case assistantPartialCommittedEventType:\n return pick(record, [\"messageId\", \"runId\", \"turnId\", \"inferenceId\", \"reason\"]);\n case summaryCreatedEventType:\n return pick(record, [\"compactionId\", \"summaryId\", \"sourceFromSeq\", \"sourceToSeq\"]);\n default:\n return payload;\n }\n};\n\nconst commandFact = (command: unknown): unknown => {\n if (typeof command !== \"object\" || command === null) {\n return command;\n }\n const record = command as Record<string, unknown>;\n return record._tag === \"SubmitMessage\"\n ? pick(record, [\"_tag\", \"commandId\", \"disposition\", \"idempotencyKey\"])\n : command;\n};\n\nconst pick = (\n record: Record<string, unknown>,\n keys: ReadonlyArray<string>,\n): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n if (record[key] !== undefined) {\n out[key] = record[key];\n }\n }\n return out;\n};\n\nconst readCommandIdFromFact = (row: DurableObjectEventRow): string => {\n const commandId = (\n JSON.parse(row.fact_json) as { readonly command?: { readonly commandId?: unknown } }\n ).command?.commandId;\n if (typeof commandId !== \"string\") {\n throw new Error(`CommandAdmitted fact at seq ${row.seq} missing command.commandId`);\n }\n return commandId;\n};\n\nconst readCommandInputPayload = (sql: DurableObjectSqlStorage, commandId: string): unknown => {\n const row = sql\n .exec<DurableObjectCommandInputPayloadRow>(\n `\n SELECT payload_json\n FROM _eda_command_inputs\n WHERE command_id = ?\n `,\n commandId,\n )\n .toArray()[0];\n if (row === undefined) {\n throw new Error(`Command input ${commandId} missing from _eda_command_inputs`);\n }\n return JSON.parse(row.payload_json);\n};\n\nconst readSummaryPayloadOptional = (\n sql: DurableObjectSqlStorage,\n summaryId: SummaryId,\n): CompactionSummaryArtifact | undefined => {\n const row = sql\n .exec<DurableObjectSummaryPayloadRow>(\n `\n SELECT payload_json\n FROM _eda_context_summaries\n WHERE summary_id = ?\n `,\n summaryId,\n )\n .toArray()[0];\n return row === undefined\n ? undefined\n : Schema.decodeUnknownSync(CompactionSummaryArtifact)(JSON.parse(row.payload_json));\n};\n\nconst readSummaryPayloadFromCreatedSeq = (\n sql: DurableObjectSqlStorage,\n createdSeq: number,\n): unknown => {\n const row = sql\n .exec<DurableObjectSummaryPayloadRow>(\n `\n SELECT payload_json\n FROM _eda_context_summaries\n WHERE created_seq = ?\n `,\n createdSeq,\n )\n .toArray()[0];\n if (row === undefined) {\n throw new Error(`SummaryCreated at seq ${createdSeq} missing from _eda_context_summaries`);\n }\n return JSON.parse(row.payload_json);\n};\n\n/**\n * Maintain bounded storage projections in the same transaction as the event.\n *\n * These rows are durability aids, not a second source of lifecycle truth: event\n * order still comes from `_eda_event_log.seq`, while projections make command\n * lookup and body-sidecar hydration bounded.\n */\nconst applySynchronousProjections = (\n sql: DurableObjectSqlStorage,\n entry: DurableAppendEntry,\n seq: SequenceNumber,\n factJson: string,\n): void => {\n const { event } = entry;\n if (event.namespace !== effectDurableAgentNamespace) {\n return;\n }\n\n writeCommandProjection(sql, event, seq, factJson);\n writeCommandInputProjection(sql, event, seq);\n writeMessageProjection(sql, event, seq);\n writeSummaryProjection(sql, event, seq);\n writeContextRebaseProjection(sql, event, seq);\n};\n\nconst writeCommandProjection = (\n sql: DurableObjectSqlStorage,\n event: DurableEventEnvelope,\n seq: SequenceNumber,\n factJson: string,\n): void => {\n const payload = event.payload as any;\n switch (event.type) {\n case commandAdmittedEventType: {\n const command = payload.command;\n const commandId = command?.commandId;\n if (commandId === undefined) {\n throw new Error(\"CommandAdmitted missing command.commandId\");\n }\n sql.exec(\n `\n INSERT INTO _eda_command_state (\n command_id,\n admitted_seq,\n status,\n idempotency_key,\n payload_json\n ) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(command_id) DO UPDATE SET\n admitted_seq = excluded.admitted_seq,\n status = excluded.status,\n idempotency_key = excluded.idempotency_key,\n payload_json = excluded.payload_json\n `,\n commandId,\n seq,\n \"admitted\",\n command.idempotencyKey ?? null,\n factJson,\n );\n return;\n }\n case commandStartedEventType:\n writeCommandStatus(sql, payload.commandId, seq, \"started\", factJson);\n return;\n case commandCompletedEventType:\n writeCommandStatus(sql, payload.commandId, seq, \"completed\", factJson);\n return;\n case commandFailedEventType:\n writeCommandStatus(sql, payload.commandId, seq, \"failed\", factJson);\n return;\n case commandCancelledEventType:\n writeCommandStatus(sql, payload.commandId, seq, \"cancelled\", factJson);\n return;\n default:\n return;\n }\n};\n\nconst writeCommandStatus = (\n sql: DurableObjectSqlStorage,\n commandId: unknown,\n seq: SequenceNumber,\n status: string,\n payloadJson: string,\n): void => {\n if (commandId === undefined) {\n throw new Error(`${status} command event missing commandId`);\n }\n sql.exec(\n `\n INSERT INTO _eda_command_state (\n command_id,\n admitted_seq,\n status,\n idempotency_key,\n payload_json\n ) VALUES (?, ?, ?, NULL, ?)\n ON CONFLICT(command_id) DO UPDATE SET\n status = excluded.status,\n payload_json = excluded.payload_json\n `,\n commandId,\n seq,\n status,\n payloadJson,\n );\n};\n\nconst writeCommandInputProjection = (\n sql: DurableObjectSqlStorage,\n event: DurableEventEnvelope,\n seq: SequenceNumber,\n): void => {\n if (event.type !== commandAdmittedEventType) {\n return;\n }\n const encoded = Schema.encodeSync(DurableEventEnvelope)(event);\n const command = (encoded.payload as { readonly command?: { readonly commandId?: unknown } })\n .command;\n const commandId = command?.commandId;\n if (commandId === undefined) {\n throw new Error(\"CommandAdmitted missing command.commandId\");\n }\n sql.exec(\n `\n INSERT INTO _eda_command_inputs (\n command_id,\n admitted_seq,\n payload_json\n ) VALUES (?, ?, ?)\n ON CONFLICT(command_id) DO UPDATE SET\n admitted_seq = excluded.admitted_seq,\n payload_json = excluded.payload_json\n `,\n commandId,\n seq,\n stringifyJsonForColumn(command, \"_eda_command_inputs.payload_json\"),\n );\n};\n\nconst contextMessageEventTypes = new Set<string>([\n systemMessageCommittedEventType,\n userMessageCommittedEventType,\n steeringMessageQueuedEventType,\n assistantMessageCommittedEventType,\n assistantPartialCommittedEventType,\n]);\n\n/** Persist model-visible message bodies with the seq that exposed them to context. */\nconst writeMessageProjection = (\n sql: DurableObjectSqlStorage,\n event: DurableEventEnvelope,\n seq: SequenceNumber,\n): void => {\n if (!contextMessageEventTypes.has(event.type)) {\n return;\n }\n\n const encoded = Schema.encodeSync(DurableEventEnvelope)(event);\n const messageId = (encoded.payload as { readonly messageId?: unknown }).messageId;\n if (messageId === undefined) {\n throw new Error(`${event.type} missing messageId`);\n }\n\n sql.exec(\n `\n INSERT INTO _eda_context_messages (\n message_id,\n context_seq,\n payload_json\n ) VALUES (?, ?, ?)\n ON CONFLICT(message_id) DO UPDATE SET\n context_seq = excluded.context_seq,\n payload_json = excluded.payload_json\n `,\n messageId,\n seq,\n stringifyJsonForColumn(encoded.payload, \"_eda_context_messages.payload_json\"),\n );\n};\n\n/**\n * Persist a cumulative summary artifact without making it the active context.\n *\n * `ContextRebased` selects summaries in the framework reduced-state checkpoint;\n * failed compactions can leave orphaned summaries without changing future context.\n */\nconst writeSummaryProjection = (\n sql: DurableObjectSqlStorage,\n event: DurableEventEnvelope,\n seq: SequenceNumber,\n): void => {\n if (event.type !== summaryCreatedEventType) {\n return;\n }\n\n const payload = event.payload as {\n readonly compactionId?: unknown;\n readonly summaryId?: unknown;\n readonly summary?: unknown;\n };\n const summaryId = payload.summaryId;\n if (summaryId === undefined) {\n throw new Error(\"SummaryCreated missing summaryId\");\n }\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n if (summary.summaryId !== summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n if (summary.compactionId !== payload.compactionId) {\n throw new Error(\"SummaryCreated compactionId does not match summary payload\");\n }\n\n sql.exec(\n `\n INSERT INTO _eda_context_summaries (\n summary_id,\n created_seq,\n payload_json\n ) VALUES (?, ?, ?)\n ON CONFLICT(summary_id) DO UPDATE SET\n created_seq = excluded.created_seq,\n payload_json = excluded.payload_json\n `,\n summaryId,\n seq,\n stringifyJsonForColumn(summary, \"_eda_context_summaries.payload_json\"),\n );\n};\n\n/** Validate that `ContextRebased` points at a committed summary sidecar. */\nconst writeContextRebaseProjection = (\n sql: DurableObjectSqlStorage,\n event: DurableEventEnvelope,\n _seq: SequenceNumber,\n): void => {\n if (event.type !== contextRebasedEventType) {\n return;\n }\n\n const payload = event.payload as {\n readonly compactionId?: unknown;\n readonly retainedFromContextSeq?: unknown;\n readonly summaryId?: unknown;\n };\n if (payload.summaryId === undefined) {\n throw new Error(\"ContextRebased missing summaryId\");\n }\n const summary = readSummaryPayloadOptional(sql, SummaryId.make(String(payload.summaryId)));\n if (summary === undefined) {\n throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);\n }\n if (summary.compactionId !== payload.compactionId) {\n throw new Error(\"ContextRebased summary compactionId does not match event payload\");\n }\n if (summary.retainedFromContextSeq !== payload.retainedFromContextSeq) {\n throw new Error(\"ContextRebased retained cursor does not match summary payload\");\n }\n};\n\n/**\n * Lookup prior command admission through `_eda_command_state` instead of genesis replay.\n *\n * Idempotency key wins over explicit command id so caller-owned retry keys remain\n * the stable dedupe surface for external ingress.\n */\nconst findCommandAdmissionRow = (\n sql: DurableObjectSqlStorage,\n commandId: unknown,\n idempotencyKey: unknown,\n): DurableObjectCommandLookupRow | undefined => {\n if (idempotencyKey !== undefined) {\n const row = sql\n .exec<DurableObjectCommandLookupRow>(\n `\n SELECT admitted_seq\n FROM _eda_command_state\n WHERE idempotency_key = ?\n `,\n idempotencyKey,\n )\n .toArray()[0];\n if (row !== undefined) {\n return row;\n }\n }\n\n if (commandId === undefined) {\n return undefined;\n }\n return sql\n .exec<DurableObjectCommandLookupRow>(\n `\n SELECT admitted_seq\n FROM _eda_command_state\n WHERE command_id = ?\n `,\n commandId,\n )\n .toArray()[0];\n};\n\n/** Serialize and size-check one JSON column before it reaches DO SQLite. */\nconst stringifyJsonForColumn = (value: unknown, column: string): string => {\n const json = JSON.stringify(value);\n if (json === undefined) {\n throw new Error(`${column} value is not JSON serializable`);\n }\n const bytes = jsonEncoder.encode(json).byteLength;\n if (bytes > durableObjectSerializedJsonHardCapBytes) {\n throw new Error(\n `${column} serialized JSON is ${bytes} bytes; hard cap is ${durableObjectSerializedJsonHardCapBytes} bytes`,\n );\n }\n return json;\n};\n\nconst durableStoreError = (operation: string, cause: unknown) =>\n new EDASessionStoreError({\n message:\n cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}`,\n });\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { EDASessionStoreError } from \"../services/session-store\";\nimport {\n SinkCheckpointStore,\n type EDASinkName,\n type SinkCheckpointStoreShape,\n} from \"../services/sink-checkpoint-store\";\nimport type { DurableObjectSessionStorage } from \"./durable-object-storage\";\n\n/**\n * Durable Object SQLite adapter for EDA sink checkpoints.\n *\n * Checkpoint SQL stays in the host layer for the same reason session storage SQL\n * does: framework sink code should depend on checkpoint semantics, not table access.\n */\nexport class DurableObjectSinkCheckpointStore {\n /** Ensure the fixed `_eda_sink_cursors` table exists during host startup. */\n static readonly migrate = (storage: DurableObjectSessionStorage) =>\n migrateSinkCheckpointStore(storage);\n\n /** Build the semantic checkpoint store over native DO SQLite. */\n static readonly make = (\n storage: DurableObjectSessionStorage,\n ): Effect.Effect<SinkCheckpointStoreShape, EDASessionStoreError> =>\n makeDurableObjectSinkCheckpointStore(storage);\n\n static readonly layer = (storage: DurableObjectSessionStorage) =>\n Layer.effect(SinkCheckpointStore, DurableObjectSinkCheckpointStore.make(storage));\n}\n\n/** Create the sink checkpoint table inside the current EDA storage schema. */\nconst migrateSinkCheckpointStore = (\n storage: DurableObjectSessionStorage,\n): Effect.Effect<void, EDASessionStoreError> =>\n Effect.try({\n try: () => {\n storage.sql.exec(`\n CREATE TABLE IF NOT EXISTS _eda_sink_cursors (\n sink_name TEXT PRIMARY KEY,\n after_seq INTEGER NOT NULL,\n payload_json TEXT NOT NULL\n )\n `);\n },\n catch: (error) => sinkCheckpointError(\"migrating SinkCheckpointStore\", error),\n });\n\n/** Interpret checkpoint load/save/commit with idempotent upserts. */\nconst makeDurableObjectSinkCheckpointStore = (\n storage: DurableObjectSessionStorage,\n): Effect.Effect<SinkCheckpointStoreShape, EDASessionStoreError> =>\n Effect.gen(function* () {\n yield* DurableObjectSinkCheckpointStore.migrate(storage);\n const { sql } = storage;\n return {\n load: (sinkName: EDASinkName) =>\n Effect.try({\n try: () => {\n const rows = sql\n .exec<{ after_seq: number; payload_json: string }>(\n `SELECT after_seq, payload_json FROM _eda_sink_cursors WHERE sink_name = ?`,\n sinkName,\n )\n .toArray();\n const row = rows[0];\n return row === undefined\n ? { afterSeq: SequenceNumber.make(0), payload: undefined }\n : {\n afterSeq: SequenceNumber.make(row.after_seq),\n payload: JSON.parse(row.payload_json),\n };\n },\n catch: (error) => sinkCheckpointError(\"reading sink checkpoint\", error),\n }),\n saveState: (sinkName: EDASinkName, payload: unknown) =>\n Effect.try({\n try: () => {\n sql.exec(\n `\n INSERT INTO _eda_sink_cursors (sink_name, after_seq, payload_json)\n VALUES (?, 0, ?)\n ON CONFLICT(sink_name) DO UPDATE SET\n payload_json = excluded.payload_json\n `,\n sinkName,\n JSON.stringify(payload),\n );\n },\n catch: (error) => sinkCheckpointError(\"saving sink checkpoint state\", error),\n }),\n commit: (sinkName: EDASinkName, afterSeq: SequenceNumber, payload: unknown | undefined) =>\n Effect.try({\n try: () => {\n sql.exec(\n `\n INSERT INTO _eda_sink_cursors (sink_name, after_seq, payload_json)\n VALUES (?, ?, ?)\n ON CONFLICT(sink_name) DO UPDATE SET\n after_seq = excluded.after_seq,\n payload_json = excluded.payload_json\n `,\n sinkName,\n afterSeq,\n JSON.stringify(payload ?? { updatedAtMs: Date.now() }),\n );\n },\n catch: (error) => sinkCheckpointError(\"committing sink checkpoint\", error),\n }),\n } satisfies SinkCheckpointStoreShape;\n });\n\nconst sinkCheckpointError = (operation: string, cause: unknown) =>\n new EDASessionStoreError({\n message:\n cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}`,\n });\n","import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as ManagedRuntime from \"effect/ManagedRuntime\";\nimport * as Queue from \"effect/Queue\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport * as Tracer from \"effect/Tracer\";\nimport type * as LanguageModel from \"effect/unstable/ai/LanguageModel\";\nimport * as FetchHttpClient from \"effect/unstable/http/FetchHttpClient\";\nimport * as HttpBody from \"effect/unstable/http/HttpBody\";\nimport * as HttpClient from \"effect/unstable/http/HttpClient\";\nimport * as HttpClientError from \"effect/unstable/http/HttpClientError\";\nimport * as HttpClientRequest from \"effect/unstable/http/HttpClientRequest\";\nimport * as HttpClientResponse from \"effect/unstable/http/HttpClientResponse\";\n\nimport type { DurableTranscriptMessage } from \"../domain/message-transcript\";\nimport type { EDASessionSnapshot } from \"../services/session-query\";\nimport { EDACommand } from \"../types/commands\";\nimport { DurableEventEnvelope } from \"../types/events\";\nimport { CommandId, SequenceNumber, SessionId } from \"../types/core\";\nimport { CommittedDurableEvent, EDASessionStoreError } from \"../services/session-store\";\nimport { CompactionExecutor, CompactionPolicy, CompactionRunner } from \"../services/compaction\";\nimport { EventFactory } from \"../services/event-factory\";\nimport { IdGenerator } from \"../services/id-generator\";\nimport { EDAKeepAlive } from \"../services/keep-alive\";\nimport { LiveEventBus } from \"../services/live-event-bus\";\nimport { EDAPromptProjector } from \"../services/prompt-projector\";\nimport { EDASinkRegistry, type EDASink } from \"../services/sink-registry\";\nimport { EDARuntime, type EDARuntimeConfig } from \"../services/runtime\";\nimport { compactSpanAttributes, toEdaExternalSpan } from \"../services/tracing\";\nimport { makeRootEDATraceMetadata, type EDATraceMetadata } from \"../types/tracing\";\nimport {\n SubscriberLagged,\n SubscriberProtocolError,\n SubscriberSendFailed,\n runWebSocketSubscriber,\n} from \"../services/websocket-subscriber\";\nimport type { EDASubmittable } from \"../services/session-state\";\nimport type { CommittedCommandTerminalEvent, EDARuntimeShape } from \"../services/runtime\";\nimport { SessionContext } from \"../services/session-context\";\nimport { EDAReducerRegistry, type EDAReducer } from \"../services/reducer-registry\";\nimport { EDASessionQuery } from \"../services/session-query\";\nimport { SessionState, type SessionCommandAdmissionError } from \"../services/session-state\";\nimport { ToolExecutor } from \"../services/tool-executor\";\nimport {\n EDAToolRegistry,\n type EDAModelToolkit,\n type EDAToolRegistryShape,\n} from \"../services/tool-registry\";\nimport { InferenceRunner } from \"../services/inference-runner\";\nimport { TurnRunner } from \"../services/turn-runner\";\nimport {\n DurableObjectKeepAlive,\n type DurableObjectAlarmStorage,\n type DurableObjectBackgroundWaiter,\n} from \"./durable-object-keepalive\";\nimport { DurableObjectSessionStore } from \"./durable-object-store\";\nimport { DurableObjectSinkCheckpointStore } from \"./durable-object-sink-checkpoints\";\nimport type { DurableObjectSessionStorage } from \"./durable-object-storage\";\nimport {\n EDA_WS_CLOSE_LAGGED,\n EDA_WS_CLOSE_PROTOCOL_ERROR,\n EDA_WS_CLOSE_SEND_FAILED,\n EDAWebSocketAttachment,\n EDAWebSocketErrorFrame,\n EDAWebSocketLaggedFrame,\n SubscriberId,\n decodeEDAWebSocketAttachment,\n decodeEDAWebSocketClientMessage,\n defaultEDAWebSocketFlowControl,\n encodeEDAWebSocketServerFrame,\n laggedCloseReason,\n type EDAWebSocketClientFrame,\n type EDAWebSocketServerFrame,\n} from \"./websocket-protocol\";\nimport type { EDAWebSocketServerFrameEncoder } from \"./websocket-wire\";\n\n/** Durable Object storage capabilities needed by the EDA session host. */\nexport type EDASessionDurableObjectStorage = DurableObjectSessionStorage &\n DurableObjectAlarmStorage;\n\n/** Options for composing one EDA runtime inside a raw Durable Object. */\nexport interface EDADurableObjectRuntimeLayerOptions {\n readonly config: EDARuntimeConfig;\n readonly compactionExecutorLayer?: Layer.Layer<\n CompactionExecutor,\n never,\n LanguageModel.LanguageModel\n >;\n readonly compactionPolicyLayer?: Layer.Layer<CompactionPolicy>;\n readonly keepAlive?: DurableObjectKeepAlive;\n readonly modelLayer: Layer.Layer<LanguageModel.LanguageModel>;\n readonly promptProjectorLayer?: Layer.Layer<EDAPromptProjector>;\n readonly reducers?: ReadonlyArray<EDAReducer<any>>;\n readonly sessionId: SessionId;\n readonly sinks?: ReadonlyArray<EDASink>;\n readonly storage: EDASessionDurableObjectStorage;\n readonly toolkit?: EDAModelToolkit;\n readonly toolRegistry?: EDAToolRegistryShape;\n readonly tracer?: Tracer.Tracer;\n}\n\n/** Options for one live raw Durable Object host instance. */\nexport interface EDASessionDurableObjectHostOptions {\n readonly background?: DurableObjectBackgroundWaiter;\n readonly config: EDARuntimeConfig;\n readonly compactionExecutorLayer?: Layer.Layer<\n CompactionExecutor,\n never,\n LanguageModel.LanguageModel\n >;\n readonly compactionPolicyLayer?: Layer.Layer<CompactionPolicy>;\n readonly keepAlive?: DurableObjectKeepAlive;\n readonly modelLayer: Layer.Layer<LanguageModel.LanguageModel>;\n readonly promptProjectorLayer?: Layer.Layer<EDAPromptProjector>;\n readonly reducers?: ReadonlyArray<EDAReducer<any>>;\n readonly sinks?: ReadonlyArray<EDASink>;\n readonly storage: EDASessionDurableObjectStorage;\n readonly toolkit?: EDAModelToolkit | EDAToolkitFactory;\n readonly toolRegistry?: EDAToolRegistryShape | EDAToolRegistryFactory;\n readonly tracer?: Tracer.Tracer | EDATracerFactory;\n readonly webSocketProtocol?: EDAWebSocketServerFrameEncoder;\n}\n\n/** Per-session factory for provider-visible model toolkit definitions. */\nexport type EDAToolkitFactory = (input: { readonly sessionId: SessionId }) => EDAModelToolkit;\n\n/** Per-session factory for custom tool registry implementations. */\nexport type EDAToolRegistryFactory = (input: {\n readonly sessionId: SessionId;\n}) => EDAToolRegistryShape;\n\nexport type EDATracerFactory = (input: { readonly sessionId: SessionId }) => Tracer.Tracer;\n\n/** Typed host input for admitting one command through RPC or route code. */\nexport interface EDASessionSubmitInput {\n readonly command: EDACommand;\n readonly sessionId: SessionId;\n readonly trace: EDATraceMetadata;\n}\n\n/** Typed host input for admitting commands and app events as one durable batch. */\nexport interface EDASessionSubmitBatchInput {\n readonly items: ReadonlyArray<EDASubmittable>;\n readonly sessionId: SessionId;\n readonly trace: EDATraceMetadata;\n}\n\n/** Typed host input for waiting on a command terminal boundary. */\nexport interface EDASessionBlockOnCommandInput {\n readonly afterSeq?: SequenceNumber;\n readonly commandId: CommandId;\n readonly sessionId: SessionId;\n readonly trace: EDATraceMetadata;\n}\n\n/** Typed host input for operations scoped only by session identity. */\nexport interface EDASessionScopedInput {\n readonly sessionId: SessionId;\n readonly trace: EDATraceMetadata;\n}\n\n/** Typed host input for opening a live event stream from a durable cursor. */\nexport interface EDASessionEventsInput {\n readonly afterSeq?: SequenceNumber;\n readonly sessionId: SessionId;\n readonly trace: EDATraceMetadata;\n}\n\ninterface HostRuntimeState {\n readonly runtime: ManagedRuntime.ManagedRuntime<EDARuntime, SessionCommandAdmissionError>;\n readonly sessionId: SessionId;\n}\n\ninterface EventWebSocketState {\n readonly closed: Deferred.Deferred<void>;\n readonly incoming: Queue.Queue<EDAWebSocketClientFrame>;\n interrupt: (() => void) | undefined;\n lastAckedSeq: SequenceNumber;\n readonly sessionId: SessionId;\n readonly subscriberId: SubscriberId;\n}\n\nconst resolveRuntimeFactory = <A>(\n value: A | ((input: { readonly sessionId: SessionId }) => A) | undefined,\n sessionId: SessionId,\n): A | undefined =>\n typeof value === \"function\"\n ? (value as (input: { readonly sessionId: SessionId }) => A)({ sessionId })\n : value;\n\n/**\n * Compose the full EDA service graph for one raw Durable Object session.\n *\n * The layer is intentionally host-owned: tests can pass a fake model layer,\n * while the Worker host can pass a provider-backed layer from Env.\n */\nexport const makeEDADurableObjectRuntimeLayer = ({\n config,\n compactionExecutorLayer,\n compactionPolicyLayer,\n keepAlive,\n modelLayer,\n promptProjectorLayer,\n reducers,\n sessionId,\n sinks,\n storage,\n toolkit,\n toolRegistry,\n tracer,\n}: EDADurableObjectRuntimeLayerOptions): Layer.Layer<EDARuntime, SessionCommandAdmissionError> => {\n const Store = DurableObjectSessionStore.layer({ sessionId, storage });\n const Bus = LiveEventBus.Live;\n const KeepAlive =\n keepAlive === undefined\n ? EDAKeepAlive.Noop\n : EDAKeepAlive.FromAcquire(() => keepAlive.acquire());\n const SinkCheckpoints = DurableObjectSinkCheckpointStore.layer(storage);\n const Ids = IdGenerator.Live;\n const Session = SessionContext.Live(sessionId);\n const Factory = EventFactory.Live.pipe(Layer.provideMerge(Layer.mergeAll(Session, Ids)));\n const PromptProjector = promptProjectorLayer ?? EDAPromptProjector.Default;\n const ReducerRegistry = EDAReducerRegistry.Live(reducers ?? []);\n const CompactionPolicyLayer = compactionPolicyLayer ?? CompactionPolicy.Disabled;\n const CompactionExecutorLayer = compactionExecutorLayer ?? CompactionExecutor.Disabled;\n const Compaction = CompactionRunner.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Factory,\n Ids,\n KeepAlive,\n modelLayer,\n CompactionPolicyLayer,\n CompactionExecutorLayer,\n ),\n ),\n );\n const SinkRegistry = EDASinkRegistry.Live(sinks ?? []).pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Session,\n Store,\n Bus,\n SinkCheckpoints,\n Factory,\n Ids,\n ReducerRegistry,\n KeepAlive,\n ),\n ),\n );\n const State = SessionState.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Bus,\n Session,\n ReducerRegistry,\n SinkRegistry,\n KeepAlive,\n Compaction,\n PromptProjector,\n ),\n ),\n );\n const Registry =\n toolRegistry !== undefined\n ? EDAToolRegistry.FromShape(toolRegistry)\n : toolkit === undefined\n ? EDAToolRegistry.Empty\n : EDAToolRegistry.FromToolkit(toolkit);\n const InferenceRunnerLayer = InferenceRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, modelLayer, Registry, Ids)),\n );\n const ToolExec = ToolExecutor.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, Registry, Ids, Session)),\n );\n const Turn = TurnRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(InferenceRunnerLayer, ToolExec, Factory, Ids)),\n );\n const StateWithRun = State.pipe(Layer.provideMerge(Layer.mergeAll(Turn, Factory, Ids)));\n const Query = EDASessionQuery.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(StateWithRun, Store, Bus)),\n );\n\n const Runtime = EDARuntime.Live(config).pipe(\n Layer.provideMerge(Layer.mergeAll(StateWithRun, Query)),\n );\n return tracer === undefined\n ? Runtime\n : Runtime.pipe(Layer.provideMerge(Layer.succeed(Tracer.Tracer, tracer)));\n};\n\n/** Provider request defaults accepted by EDA's OpenAI Responses model adapter. */\nexport type EDAOpenAiModelConfig = Omit<typeof OpenAiLanguageModel.Config.Service, \"model\">;\n\n/** OpenAI-backed Effect AI model layer for the default Worker host. */\nexport const makeEDADurableObjectOpenAiModelLayer = (options: {\n readonly aiGateway?: AiGateway;\n readonly apiKey?: string;\n readonly apiUrl?: string;\n readonly config?: EDAOpenAiModelConfig;\n readonly modelId: string;\n}): Layer.Layer<LanguageModel.LanguageModel> => {\n const apiKey = optionalNonEmptyString(options.apiKey);\n if (apiKey === undefined && options.aiGateway === undefined) {\n throw new Error(\n \"OPENAI_API_KEY is required unless the EDA OpenAI model layer is backed by a Cloudflare AI Gateway binding.\",\n );\n }\n\n const baseHttpClient =\n options.aiGateway === undefined\n ? FetchHttpClient.layer\n : Layer.succeed(HttpClient.HttpClient, makeCloudflareAiGatewayHttpClient(options.aiGateway));\n const client = OpenAiClient.layer({\n ...(apiKey === undefined ? {} : { apiKey: Redacted.make(apiKey) }),\n ...(options.apiUrl === undefined ? {} : { apiUrl: options.apiUrl }),\n }).pipe(Layer.provide(baseHttpClient));\n\n return OpenAiLanguageModel.layer({\n model: options.modelId,\n ...(options.config === undefined ? {} : { config: options.config }),\n }).pipe(Layer.provide(client));\n};\n\nconst OPENAI_API_BASE_PATH_PREFIX = \"/v1/\";\n\nconst makeCloudflareAiGatewayHttpClient = (gateway: AiGateway): HttpClient.HttpClient =>\n HttpClient.make((request, url, signal) =>\n Effect.tryPromise({\n try: async () => {\n const response = await gateway.run(\n {\n endpoint: openAiGatewayEndpointFromUrl(url),\n headers: requestHeadersForGateway(request),\n provider: \"openai\",\n query: requestBodyForGateway(request.body),\n },\n { signal },\n );\n return HttpClientResponse.fromWeb(request, response);\n },\n catch: (cause) =>\n new HttpClientError.HttpClientError({\n reason: new HttpClientError.TransportError({\n request,\n cause,\n description: \"Cloudflare AI Gateway request failed\",\n }),\n }),\n }),\n );\n\nconst openAiGatewayEndpointFromUrl = (url: URL): string => {\n const endpointPath = url.pathname.startsWith(OPENAI_API_BASE_PATH_PREFIX)\n ? url.pathname.slice(OPENAI_API_BASE_PATH_PREFIX.length)\n : url.pathname.replace(/^\\/+/, \"\");\n return `${endpointPath}${url.search}`;\n};\n\nconst requestHeadersForGateway = (\n request: HttpClientRequest.HttpClientRequest,\n): Record<string, string> =>\n Object.fromEntries(\n Object.entries(request.headers).filter((entry): entry is [string, string] => {\n const [key, value] = entry;\n return typeof value === \"string\" && key.toLowerCase() !== \"host\";\n }),\n );\n\nconst requestBodyForGateway = (body: HttpBody.HttpBody): unknown => {\n switch (body._tag) {\n case \"Empty\":\n return undefined;\n case \"Raw\":\n return body.body;\n case \"Uint8Array\":\n return JSON.parse(new TextDecoder().decode(body.body)) as unknown;\n default:\n throw new Error(`Unsupported OpenAI request body for Cloudflare AI Gateway: ${body._tag}`);\n }\n};\n\nconst optionalNonEmptyString = (value: string | undefined): string | undefined => {\n const trimmed = value?.trim();\n return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;\n};\n\nconst hostSpanOptions = (\n trace: EDATraceMetadata,\n attributes: Record<string, string | number | boolean | undefined>,\n): Tracer.SpanOptionsNoTrace => ({\n kind: \"server\",\n attributes: compactSpanAttributes({ ...trace.attributes, ...attributes }),\n links: trace.links.map((link) => ({\n span: toEdaExternalSpan(link.context),\n attributes: link.attributes,\n })),\n ...(trace.parent === null ? {} : { parent: toEdaExternalSpan(trace.parent) }),\n});\n\n/** Raw Durable Object host controller for one EDA session object. */\nexport class EDASessionDurableObjectHost {\n private readonly keepAlive: DurableObjectKeepAlive;\n private readonly eventSockets = new WeakMap<WebSocket, EventWebSocketState>();\n private runtimeState: HostRuntimeState | undefined;\n private runtimePromise: Promise<HostRuntimeState> | undefined;\n\n constructor(private readonly options: EDASessionDurableObjectHostOptions) {\n this.keepAlive =\n options.keepAlive ?? new DurableObjectKeepAlive(options.storage, options.background);\n }\n\n /** Run idempotent host and event-store migrations. Safe from `blockConcurrencyWhile`. */\n static readonly migrate = (\n storage: EDASessionDurableObjectStorage,\n ): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n yield* DurableObjectSessionStore.migrate(storage);\n yield* DurableObjectSinkCheckpointStore.migrate(storage);\n });\n\n /** Admit one command durably. Active runtime work holds EDA keep-alive leases internally. */\n async submit(input: EDASessionSubmitInput): Promise<CommittedDurableEvent> {\n const runtime = await this.getRuntime(input.sessionId);\n const trace = input.trace ?? makeRootEDATraceMetadata();\n return await runtime.runtime.runPromise(\n Effect.gen(function* () {\n const eda = yield* EDARuntime;\n return yield* eda.submit(input.command);\n }).pipe(\n Effect.withSpan(\n \"agent.command.submit\",\n hostSpanOptions(trace, {\n \"eda.session.id\": input.sessionId,\n \"eda.command.kind\": input.command._tag,\n \"eda.command.id\": input.command.commandId,\n }),\n ),\n ),\n );\n }\n\n /** Submit an ordered durable batch of commands and app events. */\n async submitBatch(\n input: EDASessionSubmitBatchInput,\n ): Promise<ReadonlyArray<CommittedDurableEvent>> {\n const runtime = await this.getRuntime(input.sessionId);\n const trace = input.trace ?? makeRootEDATraceMetadata();\n return await runtime.runtime.runPromise(\n Effect.gen(function* () {\n const eda = yield* EDARuntime;\n return yield* eda.submit(input.items);\n }).pipe(\n Effect.withSpan(\n \"agent.command.submit\",\n hostSpanOptions(trace, {\n \"eda.session.id\": input.sessionId,\n \"eda.command.submittable_count\": input.items.length,\n \"eda.command.count\": input.items.filter((item) => \"_tag\" in item).length,\n }),\n ),\n ),\n );\n }\n\n /** Admit one command and wait for its terminal command boundary. */\n async submitAndBlock(input: EDASessionSubmitInput): Promise<CommittedCommandTerminalEvent> {\n const runtime = await this.getRuntime(input.sessionId);\n const trace = input.trace ?? makeRootEDATraceMetadata();\n return await runtime.runtime.runPromise(\n Effect.gen(function* () {\n const eda = yield* EDARuntime;\n return yield* eda.submitAndBlock(input.command);\n }).pipe(\n Effect.withSpan(\n \"agent.command.submit.wait\",\n hostSpanOptions(trace, {\n \"eda.session.id\": input.sessionId,\n \"eda.command.kind\": input.command._tag,\n \"eda.command.id\": input.command.commandId,\n }),\n ),\n ),\n );\n }\n\n /** Wait for an existing command to reach its terminal command boundary. */\n async blockOnCommand(\n input: EDASessionBlockOnCommandInput,\n ): Promise<CommittedCommandTerminalEvent> {\n const runtime = await this.getRuntime(input.sessionId);\n const trace = input.trace ?? makeRootEDATraceMetadata();\n return await runtime.runtime.runPromise(\n Effect.gen(function* () {\n const eda = yield* EDARuntime;\n return yield* eda.blockOnCommand(input.commandId, input.afterSeq ?? SequenceNumber.make(0));\n }).pipe(\n Effect.withSpan(\n \"agent.command.wait\",\n hostSpanOptions(trace, {\n \"eda.session.id\": input.sessionId,\n \"eda.command.id\": input.commandId,\n \"eda.seq.after\": input.afterSeq,\n }),\n ),\n ),\n );\n }\n\n /** Read the authoritative live session snapshot. */\n snapshot(input: EDASessionScopedInput): Promise<EDASessionSnapshot> {\n const trace = input.trace ?? makeRootEDATraceMetadata();\n return this.withRuntime(input.sessionId, (eda) =>\n eda\n .snapshot()\n .pipe(\n Effect.withSpan(\n \"agent.session.snapshot\",\n hostSpanOptions(trace, { \"eda.session.id\": input.sessionId }),\n ),\n ),\n );\n }\n\n /** Read durable transcript messages in committed order. */\n messages(input: EDASessionScopedInput): Promise<ReadonlyArray<DurableTranscriptMessage>> {\n const trace = input.trace ?? makeRootEDATraceMetadata();\n return this.withRuntime(input.sessionId, (eda) =>\n eda\n .messages()\n .pipe(\n Effect.withSpan(\n \"agent.messages.list\",\n hostSpanOptions(trace, { \"eda.session.id\": input.sessionId }),\n ),\n ),\n );\n }\n\n /** Accept one WebSocket as the live event stream for this session. */\n async acceptEventWebSocket(\n input: EDASessionEventsInput & { readonly webSocket: WebSocket },\n ): Promise<void> {\n const attachment = EDAWebSocketAttachment.make({\n kind: \"eda-events-v1\",\n sessionId: input.sessionId,\n subscriberId: SubscriberId.make(crypto.randomUUID()),\n lastAckedSeq: input.afterSeq ?? SequenceNumber.make(0),\n trace: input.trace ?? makeRootEDATraceMetadata(),\n });\n input.webSocket.serializeAttachment(attachment);\n await this.startEventWebSocket(input.webSocket, attachment);\n }\n\n /** Restore hibernated event WebSockets whose in-memory subscriber fibers disappeared. */\n async restoreEventWebSockets(webSockets: ReadonlyArray<WebSocket>): Promise<void> {\n for (const webSocket of webSockets) {\n if (this.eventSockets.has(webSocket)) {\n continue;\n }\n const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());\n if (decoded._tag === \"Decoded\") {\n await this.startEventWebSocket(webSocket, decoded.attachment);\n } else if (decoded._tag === \"Malformed\") {\n closeWebSocket(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, \"attachment\");\n }\n }\n }\n\n /** Route one inbound WebSocket message into the subscriber ACK queue. */\n async webSocketMessage(webSocket: WebSocket, message: string | ArrayBuffer): Promise<void> {\n const state = await this.ensureEventWebSocket(webSocket);\n if (state === undefined) {\n closeWebSocket(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, \"protocol\");\n return;\n }\n if (typeof message !== \"string\") {\n closeWebSocket(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, \"binary\");\n state.interrupt?.();\n return;\n }\n\n try {\n const frame = await Effect.runPromise(decodeEDAWebSocketClientMessage(message));\n await Effect.runPromise(Queue.offer(state.incoming, frame));\n } catch {\n closeWebSocket(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, \"protocol\");\n state.interrupt?.();\n }\n }\n\n /** Interrupt subscriber work after the client closes the WebSocket. */\n async webSocketClose(webSocket: WebSocket): Promise<void> {\n const state = this.eventSockets.get(webSocket);\n if (state === undefined) {\n return;\n }\n await Effect.runPromise(Deferred.succeed(state.closed, undefined).pipe(Effect.ignore));\n state.interrupt?.();\n this.eventSockets.delete(webSocket);\n }\n\n /** Interrupt subscriber work after a host WebSocket error. */\n async webSocketError(webSocket: WebSocket): Promise<void> {\n const state = this.eventSockets.get(webSocket);\n if (state === undefined) {\n return;\n }\n await Effect.runPromise(Deferred.succeed(state.closed, undefined).pipe(Effect.ignore));\n state.interrupt?.();\n this.eventSockets.delete(webSocket);\n }\n\n /** Dispose any live runtime before the host deletes its Durable Object storage. */\n async destroy(_input: EDASessionScopedInput): Promise<void> {\n await this.keepAlive.shutdown();\n await this.dispose();\n this.runtimeState = undefined;\n this.runtimePromise = undefined;\n }\n\n /** Durable Object alarm hook: wake/recover the runtime and re-arm while EDA has active work. */\n async alarm(input?: EDASessionScopedInput): Promise<void> {\n const sessionId = input?.sessionId ?? this.runtimeState?.sessionId;\n if (sessionId !== undefined) {\n await this.getRuntime(sessionId);\n }\n await this.keepAlive.alarm();\n }\n\n /** Dispose the Effect runtime if the host wrapper is torn down by tests. */\n async dispose(): Promise<void> {\n await this.runtimeState?.runtime.dispose();\n }\n\n private async withRuntime<A>(\n sessionId: SessionId,\n f: (runtime: EDARuntimeShape) => Effect.Effect<A, unknown>,\n ): Promise<A> {\n const runtime = await this.getRuntime(sessionId);\n return await runtime.runtime.runPromise(\n Effect.gen(function* () {\n const eda = yield* EDARuntime;\n return yield* f(eda);\n }),\n );\n }\n\n private async ensureEventWebSocket(\n webSocket: WebSocket,\n ): Promise<EventWebSocketState | undefined> {\n const existing = this.eventSockets.get(webSocket);\n if (existing !== undefined) {\n return existing;\n }\n const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());\n if (decoded._tag !== \"Decoded\") {\n return undefined;\n }\n await this.startEventWebSocket(webSocket, decoded.attachment);\n return this.eventSockets.get(webSocket);\n }\n\n private async startEventWebSocket(\n webSocket: WebSocket,\n attachment: EDAWebSocketAttachment,\n ): Promise<void> {\n if (this.eventSockets.has(webSocket)) {\n return;\n }\n const runtime = await this.getRuntime(attachment.sessionId);\n const resources = await runtime.runtime.runPromise(\n Effect.gen(function* () {\n const incoming = yield* Queue.unbounded<EDAWebSocketClientFrame>();\n const closed = yield* Deferred.make<void>();\n return { incoming, closed };\n }),\n );\n const state: EventWebSocketState = {\n ...resources,\n interrupt: undefined,\n lastAckedSeq: attachment.lastAckedSeq,\n sessionId: attachment.sessionId,\n subscriberId: attachment.subscriberId,\n };\n this.eventSockets.set(webSocket, state);\n\n const send = (frame: EDAWebSocketServerFrame): Effect.Effect<void, SubscriberSendFailed> =>\n Effect.try({\n try: () =>\n webSocket.send(encodeEDAWebSocketServerFrame(frame, this.options.webSocketProtocol)),\n catch: (cause) => new SubscriberSendFailed({ subscriberId: state.subscriberId, cause }),\n });\n const persistAck = (seq: SequenceNumber): Effect.Effect<void> =>\n Effect.sync(() => {\n state.lastAckedSeq = seq;\n webSocket.serializeAttachment({\n kind: \"eda-events-v1\",\n sessionId: state.sessionId,\n subscriberId: state.subscriberId,\n lastAckedSeq: seq,\n trace: attachment.trace,\n } satisfies EDAWebSocketAttachment);\n });\n\n const closeForError = (error: unknown): Effect.Effect<void> => {\n if (error instanceof SubscriberLagged || isTagged(error, \"SubscriberLagged\")) {\n const lagged = error as SubscriberLagged;\n return send(\n EDAWebSocketLaggedFrame.make({\n _tag: \"lagged\",\n resumeSeq: lagged.lastAckedSeq,\n reason: lagged.reason,\n }),\n ).pipe(\n Effect.ignore,\n Effect.andThen(\n Effect.sync(() =>\n closeWebSocket(\n webSocket,\n EDA_WS_CLOSE_LAGGED,\n laggedCloseReason(lagged.lastAckedSeq),\n ),\n ),\n ),\n );\n }\n if (error instanceof SubscriberProtocolError || isTagged(error, \"SubscriberProtocolError\")) {\n const protocolError = error as SubscriberProtocolError;\n return send(\n EDAWebSocketErrorFrame.make({\n _tag: \"error\",\n message: protocolError.message.slice(0, 120),\n }),\n ).pipe(\n Effect.ignore,\n Effect.andThen(\n Effect.sync(() => closeWebSocket(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, \"protocol\")),\n ),\n );\n }\n return Effect.sync(() => closeWebSocket(webSocket, EDA_WS_CLOSE_SEND_FAILED, \"send-failed\"));\n };\n\n const program = Effect.scoped(\n runWebSocketSubscriber({\n subscriberId: state.subscriberId,\n resumeSeq: state.lastAckedSeq,\n policy: defaultEDAWebSocketFlowControl,\n transport: {\n send,\n incoming: state.incoming,\n closed: state.closed,\n persistAck,\n },\n }).pipe(\n Effect.catch((error) => closeForError(error)),\n Effect.ensuring(\n Effect.sync(() => {\n this.eventSockets.delete(webSocket);\n }),\n ),\n Effect.withSpan(\n \"agent.events.stream\",\n hostSpanOptions(attachment.trace, {\n \"eda.session.id\": state.sessionId,\n \"eda.subscriber.id\": state.subscriberId,\n \"eda.seq.after\": state.lastAckedSeq,\n }),\n ),\n ),\n );\n\n state.interrupt = runtime.runtime.runCallback(program, {\n onExit: (exit) => {\n this.eventSockets.delete(webSocket);\n if (Exit.isFailure(exit)) {\n closeWebSocket(webSocket, EDA_WS_CLOSE_SEND_FAILED, \"subscriber-failed\");\n }\n },\n });\n }\n\n private async getRuntime(sessionId: SessionId): Promise<HostRuntimeState> {\n if (this.runtimeState !== undefined) {\n if (this.runtimeState.sessionId !== sessionId) {\n throw new Error(\n `EDASessionDurableObjectHost is scoped to session ${this.runtimeState.sessionId}; received ${sessionId}`,\n );\n }\n return this.runtimeState;\n }\n\n const runtimePromise = this.runtimePromise ?? this.buildRuntime(sessionId);\n this.runtimePromise = runtimePromise;\n try {\n return await runtimePromise;\n } catch (error) {\n if (this.runtimePromise === runtimePromise) {\n this.runtimePromise = undefined;\n }\n throw error;\n }\n }\n\n private async buildRuntime(sessionId: SessionId): Promise<HostRuntimeState> {\n const runtime = ManagedRuntime.make(\n makeEDADurableObjectRuntimeLayer({\n config: this.options.config,\n compactionExecutorLayer: this.options.compactionExecutorLayer,\n compactionPolicyLayer: this.options.compactionPolicyLayer,\n keepAlive: this.keepAlive,\n modelLayer: this.options.modelLayer,\n promptProjectorLayer: this.options.promptProjectorLayer,\n reducers: this.options.reducers,\n sessionId,\n sinks: this.options.sinks,\n storage: this.options.storage,\n toolkit: resolveRuntimeFactory(this.options.toolkit, sessionId),\n toolRegistry: resolveRuntimeFactory(this.options.toolRegistry, sessionId),\n tracer: resolveRuntimeFactory(this.options.tracer, sessionId),\n }),\n );\n const state = { runtime, sessionId } satisfies HostRuntimeState;\n try {\n await runtime.context();\n this.runtimeState = state;\n return state;\n } catch (error) {\n await runtime.dispose().catch(() => undefined);\n throw error;\n }\n }\n}\n\ntype DecodedWebSocketAttachment =\n | { readonly _tag: \"Missing\" }\n | { readonly _tag: \"Malformed\" }\n | { readonly _tag: \"Decoded\"; readonly attachment: EDAWebSocketAttachment };\n\nconst decodeWebSocketAttachment = async (input: unknown): Promise<DecodedWebSocketAttachment> => {\n if (input === null || input === undefined) {\n return { _tag: \"Missing\" };\n }\n try {\n return {\n _tag: \"Decoded\",\n attachment: await Effect.runPromise(decodeEDAWebSocketAttachment(input)),\n };\n } catch {\n return { _tag: \"Malformed\" };\n }\n};\n\nconst closeWebSocket = (webSocket: WebSocket, code: number, reason: string): void => {\n try {\n webSocket.close(code, reason);\n } catch {\n // The peer may already have closed or the runtime may reject duplicate close.\n }\n};\n\nconst isTagged = (input: unknown, tag: string): boolean =>\n typeof input === \"object\" && input !== null && \"_tag\" in input && input._tag === tag;\n\n/** Decode a raw RPC command payload at the Durable Object boundary. */\nexport const decodeEdaRpcCommand = (\n input: unknown,\n): Effect.Effect<EDACommand, Schema.SchemaError> => Schema.decodeUnknownEffect(EDACommand)(input);\n\nconst EDARpcSubmittable = Schema.Union([EDACommand, DurableEventEnvelope]);\n\n/** Decode a raw RPC batch item at the Durable Object boundary. */\nexport const decodeEdaRpcSubmittable = (\n input: unknown,\n): Effect.Effect<EDASubmittable, Schema.SchemaError> =>\n Schema.decodeUnknownEffect(EDARpcSubmittable)(input);\n\n/** Decode raw RPC batch items at the Durable Object boundary. */\nexport const decodeEdaRpcSubmittables = (\n input: ReadonlyArray<unknown>,\n): Effect.Effect<ReadonlyArray<EDASubmittable>, Schema.SchemaError> =>\n Effect.forEach(input, decodeEdaRpcSubmittable);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,kCAAA;;AAGb,MAAa,sBAAsB;;AAMnC,MAAa,8BAA8B;;AAG3C,MAAa,2BAA2B;;AAMxC,MAAa,eAAe,OAAO,eAAe,KAAK,OAAO,MAAM,cAAc,CAAC;;AAInF,MAAa,UAAU,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC,EAAE,KACxE,OAAO,MAAM,SAAS,CACxB;;AAQA,MAAa,iCAA0D;CACrE,cAAc;CACd,qBAAqB;CACrB,eAAe,MAAM;CACrB,gBAAgB;CAChB,mBAAmB;CACnB,gCAAgC;AAClC;;AAGA,MAAa,yBAAyB,OAAO,OAAO;CAClD,GAAG,2BAA2B;CAC9B,cAAc;CACd,WAAW;AACb,CAAC;;AAID,MAAa,0BAA0B,OAAO,OAAO;CACnD,MAAM,OAAO,QAAQ,QAAQ;CAC7B,SAAS;CACT,QAAQ,OAAO,cAAc,eAAe;CAC5C,mBAAmB;AACrB,CAAC;;AAID,MAAa,6BAA6B,OAAO,OAAO;CACtD,GAAG,+BAA+B;CAClC,cAAc;CACd,mBAAmB;AACrB,CAAC;;AAID,MAAa,0BAA0B,OAAO,OAAO;CACnD,GAAG,4BAA4B;CAC/B,WAAW;AACb,CAAC;;AAID,MAAa,yBAAyB;AAIC,OAAO,MAAM;CAClD;CACA;CACA;CACA;CACA;AACF,CAAC;;AAID,MAAa,uBAAuB,OAAO,OAAO;CAChD,GAAG,yBAAyB;CAC5B,SAAS;CACT,mBAAmB;AACrB,CAAC;;AAID,MAAa,0BAA0B,OAAO,MAAM,CAAC,oBAAoB,CAAC;;AAI1E,MAAa,yBAAyB,OAAO,OAAO;CAClD,MAAM,OAAO,QAAQ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