@deepseek-ai/dsh-ptc-runtime-node 0.2.2-rc.1 → 0.2.2-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +19 -16
- package/README.md +36 -10
- package/README.zh.md +36 -10
- package/lib/index.js +102 -63
- package/lib/persistent-process.js +528 -112
- package/lib/process.js +523 -109
- package/lib/types/bindings.d.ts.map +1 -0
- package/lib/types/bindings.js.map +1 -0
- package/lib/types/bootstrap.d.ts.map +1 -0
- package/lib/types/bootstrap.js.map +1 -0
- package/lib/types/config.d.ts +2 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/configuration.d.ts.map +1 -0
- package/lib/types/configuration.js.map +1 -0
- package/lib/types/environment.d.ts +3 -2
- package/lib/types/environment.d.ts.map +1 -0
- package/lib/types/environment.js.map +1 -0
- package/lib/types/evaluators/async-function.d.ts +3 -3
- package/lib/types/evaluators/async-function.d.ts.map +1 -0
- package/lib/types/evaluators/async-function.js.map +1 -0
- package/lib/types/evaluators/index.d.ts +3 -2
- package/lib/types/evaluators/index.d.ts.map +1 -0
- package/lib/types/evaluators/index.js.map +1 -0
- package/lib/types/evaluators/repl.d.ts +3 -3
- package/lib/types/evaluators/repl.d.ts.map +1 -0
- package/lib/types/evaluators/repl.js.map +1 -0
- package/lib/types/evaluators/types.d.ts +44 -0
- package/lib/types/evaluators/types.d.ts.map +1 -0
- package/lib/types/evaluators/types.js.map +1 -0
- package/lib/types/evaluators/vm-script-await.d.ts.map +1 -0
- package/lib/types/evaluators/vm-script-await.js.map +1 -0
- package/lib/types/evaluators/vm-script.d.ts +3 -2
- package/lib/types/evaluators/vm-script.d.ts.map +1 -0
- package/lib/types/evaluators/vm-script.js.map +1 -0
- package/lib/types/execution.d.ts.map +1 -0
- package/lib/types/execution.js.map +1 -0
- package/lib/types/imports/evaluation-ended.d.ts +7 -0
- package/lib/types/imports/evaluation-ended.d.ts.map +1 -0
- package/lib/types/imports/evaluation-ended.js.map +1 -0
- package/lib/types/imports/module-hooks.d.ts +37 -0
- package/lib/types/imports/module-hooks.d.ts.map +1 -0
- package/lib/types/imports/module-hooks.js.map +1 -0
- package/lib/types/imports/vm-modules.d.ts +35 -0
- package/lib/types/imports/vm-modules.d.ts.map +1 -0
- package/lib/types/imports/vm-modules.js.map +1 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/json-wire.d.ts.map +1 -0
- package/lib/types/json-wire.js.map +1 -0
- package/lib/types/launch.d.ts +1 -2
- package/lib/types/launch.d.ts.map +1 -0
- package/lib/types/launch.js.map +1 -0
- package/lib/types/output-json.d.ts.map +1 -0
- package/lib/types/output-json.js.map +1 -0
- package/lib/types/output-ledger.d.ts.map +1 -0
- package/lib/types/output-ledger.js.map +1 -0
- package/lib/types/output-stream.d.ts.map +1 -0
- package/lib/types/output-stream.js.map +1 -0
- package/lib/types/persistent-process-entry.d.ts.map +1 -0
- package/lib/types/persistent-process-entry.js.map +1 -0
- package/lib/types/persistent-process.d.ts +6 -2
- package/lib/types/persistent-process.d.ts.map +1 -0
- package/lib/types/persistent-process.js.map +1 -0
- package/lib/types/policy-processes.d.ts.map +1 -0
- package/lib/types/policy-processes.js.map +1 -0
- package/lib/types/process-entry.d.ts.map +1 -0
- package/lib/types/process-entry.js.map +1 -0
- package/lib/types/process.d.ts +4 -2
- package/lib/types/process.d.ts.map +1 -0
- package/lib/types/process.js.map +1 -0
- package/lib/types/protocol.d.ts +10 -3
- package/lib/types/protocol.d.ts.map +1 -0
- package/lib/types/protocol.js.map +1 -0
- package/lib/types/rpc.d.ts.map +1 -0
- package/lib/types/rpc.js.map +1 -0
- package/lib/types/worker.d.ts +5 -3
- package/lib/types/worker.d.ts.map +1 -0
- package/lib/types/worker.js.map +1 -0
- package/package.json +24 -21
- package/src/bindings.ts +66 -0
- package/src/bootstrap.ts +286 -0
- package/src/config.ts +68 -0
- package/src/configuration.ts +19 -0
- package/src/environment.ts +19 -0
- package/src/evaluators/async-function.ts +42 -0
- package/src/evaluators/index.ts +25 -0
- package/src/evaluators/repl.ts +46 -0
- package/src/evaluators/types.ts +64 -0
- package/src/evaluators/vm-script-await.ts +290 -0
- package/src/evaluators/vm-script.ts +83 -0
- package/src/execution.ts +171 -0
- package/src/imports/evaluation-ended.ts +11 -0
- package/src/imports/module-hooks.ts +125 -0
- package/src/imports/vm-modules.ts +233 -0
- package/src/index.ts +104 -0
- package/src/json-wire.ts +420 -0
- package/src/launch.ts +71 -0
- package/src/output-json.ts +179 -0
- package/src/output-ledger.ts +66 -0
- package/src/output-stream.ts +50 -0
- package/src/persistent-process-entry.ts +5 -0
- package/src/persistent-process.ts +22 -0
- package/src/policy-processes.ts +79 -0
- package/src/process-entry.ts +5 -0
- package/src/process.ts +167 -0
- package/src/protocol.ts +89 -0
- package/src/rpc.ts +88 -0
- package/src/worker.ts +381 -0
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node REPL top-level-await transformation adapted for complete Script submissions.
|
|
3
|
+
* Source: Node.js v26.6.0, lib/internal/repl/await.js:
|
|
4
|
+
* https://github.com/nodejs/node/blob/v26.6.0/lib/internal/repl/await.js
|
|
5
|
+
* Uses public Acorn and acorn-walk; incomplete input is a SyntaxError.
|
|
6
|
+
*/
|
|
7
|
+
/*! @license
|
|
8
|
+
* Copyright Node.js contributors. All rights reserved.
|
|
9
|
+
*
|
|
10
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
* of this software and associated documentation files (the "Software"), to
|
|
12
|
+
* deal in the Software without restriction, including without limitation the
|
|
13
|
+
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
|
14
|
+
* sell copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
* furnished to do so, subject to the following conditions:
|
|
16
|
+
*
|
|
17
|
+
* The above copyright notice and this permission notice shall be included in
|
|
18
|
+
* all copies or substantial portions of the Software.
|
|
19
|
+
*
|
|
20
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
25
|
+
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
|
26
|
+
* IN THE SOFTWARE.
|
|
27
|
+
*/
|
|
28
|
+
import { Parser } from 'acorn'
|
|
29
|
+
import type { AnyNode, BlockStatement, ExpressionStatement, Identifier, Pattern, Position, Program, Statement, VariableDeclarator } from 'acorn'
|
|
30
|
+
import * as walk from 'acorn-walk'
|
|
31
|
+
|
|
32
|
+
interface TransformState {
|
|
33
|
+
body: BlockStatement
|
|
34
|
+
ancestors: AnyNode[]
|
|
35
|
+
hoistedDeclarationStatements: string[]
|
|
36
|
+
replace(from: number, to: number, str: string): void
|
|
37
|
+
prepend(node: AnyNode, str: string): void
|
|
38
|
+
append(node: AnyNode, str: string): void
|
|
39
|
+
containsAwait: boolean
|
|
40
|
+
containsReturn: boolean
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isTopLevelDeclaration(state: TransformState): boolean {
|
|
44
|
+
return state.ancestors[state.ancestors.length - 2] === state.body
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const noop = (): void => {}
|
|
48
|
+
const base = walk.base as Required<walk.RecursiveVisitors<TransformState>>
|
|
49
|
+
const visitorsWithoutAncestors: walk.RecursiveVisitors<TransformState> = {
|
|
50
|
+
ClassDeclaration(node, state, c) {
|
|
51
|
+
// Anonymous declarations are invalid inside the parsed async body.
|
|
52
|
+
const name = (node.id as Identifier).name
|
|
53
|
+
if (isTopLevelDeclaration(state)) {
|
|
54
|
+
state.prepend(node, `${name}=`)
|
|
55
|
+
state.hoistedDeclarationStatements.push(`let ${name}; `)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
base.ClassDeclaration(node, state, c)
|
|
59
|
+
},
|
|
60
|
+
ForOfStatement(node, state, c) {
|
|
61
|
+
if (node.await) {
|
|
62
|
+
state.containsAwait = true
|
|
63
|
+
}
|
|
64
|
+
base.ForOfStatement(node, state, c)
|
|
65
|
+
},
|
|
66
|
+
FunctionDeclaration(node, state) {
|
|
67
|
+
// Anonymous declarations are invalid inside the parsed async body.
|
|
68
|
+
const name = (node.id as Identifier).name
|
|
69
|
+
state.prepend(node, `this.${name} = ${name}; `)
|
|
70
|
+
state.hoistedDeclarationStatements.push(`var ${name}; `)
|
|
71
|
+
},
|
|
72
|
+
FunctionExpression: noop,
|
|
73
|
+
ArrowFunctionExpression: noop,
|
|
74
|
+
MethodDefinition(node, state, c) {
|
|
75
|
+
// Computed keys execute while the class is defined; method bodies do not.
|
|
76
|
+
if (node.computed) c(node.key, state)
|
|
77
|
+
},
|
|
78
|
+
StaticBlock: noop,
|
|
79
|
+
AwaitExpression(node, state, c) {
|
|
80
|
+
state.containsAwait = true
|
|
81
|
+
base.AwaitExpression(node, state, c)
|
|
82
|
+
},
|
|
83
|
+
ReturnStatement(node, state, c) {
|
|
84
|
+
state.containsReturn = true
|
|
85
|
+
base.ReturnStatement(node, state, c)
|
|
86
|
+
},
|
|
87
|
+
VariableDeclaration(node, state, c) {
|
|
88
|
+
const variableKind = node.kind
|
|
89
|
+
if (variableKind === 'await using') state.containsAwait = true
|
|
90
|
+
const parent = state.ancestors[state.ancestors.length - 2]
|
|
91
|
+
const isIterableForDeclaration = parent !== undefined && ['ForOfStatement', 'ForInStatement'].includes(parent.type)
|
|
92
|
+
|
|
93
|
+
if (variableKind === 'var' || isTopLevelDeclaration(state)) {
|
|
94
|
+
// Disposable bindings cannot outlive the async body's disposal scope.
|
|
95
|
+
if (variableKind === 'using' || variableKind === 'await using') {
|
|
96
|
+
throw new SyntaxError('Put using declarations inside a block; Script evaluations do not retain disposable bindings')
|
|
97
|
+
}
|
|
98
|
+
state.replace(
|
|
99
|
+
node.start,
|
|
100
|
+
node.start + variableKind.length,
|
|
101
|
+
variableKind === 'var' && isIterableForDeclaration
|
|
102
|
+
? ''
|
|
103
|
+
: 'void' + (node.declarations.length === 1 ? '' : ' ('),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
if (!isIterableForDeclaration) {
|
|
107
|
+
node.declarations.forEach((decl) => {
|
|
108
|
+
state.prepend(decl, '(')
|
|
109
|
+
state.append(decl, decl.init ? ')' : '=undefined)')
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
if (node.declarations.length !== 1) {
|
|
113
|
+
state.append(node.declarations[node.declarations.length - 1] as VariableDeclarator, ')')
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const variableIdentifiersToHoist: [['var', string[]], ['let', string[]]] = [
|
|
118
|
+
['var', []],
|
|
119
|
+
['let', []],
|
|
120
|
+
]
|
|
121
|
+
function registerVariableDeclarationIdentifiers(node: Pattern): void {
|
|
122
|
+
switch (node.type) {
|
|
123
|
+
case 'Identifier':
|
|
124
|
+
variableIdentifiersToHoist[variableKind === 'var' ? 0 : 1][1].push(node.name)
|
|
125
|
+
break
|
|
126
|
+
case 'ObjectPattern':
|
|
127
|
+
node.properties.forEach((property) => {
|
|
128
|
+
registerVariableDeclarationIdentifiers(property.type === 'RestElement' ? property.argument : property.value)
|
|
129
|
+
})
|
|
130
|
+
break
|
|
131
|
+
case 'ArrayPattern':
|
|
132
|
+
node.elements.forEach((element) => {
|
|
133
|
+
if (element) registerVariableDeclarationIdentifiers(element)
|
|
134
|
+
})
|
|
135
|
+
break
|
|
136
|
+
// Acorn exposes defaults and rest elements as separate binding nodes.
|
|
137
|
+
case 'AssignmentPattern':
|
|
138
|
+
registerVariableDeclarationIdentifiers(node.left)
|
|
139
|
+
break
|
|
140
|
+
case 'RestElement':
|
|
141
|
+
registerVariableDeclarationIdentifiers(node.argument)
|
|
142
|
+
break
|
|
143
|
+
/* v8 ignore next 4 -- Acorn declaration bindings exclude member targets and other node tags. */
|
|
144
|
+
case 'MemberExpression':
|
|
145
|
+
throw new SyntaxError('A declaration cannot bind a member expression')
|
|
146
|
+
/* v8 ignore next -- The parsed Pattern union is exhaustive above. */
|
|
147
|
+
default: return assertNever(node)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
node.declarations.forEach((decl) => {
|
|
152
|
+
registerVariableDeclarationIdentifiers(decl.id)
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
variableIdentifiersToHoist.forEach(({ 0: kind, 1: identifiers }) => {
|
|
156
|
+
if (identifiers.length > 0) {
|
|
157
|
+
state.hoistedDeclarationStatements.push(`${kind} ${identifiers.join(', ')}; `)
|
|
158
|
+
}
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
base.VariableDeclaration(node, state, c)
|
|
163
|
+
},
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
type Visitor = (node: AnyNode, state: TransformState, c: walk.WalkerCallback<TransformState>) => void
|
|
167
|
+
const visitors: walk.RecursiveVisitors<TransformState> = Object.fromEntries(
|
|
168
|
+
Object.entries({ ...base, ...visitorsWithoutAncestors }).map(([type, visitor]) => {
|
|
169
|
+
// acorn-walk selects the callback by the matching node or aggregate type.
|
|
170
|
+
const callback = visitor as Visitor
|
|
171
|
+
const withAncestors: Visitor = (node, state, c) => {
|
|
172
|
+
const isNew = node !== state.ancestors[state.ancestors.length - 1]
|
|
173
|
+
if (isNew) state.ancestors.push(node)
|
|
174
|
+
callback(node, state, c)
|
|
175
|
+
if (isNew) state.ancestors.pop()
|
|
176
|
+
}
|
|
177
|
+
return [type, withAncestors]
|
|
178
|
+
}),
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
/** Keep the native-Node bootstrap independent of workspace packages' built exports. */
|
|
182
|
+
/* v8 ignore next 3 -- Exhaustive declaration-tag assertion; parsed bindings cannot reach it. */
|
|
183
|
+
function assertNever(value: never): never {
|
|
184
|
+
throw new Error(`Unexpected declaration pattern: ${String(value)}`)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Transform top-level await using Node's retained-declaration and boxed-result convention.
|
|
189
|
+
* @param src - Type-stripped JavaScript ending in a newline, with any hashbang removed.
|
|
190
|
+
* @returns Transformed source yielding undefined or { value }, or null when native errors apply.
|
|
191
|
+
* @throws SyntaxError for invalid syntax or unsupported top-level disposable bindings.
|
|
192
|
+
*/
|
|
193
|
+
export function processTopLevelAwait(src: string): string | null {
|
|
194
|
+
const wrapPrefix = '(async () => { '
|
|
195
|
+
const wrapped = `${wrapPrefix}${src} })()`
|
|
196
|
+
const wrappedArray = wrapped.split('')
|
|
197
|
+
let root: Program
|
|
198
|
+
try {
|
|
199
|
+
root = Parser.parse(wrapped, { ecmaVersion: 'latest' })
|
|
200
|
+
} catch (error: unknown) {
|
|
201
|
+
if (!(error instanceof SyntaxError)) throw error
|
|
202
|
+
// Acorn syntax errors include offsets and positions; batches cannot request more REPL input.
|
|
203
|
+
const e = error as SyntaxError & { pos: number; loc: Position }
|
|
204
|
+
// If the parse error is before the first "await", then use the execution
|
|
205
|
+
// error. Otherwise we must emit this parse error, making it look like a
|
|
206
|
+
// proper syntax error.
|
|
207
|
+
const awaitPos = src.indexOf('await')
|
|
208
|
+
const errPos = e.pos - wrapPrefix.length
|
|
209
|
+
if (awaitPos > errPos) return null
|
|
210
|
+
// Convert keyword parse errors on await into their original errors when
|
|
211
|
+
// possible.
|
|
212
|
+
if (errPos === awaitPos + 6 && e.message.includes('Expecting Unicode escape sequence')) return null
|
|
213
|
+
if (errPos === awaitPos + 7 && e.message.includes('Unexpected token')) return null
|
|
214
|
+
const line = e.loc.line
|
|
215
|
+
const column = line === 1 ? e.loc.column - wrapPrefix.length : e.loc.column
|
|
216
|
+
let message = '\n' + (src.split('\n', line)[line - 1] as string) + '\n'
|
|
217
|
+
+ ' '.repeat(column) + '^\n\n' + e.message.replace(/ \([^)]+\)/, '')
|
|
218
|
+
// V8 unexpected token errors include the token string.
|
|
219
|
+
if (message.endsWith('Unexpected token')) {
|
|
220
|
+
message += " '"
|
|
221
|
+
// Wrapper end may cause acorn to report error position after the source
|
|
222
|
+
+ ((src[e.pos - wrapPrefix.length] ?? src[src.length - 1]) as string) + "'"
|
|
223
|
+
}
|
|
224
|
+
throw new SyntaxError(message)
|
|
225
|
+
}
|
|
226
|
+
// The fixed prefix starts an expression statement and an arrow with a block body.
|
|
227
|
+
const expression = (root.body[0] as ExpressionStatement).expression
|
|
228
|
+
if (expression.type !== 'CallExpression' || expression.callee.type !== 'ArrowFunctionExpression') return null
|
|
229
|
+
const body = expression.callee.body as BlockStatement
|
|
230
|
+
const state: TransformState = {
|
|
231
|
+
body,
|
|
232
|
+
ancestors: [],
|
|
233
|
+
hoistedDeclarationStatements: [],
|
|
234
|
+
replace(from, to, str) {
|
|
235
|
+
for (let i = from; i < to; i++) {
|
|
236
|
+
wrappedArray[i] = ''
|
|
237
|
+
}
|
|
238
|
+
wrappedArray[from] = str
|
|
239
|
+
},
|
|
240
|
+
prepend(node, str) {
|
|
241
|
+
wrappedArray[node.start] = str + (wrappedArray[node.start] as string)
|
|
242
|
+
},
|
|
243
|
+
append(node, str) {
|
|
244
|
+
wrappedArray[node.end - 1] = (wrappedArray[node.end - 1] as string) + str
|
|
245
|
+
},
|
|
246
|
+
containsAwait: false,
|
|
247
|
+
containsReturn: false,
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
walk.recursive(body, state, visitors)
|
|
251
|
+
|
|
252
|
+
// Do not transform if
|
|
253
|
+
// 1. False alarm: there isn't actually an await expression.
|
|
254
|
+
// 2. There is a top-level return, which is not allowed.
|
|
255
|
+
if (!state.containsAwait || state.containsReturn) {
|
|
256
|
+
return null
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
for (let i = body.body.length - 1; i >= 0; i--) {
|
|
260
|
+
const node = body.body[i] as Statement
|
|
261
|
+
if (node.type === 'EmptyStatement') continue
|
|
262
|
+
if (node.type === 'ExpressionStatement') {
|
|
263
|
+
// For an expression statement of the form
|
|
264
|
+
// ( expr ) ;
|
|
265
|
+
// ^^^^^^^^^^ // node
|
|
266
|
+
// ^^^^ // node.expression
|
|
267
|
+
//
|
|
268
|
+
// We do not want the left parenthesis before the `return` keyword;
|
|
269
|
+
// therefore we prepend the `return (` to `node`.
|
|
270
|
+
//
|
|
271
|
+
// On the other hand, we do not want the right parenthesis after the
|
|
272
|
+
// semicolon. Since there can only be more right parentheses between
|
|
273
|
+
// node.expression.end and the semicolon, appending one more to
|
|
274
|
+
// node.expression should be fine.
|
|
275
|
+
//
|
|
276
|
+
// We also create a wrapper object around the result of the expression.
|
|
277
|
+
// Consider an expression of the form `(await x).y`. If we just return
|
|
278
|
+
// this expression from an async function, the caller will await `y`, too,
|
|
279
|
+
// if it evaluates to a Promise. Instead, we return
|
|
280
|
+
// `{ value: ((await x).y) }`, which allows the caller to retrieve the
|
|
281
|
+
// awaited value correctly.
|
|
282
|
+
state.prepend(node.expression, '{ value: (')
|
|
283
|
+
state.prepend(node, 'return ')
|
|
284
|
+
state.append(node.expression, ') }')
|
|
285
|
+
}
|
|
286
|
+
break
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return state.hoistedDeclarationStatements.join('') + wrappedArray.join('')
|
|
290
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/** VM Script evaluation with Node globals and retained Script-scope declarations. */
|
|
2
|
+
import { resolve } from 'node:path'
|
|
3
|
+
import { constants, createContext, Script, type Context, type ScriptOptions } from 'node:vm'
|
|
4
|
+
import { VmModuleImportLoader } from '../imports/vm-modules.ts'
|
|
5
|
+
import { processTopLevelAwait } from './vm-script-await.ts'
|
|
6
|
+
import type { ProgramEvaluator, ProgramEvaluatorOptions } from './types.ts'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Create a VM context supporting Script completion values and top-level await.
|
|
10
|
+
* @param options - Runner diagnostics and optional import handling.
|
|
11
|
+
* @returns Retained globals, asynchronous evaluation and resource cleanup.
|
|
12
|
+
*/
|
|
13
|
+
export function createVmScriptEvaluator(options: ProgramEvaluatorOptions): ProgramEvaluator {
|
|
14
|
+
const context = createScriptContext()
|
|
15
|
+
const imports = options.importHandler === undefined ? undefined : new VmModuleImportLoader(options.importHandler, context)
|
|
16
|
+
return {
|
|
17
|
+
globals: context,
|
|
18
|
+
evaluate(code, finish) {
|
|
19
|
+
void evaluateScript(code, context, imports).then(
|
|
20
|
+
(value) => { finish({ ok: true, value }) },
|
|
21
|
+
(error: unknown) => { finish({ ok: false, error }) },
|
|
22
|
+
)
|
|
23
|
+
},
|
|
24
|
+
close() { imports?.close() },
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Create an independent program context with Node globals.
|
|
30
|
+
* @returns A context reusable for sequential evaluations.
|
|
31
|
+
*/
|
|
32
|
+
function createScriptContext(): Context {
|
|
33
|
+
const globals = Object.create(null) as Record<string, unknown>
|
|
34
|
+
const context = createContext(globals)
|
|
35
|
+
const realm = new Script('globalThis').runInContext(context) as Record<string, unknown>
|
|
36
|
+
for (const key of Reflect.ownKeys(globalThis)) {
|
|
37
|
+
if (key === 'global' || Object.hasOwn(realm, key)) continue
|
|
38
|
+
Object.defineProperty(globals, key, Object.getOwnPropertyDescriptor(globalThis, key) as PropertyDescriptor)
|
|
39
|
+
}
|
|
40
|
+
globals.global = realm
|
|
41
|
+
return context
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Evaluate a script, lowering top-level await while retaining Script-scope declarations.
|
|
46
|
+
* @param code - Type-stripped JavaScript; top-level return is not supported.
|
|
47
|
+
* @param context - Program globals and declarations retained between evaluations.
|
|
48
|
+
* @param imports - Runner-local import handling, or undefined for Node's default loader.
|
|
49
|
+
* @returns The script completion value after Promise settlement.
|
|
50
|
+
*/
|
|
51
|
+
async function evaluateScript(code: string, context: Context, imports: VmModuleImportLoader | undefined): Promise<unknown> {
|
|
52
|
+
const filename = resolve(process.cwd(), 'ptc-program.js')
|
|
53
|
+
const options: ScriptOptions = {
|
|
54
|
+
filename,
|
|
55
|
+
importModuleDynamically: imports === undefined ? constants.USE_MAIN_CONTEXT_DEFAULT_LOADER : imports.forFile(filename),
|
|
56
|
+
}
|
|
57
|
+
const compiled = compileScript(code, options)
|
|
58
|
+
const value: unknown = await compiled.script.runInContext(context)
|
|
59
|
+
// Node's transform boxes the last expression; the PTC caller also awaits that expression.
|
|
60
|
+
return compiled.transformed ? await (value as { value: unknown } | undefined)?.value : value
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Detect top-level await before native compilation can interpret await as an identifier. */
|
|
64
|
+
function compileScript(code: string, options: ScriptOptions): { script: Script; transformed: boolean } {
|
|
65
|
+
try {
|
|
66
|
+
let transformed: string | null = null
|
|
67
|
+
if (code.includes('await')) {
|
|
68
|
+
// Complete submissions need no REPL continuation; the newline terminates trailing comments.
|
|
69
|
+
const source = code.startsWith('#!') ? `//${code.slice(2)}` : code
|
|
70
|
+
transformed = processTopLevelAwait(`${source}\n`)
|
|
71
|
+
}
|
|
72
|
+
return { script: new Script(transformed ?? code, options), transformed: transformed !== null }
|
|
73
|
+
} catch (error: unknown) {
|
|
74
|
+
if (error instanceof SyntaxError) {
|
|
75
|
+
// V8 places the source location and caret before the error heading and its compiler frames.
|
|
76
|
+
const heading = `${error.name}: ${error.message}`
|
|
77
|
+
const stack = error.stack ?? ''
|
|
78
|
+
const headingStart = stack.indexOf(`\n${heading}`)
|
|
79
|
+
error.stack = headingStart < 0 ? heading : stack.slice(0, headingStart + heading.length + 1)
|
|
80
|
+
}
|
|
81
|
+
throw error
|
|
82
|
+
}
|
|
83
|
+
}
|
package/src/execution.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/** Select program syntax and own temporary or retained Node processes. */
|
|
2
|
+
import { stripTypeScriptTypes } from 'node:module'
|
|
3
|
+
import { isAbsolute } from 'node:path'
|
|
4
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
5
|
+
import type { PtcProgramFormat, PtcRunRequest, PtcRunResult, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
|
|
6
|
+
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
|
7
|
+
import { clampTimeout } from '@deepseek-ai/dsh-timeout'
|
|
8
|
+
import type { ResolvedConfig } from './config.ts'
|
|
9
|
+
import { validateBindings } from './bindings.ts'
|
|
10
|
+
import type { PolicyProcesses } from './policy-processes.ts'
|
|
11
|
+
import { ProgramWorker } from './worker.ts'
|
|
12
|
+
|
|
13
|
+
/** Syntax, state retention and model guidance selected during provider construction. */
|
|
14
|
+
export interface ExecutionMode {
|
|
15
|
+
/** Child evaluator selected independently of process lifetime. */
|
|
16
|
+
readonly format: PtcProgramFormat
|
|
17
|
+
/** Whether caller-owned objects retain processes between runs. */
|
|
18
|
+
readonly retainsState: boolean
|
|
19
|
+
/** Model-facing syntax, output and recovery rules. */
|
|
20
|
+
readonly executionInstructions: string
|
|
21
|
+
/**
|
|
22
|
+
* Erase TypeScript in the selected syntax without executing the program.
|
|
23
|
+
* @param program - Model-written TypeScript source.
|
|
24
|
+
* @returns JavaScript accepted by the selected evaluator.
|
|
25
|
+
*/
|
|
26
|
+
stripTypes(program: string): string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Select program semantics and create their shared process owner.
|
|
31
|
+
* @param ctx - Provider lifecycle and execution services.
|
|
32
|
+
* @param config - Validated configuration with loader defaults.
|
|
33
|
+
* @param processes - Policy invalidation and process cleanup coordination.
|
|
34
|
+
* @returns Mode selection and temporary or retained execution through one process implementation.
|
|
35
|
+
*/
|
|
36
|
+
export function createExecution(ctx: Context, config: ResolvedConfig, processes: PolicyProcesses): NodeExecution {
|
|
37
|
+
return new NodeExecution(ctx, config, processes, resolveMode(config))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Temporary processes and optional object-owned reuse share one process implementation. */
|
|
41
|
+
class NodeExecution {
|
|
42
|
+
private readonly owners = new WeakMap<object, ProgramWorker>()
|
|
43
|
+
private readonly workers = new Set<ProgramWorker>()
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Own process instances and optional owner lookup for one provider.
|
|
47
|
+
* @param ctx - Provider lifecycle and execution services.
|
|
48
|
+
* @param config - Validated limits and selected executable.
|
|
49
|
+
* @param processes - Provider-owned policy invalidation and cleanup.
|
|
50
|
+
* @param mode - Program syntax and TypeScript erasure.
|
|
51
|
+
*/
|
|
52
|
+
constructor(
|
|
53
|
+
private readonly ctx: Context, private readonly config: ResolvedConfig,
|
|
54
|
+
private readonly processes: PolicyProcesses, readonly mode: ExecutionMode,
|
|
55
|
+
) {}
|
|
56
|
+
|
|
57
|
+
/** Stop every owned process, retaining failed cleanup for a later retry. */
|
|
58
|
+
async dispose(): Promise<void> {
|
|
59
|
+
const results = await Promise.allSettled([...this.workers].map(async (worker) => {
|
|
60
|
+
await worker.dispose()
|
|
61
|
+
this.workers.delete(worker)
|
|
62
|
+
}))
|
|
63
|
+
const failed = results.find(result => result.status === 'rejected')
|
|
64
|
+
if (failed?.status === 'rejected') throw failed.reason
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Resolve the common file policy, directory and deadline defaults.
|
|
69
|
+
* @param request - Program, bindings, owner, directory and elapsed budget.
|
|
70
|
+
* @returns Resolved inputs with the selected file policy.
|
|
71
|
+
*/
|
|
72
|
+
resolve(request: PtcRunRequest): PtcRunSpec {
|
|
73
|
+
const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve()
|
|
74
|
+
const cwd = request.cwd ?? sandboxPolicy.workspaceRoot
|
|
75
|
+
if (!isAbsolute(cwd)) throw new Error(`${this.mode.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: cwd must be absolute`)
|
|
76
|
+
return { ...request, sandboxPolicy, cwd, timeoutMs: request.timeoutMs === null ? null : clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, this.mode.retainsState ? 'persistent PTC timeoutMs' : 'ptc-runtime-node: timeoutMs') }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Evaluate in a temporary process or reuse an enabled state owner's process.
|
|
81
|
+
* @param spec - Resolved request; concurrent calls for one owner are rejected.
|
|
82
|
+
* @returns Captured logs, JSON completion, or a structured execution failure.
|
|
83
|
+
*/
|
|
84
|
+
async run(spec: PtcRunSpec): Promise<PtcRunResult> {
|
|
85
|
+
if (spec.sandboxPolicy === undefined) throw new Error('ptc-runtime-node: run requires a resolved sandbox policy')
|
|
86
|
+
if (!isAbsolute(spec.cwd) || (spec.timeoutMs !== null && (!Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs))) throw new Error('ptc-runtime-node: run requires resolved cwd and timeout')
|
|
87
|
+
const bindings = validateBindings(spec)
|
|
88
|
+
const owner = this.mode.retainsState ? spec.stateOwner : undefined
|
|
89
|
+
let worker = owner === undefined ? undefined : this.owners.get(owner)
|
|
90
|
+
worker?.assertIdle()
|
|
91
|
+
if (worker && !worker.closed && (worker.policy.mode !== spec.sandboxPolicy.mode
|
|
92
|
+
|| worker.policy.workspaceRoot !== spec.sandboxPolicy.workspaceRoot
|
|
93
|
+
|| worker.policy.sessionId !== spec.sandboxPolicy.sessionId)) {
|
|
94
|
+
throw new Error('persistent PTC: release the retained environment before changing its sandbox policy')
|
|
95
|
+
}
|
|
96
|
+
// Retained processes keep their launch-time directory grants until release.
|
|
97
|
+
if (!worker || worker.closed) {
|
|
98
|
+
if (worker) this.workers.delete(worker)
|
|
99
|
+
// Direct callers can own mutable policy arrays; the retained process owns its grant snapshot.
|
|
100
|
+
worker = new ProgramWorker(this.ctx, this.config, {
|
|
101
|
+
...spec.sandboxPolicy,
|
|
102
|
+
...spec.sandboxPolicy.additionalWritableRoots === undefined
|
|
103
|
+
? {}
|
|
104
|
+
: { additionalWritableRoots: [...spec.sandboxPolicy.additionalWritableRoots] },
|
|
105
|
+
}, this.processes, this.mode, owner !== undefined)
|
|
106
|
+
this.workers.add(worker)
|
|
107
|
+
if (owner !== undefined) this.owners.set(owner, worker)
|
|
108
|
+
}
|
|
109
|
+
try { return await worker.run(spec, bindings) } finally {
|
|
110
|
+
if (owner === undefined && worker.cleanupComplete) this.workers.delete(worker)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Release retained state and await its process cleanup.
|
|
116
|
+
* @param owner - Exact object supplied to run.
|
|
117
|
+
* @returns Completion after the owned process and output streams stop.
|
|
118
|
+
*/
|
|
119
|
+
async release(owner: object): Promise<void> {
|
|
120
|
+
const worker = this.owners.get(owner)
|
|
121
|
+
if (!worker) return
|
|
122
|
+
await worker.dispose()
|
|
123
|
+
if (this.owners.get(owner) === worker) this.owners.delete(owner)
|
|
124
|
+
this.workers.delete(worker)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const STRIP_PREFIX = 'async function __dsh_program__() {\n'
|
|
129
|
+
const STRIP_SUFFIX = '\n}'
|
|
130
|
+
const RETAINED_STATE_INSTRUCTIONS = 'Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. Await tools and cleanup before returning; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before returning; raw output belongs to the active evaluation.'
|
|
131
|
+
|
|
132
|
+
function resolveMode(config: ResolvedConfig): ExecutionMode {
|
|
133
|
+
switch (config.executionMode) {
|
|
134
|
+
case 'per-call': return {
|
|
135
|
+
format: 'function-body',
|
|
136
|
+
retainsState: false,
|
|
137
|
+
executionInstructions: 'The program is the body of an async TypeScript function; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level await and return are supported. Emit output with console.log(...) or return a lossless JSON value. Only printed values and the returned value become program output. Each call runs in a fresh Node process. Node APIs are available through await import(...). Relative paths use the supplied working directory; process.env starts empty. Direct filesystem access follows this execution\'s sandbox policy.',
|
|
138
|
+
stripTypes(program) {
|
|
139
|
+
const stripped = stripTypeScriptTypes(STRIP_PREFIX + program + STRIP_SUFFIX)
|
|
140
|
+
return stripped.slice(STRIP_PREFIX.length, stripped.length - STRIP_SUFFIX.length)
|
|
141
|
+
},
|
|
142
|
+
}
|
|
143
|
+
case 'persistent-in-memory': return {
|
|
144
|
+
format: 'repl',
|
|
145
|
+
retainsState: true,
|
|
146
|
+
executionInstructions: 'The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Emit output with console.log(...) or a final lossless JSON expression. Only printed values and that final expression become program output. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. Direct filesystem access follows the environment\'s launch-time sandbox policy; process.env starts empty. ' + RETAINED_STATE_INSTRUCTIONS,
|
|
147
|
+
stripTypes: stripTypeScriptTypes,
|
|
148
|
+
}
|
|
149
|
+
case 'vm-script': {
|
|
150
|
+
const lifetime = config.scriptPersistence
|
|
151
|
+
? 'Variables, functions, and imported modules remain in memory for this Agent across calls.'
|
|
152
|
+
: 'Each call runs in a fresh Node process.'
|
|
153
|
+
const filePolicy = config.scriptPersistence
|
|
154
|
+
? 'Direct filesystem access follows the environment\'s launch-time sandbox policy; process.env starts empty.'
|
|
155
|
+
: 'Direct filesystem access follows this execution\'s sandbox policy; process.env starts empty.'
|
|
156
|
+
const asynchronousFailure = 'Await asynchronous work: an uncaught callback exception or unhandled rejection terminates the process'
|
|
157
|
+
+ (config.scriptPersistence ? ' and clears its variables.' : '.')
|
|
158
|
+
const recovery = config.scriptPersistence
|
|
159
|
+
? ' ' + RETAINED_STATE_INSTRUCTIONS + ' If a native top-level let, const, or class initializer throws, its name may remain permanently uninitialized; use a new name or restart the environment.'
|
|
160
|
+
: ''
|
|
161
|
+
return {
|
|
162
|
+
format: 'script',
|
|
163
|
+
retainsState: config.scriptPersistence,
|
|
164
|
+
executionInstructions: 'The program contains TypeScript script statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Emit output with console.log(...) or a final lossless JSON expression. The final expression is awaited if it is a Promise. Only printed values and that final expression become program output. ' + lifetime + ' Use await import(...) for modules. Relative paths use the supplied working directory. ' + filePolicy + ' ' + asynchronousFailure + ' Values from bindings and imports can belong to another realm; use Array.isArray for arrays and the supplied binding error classes for failures, because instanceof Array or Error may be false.' + recovery,
|
|
165
|
+
stripTypes: stripTypeScriptTypes,
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/* v8 ignore next -- Loader validates the closed execution-mode union before selection. */
|
|
169
|
+
default: return assertNever(config.executionMode)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Import cancellation belongs to an evaluation, not to the imported module's cached failure. */
|
|
2
|
+
export class ImportEvaluationEndedError extends Error {
|
|
3
|
+
/** Whether a later evaluation can reuse this process after the cancelled import. */
|
|
4
|
+
readonly retainsState: boolean
|
|
5
|
+
|
|
6
|
+
constructor(retainsState: boolean, pending = false) {
|
|
7
|
+
super(pending ? 'PTC evaluation ended before its import completed'
|
|
8
|
+
: 'PTC evaluation has ended; import modules from a new run_code evaluation')
|
|
9
|
+
this.retainsState = retainsState
|
|
10
|
+
}
|
|
11
|
+
}
|