@deepseek-ai/dsh-ptc-runtime-node 0.2.2-rc.1 → 0.2.2-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +19 -16
- package/README.md +36 -10
- package/README.zh.md +36 -10
- package/lib/index.js +102 -63
- package/lib/persistent-process.js +528 -112
- package/lib/process.js +523 -109
- package/lib/types/bindings.d.ts.map +1 -0
- package/lib/types/bindings.js.map +1 -0
- package/lib/types/bootstrap.d.ts.map +1 -0
- package/lib/types/bootstrap.js.map +1 -0
- package/lib/types/config.d.ts +2 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/configuration.d.ts.map +1 -0
- package/lib/types/configuration.js.map +1 -0
- package/lib/types/environment.d.ts +3 -2
- package/lib/types/environment.d.ts.map +1 -0
- package/lib/types/environment.js.map +1 -0
- package/lib/types/evaluators/async-function.d.ts +3 -3
- package/lib/types/evaluators/async-function.d.ts.map +1 -0
- package/lib/types/evaluators/async-function.js.map +1 -0
- package/lib/types/evaluators/index.d.ts +3 -2
- package/lib/types/evaluators/index.d.ts.map +1 -0
- package/lib/types/evaluators/index.js.map +1 -0
- package/lib/types/evaluators/repl.d.ts +3 -3
- package/lib/types/evaluators/repl.d.ts.map +1 -0
- package/lib/types/evaluators/repl.js.map +1 -0
- package/lib/types/evaluators/types.d.ts +44 -0
- package/lib/types/evaluators/types.d.ts.map +1 -0
- package/lib/types/evaluators/types.js.map +1 -0
- package/lib/types/evaluators/vm-script-await.d.ts.map +1 -0
- package/lib/types/evaluators/vm-script-await.js.map +1 -0
- package/lib/types/evaluators/vm-script.d.ts +3 -2
- package/lib/types/evaluators/vm-script.d.ts.map +1 -0
- package/lib/types/evaluators/vm-script.js.map +1 -0
- package/lib/types/execution.d.ts.map +1 -0
- package/lib/types/execution.js.map +1 -0
- package/lib/types/imports/evaluation-ended.d.ts +7 -0
- package/lib/types/imports/evaluation-ended.d.ts.map +1 -0
- package/lib/types/imports/evaluation-ended.js.map +1 -0
- package/lib/types/imports/module-hooks.d.ts +37 -0
- package/lib/types/imports/module-hooks.d.ts.map +1 -0
- package/lib/types/imports/module-hooks.js.map +1 -0
- package/lib/types/imports/vm-modules.d.ts +35 -0
- package/lib/types/imports/vm-modules.d.ts.map +1 -0
- package/lib/types/imports/vm-modules.js.map +1 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/json-wire.d.ts.map +1 -0
- package/lib/types/json-wire.js.map +1 -0
- package/lib/types/launch.d.ts +1 -2
- package/lib/types/launch.d.ts.map +1 -0
- package/lib/types/launch.js.map +1 -0
- package/lib/types/output-json.d.ts.map +1 -0
- package/lib/types/output-json.js.map +1 -0
- package/lib/types/output-ledger.d.ts.map +1 -0
- package/lib/types/output-ledger.js.map +1 -0
- package/lib/types/output-stream.d.ts.map +1 -0
- package/lib/types/output-stream.js.map +1 -0
- package/lib/types/persistent-process-entry.d.ts.map +1 -0
- package/lib/types/persistent-process-entry.js.map +1 -0
- package/lib/types/persistent-process.d.ts +6 -2
- package/lib/types/persistent-process.d.ts.map +1 -0
- package/lib/types/persistent-process.js.map +1 -0
- package/lib/types/policy-processes.d.ts.map +1 -0
- package/lib/types/policy-processes.js.map +1 -0
- package/lib/types/process-entry.d.ts.map +1 -0
- package/lib/types/process-entry.js.map +1 -0
- package/lib/types/process.d.ts +4 -2
- package/lib/types/process.d.ts.map +1 -0
- package/lib/types/process.js.map +1 -0
- package/lib/types/protocol.d.ts +10 -3
- package/lib/types/protocol.d.ts.map +1 -0
- package/lib/types/protocol.js.map +1 -0
- package/lib/types/rpc.d.ts.map +1 -0
- package/lib/types/rpc.js.map +1 -0
- package/lib/types/worker.d.ts +5 -3
- package/lib/types/worker.d.ts.map +1 -0
- package/lib/types/worker.js.map +1 -0
- package/package.json +24 -21
- package/src/bindings.ts +66 -0
- package/src/bootstrap.ts +286 -0
- package/src/config.ts +68 -0
- package/src/configuration.ts +19 -0
- package/src/environment.ts +19 -0
- package/src/evaluators/async-function.ts +42 -0
- package/src/evaluators/index.ts +25 -0
- package/src/evaluators/repl.ts +46 -0
- package/src/evaluators/types.ts +64 -0
- package/src/evaluators/vm-script-await.ts +290 -0
- package/src/evaluators/vm-script.ts +83 -0
- package/src/execution.ts +171 -0
- package/src/imports/evaluation-ended.ts +11 -0
- package/src/imports/module-hooks.ts +125 -0
- package/src/imports/vm-modules.ts +233 -0
- package/src/index.ts +104 -0
- package/src/json-wire.ts +420 -0
- package/src/launch.ts +71 -0
- package/src/output-json.ts +179 -0
- package/src/output-ledger.ts +66 -0
- package/src/output-stream.ts +50 -0
- package/src/persistent-process-entry.ts +5 -0
- package/src/persistent-process.ts +22 -0
- package/src/policy-processes.ts +79 -0
- package/src/process-entry.ts +5 -0
- package/src/process.ts +167 -0
- package/src/protocol.ts +89 -0
- package/src/rpc.ts +88 -0
- package/src/worker.ts +381 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Combined byte accounting for retained program output. */
|
|
2
|
+
import type { PtcJsonValue, PtcRunFailure, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime'
|
|
3
|
+
import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from './output-json.ts'
|
|
4
|
+
|
|
5
|
+
/** One run's combined outer-output ledger; binding values never enter it. */
|
|
6
|
+
export class OutputLedger {
|
|
7
|
+
private bytes = 2 // JSON serialization of the empty logs array: []
|
|
8
|
+
private entries = 0
|
|
9
|
+
|
|
10
|
+
constructor(private readonly maxBytes: number, private readonly overflowMessage?: string) {}
|
|
11
|
+
|
|
12
|
+
/** Admit one exact log entry, or report that the hard cap was crossed. */
|
|
13
|
+
admit(text: string, sink: string[]): boolean {
|
|
14
|
+
const separatorBytes = this.entries > 0 ? 1 : 0
|
|
15
|
+
const stringBytes = jsonStringBytesUpTo(text, this.maxBytes - this.bytes - separatorBytes)
|
|
16
|
+
if (stringBytes === undefined) return false
|
|
17
|
+
this.bytes += stringBytes + separatorBytes
|
|
18
|
+
this.entries += 1
|
|
19
|
+
sink.push(text)
|
|
20
|
+
return true
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Finalize a successful absent-or-JSON completion against the combined cap. */
|
|
24
|
+
success(logs: string[], value?: PtcJsonValue): PtcRunResult {
|
|
25
|
+
if (value !== undefined && jsonValueBytesUpTo(value, this.maxBytes - this.bytes) === undefined) return this.limit(logs)
|
|
26
|
+
return { logs, ...value !== undefined ? { value } : {} }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Finalize a failure diagnostic, with output-limit taking precedence when combined bytes exceed the cap. */
|
|
30
|
+
failure(logs: string[], error: PtcRunFailure): PtcRunResult {
|
|
31
|
+
if (jsonStringBytesUpTo(error.message, this.maxBytes - this.bytes) === undefined) return this.limit(logs)
|
|
32
|
+
return { logs, error }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Build the explicit output-limit failure while retaining a fitting prefix of the final log. */
|
|
36
|
+
limit(logs: string[]): PtcRunResult {
|
|
37
|
+
const fullMessage = this.overflowMessage ?? `outer output exceeded ${this.maxBytes} bytes`
|
|
38
|
+
// The fixed diagnostic is ASCII, so every character is one byte plus the quotes.
|
|
39
|
+
const messageBytes = fullMessage.length + 2
|
|
40
|
+
const retained: string[] = []
|
|
41
|
+
let retainedBytes = 2
|
|
42
|
+
const logBudget = this.maxBytes - messageBytes
|
|
43
|
+
for (const text of logs) {
|
|
44
|
+
const separatorBytes = retained.length > 0 ? 1 : 0
|
|
45
|
+
const availableBytes = logBudget - retainedBytes - separatorBytes
|
|
46
|
+
const stringBytes = jsonStringBytesUpTo(text, availableBytes)
|
|
47
|
+
if (stringBytes !== undefined) {
|
|
48
|
+
retained.push(text)
|
|
49
|
+
retainedBytes += stringBytes + separatorBytes
|
|
50
|
+
continue
|
|
51
|
+
}
|
|
52
|
+
const prefix = truncateJsonStringBytes(text, availableBytes)
|
|
53
|
+
if (prefix.length > 0) {
|
|
54
|
+
const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes)
|
|
55
|
+
/* v8 ignore next -- truncateJsonStringBytes guarantees its returned prefix fits the same budget. */
|
|
56
|
+
if (prefixBytes === undefined) throw new Error('output ledger produced an oversized log prefix')
|
|
57
|
+
retained.push(prefix)
|
|
58
|
+
retainedBytes += prefixBytes + separatorBytes
|
|
59
|
+
}
|
|
60
|
+
break
|
|
61
|
+
}
|
|
62
|
+
const availableMessageBytes = this.maxBytes - retainedBytes
|
|
63
|
+
const message = truncateJsonStringBytes(fullMessage, availableMessageBytes)
|
|
64
|
+
return { logs: retained, error: { kind: 'output-limit', message } }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Bounded drainage for raw process output after managed execution ends. */
|
|
2
|
+
import type { Readable } from 'node:stream'
|
|
3
|
+
import type { SubprocessHandle } from '@deepseek-ai/dsh-subprocess'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Wait for queued bytes without letting an inherited descriptor retain a run forever.
|
|
7
|
+
* @param stream - Caller-owned raw process output, when provided.
|
|
8
|
+
* @param graceMs - Maximum wait after managed process termination.
|
|
9
|
+
* @returns Whether the complete stream ended without a transport error.
|
|
10
|
+
*/
|
|
11
|
+
export function drainOutput(stream: Readable | undefined, graceMs: number): Promise<boolean> {
|
|
12
|
+
if (stream === undefined || stream.readableEnded) return Promise.resolve(true)
|
|
13
|
+
if (stream.destroyed) return Promise.resolve(false)
|
|
14
|
+
return new Promise((resolve) => {
|
|
15
|
+
const finish = (complete: boolean): void => {
|
|
16
|
+
clearTimeout(timer)
|
|
17
|
+
stream.off('end', onEnd)
|
|
18
|
+
stream.off('close', onClose)
|
|
19
|
+
stream.off('error', onError)
|
|
20
|
+
resolve(complete)
|
|
21
|
+
}
|
|
22
|
+
const onEnd = (): void => { finish(true) }
|
|
23
|
+
const onClose = (): void => { finish(false) }
|
|
24
|
+
const onError = (): void => { finish(false) }
|
|
25
|
+
const timer = setTimeout(() => { finish(false) }, graceMs)
|
|
26
|
+
stream.once('end', onEnd)
|
|
27
|
+
stream.once('close', onClose)
|
|
28
|
+
stream.once('error', onError)
|
|
29
|
+
})
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Terminate a managed process and drain its pipes, including failures before output listeners attach.
|
|
34
|
+
* @param handle - Process and streams owned by the runtime.
|
|
35
|
+
* @param graceMs - Maximum pipe-drain wait after managed exit.
|
|
36
|
+
* @returns Whether both output streams ended cleanly.
|
|
37
|
+
*/
|
|
38
|
+
export async function terminateProcess(handle: SubprocessHandle, graceMs: number): Promise<boolean> {
|
|
39
|
+
try {
|
|
40
|
+
handle.terminate()
|
|
41
|
+
handle.stdout?.resume()
|
|
42
|
+
handle.stderr?.resume()
|
|
43
|
+
await Promise.all([handle.done.catch(() => {}), handle.waitForExit()])
|
|
44
|
+
const drained = await Promise.all([drainOutput(handle.stdout, graceMs), drainOutput(handle.stderr, graceMs)])
|
|
45
|
+
return !drained.includes(false)
|
|
46
|
+
} finally {
|
|
47
|
+
handle.stdout?.destroy()
|
|
48
|
+
handle.stderr?.destroy()
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Private built entry for retained Node evaluations. */
|
|
2
|
+
import { openInheritedControlChannel } from '@deepseek-ai/dsh-subprocess/control'
|
|
3
|
+
import { runPersistentMain } from './persistent-process.ts'
|
|
4
|
+
|
|
5
|
+
void runPersistentMain(openInheritedControlChannel(), Number(process.argv[2]), process)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Existing retained bootstrap entry delegates to the shared Node evaluation loop. */
|
|
2
|
+
import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime'
|
|
3
|
+
import type { Duplex } from 'node:stream'
|
|
4
|
+
import { runNodeMain } from './process.ts'
|
|
5
|
+
import type { ProgramProcess } from './process.ts'
|
|
6
|
+
import type { ProgramImportHandler } from './evaluators/types.ts'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Serve evaluations through the installed retained-bootstrap entry.
|
|
10
|
+
* @param stream - Inherited private control endpoint.
|
|
11
|
+
* @param maxMessageBytes - Maximum control frame and queued output bytes.
|
|
12
|
+
* @param processState - Native child process; structural test doubles do not replace Node's globals or built-in exports.
|
|
13
|
+
* @param format - Default syntax for hosts that omit it from program data.
|
|
14
|
+
* @param importHandler - Runner-local import decisions; omission retains native loading.
|
|
15
|
+
* @returns After control closure and evaluator cleanup.
|
|
16
|
+
*/
|
|
17
|
+
export function runPersistentMain(
|
|
18
|
+
stream: Duplex, maxMessageBytes: number, processState: ProgramProcess, format: PtcProgramFormat = 'repl',
|
|
19
|
+
importHandler?: ProgramImportHandler,
|
|
20
|
+
): Promise<void> {
|
|
21
|
+
return runNodeMain(stream, maxMessageBytes, processState, format, importHandler)
|
|
22
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** Node PTC process invalidation after a committed Session file-policy change. */
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
3
|
+
import type { SessionId } from '@deepseek-ai/dsh-session'
|
|
4
|
+
import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
|
|
5
|
+
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
|
6
|
+
|
|
7
|
+
interface Process {
|
|
8
|
+
sessionId: SessionId
|
|
9
|
+
mode: SandboxMode
|
|
10
|
+
release: () => Promise<void>
|
|
11
|
+
invalidated: boolean
|
|
12
|
+
cleanup?: Promise<void>
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Owns asynchronous process cleanup without delaying permission setters. */
|
|
16
|
+
export class PolicyProcesses {
|
|
17
|
+
private readonly processes = new Set<Process>()
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Begin cleanup on policy changes, even when no subsequent program runs.
|
|
21
|
+
* @param ctx - Node provider lifecycle and Session services.
|
|
22
|
+
*/
|
|
23
|
+
constructor(private readonly ctx: Context) {
|
|
24
|
+
ctx.on('session/event', (session, event) => {
|
|
25
|
+
if (event.type !== 'sandbox/mode') return
|
|
26
|
+
for (const process of this.processes) {
|
|
27
|
+
if (process.sessionId !== session.id || process.mode === event.data.mode) continue
|
|
28
|
+
process.invalidated = true
|
|
29
|
+
void this.release(process).catch((error: unknown) => { ctx.logger.warn(error) })
|
|
30
|
+
}
|
|
31
|
+
}, { global: true })
|
|
32
|
+
ctx.effect(() => async () => {
|
|
33
|
+
await this.settle([...this.processes])
|
|
34
|
+
}, 'Node PTC policy cleanup')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Track an admitted call or retained process until its owner confirms cleanup.
|
|
39
|
+
* @param policy - Resolved process policy, including an optional Session identity.
|
|
40
|
+
* @param release - Idempotent cancellation and awaited cleanup.
|
|
41
|
+
* @returns Removal after successful process cleanup.
|
|
42
|
+
*/
|
|
43
|
+
register(policy: SandboxExecutionPolicy, release: () => Promise<void>): () => void {
|
|
44
|
+
if (policy.sessionId === undefined) return () => {}
|
|
45
|
+
const session = this.ctx.get('sessions')?.get(policy.sessionId)
|
|
46
|
+
const process: Process = {
|
|
47
|
+
sessionId: policy.sessionId,
|
|
48
|
+
mode: session === undefined ? policy.mode : this.ctx.sandboxPolicy.resolve({ session }).mode,
|
|
49
|
+
release,
|
|
50
|
+
invalidated: false,
|
|
51
|
+
}
|
|
52
|
+
this.processes.add(process)
|
|
53
|
+
return () => { this.processes.delete(process) }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Wait for invalidated processes before admitting another program.
|
|
58
|
+
* @param sessionId - Session carried by the resolved policy.
|
|
59
|
+
* @returns Completion after prior cleanup; a failure rejects and remains retryable.
|
|
60
|
+
*/
|
|
61
|
+
async wait(sessionId: SessionId | undefined): Promise<void> {
|
|
62
|
+
await this.settle([...this.processes].filter(process => process.sessionId === sessionId && process.invalidated))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private release(process: Process): Promise<void> {
|
|
66
|
+
if (process.cleanup !== undefined) return process.cleanup
|
|
67
|
+
process.cleanup = process.release().then(() => { this.processes.delete(process) }, (error: unknown) => {
|
|
68
|
+
delete process.cleanup
|
|
69
|
+
throw error
|
|
70
|
+
})
|
|
71
|
+
return process.cleanup
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private async settle(processes: Process[]): Promise<void> {
|
|
75
|
+
const results = await Promise.allSettled(processes.map(process => this.release(process)))
|
|
76
|
+
const failed = results.find(result => result.status === 'rejected')
|
|
77
|
+
if (failed?.status === 'rejected') throw failed.reason
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Private built Node-runtime child entry; source execution calls runNodeMain directly. */
|
|
2
|
+
import { openInheritedControlChannel } from '@deepseek-ai/dsh-subprocess/control'
|
|
3
|
+
import { runNodeMain } from './process.ts'
|
|
4
|
+
|
|
5
|
+
void runNodeMain(openInheritedControlChannel(), Number(process.argv[2]), process)
|
package/src/process.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/** Node child evaluation over typed RPC; the host owns process lifetime. */
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
3
|
+
import type { Duplex } from 'node:stream'
|
|
4
|
+
import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime'
|
|
5
|
+
import { createProcessRpc } from './rpc.ts'
|
|
6
|
+
import { captureStreamWrites, LogBuffer, makeConsoleShim, makeBindingErrorClass, makeNamespaces, prepareCompletion, prepareException } from './bootstrap.ts'
|
|
7
|
+
import type { BindingErrorConstructor, PatchableStream } from './bootstrap.ts'
|
|
8
|
+
import { clearProgramEnvironment } from './environment.ts'
|
|
9
|
+
import { createProgramEvaluator } from './evaluators/index.ts'
|
|
10
|
+
import { ImportEvaluationEndedError } from './imports/evaluation-ended.ts'
|
|
11
|
+
import type { ProgramEvaluator, ProgramImportHandler, ProgramImportResult } from './evaluators/types.ts'
|
|
12
|
+
import { PROGRAM_PROTOCOL_VERSION, type ProgramResult, type HostMethods, type ProgramMethods } from './protocol.ts'
|
|
13
|
+
|
|
14
|
+
/** Process-owned environment, output and directory control consumed by the child. */
|
|
15
|
+
export interface ProgramProcess {
|
|
16
|
+
env: NodeJS.ProcessEnv
|
|
17
|
+
stdout: PatchableStream
|
|
18
|
+
stderr: PatchableStream
|
|
19
|
+
exitCode?: string | number | null | undefined
|
|
20
|
+
chdir(directory: string): void
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Evaluation {
|
|
24
|
+
logs: LogBuffer
|
|
25
|
+
maxOutputBytes: number
|
|
26
|
+
active: boolean
|
|
27
|
+
reusable: boolean
|
|
28
|
+
revoked: boolean
|
|
29
|
+
finish(result: ProgramResult): void
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Serve sequential evaluations until the host closes the control channel.
|
|
34
|
+
* @param stream - Inherited, already-adopted control endpoint.
|
|
35
|
+
* @param maxMessageBytes - Maximum control message and queued output bytes.
|
|
36
|
+
* @param processState - Native child process; structural test doubles do not replace Node's globals or built-in exports.
|
|
37
|
+
* @param defaultFormat - Syntax used by installed bootstraps when the host omits it.
|
|
38
|
+
* @param importHandler - Runner-local import decisions; omission retains native loading.
|
|
39
|
+
* @returns After control closure and evaluator cleanup.
|
|
40
|
+
*/
|
|
41
|
+
export async function runNodeMain(
|
|
42
|
+
stream: Duplex, maxMessageBytes: number, processState: ProgramProcess, defaultFormat: PtcProgramFormat = 'function-body',
|
|
43
|
+
importHandler?: ProgramImportHandler,
|
|
44
|
+
): Promise<void> {
|
|
45
|
+
if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes <= 0) throw new Error('invalid control message limit')
|
|
46
|
+
clearProgramEnvironment(processState)
|
|
47
|
+
const context = new AsyncLocalStorage<Evaluation>()
|
|
48
|
+
const closed = Promise.withResolvers<void>()
|
|
49
|
+
const errors = new Map<string, { name: string; memberNameProperty: string; constructor: BindingErrorConstructor }>()
|
|
50
|
+
const errorLookup = { get: (name: string) => errors.get(name)?.constructor }
|
|
51
|
+
const unsettled = new Promise<never>(() => {})
|
|
52
|
+
let evaluator: ProgramEvaluator | undefined
|
|
53
|
+
let current: Evaluation | undefined
|
|
54
|
+
const acceptsCalls = (evaluation: Evaluation): boolean => evaluation.active && !evaluation.revoked
|
|
55
|
+
const host: Pick<HostMethods, 'invoke'> = {
|
|
56
|
+
invoke: async (global, name, args) => {
|
|
57
|
+
const evaluation = context.getStore()
|
|
58
|
+
if (evaluation && !evaluation.active && !evaluation.reusable) return unsettled
|
|
59
|
+
if (!evaluation || !acceptsCalls(evaluation)) throw new Error('PTC evaluation ended')
|
|
60
|
+
let value
|
|
61
|
+
try { value = await connection.invoke(global, name, args) } catch (error) {
|
|
62
|
+
// Closing a temporary process must not resume an unawaited call with a rejection.
|
|
63
|
+
if (!evaluation.active && !evaluation.reusable) return unsettled
|
|
64
|
+
throw error
|
|
65
|
+
}
|
|
66
|
+
if (!evaluation.active && !evaluation.reusable) return unsettled
|
|
67
|
+
if (!acceptsCalls(evaluation)) throw new Error('PTC evaluation canceled')
|
|
68
|
+
return value
|
|
69
|
+
},
|
|
70
|
+
}
|
|
71
|
+
const logSink = { push(text: string): void {
|
|
72
|
+
const evaluation = context.getStore()
|
|
73
|
+
if (evaluation && acceptsCalls(evaluation)) evaluation.logs.push(text)
|
|
74
|
+
} }
|
|
75
|
+
captureStreamWrites(logSink, processState.stdout)
|
|
76
|
+
captureStreamWrites(logSink, processState.stderr)
|
|
77
|
+
const connection = createProcessRpc<HostMethods, ProgramMethods>(stream, maxMessageBytes, {
|
|
78
|
+
async run(cwd, data) {
|
|
79
|
+
if (current?.active) throw new Error('overlapping PTC evaluation')
|
|
80
|
+
const completion = Promise.withResolvers<ProgramResult>()
|
|
81
|
+
const logs = new LogBuffer(data.maxOutputBytes,
|
|
82
|
+
(text) => { void connection.log(text) }, () => { void connection.outputLimit() })
|
|
83
|
+
const format = data.programFormat ?? defaultFormat
|
|
84
|
+
const evaluation: Evaluation = {
|
|
85
|
+
logs, maxOutputBytes: data.maxOutputBytes, active: true, reusable: data.retainsState, revoked: false,
|
|
86
|
+
finish(result) {
|
|
87
|
+
evaluation.active = false
|
|
88
|
+
if (evaluation.reusable) {
|
|
89
|
+
void connection.$rejectPendingCalls(({ reject }) => { reject(new Error('PTC evaluation ended')) })
|
|
90
|
+
}
|
|
91
|
+
completion.resolve(result)
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
current = evaluation
|
|
95
|
+
context.run(evaluation, () => {
|
|
96
|
+
try {
|
|
97
|
+
processState.chdir(cwd)
|
|
98
|
+
if (evaluator === undefined) {
|
|
99
|
+
evaluator = createProgramEvaluator(format, (error) => {
|
|
100
|
+
const active = context.getStore()
|
|
101
|
+
if (active?.active && error) active.finish(prepareException(error, active.logs.remainingOutputBytes(), active.maxOutputBytes))
|
|
102
|
+
}, importHandler === undefined ? undefined : (request) => {
|
|
103
|
+
const active = context.getStore()
|
|
104
|
+
if (!active?.active) throw new ImportEvaluationEndedError(active?.reusable ?? true)
|
|
105
|
+
const result = importHandler(request)
|
|
106
|
+
const checkActive = (decision: ProgramImportResult): ProgramImportResult => {
|
|
107
|
+
if (!active.active) throw new ImportEvaluationEndedError(active.reusable, true)
|
|
108
|
+
return decision
|
|
109
|
+
}
|
|
110
|
+
return 'then' in result ? result.then(checkActive, (error: unknown) => {
|
|
111
|
+
if (!active.active) throw new ImportEvaluationEndedError(active.reusable, true)
|
|
112
|
+
throw error
|
|
113
|
+
}) : checkActive(result)
|
|
114
|
+
})
|
|
115
|
+
evaluator.globals.console = makeConsoleShim(logSink)
|
|
116
|
+
// Context access must not reserve a function-body parameter named process.
|
|
117
|
+
Object.defineProperty(evaluator.globals, 'process', { configurable: true, writable: true, value: processState })
|
|
118
|
+
}
|
|
119
|
+
for (const namespace of data.namespaces) {
|
|
120
|
+
const descriptor = namespace.errorClass
|
|
121
|
+
if (!descriptor) { errors.delete(namespace.global); continue }
|
|
122
|
+
const previous = errors.get(namespace.global)
|
|
123
|
+
if (previous?.name === descriptor.name && previous.memberNameProperty === descriptor.memberNameProperty) continue
|
|
124
|
+
const constructor = makeBindingErrorClass(descriptor)
|
|
125
|
+
errors.set(namespace.global, { name: descriptor.name, memberNameProperty: descriptor.memberNameProperty, constructor })
|
|
126
|
+
}
|
|
127
|
+
const namespaces = makeNamespaces(data, host, errorLookup)
|
|
128
|
+
for (const [index, namespace] of data.namespaces.entries()) {
|
|
129
|
+
Object.defineProperty(evaluator.globals, namespace.global, { configurable: true, enumerable: true, value: namespaces[index] })
|
|
130
|
+
if (namespace.errorClass) {
|
|
131
|
+
Object.defineProperty(evaluator.globals, namespace.errorClass.name, {
|
|
132
|
+
configurable: true, enumerable: true, value: errorLookup.get(namespace.global),
|
|
133
|
+
})
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
evaluator.evaluate(data.code, (result) => {
|
|
137
|
+
if (!evaluation.active) return
|
|
138
|
+
if (evaluation.revoked) { evaluation.finish({}); return }
|
|
139
|
+
evaluation.finish(result.ok ? prepareCompletion(result.value, logs.remainingOutputBytes(), data.maxOutputBytes)
|
|
140
|
+
: prepareException(result.error, logs.remainingOutputBytes(), data.maxOutputBytes))
|
|
141
|
+
})
|
|
142
|
+
} catch (error: unknown) {
|
|
143
|
+
evaluation.finish(prepareException(error, logs.remainingOutputBytes(), data.maxOutputBytes))
|
|
144
|
+
}
|
|
145
|
+
})
|
|
146
|
+
return await completion.promise
|
|
147
|
+
},
|
|
148
|
+
revoke() {
|
|
149
|
+
const evaluation = current
|
|
150
|
+
if (!evaluation?.active) return
|
|
151
|
+
evaluation.revoked = true
|
|
152
|
+
void connection.$rejectPendingCalls(({ reject }) => { reject(new Error('PTC evaluation canceled')) })
|
|
153
|
+
},
|
|
154
|
+
}, ['ready', 'log', 'outputLimit'], (_error, kind) => {
|
|
155
|
+
if (current?.active || kind === 'protocol') processState.exitCode = 1
|
|
156
|
+
if (current) current.active = false
|
|
157
|
+
closed.resolve()
|
|
158
|
+
})
|
|
159
|
+
try {
|
|
160
|
+
await connection.ready(PROGRAM_PROTOCOL_VERSION)
|
|
161
|
+
await closed.promise
|
|
162
|
+
} finally {
|
|
163
|
+
evaluator?.close()
|
|
164
|
+
connection.$close()
|
|
165
|
+
context.disable()
|
|
166
|
+
}
|
|
167
|
+
}
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/** Typed methods shared by the host and its co-shipped Node execution process, and validation of untrusted program results. */
|
|
2
|
+
import type { PtcProgramFormat, PtcJsonValue, PtcRunFailure } from '@deepseek-ai/dsh-ptc-runtime'
|
|
3
|
+
import { decodePtcJsonWire, type PtcJsonWire } from './json-wire.ts'
|
|
4
|
+
|
|
5
|
+
/** Wire revision required before the host dispatches program code. */
|
|
6
|
+
export const PROGRAM_PROTOCOL_VERSION = 2
|
|
7
|
+
|
|
8
|
+
/** Inputs for one program; host functions remain in the parent process. */
|
|
9
|
+
export interface ProgramBootData {
|
|
10
|
+
/** Type-stripped JavaScript source. */
|
|
11
|
+
code: string
|
|
12
|
+
/** Evaluation syntax; omitted uses the installed bootstrap's default. */
|
|
13
|
+
programFormat?: PtcProgramFormat
|
|
14
|
+
/** Whether the host will reuse this process after the evaluation. */
|
|
15
|
+
retainsState: boolean
|
|
16
|
+
/** Globals and callable names injected into the program. */
|
|
17
|
+
namespaces: {
|
|
18
|
+
global: string
|
|
19
|
+
names: string[]
|
|
20
|
+
errorClass?: { name: string; memberNameProperty: string }
|
|
21
|
+
}[]
|
|
22
|
+
/** Combined serialized log and completion budget. */
|
|
23
|
+
maxOutputBytes: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Program completion; logs are delivered separately before this result. */
|
|
27
|
+
export interface ProgramResult {
|
|
28
|
+
value?: PtcJsonWire
|
|
29
|
+
error?: { kind: 'exception' | 'invalid-output' | 'output-limit'; message: string }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Host operations for the current evaluation; one pipe delivers its messages before its result. */
|
|
33
|
+
export interface HostMethods {
|
|
34
|
+
/**
|
|
35
|
+
* Announce readiness before accepting an evaluation.
|
|
36
|
+
* @param version - Bootstrap wire revision, checked against the host.
|
|
37
|
+
*/
|
|
38
|
+
ready(version: number): void
|
|
39
|
+
/**
|
|
40
|
+
* Invoke a binding under its originating host execution context.
|
|
41
|
+
* @param global - Namespace global.
|
|
42
|
+
* @param name - Function name within the namespace.
|
|
43
|
+
* @param args - Flat lossless JSON arguments.
|
|
44
|
+
* @returns Flat lossless JSON result; binding failures and cancellation reject.
|
|
45
|
+
*/
|
|
46
|
+
invoke(global: string, name: string, args: PtcJsonWire): Promise<PtcJsonWire>
|
|
47
|
+
/**
|
|
48
|
+
* Admit captured output before completion or interruption.
|
|
49
|
+
* @param text - Captured text.
|
|
50
|
+
*/
|
|
51
|
+
log(text: string): void
|
|
52
|
+
/** Report exhausted program-side output accounting. */
|
|
53
|
+
outputLimit(): void
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Operations implemented by either the per-call child or retained REPL. */
|
|
57
|
+
export interface ProgramMethods {
|
|
58
|
+
/**
|
|
59
|
+
* Evaluate code with the supplied binding declarations and output budget.
|
|
60
|
+
* @param cwd - Execution-world working directory.
|
|
61
|
+
* @param data - Program and injected declarations.
|
|
62
|
+
* @returns Completion or a bounded program failure, after captured output is sent.
|
|
63
|
+
*/
|
|
64
|
+
run(cwd: string, data: ProgramBootData): Promise<ProgramResult>
|
|
65
|
+
/** Notify the program thread to revoke bindings and output; run() still owns completion. */
|
|
66
|
+
revoke(): void
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const record = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Decode a remote run result without trusting model-written control traffic.
|
|
73
|
+
* @param result - Untrusted result returned by the program process.
|
|
74
|
+
* @returns Decoded completion or failure; malformed envelopes throw a protocol error.
|
|
75
|
+
*/
|
|
76
|
+
export function readProgramResult(result: unknown): { value?: PtcJsonValue; error?: PtcRunFailure } {
|
|
77
|
+
if (!record(result)) throw new Error('invalid program result')
|
|
78
|
+
if (result.error !== undefined) {
|
|
79
|
+
const error = result.error
|
|
80
|
+
if (!record(error) || typeof error.message !== 'string'
|
|
81
|
+
|| (error.kind !== 'exception' && error.kind !== 'invalid-output' && error.kind !== 'output-limit')) {
|
|
82
|
+
throw new Error('invalid terminal error')
|
|
83
|
+
}
|
|
84
|
+
return { error: { kind: error.kind, message: error.message } }
|
|
85
|
+
}
|
|
86
|
+
if (result.value === undefined) return {}
|
|
87
|
+
const value = decodePtcJsonWire(result.value)
|
|
88
|
+
return value === undefined ? { error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } } : { value }
|
|
89
|
+
}
|
package/src/rpc.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** birpc over newline-delimited JSON on the bounded private process channel. */
|
|
2
|
+
import { Buffer } from 'node:buffer'
|
|
3
|
+
import type { Duplex } from 'node:stream'
|
|
4
|
+
import { createBirpc, type BirpcReturn } from 'birpc'
|
|
5
|
+
|
|
6
|
+
const stringify = JSON.stringify
|
|
7
|
+
const parse = JSON.parse
|
|
8
|
+
const messageOf = (error: unknown): string => error instanceof Error ? error.message : String(error)
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Connect typed methods over one control endpoint; execution owns all deadlines.
|
|
12
|
+
* @param stream - Owned control endpoint; `$close()` destroys it and rejects outstanding remote calls.
|
|
13
|
+
* @param maxMessageBytes - Maximum incoming JSON line and queued outgoing bytes.
|
|
14
|
+
* @param functions - Only these own methods may be called by the peer.
|
|
15
|
+
* @param eventNames - Remote methods sent as notifications without a response.
|
|
16
|
+
* @param failure - Receives the first I/O error, peer closure or malformed-message failure after the endpoint closes.
|
|
17
|
+
* @returns Typed remote calls and birpc lifetime controls.
|
|
18
|
+
*/
|
|
19
|
+
export function createProcessRpc<Remote extends object, Local extends object>(
|
|
20
|
+
stream: Duplex,
|
|
21
|
+
maxMessageBytes: number,
|
|
22
|
+
functions: Local,
|
|
23
|
+
eventNames: (keyof Remote)[],
|
|
24
|
+
failure: (error: Error, kind: 'io' | 'closed' | 'protocol') => void,
|
|
25
|
+
): BirpcReturn<Remote, Local> {
|
|
26
|
+
const fail = (error: unknown, kind: 'io' | 'closed' | 'protocol'): void => {
|
|
27
|
+
if (rpc.$closed) return
|
|
28
|
+
rpc.$close()
|
|
29
|
+
// Streams, the JSON parser and the line checks fail only with Error objects.
|
|
30
|
+
failure(error as Error, kind)
|
|
31
|
+
}
|
|
32
|
+
let receive: ((line: string) => void) | undefined
|
|
33
|
+
const rpc = createBirpc<Remote, Local>(functions, {
|
|
34
|
+
timeout: -1,
|
|
35
|
+
eventNames,
|
|
36
|
+
on: (listener) => { receive = listener },
|
|
37
|
+
off: () => { receive = undefined; stream.destroy() },
|
|
38
|
+
// JSON drops Error fields; the peer receives only the diagnostic.
|
|
39
|
+
serialize: (message: { e?: unknown }) => `${stringify(message.e === undefined ? message : { ...message, e: { message: messageOf(message.e) } })}\n`,
|
|
40
|
+
post: (line: string) => {
|
|
41
|
+
// A binding can settle after the endpoint closes; the Writable owns already queued bytes.
|
|
42
|
+
if (rpc.$closed) return
|
|
43
|
+
if (stream.writableLength + Buffer.byteLength(line) > maxMessageBytes) fail(new Error(`control output exceeds ${maxMessageBytes} queued bytes`), 'protocol')
|
|
44
|
+
else stream.write(line)
|
|
45
|
+
},
|
|
46
|
+
deserialize: (line: string) => {
|
|
47
|
+
// A line that parses after the leading-brace check is a JSON object.
|
|
48
|
+
const message = parse(line) as { e?: { message?: unknown } }
|
|
49
|
+
if (message.e) message.e = new Error(String(message.e.message))
|
|
50
|
+
return message
|
|
51
|
+
},
|
|
52
|
+
// Only own methods are callable, and none runs once the endpoint closes,
|
|
53
|
+
// including calls that arrived in the same chunk as the closing message.
|
|
54
|
+
resolver: (name, fn) => Object.hasOwn(functions, name)
|
|
55
|
+
? (...args: unknown[]) => rpc.$closed ? undefined : fn.apply(functions, args)
|
|
56
|
+
: undefined,
|
|
57
|
+
})
|
|
58
|
+
let parts: Buffer[] = []
|
|
59
|
+
let size = 0
|
|
60
|
+
const buffer = (part: Buffer): void => {
|
|
61
|
+
// Every message is a JSON object; another release's length-prefixed frame would otherwise wait for a newline.
|
|
62
|
+
if (size === 0 && part.length > 0 && part[0] !== 0x7b) throw new Error('control message is not a JSON object; the Node bootstrap may be from another release')
|
|
63
|
+
size += part.length
|
|
64
|
+
if (size > maxMessageBytes) throw new Error(`RPC message exceeds ${maxMessageBytes} bytes`)
|
|
65
|
+
parts.push(part)
|
|
66
|
+
}
|
|
67
|
+
stream.on('data', (chunk: Buffer) => {
|
|
68
|
+
try {
|
|
69
|
+
let start = 0
|
|
70
|
+
for (let end = chunk.indexOf(10); end !== -1; end = chunk.indexOf(10, start)) {
|
|
71
|
+
buffer(chunk.subarray(start, end))
|
|
72
|
+
const line = Buffer.concat(parts, size).toString('utf8')
|
|
73
|
+
parts = []
|
|
74
|
+
size = 0
|
|
75
|
+
start = end + 1
|
|
76
|
+
void Promise.resolve(receive?.(line)).catch((error: unknown) => { fail(error, 'protocol') })
|
|
77
|
+
}
|
|
78
|
+
buffer(chunk.subarray(start))
|
|
79
|
+
} catch (error: unknown) { fail(error, 'protocol') }
|
|
80
|
+
})
|
|
81
|
+
stream.on('end', () => {
|
|
82
|
+
if (size === 0) fail(new Error('control channel ended before the program settled'), 'closed')
|
|
83
|
+
else fail(new Error('incomplete RPC message'), 'protocol')
|
|
84
|
+
})
|
|
85
|
+
stream.on('error', (error: Error) => { fail(error, 'io') })
|
|
86
|
+
stream.on('close', () => { fail(new Error('control channel closed'), 'closed') })
|
|
87
|
+
return rpc
|
|
88
|
+
}
|