@deepseek-ai/dsh-ptc-runtime-node 0.2.1-rc.5 → 0.2.2-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,16 +1,113 @@
1
1
  import { stripTypeScriptTypes } from "node:module";
2
- import { AsyncLocalStorage } from "node:async_hooks";
3
- import { dirname, isAbsolute, resolve } from "node:path";
4
2
  import { DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, PtcRuntime, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from "@deepseek-ai/dsh-ptc-runtime";
3
+ import { dirname, isAbsolute, resolve } from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { assertNever, snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
6
+ import z from "@deepseek-ai/schemastery";
5
7
  import { MAX_TIMER_DELAY_MS, clampTimeout } from "@deepseek-ai/dsh-timeout";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
6
9
  import { SandboxUnavailableError, classifyRunnerFailure, isRunnerSpawnFailure } from "@deepseek-ai/dsh-sandbox";
7
- import { assertNever, snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
8
10
  import { Buffer as Buffer$1 } from "node:buffer";
9
- import { fileURLToPath, pathToFileURL } from "node:url";
10
- import z from "@deepseek-ai/schemastery";
11
+ import { createBirpc } from "birpc";
12
+ //#region lib/types/launch.js
13
+ /** Select source or built bootstrap assets in the mounted execution world. */
14
+ /**
15
+ * Resolve the local carrier default or validate an explicit execution-world invocation.
16
+ * @param config - explicit remote or local worker configuration; omitted selects this carrier.
17
+ * @returns the worker invocation without guessing from the execution world's paths.
18
+ */
19
+ function resolveLaunch(config) {
20
+ const launch = config ?? {
21
+ kind: "pkg" in process ? "embedded" : "node-script",
22
+ executable: process.execPath
23
+ };
24
+ if (launch.executable.length === 0) throw new Error("ptc-runtime-node: launch.executable must be non-empty");
25
+ if (launch.kind === "node-script" && launch.bootstrapPath !== void 0 && !isAbsolute(launch.bootstrapPath)) throw new Error("ptc-runtime-node: launch.bootstrapPath must be absolute");
26
+ return launch;
27
+ }
28
+ /**
29
+ * Select explicit arguments without inheriting host loader or inspector flags.
30
+ * @param fs - Filesystem mapping host bootstrap assets into the process world.
31
+ * @param config - resolved worker invocation.
32
+ * @param maxMessageBytes - Validated frame and queued-write limit.
33
+ * @param persistent - Whether the selected mode requires retained-process launch support.
34
+ * @returns Arguments following the resolved Node executable.
35
+ */
36
+ function bootstrapArgs(fs, config, maxMessageBytes, persistent = false) {
37
+ switch (config.kind) {
38
+ case "embedded":
39
+ if (persistent) throw new Error("Persistent PTC requires a node-script launch");
40
+ return [String(maxMessageBytes)];
41
+ case "node-script": return scriptBootstrapArgs(fs, config.bootstrapPath, maxMessageBytes);
42
+ /* v8 ignore next -- Callers supply the resolved, closed LaunchConfig union. */
43
+ default: return assertNever(config);
44
+ }
45
+ }
46
+ function scriptBootstrapArgs(fs, bootstrapPath, maxMessageBytes) {
47
+ if (bootstrapPath !== void 0) return [bootstrapPath, String(maxMessageBytes)];
48
+ const mapped = (path) => {
49
+ const result = fs.processPathFromHostPath(path);
50
+ if (result === void 0) throw new Error(`PTC runtime bootstrap is unavailable in the subprocess execution world: ${path}`);
51
+ return result;
52
+ };
53
+ /* v8 ignore next 3 -- built-lib.e2e.ts executes the bundled provider and sibling process.js under plain Node. */
54
+ if (!new URL(import.meta.url).pathname.endsWith(".ts")) return [mapped(fileURLToPath(new URL("./process.js", import.meta.url))), String(maxMessageBytes)];
55
+ const entry = mapped(fileURLToPath(new URL("./process.ts", import.meta.url)));
56
+ const helper = mapped(resolve(dirname(fileURLToPath(import.meta.resolve("@deepseek-ai/dsh-subprocess/package.json"))), "src/control.ts"));
57
+ return [
58
+ "--input-type=module",
59
+ "--eval",
60
+ `const {openInheritedControlChannel}=await import(${JSON.stringify(pathToFileURL(helper).href)});const {runNodeMain}=await import(${JSON.stringify(pathToFileURL(entry).href)});await runNodeMain(openInheritedControlChannel(),${maxMessageBytes},process);`
61
+ ];
62
+ }
63
+ //#endregion
64
+ //#region lib/types/config.js
65
+ /** Execution mode and resource limits for the Node PTC provider. */
66
+ /** Loader defaults for the Node PTC provider. */
67
+ const NodeConfig = z.object({
68
+ executionMode: z.union([
69
+ z.const("per-call"),
70
+ z.const("persistent-in-memory"),
71
+ z.const("vm-script")
72
+ ]).default("per-call"),
73
+ scriptPersistence: z.boolean().default(false),
74
+ timeoutMs: z.number().default(12e4),
75
+ maxTimeoutMs: z.number().default(6e5),
76
+ maxOutputBytes: z.number().default(67108864),
77
+ maxOldGenerationSizeMb: z.number().default(512),
78
+ maxMessageBytes: z.number().default(134217728),
79
+ maxPendingCalls: z.number().default(128),
80
+ graceMs: z.number().default(3e3),
81
+ launch: z.union([z.object({
82
+ kind: z.const("node-script").required(),
83
+ executable: z.string().required(),
84
+ bootstrapPath: z.string()
85
+ }), z.object({
86
+ kind: z.const("embedded").required(),
87
+ executable: z.string().required()
88
+ })])
89
+ });
90
+ /**
91
+ * Validate resolved Node limits and paths.
92
+ * @param config - Loader-defaulted fields with the selected executable.
93
+ */
94
+ function validateConfig(config) {
95
+ if (config.scriptPersistence && config.executionMode !== "vm-script") throw new Error("ptc-runtime-node: scriptPersistence requires executionMode: vm-script");
96
+ 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`);
97
+ for (const key of [
98
+ "timeoutMs",
99
+ "maxTimeoutMs",
100
+ "graceMs"
101
+ ]) if (config[key] > MAX_TIMER_DELAY_MS) throw new Error(`ptc-runtime-node: ${key} exceeds the supported timer range`);
102
+ if (!Number.isSafeInteger(config.maxOutputBytes) || config.maxOutputBytes < 4) throw new Error("ptc-runtime-node: maxOutputBytes must be an integer of at least 4");
103
+ if (!Number.isSafeInteger(config.maxMessageBytes)) throw new Error("ptc-runtime-node: maxMessageBytes must be an integer");
104
+ if (!Number.isSafeInteger(config.maxPendingCalls)) throw new Error("ptc-runtime-node: maxPendingCalls must be an integer");
105
+ if (!Number.isSafeInteger(config.maxOldGenerationSizeMb)) throw new Error("ptc-runtime-node: maxOldGenerationSizeMb must be an integer");
106
+ }
107
+ //#endregion
11
108
  //#region lib/types/json-wire.js
12
109
  /**
13
- * Lossless-JSON snapshots for the dependency-free source bootstrap closure.
110
+ * Lossless-JSON snapshots shared by the host and the source bootstrap closure.
14
111
  * @module @deepseek-ai/dsh-ptc-runtime-node/json-wire
15
112
  */
16
113
  const intrinsicFunctionToString = Reflect.get(Function.prototype, "toString");
@@ -304,33 +401,116 @@ function validateBindings(request) {
304
401
  return bindings;
305
402
  }
306
403
  /**
307
- * Invoke a host binding and encode its lossless result or bounded-channel rejection.
308
- * @param id - Program-issued correlation identifier.
309
- * @param binding - Current evaluation's declared function, absent if it was removed.
404
+ * Invoke a host binding and encode its lossless result.
405
+ * @param binding - Current evaluation's function, absent if it was removed.
310
406
  * @param args - Validated JSON arguments detached from the program.
311
- * @returns A reply suitable for the runtime's bounded control channel.
407
+ * @returns Flat lossless JSON; unavailable bindings and invalid results reject.
312
408
  */
313
- async function replyToBinding(id, binding, args) {
314
- try {
315
- if (!binding) throw new Error("binding is unavailable in this evaluation; reacquire the current tool");
316
- const value = snapshotJsonValue(await binding(args));
317
- if (value === void 0) throw new Error("binding resolution must be lossless JSON");
318
- return {
319
- type: "reply",
320
- id,
321
- ok: true,
322
- value: encodePtcJsonWire(value)
323
- };
324
- } catch (error) {
325
- return {
326
- type: "reply",
327
- id,
328
- ok: false,
329
- message: error instanceof Error ? error.message : String(error)
330
- };
331
- }
409
+ async function invokeBinding(binding, args) {
410
+ if (!binding) throw new Error("binding is unavailable in this evaluation; reacquire the current tool");
411
+ const value = snapshotJsonValue(await binding(args));
412
+ if (value === void 0) throw new Error("binding resolution must be lossless JSON");
413
+ return encodePtcJsonWire(value);
414
+ }
415
+ //#endregion
416
+ //#region lib/types/rpc.js
417
+ /** birpc over newline-delimited JSON on the bounded private process channel. */
418
+ const stringify = JSON.stringify;
419
+ const parse = JSON.parse;
420
+ const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
421
+ /**
422
+ * Connect typed methods over one control endpoint; execution owns all deadlines.
423
+ * @param stream - Owned control endpoint; `$close()` destroys it and rejects outstanding remote calls.
424
+ * @param maxMessageBytes - Maximum incoming JSON line and queued outgoing bytes.
425
+ * @param functions - Only these own methods may be called by the peer.
426
+ * @param eventNames - Remote methods sent as notifications without a response.
427
+ * @param failure - Receives the first I/O error, peer closure or malformed-message failure after the endpoint closes.
428
+ * @returns Typed remote calls and birpc lifetime controls.
429
+ */
430
+ function createProcessRpc(stream, maxMessageBytes, functions, eventNames, failure) {
431
+ const fail = (error, kind) => {
432
+ if (rpc.$closed) return;
433
+ rpc.$close();
434
+ failure(error, kind);
435
+ };
436
+ let receive;
437
+ const rpc = createBirpc(functions, {
438
+ timeout: -1,
439
+ eventNames,
440
+ on: (listener) => {
441
+ receive = listener;
442
+ },
443
+ off: () => {
444
+ receive = void 0;
445
+ stream.destroy();
446
+ },
447
+ serialize: (message) => `${stringify(message.e === void 0 ? message : {
448
+ ...message,
449
+ e: { message: messageOf$1(message.e) }
450
+ })}\n`,
451
+ post: (line) => {
452
+ if (rpc.$closed) return;
453
+ if (stream.writableLength + Buffer$1.byteLength(line) > maxMessageBytes) fail(/* @__PURE__ */ new Error(`control output exceeds ${maxMessageBytes} queued bytes`), "protocol");
454
+ else stream.write(line);
455
+ },
456
+ deserialize: (line) => {
457
+ const message = parse(line);
458
+ if (message.e) message.e = new Error(String(message.e.message));
459
+ return message;
460
+ },
461
+ resolver: (name, fn) => Object.hasOwn(functions, name) ? (...args) => rpc.$closed ? void 0 : fn.apply(functions, args) : void 0
462
+ });
463
+ let parts = [];
464
+ let size = 0;
465
+ const buffer = (part) => {
466
+ if (size === 0 && part.length > 0 && part[0] !== 123) throw new Error("control message is not a JSON object; the Node bootstrap may be from another release");
467
+ size += part.length;
468
+ if (size > maxMessageBytes) throw new Error(`RPC message exceeds ${maxMessageBytes} bytes`);
469
+ parts.push(part);
470
+ };
471
+ stream.on("data", (chunk) => {
472
+ try {
473
+ let start = 0;
474
+ for (let end = chunk.indexOf(10); end !== -1; end = chunk.indexOf(10, start)) {
475
+ buffer(chunk.subarray(start, end));
476
+ const line = Buffer$1.concat(parts, size).toString("utf8");
477
+ parts = [];
478
+ size = 0;
479
+ start = end + 1;
480
+ Promise.resolve(receive?.(line)).catch((error) => {
481
+ fail(error, "protocol");
482
+ });
483
+ }
484
+ buffer(chunk.subarray(start));
485
+ } catch (error) {
486
+ fail(error, "protocol");
487
+ }
488
+ });
489
+ stream.on("end", () => {
490
+ if (size === 0) fail(/* @__PURE__ */ new Error("control channel ended before the program settled"), "closed");
491
+ else fail(/* @__PURE__ */ new Error("incomplete RPC message"), "protocol");
492
+ });
493
+ stream.on("error", (error) => {
494
+ fail(error, "io");
495
+ });
496
+ stream.on("close", () => {
497
+ fail(/* @__PURE__ */ new Error("control channel closed"), "closed");
498
+ });
499
+ return rpc;
332
500
  }
333
501
  //#endregion
502
+ //#region lib/types/environment.js
503
+ /** Startup variables required by native executables before model evaluation. */
504
+ /** Native executable search, Windows system paths, and sandbox temporary paths retained in the OS environment. */
505
+ const STARTUP_ENVIRONMENT_NAMES = new Set([
506
+ "PATH",
507
+ "PATHEXT",
508
+ "SYSTEMROOT",
509
+ "WINDIR",
510
+ "TEMP",
511
+ "TMP"
512
+ ]);
513
+ //#endregion
334
514
  //#region lib/types/output-json.js
335
515
  /** JSON string-prefix accounting for the outer-output ledger. @module @deepseek-ai/dsh-ptc-runtime-node/output-json */
336
516
  const intrinsicReflectApply = Reflect.apply;
@@ -508,381 +688,85 @@ function truncateJsonStringBytes(text, maxBytes) {
508
688
  return end === text.length ? text : intrinsicReflectApply(intrinsicStringSlice, text, [0, end]);
509
689
  }
510
690
  //#endregion
511
- //#region lib/types/channel.js
512
- /** Length-prefixed JSON transport with bounded input and queued writes. */
513
- const stringify = JSON.stringify;
514
- const parse = JSON.parse;
515
- /** One co-shipped process channel; the consumer owns frame validation and terminal outcomes. */
516
- var JsonChannel = class {
517
- stream;
691
+ //#region lib/types/output-ledger.js
692
+ /** One run's combined outer-output ledger; binding values never enter it. */
693
+ var OutputLedger = class {
518
694
  maxBytes;
519
- receive;
520
- failure;
521
- header = Buffer$1.alloc(4);
522
- headerBytes = 0;
523
- payload;
524
- payloadBytes = 0;
525
- queuedBytes = 0;
526
- closed = false;
527
- writes = /* @__PURE__ */ new Set();
528
- constructor(stream, maxBytes, receive, failure) {
529
- this.stream = stream;
695
+ overflowMessage;
696
+ bytes = 2;
697
+ entries = 0;
698
+ constructor(maxBytes, overflowMessage) {
530
699
  this.maxBytes = maxBytes;
531
- this.receive = receive;
532
- this.failure = failure;
533
- stream.on("data", this.onData);
534
- stream.on("error", this.onError);
535
- stream.on("end", this.onEnd);
536
- stream.on("close", this.onClose);
700
+ this.overflowMessage = overflowMessage;
537
701
  }
538
- onError = (error) => {
539
- this.finishWrites(error);
540
- if (!this.closed) this.failure(error, "io");
541
- };
542
- onClose = () => {
543
- this.finishWrites(/* @__PURE__ */ new Error("control channel closed during a write"));
544
- };
545
- onEnd = () => {
546
- if (!this.closed) this.failure(/* @__PURE__ */ new Error("control channel ended before the program settled"), "io");
547
- };
548
- onData = (chunk) => {
549
- if (this.closed) return;
550
- try {
551
- let offset = 0;
552
- while (offset < chunk.length && !this.closed) {
553
- if (this.payload === void 0) {
554
- const bytes = Math.min(4 - this.headerBytes, chunk.length - offset);
555
- chunk.copy(this.header, this.headerBytes, offset, offset + bytes);
556
- this.headerBytes += bytes;
557
- offset += bytes;
558
- if (this.headerBytes !== 4) continue;
559
- const length = this.header.readUInt32BE(0);
560
- if (length === 0 || length > this.maxBytes) throw new Error(`control frame exceeds ${this.maxBytes} bytes or is empty`);
561
- this.payload = Buffer$1.allocUnsafe(length);
562
- this.payloadBytes = 0;
563
- this.headerBytes = 0;
564
- }
565
- const bytes = Math.min(this.payload.length - this.payloadBytes, chunk.length - offset);
566
- chunk.copy(this.payload, this.payloadBytes, offset, offset + bytes);
567
- this.payloadBytes += bytes;
568
- offset += bytes;
569
- if (this.payloadBytes !== this.payload.length) continue;
570
- const frame = this.payload;
571
- this.payload = void 0;
572
- this.payloadBytes = 0;
573
- this.receive(parse(new TextDecoder("utf-8", { fatal: true }).decode(frame)), frame.length);
702
+ /** Admit one exact log entry, or report that the hard cap was crossed. */
703
+ admit(text, sink) {
704
+ const separatorBytes = this.entries > 0 ? 1 : 0;
705
+ const stringBytes = jsonStringBytesUpTo(text, this.maxBytes - this.bytes - separatorBytes);
706
+ if (stringBytes === void 0) return false;
707
+ this.bytes += stringBytes + separatorBytes;
708
+ this.entries += 1;
709
+ sink.push(text);
710
+ return true;
711
+ }
712
+ /** Finalize a successful absent-or-JSON completion against the combined cap. */
713
+ success(logs, value) {
714
+ if (value !== void 0 && jsonValueBytesUpTo(value, this.maxBytes - this.bytes) === void 0) return this.limit(logs);
715
+ return {
716
+ logs,
717
+ ...value !== void 0 ? { value } : {}
718
+ };
719
+ }
720
+ /** Finalize a failure diagnostic, with output-limit taking precedence when combined bytes exceed the cap. */
721
+ failure(logs, error) {
722
+ if (jsonStringBytesUpTo(error.message, this.maxBytes - this.bytes) === void 0) return this.limit(logs);
723
+ return {
724
+ logs,
725
+ error
726
+ };
727
+ }
728
+ /** Build the explicit output-limit failure while retaining a fitting prefix of the final log. */
729
+ limit(logs) {
730
+ const fullMessage = this.overflowMessage ?? `outer output exceeded ${this.maxBytes} bytes`;
731
+ const messageBytes = fullMessage.length + 2;
732
+ const retained = [];
733
+ let retainedBytes = 2;
734
+ const logBudget = this.maxBytes - messageBytes;
735
+ for (const text of logs) {
736
+ const separatorBytes = retained.length > 0 ? 1 : 0;
737
+ const availableBytes = logBudget - retainedBytes - separatorBytes;
738
+ const stringBytes = jsonStringBytesUpTo(text, availableBytes);
739
+ if (stringBytes !== void 0) {
740
+ retained.push(text);
741
+ retainedBytes += stringBytes + separatorBytes;
742
+ continue;
574
743
  }
575
- } catch (error) {
576
- this.failure(error instanceof Error ? error : new Error(String(error)), "protocol");
744
+ const prefix = truncateJsonStringBytes(text, availableBytes);
745
+ if (prefix.length > 0) {
746
+ const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes);
747
+ /* v8 ignore next -- truncateJsonStringBytes guarantees its returned prefix fits the same budget. */
748
+ if (prefixBytes === void 0) throw new Error("output ledger produced an oversized log prefix");
749
+ retained.push(prefix);
750
+ retainedBytes += prefixBytes + separatorBytes;
751
+ }
752
+ break;
577
753
  }
578
- };
579
- /**
580
- * Submit a bounded frame immediately and await the stream's write receipt.
581
- * @param message - JSON-only co-shipped protocol value.
582
- * @returns Resolves when this frame has been written, or rejects after transport failure.
583
- */
584
- send(message) {
585
- if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("control channel is closed"));
586
- const size = jsonValueBytesUpTo(message, this.maxBytes);
587
- if (size === void 0 || this.queuedBytes + size > this.maxBytes) return Promise.reject(/* @__PURE__ */ new Error(`control output exceeds ${this.maxBytes} queued bytes`));
588
- const body = Buffer$1.from(stringify(message), "utf8");
589
- const header = Buffer$1.alloc(4);
590
- header.writeUInt32BE(body.length);
591
- this.queuedBytes += body.length;
592
- const completion = Promise.withResolvers();
593
- const write = {
594
- promise: completion.promise,
595
- finish: (error) => {
596
- if (!this.writes.delete(write)) return;
597
- this.queuedBytes -= body.length;
598
- if (error) completion.reject(error);
599
- else completion.resolve();
754
+ return {
755
+ logs: retained,
756
+ error: {
757
+ kind: "output-limit",
758
+ message: truncateJsonStringBytes(fullMessage, this.maxBytes - retainedBytes)
600
759
  }
601
760
  };
602
- this.writes.add(write);
603
- try {
604
- this.stream.cork();
605
- this.stream.write(header);
606
- this.stream.write(body, (error) => {
607
- write.finish(error ?? void 0);
608
- });
609
- this.stream.uncork();
610
- } catch (error) {
611
- write.finish(error instanceof Error ? error : new Error(String(error)));
612
- }
613
- return completion.promise;
614
- }
615
- finishWrites(error) {
616
- for (const write of this.writes) write.finish(error);
617
- }
618
- /** Stop reads and close the owned endpoint; pending writes reject on closure. */
619
- close() {
620
- if (this.closed) return;
621
- this.closed = true;
622
- this.payload = void 0;
623
- this.finishWrites(/* @__PURE__ */ new Error("control channel is closed"));
624
- this.stream.off("data", this.onData);
625
- this.stream.off("end", this.onEnd);
626
- this.stream.destroy();
627
- }
628
- /** Wait for accepted writes to finish or fail. */
629
- async drain() {
630
- await Promise.allSettled([...this.writes].map((write) => write.promise));
631
761
  }
632
762
  };
633
763
  //#endregion
634
- //#region lib/types/launch.js
635
- /** Select source or built bootstrap assets in the mounted execution world. */
636
- /**
637
- * Resolve the local carrier default or validate an explicit execution-world invocation.
638
- * @param config - explicit remote or local worker configuration; omitted selects this carrier.
639
- * @returns the worker invocation without guessing from the execution world's paths.
640
- */
641
- function resolveLaunch(config) {
642
- const launch = config ?? {
643
- kind: "pkg" in process ? "embedded" : "node-script",
644
- executable: process.execPath
645
- };
646
- if (launch.executable.length === 0) throw new Error("ptc-runtime-node: launch.executable must be non-empty");
647
- if (launch.kind === "node-script" && launch.bootstrapPath !== void 0 && !isAbsolute(launch.bootstrapPath)) throw new Error("ptc-runtime-node: launch.bootstrapPath must be absolute");
648
- return launch;
649
- }
764
+ //#region lib/types/output-stream.js
650
765
  /**
651
- * Select explicit arguments without inheriting host loader or inspector flags.
652
- * @param fs - Filesystem mapping host bootstrap assets into the process world.
653
- * @param config - resolved worker invocation.
654
- * @param maxMessageBytes - Validated frame and queued-write limit.
655
- * @param persistent - Select the in-memory REPL bootstrap instead of the one-shot evaluator.
656
- * @returns Arguments following the resolved Node executable.
657
- */
658
- function bootstrapArgs(fs, config, maxMessageBytes, persistent = false) {
659
- switch (config.kind) {
660
- case "embedded":
661
- if (persistent) throw new Error("Persistent PTC requires a node-script launch");
662
- return [String(maxMessageBytes)];
663
- case "node-script": return scriptBootstrapArgs(fs, config.bootstrapPath, maxMessageBytes, persistent);
664
- /* v8 ignore next -- Callers supply the resolved, closed LaunchConfig union. */
665
- default: return assertNever(config);
666
- }
667
- }
668
- function scriptBootstrapArgs(fs, bootstrapPath, maxMessageBytes, persistent) {
669
- const moduleName = persistent ? "persistent-process" : "process";
670
- if (bootstrapPath !== void 0) return [bootstrapPath, String(maxMessageBytes)];
671
- const mapped = (path) => {
672
- const result = fs.processPathFromHostPath(path);
673
- if (result === void 0) throw new Error(`PTC runtime bootstrap is unavailable in the subprocess execution world: ${path}`);
674
- return result;
675
- };
676
- /* v8 ignore next 3 -- built-lib.e2e.ts executes the bundled provider and sibling process.js under plain Node. */
677
- if (!new URL(import.meta.url).pathname.endsWith(".ts")) return [mapped(fileURLToPath(new URL(`./${moduleName}.js`, import.meta.url))), String(maxMessageBytes)];
678
- const entry = mapped(fileURLToPath(new URL(`./${moduleName}.ts`, import.meta.url)));
679
- const helper = mapped(resolve(dirname(fileURLToPath(import.meta.resolve("@deepseek-ai/dsh-subprocess/package.json"))), "src/control.ts"));
680
- const main = persistent ? "runPersistentMain" : "runNodeMain";
681
- return [
682
- "--input-type=module",
683
- "--eval",
684
- `const {openInheritedControlChannel}=await import(${JSON.stringify(pathToFileURL(helper).href)});const {${main}}=await import(${JSON.stringify(pathToFileURL(entry).href)});await ${main}(openInheritedControlChannel(),${maxMessageBytes},process);`
685
- ];
686
- }
687
- //#endregion
688
- //#region lib/types/config.js
689
- /** Execution mode and resource limits for the Node PTC provider. */
690
- /** Loader defaults for the Node PTC provider. */
691
- const NodeConfig = z.object({
692
- executionMode: z.union([z.const("per-call"), z.const("persistent-in-memory")]).default("per-call"),
693
- timeoutMs: z.number().default(12e4),
694
- maxTimeoutMs: z.number().default(6e5),
695
- maxOutputBytes: z.number().default(67108864),
696
- maxOldGenerationSizeMb: z.number().default(512),
697
- maxMessageBytes: z.number().default(134217728),
698
- maxPendingCalls: z.number().default(128),
699
- graceMs: z.number().default(3e3),
700
- launch: z.union([z.object({
701
- kind: z.const("node-script").required(),
702
- executable: z.string().required(),
703
- bootstrapPath: z.string()
704
- }), z.object({
705
- kind: z.const("embedded").required(),
706
- executable: z.string().required()
707
- })])
708
- });
709
- /**
710
- * Validate resolved Node limits and paths.
711
- * @param config - Loader-defaulted fields with the selected executable.
712
- */
713
- function validateConfig(config) {
714
- 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`);
715
- for (const key of [
716
- "timeoutMs",
717
- "maxTimeoutMs",
718
- "graceMs"
719
- ]) if (config[key] > MAX_TIMER_DELAY_MS) throw new Error(`ptc-runtime-node: ${key} exceeds the supported timer range`);
720
- if (!Number.isSafeInteger(config.maxOutputBytes) || config.maxOutputBytes < 4) throw new Error("ptc-runtime-node: maxOutputBytes must be an integer of at least 4");
721
- if (!Number.isSafeInteger(config.maxMessageBytes) || config.maxMessageBytes > 4294967295) throw new Error("ptc-runtime-node: maxMessageBytes must fit an unsigned 32-bit frame length");
722
- if (!Number.isSafeInteger(config.maxPendingCalls)) throw new Error("ptc-runtime-node: maxPendingCalls must be an integer");
723
- if (!Number.isSafeInteger(config.maxOldGenerationSizeMb)) throw new Error("ptc-runtime-node: maxOldGenerationSizeMb must be an integer");
724
- }
725
- //#endregion
726
- //#region lib/types/policy-processes.js
727
- /** Owns asynchronous process cleanup without delaying permission setters. */
728
- var PolicyProcesses = class {
729
- ctx;
730
- processes = /* @__PURE__ */ new Set();
731
- /**
732
- * Begin cleanup on policy changes, even when no subsequent program runs.
733
- * @param ctx - Node provider lifecycle and Session services.
734
- */
735
- constructor(ctx) {
736
- this.ctx = ctx;
737
- ctx.on("session/event", (session, event) => {
738
- if (event.type !== "sandbox/mode") return;
739
- for (const process of this.processes) {
740
- if (process.sessionId !== session.id || process.mode === event.data.mode) continue;
741
- process.invalidated = true;
742
- this.release(process).catch((error) => {
743
- ctx.logger.warn(error);
744
- });
745
- }
746
- }, { global: true });
747
- ctx.effect(() => async () => {
748
- await this.settle([...this.processes]);
749
- }, "Node PTC policy cleanup");
750
- }
751
- /**
752
- * Track an admitted call or retained process until its owner confirms cleanup.
753
- * @param policy - Resolved process policy, including an optional Session identity.
754
- * @param release - Idempotent cancellation and awaited cleanup.
755
- * @returns Removal after successful process cleanup.
756
- */
757
- register(policy, release) {
758
- if (policy.sessionId === void 0) return () => {};
759
- const session = this.ctx.get("sessions")?.get(policy.sessionId);
760
- const process = {
761
- sessionId: policy.sessionId,
762
- mode: session === void 0 ? policy.mode : this.ctx.sandboxPolicy.resolve({ session }).mode,
763
- release,
764
- invalidated: false
765
- };
766
- this.processes.add(process);
767
- return () => {
768
- this.processes.delete(process);
769
- };
770
- }
771
- /**
772
- * Wait for invalidated processes before admitting another program.
773
- * @param sessionId - Session carried by the resolved policy.
774
- * @returns Completion after prior cleanup; a failure rejects and remains retryable.
775
- */
776
- async wait(sessionId) {
777
- await this.settle([...this.processes].filter((process) => process.sessionId === sessionId && process.invalidated));
778
- }
779
- release(process) {
780
- if (process.cleanup !== void 0) return process.cleanup;
781
- process.cleanup = process.release().then(() => {
782
- this.processes.delete(process);
783
- }, (error) => {
784
- delete process.cleanup;
785
- throw error;
786
- });
787
- return process.cleanup;
788
- }
789
- async settle(processes) {
790
- const failed = (await Promise.allSettled(processes.map((process) => this.release(process)))).find((result) => result.status === "rejected");
791
- if (failed?.status === "rejected") throw failed.reason;
792
- }
793
- };
794
- //#endregion
795
- //#region lib/types/environment.js
796
- /** Startup variables required by native executables before model evaluation. */
797
- /** Native executable search, Windows system paths, and sandbox temporary paths retained in the OS environment. */
798
- const STARTUP_ENVIRONMENT_NAMES = new Set([
799
- "PATH",
800
- "PATHEXT",
801
- "SYSTEMROOT",
802
- "WINDIR",
803
- "TEMP",
804
- "TMP"
805
- ]);
806
- //#endregion
807
- //#region lib/types/output-ledger.js
808
- /** One run's combined outer-output ledger; binding values never enter it. */
809
- var OutputLedger = class {
810
- maxBytes;
811
- overflowMessage;
812
- bytes = 2;
813
- entries = 0;
814
- constructor(maxBytes, overflowMessage) {
815
- this.maxBytes = maxBytes;
816
- this.overflowMessage = overflowMessage;
817
- }
818
- /** Admit one exact log entry, or report that the hard cap was crossed. */
819
- admit(text, sink) {
820
- const separatorBytes = this.entries > 0 ? 1 : 0;
821
- const stringBytes = jsonStringBytesUpTo(text, this.maxBytes - this.bytes - separatorBytes);
822
- if (stringBytes === void 0) return false;
823
- this.bytes += stringBytes + separatorBytes;
824
- this.entries += 1;
825
- sink.push(text);
826
- return true;
827
- }
828
- /** Finalize a successful absent-or-JSON completion against the combined cap. */
829
- success(logs, value) {
830
- if (value !== void 0 && jsonValueBytesUpTo(value, this.maxBytes - this.bytes) === void 0) return this.limit(logs);
831
- return {
832
- logs,
833
- ...value !== void 0 ? { value } : {}
834
- };
835
- }
836
- /** Finalize a failure diagnostic, with output-limit taking precedence when combined bytes exceed the cap. */
837
- failure(logs, error) {
838
- if (jsonStringBytesUpTo(error.message, this.maxBytes - this.bytes) === void 0) return this.limit(logs);
839
- return {
840
- logs,
841
- error
842
- };
843
- }
844
- /** Build the explicit output-limit failure while retaining a fitting prefix of the final log. */
845
- limit(logs) {
846
- const fullMessage = this.overflowMessage ?? `outer output exceeded ${this.maxBytes} bytes`;
847
- const messageBytes = fullMessage.length + 2;
848
- const retained = [];
849
- let retainedBytes = 2;
850
- const logBudget = this.maxBytes - messageBytes;
851
- for (const text of logs) {
852
- const separatorBytes = retained.length > 0 ? 1 : 0;
853
- const availableBytes = logBudget - retainedBytes - separatorBytes;
854
- const stringBytes = jsonStringBytesUpTo(text, availableBytes);
855
- if (stringBytes !== void 0) {
856
- retained.push(text);
857
- retainedBytes += stringBytes + separatorBytes;
858
- continue;
859
- }
860
- const prefix = truncateJsonStringBytes(text, availableBytes);
861
- if (prefix.length > 0) {
862
- const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes);
863
- /* v8 ignore next -- truncateJsonStringBytes guarantees its returned prefix fits the same budget. */
864
- if (prefixBytes === void 0) throw new Error("output ledger produced an oversized log prefix");
865
- retained.push(prefix);
866
- retainedBytes += prefixBytes + separatorBytes;
867
- }
868
- break;
869
- }
870
- return {
871
- logs: retained,
872
- error: {
873
- kind: "output-limit",
874
- message: truncateJsonStringBytes(fullMessage, this.maxBytes - retainedBytes)
875
- }
876
- };
877
- }
878
- };
879
- //#endregion
880
- //#region lib/types/output-stream.js
881
- /**
882
- * Wait for queued bytes without letting an inherited descriptor retain a run forever.
883
- * @param stream - Caller-owned raw process output, when provided.
884
- * @param graceMs - Maximum wait after managed process termination.
885
- * @returns Whether the complete stream ended without a transport error.
766
+ * Wait for queued bytes without letting an inherited descriptor retain a run forever.
767
+ * @param stream - Caller-owned raw process output, when provided.
768
+ * @param graceMs - Maximum wait after managed process termination.
769
+ * @returns Whether the complete stream ended without a transport error.
886
770
  */
887
771
  function drainOutput(stream, graceMs) {
888
772
  if (stream === void 0 || stream.readableEnded) return Promise.resolve(true);
@@ -931,18 +815,41 @@ async function terminateProcess(handle, graceMs) {
931
815
  }
932
816
  }
933
817
  //#endregion
934
- //#region lib/types/persistent.js
935
- /** Node PTC in-memory execution with retained processes scoped to caller-owned objects. */
936
- const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
937
- const record$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
938
- function persistentOutput(maxBytes) {
939
- return new OutputLedger(maxBytes, `retained variables were cleared; outer output exceeded ${maxBytes} bytes`);
818
+ //#region lib/types/protocol.js
819
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
820
+ /**
821
+ * Decode a remote run result without trusting model-written control traffic.
822
+ * @param result - Untrusted result returned by the program process.
823
+ * @returns Decoded completion or failure; malformed envelopes throw a protocol error.
824
+ */
825
+ function readProgramResult(result) {
826
+ if (!record(result)) throw new Error("invalid program result");
827
+ if (result.error !== void 0) {
828
+ const error = result.error;
829
+ if (!record(error) || typeof error.message !== "string" || error.kind !== "exception" && error.kind !== "invalid-output" && error.kind !== "output-limit") throw new Error("invalid terminal error");
830
+ return { error: {
831
+ kind: error.kind,
832
+ message: error.message
833
+ } };
834
+ }
835
+ if (result.value === void 0) return {};
836
+ const value = decodePtcJsonWire(result.value);
837
+ return value === void 0 ? { error: {
838
+ kind: "invalid-output",
839
+ message: "program completion must be lossless JSON"
840
+ } } : { value };
940
841
  }
842
+ //#endregion
843
+ //#region lib/types/worker.js
844
+ /** Managed Node process shared by temporary and owner-retained evaluations. */
845
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
941
846
  /** One managed process; all mutable program state belongs to this process alone. */
942
- var Kernel = class {
847
+ var ProgramWorker = class {
943
848
  ctx;
944
849
  config;
945
850
  policy;
851
+ mode;
852
+ retainsState;
946
853
  unregister;
947
854
  confined;
948
855
  handle;
@@ -952,35 +859,56 @@ var Kernel = class {
952
859
  running = false;
953
860
  cleanupPending = false;
954
861
  ready = false;
955
- sequence = 0;
956
- nextCall = 1;
957
862
  stderr = "";
863
+ controlFailure;
958
864
  stopped;
959
865
  starting;
960
866
  exitOutcome;
961
867
  controller = new AbortController();
962
868
  closed = false;
963
- constructor(ctx, config, policy, processes) {
869
+ /** Whether termination succeeded and this process no longer needs cleanup retries. */
870
+ get cleanupComplete() {
871
+ return this.closed && !this.cleanupPending;
872
+ }
873
+ /**
874
+ * Own one process under a fixed file policy.
875
+ * @param ctx - Provider execution services.
876
+ * @param config - Validated resource limits and launch selection.
877
+ * @param policy - Authority retained for the lifetime of this process.
878
+ * @param processes - Session policy invalidation and cleanup coordination.
879
+ * @param mode - Evaluator syntax and TypeScript erasure.
880
+ * @param retainsState - Whether this process belongs to an owner and survives completed evaluations.
881
+ */
882
+ constructor(ctx, config, policy, processes, mode, retainsState) {
964
883
  this.ctx = ctx;
965
884
  this.config = config;
966
885
  this.policy = policy;
886
+ this.mode = mode;
887
+ this.retainsState = retainsState;
967
888
  this.unregister = processes.register(policy, () => this.dispose());
968
889
  }
890
+ /** Reject reuse until the previous evaluation and required cleanup settle. */
969
891
  assertIdle() {
970
892
  if (this.running) throw new Error("persistent PTC does not accept concurrent runs for one state owner");
971
893
  if (this.cleanupPending) throw new Error("persistent PTC environment cleanup is incomplete; release the owner before running another program");
972
894
  }
973
- async run(spec, bindings, code) {
895
+ /**
896
+ * Evaluate a program, retaining this process only for an enabled state owner.
897
+ * @param spec - Resolved program inputs and cancellation.
898
+ * @param bindings - Current host binding implementations.
899
+ * @returns Output after any required process cleanup.
900
+ */
901
+ async run(spec, bindings) {
974
902
  this.running = true;
975
903
  const sandbox = {
976
904
  mode: this.policy.mode,
977
905
  denied: false
978
906
  };
979
907
  try {
980
- const result = await this.evaluate(spec, bindings, code);
908
+ const result = await this.evaluate(spec, bindings);
981
909
  if (this.confined !== void 0) {
982
910
  sandbox.enforcement = this.confined.enforcement;
983
- sandbox.denied = result.error?.kind !== "sandbox-unavailable" && this.confined.denialSignatures.some((signature) => result.error?.message.toLowerCase().includes(signature.toLowerCase()));
911
+ sandbox.denied ||= result.error?.kind !== "sandbox-unavailable" && this.confined.denialSignatures.some((signature) => result.error?.message.toLowerCase().includes(signature.toLowerCase()));
984
912
  }
985
913
  return {
986
914
  ...result,
@@ -990,46 +918,58 @@ var Kernel = class {
990
918
  this.running = false;
991
919
  }
992
920
  }
993
- async evaluate(spec, bindings, code) {
921
+ output() {
922
+ return new OutputLedger(this.config.maxOutputBytes, this.retainsState ? `retained variables were cleared; outer output exceeded ${this.config.maxOutputBytes} bytes` : void 0);
923
+ }
924
+ message(message) {
925
+ return this.retainsState ? `${message}; retained variables were cleared` : message;
926
+ }
927
+ abortMessage(signal) {
928
+ return this.retainsState ? "execution canceled; retained variables were cleared" : messageOf(signal?.reason);
929
+ }
930
+ async evaluate(spec, bindings) {
994
931
  if (this.exitOutcome !== void 0) {
995
- const output = persistentOutput(this.config.maxOutputBytes);
932
+ const output = this.output();
996
933
  const failure = spec.signal?.aborted ? {
997
934
  kind: "abort",
998
- message: "execution canceled; retained variables were cleared"
935
+ message: this.abortMessage(spec.signal)
999
936
  } : {
1000
937
  kind: "worker-exit",
1001
- message: `${this.exitMessage(this.exitOutcome)}; retained variables were cleared`
938
+ message: this.message(this.exitMessage(this.exitOutcome))
1002
939
  };
1003
940
  try {
1004
941
  await this.stop();
1005
942
  } catch (error) {
1006
943
  return output.failure([], {
1007
944
  kind: "worker-exit",
1008
- message: `managed process cleanup failed: ${messageOf$1(error)}`
945
+ message: `managed process cleanup failed: ${messageOf(error)}`
1009
946
  });
1010
947
  }
1011
948
  return output.failure([], failure);
1012
949
  }
1013
950
  this.stderr = "";
1014
- const output = persistentOutput(this.config.maxOutputBytes);
951
+ const output = this.output();
1015
952
  const logs = [];
953
+ let overflowed = false;
1016
954
  const result = Promise.withResolvers();
1017
955
  const timer = spec.timeoutMs === null ? void 0 : setTimeout(() => {
1018
956
  evaluation.finish({
1019
957
  kind: "timeout",
1020
- message: `execution deadline reached (${spec.timeoutMs}ms); retained variables were cleared`
958
+ message: this.message(`execution deadline reached (${spec.timeoutMs}ms)`)
1021
959
  }, void 0, true);
1022
960
  }, spec.timeoutMs);
1023
961
  const onAbort = () => {
1024
962
  evaluation.finish({
1025
963
  kind: "abort",
1026
- message: "execution canceled; retained variables were cleared"
964
+ message: this.abortMessage(spec.signal)
1027
965
  }, void 0, true);
1028
966
  };
1029
967
  const evaluation = {
1030
- id: ++this.sequence,
968
+ settled: false,
1031
969
  data: {
1032
- code,
970
+ code: "",
971
+ programFormat: this.mode.format,
972
+ retainsState: this.retainsState,
1033
973
  maxOutputBytes: this.config.maxOutputBytes,
1034
974
  namespaces: [...bindings.values()].map((binding) => ({
1035
975
  global: binding.global,
@@ -1039,11 +979,13 @@ var Kernel = class {
1039
979
  },
1040
980
  spec,
1041
981
  bindings,
1042
- reply: AsyncLocalStorage.bind(replyToBinding),
982
+ invoke: AsyncLocalStorage.bind(invokeBinding),
1043
983
  pending: 0,
1044
984
  pendingBytes: 0,
1045
985
  admit: (text) => {
986
+ if (overflowed) return;
1046
987
  if (!output.admit(text, logs)) {
988
+ overflowed = true;
1047
989
  logs.push(text);
1048
990
  evaluation.finish({
1049
991
  kind: "output-limit",
@@ -1052,20 +994,23 @@ var Kernel = class {
1052
994
  }
1053
995
  },
1054
996
  finish: (error, value, discard = false) => {
1055
- if (this.active !== evaluation) return;
997
+ if (evaluation.settled) return;
998
+ evaluation.settled = true;
1056
999
  clearTimeout(timer);
1057
1000
  spec.signal?.removeEventListener("abort", onAbort);
1058
- this.active = void 0;
1059
- const outcome = error?.kind === "output-limit" ? output.limit(logs) : error ? output.failure(logs, error) : output.success(logs, value);
1060
- (discard || outcome.error?.kind === "output-limit" || spec.stateOwner === void 0 ? this.stop() : Promise.resolve(true)).then((drained) => {
1061
- result.resolve(drained ? outcome : output.failure(logs, {
1001
+ const complete = () => overflowed || error?.kind === "output-limit" ? output.limit(logs) : error ? output.failure(logs, error) : output.success(logs, value);
1002
+ const outcome = complete();
1003
+ (discard || outcome.error?.kind === "output-limit" || !this.retainsState ? this.stop() : Promise.resolve(true)).then((drained) => {
1004
+ this.active = void 0;
1005
+ result.resolve(drained ? complete() : output.failure(logs, {
1062
1006
  kind: "worker-exit",
1063
1007
  message: "managed process exited but its output did not drain cleanly"
1064
1008
  }));
1065
1009
  }, (failure) => {
1010
+ this.active = void 0;
1066
1011
  result.resolve(output.failure(logs, {
1067
1012
  kind: "worker-exit",
1068
- message: `managed process cleanup failed: ${messageOf$1(failure)}`
1013
+ message: `managed process cleanup failed: ${messageOf(failure)}`
1069
1014
  }));
1070
1015
  });
1071
1016
  }
@@ -1073,19 +1018,31 @@ var Kernel = class {
1073
1018
  this.active = evaluation;
1074
1019
  spec.signal?.addEventListener("abort", onAbort, { once: true });
1075
1020
  if (spec.signal?.aborted) onAbort();
1076
- else if (this.ready) this.dispatch(evaluation);
1077
1021
  else {
1078
- this.starting = this.start(spec.cwd);
1079
- this.starting.catch((error) => {
1080
- this.fail(error instanceof SandboxUnavailableError || this.confined !== void 0 && isRunnerSpawnFailure(error, this.confined.argv[0], spec.cwd) ? "sandbox-unavailable" : "worker-exit", messageOf$1(error));
1081
- });
1022
+ try {
1023
+ evaluation.data.code = this.mode.stripTypes(spec.program);
1024
+ } catch (error) {
1025
+ evaluation.finish({
1026
+ kind: "exception",
1027
+ message: messageOf(error)
1028
+ });
1029
+ return await result.promise;
1030
+ }
1031
+ if (this.ready) this.dispatch(evaluation);
1032
+ else {
1033
+ this.starting = this.start(spec.cwd);
1034
+ this.starting.catch((error) => {
1035
+ this.fail(error instanceof SandboxUnavailableError || this.confined !== void 0 && isRunnerSpawnFailure(error, this.confined.argv[0], spec.cwd) ? "sandbox-unavailable" : "worker-exit", messageOf(error));
1036
+ });
1037
+ }
1082
1038
  }
1083
1039
  return await result.promise;
1084
1040
  }
1041
+ /** Cancel active work and await managed process termination and output drainage. */
1085
1042
  async dispose() {
1086
1043
  this.active?.finish({
1087
1044
  kind: "abort",
1088
- message: "PTC environment disposed; retained variables were cleared"
1045
+ message: this.message("PTC environment disposed")
1089
1046
  }, void 0, true);
1090
1047
  await this.stop();
1091
1048
  }
@@ -1094,15 +1051,15 @@ var Kernel = class {
1094
1051
  this.closed = true;
1095
1052
  this.cleanupPending = true;
1096
1053
  this.controller.abort();
1097
- this.channel?.close();
1054
+ this.channel?.$close();
1098
1055
  this.stopped = (async () => {
1099
- await this.starting?.catch(() => {});
1056
+ await this.starting?.catch((_error) => {});
1100
1057
  const handle = this.handle;
1101
1058
  return handle === void 0 || await terminateProcess(handle, this.config.graceMs);
1102
1059
  })().then((drained) => {
1103
1060
  this.unregister?.();
1104
1061
  this.cleanupPending = false;
1105
- if (!drained) this.ctx.logger.warn("persistent Node process exited but its output did not drain cleanly");
1062
+ if (!drained) this.ctx.logger.warn("Node process exited but its output did not drain cleanly");
1106
1063
  return drained;
1107
1064
  }, (error) => {
1108
1065
  this.stopped = void 0;
@@ -1113,35 +1070,41 @@ var Kernel = class {
1113
1070
  fail(kind, message) {
1114
1071
  if (this.active) this.active.finish({
1115
1072
  kind,
1116
- message: `${message}; retained variables were cleared`
1073
+ message: this.message(message)
1117
1074
  }, void 0, true);
1118
1075
  else {
1119
1076
  if (!this.closed) this.ctx.logger.warn(message);
1120
1077
  this.stop().catch((error) => {
1121
- this.ctx.logger.warn(messageOf$1(error));
1078
+ this.ctx.logger.warn(messageOf(error));
1122
1079
  });
1123
1080
  }
1124
1081
  }
1125
1082
  dispatch(evaluation) {
1126
- this.channel?.send({
1127
- type: "run",
1128
- id: evaluation.id,
1129
- cwd: evaluation.spec.cwd,
1130
- data: evaluation.data
1083
+ this.channel?.run(evaluation.spec.cwd, evaluation.data).then((raw) => {
1084
+ if (evaluation.settled) return;
1085
+ const { error, value } = readProgramResult(raw);
1086
+ setImmediate(() => {
1087
+ evaluation.finish(error, value);
1088
+ });
1131
1089
  }).catch((error) => {
1132
- this.fail("protocol", messageOf$1(error));
1090
+ if (this.active === evaluation && !this.channel?.$closed) this.fail("protocol", messageOf(error));
1133
1091
  });
1134
1092
  }
1093
+ withControlFailure(message) {
1094
+ return this.controlFailure === void 0 ? message : `${message}; control channel failed: ${this.controlFailure}`;
1095
+ }
1135
1096
  exitMessage(outcome) {
1136
- return `Node process exited (${String(outcome.exitCode)}, signal ${String(outcome.signal)})${this.stderr ? `: ${this.stderr}` : ""}`;
1097
+ return this.withControlFailure(`Node process exited (${String(outcome.exitCode)}, signal ${String(outcome.signal)})${this.stderr ? `: ${this.stderr}` : ""}`);
1137
1098
  }
1138
1099
  async start(cwd) {
1139
1100
  const executable = await this.ctx.subprocess.resolveExecutable(this.config.launch.executable, void 0, this.controller.signal);
1140
1101
  if (this.closed) return;
1102
+ const packaged = this.config.launch.kind === "embedded";
1103
+ const heapFlag = `--max-old-space-size=${this.config.maxOldGenerationSizeMb}`;
1141
1104
  const argv = [
1142
1105
  executable,
1143
- `--max-old-space-size=${this.config.maxOldGenerationSizeMb}`,
1144
- ...bootstrapArgs(this.ctx.fs, this.config.launch, this.config.maxMessageBytes, true)
1106
+ ...packaged ? [] : [heapFlag],
1107
+ ...bootstrapArgs(this.ctx.fs, this.config.launch, this.config.maxMessageBytes, this.retainsState)
1145
1108
  ];
1146
1109
  const policy = this.policy;
1147
1110
  this.confined = policy.mode === "danger-full-access" ? void 0 : await this.ctx.sandbox.confine(argv, {
@@ -1150,6 +1113,10 @@ var Kernel = class {
1150
1113
  }, this.controller.signal);
1151
1114
  if (this.closed) return;
1152
1115
  const env = Object.fromEntries(Object.keys(process.env).filter((key) => !STARTUP_ENVIRONMENT_NAMES.has(key.toUpperCase()) && key.toUpperCase() !== "ELECTRON_RUN_AS_NODE").map((key) => [key, void 0]));
1116
+ if (packaged) {
1117
+ env.DSH_PTC_RUNTIME_NODE = "1";
1118
+ env.NODE_OPTIONS = heapFlag;
1119
+ }
1153
1120
  const handle = this.ctx.subprocess.spawn({
1154
1121
  argv: this.confined?.argv ?? argv,
1155
1122
  cwd,
@@ -1163,7 +1130,7 @@ var Kernel = class {
1163
1130
  graceMs: this.config.graceMs
1164
1131
  });
1165
1132
  this.handle = handle;
1166
- if (!handle.control || !handle.stdout || !handle.stderr) throw new Error("subprocess provider did not supply persistent PTC pipes");
1133
+ if (!handle.control || !handle.stdout || !handle.stderr) throw new Error("subprocess provider did not supply the requested control and output pipes");
1167
1134
  for (const stream of [handle.stdout, handle.stderr]) {
1168
1135
  stream.setEncoding("utf8");
1169
1136
  stream.on("data", (text) => {
@@ -1174,13 +1141,59 @@ var Kernel = class {
1174
1141
  this.fail("worker-exit", error.message);
1175
1142
  });
1176
1143
  }
1177
- this.channel = new JsonChannel(handle.control, this.config.maxMessageBytes, (raw, bytes) => {
1178
- this.receive(raw, bytes);
1179
- }, (error, kind) => {
1144
+ const refuse = (message) => {
1145
+ this.fail("protocol", message);
1146
+ throw new Error(message);
1147
+ };
1148
+ this.channel = createProcessRpc(handle.control, this.config.maxMessageBytes, {
1149
+ ready: () => {
1150
+ if (this.ready || !this.active) {
1151
+ this.fail("protocol", "duplicate program readiness");
1152
+ return;
1153
+ }
1154
+ this.ready = true;
1155
+ this.dispatch(this.active);
1156
+ },
1157
+ log: (text) => {
1158
+ if (!this.ready || this.active === void 0 || typeof text !== "string") this.fail("protocol", "invalid program log");
1159
+ else this.active.admit(text);
1160
+ },
1161
+ outputLimit: () => {
1162
+ if (!this.ready || this.active === void 0) this.fail("protocol", "idle PTC output limit");
1163
+ else this.active.finish({
1164
+ kind: "output-limit",
1165
+ message: "output limit exceeded"
1166
+ }, void 0, true);
1167
+ },
1168
+ invoke: async (global, name, wire) => {
1169
+ const evaluation = this.active;
1170
+ if (!this.ready || evaluation === void 0 || evaluation.settled) return refuse("binding call arrived without an active PTC evaluation");
1171
+ const functions = evaluation.bindings.get(global)?.functions;
1172
+ const fn = functions !== void 0 && Object.hasOwn(functions, name) ? functions[name] : void 0;
1173
+ if (!this.mode.retainsState && typeof fn !== "function") return refuse("program requested an undeclared binding");
1174
+ const args = decodePtcJsonWire(wire);
1175
+ if (args === void 0) return refuse("binding arguments must be lossless JSON");
1176
+ const bytes = Buffer.byteLength(JSON.stringify(wire));
1177
+ if (evaluation.pending >= this.config.maxPendingCalls || evaluation.pendingBytes + bytes > this.config.maxMessageBytes) return refuse("pending binding calls exceed configured limits");
1178
+ evaluation.pending += 1;
1179
+ evaluation.pendingBytes += bytes;
1180
+ try {
1181
+ const value = await evaluation.invoke(fn, args);
1182
+ if (this.active !== evaluation || evaluation.settled) throw new Error("PTC evaluation ended before the binding completed");
1183
+ return value;
1184
+ } finally {
1185
+ evaluation.pending -= 1;
1186
+ evaluation.pendingBytes -= bytes;
1187
+ }
1188
+ }
1189
+ }, [], (error, kind) => {
1180
1190
  if (kind === "protocol") this.fail("protocol", error.message);
1181
- else setImmediate(() => {
1182
- if (!this.closed && this.exitOutcome === void 0) handle.terminate();
1183
- });
1191
+ else {
1192
+ if (kind === "io") this.controlFailure = error.message;
1193
+ setImmediate(() => {
1194
+ if (!this.closed && this.exitOutcome === void 0) handle.terminate();
1195
+ });
1196
+ }
1184
1197
  });
1185
1198
  handle.done.then(async (outcome) => {
1186
1199
  this.exitOutcome = outcome;
@@ -1189,194 +1202,95 @@ var Kernel = class {
1189
1202
  if (!this.closed) this.fail(this.confined !== void 0 && classifyRunnerFailure(outcome.exitCode, this.stderr, this.confined.runnerFailureRules) !== void 0 ? "sandbox-unavailable" : "worker-exit", this.exitMessage(outcome));
1190
1203
  });
1191
1204
  }, (error) => {
1192
- this.fail("worker-exit", messageOf$1(error));
1205
+ this.fail(this.confined !== void 0 && isRunnerSpawnFailure(error, this.confined.argv[0], cwd) ? "sandbox-unavailable" : "worker-exit", this.withControlFailure(messageOf(error)));
1193
1206
  });
1194
1207
  }
1195
- receive(raw, bytes) {
1196
- if (!record$1(raw)) {
1197
- this.fail("protocol", "invalid persistent PTC frame");
1198
- return;
1199
- }
1200
- const evaluation = this.active;
1201
- if (!evaluation) {
1202
- this.fail("protocol", "frame arrived without an active PTC evaluation");
1203
- return;
1204
- }
1205
- if (!this.ready) {
1206
- if (raw.type !== "ready") {
1207
- this.fail("protocol", "expected persistent PTC readiness");
1208
- return;
1209
- }
1210
- this.ready = true;
1211
- this.dispatch(evaluation);
1212
- return;
1213
- }
1214
- if (raw.id !== evaluation.id || !record$1(raw.payload)) {
1215
- this.fail("protocol", "frame does not belong to the active PTC evaluation");
1216
- return;
1217
- }
1218
- const payload = raw.payload;
1219
- switch (payload.type) {
1220
- case "log":
1221
- if (typeof payload.text === "string") evaluation.admit(payload.text);
1222
- else this.fail("protocol", "invalid persistent PTC log");
1223
- return;
1224
- case "output-limit":
1225
- evaluation.finish({
1226
- kind: "output-limit",
1227
- message: "output limit exceeded"
1228
- }, void 0, true);
1229
- return;
1230
- case "done":
1231
- if (payload.error !== void 0) {
1232
- const error = payload.error;
1233
- if (!record$1(error) || typeof error.message !== "string" || error.kind !== "exception" && error.kind !== "invalid-output" && error.kind !== "output-limit") {
1234
- this.fail("protocol", "invalid persistent PTC failure");
1235
- return;
1236
- }
1237
- const failure = {
1238
- kind: error.kind,
1239
- message: error.message
1240
- };
1241
- setImmediate(() => {
1242
- evaluation.finish(failure, void 0, failure.kind === "output-limit");
1243
- });
1244
- } else {
1245
- const value = payload.value === void 0 ? void 0 : decodePtcJsonWire(payload.value);
1246
- const failure = payload.value !== void 0 && value === void 0 ? {
1247
- kind: "invalid-output",
1248
- message: "program completion must be lossless JSON"
1249
- } : void 0;
1250
- setImmediate(() => {
1251
- evaluation.finish(failure, value);
1252
- });
1253
- }
1254
- return;
1255
- case "call": {
1256
- if (payload.id !== this.nextCall || typeof payload.global !== "string" || typeof payload.name !== "string") {
1257
- this.fail("protocol", "invalid persistent PTC binding identity");
1258
- return;
1259
- }
1260
- this.nextCall += 1;
1261
- const args = decodePtcJsonWire(payload.args);
1262
- if (args === void 0) {
1263
- this.fail("protocol", "binding arguments must be lossless JSON");
1264
- return;
1265
- }
1266
- if (++evaluation.pending > this.config.maxPendingCalls || (evaluation.pendingBytes += bytes) > this.config.maxMessageBytes) {
1267
- this.fail("protocol", "pending binding calls exceed configured limits");
1268
- return;
1269
- }
1270
- const functions = evaluation.bindings.get(payload.global)?.functions;
1271
- const fn = functions && Object.hasOwn(functions, payload.name) ? functions[payload.name] : void 0;
1272
- const id = payload.id;
1273
- (async () => {
1274
- const reply = await evaluation.reply(id, fn, args).finally(() => {
1275
- evaluation.pending -= 1;
1276
- evaluation.pendingBytes -= bytes;
1277
- });
1278
- if (this.active === evaluation) await this.channel?.send(reply);
1279
- })().catch((error) => {
1280
- this.fail("protocol", messageOf$1(error));
1281
- });
1282
- return;
1283
- }
1284
- default: this.fail("protocol", "unknown persistent PTC message");
1285
- }
1286
- }
1287
1208
  };
1288
- /** Sandboxed, best-effort retained state; restart, disposal, and interrupted execution clear it. */
1289
- var InMemoryExecution = class {
1209
+ //#endregion
1210
+ //#region lib/types/execution.js
1211
+ /** Select program syntax and own temporary or retained Node processes. */
1212
+ /**
1213
+ * Select program semantics and create their shared process owner.
1214
+ * @param ctx - Provider lifecycle and execution services.
1215
+ * @param config - Validated configuration with loader defaults.
1216
+ * @param processes - Policy invalidation and process cleanup coordination.
1217
+ * @returns Mode selection and temporary or retained execution through one process implementation.
1218
+ */
1219
+ function createExecution(ctx, config, processes) {
1220
+ return new NodeExecution(ctx, config, processes, resolveMode(config));
1221
+ }
1222
+ /** Temporary processes and optional object-owned reuse share one process implementation. */
1223
+ var NodeExecution = class {
1290
1224
  ctx;
1291
1225
  config;
1292
1226
  processes;
1293
- /**
1294
- * Model-facing rules for retained variables, authority, output, and recovery.
1295
- * @returns Usage guidance appended to the run_code schema.
1296
- */
1297
- get executionInstructions() {
1298
- return "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 this execution's sandbox policy; process.env starts empty. Changing the session sandbox mode clears retained variables. An approved sandbox escalation runs in a separate temporary environment: it cannot access retained variables, and its declarations are discarded afterward. Restart, Agent disposal, cancellation, timeout, output overflow, or process failure clears the environment. If a variable is undefined, recreate it and reacquire its resources. State is not restored from the conversation, and failed evaluations can leave earlier mutations in memory. Redeclaring an existing let, const, or class name fails; assign to a mutable binding or use a new name. Await all tool calls; background callbacks cannot call tools after their evaluation ends. Await child-process completion before ending an evaluation; raw subprocess output belongs to whichever evaluation is active when it arrives.";
1299
- }
1227
+ mode;
1300
1228
  owners = /* @__PURE__ */ new WeakMap();
1301
- kernels = /* @__PURE__ */ new Set();
1302
- disposed = false;
1229
+ workers = /* @__PURE__ */ new Set();
1303
1230
  /**
1304
- * Own retained execution resources under the existing Node provider.
1231
+ * Own process instances and optional owner lookup for one provider.
1305
1232
  * @param ctx - Provider lifecycle and execution services.
1306
1233
  * @param config - Validated limits and selected executable.
1307
1234
  * @param processes - Provider-owned policy invalidation and cleanup.
1235
+ * @param mode - Program syntax and TypeScript erasure.
1308
1236
  */
1309
- constructor(ctx, config, processes) {
1237
+ constructor(ctx, config, processes, mode) {
1310
1238
  this.ctx = ctx;
1311
1239
  this.config = config;
1312
1240
  this.processes = processes;
1313
- if (this.config.launch.kind === "embedded") throw new Error("Persistent PTC requires a node-script launch");
1314
- ctx.effect(() => async () => {
1315
- this.disposed = true;
1316
- const results = await Promise.allSettled([...this.kernels].map((kernel) => kernel.dispose()));
1317
- this.kernels.clear();
1318
- const failed = results.find((result) => result.status === "rejected");
1319
- if (failed?.status === "rejected") throw failed.reason;
1320
- }, "Persistent PTC environments");
1241
+ this.mode = mode;
1242
+ if (mode.retainsState && this.config.launch.kind === "embedded") throw new Error("Persistent PTC requires a node-script launch");
1243
+ }
1244
+ /** Stop every owned process, retaining failed cleanup for a later retry. */
1245
+ async dispose() {
1246
+ const failed = (await Promise.allSettled([...this.workers].map(async (worker) => {
1247
+ await worker.dispose();
1248
+ this.workers.delete(worker);
1249
+ }))).find((result) => result.status === "rejected");
1250
+ if (failed?.status === "rejected") throw failed.reason;
1321
1251
  }
1322
1252
  /**
1323
- * Resolve the file policy, directory and deadline for a retained REPL.
1253
+ * Resolve the common file policy, directory and deadline defaults.
1324
1254
  * @param request - Program, bindings, owner, directory and elapsed budget.
1325
1255
  * @returns Resolved inputs with the selected file policy.
1326
1256
  */
1327
1257
  resolve(request) {
1328
- if (this.disposed) throw new Error("persistent PTC: resolve after disposal");
1329
1258
  const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
1330
1259
  const cwd = request.cwd ?? sandboxPolicy.workspaceRoot;
1331
- if (!isAbsolute(cwd)) throw new Error("persistent PTC: cwd must be absolute");
1260
+ if (!isAbsolute(cwd)) throw new Error(`${this.mode.retainsState ? "persistent PTC" : "ptc-runtime-node"}: cwd must be absolute`);
1332
1261
  return {
1333
1262
  ...request,
1334
1263
  sandboxPolicy,
1335
1264
  cwd,
1336
- timeoutMs: request.timeoutMs === null ? null : clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, "persistent PTC timeoutMs")
1265
+ timeoutMs: request.timeoutMs === null ? null : clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, this.mode.retainsState ? "persistent PTC timeoutMs" : "ptc-runtime-node: timeoutMs")
1337
1266
  };
1338
1267
  }
1339
1268
  /**
1340
- * Evaluate statements using this owner's process, or a temporary process without an owner.
1269
+ * Evaluate in a temporary process or reuse an enabled state owner's process.
1341
1270
  * @param spec - Resolved request; concurrent calls for one owner are rejected.
1342
- * @returns Logs, a final JSON expression, or a structured execution failure.
1271
+ * @returns Captured logs, JSON completion, or a structured execution failure.
1343
1272
  */
1344
1273
  async run(spec) {
1345
- if (this.disposed) throw new Error("persistent PTC: run after disposal");
1346
- if (spec.sandboxPolicy === void 0 || !isAbsolute(spec.cwd) || spec.timeoutMs !== null && (!Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs)) throw new Error("persistent PTC: run requires resolved inputs with a sandbox policy");
1274
+ if (spec.sandboxPolicy === void 0) throw new Error("ptc-runtime-node: run requires a resolved sandbox policy");
1275
+ 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");
1347
1276
  const bindings = validateBindings(spec);
1348
- let kernel = spec.stateOwner === void 0 ? void 0 : this.owners.get(spec.stateOwner);
1349
- kernel?.assertIdle();
1350
- if (kernel && !kernel.closed && (kernel.policy.mode !== spec.sandboxPolicy.mode || kernel.policy.workspaceRoot !== spec.sandboxPolicy.workspaceRoot || kernel.policy.sessionId !== spec.sandboxPolicy.sessionId)) throw new Error("persistent PTC: release the retained environment before changing its sandbox policy");
1351
- let code;
1352
- try {
1353
- code = stripTypeScriptTypes(spec.program);
1354
- } catch (error) {
1355
- const output = persistentOutput(this.config.maxOutputBytes);
1356
- const outcome = output.failure([], {
1357
- kind: "exception",
1358
- message: messageOf$1(error)
1359
- });
1360
- if (outcome.error?.kind === "output-limit" && spec.stateOwner !== void 0) try {
1361
- await this.release(spec.stateOwner);
1362
- } catch (failure) {
1363
- return output.failure([], {
1364
- kind: "worker-exit",
1365
- message: `managed process cleanup failed: ${messageOf$1(failure)}`
1366
- });
1367
- }
1368
- return outcome;
1369
- }
1370
- if (!kernel || kernel.closed) {
1371
- if (kernel) this.kernels.delete(kernel);
1372
- kernel = new Kernel(this.ctx, this.config, { ...spec.sandboxPolicy }, this.processes);
1373
- this.kernels.add(kernel);
1374
- if (spec.stateOwner !== void 0) this.owners.set(spec.stateOwner, kernel);
1277
+ const owner = this.mode.retainsState ? spec.stateOwner : void 0;
1278
+ let worker = owner === void 0 ? void 0 : this.owners.get(owner);
1279
+ worker?.assertIdle();
1280
+ if (worker && !worker.closed && (worker.policy.mode !== spec.sandboxPolicy.mode || worker.policy.workspaceRoot !== spec.sandboxPolicy.workspaceRoot || worker.policy.sessionId !== spec.sandboxPolicy.sessionId || !sameAdditionalRoots(worker.policy.additionalWritableRoots, spec.sandboxPolicy.additionalWritableRoots))) throw new Error("persistent PTC: release the retained environment before changing its sandbox policy");
1281
+ if (!worker || worker.closed) {
1282
+ if (worker) this.workers.delete(worker);
1283
+ worker = new ProgramWorker(this.ctx, this.config, {
1284
+ ...spec.sandboxPolicy,
1285
+ ...spec.sandboxPolicy.additionalWritableRoots === void 0 ? {} : { additionalWritableRoots: [...spec.sandboxPolicy.additionalWritableRoots] }
1286
+ }, this.processes, this.mode, owner !== void 0);
1287
+ this.workers.add(worker);
1288
+ if (owner !== void 0) this.owners.set(owner, worker);
1375
1289
  }
1376
1290
  try {
1377
- return await kernel.run(spec, bindings, code);
1291
+ return await worker.run(spec, bindings);
1378
1292
  } finally {
1379
- if (spec.stateOwner === void 0) this.kernels.delete(kernel);
1293
+ if (owner === void 0 && worker.cleanupComplete) this.workers.delete(worker);
1380
1294
  }
1381
1295
  }
1382
1296
  /**
@@ -1385,24 +1299,130 @@ var InMemoryExecution = class {
1385
1299
  * @returns Completion after the owned process and output streams stop.
1386
1300
  */
1387
1301
  async release(owner) {
1388
- const kernel = this.owners.get(owner);
1389
- if (!kernel) return;
1390
- await kernel.dispose();
1391
- if (this.owners.get(owner) === kernel) this.owners.delete(owner);
1392
- this.kernels.delete(kernel);
1302
+ const worker = this.owners.get(owner);
1303
+ if (!worker) return;
1304
+ await worker.dispose();
1305
+ if (this.owners.get(owner) === worker) this.owners.delete(owner);
1306
+ this.workers.delete(worker);
1393
1307
  }
1394
1308
  };
1395
- //#endregion
1396
- //#region lib/types/index.js
1397
- /** Node PTC execution with configurable per-call processes or retained in-memory REPL state. */
1309
+ /**
1310
+ * Compare requested extra grants without resolving paths in another execution world.
1311
+ * @param left - one policy's additional roots.
1312
+ * @param right - the other policy's additional roots.
1313
+ * @returns whether both contain the same paths, ignoring order and duplicates.
1314
+ */
1315
+ function sameAdditionalRoots(left, right) {
1316
+ const effective = (roots) => [...new Set(roots ?? [])].sort();
1317
+ const a = effective(left);
1318
+ const b = effective(right);
1319
+ return a.length === b.length && a.every((root, index) => root === b[index]);
1320
+ }
1398
1321
  const STRIP_PREFIX = "async function __dsh_program__() {\n";
1399
1322
  const STRIP_SUFFIX = "\n}";
1400
- function messageOf(error) {
1401
- return error instanceof Error ? error.message : String(error);
1402
- }
1403
- function record(value) {
1404
- return typeof value === "object" && value !== null && !Array.isArray(value);
1323
+ function resolveMode(config) {
1324
+ switch (config.executionMode) {
1325
+ case "per-call": return {
1326
+ format: "function-body",
1327
+ retainsState: false,
1328
+ 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.",
1329
+ stripTypes(program) {
1330
+ const stripped = stripTypeScriptTypes(STRIP_PREFIX + program + STRIP_SUFFIX);
1331
+ return stripped.slice(35, stripped.length - 2);
1332
+ }
1333
+ };
1334
+ case "persistent-in-memory": return {
1335
+ format: "repl",
1336
+ retainsState: true,
1337
+ 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 this execution's sandbox policy; process.env starts empty. Changing the session sandbox mode clears retained variables. An approved sandbox escalation runs in a separate temporary environment: it cannot access retained variables, and its declarations are discarded afterward. Restart, Agent disposal, cancellation, timeout, output overflow, or process failure clears the environment. If a variable is undefined, recreate it and reacquire its resources. State is not restored from the conversation, and failed evaluations can leave earlier mutations in memory. Redeclaring an existing let, const, or class name fails; assign to a mutable binding or use a new name. Await all tool calls; background callbacks cannot call tools after their evaluation ends. Await child-process completion before ending an evaluation; raw subprocess output belongs to whichever evaluation is active when it arrives.",
1338
+ stripTypes: stripTypeScriptTypes
1339
+ };
1340
+ case "vm-script": {
1341
+ 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.";
1342
+ const asynchronousFailure = "Await asynchronous work: an uncaught callback exception or unhandled rejection terminates the process" + (config.scriptPersistence ? " and clears its variables." : ".");
1343
+ const recovery = config.scriptPersistence ? " Changing the session sandbox mode clears retained variables. An approved sandbox escalation runs in a separate temporary environment: it cannot access retained variables, and its declarations are discarded afterward. Restart, Agent disposal, cancellation, timeout, output overflow, or process failure clears the environment. If a variable is undefined, recreate it and reacquire its resources. State is not restored from the conversation, and failed evaluations can leave earlier mutations in memory. Redeclaring an existing let, const, or class name fails; assign to a mutable binding or use a new name. Await all tool calls; background callbacks cannot call tools after their evaluation ends. Await child-process completion before ending an evaluation; raw subprocess output belongs to whichever evaluation is active when it arrives. 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." : "";
1344
+ return {
1345
+ format: "script",
1346
+ retainsState: config.scriptPersistence,
1347
+ 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. Direct filesystem access follows this execution's sandbox policy; process.env starts empty. " + 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,
1348
+ stripTypes: stripTypeScriptTypes
1349
+ };
1350
+ }
1351
+ /* v8 ignore next -- Loader validates the closed execution-mode union before selection. */
1352
+ default: return assertNever(config.executionMode);
1353
+ }
1405
1354
  }
1355
+ //#endregion
1356
+ //#region lib/types/policy-processes.js
1357
+ /** Owns asynchronous process cleanup without delaying permission setters. */
1358
+ var PolicyProcesses = class {
1359
+ ctx;
1360
+ processes = /* @__PURE__ */ new Set();
1361
+ /**
1362
+ * Begin cleanup on policy changes, even when no subsequent program runs.
1363
+ * @param ctx - Node provider lifecycle and Session services.
1364
+ */
1365
+ constructor(ctx) {
1366
+ this.ctx = ctx;
1367
+ ctx.on("session/event", (session, event) => {
1368
+ if (event.type !== "sandbox/mode") return;
1369
+ for (const process of this.processes) {
1370
+ if (process.sessionId !== session.id || process.mode === event.data.mode) continue;
1371
+ process.invalidated = true;
1372
+ this.release(process).catch((error) => {
1373
+ ctx.logger.warn(error);
1374
+ });
1375
+ }
1376
+ }, { global: true });
1377
+ ctx.effect(() => async () => {
1378
+ await this.settle([...this.processes]);
1379
+ }, "Node PTC policy cleanup");
1380
+ }
1381
+ /**
1382
+ * Track an admitted call or retained process until its owner confirms cleanup.
1383
+ * @param policy - Resolved process policy, including an optional Session identity.
1384
+ * @param release - Idempotent cancellation and awaited cleanup.
1385
+ * @returns Removal after successful process cleanup.
1386
+ */
1387
+ register(policy, release) {
1388
+ if (policy.sessionId === void 0) return () => {};
1389
+ const session = this.ctx.get("sessions")?.get(policy.sessionId);
1390
+ const process = {
1391
+ sessionId: policy.sessionId,
1392
+ mode: session === void 0 ? policy.mode : this.ctx.sandboxPolicy.resolve({ session }).mode,
1393
+ release,
1394
+ invalidated: false
1395
+ };
1396
+ this.processes.add(process);
1397
+ return () => {
1398
+ this.processes.delete(process);
1399
+ };
1400
+ }
1401
+ /**
1402
+ * Wait for invalidated processes before admitting another program.
1403
+ * @param sessionId - Session carried by the resolved policy.
1404
+ * @returns Completion after prior cleanup; a failure rejects and remains retryable.
1405
+ */
1406
+ async wait(sessionId) {
1407
+ await this.settle([...this.processes].filter((process) => process.sessionId === sessionId && process.invalidated));
1408
+ }
1409
+ release(process) {
1410
+ if (process.cleanup !== void 0) return process.cleanup;
1411
+ process.cleanup = process.release().then(() => {
1412
+ this.processes.delete(process);
1413
+ }, (error) => {
1414
+ delete process.cleanup;
1415
+ throw error;
1416
+ });
1417
+ return process.cleanup;
1418
+ }
1419
+ async settle(processes) {
1420
+ const failed = (await Promise.allSettled(processes.map((process) => this.release(process)))).find((result) => result.status === "rejected");
1421
+ if (failed?.status === "rejected") throw failed.reason;
1422
+ }
1423
+ };
1424
+ //#endregion
1425
+ //#region lib/types/index.js
1406
1426
  /** Node execution under file policy, with optional owner-scoped retained memory. */
1407
1427
  var NodePtcRuntime = class extends PtcRuntime {
1408
1428
  static inject = [
@@ -1414,14 +1434,16 @@ var NodePtcRuntime = class extends PtcRuntime {
1414
1434
  static Config = NodeConfig;
1415
1435
  language = "typescript";
1416
1436
  isolation = "process";
1417
- inMemory;
1437
+ execution;
1418
1438
  processes;
1419
1439
  get programFormat() {
1420
- return this.inMemory ? "repl" : "function-body";
1440
+ return this.execution.mode.format;
1441
+ }
1442
+ get retainsState() {
1443
+ return this.execution.mode.retainsState;
1421
1444
  }
1422
1445
  get executionInstructions() {
1423
- if (this.inMemory) return this.inMemory.executionInstructions;
1424
- return "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.";
1446
+ return this.execution.mode.executionInstructions;
1425
1447
  }
1426
1448
  config;
1427
1449
  live = /* @__PURE__ */ new Set();
@@ -1434,19 +1456,20 @@ var NodePtcRuntime = class extends PtcRuntime {
1434
1456
  };
1435
1457
  validateConfig(this.config);
1436
1458
  this.processes = new PolicyProcesses(ctx);
1437
- if (this.config.executionMode === "persistent-in-memory") this.inMemory = new InMemoryExecution(ctx, this.config, this.processes);
1459
+ this.execution = createExecution(ctx, this.config, this.processes);
1438
1460
  ctx.effect(() => async () => {
1439
1461
  this.disposed = true;
1440
1462
  const active = [...this.live];
1441
1463
  for (const run of active) run.controller.abort("runtime disposed");
1442
- await Promise.all(active.map((run) => run.finished));
1464
+ const failed = (await Promise.allSettled([this.execution.dispose(), ...active.map((run) => run.finished)])).find((result) => result.status === "rejected");
1465
+ if (failed?.status === "rejected") throw failed.reason;
1443
1466
  }, "Node ptc-runtime cleanup");
1444
1467
  }
1445
1468
  get sandboxMode() {
1446
1469
  return this.ctx.sandboxPolicy.defaultMode;
1447
1470
  }
1448
1471
  release(owner) {
1449
- return this.inMemory ? this.inMemory.release(owner) : super.release(owner);
1472
+ return this.execution.release(owner);
1450
1473
  }
1451
1474
  get timeout() {
1452
1475
  return {
@@ -1460,17 +1483,11 @@ var NodePtcRuntime = class extends PtcRuntime {
1460
1483
  * @returns Complete execution inputs with a capped numeric budget or an explicit null deadline.
1461
1484
  */
1462
1485
  resolve(request) {
1463
- if (this.inMemory) return this.inMemory.resolve(request);
1464
- if (this.disposed) throw new Error("ptc-runtime-node: resolve after disposal");
1465
- const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
1466
- const cwd = request.cwd ?? sandboxPolicy.workspaceRoot;
1467
- if (!isAbsolute(cwd)) throw new Error("ptc-runtime-node: cwd must be absolute");
1468
- return {
1469
- ...request,
1470
- cwd,
1471
- timeoutMs: request.timeoutMs === null ? null : clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, "ptc-runtime-node: timeoutMs"),
1472
- sandboxPolicy
1473
- };
1486
+ if (this.disposed) {
1487
+ const source = this.retainsState ? "persistent PTC" : "ptc-runtime-node";
1488
+ throw new Error(`${source}: resolve after disposal`);
1489
+ }
1490
+ return this.execution.resolve(request);
1474
1491
  }
1475
1492
  /**
1476
1493
  * Run a resolved program under the configured execution mode.
@@ -1493,329 +1510,18 @@ var NodePtcRuntime = class extends PtcRuntime {
1493
1510
  this.live.add(live);
1494
1511
  try {
1495
1512
  await this.processes.wait(spec.sandboxPolicy?.sessionId);
1496
- if (this.inMemory) {
1497
- const signal = spec.signal === void 0 ? controller.signal : AbortSignal.any([spec.signal, controller.signal]);
1498
- return await this.inMemory.run({
1499
- ...spec,
1500
- signal
1501
- });
1502
- }
1503
- if (spec.sandboxPolicy === void 0) throw new Error("ptc-runtime-node: run requires a resolved sandbox policy");
1504
- 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");
1505
- const bindings = validateBindings(spec);
1506
- return await this.execute(spec, spec.sandboxPolicy, bindings, controller);
1513
+ if (this.disposed) throw new Error(`${this.retainsState ? "persistent PTC" : "ptc-runtime-node"}: run after disposal`);
1514
+ const signal = spec.signal === void 0 ? controller.signal : AbortSignal.any([spec.signal, controller.signal]);
1515
+ return await this.execution.run({
1516
+ ...spec,
1517
+ signal
1518
+ });
1507
1519
  } finally {
1508
1520
  unregister?.();
1509
1521
  this.live.delete(live);
1510
1522
  completion.resolve();
1511
1523
  }
1512
1524
  }
1513
- async execute(spec, policy, bindings, controller) {
1514
- const replyBinding = AsyncLocalStorage.bind(replyToBinding);
1515
- const output = new OutputLedger(this.config.maxOutputBytes);
1516
- const logs = [];
1517
- const sandbox = {
1518
- mode: policy.mode,
1519
- denied: false
1520
- };
1521
- const result = Promise.withResolvers();
1522
- const signal = spec.signal === void 0 ? controller.signal : AbortSignal.any([spec.signal, controller.signal]);
1523
- let handle;
1524
- let channel;
1525
- let confined;
1526
- let settled = false;
1527
- let timedOut = false;
1528
- let outputOverflow = false;
1529
- let overflowResult;
1530
- let stderr = "";
1531
- let parsing = true;
1532
- const wallTimer = spec.timeoutMs === null ? void 0 : setTimeout(() => {
1533
- timedOut = true;
1534
- controller.abort("execution deadline reached");
1535
- }, spec.timeoutMs);
1536
- let stopping;
1537
- const stop = () => {
1538
- if (stopping !== void 0) return stopping;
1539
- stopping = (handle === void 0 ? Promise.resolve(true) : terminateProcess(handle, this.config.graceMs)).then((drained) => {
1540
- unregister();
1541
- return drained;
1542
- }, (error) => {
1543
- stopping = void 0;
1544
- throw error;
1545
- });
1546
- return stopping;
1547
- };
1548
- const finish = (failure, value) => {
1549
- if (settled) return;
1550
- settled = true;
1551
- clearTimeout(wallTimer);
1552
- signal.removeEventListener("abort", onAbort);
1553
- channel?.close();
1554
- (async () => {
1555
- try {
1556
- if (!await stop() && failure === void 0) failure = {
1557
- kind: "worker-exit",
1558
- message: "Node process output did not close cleanly"
1559
- };
1560
- } catch (error) {
1561
- failure = {
1562
- kind: "worker-exit",
1563
- message: `managed process cleanup failed: ${messageOf(error)}`
1564
- };
1565
- }
1566
- const outcome = outputOverflow ? overflowResult ?? output.limit(logs) : failure === void 0 ? output.success(logs, value) : output.failure(logs, failure);
1567
- result.resolve({
1568
- ...outcome,
1569
- sandbox: { ...sandbox }
1570
- });
1571
- })();
1572
- };
1573
- const onAbort = () => {
1574
- finish(timedOut ? {
1575
- kind: "timeout",
1576
- message: `execution deadline reached (${spec.timeoutMs}ms)`
1577
- } : {
1578
- kind: "abort",
1579
- message: messageOf(signal.reason)
1580
- });
1581
- };
1582
- const unregister = this.processes.register(policy, async () => {
1583
- controller.abort(/* @__PURE__ */ new Error("sandbox mode changed"));
1584
- await stop();
1585
- });
1586
- signal.addEventListener("abort", onAbort, { once: true });
1587
- if (signal.aborted) onAbort();
1588
- try {
1589
- if (settled) return await result.promise;
1590
- const stripped = stripTypeScriptTypes(STRIP_PREFIX + spec.program + STRIP_SUFFIX);
1591
- parsing = false;
1592
- const data = {
1593
- code: stripped.slice(35, stripped.length - 2),
1594
- namespaces: [...bindings.values()].map((binding) => ({
1595
- global: binding.global,
1596
- names: Object.keys(binding.functions),
1597
- ...binding.errorClass ? { errorClass: binding.errorClass } : {}
1598
- })),
1599
- maxOutputBytes: this.config.maxOutputBytes
1600
- };
1601
- const executable = await this.ctx.subprocess.resolveExecutable(this.config.launch.executable, void 0, signal);
1602
- if (settled) return await result.promise;
1603
- const packaged = this.config.launch.kind === "embedded";
1604
- const heapFlag = `--max-old-space-size=${this.config.maxOldGenerationSizeMb}`;
1605
- const argv = [
1606
- executable,
1607
- ...packaged ? [] : [heapFlag],
1608
- ...bootstrapArgs(this.ctx.fs, this.config.launch, this.config.maxMessageBytes)
1609
- ];
1610
- confined = policy.mode === "danger-full-access" ? void 0 : await this.ctx.sandbox.confine(argv, {
1611
- ...policy,
1612
- mode: policy.mode
1613
- }, signal);
1614
- if (settled) return await result.promise;
1615
- if (confined !== void 0) sandbox.enforcement = confined.enforcement;
1616
- const env = Object.fromEntries(Object.keys(process.env).filter((key) => !STARTUP_ENVIRONMENT_NAMES.has(key.toUpperCase()) && key.toUpperCase() !== "ELECTRON_RUN_AS_NODE").map((key) => [key, void 0]));
1617
- if (packaged) {
1618
- env.DSH_PTC_RUNTIME_NODE = "1";
1619
- env.NODE_OPTIONS = heapFlag;
1620
- }
1621
- handle = this.ctx.subprocess.spawn({
1622
- argv: confined?.argv ?? argv,
1623
- cwd: spec.cwd,
1624
- env,
1625
- stdio: {
1626
- stdin: "ignore",
1627
- stdout: "pipe",
1628
- stderr: "pipe",
1629
- control: "pipe"
1630
- },
1631
- graceMs: this.config.graceMs,
1632
- signal
1633
- });
1634
- const launched = handle;
1635
- if (launched.control === void 0 || launched.stdout === void 0 || launched.stderr === void 0) throw new Error("subprocess provider did not supply the requested control and output pipes");
1636
- const admit = (text) => {
1637
- if (outputOverflow) return;
1638
- if (!output.admit(text, logs)) {
1639
- outputOverflow = true;
1640
- overflowResult = output.limit([...logs, text]);
1641
- finish({
1642
- kind: "output-limit",
1643
- message: `outer output exceeded ${this.config.maxOutputBytes} bytes`
1644
- });
1645
- }
1646
- };
1647
- const stdoutDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
1648
- const stderrDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
1649
- handle.stdout?.on("data", (chunk) => {
1650
- const text = stdoutDecoder.decode(chunk, { stream: true });
1651
- if (text.length > 0) admit(text);
1652
- });
1653
- handle.stdout?.on("end", () => {
1654
- const text = stdoutDecoder.decode();
1655
- if (text.length > 0) admit(text);
1656
- });
1657
- handle.stdout?.on("error", (error) => {
1658
- finish({
1659
- kind: "worker-exit",
1660
- message: messageOf(error)
1661
- });
1662
- });
1663
- handle.stderr?.on("data", (chunk) => {
1664
- const text = stderrDecoder.decode(chunk, { stream: true });
1665
- stderr = (stderr + text).slice(-this.config.maxOutputBytes);
1666
- if (text.length > 0) admit(text);
1667
- });
1668
- handle.stderr?.on("end", () => {
1669
- const text = stderrDecoder.decode();
1670
- if (text.length > 0) admit(text);
1671
- });
1672
- handle.stderr?.on("error", (error) => {
1673
- finish({
1674
- kind: "worker-exit",
1675
- message: messageOf(error)
1676
- });
1677
- });
1678
- let ready = false;
1679
- let nextId = 1;
1680
- let pending = 0;
1681
- let pendingBytes = 0;
1682
- const protocolFailure = (message) => {
1683
- finish({
1684
- kind: "protocol",
1685
- message
1686
- });
1687
- };
1688
- const processFinished = (outcome) => {
1689
- if (settled) return;
1690
- finish(confined !== void 0 && classifyRunnerFailure(outcome.exitCode, stderr, confined.runnerFailureRules) !== void 0 ? {
1691
- kind: "sandbox-unavailable",
1692
- message: stderr
1693
- } : {
1694
- kind: "worker-exit",
1695
- message: `Node process exited before completing (${String(outcome.exitCode)})${stderr ? `: ${stderr}` : ""}`
1696
- });
1697
- };
1698
- const transport = new JsonChannel(launched.control, this.config.maxMessageBytes, (raw, bytes) => {
1699
- if (!record(raw)) {
1700
- protocolFailure("invalid control frame");
1701
- return;
1702
- }
1703
- if (!ready) {
1704
- if (raw.type !== "ready") {
1705
- protocolFailure("program frame arrived before bootstrap readiness");
1706
- return;
1707
- }
1708
- ready = true;
1709
- transport.send({
1710
- type: "boot",
1711
- data
1712
- }).catch((error) => {
1713
- protocolFailure(messageOf(error));
1714
- });
1715
- return;
1716
- }
1717
- switch (raw.type) {
1718
- case "log":
1719
- if (typeof raw.text !== "string") {
1720
- protocolFailure("invalid log frame");
1721
- return;
1722
- }
1723
- admit(raw.text);
1724
- return;
1725
- case "output-limit":
1726
- outputOverflow = true;
1727
- finish();
1728
- return;
1729
- case "done": {
1730
- if (raw.error !== void 0) {
1731
- if (!record(raw.error) || typeof raw.error.message !== "string" || raw.error.kind !== "exception" && raw.error.kind !== "invalid-output" && raw.error.kind !== "output-limit") {
1732
- protocolFailure("invalid terminal error");
1733
- return;
1734
- }
1735
- const failure = {
1736
- kind: raw.error.kind,
1737
- message: raw.error.message
1738
- };
1739
- if (confined !== void 0) sandbox.denied = confined.denialSignatures.some((signature) => failure.message.toLowerCase().includes(signature.toLowerCase()));
1740
- if (failure.kind === "output-limit") outputOverflow = true;
1741
- finish(failure);
1742
- return;
1743
- }
1744
- const value = raw.value === void 0 ? void 0 : decodePtcJsonWire(raw.value);
1745
- if (raw.value !== void 0 && value === void 0) finish({
1746
- kind: "invalid-output",
1747
- message: "program completion must be lossless JSON"
1748
- });
1749
- else finish(void 0, value);
1750
- return;
1751
- }
1752
- case "call": {
1753
- if (!Number.isSafeInteger(raw.id) || raw.id !== nextId || typeof raw.global !== "string" || typeof raw.name !== "string") {
1754
- protocolFailure("invalid binding call identity");
1755
- return;
1756
- }
1757
- nextId += 1;
1758
- const functions = bindings.get(raw.global)?.functions;
1759
- const fn = functions !== void 0 && Object.hasOwn(functions, raw.name) ? functions[raw.name] : void 0;
1760
- if (typeof fn !== "function") {
1761
- protocolFailure("program requested an undeclared binding");
1762
- return;
1763
- }
1764
- const args = decodePtcJsonWire(raw.args);
1765
- if (args === void 0) {
1766
- protocolFailure("binding arguments must be lossless JSON");
1767
- return;
1768
- }
1769
- if (++pending > this.config.maxPendingCalls || (pendingBytes += bytes) > this.config.maxMessageBytes) {
1770
- protocolFailure("pending binding calls exceed configured limits");
1771
- return;
1772
- }
1773
- const id = raw.id;
1774
- (async () => {
1775
- const reply = await replyBinding(id, fn, args).finally(() => {
1776
- pending -= 1;
1777
- pendingBytes -= bytes;
1778
- });
1779
- if (!settled) await transport.send(reply);
1780
- })().catch((error) => {
1781
- protocolFailure(messageOf(error));
1782
- });
1783
- return;
1784
- }
1785
- default: protocolFailure("unknown control message");
1786
- }
1787
- }, (error, kind) => {
1788
- if (kind === "protocol") protocolFailure(messageOf(error));
1789
- else if (ready) finish({
1790
- kind: "worker-exit",
1791
- message: messageOf(error)
1792
- });
1793
- else launched.done.then(processFinished, (failure) => {
1794
- finish({
1795
- kind: "worker-exit",
1796
- message: messageOf(failure)
1797
- });
1798
- });
1799
- });
1800
- channel = transport;
1801
- launched.done.then((outcome) => {
1802
- setImmediate(() => {
1803
- processFinished(outcome);
1804
- });
1805
- }, (error) => {
1806
- finish({
1807
- kind: confined !== void 0 && isRunnerSpawnFailure(error, confined.argv[0], spec.cwd) ? "sandbox-unavailable" : "worker-exit",
1808
- message: messageOf(error)
1809
- });
1810
- });
1811
- } catch (error) {
1812
- finish({
1813
- kind: error instanceof SandboxUnavailableError ? "sandbox-unavailable" : parsing ? "exception" : "worker-exit",
1814
- message: messageOf(error)
1815
- });
1816
- }
1817
- return await result.promise;
1818
- }
1819
1525
  };
1820
1526
  //#endregion
1821
1527
  export { NodePtcRuntime, NodePtcRuntime as default };