@deepseek-ai/dsh-ptc-runtime-node 0.2.2-rc.1 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.i18n.yaml +19 -16
  2. package/README.md +36 -10
  3. package/README.zh.md +36 -10
  4. package/lib/index.js +102 -63
  5. package/lib/persistent-process.js +528 -112
  6. package/lib/process.js +523 -109
  7. package/lib/types/bindings.d.ts.map +1 -0
  8. package/lib/types/bindings.js.map +1 -0
  9. package/lib/types/bootstrap.d.ts.map +1 -0
  10. package/lib/types/bootstrap.js.map +1 -0
  11. package/lib/types/config.d.ts +2 -0
  12. package/lib/types/config.d.ts.map +1 -0
  13. package/lib/types/config.js.map +1 -0
  14. package/lib/types/configuration.d.ts.map +1 -0
  15. package/lib/types/configuration.js.map +1 -0
  16. package/lib/types/environment.d.ts +3 -2
  17. package/lib/types/environment.d.ts.map +1 -0
  18. package/lib/types/environment.js.map +1 -0
  19. package/lib/types/evaluators/async-function.d.ts +3 -3
  20. package/lib/types/evaluators/async-function.d.ts.map +1 -0
  21. package/lib/types/evaluators/async-function.js.map +1 -0
  22. package/lib/types/evaluators/index.d.ts +3 -2
  23. package/lib/types/evaluators/index.d.ts.map +1 -0
  24. package/lib/types/evaluators/index.js.map +1 -0
  25. package/lib/types/evaluators/repl.d.ts +3 -3
  26. package/lib/types/evaluators/repl.d.ts.map +1 -0
  27. package/lib/types/evaluators/repl.js.map +1 -0
  28. package/lib/types/evaluators/types.d.ts +44 -0
  29. package/lib/types/evaluators/types.d.ts.map +1 -0
  30. package/lib/types/evaluators/types.js.map +1 -0
  31. package/lib/types/evaluators/vm-script-await.d.ts.map +1 -0
  32. package/lib/types/evaluators/vm-script-await.js.map +1 -0
  33. package/lib/types/evaluators/vm-script.d.ts +3 -2
  34. package/lib/types/evaluators/vm-script.d.ts.map +1 -0
  35. package/lib/types/evaluators/vm-script.js.map +1 -0
  36. package/lib/types/execution.d.ts.map +1 -0
  37. package/lib/types/execution.js.map +1 -0
  38. package/lib/types/imports/evaluation-ended.d.ts +7 -0
  39. package/lib/types/imports/evaluation-ended.d.ts.map +1 -0
  40. package/lib/types/imports/evaluation-ended.js.map +1 -0
  41. package/lib/types/imports/module-hooks.d.ts +37 -0
  42. package/lib/types/imports/module-hooks.d.ts.map +1 -0
  43. package/lib/types/imports/module-hooks.js.map +1 -0
  44. package/lib/types/imports/vm-modules.d.ts +35 -0
  45. package/lib/types/imports/vm-modules.d.ts.map +1 -0
  46. package/lib/types/imports/vm-modules.js.map +1 -0
  47. package/lib/types/index.d.ts.map +1 -0
  48. package/lib/types/index.js.map +1 -0
  49. package/lib/types/json-wire.d.ts.map +1 -0
  50. package/lib/types/json-wire.js.map +1 -0
  51. package/lib/types/launch.d.ts +1 -2
  52. package/lib/types/launch.d.ts.map +1 -0
  53. package/lib/types/launch.js.map +1 -0
  54. package/lib/types/output-json.d.ts.map +1 -0
  55. package/lib/types/output-json.js.map +1 -0
  56. package/lib/types/output-ledger.d.ts.map +1 -0
  57. package/lib/types/output-ledger.js.map +1 -0
  58. package/lib/types/output-stream.d.ts.map +1 -0
  59. package/lib/types/output-stream.js.map +1 -0
  60. package/lib/types/persistent-process-entry.d.ts.map +1 -0
  61. package/lib/types/persistent-process-entry.js.map +1 -0
  62. package/lib/types/persistent-process.d.ts +6 -2
  63. package/lib/types/persistent-process.d.ts.map +1 -0
  64. package/lib/types/persistent-process.js.map +1 -0
  65. package/lib/types/policy-processes.d.ts.map +1 -0
  66. package/lib/types/policy-processes.js.map +1 -0
  67. package/lib/types/process-entry.d.ts.map +1 -0
  68. package/lib/types/process-entry.js.map +1 -0
  69. package/lib/types/process.d.ts +4 -2
  70. package/lib/types/process.d.ts.map +1 -0
  71. package/lib/types/process.js.map +1 -0
  72. package/lib/types/protocol.d.ts +10 -3
  73. package/lib/types/protocol.d.ts.map +1 -0
  74. package/lib/types/protocol.js.map +1 -0
  75. package/lib/types/rpc.d.ts.map +1 -0
  76. package/lib/types/rpc.js.map +1 -0
  77. package/lib/types/worker.d.ts +5 -3
  78. package/lib/types/worker.d.ts.map +1 -0
  79. package/lib/types/worker.js.map +1 -0
  80. package/package.json +24 -21
  81. package/src/bindings.ts +66 -0
  82. package/src/bootstrap.ts +286 -0
  83. package/src/config.ts +68 -0
  84. package/src/configuration.ts +19 -0
  85. package/src/environment.ts +19 -0
  86. package/src/evaluators/async-function.ts +42 -0
  87. package/src/evaluators/index.ts +25 -0
  88. package/src/evaluators/repl.ts +46 -0
  89. package/src/evaluators/types.ts +64 -0
  90. package/src/evaluators/vm-script-await.ts +290 -0
  91. package/src/evaluators/vm-script.ts +83 -0
  92. package/src/execution.ts +171 -0
  93. package/src/imports/evaluation-ended.ts +11 -0
  94. package/src/imports/module-hooks.ts +125 -0
  95. package/src/imports/vm-modules.ts +233 -0
  96. package/src/index.ts +104 -0
  97. package/src/json-wire.ts +420 -0
  98. package/src/launch.ts +71 -0
  99. package/src/output-json.ts +179 -0
  100. package/src/output-ledger.ts +66 -0
  101. package/src/output-stream.ts +50 -0
  102. package/src/persistent-process-entry.ts +5 -0
  103. package/src/persistent-process.ts +22 -0
  104. package/src/policy-processes.ts +79 -0
  105. package/src/process-entry.ts +5 -0
  106. package/src/process.ts +167 -0
  107. package/src/protocol.ts +89 -0
  108. package/src/rpc.ts +88 -0
  109. package/src/worker.ts +381 -0
package/lib/index.js CHANGED
@@ -30,15 +30,12 @@ function resolveLaunch(config) {
30
30
  * @param fs - Filesystem mapping host bootstrap assets into the process world.
31
31
  * @param config - resolved worker invocation.
32
32
  * @param maxMessageBytes - Validated frame and queued-write limit.
33
- * @param persistent - Whether the selected mode requires retained-process launch support.
34
33
  * @returns Arguments following the resolved Node executable.
35
34
  */
36
- function bootstrapArgs(fs, config, maxMessageBytes, persistent = false) {
35
+ function bootstrapArgs(fs, config, maxMessageBytes) {
37
36
  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);
37
+ case "embedded": return [String(maxMessageBytes)];
38
+ case "node-script": return ["--experimental-vm-modules", ...scriptBootstrapArgs(fs, config.bootstrapPath, maxMessageBytes)];
42
39
  /* v8 ignore next -- Callers supply the resolved, closed LaunchConfig union. */
43
40
  default: return assertNever(config);
44
41
  }
@@ -77,6 +74,7 @@ const NodeConfig = z.object({
77
74
  maxOldGenerationSizeMb: z.number().default(512),
78
75
  maxMessageBytes: z.number().default(134217728),
79
76
  maxPendingCalls: z.number().default(128),
77
+ stopGraceMs: z.number().default(3e3),
80
78
  graceMs: z.number().default(3e3),
81
79
  launch: z.union([z.object({
82
80
  kind: z.const("node-script").required(),
@@ -97,7 +95,8 @@ function validateConfig(config) {
97
95
  for (const key of [
98
96
  "timeoutMs",
99
97
  "maxTimeoutMs",
100
- "graceMs"
98
+ "graceMs",
99
+ "stopGraceMs"
101
100
  ]) if (config[key] > MAX_TIMER_DELAY_MS) throw new Error(`ptc-runtime-node: ${key} exceeds the supported timer range`);
102
101
  if (!Number.isSafeInteger(config.maxOutputBytes) || config.maxOutputBytes < 4) throw new Error("ptc-runtime-node: maxOutputBytes must be an integer of at least 4");
103
102
  if (!Number.isSafeInteger(config.maxMessageBytes)) throw new Error("ptc-runtime-node: maxMessageBytes must be an integer");
@@ -500,7 +499,6 @@ function createProcessRpc(stream, maxMessageBytes, functions, eventNames, failur
500
499
  }
501
500
  //#endregion
502
501
  //#region lib/types/environment.js
503
- /** Startup variables required by native executables before model evaluation. */
504
502
  /** Native executable search, Windows system paths, and sandbox temporary paths retained in the OS environment. */
505
503
  const STARTUP_ENVIRONMENT_NAMES = new Set([
506
504
  "PATH",
@@ -861,7 +859,7 @@ var ProgramWorker = class {
861
859
  ready = false;
862
860
  stderr = "";
863
861
  controlFailure;
864
- stopped;
862
+ termination;
865
863
  starting;
866
864
  exitOutcome;
867
865
  controller = new AbortController();
@@ -924,21 +922,18 @@ var ProgramWorker = class {
924
922
  message(message) {
925
923
  return this.retainsState ? `${message}; retained variables were cleared` : message;
926
924
  }
927
- abortMessage(signal) {
928
- return this.retainsState ? "execution canceled; retained variables were cleared" : messageOf(signal?.reason);
929
- }
930
925
  async evaluate(spec, bindings) {
931
926
  if (this.exitOutcome !== void 0) {
932
927
  const output = this.output();
933
928
  const failure = spec.signal?.aborted ? {
934
929
  kind: "abort",
935
- message: this.abortMessage(spec.signal)
930
+ message: this.message("execution canceled")
936
931
  } : {
937
932
  kind: "worker-exit",
938
933
  message: this.message(this.exitMessage(this.exitOutcome))
939
934
  };
940
935
  try {
941
- await this.stop();
936
+ await this.terminate();
942
937
  } catch (error) {
943
938
  return output.failure([], {
944
939
  kind: "worker-exit",
@@ -953,19 +948,21 @@ var ProgramWorker = class {
953
948
  let overflowed = false;
954
949
  const result = Promise.withResolvers();
955
950
  const timer = spec.timeoutMs === null ? void 0 : setTimeout(() => {
951
+ const message = `execution timed out ${evaluation.completion !== void 0 ? "during execution" : "before code started"} (${spec.timeoutMs}ms)`;
956
952
  evaluation.finish({
957
953
  kind: "timeout",
958
- message: this.message(`execution deadline reached (${spec.timeoutMs}ms)`)
959
- }, void 0, true);
954
+ message
955
+ }, void 0, evaluation.completion === void 0);
960
956
  }, spec.timeoutMs);
961
957
  const onAbort = () => {
962
958
  evaluation.finish({
963
959
  kind: "abort",
964
- message: this.abortMessage(spec.signal)
965
- }, void 0, true);
960
+ message: this.retainsState ? "execution canceled" : messageOf(spec.signal?.reason)
961
+ }, void 0, evaluation.completion === void 0);
966
962
  };
967
963
  const evaluation = {
968
964
  settled: false,
965
+ completion: void 0,
969
966
  data: {
970
967
  code: "",
971
968
  programFormat: this.mode.format,
@@ -1000,12 +997,26 @@ var ProgramWorker = class {
1000
997
  spec.signal?.removeEventListener("abort", onAbort);
1001
998
  const complete = () => overflowed || error?.kind === "output-limit" ? output.limit(logs) : error ? output.failure(logs, error) : output.success(logs, value);
1002
999
  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, {
1000
+ const cleanup = async () => {
1001
+ const interrupted = error?.kind === "timeout" || error?.kind === "abort";
1002
+ let preserved = this.retainsState && !discard && outcome.error?.kind !== "output-limit";
1003
+ if (preserved && interrupted) preserved = await this.interruptEvaluation(evaluation);
1004
+ let drained = true;
1005
+ if (!preserved) drained = await this.terminate();
1006
+ if (interrupted && this.retainsState && error) error = {
1007
+ ...error,
1008
+ message: `${error.message}; retained variables were ${preserved ? "preserved" : "cleared"}`
1009
+ };
1010
+ const completed = complete();
1011
+ if (completed.error?.kind === "output-limit" && preserved) drained = await this.terminate();
1012
+ return drained ? completed : output.failure(logs, {
1006
1013
  kind: "worker-exit",
1007
1014
  message: "managed process exited but its output did not drain cleanly"
1008
- }));
1015
+ });
1016
+ };
1017
+ cleanup().then((completed) => {
1018
+ this.active = void 0;
1019
+ result.resolve(completed);
1009
1020
  }, (failure) => {
1010
1021
  this.active = void 0;
1011
1022
  result.resolve(output.failure(logs, {
@@ -1025,7 +1036,7 @@ var ProgramWorker = class {
1025
1036
  evaluation.finish({
1026
1037
  kind: "exception",
1027
1038
  message: messageOf(error)
1028
- });
1039
+ }, void 0, !this.ready);
1029
1040
  return await result.promise;
1030
1041
  }
1031
1042
  if (this.ready) this.dispatch(evaluation);
@@ -1038,21 +1049,45 @@ var ProgramWorker = class {
1038
1049
  }
1039
1050
  return await result.promise;
1040
1051
  }
1052
+ /** True confirms evaluation settlement with the process still available for reuse. */
1053
+ async interruptEvaluation(evaluation) {
1054
+ const completion = evaluation.completion;
1055
+ if (!this.channel || this.channel.$closed || this.closed || !completion) return false;
1056
+ const deadline = Promise.withResolvers();
1057
+ const timer = setTimeout(() => {
1058
+ deadline.reject(/* @__PURE__ */ new Error(`execution did not settle within ${this.config.stopGraceMs}ms`));
1059
+ }, this.config.stopGraceMs);
1060
+ const abort = () => {
1061
+ deadline.reject(/* @__PURE__ */ new Error("environment disposed during interruption"));
1062
+ };
1063
+ this.controller.signal.addEventListener("abort", abort, { once: true });
1064
+ try {
1065
+ await Promise.race([this.channel.revoke().then(() => completion), deadline.promise]);
1066
+ this.controller.signal.throwIfAborted();
1067
+ return true;
1068
+ } catch (_error) {
1069
+ return false;
1070
+ } finally {
1071
+ clearTimeout(timer);
1072
+ this.controller.signal.removeEventListener("abort", abort);
1073
+ }
1074
+ }
1041
1075
  /** Cancel active work and await managed process termination and output drainage. */
1042
1076
  async dispose() {
1043
1077
  this.active?.finish({
1044
1078
  kind: "abort",
1045
- message: this.message("PTC environment disposed")
1079
+ message: "PTC environment disposed"
1046
1080
  }, void 0, true);
1047
- await this.stop();
1081
+ await this.terminate();
1048
1082
  }
1049
- stop() {
1050
- if (this.stopped) return this.stopped;
1083
+ /** Terminate the process; resolve to whether its output pipes drained cleanly. */
1084
+ terminate() {
1085
+ if (this.termination) return this.termination;
1051
1086
  this.closed = true;
1052
1087
  this.cleanupPending = true;
1053
1088
  this.controller.abort();
1054
1089
  this.channel?.$close();
1055
- this.stopped = (async () => {
1090
+ this.termination = (async () => {
1056
1091
  await this.starting?.catch((_error) => {});
1057
1092
  const handle = this.handle;
1058
1093
  return handle === void 0 || await terminateProcess(handle, this.config.graceMs);
@@ -1062,10 +1097,10 @@ var ProgramWorker = class {
1062
1097
  if (!drained) this.ctx.logger.warn("Node process exited but its output did not drain cleanly");
1063
1098
  return drained;
1064
1099
  }, (error) => {
1065
- this.stopped = void 0;
1100
+ this.termination = void 0;
1066
1101
  throw error;
1067
1102
  });
1068
- return this.stopped;
1103
+ return this.termination;
1069
1104
  }
1070
1105
  fail(kind, message) {
1071
1106
  if (this.active) this.active.finish({
@@ -1074,20 +1109,21 @@ var ProgramWorker = class {
1074
1109
  }, void 0, true);
1075
1110
  else {
1076
1111
  if (!this.closed) this.ctx.logger.warn(message);
1077
- this.stop().catch((error) => {
1112
+ this.terminate().catch((error) => {
1078
1113
  this.ctx.logger.warn(messageOf(error));
1079
1114
  });
1080
1115
  }
1081
1116
  }
1082
1117
  dispatch(evaluation) {
1083
- this.channel?.run(evaluation.spec.cwd, evaluation.data).then((raw) => {
1118
+ const completion = this.channel?.run(evaluation.spec.cwd, evaluation.data).then(readProgramResult);
1119
+ evaluation.completion = completion;
1120
+ completion?.then(({ error, value }) => {
1084
1121
  if (evaluation.settled) return;
1085
- const { error, value } = readProgramResult(raw);
1086
1122
  setImmediate(() => {
1087
1123
  evaluation.finish(error, value);
1088
1124
  });
1089
1125
  }).catch((error) => {
1090
- if (this.active === evaluation && !this.channel?.$closed) this.fail("protocol", messageOf(error));
1126
+ if (this.active === evaluation && !evaluation.settled && !this.channel?.$closed) this.fail("protocol", messageOf(error));
1091
1127
  });
1092
1128
  }
1093
1129
  withControlFailure(message) {
@@ -1104,7 +1140,7 @@ var ProgramWorker = class {
1104
1140
  const argv = [
1105
1141
  executable,
1106
1142
  ...packaged ? [] : [heapFlag],
1107
- ...bootstrapArgs(this.ctx.fs, this.config.launch, this.config.maxMessageBytes, this.retainsState)
1143
+ ...bootstrapArgs(this.ctx.fs, this.config.launch, this.config.maxMessageBytes)
1108
1144
  ];
1109
1145
  const policy = this.policy;
1110
1146
  this.confined = policy.mode === "danger-full-access" ? void 0 : await this.ctx.sandbox.confine(argv, {
@@ -1115,7 +1151,7 @@ var ProgramWorker = class {
1115
1151
  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
1152
  if (packaged) {
1117
1153
  env.DSH_PTC_RUNTIME_NODE = "1";
1118
- env.NODE_OPTIONS = heapFlag;
1154
+ env.NODE_OPTIONS = `${heapFlag} --experimental-vm-modules`;
1119
1155
  }
1120
1156
  const handle = this.ctx.subprocess.spawn({
1121
1157
  argv: this.confined?.argv ?? argv,
@@ -1146,7 +1182,11 @@ var ProgramWorker = class {
1146
1182
  throw new Error(message);
1147
1183
  };
1148
1184
  this.channel = createProcessRpc(handle.control, this.config.maxMessageBytes, {
1149
- ready: () => {
1185
+ ready: (version) => {
1186
+ if (version !== 2) {
1187
+ this.fail("protocol", "bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host");
1188
+ return;
1189
+ }
1150
1190
  if (this.ready || !this.active) {
1151
1191
  this.fail("protocol", "duplicate program readiness");
1152
1192
  return;
@@ -1155,19 +1195,26 @@ var ProgramWorker = class {
1155
1195
  this.dispatch(this.active);
1156
1196
  },
1157
1197
  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);
1198
+ if (!this.ready || !this.active || typeof text !== "string") {
1199
+ this.fail("protocol", "invalid program log");
1200
+ return;
1201
+ }
1202
+ if (!this.active.settled) this.active.admit(text);
1160
1203
  },
1161
1204
  outputLimit: () => {
1162
- if (!this.ready || this.active === void 0) this.fail("protocol", "idle PTC output limit");
1163
- else this.active.finish({
1205
+ if (!this.ready || !this.active) {
1206
+ this.fail("protocol", "idle PTC output limit");
1207
+ return;
1208
+ }
1209
+ this.active.finish({
1164
1210
  kind: "output-limit",
1165
1211
  message: "output limit exceeded"
1166
1212
  }, void 0, true);
1167
1213
  },
1168
1214
  invoke: async (global, name, wire) => {
1169
1215
  const evaluation = this.active;
1170
- if (!this.ready || evaluation === void 0 || evaluation.settled) return refuse("binding call arrived without an active PTC evaluation");
1216
+ if (!this.ready || !evaluation) return refuse("binding call arrived without an active PTC evaluation");
1217
+ if (evaluation.settled) throw new Error("PTC evaluation ended before the binding completed");
1171
1218
  const functions = evaluation.bindings.get(global)?.functions;
1172
1219
  const fn = functions !== void 0 && Object.hasOwn(functions, name) ? functions[name] : void 0;
1173
1220
  if (!this.mode.retainsState && typeof fn !== "function") return refuse("program requested an undeclared binding");
@@ -1177,16 +1224,20 @@ var ProgramWorker = class {
1177
1224
  if (evaluation.pending >= this.config.maxPendingCalls || evaluation.pendingBytes + bytes > this.config.maxMessageBytes) return refuse("pending binding calls exceed configured limits");
1178
1225
  evaluation.pending += 1;
1179
1226
  evaluation.pendingBytes += bytes;
1227
+ let value;
1180
1228
  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;
1229
+ value = await evaluation.invoke(fn, args);
1230
+ } catch (error) {
1231
+ if (evaluation.settled) throw new Error("PTC evaluation ended before the binding completed");
1232
+ throw error;
1184
1233
  } finally {
1185
1234
  evaluation.pending -= 1;
1186
1235
  evaluation.pendingBytes -= bytes;
1187
1236
  }
1237
+ if (evaluation.settled) throw new Error("PTC evaluation ended before the binding completed");
1238
+ return value;
1188
1239
  }
1189
- }, [], (error, kind) => {
1240
+ }, ["revoke"], (error, kind) => {
1190
1241
  if (kind === "protocol") this.fail("protocol", error.message);
1191
1242
  else {
1192
1243
  if (kind === "io") this.controlFailure = error.message;
@@ -1239,7 +1290,6 @@ var NodeExecution = class {
1239
1290
  this.config = config;
1240
1291
  this.processes = processes;
1241
1292
  this.mode = mode;
1242
- if (mode.retainsState && this.config.launch.kind === "embedded") throw new Error("Persistent PTC requires a node-script launch");
1243
1293
  }
1244
1294
  /** Stop every owned process, retaining failed cleanup for a later retry. */
1245
1295
  async dispose() {
@@ -1277,7 +1327,7 @@ var NodeExecution = class {
1277
1327
  const owner = this.mode.retainsState ? spec.stateOwner : void 0;
1278
1328
  let worker = owner === void 0 ? void 0 : this.owners.get(owner);
1279
1329
  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");
1330
+ if (worker && !worker.closed && (worker.policy.mode !== spec.sandboxPolicy.mode || worker.policy.workspaceRoot !== spec.sandboxPolicy.workspaceRoot || worker.policy.sessionId !== spec.sandboxPolicy.sessionId)) throw new Error("persistent PTC: release the retained environment before changing its sandbox policy");
1281
1331
  if (!worker || worker.closed) {
1282
1332
  if (worker) this.workers.delete(worker);
1283
1333
  worker = new ProgramWorker(this.ctx, this.config, {
@@ -1306,18 +1356,6 @@ var NodeExecution = class {
1306
1356
  this.workers.delete(worker);
1307
1357
  }
1308
1358
  };
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
- }
1321
1359
  const STRIP_PREFIX = "async function __dsh_program__() {\n";
1322
1360
  const STRIP_SUFFIX = "\n}";
1323
1361
  function resolveMode(config) {
@@ -1334,17 +1372,18 @@ function resolveMode(config) {
1334
1372
  case "persistent-in-memory": return {
1335
1373
  format: "repl",
1336
1374
  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.",
1375
+ executionInstructions: "The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Emit output with console.log(...) or a final lossless JSON expression. Only printed values and that final expression become program output. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. Await tools and cleanup before returning; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before returning; raw output belongs to the active evaluation.",
1338
1376
  stripTypes: stripTypeScriptTypes
1339
1377
  };
1340
1378
  case "vm-script": {
1341
1379
  const lifetime = config.scriptPersistence ? "Variables, functions, and imported modules remain in memory for this Agent across calls." : "Each call runs in a fresh Node process.";
1380
+ const filePolicy = config.scriptPersistence ? "Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty." : "Direct filesystem access follows this execution's sandbox policy; process.env starts empty.";
1342
1381
  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." : "";
1382
+ const recovery = config.scriptPersistence ? " Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. Await tools and cleanup before returning; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before returning; raw output belongs to the active evaluation. If a native top-level let, const, or class initializer throws, its name may remain permanently uninitialized; use a new name or restart the environment." : "";
1344
1383
  return {
1345
1384
  format: "script",
1346
1385
  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,
1386
+ executionInstructions: "The program contains TypeScript script statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Emit output with console.log(...) or a final lossless JSON expression. The final expression is awaited if it is a Promise. Only printed values and that final expression become program output. " + lifetime + " Use await import(...) for modules. Relative paths use the supplied working directory. " + filePolicy + " " + asynchronousFailure + " Values from bindings and imports can belong to another realm; use Array.isArray for arrays and the supplied binding error classes for failures, because instanceof Array or Error may be false." + recovery,
1348
1387
  stripTypes: stripTypeScriptTypes
1349
1388
  };
1350
1389
  }