fix: keep source Code Mode worker self-contained

A direct runtime import of the session package made the unbuilt worker depend on sibling lib output. Use a parity-tested local JSON snapshotter and pin the isolated source closure with a real-worker test.
This commit is contained in:
Tianyi Cui
2026-07-21 05:19:40 +08:00
parent aca8162ef2
commit 1709b8cfee
5 changed files with 193 additions and 3 deletions
@@ -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.
@@ -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
}
@@ -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<object>()
const within = <T extends CodeJsonValue>(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<string, CodeJsonValue> = {}
for (const key of Object.keys(candidate)) {
const item = copy((candidate as Record<string, unknown>)[key])
if (item === undefined) return undefined
Object.defineProperty(result, key, {
value: item,
enumerable: true,
configurable: true,
writable: true,
})
}
return result
})
}
return copy(value)
}
@@ -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<unknown>((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 })
}
})
@@ -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<string, unknown>, { shared })
const source = { list: [nullPrototype, shared], alias: shared }
const snapshot = snapshotCodeJsonValue(source) as Record<string, unknown>
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<string, unknown>
Object.defineProperty(source, '__proto__', {
enumerable: true,
get: () => {
objectReads += 1
return { safe: true }
},
})
const array = new Array<unknown>(1)
Object.defineProperty(array, 0, {
enumerable: true,
get: () => {
arrayReads += 1
return arrayReads === 1 ? source : undefined
},
})
const snapshot = snapshotCodeJsonValue(array) as Record<string, unknown>[]
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<number> {}
const cyclic: Record<string, unknown> = {}
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 })
})
})