@deepseek-ai/dsh-ptc-runtime-node 0.2.2-rc.1 → 0.2.2-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +19 -16
- package/README.md +36 -10
- package/README.zh.md +36 -10
- package/lib/index.js +102 -63
- package/lib/persistent-process.js +528 -112
- package/lib/process.js +523 -109
- package/lib/types/bindings.d.ts.map +1 -0
- package/lib/types/bindings.js.map +1 -0
- package/lib/types/bootstrap.d.ts.map +1 -0
- package/lib/types/bootstrap.js.map +1 -0
- package/lib/types/config.d.ts +2 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/configuration.d.ts.map +1 -0
- package/lib/types/configuration.js.map +1 -0
- package/lib/types/environment.d.ts +3 -2
- package/lib/types/environment.d.ts.map +1 -0
- package/lib/types/environment.js.map +1 -0
- package/lib/types/evaluators/async-function.d.ts +3 -3
- package/lib/types/evaluators/async-function.d.ts.map +1 -0
- package/lib/types/evaluators/async-function.js.map +1 -0
- package/lib/types/evaluators/index.d.ts +3 -2
- package/lib/types/evaluators/index.d.ts.map +1 -0
- package/lib/types/evaluators/index.js.map +1 -0
- package/lib/types/evaluators/repl.d.ts +3 -3
- package/lib/types/evaluators/repl.d.ts.map +1 -0
- package/lib/types/evaluators/repl.js.map +1 -0
- package/lib/types/evaluators/types.d.ts +44 -0
- package/lib/types/evaluators/types.d.ts.map +1 -0
- package/lib/types/evaluators/types.js.map +1 -0
- package/lib/types/evaluators/vm-script-await.d.ts.map +1 -0
- package/lib/types/evaluators/vm-script-await.js.map +1 -0
- package/lib/types/evaluators/vm-script.d.ts +3 -2
- package/lib/types/evaluators/vm-script.d.ts.map +1 -0
- package/lib/types/evaluators/vm-script.js.map +1 -0
- package/lib/types/execution.d.ts.map +1 -0
- package/lib/types/execution.js.map +1 -0
- package/lib/types/imports/evaluation-ended.d.ts +7 -0
- package/lib/types/imports/evaluation-ended.d.ts.map +1 -0
- package/lib/types/imports/evaluation-ended.js.map +1 -0
- package/lib/types/imports/module-hooks.d.ts +37 -0
- package/lib/types/imports/module-hooks.d.ts.map +1 -0
- package/lib/types/imports/module-hooks.js.map +1 -0
- package/lib/types/imports/vm-modules.d.ts +35 -0
- package/lib/types/imports/vm-modules.d.ts.map +1 -0
- package/lib/types/imports/vm-modules.js.map +1 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/json-wire.d.ts.map +1 -0
- package/lib/types/json-wire.js.map +1 -0
- package/lib/types/launch.d.ts +1 -2
- package/lib/types/launch.d.ts.map +1 -0
- package/lib/types/launch.js.map +1 -0
- package/lib/types/output-json.d.ts.map +1 -0
- package/lib/types/output-json.js.map +1 -0
- package/lib/types/output-ledger.d.ts.map +1 -0
- package/lib/types/output-ledger.js.map +1 -0
- package/lib/types/output-stream.d.ts.map +1 -0
- package/lib/types/output-stream.js.map +1 -0
- package/lib/types/persistent-process-entry.d.ts.map +1 -0
- package/lib/types/persistent-process-entry.js.map +1 -0
- package/lib/types/persistent-process.d.ts +6 -2
- package/lib/types/persistent-process.d.ts.map +1 -0
- package/lib/types/persistent-process.js.map +1 -0
- package/lib/types/policy-processes.d.ts.map +1 -0
- package/lib/types/policy-processes.js.map +1 -0
- package/lib/types/process-entry.d.ts.map +1 -0
- package/lib/types/process-entry.js.map +1 -0
- package/lib/types/process.d.ts +4 -2
- package/lib/types/process.d.ts.map +1 -0
- package/lib/types/process.js.map +1 -0
- package/lib/types/protocol.d.ts +10 -3
- package/lib/types/protocol.d.ts.map +1 -0
- package/lib/types/protocol.js.map +1 -0
- package/lib/types/rpc.d.ts.map +1 -0
- package/lib/types/rpc.js.map +1 -0
- package/lib/types/worker.d.ts +5 -3
- package/lib/types/worker.d.ts.map +1 -0
- package/lib/types/worker.js.map +1 -0
- package/package.json +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,125 @@
|
|
|
1
|
+
/** AsyncFunction and REPL imports backed by runner-local ESM exports and synchronous module hooks. */
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import * as module from 'node:module'
|
|
5
|
+
import { dirname, join } from 'node:path'
|
|
6
|
+
import { pathToFileURL } from 'node:url'
|
|
7
|
+
import type { ProgramImportHandler } from '../evaluators/types.ts'
|
|
8
|
+
import { ImportEvaluationEndedError } from './evaluation-ended.ts'
|
|
9
|
+
|
|
10
|
+
/* v8 ignore next 4 -- Typed decisions exhaust this union; the standalone child cannot depend on built workspace packages. */
|
|
11
|
+
function assertNever(value: never): never {
|
|
12
|
+
throw new Error(`Unsupported PTC import decision: ${String(value)}`)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Module hooks and an export bridge owned by one native evaluator. */
|
|
16
|
+
export class ModuleHooksImportLoader {
|
|
17
|
+
private readonly identity = randomUUID()
|
|
18
|
+
private readonly bridgeName = `dsh.ptc.imports.${this.identity}`
|
|
19
|
+
private readonly bridgeKey = Symbol.for(this.bridgeName)
|
|
20
|
+
private readonly hooks: module.ModuleHooks
|
|
21
|
+
private readonly programs = new Map<string | undefined, string>()
|
|
22
|
+
private readonly replPrograms = new Map<string | undefined, string>()
|
|
23
|
+
private readonly scope = new AsyncLocalStorage<boolean>()
|
|
24
|
+
private readonly sources = new Map<string, string>()
|
|
25
|
+
private readonly bindings = new Map<string, Record<string, unknown>>()
|
|
26
|
+
private modules = new WeakMap<Record<string, unknown>, string>()
|
|
27
|
+
private sequence = 0
|
|
28
|
+
private closed = false
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Install synchronous hooks for this evaluator's programs only.
|
|
32
|
+
* @param handler - Runner-local decisions; returning a Promise rejects the import.
|
|
33
|
+
*/
|
|
34
|
+
constructor(handler: ProgramImportHandler) {
|
|
35
|
+
this.hooks = module.registerHooks({
|
|
36
|
+
resolve: (specifier, context, nextResolve) => {
|
|
37
|
+
const filename = this.programs.get(context.parentURL)
|
|
38
|
+
?? (this.scope.getStore() ? this.replPrograms.get(context.parentURL) : undefined)
|
|
39
|
+
if (filename === undefined) return nextResolve(specifier, context)
|
|
40
|
+
let result
|
|
41
|
+
try {
|
|
42
|
+
result = handler({ specifier, referrer: filename, attributes: context.importAttributes })
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error instanceof ImportEvaluationEndedError && !error.retainsState) {
|
|
45
|
+
return { url: 'data:text/javascript,await new Promise(() => {})', shortCircuit: true }
|
|
46
|
+
}
|
|
47
|
+
throw error
|
|
48
|
+
}
|
|
49
|
+
if ('then' in result) {
|
|
50
|
+
// Native hooks cannot await this result; consume a rejection before reporting unsupported handling.
|
|
51
|
+
void result.catch(() => {})
|
|
52
|
+
throw new Error('Native PTC imports require a synchronous importHandler')
|
|
53
|
+
}
|
|
54
|
+
switch (result.type) {
|
|
55
|
+
case 'module': return { url: this.moduleUrl(result.exports), importAttributes: {}, shortCircuit: true }
|
|
56
|
+
case 'redirect': specifier = result.specifier; break
|
|
57
|
+
case 'default': break
|
|
58
|
+
/* v8 ignore next -- The runner supplies the closed ProgramImportResult union. */
|
|
59
|
+
default: return assertNever(result)
|
|
60
|
+
}
|
|
61
|
+
return nextResolve(specifier, { ...context, parentURL: pathToFileURL(filename).href })
|
|
62
|
+
},
|
|
63
|
+
load: (url, context, nextLoad) => {
|
|
64
|
+
const source = this.sources.get(url)
|
|
65
|
+
this.sources.delete(url)
|
|
66
|
+
return source === undefined ? nextLoad(url, context) : { format: 'module', source, shortCircuit: true }
|
|
67
|
+
},
|
|
68
|
+
})
|
|
69
|
+
const bridge = Object.freeze({ get: (url: string) => {
|
|
70
|
+
const exports = this.bindings.get(url)
|
|
71
|
+
this.bindings.delete(url)
|
|
72
|
+
return exports
|
|
73
|
+
} })
|
|
74
|
+
Object.defineProperty(globalThis, this.bridgeKey, { value: bridge, configurable: true })
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Register an AsyncFunction import parent owned by this evaluator.
|
|
79
|
+
* @param filename - Absolute program filename, captured before its evaluation.
|
|
80
|
+
* @returns Unique program URL for the native compiler and constructor source URL.
|
|
81
|
+
*/
|
|
82
|
+
forFile(filename: string): string {
|
|
83
|
+
const url = `${pathToFileURL(filename).href}?${this.identity}`
|
|
84
|
+
this.programs.set(url, filename)
|
|
85
|
+
return url
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Attribute Node REPL imports to this evaluator, including asynchronous callbacks.
|
|
90
|
+
* @param filename - Absolute program filename for the evaluation's working directory.
|
|
91
|
+
* @param evaluate - Start the REPL evaluation while its import scope is active.
|
|
92
|
+
*/
|
|
93
|
+
runRepl(filename: string, evaluate: () => void): void {
|
|
94
|
+
if (this.closed) throw new Error('PTC evaluator is closed')
|
|
95
|
+
// Node REPL captures cwd/repl as its import parent, independently of its diagnostic filename.
|
|
96
|
+
this.replPrograms.set(pathToFileURL(join(dirname(filename), 'repl')).href, filename)
|
|
97
|
+
this.scope.run(true, evaluate)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Deregister hooks and remove the export bridge; Node retains loaded ESM namespaces until process exit. */
|
|
101
|
+
close(): void {
|
|
102
|
+
this.closed = true
|
|
103
|
+
this.hooks.deregister()
|
|
104
|
+
Reflect.deleteProperty(globalThis, this.bridgeKey)
|
|
105
|
+
this.programs.clear()
|
|
106
|
+
this.replPrograms.clear()
|
|
107
|
+
this.scope.disable()
|
|
108
|
+
this.sources.clear()
|
|
109
|
+
this.bindings.clear()
|
|
110
|
+
this.modules = new WeakMap()
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private moduleUrl(exports: Record<string, unknown>): string {
|
|
114
|
+
const existing = this.modules.get(exports)
|
|
115
|
+
if (existing !== undefined) return existing
|
|
116
|
+
const url = `dsh-ptc-module:${this.identity}/${++this.sequence}`
|
|
117
|
+
const declarations = Object.keys(exports).map((name, index) =>
|
|
118
|
+
`const value${index} = bindings[${JSON.stringify(name)}]; export { value${index} as ${JSON.stringify(name)} };`)
|
|
119
|
+
const lookup = `globalThis[Symbol.for(${JSON.stringify(this.bridgeName)})].get(${JSON.stringify(url)})`
|
|
120
|
+
this.sources.set(url, `const bindings = ${lookup};\n${declarations.join('\n')}`)
|
|
121
|
+
this.bindings.set(url, exports)
|
|
122
|
+
this.modules.set(exports, url)
|
|
123
|
+
return url
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/** Adapt runner-local import decisions to Node's VM module callbacks. */
|
|
2
|
+
import * as vm from 'node:vm'
|
|
3
|
+
import { readFile } from 'node:fs/promises'
|
|
4
|
+
import { dirname, extname } from 'node:path'
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
6
|
+
import { types } from 'node:util'
|
|
7
|
+
import { registerHooks, type ImportAttributes, type ResolveFnOutput } from 'node:module'
|
|
8
|
+
import type { ProgramImportHandler } from '../evaluators/types.ts'
|
|
9
|
+
import { ImportEvaluationEndedError } from './evaluation-ended.ts'
|
|
10
|
+
|
|
11
|
+
/* v8 ignore next 4 -- Typed decisions exhaust this union; the standalone child cannot depend on built workspace packages. */
|
|
12
|
+
function assertNever(value: never): never {
|
|
13
|
+
throw new Error(`Unsupported PTC import decision: ${String(value)}`)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Node >=24.9 supplies explicit graph linking; the installed Node declarations omit these methods.
|
|
17
|
+
interface SourceModule extends vm.SourceTextModule {
|
|
18
|
+
instantiate(): void
|
|
19
|
+
linkRequests(modules: vm.Module[]): void
|
|
20
|
+
readonly moduleRequests: readonly (vm.ModuleRequest & { phase: string })[]
|
|
21
|
+
}
|
|
22
|
+
const SourceModule = vm.SourceTextModule as new (code: string, options: vm.SourceTextModuleOptions) => SourceModule
|
|
23
|
+
|
|
24
|
+
/** Node retains evaluation state; the loader owns asynchronous dependency resolution. */
|
|
25
|
+
interface ModuleRecord {
|
|
26
|
+
module: vm.Module
|
|
27
|
+
dependencies?: Promise<ModuleRecord[]>
|
|
28
|
+
expired?: boolean
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type ImportResult = ModuleRecord | { namespace: Record<string, unknown> }
|
|
32
|
+
|
|
33
|
+
/** Modules belong to one evaluator; each compiled program retains its own resolution filename. */
|
|
34
|
+
export class VmModuleImportLoader {
|
|
35
|
+
private modules = new WeakMap<Record<string, unknown>, ModuleRecord>()
|
|
36
|
+
private files = new Map<string, Promise<ModuleRecord>>()
|
|
37
|
+
private readonly handler: ProgramImportHandler
|
|
38
|
+
private readonly context: vm.Context
|
|
39
|
+
private closed = false
|
|
40
|
+
// Keep resolved URLs on Node's loader even when this file's importer transforms import().
|
|
41
|
+
private readonly nativeImport = vm.compileFunction('return import(url, { with: attributes })', ['url', 'attributes'], {
|
|
42
|
+
importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
|
|
43
|
+
}) as (url: string, attributes: ImportAttributes) => Promise<unknown>
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Own module instances for one evaluator's runner-local handler.
|
|
47
|
+
* @param handler - Runner-local import decisions.
|
|
48
|
+
* @param context - Script context receiving the imported modules.
|
|
49
|
+
*/
|
|
50
|
+
constructor(handler: ProgramImportHandler, context: vm.Context) {
|
|
51
|
+
this.handler = handler
|
|
52
|
+
this.context = context
|
|
53
|
+
if (typeof vm.SyntheticModule !== 'function') {
|
|
54
|
+
throw new Error('PTC importHandler requires the runner to start with --experimental-vm-modules')
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Bind import resolution to the filename used to compile a program.
|
|
60
|
+
* @param filename - Absolute program filename, captured before its evaluation.
|
|
61
|
+
* @returns Callback implementing the runner's import handler.
|
|
62
|
+
*/
|
|
63
|
+
forFile(filename: string): vm.DynamicModuleLoader<object> {
|
|
64
|
+
return this.callback(pathToFileURL(filename).href)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Reject further handler calls and release cached modules; imported values remain usable. */
|
|
68
|
+
close(): void {
|
|
69
|
+
this.closed = true
|
|
70
|
+
this.modules = new WeakMap()
|
|
71
|
+
this.files.clear()
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private assertOpen(late = false): void {
|
|
75
|
+
if (this.closed) throw new Error(late ? 'PTC evaluator closed before its import completed' : 'PTC evaluator is closed')
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private callback(referrer: string): vm.DynamicModuleLoader<object> {
|
|
79
|
+
const load = async (specifier: string, _referrer: object, attributes: ImportAttributes, phase = 'evaluation') => {
|
|
80
|
+
const record = await this.request(specifier, referrer, attributes, phase)
|
|
81
|
+
this.assertOpen(true)
|
|
82
|
+
if ('namespace' in record) return record.namespace
|
|
83
|
+
await this.link(record, new Set())
|
|
84
|
+
this.assertOpen(true)
|
|
85
|
+
if (record.module instanceof SourceModule && record.module.status === 'unlinked') record.module.instantiate()
|
|
86
|
+
await record.module.evaluate()
|
|
87
|
+
this.assertOpen(true)
|
|
88
|
+
return record.module
|
|
89
|
+
}
|
|
90
|
+
// Node accepts native namespaces; its callback declarations only describe vm.Module results.
|
|
91
|
+
return load as vm.DynamicModuleLoader<object>
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private async request(
|
|
95
|
+
specifier: string, referrer: string, attributes: ImportAttributes, phase: string, staticImport = false,
|
|
96
|
+
): Promise<ImportResult> {
|
|
97
|
+
this.assertOpen()
|
|
98
|
+
if (phase !== 'evaluation') throw new Error('PTC importHandler supports evaluation-phase imports only')
|
|
99
|
+
let result
|
|
100
|
+
try {
|
|
101
|
+
result = await this.handler({ specifier, referrer: fileURLToPath(referrer), attributes })
|
|
102
|
+
} catch (error) {
|
|
103
|
+
// A closing temporary process must not resume detached program catch handlers.
|
|
104
|
+
if (error instanceof ImportEvaluationEndedError && !error.retainsState) return new Promise<never>(() => {})
|
|
105
|
+
throw error
|
|
106
|
+
}
|
|
107
|
+
this.assertOpen(true)
|
|
108
|
+
switch (result.type) {
|
|
109
|
+
case 'module': return this.module(result.exports)
|
|
110
|
+
case 'redirect': specifier = result.specifier; break
|
|
111
|
+
case 'default': break
|
|
112
|
+
/* v8 ignore next -- The runner supplies the closed ProgramImportResult union. */
|
|
113
|
+
default: return assertNever(result)
|
|
114
|
+
}
|
|
115
|
+
const resolved = resolveImport(specifier, referrer)
|
|
116
|
+
const url = new URL(resolved.url)
|
|
117
|
+
if (isSourceModule(url, resolved.format)) {
|
|
118
|
+
if (Object.keys(attributes).length) throw new TypeError(`PTC ESM imports do not accept import attributes: ${url.href}`)
|
|
119
|
+
return this.file(url)
|
|
120
|
+
}
|
|
121
|
+
if (staticImport) {
|
|
122
|
+
// Export the namespace as a value so native Promise assimilation cannot consume its then export.
|
|
123
|
+
const source = `import * as namespace from ${JSON.stringify(url.href)} with ${JSON.stringify(attributes)}; export { namespace }`
|
|
124
|
+
const loaded = await this.nativeImport(`data:text/javascript,${encodeURIComponent(source)}`, {}) as { namespace: Record<string, unknown> }
|
|
125
|
+
this.assertOpen(true)
|
|
126
|
+
return { namespace: loaded.namespace }
|
|
127
|
+
}
|
|
128
|
+
const value = await this.nativeImport(url.href, attributes)
|
|
129
|
+
this.assertOpen(true)
|
|
130
|
+
if (types.isModuleNamespaceObject(value)) return { namespace: value as Record<string, unknown> }
|
|
131
|
+
// A native then export can settle to any value; the VM callback still requires a module.
|
|
132
|
+
return this.module({ then(resolve: (result: unknown) => void) { resolve(value) } })
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private async file(url: URL): Promise<ModuleRecord> {
|
|
136
|
+
let pending = this.files.get(url.href)
|
|
137
|
+
if (!pending) {
|
|
138
|
+
pending = this.sourceModule(url)
|
|
139
|
+
this.files.set(url.href, pending)
|
|
140
|
+
}
|
|
141
|
+
const record = await pending
|
|
142
|
+
if (record.expired || (record.module.status === 'errored' && record.module.error instanceof ImportEvaluationEndedError)) {
|
|
143
|
+
if (this.files.get(url.href) === pending) this.files.delete(url.href)
|
|
144
|
+
return this.file(url)
|
|
145
|
+
}
|
|
146
|
+
return record
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private async sourceModule(url: URL): Promise<ModuleRecord> {
|
|
150
|
+
const source = await readFile(url, 'utf8')
|
|
151
|
+
this.assertOpen(true)
|
|
152
|
+
const filename = fileURLToPath(url)
|
|
153
|
+
return { module: new SourceModule(source, {
|
|
154
|
+
context: this.context,
|
|
155
|
+
identifier: url.href,
|
|
156
|
+
initializeImportMeta(meta) {
|
|
157
|
+
meta.url = url.href
|
|
158
|
+
meta.filename = filename
|
|
159
|
+
meta.dirname = dirname(filename)
|
|
160
|
+
meta.main = false
|
|
161
|
+
meta.resolve = (specifier: string) => resolveImport(specifier, url.href).url
|
|
162
|
+
},
|
|
163
|
+
importModuleDynamically: this.callback(url.href),
|
|
164
|
+
}) }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private async link(record: ModuleRecord, visited: Set<ModuleRecord>): Promise<void> {
|
|
168
|
+
if (visited.has(record)) return
|
|
169
|
+
visited.add(record)
|
|
170
|
+
record.dependencies ??= this.dependencies(record.module)
|
|
171
|
+
try {
|
|
172
|
+
const dependencies = await record.dependencies
|
|
173
|
+
this.assertOpen(true)
|
|
174
|
+
await Promise.all(dependencies.map(dependency => this.link(dependency, visited)))
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (error instanceof ImportEvaluationEndedError) record.expired = true
|
|
177
|
+
throw error
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
private async dependencies(module: vm.Module): Promise<ModuleRecord[]> {
|
|
182
|
+
if (module instanceof SourceModule) {
|
|
183
|
+
const dependencies = await Promise.all(module.moduleRequests.map(async (request) => {
|
|
184
|
+
const result = await this.request(request.specifier, module.identifier, request.attributes, request.phase, true)
|
|
185
|
+
return 'namespace' in result ? this.module(result.namespace) : result
|
|
186
|
+
}))
|
|
187
|
+
this.assertOpen(true)
|
|
188
|
+
// Cache direct dependencies before walking them: cycles must not await their own graph.
|
|
189
|
+
module.linkRequests(dependencies.map(record => record.module))
|
|
190
|
+
return dependencies
|
|
191
|
+
}
|
|
192
|
+
/* v8 ignore next -- SyntheticModule has no dependencies, so Node never calls its linker. */
|
|
193
|
+
await module.link(() => module)
|
|
194
|
+
return []
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private module(exports: Record<string, unknown>): ModuleRecord {
|
|
198
|
+
this.assertOpen(true)
|
|
199
|
+
const existing = this.modules.get(exports)
|
|
200
|
+
if (existing) return existing
|
|
201
|
+
const names = Object.keys(exports)
|
|
202
|
+
const module = new vm.SyntheticModule(names, function () {
|
|
203
|
+
for (const name of names) this.setExport(name, exports[name])
|
|
204
|
+
}, { context: this.context })
|
|
205
|
+
const record = { module }
|
|
206
|
+
this.modules.set(exports, record)
|
|
207
|
+
return record
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Resolve with the native loader's conditions and flags while retaining the importing filename. */
|
|
212
|
+
function resolveImport(specifier: string, parentURL: string): ResolveFnOutput {
|
|
213
|
+
const marker = 'dsh-ptc:resolve'
|
|
214
|
+
let format: ResolveFnOutput['format']
|
|
215
|
+
const hooks = registerHooks({
|
|
216
|
+
resolve(request, context, nextResolve) {
|
|
217
|
+
if (request !== marker) return nextResolve(request, context)
|
|
218
|
+
const resolved = nextResolve(specifier, { ...context, parentURL })
|
|
219
|
+
format = resolved.format
|
|
220
|
+
return resolved
|
|
221
|
+
},
|
|
222
|
+
})
|
|
223
|
+
try { return { url: import.meta.resolve(marker), format } }
|
|
224
|
+
finally { hooks.deregister() }
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Explicit file ESM stays in the evaluator; other formats retain Node's loader. */
|
|
228
|
+
function isSourceModule(url: URL, format: ResolveFnOutput['format']): boolean {
|
|
229
|
+
if (url.protocol !== 'file:') return false
|
|
230
|
+
const extension = extname(fileURLToPath(url))
|
|
231
|
+
if (extension === '.mjs') return true
|
|
232
|
+
return extension === '.js' && format === 'module'
|
|
233
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/** Node PTC provider with uniform admission and configurable evaluation and process ownership. */
|
|
2
|
+
import { Context } from '@deepseek-ai/cordis'
|
|
3
|
+
import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime'
|
|
4
|
+
import type { PtcProgramFormat, PtcRunRequest, PtcRunResult, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
|
|
5
|
+
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
|
|
6
|
+
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
|
7
|
+
import type {} from '@deepseek-ai/dsh-fs'
|
|
8
|
+
import { resolveLaunch } from './launch.ts'
|
|
9
|
+
import { NodeConfig, validateConfig } from './config.ts'
|
|
10
|
+
import { createExecution } from './execution.ts'
|
|
11
|
+
import { PolicyProcesses } from './policy-processes.ts'
|
|
12
|
+
import type { Config, ResolvedConfig } from './config.ts'
|
|
13
|
+
export type { Config } from './config.ts'
|
|
14
|
+
export type { LaunchConfig } from './launch.ts'
|
|
15
|
+
|
|
16
|
+
interface LiveRun { controller: AbortController; finished: Promise<void> }
|
|
17
|
+
|
|
18
|
+
/** Node execution under file policy, with optional owner-scoped retained memory. */
|
|
19
|
+
export class NodePtcRuntime extends PtcRuntime {
|
|
20
|
+
static inject = ['fs', 'subprocess', 'sandbox', 'sandboxPolicy']
|
|
21
|
+
static Config = NodeConfig
|
|
22
|
+
readonly language = 'typescript'
|
|
23
|
+
readonly isolation = 'process'
|
|
24
|
+
private readonly execution: ReturnType<typeof createExecution>
|
|
25
|
+
private readonly processes: PolicyProcesses
|
|
26
|
+
|
|
27
|
+
override get programFormat(): PtcProgramFormat { return this.execution.mode.format }
|
|
28
|
+
override get retainsState(): boolean { return this.execution.mode.retainsState }
|
|
29
|
+
override get executionInstructions(): string { return this.execution.mode.executionInstructions }
|
|
30
|
+
private readonly config: ResolvedConfig
|
|
31
|
+
private readonly live = new Set<LiveRun>()
|
|
32
|
+
private disposed = false
|
|
33
|
+
|
|
34
|
+
constructor(ctx: Context, config: Config) {
|
|
35
|
+
super(ctx)
|
|
36
|
+
this.config = { ...config, launch: resolveLaunch(config.launch) } as ResolvedConfig
|
|
37
|
+
validateConfig(this.config)
|
|
38
|
+
this.processes = new PolicyProcesses(ctx)
|
|
39
|
+
this.execution = createExecution(ctx, this.config, this.processes)
|
|
40
|
+
ctx.effect(() => async () => {
|
|
41
|
+
this.disposed = true
|
|
42
|
+
const active = [...this.live]
|
|
43
|
+
for (const run of active) run.controller.abort('runtime disposed')
|
|
44
|
+
const results = await Promise.allSettled([this.execution.dispose(), ...active.map(run => run.finished)])
|
|
45
|
+
const failed = results.find(result => result.status === 'rejected')
|
|
46
|
+
if (failed?.status === 'rejected') throw failed.reason
|
|
47
|
+
}, 'Node ptc-runtime cleanup')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
override get sandboxMode(): SandboxMode | undefined { return this.ctx.sandboxPolicy.defaultMode }
|
|
51
|
+
|
|
52
|
+
override release(owner: object): Promise<void> {
|
|
53
|
+
return this.execution.release(owner)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
override get timeout(): { defaultMs: number; maxMs: number } {
|
|
57
|
+
return { defaultMs: Math.min(this.config.timeoutMs, this.config.maxTimeoutMs), maxMs: this.config.maxTimeoutMs }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Resolve directory, deadline and file policy for the selected execution mode.
|
|
62
|
+
* @param request - Program, bindings, optional cwd/deadline, and resolved authority.
|
|
63
|
+
* @returns Complete execution inputs with a capped numeric budget or an explicit null deadline.
|
|
64
|
+
*/
|
|
65
|
+
resolve(request: PtcRunRequest): PtcRunSpec {
|
|
66
|
+
if (this.disposed) {
|
|
67
|
+
const source = this.retainsState ? 'persistent PTC' : 'ptc-runtime-node'
|
|
68
|
+
throw new Error(`${source}: resolve after disposal`)
|
|
69
|
+
}
|
|
70
|
+
return this.execution.resolve(request)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Run a resolved program under the configured execution mode.
|
|
75
|
+
* Session mode changes cancel admitted calls before process launch as well as active programs.
|
|
76
|
+
* @param spec - Inputs returned by resolve for the configured mode.
|
|
77
|
+
* @returns Logs, JSON completion or failure; retained processes remain until release or invalidation.
|
|
78
|
+
*/
|
|
79
|
+
async run(spec: PtcRunSpec): Promise<PtcRunResult> {
|
|
80
|
+
if (this.disposed) throw new Error('ptc-runtime-node: run after disposal')
|
|
81
|
+
const controller = new AbortController()
|
|
82
|
+
const completion = Promise.withResolvers<void>()
|
|
83
|
+
const unregister = spec.sandboxPolicy === undefined ? undefined : this.processes.register(spec.sandboxPolicy, async () => {
|
|
84
|
+
controller.abort(new Error('sandbox mode changed'))
|
|
85
|
+
await completion.promise
|
|
86
|
+
})
|
|
87
|
+
const live = { controller, finished: completion.promise }
|
|
88
|
+
this.live.add(live)
|
|
89
|
+
try {
|
|
90
|
+
await this.processes.wait(spec.sandboxPolicy?.sessionId)
|
|
91
|
+
// Disposal can begin while a previous policy's process cleanup is pending.
|
|
92
|
+
// oxlint-disable-next-line typescript/no-unnecessary-condition
|
|
93
|
+
if (this.disposed) throw new Error(`${this.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: run after disposal`)
|
|
94
|
+
const signal = spec.signal === undefined ? controller.signal : AbortSignal.any([spec.signal, controller.signal])
|
|
95
|
+
return await this.execution.run({ ...spec, signal })
|
|
96
|
+
} finally {
|
|
97
|
+
unregister?.()
|
|
98
|
+
this.live.delete(live)
|
|
99
|
+
completion.resolve()
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export default NodePtcRuntime
|