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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +5 -2
  2. package/dist/anthropic.d.ts +44 -0
  3. package/dist/anthropic.js +66 -0
  4. package/dist/anthropic.js.map +1 -0
  5. package/dist/durable-object-DAQzdio7.js +622 -0
  6. package/dist/durable-object-DAQzdio7.js.map +1 -0
  7. package/dist/durable-object-storage-Dec6HWQ9.d.ts +136 -0
  8. package/dist/durable-object-store-yY_KaFtw.js +1231 -0
  9. package/dist/durable-object-store-yY_KaFtw.js.map +1 -0
  10. package/dist/durable-object.d.ts +2352 -55
  11. package/dist/durable-object.js +2 -193
  12. package/dist/index.d.ts +227 -6
  13. package/dist/index.js +6 -5
  14. package/dist/openai.d.ts +10 -5
  15. package/dist/openai.js +20 -48
  16. package/dist/openai.js.map +1 -1
  17. package/dist/providers.d.ts +53 -0
  18. package/dist/providers.js +221 -0
  19. package/dist/providers.js.map +1 -0
  20. package/dist/rpc-codec-B2aLiNqt.d.ts +44 -0
  21. package/dist/rpc-spec-BRNFIsY1.js +407 -0
  22. package/dist/rpc-spec-BRNFIsY1.js.map +1 -0
  23. package/dist/rpc-spec-O5conxmN.d.ts +8888 -0
  24. package/dist/rpc.d.ts +3 -16
  25. package/dist/rpc.js +2 -26
  26. package/dist/{session-controller-COHH8vA6.js → session-controller-BCtnyAEw.js} +689 -657
  27. package/dist/session-controller-BCtnyAEw.js.map +1 -0
  28. package/dist/{session-controller-Dp07FnPn.d.ts → session-controller-BZaYmBLr.d.ts} +107 -32
  29. package/dist/session-controller.d.ts +1 -1
  30. package/dist/session-controller.js +1 -1
  31. package/dist/storage.d.ts +1 -1
  32. package/dist/transport-BzgK07l4.js +205 -0
  33. package/dist/transport-BzgK07l4.js.map +1 -0
  34. package/package.json +29 -11
  35. package/dist/durable-object-storage-DCL2IyUe.d.ts +0 -41
  36. package/dist/durable-object.js.map +0 -1
  37. package/dist/rpc.js.map +0 -1
  38. package/dist/session-controller-COHH8vA6.js.map +0 -1
@@ -1,193 +1,2 @@
1
- import { decodeEdaRpcCommand, decodeEdaRpcSubmittables, encodeEdaRpcDurableEvent } from "./rpc.js";
2
- import { t as EDASessionController } from "./session-controller-COHH8vA6.js";
3
- import { DurableObject } from "cloudflare:workers";
4
- import * as Effect from "effect/Effect";
5
- import * as Schema from "effect/Schema";
6
- import { EDACommand } from "effect-durable-agent/types/commands";
7
- import { CommandId, SequenceNumber, SessionId } from "effect-durable-agent/types/core";
8
- import { EDATraceMetadata, makeEDATraceMetadataFromParent, makeRootEDATraceMetadata, parseEDATraceparent } from "effect-durable-agent/types/tracing";
9
- import { EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE } from "effect-durable-agent/websocket";
10
- //#region src/durable-object.ts
11
- /** Internal Worker-to-object header selecting an app-owned WebSocket projection. */
12
- const EDA_WEB_SOCKET_PROJECTION_HEADER = "x-eda-websocket-projection";
13
- /** Resolve a concrete EDA session Durable Object binding by domain session id. */
14
- const getEDASessionDurableObjectByName = (namespace, sessionId) => namespace.getByName(sessionId);
15
- /**
16
- * Base class for raw Cloudflare Durable Object hosts of one EDA session.
17
- *
18
- * Concrete products should extend this class, pass provider/tool layers from
19
- * their own constructor, and register only that subclass in Wrangler. The base
20
- * class is deliberately not exported from `workers/app.ts` and owns no binding
21
- * name or routing convention.
22
- */
23
- var EDASessionDurableObject = class extends DurableObject {
24
- #controller;
25
- #webSocketProjectionId;
26
- constructor(ctx, env, options) {
27
- super(ctx, env);
28
- this.#webSocketProjectionId = options.webSocketProjection?.id;
29
- const storage = toEDASessionStorage(this.ctx.storage);
30
- this.#controller = new EDASessionController({
31
- ...options,
32
- background: this.ctx,
33
- getWebSockets: () => this.ctx.getWebSockets(),
34
- storage
35
- });
36
- this.ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE));
37
- this.ctx.blockConcurrencyWhile(async () => {
38
- await Effect.runPromise(EDASessionController.migrate(storage));
39
- });
40
- }
41
- async fetch(request) {
42
- if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return new Response("Expected WebSocket upgrade.", { status: 426 });
43
- const url = new URL(request.url);
44
- const sessionIdRaw = url.searchParams.get("sessionId");
45
- if (sessionIdRaw === null) return new Response("Missing sessionId.", { status: 400 });
46
- const afterSeqRaw = url.searchParams.get("afterSeq");
47
- const afterSeq = afterSeqRaw === null ? void 0 : Number(afterSeqRaw);
48
- if (afterSeq !== void 0 && (!Number.isInteger(afterSeq) || afterSeq < 0)) return new Response("Invalid afterSeq.", { status: 400 });
49
- const projectionId = request.headers.get("x-eda-websocket-projection") ?? void 0;
50
- if (projectionId !== void 0 && projectionId !== this.#webSocketProjectionId) return new Response("Unsupported WebSocket projection.", { status: 400 });
51
- const sessionId = this.parseSessionId(sessionIdRaw);
52
- const trace = traceMetadataFromRequest(request);
53
- const prepared = await this.#controller.prepareEventWebSocket({
54
- ...afterSeq === void 0 ? {} : { afterSeq: SequenceNumber.make(afterSeq) },
55
- sessionId,
56
- trace,
57
- ...projectionId === void 0 ? {} : { projectionId }
58
- });
59
- const pair = new WebSocketPair();
60
- const client = pair[0];
61
- const server = pair[1];
62
- this.ctx.acceptWebSocket(server);
63
- await this.#controller.acceptPreparedEventWebSocket({
64
- ...prepared,
65
- webSocket: server
66
- });
67
- return new Response(null, {
68
- status: 101,
69
- webSocket: client
70
- });
71
- }
72
- async submit(input) {
73
- return encodeEdaRpcCommittedDurableEvent(await this.#controller.submit({
74
- command: await decodeCommand(input.command),
75
- sessionId: this.parseSessionId(input.sessionId),
76
- trace: decodeTraceMetadata(input.trace)
77
- }));
78
- }
79
- async submitBatch(input) {
80
- return (await this.#controller.submitBatch({
81
- items: await decodeSubmittables(input.items),
82
- sessionId: this.parseSessionId(input.sessionId),
83
- trace: decodeTraceMetadata(input.trace)
84
- })).map(encodeEdaRpcCommittedDurableEvent);
85
- }
86
- async submitAndBlock(input) {
87
- return encodeEdaRpcCommittedDurableEvent(await this.#controller.submitAndBlock({
88
- command: await decodeCommand(input.command),
89
- sessionId: this.parseSessionId(input.sessionId),
90
- trace: decodeTraceMetadata(input.trace)
91
- }));
92
- }
93
- async blockOnCommand(input) {
94
- return encodeEdaRpcCommittedDurableEvent(await this.#controller.blockOnCommand({
95
- ...input.afterSeq === void 0 ? {} : { afterSeq: SequenceNumber.make(input.afterSeq) },
96
- commandId: CommandId.make(input.commandId),
97
- sessionId: this.parseSessionId(input.sessionId),
98
- trace: decodeTraceMetadata(input.trace)
99
- }));
100
- }
101
- async snapshot(input) {
102
- return encodeEdaRpcSessionSnapshot(await this.#controller.snapshot({
103
- sessionId: this.parseSessionId(input.sessionId),
104
- trace: decodeTraceMetadata(input.trace)
105
- }));
106
- }
107
- async messages(input) {
108
- return await this.#controller.messages({
109
- sessionId: this.parseSessionId(input.sessionId),
110
- trace: decodeTraceMetadata(input.trace)
111
- });
112
- }
113
- async webSocketMessage(webSocket, message) {
114
- await this.#controller.webSocketMessage(webSocket, message);
115
- }
116
- async webSocketClose(webSocket, _code, _reason, _wasClean) {
117
- this.#controller.webSocketClose(webSocket);
118
- }
119
- async webSocketError(webSocket, _error) {
120
- this.#controller.webSocketError(webSocket);
121
- }
122
- async destroySession(input) {
123
- await this.#controller.destroy({
124
- sessionId: this.parseSessionId(input.sessionId),
125
- trace: decodeTraceMetadata(input.trace)
126
- });
127
- await this.ctx.storage.deleteAlarm();
128
- await this.ctx.storage.deleteAll();
129
- }
130
- async alarm() {
131
- const sessionId = this.sessionIdFromObjectName();
132
- await this.#controller.alarm(sessionId === void 0 ? void 0 : {
133
- sessionId,
134
- trace: makeRootEDATraceMetadata()
135
- });
136
- }
137
- parseSessionId(input) {
138
- const sessionId = SessionId.make(input);
139
- const objectName = this.ctx.id.name;
140
- if (objectName !== void 0 && objectName !== sessionId) throw new Error(`EDA Durable Object name ${objectName} cannot serve session ${sessionId}`);
141
- return sessionId;
142
- }
143
- sessionIdFromObjectName() {
144
- return this.ctx.id.name === void 0 ? void 0 : SessionId.make(this.ctx.id.name);
145
- }
146
- };
147
- const toEDASessionStorage = (storage) => {
148
- return storage;
149
- };
150
- const decodeTraceMetadata = (input) => Schema.decodeUnknownSync(EDATraceMetadata)(input);
151
- const traceMetadataFromRequest = (request) => {
152
- const parent = parseEDATraceparent(request.headers.get("traceparent"), request.headers.get("tracestate"));
153
- return parent === null ? makeRootEDATraceMetadata() : makeEDATraceMetadataFromParent(parent);
154
- };
155
- /** Convenience config constructor for subclasses that need only provider/model ids. */
156
- const edaRuntimeConfig = (input) => ({
157
- modelSelection: {
158
- modelId: input.modelId,
159
- provider: input.provider
160
- },
161
- ...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
162
- ...input.systemPrompt === void 0 ? {} : { systemPrompt: input.systemPrompt }
163
- });
164
- /** Encode committed events into structured-clone-safe Durable Object RPC payloads. */
165
- const encodeEdaRpcCommittedDurableEvent = (event) => ({
166
- position: event.position,
167
- event: encodeEdaRpcDurableEvent(event.event)
168
- });
169
- /** Encode runtime snapshots into structured-clone-safe Durable Object RPC payloads. */
170
- const encodeEdaRpcSessionSnapshot = (snapshot) => ({
171
- ...snapshot,
172
- reducerStates: new Map(snapshot.reducerStates),
173
- state: {
174
- ...snapshot.state,
175
- commands: new Map(Array.from(snapshot.state.commands, ([commandId, record]) => [commandId, encodeCommandCarrierForRpc(record)])),
176
- commandQueues: {
177
- ...snapshot.state.commandQueues,
178
- activeControlCommands: snapshot.state.commandQueues.activeControlCommands.map(encodeCommandCarrierForRpc),
179
- pendingCommands: snapshot.state.commandQueues.pendingCommands.map(encodeCommandCarrierForRpc),
180
- queuedCommands: snapshot.state.commandQueues.queuedCommands.map(encodeCommandCarrierForRpc)
181
- }
182
- }
183
- });
184
- const encodeCommandCarrierForRpc = (value) => value.command === void 0 ? value : {
185
- ...value,
186
- command: Schema.encodeSync(EDACommand)(value.command)
187
- };
188
- const decodeCommand = (input) => Effect.runPromise(decodeEdaRpcCommand(input));
189
- const decodeSubmittables = (input) => Effect.runPromise(decodeEdaRpcSubmittables(input));
190
- //#endregion
191
- export { EDASessionDurableObject, EDA_WEB_SOCKET_PROJECTION_HEADER, edaRuntimeConfig, encodeEdaRpcCommittedDurableEvent, encodeEdaRpcSessionSnapshot, getEDASessionDurableObjectByName };
192
-
193
- //# sourceMappingURL=durable-object.js.map
1
+ import { a as encodeEdaRpcCommittedDurableEvent, i as edaRuntimeConfig, n as EDA_WEB_SOCKET_PROJECTION_HEADER, o as encodeEdaRpcSessionSnapshot, r as EDA_WEB_SOCKET_STREAM_PARAM, s as getEDASessionDurableObjectByName, t as EDASessionDurableObject } from "./durable-object-DAQzdio7.js";
2
+ export { EDASessionDurableObject, EDA_WEB_SOCKET_PROJECTION_HEADER, EDA_WEB_SOCKET_STREAM_PARAM, edaRuntimeConfig, encodeEdaRpcCommittedDurableEvent, encodeEdaRpcSessionSnapshot, getEDASessionDurableObjectByName };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,227 @@
1
- import { i as DurableObjectSqlStorage, n as DurableObjectSessionStoreOptions, r as DurableObjectSqlCursor, t as DurableObjectSessionStorage } from "./durable-object-storage-DCL2IyUe.js";
2
- import { a as EDASessionEventsInput, c as EDASessionSubmitInput, d as EDAWebSocketProjectionInitial, f as EDAWebSocketProjectionResult, h as makeEDADurableObjectRuntimeLayer, i as EDASessionControllerOptions, l as EDAWebSocketProjection, m as EDASessionDurableObjectStorage, n as EDASessionBlockOnCommandInput, o as EDASessionScopedInput, p as EDADurableObjectRuntimeLayerOptions, r as EDASessionController, s as EDASessionSubmitBatchInput, t as EDAPreparedEventWebSocket, u as EDAWebSocketProjectionId } from "./session-controller-Dp07FnPn.js";
3
- import { EDASessionBlockOnCommandRpcInput, EDASessionCommandRpcInput, EDASessionDurableObject, EDASessionDurableObjectOptions, EDASessionEventsRpcInput, EDASessionRpcSurface, EDASessionScopedRpcInput, EDASessionSubmitBatchRpcInput, EDA_WEB_SOCKET_PROJECTION_HEADER, edaRuntimeConfig, encodeEdaRpcCommittedDurableEvent, encodeEdaRpcSessionSnapshot, getEDASessionDurableObjectByName } from "./durable-object.js";
4
- import { EDAOpenAiModelConfig, makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer } from "./openai.js";
5
- import { decodeEdaRpcCommand, decodeEdaRpcSubmittables, encodeEdaRpcCommand, encodeEdaRpcDurableEvent, encodeEdaRpcSubmittables } from "./rpc.js";
6
- export { DurableObjectSessionStorage, DurableObjectSessionStoreOptions, DurableObjectSqlCursor, DurableObjectSqlStorage, EDADurableObjectRuntimeLayerOptions, EDAOpenAiModelConfig, EDAPreparedEventWebSocket, EDASessionBlockOnCommandInput, EDASessionBlockOnCommandRpcInput, EDASessionCommandRpcInput, EDASessionController, EDASessionControllerOptions, EDASessionDurableObject, EDASessionDurableObjectOptions, EDASessionDurableObjectStorage, EDASessionEventsInput, EDASessionEventsRpcInput, EDASessionRpcSurface, EDASessionScopedInput, EDASessionScopedRpcInput, EDASessionSubmitBatchInput, EDASessionSubmitBatchRpcInput, EDASessionSubmitInput, EDAWebSocketProjection, EDAWebSocketProjectionId, EDAWebSocketProjectionInitial, EDAWebSocketProjectionResult, EDA_WEB_SOCKET_PROJECTION_HEADER, decodeEdaRpcCommand, decodeEdaRpcSubmittables, edaRuntimeConfig, encodeEdaRpcCommand, encodeEdaRpcCommittedDurableEvent, encodeEdaRpcDurableEvent, encodeEdaRpcSessionSnapshot, encodeEdaRpcSubmittables, getEDASessionDurableObjectByName, makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer, makeEDADurableObjectRuntimeLayer };
1
+ import { a as DurableObjectTranscriptObserver, c as TranscriptAlert, i as DurableObjectSqlStorage, l as AdoptedLogIncarnation, n as DurableObjectSessionStoreOptions, o as DurableObjectTranscriptOptions, r as DurableObjectSqlCursor, s as DurableObjectTranscriptSliceLimits, t as DurableObjectSessionStorage } from "./durable-object-storage-Dec6HWQ9.js";
2
+ import { a as SessionOutcomeInput, c as SessionTranscriptBodyResult, d as SessionTranscriptWindowInput, f as SessionTranscriptWindowResult, i as SessionGrantRunInput, l as SessionTranscriptSummaryInput, m as edaSessionRpc, n as SessionBlockInput, o as SessionScopedInput, p as TranscriptCompactionSummary, r as SessionCommandInput, s as SessionTranscriptBodyInput, t as SessionBatchInput, u as SessionTranscriptSummaryResult } from "./rpc-spec-O5conxmN.js";
3
+ import { _ as makeEDADurableObjectRuntimeLayer, a as EDASessionEventsInput, c as EDASessionSubmitInput, d as EDAWebSocketProjection, f as EDAWebSocketProjectionId, g as EDASessionDurableObjectStorage, h as EDADurableObjectRuntimeLayerOptions, i as EDASessionControllerOptions, l as EDATranscriptSocketOptions, m as EDAWebSocketProjectionResult, n as EDASessionBlockOnCommandInput, o as EDASessionScopedInput, p as EDAWebSocketProjectionInitial, r as EDASessionController, s as EDASessionSubmitBatchInput, t as EDAPreparedEventWebSocket, u as defaultActiveContentCadenceMs, v as DurableObjectAlarmStorage } from "./session-controller-BZaYmBLr.js";
4
+ import { EDASessionBlockOnCommandRpcInput, EDASessionCommandRpcInput, EDASessionDurableObject, EDASessionDurableObjectOptions, EDASessionEventsRpcInput, EDASessionGrantRunRpcInput, EDASessionRpcSurface, EDASessionRunRequestOutcomeRpcInput, EDASessionScopedRpcInput, EDASessionSubmitBatchRpcInput, EDASessionTranscriptOptions, EDA_WEB_SOCKET_PROJECTION_HEADER, EDA_WEB_SOCKET_STREAM_PARAM, edaRuntimeConfig, encodeEdaRpcCommittedDurableEvent, encodeEdaRpcSessionSnapshot, getEDASessionDurableObjectByName } from "./durable-object.js";
5
+ import { EDAOpenAiModelConfig, makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer, makeEDAOpenAiClientLayer } from "./openai.js";
6
+ import { a as encodeEdaRpcDurableEvent, i as encodeEdaRpcCommand, n as decodeEdaRpcCommand, o as encodeEdaRpcSubmittables, r as decodeEdaRpcSubmittables, t as EDARpcSubmittable } from "./rpc-codec-B2aLiNqt.js";
7
+ import * as Layer from "effect/Layer";
8
+ import * as Effect from "effect/Effect";
9
+ import * as Schema from "effect/Schema";
10
+ import { SessionId, SummaryId } from "effect-durable-agent/types/core";
11
+ import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, EDASessionStoreShape } from "effect-durable-agent/services/session-store";
12
+ import { EDATranscriptStore, EDATranscriptStoreShape, TranscriptCursorMismatch, TranscriptLogIncarnation, TranscriptVersionMeta, TranscriptWindow, TranscriptWindowLimits, TranscriptWindowSelector } from "effect-durable-agent/transcript";
13
+ import * as Result from "effect/Result";
14
+ import { CompactionSummaryArtifact } from "effect-durable-agent/domain/context-projection";
15
+ //#region src/durable-object-alarms.d.ts
16
+ /**
17
+ * The independent owners of a session object's single platform alarm.
18
+ *
19
+ * - `runtime`: the keep-alive heartbeat and run-scheduling redelivery; its wakeup builds the model
20
+ * runtime.
21
+ * - `transcript`: the transcript builder; its wakeup runs storage-only slices and must never
22
+ * build the model runtime.
23
+ */
24
+ type DurableObjectAlarmOwner = "runtime" | "transcript";
25
+ /**
26
+ * Shares one Durable Object alarm between owners that each keep a durable wakeup.
27
+ *
28
+ * Each owner's wakeup is a row in `_eda_alarm_wakeups`, and the platform alarm is always set to the
29
+ * earliest row, so no owner can delete or postpone another's wakeup, and after an eviction the
30
+ * alarm handler still knows which owners it fired for. An owner's view (`owner(...)`) has the
31
+ * same shape as the platform alarm API, so the keep-alive heartbeat uses it unchanged.
32
+ */
33
+ declare class DurableObjectAlarmScheduler {
34
+ #private;
35
+ private readonly storage;
36
+ private readonly now;
37
+ constructor(storage: DurableObjectSessionStorage & DurableObjectAlarmStorage, now?: () => number);
38
+ /**
39
+ * One owner's alarm, behaving like the platform alarm restricted to that owner. Like the
40
+ * platform's, it reports no alarm once its time has come: a wakeup left behind when the
41
+ * platform gave up retrying a failed alarm must not look armed, or its owner would never re-arm.
42
+ * "Come" includes the exact millisecond: inside the alarm it fired for, the Workers clock
43
+ * commonly reads exactly the scheduled time, and a wakeup that still looked armed then would
44
+ * keep the keep-alive from re-arming before the handler clears it.
45
+ */
46
+ owner(owner: DurableObjectAlarmOwner): DurableObjectAlarmStorage;
47
+ /**
48
+ * Adopt a platform alarm no owner recorded (one armed before wakeups were recorded) as the
49
+ * runtime's, so the first wakeup another owner requests cannot replace it. Call once at startup,
50
+ * before any owner writes a wakeup.
51
+ */
52
+ adoptUnrecordedAlarm(): Promise<void>;
53
+ /**
54
+ * Record `owner`'s wakeup without touching the platform alarm, for use inside `alarm()`: the
55
+ * caller syncs once at the end, or not at all when it rethrows, which leaves the platform's own
56
+ * retry (with its backoff and cap) in force.
57
+ */
58
+ retain(owner: DurableObjectAlarmOwner, atMs: number, failures?: number): void;
59
+ /** Consecutive failures recorded with `owner`'s wakeup; 0 without one. */
60
+ failures(owner: DurableObjectAlarmOwner): number;
61
+ /** Remove `owner`'s wakeup whatever its time; call `sync` afterwards. */
62
+ clear(owner: DurableObjectAlarmOwner): void;
63
+ /** Wake `owner` no later than `atMs`; an earlier wakeup it already holds is kept. */
64
+ request(owner: DurableObjectAlarmOwner, atMs: number): Promise<void>;
65
+ /**
66
+ * Called when the platform alarm fires: the owners it fired for (every wakeup at or before now,
67
+ * and always the earliest one) and the wakeup each held. Nothing is consumed here: each owner
68
+ * `clearThrough`s its wakeup only after its work succeeds, so a handler that throws, or dies
69
+ * mid-work (eviction, deploy, a resource limit), leaves the platform's retry attributed to every
70
+ * owner it fired for. An owner's view already reports a past wakeup as no alarm, so the runtime's
71
+ * keep-alive re-arms during its work as it did with the platform alarm.
72
+ */
73
+ due(nowMs: number): ReadonlyMap<DurableObjectAlarmOwner, number>;
74
+ /**
75
+ * Remove `owner`'s wakeup if it is still at or before `atMs`, once the work it fired for has
76
+ * succeeded. A later wakeup the owner re-armed during that work is kept.
77
+ */
78
+ clearThrough(owner: DurableObjectAlarmOwner, atMs: number): void;
79
+ /** Point the platform alarm at the earliest wakeup, or clear it when none remains. */
80
+ sync(): Promise<void>;
81
+ }
82
+ //#endregion
83
+ //#region src/durable-object-transcript.d.ts
84
+ /**
85
+ * Maintenance state of one session's transcript, as a host backfill records it (§7).
86
+ *
87
+ * - `Enabled`: the host maintains this session's transcript. `converged` is the backfill's proof
88
+ * condition: the active version is `currentVersion`, healthy and at the head, and no builder or
89
+ * cleanup work remains.
90
+ * - `Disabled`: the host has not enabled this session (a rollout ring). It is reported read-only:
91
+ * any stored versions are listed as they are, nothing is maintained, and no incarnation is
92
+ * minted, so `incarnation` is present only when one already exists or can be adopted.
93
+ */
94
+ declare const TranscriptStorageStatus: Schema.Union<readonly [Schema.TaggedStruct<"Enabled", {
95
+ readonly incarnation: Schema.brand<Schema.NonEmptyString, "TranscriptLogIncarnation">;
96
+ readonly headSeq: Schema.brand<Schema.Int, "SequenceNumber">;
97
+ readonly currentVersion: Schema.brand<Schema.String, "TranscriptVersion">;
98
+ readonly versions: Schema.$Array<Schema.Struct<{
99
+ readonly version: Schema.brand<Schema.String, "TranscriptVersion">;
100
+ readonly role: Schema.Literals<readonly ["active", "building"]>;
101
+ readonly cursor: Schema.brand<Schema.Int, "SequenceNumber">;
102
+ readonly status: Schema.TaggedUnion<{
103
+ readonly Failed: Schema.TaggedStruct<"Failed", {
104
+ readonly failedAtSeq: Schema.brand<Schema.Int, "SequenceNumber">;
105
+ readonly error: Schema.String;
106
+ }>;
107
+ readonly Ok: Schema.TaggedStruct<"Ok", {}>;
108
+ }>;
109
+ }>>;
110
+ readonly pending: Schema.Boolean;
111
+ readonly converged: Schema.Boolean;
112
+ }>, Schema.TaggedStruct<"Disabled", {
113
+ readonly incarnation: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "TranscriptLogIncarnation">>;
114
+ readonly headSeq: Schema.brand<Schema.Int, "SequenceNumber">;
115
+ readonly currentVersion: Schema.brand<Schema.String, "TranscriptVersion">;
116
+ readonly versions: Schema.$Array<Schema.Struct<{
117
+ readonly version: Schema.brand<Schema.String, "TranscriptVersion">;
118
+ readonly role: Schema.Literals<readonly ["active", "building"]>;
119
+ readonly cursor: Schema.brand<Schema.Int, "SequenceNumber">;
120
+ readonly status: Schema.TaggedUnion<{
121
+ readonly Failed: Schema.TaggedStruct<"Failed", {
122
+ readonly failedAtSeq: Schema.brand<Schema.Int, "SequenceNumber">;
123
+ readonly error: Schema.String;
124
+ }>;
125
+ readonly Ok: Schema.TaggedStruct<"Ok", {}>;
126
+ }>;
127
+ }>>;
128
+ }>]>;
129
+ type TranscriptStorageStatus = typeof TranscriptStorageStatus.Type;
130
+ /** Construction options for the runtime-free transcript store of one session. */
131
+ interface DurableObjectTranscriptStoreOptions {
132
+ readonly sessionId: SessionId;
133
+ readonly storage: DurableObjectSessionStorage;
134
+ readonly transcript: DurableObjectTranscriptOptions;
135
+ }
136
+ /**
137
+ * Storage-level transcript service of one session Durable Object: reads, status and builder
138
+ * slices over the same SQLite tables the session store maintains in its appends.
139
+ *
140
+ * It never constructs the model runtime, reducers or sinks, so a cold object can serve SSR and
141
+ * CLI reads and advance a backfill without starting an agent. It holds no cache: every call
142
+ * reads storage, so a storage wipe or another writer is always observed. Every method is
143
+ * synchronous, which makes each window a single cut. Callers must have run the store migration.
144
+ */
145
+ declare class DurableObjectTranscriptStore {
146
+ #private;
147
+ constructor(options: DurableObjectTranscriptStoreOptions);
148
+ /** The `EDATranscriptStore` port over this store. */
149
+ static readonly layer: (options: DurableObjectTranscriptStoreOptions) => Layer.Layer<EDATranscriptStore, never, never>;
150
+ /** Read one complete window of the served version at a single cut. */
151
+ readWindow(selector: TranscriptWindowSelector, limits: TranscriptWindowLimits): Result.Result<TranscriptWindow, TranscriptCursorMismatch>;
152
+ /** Maintenance state of every version present. */
153
+ readMeta(): ReadonlyArray<TranscriptVersionMeta>;
154
+ /** Status for builders, backfill proofs and alerts. */
155
+ status(): Extract<TranscriptStorageStatus, {
156
+ readonly _tag: "Enabled";
157
+ }>;
158
+ /**
159
+ * Status of a session the host has not enabled, read without writing anything: no version is
160
+ * initialized or reconciled and no incarnation is minted.
161
+ */
162
+ disabledStatus(): Extract<TranscriptStorageStatus, {
163
+ readonly _tag: "Disabled";
164
+ }>;
165
+ /**
166
+ * This log's incarnation, minted (or adopted from the host's key) inside a transaction the
167
+ * same way window reads mint it. Body and summary reads check a reference against it.
168
+ */
169
+ incarnation(): TranscriptLogIncarnation;
170
+ /** Raise the missed-session alert if the active version is no longer carried. */
171
+ auditMissedSession(): void;
172
+ /** Whether a builder or cleanup slice has work to do. */
173
+ hasPendingWork(): boolean;
174
+ /** Run one bounded builder slice in its own transaction; returns whether work remains. */
175
+ runSlice(): boolean;
176
+ /** Raise an alert through the host observer. */
177
+ alert(alert: TranscriptAlert): void;
178
+ /** The `EDATranscriptStore` port: the same reads as Effects. */
179
+ get port(): EDATranscriptStoreShape;
180
+ }
181
+ /**
182
+ * Drives builder and cleanup slices for one session object (§7 "The builder").
183
+ *
184
+ * Builder state lives entirely in `_eda_transcript_meta`, so whichever entry point notices
185
+ * pending work — the constructor, an alarm, a status request — runs or schedules the next slice;
186
+ * nothing depends on in-memory state surviving eviction. Slices run through the storage service
187
+ * only and never construct the model runtime.
188
+ */
189
+ declare class DurableObjectTranscriptBuilder {
190
+ private readonly store;
191
+ /** Durably request a builder wakeup as soon as possible. */
192
+ private readonly wake;
193
+ constructor(store: DurableObjectTranscriptStore,
194
+ /** Durably request a builder wakeup as soon as possible. */
195
+ wake: () => Promise<void>);
196
+ /** At object start: raise standing alerts and schedule a slice if any work is pending. */
197
+ start(): Promise<void>;
198
+ /** Schedule a slice if any work is pending. */
199
+ kick(): Promise<void>;
200
+ /**
201
+ * Run up to `maxSlices` slices, letting other requests in between them, and schedule a
202
+ * continuation if work remains. Returns whether work remains.
203
+ */
204
+ run(maxSlices: number): Promise<boolean>;
205
+ /** Run up to `maxSlices` slices without scheduling a continuation; returns whether work remains. */
206
+ runSlices(maxSlices: number): Promise<boolean>;
207
+ }
208
+ //#endregion
209
+ //#region src/durable-object-store.d.ts
210
+ /**
211
+ * Durable Object SQLite-backed implementation of the semantic `EDASessionStore`.
212
+ *
213
+ * This adapter is the only place EDA framework storage code touches DO SQL. It
214
+ * translates domain append intent into synchronous SQLite writes while keeping
215
+ * `SessionState` and runners SQL-agnostic.
216
+ */
217
+ declare class DurableObjectSessionStore {
218
+ /** Run the single squashed framework migration for the current pre-release schema. */
219
+ static readonly migrate: (storage: DurableObjectSessionStorage) => Effect.Effect<void, EDASessionStoreError, never>;
220
+ /** Build a session-scoped store after migrations have completed. */
221
+ static readonly make: ({ sessionId, storage, transcript }: DurableObjectSessionStoreOptions) => Effect.Effect<EDASessionStoreShape, EDASessionStoreError>;
222
+ /** Layer constructor used by the Durable Object host runtime graph. */
223
+ static readonly layer: (options: DurableObjectSessionStoreOptions) => Layer.Layer<EDASessionStore, EDASessionStoreError, never>;
224
+ }
225
+ //#endregion
226
+ export { type AdoptedLogIncarnation, DurableObjectAlarmOwner, DurableObjectAlarmScheduler, DurableObjectSessionStorage, DurableObjectSessionStore, DurableObjectSessionStoreOptions, DurableObjectSqlCursor, DurableObjectSqlStorage, DurableObjectTranscriptBuilder, type DurableObjectTranscriptObserver, type DurableObjectTranscriptOptions, type DurableObjectTranscriptSliceLimits, DurableObjectTranscriptStore, DurableObjectTranscriptStoreOptions, EDADurableObjectRuntimeLayerOptions, EDAOpenAiModelConfig, EDAPreparedEventWebSocket, EDARpcSubmittable, EDASessionBlockOnCommandInput, EDASessionBlockOnCommandRpcInput, EDASessionCommandRpcInput, EDASessionController, EDASessionControllerOptions, EDASessionDurableObject, EDASessionDurableObjectOptions, EDASessionDurableObjectStorage, EDASessionEventsInput, EDASessionEventsRpcInput, EDASessionGrantRunRpcInput, EDASessionRpcSurface, EDASessionRunRequestOutcomeRpcInput, EDASessionScopedInput, EDASessionScopedRpcInput, EDASessionSubmitBatchInput, EDASessionSubmitBatchRpcInput, EDASessionSubmitInput, EDASessionTranscriptOptions, type EDATranscriptSocketOptions, EDAWebSocketProjection, EDAWebSocketProjectionId, EDAWebSocketProjectionInitial, EDAWebSocketProjectionResult, EDA_WEB_SOCKET_PROJECTION_HEADER, EDA_WEB_SOCKET_STREAM_PARAM, SessionBatchInput, SessionBlockInput, SessionCommandInput, SessionGrantRunInput, SessionOutcomeInput, SessionScopedInput, SessionTranscriptBodyInput, SessionTranscriptBodyResult, SessionTranscriptSummaryInput, SessionTranscriptSummaryResult, SessionTranscriptWindowInput, SessionTranscriptWindowResult, type TranscriptAlert, TranscriptCompactionSummary, TranscriptStorageStatus, decodeEdaRpcCommand, decodeEdaRpcSubmittables, defaultActiveContentCadenceMs, edaRuntimeConfig, edaSessionRpc, encodeEdaRpcCommand, encodeEdaRpcCommittedDurableEvent, encodeEdaRpcDurableEvent, encodeEdaRpcSessionSnapshot, encodeEdaRpcSubmittables, getEDASessionDurableObjectByName, makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer, makeEDADurableObjectRuntimeLayer, makeEDAOpenAiClientLayer };
227
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- import { decodeEdaRpcCommand, decodeEdaRpcSubmittables, encodeEdaRpcCommand, encodeEdaRpcDurableEvent, encodeEdaRpcSubmittables } from "./rpc.js";
2
- import { n as EDAWebSocketProjectionId, r as makeEDADurableObjectRuntimeLayer, t as EDASessionController } from "./session-controller-COHH8vA6.js";
3
- import { EDASessionDurableObject, EDA_WEB_SOCKET_PROJECTION_HEADER, edaRuntimeConfig, encodeEdaRpcCommittedDurableEvent, encodeEdaRpcSessionSnapshot, getEDASessionDurableObjectByName } from "./durable-object.js";
1
+ import { C as encodeEdaRpcSubmittables, S as encodeEdaRpcDurableEvent, _ as TranscriptStorageStatus, a as SessionOutcomeInput, b as decodeEdaRpcSubmittables, c as SessionTranscriptBodyResult, d as SessionTranscriptWindowInput, f as SessionTranscriptWindowResult, g as DurableObjectTranscriptStore, h as DurableObjectTranscriptBuilder, i as SessionGrantRunInput, l as SessionTranscriptSummaryInput, m as edaSessionRpc, n as SessionBlockInput, o as SessionScopedInput, p as TranscriptCompactionSummary, r as SessionCommandInput, s as SessionTranscriptBodyInput, t as SessionBatchInput, u as SessionTranscriptSummaryResult, v as EDARpcSubmittable, x as encodeEdaRpcCommand, y as decodeEdaRpcCommand } from "./rpc-spec-BRNFIsY1.js";
2
+ import { t as DurableObjectSessionStore } from "./durable-object-store-yY_KaFtw.js";
3
+ import { i as makeEDADurableObjectRuntimeLayer, n as defaultActiveContentCadenceMs, r as EDAWebSocketProjectionId, t as EDASessionController } from "./session-controller-BCtnyAEw.js";
4
+ import { a as encodeEdaRpcCommittedDurableEvent, c as DurableObjectAlarmScheduler, i as edaRuntimeConfig, n as EDA_WEB_SOCKET_PROJECTION_HEADER, o as encodeEdaRpcSessionSnapshot, r as EDA_WEB_SOCKET_STREAM_PARAM, s as getEDASessionDurableObjectByName, t as EDASessionDurableObject } from "./durable-object-DAQzdio7.js";
4
5
  import "./storage.js";
5
- import { makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer } from "./openai.js";
6
- export { EDASessionController, EDASessionDurableObject, EDAWebSocketProjectionId, EDA_WEB_SOCKET_PROJECTION_HEADER, decodeEdaRpcCommand, decodeEdaRpcSubmittables, edaRuntimeConfig, encodeEdaRpcCommand, encodeEdaRpcCommittedDurableEvent, encodeEdaRpcDurableEvent, encodeEdaRpcSessionSnapshot, encodeEdaRpcSubmittables, getEDASessionDurableObjectByName, makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer, makeEDADurableObjectRuntimeLayer };
6
+ import { makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer, makeEDAOpenAiClientLayer } from "./openai.js";
7
+ export { DurableObjectAlarmScheduler, DurableObjectSessionStore, DurableObjectTranscriptBuilder, DurableObjectTranscriptStore, EDARpcSubmittable, EDASessionController, EDASessionDurableObject, EDAWebSocketProjectionId, EDA_WEB_SOCKET_PROJECTION_HEADER, EDA_WEB_SOCKET_STREAM_PARAM, SessionBatchInput, SessionBlockInput, SessionCommandInput, SessionGrantRunInput, SessionOutcomeInput, SessionScopedInput, SessionTranscriptBodyInput, SessionTranscriptBodyResult, SessionTranscriptSummaryInput, SessionTranscriptSummaryResult, SessionTranscriptWindowInput, SessionTranscriptWindowResult, TranscriptCompactionSummary, TranscriptStorageStatus, decodeEdaRpcCommand, decodeEdaRpcSubmittables, defaultActiveContentCadenceMs, edaRuntimeConfig, edaSessionRpc, encodeEdaRpcCommand, encodeEdaRpcCommittedDurableEvent, encodeEdaRpcDurableEvent, encodeEdaRpcSessionSnapshot, encodeEdaRpcSubmittables, getEDASessionDurableObjectByName, makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer, makeEDADurableObjectRuntimeLayer, makeEDAOpenAiClientLayer };
package/dist/openai.d.ts CHANGED
@@ -1,9 +1,8 @@
1
- import { ModelSelectionPayload } from "effect-durable-agent/types/events";
2
1
  import * as Layer from "effect/Layer";
3
- import { OpenAiLanguageModel } from "@effect/ai-openai";
2
+ import { ModelSelectionPayload } from "effect-durable-agent/types/events";
3
+ import { OpenAiClient, OpenAiLanguageModel } from "@effect/ai-openai";
4
4
  import { ModelResolver } from "effect-durable-agent/services/model-resolver";
5
- import * as LanguageModel from "effect/unstable/ai/LanguageModel";
6
-
5
+ import * as LanguageModel from "effect/ai/LanguageModel";
7
6
  //#region src/providers/openai.d.ts
8
7
  /** Provider request defaults accepted by EDA's OpenAI Responses model adapter. */
9
8
  type EDAOpenAiModelConfig = Omit<typeof OpenAiLanguageModel.Config.Service, "model">;
@@ -25,6 +24,12 @@ declare const makeEDADurableObjectOpenAiModelLayer: (options: {
25
24
  readonly config?: EDAOpenAiModelConfig;
26
25
  readonly modelId: string;
27
26
  }) => Layer.Layer<LanguageModel.LanguageModel>;
27
+ /** OpenAI client layer over EDA's provider transport (Cloudflare AI Gateway or `fetch`). */
28
+ declare const makeEDAOpenAiClientLayer: (options: {
29
+ readonly aiGateway?: AiGateway | undefined;
30
+ readonly apiKey?: string | undefined;
31
+ readonly apiUrl?: string | undefined;
32
+ }) => Layer.Layer<OpenAiClient.OpenAiClient>;
28
33
  //#endregion
29
- export { EDAOpenAiModelConfig, makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer };
34
+ export { EDAOpenAiModelConfig, makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer, makeEDAOpenAiClientLayer };
30
35
  //# sourceMappingURL=openai.d.ts.map
package/dist/openai.js CHANGED
@@ -1,23 +1,15 @@
1
- import * as Effect from "effect/Effect";
1
+ import { r as makeEDAProviderHttpClient } from "./transport-BzgK07l4.js";
2
2
  import * as Layer from "effect/Layer";
3
+ import * as Redacted from "effect/Redacted";
4
+ import * as HttpClient from "effect/http/HttpClient";
5
+ import * as Effect from "effect/Effect";
3
6
  import { OpenAiClient, OpenAiLanguageModel } from "@effect/ai-openai";
4
7
  import { ModelResolver } from "effect-durable-agent/services/model-resolver";
5
- import * as Redacted from "effect/Redacted";
6
- import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
7
- import "effect/unstable/http/HttpBody";
8
- import * as HttpClient from "effect/unstable/http/HttpClient";
9
- import * as HttpClientError from "effect/unstable/http/HttpClientError";
10
- import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
11
8
  //#region src/providers/openai.ts
12
9
  /** Resolves each durable selection while sharing the provider transport for the runtime lifetime. */
13
10
  const makeEDADurableObjectOpenAiModelResolverLayer = (options) => {
14
- const apiKey = optionalNonEmptyString(options.apiKey);
15
- if (apiKey === void 0 && options.aiGateway === void 0) throw new Error("OPENAI_API_KEY is required unless the EDA OpenAI model resolver is backed by a Cloudflare AI Gateway binding.");
16
- const transport = options.aiGateway === void 0 ? FetchHttpClient.layer : Layer.succeed(HttpClient.HttpClient, makeAiGatewayHttpClient(options.aiGateway));
17
- const client = OpenAiClient.layer({
18
- ...apiKey === void 0 ? {} : { apiKey: Redacted.make(apiKey) },
19
- ...options.apiUrl === void 0 ? {} : { apiUrl: options.apiUrl }
20
- }).pipe(Layer.provide(transport));
11
+ if (optionalNonEmptyString(options.apiKey) === void 0 && options.aiGateway === void 0) throw new Error("OPENAI_API_KEY is required unless the EDA OpenAI model resolver is backed by a Cloudflare AI Gateway binding.");
12
+ const client = makeEDAOpenAiClientLayer(options);
21
13
  return Layer.effect(ModelResolver, Effect.gen(function* () {
22
14
  const provider = yield* OpenAiClient.OpenAiClient;
23
15
  return { resolve: Effect.fn("OpenAiModelResolver.resolve")(function* (selection) {
@@ -31,50 +23,30 @@ const makeEDADurableObjectOpenAiModelResolverLayer = (options) => {
31
23
  };
32
24
  /** OpenAI-backed Effect AI model layer for a Cloudflare Worker. */
33
25
  const makeEDADurableObjectOpenAiModelLayer = (options) => {
34
- const apiKey = optionalNonEmptyString(options.apiKey);
35
- 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.");
36
- const httpClient = options.aiGateway === void 0 ? FetchHttpClient.layer : Layer.succeed(HttpClient.HttpClient, makeAiGatewayHttpClient(options.aiGateway));
37
- const client = OpenAiClient.layer({
38
- ...apiKey === void 0 ? {} : { apiKey: Redacted.make(apiKey) },
39
- ...options.apiUrl === void 0 ? {} : { apiUrl: options.apiUrl }
40
- }).pipe(Layer.provide(httpClient));
26
+ if (optionalNonEmptyString(options.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.");
27
+ const client = makeEDAOpenAiClientLayer(options);
41
28
  return OpenAiLanguageModel.layer({
42
29
  model: options.modelId,
43
30
  ...options.config === void 0 ? {} : { config: options.config }
44
31
  }).pipe(Layer.provide(client));
45
32
  };
46
- const makeAiGatewayHttpClient = (gateway) => HttpClient.make((request, url, signal) => Effect.tryPromise({
47
- try: async () => {
48
- const response = await gateway.run({
49
- endpoint: endpointFromUrl(url),
50
- headers: Object.fromEntries(Object.entries(request.headers).filter((entry) => typeof entry[1] === "string" && entry[0].toLowerCase() !== "host")),
51
- provider: "openai",
52
- query: requestBody(request.body)
53
- }, { signal });
54
- return HttpClientResponse.fromWeb(request, response);
55
- },
56
- catch: (cause) => new HttpClientError.HttpClientError({ reason: new HttpClientError.TransportError({
57
- request,
58
- cause,
59
- description: "Cloudflare AI Gateway request failed"
60
- }) })
61
- }));
62
- const endpointFromUrl = (url) => {
63
- return `${url.pathname.startsWith("/v1/") ? url.pathname.slice(4) : url.pathname.replace(/^\/+/, "")}${url.search}`;
64
- };
65
- const requestBody = (body) => {
66
- switch (body._tag) {
67
- case "Empty": return;
68
- case "Raw": return body.body;
69
- case "Uint8Array": return JSON.parse(new TextDecoder().decode(body.body));
70
- default: throw new Error(`Unsupported OpenAI request body for Cloudflare AI Gateway: ${body._tag}`);
71
- }
33
+ /** OpenAI client layer over EDA's provider transport (Cloudflare AI Gateway or `fetch`). */
34
+ const makeEDAOpenAiClientLayer = (options) => {
35
+ const apiKey = optionalNonEmptyString(options.apiKey);
36
+ if (apiKey === void 0 && options.aiGateway === void 0) throw new Error("OPENAI_API_KEY is required unless the EDA OpenAI client is backed by a Cloudflare AI Gateway binding.");
37
+ return OpenAiClient.layer({
38
+ ...apiKey === void 0 ? {} : { apiKey: Redacted.make(apiKey) },
39
+ ...options.apiUrl === void 0 ? {} : { apiUrl: options.apiUrl }
40
+ }).pipe(Layer.provide(Layer.succeed(HttpClient.HttpClient, makeEDAProviderHttpClient({
41
+ provider: "openai",
42
+ aiGateway: options.aiGateway
43
+ }))));
72
44
  };
73
45
  const optionalNonEmptyString = (value) => {
74
46
  const trimmed = value?.trim();
75
47
  return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
76
48
  };
77
49
  //#endregion
78
- export { makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer };
50
+ export { makeEDADurableObjectOpenAiModelLayer, makeEDADurableObjectOpenAiModelResolverLayer, makeEDAOpenAiClientLayer };
79
51
 
80
52
  //# sourceMappingURL=openai.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai.js","names":[],"sources":["../src/providers/openai.ts"],"sourcesContent":["import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\";\nimport { ModelResolver } from \"effect-durable-agent/services/model-resolver\";\nimport type { ModelSelectionPayload } from \"effect-durable-agent/types/events\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Redacted from \"effect/Redacted\";\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 HttpClientResponse from \"effect/unstable/http/HttpClientResponse\";\n\n/** Provider request defaults accepted by EDA's OpenAI Responses model adapter. */\nexport type EDAOpenAiModelConfig = Omit<typeof OpenAiLanguageModel.Config.Service, \"model\">;\n\n/** Resolves each durable selection while sharing the provider transport for the runtime lifetime. */\nexport const makeEDADurableObjectOpenAiModelResolverLayer = (options: {\n readonly aiGateway?: AiGateway;\n readonly apiKey?: string;\n readonly apiUrl?: string;\n readonly resolve: (selection: ModelSelectionPayload | undefined) => {\n readonly modelId: string;\n readonly config: EDAOpenAiModelConfig;\n };\n}): Layer.Layer<ModelResolver> => {\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 resolver is backed by a Cloudflare AI Gateway binding.\",\n );\n }\n const transport =\n options.aiGateway === undefined\n ? FetchHttpClient.layer\n : Layer.succeed(HttpClient.HttpClient, makeAiGatewayHttpClient(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(transport));\n return Layer.effect(\n ModelResolver,\n Effect.gen(function* () {\n const provider = yield* OpenAiClient.OpenAiClient;\n return {\n resolve: Effect.fn(\"OpenAiModelResolver.resolve\")(function* (selection) {\n const resolved = options.resolve(selection);\n return yield* OpenAiLanguageModel.make({\n model: resolved.modelId,\n config: resolved.config,\n }).pipe(Effect.provideService(OpenAiClient.OpenAiClient, provider));\n }),\n };\n }),\n ).pipe(Layer.provide(client));\n};\n\n/** OpenAI-backed Effect AI model layer for a Cloudflare Worker. */\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 httpClient =\n options.aiGateway === undefined\n ? FetchHttpClient.layer\n : Layer.succeed(HttpClient.HttpClient, makeAiGatewayHttpClient(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(httpClient));\n\n return OpenAiLanguageModel.layer({\n model: options.modelId,\n ...(options.config === undefined ? {} : { config: options.config }),\n }).pipe(Layer.provide(client));\n};\n\nconst makeAiGatewayHttpClient = (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: endpointFromUrl(url),\n headers: Object.fromEntries(\n Object.entries(request.headers).filter(\n (entry): entry is [string, string] =>\n typeof entry[1] === \"string\" && entry[0].toLowerCase() !== \"host\",\n ),\n ),\n provider: \"openai\",\n query: requestBody(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 endpointFromUrl = (url: URL): string => {\n const path = url.pathname.startsWith(\"/v1/\")\n ? url.pathname.slice(\"/v1/\".length)\n : url.pathname.replace(/^\\/+/, \"\");\n return `${path}${url.search}`;\n};\n\nconst requestBody = (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"],"mappings":";;;;;;;;;;;;AAiBA,MAAa,gDAAgD,YAQ3B;CAChC,MAAM,SAAS,uBAAuB,QAAQ,MAAM;CACpD,IAAI,WAAW,KAAA,KAAa,QAAQ,cAAc,KAAA,GAChD,MAAM,IAAI,MACR,+GACF;CAEF,MAAM,YACJ,QAAQ,cAAc,KAAA,IAClB,gBAAgB,QAChB,MAAM,QAAQ,WAAW,YAAY,wBAAwB,QAAQ,SAAS,CAAC;CACrF,MAAM,SAAS,aAAa,MAAM;EAChC,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,SAAS,KAAK,MAAM,EAAE;EAChE,GAAI,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CACnE,CAAC,EAAE,KAAK,MAAM,QAAQ,SAAS,CAAC;CAChC,OAAO,MAAM,OACX,eACA,OAAO,IAAI,aAAa;EACtB,MAAM,WAAW,OAAO,aAAa;EACrC,OAAO,EACL,SAAS,OAAO,GAAG,6BAA6B,EAAE,WAAW,WAAW;GACtE,MAAM,WAAW,QAAQ,QAAQ,SAAS;GAC1C,OAAO,OAAO,oBAAoB,KAAK;IACrC,OAAO,SAAS;IAChB,QAAQ,SAAS;GACnB,CAAC,EAAE,KAAK,OAAO,eAAe,aAAa,cAAc,QAAQ,CAAC;EACpE,CAAC,EACH;CACF,CAAC,CACH,EAAE,KAAK,MAAM,QAAQ,MAAM,CAAC;AAC9B;;AAGA,MAAa,wCAAwC,YAML;CAC9C,MAAM,SAAS,uBAAuB,QAAQ,MAAM;CACpD,IAAI,WAAW,KAAA,KAAa,QAAQ,cAAc,KAAA,GAChD,MAAM,IAAI,MACR,4GACF;CAGF,MAAM,aACJ,QAAQ,cAAc,KAAA,IAClB,gBAAgB,QAChB,MAAM,QAAQ,WAAW,YAAY,wBAAwB,QAAQ,SAAS,CAAC;CACrF,MAAM,SAAS,aAAa,MAAM;EAChC,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,SAAS,KAAK,MAAM,EAAE;EAChE,GAAI,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CACnE,CAAC,EAAE,KAAK,MAAM,QAAQ,UAAU,CAAC;CAEjC,OAAO,oBAAoB,MAAM;EAC/B,OAAO,QAAQ;EACf,GAAI,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CACnE,CAAC,EAAE,KAAK,MAAM,QAAQ,MAAM,CAAC;AAC/B;AAEA,MAAM,2BAA2B,YAC/B,WAAW,MAAM,SAAS,KAAK,WAC7B,OAAO,WAAW;CAChB,KAAK,YAAY;EACf,MAAM,WAAW,MAAM,QAAQ,IAC7B;GACE,UAAU,gBAAgB,GAAG;GAC7B,SAAS,OAAO,YACd,OAAO,QAAQ,QAAQ,OAAO,EAAE,QAC7B,UACC,OAAO,MAAM,OAAO,YAAY,MAAM,GAAG,YAAY,MAAM,MAC/D,CACF;GACA,UAAU;GACV,OAAO,YAAY,QAAQ,IAAI;EACjC,GACA,EAAE,OAAO,CACX;EACA,OAAO,mBAAmB,QAAQ,SAAS,QAAQ;CACrD;CACA,QAAQ,UACN,IAAI,gBAAgB,gBAAgB,EAClC,QAAQ,IAAI,gBAAgB,eAAe;EACzC;EACA;EACA,aAAa;CACf,CAAC,EACH,CAAC;AACL,CAAC,CACH;AAEF,MAAM,mBAAmB,QAAqB;CAI5C,OAAO,GAHM,IAAI,SAAS,WAAW,MAAM,IACvC,IAAI,SAAS,MAAM,CAAa,IAChC,IAAI,SAAS,QAAQ,QAAQ,EAAE,IAClB,IAAI;AACvB;AAEA,MAAM,eAAe,SAAqC;CACxD,QAAQ,KAAK,MAAb;EACE,KAAK,SACH;EACF,KAAK,OACH,OAAO,KAAK;EACd,KAAK,cACH,OAAO,KAAK,MAAM,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI,CAAC;EACvD,SACE,MAAM,IAAI,MAAM,8DAA8D,KAAK,MAAM;CAC7F;AACF;AAEA,MAAM,0BAA0B,UAAkD;CAChF,MAAM,UAAU,OAAO,KAAK;CAC5B,OAAO,YAAY,KAAA,KAAa,QAAQ,WAAW,IAAI,KAAA,IAAY;AACrE"}
1
+ {"version":3,"file":"openai.js","names":[],"sources":["../src/providers/openai.ts"],"sourcesContent":["import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\";\nimport { ModelResolver } from \"effect-durable-agent/services/model-resolver\";\nimport type { ModelSelectionPayload } from \"effect-durable-agent/types/events\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Redacted from \"effect/Redacted\";\nimport type * as LanguageModel from \"effect/ai/LanguageModel\";\nimport * as HttpClient from \"effect/http/HttpClient\";\n\nimport { makeEDAProviderHttpClient } from \"./transport\";\n\n/** Provider request defaults accepted by EDA's OpenAI Responses model adapter. */\nexport type EDAOpenAiModelConfig = Omit<typeof OpenAiLanguageModel.Config.Service, \"model\">;\n\n/** Resolves each durable selection while sharing the provider transport for the runtime lifetime. */\nexport const makeEDADurableObjectOpenAiModelResolverLayer = (options: {\n readonly aiGateway?: AiGateway;\n readonly apiKey?: string;\n readonly apiUrl?: string;\n readonly resolve: (selection: ModelSelectionPayload | undefined) => {\n readonly modelId: string;\n readonly config: EDAOpenAiModelConfig;\n };\n}): Layer.Layer<ModelResolver> => {\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 resolver is backed by a Cloudflare AI Gateway binding.\",\n );\n }\n const client = makeEDAOpenAiClientLayer(options);\n return Layer.effect(\n ModelResolver,\n Effect.gen(function* () {\n const provider = yield* OpenAiClient.OpenAiClient;\n return {\n resolve: Effect.fn(\"OpenAiModelResolver.resolve\")(function* (selection) {\n const resolved = options.resolve(selection);\n return yield* OpenAiLanguageModel.make({\n model: resolved.modelId,\n config: resolved.config,\n }).pipe(Effect.provideService(OpenAiClient.OpenAiClient, provider));\n }),\n };\n }),\n ).pipe(Layer.provide(client));\n};\n\n/** OpenAI-backed Effect AI model layer for a Cloudflare Worker. */\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 client = makeEDAOpenAiClientLayer(options);\n\n return OpenAiLanguageModel.layer({\n model: options.modelId,\n ...(options.config === undefined ? {} : { config: options.config }),\n }).pipe(Layer.provide(client));\n};\n\n/** OpenAI client layer over EDA's provider transport (Cloudflare AI Gateway or `fetch`). */\nexport const makeEDAOpenAiClientLayer = (options: {\n readonly aiGateway?: AiGateway | undefined;\n readonly apiKey?: string | undefined;\n readonly apiUrl?: string | undefined;\n}): Layer.Layer<OpenAiClient.OpenAiClient> => {\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 client is backed by a Cloudflare AI Gateway binding.\",\n );\n }\n return OpenAiClient.layer({\n ...(apiKey === undefined ? {} : { apiKey: Redacted.make(apiKey) }),\n ...(options.apiUrl === undefined ? {} : { apiUrl: options.apiUrl }),\n }).pipe(\n Layer.provide(\n Layer.succeed(\n HttpClient.HttpClient,\n makeEDAProviderHttpClient({ provider: \"openai\", aiGateway: options.aiGateway }),\n ),\n ),\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"],"mappings":";;;;;;;;;AAeA,MAAa,gDAAgD,YAQ3B;CAEhC,IADe,uBAAuB,QAAQ,MACrC,MAAM,KAAA,KAAa,QAAQ,cAAc,KAAA,GAChD,MAAM,IAAI,MACR,+GACF;CAEF,MAAM,SAAS,yBAAyB,OAAO;CAC/C,OAAO,MAAM,OACX,eACA,OAAO,IAAI,aAAa;EACtB,MAAM,WAAW,OAAO,aAAa;EACrC,OAAO,EACL,SAAS,OAAO,GAAG,6BAA6B,CAAC,CAAC,WAAW,WAAW;GACtE,MAAM,WAAW,QAAQ,QAAQ,SAAS;GAC1C,OAAO,OAAO,oBAAoB,KAAK;IACrC,OAAO,SAAS;IAChB,QAAQ,SAAS;GACnB,CAAC,CAAC,CAAC,KAAK,OAAO,eAAe,aAAa,cAAc,QAAQ,CAAC;EACpE,CAAC,EACH;CACF,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,MAAM,CAAC;AAC9B;;AAGA,MAAa,wCAAwC,YAML;CAE9C,IADe,uBAAuB,QAAQ,MACrC,MAAM,KAAA,KAAa,QAAQ,cAAc,KAAA,GAChD,MAAM,IAAI,MACR,4GACF;CAGF,MAAM,SAAS,yBAAyB,OAAO;CAE/C,OAAO,oBAAoB,MAAM;EAC/B,OAAO,QAAQ;EACf,GAAI,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CACnE,CAAC,CAAC,CAAC,KAAK,MAAM,QAAQ,MAAM,CAAC;AAC/B;;AAGA,MAAa,4BAA4B,YAIK;CAC5C,MAAM,SAAS,uBAAuB,QAAQ,MAAM;CACpD,IAAI,WAAW,KAAA,KAAa,QAAQ,cAAc,KAAA,GAChD,MAAM,IAAI,MACR,uGACF;CAEF,OAAO,aAAa,MAAM;EACxB,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,SAAS,KAAK,MAAM,EAAE;EAChE,GAAI,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CACnE,CAAC,CAAC,CAAC,KACD,MAAM,QACJ,MAAM,QACJ,WAAW,YACX,0BAA0B;EAAE,UAAU;EAAU,WAAW,QAAQ;CAAU,CAAC,CAChF,CACF,CACF;AACF;AAEA,MAAM,0BAA0B,UAAkD;CAChF,MAAM,UAAU,OAAO,KAAK;CAC5B,OAAO,YAAY,KAAA,KAAa,QAAQ,WAAW,IAAI,KAAA,IAAY;AACrE"}