@deepseek-ai/dsh-ptc-runtime-node 0.2.2-rc.5 → 0.2.3-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.i18n.yaml +24 -24
  2. package/README.md +49 -17
  3. package/README.zh.md +49 -17
  4. package/lib/configuration.js +15 -5
  5. package/lib/index.js +439 -148
  6. package/lib/persistent-process.js +683 -90
  7. package/lib/process.js +683 -90
  8. package/lib/types/bindings.d.ts +10 -5
  9. package/lib/types/bindings.d.ts.map +1 -1
  10. package/lib/types/bindings.js.map +1 -1
  11. package/lib/types/bootstrap.d.ts +42 -24
  12. package/lib/types/bootstrap.d.ts.map +1 -1
  13. package/lib/types/bootstrap.js.map +1 -1
  14. package/lib/types/config.d.ts +14 -2
  15. package/lib/types/config.d.ts.map +1 -1
  16. package/lib/types/config.js.map +1 -1
  17. package/lib/types/configuration.d.ts +5 -4
  18. package/lib/types/configuration.d.ts.map +1 -1
  19. package/lib/types/configuration.js.map +1 -1
  20. package/lib/types/environment.d.ts +13 -0
  21. package/lib/types/environment.d.ts.map +1 -1
  22. package/lib/types/environment.js.map +1 -1
  23. package/lib/types/evaluators/index.d.ts.map +1 -1
  24. package/lib/types/evaluators/index.js.map +1 -1
  25. package/lib/types/evaluators/scoped-repl-evaluator.d.ts +22 -0
  26. package/lib/types/evaluators/scoped-repl-evaluator.d.ts.map +1 -0
  27. package/lib/types/evaluators/scoped-repl-evaluator.js.map +1 -0
  28. package/lib/types/evaluators/scoped-repl.d.ts +130 -0
  29. package/lib/types/evaluators/scoped-repl.d.ts.map +1 -0
  30. package/lib/types/evaluators/scoped-repl.js.map +1 -0
  31. package/lib/types/evaluators/types.d.ts +3 -3
  32. package/lib/types/evaluators/types.d.ts.map +1 -1
  33. package/lib/types/evaluators/types.js.map +1 -1
  34. package/lib/types/execution.d.ts +3 -2
  35. package/lib/types/execution.d.ts.map +1 -1
  36. package/lib/types/execution.js.map +1 -1
  37. package/lib/types/index.d.ts +6 -1
  38. package/lib/types/index.d.ts.map +1 -1
  39. package/lib/types/index.js.map +1 -1
  40. package/lib/types/json-wire.d.ts +16 -4
  41. package/lib/types/json-wire.d.ts.map +1 -1
  42. package/lib/types/json-wire.js.map +1 -1
  43. package/lib/types/output-ledger.d.ts +10 -10
  44. package/lib/types/output-ledger.d.ts.map +1 -1
  45. package/lib/types/output-ledger.js.map +1 -1
  46. package/lib/types/process.d.ts +2 -0
  47. package/lib/types/process.d.ts.map +1 -1
  48. package/lib/types/process.js.map +1 -1
  49. package/lib/types/protocol.d.ts +31 -5
  50. package/lib/types/protocol.d.ts.map +1 -1
  51. package/lib/types/protocol.js.map +1 -1
  52. package/lib/types/worker.d.ts +6 -3
  53. package/lib/types/worker.d.ts.map +1 -1
  54. package/lib/types/worker.js.map +1 -1
  55. package/package.json +23 -21
  56. package/src/bindings.ts +33 -26
  57. package/src/bootstrap.ts +159 -57
  58. package/src/config.ts +21 -3
  59. package/src/configuration.ts +13 -6
  60. package/src/environment.ts +39 -0
  61. package/src/evaluators/index.ts +2 -0
  62. package/src/evaluators/scoped-repl-evaluator.ts +110 -0
  63. package/src/evaluators/scoped-repl.ts +339 -0
  64. package/src/evaluators/types.ts +3 -3
  65. package/src/execution.ts +37 -17
  66. package/src/index.ts +58 -13
  67. package/src/json-wire.ts +44 -8
  68. package/src/output-ledger.ts +42 -45
  69. package/src/process.ts +89 -18
  70. package/src/protocol.ts +37 -10
  71. package/src/worker.ts +75 -40
package/lib/index.js CHANGED
@@ -1,10 +1,13 @@
1
+ import { resolvePersistentExecution } from "./configuration.js";
1
2
  import { stripTypeScriptTypes } from "node:module";
2
- import { DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, PtcRuntime, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from "@deepseek-ai/dsh-ptc-runtime";
3
+ import { PtcImage, PtcInspectableValue, PtcRuntime, PtcRuntimeError, RESERVED_BINDING_GLOBALS, RESERVED_BINDING_WORDS, RESERVED_ERROR_MEMBERS } from "@deepseek-ai/dsh-ptc-runtime";
3
4
  import { dirname, isAbsolute, resolve } from "node:path";
4
5
  import { fileURLToPath, pathToFileURL } from "node:url";
5
- import { assertNever, snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
6
+ import { assertNever } from "@deepseek-ai/dsh-util-values";
6
7
  import z from "@deepseek-ai/schemastery";
7
8
  import { MAX_TIMER_DELAY_MS, clampTimeout } from "@deepseek-ai/dsh-timeout";
9
+ import "acorn";
10
+ import { randomUUID } from "node:crypto";
8
11
  import { AsyncLocalStorage } from "node:async_hooks";
9
12
  import { SandboxUnavailableError, classifyRunnerFailure, isRunnerSpawnFailure } from "@deepseek-ai/dsh-sandbox";
10
13
  import { Buffer as Buffer$1 } from "node:buffer";
@@ -66,8 +69,9 @@ const NodeConfig = z.object({
66
69
  z.const("per-call"),
67
70
  z.const("persistent-in-memory"),
68
71
  z.const("vm-script")
69
- ]).default("per-call"),
72
+ ]).default("persistent-in-memory"),
70
73
  scriptPersistence: z.boolean().default(false),
74
+ replScoped: z.boolean(),
71
75
  timeoutMs: z.number().default(12e4),
72
76
  maxTimeoutMs: z.number().default(6e5),
73
77
  maxOutputBytes: z.number().default(67108864),
@@ -86,11 +90,21 @@ const NodeConfig = z.object({
86
90
  })])
87
91
  });
88
92
  /**
93
+ * Select the scoped REPL setting for the configured execution mode.
94
+ * @param config - Loader-defaulted fields whose `replScoped` may be omitted.
95
+ * @returns The explicit setting; when omitted, the setting that `resolvePersistentExecution` writes for function bodies with
96
+ * `persistent-in-memory`, and false in other modes.
97
+ */
98
+ function resolveReplScoped(config) {
99
+ return config.replScoped ?? (config.executionMode === "persistent-in-memory" && resolvePersistentExecution().replScoped);
100
+ }
101
+ /**
89
102
  * Validate resolved Node limits and paths.
90
103
  * @param config - Loader-defaulted fields with the selected executable.
91
104
  */
92
105
  function validateConfig(config) {
93
106
  if (config.scriptPersistence && config.executionMode !== "vm-script") throw new Error("ptc-runtime-node: scriptPersistence requires executionMode: vm-script");
107
+ if (config.replScoped && config.executionMode !== "persistent-in-memory") throw new Error("ptc-runtime-node: replScoped requires executionMode: persistent-in-memory");
94
108
  for (const [key, value] of Object.entries(config)) if (typeof value === "number" && (!Number.isFinite(value) || value <= 0)) throw new Error(`ptc-runtime-node: ${key} must be positive and finite`);
95
109
  for (const key of [
96
110
  "timeoutMs",
@@ -128,7 +142,7 @@ const intrinsicObjectPrototype = Object.prototype;
128
142
  const intrinsicObjectPropertyIsEnumerable = Reflect.get(intrinsicObjectPrototype, "propertyIsEnumerable");
129
143
  const intrinsicReflectOwnKeys = Reflect.ownKeys;
130
144
  const intrinsicSetAdd = Reflect.get(Set.prototype, "add");
131
- Reflect.get(Set.prototype, "delete");
145
+ const intrinsicSetDelete = Reflect.get(Set.prototype, "delete");
132
146
  const intrinsicSetHas = Reflect.get(Set.prototype, "has");
133
147
  /** Build a data descriptor that cannot inherit model-defined accessor fields. */
134
148
  function dataDescriptor$1(value) {
@@ -164,6 +178,10 @@ function setHas(target, value) {
164
178
  function setAdd(target, value) {
165
179
  intrinsicReflectApply$1(intrinsicSetAdd, target, [value]);
166
180
  }
181
+ /** Delete from one captured-intrinsic Set. */
182
+ function setDelete(target, value) {
183
+ intrinsicReflectApply$1(intrinsicSetDelete, target, [value]);
184
+ }
167
185
  /** Whether a realm-owned intrinsic prototype is backed by its native constructor. */
168
186
  function hasIntrinsicConstructor(prototype, name) {
169
187
  const constructor = intrinsicObjectGetOwnPropertyDescriptor(prototype, "constructor")?.value;
@@ -201,14 +219,136 @@ function enumerableStringKeys(value) {
201
219
  return keys;
202
220
  }
203
221
  /**
222
+ * Validate and detach one process-boundary value without loading another
223
+ * workspace package at runtime. This mirrors the session-owned canonical
224
+ * JSON boundary while remaining safe to import from the unbuilt bootstrap.
225
+ * Its iterative traversal adds no JavaScript call-stack depth limit.
226
+ *
227
+ * @param value - the candidate completion value.
228
+ * @param isImage - Optional recognition of host-issued binding images.
229
+ * @returns a detached lossless-JSON snapshot, or `undefined` when invalid.
230
+ */
231
+ function snapshotPtcJsonValue(value, isImage) {
232
+ const active = new IntrinsicSet();
233
+ let root;
234
+ const assign = (destination, item) => {
235
+ if (destination.kind === "root") root = item;
236
+ else if (destination.kind === "array") defineEnumerableDataProperty$1(destination.target, destination.index, item);
237
+ else defineEnumerableDataProperty$1(destination.target, destination.key, item);
238
+ };
239
+ const tasks = [{
240
+ kind: "visit",
241
+ value,
242
+ destination: { kind: "root" }
243
+ }];
244
+ for (let task = takeLast$1(tasks); task !== void 0; task = takeLast$1(tasks)) {
245
+ if (task.kind === "leave") {
246
+ setDelete(active, task.source);
247
+ continue;
248
+ }
249
+ if (task.kind === "array-item") {
250
+ if (!intrinsicObjectHasOwn(task.source, task.index)) return void 0;
251
+ append$1(tasks, {
252
+ kind: "visit",
253
+ value: task.source[task.index],
254
+ destination: {
255
+ kind: "array",
256
+ target: task.target,
257
+ index: task.index
258
+ }
259
+ });
260
+ continue;
261
+ }
262
+ if (task.kind === "object-property") {
263
+ append$1(tasks, {
264
+ kind: "visit",
265
+ value: task.source[task.key],
266
+ destination: {
267
+ kind: "object",
268
+ target: task.target,
269
+ key: task.key
270
+ }
271
+ });
272
+ continue;
273
+ }
274
+ const candidate = task.value;
275
+ if (candidate === null) {
276
+ assign(task.destination, null);
277
+ continue;
278
+ }
279
+ if (typeof candidate === "boolean" || typeof candidate === "string") {
280
+ assign(task.destination, candidate);
281
+ continue;
282
+ }
283
+ if (typeof candidate === "number") {
284
+ if (!intrinsicNumberIsFinite(candidate) || intrinsicObjectIs(candidate, -0)) return void 0;
285
+ assign(task.destination, candidate);
286
+ continue;
287
+ }
288
+ if (typeof candidate !== "object") return void 0;
289
+ if (isImage?.(candidate)) {
290
+ assign(task.destination, candidate);
291
+ continue;
292
+ }
293
+ if (setHas(active, candidate)) return void 0;
294
+ if (intrinsicArrayIsArray$1(candidate)) {
295
+ if (!hasPlainArrayPrototype(candidate)) return void 0;
296
+ const length = candidate.length;
297
+ if (intrinsicReflectOwnKeys(candidate).length !== length + 1) return void 0;
298
+ const target = [];
299
+ assign(task.destination, target);
300
+ setAdd(active, candidate);
301
+ append$1(tasks, {
302
+ kind: "leave",
303
+ source: candidate
304
+ });
305
+ for (let index = length - 1; index >= 0; index--) append$1(tasks, {
306
+ kind: "array-item",
307
+ source: candidate,
308
+ index,
309
+ target
310
+ });
311
+ continue;
312
+ }
313
+ if (!hasPlainObjectPrototype(candidate)) return void 0;
314
+ const keys = enumerableStringKeys(candidate);
315
+ if (keys === void 0) return void 0;
316
+ const target = {};
317
+ assign(task.destination, target);
318
+ setAdd(active, candidate);
319
+ append$1(tasks, {
320
+ kind: "leave",
321
+ source: candidate
322
+ });
323
+ for (let index = keys.length - 1; index >= 0; index--) {
324
+ const key = keys[index];
325
+ /* v8 ignore next -- the loop is bounded by the captured key count. */
326
+ if (key === void 0) return void 0;
327
+ append$1(tasks, {
328
+ kind: "object-property",
329
+ source: candidate,
330
+ key,
331
+ target
332
+ });
333
+ }
334
+ }
335
+ return root;
336
+ }
337
+ /**
204
338
  * Flatten one validated JSON value for the process control channel.
205
339
  * @param value - the lossless JSON value to transport.
340
+ * @param image - Optional encoder for registered binding images.
206
341
  * @returns a pre-order token stream whose own nesting is bounded.
207
342
  */
208
- function encodePtcJsonWire(value) {
343
+ function encodePtcJsonWire(value, image) {
209
344
  const wire = [];
210
345
  const pending = [value];
211
346
  for (let current = takeLast$1(pending); current !== void 0; current = takeLast$1(pending)) {
347
+ const imageToken = current !== null && typeof current === "object" ? image?.(current) : void 0;
348
+ if (imageToken !== void 0) {
349
+ append$1(wire, imageToken);
350
+ continue;
351
+ }
212
352
  if (current === null || typeof current === "boolean" || typeof current === "number" || typeof current === "string") {
213
353
  append$1(wire, current);
214
354
  continue;
@@ -252,8 +392,8 @@ function keysContain(keys, expected) {
252
392
  for (let index = 0; index < keys.length; index++) if (keys[index] === expected) return true;
253
393
  return false;
254
394
  }
255
- /** Return one exact container marker, or reject any extra/missing fields. */
256
- function containerToken(value) {
395
+ /** Parse one array, object, or image token, rejecting extra or missing fields. */
396
+ function parseWireToken(value) {
257
397
  if (intrinsicArrayIsArray$1(value) || !hasPlainObjectPrototype(value)) return void 0;
258
398
  const keys = enumerableStringKeys(value);
259
399
  if (keys === void 0) return void 0;
@@ -284,15 +424,28 @@ function containerToken(value) {
284
424
  keys: normalizedKeys
285
425
  };
286
426
  }
427
+ if (token.kind === "image") {
428
+ if (keys.length !== 6 || !keysContain(keys, "kind") || !keysContain(keys, "id") || !keysContain(keys, "path") || !keysContain(keys, "attachmentId") || !keysContain(keys, "width") || !keysContain(keys, "height")) return void 0;
429
+ if (typeof token.id !== "string" || token.id.length === 0 || typeof token.attachmentId !== "string" || token.attachmentId.length === 0 || typeof token.path !== "string" || token.path.length === 0 || typeof token.width !== "number" || !intrinsicNumberIsSafeInteger(token.width) || token.width <= 0 || typeof token.height !== "number" || !intrinsicNumberIsSafeInteger(token.height) || token.height <= 0) return void 0;
430
+ return {
431
+ kind: "image",
432
+ id: token.id,
433
+ attachmentId: token.attachmentId,
434
+ path: token.path,
435
+ width: token.width,
436
+ height: token.height
437
+ };
438
+ }
287
439
  }
288
440
  /**
289
441
  * Rebuild one lossless JSON value from the flat process wire format.
290
442
  * Malformed or incomplete traffic returns `undefined`; traversal is iterative
291
443
  * and therefore independent of the transported value's application depth.
292
444
  * @param input - untrusted message-port payload.
445
+ * @param image - Optional decoder for registered binding images.
293
446
  * @returns the detached JSON value, or `undefined` when the wire is invalid.
294
447
  */
295
- function decodePtcJsonWire(input) {
448
+ function decodePtcJsonWire(input, image) {
296
449
  try {
297
450
  if (!intrinsicArrayIsArray$1(input) || !isDenseArray(input) || input.length === 0) return void 0;
298
451
  const wire = input;
@@ -329,7 +482,7 @@ function decodePtcJsonWire(input) {
329
482
  value = token;
330
483
  } else {
331
484
  if (typeof token !== "object") return void 0;
332
- const marker = containerToken(token);
485
+ const marker = parseWireToken(token);
333
486
  if (!marker) return void 0;
334
487
  const remainingTokens = wire.length - tokenIndex - 1;
335
488
  if (marker.kind === "array") {
@@ -342,7 +495,7 @@ function decodePtcJsonWire(input) {
342
495
  length: marker.length,
343
496
  index: 0
344
497
  };
345
- } else {
498
+ } else if (marker.kind === "object") {
346
499
  if (marker.keys.length > remainingTokens) return void 0;
347
500
  const target = {};
348
501
  value = target;
@@ -352,6 +505,9 @@ function decodePtcJsonWire(input) {
352
505
  keys: marker.keys,
353
506
  index: 0
354
507
  };
508
+ } else {
509
+ if (image === void 0) return void 0;
510
+ value = image(marker);
355
511
  }
356
512
  }
357
513
  if (!attach(value)) return void 0;
@@ -372,29 +528,30 @@ function decodePtcJsonWire(input) {
372
528
  //#endregion
373
529
  //#region lib/types/bindings.js
374
530
  /** Validate and capture the binding names available to one program. */
375
- const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
531
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
376
532
  /**
377
533
  * Reject unusable namespaces before starting a process.
378
534
  * @param request - Host-owned binding declarations.
535
+ * @param programFormat - Evaluator syntax whose internal identifiers must remain reserved.
379
536
  * @returns Namespaces keyed by their declared global.
380
537
  */
381
- function validateBindings(request) {
538
+ function validateBindings(request, programFormat) {
382
539
  const bindings = /* @__PURE__ */ new Map();
383
540
  for (const namespace of request.bindings) {
384
- if (!IDENTIFIER.test(namespace.global) || PORTABLE_RESERVED_WORDS.has(namespace.global)) throw new Error(`dsh-ptc-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`);
385
- if (RESERVED_BINDING_GLOBALS.has(namespace.global)) throw new Error(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(namespace.global)}`);
386
- if (bindings.has(namespace.global)) throw new Error(`dsh-ptc-runtime-node: duplicate binding global ${JSON.stringify(namespace.global)}`);
541
+ if (!IDENTIFIER.test(namespace.global) || RESERVED_BINDING_WORDS.has(namespace.global) || programFormat === "scoped-repl" && namespace.global.includes("__$binding_")) throw new PtcRuntimeError(`dsh-ptc-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`, "PTC_RUNTIME_INVALID_ARGUMENT");
542
+ if (RESERVED_BINDING_GLOBALS.has(namespace.global)) throw new PtcRuntimeError(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(namespace.global)}`, "PTC_RUNTIME_INVALID_ARGUMENT");
543
+ if (bindings.has(namespace.global)) throw new PtcRuntimeError(`dsh-ptc-runtime-node: duplicate binding global ${JSON.stringify(namespace.global)}`, "PTC_RUNTIME_INVALID_ARGUMENT");
387
544
  bindings.set(namespace.global, namespace);
388
545
  }
389
546
  const errorClassNames = /* @__PURE__ */ new Set();
390
547
  for (const namespace of request.bindings) {
391
548
  const descriptor = namespace.errorClass;
392
549
  if (!descriptor) continue;
393
- if (!IDENTIFIER.test(descriptor.name) || PORTABLE_RESERVED_WORDS.has(descriptor.name)) throw new Error(`dsh-ptc-runtime-node: binding error class ${JSON.stringify(descriptor.name)} is not a usable identifier`);
394
- if (RESERVED_BINDING_GLOBALS.has(descriptor.name)) throw new Error(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(descriptor.name)}`);
395
- if (bindings.has(descriptor.name) || errorClassNames.has(descriptor.name)) throw new Error(`dsh-ptc-runtime-node: duplicate injected global ${JSON.stringify(descriptor.name)}`);
550
+ if (!IDENTIFIER.test(descriptor.name) || RESERVED_BINDING_WORDS.has(descriptor.name) || programFormat === "scoped-repl" && descriptor.name.includes("__$binding_")) throw new PtcRuntimeError(`dsh-ptc-runtime-node: binding error class ${JSON.stringify(descriptor.name)} is not a usable identifier`, "PTC_RUNTIME_INVALID_ARGUMENT");
551
+ if (RESERVED_BINDING_GLOBALS.has(descriptor.name)) throw new PtcRuntimeError(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(descriptor.name)}`, "PTC_RUNTIME_INVALID_ARGUMENT");
552
+ if (bindings.has(descriptor.name) || errorClassNames.has(descriptor.name)) throw new PtcRuntimeError(`dsh-ptc-runtime-node: duplicate injected global ${JSON.stringify(descriptor.name)}`, "PTC_RUNTIME_INVALID_ARGUMENT");
396
553
  const member = descriptor.memberNameProperty;
397
- if (member.length === 0 || RESERVED_ERROR_MEMBERS.has(member) || DUNDER_MEMBER.test(member)) throw new Error(`dsh-ptc-runtime-node: binding error member property ${JSON.stringify(descriptor.memberNameProperty)} is not usable`);
554
+ if (member.length === 0 || RESERVED_ERROR_MEMBERS.has(member)) throw new PtcRuntimeError(`dsh-ptc-runtime-node: binding error member property ${JSON.stringify(descriptor.memberNameProperty)} is not usable`, "PTC_RUNTIME_INVALID_ARGUMENT");
398
555
  errorClassNames.add(descriptor.name);
399
556
  }
400
557
  return bindings;
@@ -403,13 +560,19 @@ function validateBindings(request) {
403
560
  * Invoke a host binding and encode its lossless result.
404
561
  * @param binding - Current evaluation's function, absent if it was removed.
405
562
  * @param args - Validated JSON arguments detached from the program.
406
- * @returns Flat lossless JSON; unavailable bindings and invalid results reject.
563
+ * @param image - Registers host-issued images with the owning process.
564
+ * @returns Flat binding data; unavailable bindings and invalid results reject.
407
565
  */
408
- async function invokeBinding(binding, args) {
566
+ async function invokeBinding(binding, args, image) {
409
567
  if (!binding) throw new Error("binding is unavailable in this evaluation; reacquire the current tool");
410
- const value = snapshotJsonValue(await binding(args));
568
+ const resolved = await binding(args);
569
+ const inspection = resolved instanceof PtcInspectableValue ? resolved.text : void 0;
570
+ const value = snapshotPtcJsonValue(resolved instanceof PtcInspectableValue ? resolved.value : resolved, (value) => image !== void 0 && value instanceof PtcImage);
411
571
  if (value === void 0) throw new Error("binding resolution must be lossless JSON");
412
- return encodePtcJsonWire(value);
572
+ return {
573
+ value: encodePtcJsonWire(value, (candidate) => candidate instanceof PtcImage ? image?.(candidate) : void 0),
574
+ ...inspection === void 0 ? {} : { inspection }
575
+ };
413
576
  }
414
577
  //#endregion
415
578
  //#region lib/types/rpc.js
@@ -508,6 +671,29 @@ const STARTUP_ENVIRONMENT_NAMES = new Set([
508
671
  "TEMP",
509
672
  "TMP"
510
673
  ]);
674
+ /** Warnings that the runtime's own use of experimental Node features emits once per process. */
675
+ const RUNTIME_WARNINGS = new Set(["vm.USE_MAIN_CONTEXT_DEFAULT_LOADER is an experimental feature and might change at any time", "stripTypeScriptTypes is an experimental feature and might change at any time"]);
676
+ function withoutRuntimeWarning(emitWarning) {
677
+ return function(warning, ...rest) {
678
+ const message = typeof warning === "string" ? warning : warning instanceof Error ? warning.message : void 0;
679
+ if (message !== void 0 && RUNTIME_WARNINGS.has(message)) return;
680
+ Reflect.apply(emitWarning, this, [warning, ...rest]);
681
+ };
682
+ }
683
+ /**
684
+ * Run a synchronous host call without printing the runtime's own experimental-feature warnings.
685
+ * @param call - Synchronous work, such as type stripping, that may emit such a warning on first use.
686
+ * @returns The call's result; `process.emitWarning` is restored before returning or rethrowing.
687
+ */
688
+ function quietRuntimeCall(call) {
689
+ const emitWarning = process.emitWarning;
690
+ process.emitWarning = withoutRuntimeWarning(emitWarning);
691
+ try {
692
+ return call();
693
+ } finally {
694
+ process.emitWarning = emitWarning;
695
+ }
696
+ }
511
697
  //#endregion
512
698
  //#region lib/types/output-json.js
513
699
  /** JSON string-prefix accounting for the outer-output ledger. @module @deepseek-ai/dsh-ptc-runtime-node/output-json */
@@ -687,74 +873,77 @@ function truncateJsonStringBytes(text, maxBytes) {
687
873
  }
688
874
  //#endregion
689
875
  //#region lib/types/output-ledger.js
876
+ /** Measure a text entry or an image descriptor against the remaining JSON-byte budget. */
877
+ function entryBytes(entry, available) {
878
+ return entry.type === "text" ? jsonStringBytesUpTo(entry.text, available) : jsonValueBytesUpTo({
879
+ ...entry,
880
+ attachment: { ...entry.attachment }
881
+ }, available);
882
+ }
690
883
  /** One run's combined outer-output ledger; binding values never enter it. */
691
- var OutputLedger = class {
884
+ var OutputLedger = class OutputLedger {
692
885
  maxBytes;
693
- overflowMessage;
694
886
  bytes = 2;
695
887
  entries = 0;
696
- constructor(maxBytes, overflowMessage) {
888
+ truncated = false;
889
+ constructor(maxBytes) {
697
890
  this.maxBytes = maxBytes;
698
- this.overflowMessage = overflowMessage;
699
891
  }
700
- /** Admit one exact log entry, or report that the hard cap was crossed. */
701
- admit(text, sink) {
892
+ /** Admit one ordered text or image entry against the combined output budget. */
893
+ admit(entry, sink) {
894
+ if (this.truncated) return false;
702
895
  const separatorBytes = this.entries > 0 ? 1 : 0;
703
- const stringBytes = jsonStringBytesUpTo(text, this.maxBytes - this.bytes - separatorBytes);
704
- if (stringBytes === void 0) return false;
705
- this.bytes += stringBytes + separatorBytes;
896
+ const remaining = this.maxBytes - this.bytes - separatorBytes;
897
+ const bytes = entryBytes(entry, remaining);
898
+ if (bytes === void 0) {
899
+ this.truncated = true;
900
+ if (entry.type === "text") {
901
+ const prefix = truncateJsonStringBytes(entry.text, remaining);
902
+ if (prefix.length > 0) sink.push({
903
+ type: "text",
904
+ text: prefix
905
+ });
906
+ }
907
+ return false;
908
+ }
909
+ this.bytes += bytes + separatorBytes;
706
910
  this.entries += 1;
707
- sink.push(text);
911
+ sink.push(entry);
708
912
  return true;
709
913
  }
710
914
  /** Finalize a successful absent-or-JSON completion against the combined cap. */
711
- success(logs, value) {
712
- if (value !== void 0 && jsonValueBytesUpTo(value, this.maxBytes - this.bytes) === void 0) return this.limit(logs);
915
+ success(output, value) {
916
+ const valueBytes = value === void 0 ? 0 : jsonValueBytesUpTo(value, this.maxBytes - 2);
917
+ if (valueBytes === void 0) return this.failure(output, {
918
+ kind: "output-limit",
919
+ message: `completion value exceeded ${this.maxBytes} bytes`
920
+ });
713
921
  return {
714
- logs,
922
+ ...this.retain(output, valueBytes),
715
923
  ...value !== void 0 ? { value } : {}
716
924
  };
717
925
  }
718
- /** Finalize a failure diagnostic, with output-limit taking precedence when combined bytes exceed the cap. */
719
- failure(logs, error) {
720
- if (jsonStringBytesUpTo(error.message, this.maxBytes - this.bytes) === void 0) return this.limit(logs);
926
+ /** Prioritize the terminal diagnostic without changing its failure kind. */
927
+ failure(output, error) {
928
+ const message = truncateJsonStringBytes(error.message, this.maxBytes - 2);
929
+ if (message !== error.message) this.truncated = true;
721
930
  return {
722
- logs,
723
- error
931
+ ...this.retain(output, Buffer.byteLength(JSON.stringify(message))),
932
+ error: {
933
+ ...error,
934
+ message
935
+ }
724
936
  };
725
937
  }
726
- /** Build the explicit output-limit failure while retaining a fitting prefix of the final log. */
727
- limit(logs) {
728
- const fullMessage = this.overflowMessage ?? `outer output exceeded ${this.maxBytes} bytes`;
729
- const messageBytes = fullMessage.length + 2;
938
+ /** Keep an ordered prefix after reserving bytes for the completion or diagnostic. */
939
+ retain(output, terminalBytes) {
730
940
  const retained = [];
731
- let retainedBytes = 2;
732
- const logBudget = this.maxBytes - messageBytes;
733
- for (const text of logs) {
734
- const separatorBytes = retained.length > 0 ? 1 : 0;
735
- const availableBytes = logBudget - retainedBytes - separatorBytes;
736
- const stringBytes = jsonStringBytesUpTo(text, availableBytes);
737
- if (stringBytes !== void 0) {
738
- retained.push(text);
739
- retainedBytes += stringBytes + separatorBytes;
740
- continue;
741
- }
742
- const prefix = truncateJsonStringBytes(text, availableBytes);
743
- if (prefix.length > 0) {
744
- const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes);
745
- /* v8 ignore next -- truncateJsonStringBytes guarantees its returned prefix fits the same budget. */
746
- if (prefixBytes === void 0) throw new Error("output ledger produced an oversized log prefix");
747
- retained.push(prefix);
748
- retainedBytes += prefixBytes + separatorBytes;
749
- }
750
- break;
751
- }
941
+ const ledger = new OutputLedger(this.maxBytes - terminalBytes);
942
+ for (const entry of output) if (!ledger.admit(entry, retained)) break;
943
+ this.truncated ||= ledger.truncated;
752
944
  return {
753
- logs: retained,
754
- error: {
755
- kind: "output-limit",
756
- message: truncateJsonStringBytes(fullMessage, this.maxBytes - retainedBytes)
757
- }
945
+ output: retained,
946
+ ...this.truncated ? { outputTruncated: true } : {}
758
947
  };
759
948
  }
760
949
  };
@@ -821,21 +1010,31 @@ const record = (value) => typeof value === "object" && value !== null && !Array.
821
1010
  * @returns Decoded completion or failure; malformed envelopes throw a protocol error.
822
1011
  */
823
1012
  function readProgramResult(result) {
824
- if (!record(result)) throw new Error("invalid program result");
1013
+ if (!record(result) || result.outputTruncated !== void 0 && typeof result.outputTruncated !== "boolean") throw new Error("invalid program result");
1014
+ const truncation = result.outputTruncated ? { outputTruncated: true } : {};
825
1015
  if (result.error !== void 0) {
826
1016
  const error = result.error;
827
1017
  if (!record(error) || typeof error.message !== "string" || error.kind !== "exception" && error.kind !== "invalid-output" && error.kind !== "output-limit") throw new Error("invalid terminal error");
828
- return { error: {
829
- kind: error.kind,
830
- message: error.message
831
- } };
1018
+ return {
1019
+ ...truncation,
1020
+ error: {
1021
+ kind: error.kind,
1022
+ message: error.message
1023
+ }
1024
+ };
832
1025
  }
833
- if (result.value === void 0) return {};
1026
+ if (result.value === void 0) return truncation;
834
1027
  const value = decodePtcJsonWire(result.value);
835
- return value === void 0 ? { error: {
836
- kind: "invalid-output",
837
- message: "program completion must be lossless JSON"
838
- } } : { value };
1028
+ return value === void 0 ? {
1029
+ ...truncation,
1030
+ error: {
1031
+ kind: "invalid-output",
1032
+ message: "program completion must be lossless JSON"
1033
+ }
1034
+ } : {
1035
+ ...truncation,
1036
+ value
1037
+ };
839
1038
  }
840
1039
  //#endregion
841
1040
  //#region lib/types/worker.js
@@ -848,6 +1047,7 @@ var ProgramWorker = class {
848
1047
  policy;
849
1048
  mode;
850
1049
  retainsState;
1050
+ pendingInitialization;
851
1051
  unregister;
852
1052
  confined;
853
1053
  handle;
@@ -862,6 +1062,7 @@ var ProgramWorker = class {
862
1062
  termination;
863
1063
  starting;
864
1064
  exitOutcome;
1065
+ images = /* @__PURE__ */ new Map();
865
1066
  controller = new AbortController();
866
1067
  closed = false;
867
1068
  /** Whether termination succeeded and this process no longer needs cleanup retries. */
@@ -876,19 +1077,21 @@ var ProgramWorker = class {
876
1077
  * @param processes - Session policy invalidation and cleanup coordination.
877
1078
  * @param mode - Evaluator syntax and TypeScript erasure.
878
1079
  * @param retainsState - Whether this process belongs to an owner and survives completed evaluations.
1080
+ * @param pendingInitialization - Type-erased setup source, or undefined when no initialization is required.
879
1081
  */
880
- constructor(ctx, config, policy, processes, mode, retainsState) {
1082
+ constructor(ctx, config, policy, processes, mode, retainsState, pendingInitialization) {
881
1083
  this.ctx = ctx;
882
1084
  this.config = config;
883
1085
  this.policy = policy;
884
1086
  this.mode = mode;
885
1087
  this.retainsState = retainsState;
1088
+ this.pendingInitialization = pendingInitialization;
886
1089
  this.unregister = processes.register(policy, () => this.dispose());
887
1090
  }
888
1091
  /** Reject reuse until the previous evaluation and required cleanup settle. */
889
1092
  assertIdle() {
890
- if (this.running) throw new Error("persistent PTC does not accept concurrent runs for one state owner");
891
- if (this.cleanupPending) throw new Error("persistent PTC environment cleanup is incomplete; release the owner before running another program");
1093
+ if (this.running) throw new PtcRuntimeError("persistent PTC does not accept concurrent runs for one state owner", "PTC_RUNTIME_CONFLICT");
1094
+ if (this.cleanupPending) throw new PtcRuntimeError("persistent PTC environment cleanup is incomplete; release the owner before running another program", "PTC_RUNTIME_UNAVAILABLE");
892
1095
  }
893
1096
  /**
894
1097
  * Evaluate a program, retaining this process only for an enabled state owner.
@@ -916,15 +1119,12 @@ var ProgramWorker = class {
916
1119
  this.running = false;
917
1120
  }
918
1121
  }
919
- output() {
920
- return new OutputLedger(this.config.maxOutputBytes, this.retainsState ? `retained variables were cleared; outer output exceeded ${this.config.maxOutputBytes} bytes` : void 0);
921
- }
922
1122
  message(message) {
923
1123
  return this.retainsState ? `${message}; retained variables were cleared` : message;
924
1124
  }
925
1125
  async evaluate(spec, bindings) {
1126
+ const ledger = new OutputLedger(this.config.maxOutputBytes);
926
1127
  if (this.exitOutcome !== void 0) {
927
- const output = this.output();
928
1128
  const failure = spec.signal?.aborted ? {
929
1129
  kind: "abort",
930
1130
  message: this.message("execution canceled")
@@ -935,17 +1135,15 @@ var ProgramWorker = class {
935
1135
  try {
936
1136
  await this.terminate();
937
1137
  } catch (error) {
938
- return output.failure([], {
1138
+ return ledger.failure([], {
939
1139
  kind: "worker-exit",
940
1140
  message: `managed process cleanup failed: ${messageOf(error)}`
941
1141
  });
942
1142
  }
943
- return output.failure([], failure);
1143
+ return ledger.failure([], failure);
944
1144
  }
945
1145
  this.stderr = "";
946
- const output = this.output();
947
- const logs = [];
948
- let overflowed = false;
1146
+ const output = [];
949
1147
  const result = Promise.withResolvers();
950
1148
  const timer = spec.timeoutMs === null ? void 0 : setTimeout(() => {
951
1149
  const message = `execution timed out ${evaluation.completion !== void 0 ? "during execution" : "before code started"} (${spec.timeoutMs}ms)`;
@@ -967,7 +1165,9 @@ var ProgramWorker = class {
967
1165
  code: "",
968
1166
  programFormat: this.mode.format,
969
1167
  retainsState: this.retainsState,
1168
+ ...this.pendingInitialization === void 0 ? {} : { initialization: this.pendingInitialization },
970
1169
  maxOutputBytes: this.config.maxOutputBytes,
1170
+ discardCompletion: spec.discardCompletion === true,
971
1171
  namespaces: [...bindings.values()].map((binding) => ({
972
1172
  global: binding.global,
973
1173
  names: Object.keys(binding.functions),
@@ -976,30 +1176,35 @@ var ProgramWorker = class {
976
1176
  },
977
1177
  spec,
978
1178
  bindings,
979
- invoke: AsyncLocalStorage.bind(invokeBinding),
980
1179
  pending: 0,
981
1180
  pendingBytes: 0,
982
- admit: (text) => {
983
- if (overflowed) return;
984
- if (!output.admit(text, logs)) {
985
- overflowed = true;
986
- logs.push(text);
987
- evaluation.finish({
988
- kind: "output-limit",
989
- message: "output limit exceeded"
990
- }, void 0, true);
991
- }
1181
+ invoke: AsyncLocalStorage.bind((binding, args) => invokeBinding(binding, args, (image) => this.registerImage(image))),
1182
+ truncateOutput: () => {
1183
+ ledger.truncated = true;
1184
+ const channel = this.channel;
1185
+ if (evaluation.settled || this.closed || !channel || channel.$closed) return;
1186
+ channel.discardOutput().catch((error) => {
1187
+ if (this.active !== evaluation || evaluation.settled || this.closed || channel.$closed) return;
1188
+ this.fail("protocol", `failed to send output-discard notification: ${messageOf(error)}`);
1189
+ });
1190
+ },
1191
+ admit: (entry) => {
1192
+ if (ledger.truncated) return;
1193
+ if (!ledger.admit(entry, output)) evaluation.truncateOutput();
992
1194
  },
993
1195
  finish: (error, value, discard = false) => {
994
1196
  if (evaluation.settled) return;
995
1197
  evaluation.settled = true;
996
1198
  clearTimeout(timer);
997
1199
  spec.signal?.removeEventListener("abort", onAbort);
998
- const complete = () => overflowed || error?.kind === "output-limit" ? output.limit(logs) : error ? output.failure(logs, error) : output.success(logs, value);
999
- const outcome = complete();
1200
+ const initializationIncomplete = this.pendingInitialization !== void 0;
1201
+ if (initializationIncomplete && error?.kind === "exception") error = {
1202
+ ...error,
1203
+ message: this.message(error.message)
1204
+ };
1000
1205
  const cleanup = async () => {
1001
1206
  const interrupted = error?.kind === "timeout" || error?.kind === "abort";
1002
- let preserved = this.retainsState && !discard && outcome.error?.kind !== "output-limit";
1207
+ let preserved = this.retainsState && !initializationIncomplete && !discard;
1003
1208
  if (preserved && interrupted) preserved = await this.interruptEvaluation(evaluation);
1004
1209
  let drained = true;
1005
1210
  if (!preserved) drained = await this.terminate();
@@ -1007,9 +1212,8 @@ var ProgramWorker = class {
1007
1212
  ...error,
1008
1213
  message: `${error.message}; retained variables were ${preserved ? "preserved" : "cleared"}`
1009
1214
  };
1010
- const completed = complete();
1011
- if (completed.error?.kind === "output-limit" && preserved) drained = await this.terminate();
1012
- return drained ? completed : output.failure(logs, {
1215
+ const completed = error ? ledger.failure(output, error) : ledger.success(output, value);
1216
+ return drained ? completed : ledger.failure(output, {
1013
1217
  kind: "worker-exit",
1014
1218
  message: "managed process exited but its output did not drain cleanly"
1015
1219
  });
@@ -1019,7 +1223,7 @@ var ProgramWorker = class {
1019
1223
  result.resolve(completed);
1020
1224
  }, (failure) => {
1021
1225
  this.active = void 0;
1022
- result.resolve(output.failure(logs, {
1226
+ result.resolve(ledger.failure(output, {
1023
1227
  kind: "worker-exit",
1024
1228
  message: `managed process cleanup failed: ${messageOf(failure)}`
1025
1229
  }));
@@ -1084,6 +1288,7 @@ var ProgramWorker = class {
1084
1288
  terminate() {
1085
1289
  if (this.termination) return this.termination;
1086
1290
  this.closed = true;
1291
+ this.images.clear();
1087
1292
  this.cleanupPending = true;
1088
1293
  this.controller.abort();
1089
1294
  this.channel?.$close();
@@ -1117,8 +1322,13 @@ var ProgramWorker = class {
1117
1322
  dispatch(evaluation) {
1118
1323
  const completion = this.channel?.run(evaluation.spec.cwd, evaluation.data).then(readProgramResult);
1119
1324
  evaluation.completion = completion;
1120
- completion?.then(({ error, value }) => {
1325
+ completion?.then(({ error, value, outputTruncated }) => {
1121
1326
  if (evaluation.settled) return;
1327
+ if (this.pendingInitialization !== void 0 && error === void 0) {
1328
+ this.fail("protocol", "environment initialization completed without Host acceptance");
1329
+ return;
1330
+ }
1331
+ if (outputTruncated) evaluation.truncateOutput();
1122
1332
  setImmediate(() => {
1123
1333
  evaluation.finish(error, value);
1124
1334
  });
@@ -1132,6 +1342,18 @@ var ProgramWorker = class {
1132
1342
  exitMessage(outcome) {
1133
1343
  return this.withControlFailure(`Node process exited (${String(outcome.exitCode)}, signal ${String(outcome.signal)})${this.stderr ? `: ${this.stderr}` : ""}`);
1134
1344
  }
1345
+ registerImage(image) {
1346
+ const id = randomUUID();
1347
+ this.images.set(id, image.attachment);
1348
+ return {
1349
+ kind: "image",
1350
+ id,
1351
+ attachmentId: image.attachment.attachmentId,
1352
+ path: image.path,
1353
+ width: image.attachment.width,
1354
+ height: image.attachment.height
1355
+ };
1356
+ }
1135
1357
  async start(cwd) {
1136
1358
  const executable = await this.ctx.subprocess.resolveExecutable(this.config.launch.executable, void 0, this.controller.signal);
1137
1359
  if (this.closed) return;
@@ -1171,7 +1393,10 @@ var ProgramWorker = class {
1171
1393
  stream.setEncoding("utf8");
1172
1394
  stream.on("data", (text) => {
1173
1395
  if (stream === handle.stderr) this.stderr = (this.stderr + text).slice(-this.config.maxOutputBytes);
1174
- this.active?.admit(text);
1396
+ this.active?.admit({
1397
+ type: "text",
1398
+ text
1399
+ });
1175
1400
  });
1176
1401
  stream.on("error", (error) => {
1177
1402
  this.fail("worker-exit", error.message);
@@ -1183,7 +1408,7 @@ var ProgramWorker = class {
1183
1408
  };
1184
1409
  this.channel = createProcessRpc(handle.control, this.config.maxMessageBytes, {
1185
1410
  ready: (version) => {
1186
- if (version !== 2) {
1411
+ if (version !== 5) {
1187
1412
  this.fail("protocol", "bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host");
1188
1413
  return;
1189
1414
  }
@@ -1194,22 +1419,40 @@ var ProgramWorker = class {
1194
1419
  this.ready = true;
1195
1420
  this.dispatch(this.active);
1196
1421
  },
1422
+ initialized: () => {
1423
+ const evaluation = this.active;
1424
+ if (!this.ready || !evaluation || this.pendingInitialization === void 0) return refuse("unexpected environment initialization acknowledgement");
1425
+ if (evaluation.settled || evaluation.spec.signal?.aborted) throw new Error("PTC evaluation ended before initialization completed");
1426
+ this.pendingInitialization = void 0;
1427
+ return Promise.resolve();
1428
+ },
1197
1429
  log: (text) => {
1198
1430
  if (!this.ready || !this.active || typeof text !== "string") {
1199
1431
  this.fail("protocol", "invalid program log");
1200
1432
  return;
1201
1433
  }
1202
- if (!this.active.settled) this.active.admit(text);
1434
+ if (!this.active.settled) this.active.admit({
1435
+ type: "text",
1436
+ text
1437
+ });
1438
+ },
1439
+ image: (id) => {
1440
+ const image = typeof id === "string" ? this.images.get(id) : void 0;
1441
+ if (!this.ready || !this.active || image === void 0) {
1442
+ this.fail("protocol", "invalid program image");
1443
+ return;
1444
+ }
1445
+ if (!this.active.settled) this.active.admit({
1446
+ type: "image",
1447
+ attachment: image
1448
+ });
1203
1449
  },
1204
1450
  outputLimit: () => {
1205
1451
  if (!this.ready || !this.active) {
1206
1452
  this.fail("protocol", "idle PTC output limit");
1207
1453
  return;
1208
1454
  }
1209
- this.active.finish({
1210
- kind: "output-limit",
1211
- message: "output limit exceeded"
1212
- }, void 0, true);
1455
+ this.active.truncateOutput();
1213
1456
  },
1214
1457
  invoke: async (global, name, wire) => {
1215
1458
  const evaluation = this.active;
@@ -1237,7 +1480,7 @@ var ProgramWorker = class {
1237
1480
  if (evaluation.settled) throw new Error("PTC evaluation ended before the binding completed");
1238
1481
  return value;
1239
1482
  }
1240
- }, ["revoke"], (error, kind) => {
1483
+ }, ["revoke", "discardOutput"], (error, kind) => {
1241
1484
  if (kind === "protocol") this.fail("protocol", error.message);
1242
1485
  else {
1243
1486
  if (kind === "io") this.controlFailure = error.message;
@@ -1307,7 +1550,7 @@ var NodeExecution = class {
1307
1550
  resolve(request) {
1308
1551
  const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
1309
1552
  const cwd = request.cwd ?? sandboxPolicy.workspaceRoot;
1310
- if (!isAbsolute(cwd)) throw new Error(`${this.mode.retainsState ? "persistent PTC" : "ptc-runtime-node"}: cwd must be absolute`);
1553
+ if (!isAbsolute(cwd)) throw new PtcRuntimeError(`${this.mode.retainsState ? "persistent PTC" : "ptc-runtime-node"}: cwd must be absolute`, "PTC_RUNTIME_INVALID_ARGUMENT");
1311
1554
  return {
1312
1555
  ...request,
1313
1556
  sandboxPolicy,
@@ -1318,29 +1561,30 @@ var NodeExecution = class {
1318
1561
  /**
1319
1562
  * Evaluate in a temporary process or reuse an enabled state owner's process.
1320
1563
  * @param spec - Resolved request; concurrent calls for one owner are rejected.
1564
+ * @param initialization - Type-erased source for new environments, or undefined when none is registered.
1321
1565
  * @returns Captured logs, JSON completion, or a structured execution failure.
1322
1566
  */
1323
- async run(spec) {
1324
- if (spec.sandboxPolicy === void 0) throw new Error("ptc-runtime-node: run requires a resolved sandbox policy");
1325
- 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");
1326
- const bindings = validateBindings(spec);
1567
+ async run(spec, initialization) {
1568
+ if (spec.sandboxPolicy === void 0) throw new PtcRuntimeError("ptc-runtime-node: run requires a resolved sandbox policy", "PTC_RUNTIME_INVALID_ARGUMENT");
1569
+ 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");
1570
+ const bindings = validateBindings(spec, this.mode.format);
1327
1571
  const owner = this.mode.retainsState ? spec.stateOwner : void 0;
1328
1572
  let worker = owner === void 0 ? void 0 : this.owners.get(owner);
1329
1573
  worker?.assertIdle();
1330
- if (worker && !worker.closed && (worker.policy.mode !== spec.sandboxPolicy.mode || worker.policy.workspaceRoot !== spec.sandboxPolicy.workspaceRoot || worker.policy.sessionId !== spec.sandboxPolicy.sessionId)) throw new Error("persistent PTC: release the retained environment before changing its sandbox policy");
1574
+ if (worker && !worker.closed && (worker.policy.mode !== spec.sandboxPolicy.mode || worker.policy.workspaceRoot !== spec.sandboxPolicy.workspaceRoot || worker.policy.sessionId !== spec.sandboxPolicy.sessionId)) throw new PtcRuntimeError("persistent PTC: release the retained environment before changing its sandbox policy", "PTC_RUNTIME_CONFLICT");
1331
1575
  if (!worker || worker.closed) {
1332
1576
  if (worker) this.workers.delete(worker);
1333
1577
  worker = new ProgramWorker(this.ctx, this.config, {
1334
1578
  ...spec.sandboxPolicy,
1335
1579
  ...spec.sandboxPolicy.additionalWritableRoots === void 0 ? {} : { additionalWritableRoots: [...spec.sandboxPolicy.additionalWritableRoots] }
1336
- }, this.processes, this.mode, owner !== void 0);
1580
+ }, this.processes, this.mode, owner !== void 0, initialization);
1337
1581
  this.workers.add(worker);
1338
1582
  if (owner !== void 0) this.owners.set(owner, worker);
1339
1583
  }
1340
1584
  try {
1341
1585
  return await worker.run(spec, bindings);
1342
1586
  } finally {
1343
- if (owner === void 0 && worker.cleanupComplete) this.workers.delete(worker);
1587
+ if (worker.cleanupComplete) this.workers.delete(worker);
1344
1588
  }
1345
1589
  }
1346
1590
  /**
@@ -1356,35 +1600,49 @@ var NodeExecution = class {
1356
1600
  this.workers.delete(worker);
1357
1601
  }
1358
1602
  };
1603
+ /** Erase TypeScript syntax without printing Node's warning for the experimental stripping API, which the host itself uses. */
1604
+ function stripTypeScript(source) {
1605
+ return quietRuntimeCall(() => stripTypeScriptTypes(source));
1606
+ }
1359
1607
  const STRIP_PREFIX = "async function __dsh_program__() {\n";
1360
1608
  const STRIP_SUFFIX = "\n}";
1609
+ /** Scoped REPL guidance; its output sentence is shared with the other modes. */
1610
+ function scopedReplMode(outputInstructions) {
1611
+ return {
1612
+ format: "scoped-repl",
1613
+ retainsState: true,
1614
+ 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.",
1615
+ stripTypes: stripTypeScript
1616
+ };
1617
+ }
1361
1618
  function resolveMode(config) {
1619
+ const outputInstructions = "Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal.";
1362
1620
  switch (config.executionMode) {
1363
1621
  case "per-call": return {
1364
1622
  format: "function-body",
1365
1623
  retainsState: false,
1366
- 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.",
1624
+ 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. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. 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.",
1367
1625
  stripTypes(program) {
1368
- const stripped = stripTypeScriptTypes(STRIP_PREFIX + program + STRIP_SUFFIX);
1626
+ const stripped = stripTypeScript(STRIP_PREFIX + program + STRIP_SUFFIX);
1369
1627
  return stripped.slice(35, stripped.length - 2);
1370
1628
  }
1371
1629
  };
1372
- case "persistent-in-memory": return {
1630
+ case "persistent-in-memory": return config.replScoped ? scopedReplMode(outputInstructions) : {
1373
1631
  format: "repl",
1374
1632
  retainsState: true,
1375
- 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. 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.",
1376
- stripTypes: stripTypeScriptTypes
1633
+ 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. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. 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. 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.",
1634
+ stripTypes: stripTypeScript
1377
1635
  };
1378
1636
  case "vm-script": {
1379
1637
  const lifetime = config.scriptPersistence ? "Variables, functions, and imported modules remain in memory for this Agent across calls." : "Each call runs in a fresh Node process.";
1380
1638
  const filePolicy = config.scriptPersistence ? "Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty." : "Direct filesystem access follows this execution's sandbox policy; process.env starts empty.";
1381
1639
  const asynchronousFailure = "Await asynchronous work: an uncaught callback exception or unhandled rejection terminates the process" + (config.scriptPersistence ? " and clears its variables." : ".");
1382
- const recovery = config.scriptPersistence ? " 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. 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." : "";
1640
+ const recovery = config.scriptPersistence ? " 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. 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." : "";
1383
1641
  return {
1384
1642
  format: "script",
1385
1643
  retainsState: config.scriptPersistence,
1386
- 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,
1387
- stripTypes: stripTypeScriptTypes
1644
+ 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. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. 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,
1645
+ stripTypes: stripTypeScript
1388
1646
  };
1389
1647
  }
1390
1648
  /* v8 ignore next -- Loader validates the closed execution-mode union before selection. */
@@ -1487,10 +1745,13 @@ var NodePtcRuntime = class extends PtcRuntime {
1487
1745
  config;
1488
1746
  live = /* @__PURE__ */ new Set();
1489
1747
  disposed = false;
1748
+ admitted = false;
1749
+ initializer;
1490
1750
  constructor(ctx, config) {
1491
1751
  super(ctx);
1492
1752
  this.config = {
1493
1753
  ...config,
1754
+ replScoped: resolveReplScoped(config),
1494
1755
  launch: resolveLaunch(config.launch)
1495
1756
  };
1496
1757
  validateConfig(this.config);
@@ -1498,12 +1759,41 @@ var NodePtcRuntime = class extends PtcRuntime {
1498
1759
  this.execution = createExecution(ctx, this.config, this.processes);
1499
1760
  ctx.effect(() => async () => {
1500
1761
  this.disposed = true;
1501
- const active = [...this.live];
1502
- for (const run of active) run.controller.abort("runtime disposed");
1503
- const failed = (await Promise.allSettled([this.execution.dispose(), ...active.map((run) => run.finished)])).find((result) => result.status === "rejected");
1504
- if (failed?.status === "rejected") throw failed.reason;
1762
+ await this.drain("runtime disposed");
1505
1763
  }, "Node ptc-runtime cleanup");
1506
1764
  }
1765
+ async drain(reason) {
1766
+ const active = [...this.live];
1767
+ for (const run of active) run.controller.abort(reason);
1768
+ const failed = (await Promise.allSettled([this.execution.dispose(), ...active.map((run) => run.finished)])).find((result) => result.status === "rejected");
1769
+ if (failed?.status === "rejected") throw failed.reason;
1770
+ }
1771
+ registerEnvironmentInitializer(program) {
1772
+ if (this.disposed) throw new Error("ptc-runtime-node: initialization registration after disposal");
1773
+ if (this.config.executionMode !== "persistent-in-memory") throw new Error("ptc-runtime-node: initialization requires persistent-in-memory execution");
1774
+ if (this.initializer !== void 0) throw new Error("ptc-runtime-node: environment initializer is already registered");
1775
+ if (this.admitted) throw new Error("ptc-runtime-node: register initialization before the first run");
1776
+ const registration = {
1777
+ program: this.execution.mode.stripTypes(program),
1778
+ removing: false
1779
+ };
1780
+ this.initializer = registration;
1781
+ return () => {
1782
+ if (this.initializer !== registration) return Promise.resolve();
1783
+ registration.removing = true;
1784
+ if (registration.cleanup !== void 0) return registration.cleanup;
1785
+ const completion = Promise.withResolvers();
1786
+ registration.cleanup = completion.promise;
1787
+ this.drain("environment initializer removed").then(() => {
1788
+ this.initializer = void 0;
1789
+ completion.resolve();
1790
+ }, (error) => {
1791
+ delete registration.cleanup;
1792
+ completion.reject(error);
1793
+ });
1794
+ return completion.promise;
1795
+ };
1796
+ }
1507
1797
  get sandboxMode() {
1508
1798
  return this.ctx.sandboxPolicy.defaultMode;
1509
1799
  }
@@ -1518,14 +1808,12 @@ var NodePtcRuntime = class extends PtcRuntime {
1518
1808
  }
1519
1809
  /**
1520
1810
  * Resolve directory, deadline and file policy for the selected execution mode.
1521
- * @param request - Program, bindings, optional cwd/deadline, and resolved authority.
1811
+ * @param request - Program, bindings, cwd/deadline, and resolved authority.
1522
1812
  * @returns Complete execution inputs with a capped numeric budget or an explicit null deadline.
1813
+ * @throws When an execution choice is invalid or the provider is disposed.
1523
1814
  */
1524
1815
  resolve(request) {
1525
- if (this.disposed) {
1526
- const source = this.retainsState ? "persistent PTC" : "ptc-runtime-node";
1527
- throw new Error(`${source}: resolve after disposal`);
1528
- }
1816
+ if (this.disposed) throw new PtcRuntimeError(`${this.retainsState ? "persistent PTC" : "ptc-runtime-node"}: resolve after disposal`, "PTC_RUNTIME_UNAVAILABLE");
1529
1817
  return this.execution.resolve(request);
1530
1818
  }
1531
1819
  /**
@@ -1535,7 +1823,10 @@ var NodePtcRuntime = class extends PtcRuntime {
1535
1823
  * @returns Logs, JSON completion or failure; retained processes remain until release or invalidation.
1536
1824
  */
1537
1825
  async run(spec) {
1538
- if (this.disposed) throw new Error("ptc-runtime-node: run after disposal");
1826
+ if (this.disposed) throw new PtcRuntimeError("ptc-runtime-node: run after disposal", "PTC_RUNTIME_UNAVAILABLE");
1827
+ if (this.initializer?.removing) throw new PtcRuntimeError("ptc-runtime-node: environment initialization cleanup is incomplete", "PTC_RUNTIME_UNAVAILABLE");
1828
+ this.admitted = true;
1829
+ const initialization = this.initializer?.program;
1539
1830
  const controller = new AbortController();
1540
1831
  const completion = Promise.withResolvers();
1541
1832
  const unregister = spec.sandboxPolicy === void 0 ? void 0 : this.processes.register(spec.sandboxPolicy, async () => {
@@ -1549,12 +1840,12 @@ var NodePtcRuntime = class extends PtcRuntime {
1549
1840
  this.live.add(live);
1550
1841
  try {
1551
1842
  await this.processes.wait(spec.sandboxPolicy?.sessionId);
1552
- if (this.disposed) throw new Error(`${this.retainsState ? "persistent PTC" : "ptc-runtime-node"}: run after disposal`);
1843
+ if (this.disposed) throw new PtcRuntimeError(`${this.retainsState ? "persistent PTC" : "ptc-runtime-node"}: run after disposal`, "PTC_RUNTIME_UNAVAILABLE");
1553
1844
  const signal = spec.signal === void 0 ? controller.signal : AbortSignal.any([spec.signal, controller.signal]);
1554
1845
  return await this.execution.run({
1555
1846
  ...spec,
1556
1847
  signal
1557
- });
1848
+ }, initialization);
1558
1849
  } finally {
1559
1850
  unregister?.();
1560
1851
  this.live.delete(live);