@effect-agent/platform-cloudflare 0.1.0-beta.49 → 0.1.0-beta.50

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.
@@ -201,7 +201,6 @@ const HarnessCompleted = Schema.TaggedStruct("completed", {
201
201
  logBytes: Schema.Natural,
202
202
  resultBytes: Schema.Natural
203
203
  });
204
- const HarnessSourceInvalid = Schema.TaggedStruct("source-invalid", { message: Schema.String });
205
204
  const HarnessNotAFunction = Schema.TaggedStruct("source-not-a-function", { actual: Schema.String });
206
205
  const HarnessProgramFailed = Schema.TaggedStruct("program-failed", {
207
206
  reason: Schema.Literals([
@@ -229,7 +228,6 @@ const HarnessHostCallLimit = Schema.TaggedStruct("host-call-limit", { logs: Boun
229
228
  const HarnessProtocol = Schema.TaggedStruct("protocol", { message: Schema.String });
230
229
  const HarnessOutcome = Schema.Union([
231
230
  HarnessCompleted,
232
- HarnessSourceInvalid,
233
231
  HarnessNotAFunction,
234
232
  HarnessProgramFailed,
235
233
  HarnessLogLimit,
@@ -522,11 +520,6 @@ const makeExecute = (options, clock) => Effect.fn("DynamicWorkerCodeExecutor.exe
522
520
  resultBytes: outcome.value.resultBytes
523
521
  })
524
522
  });
525
- case "source-invalid": return yield* CodeSourceError.make({
526
- implementation: dynamicWorkerImplementation,
527
- reason: "invalid",
528
- message: outcome.value.message.slice(0, 8e3)
529
- });
530
523
  case "source-not-a-function": return yield* CodeSourceError.make({
531
524
  implementation: dynamicWorkerImplementation,
532
525
  reason: "not-a-function",
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareCodeMode.mjs","names":["#dispatch"],"sources":["../src/CloudflareCodeMode.ts"],"sourcesContent":["import {\n CodeExecutionHost,\n CodeExecutionResourceUse,\n CodeExecutionResult,\n CodeExecutionTimeoutError,\n CodeExecutor,\n CodeExecutorStartError,\n CodeExecutorTerminatedError,\n CodeExecutorUnsupportedError,\n CodeExecutionProtocolError,\n CodeHostCall,\n CodeHostCallLimitError,\n CodeHostCallResult,\n CodeOutputLimitError,\n CodeProgramFailedError,\n CodeSourceError,\n type CodeExecutorExecute,\n type CodeExecutionRequest,\n} from \"@effect-agent/sandbox/CodeExecutor\";\nimport { SandboxImplementation } from \"@effect-agent/sandbox/Sandbox\";\nimport { RpcTarget } from \"cloudflare:workers\";\nimport { Clock, Duration, Effect, Exit, Fiber, Layer, Option, Queue, Schema } from \"effect\";\n\nimport { safeCauseDiagnostic, safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017;\n * DEPLOY-011). Each pass loads one fresh Worker through the Worker Loader\n * with `globalOutbound: null`, so generated code has no ambient network,\n * bindings, or secrets; its only authority is the pass-scoped RPC target that\n * routes back into the owning event's `CodeExecutionHost` service. Platform\n * CPU limits stop synchronous runaway programs; the executor-owned wall-clock\n * deadline interrupts asynchronously suspended passes. Deployment class `E`\n * only: the adapter records no persistent state and a later pass may run in a\n * completely different isolate.\n */\nexport const dynamicWorkerImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-dynamic-worker\",\n});\n\ninterface CodeModePassHost extends Rpc.RpcTargetBranded {\n readonly call: (hostCall: unknown) => Promise<unknown>;\n}\n\ninterface CodeModeHarnessEntrypoint extends Rpc.WorkerEntrypointBranded {\n readonly run: (host: CodeModePassHost) => Promise<unknown>;\n}\n\n/**\n * One object-capability endpoint for one execution pass. Workers RPC invokes\n * the target in the request context where it was created, so the native\n * Promise returned by `dispatch` and the Effect fiber that settles it share\n * one I/O owner. Passing the target as `run()`'s argument also scopes the\n * remote stub to that RPC call; no request state lives at module scope.\n */\nclass CodeModePassHostTarget extends RpcTarget implements CodeModePassHost {\n readonly #dispatch: (hostCall: unknown) => Promise<unknown>;\n\n constructor(dispatch: (hostCall: unknown) => Promise<unknown>) {\n super();\n this.#dispatch = dispatch;\n }\n\n call(hostCall: unknown): Promise<unknown> {\n return this.#dispatch(hostCall);\n }\n}\n\n/**\n * The fixed harness loaded as the dynamic worker's main module. The generated\n * source becomes `program.mjs` (`export default (<expression>);`) — a module,\n * never `eval`. The harness installs namespace globals and a bounded console,\n * imports the program, invokes it exactly once, and returns one envelope the\n * host validates through Effect Schema.\n */\nconst HARNESS_MODULE = String.raw`\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport programDefault from \"./program.js\";\n\nconst encoder = new TextEncoder();\nconst utf8 = (text) => encoder.encode(text).byteLength;\nconst safeText = (value) => {\n try {\n if (value instanceof Error) return (value.name + \": \" + value.message).slice(0, 4000);\n if (typeof value === \"string\") return value.slice(0, 4000);\n const encoded = JSON.stringify(value);\n return (encoded === undefined ? String(value) : encoded).slice(0, 4000);\n } catch {\n return \"[unserializable value]\";\n }\n};\nconst safeJson = (value) => {\n try {\n const encoded = JSON.stringify(value);\n if (encoded !== undefined && encoded.length <= 4000) return JSON.parse(encoded);\n } catch {}\n return safeText(value);\n};\n\nexport default class CodeModeHarness extends WorkerEntrypoint {\n async run(host) {\n const config = this.env.CODE_MODE_PASS;\n const limits = config.limits;\n const logs = [];\n let logBytes = 0;\n let fatal;\n const boundedLogs = () => logs.slice(0, 4096);\n const write = (...values) => {\n const joined = values.map(safeText).join(\" \");\n const line = joined.length > 16000 ? joined.slice(0, 15999) + \"…\" : joined;\n const bytes = utf8(line);\n if (logs.length >= 4096 || logBytes + bytes > limits.maxLogBytes) {\n fatal = fatal ?? { _tag: \"log-limit\", observed: logBytes + bytes, logs: boundedLogs() };\n throw new Error(\"code-mode log limit exceeded\");\n }\n logs.push(line);\n logBytes += bytes;\n };\n globalThis.console = { log: write, info: write, warn: write, error: write, debug: write };\n\n let hostCalls = 0;\n const makeMethod = (namespace, method) => async (argument) => {\n hostCalls += 1;\n if (hostCalls > limits.maxHostCalls) {\n fatal = fatal ?? { _tag: \"host-call-limit\", logs: boundedLogs() };\n throw new Error(\"code-mode host-call limit exceeded\");\n }\n let argText;\n try {\n argText = JSON.stringify(argument);\n } catch {}\n if (argText === undefined || utf8(argText) > limits.maxHostCallArgumentBytes) {\n fatal = fatal ?? {\n _tag: \"argument-limit\",\n observed: argText === undefined ? 0 : utf8(argText),\n logs: boundedLogs(),\n };\n throw new Error(\"code-mode host-call argument limit exceeded\");\n }\n const outcome = await host.call({\n namespace,\n method,\n argument: JSON.parse(argText),\n });\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallSuccess\") {\n return outcome.value;\n }\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallFailure\") {\n throw outcome.error;\n }\n fatal = fatal ?? { _tag: \"protocol\", message: \"host returned an unrecognized outcome\" };\n throw new Error(\"code-mode host protocol violation\");\n };\n for (const namespace of config.namespaces) {\n const methods = {};\n for (const method of namespace.methods) {\n methods[method] = makeMethod(namespace.name, method);\n }\n globalThis[namespace.name] = methods;\n }\n\n // program.js is imported statically at the top of this module, so a\n // syntactically invalid program fails the whole harness at load (mapped\n // to a source error by the host). Using a static import keeps this module\n // free of dynamic-import expressions, which single-script Miniflare hosts\n // reject. The isolation boundary does NOT depend on the ordering of this\n // import versus the console/namespace shims installed below: the loaded\n // Worker has globalOutbound: null and no bindings, secrets, or env from\n // the Worker Loader config BEFORE any module in the graph evaluates, so\n // module-level program code has no ambient authority regardless. The\n // shims below are usability wrappers (bounded console, namespace globals),\n // and the accepted program is a single async-function expression whose\n // body runs only when invoked here — after the shims exist.\n const program = programDefault;\n if (typeof program !== \"function\") {\n return { _tag: \"source-not-a-function\", actual: typeof program };\n }\n try {\n const value = await program();\n if (fatal !== undefined) return fatal;\n let text;\n try {\n text = JSON.stringify(value);\n } catch {}\n if (text === undefined) {\n return {\n _tag: \"program-failed\",\n reason: \"non-json-result\",\n thrown: null,\n message: \"The program must return a JSON value\",\n logs: boundedLogs(),\n };\n }\n const resultBytes = utf8(text);\n if (resultBytes > limits.maxResultBytes) {\n return { _tag: \"result-limit\", observed: resultBytes, logs: boundedLogs() };\n }\n return {\n _tag: \"completed\",\n value: JSON.parse(text),\n logs: boundedLogs(),\n hostCalls,\n logBytes,\n resultBytes,\n };\n } catch (cause) {\n if (fatal !== undefined) return fatal;\n return {\n _tag: \"program-failed\",\n reason: cause instanceof Error ? \"threw\" : \"rejected\",\n thrown: safeJson(cause),\n message: safeText(cause),\n logs: boundedLogs(),\n };\n }\n }\n}\n`;\n\nconst BoundedLogs = Schema.Array(Schema.String.check(Schema.isMaxLength(16 * 1024))).check(\n Schema.isMaxLength(4_096),\n);\n\nconst HarnessCompleted = Schema.TaggedStruct(\"completed\", {\n value: Schema.Json,\n logs: BoundedLogs,\n hostCalls: Schema.Natural,\n logBytes: Schema.Natural,\n resultBytes: Schema.Natural,\n});\n\nconst HarnessSourceInvalid = Schema.TaggedStruct(\"source-invalid\", {\n message: Schema.String,\n});\n\nconst HarnessNotAFunction = Schema.TaggedStruct(\"source-not-a-function\", {\n actual: Schema.String,\n});\n\nconst HarnessProgramFailed = Schema.TaggedStruct(\"program-failed\", {\n reason: Schema.Literals([\"threw\", \"rejected\", \"non-json-result\"]),\n thrown: Schema.Json,\n message: Schema.String,\n logs: BoundedLogs,\n});\n\nconst HarnessLogLimit = Schema.TaggedStruct(\"log-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessArgumentLimit = Schema.TaggedStruct(\"argument-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessResultLimit = Schema.TaggedStruct(\"result-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessHostCallLimit = Schema.TaggedStruct(\"host-call-limit\", {\n logs: BoundedLogs,\n});\n\nconst HarnessProtocol = Schema.TaggedStruct(\"protocol\", {\n message: Schema.String,\n});\n\nconst HarnessOutcome = Schema.Union([\n HarnessCompleted,\n HarnessSourceInvalid,\n HarnessNotAFunction,\n HarnessProgramFailed,\n HarnessLogLimit,\n HarnessArgumentLimit,\n HarnessResultLimit,\n HarnessHostCallLimit,\n HarnessProtocol,\n]);\n\nconst HarnessPassConfig = Schema.Struct({\n namespaces: Schema.Array(\n Schema.Struct({\n name: Schema.NonEmptyString,\n methods: Schema.Array(Schema.NonEmptyString).check(Schema.isMaxLength(64)),\n }),\n ).check(Schema.isMaxLength(32)),\n limits: Schema.Struct({\n maxLogBytes: Schema.Natural,\n maxResultBytes: Schema.Natural,\n maxHostCalls: Schema.Natural,\n maxHostCallArgumentBytes: Schema.Natural,\n }),\n});\n\nconst encodeHarnessPassConfig = Schema.encodeSync(HarnessPassConfig);\nconst encodeJsonPayload = Schema.encodeSync(Schema.fromJsonString(Schema.Json));\nconst decodeJsonPayload = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));\n\nconst decodeHarnessOutcome = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(HarnessOutcome)(value);\n } catch {\n return Option.none<typeof HarnessOutcome.Type>();\n }\n};\n\nconst decodeHostCall = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCall)(value);\n } catch {\n return Option.none<CodeHostCall>();\n }\n};\n\nconst decodeHostCallResult = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCallResult)(value);\n } catch {\n return Option.none<CodeHostCallResult>();\n }\n};\n\n/** Dispose a Cloudflare RPC handle when the runtime supplies its untyped disposal hook. @internal */\nexport const disposeRpcHandle = (handle: unknown): Effect.Effect<void> =>\n Effect.try({\n try: () => {\n if ((typeof handle !== \"object\" && typeof handle !== \"function\") || handle === null) return;\n if (!(Symbol.dispose in handle)) return;\n const dispose = Reflect.get(handle, Symbol.dispose);\n\n if (typeof dispose === \"function\") {\n Reflect.apply(dispose, handle, []);\n }\n },\n catch: (cause) =>\n safeCauseDiagnostic(cause, \"The Cloudflare RPC disposal hook failed without a diagnostic\"),\n }).pipe(\n Effect.catch((diagnostic) =>\n Effect.logWarning(`Cloudflare RPC handle disposal failed: ${diagnostic}`).pipe(\n Effect.ignoreCause,\n ),\n ),\n );\n\n/**\n * Project a host outcome to the plain JSON envelope the harness reads. A\n * `CodeExecutionHost` may return either real `CodeHostCallResult` instances\n * (the substitute and conformance kit) or plain-object equivalents (the Code\n * Mode capability's broker route), so this reads the shared fields rather than\n * `Schema.encodeSync`, which would reject a plain object.\n */\ninterface EncodedHostResultPayload {\n readonly encodedPayload: string;\n readonly resultBytes: number;\n}\n\nconst encodeHostResultPayload = (\n outcome: CodeHostCallResult,\n): EncodedHostResultPayload | undefined => {\n try {\n const payload = outcome._tag === \"CodeHostCallSuccess\" ? outcome.value : outcome.error;\n const encodedPayload = encodeJsonPayload(payload);\n\n return {\n encodedPayload,\n resultBytes: utf8ByteLength(encodedPayload),\n };\n } catch {\n return undefined;\n }\n};\n\nconst utf8ByteLength = (value: string): number => {\n let total = 0;\n\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n\n total += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;\n }\n\n return total;\n};\n\ninterface QueuedHostCall {\n readonly call: CodeHostCall;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\ntype HostWork =\n | { readonly _tag: \"call\"; readonly queued: QueuedHostCall }\n | { readonly _tag: \"limit\" };\n\ntype HostDispatchError =\n | CodeExecutionTimeoutError\n | CodeOutputLimitError\n | CodeExecutionProtocolError\n | CodeHostCallLimitError;\n\n/** Reserved global names the harness owns inside the dynamic worker. */\nconst reservedHarnessGlobals = new Set([\"console\"]);\n\nexport interface DynamicWorkerCodeExecutorOptions {\n /** The `worker_loader` binding. */\n readonly loader: WorkerLoader;\n /** Compatibility date for dynamic workers; defaults to `2025-05-01`. */\n readonly compatibilityDate?: string | undefined;\n}\n\nconst makeExecute = (\n options: DynamicWorkerCodeExecutorOptions,\n clock: Clock.Clock,\n): CodeExecutorExecute =>\n Effect.fn(\"DynamicWorkerCodeExecutor.execute\")(function* (request: CodeExecutionRequest) {\n if (request.network._tag !== \"NetworkDisabled\") {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"network\",\n message:\n \"The Dynamic Worker executor denies all egress with globalOutbound: null; an allowlist is not supported in the first slice\",\n });\n }\n const sourceBytes = utf8ByteLength(request.source);\n\n if (sourceBytes > request.limits.maxSourceBytes) {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"oversized\",\n message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,\n });\n }\n for (const namespace of request.namespaces) {\n if (reservedHarnessGlobals.has(namespace.name)) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"namespaces\",\n message: `Namespace ${namespace.name} collides with a harness binding`,\n });\n }\n }\n const host = yield* CodeExecutionHost;\n\n // This synchronous clock access is confined to callbacks that must compute a timeout\n // immediately. The Clock service remains the authority, so tests and hosts can replace it.\n const startedAt = clock.monotonicTimeNanosUnsafe();\n const passDeadline = startedAt + Duration.toNanosUnsafe(request.limits.maxWallTime);\n\n const remainingPassWallTime = (): Duration.Duration => {\n const now = clock.monotonicTimeNanosUnsafe();\n\n return Duration.nanos(passDeadline > now ? passDeadline - now : 0n);\n };\n\n let issuedHostCalls = 0;\n let passOpen = true;\n const queuedHostCalls: Array<QueuedHostCall> = [];\n let passFailure: HostDispatchError | undefined;\n\n const failPass = (error: HostDispatchError): void => {\n if (passFailure === undefined) passFailure = error;\n };\n\n const rejectQueuedHostCalls = (reason: Error): void => {\n for (const queued of queuedHostCalls.splice(0)) {\n queued.reject(reason);\n }\n };\n\n const queue = yield* Queue.unbounded<HostWork>();\n\n const deliverHostOutcome = (\n queued: QueuedHostCall,\n outcome: CodeHostCallResult,\n ): Effect.Effect<void, CodeExecutionProtocolError | CodeOutputLimitError> =>\n Effect.gen(function* () {\n const decoded = decodeHostCallResult(outcome);\n\n if (Option.isNone(decoded)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a value outside the CodeHostCallResult schema\",\n });\n\n failPass(error);\n\n return yield* error;\n }\n const encoded = encodeHostResultPayload(decoded.value);\n\n if (encoded === undefined || encoded.resultBytes > request.limits.maxHostCallResultBytes) {\n const error = CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-result\",\n limit: request.limits.maxHostCallResultBytes,\n observed: encoded?.resultBytes ?? 0,\n logs: [],\n });\n\n failPass(error);\n\n return yield* error;\n }\n const normalizedPayload = decodeJsonPayload(encoded.encodedPayload);\n\n if (Option.isNone(normalizedPayload)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a result that could not cross the JSON boundary\",\n });\n\n failPass(error);\n\n return yield* error;\n }\n queued.resolve(\n decoded.value._tag === \"CodeHostCallSuccess\"\n ? { _tag: \"CodeHostCallSuccess\", value: normalizedPayload.value }\n : { _tag: \"CodeHostCallFailure\", error: normalizedPayload.value },\n );\n });\n\n // Workers RPC into the loader isolate cannot settle on the fiber blocked\n // in `entrypoint.run()`. A Scope-owned sibling fiber keeps that\n // independence while inheriting the pass Context and dying with the Scope.\n const serveHostCalls = Effect.gen(function* () {\n while (true) {\n const work = yield* Queue.take(queue);\n\n if (work._tag === \"limit\") {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n\n failPass(error);\n\n return yield* error;\n }\n const queued = work.queued;\n\n yield* host.call(queued.call).pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () => {\n const error = CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n });\n\n failPass(error);\n\n return error;\n },\n }),\n Effect.flatMap((outcome) => deliverHostOutcome(queued, outcome)),\n Effect.tapError(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode host call failed\"))),\n ),\n Effect.onInterrupt(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode pass is closing\"))),\n ),\n );\n }\n });\n\n const server = yield* serveHostCalls.pipe(Effect.forkScoped);\n\n const dispatch = (hostCall: unknown): Promise<unknown> => {\n if (!passOpen) {\n return Promise.reject(new Error(\"Code Mode pass is closing\"));\n }\n issuedHostCalls += 1;\n if (issuedHostCalls > request.limits.maxHostCalls) {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n\n failPass(error);\n Queue.offerUnsafe(queue, { _tag: \"limit\" });\n\n return Promise.reject(new Error(\"host-call limit exceeded\"));\n }\n const decoded = decodeHostCall(hostCall);\n\n if (Option.isNone(decoded)) {\n return Promise.reject(new TypeError(\"host calls must match the CodeHostCall schema\"));\n }\n\n return new Promise((resolve, reject) => {\n const queued = { call: decoded.value, resolve, reject };\n\n queuedHostCalls.push(queued);\n Queue.offerUnsafe(queue, { _tag: \"call\", queued });\n });\n };\n\n const closeAdmission = Effect.sync(() => {\n passOpen = false;\n rejectQueuedHostCalls(new Error(\"Code Mode pass is closing\"));\n });\n\n yield* Effect.addFinalizer(() => closeAdmission.pipe(Effect.andThen(Fiber.interrupt(server))));\n\n // No `allowExperimental`: the runtime only accepts it when the CALLING\n // worker carries the `experimental` compatibility flag, which deployed\n // consumers cannot set — the option would reject every pass in\n // production. The harness needs no experimental runtime features.\n const workerCode: WorkerLoaderWorkerCode = {\n compatibilityDate: options.compatibilityDate ?? \"2025-05-01\",\n mainModule: \"harness.js\",\n modules: {\n \"harness.js\": HARNESS_MODULE,\n \"program.js\": `export default (\\n${request.source}\\n);`,\n },\n env: {\n CODE_MODE_PASS: encodeHarnessPassConfig({\n namespaces: request.namespaces.map((namespace) => ({\n name: namespace.name,\n methods: namespace.methods,\n })),\n limits: {\n maxLogBytes: request.limits.maxLogBytes,\n maxResultBytes: request.limits.maxResultBytes,\n maxHostCalls: request.limits.maxHostCalls,\n maxHostCallArgumentBytes: request.limits.maxHostCallArgumentBytes,\n },\n }),\n },\n globalOutbound: null,\n ...(request.limits.cpuMillis === undefined\n ? {}\n : {\n limits: {\n cpuMs: request.limits.cpuMillis,\n subRequests: request.limits.maxHostCalls + 8,\n },\n }),\n };\n\n const worker = yield* Effect.acquireRelease(\n Effect.try({\n try: () => options.loader.load(workerCode),\n catch: (cause) => {\n const text = safeCauseMessage(cause, \"The Worker Loader failed without a diagnostic\");\n\n // Blame the program's source ONLY on a genuine compile diagnostic;\n // any other load rejection is an infrastructure start failure, not\n // the model's fault (see classifyWorkerFailure for the same split).\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: `The Worker Loader rejected the pass: ${text}`.slice(0, 8_000),\n cause,\n });\n },\n }),\n disposeRpcHandle,\n );\n\n const entrypoint = yield* Effect.acquireRelease(\n Effect.try({\n try: () => worker.getEntrypoint<CodeModeHarnessEntrypoint>(),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n }),\n disposeRpcHandle,\n );\n\n const rpc = Effect.tryPromise({\n try: () => entrypoint.run(new CodeModePassHostTarget(dispatch)),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n });\n\n const exit = yield* Effect.raceFirst(\n rpc.pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () =>\n CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n }),\n }),\n ),\n Fiber.join(server),\n ).pipe(Effect.exit);\n\n yield* closeAdmission;\n yield* Fiber.interrupt(server);\n if (passFailure !== undefined) {\n return yield* passFailure;\n }\n if (Exit.isFailure(exit)) {\n return yield* Effect.failCause(exit.cause);\n }\n const raw = exit.value;\n const finishedAt = clock.monotonicTimeNanosUnsafe();\n\n const outcome = decodeHarnessOutcome(raw);\n\n if (Option.isNone(outcome)) {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The dynamic worker returned a value outside the harness envelope schema\",\n });\n }\n switch (outcome.value._tag) {\n case \"completed\": {\n return CodeExecutionResult.make({\n implementation: dynamicWorkerImplementation,\n value: outcome.value.value,\n logs: outcome.value.logs,\n resourceUse: CodeExecutionResourceUse.make({\n wallTime: Duration.nanos(finishedAt > startedAt ? finishedAt - startedAt : 0n),\n hostCalls: outcome.value.hostCalls,\n logBytes: outcome.value.logBytes,\n resultBytes: outcome.value.resultBytes,\n }),\n });\n }\n case \"source-invalid\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n case \"source-not-a-function\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"not-a-function\",\n message: `The source expression evaluated to ${outcome.value.actual}; it must evaluate to one async function`,\n });\n }\n case \"program-failed\": {\n return yield* CodeProgramFailedError.make({\n implementation: dynamicWorkerImplementation,\n reason: outcome.value.reason,\n thrown: outcome.value.thrown,\n message: outcome.value.message.slice(0, 8_000),\n logs: outcome.value.logs,\n });\n }\n case \"log-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"logs\",\n limit: request.limits.maxLogBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"argument-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-argument\",\n limit: request.limits.maxHostCallArgumentBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"result-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"result\",\n limit: request.limits.maxResultBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"host-call-limit\": {\n return yield* CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: outcome.value.logs,\n });\n }\n case \"protocol\": {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n }\n });\n\n/**\n * Expected worker-level failures map into the typed union with bounded\n * diagnostics; anything unrecognized stays a start/termination error rather\n * than a fabricated program result.\n */\nconst classifyWorkerFailure = (\n cause: unknown,\n maxWallTime: Duration.Duration,\n):\n | CodeExecutionTimeoutError\n | CodeExecutorTerminatedError\n | CodeExecutorStartError\n | CodeSourceError => {\n const text = safeCauseDiagnostic(cause, \"[unserializable worker failure]\");\n\n // `WorkerLoader.load()` is lazy, so a module-compile error in the generated\n // program surfaces here at first use. Blame the program's source ONLY on a\n // genuine compile diagnostic (a `SyntaxError` or an explicit compile\n // failure) — the fixed harness is valid, so the fault is in program.js. A\n // bare \"failed to start Worker\" without a compile diagnostic is an\n // infrastructure start failure, not the model's fault, so it must NOT be\n // misclassified as a source error.\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n if (/cpu/i.test(text)) {\n return CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"cpu\",\n maxWallTime,\n logs: [],\n });\n }\n if (/failed to start worker/i.test(text)) {\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n cause,\n });\n }\n\n return CodeExecutorTerminatedError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n });\n};\n\n/** Layer building the Dynamic Worker `CodeExecutor` from resolved bindings. */\nexport const dynamicWorkerCodeExecutorLayer = (\n options: DynamicWorkerCodeExecutorOptions,\n): Layer.Layer<CodeExecutor> =>\n Layer.effect(\n CodeExecutor,\n Effect.gen(function* () {\n const clock = yield* Clock.Clock;\n\n return CodeExecutor.of({ execute: makeExecute(options, clock) });\n }),\n );\n\n/** Assemble Code Mode handlers with the isolated Dynamic Worker executor. */\nexport const CloudflareCodeMode = {\n /**\n * Provide the selected tool handlers at construction, where Code Mode captures them.\n * Their errors and remaining dependencies stay visible. The definition still owns the\n * allowlist and limits; the runtime supplies the live Tool broker for each scoped pass.\n */\n layer: <A, E, R, Handlers, HandlerError, HandlerRequirements>(\n definition: { readonly handlers: Layer.Layer<A, E, R> },\n options: DynamicWorkerCodeExecutorOptions & {\n readonly handlers: Layer.Layer<Handlers, HandlerError, HandlerRequirements>;\n },\n ) =>\n definition.handlers.pipe(\n Layer.provide(options.handlers),\n Layer.provide(dynamicWorkerCodeExecutorLayer(options)),\n ),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,8BAA8B,sBAAsB,KAAK;CACpE,WAAW;CACX,UAAU;AACZ,CAAC;;;;;;;;AAiBD,IAAM,yBAAN,cAAqC,UAAsC;CACzE;CAEA,YAAY,UAAmD;EAC7D,MAAM;EACN,KAAKA,YAAY;CACnB;CAEA,KAAK,UAAqC;EACxC,OAAO,KAAKA,UAAU,QAAQ;CAChC;AACF;;;;;;;;AASA,MAAM,iBAAiB,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJjC,MAAM,cAAc,OAAO,MAAM,OAAO,OAAO,MAAM,OAAO,YAAY,KAAS,CAAC,CAAC,CAAC,CAAC,MACnF,OAAO,YAAY,IAAK,CAC1B;AAEA,MAAM,mBAAmB,OAAO,aAAa,aAAa;CACxD,OAAO,OAAO;CACd,MAAM;CACN,WAAW,OAAO;CAClB,UAAU,OAAO;CACjB,aAAa,OAAO;AACtB,CAAC;AAED,MAAM,uBAAuB,OAAO,aAAa,kBAAkB,E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,CAAC;CACT,CAAC;CAEH,IAAI,0BAA0B,KAAK,IAAI,GACrC,OAAO,uBAAuB,KAAK;EACjC,gBAAgB;EAChB,SAAS,KAAK,MAAM,GAAG,GAAK;EAC5B;CACF,CAAC;CAGH,OAAO,4BAA4B,KAAK;EACtC,gBAAgB;EAChB,SAAS,KAAK,MAAM,GAAG,GAAK;CAC9B,CAAC;AACH;;AAGA,MAAa,kCACX,YAEA,MAAM,OACJ,cACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,MAAM;CAE3B,OAAO,aAAa,GAAG,EAAE,SAAS,YAAY,SAAS,KAAK,EAAE,CAAC;AACjE,CAAC,CACH;;AAGF,MAAa,qBAAqB;;;;;;AAMhC,QACE,YACA,YAIA,WAAW,SAAS,KAClB,MAAM,QAAQ,QAAQ,QAAQ,GAC9B,MAAM,QAAQ,+BAA+B,OAAO,CAAC,CACvD,EACJ"}
1
+ {"version":3,"file":"CloudflareCodeMode.mjs","names":["#dispatch"],"sources":["../src/CloudflareCodeMode.ts"],"sourcesContent":["import {\n CodeExecutionHost,\n CodeExecutionResourceUse,\n CodeExecutionResult,\n CodeExecutionTimeoutError,\n CodeExecutor,\n CodeExecutorStartError,\n CodeExecutorTerminatedError,\n CodeExecutorUnsupportedError,\n CodeExecutionProtocolError,\n CodeHostCall,\n CodeHostCallLimitError,\n CodeHostCallResult,\n CodeOutputLimitError,\n CodeProgramFailedError,\n CodeSourceError,\n type CodeExecutorExecute,\n type CodeExecutionRequest,\n} from \"@effect-agent/sandbox/CodeExecutor\";\nimport { SandboxImplementation } from \"@effect-agent/sandbox/Sandbox\";\nimport { RpcTarget } from \"cloudflare:workers\";\nimport { Clock, Duration, Effect, Exit, Fiber, Layer, Option, Queue, Schema } from \"effect\";\n\nimport { safeCauseDiagnostic, safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017;\n * DEPLOY-011). Each pass loads one fresh Worker through the Worker Loader\n * with `globalOutbound: null`, so generated code has no ambient network,\n * bindings, or secrets; its only authority is the pass-scoped RPC target that\n * routes back into the owning event's `CodeExecutionHost` service. Platform\n * CPU limits stop synchronous runaway programs; the executor-owned wall-clock\n * deadline interrupts asynchronously suspended passes. Deployment class `E`\n * only: the adapter records no persistent state and a later pass may run in a\n * completely different isolate.\n */\nexport const dynamicWorkerImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-dynamic-worker\",\n});\n\ninterface CodeModePassHost extends Rpc.RpcTargetBranded {\n readonly call: (hostCall: unknown) => Promise<unknown>;\n}\n\ninterface CodeModeHarnessEntrypoint extends Rpc.WorkerEntrypointBranded {\n readonly run: (host: CodeModePassHost) => Promise<unknown>;\n}\n\n/**\n * One object-capability endpoint for one execution pass. Workers RPC invokes\n * the target in the request context where it was created, so the native\n * Promise returned by `dispatch` and the Effect fiber that settles it share\n * one I/O owner. Passing the target as `run()`'s argument also scopes the\n * remote stub to that RPC call; no request state lives at module scope.\n */\nclass CodeModePassHostTarget extends RpcTarget implements CodeModePassHost {\n readonly #dispatch: (hostCall: unknown) => Promise<unknown>;\n\n constructor(dispatch: (hostCall: unknown) => Promise<unknown>) {\n super();\n this.#dispatch = dispatch;\n }\n\n call(hostCall: unknown): Promise<unknown> {\n return this.#dispatch(hostCall);\n }\n}\n\n/**\n * The fixed harness loaded as the dynamic worker's main module. The generated\n * source becomes `program.mjs` (`export default (<expression>);`) — a module,\n * never `eval`. The harness installs namespace globals and a bounded console,\n * imports the program, invokes it exactly once, and returns one envelope the\n * host validates through Effect Schema.\n */\nconst HARNESS_MODULE = String.raw`\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport programDefault from \"./program.js\";\n\nconst encoder = new TextEncoder();\nconst utf8 = (text) => encoder.encode(text).byteLength;\nconst safeText = (value) => {\n try {\n if (value instanceof Error) return (value.name + \": \" + value.message).slice(0, 4000);\n if (typeof value === \"string\") return value.slice(0, 4000);\n const encoded = JSON.stringify(value);\n return (encoded === undefined ? String(value) : encoded).slice(0, 4000);\n } catch {\n return \"[unserializable value]\";\n }\n};\nconst safeJson = (value) => {\n try {\n const encoded = JSON.stringify(value);\n if (encoded !== undefined && encoded.length <= 4000) return JSON.parse(encoded);\n } catch {}\n return safeText(value);\n};\n\nexport default class CodeModeHarness extends WorkerEntrypoint {\n async run(host) {\n const config = this.env.CODE_MODE_PASS;\n const limits = config.limits;\n const logs = [];\n let logBytes = 0;\n let fatal;\n const boundedLogs = () => logs.slice(0, 4096);\n const write = (...values) => {\n const joined = values.map(safeText).join(\" \");\n const line = joined.length > 16000 ? joined.slice(0, 15999) + \"…\" : joined;\n const bytes = utf8(line);\n if (logs.length >= 4096 || logBytes + bytes > limits.maxLogBytes) {\n fatal = fatal ?? { _tag: \"log-limit\", observed: logBytes + bytes, logs: boundedLogs() };\n throw new Error(\"code-mode log limit exceeded\");\n }\n logs.push(line);\n logBytes += bytes;\n };\n globalThis.console = { log: write, info: write, warn: write, error: write, debug: write };\n\n let hostCalls = 0;\n const makeMethod = (namespace, method) => async (argument) => {\n hostCalls += 1;\n if (hostCalls > limits.maxHostCalls) {\n fatal = fatal ?? { _tag: \"host-call-limit\", logs: boundedLogs() };\n throw new Error(\"code-mode host-call limit exceeded\");\n }\n let argText;\n try {\n argText = JSON.stringify(argument);\n } catch {}\n if (argText === undefined || utf8(argText) > limits.maxHostCallArgumentBytes) {\n fatal = fatal ?? {\n _tag: \"argument-limit\",\n observed: argText === undefined ? 0 : utf8(argText),\n logs: boundedLogs(),\n };\n throw new Error(\"code-mode host-call argument limit exceeded\");\n }\n const outcome = await host.call({\n namespace,\n method,\n argument: JSON.parse(argText),\n });\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallSuccess\") {\n return outcome.value;\n }\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallFailure\") {\n throw outcome.error;\n }\n fatal = fatal ?? { _tag: \"protocol\", message: \"host returned an unrecognized outcome\" };\n throw new Error(\"code-mode host protocol violation\");\n };\n for (const namespace of config.namespaces) {\n const methods = {};\n for (const method of namespace.methods) {\n methods[method] = makeMethod(namespace.name, method);\n }\n globalThis[namespace.name] = methods;\n }\n\n // program.js is imported statically at the top of this module, so a\n // syntactically invalid program fails the whole harness at load (mapped\n // to a source error by the host). Using a static import keeps this module\n // free of dynamic-import expressions, which single-script Miniflare hosts\n // reject. The isolation boundary does NOT depend on the ordering of this\n // import versus the console/namespace shims installed below: the loaded\n // Worker has globalOutbound: null and no bindings, secrets, or env from\n // the Worker Loader config BEFORE any module in the graph evaluates, so\n // module-level program code has no ambient authority regardless. The\n // shims below are usability wrappers (bounded console, namespace globals),\n // and the accepted program is a single async-function expression whose\n // body runs only when invoked here — after the shims exist.\n const program = programDefault;\n if (typeof program !== \"function\") {\n return { _tag: \"source-not-a-function\", actual: typeof program };\n }\n try {\n const value = await program();\n if (fatal !== undefined) return fatal;\n let text;\n try {\n text = JSON.stringify(value);\n } catch {}\n if (text === undefined) {\n return {\n _tag: \"program-failed\",\n reason: \"non-json-result\",\n thrown: null,\n message: \"The program must return a JSON value\",\n logs: boundedLogs(),\n };\n }\n const resultBytes = utf8(text);\n if (resultBytes > limits.maxResultBytes) {\n return { _tag: \"result-limit\", observed: resultBytes, logs: boundedLogs() };\n }\n return {\n _tag: \"completed\",\n value: JSON.parse(text),\n logs: boundedLogs(),\n hostCalls,\n logBytes,\n resultBytes,\n };\n } catch (cause) {\n if (fatal !== undefined) return fatal;\n return {\n _tag: \"program-failed\",\n reason: cause instanceof Error ? \"threw\" : \"rejected\",\n thrown: safeJson(cause),\n message: safeText(cause),\n logs: boundedLogs(),\n };\n }\n }\n}\n`;\n\nconst BoundedLogs = Schema.Array(Schema.String.check(Schema.isMaxLength(16 * 1024))).check(\n Schema.isMaxLength(4_096),\n);\n\nconst HarnessCompleted = Schema.TaggedStruct(\"completed\", {\n value: Schema.Json,\n logs: BoundedLogs,\n hostCalls: Schema.Natural,\n logBytes: Schema.Natural,\n resultBytes: Schema.Natural,\n});\n\nconst HarnessNotAFunction = Schema.TaggedStruct(\"source-not-a-function\", {\n actual: Schema.String,\n});\n\nconst HarnessProgramFailed = Schema.TaggedStruct(\"program-failed\", {\n reason: Schema.Literals([\"threw\", \"rejected\", \"non-json-result\"]),\n thrown: Schema.Json,\n message: Schema.String,\n logs: BoundedLogs,\n});\n\nconst HarnessLogLimit = Schema.TaggedStruct(\"log-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessArgumentLimit = Schema.TaggedStruct(\"argument-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessResultLimit = Schema.TaggedStruct(\"result-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessHostCallLimit = Schema.TaggedStruct(\"host-call-limit\", {\n logs: BoundedLogs,\n});\n\nconst HarnessProtocol = Schema.TaggedStruct(\"protocol\", {\n message: Schema.String,\n});\n\nconst HarnessOutcome = Schema.Union([\n HarnessCompleted,\n HarnessNotAFunction,\n HarnessProgramFailed,\n HarnessLogLimit,\n HarnessArgumentLimit,\n HarnessResultLimit,\n HarnessHostCallLimit,\n HarnessProtocol,\n]);\n\nconst HarnessPassConfig = Schema.Struct({\n namespaces: Schema.Array(\n Schema.Struct({\n name: Schema.NonEmptyString,\n methods: Schema.Array(Schema.NonEmptyString).check(Schema.isMaxLength(64)),\n }),\n ).check(Schema.isMaxLength(32)),\n limits: Schema.Struct({\n maxLogBytes: Schema.Natural,\n maxResultBytes: Schema.Natural,\n maxHostCalls: Schema.Natural,\n maxHostCallArgumentBytes: Schema.Natural,\n }),\n});\n\nconst encodeHarnessPassConfig = Schema.encodeSync(HarnessPassConfig);\nconst encodeJsonPayload = Schema.encodeSync(Schema.fromJsonString(Schema.Json));\nconst decodeJsonPayload = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));\n\nconst decodeHarnessOutcome = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(HarnessOutcome)(value);\n } catch {\n return Option.none<typeof HarnessOutcome.Type>();\n }\n};\n\nconst decodeHostCall = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCall)(value);\n } catch {\n return Option.none<CodeHostCall>();\n }\n};\n\nconst decodeHostCallResult = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCallResult)(value);\n } catch {\n return Option.none<CodeHostCallResult>();\n }\n};\n\n/** Dispose a Cloudflare RPC handle when the runtime supplies its untyped disposal hook. @internal */\nexport const disposeRpcHandle = (handle: unknown): Effect.Effect<void> =>\n Effect.try({\n try: () => {\n if ((typeof handle !== \"object\" && typeof handle !== \"function\") || handle === null) return;\n if (!(Symbol.dispose in handle)) return;\n const dispose = Reflect.get(handle, Symbol.dispose);\n\n if (typeof dispose === \"function\") {\n Reflect.apply(dispose, handle, []);\n }\n },\n catch: (cause) =>\n safeCauseDiagnostic(cause, \"The Cloudflare RPC disposal hook failed without a diagnostic\"),\n }).pipe(\n Effect.catch((diagnostic) =>\n Effect.logWarning(`Cloudflare RPC handle disposal failed: ${diagnostic}`).pipe(\n Effect.ignoreCause,\n ),\n ),\n );\n\n/**\n * Project a host outcome to the plain JSON envelope the harness reads. A\n * `CodeExecutionHost` may return either real `CodeHostCallResult` instances\n * (the substitute and conformance kit) or plain-object equivalents (the Code\n * Mode capability's broker route), so this reads the shared fields rather than\n * `Schema.encodeSync`, which would reject a plain object.\n */\ninterface EncodedHostResultPayload {\n readonly encodedPayload: string;\n readonly resultBytes: number;\n}\n\nconst encodeHostResultPayload = (\n outcome: CodeHostCallResult,\n): EncodedHostResultPayload | undefined => {\n try {\n const payload = outcome._tag === \"CodeHostCallSuccess\" ? outcome.value : outcome.error;\n const encodedPayload = encodeJsonPayload(payload);\n\n return {\n encodedPayload,\n resultBytes: utf8ByteLength(encodedPayload),\n };\n } catch {\n return undefined;\n }\n};\n\nconst utf8ByteLength = (value: string): number => {\n let total = 0;\n\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n\n total += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;\n }\n\n return total;\n};\n\ninterface QueuedHostCall {\n readonly call: CodeHostCall;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\ntype HostWork =\n | { readonly _tag: \"call\"; readonly queued: QueuedHostCall }\n | { readonly _tag: \"limit\" };\n\ntype HostDispatchError =\n | CodeExecutionTimeoutError\n | CodeOutputLimitError\n | CodeExecutionProtocolError\n | CodeHostCallLimitError;\n\n/** Reserved global names the harness owns inside the dynamic worker. */\nconst reservedHarnessGlobals = new Set([\"console\"]);\n\nexport interface DynamicWorkerCodeExecutorOptions {\n /** The `worker_loader` binding. */\n readonly loader: WorkerLoader;\n /** Compatibility date for dynamic workers; defaults to `2025-05-01`. */\n readonly compatibilityDate?: string | undefined;\n}\n\nconst makeExecute = (\n options: DynamicWorkerCodeExecutorOptions,\n clock: Clock.Clock,\n): CodeExecutorExecute =>\n Effect.fn(\"DynamicWorkerCodeExecutor.execute\")(function* (request: CodeExecutionRequest) {\n if (request.network._tag !== \"NetworkDisabled\") {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"network\",\n message:\n \"The Dynamic Worker executor denies all egress with globalOutbound: null; an allowlist is not supported in the first slice\",\n });\n }\n const sourceBytes = utf8ByteLength(request.source);\n\n if (sourceBytes > request.limits.maxSourceBytes) {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"oversized\",\n message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,\n });\n }\n for (const namespace of request.namespaces) {\n if (reservedHarnessGlobals.has(namespace.name)) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"namespaces\",\n message: `Namespace ${namespace.name} collides with a harness binding`,\n });\n }\n }\n const host = yield* CodeExecutionHost;\n\n // This synchronous clock access is confined to callbacks that must compute a timeout\n // immediately. The Clock service remains the authority, so tests and hosts can replace it.\n const startedAt = clock.monotonicTimeNanosUnsafe();\n const passDeadline = startedAt + Duration.toNanosUnsafe(request.limits.maxWallTime);\n\n const remainingPassWallTime = (): Duration.Duration => {\n const now = clock.monotonicTimeNanosUnsafe();\n\n return Duration.nanos(passDeadline > now ? passDeadline - now : 0n);\n };\n\n let issuedHostCalls = 0;\n let passOpen = true;\n const queuedHostCalls: Array<QueuedHostCall> = [];\n let passFailure: HostDispatchError | undefined;\n\n const failPass = (error: HostDispatchError): void => {\n if (passFailure === undefined) passFailure = error;\n };\n\n const rejectQueuedHostCalls = (reason: Error): void => {\n for (const queued of queuedHostCalls.splice(0)) {\n queued.reject(reason);\n }\n };\n\n const queue = yield* Queue.unbounded<HostWork>();\n\n const deliverHostOutcome = (\n queued: QueuedHostCall,\n outcome: CodeHostCallResult,\n ): Effect.Effect<void, CodeExecutionProtocolError | CodeOutputLimitError> =>\n Effect.gen(function* () {\n const decoded = decodeHostCallResult(outcome);\n\n if (Option.isNone(decoded)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a value outside the CodeHostCallResult schema\",\n });\n\n failPass(error);\n\n return yield* error;\n }\n const encoded = encodeHostResultPayload(decoded.value);\n\n if (encoded === undefined || encoded.resultBytes > request.limits.maxHostCallResultBytes) {\n const error = CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-result\",\n limit: request.limits.maxHostCallResultBytes,\n observed: encoded?.resultBytes ?? 0,\n logs: [],\n });\n\n failPass(error);\n\n return yield* error;\n }\n const normalizedPayload = decodeJsonPayload(encoded.encodedPayload);\n\n if (Option.isNone(normalizedPayload)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a result that could not cross the JSON boundary\",\n });\n\n failPass(error);\n\n return yield* error;\n }\n queued.resolve(\n decoded.value._tag === \"CodeHostCallSuccess\"\n ? { _tag: \"CodeHostCallSuccess\", value: normalizedPayload.value }\n : { _tag: \"CodeHostCallFailure\", error: normalizedPayload.value },\n );\n });\n\n // Workers RPC into the loader isolate cannot settle on the fiber blocked\n // in `entrypoint.run()`. A Scope-owned sibling fiber keeps that\n // independence while inheriting the pass Context and dying with the Scope.\n const serveHostCalls = Effect.gen(function* () {\n while (true) {\n const work = yield* Queue.take(queue);\n\n if (work._tag === \"limit\") {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n\n failPass(error);\n\n return yield* error;\n }\n const queued = work.queued;\n\n yield* host.call(queued.call).pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () => {\n const error = CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n });\n\n failPass(error);\n\n return error;\n },\n }),\n Effect.flatMap((outcome) => deliverHostOutcome(queued, outcome)),\n Effect.tapError(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode host call failed\"))),\n ),\n Effect.onInterrupt(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode pass is closing\"))),\n ),\n );\n }\n });\n\n const server = yield* serveHostCalls.pipe(Effect.forkScoped);\n\n const dispatch = (hostCall: unknown): Promise<unknown> => {\n if (!passOpen) {\n return Promise.reject(new Error(\"Code Mode pass is closing\"));\n }\n issuedHostCalls += 1;\n if (issuedHostCalls > request.limits.maxHostCalls) {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n\n failPass(error);\n Queue.offerUnsafe(queue, { _tag: \"limit\" });\n\n return Promise.reject(new Error(\"host-call limit exceeded\"));\n }\n const decoded = decodeHostCall(hostCall);\n\n if (Option.isNone(decoded)) {\n return Promise.reject(new TypeError(\"host calls must match the CodeHostCall schema\"));\n }\n\n return new Promise((resolve, reject) => {\n const queued = { call: decoded.value, resolve, reject };\n\n queuedHostCalls.push(queued);\n Queue.offerUnsafe(queue, { _tag: \"call\", queued });\n });\n };\n\n const closeAdmission = Effect.sync(() => {\n passOpen = false;\n rejectQueuedHostCalls(new Error(\"Code Mode pass is closing\"));\n });\n\n yield* Effect.addFinalizer(() => closeAdmission.pipe(Effect.andThen(Fiber.interrupt(server))));\n\n // No `allowExperimental`: the runtime only accepts it when the CALLING\n // worker carries the `experimental` compatibility flag, which deployed\n // consumers cannot set — the option would reject every pass in\n // production. The harness needs no experimental runtime features.\n const workerCode: WorkerLoaderWorkerCode = {\n compatibilityDate: options.compatibilityDate ?? \"2025-05-01\",\n mainModule: \"harness.js\",\n modules: {\n \"harness.js\": HARNESS_MODULE,\n \"program.js\": `export default (\\n${request.source}\\n);`,\n },\n env: {\n CODE_MODE_PASS: encodeHarnessPassConfig({\n namespaces: request.namespaces.map((namespace) => ({\n name: namespace.name,\n methods: namespace.methods,\n })),\n limits: {\n maxLogBytes: request.limits.maxLogBytes,\n maxResultBytes: request.limits.maxResultBytes,\n maxHostCalls: request.limits.maxHostCalls,\n maxHostCallArgumentBytes: request.limits.maxHostCallArgumentBytes,\n },\n }),\n },\n globalOutbound: null,\n ...(request.limits.cpuMillis === undefined\n ? {}\n : {\n limits: {\n cpuMs: request.limits.cpuMillis,\n subRequests: request.limits.maxHostCalls + 8,\n },\n }),\n };\n\n const worker = yield* Effect.acquireRelease(\n Effect.try({\n try: () => options.loader.load(workerCode),\n catch: (cause) => {\n const text = safeCauseMessage(cause, \"The Worker Loader failed without a diagnostic\");\n\n // Blame the program's source ONLY on a genuine compile diagnostic;\n // any other load rejection is an infrastructure start failure, not\n // the model's fault (see classifyWorkerFailure for the same split).\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: `The Worker Loader rejected the pass: ${text}`.slice(0, 8_000),\n cause,\n });\n },\n }),\n disposeRpcHandle,\n );\n\n const entrypoint = yield* Effect.acquireRelease(\n Effect.try({\n try: () => worker.getEntrypoint<CodeModeHarnessEntrypoint>(),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n }),\n disposeRpcHandle,\n );\n\n const rpc = Effect.tryPromise({\n try: () => entrypoint.run(new CodeModePassHostTarget(dispatch)),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n });\n\n const exit = yield* Effect.raceFirst(\n rpc.pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () =>\n CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n }),\n }),\n ),\n Fiber.join(server),\n ).pipe(Effect.exit);\n\n yield* closeAdmission;\n yield* Fiber.interrupt(server);\n if (passFailure !== undefined) {\n return yield* passFailure;\n }\n if (Exit.isFailure(exit)) {\n return yield* Effect.failCause(exit.cause);\n }\n const raw = exit.value;\n const finishedAt = clock.monotonicTimeNanosUnsafe();\n\n const outcome = decodeHarnessOutcome(raw);\n\n if (Option.isNone(outcome)) {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The dynamic worker returned a value outside the harness envelope schema\",\n });\n }\n switch (outcome.value._tag) {\n case \"completed\": {\n return CodeExecutionResult.make({\n implementation: dynamicWorkerImplementation,\n value: outcome.value.value,\n logs: outcome.value.logs,\n resourceUse: CodeExecutionResourceUse.make({\n wallTime: Duration.nanos(finishedAt > startedAt ? finishedAt - startedAt : 0n),\n hostCalls: outcome.value.hostCalls,\n logBytes: outcome.value.logBytes,\n resultBytes: outcome.value.resultBytes,\n }),\n });\n }\n case \"source-not-a-function\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"not-a-function\",\n message: `The source expression evaluated to ${outcome.value.actual}; it must evaluate to one async function`,\n });\n }\n case \"program-failed\": {\n return yield* CodeProgramFailedError.make({\n implementation: dynamicWorkerImplementation,\n reason: outcome.value.reason,\n thrown: outcome.value.thrown,\n message: outcome.value.message.slice(0, 8_000),\n logs: outcome.value.logs,\n });\n }\n case \"log-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"logs\",\n limit: request.limits.maxLogBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"argument-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-argument\",\n limit: request.limits.maxHostCallArgumentBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"result-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"result\",\n limit: request.limits.maxResultBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"host-call-limit\": {\n return yield* CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: outcome.value.logs,\n });\n }\n case \"protocol\": {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n }\n });\n\n/**\n * Expected worker-level failures map into the typed union with bounded\n * diagnostics; anything unrecognized stays a start/termination error rather\n * than a fabricated program result.\n */\nconst classifyWorkerFailure = (\n cause: unknown,\n maxWallTime: Duration.Duration,\n):\n | CodeExecutionTimeoutError\n | CodeExecutorTerminatedError\n | CodeExecutorStartError\n | CodeSourceError => {\n const text = safeCauseDiagnostic(cause, \"[unserializable worker failure]\");\n\n // `WorkerLoader.load()` is lazy, so a module-compile error in the generated\n // program surfaces here at first use. Blame the program's source ONLY on a\n // genuine compile diagnostic (a `SyntaxError` or an explicit compile\n // failure) — the fixed harness is valid, so the fault is in program.js. A\n // bare \"failed to start Worker\" without a compile diagnostic is an\n // infrastructure start failure, not the model's fault, so it must NOT be\n // misclassified as a source error.\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n if (/cpu/i.test(text)) {\n return CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"cpu\",\n maxWallTime,\n logs: [],\n });\n }\n if (/failed to start worker/i.test(text)) {\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n cause,\n });\n }\n\n return CodeExecutorTerminatedError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n });\n};\n\n/** Layer building the Dynamic Worker `CodeExecutor` from resolved bindings. */\nexport const dynamicWorkerCodeExecutorLayer = (\n options: DynamicWorkerCodeExecutorOptions,\n): Layer.Layer<CodeExecutor> =>\n Layer.effect(\n CodeExecutor,\n Effect.gen(function* () {\n const clock = yield* Clock.Clock;\n\n return CodeExecutor.of({ execute: makeExecute(options, clock) });\n }),\n );\n\n/** Assemble Code Mode handlers with the isolated Dynamic Worker executor. */\nexport const CloudflareCodeMode = {\n /**\n * Provide the selected tool handlers at construction, where Code Mode captures them.\n * Their errors and remaining dependencies stay visible. The definition still owns the\n * allowlist and limits; the runtime supplies the live Tool broker for each scoped pass.\n */\n layer: <A, E, R, Handlers, HandlerError, HandlerRequirements>(\n definition: { readonly handlers: Layer.Layer<A, E, R> },\n options: DynamicWorkerCodeExecutorOptions & {\n readonly handlers: Layer.Layer<Handlers, HandlerError, HandlerRequirements>;\n },\n ) =>\n definition.handlers.pipe(\n Layer.provide(options.handlers),\n Layer.provide(dynamicWorkerCodeExecutorLayer(options)),\n ),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,8BAA8B,sBAAsB,KAAK;CACpE,WAAW;CACX,UAAU;AACZ,CAAC;;;;;;;;AAiBD,IAAM,yBAAN,c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,OAAO,OAAO,2BAA2B,KAAK;GAC5C,gBAAgB;GAChB,SAAS,QAAQ,MAAM,QAAQ,MAAM,GAAG,GAAK;EAC/C,CAAC;CAEL;AACF,CAAC;;;;;;AAOH,MAAM,yBACJ,OACA,gBAKqB;CACrB,MAAM,OAAO,oBAAoB,OAAO,iCAAiC;CASzE,IAAI,yCAAyC,KAAK,IAAI,GACpD,OAAO,gBAAgB,KAAK;EAC1B,gBAAgB;EAChB,QAAQ;EACR,SAAS,KAAK,MAAM,GAAG,GAAK;CAC9B,CAAC;CAEH,IAAI,OAAO,KAAK,IAAI,GAClB,OAAO,0BAA0B,KAAK;EACpC,gBAAgB;EAChB,MAAM;EACN;EACA,MAAM,CAAC;CACT,CAAC;CAEH,IAAI,0BAA0B,KAAK,IAAI,GACrC,OAAO,uBAAuB,KAAK;EACjC,gBAAgB;EAChB,SAAS,KAAK,MAAM,GAAG,GAAK;EAC5B;CACF,CAAC;CAGH,OAAO,4BAA4B,KAAK;EACtC,gBAAgB;EAChB,SAAS,KAAK,MAAM,GAAG,GAAK;CAC9B,CAAC;AACH;;AAGA,MAAa,kCACX,YAEA,MAAM,OACJ,cACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,MAAM;CAE3B,OAAO,aAAa,GAAG,EAAE,SAAS,YAAY,SAAS,KAAK,EAAE,CAAC;AACjE,CAAC,CACH;;AAGF,MAAa,qBAAqB;;;;;;AAMhC,QACE,YACA,YAIA,WAAW,SAAS,KAClB,MAAM,QAAQ,QAAQ,QAAQ,GAC9B,MAAM,QAAQ,+BAA+B,OAAO,CAAC,CACvD,EACJ"}
@@ -246,37 +246,13 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
246
246
  readonly createdAt: string;
247
247
  readonly deploymentId: string;
248
248
  readonly payload: {
249
- readonly _tag: "ToolCallPrepared";
250
- readonly runId: string;
251
- readonly turnId: string;
252
- readonly turn: number;
253
- readonly toolCallId: string;
254
- readonly toolName: string;
255
- readonly parameters: Schema.Json;
256
- readonly parametersDigest: string;
257
- readonly executionKind?: "delegation" | "ordinary" | undefined;
258
- } | {
259
- readonly _tag: "ToolCallUnknown";
260
- readonly runId: string;
261
- readonly turn: number;
262
- readonly toolCallId: string;
263
- readonly toolName: string;
264
- readonly reason: string;
265
- } | {
266
- readonly _tag: "ToolApprovalDecided";
267
- readonly runId: string;
268
- readonly turn: number;
269
- readonly toolCallId: string;
270
- readonly decision: "approved" | "denied";
271
- readonly resolver: string;
272
- readonly reason: string;
273
- } | {
274
- readonly _tag: "ToolCallResolved";
249
+ readonly _tag: "SubagentStarted";
275
250
  readonly runId: string;
276
251
  readonly toolCallId: string;
277
- readonly resolution: "completed-with-result" | "failed-with-error" | "never-started" | "safe-retry";
278
- readonly author: string;
279
- readonly reason: string;
252
+ readonly childThreadId: string;
253
+ readonly childSubmissionId: string;
254
+ readonly childReceiptId: string;
255
+ readonly childRunId: string;
280
256
  } | {
281
257
  readonly _tag: "AbortRequested";
282
258
  readonly submissionId: string;
@@ -340,6 +316,16 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
340
316
  readonly inputTokens?: number | undefined;
341
317
  readonly outputTokens?: number | undefined;
342
318
  readonly costMicrousd?: number | undefined;
319
+ } | {
320
+ readonly _tag: "ToolCallPrepared";
321
+ readonly runId: string;
322
+ readonly turnId: string;
323
+ readonly turn: number;
324
+ readonly toolCallId: string;
325
+ readonly toolName: string;
326
+ readonly parameters: Schema.Json;
327
+ readonly parametersDigest: string;
328
+ readonly executionKind?: "delegation" | "ordinary" | undefined;
343
329
  } | {
344
330
  readonly _tag: "ToolCallSettled";
345
331
  readonly runId: string;
@@ -348,6 +334,20 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
348
334
  readonly result: Schema.Json;
349
335
  readonly isFailure: boolean;
350
336
  readonly budgetRejected?: true | undefined;
337
+ } | {
338
+ readonly _tag: "ToolCallUnknown";
339
+ readonly runId: string;
340
+ readonly turn: number;
341
+ readonly toolCallId: string;
342
+ readonly toolName: string;
343
+ readonly reason: string;
344
+ } | {
345
+ readonly _tag: "ToolCallResolved";
346
+ readonly runId: string;
347
+ readonly toolCallId: string;
348
+ readonly resolution: "completed-with-result" | "failed-with-error" | "never-started" | "safe-retry";
349
+ readonly author: string;
350
+ readonly reason: string;
351
351
  } | {
352
352
  readonly _tag: "ToolStepSettled";
353
353
  readonly runId: string;
@@ -363,6 +363,14 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
363
363
  readonly toolCallId: string;
364
364
  readonly toolName: string;
365
365
  readonly parametersDigest: string;
366
+ } | {
367
+ readonly _tag: "ToolApprovalDecided";
368
+ readonly runId: string;
369
+ readonly turn: number;
370
+ readonly toolCallId: string;
371
+ readonly decision: "approved" | "denied";
372
+ readonly resolver: string;
373
+ readonly reason: string;
366
374
  } | {
367
375
  readonly _tag: "ModelResponseInterrupted";
368
376
  readonly runId: string;
@@ -373,9 +381,10 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
373
381
  readonly _tag: "CompactionCreated";
374
382
  readonly runId: string;
375
383
  readonly turn: number;
376
- readonly kind: "clear-tool-results" | "summarize";
384
+ readonly kind: "clear-tool-results" | "rollover" | "summarize";
377
385
  readonly coversThrough: number;
378
386
  readonly summary?: string | undefined;
387
+ readonly handoff?: string | undefined;
379
388
  } | {
380
389
  readonly _tag: "RunFailed";
381
390
  readonly runId: string;
@@ -478,14 +487,6 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
478
487
  readonly resultBytes: number;
479
488
  };
480
489
  } | undefined;
481
- } | {
482
- readonly _tag: "SubagentStarted";
483
- readonly runId: string;
484
- readonly toolCallId: string;
485
- readonly childThreadId: string;
486
- readonly childSubmissionId: string;
487
- readonly childReceiptId: string;
488
- readonly childRunId: string;
489
490
  } | {
490
491
  readonly _tag: "SubagentJoined";
491
492
  readonly runId: string;
@@ -573,24 +574,25 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
573
574
  } | {
574
575
  readonly _tag: "HostFailed";
575
576
  readonly failure: {
576
- readonly _tag: "OperationDenied";
577
- readonly operation: "abort" | "awaitSettlement" | "explain" | "observe" | "resolveApproval" | "resolveUnknown" | "retry" | "scanObligations" | "verify" | "wake";
578
- readonly reason: string;
579
- readonly threadId?: string | undefined;
580
- readonly submissionId?: string | undefined;
577
+ readonly _tag: "AdmissionConflict";
578
+ readonly threadId: string;
579
+ readonly principal: string;
580
+ readonly idempotencyKey: string;
581
+ readonly existingInputDigest: string;
582
+ readonly attemptedInputDigest: string;
583
+ } | {
584
+ readonly _tag: "SettlementConflict";
585
+ readonly submissionId: string;
586
+ readonly existingOutcome: "aborted" | "completed" | "failed";
587
+ } | {
588
+ readonly _tag: "JoinedToHost";
589
+ readonly submissionId: string;
590
+ readonly hostSubmissionId: string;
581
591
  } | {
582
592
  readonly _tag: "LedgerError";
583
593
  readonly operation: string;
584
594
  readonly message: string;
585
595
  readonly cause?: Schema.Json | undefined;
586
- } | {
587
- readonly _tag: "DigestError";
588
- readonly message: string;
589
- readonly cause?: Schema.Json | undefined;
590
- } | {
591
- readonly _tag: "SettlementConflict";
592
- readonly submissionId: string;
593
- readonly existingOutcome: "aborted" | "completed" | "failed";
594
596
  } | {
595
597
  readonly _tag: "ThreadStoreError";
596
598
  readonly operation: string;
@@ -611,9 +613,6 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
611
613
  readonly threadId: string;
612
614
  readonly actualEpoch: number;
613
615
  readonly attemptedEpoch: number;
614
- } | {
615
- readonly _tag: "DurableRuntimeFailpointError";
616
- readonly location: "abort:after-intent" | "approval:after-request-append" | "approval:after-suspend" | "claim:after-claim" | "compaction:after-canonical-append" | "input:after-canonical-append" | "join:after-canonical-append" | "join:after-claim" | "policy:after-reservation-append" | "policy:before-reservation-append" | "resolve:after-intent" | "run:after-start-append" | "run:before-start-append" | "step:after-step-append" | "subagent:after-admit" | "subagent:after-child-abort-intent" | "subagent:after-child-ready" | "subagent:after-join-append" | "subagent:after-release" | "subagent:after-release-pending" | "subagent:after-request-append" | "subagent:after-reserve" | "subagent:after-sibling-settle" | "subagent:after-start-append" | "subagent:after-suspend" | "submit:after-admit" | "submit:after-materialize" | "terminalize:after-canonical-append" | "terminalize:after-reserve" | "tools:after-prepared-append" | "tools:before-prepared-append" | "turn:after-canonical-append" | "turn:after-response-append" | "turn:after-results-append";
617
616
  } | {
618
617
  readonly _tag: "DurableAlarmError";
619
618
  readonly operation: string;
@@ -622,20 +621,13 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
622
621
  } | {
623
622
  readonly _tag: "HostProtocolError";
624
623
  readonly message: string;
625
- } | {
626
- readonly _tag: "AdmissionConflict";
627
- readonly threadId: string;
628
- readonly principal: string;
629
- readonly idempotencyKey: string;
630
- readonly existingInputDigest: string;
631
- readonly attemptedInputDigest: string;
632
- } | {
633
- readonly _tag: "JoinedToHost";
634
- readonly submissionId: string;
635
- readonly hostSubmissionId: string;
636
624
  } | {
637
625
  readonly _tag: "AgentInputError";
638
626
  readonly message: string;
627
+ } | {
628
+ readonly _tag: "DigestError";
629
+ readonly message: string;
630
+ readonly cause?: Schema.Json | undefined;
639
631
  } | {
640
632
  readonly _tag: "ApprovalConflict";
641
633
  readonly submissionId: string;
@@ -645,11 +637,20 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
645
637
  readonly _tag: "UnknownResolutionConflict";
646
638
  readonly submissionId: string;
647
639
  readonly toolCallId: string;
640
+ } | {
641
+ readonly _tag: "DurableRuntimeFailpointError";
642
+ readonly location: "abort:after-intent" | "approval:after-request-append" | "approval:after-suspend" | "claim:after-claim" | "compaction:after-canonical-append" | "compaction:before-canonical-append" | "input:after-canonical-append" | "join:after-canonical-append" | "join:after-claim" | "policy:after-reservation-append" | "policy:before-reservation-append" | "resolve:after-intent" | "run:after-start-append" | "run:before-start-append" | "step:after-step-append" | "subagent:after-admit" | "subagent:after-child-abort-intent" | "subagent:after-child-ready" | "subagent:after-join-append" | "subagent:after-release" | "subagent:after-release-pending" | "subagent:after-request-append" | "subagent:after-reserve" | "subagent:after-sibling-settle" | "subagent:after-start-append" | "subagent:after-suspend" | "submit:after-admit" | "submit:after-materialize" | "terminalize:after-canonical-append" | "terminalize:after-reserve" | "tools:after-prepared-append" | "tools:before-prepared-append" | "turn:after-canonical-append" | "turn:after-response-append" | "turn:after-results-append";
648
643
  } | {
649
644
  readonly _tag: "AdmissionLimitExceeded";
650
645
  readonly limit: "database-bytes" | "input-bytes" | "queue-depth";
651
646
  readonly actual: number;
652
647
  readonly maximum: number;
648
+ } | {
649
+ readonly _tag: "OperationDenied";
650
+ readonly operation: "abort" | "awaitSettlement" | "explain" | "observe" | "resolveApproval" | "resolveUnknown" | "retry" | "scanObligations" | "verify" | "wake";
651
+ readonly reason: string;
652
+ readonly threadId?: string | undefined;
653
+ readonly submissionId?: string | undefined;
653
654
  };
654
655
  }, Schema.SchemaError, never>;
655
656
  declare const decodeHostResponse: (input: unknown, options?: import("effect/SchemaAST").ParseOptions) => Effect.Effect<AbortRecorded | ApprovalRecorded | HostFailed | ObservedPage | ProgressCancelled | ProgressObserved | SettlementReached | SubmitSucceeded | UnknownResolutionRecorded, Schema.SchemaError, never>;
@@ -943,6 +943,7 @@ const makeHostService = (binding) => {
943
943
  const open = Effect.fn("BrowserRunInteractiveHost.open")(function* (policy) {
944
944
  const fixedPolicy = yield* snapshotPolicy(policy);
945
945
  const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
946
+ const runCleanup = Effect.runPromiseWith(Context.make(Clock.Clock, yield* Clock.Clock));
946
947
  const state = {
947
948
  closed: { value: false },
948
949
  disconnected: { value: false },
@@ -954,7 +955,7 @@ const makeHostService = (binding) => {
954
955
  const closers = [];
955
956
  const releaseBeforeManaged = (entry) => Effect.suspend(() => lifecycle.managedTeardownInstalled ? Effect.void : entry.close.pipe(Effect.catchCause(() => Effect.logWarning(entry.warning))));
956
957
  const browser = yield* Effect.acquireRelease(withinDeadline(Effect.tryPromise({
957
- try: (signal) => closeLateAcquisition(signal, () => binding.launch(keepAliveMillis(fixedPolicy)), (acquired) => Effect.runPromise(closeAcquired(acquired))),
958
+ try: (signal) => closeLateAcquisition(signal, () => binding.launch(keepAliveMillis(fixedPolicy)), (acquired) => runCleanup(closeAcquired(acquired))),
958
959
  catch: (cause) => isCapacityRefusal(cause) ? InteractiveBrowserCapacityError.make({
959
960
  implementation: browserRunInteractiveImplementation,
960
961
  message: "Browser Run has no capacity for a new browser session"