@yielded/agent-storage-cloudflare 0.1.0-beta.166

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 (77) hide show
  1. package/LICENSE +21 -0
  2. package/dist/DoMemoryStore.d.mts +30 -0
  3. package/dist/DoMemoryStore.mjs +66 -0
  4. package/dist/DoMemoryStore.mjs.map +1 -0
  5. package/dist/DoMessageDeliveryStore.d.mts +17 -0
  6. package/dist/DoMessageDeliveryStore.mjs +30 -0
  7. package/dist/DoMessageDeliveryStore.mjs.map +1 -0
  8. package/dist/DoScheduleStore.d.mts +36 -0
  9. package/dist/DoScheduleStore.mjs +388 -0
  10. package/dist/DoScheduleStore.mjs.map +1 -0
  11. package/dist/DoStorageConfig.d.mts +45 -0
  12. package/dist/DoStorageConfig.mjs +52 -0
  13. package/dist/DoStorageConfig.mjs.map +1 -0
  14. package/dist/DoStorageError-CGuAfSwF.d.mts +101 -0
  15. package/dist/DoStorageError.d.mts +2 -0
  16. package/dist/DoStorageError.mjs +167 -0
  17. package/dist/DoStorageError.mjs.map +1 -0
  18. package/dist/DoStorageFailpoint.d.mts +17 -0
  19. package/dist/DoStorageFailpoint.mjs +14 -0
  20. package/dist/DoStorageFailpoint.mjs.map +1 -0
  21. package/dist/DoStorageFailpointTesting.d.mts +24 -0
  22. package/dist/DoStorageFailpointTesting.mjs +22 -0
  23. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  24. package/dist/DoStorageVersion-iNSyi3cJ.d.mts +12 -0
  25. package/dist/DoStorageVersion.d.mts +2 -0
  26. package/dist/DoStorageVersion.mjs +8 -0
  27. package/dist/DoStorageVersion.mjs.map +1 -0
  28. package/dist/DoSubmissionLedger.d.mts +23 -0
  29. package/dist/DoSubmissionLedger.mjs +1979 -0
  30. package/dist/DoSubmissionLedger.mjs.map +1 -0
  31. package/dist/DoSubscriptionStore.d.mts +25 -0
  32. package/dist/DoSubscriptionStore.mjs +186 -0
  33. package/dist/DoSubscriptionStore.mjs.map +1 -0
  34. package/dist/DoThreadStore-D_83OjCH.d.mts +72 -0
  35. package/dist/DoThreadStore.d.mts +2 -0
  36. package/dist/DoThreadStore.mjs +529 -0
  37. package/dist/DoThreadStore.mjs.map +1 -0
  38. package/dist/MemoryProtocol.d.mts +38160 -0
  39. package/dist/MemoryProtocol.mjs +219 -0
  40. package/dist/MemoryProtocol.mjs.map +1 -0
  41. package/dist/PortProtocol.d.mts +7726 -0
  42. package/dist/PortProtocol.mjs +234 -0
  43. package/dist/PortProtocol.mjs.map +1 -0
  44. package/dist/PortRouting.d.mts +97 -0
  45. package/dist/PortRouting.mjs +544 -0
  46. package/dist/PortRouting.mjs.map +1 -0
  47. package/dist/do-journal-DUhjZkOf.mjs +1352 -0
  48. package/dist/do-journal-DUhjZkOf.mjs.map +1 -0
  49. package/dist/index.d.mts +14 -0
  50. package/dist/index.mjs +14 -0
  51. package/dist/migrations-DtKz_Gxr.mjs +306 -0
  52. package/dist/migrations-DtKz_Gxr.mjs.map +1 -0
  53. package/dist/owned-state-DHm2aRXx.mjs +119 -0
  54. package/dist/owned-state-DHm2aRXx.mjs.map +1 -0
  55. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  56. package/package.json +1 -0
  57. package/src/DoMemoryStore.ts +73 -0
  58. package/src/DoMessageDeliveryStore.ts +39 -0
  59. package/src/DoScheduleStore.ts +622 -0
  60. package/src/DoStorageConfig.ts +53 -0
  61. package/src/DoStorageError.ts +180 -0
  62. package/src/DoStorageFailpoint.ts +20 -0
  63. package/src/DoStorageFailpointTesting.ts +41 -0
  64. package/src/DoStorageVersion.ts +2 -0
  65. package/src/DoSubmissionLedger.ts +4027 -0
  66. package/src/DoSubscriptionStore.ts +327 -0
  67. package/src/DoThreadStore.ts +1121 -0
  68. package/src/MemoryProtocol.ts +355 -0
  69. package/src/PortProtocol.ts +436 -0
  70. package/src/PortRouting.ts +1464 -0
  71. package/src/index.ts +13 -0
  72. package/src/internal/do-journal.ts +2282 -0
  73. package/src/internal/message-delivery-schema.ts +24 -0
  74. package/src/internal/migrations.ts +304 -0
  75. package/src/internal/owned-state.ts +228 -0
  76. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  77. package/src/internal/storage-span.ts +44 -0
@@ -0,0 +1,355 @@
1
+ import * as MemoryNamespace from "@yielded/agent/memory-namespace";
2
+ import {
3
+ MemoryLookup,
4
+ MemoryRecallError,
5
+ MemoryRecallLimits,
6
+ } from "@yielded/agent/memory-reference";
7
+ import { MemoryAccess, revalidateMemoryLookup } from "@yielded/agent/memory-revalidation";
8
+ import {
9
+ MemoryKey,
10
+ MemoryReader,
11
+ MemoryConflict,
12
+ MemoryDocument,
13
+ MemoryMutationFailure,
14
+ MemoryOperationConflict,
15
+ MemoryStorageError,
16
+ MemoryWithdrawn,
17
+ MemoryWrite,
18
+ MemoryWriter,
19
+ } from "@yielded/agent/memory-store";
20
+ import {
21
+ MemoryIndexSearch,
22
+ MemoryIndexError,
23
+ SemanticMemoryProfile,
24
+ } from "@yielded/agent/semantic-memory-index";
25
+ import {
26
+ SemanticMemoryError,
27
+ SemanticCandidateLimits,
28
+ SemanticCandidateResult,
29
+ revalidateSemanticMemoryCandidates,
30
+ } from "@yielded/agent/semantic-memory-revalidation";
31
+ import { Principal } from "@yielded/agent/submission-ledger";
32
+ import { Clock, Context, Effect, Schema } from "effect";
33
+
34
+ export class MemoryRpcError extends Schema.TaggedError<MemoryRpcError>()("MemoryRpcError", {
35
+ reason: Schema.Literals(["denied", "protocol", "budget", "timeout", "unavailable"]),
36
+ }) {}
37
+
38
+ export class MemoryRpcLimits extends Schema.Class<MemoryRpcLimits>(
39
+ "@effect-agent/storage-cloudflare/MemoryRpcLimits",
40
+ )({
41
+ maxRequestBytes: Schema.Int.check(Schema.isBetween({ minimum: 256, maximum: 4_194_304 })),
42
+ maxResponseBytes: Schema.Int.check(Schema.isBetween({ minimum: 256, maximum: 16_777_216 })),
43
+ maxSourceBytes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 67_108_864 })),
44
+ maxSources: MemoryRecallLimits.fields.maxSources,
45
+ timeoutMillis: MemoryRecallLimits.fields.timeoutMillis,
46
+ }) {}
47
+
48
+ export const defaultMemoryRpcLimits = MemoryRpcLimits.make({
49
+ maxRequestBytes: 1_048_576,
50
+ maxResponseBytes: 4_194_304,
51
+ maxSourceBytes: 16_777_216,
52
+ maxSources: 16,
53
+ timeoutMillis: 10_000,
54
+ });
55
+
56
+ const RequestFields = {
57
+ version: Schema.Literal(1),
58
+ access: MemoryAccess.Wire,
59
+ /** Host-authenticated identity, never copied from model input. The owner still authorizes it. */
60
+ principal: Principal,
61
+ deadlineMillis: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
62
+ };
63
+
64
+ const RevalidateRequest = Schema.TaggedStruct("Revalidate", {
65
+ ...RequestFields,
66
+ lookup: MemoryLookup,
67
+ limits: MemoryRecallLimits,
68
+ });
69
+
70
+ const ChangeRequest = Schema.TaggedStruct("Change", { ...RequestFields, write: MemoryWrite.Wire });
71
+
72
+ const GetRequest = Schema.TaggedStruct("Get", { ...RequestFields, key: MemoryKey.Wire });
73
+
74
+ const SemanticRequest: Schema.TaggedStruct<
75
+ "RevalidateSemantic",
76
+ typeof RequestFields & {
77
+ readonly found: typeof MemoryIndexSearch.Wire;
78
+ readonly profile: typeof SemanticMemoryProfile;
79
+ readonly limits: typeof SemanticCandidateLimits;
80
+ }
81
+ > = Schema.TaggedStruct("RevalidateSemantic", {
82
+ ...RequestFields,
83
+ found: MemoryIndexSearch.Wire,
84
+ profile: SemanticMemoryProfile,
85
+ limits: SemanticCandidateLimits,
86
+ });
87
+
88
+ export const MemoryOwnerRequest: Schema.Union<
89
+ [typeof RevalidateRequest, typeof ChangeRequest, typeof SemanticRequest, typeof GetRequest]
90
+ > = Schema.Union([RevalidateRequest, ChangeRequest, SemanticRequest, GetRequest]);
91
+
92
+ export type MemoryOwnerRequest = typeof MemoryOwnerRequest.Type;
93
+
94
+ export const MemoryOwnerFailure = Schema.Union([
95
+ MemoryRpcError,
96
+ MemoryStorageError,
97
+ MemoryRecallError,
98
+ MemoryConflict,
99
+ MemoryWithdrawn,
100
+ MemoryOperationConflict,
101
+ MemoryMutationFailure,
102
+ MemoryIndexError,
103
+ SemanticMemoryError,
104
+ ]);
105
+
106
+ export type MemoryOwnerFailure = typeof MemoryOwnerFailure.Type;
107
+
108
+ const LookupResponse = Schema.TaggedStruct("Lookup", {
109
+ access: MemoryAccess.Wire,
110
+ lookup: MemoryLookup,
111
+ });
112
+
113
+ const ChangedResponse = Schema.TaggedStruct("Changed", {
114
+ access: MemoryAccess.Wire,
115
+ document: MemoryDocument.Wire,
116
+ });
117
+
118
+ const SemanticResponse = Schema.TaggedStruct("Semantic", {
119
+ access: MemoryAccess.Wire,
120
+ result: SemanticCandidateResult,
121
+ });
122
+
123
+ const DocumentResponse = Schema.TaggedStruct("Document", {
124
+ access: MemoryAccess.Wire,
125
+ key: MemoryKey.Wire,
126
+ document: Schema.NullOr(MemoryDocument.Wire),
127
+ });
128
+
129
+ const FailedResponse = Schema.TaggedStruct("Failed", { failure: MemoryOwnerFailure });
130
+
131
+ export const MemoryOwnerResponse: Schema.Union<
132
+ [
133
+ typeof LookupResponse,
134
+ typeof ChangedResponse,
135
+ typeof SemanticResponse,
136
+ typeof DocumentResponse,
137
+ typeof FailedResponse,
138
+ ]
139
+ > = Schema.Union([
140
+ LookupResponse,
141
+ ChangedResponse,
142
+ SemanticResponse,
143
+ DocumentResponse,
144
+ FailedResponse,
145
+ ]);
146
+
147
+ export type MemoryOwnerResponse = typeof MemoryOwnerResponse.Type;
148
+
149
+ /**
150
+ * Fail-closed application policy. Authorize the namespace, principal, scope, and full command.
151
+ * Get requires exact-key authority, including application source/provenance checks where needed.
152
+ * Possession of a key or scope is not authorization, including for absent or withdrawn documents.
153
+ */
154
+ export class MemoryOwnerAuthorizer extends Context.Service<
155
+ MemoryOwnerAuthorizer,
156
+ {
157
+ readonly authorize: (request: MemoryOwnerRequest) => Effect.Effect<void, MemoryRpcError>;
158
+ }
159
+ >()("@effect-agent/storage-cloudflare/MemoryOwnerAuthorizer") {}
160
+
161
+ /** Canonical namespace derived from this object's idFromName identity, never its request. */
162
+ export class MemoryOwnerIdentity extends Context.Service<
163
+ MemoryOwnerIdentity,
164
+ {
165
+ readonly namespace: MemoryNamespace.Any;
166
+ }
167
+ >()("@effect-agent/storage-cloudflare/MemoryOwnerIdentity") {}
168
+
169
+ export const memoryWireBytes = (text: string): number => new TextEncoder().encode(text).byteLength;
170
+
171
+ export const decodeMemoryWire = Effect.fn("decodeMemoryWire")(function* <A, I>(
172
+ schema: Schema.Codec<A, I, never>,
173
+ raw: unknown,
174
+ maxBytes: number,
175
+ ) {
176
+ const text = yield* Schema.decodeUnknownEffect(Schema.String)(raw).pipe(
177
+ Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })),
178
+ );
179
+
180
+ if (text.length > maxBytes || memoryWireBytes(text) > maxBytes)
181
+ return yield* MemoryRpcError.make({ reason: "budget" });
182
+
183
+ return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(text).pipe(
184
+ Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })),
185
+ );
186
+ });
187
+
188
+ export const encodeMemoryWire = Effect.fn("encodeMemoryWire")(function* <A, I>(
189
+ schema: Schema.Codec<A, I, never, never>,
190
+ value: A,
191
+ maxBytes: number,
192
+ ) {
193
+ const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(
194
+ Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })),
195
+ );
196
+
197
+ if (encoded.length > maxBytes || memoryWireBytes(encoded) > maxBytes)
198
+ return yield* MemoryRpcError.make({ reason: "budget" });
199
+
200
+ return encoded;
201
+ });
202
+
203
+ /** One local read for Get, or per distinct candidate source. No discovery or background work. */
204
+ export const handleMemoryOwnerRequest = Effect.fn("MemoryOwner.handleRequest")(function* (
205
+ raw: unknown,
206
+ limits: MemoryRpcLimits = defaultMemoryRpcLimits,
207
+ ): Effect.fn.Return<
208
+ string,
209
+ never,
210
+ MemoryOwnerIdentity | MemoryOwnerAuthorizer | MemoryReader | MemoryWriter
211
+ > {
212
+ const result = yield* Effect.gen(function* (): Effect.fn.Return<
213
+ MemoryOwnerResponse,
214
+ MemoryOwnerFailure,
215
+ MemoryOwnerIdentity | MemoryOwnerAuthorizer | MemoryReader | MemoryWriter
216
+ > {
217
+ limits = yield* Schema.decodeEffect(MemoryRpcLimits)(limits).pipe(
218
+ Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })),
219
+ );
220
+ const request = yield* decodeMemoryWire(MemoryOwnerRequest, raw, limits.maxRequestBytes);
221
+ const { namespace } = yield* MemoryOwnerIdentity;
222
+
223
+ if (
224
+ !MemoryNamespace.equals(namespace, request.access.namespace) ||
225
+ (request._tag === "Get" && !MemoryNamespace.equals(namespace, request.key.namespace)) ||
226
+ (request._tag === "Change" &&
227
+ !MemoryNamespace.equals(namespace, request.write.key.namespace)) ||
228
+ (request._tag === "RevalidateSemantic" &&
229
+ request.found.candidates.some(
230
+ (candidate) => !MemoryNamespace.equals(namespace, candidate.key.namespace),
231
+ ))
232
+ )
233
+ return yield* MemoryRpcError.make({ reason: "denied" });
234
+
235
+ const remaining = Math.min(
236
+ limits.timeoutMillis,
237
+ request.deadlineMillis - (yield* Clock.currentTimeMillis),
238
+ );
239
+
240
+ if (remaining <= 0) return yield* MemoryRpcError.make({ reason: "timeout" });
241
+
242
+ return yield* Effect.gen(function* (): Effect.fn.Return<
243
+ MemoryOwnerResponse,
244
+ MemoryOwnerFailure,
245
+ MemoryOwnerAuthorizer | MemoryReader | MemoryWriter
246
+ > {
247
+ const authorizer = yield* MemoryOwnerAuthorizer;
248
+
249
+ yield* authorizer.authorize(request);
250
+ if (request._tag === "Get") {
251
+ const reader = yield* MemoryReader;
252
+ const current = yield* reader.get(request.key);
253
+
254
+ const document =
255
+ current === null ? null : yield* MemoryDocument.restore(namespace, current);
256
+
257
+ if (document !== null) {
258
+ if (document.key.id !== request.key.id || document.source.id !== request.key.id)
259
+ return yield* MemoryStorageError.make({
260
+ operation: "validate memory read identity",
261
+ reason: "corrupt",
262
+ });
263
+ if (
264
+ document._tag === "ActiveMemoryDocument" &&
265
+ !document.scopes.includes(request.access.scope)
266
+ )
267
+ return yield* MemoryRpcError.make({ reason: "denied" });
268
+
269
+ yield* encodeMemoryWire(MemoryDocument.Wire, document, limits.maxSourceBytes);
270
+ }
271
+
272
+ return { _tag: "Document", access: request.access, key: request.key, document };
273
+ }
274
+ if (request._tag === "Change") {
275
+ const writer = yield* MemoryWriter;
276
+
277
+ return {
278
+ _tag: "Changed",
279
+ access: request.access,
280
+ document: yield* writer.change(request.write),
281
+ };
282
+ }
283
+ if (request._tag === "RevalidateSemantic") {
284
+ if (
285
+ new Set(request.found.candidates.map((candidate) => candidate.key.id)).size >
286
+ limits.maxSources
287
+ )
288
+ return yield* MemoryRpcError.make({ reason: "budget" });
289
+
290
+ const result = yield* revalidateSemanticMemoryCandidates(
291
+ request.found,
292
+ request.access,
293
+ request.profile,
294
+ {
295
+ ...request.limits,
296
+ maxSourceBytes: Math.min(
297
+ limits.maxSourceBytes,
298
+ request.limits.maxSourceBytes ?? 16_777_216,
299
+ ),
300
+ maxOutputBytes: Math.min(
301
+ limits.maxResponseBytes,
302
+ request.limits.maxOutputBytes ?? 16_777_216,
303
+ ),
304
+ },
305
+ );
306
+
307
+ return { _tag: "Semantic", access: request.access, result };
308
+ }
309
+
310
+ const count =
311
+ request.lookup._tag === "Found"
312
+ ? new Set(request.lookup.passages.map((passage) => passage.source.id)).size
313
+ : 0;
314
+
315
+ if (count > Math.min(limits.maxSources, request.limits.maxSources))
316
+ return yield* MemoryRpcError.make({ reason: "budget" });
317
+
318
+ const lookup = yield* revalidateMemoryLookup(request.lookup, request.access, {
319
+ maxSourceBytes: limits.maxSourceBytes,
320
+ maxInputBytes: Math.min(limits.maxSourceBytes, request.limits.maxInputBytes ?? 16_777_216),
321
+ });
322
+
323
+ return { _tag: "Lookup", access: request.access, lookup };
324
+ }).pipe(
325
+ Effect.scoped,
326
+ Effect.timeoutOrElse({
327
+ duration: remaining,
328
+ orElse: () => Effect.fail(MemoryRpcError.make({ reason: "timeout" })),
329
+ }),
330
+ );
331
+ }).pipe(
332
+ Effect.flatMap((response) =>
333
+ encodeMemoryWire(MemoryOwnerResponse, response, limits.maxResponseBytes),
334
+ ),
335
+ Effect.result,
336
+ );
337
+
338
+ if (result._tag === "Success") return result.success;
339
+
340
+ return yield* encodeMemoryWire(
341
+ MemoryOwnerResponse,
342
+ {
343
+ _tag: "Failed",
344
+ failure: result.failure,
345
+ },
346
+ limits.maxResponseBytes,
347
+ ).pipe(
348
+ Effect.catch(() =>
349
+ Schema.encodeEffect(Schema.fromJsonString(MemoryOwnerResponse))({
350
+ _tag: "Failed",
351
+ failure: MemoryRpcError.make({ reason: "budget" }),
352
+ }).pipe(Effect.orDie),
353
+ ),
354
+ );
355
+ });