@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,896 @@
1
+ import {
2
+ CodeExecutionHost,
3
+ CodeExecutionProtocolError,
4
+ type CodeExecutionRequest,
5
+ CodeExecutionResourceUse,
6
+ CodeExecutionResult,
7
+ CodeExecutionTimeoutError,
8
+ CodeExecutor,
9
+ type CodeExecutorExecute,
10
+ CodeExecutorStartError,
11
+ CodeExecutorTerminatedError,
12
+ CodeExecutorUnsupportedError,
13
+ CodeHostCall,
14
+ CodeHostCallLimitError,
15
+ CodeHostCallResult,
16
+ CodeOutputLimitError,
17
+ CodeProgramFailedError,
18
+ CodeSourceError,
19
+ } from '@systemfsoftware/agent/code-executor'
20
+ import { SandboxImplementation } from '@systemfsoftware/agent/sandbox'
21
+ import { RpcTarget } from 'cloudflare:workers'
22
+ import * as Clock from 'effect/Clock'
23
+ import * as Duration from 'effect/Duration'
24
+ import * as Effect from 'effect/Effect'
25
+ import * as Exit from 'effect/Exit'
26
+ import * as Fiber from 'effect/Fiber'
27
+ import * as Layer from 'effect/Layer'
28
+ import * as Option from 'effect/Option'
29
+ import * as Queue from 'effect/Queue'
30
+ import * as Schema from 'effect/Schema'
31
+
32
+ import { safeCauseDiagnostic, safeCauseMessage } from './internal/boundary'
33
+
34
+ /**
35
+ * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017;
36
+ * DEPLOY-011). Each pass loads one fresh Worker through the Worker Loader
37
+ * with `globalOutbound: null`, so generated code has no ambient network,
38
+ * bindings, or secrets; its only authority is the pass-scoped RPC target that
39
+ * routes back into the owning event's `CodeExecutionHost` service. Platform
40
+ * CPU limits stop synchronous runaway programs; the executor-owned wall-clock
41
+ * deadline interrupts asynchronously suspended passes. Deployment class `E`
42
+ * only: the adapter records no persistent state and a later pass may run in a
43
+ * completely different isolate.
44
+ */
45
+ export const dynamicWorkerImplementation = SandboxImplementation.make({
46
+ isolation: 'isolated',
47
+ identity: 'cloudflare-dynamic-worker',
48
+ })
49
+
50
+ interface CodeModePassHost extends Rpc.RpcTargetBranded {
51
+ readonly call: (hostCall: unknown) => Promise<unknown>
52
+ }
53
+
54
+ interface CodeModeHarnessEntrypoint extends Rpc.WorkerEntrypointBranded {
55
+ readonly run: (host: CodeModePassHost) => Promise<unknown>
56
+ }
57
+
58
+ /**
59
+ * One object-capability endpoint for one execution pass. Workers RPC invokes
60
+ * the target in the request context where it was created, so the native
61
+ * Promise returned by `dispatch` and the Effect fiber that settles it share
62
+ * one I/O owner. Passing the target as `run()`'s argument also scopes the
63
+ * remote stub to that RPC call; no request state lives at module scope.
64
+ */
65
+ class CodeModePassHostTarget extends RpcTarget implements CodeModePassHost {
66
+ readonly #dispatch: (hostCall: unknown) => Promise<unknown>
67
+
68
+ constructor(dispatch: (hostCall: unknown) => Promise<unknown>) {
69
+ super()
70
+ this.#dispatch = dispatch
71
+ }
72
+
73
+ call(hostCall: unknown): Promise<unknown> {
74
+ return this.#dispatch(hostCall)
75
+ }
76
+ }
77
+
78
+ /**
79
+ * The fixed harness loaded as the dynamic worker's main module. The generated
80
+ * source becomes `program.mjs` (`export default (<expression>);`) — a module,
81
+ * never `eval`. The harness installs namespace globals and a bounded console,
82
+ * imports the program, invokes it exactly once, and returns one envelope the
83
+ * host validates through Effect Schema.
84
+ */
85
+ const HARNESS_MODULE = String.raw`
86
+ import { WorkerEntrypoint } from "cloudflare:workers";
87
+ import programDefault from "./program.js";
88
+
89
+ const encoder = new TextEncoder();
90
+ const utf8 = (text) => encoder.encode(text).byteLength;
91
+ const safeText = (value) => {
92
+ try {
93
+ if (value instanceof Error) return (value.name + ": " + value.message).slice(0, 4000);
94
+ if (typeof value === "string") return value.slice(0, 4000);
95
+ const encoded = JSON.stringify(value);
96
+ return (encoded === undefined ? String(value) : encoded).slice(0, 4000);
97
+ } catch {
98
+ return "[unserializable value]";
99
+ }
100
+ };
101
+ const safeJson = (value) => {
102
+ try {
103
+ const encoded = JSON.stringify(value);
104
+ if (encoded !== undefined && encoded.length <= 4000) return JSON.parse(encoded);
105
+ } catch {}
106
+ return safeText(value);
107
+ };
108
+
109
+ export default class CodeModeHarness extends WorkerEntrypoint {
110
+ async run(host) {
111
+ const config = this.env.CODE_MODE_PASS;
112
+ const limits = config.limits;
113
+ const logs = [];
114
+ let logBytes = 0;
115
+ let fatal;
116
+ const boundedLogs = () => logs.slice(0, 4096);
117
+ const write = (...values) => {
118
+ const joined = values.map(safeText).join(" ");
119
+ const line = joined.length > 16000 ? joined.slice(0, 15999) + "…" : joined;
120
+ const bytes = utf8(line);
121
+ if (logs.length >= 4096 || logBytes + bytes > limits.maxLogBytes) {
122
+ fatal = fatal ?? { _tag: "log-limit", observed: logBytes + bytes, logs: boundedLogs() };
123
+ throw new Error("code-mode log limit exceeded");
124
+ }
125
+ logs.push(line);
126
+ logBytes += bytes;
127
+ };
128
+ globalThis.console = { log: write, info: write, warn: write, error: write, debug: write };
129
+
130
+ let hostCalls = 0;
131
+ const makeMethod = (namespace, method) => async (argument) => {
132
+ hostCalls += 1;
133
+ if (hostCalls > limits.maxHostCalls) {
134
+ fatal = fatal ?? { _tag: "host-call-limit", logs: boundedLogs() };
135
+ throw new Error("code-mode host-call limit exceeded");
136
+ }
137
+ let argText;
138
+ try {
139
+ argText = JSON.stringify(argument);
140
+ } catch {}
141
+ if (argText === undefined || utf8(argText) > limits.maxHostCallArgumentBytes) {
142
+ fatal = fatal ?? {
143
+ _tag: "argument-limit",
144
+ observed: argText === undefined ? 0 : utf8(argText),
145
+ logs: boundedLogs(),
146
+ };
147
+ throw new Error("code-mode host-call argument limit exceeded");
148
+ }
149
+ const outcome = await host.call({
150
+ namespace,
151
+ method,
152
+ argument: JSON.parse(argText),
153
+ });
154
+ if (outcome !== null && typeof outcome === "object" && outcome._tag === "CodeHostCallSuccess") {
155
+ return outcome.value;
156
+ }
157
+ if (outcome !== null && typeof outcome === "object" && outcome._tag === "CodeHostCallFailure") {
158
+ if (outcome.error !== null && typeof outcome.error === "object") {
159
+ const display = JSON.stringify(outcome.error);
160
+ Object.defineProperty(outcome.error, Symbol.toPrimitive, { value: () => display });
161
+ }
162
+ throw outcome.error;
163
+ }
164
+ fatal = fatal ?? { _tag: "protocol", message: "host returned an unrecognized outcome" };
165
+ throw new Error("code-mode host protocol violation");
166
+ };
167
+ for (const namespace of config.namespaces) {
168
+ const methods = {};
169
+ for (const method of namespace.methods) {
170
+ methods[method] = makeMethod(namespace.name, method);
171
+ }
172
+ globalThis[namespace.name] = methods;
173
+ }
174
+
175
+ // program.js is imported statically at the top of this module, so a
176
+ // syntactically invalid program fails the whole harness at load (mapped
177
+ // to a source error by the host). Using a static import keeps this module
178
+ // free of dynamic-import expressions, which single-script Miniflare hosts
179
+ // reject. The isolation boundary does NOT depend on the ordering of this
180
+ // import versus the console/namespace shims installed below: the loaded
181
+ // Worker has globalOutbound: null and no bindings, secrets, or env from
182
+ // the Worker Loader config BEFORE any module in the graph evaluates, so
183
+ // module-level program code has no ambient authority regardless. The
184
+ // shims below are usability wrappers (bounded console, namespace globals),
185
+ // and the accepted program is a single async-function expression whose
186
+ // body runs only when invoked here — after the shims exist.
187
+ const program = programDefault;
188
+ if (typeof program !== "function") {
189
+ return { _tag: "source-not-a-function", actual: typeof program };
190
+ }
191
+ try {
192
+ const value = await program();
193
+ if (fatal !== undefined) return fatal;
194
+ let text;
195
+ try {
196
+ text = JSON.stringify(value);
197
+ } catch {}
198
+ if (text === undefined) {
199
+ return {
200
+ _tag: "program-failed",
201
+ reason: "non-json-result",
202
+ thrown: null,
203
+ message: "The program must return a JSON value",
204
+ logs: boundedLogs(),
205
+ };
206
+ }
207
+ const resultBytes = utf8(text);
208
+ if (resultBytes > limits.maxResultBytes) {
209
+ return { _tag: "result-limit", observed: resultBytes, logs: boundedLogs() };
210
+ }
211
+ return {
212
+ _tag: "completed",
213
+ value: JSON.parse(text),
214
+ logs: boundedLogs(),
215
+ hostCalls,
216
+ logBytes,
217
+ resultBytes,
218
+ };
219
+ } catch (cause) {
220
+ if (fatal !== undefined) return fatal;
221
+ return {
222
+ _tag: "program-failed",
223
+ reason: cause instanceof Error ? "threw" : "rejected",
224
+ thrown: safeJson(cause),
225
+ message: safeText(cause),
226
+ logs: boundedLogs(),
227
+ };
228
+ }
229
+ }
230
+ }
231
+ `
232
+
233
+ const BoundedLogs = Schema.Array(Schema.String.check(Schema.isMaxLength(16 * 1024))).check(
234
+ Schema.isMaxLength(4_096),
235
+ )
236
+
237
+ const HarnessCompleted = Schema.TaggedStruct('completed', {
238
+ value: Schema.Json,
239
+ logs: BoundedLogs,
240
+ hostCalls: Schema.Natural,
241
+ logBytes: Schema.Natural,
242
+ resultBytes: Schema.Natural,
243
+ })
244
+
245
+ const HarnessNotAFunction = Schema.TaggedStruct('source-not-a-function', {
246
+ actual: Schema.String,
247
+ })
248
+
249
+ const HarnessProgramFailed = Schema.TaggedStruct('program-failed', {
250
+ reason: Schema.Literals(['threw', 'rejected', 'non-json-result']),
251
+ thrown: Schema.Json,
252
+ message: Schema.String,
253
+ logs: BoundedLogs,
254
+ })
255
+
256
+ const HarnessLogLimit = Schema.TaggedStruct('log-limit', {
257
+ observed: Schema.Natural,
258
+ logs: BoundedLogs,
259
+ })
260
+
261
+ const HarnessArgumentLimit = Schema.TaggedStruct('argument-limit', {
262
+ observed: Schema.Natural,
263
+ logs: BoundedLogs,
264
+ })
265
+
266
+ const HarnessResultLimit = Schema.TaggedStruct('result-limit', {
267
+ observed: Schema.Natural,
268
+ logs: BoundedLogs,
269
+ })
270
+
271
+ const HarnessHostCallLimit = Schema.TaggedStruct('host-call-limit', {
272
+ logs: BoundedLogs,
273
+ })
274
+
275
+ const HarnessProtocol = Schema.TaggedStruct('protocol', {
276
+ message: Schema.String,
277
+ })
278
+
279
+ const HarnessOutcome = Schema.Union([
280
+ HarnessCompleted,
281
+ HarnessNotAFunction,
282
+ HarnessProgramFailed,
283
+ HarnessLogLimit,
284
+ HarnessArgumentLimit,
285
+ HarnessResultLimit,
286
+ HarnessHostCallLimit,
287
+ HarnessProtocol,
288
+ ])
289
+
290
+ const HarnessPassConfig = Schema.Struct({
291
+ namespaces: Schema.Array(
292
+ Schema.Struct({
293
+ name: Schema.NonEmptyString,
294
+ methods: Schema.Array(Schema.NonEmptyString).check(Schema.isMaxLength(64)),
295
+ }),
296
+ ).check(Schema.isMaxLength(32)),
297
+ limits: Schema.Struct({
298
+ maxLogBytes: Schema.Natural,
299
+ maxResultBytes: Schema.Natural,
300
+ maxHostCalls: Schema.Natural,
301
+ maxHostCallArgumentBytes: Schema.Natural,
302
+ }),
303
+ })
304
+
305
+ const encodeHarnessPassConfig = Schema.encodeSync(HarnessPassConfig)
306
+ const encodeJsonPayload = Schema.encodeSync(Schema.fromJsonString(Schema.Json))
307
+ const decodeJsonPayload = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json))
308
+
309
+ const decodeHarnessOutcome = (value: unknown) => {
310
+ try {
311
+ return Schema.decodeUnknownOption(HarnessOutcome)(value)
312
+ } catch {
313
+ return Option.none<typeof HarnessOutcome.Type>()
314
+ }
315
+ }
316
+
317
+ const decodeHostCall = (value: unknown) => {
318
+ try {
319
+ return Schema.decodeUnknownOption(CodeHostCall)(value)
320
+ } catch {
321
+ return Option.none<CodeHostCall>()
322
+ }
323
+ }
324
+
325
+ const decodeHostCallResult = (value: unknown) => {
326
+ try {
327
+ return Schema.decodeUnknownOption(CodeHostCallResult)(value)
328
+ } catch {
329
+ return Option.none<CodeHostCallResult>()
330
+ }
331
+ }
332
+
333
+ /** Dispose a Cloudflare RPC handle when the runtime supplies its untyped disposal hook. @internal */
334
+ export const disposeRpcHandle = (handle: unknown): Effect.Effect<void> =>
335
+ Effect.try({
336
+ try: () => {
337
+ if ((typeof handle !== 'object' && typeof handle !== 'function') || handle === null) return
338
+ if (!(Symbol.dispose in handle)) return
339
+ const dispose = Reflect.get(handle, Symbol.dispose)
340
+
341
+ if (typeof dispose === 'function') {
342
+ Reflect.apply(dispose, handle, [])
343
+ }
344
+ },
345
+ catch: (cause) => safeCauseDiagnostic(cause, 'The Cloudflare RPC disposal hook failed without a diagnostic'),
346
+ }).pipe(
347
+ Effect.catch((diagnostic) =>
348
+ Effect.logWarning(`Cloudflare RPC handle disposal failed: ${diagnostic}`).pipe(
349
+ Effect.ignoreCause,
350
+ )
351
+ ),
352
+ )
353
+
354
+ /**
355
+ * Project a host outcome to the plain JSON envelope the harness reads. A
356
+ * `CodeExecutionHost` may return either real `CodeHostCallResult` instances
357
+ * (the substitute and conformance kit) or plain-object equivalents (the Code
358
+ * Mode capability's broker route), so this reads the shared fields rather than
359
+ * `Schema.encodeSync`, which would reject a plain object.
360
+ */
361
+ interface EncodedHostResultPayload {
362
+ readonly encodedPayload: string
363
+ readonly resultBytes: number
364
+ }
365
+
366
+ const encodeHostResultPayload = (
367
+ outcome: CodeHostCallResult,
368
+ ): EncodedHostResultPayload | undefined => {
369
+ try {
370
+ const payload = outcome._tag === 'CodeHostCallSuccess' ? outcome.value : outcome.error
371
+ const encodedPayload = encodeJsonPayload(payload)
372
+
373
+ return {
374
+ encodedPayload,
375
+ resultBytes: utf8ByteLength(encodedPayload),
376
+ }
377
+ } catch {
378
+ return undefined
379
+ }
380
+ }
381
+
382
+ const utf8ByteLength = (value: string): number => {
383
+ let total = 0
384
+
385
+ for (const character of value) {
386
+ const codePoint = character.codePointAt(0) ?? 0
387
+
388
+ total += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4
389
+ }
390
+
391
+ return total
392
+ }
393
+
394
+ interface QueuedHostCall {
395
+ readonly call: CodeHostCall
396
+ readonly resolve: (value: unknown) => void
397
+ readonly reject: (reason: unknown) => void
398
+ }
399
+
400
+ type HostWork =
401
+ | { readonly _tag: 'call'; readonly queued: QueuedHostCall }
402
+ | { readonly _tag: 'limit' }
403
+
404
+ type HostDispatchError =
405
+ | CodeExecutionTimeoutError
406
+ | CodeOutputLimitError
407
+ | CodeExecutionProtocolError
408
+ | CodeHostCallLimitError
409
+
410
+ /** Reserved global names the harness owns inside the dynamic worker. */
411
+ const reservedHarnessGlobals = new Set(['console'])
412
+
413
+ export interface DynamicWorkerCodeExecutorOptions {
414
+ /** The `worker_loader` binding. */
415
+ readonly loader: WorkerLoader
416
+ /** Compatibility date for dynamic workers; defaults to `2025-05-01`. */
417
+ readonly compatibilityDate?: string | undefined
418
+ }
419
+
420
+ const makeExecute = (
421
+ options: DynamicWorkerCodeExecutorOptions,
422
+ clock: Clock.Clock,
423
+ ): CodeExecutorExecute =>
424
+ Effect.fnUntraced(function*(request: CodeExecutionRequest) {
425
+ if (request.network._tag !== 'NetworkDisabled') {
426
+ return yield* CodeExecutorUnsupportedError.make({
427
+ implementation: dynamicWorkerImplementation,
428
+ feature: 'network',
429
+ message:
430
+ 'The Dynamic Worker executor denies all egress with globalOutbound: null; an allowlist is not supported in the first slice',
431
+ })
432
+ }
433
+ const sourceBytes = utf8ByteLength(request.source)
434
+
435
+ if (sourceBytes > request.limits.maxSourceBytes) {
436
+ return yield* CodeSourceError.make({
437
+ implementation: dynamicWorkerImplementation,
438
+ reason: 'oversized',
439
+ message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,
440
+ })
441
+ }
442
+ for (const namespace of request.namespaces) {
443
+ if (reservedHarnessGlobals.has(namespace.name)) {
444
+ return yield* CodeExecutorUnsupportedError.make({
445
+ implementation: dynamicWorkerImplementation,
446
+ feature: 'namespaces',
447
+ message: `Namespace ${namespace.name} collides with a harness binding`,
448
+ })
449
+ }
450
+ }
451
+ const host = yield* CodeExecutionHost
452
+
453
+ // This synchronous clock access is confined to callbacks that must compute a timeout
454
+ // immediately. The Clock service remains the authority, so tests and hosts can replace it.
455
+ const startedAt = clock.monotonicTimeNanosUnsafe()
456
+ const passDeadline = startedAt + Duration.toNanosUnsafe(request.limits.maxWallTime)
457
+
458
+ const remainingPassWallTime = (): Duration.Duration => {
459
+ const now = clock.monotonicTimeNanosUnsafe()
460
+
461
+ return Duration.nanos(passDeadline > now ? passDeadline - now : 0n)
462
+ }
463
+
464
+ let issuedHostCalls = 0
465
+ let passOpen = true
466
+ const queuedHostCalls: Array<QueuedHostCall> = []
467
+ let passFailure: HostDispatchError | undefined
468
+
469
+ const failPass = (error: HostDispatchError): void => {
470
+ if (passFailure === undefined) passFailure = error
471
+ }
472
+
473
+ const rejectQueuedHostCalls = (reason: Error): void => {
474
+ for (const queued of queuedHostCalls.splice(0)) {
475
+ queued.reject(reason)
476
+ }
477
+ }
478
+
479
+ const queue = yield* Queue.unbounded<HostWork>()
480
+
481
+ const deliverHostOutcome = (
482
+ queued: QueuedHostCall,
483
+ outcome: CodeHostCallResult,
484
+ ): Effect.Effect<void, CodeExecutionProtocolError | CodeOutputLimitError> =>
485
+ Effect.gen(function*() {
486
+ const decoded = decodeHostCallResult(outcome)
487
+
488
+ if (Option.isNone(decoded)) {
489
+ const error = CodeExecutionProtocolError.make({
490
+ implementation: dynamicWorkerImplementation,
491
+ message: 'The execution host returned a value outside the CodeHostCallResult schema',
492
+ })
493
+
494
+ failPass(error)
495
+
496
+ return yield* error
497
+ }
498
+ const encoded = encodeHostResultPayload(decoded.value)
499
+
500
+ if (encoded === undefined || encoded.resultBytes > request.limits.maxHostCallResultBytes) {
501
+ const error = CodeOutputLimitError.make({
502
+ implementation: dynamicWorkerImplementation,
503
+ surface: 'host-call-result',
504
+ limit: request.limits.maxHostCallResultBytes,
505
+ observed: encoded?.resultBytes ?? 0,
506
+ logs: [],
507
+ })
508
+
509
+ failPass(error)
510
+
511
+ return yield* error
512
+ }
513
+ const normalizedPayload = decodeJsonPayload(encoded.encodedPayload)
514
+
515
+ if (Option.isNone(normalizedPayload)) {
516
+ const error = CodeExecutionProtocolError.make({
517
+ implementation: dynamicWorkerImplementation,
518
+ message: 'The execution host returned a result that could not cross the JSON boundary',
519
+ })
520
+
521
+ failPass(error)
522
+
523
+ return yield* error
524
+ }
525
+ queued.resolve(
526
+ decoded.value._tag === 'CodeHostCallSuccess'
527
+ ? { _tag: 'CodeHostCallSuccess', value: normalizedPayload.value }
528
+ : { _tag: 'CodeHostCallFailure', error: normalizedPayload.value },
529
+ )
530
+ })
531
+
532
+ // Workers RPC into the loader isolate cannot settle on the fiber blocked
533
+ // in `entrypoint.run()`. A Scope-owned sibling fiber keeps that
534
+ // independence while inheriting the pass Context and dying with the Scope.
535
+ const serveHostCalls = Effect.gen(function*() {
536
+ while (true) {
537
+ const work = yield* Queue.take(queue)
538
+
539
+ if (work._tag === 'limit') {
540
+ const error = CodeHostCallLimitError.make({
541
+ implementation: dynamicWorkerImplementation,
542
+ limit: request.limits.maxHostCalls,
543
+ logs: [],
544
+ })
545
+
546
+ failPass(error)
547
+
548
+ return yield* error
549
+ }
550
+ const queued = work.queued
551
+
552
+ yield* host.call(queued.call).pipe(
553
+ Effect.timeoutOrElse({
554
+ duration: remainingPassWallTime(),
555
+ orElse: () => {
556
+ const error = CodeExecutionTimeoutError.make({
557
+ implementation: dynamicWorkerImplementation,
558
+ kind: 'wall-clock',
559
+ maxWallTime: request.limits.maxWallTime,
560
+ logs: [],
561
+ })
562
+
563
+ failPass(error)
564
+
565
+ return error
566
+ },
567
+ }),
568
+ Effect.flatMap((outcome) => deliverHostOutcome(queued, outcome)),
569
+ Effect.tapError(() =>
570
+ // oxlint-disable-next-line effect/no-native-error -- Native Worker RPC rejection settles the sandbox program Promise; typed host failure is tracked separately.
571
+ Effect.sync(() => queued.reject(new Error('Code Mode host call failed')))
572
+ ),
573
+ Effect.onInterrupt(() =>
574
+ // oxlint-disable-next-line effect/no-native-error -- Native Worker RPC rejection settles the sandbox program Promise; typed host failure is tracked separately.
575
+ Effect.sync(() => queued.reject(new Error('Code Mode pass is closing')))
576
+ ),
577
+ )
578
+ }
579
+ })
580
+
581
+ const concurrency = request.limits.maxHostCallConcurrency ?? 4
582
+
583
+ const server = yield* Effect.all(
584
+ Array.from({ length: concurrency }, () => serveHostCalls),
585
+ { concurrency, discard: true },
586
+ ).pipe(Effect.andThen(Effect.never), Effect.forkScoped)
587
+
588
+ const dispatch = (hostCall: unknown): Promise<unknown> => {
589
+ if (!passOpen) {
590
+ // oxlint-disable-next-line effect/no-native-error -- Native Worker RPC rejection settles the sandbox program Promise; typed host failure is tracked separately.
591
+ return Promise.reject(new Error('Code Mode pass is closing'))
592
+ }
593
+ issuedHostCalls += 1
594
+ if (issuedHostCalls > request.limits.maxHostCalls) {
595
+ const error = CodeHostCallLimitError.make({
596
+ implementation: dynamicWorkerImplementation,
597
+ limit: request.limits.maxHostCalls,
598
+ logs: [],
599
+ })
600
+
601
+ failPass(error)
602
+ Queue.offerUnsafe(queue, { _tag: 'limit' })
603
+
604
+ // oxlint-disable-next-line effect/no-native-error -- Native Worker RPC rejection settles the sandbox program Promise; typed host failure is tracked separately.
605
+ return Promise.reject(new Error('host-call limit exceeded'))
606
+ }
607
+ const decoded = decodeHostCall(hostCall)
608
+
609
+ if (Option.isNone(decoded)) {
610
+ // oxlint-disable-next-line effect/no-native-error -- Native sandbox RPC rejects invalid input through its Promise; the Effect host classifies the result.
611
+ return Promise.reject(new TypeError('host calls must match the CodeHostCall schema'))
612
+ }
613
+
614
+ return new Promise((resolve, reject) => {
615
+ const queued = { call: decoded.value, resolve, reject }
616
+
617
+ queuedHostCalls.push(queued)
618
+ Queue.offerUnsafe(queue, { _tag: 'call', queued })
619
+ })
620
+ }
621
+
622
+ const closeAdmission = Effect.sync(() => {
623
+ passOpen = false
624
+ // oxlint-disable-next-line effect/no-native-error -- Native Worker RPC rejection settles the sandbox program Promise; typed host failure is tracked separately.
625
+ rejectQueuedHostCalls(new Error('Code Mode pass is closing'))
626
+ })
627
+
628
+ yield* Effect.addFinalizer(() => closeAdmission.pipe(Effect.andThen(Fiber.interrupt(server))))
629
+
630
+ // No `allowExperimental`: the runtime only accepts it when the CALLING
631
+ // worker carries the `experimental` compatibility flag, which deployed
632
+ // consumers cannot set — the option would reject every pass in
633
+ // production. The harness needs no experimental runtime features.
634
+ const workerCode: WorkerLoaderWorkerCode = {
635
+ compatibilityDate: options.compatibilityDate ?? '2025-05-01',
636
+ mainModule: 'harness.js',
637
+ modules: {
638
+ 'harness.js': HARNESS_MODULE,
639
+ 'program.js': `export default (\n${request.source}\n);`,
640
+ },
641
+ env: {
642
+ CODE_MODE_PASS: encodeHarnessPassConfig({
643
+ namespaces: request.namespaces.map((namespace) => ({
644
+ name: namespace.name,
645
+ methods: namespace.methods,
646
+ })),
647
+ limits: {
648
+ maxLogBytes: request.limits.maxLogBytes,
649
+ maxResultBytes: request.limits.maxResultBytes,
650
+ maxHostCalls: request.limits.maxHostCalls,
651
+ maxHostCallArgumentBytes: request.limits.maxHostCallArgumentBytes,
652
+ },
653
+ }),
654
+ },
655
+ globalOutbound: null,
656
+ ...(request.limits.cpuMillis === undefined
657
+ ? {}
658
+ : {
659
+ limits: {
660
+ cpuMs: request.limits.cpuMillis,
661
+ subRequests: request.limits.maxHostCalls + 8,
662
+ },
663
+ }),
664
+ }
665
+
666
+ const worker = yield* Effect.acquireRelease(
667
+ Effect.try({
668
+ try: () => options.loader.load(workerCode),
669
+ catch: (cause) => {
670
+ const text = safeCauseMessage(cause, 'The Worker Loader failed without a diagnostic')
671
+
672
+ // Blame the program's source ONLY on a genuine compile diagnostic;
673
+ // any other load rejection is an infrastructure start failure, not
674
+ // the model's fault (see classifyWorkerFailure for the same split).
675
+ if (/syntaxerror|failed to (compile|parse)/i.test(text)) {
676
+ return CodeSourceError.make({
677
+ implementation: dynamicWorkerImplementation,
678
+ reason: 'invalid',
679
+ message: text.slice(0, 8_000),
680
+ })
681
+ }
682
+
683
+ return CodeExecutorStartError.make({
684
+ implementation: dynamicWorkerImplementation,
685
+ message: `The Worker Loader rejected the pass: ${text}`.slice(0, 8_000),
686
+ cause,
687
+ })
688
+ },
689
+ }),
690
+ disposeRpcHandle,
691
+ )
692
+
693
+ const entrypoint = yield* Effect.acquireRelease(
694
+ Effect.try({
695
+ try: () => worker.getEntrypoint<CodeModeHarnessEntrypoint>(),
696
+ catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),
697
+ }),
698
+ disposeRpcHandle,
699
+ )
700
+
701
+ const rpc = Effect.tryPromise({
702
+ try: () => entrypoint.run(new CodeModePassHostTarget(dispatch)),
703
+ catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),
704
+ })
705
+
706
+ const exit = yield* Effect.raceFirst(
707
+ rpc.pipe(
708
+ Effect.timeoutOrElse({
709
+ duration: remainingPassWallTime(),
710
+ orElse: () =>
711
+ CodeExecutionTimeoutError.make({
712
+ implementation: dynamicWorkerImplementation,
713
+ kind: 'wall-clock',
714
+ maxWallTime: request.limits.maxWallTime,
715
+ logs: [],
716
+ }),
717
+ }),
718
+ ),
719
+ Fiber.join(server),
720
+ ).pipe(Effect.exit)
721
+
722
+ yield* closeAdmission
723
+ yield* Fiber.interrupt(server)
724
+ if (passFailure !== undefined) {
725
+ return yield* passFailure
726
+ }
727
+ if (Exit.isFailure(exit)) {
728
+ return yield* Effect.failCause(exit.cause)
729
+ }
730
+ const raw = exit.value
731
+ const finishedAt = clock.monotonicTimeNanosUnsafe()
732
+
733
+ const outcome = decodeHarnessOutcome(raw)
734
+
735
+ if (Option.isNone(outcome)) {
736
+ return yield* CodeExecutionProtocolError.make({
737
+ implementation: dynamicWorkerImplementation,
738
+ message: 'The dynamic worker returned a value outside the harness envelope schema',
739
+ })
740
+ }
741
+ switch (outcome.value._tag) {
742
+ case 'completed': {
743
+ return CodeExecutionResult.make({
744
+ implementation: dynamicWorkerImplementation,
745
+ value: outcome.value.value,
746
+ logs: outcome.value.logs,
747
+ resourceUse: CodeExecutionResourceUse.make({
748
+ wallTime: Duration.nanos(finishedAt > startedAt ? finishedAt - startedAt : 0n),
749
+ hostCalls: outcome.value.hostCalls,
750
+ logBytes: outcome.value.logBytes,
751
+ resultBytes: outcome.value.resultBytes,
752
+ }),
753
+ })
754
+ }
755
+ case 'source-not-a-function': {
756
+ return yield* CodeSourceError.make({
757
+ implementation: dynamicWorkerImplementation,
758
+ reason: 'not-a-function',
759
+ message: `The source expression evaluated to ${outcome.value.actual}; it must evaluate to one async function`,
760
+ })
761
+ }
762
+ case 'program-failed': {
763
+ return yield* CodeProgramFailedError.make({
764
+ implementation: dynamicWorkerImplementation,
765
+ reason: outcome.value.reason,
766
+ thrown: outcome.value.thrown,
767
+ message: outcome.value.message.slice(0, 8_000),
768
+ logs: outcome.value.logs,
769
+ })
770
+ }
771
+ case 'log-limit': {
772
+ return yield* CodeOutputLimitError.make({
773
+ implementation: dynamicWorkerImplementation,
774
+ surface: 'logs',
775
+ limit: request.limits.maxLogBytes,
776
+ observed: outcome.value.observed,
777
+ logs: outcome.value.logs,
778
+ })
779
+ }
780
+ case 'argument-limit': {
781
+ return yield* CodeOutputLimitError.make({
782
+ implementation: dynamicWorkerImplementation,
783
+ surface: 'host-call-argument',
784
+ limit: request.limits.maxHostCallArgumentBytes,
785
+ observed: outcome.value.observed,
786
+ logs: outcome.value.logs,
787
+ })
788
+ }
789
+ case 'result-limit': {
790
+ return yield* CodeOutputLimitError.make({
791
+ implementation: dynamicWorkerImplementation,
792
+ surface: 'result',
793
+ limit: request.limits.maxResultBytes,
794
+ observed: outcome.value.observed,
795
+ logs: outcome.value.logs,
796
+ })
797
+ }
798
+ case 'host-call-limit': {
799
+ return yield* CodeHostCallLimitError.make({
800
+ implementation: dynamicWorkerImplementation,
801
+ limit: request.limits.maxHostCalls,
802
+ logs: outcome.value.logs,
803
+ })
804
+ }
805
+ case 'protocol': {
806
+ return yield* CodeExecutionProtocolError.make({
807
+ implementation: dynamicWorkerImplementation,
808
+ message: outcome.value.message.slice(0, 8_000),
809
+ })
810
+ }
811
+ }
812
+ })
813
+
814
+ /**
815
+ * Expected worker-level failures map into the typed union with bounded
816
+ * diagnostics; anything unrecognized stays a start/termination error rather
817
+ * than a fabricated program result.
818
+ */
819
+ const classifyWorkerFailure = (
820
+ cause: unknown,
821
+ maxWallTime: Duration.Duration,
822
+ ):
823
+ | CodeExecutionTimeoutError
824
+ | CodeExecutorTerminatedError
825
+ | CodeExecutorStartError
826
+ | CodeSourceError =>
827
+ {
828
+ const text = safeCauseDiagnostic(cause, '[unserializable worker failure]')
829
+
830
+ // `WorkerLoader.load()` is lazy, so a module-compile error in the generated
831
+ // program surfaces here at first use. Blame the program's source ONLY on a
832
+ // genuine compile diagnostic (a `SyntaxError` or an explicit compile
833
+ // failure) — the fixed harness is valid, so the fault is in program.js. A
834
+ // bare "failed to start Worker" without a compile diagnostic is an
835
+ // infrastructure start failure, not the model's fault, so it must NOT be
836
+ // misclassified as a source error.
837
+ if (/syntaxerror|failed to (compile|parse)/i.test(text)) {
838
+ return CodeSourceError.make({
839
+ implementation: dynamicWorkerImplementation,
840
+ reason: 'invalid',
841
+ message: text.slice(0, 8_000),
842
+ })
843
+ }
844
+ if (/cpu/i.test(text)) {
845
+ return CodeExecutionTimeoutError.make({
846
+ implementation: dynamicWorkerImplementation,
847
+ kind: 'cpu',
848
+ maxWallTime,
849
+ logs: [],
850
+ })
851
+ }
852
+ if (/failed to start worker/i.test(text)) {
853
+ return CodeExecutorStartError.make({
854
+ implementation: dynamicWorkerImplementation,
855
+ message: text.slice(0, 8_000),
856
+ cause,
857
+ })
858
+ }
859
+
860
+ return CodeExecutorTerminatedError.make({
861
+ implementation: dynamicWorkerImplementation,
862
+ message: text.slice(0, 8_000),
863
+ })
864
+ }
865
+
866
+ /** Layer building the Dynamic Worker `CodeExecutor` from resolved bindings. */
867
+ export const dynamicWorkerCodeExecutorLayer = (
868
+ options: DynamicWorkerCodeExecutorOptions,
869
+ ): Layer.Layer<CodeExecutor> =>
870
+ Layer.effect(
871
+ CodeExecutor,
872
+ Effect.gen(function*() {
873
+ const clock = yield* Clock.Clock
874
+
875
+ return CodeExecutor.of({ execute: makeExecute(options, clock) })
876
+ }),
877
+ )
878
+
879
+ /** Assemble Code Mode handlers with the isolated Dynamic Worker executor. */
880
+ export const CloudflareCodeMode = {
881
+ /**
882
+ * Provide the selected tool handlers at construction, where Code Mode captures them.
883
+ * Their errors and remaining dependencies stay visible. The definition still owns the
884
+ * allowlist and limits; the runtime supplies the live Tool broker for each scoped pass.
885
+ */
886
+ layer: <A, E, R, Handlers, HandlerError, HandlerRequirements>(
887
+ definition: { readonly handlers: Layer.Layer<A, E, R> },
888
+ options: DynamicWorkerCodeExecutorOptions & {
889
+ readonly handlers: Layer.Layer<Handlers, HandlerError, HandlerRequirements>
890
+ },
891
+ ) =>
892
+ definition.handlers.pipe(
893
+ Layer.provide(options.handlers),
894
+ Layer.provide(dynamicWorkerCodeExecutorLayer(options)),
895
+ ),
896
+ }