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