@deepseek-ai/dsh-ptc-runtime-node 0.2.2-rc.5 → 0.2.3-alpha.1
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 +24 -24
- package/README.md +49 -17
- package/README.zh.md +49 -17
- package/lib/configuration.js +15 -5
- package/lib/index.js +439 -148
- package/lib/persistent-process.js +683 -90
- package/lib/process.js +683 -90
- package/lib/types/bindings.d.ts +10 -5
- package/lib/types/bindings.d.ts.map +1 -1
- package/lib/types/bindings.js.map +1 -1
- package/lib/types/bootstrap.d.ts +42 -24
- package/lib/types/bootstrap.d.ts.map +1 -1
- package/lib/types/bootstrap.js.map +1 -1
- package/lib/types/config.d.ts +14 -2
- package/lib/types/config.d.ts.map +1 -1
- package/lib/types/config.js.map +1 -1
- package/lib/types/configuration.d.ts +5 -4
- package/lib/types/configuration.d.ts.map +1 -1
- package/lib/types/configuration.js.map +1 -1
- package/lib/types/environment.d.ts +13 -0
- package/lib/types/environment.d.ts.map +1 -1
- package/lib/types/environment.js.map +1 -1
- package/lib/types/evaluators/index.d.ts.map +1 -1
- package/lib/types/evaluators/index.js.map +1 -1
- package/lib/types/evaluators/scoped-repl-evaluator.d.ts +22 -0
- package/lib/types/evaluators/scoped-repl-evaluator.d.ts.map +1 -0
- package/lib/types/evaluators/scoped-repl-evaluator.js.map +1 -0
- package/lib/types/evaluators/scoped-repl.d.ts +130 -0
- package/lib/types/evaluators/scoped-repl.d.ts.map +1 -0
- package/lib/types/evaluators/scoped-repl.js.map +1 -0
- package/lib/types/evaluators/types.d.ts +3 -3
- package/lib/types/evaluators/types.d.ts.map +1 -1
- package/lib/types/evaluators/types.js.map +1 -1
- package/lib/types/execution.d.ts +3 -2
- package/lib/types/execution.d.ts.map +1 -1
- package/lib/types/execution.js.map +1 -1
- package/lib/types/index.d.ts +6 -1
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/index.js.map +1 -1
- package/lib/types/json-wire.d.ts +16 -4
- package/lib/types/json-wire.d.ts.map +1 -1
- package/lib/types/json-wire.js.map +1 -1
- package/lib/types/output-ledger.d.ts +10 -10
- package/lib/types/output-ledger.d.ts.map +1 -1
- package/lib/types/output-ledger.js.map +1 -1
- package/lib/types/process.d.ts +2 -0
- package/lib/types/process.d.ts.map +1 -1
- package/lib/types/process.js.map +1 -1
- package/lib/types/protocol.d.ts +31 -5
- package/lib/types/protocol.d.ts.map +1 -1
- package/lib/types/protocol.js.map +1 -1
- package/lib/types/worker.d.ts +6 -3
- package/lib/types/worker.d.ts.map +1 -1
- package/lib/types/worker.js.map +1 -1
- package/package.json +23 -21
- package/src/bindings.ts +33 -26
- package/src/bootstrap.ts +159 -57
- package/src/config.ts +21 -3
- package/src/configuration.ts +13 -6
- package/src/environment.ts +39 -0
- package/src/evaluators/index.ts +2 -0
- package/src/evaluators/scoped-repl-evaluator.ts +110 -0
- package/src/evaluators/scoped-repl.ts +339 -0
- package/src/evaluators/types.ts +3 -3
- package/src/execution.ts +37 -17
- package/src/index.ts +58 -13
- package/src/json-wire.ts +44 -8
- package/src/output-ledger.ts +42 -45
- package/src/process.ts +89 -18
- package/src/protocol.ts +37 -10
- package/src/worker.ts +75 -40
package/src/process.ts
CHANGED
|
@@ -1,16 +1,23 @@
|
|
|
1
1
|
/** Node child evaluation over typed RPC; the host owns process lifetime. */
|
|
2
2
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
3
|
+
import { inspect } from 'node:util'
|
|
3
4
|
import type { Duplex } from 'node:stream'
|
|
4
|
-
import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime'
|
|
5
|
+
import type { PtcProgramFormat, PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime'
|
|
5
6
|
import { createProcessRpc } from './rpc.ts'
|
|
6
|
-
import { captureStreamWrites, LogBuffer,
|
|
7
|
-
import type { BindingErrorConstructor, PatchableStream } from './bootstrap.ts'
|
|
8
|
-
import {
|
|
7
|
+
import { captureStreamWrites, LogBuffer, makeInspect, makeBindingErrorClass, makeNamespaces, prepareCompletion, prepareException } from './bootstrap.ts'
|
|
8
|
+
import type { BindingErrorConstructor, BindingInspection, ImageInspectOptions, PatchableStream } from './bootstrap.ts'
|
|
9
|
+
import type { PtcImageWire } from './json-wire.ts'
|
|
10
|
+
import { clearProgramEnvironment, filterRuntimeWarnings } from './environment.ts'
|
|
9
11
|
import { createProgramEvaluator } from './evaluators/index.ts'
|
|
10
12
|
import { ImportEvaluationEndedError } from './imports/evaluation-ended.ts'
|
|
11
13
|
import type { ProgramEvaluator, ProgramImportHandler, ProgramImportResult } from './evaluators/types.ts'
|
|
12
14
|
import { PROGRAM_PROTOCOL_VERSION, type ProgramResult, type HostMethods, type ProgramMethods } from './protocol.ts'
|
|
13
15
|
|
|
16
|
+
const capturedObjectCreate = Object.create
|
|
17
|
+
const capturedObjectDefineProperty = Object.defineProperty
|
|
18
|
+
const capturedObjectFreeze = Object.freeze
|
|
19
|
+
const nativeConsole = globalThis.console
|
|
20
|
+
|
|
14
21
|
/** Process-owned environment, output and directory control consumed by the child. */
|
|
15
22
|
export interface ProgramProcess {
|
|
16
23
|
env: NodeJS.ProcessEnv
|
|
@@ -18,6 +25,8 @@ export interface ProgramProcess {
|
|
|
18
25
|
stderr: PatchableStream
|
|
19
26
|
exitCode?: string | number | null | undefined
|
|
20
27
|
chdir(directory: string): void
|
|
28
|
+
/** Node's warning emitter; the child drops warnings from the runtime's own experimental features. */
|
|
29
|
+
emitWarning?: typeof process.emitWarning
|
|
21
30
|
}
|
|
22
31
|
|
|
23
32
|
interface Evaluation {
|
|
@@ -44,6 +53,7 @@ export async function runNodeMain(
|
|
|
44
53
|
): Promise<void> {
|
|
45
54
|
if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes <= 0) throw new Error('invalid control message limit')
|
|
46
55
|
clearProgramEnvironment(processState)
|
|
56
|
+
filterRuntimeWarnings(processState)
|
|
47
57
|
const context = new AsyncLocalStorage<Evaluation>()
|
|
48
58
|
const closed = Promise.withResolvers<void>()
|
|
49
59
|
const errors = new Map<string, { name: string; memberNameProperty: string; constructor: BindingErrorConstructor }>()
|
|
@@ -68,10 +78,44 @@ export async function runNodeMain(
|
|
|
68
78
|
return value
|
|
69
79
|
},
|
|
70
80
|
}
|
|
71
|
-
const
|
|
81
|
+
const images = new WeakMap<object, string>()
|
|
82
|
+
const inspections = new WeakMap<object, BindingInspection>()
|
|
83
|
+
class Image {
|
|
84
|
+
readonly [key: string]: PtcJsonValue
|
|
85
|
+
declare readonly attachmentId: string
|
|
86
|
+
declare readonly path: string
|
|
87
|
+
declare readonly width: number
|
|
88
|
+
declare readonly height: number
|
|
89
|
+
private constructor() { throw new Error('Images are created by image-producing tools') }
|
|
90
|
+
[inspect.custom](_depth: number | null, options: ImageInspectOptions): this {
|
|
91
|
+
collectImage(this, options)
|
|
92
|
+
return this
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const decodeImage = (wire: PtcImageWire): PtcJsonValue => {
|
|
96
|
+
const image = capturedObjectCreate(Image.prototype) as Image
|
|
97
|
+
for (const key of ['attachmentId', 'path', 'width', 'height'] as const) {
|
|
98
|
+
const descriptor = capturedObjectCreate(null) as PropertyDescriptor
|
|
99
|
+
descriptor.enumerable = true
|
|
100
|
+
descriptor.value = wire[key]
|
|
101
|
+
capturedObjectDefineProperty(image, key, descriptor)
|
|
102
|
+
}
|
|
103
|
+
capturedObjectFreeze(image)
|
|
104
|
+
images.set(image, wire.id)
|
|
105
|
+
return image
|
|
106
|
+
}
|
|
107
|
+
const imageSink = (id: string): void => {
|
|
72
108
|
const evaluation = context.getStore()
|
|
73
|
-
if (evaluation && acceptsCalls(evaluation)
|
|
74
|
-
}
|
|
109
|
+
if (evaluation && acceptsCalls(evaluation) && !evaluation.logs.overflowed) void connection.image(id)
|
|
110
|
+
}
|
|
111
|
+
const logSink = {
|
|
112
|
+
get overflowed(): boolean { return context.getStore()?.logs.overflowed ?? true },
|
|
113
|
+
push(text: string): void {
|
|
114
|
+
const evaluation = context.getStore()
|
|
115
|
+
if (evaluation && acceptsCalls(evaluation)) evaluation.logs.push(text)
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
const { inspect: programInspect, collectImage } = makeInspect(logSink, images, imageSink, inspections)
|
|
75
119
|
captureStreamWrites(logSink, processState.stdout)
|
|
76
120
|
captureStreamWrites(logSink, processState.stderr)
|
|
77
121
|
const connection = createProcessRpc<HostMethods, ProgramMethods>(stream, maxMessageBytes, {
|
|
@@ -92,13 +136,19 @@ export async function runNodeMain(
|
|
|
92
136
|
},
|
|
93
137
|
}
|
|
94
138
|
current = evaluation
|
|
95
|
-
|
|
139
|
+
const canContinue = (): boolean => {
|
|
140
|
+
if (!evaluation.active) return false
|
|
141
|
+
if (!evaluation.revoked) return true
|
|
142
|
+
evaluation.finish({})
|
|
143
|
+
return false
|
|
144
|
+
}
|
|
145
|
+
void context.run(evaluation, async () => {
|
|
96
146
|
try {
|
|
97
147
|
processState.chdir(cwd)
|
|
98
148
|
if (evaluator === undefined) {
|
|
99
149
|
evaluator = createProgramEvaluator(format, (error) => {
|
|
100
150
|
const active = context.getStore()
|
|
101
|
-
if (active?.active && error) active.finish(prepareException(error, active.
|
|
151
|
+
if (active?.active && error) active.finish(prepareException(error, active.maxOutputBytes - 2))
|
|
102
152
|
}, importHandler === undefined ? undefined : (request) => {
|
|
103
153
|
const active = context.getStore()
|
|
104
154
|
if (!active?.active) throw new ImportEvaluationEndedError(active?.reusable ?? true)
|
|
@@ -112,9 +162,15 @@ export async function runNodeMain(
|
|
|
112
162
|
throw error
|
|
113
163
|
}) : checkActive(result)
|
|
114
164
|
})
|
|
115
|
-
evaluator.globals.console = makeConsoleShim(logSink)
|
|
116
165
|
// Context access must not reserve a function-body parameter named process.
|
|
117
166
|
Object.defineProperty(evaluator.globals, 'process', { configurable: true, writable: true, value: processState })
|
|
167
|
+
Object.defineProperty(evaluator.globals, 'inspect', {
|
|
168
|
+
configurable: true, enumerable: true, value: programInspect,
|
|
169
|
+
})
|
|
170
|
+
Object.defineProperty(evaluator.globals, 'Image', { configurable: true, enumerable: true, value: Image })
|
|
171
|
+
if (format !== 'function-body') Object.defineProperty(evaluator.globals, 'console', {
|
|
172
|
+
configurable: true, enumerable: true, writable: true, value: nativeConsole,
|
|
173
|
+
})
|
|
118
174
|
}
|
|
119
175
|
for (const namespace of data.namespaces) {
|
|
120
176
|
const descriptor = namespace.errorClass
|
|
@@ -124,7 +180,7 @@ export async function runNodeMain(
|
|
|
124
180
|
const constructor = makeBindingErrorClass(descriptor)
|
|
125
181
|
errors.set(namespace.global, { name: descriptor.name, memberNameProperty: descriptor.memberNameProperty, constructor })
|
|
126
182
|
}
|
|
127
|
-
const namespaces = makeNamespaces(data, host, errorLookup)
|
|
183
|
+
const namespaces = makeNamespaces(data, host, errorLookup, inspections, decodeImage, image => images.has(image))
|
|
128
184
|
for (const [index, namespace] of data.namespaces.entries()) {
|
|
129
185
|
Object.defineProperty(evaluator.globals, namespace.global, { configurable: true, enumerable: true, value: namespaces[index] })
|
|
130
186
|
if (namespace.errorClass) {
|
|
@@ -133,25 +189,40 @@ export async function runNodeMain(
|
|
|
133
189
|
})
|
|
134
190
|
}
|
|
135
191
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
192
|
+
const programEvaluator = evaluator
|
|
193
|
+
const initialization = data.initialization
|
|
194
|
+
if (initialization !== undefined) {
|
|
195
|
+
await new Promise<void>((resolve, reject) => {
|
|
196
|
+
programEvaluator.evaluate(initialization, (result) => {
|
|
197
|
+
if (result.ok) resolve()
|
|
198
|
+
// oxlint-disable-next-line typescript/prefer-promise-reject-errors -- Programs may throw non-Error values.
|
|
199
|
+
else reject(result.error)
|
|
200
|
+
})
|
|
201
|
+
})
|
|
202
|
+
if (!canContinue()) return
|
|
203
|
+
await connection.initialized()
|
|
204
|
+
}
|
|
205
|
+
if (!canContinue()) return
|
|
206
|
+
programEvaluator.evaluate(data.code, (result) => {
|
|
207
|
+
if (!canContinue()) return
|
|
208
|
+
evaluation.finish(result.ok
|
|
209
|
+
? data.discardCompletion ? {} : prepareCompletion(result.value, data.maxOutputBytes - 2, data.maxOutputBytes)
|
|
210
|
+
: prepareException(result.error, data.maxOutputBytes - 2))
|
|
141
211
|
})
|
|
142
212
|
} catch (error: unknown) {
|
|
143
|
-
evaluation.finish(prepareException(error,
|
|
213
|
+
if (canContinue()) evaluation.finish(prepareException(error, data.maxOutputBytes - 2))
|
|
144
214
|
}
|
|
145
215
|
})
|
|
146
216
|
return await completion.promise
|
|
147
217
|
},
|
|
218
|
+
discardOutput() { current?.logs.discard() },
|
|
148
219
|
revoke() {
|
|
149
220
|
const evaluation = current
|
|
150
221
|
if (!evaluation?.active) return
|
|
151
222
|
evaluation.revoked = true
|
|
152
223
|
void connection.$rejectPendingCalls(({ reject }) => { reject(new Error('PTC evaluation canceled')) })
|
|
153
224
|
},
|
|
154
|
-
}, ['ready', 'log', 'outputLimit'], (_error, kind) => {
|
|
225
|
+
}, ['ready', 'log', 'image', 'outputLimit'], (_error, kind) => {
|
|
155
226
|
if (current?.active || kind === 'protocol') processState.exitCode = 1
|
|
156
227
|
if (current) current.active = false
|
|
157
228
|
closed.resolve()
|
package/src/protocol.ts
CHANGED
|
@@ -3,29 +3,42 @@ import type { PtcProgramFormat, PtcJsonValue, PtcRunFailure } from '@deepseek-ai
|
|
|
3
3
|
import { decodePtcJsonWire, type PtcJsonWire } from './json-wire.ts'
|
|
4
4
|
|
|
5
5
|
/** Wire revision required before the host dispatches program code. */
|
|
6
|
-
export const PROGRAM_PROTOCOL_VERSION =
|
|
6
|
+
export const PROGRAM_PROTOCOL_VERSION = 5
|
|
7
|
+
|
|
8
|
+
/** One binding's JSON value and optional host-authored inspection text. */
|
|
9
|
+
export interface BindingResult {
|
|
10
|
+
/** Flat lossless JSON data returned to the program. */
|
|
11
|
+
value: PtcJsonWire
|
|
12
|
+
/** Direct inspection text for an unchanged object or array. */
|
|
13
|
+
inspection?: string
|
|
14
|
+
}
|
|
7
15
|
|
|
8
16
|
/** Inputs for one program; host functions remain in the parent process. */
|
|
9
17
|
export interface ProgramBootData {
|
|
10
18
|
/** Type-stripped JavaScript source. */
|
|
11
19
|
code: string
|
|
20
|
+
/** Environment initialization, supplied only until the Host accepts initialized(). */
|
|
21
|
+
initialization?: string
|
|
12
22
|
/** Evaluation syntax; omitted uses the installed bootstrap's default. */
|
|
13
23
|
programFormat?: PtcProgramFormat
|
|
14
24
|
/** Whether the host will reuse this process after the evaluation. */
|
|
15
25
|
retainsState: boolean
|
|
26
|
+
/** Await successful completion without serializing its value. */
|
|
27
|
+
discardCompletion?: boolean
|
|
16
28
|
/** Globals and callable names injected into the program. */
|
|
17
29
|
namespaces: {
|
|
18
30
|
global: string
|
|
19
31
|
names: string[]
|
|
20
32
|
errorClass?: { name: string; memberNameProperty: string }
|
|
21
33
|
}[]
|
|
22
|
-
/** Combined serialized
|
|
34
|
+
/** Combined serialized output and completion or diagnostic budget; terminal data takes priority. */
|
|
23
35
|
maxOutputBytes: number
|
|
24
36
|
}
|
|
25
37
|
|
|
26
38
|
/** Program completion; logs are delivered separately before this result. */
|
|
27
39
|
export interface ProgramResult {
|
|
28
40
|
value?: PtcJsonWire
|
|
41
|
+
outputTruncated?: boolean
|
|
29
42
|
error?: { kind: 'exception' | 'invalid-output' | 'output-limit'; message: string }
|
|
30
43
|
}
|
|
31
44
|
|
|
@@ -36,20 +49,31 @@ export interface HostMethods {
|
|
|
36
49
|
* @param version - Bootstrap wire revision, checked against the host.
|
|
37
50
|
*/
|
|
38
51
|
ready(version: number): void
|
|
52
|
+
/**
|
|
53
|
+
* Accept successful environment initialization while the first run remains active.
|
|
54
|
+
* The child awaits the RPC reply before starting user code; cancellation rejects.
|
|
55
|
+
* @returns Host acceptance before user code may start.
|
|
56
|
+
*/
|
|
57
|
+
initialized(): Promise<void>
|
|
39
58
|
/**
|
|
40
59
|
* Invoke a binding under its originating host execution context.
|
|
41
60
|
* @param global - Namespace global.
|
|
42
61
|
* @param name - Function name within the namespace.
|
|
43
62
|
* @param args - Flat lossless JSON arguments.
|
|
44
|
-
* @returns
|
|
63
|
+
* @returns JSON data with optional inspection text; binding failures and cancellation reject.
|
|
45
64
|
*/
|
|
46
|
-
invoke(global: string, name: string, args: PtcJsonWire): Promise<
|
|
65
|
+
invoke(global: string, name: string, args: PtcJsonWire): Promise<BindingResult>
|
|
47
66
|
/**
|
|
48
67
|
* Admit captured output before completion or interruption.
|
|
49
68
|
* @param text - Captured text.
|
|
50
69
|
*/
|
|
51
70
|
log(text: string): void
|
|
52
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* Emit one registered image at the current output position.
|
|
73
|
+
* @param id - Image identity issued by this process’s host.
|
|
74
|
+
*/
|
|
75
|
+
image(id: string): void
|
|
76
|
+
/** Report discarded program output without ending the evaluation. */
|
|
53
77
|
outputLimit(): void
|
|
54
78
|
}
|
|
55
79
|
|
|
@@ -64,6 +88,8 @@ export interface ProgramMethods {
|
|
|
64
88
|
run(cwd: string, data: ProgramBootData): Promise<ProgramResult>
|
|
65
89
|
/** Notify the program thread to revoke bindings and output; run() still owns completion. */
|
|
66
90
|
revoke(): void
|
|
91
|
+
/** Discard subsequent captured output while allowing execution and binding calls to continue. */
|
|
92
|
+
discardOutput(): void
|
|
67
93
|
}
|
|
68
94
|
|
|
69
95
|
const record = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
@@ -73,17 +99,18 @@ const record = (value: unknown): value is Record<string, unknown> => typeof valu
|
|
|
73
99
|
* @param result - Untrusted result returned by the program process.
|
|
74
100
|
* @returns Decoded completion or failure; malformed envelopes throw a protocol error.
|
|
75
101
|
*/
|
|
76
|
-
export function readProgramResult(result: unknown): { value?: PtcJsonValue; error?: PtcRunFailure } {
|
|
77
|
-
if (!record(result)) throw new Error('invalid program result')
|
|
102
|
+
export function readProgramResult(result: unknown): { value?: PtcJsonValue; error?: PtcRunFailure; outputTruncated?: boolean } {
|
|
103
|
+
if (!record(result) || (result.outputTruncated !== undefined && typeof result.outputTruncated !== 'boolean')) throw new Error('invalid program result')
|
|
104
|
+
const truncation = result.outputTruncated ? { outputTruncated: true } : {}
|
|
78
105
|
if (result.error !== undefined) {
|
|
79
106
|
const error = result.error
|
|
80
107
|
if (!record(error) || typeof error.message !== 'string'
|
|
81
108
|
|| (error.kind !== 'exception' && error.kind !== 'invalid-output' && error.kind !== 'output-limit')) {
|
|
82
109
|
throw new Error('invalid terminal error')
|
|
83
110
|
}
|
|
84
|
-
return { error: { kind: error.kind, message: error.message } }
|
|
111
|
+
return { ...truncation, error: { kind: error.kind, message: error.message } }
|
|
85
112
|
}
|
|
86
|
-
if (result.value === undefined) return
|
|
113
|
+
if (result.value === undefined) return truncation
|
|
87
114
|
const value = decodePtcJsonWire(result.value)
|
|
88
|
-
return value === undefined ? { error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } } : { value }
|
|
115
|
+
return value === undefined ? { ...truncation, error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } } : { ...truncation, value }
|
|
89
116
|
}
|
package/src/worker.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
/** Managed Node process shared by temporary and owner-retained evaluations. */
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { PtcImage } from '@deepseek-ai/dsh-ptc-runtime'
|
|
4
|
+
import type { PtcOutput } from '@deepseek-ai/dsh-ptc-runtime'
|
|
2
5
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
3
6
|
import { Context } from '@deepseek-ai/cordis'
|
|
4
|
-
import type
|
|
7
|
+
import { PtcRuntimeError, type PtcRunSpec, type PtcRunResult, type PtcRunSandbox, type PtcRunFailure, type PtcBindingNamespace, type PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime'
|
|
5
8
|
import { SandboxUnavailableError, classifyRunnerFailure, isRunnerSpawnFailure } from '@deepseek-ai/dsh-sandbox'
|
|
6
9
|
import type { ConfinedArgv, SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
|
|
7
10
|
import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess'
|
|
@@ -13,7 +16,7 @@ import type { BirpcReturn } from 'birpc'
|
|
|
13
16
|
import { createProcessRpc } from './rpc.ts'
|
|
14
17
|
import { bootstrapArgs } from './launch.ts'
|
|
15
18
|
import { STARTUP_ENVIRONMENT_NAMES } from './environment.ts'
|
|
16
|
-
import { decodePtcJsonWire } from './json-wire.ts'
|
|
19
|
+
import { decodePtcJsonWire, type PtcImageWire } from './json-wire.ts'
|
|
17
20
|
import { OutputLedger } from './output-ledger.ts'
|
|
18
21
|
import { drainOutput, terminateProcess } from './output-stream.ts'
|
|
19
22
|
import { readProgramResult, PROGRAM_PROTOCOL_VERSION, type ProgramBootData, type ProgramMethods, type HostMethods } from './protocol.ts'
|
|
@@ -29,7 +32,8 @@ interface Evaluation {
|
|
|
29
32
|
invoke: typeof invokeBinding
|
|
30
33
|
pending: number
|
|
31
34
|
pendingBytes: number
|
|
32
|
-
admit(
|
|
35
|
+
admit(entry: PtcOutput): void
|
|
36
|
+
truncateOutput(): void
|
|
33
37
|
finish(error?: PtcRunFailure, value?: PtcJsonValue, discard?: boolean): void
|
|
34
38
|
}
|
|
35
39
|
|
|
@@ -49,6 +53,7 @@ export class ProgramWorker {
|
|
|
49
53
|
private termination: Promise<boolean> | undefined
|
|
50
54
|
private starting?: Promise<void>
|
|
51
55
|
private exitOutcome?: SubprocessOutcome
|
|
56
|
+
private readonly images = new Map<string, PtcImage['attachment']>()
|
|
52
57
|
private readonly controller = new AbortController()
|
|
53
58
|
closed = false
|
|
54
59
|
|
|
@@ -63,19 +68,20 @@ export class ProgramWorker {
|
|
|
63
68
|
* @param processes - Session policy invalidation and cleanup coordination.
|
|
64
69
|
* @param mode - Evaluator syntax and TypeScript erasure.
|
|
65
70
|
* @param retainsState - Whether this process belongs to an owner and survives completed evaluations.
|
|
71
|
+
* @param pendingInitialization - Type-erased setup source, or undefined when no initialization is required.
|
|
66
72
|
*/
|
|
67
73
|
constructor(
|
|
68
74
|
private readonly ctx: Context, private readonly config: ResolvedConfig,
|
|
69
75
|
readonly policy: SandboxExecutionPolicy, processes: PolicyProcesses, private readonly mode: ExecutionMode,
|
|
70
|
-
private readonly retainsState: boolean,
|
|
76
|
+
private readonly retainsState: boolean, private pendingInitialization: string | undefined,
|
|
71
77
|
) {
|
|
72
78
|
this.unregister = processes.register(policy, () => this.dispose())
|
|
73
79
|
}
|
|
74
80
|
|
|
75
81
|
/** Reject reuse until the previous evaluation and required cleanup settle. */
|
|
76
82
|
assertIdle(): void {
|
|
77
|
-
if (this.running) throw new
|
|
78
|
-
if (this.cleanupPending) throw new
|
|
83
|
+
if (this.running) throw new PtcRuntimeError('persistent PTC does not accept concurrent runs for one state owner', 'PTC_RUNTIME_CONFLICT')
|
|
84
|
+
if (this.cleanupPending) throw new PtcRuntimeError('persistent PTC environment cleanup is incomplete; release the owner before running another program', 'PTC_RUNTIME_UNAVAILABLE')
|
|
79
85
|
}
|
|
80
86
|
|
|
81
87
|
/**
|
|
@@ -98,30 +104,23 @@ export class ProgramWorker {
|
|
|
98
104
|
} finally { this.running = false }
|
|
99
105
|
}
|
|
100
106
|
|
|
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
107
|
private message(message: string): string {
|
|
107
108
|
return this.retainsState ? `${message}; retained variables were cleared` : message
|
|
108
109
|
}
|
|
109
110
|
|
|
110
111
|
private async evaluate(spec: PtcRunSpec, bindings: Map<string, PtcBindingNamespace>): Promise<PtcRunResult> {
|
|
112
|
+
const ledger = new OutputLedger(this.config.maxOutputBytes)
|
|
111
113
|
if (this.exitOutcome !== undefined) {
|
|
112
|
-
const output = this.output()
|
|
113
114
|
const failure: PtcRunFailure = spec.signal?.aborted
|
|
114
115
|
? { kind: 'abort', message: this.message('execution canceled') }
|
|
115
116
|
: { kind: 'worker-exit', message: this.message(this.exitMessage(this.exitOutcome)) }
|
|
116
117
|
try { await this.terminate() } catch (error: unknown) {
|
|
117
|
-
return
|
|
118
|
+
return ledger.failure([], { kind: 'worker-exit', message: `managed process cleanup failed: ${messageOf(error)}` })
|
|
118
119
|
}
|
|
119
|
-
return
|
|
120
|
+
return ledger.failure([], failure)
|
|
120
121
|
}
|
|
121
122
|
this.stderr = ''
|
|
122
|
-
const output =
|
|
123
|
-
const logs: string[] = []
|
|
124
|
-
let overflowed = false
|
|
123
|
+
const output: PtcOutput[] = []
|
|
125
124
|
const result = Promise.withResolvers<PtcRunResult>()
|
|
126
125
|
const timer = spec.timeoutMs === null ? undefined : setTimeout(() => {
|
|
127
126
|
const phase = evaluation.completion !== undefined ? 'during execution' : 'before code started'
|
|
@@ -136,48 +135,54 @@ export class ProgramWorker {
|
|
|
136
135
|
completion: undefined,
|
|
137
136
|
data: {
|
|
138
137
|
code: '', programFormat: this.mode.format, retainsState: this.retainsState,
|
|
138
|
+
...this.pendingInitialization === undefined ? {} : { initialization: this.pendingInitialization },
|
|
139
139
|
maxOutputBytes: this.config.maxOutputBytes,
|
|
140
|
+
discardCompletion: spec.discardCompletion === true,
|
|
140
141
|
namespaces: [...bindings.values()].map(binding => ({
|
|
141
142
|
global: binding.global, names: Object.keys(binding.functions), ...binding.errorClass ? { errorClass: binding.errorClass } : {},
|
|
142
143
|
})),
|
|
143
144
|
},
|
|
144
|
-
spec, bindings,
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
145
|
+
spec, bindings, pending: 0, pendingBytes: 0,
|
|
146
|
+
invoke: AsyncLocalStorage.bind((binding, args) => invokeBinding(binding, args, image => this.registerImage(image))),
|
|
147
|
+
truncateOutput: () => {
|
|
148
|
+
ledger.truncated = true
|
|
149
|
+
const channel = this.channel
|
|
150
|
+
if (evaluation.settled || this.closed || !channel || channel.$closed) return
|
|
151
|
+
void channel.discardOutput().catch((error: unknown) => {
|
|
152
|
+
// Ended evaluations need no notification; channel closure already owns failure reporting.
|
|
153
|
+
if (this.active !== evaluation || evaluation.settled || this.closed || channel.$closed) return
|
|
154
|
+
this.fail('protocol', `failed to send output-discard notification: ${messageOf(error)}`)
|
|
155
|
+
})
|
|
156
|
+
},
|
|
157
|
+
admit: (entry) => {
|
|
158
|
+
if (ledger.truncated) return
|
|
159
|
+
if (!ledger.admit(entry, output)) evaluation.truncateOutput()
|
|
152
160
|
},
|
|
153
161
|
finish: (error, value, discard = false) => {
|
|
154
162
|
if (evaluation.settled) return
|
|
155
163
|
evaluation.settled = true
|
|
156
164
|
clearTimeout(timer)
|
|
157
165
|
spec.signal?.removeEventListener('abort', onAbort)
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
const outcome = complete()
|
|
166
|
+
const initializationIncomplete = this.pendingInitialization !== undefined
|
|
167
|
+
if (initializationIncomplete && error?.kind === 'exception') error = { ...error, message: this.message(error.message) }
|
|
161
168
|
const cleanup = async (): Promise<PtcRunResult> => {
|
|
162
169
|
const interrupted = error?.kind === 'timeout' || error?.kind === 'abort'
|
|
163
|
-
let preserved = this.retainsState && !
|
|
170
|
+
let preserved = this.retainsState && !initializationIncomplete && !discard
|
|
164
171
|
if (preserved && interrupted) preserved = await this.interruptEvaluation(evaluation)
|
|
165
172
|
let drained = true
|
|
166
173
|
if (!preserved) drained = await this.terminate()
|
|
167
174
|
if (interrupted && this.retainsState && error) {
|
|
168
175
|
error = { ...error, message: `${error.message}; retained variables were ${preserved ? 'preserved' : 'cleared'}` }
|
|
169
176
|
}
|
|
170
|
-
const completed =
|
|
171
|
-
|
|
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' })
|
|
177
|
+
const completed = error ? ledger.failure(output, error) : ledger.success(output, value)
|
|
178
|
+
return drained ? completed : ledger.failure(output, { kind: 'worker-exit', message: 'managed process exited but its output did not drain cleanly' })
|
|
174
179
|
}
|
|
175
180
|
void cleanup().then((completed) => {
|
|
176
181
|
this.active = undefined
|
|
177
182
|
result.resolve(completed)
|
|
178
183
|
}, (failure: unknown) => {
|
|
179
184
|
this.active = undefined
|
|
180
|
-
result.resolve(
|
|
185
|
+
result.resolve(ledger.failure(output, { kind: 'worker-exit', message: `managed process cleanup failed: ${messageOf(failure)}` }))
|
|
181
186
|
})
|
|
182
187
|
},
|
|
183
188
|
}
|
|
@@ -185,7 +190,9 @@ export class ProgramWorker {
|
|
|
185
190
|
spec.signal?.addEventListener('abort', onAbort, { once: true })
|
|
186
191
|
if (spec.signal?.aborted) onAbort()
|
|
187
192
|
else {
|
|
188
|
-
try {
|
|
193
|
+
try {
|
|
194
|
+
evaluation.data.code = this.mode.stripTypes(spec.program)
|
|
195
|
+
} catch (error: unknown) {
|
|
189
196
|
// A parse failure before startup has no process state or authority to retain.
|
|
190
197
|
evaluation.finish({ kind: 'exception', message: messageOf(error) }, undefined, !this.ready)
|
|
191
198
|
return await result.promise
|
|
@@ -230,6 +237,7 @@ export class ProgramWorker {
|
|
|
230
237
|
private terminate(): Promise<boolean> {
|
|
231
238
|
if (this.termination) return this.termination
|
|
232
239
|
this.closed = true
|
|
240
|
+
this.images.clear()
|
|
233
241
|
this.cleanupPending = true
|
|
234
242
|
this.controller.abort()
|
|
235
243
|
this.channel?.$close()
|
|
@@ -259,8 +267,13 @@ export class ProgramWorker {
|
|
|
259
267
|
private dispatch(evaluation: Evaluation): void {
|
|
260
268
|
const completion = this.channel?.run(evaluation.spec.cwd, evaluation.data).then(readProgramResult)
|
|
261
269
|
evaluation.completion = completion
|
|
262
|
-
void completion?.then(({ error, value }) => {
|
|
270
|
+
void completion?.then(({ error, value, outputTruncated }) => {
|
|
263
271
|
if (evaluation.settled) return
|
|
272
|
+
if (this.pendingInitialization !== undefined && error === undefined) {
|
|
273
|
+
this.fail('protocol', 'environment initialization completed without Host acceptance')
|
|
274
|
+
return
|
|
275
|
+
}
|
|
276
|
+
if (outputTruncated) evaluation.truncateOutput()
|
|
264
277
|
// Raw stdio can be queued beside the RPC result on separate pipes.
|
|
265
278
|
setImmediate(() => { evaluation.finish(error, value) })
|
|
266
279
|
}).catch((error: unknown) => {
|
|
@@ -276,6 +289,12 @@ export class ProgramWorker {
|
|
|
276
289
|
return this.withControlFailure(`Node process exited (${String(outcome.exitCode)}, signal ${String(outcome.signal)})${this.stderr ? `: ${this.stderr}` : ''}`)
|
|
277
290
|
}
|
|
278
291
|
|
|
292
|
+
private registerImage(image: PtcImage): PtcImageWire {
|
|
293
|
+
const id = randomUUID()
|
|
294
|
+
this.images.set(id, image.attachment)
|
|
295
|
+
return { kind: 'image', id, attachmentId: image.attachment.attachmentId, path: image.path, width: image.attachment.width, height: image.attachment.height }
|
|
296
|
+
}
|
|
297
|
+
|
|
279
298
|
private async start(cwd: string): Promise<void> {
|
|
280
299
|
const executable = await this.ctx.subprocess.resolveExecutable(this.config.launch.executable, undefined, this.controller.signal)
|
|
281
300
|
if (this.closed) return
|
|
@@ -301,7 +320,7 @@ export class ProgramWorker {
|
|
|
301
320
|
stream.setEncoding('utf8')
|
|
302
321
|
stream.on('data', (text: string) => {
|
|
303
322
|
if (stream === handle.stderr) this.stderr = (this.stderr + text).slice(-this.config.maxOutputBytes)
|
|
304
|
-
this.active?.admit(text)
|
|
323
|
+
this.active?.admit({ type: 'text', text })
|
|
305
324
|
})
|
|
306
325
|
stream.on('error', (error: Error) => { this.fail('worker-exit', error.message) })
|
|
307
326
|
}
|
|
@@ -317,13 +336,29 @@ export class ProgramWorker {
|
|
|
317
336
|
this.ready = true
|
|
318
337
|
this.dispatch(this.active)
|
|
319
338
|
},
|
|
339
|
+
initialized: () => {
|
|
340
|
+
const evaluation = this.active
|
|
341
|
+
if (!this.ready || !evaluation || this.pendingInitialization === undefined) {
|
|
342
|
+
return refuse('unexpected environment initialization acknowledgement')
|
|
343
|
+
}
|
|
344
|
+
if (evaluation.settled || evaluation.spec.signal?.aborted) {
|
|
345
|
+
throw new Error('PTC evaluation ended before initialization completed')
|
|
346
|
+
}
|
|
347
|
+
this.pendingInitialization = undefined
|
|
348
|
+
return Promise.resolve()
|
|
349
|
+
},
|
|
320
350
|
log: (text: unknown) => {
|
|
321
351
|
if (!this.ready || !this.active || typeof text !== 'string') { this.fail('protocol', 'invalid program log'); return }
|
|
322
|
-
if (!this.active.settled) this.active.admit(text)
|
|
352
|
+
if (!this.active.settled) this.active.admit({ type: 'text', text })
|
|
353
|
+
},
|
|
354
|
+
image: (id: unknown) => {
|
|
355
|
+
const image = typeof id === 'string' ? this.images.get(id) : undefined
|
|
356
|
+
if (!this.ready || !this.active || image === undefined) { this.fail('protocol', 'invalid program image'); return }
|
|
357
|
+
if (!this.active.settled) this.active.admit({ type: 'image', attachment: image })
|
|
323
358
|
},
|
|
324
359
|
outputLimit: () => {
|
|
325
360
|
if (!this.ready || !this.active) { this.fail('protocol', 'idle PTC output limit'); return }
|
|
326
|
-
this.active.
|
|
361
|
+
this.active.truncateOutput()
|
|
327
362
|
},
|
|
328
363
|
invoke: async (global, name, wire) => {
|
|
329
364
|
const evaluation = this.active
|
|
@@ -356,7 +391,7 @@ export class ProgramWorker {
|
|
|
356
391
|
if (evaluation.settled) throw new Error('PTC evaluation ended before the binding completed')
|
|
357
392
|
return value
|
|
358
393
|
},
|
|
359
|
-
}, ['revoke'], (error, kind) => {
|
|
394
|
+
}, ['revoke', 'discardOutput'], (error, kind) => {
|
|
360
395
|
if (kind === 'protocol') this.fail('protocol', error.message)
|
|
361
396
|
else {
|
|
362
397
|
if (kind === 'io') this.controlFailure = error.message
|