effect-durable-agent-cloudflare 0.1.0-alpha.4
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.
- package/LICENSE +21 -0
- package/README.md +28 -0
- package/dist/chunk-BBjsoOtd.js +27 -0
- package/dist/durable-object-CjWWNyek.js +194 -0
- package/dist/durable-object-CjWWNyek.js.map +1 -0
- package/dist/durable-object-runtime-Dehm7PsO.d.ts +265 -0
- package/dist/durable-object-runtime-LgOJbsVm.js +1255 -0
- package/dist/durable-object-runtime-LgOJbsVm.js.map +1 -0
- package/dist/durable-object-runtime.d.ts +2 -0
- package/dist/durable-object-runtime.js +2 -0
- package/dist/durable-object-storage-DCL2IyUe.d.ts +41 -0
- package/dist/durable-object-storage.d.ts +2 -0
- package/dist/durable-object-storage.js +0 -0
- package/dist/durable-object.d.ts +83 -0
- package/dist/durable-object.js +2 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -0
- package/dist/websocket-protocol.d.ts +1 -0
- package/dist/websocket-protocol.js +10 -0
- package/dist/websocket-protocol.js.map +1 -0
- package/package.json +82 -0
|
@@ -0,0 +1,1255 @@
|
|
|
1
|
+
import { t as websocket_protocol_exports } from "./websocket-protocol.js";
|
|
2
|
+
import * as Effect from "effect/Effect";
|
|
3
|
+
import * as Schema from "effect/Schema";
|
|
4
|
+
import { DurableEventEnvelope, assistantMessageCommittedEventType, assistantMessageImportedEventType, assistantPartialCommittedEventType, commandAdmittedEventType, commandCancelledEventType, commandCompletedEventType, commandFailedEventType, commandStartedEventType, contextRebasedEventType, decodeUnknownEDADurableEventSync, effectDurableAgentNamespace, steeringMessageQueuedEventType, summaryCreatedEventType, systemMessageCommittedEventType, userMessageCommittedEventType } from "effect-durable-agent/types/events";
|
|
5
|
+
import { EDACommand } from "effect-durable-agent/types/commands";
|
|
6
|
+
import { SequenceNumber, SummaryId, durablePosition } from "effect-durable-agent/types/core";
|
|
7
|
+
import { makeRootEDATraceMetadata } from "effect-durable-agent/types/tracing";
|
|
8
|
+
import { OpenAiClient, OpenAiLanguageModel } from "@effect/ai-openai";
|
|
9
|
+
import * as Deferred from "effect/Deferred";
|
|
10
|
+
import * as Exit from "effect/Exit";
|
|
11
|
+
import * as Layer from "effect/Layer";
|
|
12
|
+
import * as ManagedRuntime from "effect/ManagedRuntime";
|
|
13
|
+
import * as Queue from "effect/Queue";
|
|
14
|
+
import * as Redacted from "effect/Redacted";
|
|
15
|
+
import "effect/Tracer";
|
|
16
|
+
import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
|
|
17
|
+
import "effect/unstable/http/HttpBody";
|
|
18
|
+
import * as HttpClient from "effect/unstable/http/HttpClient";
|
|
19
|
+
import * as HttpClientError from "effect/unstable/http/HttpClientError";
|
|
20
|
+
import "effect/unstable/http/HttpClientRequest";
|
|
21
|
+
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
|
22
|
+
import "effect-durable-agent/services/compaction";
|
|
23
|
+
import { EDAKeepAlive } from "effect-durable-agent/services/keep-alive";
|
|
24
|
+
import "effect-durable-agent/services/prompt-projector";
|
|
25
|
+
import { EDAReducerRegistry } from "effect-durable-agent/services/reducer-registry";
|
|
26
|
+
import { EDARuntime } from "effect-durable-agent/services/runtime";
|
|
27
|
+
import { makeEDARuntimeLayer } from "effect-durable-agent/services/runtime-layer";
|
|
28
|
+
import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from "effect-durable-agent/services/session-store";
|
|
29
|
+
import { annotateEdaSpan, committedBatchAttributes, compactSpanAttributes, toEdaExternalSpan } from "effect-durable-agent/services/tracing";
|
|
30
|
+
import { SubscriberLagged, SubscriberProtocolError, SubscriberSendFailed, runWebSocketSubscriber } from "effect-durable-agent/services/websocket-subscriber";
|
|
31
|
+
import * as Cause from "effect/Cause";
|
|
32
|
+
import * as Option from "effect/Option";
|
|
33
|
+
import * as Stream from "effect/Stream";
|
|
34
|
+
import { CompactionSummaryArtifact } from "effect-durable-agent/domain/context-projection";
|
|
35
|
+
import { SinkCheckpointStore } from "effect-durable-agent/services/sink-checkpoint-store";
|
|
36
|
+
/**
|
|
37
|
+
* Alarm-backed in-memory keepalive for a raw Durable Object host.
|
|
38
|
+
*
|
|
39
|
+
* The active lease count is intentionally not durable: if the object is evicted
|
|
40
|
+
* or crashes, the fibers the leases represented are gone too, and normal EDA
|
|
41
|
+
* durable recovery must explain any escaped lifecycle boundaries.
|
|
42
|
+
*/
|
|
43
|
+
var DurableObjectKeepAlive = class {
|
|
44
|
+
storage;
|
|
45
|
+
background;
|
|
46
|
+
intervalMs;
|
|
47
|
+
now;
|
|
48
|
+
onBackgroundError;
|
|
49
|
+
activeLeases = 0;
|
|
50
|
+
generation = 0;
|
|
51
|
+
scheduleTail = Promise.resolve();
|
|
52
|
+
shutdownRequested = false;
|
|
53
|
+
constructor(storage, background = void 0, options = {}) {
|
|
54
|
+
this.storage = storage;
|
|
55
|
+
this.background = background;
|
|
56
|
+
this.intervalMs = options.intervalMs ?? 3e4;
|
|
57
|
+
this.now = options.now ?? (() => Date.now());
|
|
58
|
+
this.onBackgroundError = options.onBackgroundError ?? (() => void 0);
|
|
59
|
+
}
|
|
60
|
+
/** Number of active unsettled host roots currently holding the heartbeat. */
|
|
61
|
+
get activeLeaseCount() {
|
|
62
|
+
return this.activeLeases;
|
|
63
|
+
}
|
|
64
|
+
/** Acquire one active-work lease and arm the heartbeat if this is the first lease. */
|
|
65
|
+
acquire() {
|
|
66
|
+
if (this.shutdownRequested) return Promise.reject(/* @__PURE__ */ new Error("DurableObjectKeepAlive is shut down"));
|
|
67
|
+
this.activeLeases += 1;
|
|
68
|
+
const generation = this.generation;
|
|
69
|
+
let released = false;
|
|
70
|
+
return this.reschedule().then(() => ({ release: async () => {
|
|
71
|
+
if (released) return;
|
|
72
|
+
released = true;
|
|
73
|
+
if (generation !== this.generation) return;
|
|
74
|
+
this.activeLeases = Math.max(0, this.activeLeases - 1);
|
|
75
|
+
await this.reschedule();
|
|
76
|
+
} }), async (error) => {
|
|
77
|
+
released = true;
|
|
78
|
+
if (generation !== this.generation) throw error;
|
|
79
|
+
this.activeLeases = Math.max(0, this.activeLeases - 1);
|
|
80
|
+
await this.reschedule().catch(this.onBackgroundError);
|
|
81
|
+
throw error;
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/** Run a promise while holding a lease. Intended for host adapters, not EDA internals. */
|
|
85
|
+
async runWhileActive(fn) {
|
|
86
|
+
const lease = await this.acquire();
|
|
87
|
+
try {
|
|
88
|
+
return await fn();
|
|
89
|
+
} finally {
|
|
90
|
+
await lease.release();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Track an already-forked Effect fiber as active host work until it settles.
|
|
95
|
+
*
|
|
96
|
+
* Use this with `ManagedRuntime.runFork(...)` when the fiber needs an already
|
|
97
|
+
* built runtime context. The returned lease can be released manually, but it
|
|
98
|
+
* is normally released by the fiber observer.
|
|
99
|
+
*/
|
|
100
|
+
async trackFiber(fiber) {
|
|
101
|
+
const lease = await this.acquire();
|
|
102
|
+
fiber.addObserver(() => {
|
|
103
|
+
this.waitUntil(lease.release().catch((error) => {
|
|
104
|
+
this.onBackgroundError(error);
|
|
105
|
+
}));
|
|
106
|
+
});
|
|
107
|
+
if (fiber.pollUnsafe() !== void 0) await lease.release();
|
|
108
|
+
return lease;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Fork an Effect as host-tracked active work.
|
|
112
|
+
*
|
|
113
|
+
* This mirrors Effect's host-runner pattern: observe the root fiber and release
|
|
114
|
+
* the alarm lease when it settles. It deliberately does not patch Effect
|
|
115
|
+
* internals or try to classify runnable vs suspended fibers.
|
|
116
|
+
*/
|
|
117
|
+
async fork(effect) {
|
|
118
|
+
const fiber = Effect.runFork(effect);
|
|
119
|
+
await this.trackFiber(fiber);
|
|
120
|
+
return fiber;
|
|
121
|
+
}
|
|
122
|
+
/** Handle the Durable Object `alarm()` callback and re-arm while work remains. */
|
|
123
|
+
alarm() {
|
|
124
|
+
return this.reschedule();
|
|
125
|
+
}
|
|
126
|
+
/** Permanently stop the heartbeat and prevent later lease releases from re-arming it. */
|
|
127
|
+
shutdown() {
|
|
128
|
+
this.shutdownRequested = true;
|
|
129
|
+
this.generation += 1;
|
|
130
|
+
this.activeLeases = 0;
|
|
131
|
+
return this.reschedule();
|
|
132
|
+
}
|
|
133
|
+
/** Start a fresh lease generation after the host intentionally resets its durable state. */
|
|
134
|
+
restart() {
|
|
135
|
+
this.shutdownRequested = false;
|
|
136
|
+
}
|
|
137
|
+
waitUntil(promise) {
|
|
138
|
+
if (this.background !== void 0) {
|
|
139
|
+
this.background.waitUntil(promise);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
reschedule() {
|
|
144
|
+
this.scheduleTail = this.scheduleTail.catch(() => void 0).then(() => this.syncAlarm());
|
|
145
|
+
return this.scheduleTail;
|
|
146
|
+
}
|
|
147
|
+
async syncAlarm() {
|
|
148
|
+
if (this.shutdownRequested || this.activeLeases === 0) {
|
|
149
|
+
await this.storage.deleteAlarm();
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const desiredAt = this.now() + this.intervalMs;
|
|
153
|
+
const currentAt = await this.storage.getAlarm();
|
|
154
|
+
if (currentAt === null || currentAt > desiredAt) await this.storage.setAlarm(desiredAt);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/durable-object-store.ts
|
|
159
|
+
/** Safe payload ceiling below the Durable Object SQLite 2 MB value limit. */
|
|
160
|
+
/** Conservative JSON limit below the Durable Object SQLite per-value ceiling. */
|
|
161
|
+
const durableObjectSerializedJsonHardCapBytes = 15e5;
|
|
162
|
+
const ProjectionPayload = Schema.Record(Schema.String, Schema.Unknown);
|
|
163
|
+
const AdmittedCommandProjection = Schema.Struct({
|
|
164
|
+
commandId: Schema.Unknown,
|
|
165
|
+
idempotencyKey: Schema.optionalKey(Schema.Unknown)
|
|
166
|
+
});
|
|
167
|
+
/** Single squashed schema version for the current pre-release DO store. */
|
|
168
|
+
const durableObjectSessionStoreSchemaVersion = 1;
|
|
169
|
+
const jsonEncoder = new TextEncoder();
|
|
170
|
+
/**
|
|
171
|
+
* Bound one synchronous DO SQLite event-log read/decode to a small CPU and memory slice.
|
|
172
|
+
*
|
|
173
|
+
* A single logical event can already approach the per-row JSON hard cap, and logical decode may
|
|
174
|
+
* touch sidecar rows. Sixteen rows keeps worst-case page memory materially below isolate limits
|
|
175
|
+
* while still amortizing SQL cursor setup for normal small framework events. Revisit with page
|
|
176
|
+
* duration/byte telemetry before increasing.
|
|
177
|
+
*/
|
|
178
|
+
const durableObjectEventReadPageRows = 16;
|
|
179
|
+
/**
|
|
180
|
+
* Durable Object SQLite-backed implementation of the semantic `EDASessionStore`.
|
|
181
|
+
*
|
|
182
|
+
* This adapter is the only place EDA framework storage code touches DO SQL. It
|
|
183
|
+
* translates domain append intent into synchronous SQLite writes while keeping
|
|
184
|
+
* `SessionState` and runners SQL-agnostic.
|
|
185
|
+
*/
|
|
186
|
+
var DurableObjectSessionStore = class DurableObjectSessionStore {
|
|
187
|
+
/** Run the single squashed framework migration for the current pre-release schema. */
|
|
188
|
+
static migrate = (storage) => migrateDurableObjectSessionStore(storage);
|
|
189
|
+
/** Build a session-scoped store after migrations have completed. */
|
|
190
|
+
static make = ({ sessionId, storage }) => Effect.gen(function* () {
|
|
191
|
+
yield* DurableObjectSessionStore.migrate(storage);
|
|
192
|
+
return makeDurableObjectSessionStore(sessionId, storage);
|
|
193
|
+
});
|
|
194
|
+
/** Layer constructor used by the Durable Object host runtime graph. */
|
|
195
|
+
static layer = (options) => Layer.effect(EDASessionStore, DurableObjectSessionStore.make(options));
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* Create all framework-owned tables in one idempotent startup step.
|
|
199
|
+
*
|
|
200
|
+
* The project is still pre-release, so this remains a squashed version-1 schema
|
|
201
|
+
* rather than a chain of compatibility migrations.
|
|
202
|
+
*/
|
|
203
|
+
const migrateDurableObjectSessionStore = (storage) => Effect.try({
|
|
204
|
+
try: () => storage.transactionSync(() => {
|
|
205
|
+
const { sql } = storage;
|
|
206
|
+
sql.exec(`
|
|
207
|
+
CREATE TABLE IF NOT EXISTS _eda_schema_migrations (
|
|
208
|
+
id INTEGER PRIMARY KEY,
|
|
209
|
+
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
210
|
+
)
|
|
211
|
+
`);
|
|
212
|
+
if ((sql.exec("SELECT COALESCE(MAX(id), 0) AS version FROM _eda_schema_migrations").one().version ?? 0) < durableObjectSessionStoreSchemaVersion) {
|
|
213
|
+
sql.exec(`
|
|
214
|
+
CREATE TABLE IF NOT EXISTS _eda_event_log (
|
|
215
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
216
|
+
event_id TEXT NOT NULL UNIQUE,
|
|
217
|
+
namespace TEXT NOT NULL,
|
|
218
|
+
type TEXT NOT NULL,
|
|
219
|
+
schema_version INTEGER NOT NULL,
|
|
220
|
+
created_at_ms INTEGER NOT NULL,
|
|
221
|
+
trace_json TEXT NOT NULL,
|
|
222
|
+
fact_json TEXT NOT NULL
|
|
223
|
+
)
|
|
224
|
+
`);
|
|
225
|
+
sql.exec(`
|
|
226
|
+
CREATE INDEX IF NOT EXISTS _eda_event_log_namespace_type_seq_idx
|
|
227
|
+
ON _eda_event_log(namespace, type, seq)
|
|
228
|
+
`);
|
|
229
|
+
sql.exec(`
|
|
230
|
+
CREATE TABLE IF NOT EXISTS _eda_command_state (
|
|
231
|
+
command_id TEXT PRIMARY KEY,
|
|
232
|
+
admitted_seq INTEGER NOT NULL,
|
|
233
|
+
status TEXT NOT NULL,
|
|
234
|
+
idempotency_key TEXT,
|
|
235
|
+
payload_json TEXT NOT NULL
|
|
236
|
+
)
|
|
237
|
+
`);
|
|
238
|
+
sql.exec(`
|
|
239
|
+
CREATE TABLE IF NOT EXISTS _eda_command_inputs (
|
|
240
|
+
command_id TEXT PRIMARY KEY,
|
|
241
|
+
admitted_seq INTEGER NOT NULL UNIQUE,
|
|
242
|
+
payload_json TEXT NOT NULL
|
|
243
|
+
)
|
|
244
|
+
`);
|
|
245
|
+
sql.exec(`
|
|
246
|
+
CREATE INDEX IF NOT EXISTS _eda_command_state_status_seq_idx
|
|
247
|
+
ON _eda_command_state(status, admitted_seq)
|
|
248
|
+
`);
|
|
249
|
+
sql.exec(`
|
|
250
|
+
CREATE UNIQUE INDEX IF NOT EXISTS _eda_command_state_idempotency_idx
|
|
251
|
+
ON _eda_command_state(idempotency_key) WHERE idempotency_key IS NOT NULL
|
|
252
|
+
`);
|
|
253
|
+
sql.exec(`
|
|
254
|
+
CREATE TABLE IF NOT EXISTS _eda_context_messages (
|
|
255
|
+
message_id TEXT PRIMARY KEY,
|
|
256
|
+
context_seq INTEGER NOT NULL UNIQUE,
|
|
257
|
+
payload_json TEXT NOT NULL
|
|
258
|
+
)
|
|
259
|
+
`);
|
|
260
|
+
sql.exec(`
|
|
261
|
+
CREATE INDEX IF NOT EXISTS _eda_context_messages_context_seq_idx
|
|
262
|
+
ON _eda_context_messages(context_seq)
|
|
263
|
+
`);
|
|
264
|
+
sql.exec(`
|
|
265
|
+
CREATE TABLE IF NOT EXISTS _eda_context_summaries (
|
|
266
|
+
summary_id TEXT PRIMARY KEY,
|
|
267
|
+
created_seq INTEGER NOT NULL UNIQUE,
|
|
268
|
+
payload_json TEXT NOT NULL
|
|
269
|
+
)
|
|
270
|
+
`);
|
|
271
|
+
sql.exec(`
|
|
272
|
+
CREATE INDEX IF NOT EXISTS _eda_context_summaries_created_seq_idx
|
|
273
|
+
ON _eda_context_summaries(created_seq)
|
|
274
|
+
`);
|
|
275
|
+
sql.exec(`
|
|
276
|
+
CREATE TABLE IF NOT EXISTS _eda_reducer_checkpoints (
|
|
277
|
+
reducer_name TEXT PRIMARY KEY,
|
|
278
|
+
schema_version INTEGER NOT NULL,
|
|
279
|
+
through_seq INTEGER NOT NULL,
|
|
280
|
+
payload_json TEXT NOT NULL,
|
|
281
|
+
updated_at_ms INTEGER NOT NULL
|
|
282
|
+
)
|
|
283
|
+
`);
|
|
284
|
+
sql.exec(`
|
|
285
|
+
CREATE TABLE IF NOT EXISTS _eda_sink_cursors (
|
|
286
|
+
sink_name TEXT PRIMARY KEY,
|
|
287
|
+
after_seq INTEGER NOT NULL,
|
|
288
|
+
payload_json TEXT NOT NULL
|
|
289
|
+
)
|
|
290
|
+
`);
|
|
291
|
+
sql.exec("INSERT INTO _eda_schema_migrations (id) VALUES (?)", durableObjectSessionStoreSchemaVersion);
|
|
292
|
+
}
|
|
293
|
+
}),
|
|
294
|
+
catch: (error) => durableStoreError("migrating DurableObjectSessionStore", error)
|
|
295
|
+
});
|
|
296
|
+
/**
|
|
297
|
+
* Interpret the semantic store API with native DO SQLite.
|
|
298
|
+
*
|
|
299
|
+
* All writes that affect durable ordering happen inside `transactionSync`; replay
|
|
300
|
+
* and lookup reads stay synchronous SQL wrapped in Effect boundaries.
|
|
301
|
+
*/
|
|
302
|
+
const makeDurableObjectSessionStore = (sessionId, storage) => {
|
|
303
|
+
const { sql } = storage;
|
|
304
|
+
const ensureSession = (event) => {
|
|
305
|
+
if (event.sessionId !== sessionId) throw new Error(`DurableObjectSessionStore is scoped to session ${sessionId}; received ${event.sessionId}`);
|
|
306
|
+
};
|
|
307
|
+
/**
|
|
308
|
+
* Insert one append entry or return its existing idempotent event position.
|
|
309
|
+
*
|
|
310
|
+
* The event row is the sequence allocator. Artifact/projection writes happen
|
|
311
|
+
* only for newly inserted events, preventing duplicate appends from advancing
|
|
312
|
+
* body rows or metadata.
|
|
313
|
+
*/
|
|
314
|
+
const insertOrRead = (entry) => {
|
|
315
|
+
const { event } = entry;
|
|
316
|
+
ensureSession(event);
|
|
317
|
+
const existing = readCommittedByEventIdOptional(sql, sessionId, event.eventId);
|
|
318
|
+
if (existing !== void 0) return existing;
|
|
319
|
+
const encoded = encodeEventLogRow(event);
|
|
320
|
+
sql.exec(`
|
|
321
|
+
INSERT INTO _eda_event_log (
|
|
322
|
+
event_id,
|
|
323
|
+
namespace,
|
|
324
|
+
type,
|
|
325
|
+
schema_version,
|
|
326
|
+
created_at_ms,
|
|
327
|
+
trace_json,
|
|
328
|
+
fact_json
|
|
329
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
330
|
+
`, encoded.eventId, encoded.namespace, encoded.type, encoded.schemaVersion, encoded.createdAtMs, encoded.traceJson, encoded.factJson);
|
|
331
|
+
const row = readEventLogRowByEventId(sql, event.eventId);
|
|
332
|
+
applySynchronousProjections(sql, entry, SequenceNumber.make(row.seq), encoded.factJson);
|
|
333
|
+
return rowToCommittedDurableEvent(sql, row, sessionId);
|
|
334
|
+
};
|
|
335
|
+
/** Execute an entire append batch as one synchronous SQLite transaction. */
|
|
336
|
+
const append = (batch) => Effect.try({
|
|
337
|
+
try: () => storage.transactionSync(() => batch.entries.map(insertOrRead)),
|
|
338
|
+
catch: (error) => durableStoreError("appending DurableObjectSessionStore batch", error)
|
|
339
|
+
}).pipe(Effect.tap((committed) => annotateEdaSpan(committedBatchAttributes(committed))));
|
|
340
|
+
return {
|
|
341
|
+
append,
|
|
342
|
+
eventsAfter: (afterSeq) => makeCommittedEventStream(sql, sessionId, afterSeq),
|
|
343
|
+
loadCommittedEventsBySeq: (seqs) => Effect.try({
|
|
344
|
+
try: () => uniqueSequenceNumbers(seqs).sort((left, right) => left - right).map((seq) => readCommittedBySeq(sql, sessionId, seq)),
|
|
345
|
+
catch: (error) => durableStoreError("loading DurableObjectSessionStore events by seq", error)
|
|
346
|
+
}),
|
|
347
|
+
findCommandAdmission: (input) => Effect.try({
|
|
348
|
+
try: () => {
|
|
349
|
+
const row = findCommandAdmissionRow(sql, input.commandId, input.idempotencyKey);
|
|
350
|
+
return row === void 0 ? void 0 : readCommittedBySeq(sql, sessionId, row.admitted_seq);
|
|
351
|
+
},
|
|
352
|
+
catch: (error) => durableStoreError("finding command admission", error)
|
|
353
|
+
}),
|
|
354
|
+
loadSummaryArtifact: (summaryId) => Effect.try({
|
|
355
|
+
try: () => readSummaryPayloadOptional(sql, summaryId),
|
|
356
|
+
catch: (error) => durableStoreError("loading DurableObjectSessionStore summary", error)
|
|
357
|
+
}),
|
|
358
|
+
loadReducerCheckpoint: (name) => Effect.try({
|
|
359
|
+
try: () => readReducerCheckpoint(sql, name),
|
|
360
|
+
catch: (error) => durableStoreError(`loading DurableObjectSessionStore reducer checkpoint ${name}`, error)
|
|
361
|
+
}),
|
|
362
|
+
saveReducerCheckpoint: (checkpoint) => Effect.try({
|
|
363
|
+
try: () => writeReducerCheckpoint(sql, checkpoint),
|
|
364
|
+
catch: (error) => durableStoreError(`saving DurableObjectSessionStore reducer checkpoint ${checkpoint.name}`, error)
|
|
365
|
+
}),
|
|
366
|
+
saveReducerCheckpoints: (checkpoints) => Effect.try({
|
|
367
|
+
try: () => storage.transactionSync(() => checkpoints.forEach((checkpoint) => writeReducerCheckpoint(sql, checkpoint))),
|
|
368
|
+
catch: (error) => durableStoreError("saving DurableObjectSessionStore reducer checkpoints", error)
|
|
369
|
+
})
|
|
370
|
+
};
|
|
371
|
+
};
|
|
372
|
+
const makeCommittedEventStream = (sql, sessionId, afterSeq) => Stream.fromPull(Effect.sync(() => {
|
|
373
|
+
let cursor = {
|
|
374
|
+
afterSeq,
|
|
375
|
+
throughSeq: void 0
|
|
376
|
+
};
|
|
377
|
+
let done = false;
|
|
378
|
+
return Effect.gen(function* () {
|
|
379
|
+
if (done) return yield* Cause.done();
|
|
380
|
+
yield* Effect.yieldNow;
|
|
381
|
+
const page = yield* readCommittedEventPage(sql, sessionId, cursor);
|
|
382
|
+
if (page.events.length === 0) {
|
|
383
|
+
done = true;
|
|
384
|
+
return yield* Cause.done();
|
|
385
|
+
}
|
|
386
|
+
if (Option.isSome(page.next)) cursor = page.next.value;
|
|
387
|
+
else done = true;
|
|
388
|
+
return page.events;
|
|
389
|
+
});
|
|
390
|
+
}));
|
|
391
|
+
const readCommittedEventPage = (sql, sessionId, cursor) => Effect.try({
|
|
392
|
+
try: () => {
|
|
393
|
+
const throughSeq = cursor.throughSeq ?? readEventLogHead(sql);
|
|
394
|
+
if (cursor.afterSeq >= throughSeq) return {
|
|
395
|
+
events: [],
|
|
396
|
+
next: Option.none()
|
|
397
|
+
};
|
|
398
|
+
const events = sql.exec(`
|
|
399
|
+
SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
|
|
400
|
+
FROM _eda_event_log
|
|
401
|
+
WHERE seq > ? AND seq <= ?
|
|
402
|
+
ORDER BY seq ASC
|
|
403
|
+
LIMIT ?
|
|
404
|
+
`, cursor.afterSeq, throughSeq, durableObjectEventReadPageRows).toArray().map((row) => rowToCommittedDurableEvent(sql, row, sessionId));
|
|
405
|
+
const lastSeq = events.at(-1)?.position.seq ?? cursor.afterSeq;
|
|
406
|
+
return {
|
|
407
|
+
events,
|
|
408
|
+
next: lastSeq < throughSeq ? Option.some({
|
|
409
|
+
afterSeq: lastSeq,
|
|
410
|
+
throughSeq
|
|
411
|
+
}) : Option.none()
|
|
412
|
+
};
|
|
413
|
+
},
|
|
414
|
+
catch: (error) => durableStoreError("replaying DurableObjectSessionStore events", error)
|
|
415
|
+
});
|
|
416
|
+
const readEventLogHead = (sql) => SequenceNumber.make(sql.exec(`
|
|
417
|
+
SELECT COALESCE(MAX(seq), 0) AS head
|
|
418
|
+
FROM _eda_event_log
|
|
419
|
+
`).one().head ?? 0);
|
|
420
|
+
const uniqueSequenceNumbers = (seqs) => Array.from(new Set(seqs.map((seq) => Number(seq)))).map((seq) => SequenceNumber.make(seq));
|
|
421
|
+
const readEventLogRowByEventId = (sql, eventId) => sql.exec(`
|
|
422
|
+
SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
|
|
423
|
+
FROM _eda_event_log
|
|
424
|
+
WHERE event_id = ?
|
|
425
|
+
`, eventId).one();
|
|
426
|
+
const readCommittedByEventIdOptional = (sql, sessionId, eventId) => {
|
|
427
|
+
const row = sql.exec(`
|
|
428
|
+
SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
|
|
429
|
+
FROM _eda_event_log
|
|
430
|
+
WHERE event_id = ?
|
|
431
|
+
`, eventId).toArray()[0];
|
|
432
|
+
return row === void 0 ? void 0 : rowToCommittedDurableEvent(sql, row, sessionId);
|
|
433
|
+
};
|
|
434
|
+
const readReducerCheckpoint = (sql, name) => {
|
|
435
|
+
const row = sql.exec(`
|
|
436
|
+
SELECT reducer_name, schema_version, through_seq, payload_json, updated_at_ms
|
|
437
|
+
FROM _eda_reducer_checkpoints
|
|
438
|
+
WHERE reducer_name = ?
|
|
439
|
+
`, name).toArray()[0];
|
|
440
|
+
return row === void 0 ? void 0 : {
|
|
441
|
+
name: row.reducer_name,
|
|
442
|
+
schemaVersion: row.schema_version,
|
|
443
|
+
throughSeq: SequenceNumber.make(row.through_seq),
|
|
444
|
+
payload: JSON.parse(row.payload_json),
|
|
445
|
+
updatedAtMs: row.updated_at_ms
|
|
446
|
+
};
|
|
447
|
+
};
|
|
448
|
+
const writeReducerCheckpoint = (sql, checkpoint) => {
|
|
449
|
+
sql.exec(`
|
|
450
|
+
INSERT INTO _eda_reducer_checkpoints (
|
|
451
|
+
reducer_name,
|
|
452
|
+
schema_version,
|
|
453
|
+
through_seq,
|
|
454
|
+
payload_json,
|
|
455
|
+
updated_at_ms
|
|
456
|
+
) VALUES (?, ?, ?, ?, ?)
|
|
457
|
+
ON CONFLICT(reducer_name) DO UPDATE SET
|
|
458
|
+
schema_version = excluded.schema_version,
|
|
459
|
+
through_seq = excluded.through_seq,
|
|
460
|
+
payload_json = excluded.payload_json,
|
|
461
|
+
updated_at_ms = excluded.updated_at_ms
|
|
462
|
+
`, checkpoint.name, checkpoint.schemaVersion, checkpoint.throughSeq, stringifyJsonForColumn(checkpoint.payload, "_eda_reducer_checkpoints.payload_json"), checkpoint.updatedAtMs);
|
|
463
|
+
};
|
|
464
|
+
const readMessagePayloadByContextSeq = (sql, contextSeq) => {
|
|
465
|
+
const message = sql.exec(`
|
|
466
|
+
SELECT context_seq, payload_json
|
|
467
|
+
FROM _eda_context_messages
|
|
468
|
+
WHERE context_seq = ?
|
|
469
|
+
`, contextSeq).toArray()[0];
|
|
470
|
+
if (message === void 0) throw new Error(`Context message at seq ${contextSeq} missing from _eda_context_messages`);
|
|
471
|
+
return message;
|
|
472
|
+
};
|
|
473
|
+
const readCommittedBySeq = (sql, sessionId, seq) => {
|
|
474
|
+
return rowToCommittedDurableEvent(sql, sql.exec(`
|
|
475
|
+
SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
|
|
476
|
+
FROM _eda_event_log
|
|
477
|
+
WHERE seq = ?
|
|
478
|
+
`, seq).one(), sessionId);
|
|
479
|
+
};
|
|
480
|
+
const rowToCommittedDurableEvent = (sql, row, sessionId) => CommittedDurableEvent.make({
|
|
481
|
+
position: durablePosition(SequenceNumber.make(row.seq)),
|
|
482
|
+
event: decodeDurableEvent({
|
|
483
|
+
namespace: row.namespace,
|
|
484
|
+
type: row.type,
|
|
485
|
+
schemaVersion: row.schema_version,
|
|
486
|
+
durability: "durable",
|
|
487
|
+
eventId: row.event_id,
|
|
488
|
+
sessionId,
|
|
489
|
+
createdAtMs: row.created_at_ms,
|
|
490
|
+
trace: JSON.parse(row.trace_json),
|
|
491
|
+
payload: readLogicalPayload(sql, row)
|
|
492
|
+
})
|
|
493
|
+
});
|
|
494
|
+
const decodeDurableEvent = (input) => {
|
|
495
|
+
const event = Schema.decodeUnknownSync(DurableEventEnvelope)(input);
|
|
496
|
+
return event.namespace === effectDurableAgentNamespace ? decodeUnknownEDADurableEventSync(event) : event;
|
|
497
|
+
};
|
|
498
|
+
const encodeEventLogRow = (event) => {
|
|
499
|
+
const encoded = Schema.encodeSync(DurableEventEnvelope)(event);
|
|
500
|
+
return {
|
|
501
|
+
eventId: encoded.eventId,
|
|
502
|
+
namespace: encoded.namespace,
|
|
503
|
+
type: encoded.type,
|
|
504
|
+
schemaVersion: encoded.schemaVersion,
|
|
505
|
+
createdAtMs: encoded.createdAtMs,
|
|
506
|
+
traceJson: stringifyJsonForColumn(encoded.trace, "_eda_event_log.trace_json"),
|
|
507
|
+
factJson: stringifyJsonForColumn(eventLogFactPayload(encoded.namespace, encoded.type, encoded.payload), "_eda_event_log.fact_json")
|
|
508
|
+
};
|
|
509
|
+
};
|
|
510
|
+
const readLogicalPayload = (sql, row) => {
|
|
511
|
+
if (row.namespace !== effectDurableAgentNamespace) return JSON.parse(row.fact_json);
|
|
512
|
+
if (row.type === commandAdmittedEventType) return { command: readCommandInputPayload(sql, readCommandIdFromFact(row)) };
|
|
513
|
+
if (contextMessageEventTypes.has(row.type)) return JSON.parse(readMessagePayloadByContextSeq(sql, row.seq).payload_json);
|
|
514
|
+
if (row.type === summaryCreatedEventType) return {
|
|
515
|
+
...JSON.parse(row.fact_json),
|
|
516
|
+
summary: readSummaryPayloadFromCreatedSeq(sql, row.seq)
|
|
517
|
+
};
|
|
518
|
+
return JSON.parse(row.fact_json);
|
|
519
|
+
};
|
|
520
|
+
const eventLogFactPayload = (namespace, type, payload) => {
|
|
521
|
+
if (namespace !== effectDurableAgentNamespace || typeof payload !== "object" || payload === null) return payload;
|
|
522
|
+
const record = payload;
|
|
523
|
+
switch (type) {
|
|
524
|
+
case commandAdmittedEventType: return { command: commandFact(record.command) };
|
|
525
|
+
case systemMessageCommittedEventType: return pick(record, ["messageId"]);
|
|
526
|
+
case userMessageCommittedEventType: return pick(record, ["commandId", "messageId"]);
|
|
527
|
+
case steeringMessageQueuedEventType: return pick(record, [
|
|
528
|
+
"commandId",
|
|
529
|
+
"messageId",
|
|
530
|
+
"runId"
|
|
531
|
+
]);
|
|
532
|
+
case assistantMessageCommittedEventType:
|
|
533
|
+
case assistantMessageImportedEventType: return pick(record, [
|
|
534
|
+
"messageId",
|
|
535
|
+
"runId",
|
|
536
|
+
"turnId",
|
|
537
|
+
"inferenceId"
|
|
538
|
+
]);
|
|
539
|
+
case assistantPartialCommittedEventType: return pick(record, [
|
|
540
|
+
"messageId",
|
|
541
|
+
"runId",
|
|
542
|
+
"turnId",
|
|
543
|
+
"inferenceId",
|
|
544
|
+
"reason"
|
|
545
|
+
]);
|
|
546
|
+
case summaryCreatedEventType: return pick(record, [
|
|
547
|
+
"compactionId",
|
|
548
|
+
"summaryId",
|
|
549
|
+
"sourceFromSeq",
|
|
550
|
+
"sourceToSeq"
|
|
551
|
+
]);
|
|
552
|
+
default: return payload;
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
const commandFact = (command) => {
|
|
556
|
+
if (typeof command !== "object" || command === null) return command;
|
|
557
|
+
const record = command;
|
|
558
|
+
return record._tag === "SubmitMessage" ? pick(record, [
|
|
559
|
+
"_tag",
|
|
560
|
+
"commandId",
|
|
561
|
+
"disposition",
|
|
562
|
+
"idempotencyKey"
|
|
563
|
+
]) : command;
|
|
564
|
+
};
|
|
565
|
+
const pick = (record, keys) => {
|
|
566
|
+
const out = {};
|
|
567
|
+
for (const key of keys) if (record[key] !== void 0) out[key] = record[key];
|
|
568
|
+
return out;
|
|
569
|
+
};
|
|
570
|
+
const readCommandIdFromFact = (row) => {
|
|
571
|
+
const commandId = JSON.parse(row.fact_json).command?.commandId;
|
|
572
|
+
if (typeof commandId !== "string") throw new Error(`CommandAdmitted fact at seq ${row.seq} missing command.commandId`);
|
|
573
|
+
return commandId;
|
|
574
|
+
};
|
|
575
|
+
const readCommandInputPayload = (sql, commandId) => {
|
|
576
|
+
const row = sql.exec(`
|
|
577
|
+
SELECT payload_json
|
|
578
|
+
FROM _eda_command_inputs
|
|
579
|
+
WHERE command_id = ?
|
|
580
|
+
`, commandId).toArray()[0];
|
|
581
|
+
if (row === void 0) throw new Error(`Command input ${commandId} missing from _eda_command_inputs`);
|
|
582
|
+
return JSON.parse(row.payload_json);
|
|
583
|
+
};
|
|
584
|
+
const readSummaryPayloadOptional = (sql, summaryId) => {
|
|
585
|
+
const row = sql.exec(`
|
|
586
|
+
SELECT payload_json
|
|
587
|
+
FROM _eda_context_summaries
|
|
588
|
+
WHERE summary_id = ?
|
|
589
|
+
`, summaryId).toArray()[0];
|
|
590
|
+
return row === void 0 ? void 0 : Schema.decodeUnknownSync(CompactionSummaryArtifact)(JSON.parse(row.payload_json));
|
|
591
|
+
};
|
|
592
|
+
const readSummaryPayloadFromCreatedSeq = (sql, createdSeq) => {
|
|
593
|
+
const row = sql.exec(`
|
|
594
|
+
SELECT payload_json
|
|
595
|
+
FROM _eda_context_summaries
|
|
596
|
+
WHERE created_seq = ?
|
|
597
|
+
`, createdSeq).toArray()[0];
|
|
598
|
+
if (row === void 0) throw new Error(`SummaryCreated at seq ${createdSeq} missing from _eda_context_summaries`);
|
|
599
|
+
return JSON.parse(row.payload_json);
|
|
600
|
+
};
|
|
601
|
+
/**
|
|
602
|
+
* Maintain bounded storage projections in the same transaction as the event.
|
|
603
|
+
*
|
|
604
|
+
* These rows are durability aids, not a second source of lifecycle truth: event
|
|
605
|
+
* order still comes from `_eda_event_log.seq`, while projections make command
|
|
606
|
+
* lookup and body-sidecar hydration bounded.
|
|
607
|
+
*/
|
|
608
|
+
const applySynchronousProjections = (sql, entry, seq, factJson) => {
|
|
609
|
+
const { event } = entry;
|
|
610
|
+
if (event.namespace !== effectDurableAgentNamespace) return;
|
|
611
|
+
writeCommandProjection(sql, event, seq, factJson);
|
|
612
|
+
writeCommandInputProjection(sql, event, seq);
|
|
613
|
+
writeMessageProjection(sql, event, seq);
|
|
614
|
+
writeSummaryProjection(sql, event, seq);
|
|
615
|
+
writeContextRebaseProjection(sql, event, seq);
|
|
616
|
+
};
|
|
617
|
+
const writeCommandProjection = (sql, event, seq, factJson) => {
|
|
618
|
+
const payload = Schema.decodeUnknownSync(ProjectionPayload)(event.payload);
|
|
619
|
+
switch (event.type) {
|
|
620
|
+
case commandAdmittedEventType: {
|
|
621
|
+
const command = Schema.decodeUnknownSync(AdmittedCommandProjection)(payload.command);
|
|
622
|
+
const commandId = command.commandId;
|
|
623
|
+
if (commandId === void 0) throw new Error("CommandAdmitted missing command.commandId");
|
|
624
|
+
sql.exec(`
|
|
625
|
+
INSERT INTO _eda_command_state (
|
|
626
|
+
command_id,
|
|
627
|
+
admitted_seq,
|
|
628
|
+
status,
|
|
629
|
+
idempotency_key,
|
|
630
|
+
payload_json
|
|
631
|
+
) VALUES (?, ?, ?, ?, ?)
|
|
632
|
+
ON CONFLICT(command_id) DO UPDATE SET
|
|
633
|
+
admitted_seq = excluded.admitted_seq,
|
|
634
|
+
status = excluded.status,
|
|
635
|
+
idempotency_key = excluded.idempotency_key,
|
|
636
|
+
payload_json = excluded.payload_json
|
|
637
|
+
`, commandId, seq, "admitted", command.idempotencyKey ?? null, factJson);
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
case commandStartedEventType:
|
|
641
|
+
writeCommandStatus(sql, payload.commandId, seq, "started", factJson);
|
|
642
|
+
return;
|
|
643
|
+
case commandCompletedEventType:
|
|
644
|
+
writeCommandStatus(sql, payload.commandId, seq, "completed", factJson);
|
|
645
|
+
return;
|
|
646
|
+
case commandFailedEventType:
|
|
647
|
+
writeCommandStatus(sql, payload.commandId, seq, "failed", factJson);
|
|
648
|
+
return;
|
|
649
|
+
case commandCancelledEventType:
|
|
650
|
+
writeCommandStatus(sql, payload.commandId, seq, "cancelled", factJson);
|
|
651
|
+
return;
|
|
652
|
+
default: return;
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
const writeCommandStatus = (sql, commandId, seq, status, payloadJson) => {
|
|
656
|
+
if (commandId === void 0) throw new Error(`${status} command event missing commandId`);
|
|
657
|
+
sql.exec(`
|
|
658
|
+
INSERT INTO _eda_command_state (
|
|
659
|
+
command_id,
|
|
660
|
+
admitted_seq,
|
|
661
|
+
status,
|
|
662
|
+
idempotency_key,
|
|
663
|
+
payload_json
|
|
664
|
+
) VALUES (?, ?, ?, NULL, ?)
|
|
665
|
+
ON CONFLICT(command_id) DO UPDATE SET
|
|
666
|
+
status = excluded.status,
|
|
667
|
+
payload_json = excluded.payload_json
|
|
668
|
+
`, commandId, seq, status, payloadJson);
|
|
669
|
+
};
|
|
670
|
+
const writeCommandInputProjection = (sql, event, seq) => {
|
|
671
|
+
if (event.type !== commandAdmittedEventType) return;
|
|
672
|
+
const command = Schema.encodeSync(DurableEventEnvelope)(event).payload.command;
|
|
673
|
+
const commandId = command?.commandId;
|
|
674
|
+
if (commandId === void 0) throw new Error("CommandAdmitted missing command.commandId");
|
|
675
|
+
sql.exec(`
|
|
676
|
+
INSERT INTO _eda_command_inputs (
|
|
677
|
+
command_id,
|
|
678
|
+
admitted_seq,
|
|
679
|
+
payload_json
|
|
680
|
+
) VALUES (?, ?, ?)
|
|
681
|
+
ON CONFLICT(command_id) DO UPDATE SET
|
|
682
|
+
admitted_seq = excluded.admitted_seq,
|
|
683
|
+
payload_json = excluded.payload_json
|
|
684
|
+
`, commandId, seq, stringifyJsonForColumn(command, "_eda_command_inputs.payload_json"));
|
|
685
|
+
};
|
|
686
|
+
const contextMessageEventTypes = new Set([
|
|
687
|
+
systemMessageCommittedEventType,
|
|
688
|
+
userMessageCommittedEventType,
|
|
689
|
+
steeringMessageQueuedEventType,
|
|
690
|
+
assistantMessageCommittedEventType,
|
|
691
|
+
assistantMessageImportedEventType,
|
|
692
|
+
assistantPartialCommittedEventType
|
|
693
|
+
]);
|
|
694
|
+
/** Persist model-visible message bodies with the seq that exposed them to context. */
|
|
695
|
+
const writeMessageProjection = (sql, event, seq) => {
|
|
696
|
+
if (!contextMessageEventTypes.has(event.type)) return;
|
|
697
|
+
const encoded = Schema.encodeSync(DurableEventEnvelope)(event);
|
|
698
|
+
const messageId = encoded.payload.messageId;
|
|
699
|
+
if (messageId === void 0) throw new Error(`${event.type} missing messageId`);
|
|
700
|
+
sql.exec(`
|
|
701
|
+
INSERT INTO _eda_context_messages (
|
|
702
|
+
message_id,
|
|
703
|
+
context_seq,
|
|
704
|
+
payload_json
|
|
705
|
+
) VALUES (?, ?, ?)
|
|
706
|
+
ON CONFLICT(message_id) DO UPDATE SET
|
|
707
|
+
context_seq = excluded.context_seq,
|
|
708
|
+
payload_json = excluded.payload_json
|
|
709
|
+
`, messageId, seq, stringifyJsonForColumn(encoded.payload, "_eda_context_messages.payload_json"));
|
|
710
|
+
};
|
|
711
|
+
/**
|
|
712
|
+
* Persist a cumulative summary artifact without making it the active context.
|
|
713
|
+
*
|
|
714
|
+
* `ContextRebased` selects summaries in the framework reduced-state checkpoint;
|
|
715
|
+
* failed compactions can leave orphaned summaries without changing future context.
|
|
716
|
+
*/
|
|
717
|
+
const writeSummaryProjection = (sql, event, seq) => {
|
|
718
|
+
if (event.type !== summaryCreatedEventType) return;
|
|
719
|
+
const payload = event.payload;
|
|
720
|
+
const summaryId = payload.summaryId;
|
|
721
|
+
if (summaryId === void 0) throw new Error("SummaryCreated missing summaryId");
|
|
722
|
+
if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
|
|
723
|
+
const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
|
|
724
|
+
if (summary.summaryId !== summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
|
|
725
|
+
if (summary.compactionId !== payload.compactionId) throw new Error("SummaryCreated compactionId does not match summary payload");
|
|
726
|
+
sql.exec(`
|
|
727
|
+
INSERT INTO _eda_context_summaries (
|
|
728
|
+
summary_id,
|
|
729
|
+
created_seq,
|
|
730
|
+
payload_json
|
|
731
|
+
) VALUES (?, ?, ?)
|
|
732
|
+
ON CONFLICT(summary_id) DO UPDATE SET
|
|
733
|
+
created_seq = excluded.created_seq,
|
|
734
|
+
payload_json = excluded.payload_json
|
|
735
|
+
`, summaryId, seq, stringifyJsonForColumn(summary, "_eda_context_summaries.payload_json"));
|
|
736
|
+
};
|
|
737
|
+
/** Validate that `ContextRebased` points at a committed summary sidecar. */
|
|
738
|
+
const writeContextRebaseProjection = (sql, event, _seq) => {
|
|
739
|
+
if (event.type !== contextRebasedEventType) return;
|
|
740
|
+
const payload = event.payload;
|
|
741
|
+
if (payload.summaryId === void 0) throw new Error("ContextRebased missing summaryId");
|
|
742
|
+
const summary = readSummaryPayloadOptional(sql, SummaryId.make(String(payload.summaryId)));
|
|
743
|
+
if (summary === void 0) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
|
|
744
|
+
if (summary.compactionId !== payload.compactionId) throw new Error("ContextRebased summary compactionId does not match event payload");
|
|
745
|
+
if (summary.retainedFromContextSeq !== payload.retainedFromContextSeq) throw new Error("ContextRebased retained cursor does not match summary payload");
|
|
746
|
+
};
|
|
747
|
+
/**
|
|
748
|
+
* Lookup prior command admission through `_eda_command_state` instead of genesis replay.
|
|
749
|
+
*
|
|
750
|
+
* Idempotency key wins over explicit command id so caller-owned retry keys remain
|
|
751
|
+
* the stable dedupe surface for external ingress.
|
|
752
|
+
*/
|
|
753
|
+
const findCommandAdmissionRow = (sql, commandId, idempotencyKey) => {
|
|
754
|
+
if (idempotencyKey !== void 0) {
|
|
755
|
+
const row = sql.exec(`
|
|
756
|
+
SELECT admitted_seq
|
|
757
|
+
FROM _eda_command_state
|
|
758
|
+
WHERE idempotency_key = ?
|
|
759
|
+
`, idempotencyKey).toArray()[0];
|
|
760
|
+
if (row !== void 0) return row;
|
|
761
|
+
}
|
|
762
|
+
if (commandId === void 0) return;
|
|
763
|
+
return sql.exec(`
|
|
764
|
+
SELECT admitted_seq
|
|
765
|
+
FROM _eda_command_state
|
|
766
|
+
WHERE command_id = ?
|
|
767
|
+
`, commandId).toArray()[0];
|
|
768
|
+
};
|
|
769
|
+
/** Serialize and size-check one JSON column before it reaches DO SQLite. */
|
|
770
|
+
const stringifyJsonForColumn = (value, column) => {
|
|
771
|
+
const json = JSON.stringify(value);
|
|
772
|
+
if (json === void 0) throw new Error(`${column} value is not JSON serializable`);
|
|
773
|
+
const bytes = jsonEncoder.encode(json).byteLength;
|
|
774
|
+
if (bytes > 15e5) throw new Error(`${column} serialized JSON is ${bytes} bytes; hard cap is ${durableObjectSerializedJsonHardCapBytes} bytes`);
|
|
775
|
+
return json;
|
|
776
|
+
};
|
|
777
|
+
const durableStoreError = (operation, cause) => new EDASessionStoreError({ message: cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}` });
|
|
778
|
+
//#endregion
|
|
779
|
+
//#region src/durable-object-sink-checkpoints.ts
|
|
780
|
+
/**
|
|
781
|
+
* Durable Object SQLite adapter for EDA sink checkpoints.
|
|
782
|
+
*
|
|
783
|
+
* Checkpoint SQL stays in the host layer for the same reason session storage SQL
|
|
784
|
+
* does: framework sink code should depend on checkpoint semantics, not table access.
|
|
785
|
+
*/
|
|
786
|
+
var DurableObjectSinkCheckpointStore = class DurableObjectSinkCheckpointStore {
|
|
787
|
+
/** Ensure the fixed `_eda_sink_cursors` table exists during host startup. */
|
|
788
|
+
static migrate = (storage) => migrateSinkCheckpointStore(storage);
|
|
789
|
+
/** Build the semantic checkpoint store over native DO SQLite. */
|
|
790
|
+
static make = (storage) => makeDurableObjectSinkCheckpointStore(storage);
|
|
791
|
+
static layer = (storage) => Layer.effect(SinkCheckpointStore, DurableObjectSinkCheckpointStore.make(storage));
|
|
792
|
+
};
|
|
793
|
+
/** Create the sink checkpoint table inside the current EDA storage schema. */
|
|
794
|
+
const migrateSinkCheckpointStore = (storage) => Effect.try({
|
|
795
|
+
try: () => {
|
|
796
|
+
storage.sql.exec(`
|
|
797
|
+
CREATE TABLE IF NOT EXISTS _eda_sink_cursors (
|
|
798
|
+
sink_name TEXT PRIMARY KEY,
|
|
799
|
+
after_seq INTEGER NOT NULL,
|
|
800
|
+
payload_json TEXT NOT NULL
|
|
801
|
+
)
|
|
802
|
+
`);
|
|
803
|
+
},
|
|
804
|
+
catch: (error) => sinkCheckpointError("migrating SinkCheckpointStore", error)
|
|
805
|
+
});
|
|
806
|
+
/** Interpret checkpoint load/save/commit with idempotent upserts. */
|
|
807
|
+
const makeDurableObjectSinkCheckpointStore = (storage) => Effect.gen(function* () {
|
|
808
|
+
yield* DurableObjectSinkCheckpointStore.migrate(storage);
|
|
809
|
+
const { sql } = storage;
|
|
810
|
+
return {
|
|
811
|
+
load: (sinkName) => Effect.try({
|
|
812
|
+
try: () => {
|
|
813
|
+
const row = sql.exec(`SELECT after_seq, payload_json FROM _eda_sink_cursors WHERE sink_name = ?`, sinkName).toArray()[0];
|
|
814
|
+
return row === void 0 ? {
|
|
815
|
+
afterSeq: SequenceNumber.make(0),
|
|
816
|
+
payload: void 0
|
|
817
|
+
} : {
|
|
818
|
+
afterSeq: SequenceNumber.make(row.after_seq),
|
|
819
|
+
payload: JSON.parse(row.payload_json)
|
|
820
|
+
};
|
|
821
|
+
},
|
|
822
|
+
catch: (error) => sinkCheckpointError("reading sink checkpoint", error)
|
|
823
|
+
}),
|
|
824
|
+
saveState: (sinkName, payload) => Effect.try({
|
|
825
|
+
try: () => {
|
|
826
|
+
sql.exec(`
|
|
827
|
+
INSERT INTO _eda_sink_cursors (sink_name, after_seq, payload_json)
|
|
828
|
+
VALUES (?, 0, ?)
|
|
829
|
+
ON CONFLICT(sink_name) DO UPDATE SET
|
|
830
|
+
payload_json = excluded.payload_json
|
|
831
|
+
`, sinkName, JSON.stringify(payload));
|
|
832
|
+
},
|
|
833
|
+
catch: (error) => sinkCheckpointError("saving sink checkpoint state", error)
|
|
834
|
+
}),
|
|
835
|
+
commit: (sinkName, afterSeq, payload) => Effect.try({
|
|
836
|
+
try: () => {
|
|
837
|
+
sql.exec(`
|
|
838
|
+
INSERT INTO _eda_sink_cursors (sink_name, after_seq, payload_json)
|
|
839
|
+
VALUES (?, ?, ?)
|
|
840
|
+
ON CONFLICT(sink_name) DO UPDATE SET
|
|
841
|
+
after_seq = excluded.after_seq,
|
|
842
|
+
payload_json = excluded.payload_json
|
|
843
|
+
`, sinkName, afterSeq, JSON.stringify(payload ?? { updatedAtMs: Date.now() }));
|
|
844
|
+
},
|
|
845
|
+
catch: (error) => sinkCheckpointError("committing sink checkpoint", error)
|
|
846
|
+
})
|
|
847
|
+
};
|
|
848
|
+
});
|
|
849
|
+
const sinkCheckpointError = (operation, cause) => new EDASessionStoreError({ message: cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}` });
|
|
850
|
+
//#endregion
|
|
851
|
+
//#region src/durable-object-runtime.ts
|
|
852
|
+
const resolveRuntimeFactory = (value, sessionId) => typeof value === "function" ? value({ sessionId }) : value;
|
|
853
|
+
/**
|
|
854
|
+
* Compose the full EDA service graph for one raw Durable Object session.
|
|
855
|
+
*
|
|
856
|
+
* The layer is intentionally host-owned: tests can pass a fake model layer,
|
|
857
|
+
* while the Worker host can pass a provider-backed layer from Env.
|
|
858
|
+
*/
|
|
859
|
+
const makeEDADurableObjectRuntimeLayer = ({ config, compactionExecutorLayer, compactionPolicyLayer, keepAlive, modelLayer, promptProjectorLayer, reducers, sessionId, sinks, storage, toolkit, toolRegistry, tracer }) => {
|
|
860
|
+
const Store = DurableObjectSessionStore.layer({
|
|
861
|
+
sessionId,
|
|
862
|
+
storage
|
|
863
|
+
});
|
|
864
|
+
const KeepAlive = keepAlive === void 0 ? EDAKeepAlive.Noop : EDAKeepAlive.FromAcquire(() => keepAlive.acquire());
|
|
865
|
+
const SinkCheckpoints = DurableObjectSinkCheckpointStore.layer(storage);
|
|
866
|
+
return makeEDARuntimeLayer({
|
|
867
|
+
config,
|
|
868
|
+
compactionExecutorLayer,
|
|
869
|
+
compactionPolicyLayer,
|
|
870
|
+
keepAliveLayer: KeepAlive,
|
|
871
|
+
modelLayer,
|
|
872
|
+
promptProjectorLayer,
|
|
873
|
+
reducerRegistryLayer: EDAReducerRegistry.Live(reducers ?? []),
|
|
874
|
+
sessionId,
|
|
875
|
+
sessionStoreLayer: Store,
|
|
876
|
+
sinkCheckpointStoreLayer: SinkCheckpoints,
|
|
877
|
+
sinks,
|
|
878
|
+
toolkit,
|
|
879
|
+
toolRegistry,
|
|
880
|
+
tracer
|
|
881
|
+
});
|
|
882
|
+
};
|
|
883
|
+
/** OpenAI-backed Effect AI model layer for the default Worker host. */
|
|
884
|
+
const makeEDADurableObjectOpenAiModelLayer = (options) => {
|
|
885
|
+
const apiKey = optionalNonEmptyString(options.apiKey);
|
|
886
|
+
if (apiKey === void 0 && options.aiGateway === void 0) throw new Error("OPENAI_API_KEY is required unless the EDA OpenAI model layer is backed by a Cloudflare AI Gateway binding.");
|
|
887
|
+
const baseHttpClient = options.aiGateway === void 0 ? FetchHttpClient.layer : Layer.succeed(HttpClient.HttpClient, makeCloudflareAiGatewayHttpClient(options.aiGateway));
|
|
888
|
+
const client = OpenAiClient.layer({
|
|
889
|
+
...apiKey === void 0 ? {} : { apiKey: Redacted.make(apiKey) },
|
|
890
|
+
...options.apiUrl === void 0 ? {} : { apiUrl: options.apiUrl }
|
|
891
|
+
}).pipe(Layer.provide(baseHttpClient));
|
|
892
|
+
return OpenAiLanguageModel.layer({
|
|
893
|
+
model: options.modelId,
|
|
894
|
+
...options.config === void 0 ? {} : { config: options.config }
|
|
895
|
+
}).pipe(Layer.provide(client));
|
|
896
|
+
};
|
|
897
|
+
const OPENAI_API_BASE_PATH_PREFIX = "/v1/";
|
|
898
|
+
const makeCloudflareAiGatewayHttpClient = (gateway) => HttpClient.make((request, url, signal) => Effect.tryPromise({
|
|
899
|
+
try: async () => {
|
|
900
|
+
const response = await gateway.run({
|
|
901
|
+
endpoint: openAiGatewayEndpointFromUrl(url),
|
|
902
|
+
headers: requestHeadersForGateway(request),
|
|
903
|
+
provider: "openai",
|
|
904
|
+
query: requestBodyForGateway(request.body)
|
|
905
|
+
}, { signal });
|
|
906
|
+
return HttpClientResponse.fromWeb(request, response);
|
|
907
|
+
},
|
|
908
|
+
catch: (cause) => new HttpClientError.HttpClientError({ reason: new HttpClientError.TransportError({
|
|
909
|
+
request,
|
|
910
|
+
cause,
|
|
911
|
+
description: "Cloudflare AI Gateway request failed"
|
|
912
|
+
}) })
|
|
913
|
+
}));
|
|
914
|
+
const openAiGatewayEndpointFromUrl = (url) => {
|
|
915
|
+
return `${url.pathname.startsWith(OPENAI_API_BASE_PATH_PREFIX) ? url.pathname.slice(4) : url.pathname.replace(/^\/+/, "")}${url.search}`;
|
|
916
|
+
};
|
|
917
|
+
const requestHeadersForGateway = (request) => Object.fromEntries(Object.entries(request.headers).filter((entry) => {
|
|
918
|
+
const [key, value] = entry;
|
|
919
|
+
return typeof value === "string" && key.toLowerCase() !== "host";
|
|
920
|
+
}));
|
|
921
|
+
const requestBodyForGateway = (body) => {
|
|
922
|
+
switch (body._tag) {
|
|
923
|
+
case "Empty": return;
|
|
924
|
+
case "Raw": return body.body;
|
|
925
|
+
case "Uint8Array": return JSON.parse(new TextDecoder().decode(body.body));
|
|
926
|
+
default: throw new Error(`Unsupported OpenAI request body for Cloudflare AI Gateway: ${body._tag}`);
|
|
927
|
+
}
|
|
928
|
+
};
|
|
929
|
+
const optionalNonEmptyString = (value) => {
|
|
930
|
+
const trimmed = value?.trim();
|
|
931
|
+
return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
|
|
932
|
+
};
|
|
933
|
+
const hostSpanOptions = (trace, attributes) => ({
|
|
934
|
+
kind: "server",
|
|
935
|
+
attributes: compactSpanAttributes({
|
|
936
|
+
...trace.attributes,
|
|
937
|
+
...attributes
|
|
938
|
+
}),
|
|
939
|
+
links: trace.links.map((link) => ({
|
|
940
|
+
span: toEdaExternalSpan(link.context),
|
|
941
|
+
attributes: link.attributes
|
|
942
|
+
})),
|
|
943
|
+
...trace.parent === null ? {} : { parent: toEdaExternalSpan(trace.parent) }
|
|
944
|
+
});
|
|
945
|
+
/** Raw Durable Object host controller for one EDA session object. */
|
|
946
|
+
var EDASessionDurableObjectHost = class {
|
|
947
|
+
options;
|
|
948
|
+
keepAlive;
|
|
949
|
+
eventSockets = /* @__PURE__ */ new WeakMap();
|
|
950
|
+
runtimeState;
|
|
951
|
+
runtimePromise;
|
|
952
|
+
constructor(options) {
|
|
953
|
+
this.options = options;
|
|
954
|
+
this.keepAlive = options.keepAlive ?? new DurableObjectKeepAlive(options.storage, options.background);
|
|
955
|
+
}
|
|
956
|
+
/** Run idempotent host and event-store migrations. Safe from `blockConcurrencyWhile`. */
|
|
957
|
+
static migrate = (storage) => Effect.gen(function* () {
|
|
958
|
+
yield* DurableObjectSessionStore.migrate(storage);
|
|
959
|
+
yield* DurableObjectSinkCheckpointStore.migrate(storage);
|
|
960
|
+
});
|
|
961
|
+
/** Admit one command durably. Active runtime work holds EDA keep-alive leases internally. */
|
|
962
|
+
async submit(input) {
|
|
963
|
+
const runtime = await this.getRuntime(input.sessionId);
|
|
964
|
+
const trace = input.trace ?? makeRootEDATraceMetadata();
|
|
965
|
+
return await runtime.runtime.runPromise(Effect.gen(function* () {
|
|
966
|
+
return yield* (yield* EDARuntime).submit(input.command);
|
|
967
|
+
}).pipe(Effect.withSpan("agent.command.submit", hostSpanOptions(trace, {
|
|
968
|
+
"eda.session.id": input.sessionId,
|
|
969
|
+
"eda.command.kind": input.command._tag,
|
|
970
|
+
"eda.command.id": input.command.commandId
|
|
971
|
+
}))));
|
|
972
|
+
}
|
|
973
|
+
/** Submit an ordered durable batch of commands and app events. */
|
|
974
|
+
async submitBatch(input) {
|
|
975
|
+
const runtime = await this.getRuntime(input.sessionId);
|
|
976
|
+
const trace = input.trace ?? makeRootEDATraceMetadata();
|
|
977
|
+
return await runtime.runtime.runPromise(Effect.gen(function* () {
|
|
978
|
+
return yield* (yield* EDARuntime).submit(input.items);
|
|
979
|
+
}).pipe(Effect.withSpan("agent.command.submit", hostSpanOptions(trace, {
|
|
980
|
+
"eda.session.id": input.sessionId,
|
|
981
|
+
"eda.command.submittable_count": input.items.length,
|
|
982
|
+
"eda.command.count": input.items.filter((item) => "_tag" in item).length
|
|
983
|
+
}))));
|
|
984
|
+
}
|
|
985
|
+
/** Admit one command and wait for its terminal command boundary. */
|
|
986
|
+
async submitAndBlock(input) {
|
|
987
|
+
const runtime = await this.getRuntime(input.sessionId);
|
|
988
|
+
const trace = input.trace ?? makeRootEDATraceMetadata();
|
|
989
|
+
return await runtime.runtime.runPromise(Effect.gen(function* () {
|
|
990
|
+
return yield* (yield* EDARuntime).submitAndBlock(input.command);
|
|
991
|
+
}).pipe(Effect.withSpan("agent.command.submit.wait", hostSpanOptions(trace, {
|
|
992
|
+
"eda.session.id": input.sessionId,
|
|
993
|
+
"eda.command.kind": input.command._tag,
|
|
994
|
+
"eda.command.id": input.command.commandId
|
|
995
|
+
}))));
|
|
996
|
+
}
|
|
997
|
+
/** Wait for an existing command to reach its terminal command boundary. */
|
|
998
|
+
async blockOnCommand(input) {
|
|
999
|
+
const runtime = await this.getRuntime(input.sessionId);
|
|
1000
|
+
const trace = input.trace ?? makeRootEDATraceMetadata();
|
|
1001
|
+
return await runtime.runtime.runPromise(Effect.gen(function* () {
|
|
1002
|
+
return yield* (yield* EDARuntime).blockOnCommand(input.commandId, input.afterSeq ?? SequenceNumber.make(0));
|
|
1003
|
+
}).pipe(Effect.withSpan("agent.command.wait", hostSpanOptions(trace, {
|
|
1004
|
+
"eda.session.id": input.sessionId,
|
|
1005
|
+
"eda.command.id": input.commandId,
|
|
1006
|
+
"eda.seq.after": input.afterSeq
|
|
1007
|
+
}))));
|
|
1008
|
+
}
|
|
1009
|
+
/** Read the authoritative live session snapshot. */
|
|
1010
|
+
snapshot(input) {
|
|
1011
|
+
const trace = input.trace ?? makeRootEDATraceMetadata();
|
|
1012
|
+
return this.withRuntime(input.sessionId, (eda) => eda.snapshot().pipe(Effect.withSpan("agent.session.snapshot", hostSpanOptions(trace, { "eda.session.id": input.sessionId }))));
|
|
1013
|
+
}
|
|
1014
|
+
/** Read durable transcript messages in committed order. */
|
|
1015
|
+
messages(input) {
|
|
1016
|
+
const trace = input.trace ?? makeRootEDATraceMetadata();
|
|
1017
|
+
return this.withRuntime(input.sessionId, (eda) => eda.messages().pipe(Effect.withSpan("agent.messages.list", hostSpanOptions(trace, { "eda.session.id": input.sessionId }))));
|
|
1018
|
+
}
|
|
1019
|
+
/** Accept one WebSocket as the live event stream for this session. */
|
|
1020
|
+
async acceptEventWebSocket(input) {
|
|
1021
|
+
const attachment = websocket_protocol_exports.EDAWebSocketAttachment.make({
|
|
1022
|
+
kind: "eda-events-v1",
|
|
1023
|
+
sessionId: input.sessionId,
|
|
1024
|
+
subscriberId: websocket_protocol_exports.SubscriberId.make(crypto.randomUUID()),
|
|
1025
|
+
lastAckedSeq: input.afterSeq ?? SequenceNumber.make(0),
|
|
1026
|
+
trace: input.trace ?? makeRootEDATraceMetadata()
|
|
1027
|
+
});
|
|
1028
|
+
input.webSocket.serializeAttachment(attachment);
|
|
1029
|
+
await this.startEventWebSocket(input.webSocket, attachment);
|
|
1030
|
+
}
|
|
1031
|
+
/** Restore hibernated event WebSockets whose in-memory subscriber fibers disappeared. */
|
|
1032
|
+
async restoreEventWebSockets(webSockets) {
|
|
1033
|
+
for (const webSocket of webSockets) {
|
|
1034
|
+
if (this.eventSockets.has(webSocket)) continue;
|
|
1035
|
+
const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());
|
|
1036
|
+
if (decoded._tag === "Decoded") await this.startEventWebSocket(webSocket, decoded.attachment);
|
|
1037
|
+
else if (decoded._tag === "Malformed") closeWebSocket(webSocket, websocket_protocol_exports.EDA_WS_CLOSE_PROTOCOL_ERROR, "attachment");
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
/** Route one inbound WebSocket message into the subscriber ACK queue. */
|
|
1041
|
+
async webSocketMessage(webSocket, message) {
|
|
1042
|
+
const state = await this.ensureEventWebSocket(webSocket);
|
|
1043
|
+
if (state === void 0) {
|
|
1044
|
+
closeWebSocket(webSocket, websocket_protocol_exports.EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
if (typeof message !== "string") {
|
|
1048
|
+
closeWebSocket(webSocket, websocket_protocol_exports.EDA_WS_CLOSE_PROTOCOL_ERROR, "binary");
|
|
1049
|
+
state.interrupt?.();
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
try {
|
|
1053
|
+
const frame = await Effect.runPromise((0, websocket_protocol_exports.decodeEDAWebSocketClientMessage)(message));
|
|
1054
|
+
await Effect.runPromise(Queue.offer(state.incoming, frame));
|
|
1055
|
+
} catch {
|
|
1056
|
+
closeWebSocket(webSocket, websocket_protocol_exports.EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
|
|
1057
|
+
state.interrupt?.();
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
/** Interrupt subscriber work after the client closes the WebSocket. */
|
|
1061
|
+
async webSocketClose(webSocket) {
|
|
1062
|
+
const state = this.eventSockets.get(webSocket);
|
|
1063
|
+
if (state === void 0) return;
|
|
1064
|
+
await Effect.runPromise(Deferred.succeed(state.closed, void 0).pipe(Effect.ignore));
|
|
1065
|
+
state.interrupt?.();
|
|
1066
|
+
this.eventSockets.delete(webSocket);
|
|
1067
|
+
}
|
|
1068
|
+
/** Interrupt subscriber work after a host WebSocket error. */
|
|
1069
|
+
async webSocketError(webSocket) {
|
|
1070
|
+
const state = this.eventSockets.get(webSocket);
|
|
1071
|
+
if (state === void 0) return;
|
|
1072
|
+
await Effect.runPromise(Deferred.succeed(state.closed, void 0).pipe(Effect.ignore));
|
|
1073
|
+
state.interrupt?.();
|
|
1074
|
+
this.eventSockets.delete(webSocket);
|
|
1075
|
+
}
|
|
1076
|
+
/** Dispose any live runtime before the host deletes its Durable Object storage. */
|
|
1077
|
+
async destroy(_input) {
|
|
1078
|
+
await this.keepAlive.shutdown();
|
|
1079
|
+
await this.dispose();
|
|
1080
|
+
this.runtimeState = void 0;
|
|
1081
|
+
this.runtimePromise = void 0;
|
|
1082
|
+
}
|
|
1083
|
+
/** Durable Object alarm hook: wake/recover the runtime and re-arm while EDA has active work. */
|
|
1084
|
+
async alarm(input) {
|
|
1085
|
+
const sessionId = input?.sessionId ?? this.runtimeState?.sessionId;
|
|
1086
|
+
if (sessionId !== void 0) await this.getRuntime(sessionId);
|
|
1087
|
+
await this.keepAlive.alarm();
|
|
1088
|
+
}
|
|
1089
|
+
/** Dispose the Effect runtime if the host wrapper is torn down by tests. */
|
|
1090
|
+
async dispose() {
|
|
1091
|
+
await this.runtimeState?.runtime.dispose();
|
|
1092
|
+
}
|
|
1093
|
+
async withRuntime(sessionId, f) {
|
|
1094
|
+
return await (await this.getRuntime(sessionId)).runtime.runPromise(Effect.gen(function* () {
|
|
1095
|
+
return yield* f(yield* EDARuntime);
|
|
1096
|
+
}));
|
|
1097
|
+
}
|
|
1098
|
+
async ensureEventWebSocket(webSocket) {
|
|
1099
|
+
const existing = this.eventSockets.get(webSocket);
|
|
1100
|
+
if (existing !== void 0) return existing;
|
|
1101
|
+
const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());
|
|
1102
|
+
if (decoded._tag !== "Decoded") return;
|
|
1103
|
+
await this.startEventWebSocket(webSocket, decoded.attachment);
|
|
1104
|
+
return this.eventSockets.get(webSocket);
|
|
1105
|
+
}
|
|
1106
|
+
async startEventWebSocket(webSocket, attachment) {
|
|
1107
|
+
if (this.eventSockets.has(webSocket)) return;
|
|
1108
|
+
const runtime = await this.getRuntime(attachment.sessionId);
|
|
1109
|
+
const state = {
|
|
1110
|
+
...await runtime.runtime.runPromise(Effect.gen(function* () {
|
|
1111
|
+
return {
|
|
1112
|
+
incoming: yield* Queue.unbounded(),
|
|
1113
|
+
closed: yield* Deferred.make()
|
|
1114
|
+
};
|
|
1115
|
+
})),
|
|
1116
|
+
interrupt: void 0,
|
|
1117
|
+
lastAckedSeq: attachment.lastAckedSeq,
|
|
1118
|
+
sessionId: attachment.sessionId,
|
|
1119
|
+
subscriberId: attachment.subscriberId
|
|
1120
|
+
};
|
|
1121
|
+
this.eventSockets.set(webSocket, state);
|
|
1122
|
+
const send = (frame) => Effect.try({
|
|
1123
|
+
try: () => webSocket.send((0, websocket_protocol_exports.encodeEDAWebSocketServerFrame)(frame, this.options.webSocketProtocol)),
|
|
1124
|
+
catch: (cause) => new SubscriberSendFailed({
|
|
1125
|
+
subscriberId: state.subscriberId,
|
|
1126
|
+
cause
|
|
1127
|
+
})
|
|
1128
|
+
});
|
|
1129
|
+
const persistAck = (seq) => Effect.sync(() => {
|
|
1130
|
+
state.lastAckedSeq = seq;
|
|
1131
|
+
webSocket.serializeAttachment({
|
|
1132
|
+
kind: "eda-events-v1",
|
|
1133
|
+
sessionId: state.sessionId,
|
|
1134
|
+
subscriberId: state.subscriberId,
|
|
1135
|
+
lastAckedSeq: seq,
|
|
1136
|
+
trace: attachment.trace
|
|
1137
|
+
});
|
|
1138
|
+
});
|
|
1139
|
+
const closeForError = (error) => {
|
|
1140
|
+
if (error instanceof SubscriberLagged || isTagged(error, "SubscriberLagged")) {
|
|
1141
|
+
const lagged = error;
|
|
1142
|
+
return send(websocket_protocol_exports.EDAWebSocketLaggedFrame.make({
|
|
1143
|
+
_tag: "lagged",
|
|
1144
|
+
resumeSeq: lagged.lastAckedSeq,
|
|
1145
|
+
reason: lagged.reason
|
|
1146
|
+
})).pipe(Effect.ignore, Effect.andThen(Effect.sync(() => closeWebSocket(webSocket, websocket_protocol_exports.EDA_WS_CLOSE_LAGGED, (0, websocket_protocol_exports.laggedCloseReason)(lagged.lastAckedSeq)))));
|
|
1147
|
+
}
|
|
1148
|
+
if (error instanceof SubscriberProtocolError || isTagged(error, "SubscriberProtocolError")) {
|
|
1149
|
+
const protocolError = error;
|
|
1150
|
+
return send(websocket_protocol_exports.EDAWebSocketErrorFrame.make({
|
|
1151
|
+
_tag: "error",
|
|
1152
|
+
message: protocolError.message.slice(0, 120)
|
|
1153
|
+
})).pipe(Effect.ignore, Effect.andThen(Effect.sync(() => closeWebSocket(webSocket, websocket_protocol_exports.EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol"))));
|
|
1154
|
+
}
|
|
1155
|
+
return Effect.sync(() => closeWebSocket(webSocket, websocket_protocol_exports.EDA_WS_CLOSE_SEND_FAILED, "send-failed"));
|
|
1156
|
+
};
|
|
1157
|
+
const program = Effect.scoped(runWebSocketSubscriber({
|
|
1158
|
+
subscriberId: state.subscriberId,
|
|
1159
|
+
resumeSeq: state.lastAckedSeq,
|
|
1160
|
+
policy: websocket_protocol_exports.defaultEDAWebSocketFlowControl,
|
|
1161
|
+
transport: {
|
|
1162
|
+
send,
|
|
1163
|
+
incoming: state.incoming,
|
|
1164
|
+
closed: state.closed,
|
|
1165
|
+
persistAck
|
|
1166
|
+
}
|
|
1167
|
+
}).pipe(Effect.catch((error) => closeForError(error)), Effect.ensuring(Effect.sync(() => {
|
|
1168
|
+
this.eventSockets.delete(webSocket);
|
|
1169
|
+
})), Effect.withSpan("agent.events.stream", hostSpanOptions(attachment.trace, {
|
|
1170
|
+
"eda.session.id": state.sessionId,
|
|
1171
|
+
"eda.subscriber.id": state.subscriberId,
|
|
1172
|
+
"eda.seq.after": state.lastAckedSeq
|
|
1173
|
+
}))));
|
|
1174
|
+
state.interrupt = runtime.runtime.runCallback(program, { onExit: (exit) => {
|
|
1175
|
+
this.eventSockets.delete(webSocket);
|
|
1176
|
+
if (Exit.isFailure(exit)) closeWebSocket(webSocket, websocket_protocol_exports.EDA_WS_CLOSE_SEND_FAILED, "subscriber-failed");
|
|
1177
|
+
} });
|
|
1178
|
+
}
|
|
1179
|
+
async getRuntime(sessionId) {
|
|
1180
|
+
if (this.runtimeState !== void 0) {
|
|
1181
|
+
if (this.runtimeState.sessionId !== sessionId) throw new Error(`EDASessionDurableObjectHost is scoped to session ${this.runtimeState.sessionId}; received ${sessionId}`);
|
|
1182
|
+
return this.runtimeState;
|
|
1183
|
+
}
|
|
1184
|
+
this.keepAlive.restart();
|
|
1185
|
+
const runtimePromise = this.runtimePromise ?? this.buildRuntime(sessionId);
|
|
1186
|
+
this.runtimePromise = runtimePromise;
|
|
1187
|
+
try {
|
|
1188
|
+
return await runtimePromise;
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
if (this.runtimePromise === runtimePromise) this.runtimePromise = void 0;
|
|
1191
|
+
throw error;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
async buildRuntime(sessionId) {
|
|
1195
|
+
const runtime = ManagedRuntime.make(makeEDADurableObjectRuntimeLayer({
|
|
1196
|
+
config: this.options.config,
|
|
1197
|
+
compactionExecutorLayer: this.options.compactionExecutorLayer,
|
|
1198
|
+
compactionPolicyLayer: this.options.compactionPolicyLayer,
|
|
1199
|
+
keepAlive: this.keepAlive,
|
|
1200
|
+
modelLayer: this.options.modelLayer,
|
|
1201
|
+
promptProjectorLayer: this.options.promptProjectorLayer,
|
|
1202
|
+
reducers: this.options.reducers,
|
|
1203
|
+
sessionId,
|
|
1204
|
+
sinks: this.options.sinks,
|
|
1205
|
+
storage: this.options.storage,
|
|
1206
|
+
toolkit: resolveRuntimeFactory(this.options.toolkit, sessionId),
|
|
1207
|
+
toolRegistry: resolveRuntimeFactory(this.options.toolRegistry, sessionId),
|
|
1208
|
+
tracer: resolveRuntimeFactory(this.options.tracer, sessionId)
|
|
1209
|
+
}));
|
|
1210
|
+
const state = {
|
|
1211
|
+
runtime,
|
|
1212
|
+
sessionId
|
|
1213
|
+
};
|
|
1214
|
+
try {
|
|
1215
|
+
await runtime.context();
|
|
1216
|
+
this.runtimeState = state;
|
|
1217
|
+
return state;
|
|
1218
|
+
} catch (error) {
|
|
1219
|
+
await runtime.dispose().catch(() => void 0);
|
|
1220
|
+
throw error;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
};
|
|
1224
|
+
const decodeWebSocketAttachment = async (input) => {
|
|
1225
|
+
if (input === null || input === void 0) return { _tag: "Missing" };
|
|
1226
|
+
try {
|
|
1227
|
+
return {
|
|
1228
|
+
_tag: "Decoded",
|
|
1229
|
+
attachment: await Effect.runPromise((0, websocket_protocol_exports.decodeEDAWebSocketAttachment)(input))
|
|
1230
|
+
};
|
|
1231
|
+
} catch {
|
|
1232
|
+
return { _tag: "Malformed" };
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
const closeWebSocket = (webSocket, code, reason) => {
|
|
1236
|
+
try {
|
|
1237
|
+
webSocket.close(code, reason);
|
|
1238
|
+
} catch {}
|
|
1239
|
+
};
|
|
1240
|
+
const isTagged = (input, tag) => typeof input === "object" && input !== null && "_tag" in input && input._tag === tag;
|
|
1241
|
+
/** Decode a raw RPC command payload at the Durable Object boundary. */
|
|
1242
|
+
const encodeEdaRpcCommand = (input) => Schema.encodeSync(EDACommand)(input);
|
|
1243
|
+
const EDARpcSubmittable = Schema.Union([EDACommand, DurableEventEnvelope]);
|
|
1244
|
+
/** Encode a command/app-event batch into structured-clone-safe RPC values. */
|
|
1245
|
+
const encodeEdaRpcSubmittables = (input) => input.map((item) => Schema.encodeSync(EDARpcSubmittable)(item));
|
|
1246
|
+
/** Decode a raw RPC command payload at the Durable Object boundary. */
|
|
1247
|
+
const decodeEdaRpcCommand = (input) => Schema.decodeUnknownEffect(EDACommand)(input);
|
|
1248
|
+
/** Decode a raw RPC batch item at the Durable Object boundary. */
|
|
1249
|
+
const decodeEdaRpcSubmittable = (input) => Schema.decodeUnknownEffect(EDARpcSubmittable)(input);
|
|
1250
|
+
/** Decode raw RPC batch items at the Durable Object boundary. */
|
|
1251
|
+
const decodeEdaRpcSubmittables = (input) => Effect.forEach(input, decodeEdaRpcSubmittable);
|
|
1252
|
+
//#endregion
|
|
1253
|
+
export { encodeEdaRpcCommand as a, makeEDADurableObjectRuntimeLayer as c, decodeEdaRpcSubmittables as i, decodeEdaRpcCommand as n, encodeEdaRpcSubmittables as o, decodeEdaRpcSubmittable as r, makeEDADurableObjectOpenAiModelLayer as s, EDASessionDurableObjectHost as t };
|
|
1254
|
+
|
|
1255
|
+
//# sourceMappingURL=durable-object-runtime-LgOJbsVm.js.map
|