@effect-agent/platform-cloudflare 0.0.1-beta.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.
- package/dist/index.d.mts +1486 -0
- package/dist/index.mjs +1073 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +56 -0
- package/src/alarm.ts +334 -0
- package/src/bindings.ts +145 -0
- package/src/client.ts +646 -0
- package/src/config.ts +137 -0
- package/src/conversation-object.ts +709 -0
- package/src/index.ts +22 -0
- package/src/layers.ts +376 -0
- package/src/transport.ts +38 -0
- package/src/wake-scheduler.ts +85 -0
|
@@ -0,0 +1,709 @@
|
|
|
1
|
+
import type { AgentId } from "@effect-agent/core";
|
|
2
|
+
import { SubmissionId } from "@effect-agent/core";
|
|
3
|
+
import {
|
|
4
|
+
AppendConflict,
|
|
5
|
+
ConversationNotMaterialized,
|
|
6
|
+
ConversationRead,
|
|
7
|
+
ConversationStore,
|
|
8
|
+
ConversationStoreError,
|
|
9
|
+
DigestError,
|
|
10
|
+
DurableAgentRuntime,
|
|
11
|
+
DurableRuntimeFailpointError,
|
|
12
|
+
FenceRejected,
|
|
13
|
+
IntegrityReport,
|
|
14
|
+
LedgerError,
|
|
15
|
+
ObligationReport,
|
|
16
|
+
ObligationThresholds,
|
|
17
|
+
OperationAuthorizationRequest,
|
|
18
|
+
OperationAuthorizer,
|
|
19
|
+
OperationDenied,
|
|
20
|
+
OwnershipLost,
|
|
21
|
+
PersistedJson,
|
|
22
|
+
RecoveryExplanation,
|
|
23
|
+
RecoveryReport,
|
|
24
|
+
RetryCommand,
|
|
25
|
+
RetryRefused,
|
|
26
|
+
RunJournalError,
|
|
27
|
+
SettlementConflict,
|
|
28
|
+
SubmissionLedger,
|
|
29
|
+
SubmissionLookupByKey,
|
|
30
|
+
type DurableSubmitAgent,
|
|
31
|
+
} from "@effect-agent/session";
|
|
32
|
+
import { DurableObject } from "cloudflare:workers";
|
|
33
|
+
import { Effect, Layer, ManagedRuntime, Option, Schema, Stream } from "effect";
|
|
34
|
+
|
|
35
|
+
import { ConversationMaintenance, DurableAlarmError, DurableAlarmService } from "./alarm.ts";
|
|
36
|
+
import {
|
|
37
|
+
ConversationObjectIdentity,
|
|
38
|
+
DurableObjectContext,
|
|
39
|
+
conversationNamespaceLayer,
|
|
40
|
+
type CloudflareBindingError,
|
|
41
|
+
type ConversationObjectRpc,
|
|
42
|
+
} from "./bindings.ts";
|
|
43
|
+
import {
|
|
44
|
+
AbortRecorded,
|
|
45
|
+
ApprovalRecorded,
|
|
46
|
+
HostFailed,
|
|
47
|
+
HostProtocolError,
|
|
48
|
+
ObservedPage,
|
|
49
|
+
SettlementReached,
|
|
50
|
+
SubmitSucceeded,
|
|
51
|
+
UnknownResolutionRecorded,
|
|
52
|
+
boundHostDiagnostic,
|
|
53
|
+
decodeAbortCommand,
|
|
54
|
+
decodeApprovalDecisionCommand,
|
|
55
|
+
decodeObservePageRequest,
|
|
56
|
+
decodeReceipt,
|
|
57
|
+
decodeSubmitRequest,
|
|
58
|
+
decodeUnknownResolutionCommand,
|
|
59
|
+
encodeHostResponse,
|
|
60
|
+
type HostFailure,
|
|
61
|
+
type HostResponse,
|
|
62
|
+
} from "./client.ts";
|
|
63
|
+
import { AdmissionLimitExceeded, CloudflareDurableRuntimeConfig } from "./config.ts";
|
|
64
|
+
import {
|
|
65
|
+
CloudflareDurableRuntime,
|
|
66
|
+
ConversationObjectPorts,
|
|
67
|
+
type CloudflareDurableRuntimeInitializationError,
|
|
68
|
+
type CloudflareDurableRuntimeOptions,
|
|
69
|
+
type CloudflareDurableRuntimeServices,
|
|
70
|
+
} from "./layers.ts";
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* `makeConversationObjectClass(options)` — the Conversation Durable Object (plan §1.4,
|
|
74
|
+
* D-P6-1): a factory returning a class that applications export from their Worker entry.
|
|
75
|
+
* One SQLite-backed Object per Conversation is the serialized owner (durability §6); the
|
|
76
|
+
* Object never runs `runResolvedWorker`'s infinite loop — each ingress event or alarm runs
|
|
77
|
+
* ONE bounded `runRecovery` + `processConversationResolved` pass, and the persisted alarm
|
|
78
|
+
* (the single multiplexed slot, D-P6-2) finishes accepted work across evictions WITHOUT any
|
|
79
|
+
* incoming request.
|
|
80
|
+
*
|
|
81
|
+
* Constructor gate (`blockConcurrencyWhile`) is LOCAL-ONLY: schema migration and the
|
|
82
|
+
* exact-version check, configuration decode, and the defensive ensure-alarm half of the
|
|
83
|
+
* alarm invariant. It deliberately does NOT run the recovery pass: parent recovery can
|
|
84
|
+
* require child-Object reads and vice versa, and two Objects blocked in constructor gates
|
|
85
|
+
* awaiting each other's RPC would deadlock (plan §1.4). Instead every pass runs
|
|
86
|
+
* `runRecovery` BEFORE any claim, so reconciliation still strictly precedes new work.
|
|
87
|
+
*/
|
|
88
|
+
|
|
89
|
+
/** Construction options for one deployed Conversation Object class. */
|
|
90
|
+
export interface ConversationObjectOptions extends CloudflareDurableRuntimeOptions {
|
|
91
|
+
/**
|
|
92
|
+
* Name of the Worker `env` binding carrying THIS class's `DurableObjectNamespace` — the
|
|
93
|
+
* Object's route back to sibling Conversation Objects for the WP2 cross-Object port calls
|
|
94
|
+
* and remote wakes (DEPLOY-010: the binding enters through a Layer, never ambiently).
|
|
95
|
+
*/
|
|
96
|
+
readonly namespaceBinding: string;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Public instance surface of the class returned by `makeConversationObjectClass`. It includes
|
|
101
|
+
* the Worker/sibling RPC contract, the administrative RPC entry points, the platform alarm
|
|
102
|
+
* handler, and the inherited Object context used by application subclasses.
|
|
103
|
+
*/
|
|
104
|
+
export interface ConversationObjectInstance
|
|
105
|
+
extends DurableObject<Cloudflare.Env>, ConversationObjectRpc {
|
|
106
|
+
explainEncoded(encoded: unknown): Promise<unknown>;
|
|
107
|
+
verifyEncoded(encoded: unknown): Promise<unknown>;
|
|
108
|
+
retryEncoded(encoded: unknown): Promise<unknown>;
|
|
109
|
+
obligationsEncoded(encoded: unknown): Promise<unknown>;
|
|
110
|
+
alarm(): Promise<void>;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Public constructor returned by `makeConversationObjectClass`. */
|
|
114
|
+
export interface ConversationObjectConstructor {
|
|
115
|
+
new (ctx: DurableObjectState, env: Cloudflare.Env): ConversationObjectInstance;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
type ConversationObjectError = CloudflareDurableRuntimeInitializationError | CloudflareBindingError;
|
|
119
|
+
|
|
120
|
+
type EndpointServices = CloudflareDurableRuntimeServices | DurableObjectContext;
|
|
121
|
+
|
|
122
|
+
/** Port envelope tags whose owner-side execution durably mutates this Object's lane. */
|
|
123
|
+
const MUTATING_PORT_TAGS: ReadonlySet<string> = new Set([
|
|
124
|
+
"LedgerAdmit",
|
|
125
|
+
"LedgerMarkReady",
|
|
126
|
+
"LedgerRequestAbort",
|
|
127
|
+
"LedgerRecordChildSettled",
|
|
128
|
+
"StoreMaterialize",
|
|
129
|
+
"StoreAppend",
|
|
130
|
+
]);
|
|
131
|
+
|
|
132
|
+
const isMutatingPortRequest = (encoded: unknown): boolean =>
|
|
133
|
+
typeof encoded === "object" &&
|
|
134
|
+
encoded !== null &&
|
|
135
|
+
"_tag" in encoded &&
|
|
136
|
+
typeof encoded._tag === "string" &&
|
|
137
|
+
MUTATING_PORT_TAGS.has(encoded._tag);
|
|
138
|
+
|
|
139
|
+
/** The literal encoded `PortFailed(PortProtocolError)` fallback (same shape as WP2's). */
|
|
140
|
+
const encodedPortProtocolFailure = (message: string): unknown => ({
|
|
141
|
+
_tag: "PortFailed",
|
|
142
|
+
failure: { _tag: "PortProtocolError", message: boundHostDiagnostic(message) },
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const protocolFailure = (context: string) => (error: { readonly message: string }) =>
|
|
146
|
+
HostProtocolError.make({
|
|
147
|
+
message: boundHostDiagnostic(`${context}: ${error.message}`),
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
/** Fold one endpoint's typed failures into the uniform `HostResponse` envelope. */
|
|
151
|
+
const respond = <Result extends HostResponse, Failure extends HostFailure>(
|
|
152
|
+
effect: Effect.Effect<Result, Failure, EndpointServices>,
|
|
153
|
+
): Effect.Effect<HostResponse, never, EndpointServices> =>
|
|
154
|
+
effect.pipe(
|
|
155
|
+
Effect.map((result): HostResponse => result),
|
|
156
|
+
Effect.catch((failure) => Effect.succeed<HostResponse>(HostFailed.make({ failure }))),
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
/** Encode the response envelope; an unencodable response degrades to a protocol failure. */
|
|
160
|
+
const encodeResponse = (response: HostResponse): Effect.Effect<unknown> =>
|
|
161
|
+
encodeHostResponse(response).pipe(
|
|
162
|
+
Effect.catch((error) =>
|
|
163
|
+
Effect.succeed<unknown>({
|
|
164
|
+
_tag: "HostFailed",
|
|
165
|
+
failure: {
|
|
166
|
+
_tag: "HostProtocolError",
|
|
167
|
+
message: boundHostDiagnostic(`The host response could not be encoded: ${error.message}`),
|
|
168
|
+
},
|
|
169
|
+
}),
|
|
170
|
+
),
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
const utf8Bytes = (value: unknown): number =>
|
|
174
|
+
new TextEncoder().encode(JSON.stringify(value)).length;
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The admission-limits gate, BEFORE `runtime.submit` touches the ledger (exit gate
|
|
178
|
+
* "resource limits are checked before admission"; DEPLOY-007). A replayed idempotency key is
|
|
179
|
+
* exempt: its accepted-work obligation already exists, and returning the original Receipt
|
|
180
|
+
* consumes no new quota. Refusals are typed `AdmissionLimitExceeded` and nothing is written.
|
|
181
|
+
*/
|
|
182
|
+
const gateAdmissionLimits = Effect.fn("ConversationObject.gateAdmissionLimits")(
|
|
183
|
+
function* (request: {
|
|
184
|
+
readonly principal: SubmissionLookupByKey["principal"];
|
|
185
|
+
readonly idempotencyKey: SubmissionLookupByKey["idempotencyKey"];
|
|
186
|
+
readonly inputPayload: PersistedJson;
|
|
187
|
+
}) {
|
|
188
|
+
const identity = yield* ConversationObjectIdentity;
|
|
189
|
+
const config = yield* CloudflareDurableRuntimeConfig;
|
|
190
|
+
const ledger = yield* SubmissionLedger;
|
|
191
|
+
const { ctx } = yield* DurableObjectContext;
|
|
192
|
+
|
|
193
|
+
const existing = yield* ledger.lookup(
|
|
194
|
+
SubmissionLookupByKey.make({
|
|
195
|
+
conversationId: identity.conversationId,
|
|
196
|
+
principal: request.principal,
|
|
197
|
+
idempotencyKey: request.idempotencyKey,
|
|
198
|
+
}),
|
|
199
|
+
);
|
|
200
|
+
if (Option.isSome(existing)) return;
|
|
201
|
+
|
|
202
|
+
const inputBytes = utf8Bytes(request.inputPayload);
|
|
203
|
+
if (inputBytes > config.limits.maxInputBytes) {
|
|
204
|
+
return yield* AdmissionLimitExceeded.make({
|
|
205
|
+
limit: "input-bytes",
|
|
206
|
+
actual: inputBytes,
|
|
207
|
+
maximum: config.limits.maxInputBytes,
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// One Conversation per Object (durability §5): the local scan IS this lane's queue.
|
|
212
|
+
const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);
|
|
213
|
+
if (nonterminal.length >= config.limits.maxQueueDepthPerLane) {
|
|
214
|
+
return yield* AdmissionLimitExceeded.make({
|
|
215
|
+
limit: "queue-depth",
|
|
216
|
+
actual: nonterminal.length,
|
|
217
|
+
maximum: config.limits.maxQueueDepthPerLane,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const databaseBytes = yield* Effect.sync(() => ctx.storage.sql.databaseSize);
|
|
222
|
+
if (databaseBytes > config.limits.maxDatabaseBytes) {
|
|
223
|
+
return yield* AdmissionLimitExceeded.make({
|
|
224
|
+
limit: "database-bytes",
|
|
225
|
+
actual: databaseBytes,
|
|
226
|
+
maximum: config.limits.maxDatabaseBytes,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* The submit-capable projection of an Agent Binding on the OBJECT side: the input arrived
|
|
234
|
+
* already encoded through the real input schema on the Worker side (`client.ts`), so the
|
|
235
|
+
* Object admits the canonical `PersistedJson` payload as-is; the resolved Binding re-derives
|
|
236
|
+
* everything else from the stored `(agentId, agentDigests)` at claim time (SUB-023).
|
|
237
|
+
*/
|
|
238
|
+
const passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({
|
|
239
|
+
definition: {
|
|
240
|
+
id: agentId,
|
|
241
|
+
input: PersistedJson,
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
const submitEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
|
|
246
|
+
decodeSubmitRequest(encoded).pipe(
|
|
247
|
+
Effect.mapError(protocolFailure("The submit request could not be decoded")),
|
|
248
|
+
Effect.flatMap((request) =>
|
|
249
|
+
Effect.gen(function* () {
|
|
250
|
+
const identity = yield* ConversationObjectIdentity;
|
|
251
|
+
const maintenance = yield* ConversationMaintenance;
|
|
252
|
+
const runtime = yield* DurableAgentRuntime;
|
|
253
|
+
yield* gateAdmissionLimits(request);
|
|
254
|
+
// Alarm invariant: the alarm commits BEFORE the admission it will finish (D-P6-2).
|
|
255
|
+
yield* maintenance.preArm;
|
|
256
|
+
const receipt = yield* runtime.submit(
|
|
257
|
+
passthroughSubmitAgent(request.agentId),
|
|
258
|
+
request.inputPayload,
|
|
259
|
+
{
|
|
260
|
+
conversationId: identity.conversationId,
|
|
261
|
+
principal: request.principal,
|
|
262
|
+
idempotencyKey: request.idempotencyKey,
|
|
263
|
+
definitions: request.definitions,
|
|
264
|
+
},
|
|
265
|
+
);
|
|
266
|
+
return SubmitSucceeded.make({ receipt });
|
|
267
|
+
}),
|
|
268
|
+
),
|
|
269
|
+
respond,
|
|
270
|
+
Effect.flatMap(encodeResponse),
|
|
271
|
+
);
|
|
272
|
+
|
|
273
|
+
const awaitSettlementEndpoint = (
|
|
274
|
+
encoded: unknown,
|
|
275
|
+
): Effect.Effect<unknown, never, EndpointServices> =>
|
|
276
|
+
decodeReceipt(encoded).pipe(
|
|
277
|
+
Effect.mapError(protocolFailure("The receipt could not be decoded")),
|
|
278
|
+
Effect.flatMap((receipt) =>
|
|
279
|
+
Effect.gen(function* () {
|
|
280
|
+
const runtime = yield* DurableAgentRuntime;
|
|
281
|
+
const settlement = yield* runtime.awaitSettlement(receipt);
|
|
282
|
+
return SettlementReached.make({ settlement });
|
|
283
|
+
}),
|
|
284
|
+
),
|
|
285
|
+
respond,
|
|
286
|
+
Effect.flatMap(encodeResponse),
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
const observePageEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
|
|
290
|
+
decodeObservePageRequest(encoded).pipe(
|
|
291
|
+
Effect.mapError(protocolFailure("The observe request could not be decoded")),
|
|
292
|
+
Effect.flatMap((request) =>
|
|
293
|
+
Effect.gen(function* () {
|
|
294
|
+
const identity = yield* ConversationObjectIdentity;
|
|
295
|
+
const store = yield* ConversationStore;
|
|
296
|
+
// The same fail-closed authorization seam the runtime's `observe` consults (P7 WP1);
|
|
297
|
+
// the default reference preserves the possession behavior.
|
|
298
|
+
const authorizer = yield* OperationAuthorizer;
|
|
299
|
+
yield* authorizer
|
|
300
|
+
.authorize(
|
|
301
|
+
OperationAuthorizationRequest.make({
|
|
302
|
+
operation: "observe",
|
|
303
|
+
conversationId: identity.conversationId,
|
|
304
|
+
}),
|
|
305
|
+
)
|
|
306
|
+
.pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
|
|
307
|
+
const records = yield* Stream.runCollect(
|
|
308
|
+
store.read(
|
|
309
|
+
ConversationRead.make({
|
|
310
|
+
conversationId: identity.conversationId,
|
|
311
|
+
...(request.afterSequence === undefined
|
|
312
|
+
? {}
|
|
313
|
+
: { afterSequence: request.afterSequence }),
|
|
314
|
+
limit: request.limit,
|
|
315
|
+
}),
|
|
316
|
+
),
|
|
317
|
+
);
|
|
318
|
+
return ObservedPage.make({ records: [...records] });
|
|
319
|
+
}),
|
|
320
|
+
),
|
|
321
|
+
respond,
|
|
322
|
+
Effect.flatMap(encodeResponse),
|
|
323
|
+
);
|
|
324
|
+
|
|
325
|
+
const abortEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
|
|
326
|
+
decodeAbortCommand(encoded).pipe(
|
|
327
|
+
Effect.mapError(protocolFailure("The abort command could not be decoded")),
|
|
328
|
+
Effect.flatMap((command) =>
|
|
329
|
+
Effect.gen(function* () {
|
|
330
|
+
const maintenance = yield* ConversationMaintenance;
|
|
331
|
+
const runtime = yield* DurableAgentRuntime;
|
|
332
|
+
yield* maintenance.preArm;
|
|
333
|
+
const intent = yield* runtime.abort(command);
|
|
334
|
+
return AbortRecorded.make({ intent });
|
|
335
|
+
}),
|
|
336
|
+
),
|
|
337
|
+
respond,
|
|
338
|
+
Effect.flatMap(encodeResponse),
|
|
339
|
+
);
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* The pre-P7 host protocol's failure union does not carry `OperationDenied` (the Worker client
|
|
343
|
+
* predates the authorizer). This assembly always runs the default possession authorizer — no
|
|
344
|
+
* `CloudflareDurableRuntimeOptions` authorizer lever exists yet — so a denial here is
|
|
345
|
+
* unreachable today; if one ever surfaces it degrades to the protocol failure instead of an
|
|
346
|
+
* out-of-contract throw. The four P7 admin entry points below carry `OperationDenied` typed.
|
|
347
|
+
*/
|
|
348
|
+
const deniedToProtocolFailure = (
|
|
349
|
+
denied: OperationDenied,
|
|
350
|
+
): Effect.Effect<never, HostProtocolError> =>
|
|
351
|
+
Effect.fail(
|
|
352
|
+
HostProtocolError.make({
|
|
353
|
+
message: boundHostDiagnostic(
|
|
354
|
+
`The ${denied.operation} operation was denied: ${denied.reason}`,
|
|
355
|
+
),
|
|
356
|
+
}),
|
|
357
|
+
);
|
|
358
|
+
|
|
359
|
+
const resolveApprovalEndpoint = (
|
|
360
|
+
encoded: unknown,
|
|
361
|
+
): Effect.Effect<unknown, never, EndpointServices> =>
|
|
362
|
+
decodeApprovalDecisionCommand(encoded).pipe(
|
|
363
|
+
Effect.mapError(protocolFailure("The approval command could not be decoded")),
|
|
364
|
+
Effect.flatMap((command) =>
|
|
365
|
+
Effect.gen(function* () {
|
|
366
|
+
const maintenance = yield* ConversationMaintenance;
|
|
367
|
+
const runtime = yield* DurableAgentRuntime;
|
|
368
|
+
yield* maintenance.preArm;
|
|
369
|
+
const intent = yield* runtime
|
|
370
|
+
.resolveApproval(command)
|
|
371
|
+
.pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
|
|
372
|
+
return ApprovalRecorded.make({ intent });
|
|
373
|
+
}),
|
|
374
|
+
),
|
|
375
|
+
respond,
|
|
376
|
+
Effect.flatMap(encodeResponse),
|
|
377
|
+
);
|
|
378
|
+
|
|
379
|
+
const resolveUnknownEndpoint = (
|
|
380
|
+
encoded: unknown,
|
|
381
|
+
): Effect.Effect<unknown, never, EndpointServices> =>
|
|
382
|
+
decodeUnknownResolutionCommand(encoded).pipe(
|
|
383
|
+
Effect.mapError(protocolFailure("The resolution command could not be decoded")),
|
|
384
|
+
Effect.flatMap((command) =>
|
|
385
|
+
Effect.gen(function* () {
|
|
386
|
+
const maintenance = yield* ConversationMaintenance;
|
|
387
|
+
const runtime = yield* DurableAgentRuntime;
|
|
388
|
+
yield* maintenance.preArm;
|
|
389
|
+
const intent = yield* runtime
|
|
390
|
+
.resolveUnknown(command)
|
|
391
|
+
.pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
|
|
392
|
+
return UnknownResolutionRecorded.make({ intent });
|
|
393
|
+
}),
|
|
394
|
+
),
|
|
395
|
+
respond,
|
|
396
|
+
Effect.flatMap(encodeResponse),
|
|
397
|
+
);
|
|
398
|
+
|
|
399
|
+
// ---------------------------------------------------------------------------
|
|
400
|
+
// P7 administrative entry points (plan §3): explain/verify/retry/obligations over the SAME
|
|
401
|
+
// envelope discipline as the host protocol — closed request/response Schema unions, typed
|
|
402
|
+
// failures that re-decode to identical tags, protocol anomalies answered typed. The envelopes
|
|
403
|
+
// live here (not `client.ts`) because no Worker-side client consumption exists yet; `wake`
|
|
404
|
+
// already exists as the `wake()` entry point.
|
|
405
|
+
// ---------------------------------------------------------------------------
|
|
406
|
+
|
|
407
|
+
/** Explain one Submission (`submissionId` present) or every nonterminal lane member. */
|
|
408
|
+
export class AdminExplainRequest extends Schema.Class<AdminExplainRequest>(
|
|
409
|
+
"@effect-agent/platform-cloudflare/AdminExplainRequest",
|
|
410
|
+
)({
|
|
411
|
+
submissionId: Schema.optionalKey(SubmissionId),
|
|
412
|
+
}) {}
|
|
413
|
+
|
|
414
|
+
/** Verify carries no parameters — the addressed Object IS the lane. */
|
|
415
|
+
export class AdminVerifyRequest extends Schema.Class<AdminVerifyRequest>(
|
|
416
|
+
"@effect-agent/platform-cloudflare/AdminVerifyRequest",
|
|
417
|
+
)({}) {}
|
|
418
|
+
|
|
419
|
+
/** Every typed failure of the four admin entry points, plus the protocol's own errors. */
|
|
420
|
+
export const AdminFailure = Schema.Union([
|
|
421
|
+
OperationDenied,
|
|
422
|
+
RetryRefused,
|
|
423
|
+
LedgerError,
|
|
424
|
+
RunJournalError,
|
|
425
|
+
DigestError,
|
|
426
|
+
OwnershipLost,
|
|
427
|
+
SettlementConflict,
|
|
428
|
+
ConversationStoreError,
|
|
429
|
+
ConversationNotMaterialized,
|
|
430
|
+
AppendConflict,
|
|
431
|
+
FenceRejected,
|
|
432
|
+
DurableRuntimeFailpointError,
|
|
433
|
+
DurableAlarmError,
|
|
434
|
+
HostProtocolError,
|
|
435
|
+
]);
|
|
436
|
+
export type AdminFailure = typeof AdminFailure.Type;
|
|
437
|
+
|
|
438
|
+
export class ExplainedRecovery extends Schema.TaggedClass<ExplainedRecovery>(
|
|
439
|
+
"@effect-agent/platform-cloudflare/ExplainedRecovery",
|
|
440
|
+
)("ExplainedRecovery", {
|
|
441
|
+
explanations: Schema.Array(RecoveryExplanation).check(Schema.isMaxLength(1_024)),
|
|
442
|
+
}) {}
|
|
443
|
+
|
|
444
|
+
export class VerifiedIntegrity extends Schema.TaggedClass<VerifiedIntegrity>(
|
|
445
|
+
"@effect-agent/platform-cloudflare/VerifiedIntegrity",
|
|
446
|
+
)("VerifiedIntegrity", {
|
|
447
|
+
report: IntegrityReport,
|
|
448
|
+
}) {}
|
|
449
|
+
|
|
450
|
+
export class RetryExecuted extends Schema.TaggedClass<RetryExecuted>(
|
|
451
|
+
"@effect-agent/platform-cloudflare/RetryExecuted",
|
|
452
|
+
)("RetryExecuted", {
|
|
453
|
+
report: RecoveryReport,
|
|
454
|
+
}) {}
|
|
455
|
+
|
|
456
|
+
export class ObligationsScanned extends Schema.TaggedClass<ObligationsScanned>(
|
|
457
|
+
"@effect-agent/platform-cloudflare/ObligationsScanned",
|
|
458
|
+
)("ObligationsScanned", {
|
|
459
|
+
report: ObligationReport,
|
|
460
|
+
}) {}
|
|
461
|
+
|
|
462
|
+
/** The admin entry point failed TYPED on the Object; the failure re-decodes verbatim. */
|
|
463
|
+
export class AdminFailed extends Schema.TaggedClass<AdminFailed>(
|
|
464
|
+
"@effect-agent/platform-cloudflare/AdminFailed",
|
|
465
|
+
)("AdminFailed", {
|
|
466
|
+
failure: AdminFailure,
|
|
467
|
+
}) {}
|
|
468
|
+
|
|
469
|
+
/** The uniform answer of one admin entry point. Callers narrow by the tag their call implies. */
|
|
470
|
+
export const AdminResponse = Schema.Union([
|
|
471
|
+
ExplainedRecovery,
|
|
472
|
+
VerifiedIntegrity,
|
|
473
|
+
RetryExecuted,
|
|
474
|
+
ObligationsScanned,
|
|
475
|
+
AdminFailed,
|
|
476
|
+
]);
|
|
477
|
+
export type AdminResponse = typeof AdminResponse.Type;
|
|
478
|
+
|
|
479
|
+
export const decodeAdminExplainRequest = Schema.decodeUnknownEffect(AdminExplainRequest);
|
|
480
|
+
export const decodeAdminVerifyRequest = Schema.decodeUnknownEffect(AdminVerifyRequest);
|
|
481
|
+
export const decodeRetryCommand = Schema.decodeUnknownEffect(RetryCommand);
|
|
482
|
+
export const decodeObligationThresholds = Schema.decodeUnknownEffect(ObligationThresholds);
|
|
483
|
+
export const encodeAdminResponse = Schema.encodeEffect(AdminResponse);
|
|
484
|
+
export const decodeAdminResponse = Schema.decodeUnknownEffect(AdminResponse);
|
|
485
|
+
|
|
486
|
+
/** Fold one admin endpoint's typed failures into the uniform `AdminResponse` envelope. */
|
|
487
|
+
const respondAdmin = <Result extends AdminResponse, Failure extends AdminFailure>(
|
|
488
|
+
effect: Effect.Effect<Result, Failure, EndpointServices>,
|
|
489
|
+
): Effect.Effect<AdminResponse, never, EndpointServices> =>
|
|
490
|
+
effect.pipe(
|
|
491
|
+
Effect.map((result): AdminResponse => result),
|
|
492
|
+
Effect.catch((failure) => Effect.succeed<AdminResponse>(AdminFailed.make({ failure }))),
|
|
493
|
+
);
|
|
494
|
+
|
|
495
|
+
/** Encode the admin response envelope; an unencodable response degrades to a protocol failure. */
|
|
496
|
+
const encodeAdminResponseTotal = (response: AdminResponse): Effect.Effect<unknown> =>
|
|
497
|
+
encodeAdminResponse(response).pipe(
|
|
498
|
+
Effect.catch((error) =>
|
|
499
|
+
Effect.succeed<unknown>({
|
|
500
|
+
_tag: "AdminFailed",
|
|
501
|
+
failure: {
|
|
502
|
+
_tag: "HostProtocolError",
|
|
503
|
+
message: boundHostDiagnostic(`The admin response could not be encoded: ${error.message}`),
|
|
504
|
+
},
|
|
505
|
+
}),
|
|
506
|
+
),
|
|
507
|
+
);
|
|
508
|
+
|
|
509
|
+
const explainEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
|
|
510
|
+
decodeAdminExplainRequest(encoded).pipe(
|
|
511
|
+
Effect.mapError(protocolFailure("The explain request could not be decoded")),
|
|
512
|
+
Effect.flatMap((request) =>
|
|
513
|
+
Effect.gen(function* () {
|
|
514
|
+
const identity = yield* ConversationObjectIdentity;
|
|
515
|
+
const runtime = yield* DurableAgentRuntime;
|
|
516
|
+
const explanations =
|
|
517
|
+
request.submissionId === undefined
|
|
518
|
+
? yield* runtime.explainConversation(identity.conversationId)
|
|
519
|
+
: [yield* runtime.explain(request.submissionId)];
|
|
520
|
+
return ExplainedRecovery.make({ explanations });
|
|
521
|
+
}),
|
|
522
|
+
),
|
|
523
|
+
respondAdmin,
|
|
524
|
+
Effect.flatMap(encodeAdminResponseTotal),
|
|
525
|
+
);
|
|
526
|
+
|
|
527
|
+
const verifyEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
|
|
528
|
+
decodeAdminVerifyRequest(encoded).pipe(
|
|
529
|
+
Effect.mapError(protocolFailure("The verify request could not be decoded")),
|
|
530
|
+
Effect.flatMap(() =>
|
|
531
|
+
Effect.gen(function* () {
|
|
532
|
+
const identity = yield* ConversationObjectIdentity;
|
|
533
|
+
const runtime = yield* DurableAgentRuntime;
|
|
534
|
+
const report = yield* runtime.verify(identity.conversationId);
|
|
535
|
+
return VerifiedIntegrity.make({ report });
|
|
536
|
+
}),
|
|
537
|
+
),
|
|
538
|
+
respondAdmin,
|
|
539
|
+
Effect.flatMap(encodeAdminResponseTotal),
|
|
540
|
+
);
|
|
541
|
+
|
|
542
|
+
const retryEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
|
|
543
|
+
decodeRetryCommand(encoded).pipe(
|
|
544
|
+
Effect.mapError(protocolFailure("The retry command could not be decoded")),
|
|
545
|
+
Effect.flatMap((command) =>
|
|
546
|
+
Effect.gen(function* () {
|
|
547
|
+
const maintenance = yield* ConversationMaintenance;
|
|
548
|
+
const runtime = yield* DurableAgentRuntime;
|
|
549
|
+
// Alarm invariant: retry may repair durable state, so the alarm that will finish the
|
|
550
|
+
// lane commits BEFORE the mutation (D-P6-2), exactly like abort.
|
|
551
|
+
yield* maintenance.preArm;
|
|
552
|
+
const report = yield* runtime.retry(command);
|
|
553
|
+
return RetryExecuted.make({ report });
|
|
554
|
+
}),
|
|
555
|
+
),
|
|
556
|
+
respondAdmin,
|
|
557
|
+
Effect.flatMap(encodeAdminResponseTotal),
|
|
558
|
+
);
|
|
559
|
+
|
|
560
|
+
const obligationsEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
|
|
561
|
+
decodeObligationThresholds(encoded).pipe(
|
|
562
|
+
Effect.mapError(protocolFailure("The obligation thresholds could not be decoded")),
|
|
563
|
+
Effect.flatMap((thresholds) =>
|
|
564
|
+
Effect.gen(function* () {
|
|
565
|
+
const runtime = yield* DurableAgentRuntime;
|
|
566
|
+
const report = yield* runtime.scanObligations(thresholds);
|
|
567
|
+
return ObligationsScanned.make({ report });
|
|
568
|
+
}),
|
|
569
|
+
),
|
|
570
|
+
respondAdmin,
|
|
571
|
+
Effect.flatMap(encodeAdminResponseTotal),
|
|
572
|
+
);
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Owner-side `portCall`: pre-arm before a mutating envelope (a routed admission committed by
|
|
576
|
+
* THIS Object must already carry the alarm that will finish it), execute on the LOCAL facets
|
|
577
|
+
* (never the routed decorators), then arm an immediate alarm so the mutated lane is
|
|
578
|
+
* processed promptly. Protocol anomalies answer `PortFailed(PortProtocolError)`.
|
|
579
|
+
*/
|
|
580
|
+
const portCallEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
|
|
581
|
+
Effect.gen(function* () {
|
|
582
|
+
const ports = yield* ConversationObjectPorts;
|
|
583
|
+
const maintenance = yield* ConversationMaintenance;
|
|
584
|
+
const alarm = yield* DurableAlarmService;
|
|
585
|
+
const mutating = isMutatingPortRequest(encoded);
|
|
586
|
+
if (mutating) {
|
|
587
|
+
const preArmed = yield* maintenance.preArm.pipe(Effect.exit);
|
|
588
|
+
if (preArmed._tag === "Failure") {
|
|
589
|
+
// Without the committed alarm the invariant cannot be promised; refuse the mutation.
|
|
590
|
+
return encodedPortProtocolFailure(
|
|
591
|
+
"The owner Object could not arm its maintenance alarm before the mutation.",
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
const response = yield* ports.handle(encoded);
|
|
596
|
+
if (mutating) {
|
|
597
|
+
// Prompt processing hint; the pre-armed alarm already guarantees convergence.
|
|
598
|
+
yield* alarm.scheduleNow.pipe(
|
|
599
|
+
Effect.catch((error) =>
|
|
600
|
+
Effect.logWarning("ConversationObject.portCall: immediate re-arm failed", error),
|
|
601
|
+
),
|
|
602
|
+
);
|
|
603
|
+
}
|
|
604
|
+
return response;
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
const wakeEndpoint: Effect.Effect<void, never, EndpointServices> = Effect.gen(function* () {
|
|
608
|
+
const alarm = yield* DurableAlarmService;
|
|
609
|
+
// Wake hints are droppable by contract: a failed alarm write is logged and swallowed; the
|
|
610
|
+
// sender's own alarm/scan pairing (or this Object's next entry point) restores liveness.
|
|
611
|
+
yield* alarm.scheduleNow.pipe(
|
|
612
|
+
Effect.catch((error) => Effect.logWarning("ConversationObject.wake dropped", error)),
|
|
613
|
+
);
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
const alarmEndpoint: Effect.Effect<void, unknown, EndpointServices> = Effect.gen(function* () {
|
|
617
|
+
const maintenance = yield* ConversationMaintenance;
|
|
618
|
+
// Typed pass failures propagate: the rejected promise makes workerd retry the alarm
|
|
619
|
+
// (at-least-once delivery), and the pass's own pre-arm keeps the slot committed meanwhile.
|
|
620
|
+
yield* maintenance.pass;
|
|
621
|
+
});
|
|
622
|
+
|
|
623
|
+
const gateEndpoint: Effect.Effect<void, unknown, EndpointServices> = Effect.gen(function* () {
|
|
624
|
+
// Forcing ConversationMaintenance forces the whole Layer stack: migration + exact-version
|
|
625
|
+
// check + configuration decode (DEPLOY-008 fails typed here, before any mutation), then
|
|
626
|
+
// the defensive local ensure-alarm half of the invariant. LOCAL-ONLY by construction.
|
|
627
|
+
const maintenance = yield* ConversationMaintenance;
|
|
628
|
+
yield* maintenance.ensureAlarm;
|
|
629
|
+
});
|
|
630
|
+
|
|
631
|
+
/** Build the application's Conversation Object class (export it from the Worker entry). */
|
|
632
|
+
export const makeConversationObjectClass = (
|
|
633
|
+
options: ConversationObjectOptions,
|
|
634
|
+
): ConversationObjectConstructor => {
|
|
635
|
+
class ConversationObject extends DurableObject {
|
|
636
|
+
readonly #runtime: ManagedRuntime.ManagedRuntime<EndpointServices, ConversationObjectError>;
|
|
637
|
+
|
|
638
|
+
constructor(ctx: DurableObjectState, env: Cloudflare.Env) {
|
|
639
|
+
super(ctx, env);
|
|
640
|
+
this.#runtime = ManagedRuntime.make(
|
|
641
|
+
CloudflareDurableRuntime.layer(options).pipe(
|
|
642
|
+
Layer.provideMerge(
|
|
643
|
+
Layer.mergeAll(
|
|
644
|
+
DurableObjectContext.layer(ctx, env),
|
|
645
|
+
conversationNamespaceLayer(env, options.namespaceBinding),
|
|
646
|
+
),
|
|
647
|
+
),
|
|
648
|
+
),
|
|
649
|
+
);
|
|
650
|
+
// The constructor gate: local-only checks; never the recovery pass (deadlock argument,
|
|
651
|
+
// plan §1.4). A failure here fails every delivery with the typed construction error.
|
|
652
|
+
void ctx.blockConcurrencyWhile(() => this.#runtime.runPromise(gateEndpoint));
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
async submitEncoded(encoded: unknown): Promise<unknown> {
|
|
656
|
+
return this.#runtime.runPromise(submitEndpoint(encoded));
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
async awaitSettlementEncoded(encoded: unknown): Promise<unknown> {
|
|
660
|
+
return this.#runtime.runPromise(awaitSettlementEndpoint(encoded));
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
async observePage(encoded: unknown): Promise<unknown> {
|
|
664
|
+
return this.#runtime.runPromise(observePageEndpoint(encoded));
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
async abortEncoded(encoded: unknown): Promise<unknown> {
|
|
668
|
+
return this.#runtime.runPromise(abortEndpoint(encoded));
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
async resolveApprovalEncoded(encoded: unknown): Promise<unknown> {
|
|
672
|
+
return this.#runtime.runPromise(resolveApprovalEndpoint(encoded));
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
async resolveUnknownEncoded(encoded: unknown): Promise<unknown> {
|
|
676
|
+
return this.#runtime.runPromise(resolveUnknownEndpoint(encoded));
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
async explainEncoded(encoded: unknown): Promise<unknown> {
|
|
680
|
+
return this.#runtime.runPromise(explainEndpoint(encoded));
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
async verifyEncoded(encoded: unknown): Promise<unknown> {
|
|
684
|
+
return this.#runtime.runPromise(verifyEndpoint(encoded));
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
async retryEncoded(encoded: unknown): Promise<unknown> {
|
|
688
|
+
return this.#runtime.runPromise(retryEndpoint(encoded));
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
async obligationsEncoded(encoded: unknown): Promise<unknown> {
|
|
692
|
+
return this.#runtime.runPromise(obligationsEndpoint(encoded));
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
async portCall(encoded: unknown): Promise<unknown> {
|
|
696
|
+
return this.#runtime.runPromise(portCallEndpoint(encoded));
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
async wake(): Promise<void> {
|
|
700
|
+
await this.#runtime.runPromise(wakeEndpoint);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
override async alarm(): Promise<void> {
|
|
704
|
+
await this.#runtime.runPromise(alarmEndpoint);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
return ConversationObject;
|
|
709
|
+
};
|