diff --git a/packages/code-runtime/code-runtime-worker/README.md b/packages/code-runtime/code-runtime-worker/README.md index cc49c2f723..bfa19b1189 100644 --- a/packages/code-runtime/code-runtime-worker/README.md +++ b/packages/code-runtime/code-runtime-worker/README.md @@ -29,7 +29,7 @@ Every field is validated and defaulted; `maxOutputBytes` is a safe integer of at ## The worker entry, unbuilt and built -Source mode loads erasable-only `src/worker.ts` through Node's native type stripping. Built mode passes the sibling `lib/worker.cjs` as a filesystem path because pkg's VFS Worker hook expects CommonJS; the same path works under ordinary Node. `tests/built-lib.e2e.ts` pins the real load path required by [docs/testing.md](../../../docs/testing.md). +Source mode loads erasable-only `src/worker.ts` through Node's native type stripping. Its transitive runtime closure contains only Node built-ins and relative source modules, so a fresh checkout never requires a sibling workspace package's unbuilt `lib/` export. The worker-local JSON snapshotter is parity-tested against the session-owned canonical boundary; the host repeats canonical validation after structured clone. Built mode passes the sibling `lib/worker.cjs` as a filesystem path because pkg's VFS Worker hook expects CommonJS; the same path works under ordinary Node. `tests/built-lib.e2e.ts` pins the real load path required by [docs/testing.md](../../../docs/testing.md). The SDK surface is the default/named `WorkerCodeRuntime` class plus `Config`. The operational `./worker` subpath exists only as the packaged spawn entry; the wire protocol and bootstrap helpers are source-private implementation details. diff --git a/packages/code-runtime/code-runtime-worker/src/bootstrap.ts b/packages/code-runtime/code-runtime-worker/src/bootstrap.ts index e62ddd405e..45c8a4d2d2 100644 --- a/packages/code-runtime/code-runtime-worker/src/bootstrap.ts +++ b/packages/code-runtime/code-runtime-worker/src/bootstrap.ts @@ -6,8 +6,8 @@ */ import { inspect } from 'node:util' -import { snapshotJsonValue } from '@deepseek-ai/dsh-session' import type { DoneMessage, ReplyMessage, WorkerBootData, WorkerToHost } from './protocol.ts' +import { snapshotCodeJsonValue } from './worker-json.ts' /** The port surface the bootstrap needs — satisfied by `parentPort` and by the tests' fake. */ export interface BootstrapPort { @@ -157,7 +157,7 @@ export function prepareCompletion(value: unknown, maxOutputBytes: number): Omit< if (value === undefined) return {} let snapshot: unknown try { - snapshot = snapshotJsonValue(value) + snapshot = snapshotCodeJsonValue(value) } catch { snapshot = undefined } diff --git a/packages/code-runtime/code-runtime-worker/src/worker-json.ts b/packages/code-runtime/code-runtime-worker/src/worker-json.ts new file mode 100644 index 0000000000..eec80184f6 --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/src/worker-json.ts @@ -0,0 +1,67 @@ +/** Lossless-JSON snapshots for the dependency-free source worker closure. @module @deepseek-ai/dsh-code-runtime-worker/worker-json */ + +import type { CodeJsonValue } from '@deepseek-ai/dsh-code-runtime' + +/** + * Validate and detach one worker-boundary value without loading another + * workspace package at runtime. This mirrors the session-owned canonical + * JSON boundary while remaining safe to import from the unbuilt worker. + * + * @param value - the candidate completion value. + * @returns a detached lossless-JSON snapshot, or `undefined` when invalid. + */ +export function snapshotCodeJsonValue(value: unknown): CodeJsonValue | undefined { + const active = new Set() + + const within = (source: object, build: () => T | undefined): T | undefined => { + if (active.has(source)) return undefined + active.add(source) + try { + return build() + } finally { + active.delete(source) + } + } + + const copy = (candidate: unknown): CodeJsonValue | undefined => { + if (candidate === null) return null + if (typeof candidate === 'boolean' || typeof candidate === 'string') return candidate + if (typeof candidate === 'number') { + return Number.isFinite(candidate) && !Object.is(candidate, -0) ? candidate : undefined + } + if (typeof candidate !== 'object') return undefined + + if (Array.isArray(candidate)) { + if (Object.getPrototypeOf(candidate) !== Array.prototype) return undefined + return within(candidate, () => { + const result: CodeJsonValue[] = [] + for (let index = 0; index < candidate.length; index++) { + if (!Object.hasOwn(candidate, index)) return undefined + const item = copy(candidate[index]) + if (item === undefined) return undefined + result.push(item) + } + return result + }) + } + + const prototype = Object.getPrototypeOf(candidate) as unknown + if (prototype !== Object.prototype && prototype !== null) return undefined + return within(candidate, () => { + const result: Record = {} + for (const key of Object.keys(candidate)) { + const item = copy((candidate as Record)[key]) + if (item === undefined) return undefined + Object.defineProperty(result, key, { + value: item, + enumerable: true, + configurable: true, + writable: true, + }) + } + return result + }) + } + + return copy(value) +} diff --git a/packages/code-runtime/code-runtime-worker/tests/source-worker.compat.spec.ts b/packages/code-runtime/code-runtime-worker/tests/source-worker.compat.spec.ts new file mode 100644 index 0000000000..5b71a9a94a --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/tests/source-worker.compat.spec.ts @@ -0,0 +1,36 @@ +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' + +/** + * 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'] + 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).toEqual({ type: 'done', value: { answer: 42 } }) + } finally { + if (worker) await worker.terminate() + await rm(directory, { recursive: true, force: true }) + } +}) diff --git a/packages/code-runtime/code-runtime-worker/tests/worker-json.spec.ts b/packages/code-runtime/code-runtime-worker/tests/worker-json.spec.ts new file mode 100644 index 0000000000..3f717599b7 --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/tests/worker-json.spec.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest' +import { snapshotJsonValue } from '@deepseek-ai/dsh-session' +import { snapshotCodeJsonValue } from '../src/worker-json.ts' + +describe('snapshotCodeJsonValue', () => { + it('matches the canonical scalar boundary', () => { + const unsupported = [undefined, 1n, Symbol('value'), () => 1] + for (const value of [null, false, 'text', 1.25, -0, Number.NaN, Number.POSITIVE_INFINITY, ...unsupported]) { + expect(snapshotCodeJsonValue(value)).toEqual(snapshotJsonValue(value)) + } + }) + + it('detaches dense arrays and plain or null-prototype records', () => { + const shared = { value: 1 } + const nullPrototype = Object.assign(Object.create(null) as Record, { shared }) + const source = { list: [nullPrototype, shared], alias: shared } + + const snapshot = snapshotCodeJsonValue(source) as Record + shared.value = 2 + + expect(snapshot).toEqual({ list: [{ shared: { value: 1 } }, { value: 1 }], alias: { value: 1 } }) + expect(snapshot).not.toBe(source) + expect((snapshot.list as unknown[])[0]).not.toBe(nullPrototype) + expect(snapshot.alias).not.toBe(shared) + }) + + it('reads each accepted slot once and preserves a literal __proto__ key', () => { + let objectReads = 0 + let arrayReads = 0 + const source = Object.create(null) as Record + Object.defineProperty(source, '__proto__', { + enumerable: true, + get: () => { + objectReads += 1 + return { safe: true } + }, + }) + const array = new Array(1) + Object.defineProperty(array, 0, { + enumerable: true, + get: () => { + arrayReads += 1 + return arrayReads === 1 ? source : undefined + }, + }) + + const snapshot = snapshotCodeJsonValue(array) as Record[] + + expect(objectReads).toBe(1) + expect(arrayReads).toBe(1) + expect(Object.getPrototypeOf(snapshot[0])).toBe(Object.prototype) + expect(Object.hasOwn(snapshot[0]!, '__proto__')).toBe(true) + expect(snapshot[0]?.['__proto__']).toEqual({ safe: true }) + }) + + it('rejects exotic containers, sparse arrays, cycles, and invalid children', () => { + class ExoticObject { + readonly value = 1 + } + class ExoticArray extends Array {} + const cyclic: Record = {} + cyclic.self = cyclic + + for (const value of [ + new ExoticObject(), + new Map([['value', 1]]), + new ExoticArray(1), + new Array(1), + cyclic, + [undefined], + { value: undefined }, + ]) { + expect(snapshotCodeJsonValue(value)).toBeUndefined() + } + }) + + it('propagates a throwing getter and releases its recursion guard', () => { + const failure = new Error('getter failed') + const source = Object.defineProperty({}, 'value', { + enumerable: true, + get: () => { throw failure }, + }) + + expect(() => snapshotCodeJsonValue(source)).toThrow(failure) + expect(snapshotCodeJsonValue({ after: true })).toEqual({ after: true }) + }) +})