@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
package/src/bootstrap.ts
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Output capture, result encoding, and host binding proxies over the process channel.
|
|
3
|
+
* @module @deepseek-ai/dsh-ptc-runtime-node/src/bootstrap
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { inspect, types } from 'node:util'
|
|
7
|
+
import type { HostMethods, ProgramResult, ProgramBootData } from './protocol.ts'
|
|
8
|
+
import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from './output-json.ts'
|
|
9
|
+
import { decodePtcJsonWire, encodePtcJsonWire, snapshotPtcJsonValue } from './json-wire.ts'
|
|
10
|
+
|
|
11
|
+
const CapturedError = Error
|
|
12
|
+
const isNativeError = types.isNativeError
|
|
13
|
+
const capturedObjectCreate = Object.create
|
|
14
|
+
const capturedObjectDefineProperty = Object.defineProperty
|
|
15
|
+
|
|
16
|
+
/** Define one public binding-error field without consulting mutable globals or descriptor prototypes. */
|
|
17
|
+
function defineBindingErrorField(error: Error, key: string, value: string): void {
|
|
18
|
+
const attributes = capturedObjectCreate(null) as PropertyDescriptor
|
|
19
|
+
attributes.enumerable = true
|
|
20
|
+
attributes.value = value
|
|
21
|
+
capturedObjectDefineProperty(error, key, attributes)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A writable stream's `write` slot, as the bootstrap patches it (see
|
|
26
|
+
* {@link captureStreamWrites}). Method-typed so the real
|
|
27
|
+
* `process.stdout`/`process.stderr` (narrower chunk parameters) remain
|
|
28
|
+
* assignable.
|
|
29
|
+
*/
|
|
30
|
+
export interface PatchableStream {
|
|
31
|
+
write(chunk: unknown, ...rest: unknown[]): boolean
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Ordered text capture under the shared outer JSON-byte budget, delivered to
|
|
36
|
+
* a sink as each item lands (the real sink sends text to the host eagerly,
|
|
37
|
+
* so captured output survives a mid-run termination). It includes the log
|
|
38
|
+
* array syntax and string escaping in its accounting. Once exhausted it emits
|
|
39
|
+
* the fitting prefix and reports the limit once; the host turns that condition
|
|
40
|
+
* into an explicit `output-limit` run failure.
|
|
41
|
+
*/
|
|
42
|
+
export class LogBuffer {
|
|
43
|
+
private bytes = 2 // JSON serialization of the empty logs array: []
|
|
44
|
+
private entries = 0
|
|
45
|
+
private truncated = false
|
|
46
|
+
// Explicit fields, not constructor parameter properties: this module loads
|
|
47
|
+
// under Node's native strip-only mode, which rejects non-erasable syntax —
|
|
48
|
+
// and parameter properties are non-erasable.
|
|
49
|
+
private readonly sink: (text: string) => void
|
|
50
|
+
private readonly onLimit: () => void
|
|
51
|
+
private readonly maxBytes: number
|
|
52
|
+
|
|
53
|
+
constructor(maxBytes: number, sink: (text: string) => void, onLimit: () => void = () => {}) {
|
|
54
|
+
this.maxBytes = maxBytes
|
|
55
|
+
this.sink = sink
|
|
56
|
+
this.onLimit = onLimit
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Emit text to the sink, charging it against the budget (drops + marks once exhausted).
|
|
61
|
+
* @param text - the captured text to deliver.
|
|
62
|
+
*/
|
|
63
|
+
push(text: string): void {
|
|
64
|
+
if (this.truncated) return
|
|
65
|
+
const separatorBytes = this.entries > 0 ? 1 : 0
|
|
66
|
+
const availableBytes = this.maxBytes - this.bytes - separatorBytes
|
|
67
|
+
const stringBytes = jsonStringBytesUpTo(text, availableBytes)
|
|
68
|
+
if (stringBytes === undefined) {
|
|
69
|
+
this.truncated = true
|
|
70
|
+
const prefix = truncateJsonStringBytes(text, availableBytes)
|
|
71
|
+
if (prefix.length > 0) {
|
|
72
|
+
const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes)
|
|
73
|
+
/* v8 ignore next -- truncateJsonStringBytes guarantees the returned prefix fits. */
|
|
74
|
+
if (prefixBytes === undefined) throw new CapturedError('program output ledger produced an oversized log prefix')
|
|
75
|
+
this.bytes += prefixBytes + separatorBytes
|
|
76
|
+
this.entries += 1
|
|
77
|
+
this.sink(prefix)
|
|
78
|
+
}
|
|
79
|
+
this.onLimit()
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
this.bytes += stringBytes + separatorBytes
|
|
83
|
+
this.entries += 1
|
|
84
|
+
this.sink(text)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Remaining exact JSON-byte budget for the completion value or failure message. */
|
|
88
|
+
remainingOutputBytes(): number {
|
|
89
|
+
return this.maxBytes - this.bytes
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The five console methods the shim captures, in the seam's level vocabulary. */
|
|
94
|
+
const CONSOLE_LEVELS = ['log', 'info', 'warn', 'error', 'debug'] as const
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* A `console` replacement whose five leveled methods render their arguments
|
|
98
|
+
* `util.inspect`-style (matching real console formatting closely enough for
|
|
99
|
+
* a model to recognize its own output) into the buffer. Only these five
|
|
100
|
+
* exist — the program gets a deliberately small console, not Node's full
|
|
101
|
+
* console API.
|
|
102
|
+
* @param logs - the buffer every rendered line is pushed into.
|
|
103
|
+
* @returns the five-method console object handed to the program.
|
|
104
|
+
*/
|
|
105
|
+
export function makeConsoleShim(logs: Pick<LogBuffer, 'push'>): Record<(typeof CONSOLE_LEVELS)[number], (...args: unknown[]) => void> {
|
|
106
|
+
const render = (args: unknown[]): string =>
|
|
107
|
+
args.map(arg => typeof arg === 'string' ? arg : inspect(arg, INSPECT_OPTIONS)).join(' ')
|
|
108
|
+
const shim = Object.create(null) as Record<(typeof CONSOLE_LEVELS)[number], (...args: unknown[]) => void>
|
|
109
|
+
for (const level of CONSOLE_LEVELS) {
|
|
110
|
+
shim[level] = (...args: unknown[]) => { logs.push(render(args)) }
|
|
111
|
+
}
|
|
112
|
+
return shim
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Redirect a stream's `write` into the log buffer (the program-visible
|
|
117
|
+
* `process.stdout`/`process.stderr` in the Node child), so raw writes land in emission order
|
|
118
|
+
* alongside console output instead of racing down a pipe. It preserves Node's optional callback
|
|
119
|
+
* contract: the callback runs asynchronously after admission, even when the log budget drops
|
|
120
|
+
* the write.
|
|
121
|
+
*
|
|
122
|
+
* @param logs - the buffer captured writes are pushed into.
|
|
123
|
+
* @param stream - the stream whose `write` slot is patched.
|
|
124
|
+
* @returns the restore function (the in-process tests un-patch; the real
|
|
125
|
+
* child never needs to).
|
|
126
|
+
*/
|
|
127
|
+
export function captureStreamWrites(logs: Pick<LogBuffer, 'push'>, stream: PatchableStream): () => void {
|
|
128
|
+
// The slot's VALUE is stored for restore and reassigned — never invoked
|
|
129
|
+
// detached, so the unbound-method concern does not apply.
|
|
130
|
+
// oxlint-disable-next-line typescript/unbound-method
|
|
131
|
+
const original = stream.write
|
|
132
|
+
stream.write = (chunk: unknown, ...rest: unknown[]): boolean => {
|
|
133
|
+
logs.push(typeof chunk === 'string' ? chunk : String(chunk))
|
|
134
|
+
// Node's optional-encoding shape: the callback is whichever of the next
|
|
135
|
+
// two positions holds a function (a non-function there is the encoding).
|
|
136
|
+
const callback = [rest[0], rest[1]].find(
|
|
137
|
+
(arg): arg is (error?: Error | null) => void => typeof arg === 'function',
|
|
138
|
+
)
|
|
139
|
+
if (callback) queueMicrotask(() => { callback(null) })
|
|
140
|
+
return true
|
|
141
|
+
}
|
|
142
|
+
return () => { stream.write = original }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Bounded inspect options: deep enough to be useful, bounded so a pathological value cannot explode the rendering. */
|
|
146
|
+
const INSPECT_OPTIONS = { depth: 4, maxArrayLength: 100, maxStringLength: 10_000 } as const
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Prepare the program's completion value for the run result. Only lossless
|
|
150
|
+
* JSON crosses, and a value that does not fit the remaining combined outer
|
|
151
|
+
* budget reports `output-limit`; the host revalidates hostile traffic and
|
|
152
|
+
* remains authoritative for native pipe writes the program shim cannot observe.
|
|
153
|
+
*
|
|
154
|
+
* @param value - the program's completion value.
|
|
155
|
+
* @param remainingOutputBytes - exact bytes left after captured logs.
|
|
156
|
+
* @param maxOutputBytes - the configured cap named in an overflow diagnostic.
|
|
157
|
+
* @returns the result fragment: `{}` for `undefined`, else a flat wire `{ value }`.
|
|
158
|
+
*/
|
|
159
|
+
export function prepareCompletion(
|
|
160
|
+
value: unknown,
|
|
161
|
+
remainingOutputBytes: number,
|
|
162
|
+
maxOutputBytes: number = remainingOutputBytes,
|
|
163
|
+
): ProgramResult {
|
|
164
|
+
if (value === undefined) return {}
|
|
165
|
+
let snapshot: ReturnType<typeof snapshotPtcJsonValue>
|
|
166
|
+
try {
|
|
167
|
+
snapshot = snapshotPtcJsonValue(value)
|
|
168
|
+
} catch {
|
|
169
|
+
snapshot = undefined
|
|
170
|
+
}
|
|
171
|
+
if (snapshot === undefined) {
|
|
172
|
+
return prepareFailure(
|
|
173
|
+
'invalid-output',
|
|
174
|
+
'program completion must be lossless JSON',
|
|
175
|
+
remainingOutputBytes,
|
|
176
|
+
maxOutputBytes,
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
if (jsonValueBytesUpTo(snapshot, remainingOutputBytes) === undefined) {
|
|
180
|
+
return outputLimit(maxOutputBytes)
|
|
181
|
+
}
|
|
182
|
+
return { value: encodePtcJsonWire(snapshot) }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Build the fixed overflow fragment without carrying rejected variable bytes. */
|
|
186
|
+
function outputLimit(maxOutputBytes: number): ProgramResult {
|
|
187
|
+
return { error: { kind: 'output-limit', message: `outer output exceeded ${maxOutputBytes} bytes` } }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Admit one bounded failure message or replace it with the fixed overflow diagnostic. */
|
|
191
|
+
function prepareFailure(
|
|
192
|
+
kind: 'exception' | 'invalid-output',
|
|
193
|
+
message: string,
|
|
194
|
+
remainingOutputBytes: number,
|
|
195
|
+
maxOutputBytes: number,
|
|
196
|
+
): ProgramResult {
|
|
197
|
+
if (jsonStringBytesUpTo(message, remainingOutputBytes) === undefined) return outputLimit(maxOutputBytes)
|
|
198
|
+
return { error: { kind, message } }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Prepare a thrown program value, including cross-realm errors, without sending
|
|
203
|
+
* an unbounded stack or string across the process channel.
|
|
204
|
+
* @param error - the value thrown by the program.
|
|
205
|
+
* @param remainingOutputBytes - exact bytes left after captured logs.
|
|
206
|
+
* @param maxOutputBytes - the configured cap named in an overflow diagnostic.
|
|
207
|
+
* @returns a bounded exception or fixed output-limit fragment.
|
|
208
|
+
*/
|
|
209
|
+
export function prepareException(
|
|
210
|
+
error: unknown,
|
|
211
|
+
remainingOutputBytes: number,
|
|
212
|
+
maxOutputBytes: number = remainingOutputBytes,
|
|
213
|
+
): ProgramResult {
|
|
214
|
+
let message: string
|
|
215
|
+
try {
|
|
216
|
+
const detail: unknown = isNativeError(error) ? error.stack ?? error.message : error
|
|
217
|
+
message = typeof detail === 'string' ? detail : String(detail)
|
|
218
|
+
} catch {
|
|
219
|
+
message = 'program threw an unrenderable value'
|
|
220
|
+
}
|
|
221
|
+
return prepareFailure('exception', message, remainingOutputBytes, maxOutputBytes)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Constructor type for one program-visible binding rejection class. */
|
|
225
|
+
export type BindingErrorConstructor = new (memberName: string, message: string) => Error
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Materialize the real error constructor declared by one namespace.
|
|
229
|
+
* @param descriptor - program-global class name and member-name property.
|
|
230
|
+
* @returns the constructor injected into the program and used for rejections.
|
|
231
|
+
*/
|
|
232
|
+
export function makeBindingErrorClass(
|
|
233
|
+
descriptor: { name: string; memberNameProperty: string },
|
|
234
|
+
): BindingErrorConstructor {
|
|
235
|
+
return class BindingCallError extends CapturedError {
|
|
236
|
+
constructor(memberName: string, message: string) {
|
|
237
|
+
super(message)
|
|
238
|
+
defineBindingErrorField(this, 'name', descriptor.name)
|
|
239
|
+
defineBindingErrorField(this, descriptor.memberNameProperty, memberName)
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Create the namespace-specific rejection for one failed binding call. */
|
|
245
|
+
function bindingFailure(errorClass: BindingErrorConstructor | undefined, memberName: string, message: string): Error {
|
|
246
|
+
return errorClass ? new errorClass(memberName, message) : new CapturedError(message)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Build null-prototype binding globals with namespace-specific rejection classes.
|
|
251
|
+
* @param data - Namespace declarations injected into the program.
|
|
252
|
+
* @param host - Evaluation-scoped remote binding calls.
|
|
253
|
+
* @param errorClasses - Constructors shared with program globals, resolved per invocation.
|
|
254
|
+
* @returns One namespace object per declaration; arguments and results must be lossless JSON.
|
|
255
|
+
*/
|
|
256
|
+
export function makeNamespaces(
|
|
257
|
+
data: Pick<ProgramBootData, 'namespaces'>,
|
|
258
|
+
host: Pick<HostMethods, 'invoke'>,
|
|
259
|
+
errorClasses: Pick<ReadonlyMap<string, BindingErrorConstructor>, 'get'>,
|
|
260
|
+
): Record<string, unknown>[] {
|
|
261
|
+
return data.namespaces.map(({ global, names }) => {
|
|
262
|
+
const namespace = Object.create(null) as Record<string, unknown>
|
|
263
|
+
for (const name of names) {
|
|
264
|
+
Object.defineProperty(namespace, name, {
|
|
265
|
+
enumerable: true,
|
|
266
|
+
value: async (args: unknown): Promise<unknown> => {
|
|
267
|
+
const errorClass = errorClasses.get(global)
|
|
268
|
+
try {
|
|
269
|
+
let detached: ReturnType<typeof snapshotPtcJsonValue>
|
|
270
|
+
try { detached = snapshotPtcJsonValue(args) } catch {
|
|
271
|
+
// Model-defined getters can fail while arguments are detached.
|
|
272
|
+
detached = undefined
|
|
273
|
+
}
|
|
274
|
+
if (detached === undefined) throw new CapturedError('binding arguments must be lossless JSON')
|
|
275
|
+
const result = decodePtcJsonWire(await host.invoke(global, name, encodePtcJsonWire(detached)))
|
|
276
|
+
if (result === undefined) throw new CapturedError('binding resolution must be lossless JSON')
|
|
277
|
+
return result
|
|
278
|
+
} catch (error: unknown) {
|
|
279
|
+
throw bindingFailure(errorClass, name, error instanceof CapturedError ? error.message : String(error))
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
})
|
|
283
|
+
}
|
|
284
|
+
return namespace
|
|
285
|
+
})
|
|
286
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** Execution mode and resource limits for the Node PTC provider. */
|
|
2
|
+
import z from '@deepseek-ai/schemastery'
|
|
3
|
+
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
|
4
|
+
import type { LaunchConfig } from './launch.ts'
|
|
5
|
+
|
|
6
|
+
/** Deployment-varying runtime bounds and launch choices. */
|
|
7
|
+
export interface Config {
|
|
8
|
+
/** Worker invocation in the subprocess world; omitted selects the local carrier. */
|
|
9
|
+
launch?: LaunchConfig
|
|
10
|
+
/** per-call uses fresh async function bodies; vm-script uses VM contexts; persistent-in-memory retains a REPL per owner. */
|
|
11
|
+
executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script'
|
|
12
|
+
/** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */
|
|
13
|
+
scriptPersistence?: boolean
|
|
14
|
+
/** Default elapsed deadline, including nested tool and approval waits. */
|
|
15
|
+
timeoutMs?: number
|
|
16
|
+
/** Maximum numeric elapsed budget accepted by resolve. */
|
|
17
|
+
maxTimeoutMs?: number
|
|
18
|
+
/** Combined serialized logs, completion and diagnostic byte cap. */
|
|
19
|
+
maxOutputBytes?: number
|
|
20
|
+
/** V8 old-generation heap limit in MiB; native allocations are excluded. */
|
|
21
|
+
maxOldGenerationSizeMb?: number
|
|
22
|
+
/** Maximum control message, outstanding binding-argument and queued control-output bytes. */
|
|
23
|
+
maxMessageBytes?: number
|
|
24
|
+
/** Maximum simultaneous host binding calls accepted from a program. */
|
|
25
|
+
maxPendingCalls?: number
|
|
26
|
+
/** Time to wait for cooperative stop acknowledgment before terminating the process. */
|
|
27
|
+
stopGraceMs?: number
|
|
28
|
+
/** Managed process termination and output-drain grace in milliseconds. */
|
|
29
|
+
graceMs?: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Configuration after Loader defaults and executable selection. */
|
|
33
|
+
export type ResolvedConfig = Required<Config>
|
|
34
|
+
/** Loader defaults for the Node PTC provider. */
|
|
35
|
+
export const NodeConfig: z<Config> = z.object({
|
|
36
|
+
executionMode: z.union([z.const('per-call'), z.const('persistent-in-memory'), z.const('vm-script')]).default('per-call'),
|
|
37
|
+
scriptPersistence: z.boolean().default(false),
|
|
38
|
+
timeoutMs: z.number().default(120_000),
|
|
39
|
+
maxTimeoutMs: z.number().default(600_000),
|
|
40
|
+
maxOutputBytes: z.number().default(67_108_864),
|
|
41
|
+
maxOldGenerationSizeMb: z.number().default(512),
|
|
42
|
+
maxMessageBytes: z.number().default(134_217_728),
|
|
43
|
+
maxPendingCalls: z.number().default(128),
|
|
44
|
+
stopGraceMs: z.number().default(3_000),
|
|
45
|
+
graceMs: z.number().default(3_000),
|
|
46
|
+
launch: z.union([
|
|
47
|
+
z.object({ kind: z.const('node-script').required(), executable: z.string().required(), bootstrapPath: z.string() }),
|
|
48
|
+
z.object({ kind: z.const('embedded').required(), executable: z.string().required() }),
|
|
49
|
+
]),
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Validate resolved Node limits and paths.
|
|
54
|
+
* @param config - Loader-defaulted fields with the selected executable.
|
|
55
|
+
*/
|
|
56
|
+
export function validateConfig(config: ResolvedConfig): void {
|
|
57
|
+
if (config.scriptPersistence && config.executionMode !== 'vm-script') throw new Error('ptc-runtime-node: scriptPersistence requires executionMode: vm-script')
|
|
58
|
+
for (const [key, value] of Object.entries(config)) {
|
|
59
|
+
if (typeof value === 'number' && (!Number.isFinite(value) || value <= 0)) throw new Error(`ptc-runtime-node: ${key} must be positive and finite`)
|
|
60
|
+
}
|
|
61
|
+
for (const key of ['timeoutMs', 'maxTimeoutMs', 'graceMs', 'stopGraceMs'] as const) {
|
|
62
|
+
if (config[key] > MAX_TIMER_DELAY_MS) throw new Error(`ptc-runtime-node: ${key} exceeds the supported timer range`)
|
|
63
|
+
}
|
|
64
|
+
if (!Number.isSafeInteger(config.maxOutputBytes) || config.maxOutputBytes < 4) throw new Error('ptc-runtime-node: maxOutputBytes must be an integer of at least 4')
|
|
65
|
+
if (!Number.isSafeInteger(config.maxMessageBytes)) throw new Error('ptc-runtime-node: maxMessageBytes must be an integer')
|
|
66
|
+
if (!Number.isSafeInteger(config.maxPendingCalls)) throw new Error('ptc-runtime-node: maxPendingCalls must be an integer')
|
|
67
|
+
if (!Number.isSafeInteger(config.maxOldGenerationSizeMb)) throw new Error('ptc-runtime-node: maxOldGenerationSizeMb must be an integer')
|
|
68
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Pure configuration changes for Node PTC profile editors. */
|
|
2
|
+
import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime'
|
|
3
|
+
import type { Config } from './config.ts'
|
|
4
|
+
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Select retained Node execution while preserving Script syntax.
|
|
8
|
+
* @param programFormat - Effective syntax; omission uses the Node provider's default function-body syntax.
|
|
9
|
+
* @returns Both execution settings to merge into the profile atomically; function bodies switch to the retained REPL.
|
|
10
|
+
*/
|
|
11
|
+
export function resolvePersistentExecution(programFormat: PtcProgramFormat = 'function-body'): Pick<Required<Config>, 'executionMode' | 'scriptPersistence'> {
|
|
12
|
+
switch (programFormat) {
|
|
13
|
+
case 'script': return { executionMode: 'vm-script', scriptPersistence: true }
|
|
14
|
+
case 'function-body':
|
|
15
|
+
case 'repl': return { executionMode: 'persistent-in-memory', scriptPersistence: false }
|
|
16
|
+
/* v8 ignore next -- The runtime supplies the closed, typed program-format union. */
|
|
17
|
+
default: return assertNever(programFormat)
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Startup variables required by native executables before model evaluation. */
|
|
2
|
+
import { syncBuiltinESMExports } from 'node:module'
|
|
3
|
+
|
|
4
|
+
/** Native executable search, Windows system paths, and sandbox temporary paths retained in the OS environment. */
|
|
5
|
+
export const STARTUP_ENVIRONMENT_NAMES: ReadonlySet<string> = new Set(['PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR', 'TEMP', 'TMP'])
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Clear inherited credentials while preserving native child-process startup paths.
|
|
9
|
+
* With the native child process, preloaded node:process exports observe the replacement.
|
|
10
|
+
* Isolated state objects only replace their own environment; they do not replace the native process.
|
|
11
|
+
* @param state - Native child process in production, or isolated state in in-process tests.
|
|
12
|
+
*/
|
|
13
|
+
export function clearProgramEnvironment(state: { env: NodeJS.ProcessEnv }): void {
|
|
14
|
+
for (const key of Object.keys(state.env)) {
|
|
15
|
+
if (!STARTUP_ENVIRONMENT_NAMES.has(key.toUpperCase())) Reflect.deleteProperty(state.env, key)
|
|
16
|
+
}
|
|
17
|
+
state.env = Object.create(null) as NodeJS.ProcessEnv
|
|
18
|
+
syncBuiltinESMExports()
|
|
19
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Strict async-function-body evaluation with host bindings as parameters. */
|
|
2
|
+
import { resolve } from 'node:path'
|
|
3
|
+
import { compileFunction, constants } from 'node:vm'
|
|
4
|
+
import { ModuleHooksImportLoader } from '../imports/module-hooks.ts'
|
|
5
|
+
import type { ProgramEvaluator, ProgramEvaluatorOptions } from './types.ts'
|
|
6
|
+
|
|
7
|
+
type AsyncProgram = (...args: unknown[]) => Promise<unknown>
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Create an evaluator whose function-local declarations end with each call.
|
|
11
|
+
* @param options - Runner diagnostics and optional synchronous import handling.
|
|
12
|
+
* @returns Binding globals, asynchronous evaluation and resource cleanup.
|
|
13
|
+
*/
|
|
14
|
+
export function createAsyncFunctionEvaluator(options: ProgramEvaluatorOptions): ProgramEvaluator {
|
|
15
|
+
const globals = Object.create(null) as Record<string, unknown>
|
|
16
|
+
const imports = options.importHandler === undefined ? undefined : new ModuleHooksImportLoader(options.importHandler)
|
|
17
|
+
let closed = false
|
|
18
|
+
return {
|
|
19
|
+
globals,
|
|
20
|
+
evaluate(code, finish) {
|
|
21
|
+
if (closed) throw new Error('PTC evaluator is closed')
|
|
22
|
+
/* v8 ignore next -- The arrow supplies the intrinsic constructor and is never invoked. */
|
|
23
|
+
const AsyncFunction = (async () => {}).constructor as new (...args: string[]) => AsyncProgram
|
|
24
|
+
const body = `'use strict';\n${code}`
|
|
25
|
+
let fn: AsyncProgram
|
|
26
|
+
if (imports === undefined) fn = new AsyncFunction(...Object.keys(globals), body)
|
|
27
|
+
else {
|
|
28
|
+
const sourceUrl = imports.forFile(resolve(process.cwd(), 'ptc-program.js'))
|
|
29
|
+
const factory = compileFunction('return new (async () => {}).constructor(...args)', ['args'], {
|
|
30
|
+
filename: sourceUrl, importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
|
|
31
|
+
}) as (args: string[]) => AsyncProgram
|
|
32
|
+
// V8 caches constructor bodies across callers; each evaluator and filename needs a distinct source URL.
|
|
33
|
+
fn = factory([...Object.keys(globals), `${body}\n//# sourceURL=${sourceUrl}`])
|
|
34
|
+
}
|
|
35
|
+
void fn(...Object.values(globals)).then(
|
|
36
|
+
(value) => { finish({ ok: true, value }) },
|
|
37
|
+
(error: unknown) => { finish({ ok: false, error }) },
|
|
38
|
+
)
|
|
39
|
+
},
|
|
40
|
+
close() { closed = true; imports?.close() },
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Select one child evaluator without process-lifetime policy. */
|
|
2
|
+
import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime'
|
|
3
|
+
import { createAsyncFunctionEvaluator } from './async-function.ts'
|
|
4
|
+
import { createReplEvaluator } from './repl.ts'
|
|
5
|
+
import { createVmScriptEvaluator } from './vm-script.ts'
|
|
6
|
+
import type { ProgramEvaluator, ProgramEvaluatorOptions, ProgramImportHandler } from './types.ts'
|
|
7
|
+
|
|
8
|
+
const evaluators: Record<PtcProgramFormat, (options: ProgramEvaluatorOptions) => ProgramEvaluator> = {
|
|
9
|
+
'function-body': createAsyncFunctionEvaluator,
|
|
10
|
+
repl: createReplEvaluator,
|
|
11
|
+
script: createVmScriptEvaluator,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Create the selected evaluator for either a fresh or retained process.
|
|
16
|
+
* @param format - Evaluation syntax selected by the host.
|
|
17
|
+
* @param reportError - Asynchronous diagnostics attributed to the active evaluation.
|
|
18
|
+
* @param importHandler - Runner-local import handling; omission uses Node's loader.
|
|
19
|
+
* @returns Globals, evaluation entry point, and resource cleanup.
|
|
20
|
+
*/
|
|
21
|
+
export function createProgramEvaluator(
|
|
22
|
+
format: PtcProgramFormat, reportError: (message: string) => void, importHandler?: ProgramImportHandler,
|
|
23
|
+
): ProgramEvaluator {
|
|
24
|
+
return evaluators[format]({ reportError, ...importHandler === undefined ? {} : { importHandler } })
|
|
25
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** Node REPL evaluation with declarations retained in its context. */
|
|
2
|
+
import { start } from 'node:repl'
|
|
3
|
+
import { resolve } from 'node:path'
|
|
4
|
+
import { PassThrough, Writable } from 'node:stream'
|
|
5
|
+
import { ModuleHooksImportLoader } from '../imports/module-hooks.ts'
|
|
6
|
+
import type { ProgramEvaluator, ProgramEvaluatorOptions } from './types.ts'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Create a REPL whose globals survive sequential evaluations until close.
|
|
10
|
+
* @param options - Runner diagnostics and optional synchronous import handling.
|
|
11
|
+
* @returns Retained globals, asynchronous evaluation and REPL cleanup.
|
|
12
|
+
*/
|
|
13
|
+
export function createReplEvaluator(options: ProgramEvaluatorOptions): ProgramEvaluator {
|
|
14
|
+
const imports = options.importHandler === undefined ? undefined : new ModuleHooksImportLoader(options.importHandler)
|
|
15
|
+
const input = new PassThrough()
|
|
16
|
+
const output = new Writable({ write(chunk: Buffer, _encoding, callback) {
|
|
17
|
+
const message = chunk.toString().trim()
|
|
18
|
+
if (message) options.reportError(message)
|
|
19
|
+
callback()
|
|
20
|
+
} })
|
|
21
|
+
const repl = start({ input, output, terminal: false, prompt: '', useGlobal: false, ignoreUndefined: true })
|
|
22
|
+
// Interactive result setters print notices; program assignments use ordinary retained globals.
|
|
23
|
+
for (const name of ['_', '_error']) {
|
|
24
|
+
Object.defineProperty(repl.context, name, { configurable: true, enumerable: true, writable: true, value: undefined })
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
globals: repl.context,
|
|
28
|
+
evaluate(code, finish) {
|
|
29
|
+
// Node's REPL treats a leading brace as an object expression before transforming await.
|
|
30
|
+
const program = code.trimStart().startsWith('{') ? `;${code}` : code
|
|
31
|
+
const evaluate = (): void => {
|
|
32
|
+
repl.eval(`${program}\n`, repl.context, 'ptc-repl', (error: Error | null, value: unknown) => {
|
|
33
|
+
finish(error ? { ok: false, error } : { ok: true, value })
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
if (imports === undefined) evaluate()
|
|
37
|
+
else imports.runRepl(resolve(process.cwd(), 'ptc-program.js'), evaluate)
|
|
38
|
+
},
|
|
39
|
+
close() {
|
|
40
|
+
imports?.close()
|
|
41
|
+
repl.close()
|
|
42
|
+
input.destroy()
|
|
43
|
+
output.destroy()
|
|
44
|
+
},
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Evaluation results and operations shared by the three child evaluators. */
|
|
2
|
+
|
|
3
|
+
/** An import requested by a program or its VM-loaded ESM dependencies in the runner process. */
|
|
4
|
+
export interface ProgramImportRequest {
|
|
5
|
+
/** Specifier after JavaScript's import argument conversion. */
|
|
6
|
+
specifier: string
|
|
7
|
+
/** Absolute filename containing this import, retained with the importing program or module. */
|
|
8
|
+
referrer: string
|
|
9
|
+
/** Import attributes supplied by the program, or an empty object. */
|
|
10
|
+
attributes: Readonly<Record<string, string | undefined>>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Runner-owned handling of one import. */
|
|
14
|
+
export type ProgramImportResult =
|
|
15
|
+
| { type: 'default' }
|
|
16
|
+
| { type: 'redirect'; specifier: string }
|
|
17
|
+
| {
|
|
18
|
+
type: 'module'
|
|
19
|
+
/**
|
|
20
|
+
* Own enumerable string properties become exports, including `default`.
|
|
21
|
+
* Values stay in this process and retain their identity, prototypes and closures.
|
|
22
|
+
* One exports object identifies one module per evaluator; names and values are read once.
|
|
23
|
+
*/
|
|
24
|
+
exports: Record<string, unknown>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Intercept program imports inside the runner, independently of evaluation syntax.
|
|
29
|
+
* VM Script recursively loads .mjs files and .js files in type: module packages in its context.
|
|
30
|
+
* Their static and dynamic imports also consult the handler; each static request binds once.
|
|
31
|
+
* Default and redirect use Node's active resolution conditions relative to the importer; replacements do not reenter the handler.
|
|
32
|
+
* Other formats, AsyncFunction and Node REPL use Node's loader without intercepting dependencies.
|
|
33
|
+
* A thrown or rejected value rejects the program's import; there is no fallback after failure.
|
|
34
|
+
* VM Script accepts async handlers and requires --experimental-vm-modules.
|
|
35
|
+
* AsyncFunction and Node REPL require synchronous decisions and no VM startup flag.
|
|
36
|
+
* @param request - Specifier, importing filename and import attributes.
|
|
37
|
+
* @returns Default loading, one redirect, or runner-local module exports.
|
|
38
|
+
*/
|
|
39
|
+
export type ProgramImportHandler = (request: ProgramImportRequest) => ProgramImportResult | Promise<ProgramImportResult>
|
|
40
|
+
|
|
41
|
+
/** Runner capabilities supplied to every evaluator. */
|
|
42
|
+
export interface ProgramEvaluatorOptions {
|
|
43
|
+
/** Asynchronous diagnostics attributed to the active evaluation. */
|
|
44
|
+
reportError: (message: string) => void
|
|
45
|
+
/** Omission uses native imports; AsyncFunction and Node REPL require synchronous decisions. */
|
|
46
|
+
importHandler?: ProgramImportHandler
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** One evaluation's completion or thrown value. */
|
|
50
|
+
type EvaluationResult = { ok: true; value: unknown } | { ok: false; error: unknown }
|
|
51
|
+
|
|
52
|
+
/** Program globals and resources owned by one evaluator. */
|
|
53
|
+
export interface ProgramEvaluator {
|
|
54
|
+
/** Mutable globals populated with the current evaluation's bindings. */
|
|
55
|
+
globals: Record<string, unknown>
|
|
56
|
+
/**
|
|
57
|
+
* Evaluate source and deliver its result after any supported asynchronous work.
|
|
58
|
+
* @param code - Type-stripped program in the selected syntax.
|
|
59
|
+
* @param finish - Callback receiving the completion or exception.
|
|
60
|
+
*/
|
|
61
|
+
evaluate(code: string, finish: (result: EvaluationResult) => void): void
|
|
62
|
+
/** Release evaluator-owned resources after evaluation or process shutdown. */
|
|
63
|
+
close(): void
|
|
64
|
+
}
|