@deepseek-ai/dsh-ptc-runtime-node 0.2.2-rc.4 → 0.2.3-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +24 -24
- package/README.md +49 -17
- package/README.zh.md +49 -17
- package/lib/configuration.js +15 -5
- package/lib/index.js +439 -148
- package/lib/persistent-process.js +683 -90
- package/lib/process.js +683 -90
- package/lib/types/bindings.d.ts +10 -5
- package/lib/types/bindings.d.ts.map +1 -1
- package/lib/types/bindings.js.map +1 -1
- package/lib/types/bootstrap.d.ts +42 -24
- package/lib/types/bootstrap.d.ts.map +1 -1
- package/lib/types/bootstrap.js.map +1 -1
- package/lib/types/config.d.ts +14 -2
- package/lib/types/config.d.ts.map +1 -1
- package/lib/types/config.js.map +1 -1
- package/lib/types/configuration.d.ts +5 -4
- package/lib/types/configuration.d.ts.map +1 -1
- package/lib/types/configuration.js.map +1 -1
- package/lib/types/environment.d.ts +13 -0
- package/lib/types/environment.d.ts.map +1 -1
- package/lib/types/environment.js.map +1 -1
- package/lib/types/evaluators/index.d.ts.map +1 -1
- package/lib/types/evaluators/index.js.map +1 -1
- package/lib/types/evaluators/scoped-repl-evaluator.d.ts +22 -0
- package/lib/types/evaluators/scoped-repl-evaluator.d.ts.map +1 -0
- package/lib/types/evaluators/scoped-repl-evaluator.js.map +1 -0
- package/lib/types/evaluators/scoped-repl.d.ts +130 -0
- package/lib/types/evaluators/scoped-repl.d.ts.map +1 -0
- package/lib/types/evaluators/scoped-repl.js.map +1 -0
- package/lib/types/evaluators/types.d.ts +3 -3
- package/lib/types/evaluators/types.d.ts.map +1 -1
- package/lib/types/evaluators/types.js.map +1 -1
- package/lib/types/execution.d.ts +3 -2
- package/lib/types/execution.d.ts.map +1 -1
- package/lib/types/execution.js.map +1 -1
- package/lib/types/index.d.ts +6 -1
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/index.js.map +1 -1
- package/lib/types/json-wire.d.ts +16 -4
- package/lib/types/json-wire.d.ts.map +1 -1
- package/lib/types/json-wire.js.map +1 -1
- package/lib/types/output-ledger.d.ts +10 -10
- package/lib/types/output-ledger.d.ts.map +1 -1
- package/lib/types/output-ledger.js.map +1 -1
- package/lib/types/process.d.ts +2 -0
- package/lib/types/process.d.ts.map +1 -1
- package/lib/types/process.js.map +1 -1
- package/lib/types/protocol.d.ts +31 -5
- package/lib/types/protocol.d.ts.map +1 -1
- package/lib/types/protocol.js.map +1 -1
- package/lib/types/worker.d.ts +6 -3
- package/lib/types/worker.d.ts.map +1 -1
- package/lib/types/worker.js.map +1 -1
- package/package.json +23 -21
- package/src/bindings.ts +33 -26
- package/src/bootstrap.ts +159 -57
- package/src/config.ts +21 -3
- package/src/configuration.ts +13 -6
- package/src/environment.ts +39 -0
- package/src/evaluators/index.ts +2 -0
- package/src/evaluators/scoped-repl-evaluator.ts +110 -0
- package/src/evaluators/scoped-repl.ts +339 -0
- package/src/evaluators/types.ts +3 -3
- package/src/execution.ts +37 -17
- package/src/index.ts +58 -13
- package/src/json-wire.ts +44 -8
- package/src/output-ledger.ts +42 -45
- package/src/process.ts +89 -18
- package/src/protocol.ts +37 -10
- package/src/worker.ts +75 -40
package/src/execution.ts
CHANGED
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
import { stripTypeScriptTypes } from 'node:module'
|
|
3
3
|
import { isAbsolute } from 'node:path'
|
|
4
4
|
import type { Context } from '@deepseek-ai/cordis'
|
|
5
|
-
import type
|
|
5
|
+
import { PtcRuntimeError, type PtcProgramFormat, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
|
|
6
6
|
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
|
7
7
|
import { clampTimeout } from '@deepseek-ai/dsh-timeout'
|
|
8
8
|
import type { ResolvedConfig } from './config.ts'
|
|
9
9
|
import { validateBindings } from './bindings.ts'
|
|
10
10
|
import type { PolicyProcesses } from './policy-processes.ts'
|
|
11
11
|
import { ProgramWorker } from './worker.ts'
|
|
12
|
+
import { quietRuntimeCall } from './environment.ts'
|
|
12
13
|
|
|
13
14
|
/** Syntax, state retention and model guidance selected during provider construction. */
|
|
14
15
|
export interface ExecutionMode {
|
|
@@ -72,26 +73,27 @@ class NodeExecution {
|
|
|
72
73
|
resolve(request: PtcRunRequest): PtcRunSpec {
|
|
73
74
|
const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve()
|
|
74
75
|
const cwd = request.cwd ?? sandboxPolicy.workspaceRoot
|
|
75
|
-
if (!isAbsolute(cwd)) throw new
|
|
76
|
+
if (!isAbsolute(cwd)) throw new PtcRuntimeError(`${this.mode.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: cwd must be absolute`, 'PTC_RUNTIME_INVALID_ARGUMENT')
|
|
76
77
|
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
|
}
|
|
78
79
|
|
|
79
80
|
/**
|
|
80
81
|
* Evaluate in a temporary process or reuse an enabled state owner's process.
|
|
81
82
|
* @param spec - Resolved request; concurrent calls for one owner are rejected.
|
|
83
|
+
* @param initialization - Type-erased source for new environments, or undefined when none is registered.
|
|
82
84
|
* @returns Captured logs, JSON completion, or a structured execution failure.
|
|
83
85
|
*/
|
|
84
|
-
async run(spec: PtcRunSpec): Promise<PtcRunResult> {
|
|
85
|
-
if (spec.sandboxPolicy === undefined) throw new
|
|
86
|
-
if (!isAbsolute(spec.cwd) || (spec.timeoutMs !== null && (!Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs))) throw new
|
|
87
|
-
const bindings = validateBindings(spec)
|
|
86
|
+
async run(spec: PtcRunSpec, initialization: string | undefined): Promise<PtcRunResult> {
|
|
87
|
+
if (spec.sandboxPolicy === undefined) throw new PtcRuntimeError('ptc-runtime-node: run requires a resolved sandbox policy', 'PTC_RUNTIME_INVALID_ARGUMENT')
|
|
88
|
+
if (!isAbsolute(spec.cwd) || (spec.timeoutMs !== null && (!Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs))) throw new PtcRuntimeError('ptc-runtime-node: run requires resolved cwd and timeout', 'PTC_RUNTIME_INVALID_ARGUMENT')
|
|
89
|
+
const bindings = validateBindings(spec, this.mode.format)
|
|
88
90
|
const owner = this.mode.retainsState ? spec.stateOwner : undefined
|
|
89
91
|
let worker = owner === undefined ? undefined : this.owners.get(owner)
|
|
90
92
|
worker?.assertIdle()
|
|
91
93
|
if (worker && !worker.closed && (worker.policy.mode !== spec.sandboxPolicy.mode
|
|
92
94
|
|| worker.policy.workspaceRoot !== spec.sandboxPolicy.workspaceRoot
|
|
93
95
|
|| worker.policy.sessionId !== spec.sandboxPolicy.sessionId)) {
|
|
94
|
-
throw new
|
|
96
|
+
throw new PtcRuntimeError('persistent PTC: release the retained environment before changing its sandbox policy', 'PTC_RUNTIME_CONFLICT')
|
|
95
97
|
}
|
|
96
98
|
// Retained processes keep their launch-time directory grants until release.
|
|
97
99
|
if (!worker || worker.closed) {
|
|
@@ -102,12 +104,12 @@ class NodeExecution {
|
|
|
102
104
|
...spec.sandboxPolicy.additionalWritableRoots === undefined
|
|
103
105
|
? {}
|
|
104
106
|
: { additionalWritableRoots: [...spec.sandboxPolicy.additionalWritableRoots] },
|
|
105
|
-
}, this.processes, this.mode, owner !== undefined)
|
|
107
|
+
}, this.processes, this.mode, owner !== undefined, initialization)
|
|
106
108
|
this.workers.add(worker)
|
|
107
109
|
if (owner !== undefined) this.owners.set(owner, worker)
|
|
108
110
|
}
|
|
109
111
|
try { return await worker.run(spec, bindings) } finally {
|
|
110
|
-
if (
|
|
112
|
+
if (worker.cleanupComplete) this.workers.delete(worker)
|
|
111
113
|
}
|
|
112
114
|
}
|
|
113
115
|
|
|
@@ -125,26 +127,44 @@ class NodeExecution {
|
|
|
125
127
|
}
|
|
126
128
|
}
|
|
127
129
|
|
|
130
|
+
/** Erase TypeScript syntax without printing Node's warning for the experimental stripping API, which the host itself uses. */
|
|
131
|
+
function stripTypeScript(source: string): string {
|
|
132
|
+
return quietRuntimeCall(() => stripTypeScriptTypes(source))
|
|
133
|
+
}
|
|
134
|
+
|
|
128
135
|
const STRIP_PREFIX = 'async function __dsh_program__() {\n'
|
|
129
136
|
const STRIP_SUFFIX = '\n}'
|
|
130
|
-
const RETAINED_STATE_INSTRUCTIONS = 'Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes,
|
|
137
|
+
const RETAINED_STATE_INSTRUCTIONS = 'Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, 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 the program ends; 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 the program ends; raw output belongs to the active evaluation.'
|
|
138
|
+
/** Scoped REPL guidance; its output sentence is shared with the other modes. */
|
|
139
|
+
function scopedReplMode(outputInstructions: string): ExecutionMode {
|
|
140
|
+
return {
|
|
141
|
+
format: 'scoped-repl',
|
|
142
|
+
retainsState: true,
|
|
143
|
+
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. ' + outputInstructions + ' The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program\'s copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name\'s earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment\'s first program, while process.cwd() and relative file paths follow each program\'s working directory. Direct filesystem access follows the environment\'s launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, 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. Await tools and cleanup before the program ends; 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 the program ends; raw output belongs to the active evaluation.',
|
|
144
|
+
stripTypes: stripTypeScript,
|
|
145
|
+
}
|
|
146
|
+
}
|
|
131
147
|
|
|
132
148
|
function resolveMode(config: ResolvedConfig): ExecutionMode {
|
|
149
|
+
const outputInstructions = 'Use inspect(...values) to display output. Do not use console.'
|
|
150
|
+
+ ' Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression;'
|
|
151
|
+
+ ' write other text, in particular file contents and commands, as ordinary strings.'
|
|
152
|
+
+ ' Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal.'
|
|
133
153
|
switch (config.executionMode) {
|
|
134
154
|
case 'per-call': return {
|
|
135
155
|
format: 'function-body',
|
|
136
156
|
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.
|
|
157
|
+
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. ' + outputInstructions + ' 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
158
|
stripTypes(program) {
|
|
139
|
-
const stripped =
|
|
159
|
+
const stripped = stripTypeScript(STRIP_PREFIX + program + STRIP_SUFFIX)
|
|
140
160
|
return stripped.slice(STRIP_PREFIX.length, stripped.length - STRIP_SUFFIX.length)
|
|
141
161
|
},
|
|
142
162
|
}
|
|
143
|
-
case 'persistent-in-memory': return {
|
|
163
|
+
case 'persistent-in-memory': return config.replScoped ? scopedReplMode(outputInstructions) : {
|
|
144
164
|
format: 'repl',
|
|
145
165
|
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.
|
|
147
|
-
stripTypes:
|
|
166
|
+
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. ' + outputInstructions + ' 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,
|
|
167
|
+
stripTypes: stripTypeScript,
|
|
148
168
|
}
|
|
149
169
|
case 'vm-script': {
|
|
150
170
|
const lifetime = config.scriptPersistence
|
|
@@ -161,8 +181,8 @@ function resolveMode(config: ResolvedConfig): ExecutionMode {
|
|
|
161
181
|
return {
|
|
162
182
|
format: 'script',
|
|
163
183
|
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.
|
|
165
|
-
stripTypes:
|
|
184
|
+
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. ' + outputInstructions + ' The final expression is awaited if it is a Promise. ' + 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,
|
|
185
|
+
stripTypes: stripTypeScript,
|
|
166
186
|
}
|
|
167
187
|
}
|
|
168
188
|
/* v8 ignore next -- Loader validates the closed execution-mode union before selection. */
|
package/src/index.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/** Node PTC provider with uniform admission and configurable evaluation and process ownership. */
|
|
2
2
|
import { Context } from '@deepseek-ai/cordis'
|
|
3
|
-
import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime'
|
|
3
|
+
import { PtcRuntime, PtcRuntimeError } from '@deepseek-ai/dsh-ptc-runtime'
|
|
4
4
|
import type { PtcProgramFormat, PtcRunRequest, PtcRunResult, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
|
|
5
5
|
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
|
|
6
6
|
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
|
7
7
|
import type {} from '@deepseek-ai/dsh-fs'
|
|
8
8
|
import { resolveLaunch } from './launch.ts'
|
|
9
|
-
import { NodeConfig, validateConfig } from './config.ts'
|
|
9
|
+
import { NodeConfig, resolveReplScoped, validateConfig } from './config.ts'
|
|
10
10
|
import { createExecution } from './execution.ts'
|
|
11
11
|
import { PolicyProcesses } from './policy-processes.ts'
|
|
12
12
|
import type { Config, ResolvedConfig } from './config.ts'
|
|
@@ -14,6 +14,11 @@ export type { Config } from './config.ts'
|
|
|
14
14
|
export type { LaunchConfig } from './launch.ts'
|
|
15
15
|
|
|
16
16
|
interface LiveRun { controller: AbortController; finished: Promise<void> }
|
|
17
|
+
interface InitializerRegistration {
|
|
18
|
+
program: string
|
|
19
|
+
removing: boolean
|
|
20
|
+
cleanup?: Promise<void>
|
|
21
|
+
}
|
|
17
22
|
|
|
18
23
|
/** Node execution under file policy, with optional owner-scoped retained memory. */
|
|
19
24
|
export class NodePtcRuntime extends PtcRuntime {
|
|
@@ -30,23 +35,57 @@ export class NodePtcRuntime extends PtcRuntime {
|
|
|
30
35
|
private readonly config: ResolvedConfig
|
|
31
36
|
private readonly live = new Set<LiveRun>()
|
|
32
37
|
private disposed = false
|
|
38
|
+
private admitted = false
|
|
39
|
+
private initializer: InitializerRegistration | undefined
|
|
33
40
|
|
|
34
41
|
constructor(ctx: Context, config: Config) {
|
|
35
42
|
super(ctx)
|
|
36
|
-
this.config = { ...config, launch: resolveLaunch(config.launch) } as ResolvedConfig
|
|
43
|
+
this.config = { ...config, replScoped: resolveReplScoped(config), launch: resolveLaunch(config.launch) } as ResolvedConfig
|
|
37
44
|
validateConfig(this.config)
|
|
38
45
|
this.processes = new PolicyProcesses(ctx)
|
|
39
46
|
this.execution = createExecution(ctx, this.config, this.processes)
|
|
40
47
|
ctx.effect(() => async () => {
|
|
41
48
|
this.disposed = true
|
|
42
|
-
|
|
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
|
|
49
|
+
await this.drain('runtime disposed')
|
|
47
50
|
}, 'Node ptc-runtime cleanup')
|
|
48
51
|
}
|
|
49
52
|
|
|
53
|
+
private async drain(reason: string): Promise<void> {
|
|
54
|
+
const active = [...this.live]
|
|
55
|
+
for (const run of active) run.controller.abort(reason)
|
|
56
|
+
const results = await Promise.allSettled([this.execution.dispose(), ...active.map(run => run.finished)])
|
|
57
|
+
const failed = results.find(result => result.status === 'rejected')
|
|
58
|
+
if (failed?.status === 'rejected') throw failed.reason
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
override registerEnvironmentInitializer(program: string): () => Promise<void> {
|
|
62
|
+
if (this.disposed) throw new Error('ptc-runtime-node: initialization registration after disposal')
|
|
63
|
+
if (this.config.executionMode !== 'persistent-in-memory') {
|
|
64
|
+
throw new Error('ptc-runtime-node: initialization requires persistent-in-memory execution')
|
|
65
|
+
}
|
|
66
|
+
if (this.initializer !== undefined) throw new Error('ptc-runtime-node: environment initializer is already registered')
|
|
67
|
+
if (this.admitted) throw new Error('ptc-runtime-node: register initialization before the first run')
|
|
68
|
+
const registration: InitializerRegistration = {
|
|
69
|
+
program: this.execution.mode.stripTypes(program), removing: false,
|
|
70
|
+
}
|
|
71
|
+
this.initializer = registration
|
|
72
|
+
return () => {
|
|
73
|
+
if (this.initializer !== registration) return Promise.resolve()
|
|
74
|
+
registration.removing = true
|
|
75
|
+
if (registration.cleanup !== undefined) return registration.cleanup
|
|
76
|
+
const completion: PromiseWithResolvers<void> = Promise.withResolvers()
|
|
77
|
+
registration.cleanup = completion.promise
|
|
78
|
+
void this.drain('environment initializer removed').then(() => {
|
|
79
|
+
this.initializer = undefined
|
|
80
|
+
completion.resolve()
|
|
81
|
+
}, (error: unknown) => {
|
|
82
|
+
delete registration.cleanup
|
|
83
|
+
completion.reject(error)
|
|
84
|
+
})
|
|
85
|
+
return completion.promise
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
50
89
|
override get sandboxMode(): SandboxMode | undefined { return this.ctx.sandboxPolicy.defaultMode }
|
|
51
90
|
|
|
52
91
|
override release(owner: object): Promise<void> {
|
|
@@ -59,13 +98,14 @@ export class NodePtcRuntime extends PtcRuntime {
|
|
|
59
98
|
|
|
60
99
|
/**
|
|
61
100
|
* Resolve directory, deadline and file policy for the selected execution mode.
|
|
62
|
-
* @param request - Program, bindings,
|
|
101
|
+
* @param request - Program, bindings, cwd/deadline, and resolved authority.
|
|
63
102
|
* @returns Complete execution inputs with a capped numeric budget or an explicit null deadline.
|
|
103
|
+
* @throws When an execution choice is invalid or the provider is disposed.
|
|
64
104
|
*/
|
|
65
105
|
resolve(request: PtcRunRequest): PtcRunSpec {
|
|
66
106
|
if (this.disposed) {
|
|
67
107
|
const source = this.retainsState ? 'persistent PTC' : 'ptc-runtime-node'
|
|
68
|
-
throw new
|
|
108
|
+
throw new PtcRuntimeError(`${source}: resolve after disposal`, 'PTC_RUNTIME_UNAVAILABLE')
|
|
69
109
|
}
|
|
70
110
|
return this.execution.resolve(request)
|
|
71
111
|
}
|
|
@@ -77,7 +117,12 @@ export class NodePtcRuntime extends PtcRuntime {
|
|
|
77
117
|
* @returns Logs, JSON completion or failure; retained processes remain until release or invalidation.
|
|
78
118
|
*/
|
|
79
119
|
async run(spec: PtcRunSpec): Promise<PtcRunResult> {
|
|
80
|
-
if (this.disposed) throw new
|
|
120
|
+
if (this.disposed) throw new PtcRuntimeError('ptc-runtime-node: run after disposal', 'PTC_RUNTIME_UNAVAILABLE')
|
|
121
|
+
if (this.initializer?.removing) {
|
|
122
|
+
throw new PtcRuntimeError('ptc-runtime-node: environment initialization cleanup is incomplete', 'PTC_RUNTIME_UNAVAILABLE')
|
|
123
|
+
}
|
|
124
|
+
this.admitted = true
|
|
125
|
+
const initialization = this.initializer?.program
|
|
81
126
|
const controller = new AbortController()
|
|
82
127
|
const completion = Promise.withResolvers<void>()
|
|
83
128
|
const unregister = spec.sandboxPolicy === undefined ? undefined : this.processes.register(spec.sandboxPolicy, async () => {
|
|
@@ -90,9 +135,9 @@ export class NodePtcRuntime extends PtcRuntime {
|
|
|
90
135
|
await this.processes.wait(spec.sandboxPolicy?.sessionId)
|
|
91
136
|
// Disposal can begin while a previous policy's process cleanup is pending.
|
|
92
137
|
// oxlint-disable-next-line typescript/no-unnecessary-condition
|
|
93
|
-
if (this.disposed) throw new
|
|
138
|
+
if (this.disposed) throw new PtcRuntimeError(`${this.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: run after disposal`, 'PTC_RUNTIME_UNAVAILABLE')
|
|
94
139
|
const signal = spec.signal === undefined ? controller.signal : AbortSignal.any([spec.signal, controller.signal])
|
|
95
|
-
return await this.execution.run({ ...spec, signal })
|
|
140
|
+
return await this.execution.run({ ...spec, signal }, initialization)
|
|
96
141
|
} finally {
|
|
97
142
|
unregister?.()
|
|
98
143
|
this.live.delete(live)
|
package/src/json-wire.ts
CHANGED
|
@@ -145,9 +145,10 @@ type SnapshotTask =
|
|
|
145
145
|
* Its iterative traversal adds no JavaScript call-stack depth limit.
|
|
146
146
|
*
|
|
147
147
|
* @param value - the candidate completion value.
|
|
148
|
+
* @param isImage - Optional recognition of host-issued binding images.
|
|
148
149
|
* @returns a detached lossless-JSON snapshot, or `undefined` when invalid.
|
|
149
150
|
*/
|
|
150
|
-
export function snapshotPtcJsonValue(value: unknown): PtcJsonValue | undefined {
|
|
151
|
+
export function snapshotPtcJsonValue(value: unknown, isImage?: (value: object) => boolean): PtcJsonValue | undefined {
|
|
151
152
|
const active = new IntrinsicSet<object>()
|
|
152
153
|
let root: PtcJsonValue | undefined
|
|
153
154
|
const assign = (destination: SnapshotDestination, item: PtcJsonValue): void => {
|
|
@@ -199,6 +200,10 @@ export function snapshotPtcJsonValue(value: unknown): PtcJsonValue | undefined {
|
|
|
199
200
|
continue
|
|
200
201
|
}
|
|
201
202
|
if (typeof candidate !== 'object') return undefined
|
|
203
|
+
if (isImage?.(candidate)) {
|
|
204
|
+
assign(task.destination, candidate as PtcJsonValue)
|
|
205
|
+
continue
|
|
206
|
+
}
|
|
202
207
|
if (setHas(active, candidate)) return undefined
|
|
203
208
|
|
|
204
209
|
if (intrinsicArrayIsArray(candidate)) {
|
|
@@ -242,7 +247,17 @@ interface ObjectWireToken {
|
|
|
242
247
|
keys: string[]
|
|
243
248
|
}
|
|
244
249
|
|
|
245
|
-
|
|
250
|
+
/** One registered image crossing the program control channel. */
|
|
251
|
+
export interface PtcImageWire {
|
|
252
|
+
kind: 'image'
|
|
253
|
+
id: string
|
|
254
|
+
attachmentId: string
|
|
255
|
+
path: string
|
|
256
|
+
width: number
|
|
257
|
+
height: number
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
type PtcJsonToken = null | boolean | number | string | ArrayWireToken | ObjectWireToken | PtcImageWire
|
|
246
261
|
|
|
247
262
|
/**
|
|
248
263
|
* A pre-order, bounded-depth transport for one lossless JSON value. Container
|
|
@@ -254,12 +269,18 @@ export type PtcJsonWire = PtcJsonToken[]
|
|
|
254
269
|
/**
|
|
255
270
|
* Flatten one validated JSON value for the process control channel.
|
|
256
271
|
* @param value - the lossless JSON value to transport.
|
|
272
|
+
* @param image - Optional encoder for registered binding images.
|
|
257
273
|
* @returns a pre-order token stream whose own nesting is bounded.
|
|
258
274
|
*/
|
|
259
|
-
export function encodePtcJsonWire(value: PtcJsonValue): PtcJsonWire {
|
|
275
|
+
export function encodePtcJsonWire(value: PtcJsonValue, image?: (value: object) => PtcImageWire | undefined): PtcJsonWire {
|
|
260
276
|
const wire: PtcJsonWire = []
|
|
261
277
|
const pending: PtcJsonValue[] = [value]
|
|
262
278
|
for (let current = takeLast(pending); current !== undefined; current = takeLast(pending)) {
|
|
279
|
+
const imageToken = current !== null && typeof current === 'object' ? image?.(current) : undefined
|
|
280
|
+
if (imageToken !== undefined) {
|
|
281
|
+
append(wire, imageToken)
|
|
282
|
+
continue
|
|
283
|
+
}
|
|
263
284
|
if (current === null || typeof current === 'boolean' || typeof current === 'number' || typeof current === 'string') {
|
|
264
285
|
append(wire, current)
|
|
265
286
|
continue
|
|
@@ -308,8 +329,8 @@ function keysContain(keys: string[], expected: string): boolean {
|
|
|
308
329
|
return false
|
|
309
330
|
}
|
|
310
331
|
|
|
311
|
-
/**
|
|
312
|
-
function
|
|
332
|
+
/** Parse one array, object, or image token, rejecting extra or missing fields. */
|
|
333
|
+
function parseWireToken(value: object): ArrayWireToken | ObjectWireToken | PtcImageWire | undefined {
|
|
313
334
|
if (intrinsicArrayIsArray(value) || !hasPlainObjectPrototype(value)) return undefined
|
|
314
335
|
const keys = enumerableStringKeys(value)
|
|
315
336
|
if (keys === undefined) return undefined
|
|
@@ -336,6 +357,17 @@ function containerToken(value: object): ArrayWireToken | ObjectWireToken | undef
|
|
|
336
357
|
}
|
|
337
358
|
return { kind: 'object', keys: normalizedKeys }
|
|
338
359
|
}
|
|
360
|
+
if (token.kind === 'image') {
|
|
361
|
+
if (keys.length !== 6
|
|
362
|
+
|| !keysContain(keys, 'kind') || !keysContain(keys, 'id') || !keysContain(keys, 'path')
|
|
363
|
+
|| !keysContain(keys, 'attachmentId') || !keysContain(keys, 'width') || !keysContain(keys, 'height')) return undefined
|
|
364
|
+
if (typeof token.id !== 'string' || token.id.length === 0
|
|
365
|
+
|| typeof token.attachmentId !== 'string' || token.attachmentId.length === 0
|
|
366
|
+
|| typeof token.path !== 'string' || token.path.length === 0
|
|
367
|
+
|| typeof token.width !== 'number' || !intrinsicNumberIsSafeInteger(token.width) || token.width <= 0
|
|
368
|
+
|| typeof token.height !== 'number' || !intrinsicNumberIsSafeInteger(token.height) || token.height <= 0) return undefined
|
|
369
|
+
return { kind: 'image', id: token.id, attachmentId: token.attachmentId, path: token.path, width: token.width, height: token.height }
|
|
370
|
+
}
|
|
339
371
|
return undefined
|
|
340
372
|
}
|
|
341
373
|
|
|
@@ -344,9 +376,10 @@ function containerToken(value: object): ArrayWireToken | ObjectWireToken | undef
|
|
|
344
376
|
* Malformed or incomplete traffic returns `undefined`; traversal is iterative
|
|
345
377
|
* and therefore independent of the transported value's application depth.
|
|
346
378
|
* @param input - untrusted message-port payload.
|
|
379
|
+
* @param image - Optional decoder for registered binding images.
|
|
347
380
|
* @returns the detached JSON value, or `undefined` when the wire is invalid.
|
|
348
381
|
*/
|
|
349
|
-
export function decodePtcJsonWire(input: unknown): PtcJsonValue | undefined {
|
|
382
|
+
export function decodePtcJsonWire(input: unknown, image?: (value: PtcImageWire) => PtcJsonValue): PtcJsonValue | undefined {
|
|
350
383
|
try {
|
|
351
384
|
if (!intrinsicArrayIsArray(input) || !isDenseArray(input) || input.length === 0) return undefined
|
|
352
385
|
const wire = input as unknown[]
|
|
@@ -387,7 +420,7 @@ export function decodePtcJsonWire(input: unknown): PtcJsonValue | undefined {
|
|
|
387
420
|
value = token
|
|
388
421
|
} else {
|
|
389
422
|
if (typeof token !== 'object') return undefined
|
|
390
|
-
const marker =
|
|
423
|
+
const marker = parseWireToken(token)
|
|
391
424
|
if (!marker) return undefined
|
|
392
425
|
const remainingTokens = wire.length - tokenIndex - 1
|
|
393
426
|
if (marker.kind === 'array') {
|
|
@@ -395,11 +428,14 @@ export function decodePtcJsonWire(input: unknown): PtcJsonValue | undefined {
|
|
|
395
428
|
const target: PtcJsonValue[] = []
|
|
396
429
|
value = target
|
|
397
430
|
if (marker.length > 0) frame = { kind: 'array', target, length: marker.length, index: 0 }
|
|
398
|
-
} else {
|
|
431
|
+
} else if (marker.kind === 'object') {
|
|
399
432
|
if (marker.keys.length > remainingTokens) return undefined
|
|
400
433
|
const target: Record<string, PtcJsonValue> = {}
|
|
401
434
|
value = target
|
|
402
435
|
if (marker.keys.length > 0) frame = { kind: 'object', target, keys: marker.keys, index: 0 }
|
|
436
|
+
} else {
|
|
437
|
+
if (image === undefined) return undefined
|
|
438
|
+
value = image(marker)
|
|
403
439
|
}
|
|
404
440
|
}
|
|
405
441
|
if (!attach(value)) return undefined
|
package/src/output-ledger.ts
CHANGED
|
@@ -1,66 +1,63 @@
|
|
|
1
1
|
/** Combined byte accounting for retained program output. */
|
|
2
|
-
import type { PtcJsonValue, PtcRunFailure, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime'
|
|
2
|
+
import type { PtcOutput, PtcJsonValue, PtcRunFailure, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime'
|
|
3
3
|
import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from './output-json.ts'
|
|
4
4
|
|
|
5
|
+
/** Measure a text entry or an image descriptor against the remaining JSON-byte budget. */
|
|
6
|
+
function entryBytes(entry: PtcOutput, available: number): number | undefined {
|
|
7
|
+
return entry.type === 'text' ? jsonStringBytesUpTo(entry.text, available)
|
|
8
|
+
: jsonValueBytesUpTo({ ...entry, attachment: { ...entry.attachment } }, available)
|
|
9
|
+
}
|
|
10
|
+
|
|
5
11
|
/** One run's combined outer-output ledger; binding values never enter it. */
|
|
6
12
|
export class OutputLedger {
|
|
7
|
-
private bytes = 2 // JSON serialization of the empty
|
|
13
|
+
private bytes = 2 // JSON serialization of the empty output array: []
|
|
8
14
|
private entries = 0
|
|
15
|
+
truncated = false
|
|
9
16
|
|
|
10
|
-
constructor(private readonly maxBytes: number
|
|
17
|
+
constructor(private readonly maxBytes: number) {}
|
|
11
18
|
|
|
12
|
-
/** Admit one
|
|
13
|
-
admit(
|
|
19
|
+
/** Admit one ordered text or image entry against the combined output budget. */
|
|
20
|
+
admit(entry: PtcOutput, sink: PtcOutput[]): boolean {
|
|
21
|
+
if (this.truncated) return false
|
|
14
22
|
const separatorBytes = this.entries > 0 ? 1 : 0
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
23
|
+
const remaining = this.maxBytes - this.bytes - separatorBytes
|
|
24
|
+
const bytes = entryBytes(entry, remaining)
|
|
25
|
+
if (bytes === undefined) {
|
|
26
|
+
this.truncated = true
|
|
27
|
+
if (entry.type === 'text') {
|
|
28
|
+
const prefix = truncateJsonStringBytes(entry.text, remaining)
|
|
29
|
+
if (prefix.length > 0) sink.push({ type: 'text', text: prefix })
|
|
30
|
+
}
|
|
31
|
+
return false
|
|
32
|
+
}
|
|
33
|
+
this.bytes += bytes + separatorBytes
|
|
18
34
|
this.entries += 1
|
|
19
|
-
sink.push(
|
|
35
|
+
sink.push(entry)
|
|
20
36
|
return true
|
|
21
37
|
}
|
|
22
38
|
|
|
23
39
|
/** Finalize a successful absent-or-JSON completion against the combined cap. */
|
|
24
|
-
success(
|
|
25
|
-
|
|
26
|
-
return
|
|
40
|
+
success(output: PtcOutput[], value?: PtcJsonValue): PtcRunResult {
|
|
41
|
+
const valueBytes = value === undefined ? 0 : jsonValueBytesUpTo(value, this.maxBytes - 2)
|
|
42
|
+
if (valueBytes === undefined) return this.failure(output, { kind: 'output-limit', message: `completion value exceeded ${this.maxBytes} bytes` })
|
|
43
|
+
return { ...this.retain(output, valueBytes), ...value !== undefined ? { value } : {} }
|
|
27
44
|
}
|
|
28
45
|
|
|
29
|
-
/**
|
|
30
|
-
failure(
|
|
31
|
-
|
|
32
|
-
|
|
46
|
+
/** Prioritize the terminal diagnostic without changing its failure kind. */
|
|
47
|
+
failure(output: PtcOutput[], error: PtcRunFailure): PtcRunResult {
|
|
48
|
+
const message = truncateJsonStringBytes(error.message, this.maxBytes - 2)
|
|
49
|
+
if (message !== error.message) this.truncated = true
|
|
50
|
+
return { ...this.retain(output, Buffer.byteLength(JSON.stringify(message))), error: { ...error, message } }
|
|
33
51
|
}
|
|
34
52
|
|
|
35
|
-
/**
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
let retainedBytes = 2
|
|
42
|
-
const logBudget = this.maxBytes - messageBytes
|
|
43
|
-
for (const text of logs) {
|
|
44
|
-
const separatorBytes = retained.length > 0 ? 1 : 0
|
|
45
|
-
const availableBytes = logBudget - retainedBytes - separatorBytes
|
|
46
|
-
const stringBytes = jsonStringBytesUpTo(text, availableBytes)
|
|
47
|
-
if (stringBytes !== undefined) {
|
|
48
|
-
retained.push(text)
|
|
49
|
-
retainedBytes += stringBytes + separatorBytes
|
|
50
|
-
continue
|
|
51
|
-
}
|
|
52
|
-
const prefix = truncateJsonStringBytes(text, availableBytes)
|
|
53
|
-
if (prefix.length > 0) {
|
|
54
|
-
const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes)
|
|
55
|
-
/* v8 ignore next -- truncateJsonStringBytes guarantees its returned prefix fits the same budget. */
|
|
56
|
-
if (prefixBytes === undefined) throw new Error('output ledger produced an oversized log prefix')
|
|
57
|
-
retained.push(prefix)
|
|
58
|
-
retainedBytes += prefixBytes + separatorBytes
|
|
59
|
-
}
|
|
60
|
-
break
|
|
53
|
+
/** Keep an ordered prefix after reserving bytes for the completion or diagnostic. */
|
|
54
|
+
private retain(output: PtcOutput[], terminalBytes: number): Pick<PtcRunResult, 'output' | 'outputTruncated'> {
|
|
55
|
+
const retained: PtcOutput[] = []
|
|
56
|
+
const ledger = new OutputLedger(this.maxBytes - terminalBytes)
|
|
57
|
+
for (const entry of output) {
|
|
58
|
+
if (!ledger.admit(entry, retained)) break
|
|
61
59
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
return { logs: retained, error: { kind: 'output-limit', message } }
|
|
60
|
+
this.truncated ||= ledger.truncated
|
|
61
|
+
return { output: retained, ...this.truncated ? { outputTruncated: true } : {} }
|
|
65
62
|
}
|
|
66
63
|
}
|