@deepseek-ai/dsh-ptc-runtime-node 0.2.2-alpha.3 → 0.2.2-rc.2
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 +27 -24
- 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
package/src/worker.ts
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/** Managed Node process shared by temporary and owner-retained evaluations. */
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
3
|
+
import { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import type { PtcRunSpec, PtcRunResult, PtcRunSandbox, PtcRunFailure, PtcBindingNamespace, PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime'
|
|
5
|
+
import { SandboxUnavailableError, classifyRunnerFailure, isRunnerSpawnFailure } from '@deepseek-ai/dsh-sandbox'
|
|
6
|
+
import type { ConfinedArgv, SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
|
|
7
|
+
import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess'
|
|
8
|
+
import type { PolicyProcesses } from './policy-processes.ts'
|
|
9
|
+
import type { ResolvedConfig } from './config.ts'
|
|
10
|
+
import type { ExecutionMode } from './execution.ts'
|
|
11
|
+
import { invokeBinding } from './bindings.ts'
|
|
12
|
+
import type { BirpcReturn } from 'birpc'
|
|
13
|
+
import { createProcessRpc } from './rpc.ts'
|
|
14
|
+
import { bootstrapArgs } from './launch.ts'
|
|
15
|
+
import { STARTUP_ENVIRONMENT_NAMES } from './environment.ts'
|
|
16
|
+
import { decodePtcJsonWire } from './json-wire.ts'
|
|
17
|
+
import { OutputLedger } from './output-ledger.ts'
|
|
18
|
+
import { drainOutput, terminateProcess } from './output-stream.ts'
|
|
19
|
+
import { readProgramResult, PROGRAM_PROTOCOL_VERSION, type ProgramBootData, type ProgramMethods, type HostMethods } from './protocol.ts'
|
|
20
|
+
|
|
21
|
+
const messageOf = (error: unknown): string => error instanceof Error ? error.message : String(error)
|
|
22
|
+
|
|
23
|
+
interface Evaluation {
|
|
24
|
+
settled: boolean
|
|
25
|
+
completion: Promise<ReturnType<typeof readProgramResult>> | undefined
|
|
26
|
+
data: ProgramBootData
|
|
27
|
+
spec: PtcRunSpec
|
|
28
|
+
bindings: Map<string, PtcBindingNamespace>
|
|
29
|
+
invoke: typeof invokeBinding
|
|
30
|
+
pending: number
|
|
31
|
+
pendingBytes: number
|
|
32
|
+
admit(text: string): void
|
|
33
|
+
finish(error?: PtcRunFailure, value?: PtcJsonValue, discard?: boolean): void
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** One managed process; all mutable program state belongs to this process alone. */
|
|
37
|
+
export class ProgramWorker {
|
|
38
|
+
private readonly unregister: (() => void) | undefined
|
|
39
|
+
private confined: ConfinedArgv | undefined
|
|
40
|
+
private handle?: SubprocessHandle
|
|
41
|
+
private channel?: BirpcReturn<ProgramMethods, HostMethods>
|
|
42
|
+
private active: Evaluation | undefined
|
|
43
|
+
/** Admission remains reserved until the result includes completed process cleanup. */
|
|
44
|
+
private running = false
|
|
45
|
+
private cleanupPending = false
|
|
46
|
+
private ready = false
|
|
47
|
+
private stderr = ''
|
|
48
|
+
private controlFailure: string | undefined
|
|
49
|
+
private termination: Promise<boolean> | undefined
|
|
50
|
+
private starting?: Promise<void>
|
|
51
|
+
private exitOutcome?: SubprocessOutcome
|
|
52
|
+
private readonly controller = new AbortController()
|
|
53
|
+
closed = false
|
|
54
|
+
|
|
55
|
+
/** Whether termination succeeded and this process no longer needs cleanup retries. */
|
|
56
|
+
get cleanupComplete(): boolean { return this.closed && !this.cleanupPending }
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Own one process under a fixed file policy.
|
|
60
|
+
* @param ctx - Provider execution services.
|
|
61
|
+
* @param config - Validated resource limits and launch selection.
|
|
62
|
+
* @param policy - Authority retained for the lifetime of this process.
|
|
63
|
+
* @param processes - Session policy invalidation and cleanup coordination.
|
|
64
|
+
* @param mode - Evaluator syntax and TypeScript erasure.
|
|
65
|
+
* @param retainsState - Whether this process belongs to an owner and survives completed evaluations.
|
|
66
|
+
*/
|
|
67
|
+
constructor(
|
|
68
|
+
private readonly ctx: Context, private readonly config: ResolvedConfig,
|
|
69
|
+
readonly policy: SandboxExecutionPolicy, processes: PolicyProcesses, private readonly mode: ExecutionMode,
|
|
70
|
+
private readonly retainsState: boolean,
|
|
71
|
+
) {
|
|
72
|
+
this.unregister = processes.register(policy, () => this.dispose())
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Reject reuse until the previous evaluation and required cleanup settle. */
|
|
76
|
+
assertIdle(): void {
|
|
77
|
+
if (this.running) throw new Error('persistent PTC does not accept concurrent runs for one state owner')
|
|
78
|
+
if (this.cleanupPending) throw new Error('persistent PTC environment cleanup is incomplete; release the owner before running another program')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Evaluate a program, retaining this process only for an enabled state owner.
|
|
83
|
+
* @param spec - Resolved program inputs and cancellation.
|
|
84
|
+
* @param bindings - Current host binding implementations.
|
|
85
|
+
* @returns Output after any required process cleanup.
|
|
86
|
+
*/
|
|
87
|
+
async run(spec: PtcRunSpec, bindings: Map<string, PtcBindingNamespace>): Promise<PtcRunResult> {
|
|
88
|
+
this.running = true
|
|
89
|
+
const sandbox: PtcRunSandbox = { mode: this.policy.mode, denied: false }
|
|
90
|
+
try {
|
|
91
|
+
const result = await this.evaluate(spec, bindings)
|
|
92
|
+
if (this.confined !== undefined) {
|
|
93
|
+
sandbox.enforcement = this.confined.enforcement
|
|
94
|
+
sandbox.denied ||= result.error?.kind !== 'sandbox-unavailable' && this.confined.denialSignatures.some(signature =>
|
|
95
|
+
result.error?.message.toLowerCase().includes(signature.toLowerCase()))
|
|
96
|
+
}
|
|
97
|
+
return { ...result, sandbox }
|
|
98
|
+
} finally { this.running = false }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
private output(): OutputLedger {
|
|
102
|
+
return new OutputLedger(this.config.maxOutputBytes, this.retainsState
|
|
103
|
+
? `retained variables were cleared; outer output exceeded ${this.config.maxOutputBytes} bytes` : undefined)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private message(message: string): string {
|
|
107
|
+
return this.retainsState ? `${message}; retained variables were cleared` : message
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
private async evaluate(spec: PtcRunSpec, bindings: Map<string, PtcBindingNamespace>): Promise<PtcRunResult> {
|
|
111
|
+
if (this.exitOutcome !== undefined) {
|
|
112
|
+
const output = this.output()
|
|
113
|
+
const failure: PtcRunFailure = spec.signal?.aborted
|
|
114
|
+
? { kind: 'abort', message: this.message('execution canceled') }
|
|
115
|
+
: { kind: 'worker-exit', message: this.message(this.exitMessage(this.exitOutcome)) }
|
|
116
|
+
try { await this.terminate() } catch (error: unknown) {
|
|
117
|
+
return output.failure([], { kind: 'worker-exit', message: `managed process cleanup failed: ${messageOf(error)}` })
|
|
118
|
+
}
|
|
119
|
+
return output.failure([], failure)
|
|
120
|
+
}
|
|
121
|
+
this.stderr = ''
|
|
122
|
+
const output = this.output()
|
|
123
|
+
const logs: string[] = []
|
|
124
|
+
let overflowed = false
|
|
125
|
+
const result = Promise.withResolvers<PtcRunResult>()
|
|
126
|
+
const timer = spec.timeoutMs === null ? undefined : setTimeout(() => {
|
|
127
|
+
const phase = evaluation.completion !== undefined ? 'during execution' : 'before code started'
|
|
128
|
+
const message = `execution timed out ${phase} (${spec.timeoutMs}ms)`
|
|
129
|
+
evaluation.finish({ kind: 'timeout', message }, undefined, evaluation.completion === undefined)
|
|
130
|
+
}, spec.timeoutMs)
|
|
131
|
+
const onAbort = (): void => {
|
|
132
|
+
evaluation.finish({ kind: 'abort', message: this.retainsState ? 'execution canceled' : messageOf(spec.signal?.reason) }, undefined, evaluation.completion === undefined)
|
|
133
|
+
}
|
|
134
|
+
const evaluation: Evaluation = {
|
|
135
|
+
settled: false,
|
|
136
|
+
completion: undefined,
|
|
137
|
+
data: {
|
|
138
|
+
code: '', programFormat: this.mode.format, retainsState: this.retainsState,
|
|
139
|
+
maxOutputBytes: this.config.maxOutputBytes,
|
|
140
|
+
namespaces: [...bindings.values()].map(binding => ({
|
|
141
|
+
global: binding.global, names: Object.keys(binding.functions), ...binding.errorClass ? { errorClass: binding.errorClass } : {},
|
|
142
|
+
})),
|
|
143
|
+
},
|
|
144
|
+
spec, bindings, invoke: AsyncLocalStorage.bind(invokeBinding), pending: 0, pendingBytes: 0,
|
|
145
|
+
admit: (text) => {
|
|
146
|
+
if (overflowed) return
|
|
147
|
+
if (!output.admit(text, logs)) {
|
|
148
|
+
overflowed = true
|
|
149
|
+
logs.push(text)
|
|
150
|
+
evaluation.finish({ kind: 'output-limit', message: 'output limit exceeded' }, undefined, true)
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
finish: (error, value, discard = false) => {
|
|
154
|
+
if (evaluation.settled) return
|
|
155
|
+
evaluation.settled = true
|
|
156
|
+
clearTimeout(timer)
|
|
157
|
+
spec.signal?.removeEventListener('abort', onAbort)
|
|
158
|
+
const complete = (): PtcRunResult => overflowed || error?.kind === 'output-limit' ? output.limit(logs)
|
|
159
|
+
: error ? output.failure(logs, error) : output.success(logs, value)
|
|
160
|
+
const outcome = complete()
|
|
161
|
+
const cleanup = async (): Promise<PtcRunResult> => {
|
|
162
|
+
const interrupted = error?.kind === 'timeout' || error?.kind === 'abort'
|
|
163
|
+
let preserved = this.retainsState && !discard && outcome.error?.kind !== 'output-limit'
|
|
164
|
+
if (preserved && interrupted) preserved = await this.interruptEvaluation(evaluation)
|
|
165
|
+
let drained = true
|
|
166
|
+
if (!preserved) drained = await this.terminate()
|
|
167
|
+
if (interrupted && this.retainsState && error) {
|
|
168
|
+
error = { ...error, message: `${error.message}; retained variables were ${preserved ? 'preserved' : 'cleared'}` }
|
|
169
|
+
}
|
|
170
|
+
const completed = complete()
|
|
171
|
+
// The final interruption diagnostic also consumes output budget.
|
|
172
|
+
if (completed.error?.kind === 'output-limit' && preserved) drained = await this.terminate()
|
|
173
|
+
return drained ? completed : output.failure(logs, { kind: 'worker-exit', message: 'managed process exited but its output did not drain cleanly' })
|
|
174
|
+
}
|
|
175
|
+
void cleanup().then((completed) => {
|
|
176
|
+
this.active = undefined
|
|
177
|
+
result.resolve(completed)
|
|
178
|
+
}, (failure: unknown) => {
|
|
179
|
+
this.active = undefined
|
|
180
|
+
result.resolve(output.failure(logs, { kind: 'worker-exit', message: `managed process cleanup failed: ${messageOf(failure)}` }))
|
|
181
|
+
})
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
this.active = evaluation
|
|
185
|
+
spec.signal?.addEventListener('abort', onAbort, { once: true })
|
|
186
|
+
if (spec.signal?.aborted) onAbort()
|
|
187
|
+
else {
|
|
188
|
+
try { evaluation.data.code = this.mode.stripTypes(spec.program) } catch (error: unknown) {
|
|
189
|
+
// A parse failure before startup has no process state or authority to retain.
|
|
190
|
+
evaluation.finish({ kind: 'exception', message: messageOf(error) }, undefined, !this.ready)
|
|
191
|
+
return await result.promise
|
|
192
|
+
}
|
|
193
|
+
if (this.ready) this.dispatch(evaluation)
|
|
194
|
+
else {
|
|
195
|
+
this.starting = this.start(spec.cwd)
|
|
196
|
+
void this.starting.catch((error: unknown) => { this.fail(error instanceof SandboxUnavailableError || (this.confined !== undefined && isRunnerSpawnFailure(error, this.confined.argv[0], spec.cwd)) ? 'sandbox-unavailable' : 'worker-exit', messageOf(error)) })
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return await result.promise
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** True confirms evaluation settlement with the process still available for reuse. */
|
|
203
|
+
private async interruptEvaluation(evaluation: Evaluation): Promise<boolean> {
|
|
204
|
+
const completion = evaluation.completion
|
|
205
|
+
if (!this.channel || this.channel.$closed || this.closed || !completion) return false
|
|
206
|
+
const deadline = Promise.withResolvers<never>()
|
|
207
|
+
const timer = setTimeout(() => { deadline.reject(new Error(`execution did not settle within ${this.config.stopGraceMs}ms`)) }, this.config.stopGraceMs)
|
|
208
|
+
const abort = (): void => { deadline.reject(new Error('environment disposed during interruption')) }
|
|
209
|
+
this.controller.signal.addEventListener('abort', abort, { once: true })
|
|
210
|
+
try {
|
|
211
|
+
await Promise.race([this.channel.revoke().then(() => completion), deadline.promise])
|
|
212
|
+
this.controller.signal.throwIfAborted()
|
|
213
|
+
return true
|
|
214
|
+
} catch (_error: unknown) {
|
|
215
|
+
// Only a validated run result confirms settlement.
|
|
216
|
+
return false
|
|
217
|
+
} finally {
|
|
218
|
+
clearTimeout(timer)
|
|
219
|
+
this.controller.signal.removeEventListener('abort', abort)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Cancel active work and await managed process termination and output drainage. */
|
|
224
|
+
async dispose(): Promise<void> {
|
|
225
|
+
this.active?.finish({ kind: 'abort', message: 'PTC environment disposed' }, undefined, true)
|
|
226
|
+
await this.terminate()
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Terminate the process; resolve to whether its output pipes drained cleanly. */
|
|
230
|
+
private terminate(): Promise<boolean> {
|
|
231
|
+
if (this.termination) return this.termination
|
|
232
|
+
this.closed = true
|
|
233
|
+
this.cleanupPending = true
|
|
234
|
+
this.controller.abort()
|
|
235
|
+
this.channel?.$close()
|
|
236
|
+
this.termination = (async () => {
|
|
237
|
+
await this.starting?.catch((_error: unknown) => {
|
|
238
|
+
// Evaluation reports startup failure; cleanup still owns any process already created.
|
|
239
|
+
})
|
|
240
|
+
const handle = this.handle
|
|
241
|
+
return handle === undefined || await terminateProcess(handle, this.config.graceMs)
|
|
242
|
+
})().then((drained) => {
|
|
243
|
+
this.unregister?.()
|
|
244
|
+
this.cleanupPending = false
|
|
245
|
+
if (!drained) this.ctx.logger.warn('Node process exited but its output did not drain cleanly')
|
|
246
|
+
return drained
|
|
247
|
+
}, (error: unknown) => { this.termination = undefined; throw error })
|
|
248
|
+
return this.termination
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private fail(kind: PtcRunFailure['kind'], message: string): void {
|
|
252
|
+
if (this.active) this.active.finish({ kind, message: this.message(message) }, undefined, true)
|
|
253
|
+
else {
|
|
254
|
+
if (!this.closed) this.ctx.logger.warn(message)
|
|
255
|
+
void this.terminate().catch((error: unknown) => { this.ctx.logger.warn(messageOf(error)) })
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private dispatch(evaluation: Evaluation): void {
|
|
260
|
+
const completion = this.channel?.run(evaluation.spec.cwd, evaluation.data).then(readProgramResult)
|
|
261
|
+
evaluation.completion = completion
|
|
262
|
+
void completion?.then(({ error, value }) => {
|
|
263
|
+
if (evaluation.settled) return
|
|
264
|
+
// Raw stdio can be queued beside the RPC result on separate pipes.
|
|
265
|
+
setImmediate(() => { evaluation.finish(error, value) })
|
|
266
|
+
}).catch((error: unknown) => {
|
|
267
|
+
if (this.active === evaluation && !evaluation.settled && !this.channel?.$closed) this.fail('protocol', messageOf(error))
|
|
268
|
+
})
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
private withControlFailure(message: string): string {
|
|
272
|
+
return this.controlFailure === undefined ? message : `${message}; control channel failed: ${this.controlFailure}`
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private exitMessage(outcome: SubprocessOutcome): string {
|
|
276
|
+
return this.withControlFailure(`Node process exited (${String(outcome.exitCode)}, signal ${String(outcome.signal)})${this.stderr ? `: ${this.stderr}` : ''}`)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
private async start(cwd: string): Promise<void> {
|
|
280
|
+
const executable = await this.ctx.subprocess.resolveExecutable(this.config.launch.executable, undefined, this.controller.signal)
|
|
281
|
+
if (this.closed) return
|
|
282
|
+
const packaged = this.config.launch.kind === 'embedded'
|
|
283
|
+
const heapFlag = `--max-old-space-size=${this.config.maxOldGenerationSizeMb}`
|
|
284
|
+
const argv = [executable, ...packaged ? [] : [heapFlag],
|
|
285
|
+
...bootstrapArgs(this.ctx.fs, this.config.launch, this.config.maxMessageBytes)]
|
|
286
|
+
const policy = this.policy
|
|
287
|
+
this.confined = policy.mode === 'danger-full-access' ? undefined : await this.ctx.sandbox.confine(argv, { ...policy, mode: policy.mode }, this.controller.signal)
|
|
288
|
+
// oxlint-disable-next-line typescript/no-unnecessary-condition -- Confinement may yield while disposal closes the process.
|
|
289
|
+
if (this.closed) return
|
|
290
|
+
const env: NodeJS.ProcessEnv = Object.fromEntries(Object.keys(process.env)
|
|
291
|
+
.filter(key => !STARTUP_ENVIRONMENT_NAMES.has(key.toUpperCase()) && key.toUpperCase() !== 'ELECTRON_RUN_AS_NODE')
|
|
292
|
+
.map(key => [key, undefined]))
|
|
293
|
+
if (packaged) {
|
|
294
|
+
env.DSH_PTC_RUNTIME_NODE = '1'
|
|
295
|
+
env.NODE_OPTIONS = `${heapFlag} --experimental-vm-modules`
|
|
296
|
+
}
|
|
297
|
+
const handle = this.ctx.subprocess.spawn({ argv: this.confined?.argv ?? argv, cwd, env, stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', control: 'pipe' }, graceMs: this.config.graceMs })
|
|
298
|
+
this.handle = handle
|
|
299
|
+
if (!handle.control || !handle.stdout || !handle.stderr) throw new Error('subprocess provider did not supply the requested control and output pipes')
|
|
300
|
+
for (const stream of [handle.stdout, handle.stderr]) {
|
|
301
|
+
stream.setEncoding('utf8')
|
|
302
|
+
stream.on('data', (text: string) => {
|
|
303
|
+
if (stream === handle.stderr) this.stderr = (this.stderr + text).slice(-this.config.maxOutputBytes)
|
|
304
|
+
this.active?.admit(text)
|
|
305
|
+
})
|
|
306
|
+
stream.on('error', (error: Error) => { this.fail('worker-exit', error.message) })
|
|
307
|
+
}
|
|
308
|
+
// A rejected wire call closes its endpoint before birpc can answer it.
|
|
309
|
+
const refuse = (message: string): never => { this.fail('protocol', message); throw new Error(message) }
|
|
310
|
+
this.channel = createProcessRpc<ProgramMethods, HostMethods>(handle.control, this.config.maxMessageBytes, {
|
|
311
|
+
ready: (version) => {
|
|
312
|
+
if (version !== PROGRAM_PROTOCOL_VERSION) {
|
|
313
|
+
this.fail('protocol', 'bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host')
|
|
314
|
+
return
|
|
315
|
+
}
|
|
316
|
+
if (this.ready || !this.active) { this.fail('protocol', 'duplicate program readiness'); return }
|
|
317
|
+
this.ready = true
|
|
318
|
+
this.dispatch(this.active)
|
|
319
|
+
},
|
|
320
|
+
log: (text: unknown) => {
|
|
321
|
+
if (!this.ready || !this.active || typeof text !== 'string') { this.fail('protocol', 'invalid program log'); return }
|
|
322
|
+
if (!this.active.settled) this.active.admit(text)
|
|
323
|
+
},
|
|
324
|
+
outputLimit: () => {
|
|
325
|
+
if (!this.ready || !this.active) { this.fail('protocol', 'idle PTC output limit'); return }
|
|
326
|
+
this.active.finish({ kind: 'output-limit', message: 'output limit exceeded' }, undefined, true)
|
|
327
|
+
},
|
|
328
|
+
invoke: async (global, name, wire) => {
|
|
329
|
+
const evaluation = this.active
|
|
330
|
+
if (!this.ready || !evaluation) return refuse('binding call arrived without an active PTC evaluation')
|
|
331
|
+
if (evaluation.settled) throw new Error('PTC evaluation ended before the binding completed')
|
|
332
|
+
const functions = evaluation.bindings.get(global)?.functions
|
|
333
|
+
const fn = functions !== undefined && Object.hasOwn(functions, name) ? functions[name] : undefined
|
|
334
|
+
if (!this.mode.retainsState && typeof fn !== 'function') return refuse('program requested an undeclared binding')
|
|
335
|
+
const args = decodePtcJsonWire(wire)
|
|
336
|
+
if (args === undefined) return refuse('binding arguments must be lossless JSON')
|
|
337
|
+
const bytes = Buffer.byteLength(JSON.stringify(wire))
|
|
338
|
+
if (evaluation.pending >= this.config.maxPendingCalls || evaluation.pendingBytes + bytes > this.config.maxMessageBytes) {
|
|
339
|
+
return refuse('pending binding calls exceed configured limits')
|
|
340
|
+
}
|
|
341
|
+
evaluation.pending += 1
|
|
342
|
+
evaluation.pendingBytes += bytes
|
|
343
|
+
let value
|
|
344
|
+
try {
|
|
345
|
+
value = await evaluation.invoke(fn, args)
|
|
346
|
+
} catch (error) {
|
|
347
|
+
// oxlint-disable-next-line typescript/no-unnecessary-condition -- The evaluation may settle while the binding is pending.
|
|
348
|
+
if (evaluation.settled) throw new Error('PTC evaluation ended before the binding completed')
|
|
349
|
+
throw error
|
|
350
|
+
} finally {
|
|
351
|
+
evaluation.pending -= 1
|
|
352
|
+
evaluation.pendingBytes -= bytes
|
|
353
|
+
}
|
|
354
|
+
// A late binding result must not fill the pipe shared with the next evaluation.
|
|
355
|
+
// oxlint-disable-next-line typescript/no-unnecessary-condition -- The evaluation may settle while the binding is pending.
|
|
356
|
+
if (evaluation.settled) throw new Error('PTC evaluation ended before the binding completed')
|
|
357
|
+
return value
|
|
358
|
+
},
|
|
359
|
+
}, ['revoke'], (error, kind) => {
|
|
360
|
+
if (kind === 'protocol') this.fail('protocol', error.message)
|
|
361
|
+
else {
|
|
362
|
+
if (kind === 'io') this.controlFailure = error.message
|
|
363
|
+
setImmediate(() => {
|
|
364
|
+
if (!this.closed && this.exitOutcome === undefined) handle.terminate()
|
|
365
|
+
})
|
|
366
|
+
}
|
|
367
|
+
})
|
|
368
|
+
void handle.done.then(async (outcome) => {
|
|
369
|
+
this.exitOutcome = outcome
|
|
370
|
+
await Promise.all([drainOutput(handle.stdout, this.config.graceMs), drainOutput(handle.stderr, this.config.graceMs)])
|
|
371
|
+
// The RPC result can already be queued when process exit arrives.
|
|
372
|
+
setImmediate(() => {
|
|
373
|
+
if (!this.closed) this.fail(this.confined !== undefined && classifyRunnerFailure(outcome.exitCode, this.stderr, this.confined.runnerFailureRules) !== undefined ? 'sandbox-unavailable' : 'worker-exit', this.exitMessage(outcome))
|
|
374
|
+
})
|
|
375
|
+
}, (error: unknown) => {
|
|
376
|
+
this.fail(this.confined !== undefined && isRunnerSpawnFailure(error, this.confined.argv[0], cwd)
|
|
377
|
+
? 'sandbox-unavailable' : 'worker-exit', this.withControlFailure(messageOf(error)))
|
|
378
|
+
})
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
}
|