@systemfsoftware/agent-platform-cloudflare 0.0.0-bootstrap.0 → 0.1.0-beta.192

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 (143) hide show
  1. package/LICENSE +21 -0
  2. package/dist/Alarm-CbhflIzz.mjs +1931 -0
  3. package/dist/Alarm-CbhflIzz.mjs.map +1 -0
  4. package/dist/Alarm-Nz1gIjfv.d.mts +252 -0
  5. package/dist/Alarm.d.mts +3 -0
  6. package/dist/Alarm.mjs +3 -0
  7. package/dist/BrowserCredentials-BWC4RqRn.d.mts +116 -0
  8. package/dist/BrowserCredentials-CktBoPgE.mjs +140 -0
  9. package/dist/BrowserCredentials-CktBoPgE.mjs.map +1 -0
  10. package/dist/BrowserCredentials.d.mts +2 -0
  11. package/dist/BrowserCredentials.mjs +1 -0
  12. package/dist/BrowserRestCapture.d.mts +14 -0
  13. package/dist/BrowserRestCapture.mjs +195 -0
  14. package/dist/BrowserRestCapture.mjs.map +1 -0
  15. package/dist/BrowserSession-5bdpqPIT.d.mts +152 -0
  16. package/dist/BrowserSession-Ce8cWN1A.mjs +673 -0
  17. package/dist/BrowserSession-Ce8cWN1A.mjs.map +1 -0
  18. package/dist/BrowserSession.d.mts +3 -0
  19. package/dist/BrowserSession.mjs +4 -0
  20. package/dist/BrowserUse-Bsi830Yv.mjs +263 -0
  21. package/dist/BrowserUse-Bsi830Yv.mjs.map +1 -0
  22. package/dist/BrowserUse-DF8afbNt.d.mts +59 -0
  23. package/dist/BrowserUse.d.mts +2 -0
  24. package/dist/BrowserUse.mjs +1 -0
  25. package/dist/CloudflareAiGateway-By8C8c5z.mjs +79 -0
  26. package/dist/CloudflareAiGateway-By8C8c5z.mjs.map +1 -0
  27. package/dist/CloudflareAiGateway-ukN34014.d.mts +63 -0
  28. package/dist/CloudflareAiGateway.d.mts +2 -0
  29. package/dist/CloudflareAiGateway.mjs +1 -0
  30. package/dist/CloudflareBindings-Dylkir84.mjs +123 -0
  31. package/dist/CloudflareBindings-Dylkir84.mjs.map +1 -0
  32. package/dist/CloudflareBindings-E1Sty9Vq.d.mts +134 -0
  33. package/dist/CloudflareBindings.d.mts +2 -0
  34. package/dist/CloudflareBindings.mjs +1 -0
  35. package/dist/CloudflareBrowser-CmiQpslZ.d.mts +41 -0
  36. package/dist/CloudflareBrowser-DmMCFeIQ.mjs +397 -0
  37. package/dist/CloudflareBrowser-DmMCFeIQ.mjs.map +1 -0
  38. package/dist/CloudflareBrowser.d.mts +3 -0
  39. package/dist/CloudflareBrowser.mjs +1 -0
  40. package/dist/CloudflareCodeMode-BMva6dCs.mjs +627 -0
  41. package/dist/CloudflareCodeMode-BMva6dCs.mjs.map +1 -0
  42. package/dist/CloudflareCodeMode-CeGXZtHv.d.mts +43 -0
  43. package/dist/CloudflareCodeMode.d.mts +2 -0
  44. package/dist/CloudflareCodeMode.mjs +1 -0
  45. package/dist/CloudflareConfig-BFWgEyhH.d.mts +102 -0
  46. package/dist/CloudflareConfig-rBlbPSIZ.mjs +125 -0
  47. package/dist/CloudflareConfig-rBlbPSIZ.mjs.map +1 -0
  48. package/dist/CloudflareConfig.d.mts +2 -0
  49. package/dist/CloudflareConfig.mjs +1 -0
  50. package/dist/CloudflareMemory-Bzp32ZpR.d.mts +120 -0
  51. package/dist/CloudflareMemory-DejIVKBT.mjs +207 -0
  52. package/dist/CloudflareMemory-DejIVKBT.mjs.map +1 -0
  53. package/dist/CloudflareMemory.d.mts +2 -0
  54. package/dist/CloudflareMemory.mjs +1 -0
  55. package/dist/CloudflareScheduling-BleqfC44.mjs +395 -0
  56. package/dist/CloudflareScheduling-BleqfC44.mjs.map +1 -0
  57. package/dist/CloudflareScheduling-vZ7iSR57.d.mts +54 -0
  58. package/dist/CloudflareScheduling.d.mts +2 -0
  59. package/dist/CloudflareScheduling.mjs +1 -0
  60. package/dist/CloudflareSubscriptions-IHSo19MU.d.mts +91 -0
  61. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs +529 -0
  62. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs.map +1 -0
  63. package/dist/CloudflareSubscriptions.d.mts +2 -0
  64. package/dist/CloudflareSubscriptions.mjs +1 -0
  65. package/dist/CloudflareThreadClient-BUv9Te1s.d.mts +2141 -0
  66. package/dist/CloudflareThreadClient-K7QJHYpK.mjs +496 -0
  67. package/dist/CloudflareThreadClient-K7QJHYpK.mjs.map +1 -0
  68. package/dist/CloudflareThreadClient.d.mts +3 -0
  69. package/dist/CloudflareThreadClient.mjs +3 -0
  70. package/dist/InteractiveBrowser-CMbA7YPP.d.mts +228 -0
  71. package/dist/InteractiveBrowser-e8ZvxC1C.mjs +2013 -0
  72. package/dist/InteractiveBrowser-e8ZvxC1C.mjs.map +1 -0
  73. package/dist/InteractiveBrowser.d.mts +2 -0
  74. package/dist/InteractiveBrowser.mjs +1 -0
  75. package/dist/LiveText-CfpcZaGb.d.mts +91 -0
  76. package/dist/LiveText-DaF0tN_p.mjs +148 -0
  77. package/dist/LiveText-DaF0tN_p.mjs.map +1 -0
  78. package/dist/LiveText.d.mts +2 -0
  79. package/dist/LiveText.mjs +1 -0
  80. package/dist/R2ToolResultStorage.d.mts +27 -0
  81. package/dist/R2ToolResultStorage.mjs +84 -0
  82. package/dist/R2ToolResultStorage.mjs.map +1 -0
  83. package/dist/ThreadObject-B2-PqnpT.d.mts +390 -0
  84. package/dist/ThreadObject-D1pCeNrq.mjs +1225 -0
  85. package/dist/ThreadObject-D1pCeNrq.mjs.map +1 -0
  86. package/dist/ThreadObject.d.mts +2 -0
  87. package/dist/ThreadObject.mjs +1 -0
  88. package/dist/WakeScheduler-67UeXBYK.d.mts +22 -0
  89. package/dist/WakeScheduler-DV4J4TRe.mjs +69 -0
  90. package/dist/WakeScheduler-DV4J4TRe.mjs.map +1 -0
  91. package/dist/WakeScheduler.d.mts +2 -0
  92. package/dist/WakeScheduler.mjs +1 -0
  93. package/dist/boundary-YrOnE2zO.mjs +41 -0
  94. package/dist/boundary-YrOnE2zO.mjs.map +1 -0
  95. package/dist/browser-failure-CWBBnf1j.mjs +70 -0
  96. package/dist/browser-failure-CWBBnf1j.mjs.map +1 -0
  97. package/dist/index.d.mts +17 -0
  98. package/dist/index.mjs +17 -0
  99. package/dist/prepared-admission-DngoYN74.mjs +57 -0
  100. package/dist/prepared-admission-DngoYN74.mjs.map +1 -0
  101. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  102. package/package.json +132 -5
  103. package/src/Alarm.ts +3402 -0
  104. package/src/BrowserCredentials.ts +181 -0
  105. package/src/BrowserRestCapture.ts +383 -0
  106. package/src/BrowserSession.ts +993 -0
  107. package/src/BrowserUse.ts +438 -0
  108. package/src/CloudflareAiGateway.ts +176 -0
  109. package/src/CloudflareBindings.ts +225 -0
  110. package/src/CloudflareBrowser.ts +9 -0
  111. package/src/CloudflareCodeMode.ts +896 -0
  112. package/src/CloudflareConfig.ts +142 -0
  113. package/src/CloudflareMemory.ts +418 -0
  114. package/src/CloudflareScheduling.ts +736 -0
  115. package/src/CloudflareSubscriptions.ts +1032 -0
  116. package/src/CloudflareThreadClient.ts +980 -0
  117. package/src/InteractiveBrowser.ts +3300 -0
  118. package/src/LiveText.ts +145 -0
  119. package/src/R2ToolResultStorage.ts +131 -0
  120. package/src/ThreadObject.ts +1348 -0
  121. package/src/WakeScheduler.ts +102 -0
  122. package/src/index.ts +16 -0
  123. package/src/internal/boundary.ts +53 -0
  124. package/src/internal/browser-binding.ts +483 -0
  125. package/src/internal/browser-credentials.ts +481 -0
  126. package/src/internal/browser-failure.ts +145 -0
  127. package/src/internal/browser-file-selection.ts +146 -0
  128. package/src/internal/browser-quick-action.ts +666 -0
  129. package/src/internal/browser-readonly-live-view.ts +121 -0
  130. package/src/internal/browser-session-lifecycle.ts +200 -0
  131. package/src/internal/crypto.ts +44 -0
  132. package/src/internal/due-queue.ts +452 -0
  133. package/src/internal/host-protocol-error.ts +23 -0
  134. package/src/internal/layers.ts +1181 -0
  135. package/src/internal/live-text-observation.ts +8 -0
  136. package/src/internal/live-text-protocol.ts +59 -0
  137. package/src/internal/live-text.ts +339 -0
  138. package/src/internal/message-delivery.ts +149 -0
  139. package/src/internal/page-function.ts +12 -0
  140. package/src/internal/prepared-admission.ts +83 -0
  141. package/src/internal/progress-wait.ts +121 -0
  142. package/src/internal/transport.ts +53 -0
  143. package/README.md +0 -3
@@ -0,0 +1,142 @@
1
+ import { DEFAULT_MAX_STORED_VALUE_BYTES } from '@systemfsoftware/agent-storage-cloudflare/do-storage-config'
2
+ import { DeploymentId } from '@systemfsoftware/agent/records'
3
+ import * as Context from 'effect/Context'
4
+ import * as Schema from 'effect/Schema'
5
+
6
+ /**
7
+ * Schema-validated configuration for the Cloudflare durable runtime (deployment spec §4:
8
+ * decoded once during Layer construction, exposed as a typed service; DEPLOY-003). Every
9
+ * cadence is in milliseconds; every bound is finite and checked before any resource opens.
10
+ */
11
+
12
+ const PositiveMillis = Schema.Int.check(Schema.isGreaterThan(0))
13
+
14
+ /** Maximum supported auxiliary wave equals the native message policy's five-minute ceiling. */
15
+ export const AuxiliaryDispatchMillis = PositiveMillis.check(Schema.isLessThanOrEqualTo(300_000))
16
+ const NonNegativeMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
17
+
18
+ /** Recovery coverage retained after activity; independent of work-start and retry deadlines. */
19
+ export const DEFAULT_RECOVERY_WINDOW_MILLIS = 60_000
20
+
21
+ /** The supplied Cloudflare durable runtime configuration failed validation (DEPLOY-003). */
22
+ export class CloudflarePlatformConfigError extends Schema.TaggedError<CloudflarePlatformConfigError>()(
23
+ 'CloudflarePlatformConfigError',
24
+ {
25
+ message: Schema.String,
26
+ cause: Schema.optionalKey(Schema.Defect()),
27
+ },
28
+ ) {}
29
+
30
+ /**
31
+ * An admission was refused by a host resource limit BEFORE any ledger row existed
32
+ * (deployment spec §8, DEPLOY-007: "Admission has explicit bounded quota and overload
33
+ * behavior... a typed rejection"). This is the DC analogue of `NodeDurableHost`'s
34
+ * `AdmissionClosed` host gate: the port surface stays untouched, the refusal happens in the
35
+ * Thread Object's submit entry point before `DurableAgentRuntime.submit` runs, and
36
+ * nothing was admitted or written.
37
+ */
38
+ export class AdmissionLimitExceeded extends Schema.TaggedError<AdmissionLimitExceeded>()(
39
+ 'AdmissionLimitExceeded',
40
+ {
41
+ limit: Schema.Literals(['queue-depth', 'input-bytes', 'database-bytes']),
42
+ actual: Schema.Int,
43
+ maximum: Schema.Int,
44
+ },
45
+ ) {
46
+ override get message() {
47
+ return (
48
+ `Admission refused before any ledger row existed: ${this.limit} ${this.actual} exceeds ` +
49
+ `the configured maximum ${this.maximum}. Accepted work is unaffected; retry after the ` +
50
+ 'lane drains or raise the limit (DEPLOY-007).'
51
+ )
52
+ }
53
+ }
54
+
55
+ /** The platform's hard per-Object database cap (10 GB, developers.cloudflare.com limits). */
56
+ export const CLOUDFLARE_DATABASE_CAP_BYTES = 10_000_000_000
57
+
58
+ /** Default database-size admission ceiling: a 1 GB safety margin under the platform cap. */
59
+ export const DEFAULT_MAX_DATABASE_BYTES = 9_000_000_000
60
+
61
+ /**
62
+ * Explicit bounded admission quotas checked by the Thread Object BEFORE admission
63
+ * (exit gate "resource limits are checked before admission").
64
+ */
65
+ export class CloudflareAdmissionLimitsValue extends Schema.Class<CloudflareAdmissionLimitsValue>(
66
+ '@effect-agent/platform-cloudflare/CloudflareAdmissionLimitsValue',
67
+ )({
68
+ /** Maximum nonterminal Submissions per Thread lane before new admissions refuse. */
69
+ maxQueueDepthPerLane: Schema.Int.check(
70
+ Schema.isGreaterThan(0),
71
+ Schema.isLessThanOrEqualTo(100_000),
72
+ ),
73
+ /** Maximum encoded input bytes; never above the storage per-value bound. */
74
+ maxInputBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(2_000_000)),
75
+ /** Maximum `ctx.storage.sql.databaseSize` at admission; stays under the 10 GB platform cap. */
76
+ maxDatabaseBytes: Schema.Int.check(
77
+ Schema.isGreaterThan(0),
78
+ Schema.isLessThanOrEqualTo(CLOUDFLARE_DATABASE_CAP_BYTES),
79
+ ),
80
+ }) {}
81
+
82
+ /**
83
+ * Validated Cloudflare durable runtime configuration. The producer identity of one
84
+ * Thread Object is `{producerPrefix}:{threadId}` — stable across incarnations of
85
+ * the same deployment, distinct across deployments. The Object owns its Thread exclusively;
86
+ * scoped local generations reject callbacks from an earlier Run owner.
87
+ */
88
+ export class CloudflareDurableRuntimeConfigValue extends Schema.Class<CloudflareDurableRuntimeConfigValue>(
89
+ '@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfigValue',
90
+ )({
91
+ deploymentId: DeploymentId,
92
+ /** Head of the minted producer identity `{producerPrefix}:{threadId}`. */
93
+ producerPrefix: Schema.NonEmptyString.check(Schema.isMaxLength(256)),
94
+ /** Recovery-only window. Zero restores immediate idle cancellation and the short guards. */
95
+ recoveryWindowMillis: NonNegativeMillis,
96
+ /**
97
+ * Base delay of exponential backoff when a pass fails or makes no progress.
98
+ * Half this delay (rounded up, at least 1ms) starts alarm-driven work and recovers
99
+ * startup work. It also pre-arms mutations when the recovery window is disabled.
100
+ */
101
+ alarmBackoffBase: PositiveMillis,
102
+ /** Ceiling of exponential backoff after failed or no-progress maintenance passes. */
103
+ alarmBackoffCap: PositiveMillis,
104
+ /** `awaitSettlement` ledger re-check cadence when no wake arrives. */
105
+ settlementPollInterval: PositiveMillis,
106
+ /** Active-Run abort-intent poll cadence. */
107
+ abortPollInterval: PositiveMillis,
108
+ /** Canonical observation poll cadence of the Durable Object store. */
109
+ observationPollInterval: NonNegativeMillis,
110
+ /** One disposable projection backfill wave; independent of required live applyCommitted. */
111
+ projectionDispatchTimeoutMillis: AuxiliaryDispatchMillis,
112
+ /** Per-value byte bound; must stay under the platform's 2 MB SQLite value limit. */
113
+ maxStoredValueBytes: Schema.Int.check(
114
+ Schema.isGreaterThan(0),
115
+ Schema.isLessThanOrEqualTo(2_000_000),
116
+ ),
117
+ /** Opt-in full history and active-state validation while opening the store. */
118
+ verifyOnOpen: Schema.Boolean,
119
+ limits: CloudflareAdmissionLimitsValue,
120
+ }) {}
121
+
122
+ /** Explicit configuration authority for the assembled Cloudflare durable runtime. */
123
+ export class CloudflareDurableRuntimeConfig extends Context.Service<
124
+ CloudflareDurableRuntimeConfig,
125
+ CloudflareDurableRuntimeConfigValue
126
+ >()('@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfig') {}
127
+
128
+ /** Documented production defaults applied by `ThreadObject.layer`. */
129
+ export const CLOUDFLARE_RUNTIME_DEFAULTS = {
130
+ recoveryWindowMillis: DEFAULT_RECOVERY_WINDOW_MILLIS,
131
+ alarmBackoffBase: 100,
132
+ alarmBackoffCap: 5_000,
133
+ settlementPollInterval: 500,
134
+ abortPollInterval: 500,
135
+ observationPollInterval: 25,
136
+ projectionDispatchTimeoutMillis: 30_000,
137
+ maxStoredValueBytes: DEFAULT_MAX_STORED_VALUE_BYTES,
138
+ verifyOnOpen: false,
139
+ maxQueueDepthPerLane: 256,
140
+ maxInputBytes: DEFAULT_MAX_STORED_VALUE_BYTES,
141
+ maxDatabaseBytes: DEFAULT_MAX_DATABASE_BYTES,
142
+ } as const
@@ -0,0 +1,418 @@
1
+ import {
2
+ defaultDoMemoryStorageLimits,
3
+ type DoMemoryStorageLimits,
4
+ doMemoryStoreLayerWithFailpoints,
5
+ } from '@systemfsoftware/agent-storage-cloudflare/do-memory-store'
6
+ import {
7
+ decodeMemoryWire,
8
+ defaultMemoryRpcLimits,
9
+ encodeMemoryWire,
10
+ handleMemoryOwnerRequest,
11
+ type MemoryOwnerAuthorizer,
12
+ type MemoryOwnerFailure,
13
+ MemoryOwnerIdentity,
14
+ MemoryOwnerRequest,
15
+ MemoryOwnerResponse,
16
+ MemoryRpcError,
17
+ MemoryRpcLimits,
18
+ } from '@systemfsoftware/agent-storage-cloudflare/memory-protocol'
19
+ import * as Memory from '@systemfsoftware/agent/memory'
20
+ import * as MemoryNamespace from '@systemfsoftware/agent/memory-namespace'
21
+ import { MemoryNamespaceAddress } from '@systemfsoftware/agent/memory-namespace'
22
+ import { type MemoryLookup, MemoryRecallLimits } from '@systemfsoftware/agent/memory-reference'
23
+ import { MemoryAccess } from '@systemfsoftware/agent/memory-revalidation'
24
+ import {
25
+ MemoryDocument,
26
+ MemoryKey,
27
+ MemoryMutationFailpoint,
28
+ type MemoryReader,
29
+ MemoryStorageError,
30
+ type MemoryWrite,
31
+ MemoryWriter,
32
+ } from '@systemfsoftware/agent/memory-store'
33
+ import { type MemoryIndexSearch, type SemanticMemoryProfile } from '@systemfsoftware/agent/semantic-memory-index'
34
+ import { type SemanticCandidateLimits } from '@systemfsoftware/agent/semantic-memory-revalidation'
35
+ import { Principal } from '@systemfsoftware/agent/submission-ledger'
36
+ import {
37
+ DurableObject as EffectCfDurableObject,
38
+ DurableObjectState,
39
+ RpcTargets,
40
+ type WorkerEnvironment,
41
+ } from 'effect-cf'
42
+ import * as Clock from 'effect/Clock'
43
+ import * as Context from 'effect/Context'
44
+ import * as Effect from 'effect/Effect'
45
+ import * as Layer from 'effect/Layer'
46
+ import * as Schema from 'effect/Schema'
47
+
48
+ export interface MemoryObjectRpc extends Rpc.DurableObjectBranded {
49
+ memory(encoded: string): Promise<string>
50
+ }
51
+
52
+ export class MemoryObjectNamespace extends Context.Service<
53
+ MemoryObjectNamespace,
54
+ {
55
+ readonly namespace: DurableObjectNamespace<MemoryObjectRpc>
56
+ }
57
+ >()('@effect-agent/platform-cloudflare/MemoryObjectNamespace') {}
58
+
59
+ /** Namespace version and identity are already canonicalized by MemoryNamespace. */
60
+ export const memoryObjectName = (namespace: MemoryNamespace.Any): string => namespace.address
61
+
62
+ /**
63
+ * Effect-native, host-bound memory client. Recall revalidates the entire admitted lookup
64
+ * in one RPC and renders it locally. No retries or per-source splitting occur here.
65
+ * Interrupted callers stop waiting; the owner has its own deadline. A timed-out write
66
+ * may have committed: reconcile by sending the identical operation ID and command.
67
+ */
68
+ const makeMemoryClient = Effect.fnUntraced(function*<Namespace extends MemoryNamespace.Any>(
69
+ access: MemoryAccess<Namespace>,
70
+ principal: Principal,
71
+ rpcLimits: MemoryRpcLimits = defaultMemoryRpcLimits,
72
+ ) {
73
+ const validated = yield* Schema.decodeEffect(MemoryRpcLimits)(rpcLimits).pipe(
74
+ Effect.mapError(() => MemoryRpcError.make({ reason: 'protocol' })),
75
+ )
76
+
77
+ const bound = yield* Schema.decodeUnknownEffect(MemoryAccess.Wire)(access).pipe(
78
+ Effect.mapError(() => MemoryRpcError.make({ reason: 'protocol' })),
79
+ )
80
+
81
+ principal = yield* Schema.decodeEffect(Principal)(principal).pipe(
82
+ Effect.mapError(() => MemoryRpcError.make({ reason: 'protocol' })),
83
+ )
84
+ const { namespace } = yield* MemoryObjectNamespace
85
+
86
+ const call = Effect.fnUntraced(function*(request: MemoryOwnerRequest) {
87
+ const decoded = yield* Schema.decodeEffect(MemoryOwnerRequest)(request).pipe(
88
+ Effect.mapError(() => MemoryRpcError.make({ reason: 'protocol' })),
89
+ )
90
+
91
+ const encoded = yield* encodeMemoryWire(MemoryOwnerRequest, decoded, validated.maxRequestBytes)
92
+
93
+ const unavailable = (cause: unknown) => {
94
+ const error = MemoryRpcError.make({ reason: 'unavailable' })
95
+
96
+ error.cause = cause
97
+
98
+ return error
99
+ }
100
+
101
+ const address = memoryObjectName(bound.namespace)
102
+
103
+ const target = yield* RpcTargets.get(namespace, address, () => namespace.get(namespace.idFromName(address))).pipe(
104
+ Effect.mapError(unavailable),
105
+ )
106
+
107
+ const raw = yield* Effect.tryPromise({
108
+ try: () => target.memory(encoded),
109
+ catch: unavailable,
110
+ }).pipe(Effect.tapCause(() => RpcTargets.invalidate(target)))
111
+
112
+ const response = yield* decodeMemoryWire(MemoryOwnerResponse, raw, validated.maxResponseBytes)
113
+
114
+ if (response._tag === 'Failed') return yield* response.failure
115
+ if (
116
+ !MemoryNamespace.equals(response.access.namespace, bound.namespace) ||
117
+ response.access.scope !== bound.scope
118
+ ) {
119
+ return yield* MemoryRpcError.make({ reason: 'protocol' })
120
+ }
121
+
122
+ return response
123
+ })
124
+
125
+ const withinDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>, timeoutMillis: number) =>
126
+ effect.pipe(
127
+ Effect.timeoutOrElse({
128
+ duration: timeoutMillis,
129
+ orElse: () => Effect.fail(MemoryRpcError.make({ reason: 'timeout' })),
130
+ }),
131
+ )
132
+
133
+ const revalidate = Effect.fnUntraced(function*(
134
+ lookup: MemoryLookup,
135
+ limits: MemoryRecallLimits,
136
+ ) {
137
+ limits = yield* Schema.decodeEffect(MemoryRecallLimits)(limits).pipe(
138
+ Effect.mapError(() => MemoryRpcError.make({ reason: 'protocol' })),
139
+ )
140
+ const timeoutMillis = Math.min(validated.timeoutMillis, limits.timeoutMillis)
141
+
142
+ return yield* Effect.gen(function*() {
143
+ const response = yield* call({
144
+ _tag: 'Revalidate',
145
+ version: 1,
146
+ access: bound,
147
+ principal,
148
+ lookup,
149
+ limits,
150
+ deadlineMillis: (yield* Clock.currentTimeMillis) + timeoutMillis,
151
+ })
152
+
153
+ if (response._tag !== 'Lookup') return yield* MemoryRpcError.make({ reason: 'protocol' })
154
+
155
+ return response.lookup
156
+ }).pipe((effect) => withinDeadline(effect, timeoutMillis))
157
+ })
158
+
159
+ const change = Effect.fnUntraced(function*(write: MemoryWrite<Namespace>) {
160
+ if (!MemoryNamespace.equals(write.key.namespace, bound.namespace)) {
161
+ return yield* MemoryRpcError.make({ reason: 'denied' })
162
+ }
163
+
164
+ return yield* Effect.gen(function*() {
165
+ const response = yield* call({
166
+ _tag: 'Change',
167
+ version: 1,
168
+ access: bound,
169
+ principal,
170
+ write,
171
+ deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,
172
+ })
173
+
174
+ if (response._tag !== 'Changed' || response.document.key.id !== write.key.id) {
175
+ return yield* MemoryRpcError.make({ reason: 'protocol' })
176
+ }
177
+
178
+ return yield* MemoryDocument.restore(access.namespace, response.document)
179
+ }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis))
180
+ })
181
+
182
+ /**
183
+ * Read one exact current document in one owner RPC. Null means absent; withdrawals return
184
+ * tombstones. Denial, unavailable storage and deadlines fail typed, never become absence.
185
+ * Reads begun after an acknowledged write observe it or a later revision. The owner checks
186
+ * exact-key authority and active document scopes; source-dependent provenance policy remains
187
+ * application-owned. No extraction, job draining, embedding, discovery or rendering occurs.
188
+ */
189
+ const get = Effect.fnUntraced(function*(key: MemoryKey<Namespace>) {
190
+ const decodedKey = yield* Schema.decodeUnknownEffect(MemoryKey.Wire)(key).pipe(
191
+ Effect.mapError(() => MemoryRpcError.make({ reason: 'protocol' })),
192
+ )
193
+
194
+ if (!MemoryNamespace.equals(decodedKey.namespace, bound.namespace)) {
195
+ return yield* MemoryRpcError.make({ reason: 'denied' })
196
+ }
197
+
198
+ return yield* Effect.gen(function*() {
199
+ const response = yield* call({
200
+ _tag: 'Get',
201
+ version: 1,
202
+ access: bound,
203
+ principal,
204
+ key: decodedKey,
205
+ deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,
206
+ })
207
+
208
+ if (
209
+ response._tag !== 'Document' ||
210
+ !MemoryNamespace.equals(response.key.namespace, bound.namespace) ||
211
+ response.key.id !== decodedKey.id
212
+ ) {
213
+ return yield* MemoryRpcError.make({ reason: 'protocol' })
214
+ }
215
+ if (response.document === null) return null
216
+ if (
217
+ response.document.key.id !== decodedKey.id ||
218
+ response.document.source.id !== decodedKey.id ||
219
+ (response.document._tag === 'ActiveMemoryDocument' &&
220
+ !response.document.scopes.includes(bound.scope))
221
+ ) {
222
+ return yield* MemoryRpcError.make({ reason: 'protocol' })
223
+ }
224
+
225
+ yield* encodeMemoryWire(MemoryDocument.Wire, response.document, validated.maxSourceBytes)
226
+
227
+ return yield* MemoryDocument.restore(access.namespace, response.document)
228
+ }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis))
229
+ })
230
+
231
+ const revalidateSemantic = Effect.fnUntraced(
232
+ function*(
233
+ found: MemoryIndexSearch<Namespace>,
234
+ profile: SemanticMemoryProfile,
235
+ limits: SemanticCandidateLimits,
236
+ ) {
237
+ const response = yield* call({
238
+ _tag: 'RevalidateSemantic',
239
+ version: 1,
240
+ access: bound,
241
+ principal,
242
+ found,
243
+ profile,
244
+ limits,
245
+ deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,
246
+ })
247
+
248
+ if (response._tag !== 'Semantic') return yield* MemoryRpcError.make({ reason: 'protocol' })
249
+
250
+ return response.result
251
+ },
252
+ (effect) => withinDeadline(effect, validated.timeoutMillis),
253
+ )
254
+
255
+ /**
256
+ * Revalidate in one owner RPC, then render whole passages within the caller's budget.
257
+ * The bound source is essential: unavailable/stale results and matches that cannot fit
258
+ * fail instead of silently producing empty context. No-match remains successful.
259
+ * The single outcome has sourceId "memory". No embedding or candidate search is performed.
260
+ * Use revalidate with Memory.recall for multiple readers sharing one output budget.
261
+ */
262
+ const recall = (
263
+ lookup: MemoryLookup,
264
+ limits: MemoryRecallLimits,
265
+ estimateTokens?: (text: string) => number,
266
+ ) =>
267
+ Memory.recall(
268
+ [{ id: 'memory', essential: true, read: revalidate(lookup, limits) }],
269
+ limits,
270
+ estimateTokens,
271
+ )
272
+
273
+ return { get, recall, revalidate, revalidateSemantic, change }
274
+ })
275
+
276
+ export const CloudflareMemoryClient = {
277
+ /** Bind access and principal using the MemoryObjectNamespace supplied by the application. */
278
+ make: makeMemoryClient,
279
+ /** Use a resolved Worker or Durable Object binding without manual service provisioning. */
280
+ fromBinding: <Namespace extends MemoryNamespace.Any>(
281
+ binding: DurableObjectNamespace<MemoryObjectRpc>,
282
+ options: {
283
+ readonly access: MemoryAccess<Namespace>
284
+ readonly principal: Principal
285
+ readonly rpcLimits?: MemoryRpcLimits
286
+ },
287
+ ) =>
288
+ makeMemoryClient(options.access, options.principal, options.rpcLimits).pipe(
289
+ Effect.provideService(MemoryObjectNamespace, { namespace: binding }),
290
+ ),
291
+ }
292
+
293
+ /**
294
+ * Optional activity-processor destination. Keeps domain write errors intact; transport,
295
+ * authorization and deadline failures become the existing MemoryStorageError contract.
296
+ * Receipts remain authoritative, including after caller interruption or lost replies.
297
+ */
298
+ export const cloudflareMemoryWriterLayer = (
299
+ access: MemoryAccess,
300
+ principal: Principal,
301
+ limits: MemoryRpcLimits = defaultMemoryRpcLimits,
302
+ ) =>
303
+ Layer.effect(
304
+ MemoryWriter,
305
+ Effect.gen(function*() {
306
+ const client = yield* CloudflareMemoryClient.make(access, principal, limits)
307
+
308
+ return MemoryWriter.fromAdapter({
309
+ change: (write) =>
310
+ client.change(write).pipe(
311
+ Effect.catchTag('MemoryRpcError', (error) =>
312
+ Effect.fail(
313
+ MemoryStorageError.make({
314
+ operation: `memory RPC ${error.reason}`,
315
+ reason: error.reason === 'unavailable' || error.reason === 'timeout'
316
+ ? 'unavailable'
317
+ : 'invalid-input',
318
+ }),
319
+ )),
320
+ Effect.catchTag(['MemoryRecallError', 'MemoryIndexError', 'SemanticMemoryError'], () =>
321
+ Effect.fail(
322
+ MemoryStorageError.make({ operation: 'memory RPC response', reason: 'corrupt' }),
323
+ )),
324
+ ),
325
+ })
326
+ }),
327
+ )
328
+
329
+ type OwnerServices = MemoryReader | MemoryWriter | MemoryOwnerAuthorizer | MemoryOwnerIdentity
330
+
331
+ export interface MemoryObjectInstance extends
332
+ InstanceType<
333
+ EffectCfDurableObject.DurableObjectClass<Record<never, never>, OwnerServices>
334
+ >
335
+ {
336
+ memory(encoded: string): Promise<string>
337
+ }
338
+
339
+ export interface MemoryObjectClass {
340
+ new(ctx: globalThis.DurableObjectState, env: Cloudflare.Env): MemoryObjectInstance
341
+ }
342
+
343
+ /**
344
+ * Dedicated SQLite owner, independent of Thread lifetimes. The host binds authorization
345
+ * after restoring its namespace definition from MemoryOwnerIdentity. Do not retain
346
+ * cleanup-scoped resources in the host Layer; it lives for the DO incarnation.
347
+ */
348
+ const makeMemoryObject = <E>(
349
+ host: Layer.Layer<
350
+ MemoryOwnerAuthorizer,
351
+ E,
352
+ MemoryOwnerIdentity | DurableObjectState.DurableObjectState | WorkerEnvironment
353
+ >,
354
+ options: {
355
+ readonly storageLimits?: DoMemoryStorageLimits
356
+ readonly rpcLimits?: MemoryRpcLimits
357
+ readonly failpoints?: Layer.Layer<
358
+ MemoryMutationFailpoint,
359
+ never,
360
+ DurableObjectState.DurableObjectState
361
+ >
362
+ } = {},
363
+ ): MemoryObjectClass => {
364
+ const identity = Layer.effect(
365
+ MemoryOwnerIdentity,
366
+ Effect.gen(function*() {
367
+ const state = yield* DurableObjectState.DurableObjectState
368
+
369
+ const address = yield* Schema.decodeUnknownEffect(MemoryNamespaceAddress)(
370
+ state.raw.id.name,
371
+ ).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: 'denied' })))
372
+
373
+ return { namespace: MemoryNamespace.Any.make({ address }) }
374
+ }),
375
+ )
376
+
377
+ const store = Layer.unwrap(
378
+ Effect.map(DurableObjectState.DurableObjectState, (state) =>
379
+ doMemoryStoreLayerWithFailpoints(
380
+ state.raw.storage,
381
+ options.storageLimits ?? defaultDoMemoryStorageLimits,
382
+ )),
383
+ ).pipe(Layer.provide(options.failpoints ?? MemoryMutationFailpoint.layer))
384
+
385
+ const application = Layer.merge(store, host).pipe(Layer.provideMerge(identity))
386
+
387
+ const runtime: Layer.Layer<
388
+ OwnerServices,
389
+ E | MemoryOwnerFailure,
390
+ DurableObjectState.DurableObjectState | WorkerEnvironment
391
+ > = Layer.effectContext(
392
+ Effect.gen(function*() {
393
+ const state = yield* DurableObjectState.DurableObjectState
394
+ const scope = yield* Effect.scope
395
+
396
+ yield* Schema.decodeEffect(MemoryRpcLimits)(options.rpcLimits ?? defaultMemoryRpcLimits).pipe(
397
+ Effect.mapError(() => MemoryRpcError.make({ reason: 'protocol' })),
398
+ )
399
+
400
+ return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope))
401
+ }),
402
+ )
403
+
404
+ const rpc = { memory: (encoded: string) => handleMemoryOwnerRequest(encoded, options.rpcLimits) }
405
+
406
+ return EffectCfDurableObject.make<
407
+ OwnerServices,
408
+ E | MemoryOwnerFailure,
409
+ never,
410
+ never,
411
+ typeof rpc
412
+ >(runtime, { rpc })
413
+ }
414
+
415
+ export const MemoryObject = {
416
+ /** Build the SQLite Durable Object class with the application's owner authorization Layer. */
417
+ make: makeMemoryObject,
418
+ }