diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts index 20056de1b2..3fc18ad818 100644 --- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts @@ -18,7 +18,7 @@ import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' -import { NodeCodeRuntime } from '@deepseek-ai/dsh-code-runtime-node' +import { mountRuntime } from '../../../../../../packages/code-runtime/code-runtime-node/tests/setup.ts' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import * as ToolFs from '@deepseek-ai/dsh-tool-fs' import * as WorkspaceContext from '@deepseek-ai/dsh-agent-instructions' @@ -60,11 +60,11 @@ async function ptcModeHarness(cwd: string): Promise { await harness.plugin(AgentRegistry) await harness.plugin(AgentLoop, { agents: [] }) await harness.plugin(LlmDeepSeek) - await harness.plugin(LocalSubprocessRuntime) + if (harness.get('subprocess') === undefined) await harness.plugin(LocalSubprocessRuntime) await harness.plugin(BashEnvPlugin) await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 }) await harness.plugin(ToolBash) - await harness.plugin(NodeCodeRuntime, {}) + await mountRuntime(harness) return harness } @@ -81,14 +81,14 @@ async function workspacePtcModeHarness(): Promise { await harness.plugin(WorkspaceContext, { maxBytes: 65536 }) await harness.plugin(AgentLoop, { agents: [] }) await harness.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] }) - await harness.plugin(NodeCodeRuntime, {}) + await mountRuntime(harness) return harness } let keylessCall = 0 const testToolSignal = new AbortController().signal -/** Execute one outer PTC mode call through the real registry and worker. */ +/** Execute one outer PTC mode call through the real registry and Node process. */ function runCode( harness: Context, code: string, @@ -114,28 +114,28 @@ function completion(result: ToolExecutionResult): unknown { return value.result } -/** Keyless real-worker harness for direct typed-binding acceptance tests. */ +/** Keyless real-process harness for direct typed-binding acceptance tests. */ async function typedPtcModeHarness(): Promise { const harness = new Context() await harness.plugin(SystemPrompt) await harness.plugin(ToolRuntime, { mode: 'ptc' }) - await harness.plugin(NodeCodeRuntime, {}) + await mountRuntime(harness) return harness } -/** Keyless real-worker harness with the task-owned bash lifecycle. */ +/** Keyless real-process harness with the task-owned bash lifecycle. */ async function backgroundPtcModeHarness(cwd: string): Promise { const harness = await typedPtcModeHarness() await harness.plugin(LocalJobRegistry) await harness.plugin(ToolTasks, {}) - await harness.plugin(LocalSubprocessRuntime) + if (harness.get('subprocess') === undefined) await harness.plugin(LocalSubprocessRuntime) await harness.plugin(BashEnvPlugin) await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 }) await harness.plugin(ToolBash) return harness } -describe('PTC mode typed values: keyless real-worker contracts', () => { +describe('PTC mode typed values: keyless real-process contracts', () => { it('crosses a large intermediate value intact and exposes only typed tool failure fields', async () => { ctx = await typedPtcModeHarness() ctx.tools.register(defineTool({ diff --git a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts index 701b1497bd..54268f8798 100644 --- a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts +++ b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts @@ -2,7 +2,7 @@ import { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type { ToolResultNode } from '@deepseek-ai/dsh-client-ui-chat/client' -import { NodeCodeRuntime } from '@deepseek-ai/dsh-code-runtime-node' +import { mountRuntime } from '../../../code-runtime/code-runtime-node/tests/setup.ts' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' import { SpillLocator, SpillStore, type SaveTextSpill, type SpillRef } from '@deepseek-ai/dsh-spill' @@ -40,7 +40,7 @@ async function executeShell(text: string, nested: boolean, name = 'bash', maxInl await ctx.plugin(ToolRuntime, { mode: 'both' }) await ctx.plugin(MemorySpillStore) await ctx.plugin(SpillPolicy, { maxInlineBytes }) - if (nested) await ctx.plugin(NodeCodeRuntime, {}) + if (nested) await mountRuntime(ctx, {}) ctx.effect(() => ctx.tools.register(defineContentToolFixture({ name, description: 'Return deterministic shell text without spawning a process.', diff --git a/packages/code-runtime/code-runtime-node/package.json b/packages/code-runtime/code-runtime-node/package.json index 0c72921032..83c4a6db2f 100644 --- a/packages/code-runtime/code-runtime-node/package.json +++ b/packages/code-runtime/code-runtime-node/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-code-runtime-node", - "description": "Worker-thread implementation of the DeepSeek Harness code-execution seam", + "description": "Sandboxed Node process implementation of the DeepSeek Harness code-execution capability", "version": "0.1.5-rc.2", "publishConfig": { "access": "public" @@ -18,15 +18,14 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, - "./worker": { - "types": "./lib/types/worker.d.ts", - "default": "./lib/worker.cjs" - }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./process": { + "default": "./lib/process.js" + } }, "files": [ "lib/index.js", - "lib/worker.cjs", + "lib/process.js", "lib/types/**/*.d.ts" ], "license": "MIT", @@ -34,7 +33,11 @@ "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-code-runtime": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", - "@deepseek-ai/dsh-timeout": "workspace:^" + "@deepseek-ai/dsh-timeout": "workspace:^", + "@deepseek-ai/dsh-fs": "workspace:^", + "@deepseek-ai/dsh-subprocess": "workspace:^", + "@deepseek-ai/dsh-sandbox": "workspace:^", + "@deepseek-ai/dsh-sandbox-policy": "workspace:^" }, "dependencies": { "@deepseek-ai/dsh-util-values": "workspace:^", @@ -44,6 +47,14 @@ "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-code-runtime": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", - "@deepseek-ai/dsh-timeout": "workspace:^" + "@deepseek-ai/dsh-timeout": "workspace:^", + "@deepseek-ai/dsh-fs": "workspace:^", + "@deepseek-ai/dsh-subprocess": "workspace:^", + "@deepseek-ai/dsh-sandbox": "workspace:^", + "@deepseek-ai/dsh-sandbox-policy": "workspace:^", + "@deepseek-ai/dsh-fs-local": "workspace:^", + "@deepseek-ai/dsh-subprocess-local": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/dsh-sandbox-local": "workspace:^" } } diff --git a/packages/code-runtime/code-runtime-node/src/bindings.ts b/packages/code-runtime/code-runtime-node/src/bindings.ts new file mode 100644 index 0000000000..ce7d50153a --- /dev/null +++ b/packages/code-runtime/code-runtime-node/src/bindings.ts @@ -0,0 +1,51 @@ +/** Validate and capture the binding names available to one program. */ +import { DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-code-runtime' +import type { CodeBindingNamespace, CodeRunRequest } from '@deepseek-ai/dsh-code-runtime' +const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/ +/** + * Reject unusable namespaces before starting a process. + * @param request - Host-owned binding declarations. + * @returns Namespaces keyed by their declared global. + */ +export function validateBindings(request: CodeRunRequest): Map { + const bindings = new Map() + for (const namespace of request.bindings) { + if (!IDENTIFIER.test(namespace.global) || PORTABLE_RESERVED_WORDS.has(namespace.global)) { + throw new Error(`dsh-code-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`) + } + // RESERVED_BINDING_GLOBALS is the seam's shared backend-owned set: + // `console` is THIS backend's log-capture slot; the dunder entries exist + // for the Python side — its seeded/wrapped slots plus the `__debug__` + // compile-time constant — refused here too so the namespace list stays + // portable across backends. The seam declaration is the single home for + // why each entry is reserved. + if (RESERVED_BINDING_GLOBALS.has(namespace.global)) { + throw new Error(`dsh-code-runtime-node: reserved binding global ${JSON.stringify(namespace.global)}`) + } + if (bindings.has(namespace.global)) { + throw new Error(`dsh-code-runtime-node: duplicate binding global ${JSON.stringify(namespace.global)}`) + } + bindings.set(namespace.global, namespace) + } + + const errorClassNames = new Set() + for (const namespace of request.bindings) { + const descriptor = namespace.errorClass + if (!descriptor) continue + if (!IDENTIFIER.test(descriptor.name) || PORTABLE_RESERVED_WORDS.has(descriptor.name)) { + throw new Error(`dsh-code-runtime-node: binding error class ${JSON.stringify(descriptor.name)} is not a usable identifier`) + } + if (RESERVED_BINDING_GLOBALS.has(descriptor.name)) { + throw new Error(`dsh-code-runtime-node: reserved binding global ${JSON.stringify(descriptor.name)}`) + } + if (bindings.has(descriptor.name) || errorClassNames.has(descriptor.name)) { + throw new Error(`dsh-code-runtime-node: duplicate injected global ${JSON.stringify(descriptor.name)}`) + } + const member = descriptor.memberNameProperty + if (member.length === 0 || RESERVED_ERROR_MEMBERS.has(member) || DUNDER_MEMBER.test(member)) { + throw new Error(`dsh-code-runtime-node: binding error member property ${JSON.stringify(descriptor.memberNameProperty)} is not usable`) + } + errorClassNames.add(descriptor.name) + } + return bindings +} diff --git a/packages/code-runtime/code-runtime-node/src/bootstrap.ts b/packages/code-runtime/code-runtime-node/src/bootstrap.ts index 5a61c19290..acf876edb7 100644 --- a/packages/code-runtime/code-runtime-node/src/bootstrap.ts +++ b/packages/code-runtime/code-runtime-node/src/bootstrap.ts @@ -1,14 +1,12 @@ /** - * Worker-side execution logic, written as plain functions over an injected port so the unit - * suite can run every line IN-PROCESS against a fake port (a real worker thread is a separate - * V8 isolate the coverage provider cannot observe). + * Program evaluation, output capture, and host binding proxies over the process channel. * @module @deepseek-ai/dsh-code-runtime-node/src/bootstrap */ import { inspect } from 'node:util' -import type { DoneMessage, ReplyMessage, WorkerBootData, WorkerToHost } from './protocol.ts' +import type { DoneMessage, ReplyMessage, ProgramBootData, ProgramToHost } from './protocol.ts' import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from './output-json.ts' -import { decodeWorkerJson, encodeWorkerJson, snapshotCodeJsonValue } from './worker-json.ts' +import { decodeCodeJsonWire, encodeCodeJsonWire, snapshotCodeJsonValue } from './json-wire.ts' const CapturedError = Error const capturedObjectCreate = Object.create @@ -24,7 +22,7 @@ function defineBindingErrorField(error: Error, key: string, value: string): void /** The port API the bootstrap needs — satisfied by `parentPort` and by the tests' fake. */ export interface BootstrapPort { - postMessage(message: WorkerToHost): void + postMessage(message: ProgramToHost): void on(event: 'message', listener: (message: ReplyMessage) => void): void } @@ -121,7 +119,7 @@ export function makeConsoleShim(logs: LogBuffer): Record<(typeof CONSOLE_LEVELS) /** * Redirect a stream's `write` into the log buffer (the program-visible - * `process.stdout`/`process.stderr` in the real worker), so raw writes land in emission order + * `process.stdout`/`process.stderr` in the Node child), so raw writes land in emission order * alongside console output instead of racing down a pipe. It preserves Node's optional callback * contract: the callback runs asynchronously after admission, even when the log budget drops * the write. @@ -186,7 +184,7 @@ export function prepareCompletion( if (jsonValueBytesUpTo(snapshot, remainingOutputBytes) === undefined) { return outputLimit(maxOutputBytes) } - return { value: encodeWorkerJson(snapshot) } + return { value: encodeCodeJsonWire(snapshot) } } /** Build the fixed overflow fragment without carrying rejected variable bytes. */ @@ -265,7 +263,7 @@ function bindingFailure(errorClass: BindingErrorConstructor | undefined, memberN * @returns constructors keyed by their owning namespace global. */ export function makeBindingErrorClasses( - data: Pick, + data: Pick, ): Map { const classes = new Map() for (const namespace of data.namespaces) { @@ -278,7 +276,7 @@ export function makeBindingErrorClasses( * Route host replies into the pending-call map: each reply settles its call * at most once, and a reply for an unknown id (stray, or a duplicate answer * to an id already settled) is ignored. Shared wiring between - * {@link runWorkerMain} and the tests that exercise {@link makeNamespaces} + * {@link runProgram} and the tests that exercise {@link makeNamespaces} * standalone. * @param port - the port whose `message` events carry the replies. * @param pending - the id-keyed map of unsettled binding calls. @@ -289,7 +287,7 @@ export function wireReplies(port: BootstrapPort, pending: Map, + data: Pick, port: BootstrapPort, pending: Map, nextId: { value: number }, @@ -344,7 +342,7 @@ export function makeNamespaces( }, }) try { - port.postMessage({ type: 'call', id, global, name, args: encodeWorkerJson(detached) }) + port.postMessage({ type: 'call', id, global, name, args: encodeCodeJsonWire(detached) }) } catch (error: unknown) { pending.delete(id) const message = `binding arguments must be structured-cloneable: ${error instanceof CapturedError ? error.message : String(error)}` @@ -366,9 +364,9 @@ export function makeNamespaces( * @param streams - stdout/stderr objects captured as program logs. * @returns after posting the done message. */ -export async function runWorkerMain( +export async function runProgram( port: BootstrapPort, - data: WorkerBootData, + data: ProgramBootData, streams: { stdout: PatchableStream; stderr: PatchableStream }, ): Promise { const logs = new LogBuffer( diff --git a/packages/code-runtime/code-runtime-node/src/channel.ts b/packages/code-runtime/code-runtime-node/src/channel.ts new file mode 100644 index 0000000000..1d6c2eea03 --- /dev/null +++ b/packages/code-runtime/code-runtime-node/src/channel.ts @@ -0,0 +1,124 @@ +/** Length-prefixed JSON transport with bounded input and queued writes. */ +import { Buffer } from 'node:buffer' +import type { Duplex } from 'node:stream' +import type { CodeJsonValue } from '@deepseek-ai/dsh-code-runtime' +import { jsonValueBytesUpTo } from './output-json.ts' + +const stringify = JSON.stringify +const parse = JSON.parse + +/** One co-shipped process channel; the consumer owns frame validation and terminal outcomes. */ +export class JsonChannel { + private readonly stream: Duplex + private readonly maxBytes: number + private readonly receive: (message: unknown, bytes: number) => void + private readonly failure: (error: Error, kind: 'io' | 'protocol') => void + private readonly header = Buffer.alloc(4) + private headerBytes = 0 + private payload: Buffer | undefined + private payloadBytes = 0 + private queuedBytes = 0 + private closed = false + private tail: Promise = Promise.resolve() + + constructor( + stream: Duplex, + maxBytes: number, + receive: (message: unknown, bytes: number) => void, + failure: (error: Error, kind: 'io' | 'protocol') => void, + ) { + this.stream = stream + this.maxBytes = maxBytes + this.receive = receive + this.failure = failure + stream.on('data', this.onData) + stream.on('error', this.onError) + stream.on('end', this.onEnd) + } + + private readonly onError = (error: Error): void => { if (!this.closed) this.failure(error, 'io') } + private readonly onEnd = (): void => { if (!this.closed) this.failure(new Error('control channel ended before the program settled'), 'io') } + private readonly onData = (chunk: Buffer): void => { + if (this.closed) return + try { + let offset = 0 + while (offset < chunk.length && !this.closed) { + if (this.payload === undefined) { + const bytes = Math.min(4 - this.headerBytes, chunk.length - offset) + chunk.copy(this.header, this.headerBytes, offset, offset + bytes) + this.headerBytes += bytes + offset += bytes + if (this.headerBytes !== 4) continue + const length = this.header.readUInt32BE(0) + if (length === 0 || length > this.maxBytes) throw new Error(`control frame exceeds ${this.maxBytes} bytes or is empty`) + this.payload = Buffer.allocUnsafe(length) + this.payloadBytes = 0 + this.headerBytes = 0 + } + const bytes = Math.min(this.payload.length - this.payloadBytes, chunk.length - offset) + chunk.copy(this.payload, this.payloadBytes, offset, offset + bytes) + this.payloadBytes += bytes + offset += bytes + if (this.payloadBytes !== this.payload.length) continue + const frame = this.payload + this.payload = undefined + this.payloadBytes = 0 + this.receive(parse(new TextDecoder('utf-8', { fatal: true }).decode(frame)), frame.length) + } + } catch (error: unknown) { + this.failure(error instanceof Error ? error : new Error(String(error)), 'protocol') + } + } + + /** + * Queue a bounded frame and honor stream backpressure. + * @param message - JSON-only co-shipped protocol value. + * @returns Resolves when this frame has been written, or rejects after transport failure. + */ + send(message: unknown): Promise { + if (this.closed) return Promise.reject(new Error('control channel is closed')) + const size = jsonValueBytesUpTo(message as CodeJsonValue, this.maxBytes) + if (size === undefined || this.queuedBytes + size > this.maxBytes) { + return Promise.reject(new Error(`control output exceeds ${this.maxBytes} queued bytes`)) + } + const body = Buffer.from(stringify(message), 'utf8') + const header = Buffer.alloc(4) + header.writeUInt32BE(body.length) + this.queuedBytes += body.length + const write = async (): Promise => { + if (this.closed) throw new Error('control channel is closed') + await new Promise((resolve, reject) => { + const stop = (error?: Error): void => { + this.stream.off('error', onError) + this.stream.off('close', onClose) + if (error) reject(error) + else resolve() + } + const onError = (error: Error): void => { stop(error) } + const onClose = (): void => { stop(new Error('control channel closed during a write')) } + this.stream.once('error', onError) + this.stream.once('close', onClose) + this.stream.cork() + this.stream.write(header) + this.stream.write(body, (error) => { stop(error ?? undefined) }) + this.stream.uncork() + }) + } + const result = this.tail.then(write).finally(() => { this.queuedBytes -= body.length }) + this.tail = result.catch(() => {}) + return result + } + + /** Stop reads and close the owned endpoint; pending writes reject on closure. */ + close(): void { + if (this.closed) return + this.closed = true + this.payload = undefined + this.stream.off('data', this.onData) + this.stream.off('end', this.onEnd) + this.stream.destroy() + } + + /** Wait for accepted writes to finish or fail. */ + async drain(): Promise { await this.tail } +} diff --git a/packages/code-runtime/code-runtime-node/src/index.ts b/packages/code-runtime/code-runtime-node/src/index.ts index c55237ccae..ae54718bc9 100644 --- a/packages/code-runtime/code-runtime-node/src/index.ts +++ b/packages/code-runtime/code-runtime-node/src/index.ts @@ -1,560 +1,308 @@ -/** - * Worker-thread code runtime: a fresh worker runs each host-type-stripped TypeScript program - * and bridges bindings over its message port. This is containment, not a security boundary: - * model code has bash-equivalent trust despite an empty environment, a heap cap, measured - * event-loop busy-time and wall-time budgets, and termination that also stops synchronous loops. - * @module @deepseek-ai/dsh-code-runtime-node - */ - -import { Worker } from 'node:worker_threads' +/** Confined Node programs with host-owned bindings, output limits, and managed process cleanup. */ import { stripTypeScriptTypes } from 'node:module' -import type { Readable } from 'node:stream' -import { fileURLToPath } from 'node:url' +import { isAbsolute } from 'node:path' +import { StringDecoder } from 'node:string_decoder' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' -import { CodeRuntime, DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-code-runtime' -import type { CodeBindingNamespace, CodeJsonValue, CodeRunFailure, CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' +import type { CodeBindingNamespace, CodeJsonValue, CodeRunFailure, CodeRunRequest, CodeRunResult, CodeRunSandbox, CodeRunSpec } from '@deepseek-ai/dsh-code-runtime' +import { MAX_TIMER_DELAY_MS, clampTimeout } from '@deepseek-ai/dsh-timeout' +import { SandboxUnavailableError, classifyRunnerFailure, isRunnerSpawnFailure } from '@deepseek-ai/dsh-sandbox' +import type { ConfinedArgv, SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' +import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess' +import type {} from '@deepseek-ai/dsh-sandbox-policy' +import type {} from '@deepseek-ai/dsh-fs' import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values' -import type { ReplyMessage, WorkerBootData, WorkerToHost } from './protocol.ts' -import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from './output-json.ts' -import { decodeWorkerJson, encodeWorkerJson } from './worker-json.ts' -import type { WorkerJsonWire } from './worker-json.ts' +import { validateBindings } from './bindings.ts' +import { JsonChannel } from './channel.ts' +import { bootstrapArgs } from './launch.ts' +import type { LaunchConfig } from './launch.ts' +import { OutputLedger } from './output-ledger.ts' +import { decodeCodeJsonWire, encodeCodeJsonWire } from './json-wire.ts' +import type { ProgramBootData } from './protocol.ts' -/** Plugin config: every execution cap, changeable from `cordis.yml` (no hardcoded tunables). */ -export interface Config { - /** - * Busy-time budget in milliseconds: the run fails with kind `'timeout'` - * once the worker's MEASURED event-loop active time - * (`worker.performance.eventLoopUtilization()`) exceeds this. Metering - * measured busy time — not wall time, not host-side pending-call - * bookkeeping — is what makes the budget both fair (a program awaiting a - * slow tool accrues nothing) and ungameable (a hot loop accrues whether - * or not a decoy dispatch is in flight). - */ - computeMs?: number - /** - * Wall-clock ceiling in milliseconds; never pauses for anything. The - * backstop for what busy-time cannot see (a program awaiting a promise - * nobody will resolve). At most `2_147_483_647` (Node's maximum - * `setTimeout` delay, about 24.9 days): a longer value is rejected at load - * because `setTimeout` would clamp it to 1 ms. - */ - maxWallMs?: number - /** - * Hard cap for serialized log-array, completion-value, and failure-message payloads; - * fixed result-envelope syntax is excluded. - */ +/** Deployment-varying runtime bounds and launch choices. */ +export interface Config extends LaunchConfig { + /** Default elapsed deadline, including nested tool and approval waits. */ + timeoutMs?: number + /** Maximum elapsed deadline accepted by resolve. */ + maxTimeoutMs?: number + /** Combined serialized logs, completion and diagnostic byte cap. */ maxOutputBytes?: number - /** The worker's max old-generation heap in MiB (`resourceLimits`); overflow kills the worker, surfacing as kind `'worker-exit'`. */ + /** V8 old-generation heap limit in MiB; native allocations are excluded. */ maxOldGenerationSizeMb?: number + /** Maximum control frame, outstanding argument and queued control-output bytes. */ + maxMessageBytes?: number + /** Maximum simultaneous host binding calls accepted from a program. */ + maxPendingCalls?: number + /** Managed process termination and output-drain grace in milliseconds. */ + graceMs?: number } -/** {@link Config} after schemastery fills the defaults (every field present). */ -type ResolvedConfig = Required +type ResolvedConfig = Required> & Pick +interface LiveRun { controller: AbortController; finished: Promise } +const STRIP_PREFIX = 'async function __dsh_program__() {\n' +const STRIP_SUFFIX = '\n}' -/** - * How often the host samples the worker's event-loop utilization for the - * `computeMs` budget. An internal cadence, not config: the only effect of - * the interval is budget-expiry granularity (a run can overshoot by up to - * one interval), and nothing a deployment could tune here improves that - * without burning host CPU. - */ -const ELU_POLL_INTERVAL_MS = 25 +function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error) } +function record(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } -/** Smallest cap that can represent the counted payloads: an empty logs array plus an empty JSON failure message. */ -const MIN_OUTPUT_BYTES = 4 - -/** - * The seam's language-portable identifier subset (see - * `CodeBindingNamespace.global`): no `$`, which is JS-only spelling — the same - * namespace list must be usable against every backend regardless of language. - */ -const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/ - -/** - * The shell a program is wrapped in for the type-strip, matching the - * grammatical context it will execute in (an async function body, where - * top-level `return` and `await` are legal — a bare module parse would - * reject the `return`). Strip mode is position-preserving (removed syntax - * becomes whitespace, nothing shifts), so the wrapper survives the strip - * byte-identical and the body slices back out with the model's own - * line/column positions intact. - */ -const STRIP_WRAP = { prefix: 'async function __dsh_program__() {\n', suffix: '\n}' } as const - -/** One in-flight run's host-side state, tracked for disposal. */ -interface LiveRun { - worker: Worker - settle(failure: CodeRunFailure): void - finished: Promise -} - -/** - * The worker entry path. Source runs unbuilt (`src/worker.ts`, loadable - * directly on this repo's Node range via native type stripping — the file - * is erasable-only with type-only relative imports); the built package - * ships it as a sibling CommonJS bundle (`lib/worker.cjs`, its own tsdown - * entry) because pkg's VFS Worker hook compiles string-path entries as - * CommonJS. - * The URL *pathname*'s extension says which world this module is in — - * pathname, because dev-time module runners (vitest) may suffix - * `import.meta.url` with a query string; relative resolution drops it. Worker - * receives a filesystem string so pkg's VFS Worker hook can resolve it. - */ -/* v8 ignore next -- the './worker.cjs' arm is the built-lib world, unreachable unbuilt by construction; the built-lib e2e pins it. */ -const WORKER_PATH = fileURLToPath(new URL(new URL(import.meta.url).pathname.endsWith('.ts') ? './worker.ts' : './worker.cjs', import.meta.url)) - -/** Render an unknown thrown value as a message, `Error` or not. */ -function messageOf(error: unknown): string { - return error instanceof Error ? error.message : String(error) -} - -/** Resolve after a worker pipe emits all queued data, or closes/errors during termination. */ -function waitForPipeDrain(stream: Readable): Promise { - if (stream.readableEnded || stream.destroyed) return Promise.resolve() - return new Promise((resolve) => { - const done = (): void => { - stream.off('end', done) - stream.off('close', done) - stream.off('error', done) - resolve() - } - stream.once('end', done) - stream.once('close', done) - stream.once('error', done) - // Close the event-registration race if termination finished between the - // initial state check and the listeners above. - /* v8 ignore next -- this race cannot be scheduled deterministically between the adjacent state check and listener registration. */ - if (stream.readableEnded || stream.destroyed) done() - }) -} - -/** - * Runtime shape gate for inbound port traffic. The peer runs MODEL CODE and - * can post anything — `null`, primitives, objects with poisoned fields — so - * the compile-time `WorkerToHost` type means nothing here: everything is - * re-validated and REBUILT field by field (a forged extra field never rides - * along; a non-number call id can never be echoed into a reply). Junk returns - * `undefined` and is dropped — a throw in the host's `message` listener would - * crash the host process. - */ -function parseWorkerMessage(raw: unknown): WorkerToHost | undefined { - if (typeof raw !== 'object' || raw === null) return undefined - const m = raw as Record - switch (m.type) { - case 'call': { - if (typeof m.id !== 'number' || typeof m.global !== 'string' || typeof m.name !== 'string') return undefined - return { type: 'call', id: m.id, global: m.global, name: m.name, args: m.args as WorkerJsonWire } - } - case 'log': { - if (typeof m.text !== 'string') return undefined - return { type: 'log', text: m.text } - } - case 'output-limit': return { type: 'output-limit' } - case 'done': { - if (m.error === undefined) return { type: 'done', ...m.value !== undefined ? { value: m.value as WorkerJsonWire } : {} } - const error = m.error - if (typeof error !== 'object' || error === null) return undefined - const { kind, message } = error as Record - if ((kind !== 'exception' && kind !== 'invalid-output' && kind !== 'output-limit') || typeof message !== 'string') return undefined - return { type: 'done', error: { kind, message } } - } - default: return undefined - } -} - - -/** One run's combined outer-output ledger; binding values never enter it. */ -class OutputLedger { - private bytes = 2 // JSON serialization of the empty logs array: [] - private entries = 0 - - constructor(private readonly maxBytes: number) {} - - /** Admit one exact log entry, or report that the hard cap was crossed. */ - admit(text: string, sink: string[]): boolean { - const separatorBytes = this.entries > 0 ? 1 : 0 - const stringBytes = jsonStringBytesUpTo(text, this.maxBytes - this.bytes - separatorBytes) - if (stringBytes === undefined) return false - this.bytes += stringBytes + separatorBytes - this.entries += 1 - sink.push(text) - return true - } - - /** Finalize a successful absent-or-JSON completion against the combined cap. */ - success(logs: string[], value?: CodeJsonValue): CodeRunResult { - if (value !== undefined && jsonValueBytesUpTo(value, this.maxBytes - this.bytes) === undefined) return this.limit(logs) - return { logs, ...value !== undefined ? { value } : {} } - } - - /** Finalize a failure diagnostic, with output-limit taking precedence when combined bytes exceed the cap. */ - failure(logs: string[], error: CodeRunFailure): CodeRunResult { - if (jsonStringBytesUpTo(error.message, this.maxBytes - this.bytes) === undefined) return this.limit(logs) - return { logs, error } - } - - /** Build the explicit output-limit failure while retaining a fitting prefix of the final log. */ - limit(logs: string[]): CodeRunResult { - const fullMessage = `outer output exceeded ${this.maxBytes} bytes` - // The fixed diagnostic is ASCII, so every character is one byte plus the quotes. - const messageBytes = fullMessage.length + 2 - const retained: string[] = [] - let retainedBytes = 2 - const logBudget = this.maxBytes - messageBytes - for (const text of logs) { - const separatorBytes = retained.length > 0 ? 1 : 0 - const availableBytes = logBudget - retainedBytes - separatorBytes - const stringBytes = jsonStringBytesUpTo(text, availableBytes) - if (stringBytes !== undefined) { - retained.push(text) - retainedBytes += stringBytes + separatorBytes - continue - } - const prefix = truncateJsonStringBytes(text, availableBytes) - if (prefix.length > 0) { - const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes) - /* v8 ignore next -- truncateJsonStringBytes guarantees its returned prefix fits the same budget. */ - if (prefixBytes === undefined) throw new Error('output ledger produced an oversized log prefix') - retained.push(prefix) - retainedBytes += prefixBytes + separatorBytes - } - break - } - const availableMessageBytes = this.maxBytes - retainedBytes - const message = truncateJsonStringBytes(fullMessage, availableMessageBytes) - return { logs: retained, error: { kind: 'output-limit', message } } - } -} - -/** - * The shipped {@link CodeRuntime} backend (`ctx.codeRuntime`). Registers as - * the `codeRuntime` service; every cap comes from validated config. See the - * module doc for the containment model and the Service Definition's class JSDoc for - * the contract this implements (error-as-field, hostile-peer port, - * no cross-run state, dispose to quiescence). - */ +/** Node provider; direct file effects use the same sandbox service as Bash. */ export class NodeCodeRuntime extends CodeRuntime { + static inject = ['fs', 'subprocess', 'sandbox', 'sandboxPolicy'] static Config: z = z.object({ - computeMs: z.number().default(60_000), - maxWallMs: z.number().default(600_000), + timeoutMs: z.number().default(120_000), + maxTimeoutMs: z.number().default(600_000), maxOutputBytes: z.number().default(67_108_864), maxOldGenerationSizeMb: z.number().default(512), + maxMessageBytes: z.number().default(134_217_728), + maxPendingCalls: z.number().default(128), + graceMs: z.number().default(3_000), + nodeExecutable: z.string(), + bootstrapPath: z.string(), }) - readonly language = 'typescript' - readonly isolation = 'worker-thread' - + readonly isolation = 'process' private readonly config: ResolvedConfig private readonly live = new Set() private disposed = false constructor(ctx: Context, config: Config) { super(ctx) - // Schemastery filled the defaults; the cast records that. Positivity is a - // semantic check the schema's plain number type does not carry. - this.config = config as ResolvedConfig + this.config = { ...config, nodeExecutable: config.nodeExecutable ?? process.execPath } as ResolvedConfig for (const [key, value] of Object.entries(this.config)) { - if (!(Number.isFinite(value) && value > 0)) throw new Error(`dsh-code-runtime-node: config.${key} must be a positive number, got ${String(value)}`) + if (typeof value === 'number' && (!Number.isFinite(value) || value <= 0)) throw new Error(`code-runtime-node: ${key} must be positive and finite`) } - if (!Number.isSafeInteger(this.config.maxOutputBytes) || this.config.maxOutputBytes < MIN_OUTPUT_BYTES) { - throw new Error(`dsh-code-runtime-node: config.maxOutputBytes must be a safe integer of at least ${MIN_OUTPUT_BYTES}, got ${String(this.config.maxOutputBytes)}`) + for (const key of ['timeoutMs', 'maxTimeoutMs', 'graceMs'] as const) { + if (this.config[key] > MAX_TIMER_DELAY_MS) throw new Error(`code-runtime-node: ${key} exceeds the supported timer range`) } - // maxWallMs reaches setTimeout, which clamps any delay above - // MAX_TIMER_DELAY_MS to 1 ms; the positivity check above accepts such a - // value, so a 25-day ceiling would time the run out immediately. - if (this.config.maxWallMs > MAX_TIMER_DELAY_MS) { - throw new Error(`dsh-code-runtime-node: config.maxWallMs must be at most ${MAX_TIMER_DELAY_MS} (Node clamps a longer setTimeout delay to 1ms), got ${String(this.config.maxWallMs)}`) + if (!Number.isSafeInteger(this.config.maxOutputBytes) || this.config.maxOutputBytes < 4) throw new Error('code-runtime-node: maxOutputBytes must be an integer of at least 4') + if (!Number.isSafeInteger(this.config.maxMessageBytes) || this.config.maxMessageBytes > 0xffff_ffff) throw new Error('code-runtime-node: maxMessageBytes must fit an unsigned 32-bit frame length') + if (!Number.isSafeInteger(this.config.maxPendingCalls)) throw new Error('code-runtime-node: maxPendingCalls must be an integer') + if (!Number.isSafeInteger(this.config.maxOldGenerationSizeMb)) throw new Error('code-runtime-node: maxOldGenerationSizeMb must be an integer') + if (this.config.nodeExecutable.length === 0) throw new Error('code-runtime-node: nodeExecutable must be non-empty') + if (this.config.bootstrapPath !== undefined && !isAbsolute(this.config.bootstrapPath)) throw new Error('code-runtime-node: bootstrapPath must be absolute') + ctx.effect(() => async () => { + this.disposed = true + const active = [...this.live] + for (const run of active) run.controller.abort('runtime disposed') + await Promise.all(active.map(run => run.finished)) + }, 'Node code-runtime cleanup') + } + + override get sandboxMode(): SandboxMode { return this.ctx.sandboxPolicy.defaultMode } + + /** + * Resolve an execution under explicit or deployment policy. + * @param request - Program, bindings, optional cwd/deadline, and resolved authority. + * @returns Complete execution inputs with a capped deadline. + */ + resolve(request: CodeRunRequest): CodeRunSpec { + const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve() + const cwd = request.cwd ?? sandboxPolicy.workspaceRoot + if (!isAbsolute(cwd)) throw new Error('code-runtime-node: cwd must be absolute') + return { + ...request, + cwd, + timeoutMs: clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, 'code-runtime-node: timeoutMs'), + sandboxPolicy, } - ctx.effect(() => () => this.teardown(), 'worker code-runtime teardown') } /** - * Dispose to quiescence: mark the service unusable, fail every in-flight - * run as aborted, and AWAIT each worker's exit so no worker outlives the - * fiber. + * Run a resolved program in a fresh managed and confined Node process. + * @param spec - Inputs returned by resolve; missing authority is caller misuse. + * @returns Output and file-confinement facts after managed cleanup. */ - private async teardown(): Promise { - this.disposed = true - const runs = [...this.live] - for (const run of runs) run.settle({ kind: 'abort', message: 'runtime disposed' }) - await Promise.all(runs.map(run => run.finished)) - } - - /** - * Execute one program in a fresh worker. Program outcomes — including a - * type-strip syntax error, which never spawns a worker — resolve with - * `result.error`; the method rejects only for Service Definition contract misuse (a disposed - * runtime, an invalid binding namespace). - * @param request - the program, its bindings, and the abort signal. - * @returns the run's outcome per the seam contract. - */ - async run(request: CodeRunRequest): Promise { - if (this.disposed) throw new Error('dsh-code-runtime-node: run() after disposal') - const bindings = this.validateBindings(request) - if (request.signal?.aborted) { - return this.failureBeforeWorker({ kind: 'abort', message: String(request.signal.reason) }) - } - - let code: string + async run(spec: CodeRunSpec): Promise { + if (this.disposed) throw new Error('code-runtime-node: run after disposal') + if (spec.sandboxPolicy === undefined) throw new Error('code-runtime-node: run requires a resolved sandbox policy') + if (!isAbsolute(spec.cwd) || !Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs) throw new Error('code-runtime-node: run requires resolved cwd and timeout') + const bindings = validateBindings(spec) + const controller = new AbortController() + const completion = Promise.withResolvers() + const live = { controller, finished: completion.promise } + this.live.add(live) try { - const stripped = stripTypeScriptTypes(STRIP_WRAP.prefix + request.program + STRIP_WRAP.suffix) - code = stripped.slice(STRIP_WRAP.prefix.length, stripped.length - STRIP_WRAP.suffix.length) - } catch (error: unknown) { - // A program that does not survive the type-strip (syntax error, - // non-erasable syntax like `enum`) is a program failure, reported the - // same way a thrown exception would be — and no worker ever spawns. - return this.failureBeforeWorker({ kind: 'exception', message: messageOf(error) }) + return await this.execute(spec, spec.sandboxPolicy, bindings, controller) + } finally { + this.live.delete(live) + completion.resolve() } - - return await this.execute(request, code, bindings) } - /** Apply the outer-output ledger to failures that occur before a worker owns one. */ - private failureBeforeWorker(error: CodeRunFailure): CodeRunResult { - return new OutputLedger(this.config.maxOutputBytes).failure([], error) - } - - /** Reject malformed binding globals or typed-error declarations as Service Definition contract misuse. */ - private validateBindings(request: CodeRunRequest): Map { - const bindings = new Map() - for (const namespace of request.bindings) { - if (!IDENTIFIER.test(namespace.global) || PORTABLE_RESERVED_WORDS.has(namespace.global)) { - throw new Error(`dsh-code-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`) - } - // RESERVED_BINDING_GLOBALS is the seam's shared backend-owned set: - // `console` is THIS backend's log-capture slot; the dunder entries exist - // for the Python side — its seeded/wrapped slots plus the `__debug__` - // compile-time constant — refused here too so the namespace list stays - // portable across backends. The seam declaration is the single home for - // why each entry is reserved. - if (RESERVED_BINDING_GLOBALS.has(namespace.global)) { - throw new Error(`dsh-code-runtime-node: reserved binding global ${JSON.stringify(namespace.global)}`) - } - if (bindings.has(namespace.global)) { - throw new Error(`dsh-code-runtime-node: duplicate binding global ${JSON.stringify(namespace.global)}`) - } - bindings.set(namespace.global, namespace) - } - - const errorClassNames = new Set() - for (const namespace of request.bindings) { - const descriptor = namespace.errorClass - if (!descriptor) continue - if (!IDENTIFIER.test(descriptor.name) || PORTABLE_RESERVED_WORDS.has(descriptor.name)) { - throw new Error(`dsh-code-runtime-node: binding error class ${JSON.stringify(descriptor.name)} is not a usable identifier`) - } - if (RESERVED_BINDING_GLOBALS.has(descriptor.name)) { - throw new Error(`dsh-code-runtime-node: reserved binding global ${JSON.stringify(descriptor.name)}`) - } - if (bindings.has(descriptor.name) || errorClassNames.has(descriptor.name)) { - throw new Error(`dsh-code-runtime-node: duplicate injected global ${JSON.stringify(descriptor.name)}`) - } - const member = descriptor.memberNameProperty - if (member.length === 0 || RESERVED_ERROR_MEMBERS.has(member) || DUNDER_MEMBER.test(member)) { - throw new Error(`dsh-code-runtime-node: binding error member property ${JSON.stringify(descriptor.memberNameProperty)} is not usable`) - } - errorClassNames.add(descriptor.name) - } - return bindings - } - - /** Spawn the worker for one validated, type-stripped run and drive it to settlement. */ - private execute( - request: CodeRunRequest, - code: string, + private async execute( + spec: CodeRunSpec, + policy: SandboxExecutionPolicy, bindings: Map, + controller: AbortController, ): Promise { - const bootData: WorkerBootData = { - code, - namespaces: [...bindings].map(([global, namespace]) => ({ - global, - names: Object.keys(namespace.functions), - ...namespace.errorClass ? { errorClass: namespace.errorClass } : {}, - })), - maxOutputBytes: this.config.maxOutputBytes, - } - const worker = new Worker(WORKER_PATH, { - workerData: bootData, - // Model code gets NO ambient environment — stronger than the scrubbed - // env the defensive-patterns rule requires for spawned commands. - env: {}, - // Hermetic flags too: without this the worker inherits the host process's execArgv (a - // test runner's or tsx's loader hooks), which a bare isolate with an empty environment - // cannot satisfy. - execArgv: [], - resourceLimits: { maxOldGenerationSizeMb: this.config.maxOldGenerationSizeMb }, - // Backstop capture: the bootstrap patches JS-level writes into its own - // ordered buffer, so these pipes normally stay silent; anything that - // still arrives (native-level writes) is appended after the done logs. - stdout: true, - stderr: true, - }) - - return new Promise((resolve) => { - let settled = false - const answered = new Set() - const logs: string[] = [] - const strayLogs: string[] = [] - const output = new OutputLedger(this.config.maxOutputBytes) - let terminalOverride: CodeRunResult | undefined - - // Pipe and message-port delivery are independent. Continue bounded pipe - // capture after a terminal message while worker termination drains bytes - // that were already queued; `finish` materializes the result only after - // termination completes. - const captureStray = (chunk: Buffer): void => { - /* v8 ignore next -- a second post-overflow chunk races immediate worker termination; the first overflow path is covered. */ - if (terminalOverride !== undefined) return - const text = chunk.toString('utf8') - if (!output.admit(text, strayLogs)) { - const limited = output.limit([...logs, ...strayLogs, text]) - terminalOverride = limited - finish(limited) - } - } - worker.stdout.on('data', captureStray) - worker.stderr.on('data', captureStray) - - // Exactly one outcome wins. Every path cleans up, terminates, and awaits the worker; - // logs captured before timeout, abort, or failure remain in the result. - let finishResolve!: () => void - const finished = new Promise((done) => { finishResolve = done }) - const finish = (finalize: CodeRunResult | (() => CodeRunResult)): void => { - if (settled) return - settled = true - clearInterval(eluTimer) - clearTimeout(wallTimer) - request.signal?.removeEventListener('abort', onAbort) - this.live.delete(live) - // Let the poll phase deliver pipe bytes already queued independently - // of the terminal port message before termination closes the streams. - void new Promise((resume) => { setImmediate(resume) }).then(async () => { - const stdoutDrained = waitForPipeDrain(worker.stdout) - const stderrDrained = waitForPipeDrain(worker.stderr) - await Promise.all([worker.terminate(), stdoutDrained, stderrDrained]) - const result = terminalOverride ?? (typeof finalize === 'function' ? finalize() : finalize) - finishResolve() - resolve(result) - }) - } - - const onDone = (message: WorkerToHost): void => { - if (message.type !== 'done') return - if (message.error) { - const error = message.error - finish(() => output.failure([...logs, ...strayLogs], error)) - return - } - if (message.value === undefined) { - finish(() => output.success([...logs, ...strayLogs])) - return - } - const value = decodeWorkerJson(message.value) - if (value === undefined) { - finish(() => output.failure([...logs, ...strayLogs], { kind: 'invalid-output', message: 'program completion must be lossless JSON' })) - } else { - finish(() => output.success([...logs, ...strayLogs], value)) - } - } - - const onCall = (message: WorkerToHost): void => { - if (message.type !== 'call' || settled) return - // Hostile-peer rules: a duplicate id is ignored, an unknown name is - // answered with a failure, and a binding throw/reject becomes the - // program-side rejection — contained here, never a host crash. - if (answered.has(message.id)) return - answered.add(message.id) - const reply = (payload: ReplyMessage): void => { - if (settled) return - // Canonical resolutions were snapshotted as lossless JSON before - // this point, so this payload is structured-cloneable by contract. - worker.postMessage(payload) - } - const record = bindings.get(message.global)?.functions - // Own-property lookup only: a forged name like 'constructor' or - // 'hasOwnProperty' must not walk the record's prototype chain and - // reach a callable the consumer never declared. - const fn = record && Object.hasOwn(record, message.name) ? record[message.name] : undefined - if (typeof fn !== 'function') { - reply({ type: 'reply', id: message.id, ok: false, message: `unknown binding ${JSON.stringify(`${message.global}.${message.name}`)}` }) - return - } - const args = decodeWorkerJson(message.args) - if (args === undefined) { - reply({ type: 'reply', id: message.id, ok: false, message: 'binding arguments must be lossless JSON' }) - return - } - void (async () => { + const output = new OutputLedger(this.config.maxOutputBytes) + const logs: string[] = [] + const sandbox: CodeRunSandbox = { mode: policy.mode, denied: false } + const result = Promise.withResolvers() + const signal = spec.signal === undefined ? controller.signal : AbortSignal.any([spec.signal, controller.signal]) + let handle: SubprocessHandle | undefined + let channel: JsonChannel | undefined + let confined: ConfinedArgv | undefined + let settled = false + let timedOut = false + let outputOverflow = false + let stderr = '' + let parsing = true + const wallTimer = setTimeout(() => { timedOut = true; controller.abort('execution deadline reached') }, spec.timeoutMs) + const finish = (failure?: CodeRunFailure, value?: CodeJsonValue): void => { + if (settled) return + settled = true + clearTimeout(wallTimer) + signal.removeEventListener('abort', onAbort) + channel?.close() + void (async () => { + if (handle !== undefined) { + handle.terminate() try { - const resolved = await fn(args) - let value: CodeJsonValue | undefined - try { - value = snapshotJsonValue(resolved) - } catch { - value = undefined - } - if (value === undefined) { - reply({ type: 'reply', id: message.id, ok: false, message: 'binding resolution must be lossless JSON' }) - } else { - reply({ type: 'reply', id: message.id, ok: true, value: encodeWorkerJson(value) }) - } + await Promise.all([handle.done.catch(() => {}), handle.waitForExit()]) } catch (error: unknown) { - reply({ type: 'reply', id: message.id, ok: false, message: messageOf(error) }) + failure = { kind: 'worker-exit', message: `managed process cleanup failed: ${messageOf(error)}` } + } finally { + handle.stdout?.destroy() + handle.stderr?.destroy() } - })() + } + const outcome = outputOverflow ? output.limit(logs) + : failure === undefined ? output.success(logs, value) : output.failure(logs, failure) + result.resolve({ ...outcome, sandbox: { ...sandbox } }) + })() + } + const onAbort = (): void => { + finish(timedOut + ? { kind: 'timeout', message: `execution deadline reached (${spec.timeoutMs}ms)` } + : { kind: 'abort', message: messageOf(signal.reason) }) + } + signal.addEventListener('abort', onAbort, { once: true }) + if (signal.aborted) onAbort() + try { + if (settled) return await result.promise + const stripped = stripTypeScriptTypes(STRIP_PREFIX + spec.program + STRIP_SUFFIX) + parsing = false + const data: ProgramBootData = { + code: stripped.slice(STRIP_PREFIX.length, stripped.length - STRIP_SUFFIX.length), + namespaces: [...bindings.values()].map(binding => ({ + global: binding.global, + names: Object.keys(binding.functions), + ...binding.errorClass ? { errorClass: binding.errorClass } : {}, + })), + maxOutputBytes: this.config.maxOutputBytes, } - - worker.on('message', (raw: unknown) => { - // Parse before touching: the peer can post ANY shape, and a throw in - // this listener would crash the host process. Junk drops silently. - const message = parseWorkerMessage(raw) - if (!message) return - if (message.type === 'log' && !settled && !output.admit(message.text, logs)) { - const limited = output.limit([...logs, ...strayLogs, message.text]) - finish(limited) + const executable = await this.ctx.subprocess.resolveExecutable(this.config.nodeExecutable, undefined, signal) + if (settled) return await result.promise + const argv = [executable, `--max-old-space-size=${this.config.maxOldGenerationSizeMb}`, ...bootstrapArgs(this.ctx.fs, this.config, this.config.maxMessageBytes)] + confined = policy.mode === 'danger-full-access' ? undefined : this.ctx.sandbox.confine(argv, { ...policy, mode: policy.mode }) + if (confined !== undefined) sandbox.enforcement = confined.enforcement + const env: NodeJS.ProcessEnv = Object.fromEntries(Object.keys(process.env).map(key => [key, undefined])) + if ('pkg' in process && this.config.bootstrapPath === undefined) env.DSH_CODE_RUNTIME_NODE = '1' + handle = this.ctx.subprocess.spawn({ argv: confined?.argv ?? argv, cwd: spec.cwd, env, stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', control: 'pipe' }, graceMs: this.config.graceMs, signal }) + const launched = handle + if (launched.control === undefined) throw new Error('subprocess provider did not supply the requested control channel') + const admit = (text: string): void => { + if (outputOverflow || text.length === 0) return + if (!output.admit(text, logs)) { + outputOverflow = true + finish({ kind: 'output-limit', message: `outer output exceeded ${this.config.maxOutputBytes} bytes` }) + } + } + const stdoutDecoder = new StringDecoder('utf8') + const stderrDecoder = new StringDecoder('utf8') + handle.stdout?.on('data', (chunk: Buffer) => { admit(stdoutDecoder.write(chunk)) }) + handle.stdout?.on('end', () => { admit(stdoutDecoder.end()) }) + handle.stderr?.on('data', (chunk: Buffer) => { + const text = stderrDecoder.write(chunk) + stderr = (stderr + text).slice(-this.config.maxOutputBytes) + admit(text) + }) + handle.stderr?.on('end', () => { admit(stderrDecoder.end()) }) + let ready = false + let nextId = 1 + let pending = 0 + let pendingBytes = 0 + const protocolFailure = (message: string): void => { finish({ kind: 'protocol', message }) } + const processFinished = (outcome: SubprocessOutcome): void => { + if (settled) return + finish((confined !== undefined && classifyRunnerFailure(outcome.exitCode, stderr, confined.runnerFailureRules) !== undefined) + ? { kind: 'sandbox-unavailable', message: stderr } + : { kind: 'worker-exit', message: `Node process exited before completing (${String(outcome.exitCode)})${stderr ? `: ${stderr}` : ''}` }) + } + const transport: JsonChannel = new JsonChannel(launched.control, this.config.maxMessageBytes, (raw, bytes) => { + if (settled) return + if (!record(raw)) { protocolFailure('invalid control frame'); return } + if (!ready) { + if (raw.type !== 'ready') { protocolFailure('program frame arrived before bootstrap readiness'); return } + ready = true + void transport.send({ type: 'boot', data }).catch((error) => { protocolFailure(messageOf(error)) }) return } - if (message.type === 'output-limit' && !settled) { - const limited = output.limit([...logs, ...strayLogs]) - finish(limited) - return + switch (raw.type) { + case 'log': + if (typeof raw.text !== 'string') { protocolFailure('invalid log frame'); return } + admit(raw.text) + return + case 'output-limit': outputOverflow = true; finish(); return + case 'done': { + if (raw.error !== undefined) { + if (!record(raw.error) || typeof raw.error.message !== 'string' || (raw.error.kind !== 'exception' && raw.error.kind !== 'invalid-output' && raw.error.kind !== 'output-limit')) { protocolFailure('invalid terminal error'); return } + const failure = { kind: raw.error.kind, message: raw.error.message } as CodeRunFailure + if (confined !== undefined) { + sandbox.denied = confined.denialSignatures.some(signature => + failure.message.toLowerCase().includes(signature.toLowerCase())) + } + if (failure.kind === 'output-limit') outputOverflow = true + finish(failure) + return + } + const value = raw.value === undefined ? undefined : decodeCodeJsonWire(raw.value) + if (raw.value !== undefined && value === undefined) finish({ kind: 'invalid-output', message: 'program completion must be lossless JSON' }) + else finish(undefined, value) + return + } + case 'call': { + if (!Number.isSafeInteger(raw.id) || raw.id !== nextId || typeof raw.global !== 'string' || typeof raw.name !== 'string') { protocolFailure('invalid binding call identity'); return } + nextId += 1 + const functions = bindings.get(raw.global)?.functions + const fn = functions !== undefined && Object.hasOwn(functions, raw.name) ? functions[raw.name] : undefined + if (typeof fn !== 'function') { protocolFailure('program requested an undeclared binding'); return } + const args = decodeCodeJsonWire(raw.args) + if (args === undefined) { protocolFailure('binding arguments must be lossless JSON'); return } + if (++pending > this.config.maxPendingCalls || (pendingBytes += bytes) > this.config.maxMessageBytes) { protocolFailure('pending binding calls exceed configured limits'); return } + const id = raw.id as number + void (async () => { + let reply: unknown + try { + const value = snapshotJsonValue(await fn(args)) + if (value === undefined) throw new Error('binding resolution must be lossless JSON') + reply = { type: 'reply', id, ok: true, value: encodeCodeJsonWire(value) } + } catch (error: unknown) { + reply = { type: 'reply', id, ok: false, message: messageOf(error) } + } finally { + pending -= 1 + pendingBytes -= bytes + } + if (!settled) await transport.send(reply) + })().catch((error) => { protocolFailure(messageOf(error)) }) + return + } + default: protocolFailure('unknown control message') } - onCall(message) - onDone(message) + }, (error, kind) => { + if (kind === 'protocol') protocolFailure(messageOf(error)) + else if (ready) finish({ kind: 'worker-exit', message: messageOf(error) }) + else void launched.done.then(processFinished, (failure) => { finish({ kind: 'worker-exit', message: messageOf(failure) }) }) }) - worker.on('error', (error: Error) => { - finish(() => output.failure([...logs, ...strayLogs], { kind: 'worker-exit', message: `worker error: ${error.message}` })) - }) - worker.on('exit', (exitCode: number) => { - finish(() => output.failure([...logs, ...strayLogs], { kind: 'worker-exit', message: `worker exited with code ${exitCode} before completing` })) - }) - - // The compute budget reads the worker's own measured busy time, so a - // hot loop expires it no matter what dispatches are in flight, while a - // program idling on a slow binding accrues nothing. - const eluTimer = setInterval(() => { - const elu = worker.performance.eventLoopUtilization() - if (elu.active > this.config.computeMs) { - finish(() => output.failure([...logs, ...strayLogs], { kind: 'timeout', message: `compute budget exhausted (${this.config.computeMs}ms busy)` })) - } - }, ELU_POLL_INTERVAL_MS) - const wallTimer = setTimeout(() => { - finish(() => output.failure([...logs, ...strayLogs], { kind: 'timeout', message: `wall-clock ceiling reached (${this.config.maxWallMs}ms)` })) - }, this.config.maxWallMs) - const onAbort = (): void => { - finish(() => output.failure([...logs, ...strayLogs], { kind: 'abort', message: String(request.signal?.reason) })) - } - request.signal?.addEventListener('abort', onAbort, { once: true }) - - const live: LiveRun = { - worker, - finished, - settle: (failure: CodeRunFailure) => { finish(() => output.failure([...logs, ...strayLogs], failure)) }, - } - this.live.add(live) - }) + channel = transport + void launched.done.then((outcome) => { setImmediate(() => { processFinished(outcome) }) }, (error) => { finish({ kind: confined !== undefined && isRunnerSpawnFailure(error, confined.argv[0], spec.cwd) ? 'sandbox-unavailable' : 'worker-exit', message: messageOf(error) }) }) + } catch (error: unknown) { + finish({ kind: error instanceof SandboxUnavailableError ? 'sandbox-unavailable' : parsing ? 'exception' : 'worker-exit', message: messageOf(error) }) + } + return await result.promise } } diff --git a/packages/code-runtime/code-runtime-node/src/worker-json.ts b/packages/code-runtime/code-runtime-node/src/json-wire.ts similarity index 98% rename from packages/code-runtime/code-runtime-node/src/worker-json.ts rename to packages/code-runtime/code-runtime-node/src/json-wire.ts index 0250895a1d..b2f750c7c6 100644 --- a/packages/code-runtime/code-runtime-node/src/worker-json.ts +++ b/packages/code-runtime/code-runtime-node/src/json-wire.ts @@ -1,6 +1,6 @@ /** * Lossless-JSON snapshots for the dependency-free source worker closure. - * @module @deepseek-ai/dsh-code-runtime-node/worker-json + * @module @deepseek-ai/dsh-code-runtime-node/json-wire */ import type { CodeJsonValue } from '@deepseek-ai/dsh-code-runtime' @@ -249,15 +249,15 @@ type WorkerJsonToken = null | boolean | number | string | ArrayWireToken | Objec * markers and scalar leaves share one flat token array, so `worker_threads` * never has to structured-clone the value's application nesting. */ -export type WorkerJsonWire = WorkerJsonToken[] +export type CodeJsonWire = WorkerJsonToken[] /** * Flatten one validated JSON value for the worker-thread message port. * @param value - the lossless JSON value to transport. * @returns a pre-order token stream whose own nesting is bounded. */ -export function encodeWorkerJson(value: CodeJsonValue): WorkerJsonWire { - const wire: WorkerJsonWire = [] +export function encodeCodeJsonWire(value: CodeJsonValue): CodeJsonWire { + const wire: CodeJsonWire = [] const pending: CodeJsonValue[] = [value] for (let current = takeLast(pending); current !== undefined; current = takeLast(pending)) { if (current === null || typeof current === 'boolean' || typeof current === 'number' || typeof current === 'string') { @@ -346,7 +346,7 @@ function containerToken(value: object): ArrayWireToken | ObjectWireToken | undef * @param input - untrusted message-port payload. * @returns the detached JSON value, or `undefined` when the wire is invalid. */ -export function decodeWorkerJson(input: unknown): CodeJsonValue | undefined { +export function decodeCodeJsonWire(input: unknown): CodeJsonValue | undefined { try { if (!intrinsicArrayIsArray(input) || !isDenseArray(input) || input.length === 0) return undefined const wire = input as unknown[] diff --git a/packages/code-runtime/code-runtime-node/src/launch.ts b/packages/code-runtime/code-runtime-node/src/launch.ts new file mode 100644 index 0000000000..ade86dbfa8 --- /dev/null +++ b/packages/code-runtime/code-runtime-node/src/launch.ts @@ -0,0 +1,37 @@ +/** Select source or built bootstrap assets in the mounted execution world. */ +import { dirname, resolve } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import type { FileSystem } from '@deepseek-ai/dsh-fs' + +/** Deployment-owned Node executable and optional preinstalled built bootstrap. */ +export interface LaunchConfig { + /** Executable in the subprocess world; defaults to the current Node executable. */ + nodeExecutable?: string + /** Absolute preinstalled built bootstrap in the execution world. */ + bootstrapPath?: string +} + +/** + * Select explicit arguments without inheriting host loader or inspector flags. + * @param fs - Filesystem mapping host bootstrap assets into the process world. + * @param config - Optional preinstalled built bootstrap. + * @param maxMessageBytes - Validated frame and queued-write limit. + * @returns Arguments following the resolved Node executable. + */ +export function bootstrapArgs(fs: FileSystem, config: LaunchConfig, maxMessageBytes: number): string[] { + if (config.bootstrapPath !== undefined) return [config.bootstrapPath, String(maxMessageBytes)] + if ('pkg' in process) return [String(maxMessageBytes)] + const mapped = (path: string): string => { + const result = fs.processPathFromHostPath(path) + if (result === undefined) throw new Error(`code runtime bootstrap is unavailable in the subprocess execution world: ${path}`) + return result + } + if (!new URL(import.meta.url).pathname.endsWith('.ts')) { + return [mapped(fileURLToPath(new URL('./process.js', import.meta.url))), String(maxMessageBytes)] + } + const entry = mapped(fileURLToPath(new URL('./process.ts', import.meta.url))) + const subprocess = dirname(fileURLToPath(import.meta.resolve('@deepseek-ai/dsh-subprocess/package.json'))) + const helper = mapped(resolve(subprocess, 'src/control.ts')) + const source = `const {openInheritedControlChannel}=await import(${JSON.stringify(pathToFileURL(helper).href)});const {runNodeMain}=await import(${JSON.stringify(pathToFileURL(entry).href)});await runNodeMain(openInheritedControlChannel(),${maxMessageBytes},process);` + return ['--input-type=module', '--eval', source] +} diff --git a/packages/code-runtime/code-runtime-node/src/output-ledger.ts b/packages/code-runtime/code-runtime-node/src/output-ledger.ts new file mode 100644 index 0000000000..ec3ae4b2dc --- /dev/null +++ b/packages/code-runtime/code-runtime-node/src/output-ledger.ts @@ -0,0 +1,66 @@ +/** Combined byte accounting for retained program output. */ +import type { CodeJsonValue, CodeRunFailure, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from './output-json.ts' + +/** One run's combined outer-output ledger; binding values never enter it. */ +export class OutputLedger { + private bytes = 2 // JSON serialization of the empty logs array: [] + private entries = 0 + + constructor(private readonly maxBytes: number) {} + + /** Admit one exact log entry, or report that the hard cap was crossed. */ + admit(text: string, sink: string[]): boolean { + const separatorBytes = this.entries > 0 ? 1 : 0 + const stringBytes = jsonStringBytesUpTo(text, this.maxBytes - this.bytes - separatorBytes) + if (stringBytes === undefined) return false + this.bytes += stringBytes + separatorBytes + this.entries += 1 + sink.push(text) + return true + } + + /** Finalize a successful absent-or-JSON completion against the combined cap. */ + success(logs: string[], value?: CodeJsonValue): CodeRunResult { + if (value !== undefined && jsonValueBytesUpTo(value, this.maxBytes - this.bytes) === undefined) return this.limit(logs) + return { logs, ...value !== undefined ? { value } : {} } + } + + /** Finalize a failure diagnostic, with output-limit taking precedence when combined bytes exceed the cap. */ + failure(logs: string[], error: CodeRunFailure): CodeRunResult { + if (jsonStringBytesUpTo(error.message, this.maxBytes - this.bytes) === undefined) return this.limit(logs) + return { logs, error } + } + + /** Build the explicit output-limit failure while retaining a fitting prefix of the final log. */ + limit(logs: string[]): CodeRunResult { + const fullMessage = `outer output exceeded ${this.maxBytes} bytes` + // The fixed diagnostic is ASCII, so every character is one byte plus the quotes. + const messageBytes = fullMessage.length + 2 + const retained: string[] = [] + let retainedBytes = 2 + const logBudget = this.maxBytes - messageBytes + for (const text of logs) { + const separatorBytes = retained.length > 0 ? 1 : 0 + const availableBytes = logBudget - retainedBytes - separatorBytes + const stringBytes = jsonStringBytesUpTo(text, availableBytes) + if (stringBytes !== undefined) { + retained.push(text) + retainedBytes += stringBytes + separatorBytes + continue + } + const prefix = truncateJsonStringBytes(text, availableBytes) + if (prefix.length > 0) { + const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes) + /* v8 ignore next -- truncateJsonStringBytes guarantees its returned prefix fits the same budget. */ + if (prefixBytes === undefined) throw new Error('output ledger produced an oversized log prefix') + retained.push(prefix) + retainedBytes += prefixBytes + separatorBytes + } + break + } + const availableMessageBytes = this.maxBytes - retainedBytes + const message = truncateJsonStringBytes(fullMessage, availableMessageBytes) + return { logs: retained, error: { kind: 'output-limit', message } } + } +} diff --git a/packages/code-runtime/code-runtime-node/src/process-entry.ts b/packages/code-runtime/code-runtime-node/src/process-entry.ts new file mode 100644 index 0000000000..b57dfbc0cd --- /dev/null +++ b/packages/code-runtime/code-runtime-node/src/process-entry.ts @@ -0,0 +1,5 @@ +/** Private built Node-runtime child entry; source execution calls runNodeMain directly. */ +import { openInheritedControlChannel } from '@deepseek-ai/dsh-subprocess/control' +import { runNodeMain } from './process.ts' + +await runNodeMain(openInheritedControlChannel(), Number(process.argv[2]), process) diff --git a/packages/code-runtime/code-runtime-node/src/process.ts b/packages/code-runtime/code-runtime-node/src/process.ts new file mode 100644 index 0000000000..616a91ab1a --- /dev/null +++ b/packages/code-runtime/code-runtime-node/src/process.ts @@ -0,0 +1,69 @@ +/** Node child execution over an inherited control channel; no Harness services run here. */ +import type { Duplex } from 'node:stream' +import { JsonChannel } from './channel.ts' +import { runProgram } from './bootstrap.ts' +import type { PatchableStream } from './bootstrap.ts' +import type { ReplyMessage, ProgramBootData, ProgramToHost } from './protocol.ts' + +/** Process-owned environment and output streams consumed by the child bootstrap. */ +export interface ProgramProcess { + env: NodeJS.ProcessEnv + stdout: PatchableStream + stderr: PatchableStream + exitCode: string | number | null | undefined +} + +/** + * Run one host-supplied program after the control handshake. + * @param stream - Inherited, already-adopted control endpoint. + * @param maxMessageBytes - Host-validated maximum frame and queued-write bytes. + * @param processState - Environment, output streams and exit status of this Node child. + * @returns After the program has settled and its control output has flushed. + */ +export async function runNodeMain(stream: Duplex, maxMessageBytes: number, processState: ProgramProcess): Promise { + if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes <= 0 || maxMessageBytes > 0xffff_ffff) throw new Error('invalid control message limit') + for (const key of Object.keys(processState.env)) Reflect.deleteProperty(processState.env, key) + const boot = Promise.withResolvers() + const listeners: Array<(message: ReplyMessage) => void> = [] + let started = false + let failed = false + const channel = new JsonChannel(stream, maxMessageBytes, (raw) => { + if (!started) { + started = true + if (typeof raw !== 'object' || raw === null || (raw as { type?: unknown }).type !== 'boot') { + boot.reject(new Error('expected program boot frame')) + return + } + boot.resolve((raw as { data: ProgramBootData }).data) + return + } + for (const listener of listeners) listener(raw as ReplyMessage) + }, (error) => { + failed = true + boot.reject(error) + channel.close() + processState.exitCode = 1 + }) + const pending = new Set>() + const send = (message: ProgramToHost): void => { + const task = channel.send(message).catch(() => { + failed = true + channel.close() + processState.exitCode = 1 + }).finally(() => { pending.delete(task) }) + pending.add(task) + } + try { + await channel.send({ type: 'ready' }) + const data = await boot.promise + await runProgram({ + postMessage: send, + on: (_event, listener) => { listeners.push(listener) }, + }, data, { stdout: processState.stdout, stderr: processState.stderr }) + while (pending.size > 0) await Promise.all(pending) + await channel.drain() + } finally { + channel.close() + if (failed) processState.exitCode = 1 + } +} diff --git a/packages/code-runtime/code-runtime-node/src/protocol.ts b/packages/code-runtime/code-runtime-node/src/protocol.ts index 1cf3c470b7..cc2bef5365 100644 --- a/packages/code-runtime/code-runtime-node/src/protocol.ts +++ b/packages/code-runtime/code-runtime-node/src/protocol.ts @@ -1,14 +1,13 @@ /** - * Versionless, structured-clone wire protocol between co-shipped host and worker code. The host - * treats inbound traffic as hostile because model code can forge `parentPort` messages; the - * worker trusts host replies. + * JSON message vocabulary carried by the bounded process channel. The host validates every + * message because model code can write directly to the inherited descriptor. * @module @deepseek-ai/dsh-code-runtime-node/src/protocol */ -import type { WorkerJsonWire } from './worker-json.ts' +import type { CodeJsonWire } from './json-wire.ts' -/** What the host hands the worker at spawn, via `workerData`. */ -export interface WorkerBootData { +/** What the host hands the program at spawn, after the readiness handshake. */ +export interface ProgramBootData { /** The type-stripped (plain JS) program body. */ code: string /** Binding namespaces to materialize; functions themselves stay host-side. */ @@ -21,32 +20,32 @@ export interface WorkerBootData { maxOutputBytes: number } -/** Worker → host: one bridged binding call. */ +/** Program → host: one bridged binding call. */ interface CallMessage { type: 'call' - /** Worker-issued correlation id; the host answers each id at most once and ignores duplicates. */ + /** Program-issued correlation id; the host answers each id at most once and ignores duplicates. */ id: number /** The namespace global the call targets. */ global: string /** The function name within the namespace. */ name: string /** The single argument as a flat lossless-JSON wire value. */ - args: WorkerJsonWire + args: CodeJsonWire } -/** Worker → host: captured text, streamed eagerly so output survives a mid-run termination (timeout, abort, OOM). */ +/** Program → host: captured text, streamed eagerly so output survives a mid-run termination (timeout, abort, OOM). */ interface LogMessage { type: 'log' text: string } -/** Worker → host: worker-side capture or completion measurement exceeded the outer cap. */ +/** Program → host: program-side capture or completion measurement exceeded the outer cap. */ interface OutputLimitMessage { type: 'output-limit' } /** - * Worker → host: the program settled. `error` carries a program exception, + * Program → host: the program settled. `error` carries a program exception, * invalid completion, or output overflow (budgets, aborts, and substrate death * are observed host-side). `value` is present only on a clean completion that * produced one, as a flat wire value already lossless and admitted against @@ -55,14 +54,14 @@ interface OutputLimitMessage { */ export interface DoneMessage { type: 'done' - value?: WorkerJsonWire + value?: CodeJsonWire error?: { kind: 'exception' | 'invalid-output' | 'output-limit'; message: string } } -/** Every message the worker sends. */ -export type WorkerToHost = CallMessage | LogMessage | OutputLimitMessage | DoneMessage +/** Every message the program sends. */ +export type ProgramToHost = CallMessage | LogMessage | OutputLimitMessage | DoneMessage -/** Host → worker: the answer to one {@link CallMessage}. */ +/** Host → program: the answer to one {@link CallMessage}. */ export type ReplyMessage = - | { type: 'reply'; id: number; ok: true; value: WorkerJsonWire } + | { type: 'reply'; id: number; ok: true; value: CodeJsonWire } | { type: 'reply'; id: number; ok: false; message: string } diff --git a/packages/code-runtime/code-runtime-node/src/worker.ts b/packages/code-runtime/code-runtime-node/src/worker.ts deleted file mode 100644 index 9bd3bf80be..0000000000 --- a/packages/code-runtime/code-runtime-node/src/worker.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Spawn-only worker entrypoint over {@link runWorkerMain}. Executable logic stays in - * `bootstrap.ts` for in-process coverage; real-worker tests cover this glue. - * @module @deepseek-ai/dsh-code-runtime-node/src/worker - */ - -import { parentPort, workerData } from 'node:worker_threads' -import { runWorkerMain } from './bootstrap.ts' -import type { WorkerBootData } from './protocol.ts' - -// A worker always has a parent port; guard loudly rather than run detached. -if (!parentPort) throw new Error('dsh-code-runtime-node: worker entry loaded outside a worker thread') - -void runWorkerMain(parentPort, workerData as WorkerBootData, { stdout: process.stdout, stderr: process.stderr }) diff --git a/packages/code-runtime/code-runtime-node/tests/bindings.spec.ts b/packages/code-runtime/code-runtime-node/tests/bindings.spec.ts new file mode 100644 index 0000000000..85345e72d3 --- /dev/null +++ b/packages/code-runtime/code-runtime-node/tests/bindings.spec.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { validateBindings } from '../src/bindings.ts' + +describe('program binding validation', () => { + it.each(['$name', '', 'while', 'lambda', 'console'])('rejects unusable global %s', (global) => { + expect(() => validateBindings({ program: '', bindings: [{ global, functions: {} }] })).toThrow() + }) + it('rejects duplicated globals and accepts arbitrary own member names', () => { + const functions = Object.create(null) as Record Promise> + functions.__proto__ = async () => 'own' + expect(validateBindings({ program: '', bindings: [{ global: 'tools', functions }] }).get('tools')?.functions).toBe(functions) + expect(() => validateBindings({ program: '', bindings: [{ global: 'tools', functions }, { global: 'tools', functions }] })).toThrow('duplicate') + }) + it.each(['$name', 'while', 'console', 'tools'])('rejects invalid error class name %s', (name) => { + expect(() => validateBindings({ program: '', bindings: [{ global: 'tools', functions: {}, errorClass: { name, memberNameProperty: 'member' } }] })).toThrow() + }) + it.each(['', 'name', '__member__'])('rejects invalid error member %s', (memberNameProperty) => { + expect(() => validateBindings({ program: '', bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'ToolError', memberNameProperty } }] })).toThrow() + }) + it('rejects two injected constructors with the same name', () => { + expect(() => validateBindings({ program: '', bindings: ['first', 'second'].map(global => ({ global, functions: {}, errorClass: { name: 'ToolError', memberNameProperty: 'member' } })) })).toThrow('duplicate') + }) +}) diff --git a/packages/code-runtime/code-runtime-node/tests/bootstrap.spec.ts b/packages/code-runtime/code-runtime-node/tests/bootstrap.spec.ts index a7966d7417..fe898e5dcc 100644 --- a/packages/code-runtime/code-runtime-node/tests/bootstrap.spec.ts +++ b/packages/code-runtime/code-runtime-node/tests/bootstrap.spec.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest' import { EventEmitter } from 'node:events' -import { LogBuffer, makeBindingErrorClasses, makeConsoleShim, makeNamespaces, captureStreamWrites, prepareCompletion, prepareException, runWorkerMain, wireReplies } from '../src/bootstrap.ts' +import { LogBuffer, makeBindingErrorClasses, makeConsoleShim, makeNamespaces, captureStreamWrites, prepareCompletion, prepareException, runProgram, wireReplies } from '../src/bootstrap.ts' import type { BootstrapPort, PatchableStream, PendingCall } from '../src/bootstrap.ts' -import type { ReplyMessage, WorkerToHost } from '../src/protocol.ts' -import { decodeWorkerJson, encodeWorkerJson } from '../src/worker-json.ts' +import type { ReplyMessage, ProgramToHost } from '../src/protocol.ts' +import { decodeCodeJsonWire, encodeCodeJsonWire } from '../src/json-wire.ts' /** * An in-process stand-in for the worker's parentPort: the test plays the @@ -12,12 +12,12 @@ import { decodeWorkerJson, encodeWorkerJson } from '../src/worker-json.ts' * isolate (real-worker behavior is pinned by runtime.spec.ts). */ class FakePort implements BootstrapPort { - sent: WorkerToHost[] = [] + sent: ProgramToHost[] = [] private readonly emitter = new EventEmitter() /** Host-scripted responder; return undefined to leave the call pending. */ - respond: (message: WorkerToHost) => ReplyMessage | undefined = () => undefined + respond: (message: ProgramToHost) => ReplyMessage | undefined = () => undefined - postMessage(message: WorkerToHost): void { + postMessage(message: ProgramToHost): void { this.sent.push(message) const reply = this.respond(message) if (reply) queueMicrotask(() => this.emitter.emit('message', reply)) @@ -35,13 +35,13 @@ class FakePort implements BootstrapPort { return this.sent.filter(message => message.type === 'log').map(message => message.text) } - done(): WorkerToHost | undefined { + done(): ProgramToHost | undefined { return this.sent.find(message => message.type === 'done') } doneValue(): unknown { const done = this.done() - return done?.type === 'done' && done.value !== undefined ? decodeWorkerJson(done.value) : undefined + return done?.type === 'done' && done.value !== undefined ? decodeCodeJsonWire(done.value) : undefined } } @@ -140,7 +140,7 @@ describe('captureStreamWrites', () => { describe('prepareCompletion', () => { it('omits undefined and passes lossless JSON values exactly', () => { expect(prepareCompletion(undefined, 100)).toEqual({}) - expect(prepareCompletion({ a: [1, 'two'] }, 100)).toEqual({ value: encodeWorkerJson({ a: [1, 'two'] }) }) + expect(prepareCompletion({ a: [1, 'two'] }, 100)).toEqual({ value: encodeCodeJsonWire({ a: [1, 'two'] }) }) }) it('turns every lossy completion shape into invalid-output', () => { @@ -162,7 +162,7 @@ describe('prepareCompletion', () => { }) it('measures the exact JSON serialization at and over the boundary', () => { - expect(prepareCompletion('€', 5)).toEqual({ value: encodeWorkerJson('€') }) + expect(prepareCompletion('€', 5)).toEqual({ value: encodeCodeJsonWire('€') }) expect(prepareCompletion('€', 4)).toEqual({ error: { kind: 'output-limit', message: 'outer output exceeded 4 bytes' }, }) @@ -216,7 +216,7 @@ describe('makeNamespaces', () => { it('exposes prototype-colliding names as ordinary own properties', async () => { const port = new FakePort() port.respond = message => message.type === 'call' - ? { type: 'reply', id: message.id, ok: true, value: encodeWorkerJson(`${message.name}-ok`) } + ? { type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire(`${message.name}-ok`) } : undefined const pending = new Map() wireReplies(port, pending) @@ -311,15 +311,15 @@ describe('makeNamespaces', () => { }) }) -describe('runWorkerMain', () => { +describe('runProgram', () => { it('runs a program end-to-end: bindings, console, return value', async () => { const port = new FakePort() port.respond = (message) => { if (message.type !== 'call') return undefined - const args = decodeWorkerJson(message.args) as { n: number } - return { type: 'reply', id: message.id, ok: true, value: encodeWorkerJson(args.n * 2) } + const args = decodeCodeJsonWire(message.args) as { n: number } + return { type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire(args.n * 2) } } - await runWorkerMain(port, { + await runProgram(port, { ...BOOT, code: 'const doubled = await tools.double({ n: 21 }); console.log("got", doubled); return { doubled };', namespaces: [{ global: 'tools', names: ['double'] }], @@ -330,7 +330,7 @@ describe('runWorkerMain', () => { it('reports worker-side log capture overflow before completing', async () => { const port = new FakePort() - await runWorkerMain(port, { + await runProgram(port, { maxOutputBytes: 4, code: 'console.log("12345"); return null', namespaces: [], @@ -345,7 +345,7 @@ describe('runWorkerMain', () => { it('reports a thrown program error on the done message', async () => { const port = new FakePort() - await runWorkerMain(port, { ...BOOT, code: 'throw new Error("boom")', namespaces: [] }, fakeStreams()) + await runProgram(port, { ...BOOT, code: 'throw new Error("boom")', namespaces: [] }, fakeStreams()) const done = port.done() expect(done?.type).toBe('done') expect(done?.type === 'done' ? done.error?.kind : undefined).toBe('exception') @@ -355,17 +355,17 @@ describe('runWorkerMain', () => { it('renders non-Error throws and stack-less Errors on the done message', async () => { const rawPort = new FakePort() - await runWorkerMain(rawPort, { ...BOOT, code: 'throw "raw-throw"', namespaces: [] }, fakeStreams()) + await runProgram(rawPort, { ...BOOT, code: 'throw "raw-throw"', namespaces: [] }, fakeStreams()) expect(rawPort.done()).toEqual({ type: 'done', error: { kind: 'exception', message: 'raw-throw' } }) const barePort = new FakePort() - await runWorkerMain(barePort, { ...BOOT, code: 'const e = new Error("bare"); e.stack = undefined; throw e', namespaces: [] }, fakeStreams()) + await runProgram(barePort, { ...BOOT, code: 'const e = new Error("bare"); e.stack = undefined; throw e', namespaces: [] }, fakeStreams()) expect(barePort.done()).toEqual({ type: 'done', error: { kind: 'exception', message: 'bare' } }) }) it('replaces giant thrown strings and Error stacks before posting the done message', async () => { const rawPort = new FakePort() - await runWorkerMain(rawPort, { + await runProgram(rawPort, { maxOutputBytes: 64, code: 'throw "x".repeat(1_000_000)', namespaces: [], @@ -376,7 +376,7 @@ describe('runWorkerMain', () => { }) const stackPort = new FakePort() - await runWorkerMain(stackPort, { + await runProgram(stackPort, { maxOutputBytes: 64, code: 'throw new Error("x".repeat(1_000_000))', namespaces: [], @@ -390,7 +390,7 @@ describe('runWorkerMain', () => { it('surfaces a host failure reply as a program-side rejection it can catch', async () => { const port = new FakePort() port.respond = message => message.type === 'call' ? { type: 'reply', id: message.id, ok: false, message: 'denied by host' } : undefined - await runWorkerMain(port, { + await runProgram(port, { ...BOOT, code: 'try { await tools.x({}) } catch (error) { return { caught: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message } }', namespaces: [toolNamespace(['x'])], @@ -403,7 +403,7 @@ describe('runWorkerMain', () => { port.respond = message => message.type === 'call' ? { type: 'reply', id: message.id, ok: false, message: 'helper denied' } : undefined - await runWorkerMain(port, { + await runProgram(port, { ...BOOT, code: 'try { await helpers.x({}) } catch (error) { return { caught: error instanceof HelperCallError, name: error.name, helperName: error.helperName, message: error.message } }', namespaces: [{ @@ -420,10 +420,10 @@ describe('runWorkerMain', () => { port.respond = (message) => { if (message.type !== 'call') return undefined // Deliver a stray reply first; the real one follows. - port.deliver({ type: 'reply', id: 9_999, ok: true, value: encodeWorkerJson('stray') }) - return { type: 'reply', id: message.id, ok: true, value: encodeWorkerJson('real') } + port.deliver({ type: 'reply', id: 9_999, ok: true, value: encodeCodeJsonWire('stray') }) + return { type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire('real') } } - await runWorkerMain(port, { + await runProgram(port, { ...BOOT, code: 'return await tools.x({})', namespaces: [{ global: 'tools', names: ['x'] }], @@ -434,7 +434,7 @@ describe('runWorkerMain', () => { it('captures raw stream writes through the patched process streams', async () => { const port = new FakePort() const streams = fakeStreams() - await runWorkerMain(port, { ...BOOT, code: 'return 1', namespaces: [] }, streams) + await runProgram(port, { ...BOOT, code: 'return 1', namespaces: [] }, streams) streams.stdout.write('never seen — already restored? no: patch persists in worker') // The patch stays installed for the worker's lifetime; writes during the // program landed in order. Here the program wrote nothing via streams, so diff --git a/packages/code-runtime/code-runtime-node/tests/budget.spec.ts b/packages/code-runtime/code-runtime-node/tests/budget.spec.ts deleted file mode 100644 index c738b00e2c..0000000000 --- a/packages/code-runtime/code-runtime-node/tests/budget.spec.ts +++ /dev/null @@ -1,95 +0,0 @@ -/** Host budget decisions use controlled clocks and ELU samples; worker execution and binding transport stay real. */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { Context } from '@deepseek-ai/cordis' -import { NodeCodeRuntime } from '@deepseek-ai/dsh-code-runtime-node' -import type { CodeRunResult } from '@deepseek-ai/dsh-code-runtime' - -const meter = vi.hoisted(() => ({ sample: vi.fn() })) - -vi.mock('node:worker_threads', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - Worker: class extends original.Worker { - constructor(...args: ConstructorParameters) { - super(...args) - this.performance.eventLoopUtilization = meter.sample - } - }, - } -}) - -describe('worker budgets with controlled ELU samples and real binding transport', () => { - let ctx: Context - let controller: AbortController - let run: Promise | undefined - let release: (() => void) | undefined - - beforeEach(() => { - ctx = new Context() - controller = new AbortController() - run = undefined - release = undefined - meter.sample.mockReset().mockReturnValue({ active: 10, idle: 0, utilization: 1 }) - // Worker bootstrap and scheduling contribute to ELU active time; only the - // measured input and host deadlines are controlled, not worker execution. - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] }) - }) - - afterEach(async () => { - const owned = { ctx, controller, run, release } - try { - owned.controller.abort('test cleanup') - owned.release?.() - } finally { - vi.useRealTimers() - } - try { - await owned.run - } finally { - await owned.ctx.fiber.dispose() - } - }) - - async function pendingBinding(): Promise { - await ctx.plugin(NodeCodeRuntime, { computeMs: 1_000, maxWallMs: 30_000 }) - let entered!: () => void - const ready = new Promise((resolve) => { entered = resolve }) - const binding = new Promise((resolve) => { release = () => { resolve('slow-done') } }) - run = ctx.codeRuntime.run({ - program: 'return await tools.slow({})', - bindings: [{ global: 'tools', functions: { slow: () => { entered(); return binding } } }], - signal: controller.signal, - }) - await Promise.race([ - ready, - run.then((result) => { throw new Error('Worker settled before binding entry: ' + JSON.stringify(result)) }), - ]) - } - - it('does not charge a binding wait longer than the compute budget', async () => { - await pendingBinding() - const settled = vi.fn() - void run!.then(settled, settled) - meter.sample.mockReturnValue({ active: 10, idle: 1_500, utilization: 10 / 1_510 }) - await vi.advanceTimersByTimeAsync(1_500) - expect(meter.sample).toHaveBeenCalled() - expect(settled).not.toHaveBeenCalled() - release!() - expect(await run).toEqual({ logs: [], value: 'slow-done' }) - }) - - it('expires active time even while a binding is pending', async () => { - await pendingBinding() - meter.sample.mockReturnValue({ active: 1_001, idle: 1_500, utilization: 1_001 / 2_501 }) - await vi.advanceTimersByTimeAsync(25) - expect(await run).toEqual({ logs: [], error: { kind: 'timeout', message: 'compute budget exhausted (1000ms busy)' } }) - }) - - it('expires the wall ceiling while active time remains below the compute budget', async () => { - await pendingBinding() - meter.sample.mockReturnValue({ active: 10, idle: 30_000, utilization: 10 / 30_010 }) - await vi.advanceTimersByTimeAsync(30_000) - expect(await run).toEqual({ logs: [], error: { kind: 'timeout', message: 'wall-clock ceiling reached (30000ms)' } }) - }) -}) diff --git a/packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts b/packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts index 563afdaa94..27c02a176a 100644 --- a/packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts +++ b/packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts @@ -6,23 +6,29 @@ import { describe, expect, it } from 'vitest' /** * Keyless built-artifact smoke: plain Node imports the package by name through its exports map, - * then exercises type stripping, sibling `worker.cjs` loading, bindings, and logs. Unit tests use - * `src/worker.ts`; this pins the downstream `lib/index.js` path. It skips when `lib/` is absent, + * then exercises type stripping, sibling `process.js` loading, bindings, and logs. Unit tests use + * `src/process.ts`; this pins the downstream `lib/index.js` path. It skips when `lib/` is absent, * and CI runs it after the build. */ const pkgDir = fileURLToPath(new URL('..', import.meta.url)) -const built = ['lib/index.js', 'lib/worker.cjs'].every(file => existsSync(join(pkgDir, file))) +const built = ['lib/index.js', 'lib/process.js'].every(file => existsSync(join(pkgDir, file))) && existsSync(join(pkgDir, '../code-runtime/lib/index.js')) describe.skipIf(!built)('built lib real load path (plain node)', () => { - it('runs a TypeScript program with a binding through lib/index.js and its lib/worker.cjs entry', async () => { + it('runs a TypeScript program with a binding through lib/index.js and its lib/process.js entry', async () => { const script = ` const { Context } = await import('@deepseek-ai/cordis') const { NodeCodeRuntime } = await import('@deepseek-ai/dsh-code-runtime-node') const ctx = new Context() + for (const name of ['session-projection', 'fs-local', 'subprocess-local', 'sandbox-local']) { + const plugin = await import('@deepseek-ai/dsh-' + name) + await ctx.plugin(plugin.default, {}) + } + const { default: SandboxPolicy } = await import('@deepseek-ai/dsh-sandbox-policy') + await ctx.plugin(SandboxPolicy, { mode: 'read-only' }) await ctx.plugin(NodeCodeRuntime, {}) - const result = await ctx.codeRuntime.run({ + const result = await ctx.codeRuntime.run(ctx.codeRuntime.resolve({ program: 'const doubled: number = await tools.double({ n: 21 }); console.log("halfway", doubled); let failure; try { await tools.fail({}) } catch (error) { failure = { typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message } } return { doubled, failure };', bindings: [{ global: 'tools', @@ -32,9 +38,9 @@ describe.skipIf(!built)('built lib real load path (plain node)', () => { }, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' }, }], - }) + })) + await ctx.fiber.dispose() console.log(JSON.stringify(result)) - process.exit(0) ` const { exitCode, stdout, stderr } = await execa(process.execPath, ['--input-type=module', '-e', script], { cwd: pkgDir, diff --git a/packages/code-runtime/code-runtime-node/tests/channel.spec.ts b/packages/code-runtime/code-runtime-node/tests/channel.spec.ts new file mode 100644 index 0000000000..511eaa9f2f --- /dev/null +++ b/packages/code-runtime/code-runtime-node/tests/channel.spec.ts @@ -0,0 +1,156 @@ +import { Duplex, PassThrough } from 'node:stream' +import { describe, expect, it, onTestFinished } from 'vitest' +import { JsonChannel } from '../src/channel.ts' + +function pair() { + const left = new PassThrough() + const right = new PassThrough() + const a = Duplex.from({ readable: left, writable: right }) + const b = Duplex.from({ readable: right, writable: left }) + // Duplex.from forwards peer destruction as ABORT_ERR; channel owners observe their own failures. + a.on('error', () => {}) + b.on('error', () => {}) + onTestFinished(() => { a.destroy(); b.destroy() }) + return { a, b } +} + +function frame(value: unknown): Buffer { + const body = Buffer.from(JSON.stringify(value)) + const header = Buffer.alloc(4) + header.writeUInt32BE(body.length) + return Buffer.concat([header, body]) +} + +describe('bounded process frames', () => { + it('reassembles split binary headers and UTF-8 bodies', async () => { + const { a, b } = pair() + const received = Promise.withResolvers() + const channel = new JsonChannel(a, 1000, value => received.resolve(value), error => received.reject(error)) + onTestFinished(() => channel.close()) + const bytes = frame({ text: '你好🙂' }) + for (const byte of bytes) b.write(Buffer.from([byte])) + expect(await received.promise).toEqual({ text: '你好🙂' }) + }) + + it('accepts consecutive frames and writes complete responses', async () => { + const { a, b } = pair() + const received: unknown[] = [] + const done = Promise.withResolvers() + const channel = new JsonChannel(a, 1000, (value) => { + received.push(value) + if (received.length === 2) done.resolve(undefined) + }, error => done.reject(error)) + const peer = new JsonChannel(b, 1000, () => {}, error => done.reject(error)) + onTestFinished(() => { channel.close(); peer.close() }) + await Promise.all([peer.send({ n: 1 }), peer.send({ n: 2 })]) + await done.promise + expect(received).toEqual([{ n: 1 }, { n: 2 }]) + await peer.drain() + }) + + it.each([0, 65])('rejects a declared %i-byte frame before accepting its body', async (length) => { + const { a, b } = pair() + const failure = Promise.withResolvers() + const channel = new JsonChannel(a, 64, () => { throw new Error('must not dispatch') }, error => failure.resolve(error)) + onTestFinished(() => channel.close()) + const header = Buffer.alloc(4) + header.writeUInt32BE(length) + b.write(header) + expect((await failure.promise).message).toContain('control frame') + }) + + it('contains malformed JSON, invalid UTF-8 and receiver failures', async () => { + for (const payload of [Buffer.from('{'), Buffer.from([0xff]), Buffer.from('{}')]) { + const { a, b } = pair() + const failure = Promise.withResolvers() + const channel = new JsonChannel(a, 64, () => { throw new Error('receiver failed') }, error => failure.resolve(error)) + const header = Buffer.alloc(4) + header.writeUInt32BE(payload.length) + b.write(Buffer.concat([header, payload])) + expect(await failure.promise).toBeInstanceOf(Error) + channel.close() + } + }) + + it('rejects oversized writes and closed channels', async () => { + const { a } = pair() + const channel = new JsonChannel(a, 20, () => {}, () => {}) + await expect(channel.send({ text: 'x'.repeat(30) })).rejects.toThrow('queued bytes') + channel.close() + channel.close() + await expect(channel.send({})).rejects.toThrow('closed') + }) + + it('reports peer EOF while a program is active', async () => { + const { a, b } = pair() + const failure = Promise.withResolvers() + const channel = new JsonChannel(a, 64, () => {}, error => failure.resolve(error)) + onTestFinished(() => channel.close()) + b.end() + expect((await failure.promise).message).toContain('ended') + }) +}) + +it('retains a partial header and partial payload across distinct stream deliveries', () => { + const { a } = pair() + const values: unknown[] = [] + const channel = new JsonChannel(a, 64, (value) => { values.push(value) }, (error) => { throw error }) + const bytes = frame({ value: 1 }) + a.emit('data', bytes.subarray(0, 2)) + a.emit('data', bytes.subarray(2, 6)) + a.emit('data', bytes.subarray(6)) + expect(values).toEqual([{ value: 1 }]) + channel.close() +}) + +it('contains a receiver throwing a non-Error value', () => { + const { a } = pair() + const failures: string[] = [] + const channel = new JsonChannel(a, 64, () => { throw 'receiver failure' }, (error) => { failures.push(error.message) }) + a.emit('data', frame({})) + expect(failures).toEqual(['receiver failure']) + channel.close() +}) + +it('ignores callbacks already captured by an emission when an earlier listener closes the channel', () => { + for (const event of ['data', 'end']) { + const { a } = pair() + let failures = 0 + const channel = new JsonChannel(a, 64, () => { throw new Error('closed channel dispatched') }, () => { failures += 1 }) + a.prependOnceListener(event, () => channel.close()) + a.emit(event, frame({})) + a.emit('error', new Error('late closed stream error')) + expect(failures).toBe(0) + } +}) + +it('rejects queued writes if the owner closes before they start', async () => { + const { a } = pair() + const channel = new JsonChannel(a, 64, () => {}, () => {}) + const pending = channel.send({ n: 1 }) + channel.close() + await expect(pending).rejects.toThrow('closed') + await channel.drain() +}) + +it('bounds queued frames while a receiver is not reading', async () => { + const stream = new Duplex({ read() {}, write(_chunk, _encoding, _callback) {} }) + const channel = new JsonChannel(stream, 32, () => {}, () => {}) + const pending = channel.send({ value: '1234567890' }) + await expect(channel.send({ value: '1234567890' })).rejects.toThrow('queued bytes') + channel.close() + await expect(pending).rejects.toThrow('closed') +}) + +it.each(['error', 'close'])('settles a blocked write when the stream emits %s', async (event) => { + const entered = Promise.withResolvers() + const stream = new Duplex({ read() {}, write(_chunk, _encoding, _callback) { entered.resolve(undefined) } }) + let failure: Error | undefined + const channel = new JsonChannel(stream, 64, () => {}, (error) => { failure = error }) + const pending = channel.send({ value: 1 }) + await entered.promise + stream.emit(event, new Error('transport failed')) + await expect(pending).rejects.toThrow(event === 'error' ? 'transport failed' : 'closed') + if (event === 'error') expect(failure?.message).toBe('transport failed') + channel.close() +}) diff --git a/packages/code-runtime/code-runtime-node/tests/worker-json.spec.ts b/packages/code-runtime/code-runtime-node/tests/json-wire.spec.ts similarity index 93% rename from packages/code-runtime/code-runtime-node/tests/worker-json.spec.ts rename to packages/code-runtime/code-runtime-node/tests/json-wire.spec.ts index 8617074cd2..4b0cb1cee5 100644 --- a/packages/code-runtime/code-runtime-node/tests/worker-json.spec.ts +++ b/packages/code-runtime/code-runtime-node/tests/json-wire.spec.ts @@ -1,7 +1,7 @@ import { runInNewContext } from 'node:vm' import { describe, expect, it } from 'vitest' import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values' -import { decodeWorkerJson, encodeWorkerJson, snapshotCodeJsonValue } from '../src/worker-json.ts' +import { decodeCodeJsonWire, encodeCodeJsonWire, snapshotCodeJsonValue } from '../src/json-wire.ts' describe('snapshotCodeJsonValue', () => { it('matches the canonical scalar boundary', () => { @@ -176,9 +176,9 @@ describe('flat worker JSON wire', () => { for (const value of values) { const snapshot = snapshotCodeJsonValue(value) expect(snapshot).not.toBeUndefined() - expect(decodeWorkerJson(encodeWorkerJson(snapshot!))).toEqual(snapshot) + expect(decodeCodeJsonWire(encodeCodeJsonWire(snapshot!))).toEqual(snapshot) } - const decoded = decodeWorkerJson(encodeWorkerJson(snapshotCodeJsonValue(withPrototypeKey)!)) as Record + const decoded = decodeCodeJsonWire(encodeCodeJsonWire(snapshotCodeJsonValue(withPrototypeKey)!)) as Record expect(Object.hasOwn(decoded, '__proto__')).toBe(true) expect(decoded.__proto__).toEqual({ safe: true }) }) @@ -187,10 +187,10 @@ describe('flat worker JSON wire', () => { let value: unknown = 'leaf' for (let depth = 0; depth < 5_000; depth++) value = [value] const snapshot = snapshotCodeJsonValue(value)! - const wire = encodeWorkerJson(snapshot) + const wire = encodeCodeJsonWire(snapshot) expect(wire).toHaveLength(5_001) - let cursor = decodeWorkerJson(wire) + let cursor = decodeCodeJsonWire(wire) for (let depth = 0; depth < 5_000; depth++) { expect(Array.isArray(cursor)).toBe(true) cursor = Array.isArray(cursor) ? cursor[0] : undefined @@ -246,12 +246,12 @@ describe('flat worker JSON wire', () => { [{ kind: 'object', keys: ['x'] }], [{ kind: 'object', keys: [], extra: true }], ]) { - expect(decodeWorkerJson(value)).toBeUndefined() + expect(decodeCodeJsonWire(value)).toBeUndefined() } }) it('rejects invalid values passed through a forged static type', () => { - expect(() => encodeWorkerJson([undefined] as never)).toThrow(/sparse JSON array/) - expect(() => encodeWorkerJson({ value: undefined } as never)).toThrow(/undefined JSON object property/) + expect(() => encodeCodeJsonWire([undefined] as never)).toThrow(/sparse JSON array/) + expect(() => encodeCodeJsonWire({ value: undefined } as never)).toThrow(/undefined JSON object property/) }) }) diff --git a/packages/code-runtime/code-runtime-node/tests/process-main.spec.ts b/packages/code-runtime/code-runtime-node/tests/process-main.spec.ts new file mode 100644 index 0000000000..8ac0681481 --- /dev/null +++ b/packages/code-runtime/code-runtime-node/tests/process-main.spec.ts @@ -0,0 +1,66 @@ +import { Duplex, PassThrough } from 'node:stream' +import { expect, it, onTestFinished } from 'vitest' +import { JsonChannel } from '../src/channel.ts' +import { runNodeMain } from '../src/process.ts' +import type { ProgramProcess } from '../src/process.ts' +import { decodeCodeJsonWire, encodeCodeJsonWire } from '../src/json-wire.ts' + +function endpoints() { + const first = new PassThrough() + const second = new PassThrough() + const child = Duplex.from({ readable: first, writable: second }) + const host = Duplex.from({ readable: second, writable: first }) + child.on('error', () => {}) + host.on('error', () => {}) + onTestFinished(() => { child.destroy(); host.destroy() }) + return { child, host } +} +function processState(): ProgramProcess { return { env: { FIXTURE_SECRET: 'test' }, stdout: { write: () => true }, stderr: { write: () => true }, exitCode: undefined } } + +it('clears process environment, dispatches a binding reply and flushes the terminal frame', async () => { + const { child, host } = endpoints() + const state = processState() + const messages: Record[] = [] + const peer = new JsonChannel(host, 4096, (raw) => { + const message = raw as Record + messages.push(message) + if (message.type === 'ready') void peer.send({ type: 'boot', data: { code: 'console.log("ready"); return await tools.echo({});', namespaces: [{ global: 'tools', names: ['echo'] }], maxOutputBytes: 1024 } }) + if (message.type === 'call') void peer.send({ type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire(42) }) + }, () => {}) + onTestFinished(() => peer.close()) + await runNodeMain(child, 4096, state) + expect(state.env).toEqual({}) + expect(state.exitCode).toBeUndefined() + expect(decodeCodeJsonWire(messages.find(message => message.type === 'done')?.value)).toBe(42) +}) + +it.each([0, -1, 1.5, 4294967296])('rejects an invalid bootstrap frame limit %i', async (limit) => { + const { child } = endpoints() + await expect(runNodeMain(child, limit, processState())).rejects.toThrow('invalid control message limit') +}) + +it('rejects an unexpected first control frame', async () => { + const { child, host } = endpoints() + const peer = new JsonChannel(host, 4096, () => { void peer.send({ type: 'reply' }) }, () => {}) + onTestFinished(() => peer.close()) + await expect(runNodeMain(child, 4096, processState())).rejects.toThrow('expected program boot') +}) + +it('records an I/O failure before the boot frame', async () => { + const { child, host } = endpoints() + const state = processState() + const peer = new JsonChannel(host, 4096, () => { peer.close() }, () => {}) + await expect(runNodeMain(child, 4096, state)).rejects.toBeInstanceOf(Error) + expect(state.exitCode).toBe(1) +}) + +it('contains program writes that exceed queued control output', async () => { + const { child, host } = endpoints() + const state = processState() + const peer = new JsonChannel(host, 1024, (raw) => { + if ((raw as { type: string }).type === 'ready') void peer.send({ type: 'boot', data: { code: 'for(let i=0;i<30;i++) console.log("x".repeat(100));', namespaces: [], maxOutputBytes: 8000 } }) + }, () => {}) + onTestFinished(() => peer.close()) + await runNodeMain(child, 1024, state) + expect(state.exitCode).toBe(1) +}) diff --git a/packages/code-runtime/code-runtime-node/tests/process.spec.ts b/packages/code-runtime/code-runtime-node/tests/process.spec.ts new file mode 100644 index 0000000000..8b20a82f75 --- /dev/null +++ b/packages/code-runtime/code-runtime-node/tests/process.spec.ts @@ -0,0 +1,47 @@ +import { spawn } from 'node:child_process' +import { copyFile, mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import type { Duplex } from 'node:stream' +import { expect, it, onTestFinished } from 'vitest' +import { JsonChannel } from '../src/channel.ts' +import { decodeCodeJsonWire, encodeCodeJsonWire } from '../src/json-wire.ts' + +it('boots an unbuilt source closure outside the workspace and exchanges tool replies', async () => { + const directory = await mkdtemp(join(tmpdir(), 'dsh-node-source-')) + onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) }) + for (const file of ['process.ts', 'bootstrap.ts', 'channel.ts', 'json-wire.ts', 'output-json.ts', 'protocol.ts']) { + await copyFile(new URL(`../src/${file}`, import.meta.url), join(directory, file)) + } + const source = `import {Socket} from 'node:net';import {runNodeMain} from ${JSON.stringify(pathToFileURL(join(directory, 'process.ts')).href)};await runNodeMain(new Socket({fd:7,readable:true,writable:true}),100000,process);` + const child = spawn(process.execPath, ['--input-type=module', '--eval', source], { + env: { PLACEHOLDER_SECRET: 'fixture-only' }, + stdio: ['ignore', 'pipe', 'pipe', 'ignore', 'ignore', 'ignore', 'ignore', 'pipe'], + }) + let stderr = '' + child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') }) + const finished = new Promise((resolve) => { child.once('close', () => { resolve() }) }) + const completed = Promise.withResolvers() + child.once('error', error => completed.reject(error)) + child.once('exit', (code) => { if (code !== 0) completed.reject(new Error(`child exit ${code}: ${stderr}`)) }) + const channel = new JsonChannel(child.stdio[7] as Duplex, 100_000, (raw) => { + const message = raw as { type: string; id?: number; args?: unknown; value?: unknown; error?: unknown } + if (message.type === 'ready') { + void channel.send({ type: 'boot', data: { + code: 'const answer = await tools.echo({ n: 21 }); return { answer, env: { ...process.env } }', + namespaces: [{ global: 'tools', names: ['echo'] }], + maxOutputBytes: 10_000, + } }).catch(error => completed.reject(error)) + } else if (message.type === 'call') { + expect(decodeCodeJsonWire(message.args)).toEqual({ n: 21 }) + void channel.send({ type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire(42) }).catch(error => completed.reject(error)) + } else if (message.type === 'done') { + if (message.error !== undefined) completed.reject(new Error(JSON.stringify(message.error))) + else completed.resolve(decodeCodeJsonWire(message.value)) + } + }, error => completed.reject(error)) + onTestFinished(async () => { channel.close(); child.kill(); await finished }) + expect(await completed.promise).toEqual({ answer: 42, env: {} }) + await finished +}) diff --git a/packages/code-runtime/code-runtime-node/tests/runtime.spec.ts b/packages/code-runtime/code-runtime-node/tests/runtime.spec.ts index 68294033c4..0a1f9830c1 100644 --- a/packages/code-runtime/code-runtime-node/tests/runtime.spec.ts +++ b/packages/code-runtime/code-runtime-node/tests/runtime.spec.ts @@ -1,902 +1,142 @@ -import { describe, expect, it, onTestFinished } from 'vitest' +import { mkdtemp, mkdir, readFile, rm, symlink } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' -import { NodeCodeRuntime } from '@deepseek-ai/dsh-code-runtime-node' -import type { Config } from '@deepseek-ai/dsh-code-runtime-node' -import type { CodeBindingFunction, CodeBindingNamespace, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { describe, expect, it, onTestFinished } from 'vitest' +import type { CodeBindingFunction, CodeBindingNamespace, CodeRunRequest } from '@deepseek-ai/dsh-code-runtime' +import type { Config } from '../src/index.ts' +import { mountRuntime } from './setup.ts' -/** - * Integration suite over REAL worker threads (no mocks — workers are cheap - * and local, per docs/testing.md's real-over-mock policy). Each test builds - * a fresh context so budgets can be tuned per case. - */ -async function setup(config: Config = {}) { +async function setup(config: Config = {}, mode: 'read-only' | 'workspace-write' | 'danger-full-access' = 'danger-full-access') { + const root = await mkdtemp(join(homedir(), '.dsh-node-runtime-test-')) + const cwd = join(root, 'workspace') + await mkdir(cwd) const ctx = new Context() - await ctx.plugin(NodeCodeRuntime, config) - const runtime = ctx.codeRuntime as NodeCodeRuntime - return { ctx, runtime } + onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) + const runtime = await mountRuntime(ctx, config, { mode, workspaceRoot: cwd }) + const run = (request: CodeRunRequest) => runtime.run(runtime.resolve(request)) + return { ctx, runtime, root, cwd, run } } -/** Convenience: one namespace `tools` with the given functions. */ -function tools(functions: Record Promise>): CodeBindingNamespace[] { - return [{ - global: 'tools', - functions: functions as Record, - errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' }, - }] +function bindings(functions: Record): CodeBindingNamespace[] { + return [{ global: 'tools', functions, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' } }] } -describe('NodeCodeRuntime — programs and bindings (real workers)', () => { - it('registers with the seam descriptors', async () => { - const { runtime } = await setup() - expect(runtime.language).toBe('typescript') - expect(runtime.isolation).toBe('worker-thread') +describe('Node program process', () => { + it('runs erasable TypeScript in the resolved directory with an empty environment', async () => { + const { run, cwd } = await setup() + const result = await run({ program: 'const n: number = 6; console.log("ready"); return { n: n * 7, cwd: process.cwd(), env: { ...process.env } };', bindings: [] }) + expect(result.error).toBeUndefined() + expect(result.value).toEqual({ n: 42, cwd, env: {} }) + expect(result.logs).toEqual(['ready']) + expect(result.sandbox).toEqual({ mode: 'danger-full-access', denied: false }) }) - it('runs TypeScript (erasable syntax), captures output in order, returns the value', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - interface Point { x: number; y: number } - const p: Point = { x: 1, y: 2 } as Point; - console.log('point', p); - process.stdout.write('raw-out\\n'); - console.warn('careful'); - return p.x + p.y; - `, - bindings: [], + it('returns binding values and preserves typed binding rejection', async () => { + const { run } = await setup() + const result = await run({ + program: 'const value = await tools.echo({ n: 42 }); let rejected; try { await tools.fail({}) } catch (e) { rejected = [e instanceof ToolCallError,e.name,e.toolName,e.message]; } return {value,rejected};', + bindings: bindings({ echo: async args => args as { n: number }, fail: async () => { throw new Error('denied') } }), }) expect(result.error).toBeUndefined() - expect(result.value).toBe(3) - expect(result.logs).toEqual(['point { x: 1, y: 2 }', 'raw-out\n', 'careful']) + expect(result.value).toEqual({ value: { n: 42 }, rejected: [true, 'ToolCallError', 'fail', 'denied'] }) }) - it('bridges binding calls both ways and rejects the program-side call on a host rejection', async () => { - const { runtime } = await setup() - const calls: unknown[] = [] - const result = await runtime.run({ - program: ` - const first = await tools.echo({ n: 1 }); - let caught = {}; - try { await tools.fail({}) } catch (error) { caught = { isTyped: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message } } - let caughtRaw = {}; - try { await tools.failRaw({}) } catch (error) { caughtRaw = { name: error.name, toolName: error.toolName, message: error.message } } - return { first, caught, caughtRaw }; - `, - bindings: tools({ - echo: async (args) => { calls.push(args); return { echoed: args } }, - fail: async () => { throw new Error('nope') }, - // A non-Error throw: the host renders it, the program still catches. - failRaw: async () => { throw 'raw-nope' }, - }), - }) + it('retains raw native stdout and stderr separately from control frames', async () => { + const { run } = await setup() + const result = await run({ program: 'const fs = await import("node:fs"); fs.writeSync(1,"native-out你好"); fs.writeSync(2,"native-err🙂"); return 42;', bindings: [] }) expect(result.error).toBeUndefined() - expect(result.value).toEqual({ - first: { echoed: { n: 1 } }, - caught: { isTyped: true, name: 'ToolCallError', toolName: 'fail', message: 'nope' }, - caughtRaw: { name: 'ToolCallError', toolName: 'failRaw', message: 'raw-nope' }, - }) - expect(calls).toEqual([{ n: 1 }]) + expect(result.value).toBe(42) + expect(result.logs.join('')).toContain('native-out你好') + expect(result.logs.join('')).toContain('native-err🙂') }) - it('materializes a typed rejection from a generic namespace descriptor', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - try { await helpers.fail({}) } catch (error) { - return { - isTyped: error instanceof HelperCallError, - name: error.name, - helperName: error.helperName, - message: error.message, - }; - } - `, - bindings: [{ - global: 'helpers', - functions: { fail: async () => { throw new Error('nope') } }, - errorClass: { name: 'HelperCallError', memberNameProperty: 'helperName' }, - }], - }) - expect(result.value).toEqual({ - isTyped: true, - name: 'HelperCallError', - helperName: 'fail', - message: 'nope', - }) + it.each(['throw new Error("broken")', 'enum E { A }'])('reports program failure for %s', async (program) => { + const { run } = await setup() + expect((await run({ program, bindings: [] })).error?.kind).toBe('exception') }) - it('bridges a deeply nested lossless JSON argument, resolution, and completion', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - let value = 'leaf'; - for (let depth = 0; depth < 3_000; depth++) value = [value]; - return await tools.echo(value); - `, - bindings: tools({ echo: async args => args }), - }) - - expect(result.error).toBeUndefined() - let cursor = result.value - for (let depth = 0; depth < 3_000; depth++) { - expect(Array.isArray(cursor)).toBe(true) - cursor = Array.isArray(cursor) ? cursor[0] : undefined - } - expect(cursor).toBe('leaf') - }, 15_000) - - it('reports non-erasable syntax as an exception without spawning a worker', async () => { - const { runtime } = await setup() - const result = await runtime.run({ program: 'enum E { A }\nreturn 1', bindings: [] }) - expect(result.error?.kind).toBe('exception') - expect(result.error?.message).toMatch(/enum|strip/i) + it('rejects lossy program output', async () => { + const { run } = await setup() + expect((await run({ program: 'return { value: undefined }', bindings: [] })).error?.kind).toBe('invalid-output') }) - it('reports a runtime throw as an exception with the message', async () => { - const { runtime } = await setup() - const result = await runtime.run({ program: 'throw new Error("kaboom")', bindings: [] }) - expect(result.error?.kind).toBe('exception') - expect(result.error?.message).toContain('kaboom') + it('enforces the combined output cap', async () => { + const { run } = await setup({ maxOutputBytes: 80 }) + const result = await run({ program: 'console.log("x".repeat(500)); return 42;', bindings: [] }) + expect(result.error?.kind).toBe('output-limit') + const bytes = Buffer.byteLength(JSON.stringify(result.logs)) + Buffer.byteLength(JSON.stringify(result.error?.message)) + expect(bytes).toBeLessThanOrEqual(80) }) - it('gives the program an EMPTY environment', async () => { + it('uses the default deadline and caps explicit requests', async () => { const { runtime } = await setup() - const result = await runtime.run({ program: 'return JSON.stringify(process.env)', bindings: [] }) - expect(result.value).toBe('{}') + expect(runtime.resolve({ program: '', bindings: [] }).timeoutMs).toBe(120_000) + expect(runtime.resolve({ program: '', bindings: [], timeoutMs: 900_000 }).timeoutMs).toBe(600_000) + for (const timeoutMs of [0, -1, NaN, Infinity]) expect(() => runtime.resolve({ program: '', bindings: [], timeoutMs })).toThrow() + await expect(runtime.run({ program: '', bindings: [], cwd: process.cwd(), timeoutMs: 1000 })).rejects.toThrow('sandbox policy') }) - it('rejects a non-lossless completion instead of replacing it with rendered text', async () => { - const { runtime } = await setup() - const result = await runtime.run({ program: 'return { f: () => 1 }', bindings: [] }) - expect(result.value).toBeUndefined() - expect(result.error).toEqual({ kind: 'invalid-output', message: 'program completion must be lossless JSON' }) + it.each(['for (;;) {}', 'await new Promise(() => {})'])('ends an unfinished program at its elapsed deadline: %s', async (program) => { + const { run } = await setup({ timeoutMs: 600, graceMs: 50 }) + expect((await run({ program, bindings: [] })).error?.kind).toBe('timeout') }) - it('completes a program that returns nothing with no value at all', async () => { - const { runtime } = await setup() - const result = await runtime.run({ program: 'const x = 1', bindings: [] }) - expect(result.error).toBeUndefined() - expect('value' in result).toBe(false) - }) - - it('keeps logs streamed before a failure', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: 'console.log("before"); throw new Error("after-log")', - bindings: [], - }) - expect(result.error?.kind).toBe('exception') - expect(result.logs).toContain('before') - }) -}) - -describe('NodeCodeRuntime — budgets and containment (real workers)', () => { - it('ends a hot loop at the compute budget — including behind a pending decoy dispatch', async () => { - const { runtime } = await setup({ computeMs: 300, maxWallMs: 30_000 }) - const result = await runtime.run({ - // The decoy: fire a call at a never-resolving binding WITHOUT awaiting, - // then spin. Host-side pending-call bookkeeping would pause a naive - // budget here; measured busy time cannot be fooled. - program: 'void tools.slow({}); for (;;) {}', - bindings: tools({ slow: () => new Promise(() => {}) }), - }) + it('does not pause the deadline while a binding is pending', async () => { + const { run } = await setup({ timeoutMs: 1000, graceMs: 50 }) + const result = await run({ program: 'void tools.wait({}); for (;;) {}', bindings: bindings({ wait: () => new Promise(() => {}) }) }) expect(result.error?.kind).toBe('timeout') - expect(result.error?.message).toContain('compute budget') - }, 15_000) + }) - it('does not charge time spent awaiting a slow binding against the compute budget', async () => { - // Source-worker bootstrap consumes busy time before the binding can begin. - // The idle delay must still exceed the entire compute allowance. - const computeMs = 5_000 - const bindingDelayMs = computeMs + 1_500 - const { ctx, runtime } = await setup({ computeMs, maxWallMs: 30_000 }) - let bindingTimer: ReturnType | undefined - onTestFinished(async () => { - clearTimeout(bindingTimer) - await ctx.fiber.dispose() - }) - const result = await runtime.run({ - program: 'return await tools.slow({})', - bindings: tools({ slow: () => new Promise((resolve) => { - bindingTimer = setTimeout(() => { resolve('slow-done') }, bindingDelayMs) - }) }), - }) - expect(result.error).toBeUndefined() - expect(result.value).toBe('slow-done') - }, 15_000) - - it('ends an idle-forever run at the wall-clock ceiling', async () => { - const { runtime } = await setup({ computeMs: 30_000, maxWallMs: 400 }) - const result = await runtime.run({ - program: 'await tools.never({}); return 1', - bindings: tools({ never: () => new Promise(() => {}) }), - }) - expect(result.error?.kind).toBe('timeout') - expect(result.error?.message).toContain('wall-clock ceiling') - }, 15_000) - - it('reports an abort mid-run and stops the worker', async () => { - const { runtime } = await setup() + it('cancels a live program and closes its managed process', async () => { + const { run } = await setup() + const entered = Promise.withResolvers() const controller = new AbortController() - setTimeout(() => { controller.abort('user-cancel') }, 150) - const result = await runtime.run({ program: 'for (;;) {}', bindings: [], signal: controller.signal }) - expect(result.error).toEqual({ kind: 'abort', message: 'user-cancel' }) - }, 15_000) - - it('reports a pre-aborted signal without spawning', async () => { - const { runtime } = await setup() - const controller = new AbortController() - controller.abort('too-late') - const result = await runtime.run({ program: 'return 1', bindings: [], signal: controller.signal }) - expect(result.error).toEqual({ kind: 'abort', message: 'too-late' }) + const active = run({ program: 'await tools.enter({}); for (;;) {}', signal: controller.signal, bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) }) + await entered.promise + controller.abort('stop') + expect((await active).error).toEqual({ kind: 'abort', message: 'stop' }) }) - it('applies the outer-output cap to failures before worker startup', async () => { - const capped = await setup({ maxOutputBytes: 64 }) - const controller = new AbortController() - controller.abort('A'.repeat(1_000)) - const aborted = await capped.runtime.run({ program: 'return 1', bindings: [], signal: controller.signal }) - expect(aborted).toEqual({ logs: [], error: { kind: 'output-limit', message: 'outer output exceeded 64 bytes' } }) - - const minimal = await setup({ maxOutputBytes: 4 }) - const invalid = await minimal.runtime.run({ program: 'enum E { A }\nreturn 1', bindings: [] }) - expect(invalid.error?.kind).toBe('output-limit') - expect(Buffer.byteLength(JSON.stringify(invalid.logs), 'utf8') + Buffer.byteLength(JSON.stringify(invalid.error?.message), 'utf8')).toBeLessThanOrEqual(4) + it('disposes active programs and rejects later execution', async () => { + const { ctx, run, runtime } = await setup() + const entered = Promise.withResolvers() + const active = run({ program: 'await tools.enter({}); await new Promise(() => {})', bindings: bindings({ enter: async () => { entered.resolve(undefined); return null } }) }) + await entered.promise + await ctx.fiber.dispose() + expect((await active).error?.kind).toBe('abort') + await expect(run({ program: '', bindings: [] })).rejects.toThrow('disposal') + expect(runtime.isolation).toBe('process') }) - it('drops a binding resolution that lands after the run settled', async () => { - const { runtime } = await setup() - const controller = new AbortController() - let replyDelivered!: Promise - const result = await runtime.run({ - program: 'void tools.late({}); for (;;) {}', - bindings: tools({ - // Anchored on invocation: abort 100ms after the call reaches the - // host, resolve 400ms after — by then the run has settled, so the - // resolution's reply hits the post-settlement drop. - late: () => new Promise((resolve) => { - setTimeout(() => { controller.abort('cancel-now') }, 100) - replyDelivered = new Promise(done => setTimeout(() => { resolve('too-late'); done() }, 400)) - }), - }), - signal: controller.signal, - }) - expect(result.error).toEqual({ kind: 'abort', message: 'cancel-now' }) - // Let the late resolution actually fire so its reply executes instead of - // being cancelled with the test. - await replyDelivered - }, 15_000) - - it('contains an OOM under resourceLimits as worker-exit, host process healthy', async () => { - const { runtime } = await setup({ maxOldGenerationSizeMb: 32 }) - const result = await runtime.run({ - program: 'const hog = []; for (;;) hog.push(new Array(1e6).fill(1));', - bindings: [], - }) - expect(result.error?.kind).toBe('worker-exit') - // And the host is fine: run something else. - const after = await runtime.run({ program: 'return "alive"', bindings: [] }) - expect(after.value).toBe('alive') - }, 30_000) - - it('reports a worker that exits before publishing a completion', async () => { - const { runtime } = await setup() - const result = await runtime.run({ program: 'process.exit(7)', bindings: [] }) - expect(result).toEqual({ - logs: [], - error: { kind: 'worker-exit', message: 'worker exited with code 7 before completing' }, - }) + it.each([ + 'const fs = await import("node:fs"); const b=Buffer.alloc(4); b.writeUInt32BE(4294967295); fs.writeSync(7,b); await new Promise(()=>{});', + 'const fs = await import("node:fs"); const body=Buffer.from(JSON.stringify({type:"call",id:1,global:"tools",name:"undeclared",args:[]})); const h=Buffer.alloc(4); h.writeUInt32BE(body.length); fs.writeSync(7,Buffer.concat([h,body])); await new Promise(()=>{});', + ])('refuses hostile program control traffic', async (program) => { + const { run } = await setup() + expect((await run({ program, bindings: [] })).error?.kind).toBe('protocol') }) - it('fails runaway log output explicitly while retaining a bounded prefix', async () => { - const { runtime } = await setup({ maxOutputBytes: 300 }) - const result = await runtime.run({ - program: 'for (let i = 0; i < 1000; i++) console.log("spam line", i); return 1', - bindings: [], - }) - expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 300 bytes' }) - expect(result.value).toBeUndefined() - expect(result.logs.length).toBeGreaterThan(0) - expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(300) + it('applies read-only confinement to direct Node filesystem writes', async () => { + const { run, cwd } = await setup({}, 'read-only') + const path = join(cwd, 'denied.txt') + const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(path)}, 'denied')`, bindings: [] }) + expect(result.error?.kind).toBe('exception') + expect(result.sandbox).toMatchObject({ mode: 'read-only', denied: true }) + await expect(readFile(path)).rejects.toMatchObject({ code: 'ENOENT' }) }) - it('retains a fitting prefix when one oversized log is the first output', async () => { - const { runtime } = await setup({ maxOutputBytes: 96 }) - const result = await runtime.run({ - program: 'console.log(`start-${`😀"\\\\\\n`.repeat(100)}`); return null', - bindings: [], - }) - expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 96 bytes' }) - expect(result.logs).toHaveLength(1) - expect(result.logs[0]?.startsWith('start-')).toBe(true) - expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') - + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(96) - }) - - it('fails an oversized return value without substituting a string', async () => { - const { runtime } = await setup({ maxOutputBytes: 64 }) - const result = await runtime.run({ program: 'return "y".repeat(10_000)', bindings: [] }) - expect(result.value).toBeUndefined() - expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' }) - }) - - it('uses UTF-8 serialized bytes at the exact completion boundary', async () => { - const exact = await setup({ maxOutputBytes: 7 }) - const exactResult = await exact.runtime.run({ program: 'return "€"', bindings: [] }) - // [] costs two bytes and JSON serialization of "€" costs five. - expect(exactResult).toEqual({ logs: [], value: '€' }) - - const over = await setup({ maxOutputBytes: 6 }) - const overResult = await over.runtime.run({ program: 'return "€"', bindings: [] }) - expect(overResult.error?.kind).toBe('output-limit') - }) - - it('accounts logs and completion in one exact combined ledger', async () => { - // JSON(["abc"]) is seven bytes and JSON("xy") is four. - const exact = await setup({ maxOutputBytes: 11 }) - expect(await exact.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] })) - .toEqual({ logs: ['abc'], value: 'xy' }) - - const over = await setup({ maxOutputBytes: 10 }) - const result = await over.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] }) - expect(result.value).toBeUndefined() - expect(result.error?.kind).toBe('output-limit') - expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(10) - }) - - it('accounts logs and exception diagnostics before the worker port boundary', async () => { - // JSON(["abc"]) is seven bytes and JSON("xy") is four. - const exact = await setup({ maxOutputBytes: 11 }) - expect(await exact.runtime.run({ program: 'console.log("abc"); throw "xy"', bindings: [] })) - .toEqual({ logs: ['abc'], error: { kind: 'exception', message: 'xy' } }) - - const over = await setup({ maxOutputBytes: 10 }) - const result = await over.runtime.run({ program: 'console.log("abc"); throw "xy"', bindings: [] }) - expect(result.error?.kind).toBe('output-limit') - expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') - + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(10) - }) - - it('does not send a giant Error stack across the worker port', async () => { - const { runtime } = await setup({ maxOutputBytes: 64 }) - const result = await runtime.run({ - program: 'throw new Error("x".repeat(1_000_000))', - bindings: [], - }) - expect(result).toEqual({ - logs: [], - error: { kind: 'output-limit', message: 'outer output exceeded 64 bytes' }, - }) - }) - - it('completes a program that awaits its write callback, capturing the chunk', async () => { - // Node's write(chunk[, encoding][, callback]) contract: dropping the - // callback would leave this promise pending until the wall ceiling and - // misreport a completed program as a timeout. - const { runtime } = await setup({ maxWallMs: 2_000 }) - const result = await runtime.run({ - program: 'await new Promise(resolve => process.stdout.write("flushed", resolve)); return "done"', - bindings: [], - }) - expect(result.error).toBeUndefined() - expect(result.value).toBe('done') - expect(result.logs).toContain('flushed') - }) - - it('returns a large JSON container exactly when the outer cap permits it', async () => { - const { runtime } = await setup() - const result = await runtime.run({ program: 'return new Array(50_000).fill(7)', bindings: [] }) - expect(result.error).toBeUndefined() - expect(result.value).toEqual(new Array(50_000).fill(7)) - }) - - it('returns an exact completion at the default 64 MiB combined boundary', async () => { - const { runtime } = await setup() - // [] costs two bytes and the JSON string contributes two quotes, leaving - // exactly this many payload bytes under the 67_108_864-byte default. - const result = await runtime.run({ program: 'return "x".repeat(67_108_860)', bindings: [] }) - expect(result.error).toBeUndefined() - expect(result.logs).toEqual([]) - expect(result.value).toHaveLength(67_108_860) - }, 60_000) - - it('fails one byte over the default 64 MiB combined boundary', async () => { - const { runtime } = await setup() - const result = await runtime.run({ program: 'return "x".repeat(67_108_861)', bindings: [] }) - expect(result.value).toBeUndefined() - expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' }) - }, 60_000) - - it('accounts pipe writes that bypass the patched write slot in the same outer ledger', async () => { - const { runtime } = await setup({ maxOutputBytes: 80 }) - const result = await runtime.run({ - // The prototype write bypasses the patched instance and reaches the real pipe. Pauses keep - // writes in separate chunks and let both reach the host before settlement. - program: ` - const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text); - write('a'.repeat(20)); - await new Promise(resolve => setTimeout(resolve, 150)); - write('b'.repeat(100)); - await new Promise(resolve => setTimeout(resolve, 100)); - return 1; - `, - bindings: [], - }) - expect(result.error?.kind).toBe('output-limit') - expect(result.logs).toContain('a'.repeat(20)) - expect(result.logs[1]?.length).toBeGreaterThan(0) - expect('b'.repeat(100).startsWith(result.logs[1] ?? '')).toBe(true) - }, 15_000) - - it('drains pipe output queued before terminal worker teardown completes', async () => { - const { runtime } = await setup({ maxOutputBytes: 200_000 }) - const payload = `late-pipe-${'x'.repeat(100_000)}` - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text); - write('late-pipe-' + 'x'.repeat(100_000)); - parentPort.postMessage({ type: 'done', value: ['done'] }); - for (;;) {} - `, - bindings: [], - }) - expect(result.error).toBeUndefined() - expect(result.value).toBe('done') - expect(result.logs.join('') === payload).toBe(true) - }, 15_000) -}) - -describe('NodeCodeRuntime — hostile programs (real workers)', () => { - it('survives forged port traffic: unknown binding names, duplicate ids, junk shapes', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} }); - parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} }); - parentPort.postMessage({ type: 'call', id: 7778, global: 'tools', name: 'constructor', args: {} }); - parentPort.postMessage({ type: 'junk' }); - return await tools.real({}); - `, - bindings: tools({ real: async () => 'still-works' }), - }) - expect(result.error).toBeUndefined() - expect(result.value).toBe('still-works') - }) - - it('survives arbitrary junk on the port: non-objects, junk types, malformed calls, logs, and dones', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - for (const junk of [ - null, 42, 'junk', [], - { type: 'nope' }, - { type: 'call' }, - { type: 'call', id: 'x', global: 'tools', name: 'real', args: {} }, - { type: 'call', id: 1e9, global: 7, name: 'real', args: {} }, - { type: 'call', id: 1e9, global: 'tools', name: 7, args: {} }, - { type: 'log' }, - { type: 'log', text: null }, - { type: 'log', text: 7 }, - { type: 'log', text: {} }, - { type: 'done', error: 5 }, - { type: 'done', error: { kind: 'exception', message: 5 } }, - { type: 'done', error: { kind: 'invented', message: 'bad kind' } }, - ]) parentPort.postMessage(junk); - return await tools.real({}); - `, - bindings: tools({ real: async () => 'still-works' }), - }) - expect(result.error).toBeUndefined() - expect(result.value).toBe('still-works') - expect(result.logs).toEqual([]) - }) - - it('fails forged log floods and forged done values through the same outer cap', async () => { - const { runtime } = await setup({ maxOutputBytes: 200 }) - const result = await runtime.run({ - // Forged messages bypass the worker-side LogBuffer and completion check - // entirely — only the host-side ledger and re-cap stand between model - // code and an unbounded result. - program: ` - const { parentPort } = await import('node:worker_threads'); - for (let i = 0; i < 50; i++) parentPort.postMessage({ type: 'log', text: 'F'.repeat(100), forged: true }); - parentPort.postMessage({ type: 'done', value: ['V'.repeat(100000)] }); - for (;;) {} - `, - bindings: [], - }) - expect(result.value).toBeUndefined() - expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 200 bytes' }) - expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(200) - }) - - it('re-caps an oversized forged done value at the host boundary', async () => { - const { runtime } = await setup({ maxOutputBytes: 64 }) - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - parentPort.postMessage({ type: 'done', value: ['V'.repeat(100_000)] }); - for (;;) {} - `, - bindings: [], - }) - expect(result).toEqual({ - logs: [], - error: { kind: 'output-limit', message: 'outer output exceeded 64 bytes' }, - }) - }) - - it('bounds one oversized forged log while retaining its fitting escaped prefix', async () => { - const { runtime } = await setup({ maxOutputBytes: 96 }) - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - parentPort.postMessage({ type: 'log', text: '"'.repeat(1_000_000) }); - for (;;) {} - `, - bindings: [], - }) - expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 96 bytes' }) - expect(result.logs).toHaveLength(1) - expect(result.logs[0]).toMatch(/^"+$/) - expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') + Buffer.byteLength(JSON.stringify('outer output exceeded 96 bytes'), 'utf8')).toBeLessThanOrEqual(96) - }) - - it('drops a malformed forged done carrying both value and error', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - parentPort.postMessage({ type: 'done', value: 'lied', error: { kind: 'exception', message: 'fake failure' } }); - return 'honest'; - `, - bindings: [], - }) - expect(result).toEqual({ logs: [], error: { kind: 'exception', message: 'fake failure' } }) - }) - - it('contains a deeply nested forged completion without overflowing the host meter', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - const value = []; - for (let depth = 0; depth < 3_000; depth++) value.push({ kind: 'array', length: 1 }); - value.push(null); - setTimeout(() => { parentPort.postMessage({ type: 'done', value }) }, 25); - // Prevent bootstrap's normal undefined completion from racing the forged terminal. - await new Promise(() => {}); - `, - bindings: [], - }) - expect(result.error).toBeUndefined() - let value = result.value - let depth = 0 - while (Array.isArray(value)) { - expect(value).toHaveLength(1) - value = value[0] - depth += 1 - } - expect(depth).toBe(3_000) - expect(value).toBeNull() - }, 15_000) - - it('turns forged over-limit error text into output-limit at the host', async () => { - const { runtime } = await setup({ maxOutputBytes: 64 }) - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - parentPort.postMessage({ type: 'done', error: { kind: 'exception', message: '€'.repeat(1000) } }); - for (;;) {} - `, - bindings: [], - }) - expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' }) - }) - - it('answers a binding whose resolution is not lossless JSON with a typed failure reply', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }', - bindings: tools({ bad: async () => (() => 1) }), - }) - expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' }) - }) - - it('rejects lossy binding arguments in the worker before invoking the host binding', async () => { - const { runtime } = await setup() - let calls = 0 - const result = await runtime.run({ - program: ` - const decorated = [1]; Object.defineProperty(decorated, 'extra', { value: true }); - const values = [new Date(), decorated, () => 1]; - const failures = []; - for (const value of values) { - try { await tools.never(value) } catch (error) { - failures.push({ typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message }); - } - } - return failures; - `, - bindings: tools({ never: async () => { calls += 1; return null } }), - }) - expect(calls).toBe(0) - expect(result.value).toEqual(new Array(3).fill({ - typed: true, - name: 'ToolCallError', - toolName: 'never', - message: 'binding arguments must be lossless JSON', - })) - }) - - it('rejects intrinsic-looking exotic objects as arguments and completions', async () => { - const { runtime } = await setup() - let calls = 0 - const forgeObject = ` - const prototype = Object.create(null); - const SpoofedObject = function Object() {}; - SpoofedObject.prototype = prototype; - Object.defineProperty(prototype, 'constructor', { value: SpoofedObject }); - const forged = Object.assign(Object.create(prototype), { value: 1 }); - Function.prototype.toString = () => 'function Object() { [native code] }'; - ` - const argument = await runtime.run({ - program: `${forgeObject} - try { await tools.never(forged) } catch (error) { - return { typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message }; - } - `, - bindings: tools({ never: async () => { calls += 1; return null } }), - }) - expect(calls).toBe(0) - expect(argument.value).toEqual({ - typed: true, - name: 'ToolCallError', - toolName: 'never', - message: 'binding arguments must be lossless JSON', - }) - - const completion = await runtime.run({ program: `${forgeObject}\nreturn forged`, bindings: [] }) - expect(completion).toEqual({ - logs: [], - error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' }, - }) - }) - - it('preserves binding and completion JSON after model code mutates boundary globals', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - const arrayPrototype = Array.prototype; - const objectPrototype = Object.prototype; - const setPrototype = Set.prototype; - const stringPrototype = String.prototype; - Array.isArray = () => false; - arrayPrototype.at = arrayPrototype.includes = arrayPrototype.pop = arrayPrototype.push = () => { throw new Error('mutated array method') }; - Object.defineProperty = Object.getOwnPropertyDescriptor = Object.getPrototypeOf = Object.keys = () => { throw new Error('mutated object method') }; - Object.hasOwn = () => false; - Object.is = () => true; - objectPrototype.propertyIsEnumerable = () => false; - Number.isFinite = Number.isSafeInteger = () => false; - Reflect.apply = Reflect.ownKeys = () => { throw new Error('mutated reflect method') }; - setPrototype.add = setPrototype.delete = setPrototype.has = () => { throw new Error('mutated set method') }; - stringPrototype.charCodeAt = stringPrototype.codePointAt = stringPrototype.slice = () => { throw new Error('mutated string method') }; - Buffer.byteLength = () => 0; - Function.prototype.toString = () => 'mutated'; - objectPrototype.get = () => undefined; - objectPrototype.constructor = arrayPrototype.constructor = null; - globalThis.Array = globalThis.Buffer = globalThis.Error = globalThis.Function = globalThis.Number = globalThis.Object = globalThis.Reflect = globalThis.Set = globalThis.String = undefined; - const echoed = await tools.echo({ request: ['€', 1] }); - let failure; - try { await tools.fail({}) } catch (error) { - failure = { typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message }; - } - return { echoed, failure, completion: { ok: true, amount: 42 } }; - `, - bindings: tools({ echo: async args => args, fail: async () => { throw new Error('nope') } }), - }) - expect(result).toEqual({ - logs: [], - value: { - echoed: { request: ['€', 1] }, - failure: { typed: true, name: 'ToolCallError', toolName: 'fail', message: 'nope' }, - completion: { ok: true, amount: 42 }, - }, - }) - }) - - it('rejects forged lossy binding arguments again at the host boundary', async () => { - const { runtime } = await setup() - let calls = 0 - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - const forged = (id, args) => new Promise((resolve) => { - const receive = (message) => { - if (message?.type !== 'reply' || message.id !== id) return; - parentPort.off('message', receive); - resolve(message); - }; - parentPort.on('message', receive); - parentPort.postMessage({ type: 'call', id, global: 'tools', name: 'never', args }); - }); - const sparse = []; sparse.length = 1; - const cycle = {}; cycle.self = cycle; - return await Promise.all([ - forged(8001, new Date()), - forged(8002, -0), - forged(8003, sparse), - forged(8004, cycle), - ]); - `, - bindings: tools({ never: async () => { calls += 1; return null } }), - }) - expect(calls).toBe(0) - expect(result.value).toEqual([8001, 8002, 8003, 8004].map(id => ({ - type: 'reply', - id, - ok: false, - message: 'binding arguments must be lossless JSON', - }))) - }) - - it('contains throwing getters while snapshotting binding resolutions', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }', - bindings: tools({ bad: async () => Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('getter exploded') } }) }), - }) - expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' }) - }) - - it('revalidates a forged lossy completion at the host boundary', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - parentPort.postMessage({ type: 'done', value: -0 }); - for (;;) {} - `, - bindings: [], - }) - expect(result).toEqual({ logs: [], error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } }) - }) - - it('honors a forged worker-side output-limit signal', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: ` - const { parentPort } = await import('node:worker_threads'); - parentPort.postMessage({ type: 'output-limit' }); - for (;;) {} - `, - bindings: [], - }) - expect(result).toEqual({ logs: [], error: { kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' } }) - }) - - it('exposes binding names that collide with Object.prototype as ordinary functions', async () => { - const { runtime } = await setup() - const result = await runtime.run({ - program: 'return [await tools["__proto__"]({}), await tools["constructor"]({}), typeof tools["hasOwnProperty"]]', - // Computed keys: a literal `'__proto__': …` entry would SET the record's - // prototype instead of declaring a binding of that name. - bindings: tools({ ['__proto__']: async () => 'proto-ok', ['constructor']: async () => 'ctor-ok' }), - }) - expect(result.value).toEqual(['proto-ok', 'ctor-ok', 'undefined']) - }) -}) - -describe('NodeCodeRuntime — seam misuse and lifecycle', () => { - it('rejects invalid and duplicate binding globals loudly', async () => { - const { runtime } = await setup() - const cases: [string, RegExp][] = [ - ['not valid!', /not a usable identifier/], - ['await', /not a usable identifier/], - // `$tools` is legal JS but outside the seam's language-portable subset: - // the same namespace list must work against every backend's language. - ['$tools', /not a usable identifier/], - // `a$b` pins the second character class too: the old identifier regex - // `[A-Za-z0-9_$]*` would have accepted a `$` after the first character. - ['a$b', /not a usable identifier/], - // `lambda` is a Python keyword, refused here directly (not just - // transitively) so the worker's adoption of PORTABLE_RESERVED_WORDS is - // its own regression, symmetric with the `$tools` case. - ['lambda', /not a usable identifier/], - ['console', /reserved binding global/], - ] - for (const [global, message] of cases) { - await expect(runtime.run({ program: 'return 1', bindings: [{ global, functions: {} }] })).rejects.toThrow(message) - } - await expect(runtime.run({ - program: 'return 1', - bindings: [{ global: 'tools', functions: {} }, { global: 'tools', functions: {} }], - })).rejects.toThrow(/duplicate binding global/) - - await expect(runtime.run({ - program: 'return typeof ToolCallError', - bindings: [{ global: 'ToolCallError', functions: {} }], - })).resolves.toMatchObject({ value: 'object' }) - }) - - it('rejects malformed or colliding binding error-class declarations', async () => { - const { runtime } = await setup() - const run = async (bindings: CodeBindingNamespace[]) => await runtime.run({ program: 'return 1', bindings }) - const namespace = (global: string, name: string, memberNameProperty = 'memberName'): CodeBindingNamespace => ({ - global, - functions: {}, - errorClass: { name, memberNameProperty }, - }) - - await expect(run([namespace('tools', 'not valid!')])).rejects.toThrow(/error class.*not a usable identifier/) - await expect(run([namespace('tools', 'await')])).rejects.toThrow(/error class.*not a usable identifier/) - await expect(run([namespace('tools', 'console')])).rejects.toThrow(/reserved binding global/) - await expect(run([namespace('tools', 'tools')])).rejects.toThrow(/duplicate injected global/) - await expect(run([ - namespace('tools', 'CallError'), - namespace('helpers', 'CallError'), - ])).rejects.toThrow(/duplicate injected global/) - await expect(run([namespace('tools', 'CallError', '')])).rejects.toThrow(/member property.*not usable/) - await expect(run([namespace('tools', 'CallError', 'message')])).rejects.toThrow(/member property.*not usable/) - // The shared exclusion set covers Python's exception-protocol members and - // dunders too, so the same errorClass is valid (or not) on every backend. - await expect(run([namespace('tools', 'CallError', 'args')])).rejects.toThrow(/member property.*not usable/) - await expect(run([namespace('tools', 'CallError', '__dict__')])).rejects.toThrow(/member property.*not usable/) - // The Python backend's owned globals are refused here too (shared - // RESERVED_BINDING_GLOBALS), keeping namespace lists backend-portable. - await expect(runtime.run({ program: 'return 1', bindings: [{ global: '__dsh_main__', functions: {} }] })) - .rejects.toThrow(/reserved binding global/) - }) - - it('rejects config values that are not positive numbers', async () => { - const ctx = new Context() - await expect(ctx.plugin(NodeCodeRuntime, { computeMs: -1 })).rejects.toThrow(/positive number/) - }) - - it('rejects a maxWallMs above Node\'s maximum timer delay', async () => { - // setTimeout clamps a delay past 2^31-1 ms to 1 ms, so the positivity check - // alone would accept a 25-day ceiling that expires on the first tick. - const ctx = new Context() - await expect(ctx.plugin(NodeCodeRuntime, { maxWallMs: 2_147_483_648 })) - .rejects.toThrow(/maxWallMs must be at most 2147483647/) - // The boundary itself is usable. - await expect(ctx.plugin(NodeCodeRuntime, { maxWallMs: 2_147_483_647 })).resolves.toBeTruthy() - }) - - it('requires maxOutputBytes to fit the smallest counted outer payloads', async () => { - const ctx = new Context() - await expect(ctx.plugin(NodeCodeRuntime, { maxOutputBytes: 3 })).rejects.toThrow(/safe integer of at least 4/) - await expect(ctx.plugin(NodeCodeRuntime, { maxOutputBytes: 4.5 })).rejects.toThrow(/safe integer of at least 4/) - }) - - it('keeps runs isolated: no state survives from one run to the next', async () => { - const { runtime } = await setup() - await runtime.run({ program: 'globalThis.leak = "value"; return 1', bindings: [] }) - const second = await runtime.run({ program: 'return typeof globalThis.leak', bindings: [] }) - expect(second.value).toBe('undefined') - }) - - it('disposal aborts in-flight runs, awaits worker exit, and rejects later runs', async () => { - const ctx = new Context() - const fiber = await ctx.plugin(NodeCodeRuntime) - const runtime = ctx.codeRuntime as NodeCodeRuntime - const inflight: Promise = runtime.run({ program: 'for (;;) {}', bindings: [] }) - // Give the worker a moment to actually start spinning. - await new Promise(resolve => setTimeout(resolve, 200)) - await fiber.dispose() - const result = await inflight - expect(result.error).toEqual({ kind: 'abort', message: 'runtime disposed' }) - await expect(runtime.run({ program: 'return 1', bindings: [] })).rejects.toThrow(/after disposal/) - }, 15_000) - - it('removes ctx.codeRuntime when the providing fiber disposes (HMR safety)', async () => { - const ctx = new Context() - const fiber = await ctx.plugin(NodeCodeRuntime) - expect(ctx.get('codeRuntime')).toBeInstanceOf(NodeCodeRuntime) - await fiber.dispose() - expect(ctx.get('codeRuntime')).toBeUndefined() + it('permits workspace writes and denies a symlink to a sibling outside it', async () => { + const { run, cwd, root } = await setup({}, 'workspace-write') + const target = join(cwd, 'allowed.txt') + expect((await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(target)}, 'allowed'); return true`, bindings: [] })).value).toBe(true) + expect(await readFile(target, 'utf8')).toBe('allowed') + const outside = join(root, 'outside') + await mkdir(outside) + await symlink(outside, join(cwd, 'escape'), process.platform === 'win32' ? 'junction' : 'dir') + const result = await run({ program: `await (await import('node:fs/promises')).writeFile(${JSON.stringify(join(cwd, 'escape', 'denied.txt'))}, 'denied')`, bindings: [] }) + expect(result.error?.kind).toBe('exception') + expect(result.sandbox).toMatchObject({ mode: 'workspace-write', denied: true }) + await expect(readFile(join(outside, 'denied.txt'))).rejects.toMatchObject({ code: 'ENOENT' }) }) }) diff --git a/packages/code-runtime/code-runtime-node/tests/setup.ts b/packages/code-runtime/code-runtime-node/tests/setup.ts new file mode 100644 index 0000000000..245729e194 --- /dev/null +++ b/packages/code-runtime/code-runtime-node/tests/setup.ts @@ -0,0 +1,19 @@ +import { Context } from '@deepseek-ai/cordis' +import FileSystem from '@deepseek-ai/dsh-fs-local' +import Subprocess from '@deepseek-ai/dsh-subprocess-local' +import Sandbox from '@deepseek-ai/dsh-sandbox-local' +import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' +import SessionProjections from '@deepseek-ai/dsh-session-projection' +import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' +import NodeRuntime from '../src/index.ts' +import type { Config } from '../src/index.ts' + +export async function mountRuntime(ctx: Context, config: Config = {}, policy: { mode?: SandboxMode; workspaceRoot?: string } = {}) { + if (!ctx.get('fs')) await ctx.plugin(FileSystem) + if (!ctx.get('subprocess')) await ctx.plugin(Subprocess) + if (!ctx.get('sandbox')) await ctx.plugin(Sandbox, {}) + if (!ctx.get('sessionProjections')) await ctx.plugin(SessionProjections) + if (!ctx.get('sandboxPolicy')) await ctx.plugin(SandboxPolicy, { mode: 'danger-full-access', ...policy }) + await ctx.plugin(NodeRuntime, config) + return ctx.codeRuntime as NodeRuntime +} diff --git a/packages/code-runtime/code-runtime-node/tests/source-worker.compat.spec.ts b/packages/code-runtime/code-runtime-node/tests/source-worker.compat.spec.ts deleted file mode 100644 index 6ef2775114..0000000000 --- a/packages/code-runtime/code-runtime-node/tests/source-worker.compat.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { copyFile, mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { Worker } from 'node:worker_threads' -import { expect, it } from 'vitest' -import { decodeWorkerJson } from '../src/worker-json.ts' - -/** - * Prove the unbuilt worker is a self-contained source closure. Copying it out - * of the workspace makes any package runtime import fail even when local - * `lib/` artifacts happen to exist. - */ -it('boots the source worker without workspace package outputs', async () => { - const directory = await mkdtemp(join(tmpdir(), 'dsh-code-source-worker-')) - let worker: Worker | undefined - try { - const files = ['worker.ts', 'bootstrap.ts', 'protocol.ts', 'worker-json.ts', 'output-json.ts'] - await Promise.all(files.map(async (file) => { - await copyFile(new URL(`../src/${file}`, import.meta.url), join(directory, file)) - })) - - worker = new Worker(join(directory, 'worker.ts'), { - workerData: { code: 'return { answer: 42 }', namespaces: [], maxOutputBytes: 65_536 }, - env: {}, - execArgv: [], - }) - const message = await new Promise((resolve, reject) => { - worker?.once('message', resolve) - worker?.once('error', reject) - }) - - expect(message).toMatchObject({ type: 'done' }) - const value = typeof message === 'object' && message !== null ? (message as { value?: unknown }).value : undefined - expect(decodeWorkerJson(value)).toEqual({ answer: 42 }) - } finally { - if (worker) await worker.terminate() - await rm(directory, { recursive: true, force: true }) - } -}) diff --git a/packages/code-runtime/code-runtime-node/tsconfig.json b/packages/code-runtime/code-runtime-node/tsconfig.json index 2bbaf44da7..99dc9c158f 100644 --- a/packages/code-runtime/code-runtime-node/tsconfig.json +++ b/packages/code-runtime/code-runtime-node/tsconfig.json @@ -25,6 +25,18 @@ }, { "path": "../../util/timeout" + }, + { + "path": "../../fs/fs" + }, + { + "path": "../../subprocess/subprocess" + }, + { + "path": "../../sandbox/sandbox" + }, + { + "path": "../../sandbox/sandbox-policy" } ] } diff --git a/packages/code-runtime/code-runtime-node/tsdown.config.ts b/packages/code-runtime/code-runtime-node/tsdown.config.ts index 6fee724195..820b4d923f 100644 --- a/packages/code-runtime/code-runtime-node/tsdown.config.ts +++ b/packages/code-runtime/code-runtime-node/tsdown.config.ts @@ -1,29 +1,7 @@ import { defineConfig } from 'tsdown' -/** - * Build the index and worker as separate single-entry bundles. The sibling `worker.cjs` is loaded - * by file and must be CommonJS for pkg's VFS Worker hook. A multi-entry build emits an unlisted - * shared chunk omitted by the package's exact `files` whitelist; separate builds inline it. - */ +/** Separate entry bundles keep the private process bootstrap self-contained. */ export default defineConfig([ - { - entry: ['lib/types/index.js'], - outDir: 'lib', - format: ['esm'], - platform: 'node', - target: 'es2024', - fixedExtension: false, - dts: false, - clean: false, - }, - { - entry: ['lib/types/worker.js'], - outDir: 'lib', - format: ['cjs'], - platform: 'node', - target: 'es2024', - fixedExtension: false, - dts: false, - clean: false, - }, + { entry: ['lib/types/index.js'], outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', fixedExtension: false, dts: false, clean: false }, + { entry: { process: 'lib/types/process-entry.js' }, outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', fixedExtension: false, dts: false, clean: false, noExternal: ['@deepseek-ai/dsh-subprocess/control'] }, ]) diff --git a/packages/code-runtime/code-runtime/package.json b/packages/code-runtime/code-runtime/package.json index 7e31f4998e..f9cd506334 100644 --- a/packages/code-runtime/code-runtime/package.json +++ b/packages/code-runtime/code-runtime/package.json @@ -27,9 +27,11 @@ ], "license": "MIT", "peerDependencies": { - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-sandbox": "workspace:^" }, "devDependencies": { - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-sandbox": "workspace:^" } } diff --git a/packages/code-runtime/code-runtime/src/index.ts b/packages/code-runtime/code-runtime/src/index.ts index 7314131279..a7e58a78c0 100644 --- a/packages/code-runtime/code-runtime/src/index.ts +++ b/packages/code-runtime/code-runtime/src/index.ts @@ -5,7 +5,8 @@ */ import { Context, Service } from '@deepseek-ai/cordis' -import type { CodeRunRequest, CodeRunResult } from './types.ts' +import type { CodeRunRequest, CodeRunResult, CodeRunSpec } from './types.ts' +import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' export type { CodeBindingErrorClass, @@ -15,6 +16,8 @@ export type { CodeRunFailure, CodeRunRequest, CodeRunResult, + CodeRunSpec, + CodeRunSandbox, } from './types.ts' /** @@ -118,20 +121,27 @@ export abstract class CodeRuntime extends Service { */ abstract readonly isolation: string + /** Deployment file-policy mode, or undefined for a provider without confinement support. */ + get sandboxMode(): SandboxMode | undefined { return undefined } + constructor(ctx: Context) { super(ctx, 'codeRuntime') } /** - * Execute one program against the request's bindings and capture what it - * emitted. See the class doc for the resolution contract (error is a result - * field; rejection means Service Definition contract misuse only). - * @param request - the program, its bindings, and the abort signal; the - * request carries everything the runtime acts on, with no hidden defaults. - * @returns the run's outcome: completion value (when transferable), the - * ordered log capture, and the failure (if any). + * Resolve supported options and provider defaults before execution. + * @param request - Program, bindings, cancellation and optional execution choices. + * @returns Complete directory, deadline and supported authority for run. + * @throws When an explicit choice is invalid or unsupported by this provider. */ - abstract run(request: CodeRunRequest): Promise + abstract resolve(request: CodeRunRequest): CodeRunSpec + + /** + * Execute resolved inputs; program outcomes resolve as result fields. + * @param spec - directory, deadline, program, bindings, cancellation and supported policy. + * @returns Captured output and the execution outcome. + */ + abstract run(spec: CodeRunSpec): Promise } export default CodeRuntime diff --git a/packages/code-runtime/code-runtime/src/types.ts b/packages/code-runtime/code-runtime/src/types.ts index a6f80d4d00..9d1a3e1f13 100644 --- a/packages/code-runtime/code-runtime/src/types.ts +++ b/packages/code-runtime/code-runtime/src/types.ts @@ -6,6 +6,8 @@ * @module @deepseek-ai/dsh-code-runtime/src/types */ +import type { SandboxEnforcement, SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' + /** * One host-side function exposed to the program as an async callable. The * runtime bridges calls to it (possibly across a serialization boundary), so @@ -65,10 +67,8 @@ export interface CodeBindingNamespace { } /** - * One run: the program source plus everything the runtime acts on. Per the - * explicit-over-implicit convention, defaulting (time budgets, output caps) - * is the implementation's validated config — a request carries no optional - * tuning knobs for a hidden `??` to fill in. + * Caller inputs for one program. The provider's resolve method validates supported + * options and supplies directory, deadline, and authority before execution. */ export interface CodeRunRequest { /** @@ -80,6 +80,12 @@ export interface CodeRunRequest { program: string /** Host functions exposed to the program, one global object per namespace. */ bindings: CodeBindingNamespace[] + /** Working directory in the mounted filesystem and subprocess execution world. */ + cwd?: string + /** Requested elapsed execution time; the provider's resolver validates and caps it. */ + timeoutMs?: number + /** Resolved authority for this execution. Providers without confinement reject an explicit policy. */ + sandboxPolicy?: SandboxExecutionPolicy /** * Abort the run: the runtime stops the program (hard, even mid-loop) and * resolves with a {@link CodeRunFailure} of kind `'abort'`. In-flight @@ -88,6 +94,24 @@ export interface CodeRunRequest { signal?: AbortSignal } +/** Fully resolved execution inputs; run never supplies a missing directory or timeout. */ +export interface CodeRunSpec extends CodeRunRequest { + /** Absolute directory in the provider's execution world. */ + cwd: string + /** Positive finite execution deadline in milliseconds, after provider capping. */ + timeoutMs: number +} + +/** File confinement applied to a program, independently of its terminal outcome. */ +export interface CodeRunSandbox { + /** File-effect mode used for this execution. */ + mode: SandboxMode + /** Whether an observed failure matches the selected backend's denial diagnostics. */ + denied: boolean + /** Completeness reported by the selected confining backend; absent for full access. */ + enforcement?: SandboxEnforcement +} + /** * Why a run failed. The kinds are orthogonal outcomes reported independently * (per docs/defensive-patterns.md): a budget expiry is not an exception, an @@ -102,7 +126,7 @@ export interface CodeRunRequest { */ export interface CodeRunFailure { /** The failure class (see the interface doc for each kind's meaning). */ - kind: 'exception' | 'timeout' | 'abort' | 'worker-exit' | 'invalid-output' | 'output-limit' + kind: 'exception' | 'timeout' | 'abort' | 'worker-exit' | 'invalid-output' | 'output-limit' | 'protocol' | 'sandbox-unavailable' /** Human-readable detail, suitable for feeding back to a model to self-correct. */ message: string } @@ -113,6 +137,8 @@ export interface CodeRunFailure { * an exception path. */ export interface CodeRunResult { + /** Applied file policy and observed denial, when the provider enforces file policy. */ + sandbox?: CodeRunSandbox /** * The program's completion value (its top-level `return`), when it ran to * completion and the value crossed the runtime's lossless-JSON boundary. diff --git a/packages/code-runtime/code-runtime/tests/service.spec.ts b/packages/code-runtime/code-runtime/tests/service.spec.ts index 44e356329a..3b4685d37d 100644 --- a/packages/code-runtime/code-runtime/tests/service.spec.ts +++ b/packages/code-runtime/code-runtime/tests/service.spec.ts @@ -10,6 +10,8 @@ import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtim * the smallest subclass that honors it. */ class StubRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language = 'typescript' readonly isolation = 'in-process-stub' requests: CodeRunRequest[] = [] @@ -43,10 +45,10 @@ describe('CodeRuntime service seam', () => { expect(runtime.isolation).toBe('in-process-stub') const calls: unknown[] = [] - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: { probe: async (args) => { calls.push(args); return null } } }], - }) + })) expect(result).toEqual({ logs: [] }) expect(calls).toEqual([{ from: 'stub' }]) expect(runtime.requests).toHaveLength(1) @@ -58,7 +60,7 @@ describe('CodeRuntime service seam', () => { logs: ['boom'], error: { kind: 'exception', message: 'boom' }, } - const result = await runtime.run({ program: 'throw new Error("boom")', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'throw new Error("boom")', bindings: [] })) expect(result.error).toEqual({ kind: 'exception', message: 'boom' }) expect(result.value).toBeUndefined() }) @@ -67,7 +69,7 @@ describe('CodeRuntime service seam', () => { const { runtime } = await setup() const controller = new AbortController() controller.abort('cancelled') - const result = await runtime.run({ program: 'return 1', bindings: [], signal: controller.signal }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [], signal: controller.signal })) expect(result.error).toEqual({ kind: 'abort', message: 'cancelled' }) }) diff --git a/packages/code-runtime/code-runtime/tsconfig.json b/packages/code-runtime/code-runtime/tsconfig.json index 754725418e..de6feb55b9 100644 --- a/packages/code-runtime/code-runtime/tsconfig.json +++ b/packages/code-runtime/code-runtime/tsconfig.json @@ -13,6 +13,9 @@ }, { "path": "../../../vendor/cordis" + }, + { + "path": "../../sandbox/sandbox" } ] } diff --git a/packages/core/agent-loop/tests/tool-calls.spec.ts b/packages/core/agent-loop/tests/tool-calls.spec.ts index 74871d4a0d..3aeabad540 100644 --- a/packages/core/agent-loop/tests/tool-calls.spec.ts +++ b/packages/core/agent-loop/tests/tool-calls.spec.ts @@ -699,6 +699,8 @@ describe('tool-call scheduler: failure quiescence', () => { describe('PTC mode native-tool denial through the agent loop', () => { /** A minimal in-process code runtime for test purposes — never actually runs. */ class FakeCodeRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language = 'typescript' readonly isolation = 'fake' as const async run(_request: CodeRunRequest): Promise { diff --git a/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts b/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts index 3110036e26..51f6062a10 100644 --- a/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts +++ b/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts @@ -19,6 +19,8 @@ import { apply, Config, inject, name } from '@deepseek-ai/dsh-agent-tool-present /** A runtime that never runs anything: presentation never dispatches. */ class StubRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language = 'typescript' readonly isolation = 'stub' diff --git a/packages/core/tools/package.json b/packages/core/tools/package.json index e3d6cdc3b8..c501d07d90 100644 --- a/packages/core/tools/package.json +++ b/packages/core/tools/package.json @@ -49,7 +49,9 @@ "@deepseek-ai/dsh-scope": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", - "@deepseek-ai/dsh-user-approval": "workspace:^" + "@deepseek-ai/dsh-user-approval": "workspace:^", + "@deepseek-ai/dsh-sandbox": "workspace:^", + "@deepseek-ai/dsh-sandbox-policy": "workspace:^" }, "dependencies": { "@deepseek-ai/dsh-brand": "workspace:^", @@ -66,6 +68,8 @@ "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", - "@deepseek-ai/dsh-user-approval": "workspace:^" + "@deepseek-ai/dsh-user-approval": "workspace:^", + "@deepseek-ai/dsh-sandbox": "workspace:^", + "@deepseek-ai/dsh-sandbox-policy": "workspace:^" } } diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index 9e40c34b90..103451d48a 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -15,6 +15,7 @@ import type { UserMessage } from '@deepseek-ai/dsh-session' import { assertNever, deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values' import type { PromptSection, ToolProviderResult } from '@deepseek-ai/dsh-system-prompt' import type { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' +import type {} from '@deepseek-ai/dsh-sandbox-policy' // Type-only: makes `ctx.get('approval')` resolve to the ApprovalService // augmentation. The seam stays optional at runtime — see `serviceAsk`. import type {} from '@deepseek-ai/dsh-user-approval' @@ -915,6 +916,11 @@ export class ToolRuntime extends Service { private requireCodeTransport(): ToolDefinition { this.ptcTransport ??= createRunCodeTool(this, { requireRuntime: () => this.requireCodeRuntime(this.defaultMode), + resolveSandboxPolicy: (exec) => { + const policy = this.ctx.get('sandboxPolicy') + if (policy === undefined) throw new Error('dsh-tools: confined code runtime requires sandboxPolicy') + return policy.resolve({ session: exec.agent?.session }) + }, // The language-aware description/parameters getters read the runtime // without demanding one, so a native-default process can still project // the transport for an agent that chose code. diff --git a/packages/core/tools/src/ptc.ts b/packages/core/tools/src/ptc.ts index cc6e947997..f76f2bfff9 100644 --- a/packages/core/tools/src/ptc.ts +++ b/packages/core/tools/src/ptc.ts @@ -9,7 +9,8 @@ import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, HarnessError } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId } from '@deepseek-ai/dsh-llm' -import type { CodeBindingFunction, CodeRunResult, CodeRuntime } from '@deepseek-ai/dsh-code-runtime' +import type { CodeBindingFunction, CodeRunResult, CodeRunSandbox, CodeRuntime } from '@deepseek-ai/dsh-code-runtime' +import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' import { snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values' import { defineTool, parameterSchemaSpecToJsonSchema } from './schema.ts' import { TOOL_RUNTIME_SCHEDULER } from './index.ts' @@ -256,7 +257,7 @@ function renderValue(value: JsonValue): string { } /** Canonical value returned by the outer PTC mode transport. */ -type RunCodeOutput = { logs: string[]; result?: JsonValue } +type RunCodeOutput = { logs: string[]; result?: JsonValue; sandbox?: CodeRunSandbox } /** * Registry-private capabilities the bridge receives at construction — the @@ -264,6 +265,8 @@ type RunCodeOutput = { logs: string[]; result?: JsonValue } * off its public service API and flow here as closures instead. */ export interface RunCodeBridgeOptions { + /** Resolves standing Session authority only for a runtime that enforces file policy. */ + resolveSandboxPolicy: (exec: ToolRunContext) => SandboxExecutionPolicy /** Resolves `ctx.codeRuntime` or throws the loud misconfiguration error (shared with the registry's assembly-time checks). */ requireRuntime: () => CodeRuntime /** @@ -316,11 +319,22 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO properties: { logs: { type: 'array', required: true, items: { type: 'string' } }, result: { type: 'json' }, + sandbox: { + type: 'object', + additionalProperties: false, + properties: { + mode: { type: 'string', required: true, enum: ['read-only', 'workspace-write', 'danger-full-access'] }, + denied: { type: 'boolean', required: true }, + enforcement: { type: 'string', enum: ['full', 'partial'] }, + }, + }, }, }, render: (_args, value) => { const rendered = value.result === undefined ? '' : renderValue(value.result) const parts = [value.logs.join('\n'), rendered].filter(part => part.length > 0) + if (value.sandbox?.enforcement === 'partial') parts.push('File sandbox enforcement is partial on this host.') + if (value.sandbox?.denied) parts.push(`The ${value.sandbox.mode} file sandbox denied an operation.`) return [{ type: 'text', text: parts.length > 0 ? parts.join('\n') : '(run_code completed with no output)' }] }, }, @@ -616,7 +630,7 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO try { let result: CodeRunResult try { - result = await runtime.run({ + result = await runtime.run(runtime.resolve({ program: args.code, bindings: [{ global: 'tools', @@ -624,7 +638,9 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' }, }], signal: runController.signal, - }) + ...exec.agent?.session.header.cwd !== undefined ? { cwd: exec.agent.session.header.cwd } : {}, + ...runtime.sandboxMode !== undefined ? { sandboxPolicy: options.resolveSandboxPolicy(exec) } : {}, + })) } finally { // Abort sub-dispatches and drain every in-flight dispatch before // closing the turn (queued-unstarted ones are abandoned unlogged). @@ -635,10 +651,13 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO if (result.error) { const logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join('\n')}` : '' - throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}`) + const sandboxText = result.sandbox === undefined ? '' + : `\nFile sandbox: ${result.sandbox.mode}${result.sandbox.enforcement === undefined ? '' : `; enforcement: ${result.sandbox.enforcement}`}${result.sandbox.denied ? '; operation denied' : ''}.` + throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}${sandboxText}`) } return { logs: result.logs, + ...result.sandbox === undefined ? {} : { sandbox: result.sandbox }, ...result.value !== undefined ? { result: result.value } : {}, } } finally { diff --git a/packages/core/tools/tests/ptc.spec.ts b/packages/core/tools/tests/ptc.spec.ts index 2ebd121f0c..ddbc9e97df 100644 --- a/packages/core/tools/tests/ptc.spec.ts +++ b/packages/core/tools/tests/ptc.spec.ts @@ -25,6 +25,8 @@ const testToolSignal = new AbortController().signal /** A scriptable in-repo CodeRuntime: each test sets `behavior` to drive the bindings however it needs. */ class FakeRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language: string readonly isolation = 'fake' behavior: (request: CodeRunRequest) => Promise = () => Promise.resolve({ logs: [] }) @@ -62,7 +64,7 @@ async function setup(options: SetupOptions = {}) { /** Mint an agent scope configured like production that can register scoped tool policy. */ async function mintAgentScope(ctx: Context, name = 'scoped'): Promise<{ scope: Scope; agent: Agent }> { - const agent = { id: SessionId(name) } as Agent + const agent = { id: SessionId(name), session: { header: {}, append: () => {} } } as unknown as Agent let scope!: Scope await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, { inject: ['tools', 'systemPrompt'] })) diff --git a/packages/core/tools/tsconfig.json b/packages/core/tools/tsconfig.json index 26e90088d1..c3e80174bc 100644 --- a/packages/core/tools/tsconfig.json +++ b/packages/core/tools/tsconfig.json @@ -37,6 +37,12 @@ }, { "path": "../../runtime-diagnostics/invariants" + }, + { + "path": "../../sandbox/sandbox" + }, + { + "path": "../../sandbox/sandbox-policy" } ] } diff --git a/packages/experimental/code-runtime-python/src/index.ts b/packages/experimental/code-runtime-python/src/index.ts index ed42c10730..186c9c2102 100644 --- a/packages/experimental/code-runtime-python/src/index.ts +++ b/packages/experimental/code-runtime-python/src/index.ts @@ -20,7 +20,7 @@ import type { Duplex } from 'node:stream' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { CodeRuntime, DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-code-runtime' -import type { CodeBindingErrorClass, CodeBindingFunction, CodeJsonValue, CodeRunFailure, CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import type { CodeBindingErrorClass, CodeBindingFunction, CodeJsonValue, CodeRunFailure, CodeRunRequest, CodeRunResult, CodeRunSpec } from '@deepseek-ai/dsh-code-runtime' import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type { BootMessage, ChildToHost, ReplyMessage } from './protocol.ts' @@ -1030,13 +1030,26 @@ export class PythonCodeRuntime extends CodeRuntime { } /** - * Execute one program in a fresh Python subprocess. Success resolves with - * `result.value` (and no `result.error`); failure — parse failure, thrown - * exception, invalid completion, output overflow, budget expiry, abort, or - * substrate death — resolves with `result.error` set (classified by - * `CodeRunFailure.kind`). The method rejects only for seam misuse. + * Resolve directory and the experimental provider's configured wall deadline. + * @param request - Program inputs; explicit sandbox or timeout overrides are unsupported. + * @returns Complete inputs for the provider's run method. + * @throws When a requested override is unsupported or cwd is relative. */ - async run(request: CodeRunRequest): Promise { + resolve(request: CodeRunRequest): CodeRunSpec { + if (request.sandboxPolicy !== undefined) throw new Error('dsh-code-runtime-python: sandbox policy is unsupported') + if (request.timeoutMs !== undefined) throw new Error('dsh-code-runtime-python: per-call timeout is unsupported') + const cwd = request.cwd ?? process.cwd() + if (!isAbsolute(cwd)) throw new Error('dsh-code-runtime-python: cwd must be absolute') + return { ...request, cwd, timeoutMs: this.config.maxWallMs } + } + + /** + * Execute a resolved Python program; this experimental provider has no file confinement. + * @param request - Resolved cwd, provider deadline, program and bindings. + * @returns Captured output and the program outcome. + */ + async run(request: CodeRunSpec): Promise { + if (request.sandboxPolicy !== undefined || request.timeoutMs !== this.config.maxWallMs) throw new Error('dsh-code-runtime-python: unsupported execution policy or timeout') if (this.disposed) throw new Error('dsh-code-runtime-python: run() after disposal') const bindings = this.validateBindings(request) if (request.signal?.aborted) { @@ -1155,7 +1168,7 @@ export class PythonCodeRuntime extends CodeRuntime { /** Spawn the child for one validated run and drive it to settlement. */ private execute( - request: CodeRunRequest, + request: CodeRunSpec, bindings: Map, bootstrapPath: string, ): Promise { @@ -1182,6 +1195,7 @@ export class PythonCodeRuntime extends CodeRuntime { // run. The `_LogStream` replacement of `sys.stdout`/`sys.stderr` is // unaffected (it is a Python object, not the C-level stdio buffer). child = spawn(this.pythonBin, ['-u', '-I', bootstrapPath], { + cwd: request.cwd, // Preserve only the platform temp directory. macOS system Python emits a // startup warning when TMPDIR is absent; ambient credentials, PATH, HOME, // and other host state remain unavailable to model code. diff --git a/packages/experimental/code-runtime-python/tests/boot-write-failure.spec.ts b/packages/experimental/code-runtime-python/tests/boot-write-failure.spec.ts index a55ae10746..ba2b1cddc4 100644 --- a/packages/experimental/code-runtime-python/tests/boot-write-failure.spec.ts +++ b/packages/experimental/code-runtime-python/tests/boot-write-failure.spec.ts @@ -146,10 +146,10 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { const ctx = new Context() const fiber = await ctx.plugin(PythonCodeRuntime) const runtime = ctx.codeRuntime as InstanceType - const run = runtime.run({ + const run = runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: { echo: async (value: unknown) => value as number } }], - }) + })) onTestFinished(async () => { await fiber.dispose() await run @@ -210,7 +210,7 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { const fiber = await ctx.plugin(PythonCodeRuntime) const runtime = ctx.codeRuntime as InstanceType - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('failed to boot python subprocess') @@ -240,7 +240,7 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { const fiber = await ctx.plugin(PythonCodeRuntime) const runtime = ctx.codeRuntime as InstanceType - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('python spawn error') @@ -258,7 +258,7 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { const fiber = await ctx.plugin(PythonCodeRuntime) const runtime = ctx.codeRuntime as InstanceType - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('failed to boot python subprocess') @@ -275,7 +275,7 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { const fiber = await ctx.plugin(PythonCodeRuntime) const runtime = ctx.codeRuntime as InstanceType - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('python spawn error') @@ -302,10 +302,10 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { const fiber = await ctx.plugin(PythonCodeRuntime, { maxWallMs: 3000 }) const runtime = ctx.codeRuntime as InstanceType - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: { f: async () => 'x'.repeat(4 * 1024 * 1024) } }], - }) + })) expect(result.error?.kind).toBe('timeout') // The drain wait settled on `close` and cleaned up after itself. The diff --git a/packages/experimental/code-runtime-python/tests/runtime.spec.ts b/packages/experimental/code-runtime-python/tests/runtime.spec.ts index d1a38fc543..b2861b0a6a 100644 --- a/packages/experimental/code-runtime-python/tests/runtime.spec.ts +++ b/packages/experimental/code-runtime-python/tests/runtime.spec.ts @@ -331,7 +331,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // is the deployment form the validation exists to serve. const pyAbs = resolvePythonBin('python3') ?? 'python3' const { runtime, fiber } = await setup({ pythonBin: pyAbs, maxWallMs: 30_000 }) - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error).toBeUndefined() expect(result.value).toBe(1) await fiber.dispose() @@ -350,10 +350,10 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { throw new Error('getter blew up') }, } - await expect(runtime.run({ + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: exploding }], - })).rejects.toThrow(/getter blew up/) + }))).rejects.toThrow(/getter blew up/) }) it('snapshots binding callables once, so a getter is read exactly once', async () => { @@ -368,10 +368,10 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { }, } const { runtime, fiber } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: countReads }], - }) + })) expect(result.error).toBeUndefined() // One read for the validation snapshot; the boot frame and every dispatch // read the snapshot, not the getter. @@ -386,13 +386,13 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // setter on assignment and drop the member, so the child would never learn // the name and a call to it would fail with KeyError. const { runtime, fiber } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return await tools["__proto__"]({})', bindings: [{ global: 'tools', functions: { ['__proto__']: async () => 'proto-callable' }, }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('proto-callable') await fiber.dispose() @@ -410,10 +410,10 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { const mounted = await setup({ pythonBin: 'python3' }) fiber = mounted.fiber vi.stubEnv('PATH', secondDir) - const result = await mounted.runtime.run({ + const result = await mounted.runtime.run(mounted.runtime.resolve({ program: 'import os\nreturn os.environ.get("DSH_TEST_PYTHON")', bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('first') } finally { @@ -438,7 +438,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { vi.stubEnv('PATH', `.:${pythonDir}`) try { const { runtime, fiber } = await setup({ pythonBin: 'python3', maxWallMs: 30_000 }) - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error).toBeUndefined() expect(result.value).toBe(1) await fiber.dispose() @@ -454,7 +454,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // child sends exactly one ack; the forged one exercises the re-entry // guard. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', // One forged boot-ack after the program starts; the run already went @@ -463,7 +463,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') }, 15_000) @@ -482,7 +482,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { vi.stubEnv('PATH', `${fakeDir}:${realPythonDir}`) try { const { runtime, fiber } = await setup({ pythonBin: 'python3', maxWallMs: 30_000 }) - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error).toBeUndefined() expect(result.value).toBe(1) await fiber.dispose() @@ -525,31 +525,31 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { it('rejects a binding global that is not a Python identifier or is reserved', async () => { const { runtime } = await setup() - await expect(runtime.run({ + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: '1bad', functions: {} }], - })).rejects.toThrow(/is not a usable Python identifier/) - await expect(runtime.run({ + }))).rejects.toThrow(/is not a usable Python identifier/) + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'class', functions: {} }], - })).rejects.toThrow(/is not a usable Python identifier/) + }))).rejects.toThrow(/is not a usable Python identifier/) }) it('rejects duplicate binding namespaces', async () => { const { runtime } = await setup() - await expect(runtime.run({ + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [ { global: 'tools', functions: {} }, { global: 'tools', functions: {} }, ], - })).rejects.toThrow(/duplicate binding global/) + }))).rejects.toThrow(/duplicate binding global/) }) it('rejects run() after disposal, and unregisters ctx.codeRuntime', async () => { const { ctx, fiber, runtime } = await setup() await fiber.dispose() - await expect(runtime.run({ program: 'return 1', bindings: [] })) + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [] }))) .rejects.toThrow(/after disposal/) expect(ctx.get('codeRuntime')).toBeUndefined() }) @@ -557,7 +557,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { it('short-circuits when the request signal is already aborted', async () => { const { runtime } = await setup() const signal = AbortSignal.abort('already-cancelled') - const result = await runtime.run({ program: 'return 1', bindings: [], signal }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [], signal })) expect(result.error?.kind).toBe('abort') expect(result.error?.message).toContain('already-cancelled') expect(result.logs).toEqual([]) @@ -571,7 +571,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { const signal = AbortSignal.abort({ [Symbol.toPrimitive]() { throw new Error('reason blew up') }, }) - const result = await runtime.run({ program: 'return 1', bindings: [], signal }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [], signal })) expect(result.error?.kind).toBe('abort') expect(result.error?.message).toBe('') expect(result.logs).toEqual([]) @@ -593,7 +593,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // already exercises that import. const { runtime } = await setup() const entryOf = async (): Promise => { - const result = await runtime.run({ program: 'import sys\nreturn sys.modules["__main__"].__file__', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'import sys\nreturn sys.modules["__main__"].__file__', bindings: [] })) expect(result.error).toBeUndefined() return result.value as string } @@ -620,7 +620,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // (measured: it settled as `worker-exit`), and substituted code would have // run before the resource limits were applied. const { runtime } = await setup({ maxWallMs: 10_000 }) - const sabotage = await runtime.run({ + const sabotage = await runtime.run(runtime.resolve({ program: [ 'import sys', 'path = sys.modules["__main__"].__file__', @@ -628,10 +628,10 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { 'return path', ].join('\n'), bindings: [], - }) + })) expect(sabotage.error).toBeUndefined() // The damage stayed inside the run that caused it. - const after = await runtime.run({ program: 'return 1 + 1', bindings: [] }) + const after = await runtime.run(runtime.resolve({ program: 'return 1 + 1', bindings: [] })) expect(after.error).toBeUndefined() expect(after.value).toBe(2) }, 20_000) @@ -653,7 +653,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // this test (boot-write-failure.spec.ts records the same race). const stagedBefore = stagedDirs.length const { fiber, runtime } = await setup({ maxWallMs: 8_000 }) - const pending = runtime.run({ program: 'import time\nwhile True: time.sleep(0.1)', bindings: [] }) + const pending = runtime.run(runtime.resolve({ program: 'import time\nwhile True: time.sleep(0.1)', bindings: [] })) const disposed = fiber.dispose() const result = await pending await disposed @@ -674,11 +674,11 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // no gap for the signal to slip through. const { runtime } = await setup({ maxWallMs: 4_000, graceMs: 200 }) const controller = new AbortController() - const pending = runtime.run({ + const pending = runtime.run(runtime.resolve({ program: 'import time\nwhile True: time.sleep(0.1)', bindings: [], signal: controller.signal, - }) + })) controller.abort('same-turn-abort') const result = await pending expect(result.error?.kind).toBe('abort') @@ -701,7 +701,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { process.env.TMPDIR = notADirectory try { const { runtime } = await setup() - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('failed to stage the python bootstrap') expect(result.logs).toEqual([]) @@ -726,7 +726,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { failNextCopyOf.value = 'protocol.py' try { const { runtime } = await setup() - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('failed to stage the python bootstrap') // The partial directory is gone, so nothing accumulates across retries. @@ -789,10 +789,10 @@ describe('PythonCodeRuntime — inherited resource limits', () => { // unambiguously above the inherited ceiling. await writeFile(wrapper, `#!/bin/sh\nulimit -v 262144\nexec "${PYABS}" "$@"\n`, { mode: 0o755 }) const { runtime } = await setup({ pythonBin: wrapper }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'import resource\nreturn resource.getrlimit(resource.RLIMIT_AS)[1]', bindings: [], - }) + })) expect(result.error).toBeUndefined() // The applied hard limit is the inherited one, not the configured 512 MiB. expect(result.value).toBe(256 * 1024 * 1024) @@ -815,7 +815,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { const wrapper = join(dir, 'python3-tight') await writeFile(wrapper, `#!/bin/sh\nulimit -v 131072\nexec "${PYABS}" "$@"\n`, { mode: 0o755 }) const { runtime } = await setup({ pythonBin: wrapper, maxLogBytes: 32 * 1024 * 1024, addressSpaceMb: 512 }) - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) if (process.platform === 'darwin') { expect(result.error).toBeUndefined() } else { @@ -833,7 +833,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { // limit there is nothing to clamp against, and RLIM_INFINITY compares as -1, // so treating it as a numeric bound would collapse every limit to -1. const { runtime } = await setup({ cpuSeconds: 42, addressSpaceMb: 400 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ // `getrlimit` returns a tuple, which the lossless-JSON completion check // rejects; the pair is listed explicitly rather than converted. program: [ @@ -843,7 +843,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { 'return {"cpu": [cpu[0], cpu[1]], "addressSpace": address_space}', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() // Darwin deliberately skips RLIMIT_AS; every other Unix host applies the // configured bytes alongside the CPU soft/hard pair. @@ -867,10 +867,10 @@ describe('PythonCodeRuntime — inherited resource limits', () => { // Soft CPU 5 s, well below the configured 30 s, hard left unlimited. await writeFile(wrapper, `#!/bin/sh\nulimit -S -t 5\nexec "${PYABS}" "$@"\n`, { mode: 0o755 }) const { runtime } = await setup({ pythonBin: wrapper, cpuSeconds: 30 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'import resource\nreturn resource.getrlimit(resource.RLIMIT_CPU)[0]', bindings: [], - }) + })) expect(result.error).toBeUndefined() // The applied SOFT limit is the inherited 5 s, not the configured 30 s. expect(result.value).toBe(5) @@ -892,14 +892,14 @@ describe('PythonCodeRuntime — inherited resource limits', () => { // Both soft and hard CPU 2 s; configured cpuSeconds 30 s. await writeFile(wrapper, `#!/bin/sh\nulimit -t 2\nexec "${PYABS}" "$@"\n`, { mode: 0o755 }) const { runtime } = await setup({ pythonBin: wrapper, cpuSeconds: 30, maxWallMs: 12_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'while True:', ' pass', 'return "unreachable"', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('timeout') expect(result.error?.message).toContain('CPU time exhausted') }, 15_000) @@ -915,7 +915,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { // run reports `value: "escaped"` and no error. The masking is guarded by // hasattr so the case is a no-op on platforms without pthread_sigmask. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 12_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import signal, time', 'if hasattr(signal, "pthread_sigmask"):', @@ -926,7 +926,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { 'return "escaped"', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('timeout') expect(result.value).toBeUndefined() }, 20_000) @@ -942,10 +942,10 @@ describe('PythonCodeRuntime — inherited resource limits', () => { writeFileSync(wrapper, `#!/bin/sh\ntrap "" XCPU\nexec "${PYABS}" "$@"\n`, { mode: 0o755 }) try { const { runtime } = await setup({ maxWallMs: 30_000, cpuSeconds: 1, pythonBin: wrapper }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['while True: pass'].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('timeout') } finally { rmSync(wrapper, { force: true }) @@ -963,7 +963,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { // window; without it, the handler re-blocks and the child exits normally // with a success value. Fail-before: the run reports `value: "escaped"`. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 12_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import signal, time', 'if hasattr(signal, "pthread_sigmask"):', @@ -977,7 +977,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { 'return "escaped"', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('timeout') expect(result.value).toBeUndefined() }, 20_000) @@ -995,7 +995,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { const wrapper = join(dir, 'python3-cpu-capped') await writeFile(wrapper, `#!/bin/sh\nulimit -S -t 1\nexec "${PYABS}" "$@"\n`, { mode: 0o755 }) const { runtime } = await setup({ pythonBin: wrapper, cpuSeconds: 30, maxWallMs: 12_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import signal, time', // Trap SIGXCPU so the soft limit does not terminate the program; burn @@ -1007,7 +1007,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { 'return "returned"', ].join('\n'), bindings: [], - }) + })) // The recheck compares spent CPU against the effective 1 s soft, not 30 s, so // the run is a timeout rather than a false success. expect(result.error?.kind).toBe('timeout') @@ -1017,7 +1017,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { describe('PythonCodeRuntime — programs and bindings', () => { it('runs a top-level script, captures print output, and returns `result`', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'x = 40', 'y = 2', @@ -1025,7 +1025,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return {"answer": x + y}', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ answer: 42 }) // `print` in Python emits: text, ' ', text, '\n'. Concat the captured @@ -1038,7 +1038,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { it('exposes only the platform temp directory from the host environment', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'return {', @@ -1049,7 +1049,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { '}', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ tmpdir: tmpdir(), path: null, home: null, token: null }) expect(result.logs).toEqual([]) @@ -1058,7 +1058,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { it('bridges binding calls both ways and rejects the program-side call on a host rejection', async () => { const { runtime } = await setup() const calls: unknown[] = [] - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'first = await tools.echo({"n": 1})', 'caught = ""', @@ -1072,7 +1072,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { echo: async (args) => { calls.push(args); return { echoed: args as CodeJsonValue } }, fail: async () => { throw new Error('nope') }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ first: { echoed: { n: 1 } }, caught: 'nope' }) expect(calls).toEqual([{ n: 1 }]) @@ -1085,7 +1085,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // decode primitives are def-time captures on the channel methods, so a // rebind cannot break reply delivery. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', '__main__._decode_json_plain = None', @@ -1095,7 +1095,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { bindings: tools({ echo: async args => ({ echoed: args as CodeJsonValue }), }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ echoed: { n: 1 } }) }, 15_000) @@ -1107,7 +1107,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // __main__.ProtocolChannel.send_sync cannot turn a legitimate binding call // into an exception or a wall-clock timeout. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', 'def boom(*a, **k):', @@ -1123,7 +1123,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { bindings: tools({ echo: async args => ({ echoed: args as CodeJsonValue }), }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ echoed: { n: 1 } }) }, 15_000) @@ -1136,7 +1136,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // class attribute, since the pump starts after the program's top-level // statements). const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', 'async def boom(*a, **k):', @@ -1148,7 +1148,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { bindings: tools({ echo: async args => ({ echoed: args as CodeJsonValue }), }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ echoed: { n: 1 } }) }, 15_000) @@ -1161,7 +1161,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // into `_run` locals before the program runs, so a host rejection still // surfaces as the declared `RuntimeError`. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', '__main__._BindingRejection = ValueError', @@ -1177,7 +1177,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { bindings: tools({ fail: async () => { throw new Error('nope') }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('nope') }, 15_000) @@ -1191,7 +1191,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // `unhandledRejection` listener would exit instead. The rejection must reach // the program as an ordinary error carrying a fixed placeholder. const { runtime } = await setup({ maxWallMs: 8_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'try:', ' await tools.hostile({})', @@ -1204,7 +1204,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { throw { [Symbol.toPrimitive]() { throw new Error('toPrimitive blew up') } } }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('rejected: ') }, 15_000) @@ -1219,7 +1219,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // must contain it — `String()` on a cycle throws inside the guard and lands // on the placeholder, so the program sees an ordinary error. const { runtime } = await setup({ maxWallMs: 8_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'try:', ' await tools.hostile({})', @@ -1241,7 +1241,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { throw error }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('rejected: ') }, 15_000) @@ -1255,7 +1255,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // on `await` until the wall ceiling (observed). Converting first sends the // string "undefined", which the program receives as an ordinary rejection. const { runtime } = await setup({ maxWallMs: 8_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'try:', ' await tools.absent({})', @@ -1270,17 +1270,17 @@ describe('PythonCodeRuntime — programs and bindings', () => { throw error }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('rejected: undefined') }, 15_000) it('runs a program with no await', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return 2 + 2', bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(4) }) @@ -1291,10 +1291,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // (The worker/TS backend can tell `return undefined` from `return null`; // Python cannot, and reporting null for both is the honest rendering.) const { runtime } = await setup() - const explicit = await runtime.run({ program: 'return None', bindings: [] }) + const explicit = await runtime.run(runtime.resolve({ program: 'return None', bindings: [] })) expect(explicit.error).toBeUndefined() expect(explicit.value).toBeNull() - const noReturn = await runtime.run({ program: 'x = 1', bindings: [] }) + const noReturn = await runtime.run(runtime.resolve({ program: 'x = 1', bindings: [] })) expect(noReturn.error).toBeUndefined() expect(noReturn.value).toBeNull() }) @@ -1304,7 +1304,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // frame with no value key can only be forged; the host settles it as a // value-less completion rather than crashing on the absent field. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'os.write(3, b\'{"type":"done"}\\n\')', @@ -1312,7 +1312,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'time.sleep(5)', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBeUndefined() }) @@ -1322,20 +1322,20 @@ describe('PythonCodeRuntime — programs and bindings', () => { // one logical line "a b" so PTC mode's join(newline) does not insert // spurious blank lines. Two prints → exactly two entries, no empties. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['print("a", "b")', 'print("c")', 'return None'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['a b', 'c']) }) it('flushes a print with no trailing newline', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['print("partial", end="")', 'return None'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['partial']) }) @@ -1349,10 +1349,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // with no newline reads back as exactly one entry with no interior breaks. const { runtime } = await setup({ maxLogBytes: 300_000 }) const size = 200_000 - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['import os', `os.write(1, b"A" * ${size})`, 'return None'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['A'.repeat(size)]) }) @@ -1361,17 +1361,17 @@ describe('PythonCodeRuntime — programs and bindings', () => { // The complement of the aggregation case: real newlines in a native write // still delimit entries, matching the child's line-granular `log` frames. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['import os', 'os.write(1, b"one\\ntwo\\nthree")', 'return None'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['one', 'two', 'three']) }) it('preserves each native stream order while allowing backend-dependent interleaving', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'os.write(1, b"stdout-one\\n")', @@ -1381,7 +1381,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return None', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.indexOf('stdout-one')).toBeLessThan(result.logs.indexOf('stdout-two')) expect(result.logs.indexOf('stderr-one')).toBeLessThan(result.logs.indexOf('stderr-two')) @@ -1395,10 +1395,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // and the captured output ends at the truncation marker rather than // retaining the whole flood. const { runtime } = await setup({ maxLogBytes: 4096 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['import os', 'os.write(1, b"A" * 2_000_000)', 'return None'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.at(-1)).toBe(logTruncationMarker(4096)) // The retained output is bounded by the budget, not the 2 MB flood. @@ -1417,7 +1417,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // seal does. This drives well past the cap and asserts the run still // completes with a truncation marker rather than a MemoryError. const { runtime } = await setup({ maxLogBytes: 4096 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', 'for _ in range(200_000):', @@ -1425,7 +1425,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return None', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.at(-1)).toBe(logTruncationMarker(4096)) }) @@ -1440,10 +1440,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // result. Under a small budget the residual is truncated once the serialized // cost crosses it. const { runtime } = await setup({ maxLogBytes: 4096 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['import os', 'os.write(1, b"\\x00" * 4000)', 'return None'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.at(-1)).toBe(logTruncationMarker(4096)) }) @@ -1503,7 +1503,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // cost walker charges surrogates the full 6, so a flood truncates at budget. // Forged on fd 3 because Python stdout will not emit lone surrogates. const { runtime } = await setup({ maxLogBytes: 4096 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', // 1000 \ud800 escapes: charged at the buggy raw width 1000 * 3 = 3000 @@ -1516,7 +1516,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return None', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.at(-1)).toBe(logTruncationMarker(4096)) }) @@ -1532,10 +1532,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // branch un-exercised, which would be a hard-to-attribute per-file coverage // flake. The first line's 100 bytes already exceed the 64-byte budget, so it truncates. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['import os', 'os.write(1, b"A" * 100 + b"\\nSECOND\\n")', 'return None'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.at(-1)).toBe(logTruncationMarker(64)) expect(result.logs.join('\n')).not.toContain('SECOND') @@ -1549,7 +1549,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // cross-chunk broken-sequence branch. The run completes and the bytes are // captured (rendered U+FFFD by toString), proving the walk resynchronizes. const { runtime } = await setup({ maxLogBytes: 1024 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'os.write(1, b"\\xe4")', @@ -1558,7 +1558,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return None', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.join('')).toContain('A') expect(result.logs.join('')).toContain('�') @@ -1572,10 +1572,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // enough to admit it, the line survives verbatim — proving the cost walker // does not over- or under-charge and the string round-trips unescaped. const { runtime } = await setup({ maxLogBytes: 4096 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['import os', String.raw`os.write(1, "\ta\"b\\c\x01é\n".encode("utf-8"))`, 'return None'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['\ta"b\\c\x01é']) }) @@ -1584,10 +1584,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // json.dumps would coerce {1: "a", "1": "b"} to a single "1" key, silently // dropping data. The shape validator rejects it before encoding. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return {1: "first", "1": "second"}', bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('invalid-output') expect(result.error?.message).toContain('non-string dict key') @@ -1596,7 +1596,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { it('rejects a binding argument with a non-string dict key before dispatch', async () => { const { runtime } = await setup() let called = false - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'caught = ""', 'try:', @@ -1606,7 +1606,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return caught', ].join('\n'), bindings: tools({ sink: async () => { called = true; return null } }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toContain('lossless JSON') expect(called).toBe(false) @@ -1616,10 +1616,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // A set is not lossless JSON. The old draft substituted repr(); the seam // now requires refusing the run instead. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return {1, 2, 3}', bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('invalid-output') expect(result.error?.message).toContain('lossless JSON') @@ -1631,13 +1631,13 @@ describe('PythonCodeRuntime — programs and bindings', () => { // sign bit; the canonical lossless-JSON boundary rejects it, so the // Python side must too — as a completion and as a binding argument. const { runtime } = await setup() - const completion = await runtime.run({ + const completion = await runtime.run(runtime.resolve({ program: 'return -0.0', bindings: [], - }) + })) expect(completion.error?.kind).toBe('invalid-output') expect(completion.error?.message).toContain('negative zero') - const argument = await runtime.run({ + const argument = await runtime.run(runtime.resolve({ program: [ 'try:', ' await tools.echo(-0.0)', @@ -1646,7 +1646,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { ' return str(e)', ].join('\n'), bindings: tools({ echo: async args => args as never }), - }) + })) expect(argument.error).toBeUndefined() expect(argument.value).toContain('negative zero') }) @@ -1655,19 +1655,19 @@ describe('PythonCodeRuntime — programs and bindings', () => { // json.dumps would happily emit NaN by default, but NaN is not JSON; the // bootstrap passes allow_nan=False so it fails as invalid-output. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return float("nan")', bindings: [], - }) + })) expect(result.error?.kind).toBe('invalid-output') }) it('fails an over-budget completion value as output-limit (child-side check)', async () => { const { runtime } = await setup({ maxValueBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return "V" * 5000', bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('output-limit') expect(result.error?.message).toContain('exceeded 64 bytes') @@ -1687,10 +1687,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // only when charged the escaped cost, so this also pins that the cheap // character bound alone does not decide the verdict. const { runtime } = await setup({ maxValueBytes: 16 * 1024 * 1024, maxWallMs: 60_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return "\\x00" * 8_000_000', bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('output-limit') }, 90_000) @@ -1701,10 +1701,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // BEFORE pushing two million elements onto the walk — so a small // addressSpaceMb does not turn the check itself into an RLIMIT_AS death. const { runtime } = await setup({ maxValueBytes: 64, addressSpaceMb: 256, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return [0] * 2000000', bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('output-limit') expect(result.error?.message).toContain('exceeded 64 bytes') @@ -1717,10 +1717,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // fits the 256 MiB address space as a dict but not as a dict PLUS a // two-million-tuple list. const { runtime } = await setup({ maxValueBytes: 64, addressSpaceMb: 256, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return {str(i): 0 for i in range(2000000)}', bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('output-limit') expect(result.error?.message).toContain('exceeded 64 bytes') @@ -1733,19 +1733,19 @@ describe('PythonCodeRuntime — programs and bindings', () => { // bytes the host will receive — otherwise a boundary-sized value is // falsely reported as output-limit. const { runtime } = await setup({ maxValueBytes: 1 }) - const integral = await runtime.run({ program: 'return 1.0', bindings: [] }) + const integral = await runtime.run(runtime.resolve({ program: 'return 1.0', bindings: [] })) expect(integral.error).toBeUndefined() expect(integral.value).toBe(1) const exponent = await setup({ maxValueBytes: 4 }) - const small = await exponent.runtime.run({ program: 'return 1e-7', bindings: [] }) + const small = await exponent.runtime.run(exponent.runtime.resolve({ program: 'return 1e-7', bindings: [] })) expect(small.error).toBeUndefined() expect(small.value).toBe(1e-7) // The spelling is a meter input, not a licence to overshoot: `1.5` is three // bytes on both sides and still fails a two-byte budget. const tight = await setup({ maxValueBytes: 2 }) - const over = await tight.runtime.run({ program: 'return 1.5', bindings: [] }) + const over = await tight.runtime.run(tight.runtime.resolve({ program: 'return 1.5', bindings: [] })) expect(over.error?.kind).toBe('output-limit') }) @@ -1756,10 +1756,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // exponents, >= 1e21, and beyond-safe-range integral doubles whose exact // digits differ from the shortest round-trip form). const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return [1.0, 100.0, 1.5, 0.1, 1e-7, 1e-6, 1e-5, 123.456, -2.5e-8, 1e21, float(2**60), 5e-324, 1.7976931348623157e308]', bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual([1, 100, 1.5, 0.1, 1e-7, 1e-6, 1e-5, 123.456, -2.5e-8, 1e21, 2 ** 60, 5e-324, 1.7976931348623157e308]) }) @@ -1769,7 +1769,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // turns 1e400 into Infinity; validateChildFrame no longer scans done.value, // so the host's own checkDoneValue must catch the non-lossless number. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', String.raw`os.write(3, b'{"type":"done","value":1e400}' + b'\n')`, @@ -1777,7 +1777,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'time.sleep(5)', ].join('\n'), bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('invalid-output') expect(result.error?.message).toContain('non-lossless number') @@ -1785,10 +1785,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { it('reports a syntax error as an exception without settling with a value', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: '$$invalid python$$', bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('SyntaxError') // The parse-time diagnostic must carry the same source label as compile and @@ -1800,10 +1800,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { it('reports a runtime raise as an exception with the traceback', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'raise ValueError("intentional")', bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('ValueError') expect(result.error?.message).toContain('intentional') @@ -1816,7 +1816,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // budget rather than timing out. const { runtime } = await setup({ maxValueBytes: 1024 * 1024, maxWallMs: 20_000 }) const start = Date.now() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'err = None', 'for i in range(3000):', @@ -1827,7 +1827,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'raise err', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('exception chain truncated at 100 links') expect(Date.now() - start).toBeLessThan(15_000) @@ -1844,7 +1844,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // reports `exception`. const { runtime } = await setup({ maxValueBytes: 1024 * 1024, maxWallMs: 15_000 }) const start = Date.now() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'class Sealed(Exception):', ' def __setattr__(self, name, value):', @@ -1858,7 +1858,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'raise err', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('Sealed') expect(result.error?.message).toContain('exception chain truncated at 100 links') @@ -1877,7 +1877,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // invariant that matters: a `done` frame carrying `exception`, never a // timeout, and never the failing renderer's own message. const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'class Unprintable(Exception):', ' def __str__(self):', @@ -1887,7 +1887,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'raise Unprintable()', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('Unprintable') expect(result.error?.message).not.toContain('str refused') @@ -1902,7 +1902,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // wrapper it escapes the handler, the `done` send never runs, and the host // times out at maxWallMs. const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'class Meta(type):', ' @property', @@ -1913,7 +1913,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'raise Hostile("original failure")', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') // The inert fallback names the class and a fixed literal; it must not carry // the renderer's message, and must not have become a timeout. `__name__` is @@ -1927,7 +1927,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // format a non-str __name__ into the message. The hostile `__module__` is // what drives execution into the fallback in the first place. const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'class Meta(type):', ' @property', @@ -1941,7 +1941,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'raise Nameless()', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toBe(': ') }, 15_000) @@ -1956,7 +1956,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // exception. Rebind all of them at once; the run must still carry the real // ValueError. const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', 'def boom(*a, **k):', @@ -1975,7 +1975,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'raise ValueError("real failure")', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('ValueError: real failure') expect(result.error?.message).not.toContain('hijacked') @@ -1995,7 +1995,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // carries a fixed `` text), which is acceptable: the verdict // outranks the diagnostic detail. const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', 'def boom(*a, **k):', @@ -2009,7 +2009,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'raise ValueError("real failure")', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.kind).not.toBe('worker-exit') }, 15_000) @@ -2025,14 +2025,14 @@ describe('PythonCodeRuntime — programs and bindings', () => { // cannot change which class the clause catches; the run must still report an // `exception`, not a `worker-exit`. const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', '__main__.BaseException = RuntimeError', 'raise ValueError("real failure")', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.kind).not.toBe('worker-exit') }, 15_000) @@ -2048,7 +2048,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // misreport as `worker-exit`; with it, the run reports the exception and the // fallback reporter still produces the fixed literal. const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', 'def boom(*a, **k):', @@ -2061,7 +2061,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'raise KeyError("real failure")', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.kind).not.toBe('worker-exit') }, 15_000) @@ -2077,7 +2077,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // without the check the frame is joined whole and parsed (its log text // admitted, truncating the ledger), and the run completes normally. const { runtime } = await setup({ maxWallMs: 60_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', // One frame just past the 64 MiB parse cap. @@ -2085,7 +2085,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('protocol frame exceeded') }, 90_000) @@ -2097,12 +2097,12 @@ describe('PythonCodeRuntime — programs and bindings', () => { // invalid-output run as a worker-exit. The diagnostic is capped to the // value budget, so the frame always crosses the parser. const { runtime } = await setup({ maxWallMs: 60_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'return type("N" * (70 * 1024 * 1024), (), {})()', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('invalid-output') expect(result.error?.kind).not.toBe('worker-exit') }, 90_000) @@ -2114,14 +2114,14 @@ describe('PythonCodeRuntime — programs and bindings', () => { // printed as one line. The flush frame now carries `open: true` and the // host appends the next frame to the same entry. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ "print('a', end='', flush=True)", "print('b')", 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['ab']) }, 15_000) @@ -2131,7 +2131,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // lands in openSealed, and the run ends without a closing frame — finish() // must commit the SEALED prefix, not only the current fragments. const { runtime } = await setup({ maxLogBytes: 65536 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', "os.write(3, b'{\"type\":\"log\",\"text\":\"x\",\"open\":true}\\n')", @@ -2140,7 +2140,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['x' + 'a'.repeat(3000)]) }, 15_000) @@ -2150,13 +2150,13 @@ describe('PythonCodeRuntime — programs and bindings', () => { // admits it so a program that commits a partial line and returns does not // lose it from logs. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ "print('committed', end='', flush=True)", 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['committed']) }, 15_000) @@ -2167,7 +2167,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // entry, and holding it would let a forged empty-open flood grow host // memory without touching the ledger). const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', "os.write(3, b'{\"type\":\"log\",\"text\":\"x\",\"open\":true}\\n')", @@ -2176,7 +2176,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['xy']) }, 15_000) @@ -2187,7 +2187,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // overhead the byte cap cannot see). The hold seals into one block past // MAX_PENDING_CHUNKS; the merged entry is byte-identical. const { runtime } = await setup({ maxLogBytes: 65536 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', "os.write(3, b'{\"type\":\"log\",\"text\":\"x\",\"open\":true}\\n')", @@ -2198,7 +2198,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['x' + 'a'.repeat(3000) + 'y']) }, 15_000) @@ -2209,7 +2209,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // logBudget — unbounded host retention under a small budget. The flood now // truncates to the marker like any over-budget log traffic. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', // 2000 forged open frames, each under the frame parse cap. @@ -2218,7 +2218,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['a'.repeat(60), logTruncationMarker(64)]) }, 15_000) @@ -2229,7 +2229,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // truncates — truncateLogs must commit the SEALED prefix (not only the // current fragments) before the marker. const { runtime } = await setup({ maxLogBytes: 65536 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', "os.write(3, b'{\"type\":\"log\",\"text\":\"x\",\"open\":true}\\n')", @@ -2242,7 +2242,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs[0]).toBe('x' + 'a'.repeat(3000)) expect(result.logs[result.logs.length - 1]).toBe(logTruncationMarker(65536)) @@ -2253,14 +2253,14 @@ describe('PythonCodeRuntime — programs and bindings', () => { // over-budget write truncates, the committed prefix must appear BEFORE the // marker — the ledger charged for it, so it cannot vanish. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ "print('committed', end='', flush=True)", "print('x' * 100)", 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['committed', logTruncationMarker(64)]) }, 15_000) @@ -2271,14 +2271,14 @@ describe('PythonCodeRuntime — programs and bindings', () => { // throws and the frame is dropped. The program's real return still settles // the run with the honest value. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', "os.write(3, b'{\"type\":\"done\",\"value\":\"bad' + bytes([0xFF]) + b'\"}\\n')", 'return "ok"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('ok') }, 15_000) @@ -2288,7 +2288,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // the ledger (logsTruncated set, marker pushed), then a closing frame // arrives — it must be a no-op, not append content past the marker. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'for _ in range(2000):', @@ -2297,7 +2297,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['a'.repeat(60), logTruncationMarker(64)]) }, 15_000) @@ -2310,7 +2310,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // fragment billing (each charged quotes+separator, ~4 bytes) would truncate // at 16 x 4 = 64. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'for _ in range(16):', " print('x', end='', flush=True)", @@ -2318,7 +2318,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['x'.repeat(16)]) }, 15_000) @@ -2330,14 +2330,14 @@ describe('PythonCodeRuntime — programs and bindings', () => { // cap math (logBudget - openCost) made the closing frame's walk see a // negative cap and truncate a compliant entry. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ "print('a' * 30, end='', flush=True)", "print('b' * 25)", 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['a'.repeat(30) + 'b'.repeat(25)]) }, 15_000) @@ -2350,14 +2350,14 @@ describe('PythonCodeRuntime — programs and bindings', () => { // truncate first: a reverted cap of logBudget (63) would admit the frame, // hold it, and flush it at settlement, so the marker assertion fails. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', "os.write(3, ('{\"type\":\"log\",\"text\":\"' + 'x' * 61 + '\",\"open\":true}\\n').encode())", 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual([logTruncationMarker(64)]) }, 15_000) @@ -2368,14 +2368,14 @@ describe('PythonCodeRuntime — programs and bindings', () => { // the merged tail (content only), not as a fresh entry (which would // double-charge the quotes+separator and truncate an exact-fit entry). const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ "print('a' * 30, end='', flush=True)", "print('b' * 30)", 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['a'.repeat(30) + 'b'.repeat(30)]) }, 15_000) @@ -2391,7 +2391,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // a budget prefix, and pushed past the ledger, emitting the marker for a // line that fits (merged cost 2 + 59 + 1 = 62 <= 63). const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', "sys.stdout.write('a' * 29)", @@ -2400,7 +2400,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['a'.repeat(29) + 'b'.repeat(30)]) }, 15_000) @@ -2411,7 +2411,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // host ledger down to 1 byte, then a new open entry's first-fragment cap // (logBudget - 1 = 0) trips the guard and truncates. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', "os.write(3, ('{\"type\":\"log\",\"text\":\"' + 'a' * 28 + '\",\"open\":true}\\n').encode())", @@ -2420,7 +2420,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['a'.repeat(59), logTruncationMarker(64)]) }, 15_000) @@ -2431,14 +2431,14 @@ describe('PythonCodeRuntime — programs and bindings', () => { // the closing frame's exact-cost walk trips and the marker replaces the // entry, exactly like any other over-budget log traffic. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ "print('x' * 40, end='', flush=True)", "print('y' * 40)", 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs).toEqual(['x'.repeat(40), logTruncationMarker(64)]) }, 15_000) @@ -2451,7 +2451,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // successful run as an exception. A fixed module-level Context(prec=28) // makes the spelling decision context-independent. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'from decimal import getcontext', 'getcontext().prec = 2', @@ -2459,7 +2459,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return 1.2345678901234567', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(1.2345678901234567) }, 15_000) @@ -2469,7 +2469,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // dunders, so the cap has to count that edge too — otherwise a deeply // nested group walks past the bound the marker claims to enforce. const { runtime } = await setup({ maxValueBytes: 1024 * 1024, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', // ExceptionGroup is a 3.11+ builtin; on 3.10 the NameError is the @@ -2482,7 +2482,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'raise group', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') // The version guard skips on Python < 3.11 (ExceptionGroup is a 3.11+ // builtin) with a distinct message; the truncation assertion applies on @@ -2496,10 +2496,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // durable output — a bootstrap.py path would leak host absolutes and make // transcripts machine-dependent. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'await tools.boom({})', bindings: tools({ boom: async () => { throw new Error('exploded') } }), - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('exploded') expect(result.error?.message).toContain('') @@ -2508,7 +2508,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { it('renders a non-Error thrown value from a host binding as its String form', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'caught = ""', 'try:', @@ -2520,7 +2520,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { bindings: tools({ failRaw: async () => { throw 'raw-nope' }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toContain('raw-nope') }) @@ -2530,7 +2530,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // residual after the newline loop; the tail must survive until its own // newline arrives and then parse as a normal frame. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'head = json.dumps({"type":"log","text":"first"}).encode()', @@ -2542,7 +2542,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "ok"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('ok') expect(result.logs).toContain('first') @@ -2553,7 +2553,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // PTC mode declares { name: ToolCallError, memberNameProperty: toolName }; // a host rejection must surface as that class, carrying the failed tool. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'caught = ""', 'try:', @@ -2567,7 +2567,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { functions: { fail: async () => { throw new Error('typed-nope') } }, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' }, }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('ToolCallError:fail:typed-nope') }) @@ -2578,7 +2578,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // cannot break the rejection constructor: `except ToolCallError` must still // catch and read the member property. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', 'def boom(*a, **k):', @@ -2597,7 +2597,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { functions: { fail: async () => { throw new Error('typed-nope') } }, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' }, }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('ToolCallError:fail') }, 15_000) @@ -2625,10 +2625,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { }, } const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return "ok"', bindings: [{ global: 'tools', functions: {}, errorClass }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('ok') expect(nameReads).toBe(1) @@ -2651,10 +2651,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { functions: { echo: async (args: unknown) => args as CodeJsonValue }, } const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return await tools.echo(41)', bindings: [namespace], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(41) expect(globalReads).toBe(1) @@ -2662,10 +2662,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { it('rejects an errorClass name colliding with its namespace global at the seam', async () => { const { runtime } = await setup() - await expect(runtime.run({ + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'tools', memberNameProperty: 'toolName' } }], - })).rejects.toThrow(/collides with another injected global/) + }))).rejects.toThrow(/collides with another injected global/) }) it('rejects a namespace global colliding with a runtime-owned name at the seam', async () => { @@ -2679,10 +2679,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // assign the name at compile time, so an injected global under it is // unreachable from the program — accepted by the seam, unusable here. for (const global of ['__dsh_main__', 'console', '__debug__']) { - await expect(runtime.run({ + await expect(runtime.run(runtime.resolve({ program: 'x = 1', bindings: [{ global, functions: {} }], - })).rejects.toThrow(/collides with a runtime-owned global/) + }))).rejects.toThrow(/collides with a runtime-owned global/) } }) @@ -2691,7 +2691,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // members; Python setattr/getattr carry exotic names like `tool-name`, // and the worker backend accepts them, so this backend must too. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'try:', ' await tools.boom({})', @@ -2703,20 +2703,20 @@ describe('PythonCodeRuntime — programs and bindings', () => { functions: { boom: async () => { throw new Error('nope') } }, errorClass: { name: 'ToolCallError', memberNameProperty: 'tool-name' }, }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('boom') - await expect(runtime.run({ + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'ToolCallError', memberNameProperty: '' } }], - })).rejects.toThrow(/memberNameProperty must be a non-empty attribute name/) + }))).rejects.toThrow(/memberNameProperty must be a non-empty attribute name/) }) it('resolves a basename pythonBin to an absolute path (runs a real program)', async () => { // A bare `python3` basename must resolve against PATH and actually launch // under the empty-env spawn — exercises the accessSync success branch. const { runtime } = await setup({ pythonBin: 'python3' }) - const result = await runtime.run({ program: 'return 7', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 7', bindings: [] })) expect(result.error).toBeUndefined() expect(result.value).toBe(7) }) @@ -2740,10 +2740,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // name/message/stack are the seam's own exclusions (CodeBindingErrorClass // forbids replacing them; the worker backend rejects them identically). for (const member of ['__traceback__', '__dict__', '__class__', 'args', 'name', 'message', 'stack']) { - await expect(runtime.run({ + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'ToolCallError', memberNameProperty: member } }], - })).rejects.toThrow(/reserved error member/) + }))).rejects.toThrow(/reserved error member/) } }) @@ -2751,7 +2751,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // JSON.stringify would turn NaN into null and drop undefined fields; the // seam requires a descriptive rejection so data cannot silently corrupt. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'caught = ""', 'try:', @@ -2761,7 +2761,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return caught', ].join('\n'), bindings: tools({ bad: async () => Number.NaN }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toContain('lossless JSON') }) @@ -2771,7 +2771,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // JSON.stringify; the host's iterative encoder measures it stack-safely // and fails it deterministically on the byte budget (40 kB > 32 KiB). const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'depth = 20000', @@ -2781,7 +2781,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'time.sleep(5)', ].join('\n'), bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('output-limit') }) @@ -2795,7 +2795,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // encodeJsonPlain together. The host JSON.parse of the frame is iterative // in V8 for arrays, so only the two encoders were at risk. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'v = None', 'for _ in range(10000):', @@ -2803,7 +2803,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return v', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() // Walk down iteratively (a recursive toEqual would itself overflow). let depth = 0 @@ -2829,7 +2829,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { for (let i = 0; i < 12000; i++) v = [v] return v })() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'v = await tools.deep({})', 'depth = 0', @@ -2839,21 +2839,21 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return depth', ].join('\n'), bindings: tools({ deep: async () => deep as never }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(12000) }) it('rejects a reserved errorClass name at the seam', async () => { const { runtime } = await setup() - await expect(runtime.run({ + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'class', memberNameProperty: 'toolName' }, }], - })).rejects.toThrow(/errorClass.name "class" is not a usable Python identifier/) + }))).rejects.toThrow(/errorClass.name "class" is not a usable Python identifier/) }) it('routes a declared inherited-attribute name through the bridge via subscript', async () => { @@ -2862,7 +2862,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // is the SDK-advertised route for underscore names. const { runtime } = await setup() const seen: string[] = [] - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'a = await tools["__class__"]({"via": "subscript"})', 'b = await tools.__class__({"via": "dot"})', @@ -2871,7 +2871,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { bindings: tools({ '__class__': async () => { seen.push('called'); return 'bridged' }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual(['bridged', 'bridged']) expect(seen).toEqual(['called', 'called']) @@ -2883,7 +2883,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // allow_nan=False raises in-program right away. const { runtime } = await setup({ maxWallMs: 8000 }) const start = Date.now() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'caught = ""', 'try:', @@ -2893,7 +2893,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return caught', ].join('\n'), bindings: tools({ echo: async args => args as CodeJsonValue }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toContain('lossless JSON') expect(Date.now() - start).toBeLessThan(5000) @@ -2906,7 +2906,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { const maxValueBytes = 4096 const { runtime } = await setup({ maxValueBytes }) let receivedLength = 0 - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ `big = "B" * ${maxValueBytes * 50}`, 'r = await tools.measure({"payload": big})', @@ -2918,7 +2918,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { return receivedLength }, }), - }) + })) expect(result.error).toBeUndefined() expect(receivedLength).toBe(maxValueBytes * 50) expect(result.value).toBe(maxValueBytes * 50) @@ -2926,7 +2926,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { it('rejects an unknown binding name inside the program with a matching error', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'caught = ""', 'try:', @@ -2936,7 +2936,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return caught', ].join('\n'), bindings: tools({ known: async () => 'ok' }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toContain('nope') }) @@ -2955,7 +2955,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // slices in place. The child's address space stays generous enough to BUILD // the forgery, which is not what is under test. const { runtime } = await setup({ maxValueBytes: 128, addressSpaceMb: 1024, maxWallMs: 20_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'frame = b\'{"type":"call","id":9001,"global":"tools","name":"\' + b"n" * (8 * 1024 * 1024) + b\'","args":{}}\\n\'', @@ -2971,7 +2971,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return "settled"', ].join('\n'), bindings: tools({ known: async () => 'ok' }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('settled') }, 40_000) @@ -2980,20 +2980,20 @@ describe('PythonCodeRuntime — programs and bindings', () => { // The SDK tells the model `await tools["my-tool"](args)` works for exotic // names; the proxy's __getitem__ must route it through the bridge. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'r = await tools["my-tool"]({"n": 7})', 'return r', ].join('\n'), bindings: tools({ 'my-tool': async args => ({ got: args as CodeJsonValue }) }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ got: { n: 7 } }) }) it('raises KeyError for an undeclared subscript name', async () => { const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'caught = ""', 'try:', @@ -3003,7 +3003,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return caught', ].join('\n'), bindings: tools({ known: async () => 'ok' }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toContain('absent') }) @@ -3013,10 +3013,10 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { it('kills a wall-clock runaway program via SIGTERM/SIGKILL and reports timeout', async () => { const { runtime } = await setup({ maxWallMs: 500, graceMs: 200 }) const start = Date.now() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'import time\nwhile True: time.sleep(1)', bindings: [], - }) + })) const elapsed = Date.now() - start // The wall timer may fire first or the exit-after-signal may resolve; both are ok. expect(['timeout', 'worker-exit']).toContain(result.error?.kind) @@ -3027,11 +3027,11 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { it('aborts a run when the outer signal fires mid-flight', async () => { const { runtime } = await setup({ maxWallMs: 10_000 }) const controller = new AbortController() - const settled: Promise = runtime.run({ + const settled: Promise = runtime.run(runtime.resolve({ program: 'import time\nwhile True: time.sleep(0.1)', bindings: [], signal: controller.signal, - }) + })) setTimeout(() => { controller.abort('outer-abort') }, 200) const result = await settled expect(['abort', 'worker-exit']).toContain(result.error?.kind) @@ -3050,11 +3050,11 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { try { const { runtime } = await setup({ maxWallMs: 4_000, graceMs: 200 }) const controller = new AbortController() - const settled: Promise = runtime.run({ + const settled: Promise = runtime.run(runtime.resolve({ program: 'import time\nwhile True: time.sleep(0.1)', bindings: [], signal: controller.signal, - }) + })) setTimeout(() => { controller.abort({ [Symbol.toPrimitive]() { throw new Error('reason blew up') } }) }, 200) @@ -3069,10 +3069,10 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { it('disposes to quiescence: an in-flight run resolves as abort and the child exits', async () => { const { fiber, runtime } = await setup({ maxWallMs: 10_000 }) - const pending = runtime.run({ + const pending = runtime.run(runtime.resolve({ program: 'import time\nwhile True: time.sleep(0.1)', bindings: [], - }) + })) // Give the process time to spawn and start running. await new Promise(resolve => setTimeout(resolve, 200)) await fiber.dispose() @@ -3087,7 +3087,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { const { runtime, fiber } = await setup({ pythonBin, maxWallMs: 3000 }) rmSync(pythonBin) try { - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error?.kind).toBe('worker-exit') } finally { await fiber.dispose() @@ -3116,7 +3116,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // What is observable: a very large cap still yields a working run, and the // containment it promises is met by the inherited ceiling. const { runtime } = await setup({ cpuSeconds: Number.MAX_SAFE_INTEGER - 1, maxWallMs: 10_000 }) - const result = await runtime.run({ program: 'return 1', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) expect(result.error).toBeUndefined() expect(result.value).toBe(1) }, 20_000) @@ -3127,10 +3127,10 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // listener that never fired — run() hung forever whenever the exit event // beat the final fd-3 data (deterministic on macOS, a lost race elsewhere). const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'import os\nos._exit(7)', bindings: [], - }) + })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('code=7') }, 5000) @@ -3141,10 +3141,10 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // differently, so we assert only kind/message here — CI's darwin leg // validates real delivery. cpuSeconds must be an integer for setrlimit. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 20_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'while True: pass', bindings: [], - }) + })) expect(result.error?.kind).toBe('timeout') expect(result.error?.message).toContain('CPU time exhausted') }, 8000) @@ -3155,13 +3155,13 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // seconds before that (cgroup OOM, an operator, os.kill) is substrate // death and stays worker-exit per the orthogonal taxonomy. const { runtime } = await setup({ cpuSeconds: 60, maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, signal', 'os.kill(os.getpid(), signal.SIGKILL)', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('SIGKILL') }) @@ -3175,7 +3175,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // settle-time check meters RUSAGE_SELF + RUSAGE_CHILDREN and converts the // overrun into the same SIGXCPU the untrapped soft limit sends. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import subprocess, sys', 'for _ in range(2):', @@ -3183,7 +3183,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return "escaped the cpu budget"', ].join('\n'), bindings: [], - }) + })) // Darwin's SIGXCPU re-delivery differs, so accept either terminal // classification; what must NOT happen is the completion crossing. expect(['timeout', 'worker-exit']).toContain(result.error?.kind) @@ -3196,20 +3196,20 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // have to complete normally, or the check would reject every program that // shells out. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 30_000 }) - const slept = await runtime.run({ + const slept = await runtime.run(runtime.resolve({ program: 'import time\ntime.sleep(1.5)\nreturn "slept"', bindings: [], - }) + })) expect(slept.error).toBeUndefined() expect(slept.value).toBe('slept') - const cheap = await runtime.run({ + const cheap = await runtime.run(runtime.resolve({ program: [ 'import subprocess, sys', 'subprocess.run([sys.executable, "-c", "pass"])', 'return "cheap child"', ].join('\n'), bindings: [], - }) + })) expect(cheap.error).toBeUndefined() expect(cheap.value).toBe('cheap child') }, 40_000) @@ -3229,7 +3229,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // unsettable) and /proc/self/maps does not exist there, so the mapping // assertion is Linux-only; the completion path is checked everywhere. const { runtime } = await setup({ maxValueBytes: 4096, addressSpaceMb: 256 }) - const mapped = await runtime.run({ + const mapped = await runtime.run(runtime.resolve({ program: [ 'import sys', 'if sys.platform != "linux":', @@ -3242,7 +3242,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return total // (1024 * 1024)', ].join('\n'), bindings: [], - }) + })) expect(mapped.error).toBeUndefined() expect(mapped.value).toBeLessThan(48) }, 20_000) @@ -3262,7 +3262,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // after-the-fact number cannot separate the pump's cost from the // interpreter's own footprint. Linux-only for the same reason as above. const { runtime } = await setup({ addressSpaceMb: 256, maxWallMs: 20_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', 'def mapped():', @@ -3279,7 +3279,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return {"before": before, "after": mapped(), "echoed": echoed}', ].join('\n'), bindings: tools({ echo: async args => args as CodeJsonValue }), - }) + })) expect(result.error).toBeUndefined() const value = result.value as { before: number; after: number; echoed: unknown } // The binding call really happened, so the pump really ran. @@ -3298,14 +3298,14 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // as timeout). Either way the run TERMINATES within the budget — the // backstop holds even when the classification is the opaque one. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 6_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import signal', 'signal.signal(signal.SIGXCPU, signal.SIG_IGN)', 'while True: pass', ].join('\n'), bindings: [], - }) + })) expect(['timeout', 'worker-exit']).toContain(result.error?.kind) }, 12_000) @@ -3315,7 +3315,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // defang it: a trapping program that also swaps the callables and burns // past the budget still dies by the authoritative SIGXCPU. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import signal, os, resource, time', 'signal.signal(signal.SIGXCPU, lambda *a: None)', @@ -3327,7 +3327,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return "escaped"', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('timeout') expect(result.value).toBeUndefined() }, 15_000) @@ -3338,7 +3338,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // and dies by SIGXCPU with the default disposition restored, so the host // still classifies the exhausted budget as a timeout instead of success. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import signal, time', 'fired = []', @@ -3348,7 +3348,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return "escaped"', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('timeout') expect(result.error?.message).toContain('CPU time exhausted') expect(result.value).toBeUndefined() @@ -3361,7 +3361,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // before the program starts, so neither replacing the global nor swapping // the module's captured names changes what runs after settlement. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import signal, time, __main__', 'signal.signal(signal.SIGXCPU, lambda *a: None)', @@ -3371,7 +3371,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return "escaped"', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('timeout') expect(result.value).toBeUndefined() }, 15_000) @@ -3389,7 +3389,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // reportable either way. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 20_000 }) const start = Date.now() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import signal, sys, time', 'signal.signal(signal.SIGXCPU, lambda *a: None)', @@ -3412,7 +3412,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'while True: pass', ].join('\n'), bindings: [], - }) + })) // What holds on EVERY platform: the tampering bought no success. The run // failed, carried no value, and the reported kind is one of the two // kernel-level outcomes — never a completion. @@ -3448,7 +3448,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // sleep lost that race on slow CI runners — SIGTERM landed pre-trap). let reportedPid!: (pid: number) => void const trapReady = new Promise((resolve) => { reportedPid = resolve }) - const pending = runtime.run({ + const pending = runtime.run(runtime.resolve({ program: [ 'import signal, time, os', 'signal.signal(signal.SIGTERM, lambda *a: None)', @@ -3461,7 +3461,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { return 'ok' }, }), - }) + })) const pid = await trapReady const start = Date.now() await fiber.dispose() @@ -3485,7 +3485,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // must force settlement on the value the `done` frame already decided. const { runtime } = await setup({ graceMs: 100 }) const start = Date.now() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import subprocess, sys', // Orphan in a fresh session, inheriting our stdout/stderr/fd 3, alive @@ -3500,7 +3500,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return "escaped"', ].join('\n'), bindings: [], - }) + })) const elapsed = Date.now() - start // The done frame decided the value; the deadline settled it despite the // orphan pinning the pipes open. @@ -3519,7 +3519,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // be flushed before destroy() drops it, or the diagnostic is lost from // `logs`. The value is decided by the done frame; the diagnostic must survive. const { runtime } = await setup({ graceMs: 100 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, subprocess, sys', 'os.write(1, b"leader-diagnostic-no-newline")', @@ -3528,7 +3528,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return "escaped"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('escaped') expect(result.logs).toContain('leader-diagnostic-no-newline') @@ -3542,14 +3542,14 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // open and no data written, `sys.stdin.read()` blocks and the run would // hang to maxWallMs as a timeout. const { runtime } = await setup({ maxWallMs: 8_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', 'data = sys.stdin.read()', 'return "read: " + repr(data)', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe("read: ''") }, 15_000) @@ -3560,14 +3560,14 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { // compiled code and stringifies its type annotations, changing the semantics // of a legal program that reads `f.__annotations__` at runtime. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'def f(x: int) -> int:', ' return x', 'return f.__annotations__["x"].__name__', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('int') }, 15_000) @@ -3595,7 +3595,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { const readyMarker = join(handoff, 'ready') const heartbeat = join(handoff, 'heartbeat') const { runtime } = await setup({ maxWallMs: 10_000, graceMs: 300 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import subprocess, sys, os, time', `marker = ${JSON.stringify(readyMarker)}`, @@ -3622,7 +3622,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return "spawned"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('spawned') // The trap really installed before the leader returned, so this is the @@ -3660,7 +3660,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { const readyMarker = join(handoff, 'ready') const heartbeat = join(handoff, 'heartbeat') const { runtime, fiber } = await setup({ maxWallMs: 10_000, graceMs: 300 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import subprocess, sys, os, time', `marker = ${JSON.stringify(readyMarker)}`, @@ -3682,7 +3682,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return "spawned"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(existsSync(readyMarker)).toBe(true) // dispose() must not return until the group is reaped. After it resolves, the @@ -3714,7 +3714,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { const heartbeat = join(handoff, 'heartbeat') const graceMs = 300 const { runtime } = await setup({ maxWallMs: 10_000, graceMs }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import subprocess, sys, os, time', `marker = ${JSON.stringify(readyMarker)}`, @@ -3736,7 +3736,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'return "spawned"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(existsSync(readyMarker)).toBe(true) // Block the event loop synchronously past graceMs + CLOSE_REAP_MARGIN_MS @@ -3765,7 +3765,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // non-JSON line, a valid JSON but unknown-shape frame, and a broken done // frame; the host must not crash, and the real `done` still settles the run. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'os.write(3, b"not-json\\n")', @@ -3774,7 +3774,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "survived"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('survived') }) @@ -3787,7 +3787,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the id-bound test below, not this one. const { runtime } = await setup({ maxWallMs: 8_000 }) let seenLegitCall = false - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'x = await tools.echo({"ping": True})', @@ -3799,7 +3799,7 @@ describe('PythonCodeRuntime — hostile peer', () => { bindings: tools({ echo: async (args) => { seenLegitCall = true; return args as CodeJsonValue }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ ping: true }) expect(seenLegitCall).toBe(true) @@ -3812,7 +3812,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // with a huge global/name cannot spike host memory near the value ceiling; // the reply still identifies the binding. const { runtime } = await setup({ maxWallMs: 8_000, maxValueBytes: 1024 * 1024 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'x = await tools.echo({"ping": True})', @@ -3823,7 +3823,7 @@ describe('PythonCodeRuntime — hostile peer', () => { bindings: tools({ echo: async args => args as CodeJsonValue, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ ping: true }) }, 15_000) @@ -3841,7 +3841,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // call that follows rather than the forgeries. const { runtime } = await setup() let echoCalls = 0 - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'for i in range(2000, 0, -1):', @@ -3852,7 +3852,7 @@ describe('PythonCodeRuntime — hostile peer', () => { bindings: tools({ echo: async (args) => { echoCalls += 1; return args as CodeJsonValue }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ ping: true }) expect(echoCalls).toBe(1) @@ -3865,7 +3865,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // would hang to the wall ceiling instead of completing. const { runtime } = await setup({ maxWallMs: 8_000 }) const seen: unknown[] = [] - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'caught = ""', 'try:', @@ -3878,7 +3878,7 @@ describe('PythonCodeRuntime — hostile peer', () => { bindings: tools({ echo: async (args) => { seen.push(args); return args as CodeJsonValue }, }), - }) + })) expect(result.error).toBeUndefined() const value = result.value as { caught: string; after: unknown } expect(value.caught).toContain('lossless JSON') @@ -3894,7 +3894,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // child cannot produce one (its validator rejects unsafe ints). const { runtime } = await setup() let dispatched: unknown - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', // Forged call frame with an unsafe int argument, then a forged done @@ -3907,7 +3907,7 @@ describe('PythonCodeRuntime — hostile peer', () => { bindings: tools({ echo: async (args) => { dispatched = args; return args as CodeJsonValue }, }), - }) + })) expect(result.error).toBeUndefined() // The forged done did not settle the run; the legit call and completion did. expect(result.value).toEqual({ ok: true }) @@ -3918,14 +3918,14 @@ describe('PythonCodeRuntime — hostile peer', () => { // Set a tiny host-side budget; the Python side has a much larger one, so // its LogBuffer will not truncate — the host ledger fires first. const { runtime } = await setup({ maxLogBytes: 128 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'for _ in range(50):', ' print("aaaaaaaaaa")', 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() const markers = result.logs.filter(line => line.includes('log capture truncated at 128 bytes')) expect(markers.length).toBeGreaterThanOrEqual(1) @@ -3935,10 +3935,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // A strict UTF-8 encode of "\ud800" throws while BUILDING the failure // frame; the run would then hang to maxWallMs and misreport as timeout. const { runtime } = await setup({ maxWallMs: 8_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: String.raw`raise Exception("bad \ud800 surrogate")`, bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('bad') expect(result.error?.message).toContain('surrogate') @@ -3950,10 +3950,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // unit. `CodeJsonValue`, `snapshotJsonValue`, and the worker backend all // accept such a string, so this backend must not narrow the shared seam. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: String.raw`return {"lone": "a\ud800b", "spelled": "😀"}`, bindings: [], - }) + })) expect(result.error).toBeUndefined() // The lone half survives as the code unit itself; a spelled-out high-low // PAIR folds into the astral character the host would hold for it. @@ -3964,11 +3964,11 @@ describe('PythonCodeRuntime — hostile peer', () => { // The child and the host share maxValueBytes, so the child must charge the // escape's six ASCII bytes (plus two quotes): eight fits, nine does not. const { runtime } = await setup({ maxValueBytes: 8 }) - const ok = await runtime.run({ program: String.raw`return "\ud800"`, bindings: [] }) + const ok = await runtime.run(runtime.resolve({ program: String.raw`return "\ud800"`, bindings: [] })) expect(ok.error).toBeUndefined() expect(ok.value).toBe('\ud800') const over = await setup({ maxValueBytes: 7 }) - const result = await over.runtime.run({ program: String.raw`return "\ud800"`, bindings: [] }) + const result = await over.runtime.run(over.runtime.resolve({ program: String.raw`return "\ud800"`, bindings: [] })) expect(result.error?.kind).toBe('output-limit') }) @@ -3985,11 +3985,11 @@ describe('PythonCodeRuntime — hostile peer', () => { // report output-limit one byte under, proving the meter counts every // surrogate exactly rather than dropping or over-charging any. const { runtime } = await setup({ maxValueBytes: 18_000_002 }) - const ok = await runtime.run({ program: 'return "\\ud800" * 3000000', bindings: [] }) + const ok = await runtime.run(runtime.resolve({ program: 'return "\\ud800" * 3000000', bindings: [] })) expect(ok.error).toBeUndefined() expect(ok.value).toBe('\ud800'.repeat(3_000_000)) const over = await setup({ maxValueBytes: 18_000_001 }) - const result = await over.runtime.run({ program: 'return "\\ud800" * 3000000', bindings: [] }) + const result = await over.runtime.run(over.runtime.resolve({ program: 'return "\\ud800" * 3000000', bindings: [] })) expect(result.error?.kind).toBe('output-limit') }, 60_000) @@ -3998,10 +3998,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // binding must receive the code unit the program passed. const seen: unknown[] = [] const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: String.raw`return await tools.echo({"text": "x\udfff"})`, bindings: tools({ echo: async (args: unknown) => { seen.push(args); return args as CodeJsonValue } }), - }) + })) expect(result.error).toBeUndefined() expect(seen).toEqual([{ text: 'x\udfff' }]) expect(result.value).toEqual({ text: 'x\udfff' }) @@ -4012,10 +4012,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // the host meter counts its UTF-8 JSON form (4); the shared budget must // agree, so a 4-byte-fitting value passes a maxValueBytes of 4. const { runtime } = await setup({ maxValueBytes: 4 }) - const ok = await runtime.run({ program: 'return "é"', bindings: [] }) + const ok = await runtime.run(runtime.resolve({ program: 'return "é"', bindings: [] })) expect(ok.error).toBeUndefined() expect(ok.value).toBe('é') - const over = await runtime.run({ program: 'return "éx"', bindings: [] }) + const over = await runtime.run(runtime.resolve({ program: 'return "éx"', bindings: [] })) expect(over.error?.kind).toBe('output-limit') }) @@ -4023,7 +4023,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // Python 3.11+ stores member stacks under TracebackException.exceptions; // the -frame filter must recurse into them too. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import asyncio, sys', 'if sys.version_info < (3, 11):', @@ -4034,7 +4034,7 @@ describe('PythonCodeRuntime — hostile peer', () => { ' tg.create_task(boom())', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('') expect(result.error?.message).not.toContain('bootstrap.py') @@ -4046,7 +4046,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // interleave bytes mid-frame and the host would drop the malformed JSON, // hanging the run to the wall clock (or losing the completion). const { runtime } = await setup({ maxValueBytes: 1024 * 1024, maxLogBytes: 4 * 1024 * 1024, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import threading', 'stop = False', @@ -4062,7 +4062,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return big', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('x'.repeat(300 * 1024)) }, 20_000) @@ -4084,7 +4084,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the body returns and settlement flushes. Repeated so the interleave lands. for (let attempt = 0; attempt < 5; attempt++) { const { runtime, fiber } = await setup({ maxLogBytes: 4 * 1024 * 1024, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys, threading', 'stop = False', @@ -4101,7 +4101,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "settled"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('settled') await fiber.dispose() @@ -4126,7 +4126,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // this test pins. const { runtime } = await setup({ maxWallMs: 8_000 }) const seen: unknown[] = [] - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import asyncio, threading', 'result = {}', @@ -4142,7 +4142,7 @@ describe('PythonCodeRuntime — hostile peer', () => { bindings: tools({ echo: async (args) => { seen.push(args); return args as CodeJsonValue }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ from: 'thread' }) // The host binding actually ran (the reply round-tripped), not a timeout. @@ -4169,7 +4169,7 @@ describe('PythonCodeRuntime — hostile peer', () => { let releaseSlow!: () => void const slowGate = new Promise((resolve) => { releaseSlow = resolve }) const { runtime } = await setup({ maxWallMs: 6_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import asyncio, threading', 'closed = threading.Event()', @@ -4208,7 +4208,7 @@ describe('PythonCodeRuntime — hostile peer', () => { return 'released' }, }), - }) + })) expect(result.error).toBeUndefined() // The pump survived the closed-loop reply and delivered the later binding. expect(result.value).toBe('released') @@ -4229,7 +4229,7 @@ describe('PythonCodeRuntime — hostile peer', () => { let releaseSlow!: () => void const slowGate = new Promise((resolve) => { releaseSlow = resolve }) const { runtime } = await setup({ maxWallMs: 6_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', '__main__.RuntimeError = ValueError', @@ -4254,7 +4254,7 @@ describe('PythonCodeRuntime — hostile peer', () => { slow: async () => { await slowGate; return 'late' }, release: async () => { releaseSlow(); await new Promise(resolve => setImmediate(resolve)); return 'released' }, }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('released') }, 15_000) @@ -4268,7 +4268,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // before the program runs, so the entry name is immune; the run must still // report the success value. const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import __main__', 'def boom(*a, **k):', @@ -4277,7 +4277,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return 1', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(1) }, 15_000) @@ -4287,13 +4287,13 @@ describe('PythonCodeRuntime — hostile peer', () => { // integral double: String(2**60) emits a rounded form, and the child // would receive a DIFFERENT integer than the binding resolved. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'v = await tools.echo(2**60)', 'return v == 2**60', ].join('\n'), bindings: tools({ echo: async args => args as never }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(true) }) @@ -4303,10 +4303,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // 2**60 round-trip exactly and must cross (matching the worker backend); // 2**53+1 rounds and must fail as invalid-output. const { runtime } = await setup() - const exact = await runtime.run({ program: 'return [2**53, 2**60]', bindings: [] }) + const exact = await runtime.run(runtime.resolve({ program: 'return [2**53, 2**60]', bindings: [] })) expect(exact.error).toBeUndefined() expect(exact.value).toEqual([2 ** 53, 2 ** 60]) - const lossy = await runtime.run({ program: 'return 2**53 + 1', bindings: [] }) + const lossy = await runtime.run(runtime.resolve({ program: 'return 2**53 + 1', bindings: [] })) expect(lossy.error?.kind).toBe('invalid-output') expect(lossy.error?.message).toContain('not exactly representable') }) @@ -4317,7 +4317,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // compute. Exact-type matching fails it as invalid-output instead. The // worker backend rejects the prototype-equivalent shapes the same way. const { runtime } = await setup() - const hidden = await runtime.run({ + const hidden = await runtime.run(runtime.resolve({ program: [ 'class Sneaky(dict):', ' def items(self): return []', @@ -4327,18 +4327,18 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return Sneaky(secret="kept")', ].join('\n'), bindings: [], - }) + })) expect(hidden.error?.kind).toBe('invalid-output') expect(hidden.error?.message).toContain('unsupported type (Sneaky)') // A list subclass is refused on the same rule. - const listish = await runtime.run({ + const listish = await runtime.run(runtime.resolve({ program: ['class L(list):', ' def __iter__(self): return iter([])', 'return L([1, 2, 3])'].join('\n'), bindings: [], - }) + })) expect(listish.error?.kind).toBe('invalid-output') expect(listish.error?.message).toContain('unsupported type (L)') // The exact built-in containers still cross unchanged. - const plain = await runtime.run({ program: 'return {"secret": [1, 2]}', bindings: [] }) + const plain = await runtime.run(runtime.resolve({ program: 'return {"secret": [1, 2]}', bindings: [] })) expect(plain.error).toBeUndefined() expect(plain.value).toEqual({ secret: [1, 2] }) }) @@ -4351,20 +4351,20 @@ describe('PythonCodeRuntime — hostile peer', () => { const { runtime } = await setup() // _dump_float spells a float from repr(value), so an overridden __repr__ // decides the digits: F(2.5) serialized as 1. - const floated = await runtime.run({ + const floated = await runtime.run(runtime.resolve({ program: [ 'class F(float):', ' def __repr__(self): return "1.0"', 'return F(2.5)', ].join('\n'), bindings: [], - }) + })) expect(floated.error?.kind).toBe('invalid-output') expect(floated.error?.message).toContain('unsupported type (F)') // The JS-safe-range bound is two comparisons, so overriding them admits an // int whose true digits (json.dumps reads the C-level value) the host's // JSON.parse rounds: 9007199254740993 arrives as ...992. - const inted = await runtime.run({ + const inted = await runtime.run(runtime.resolve({ program: [ 'class I(int):', ' def __gt__(self, other): return False', @@ -4372,38 +4372,38 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return I(2 ** 53 + 1)', ].join('\n'), bindings: [], - }) + })) expect(inted.error?.kind).toBe('invalid-output') expect(inted.error?.message).toContain('unsupported type (I)') // The pre-encode size bound reads len(), so overriding it to 0 admits a // string of any length past maxValueBytes. - const stringed = await runtime.run({ + const stringed = await runtime.run(runtime.resolve({ program: [ 'class S(str):', ' def __len__(self): return 0', 'return S("Q" * 100000)', ].join('\n'), bindings: [], - }) + })) expect(stringed.error?.kind).toBe('invalid-output') expect(stringed.error?.message).toContain('unsupported type (S)') // A str-subclass dict KEY reaches the same len() bound. - const keyed = await runtime.run({ + const keyed = await runtime.run(runtime.resolve({ program: [ 'class S(str):', ' def __len__(self): return 0', 'return {S("Q" * 100000): 1}', ].join('\n'), bindings: [], - }) + })) expect(keyed.error?.kind).toBe('invalid-output') expect(keyed.error?.message).toContain('non-string dict key (S)') // bool is an int subclass that IS lossless JSON, and the exact scalars all // still cross unchanged. - const plain = await runtime.run({ + const plain = await runtime.run(runtime.resolve({ program: 'return {"t": True, "f": False, "n": None, "i": 7, "d": 2.5, "s": "ok"}', bindings: [], - }) + })) expect(plain.error).toBeUndefined() expect(plain.value).toEqual({ t: true, f: false, n: null, i: 7, d: 2.5, s: 'ok' }) }) @@ -4414,7 +4414,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // float whose digits come from an override. const { runtime } = await setup() const seen: CodeJsonValue[] = [] - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'class F(float):', ' def __repr__(self): return "1.0"', @@ -4427,7 +4427,7 @@ describe('PythonCodeRuntime — hostile peer', () => { seen.push(args as CodeJsonValue) return null } }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toContain('unsupported type (F)') expect(seen).toEqual([]) @@ -4439,7 +4439,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // value whose serialization disagrees with what was validated. const { runtime } = await setup() const seen: CodeJsonValue[] = [] - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'class Sneaky(dict):', ' def items(self): return []', @@ -4452,7 +4452,7 @@ describe('PythonCodeRuntime — hostile peer', () => { seen.push(args as CodeJsonValue) return null } }), - }) + })) expect(result.error).toBeUndefined() expect(result.value).toContain('unsupported type (Sneaky)') expect(seen).toEqual([]) @@ -4465,10 +4465,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // which materialized chunk fragments plus the joined copy (~2 more // copies) and died on RLIMIT_AS as MemoryError/worker-exit. const { runtime } = await setup({ maxValueBytes: 1024, addressSpaceMb: 384, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return "x" * (100 * 1024 * 1024)', bindings: [], - }) + })) expect(result.error?.kind).toBe('output-limit') expect(result.error?.message).toContain('exceeded 1024 bytes') }, 20_000) @@ -4480,10 +4480,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // string but not its escaped expansion, so a pre-escape check dies on // RLIMIT_AS instead of returning output-limit. const { runtime } = await setup({ maxValueBytes: 1024, addressSpaceMb: 384, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return "\\x00" * (40 * 1024 * 1024)', bindings: [], - }) + })) expect(result.error?.kind).toBe('output-limit') expect(result.error?.message).toContain('exceeded 1024 bytes') }, 20_000) @@ -4495,13 +4495,13 @@ describe('PythonCodeRuntime — hostile peer', () => { // address space comfortably holds one copy of the 100 MB string but // not the pre-fix double allocation plus interpreter overhead spikes. const { runtime } = await setup({ maxLogBytes: 1024, addressSpaceMb: 256, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'print("x" * (100 * 1024 * 1024))', 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true) @@ -4520,7 +4520,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the host as stray stdout and take the host ledger path rather than the // child's — which is exactly the route that leaked past the marker. const { runtime } = await setup({ maxLogBytes: 64, maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'print("y" * 70000)', @@ -4528,7 +4528,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') const markers = result.logs.filter(line => line.includes('log capture truncated')) @@ -4545,7 +4545,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the literal `true` counts — a forged `"yes"` is rebuilt away by // validateChildFrame, so that frame stays ordinary text. const { runtime } = await setup({ maxLogBytes: 4096, maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'os.write(3, json.dumps({"type":"log","text":"first","truncated":"yes"}).encode() + b"\\n")', @@ -4554,7 +4554,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') // The non-boolean flag did not truncate, so its text was captured normally. @@ -4575,7 +4575,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // so the retained size is fixed regardless of what the program sent. const forgedBytes = 1024 * 1024 const { runtime } = await setup({ maxLogBytes: 64, maxWallMs: 20_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', `big = "A" * ${forgedBytes}`, @@ -4583,7 +4583,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') // Only the host marker is kept, so the total stays orders of magnitude below @@ -4639,7 +4639,7 @@ describe('PythonCodeRuntime — hostile peer', () => { let result: CodeRunResult try { const { runtime } = await setup({ maxWallMs: 30_000 }) - result = await runtime.run({ program, bindings: [] }) + result = await runtime.run(runtime.resolve({ program, bindings: [] })) } finally { Buffer.concat = realConcat } @@ -4664,10 +4664,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // it at maxValueBytes before formatting/sending, not ship the whole // payload for the host to truncate after parsing. const { runtime } = await setup({ maxValueBytes: 1024 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'raise ValueError("boom-" + "x" * (8 * 1024 * 1024))', bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toContain('boom-') expect(result.error?.message.endsWith('… [truncated]')).toBe(true) @@ -4683,11 +4683,11 @@ describe('PythonCodeRuntime — hostile peer', () => { // by its serialized cost, so a NUL flood is truncated to fit the frame and // the run still reports the exception rather than a worker-exit. const { runtime } = await setup({ maxValueBytes: 4096 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ // 512 KiB of NUL: ~3 MiB once escaped, far past the 4 KiB cap. program: 'raise ValueError("\\x00" * (512 * 1024))', bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message.endsWith('… [truncated]')).toBe(true) // The SERIALIZED form (what the frame carried) fits the budget, so its raw @@ -4702,14 +4702,14 @@ describe('PythonCodeRuntime — hostile peer', () => { // Python LogBuffer until settlement — the buffered tail must still hit // the budget mid-run instead of growing without bound to RLIMIT/timeout. const { runtime } = await setup({ maxLogBytes: 1024, maxWallMs: 15_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'for _ in range(100000):', ' print("xxxxxxxxxx", end="")', 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true) @@ -4726,7 +4726,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // empty writes must instead settle normally and contribute NO log entry, // proving the chunk was dropped rather than joined at flush_line. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 256, maxWallMs: 20_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', 'for _ in range(2000000):', @@ -4734,7 +4734,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs).toEqual([]) @@ -4747,10 +4747,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // the run instead settles quickly with exactly one truncation marker. const { runtime } = await setup({ maxLogBytes: 256, maxWallMs: 10_000 }) const start = Date.now() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['print("x\\n" * 500000, end="")', 'return "done"'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1) @@ -4769,7 +4769,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // payload itself fits and the only remaining allocation is the stream's own // slice; 340 MiB of a 400 MiB cap cannot survive one more copy of it. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 400, maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', 'payload = "\\n".rjust(340 * 1024 * 1024, "A")', @@ -4777,7 +4777,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs).toEqual([logTruncationMarker(256)]) @@ -4797,7 +4797,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // bound must be applied BEFORE the join and the chunks dropped on that path, // so the run settles with the truncation marker it promises. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 400, maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', // One unterminated character first, so `_pending` is non-empty and the @@ -4808,7 +4808,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs).toEqual([logTruncationMarker(256)]) @@ -4826,7 +4826,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // and only a budget-sized prefix of it is copied; the rest of the write is // scanned in place. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 400, maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', 'sys.stdout.write("x")', @@ -4835,7 +4835,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs).toEqual([logTruncationMarker(256)]) @@ -4849,14 +4849,14 @@ describe('PythonCodeRuntime — hostile peer', () => { // "before hang" with flush=True ahead of an infinite loop returned // `logs: []`, losing the one diagnostic the program deliberately committed. const { runtime } = await setup({ maxWallMs: 4_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', 'print("before hang", end="", flush=True)', 'while True: pass', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('timeout') expect(result.logs).toContain('before hang') }, 15_000) @@ -4877,10 +4877,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // exactly 104 bytes (103 payload + 1 envelope), so 104 is the smallest // budget that admits the entry. const { runtime } = await setup({ maxLogBytes: 104, maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['print("y" * 100 + "\\n" + "z" * 10, end="")', 'return "done"'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs).toContain('y'.repeat(100)) @@ -4900,10 +4900,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // = 64 = the cap; a 61-character line costs 64 > 63 and truncates. The // marker rides envelope, so the serialized logs run to cap + marker. const { runtime } = await setup({ maxLogBytes: 64, maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: ['print("a" * 60 + "\\n" + "b" * 61, end="")', 'return "done"'].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') // The 60-character line was admitted; the 61-character line was not (a @@ -4926,14 +4926,14 @@ describe('PythonCodeRuntime — hostile peer', () => { // ledger must charge that expansion, or a control-character flood admits // 6x the configured cap. const { runtime } = await setup({ maxLogBytes: 256 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'for _ in range(500):', ' print("\\x00" * 10)', 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true) // Serialized (escaped) size of retained entries stays in the budget's @@ -4952,13 +4952,13 @@ describe('PythonCodeRuntime — hostile peer', () => { // clearing the 12x load gate for a 32 MiB budget) is sized so the run loads; // the gate separately guarantees a correctly-charged near-budget entry fits. const { runtime } = await setup({ maxLogBytes: 32 * 1024 * 1024, addressSpaceMb: 512, maxWallMs: 20_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'print("\\x00" * (24 * 1024 * 1024))', 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1) @@ -4980,7 +4980,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // space at N = 150 MiB (~300 MiB). The pre-fix code then buffered the whole // ~150 MiB tail again, pushing past 384 MiB; the sliced prefix does not. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 384, maxWallMs: 20_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', 'tail = "A" * (150 * 1024 * 1024)', @@ -4988,7 +4988,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true) @@ -5019,14 +5019,14 @@ describe('PythonCodeRuntime — hostile peer', () => { addressSpaceMb: 512, maxWallMs: 20_000, }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', 'sys.stdout.write("\\U0001F600" * 33_000_000)', 'return "\\U0001F600" * 33_000_000', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('output-limit') }, 30_000) @@ -5054,7 +5054,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // loaded runner's scheduling latency read as a `timeout` — what this test asserts // is the O(depth) memory shape, not a speed claim. const { runtime } = await setup({ maxValueBytes: 20 * 1024 * 1024, addressSpaceMb: 384, maxWallMs: 60_000 }) - const result = await runtime.run({ program: 'return [0] * 6_000_000', bindings: [] }) + const result = await runtime.run(runtime.resolve({ program: 'return [0] * 6_000_000', bindings: [] })) expect(result.error).toBeUndefined() expect(Array.isArray(result.value)).toBe(true) expect((result.value as number[]).length).toBe(6_000_000) @@ -5075,13 +5075,13 @@ describe('PythonCodeRuntime — hostile peer', () => { // The binding echoes its argument's length back, so the assertion proves the // call actually round-tripped rather than merely avoiding a crash. const { runtime } = await setup({ addressSpaceMb: 384, maxWallMs: 60_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return await tools.width([0] * 6_000_000)', bindings: [{ global: 'tools', functions: { width: async (items: unknown) => (items as number[]).length }, }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(6_000_000) }, 90_000) @@ -5103,10 +5103,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // Darwin does not apply the limit, so the spike is merely allocated there. const reply = 'A'.repeat(4 * 1024 * 1024) const { runtime } = await setup({ maxWallMs: 60_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'value = await tools.big({})\nreturn len(value)', bindings: [{ global: 'tools', functions: { big: async () => reply } }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(reply.length) }, 90_000) @@ -5122,7 +5122,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the run must still report `timeout`, and the late value must not appear. let resolvedLate = false const { runtime } = await setup({ maxWallMs: 1_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return await tools.slow({})', bindings: [{ global: 'tools', @@ -5134,7 +5134,7 @@ describe('PythonCodeRuntime — hostile peer', () => { }, }, }], - }) + })) expect(result.error?.kind).toBe('timeout') expect(result.value).toBeUndefined() // Pin that the late path actually ran, so the assertion above is not vacuous. @@ -5159,14 +5159,14 @@ describe('PythonCodeRuntime — hostile peer', () => { // peaked at 0.0 MiB. const chunk = 'A'.repeat(4 * 1024 * 1024) const { runtime } = await setup({ maxWallMs: 60_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import asyncio', 'parts = await asyncio.gather(*[tools.chunk({}) for _ in range(8)])', 'return sum(len(p) for p in parts)', ].join('\n'), bindings: [{ global: 'tools', functions: { chunk: async () => chunk } }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(8 * chunk.length) }, 90_000) @@ -5182,7 +5182,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // drain wait. const chunk = 'A'.repeat(4 * 1024 * 1024) const { runtime } = await setup({ maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import asyncio', // Resolve a reply big enough to backpressure fd 3, then exit without @@ -5193,7 +5193,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [{ global: 'tools', functions: { chunk: async () => chunk } }], - }) + })) // The program returned, so the completion wins over the mid-flight reply; // whatever the result, the run must settle (no hang on the drain wait). expect(result.error).toBeUndefined() @@ -5215,7 +5215,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the run must settle worker-exit with the reply-queue message, not a // wall-clock timeout. const { runtime } = await setup({ maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, time', 'frame = b\'{"type":"call","id":%d,"global":"tools","name":"echo","args":{}}\\n\'', @@ -5229,7 +5229,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "unreachable"', ].join('\n'), bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as CodeJsonValue } }], - }) + })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('reply queue exceeded') }, 30_000) @@ -5244,7 +5244,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // so no reply is ever produced; the flood of 5000 sequential calls must // cross the in-flight bound long before maxWallMs. const { runtime } = await setup({ maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, time', 'frame = b\'{"type":"call","id":%d,"global":"tools","name":"hang","args":{}}\\n\'', @@ -5256,7 +5256,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "unreachable"', ].join('\n'), bindings: [{ global: 'tools', functions: { hang: async () => await new Promise(() => {}) } }], - }) + })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('call backlog exceeded') }, 30_000) @@ -5270,13 +5270,13 @@ describe('PythonCodeRuntime — hostile peer', () => { // The cap is checked at event boundaries (after the microtask queue // drained), so this gather of 1025 instant calls completes. const { runtime } = await setup({ maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import asyncio', 'return len(await asyncio.gather(*[tools.echo(i) for i in range(1025)]))', ].join('\n'), bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as CodeJsonValue } }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(1025) }, 30_000) @@ -5289,7 +5289,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the done frame arrives with the outstanding count AT the cap — the event // must complete with its value, not settle as `call backlog exceeded`. const { runtime } = await setup({ maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import asyncio', 'for i in range(1024):', @@ -5301,7 +5301,7 @@ describe('PythonCodeRuntime — hostile peer', () => { global: 'tools', functions: { slow: async () => { await new Promise((resolve) => { setTimeout(resolve, 5_000) }); return 1 } }, }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') }, 30_000) @@ -5315,7 +5315,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the batch's finallys (which never run for this binding) and settles the // run as worker-exit long before maxWallMs. const { runtime } = await setup({ maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, time', 'frame = b\'{"type":"call","id":%d,"global":"tools","name":"hang","args":{}}\\n\'', @@ -5327,7 +5327,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "unreachable"', ].join('\n'), bindings: [{ global: 'tools', functions: { hang: async () => await new Promise(() => {}) } }], - }) + })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('call backlog exceeded') }, 30_000) @@ -5340,13 +5340,13 @@ describe('PythonCodeRuntime — hostile peer', () => { // sees the true count (all finallys have run), so this burst of compact // frames — sized so the pipe read splits it — completes with all results. const { runtime } = await setup({ maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import asyncio', 'return len(await asyncio.gather(*[t.e(i) for i in range(1300)]))', ].join('\n'), bindings: [{ global: 't', functions: { e: async (args: unknown) => args as CodeJsonValue } }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe(1300) }, 30_000) @@ -5360,7 +5360,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the frame, so the run settles as worker-exit with the call-backlog // message instead. const { runtime } = await setup({ maxWallMs: 30_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, time', 'frame = b\'{"type":"call","id":%d,"global":"tools","name":"hang","args":{}}\\n\'', @@ -5372,7 +5372,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "unreachable"', ].join('\n'), bindings: [{ global: 'tools', functions: { hang: async () => await new Promise(() => {}) } }], - }) + })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('call backlog exceeded') }, 30_000) @@ -5384,10 +5384,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // silently drop one of them, violating the lossless-JSON completion // contract. The child's meter rejects the collision before encoding. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: 'return {"\\ud83d\\ude00": 1, "\\U0001f600": 2}', bindings: [], - }) + })) expect(result.error?.kind).toBe('invalid-output') expect(result.error?.message).toContain('duplicate dict key') }, 30_000) @@ -5397,7 +5397,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // not lossless JSON, so the program's `await` raises and the program // surfaces the rejection message. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'try:', ' await tools.echo({"\\ud83d\\ude00": 1, "\\U0001f600": 2})', @@ -5406,7 +5406,7 @@ describe('PythonCodeRuntime — hostile peer', () => { ' return str(e)', ].join('\n'), bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as CodeJsonValue } }], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toContain('duplicate dict key') }, 30_000) @@ -5417,14 +5417,14 @@ describe('PythonCodeRuntime — hostile peer', () => { // array without bound. Each empty entry costs one byte, so a 64-byte // budget retains at most 64 entries before the marker. const { runtime } = await setup({ maxLogBytes: 64, maxWallMs: 10_000 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'for _ in range(10000):', ' print()', 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.length).toBeLessThanOrEqual(65) expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true) @@ -5442,7 +5442,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // 3-byte), U+1F600 (F0, the range-restricted F0 lead), and U+10FFFF (F4 8F // BF BF, the range-restricted F4 lead). const { runtime } = await setup({ maxLogBytes: 1024 * 1024 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', // os.write is one syscall and returns a partial count on a full @@ -5455,7 +5455,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() const text = result.logs.join('') expect(text).toContain('\u0900\u4f60\u597d\u{1f600}\u{10ffff}') @@ -5468,7 +5468,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // residual. The 'end' flush decodes the residual with `toString('utf8')`, // which renders the stranded bytes as U+FFFD instead of dropping them. const { runtime } = await setup({ maxLogBytes: 1024 * 1024 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', // b"\xe4\xbd" is the leading two bytes of U+4F60; no continuation byte @@ -5477,7 +5477,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.join('')).toContain('�') }) @@ -5488,10 +5488,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // namespace list valid on one backend is valid on every backend. const { runtime } = await setup() for (const global of ['lambda', 'typeof']) { - await expect(runtime.run({ + await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global, functions: {} }], - })).rejects.toThrow(/is not a usable Python identifier/) + }))).rejects.toThrow(/is not a usable Python identifier/) } }) @@ -5500,7 +5500,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // LogBuffer, so the host's stray-byte capture on child.stdout is what // records it. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'os.write(1, b"stray stdout\\n")', @@ -5508,7 +5508,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.join('')).toContain('stray stdout') expect(result.logs.join('')).toContain('stray stderr') @@ -5524,7 +5524,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // std streams before sending the done frame, so the bytes land in the // kernel pipe buffer and the host's stray capture records them. const { runtime } = await setup() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import sys', // `-u` makes the streams write-through; re-enable block buffering so @@ -5538,7 +5538,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs.join('')).toContain('orig stdout') @@ -5550,14 +5550,14 @@ describe('PythonCodeRuntime — hostile peer', () => { // fires SIGKILL after graceMs. The full run reports either timeout (wall) // or worker-exit depending on which finish reason wins the race. const { runtime } = await setup({ maxWallMs: 400, graceMs: 200 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import signal, time', 'signal.signal(signal.SIGTERM, lambda *a: None)', 'while True: time.sleep(1)', ].join('\n'), bindings: [], - }) + })) expect(['timeout', 'worker-exit']).toContain(result.error?.kind) }, 6000) @@ -5571,7 +5571,7 @@ describe('PythonCodeRuntime — hostile peer', () => { const ceiling = 64 * 1024 * 1024 const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 }) const start = Date.now() - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', `for _ in range(${Math.ceil((ceiling * 1.1) / (8 * 1024 * 1024))}):`, @@ -5579,7 +5579,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "never"', ].join('\n'), bindings: [], - }) + })) const elapsed = Date.now() - start expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain(`protocol frame exceeded ${ceiling} bytes`) @@ -5596,7 +5596,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // instead of returning a lie. const maxValueBytes = 64 const { runtime } = await setup({ maxValueBytes }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'big = "B" * 5000', @@ -5606,7 +5606,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'time.sleep(5)', ].join('\n'), bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('output-limit') expect(result.error?.message).toContain('exceeded 64 bytes') @@ -5623,7 +5623,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // space generous enough to BUILD the frame. const { runtime } = await setup({ maxLogBytes: 128, addressSpaceMb: 1024, maxWallMs: 60_000 }) const before = process.memoryUsage().heapUsed - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', // Written as a raw frame so the child's own ledger never sees it. @@ -5631,7 +5631,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "settled"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('settled') // The frame was dropped as one truncation marker, not retained. @@ -5646,14 +5646,14 @@ describe('PythonCodeRuntime — hostile peer', () => { // the wire. Eleven NULs are 14 against the 64-byte ledger's cheap bound // (six bytes each, two quotes, one separator), so the full charge truncates. const { runtime } = await setup({ maxLogBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'os.write(3, b\'{"type":"log","text":"\' + b"\\\\u0000" * 11 + b\'"}\\n\')', 'return "settled"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('settled') expect(result.logs).toEqual([logTruncationMarker(64)]) @@ -5668,7 +5668,7 @@ describe('PythonCodeRuntime — hostile peer', () => { const maxValueBytes = 64 const { runtime } = await setup({ maxValueBytes, addressSpaceMb: 1024, maxWallMs: 60_000 }) const before = process.memoryUsage().heapUsed - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'os.write(3, b\'{"type":"done","error":{"kind":"exception","message":"\' + b"E" * (48 * 1024 * 1024) + b\'"}}\\n\')', @@ -5676,7 +5676,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'time.sleep(30)', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') const message = result.error?.message ?? '' // The marker's 15 bytes come OUT of the 64-byte cap, so 49 E's precede it @@ -5695,15 +5695,15 @@ describe('PythonCodeRuntime — hostile peer', () => { // (a raised exception) and the host's capMessage (a forged done frame). const maxValueBytes = 40 const { runtime } = await setup({ maxValueBytes }) - const raised = await runtime.run({ + const raised = await runtime.run(runtime.resolve({ program: 'raise ValueError("R" * 100000)', bindings: [], - }) + })) expect(raised.error?.kind).toBe('exception') const raisedMessage = raised.error?.message ?? '' expect(raisedMessage.endsWith('… [truncated]')).toBe(true) expect(Buffer.byteLength(raisedMessage, 'utf8')).toBeLessThanOrEqual(maxValueBytes) - const forged = await runtime.run({ + const forged = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'msg = "F" * 100000', @@ -5712,7 +5712,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'time.sleep(5)', ].join('\n'), bindings: [], - }) + })) expect(forged.error?.kind).toBe('exception') const forgedMessage = forged.error?.message ?? '' expect(forgedMessage.endsWith('… [truncated]')).toBe(true) @@ -5724,10 +5724,10 @@ describe('PythonCodeRuntime — hostile peer', () => { // message text; the marker still goes out, so the truncation stays reported // instead of the diagnostic silently becoming empty. Both producers agree. const { runtime } = await setup({ maxValueBytes: 4 }) - const raised = await runtime.run({ program: 'raise ValueError("R" * 500)', bindings: [] }) + const raised = await runtime.run(runtime.resolve({ program: 'raise ValueError("R" * 500)', bindings: [] })) expect(raised.error?.kind).toBe('exception') expect(raised.error?.message).toBe('… [truncated]') - const forged = await runtime.run({ + const forged = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'os.write(3, json.dumps({"type":"done","error":{"kind":"exception","message":"F" * 500}}).encode() + b"\\n")', @@ -5735,7 +5735,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'time.sleep(5)', ].join('\n'), bindings: [], - }) + })) expect(forged.error?.kind).toBe('exception') expect(forged.error?.message).toBe('… [truncated]') }, 15_000) @@ -5748,7 +5748,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the byte trim-back drops them. const maxValueBytes = 32 const { runtime } = await setup({ maxValueBytes }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', // 32 ASCII chars then astral characters: code unit 32 is the first @@ -5760,7 +5760,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'time.sleep(5)', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') // 17 A's fill the marker-reserved budget; no orphaned half, no U+FFFD. expect(result.error?.message).toBe(`${'A'.repeat(17)}… [truncated]`) @@ -5774,7 +5774,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the code-unit count, not a byte assumption: 6 characters at 3 bytes each // is 18 bytes, inside the 64-byte cap. const { runtime } = await setup({ maxValueBytes: 64 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'os.write(3, json.dumps({"type":"done","error":{"kind":"exception","message":"中文中文中文"}}).encode() + b"\\n")', @@ -5782,7 +5782,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'time.sleep(5)', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') expect(result.error?.message).toBe('中文中文中文') }, 8000) @@ -5797,7 +5797,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // would also exceed the cap. const maxValueBytes = 66 const { runtime } = await setup({ maxValueBytes }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os, json', 'msg = "E" + "\\U0001f600" * 2000', @@ -5806,7 +5806,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'time.sleep(5)', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('exception') const message = result.error?.message ?? '' expect(message.endsWith('… [truncated]')).toBe(true) @@ -5827,7 +5827,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // then a small newline tail, which is the chunk that crosses. const ceiling = 64 * 1024 * 1024 const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'chunk = b"A" * (8 * 1024 * 1024)', @@ -5837,7 +5837,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "never"', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain(`protocol frame exceeded ${ceiling} bytes`) }, 90_000) @@ -5855,7 +5855,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // that the per-line bound then dropped only after the doubling had happened. const ceiling = 64 * 1024 * 1024 const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'chunk = b"A" * (8 * 1024 * 1024)', @@ -5864,7 +5864,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "never"', ].join('\n'), bindings: [], - }) + })) expect(result.value).toBeUndefined() expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain(`protocol frame exceeded ${ceiling} bytes`) @@ -5878,7 +5878,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // must let them through, or a legitimate near-cap frame plus a trailing // frame would be misreported as a worker-exit. const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', 'chunk = b"A" * (8 * 1024 * 1024)', @@ -5890,7 +5890,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs).toContain('after-cap-frames') @@ -5907,7 +5907,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // case pins the worker-exit settlement, not a pre/post copy-count // distinction (both orders reject an over-cap frame). const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 }) - const result = await runtime.run({ + const result = await runtime.run(runtime.resolve({ program: [ 'import os', // 4 KiB writes are <= PIPE_BUF, so each os.write is atomic and the @@ -5925,7 +5925,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return "done"', ].join('\n'), bindings: [], - }) + })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('protocol frame exceeded') }, 120_000) diff --git a/packages/experimental/code-runtime-python/tests/stray-fragments.spec.ts b/packages/experimental/code-runtime-python/tests/stray-fragments.spec.ts index 500082b238..fd74737e12 100644 --- a/packages/experimental/code-runtime-python/tests/stray-fragments.spec.ts +++ b/packages/experimental/code-runtime-python/tests/stray-fragments.spec.ts @@ -39,10 +39,10 @@ it('seals stray fragments without recopying the sealed prefix', async () => { return realConcat(list, total) }) try { - const result = await ctx.codeRuntime.run({ + const result = await ctx.codeRuntime.run(ctx.codeRuntime.resolve({ program: 'import os\nos.write(1, b"x" * 60000 + b"\\n")\nreturn "done"', bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.value).toBe('done') expect(result.logs).toEqual(['x'.repeat(60_000)]) @@ -70,10 +70,10 @@ it.each([ return merged }) try { - const result = await ctx.codeRuntime.run({ + const result = await ctx.codeRuntime.run(ctx.codeRuntime.resolve({ program: `import os\nos.write(1, ${payload})\nreturn None`, bindings: [], - }) + })) expect(result.error).toBeUndefined() expect(result.logs.at(-1)).toBe(logTruncationMarker(3072)) // Each raw byte decodes to U+FFFD (three UTF-8 bytes), so a 3072-byte diff --git a/packages/fs/tool-fs/tests/read-image.spec.ts b/packages/fs/tool-fs/tests/read-image.spec.ts index d5b4dc5b46..ba1128fe30 100644 --- a/packages/fs/tool-fs/tests/read-image.spec.ts +++ b/packages/fs/tool-fs/tests/read-image.spec.ts @@ -71,6 +71,8 @@ class CatalogAdapter extends LlmAdapter { /** In-process PTC mode seam fake that invokes the real registry bindings. */ class FakeRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language = 'typescript' readonly isolation = 'fake' behavior: (request: CodeRunRequest) => Promise = () => Promise.resolve({ logs: [] }) diff --git a/packages/fs/tool-fs/tests/tools.spec.ts b/packages/fs/tool-fs/tests/tools.spec.ts index 49ad5d74f9..1a7e555c82 100644 --- a/packages/fs/tool-fs/tests/tools.spec.ts +++ b/packages/fs/tool-fs/tests/tools.spec.ts @@ -1049,6 +1049,8 @@ function withPersona(...sections: string[]): string { /** Schema assembly only: these cases never execute user code. */ class GuidanceCodeRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language = 'typescript' readonly isolation = 'fake' run() { return Promise.resolve({ logs: [] }) } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 118d112c52..e5dadf312f 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -509,6 +509,8 @@ describe('the soft layer', () => { // Minimal scriptable runtime: the SDK section resolves ctx.codeRuntime at // assembly time (the ptc.spec fake's shape). class FakeRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language = 'typescript' readonly isolation = 'fake' run(_request: CodeRunRequest): Promise { return Promise.resolve({ logs: [] }) } @@ -531,6 +533,8 @@ describe('the soft layer', () => { it('keeps native wire schemas and the SDK in step under mode both', async () => { class FakeRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language = 'typescript' readonly isolation = 'fake' run(_request: CodeRunRequest): Promise { return Promise.resolve({ logs: [] }) } @@ -553,6 +557,8 @@ describe('the soft layer', () => { it('keeps the PTC mode SDK byte-identical across mode switches', async () => { class FakeRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language = 'typescript' readonly isolation = 'fake' run(_request: CodeRunRequest): Promise { return Promise.resolve({ logs: [] }) } @@ -926,6 +932,8 @@ describe('exit_plan_mode', () => { it('carries the exact plan through a PTC mode review and logs the nested dispatch', async () => { const plan = '# PTC mode plan\n\nUse the existing seam.' class ExitRuntime extends CodeRuntime { + resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + readonly language = 'typescript' readonly isolation = 'fake' async run(request: CodeRunRequest): Promise { diff --git a/packages/sandbox/sandbox/src/diagnostics.ts b/packages/sandbox/sandbox/src/diagnostics.ts new file mode 100644 index 0000000000..d515ab20f7 --- /dev/null +++ b/packages/sandbox/sandbox/src/diagnostics.ts @@ -0,0 +1,100 @@ +/** Classify observed sandbox runner failures and file-effect denials. */ +import { accessSync, constants, statSync } from 'node:fs' +import type { RunnerFailureRule } from './index.ts' + +/** Node-local spawn codes proven to identify executable resolution or permission failure. */ +const EXECUTABLE_SPAWN_CODES = new Set(['EACCES', 'ENOENT']) + +/** Whether the caller-owned spawn cwd can be entered. */ +function isUsableWorkdir(path: string): boolean { + try { + if (!statSync(path).isDirectory()) return false + accessSync(path, constants.X_OK) + return true + } catch { + return false + } +} + +/** + * Attribute only Node ENOENT/EACCES failures whose error path equals argv[0] + * after independently ruling out the caller-owned cwd. A supplied error path + * must exactly identify the runner; without one, the syscall must. With a + * usable cwd, these codes describe resolution or execute permission for that + * argv[0] or its shebang interpreter. + * The workdir is checked at classification time, not atomically with spawn; + * concurrent path replacement may change attribution but cannot permit an + * unconfined execution. + * @param error - the original spawn rejection. + * @param runnerProgram - provider argv[0], the executable that establishes confinement. + * @param workdir - the caller-owned spawn cwd, checked independently for usability. + * @returns whether the rejection has executable-specific runner evidence. + */ +export function isRunnerSpawnFailure( + error: unknown, + runnerProgram: string | undefined, + workdir: string, +): boolean { + if (runnerProgram === undefined || !isUsableWorkdir(workdir)) return false + if (typeof error !== 'object' || error === null) return false + const { code, path, syscall } = error as { code?: unknown; path?: unknown; syscall?: unknown } + if (typeof code !== 'string' || !EXECUTABLE_SPAWN_CODES.has(code)) return false + if (typeof syscall !== 'string') return false + const exactSyscall = `spawn ${runnerProgram}` + if (path === undefined) return syscall === exactSyscall + if (typeof path !== 'string' || path.length === 0 || path !== runnerProgram) return false + return syscall === 'spawn' || syscall === exactSyscall +} + +/** Fatal runner evidence retained for infrastructure-error detail. */ +interface RunnerFailureMatch { + /** The original stderr line that matched a fatal signature. */ + detail: string +} + +/** + * Classify one settled process against the selected backend's structured + * runner-failure rules. Each rule requires a nonzero exit, its optional + * exit-code gate, and a fatal signature on one stderr line after exact + * informational lines are excluded. + * @param exitCode - process exit code; null means signal termination. + * @param stderr - collected stderr text, left unchanged. + * @param rules - structured runner-failure rules from the active wrap. + * @returns the first matching fatal line, or undefined when evidence is insufficient. + */ +export function classifyRunnerFailure( + exitCode: number | null, + stderr: string, + rules: readonly RunnerFailureRule[], +): RunnerFailureMatch | undefined { + if (exitCode === null || exitCode === 0) return undefined + const lines = stderr.split(/\r?\n/) + for (const rule of rules) { + if (rule.allowedExitCodes !== undefined && !rule.allowedExitCodes.includes(exitCode)) continue + const informationalLines = new Set((rule.informationalLines ?? []).map(line => line.toLowerCase())) + // An empty or whitespace-only substring is not meaningful runner evidence. + // Ignore it while keeping any valid signatures beside it active. + const fatalSignatures = rule.fatalSignatures + .filter(signature => signature.trim().length > 0) + .map(signature => signature.toLowerCase()) + for (const line of lines) { + const lowered = line.toLowerCase() + if (informationalLines.has(lowered)) continue + if (fatalSignatures.some(signature => lowered.includes(signature))) return { detail: line } + } + } + return undefined +} + +/** + * Match a non-zero exit against case-insensitive stderr signatures. + * @param exitCode - process exit code; null means signal termination. + * @param stderr - collected stderr text. + * @param signatures - substrings identifying the selected backend's dialect. + * @returns whether this is a non-zero exit whose stderr matches a signature. + */ +export function matchesSignature(exitCode: number | null, stderr: string, signatures: readonly string[]): boolean { + if (exitCode === null || exitCode === 0) return false + const lowered = stderr.toLowerCase() + return signatures.some(signature => lowered.includes(signature.toLowerCase())) +} diff --git a/packages/sandbox/sandbox/src/index.ts b/packages/sandbox/sandbox/src/index.ts index 2d9ee5b91b..e2d24e5001 100644 --- a/packages/sandbox/sandbox/src/index.ts +++ b/packages/sandbox/sandbox/src/index.ts @@ -176,3 +176,5 @@ export abstract class SandboxProvider extends Service { } export default SandboxProvider + +export { classifyRunnerFailure, isRunnerSpawnFailure, matchesSignature } from './diagnostics.ts' diff --git a/packages/shell/bash-sandbox/src/helpers.ts b/packages/shell/bash-sandbox/src/helpers.ts index d582e1def1..317faa429f 100644 --- a/packages/shell/bash-sandbox/src/helpers.ts +++ b/packages/shell/bash-sandbox/src/helpers.ts @@ -1,62 +1,7 @@ -/** - * Internal sandbox-result classification helpers. - * - * @module @deepseek-ai/dsh-bash-sandbox/helpers - */ - -import { accessSync, constants, statSync } from 'node:fs' +/** Shell-result projection over shared sandbox diagnostics. */ import type { ShellRunResult } from '@deepseek-ai/dsh-shell' -import type { RunnerFailureRule } from '@deepseek-ai/dsh-sandbox' - -/** Node-local spawn codes proven to identify executable resolution or permission failure. */ -const EXECUTABLE_SPAWN_CODES = new Set(['EACCES', 'ENOENT']) - -/** Whether the caller-owned spawn cwd can be entered. */ -function isUsableWorkdir(path: string): boolean { - try { - if (!statSync(path).isDirectory()) return false - accessSync(path, constants.X_OK) - return true - } catch { - return false - } -} - -/** - * Attribute only Node ENOENT/EACCES failures whose error path equals argv[0] - * after independently ruling out the caller-owned cwd. A supplied error path - * must exactly identify the runner; without one, the syscall must. With a - * usable cwd, these codes describe resolution or execute permission for that - * argv[0] or its shebang interpreter. - * The workdir is checked at classification time, not atomically with spawn; - * concurrent path replacement may change attribution but cannot permit an - * unconfined execution. - * @param error - the original spawn rejection. - * @param runnerProgram - provider argv[0], the executable that establishes confinement. - * @param workdir - the caller-owned spawn cwd, checked independently for usability. - * @returns whether the rejection has executable-specific runner evidence. - */ -export function isRunnerSpawnFailure( - error: unknown, - runnerProgram: string | undefined, - workdir: string, -): boolean { - if (runnerProgram === undefined || !isUsableWorkdir(workdir)) return false - if (typeof error !== 'object' || error === null) return false - const { code, path, syscall } = error as { code?: unknown; path?: unknown; syscall?: unknown } - if (typeof code !== 'string' || !EXECUTABLE_SPAWN_CODES.has(code)) return false - if (typeof syscall !== 'string') return false - const exactSyscall = `spawn ${runnerProgram}` - if (path === undefined) return syscall === exactSyscall - if (typeof path !== 'string' || path.length === 0 || path !== runnerProgram) return false - return syscall === 'spawn' || syscall === exactSyscall -} - -/** Fatal runner evidence retained for infrastructure-error detail. */ -interface RunnerFailureMatch { - /** The original stderr line that matched a fatal signature. */ - detail: string -} +import { matchesSignature } from '@deepseek-ai/dsh-sandbox' +export { isRunnerSpawnFailure, classifyRunnerFailure, matchesSignature } from '@deepseek-ai/dsh-sandbox' /** * Classify a failed run against the selected backend's denial dialect. @@ -67,50 +12,3 @@ interface RunnerFailureMatch { export function classifyDenial(result: ShellRunResult, signatures: readonly string[]): boolean { return matchesSignature(result.exitCode, result.stderr.text, signatures) } - -/** - * Classify one settled process against the selected backend's structured - * runner-failure rules. Each rule requires a nonzero exit, its optional - * exit-code gate, and a fatal signature on one stderr line after exact - * informational lines are excluded. - * @param exitCode - process exit code; null means signal termination. - * @param stderr - collected stderr text, left unchanged. - * @param rules - structured runner-failure rules from the active wrap. - * @returns the first matching fatal line, or undefined when evidence is insufficient. - */ -export function classifyRunnerFailure( - exitCode: number | null, - stderr: string, - rules: readonly RunnerFailureRule[], -): RunnerFailureMatch | undefined { - if (exitCode === null || exitCode === 0) return undefined - const lines = stderr.split(/\r?\n/) - for (const rule of rules) { - if (rule.allowedExitCodes !== undefined && !rule.allowedExitCodes.includes(exitCode)) continue - const informationalLines = new Set((rule.informationalLines ?? []).map(line => line.toLowerCase())) - // An empty or whitespace-only substring is not meaningful runner evidence. - // Ignore it while keeping any valid signatures beside it active. - const fatalSignatures = rule.fatalSignatures - .filter(signature => signature.trim().length > 0) - .map(signature => signature.toLowerCase()) - for (const line of lines) { - const lowered = line.toLowerCase() - if (informationalLines.has(lowered)) continue - if (fatalSignatures.some(signature => lowered.includes(signature))) return { detail: line } - } - } - return undefined -} - -/** - * Match a non-zero exit against case-insensitive stderr signatures. - * @param exitCode - process exit code; null means signal termination. - * @param stderr - collected stderr text. - * @param signatures - substrings identifying the selected backend's dialect. - * @returns whether this is a non-zero exit whose stderr matches a signature. - */ -export function matchesSignature(exitCode: number | null, stderr: string, signatures: readonly string[]): boolean { - if (exitCode === null || exitCode === 0) return false - const lowered = stderr.toLowerCase() - return signatures.some(signature => lowered.includes(signature.toLowerCase())) -} diff --git a/packages/spill/spill-policy/tests/spill-policy.spec.ts b/packages/spill/spill-policy/tests/spill-policy.spec.ts index 43ca7ca6b7..0ed4199272 100644 --- a/packages/spill/spill-policy/tests/spill-policy.spec.ts +++ b/packages/spill/spill-policy/tests/spill-policy.spec.ts @@ -21,7 +21,7 @@ import type { PostToolDecision, ToolExecution, ToolExecutionToken } from '@deeps import { SpillLocator, SpillStore } from '@deepseek-ai/dsh-spill' import type { SaveTextSpill, SpillRef } from '@deepseek-ai/dsh-spill' import * as SpillPolicy from '@deepseek-ai/dsh-spill-policy' -import { NodeCodeRuntime } from '@deepseek-ai/dsh-code-runtime-node' +import { mountRuntime } from '../../../code-runtime/code-runtime-node/tests/setup.ts' const testToolSignal = new AbortController().signal @@ -193,7 +193,7 @@ describe('outer PTC mode failure capture', () => { await ctx.plugin(ToolRuntime, { mode: 'ptc' }) await ctx.plugin(StubStore) await ctx.plugin(SpillPolicy, { maxInlineBytes: 200 }) - await ctx.plugin(NodeCodeRuntime, { maxOutputBytes: 500 }) + await mountRuntime(ctx, { maxOutputBytes: 500 }) const events: unknown[] = [] const agent = { session: { @@ -242,7 +242,7 @@ describe('the durable dispatch-log arm', () => { await ctx.plugin(ToolRuntime, { mode: 'ptc' }) await ctx.plugin(StubStore) await ctx.plugin(SpillPolicy, { maxInlineBytes }) - await ctx.plugin(NodeCodeRuntime, {}) + await mountRuntime(ctx, {}) const events: { type: string; data: unknown }[] = [] const agent = { session: { @@ -316,7 +316,7 @@ describe('the durable dispatch-log arm', () => { await ctx.plugin(ToolRuntime, { mode: 'ptc' }) await ctx.plugin(StubStore) await ctx.plugin(SpillPolicy, { maxInlineBytes: 100 }) - await ctx.plugin(NodeCodeRuntime, {}) + await mountRuntime(ctx, {}) // A spill backend that hangs until released. let releaseSave!: () => void const gate = new Promise((resolve) => { releaseSave = resolve }) @@ -380,7 +380,7 @@ describe('the durable dispatch-log arm', () => { await ctx.plugin(ToolRuntime, { mode: 'ptc', maxParallelSubCalls: 1 }) await ctx.plugin(StubStore) await ctx.plugin(SpillPolicy, { maxInlineBytes: 100 }) - await ctx.plugin(NodeCodeRuntime, {}) + await mountRuntime(ctx, {}) const store = ctx.spillStore as StubStore const releases: (() => void)[] = [] store.gate = () => new Promise((resolve) => { releases.push(resolve) }) @@ -433,7 +433,7 @@ describe('the durable dispatch-log arm', () => { await ctx.plugin(ToolRuntime, { mode: 'ptc' }) await ctx.plugin(StubStore) await ctx.plugin(SpillPolicy, { maxInlineBytes: 100 }) - await ctx.plugin(NodeCodeRuntime, {}) + await mountRuntime(ctx, {}) ;(ctx.spillStore as StubStore).fail = true const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) const events: { type: string; data: unknown }[] = [] diff --git a/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts b/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts index fa4bfdb22b..0521638fa9 100644 --- a/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts +++ b/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts @@ -63,6 +63,7 @@ async function setup(script: Script, options: SetupOptions = {}) { ctx.provide('codeRuntime', { language: 'typescript', isolation: 'test', + resolve: (request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest) => ({ ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: 120_000 }), run: options.codeRun ?? (() => Promise.resolve({ logs: [] })), } as never) } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d34a9ebc86..e737e3f96e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4584,6 +4584,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:^ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-sandbox': + specifier: workspace:^ + version: link:../../sandbox/sandbox packages/code-runtime/code-runtime-node: dependencies: @@ -4600,9 +4603,33 @@ importers: '@deepseek-ai/dsh-code-runtime': specifier: workspace:^ version: link:../code-runtime + '@deepseek-ai/dsh-fs': + specifier: workspace:^ + version: link:../../fs/fs + '@deepseek-ai/dsh-fs-local': + specifier: workspace:^ + version: link:../../fs/fs-local + '@deepseek-ai/dsh-sandbox': + specifier: workspace:^ + version: link:../../sandbox/sandbox + '@deepseek-ai/dsh-sandbox-local': + specifier: workspace:^ + version: link:../../sandbox/sandbox-local + '@deepseek-ai/dsh-sandbox-policy': + specifier: workspace:^ + version: link:../../sandbox/sandbox-policy '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session + '@deepseek-ai/dsh-session-projection': + specifier: workspace:^ + version: link:../../session/session-projection + '@deepseek-ai/dsh-subprocess': + specifier: workspace:^ + version: link:../../subprocess/subprocess + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:^ + version: link:../../subprocess/subprocess-local '@deepseek-ai/dsh-timeout': specifier: workspace:^ version: link:../../util/timeout @@ -5225,6 +5252,12 @@ importers: '@deepseek-ai/dsh-llm': specifier: workspace:^ version: link:../../llm/llm + '@deepseek-ai/dsh-sandbox': + specifier: workspace:^ + version: link:../../sandbox/sandbox + '@deepseek-ai/dsh-sandbox-policy': + specifier: workspace:^ + version: link:../../sandbox/sandbox-policy '@deepseek-ai/dsh-scope': specifier: workspace:^ version: link:../scope diff --git a/python/sdk-runtime/runtime-bootstrap.mjs b/python/sdk-runtime/runtime-bootstrap.mjs index bc2fbede75..153bdcd0e4 100644 --- a/python/sdk-runtime/runtime-bootstrap.mjs +++ b/python/sdk-runtime/runtime-bootstrap.mjs @@ -4,7 +4,10 @@ const selectorName = 'DSH_SUBPROCESS_RUNNER' const selection = process.env[selectorName] -if (selection === undefined) { +if (process.env.DSH_CODE_RUNTIME_NODE === '1') { + Reflect.deleteProperty(process.env, 'DSH_CODE_RUNTIME_NODE') + await import('@deepseek-ai/dsh-code-runtime-node/process') +} else if (selection === undefined) { const { runCli } = await import('@deepseek-ai/dsh/lib/bin.js') await runCli() } else { diff --git a/vitest.config.ts b/vitest.config.ts index 8556b58442..c22eafe72f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -210,6 +210,8 @@ export default defineConfig({ 'packages/*/*/src/types.ts', 'packages/*/*/src/bin.ts', 'packages/*/*/src/worker.ts', + // The built Node entry invokes the independently covered process bootstrap through fd 7. + 'packages/code-runtime/code-runtime-node/src/process-entry.ts', // Dynamic Host/Client composition is covered by its focused lifecycle // tests and assembled application checks rather than per-file coverage. 'packages/self-modification/*/src/**/*.{ts,tsx}',