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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.i18n.yaml +24 -24
  2. package/README.md +49 -17
  3. package/README.zh.md +49 -17
  4. package/lib/configuration.js +15 -5
  5. package/lib/index.js +439 -148
  6. package/lib/persistent-process.js +683 -90
  7. package/lib/process.js +683 -90
  8. package/lib/types/bindings.d.ts +10 -5
  9. package/lib/types/bindings.d.ts.map +1 -1
  10. package/lib/types/bindings.js.map +1 -1
  11. package/lib/types/bootstrap.d.ts +42 -24
  12. package/lib/types/bootstrap.d.ts.map +1 -1
  13. package/lib/types/bootstrap.js.map +1 -1
  14. package/lib/types/config.d.ts +14 -2
  15. package/lib/types/config.d.ts.map +1 -1
  16. package/lib/types/config.js.map +1 -1
  17. package/lib/types/configuration.d.ts +5 -4
  18. package/lib/types/configuration.d.ts.map +1 -1
  19. package/lib/types/configuration.js.map +1 -1
  20. package/lib/types/environment.d.ts +13 -0
  21. package/lib/types/environment.d.ts.map +1 -1
  22. package/lib/types/environment.js.map +1 -1
  23. package/lib/types/evaluators/index.d.ts.map +1 -1
  24. package/lib/types/evaluators/index.js.map +1 -1
  25. package/lib/types/evaluators/scoped-repl-evaluator.d.ts +22 -0
  26. package/lib/types/evaluators/scoped-repl-evaluator.d.ts.map +1 -0
  27. package/lib/types/evaluators/scoped-repl-evaluator.js.map +1 -0
  28. package/lib/types/evaluators/scoped-repl.d.ts +130 -0
  29. package/lib/types/evaluators/scoped-repl.d.ts.map +1 -0
  30. package/lib/types/evaluators/scoped-repl.js.map +1 -0
  31. package/lib/types/evaluators/types.d.ts +3 -3
  32. package/lib/types/evaluators/types.d.ts.map +1 -1
  33. package/lib/types/evaluators/types.js.map +1 -1
  34. package/lib/types/execution.d.ts +3 -2
  35. package/lib/types/execution.d.ts.map +1 -1
  36. package/lib/types/execution.js.map +1 -1
  37. package/lib/types/index.d.ts +6 -1
  38. package/lib/types/index.d.ts.map +1 -1
  39. package/lib/types/index.js.map +1 -1
  40. package/lib/types/json-wire.d.ts +16 -4
  41. package/lib/types/json-wire.d.ts.map +1 -1
  42. package/lib/types/json-wire.js.map +1 -1
  43. package/lib/types/output-ledger.d.ts +10 -10
  44. package/lib/types/output-ledger.d.ts.map +1 -1
  45. package/lib/types/output-ledger.js.map +1 -1
  46. package/lib/types/process.d.ts +2 -0
  47. package/lib/types/process.d.ts.map +1 -1
  48. package/lib/types/process.js.map +1 -1
  49. package/lib/types/protocol.d.ts +31 -5
  50. package/lib/types/protocol.d.ts.map +1 -1
  51. package/lib/types/protocol.js.map +1 -1
  52. package/lib/types/worker.d.ts +6 -3
  53. package/lib/types/worker.d.ts.map +1 -1
  54. package/lib/types/worker.js.map +1 -1
  55. package/package.json +23 -21
  56. package/src/bindings.ts +33 -26
  57. package/src/bootstrap.ts +159 -57
  58. package/src/config.ts +21 -3
  59. package/src/configuration.ts +13 -6
  60. package/src/environment.ts +39 -0
  61. package/src/evaluators/index.ts +2 -0
  62. package/src/evaluators/scoped-repl-evaluator.ts +110 -0
  63. package/src/evaluators/scoped-repl.ts +339 -0
  64. package/src/evaluators/types.ts +3 -3
  65. package/src/execution.ts +37 -17
  66. package/src/index.ts +58 -13
  67. package/src/json-wire.ts +44 -8
  68. package/src/output-ledger.ts +42 -45
  69. package/src/process.ts +89 -18
  70. package/src/protocol.ts +37 -10
  71. package/src/worker.ts +75 -40
@@ -2,8 +2,8 @@ import * as module from "node:module";
2
2
  import { registerHooks, syncBuiltinESMExports } from "node:module";
3
3
  import { Socket } from "node:net";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
- import { Buffer as Buffer$1 } from "node:buffer";
6
5
  import { inspect, types } from "node:util";
6
+ import { Buffer as Buffer$1 } from "node:buffer";
7
7
  import { dirname, extname, join, resolve } from "node:path";
8
8
  import * as vm from "node:vm";
9
9
  import { Script, compileFunction, constants, createContext } from "node:vm";
@@ -233,7 +233,7 @@ function createBirpc($functions, options) {
233
233
  //#region lib/types/rpc.js
234
234
  /** birpc over newline-delimited JSON on the bounded private process channel. */
235
235
  const stringify = JSON.stringify;
236
- const parse = JSON.parse;
236
+ const parse$1 = JSON.parse;
237
237
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
238
238
  /**
239
239
  * Connect typed methods over one control endpoint; execution owns all deadlines.
@@ -271,7 +271,7 @@ function createProcessRpc(stream, maxMessageBytes, functions, eventNames, failur
271
271
  else stream.write(line);
272
272
  },
273
273
  deserialize: (line) => {
274
- const message = parse(line);
274
+ const message = parse$1(line);
275
275
  if (message.e) message.e = new Error(String(message.e.message));
276
276
  return message;
277
277
  },
@@ -600,9 +600,10 @@ function enumerableStringKeys(value) {
600
600
  * Its iterative traversal adds no JavaScript call-stack depth limit.
601
601
  *
602
602
  * @param value - the candidate completion value.
603
+ * @param isImage - Optional recognition of host-issued binding images.
603
604
  * @returns a detached lossless-JSON snapshot, or `undefined` when invalid.
604
605
  */
605
- function snapshotPtcJsonValue(value) {
606
+ function snapshotPtcJsonValue(value, isImage) {
606
607
  const active = new IntrinsicSet();
607
608
  let root;
608
609
  const assign = (destination, item) => {
@@ -660,6 +661,10 @@ function snapshotPtcJsonValue(value) {
660
661
  continue;
661
662
  }
662
663
  if (typeof candidate !== "object") return void 0;
664
+ if (isImage?.(candidate)) {
665
+ assign(task.destination, candidate);
666
+ continue;
667
+ }
663
668
  if (setHas(active, candidate)) return void 0;
664
669
  if (intrinsicArrayIsArray(candidate)) {
665
670
  if (!hasPlainArrayPrototype(candidate)) return void 0;
@@ -707,12 +712,18 @@ function snapshotPtcJsonValue(value) {
707
712
  /**
708
713
  * Flatten one validated JSON value for the process control channel.
709
714
  * @param value - the lossless JSON value to transport.
715
+ * @param image - Optional encoder for registered binding images.
710
716
  * @returns a pre-order token stream whose own nesting is bounded.
711
717
  */
712
- function encodePtcJsonWire(value) {
718
+ function encodePtcJsonWire(value, image) {
713
719
  const wire = [];
714
720
  const pending = [value];
715
721
  for (let current = takeLast(pending); current !== void 0; current = takeLast(pending)) {
722
+ const imageToken = current !== null && typeof current === "object" ? image?.(current) : void 0;
723
+ if (imageToken !== void 0) {
724
+ append(wire, imageToken);
725
+ continue;
726
+ }
716
727
  if (current === null || typeof current === "boolean" || typeof current === "number" || typeof current === "string") {
717
728
  append(wire, current);
718
729
  continue;
@@ -756,8 +767,8 @@ function keysContain(keys, expected) {
756
767
  for (let index = 0; index < keys.length; index++) if (keys[index] === expected) return true;
757
768
  return false;
758
769
  }
759
- /** Return one exact container marker, or reject any extra/missing fields. */
760
- function containerToken(value) {
770
+ /** Parse one array, object, or image token, rejecting extra or missing fields. */
771
+ function parseWireToken(value) {
761
772
  if (intrinsicArrayIsArray(value) || !hasPlainObjectPrototype(value)) return void 0;
762
773
  const keys = enumerableStringKeys(value);
763
774
  if (keys === void 0) return void 0;
@@ -788,15 +799,28 @@ function containerToken(value) {
788
799
  keys: normalizedKeys
789
800
  };
790
801
  }
802
+ if (token.kind === "image") {
803
+ if (keys.length !== 6 || !keysContain(keys, "kind") || !keysContain(keys, "id") || !keysContain(keys, "path") || !keysContain(keys, "attachmentId") || !keysContain(keys, "width") || !keysContain(keys, "height")) return void 0;
804
+ if (typeof token.id !== "string" || token.id.length === 0 || typeof token.attachmentId !== "string" || token.attachmentId.length === 0 || typeof token.path !== "string" || token.path.length === 0 || typeof token.width !== "number" || !intrinsicNumberIsSafeInteger(token.width) || token.width <= 0 || typeof token.height !== "number" || !intrinsicNumberIsSafeInteger(token.height) || token.height <= 0) return void 0;
805
+ return {
806
+ kind: "image",
807
+ id: token.id,
808
+ attachmentId: token.attachmentId,
809
+ path: token.path,
810
+ width: token.width,
811
+ height: token.height
812
+ };
813
+ }
791
814
  }
792
815
  /**
793
816
  * Rebuild one lossless JSON value from the flat process wire format.
794
817
  * Malformed or incomplete traffic returns `undefined`; traversal is iterative
795
818
  * and therefore independent of the transported value's application depth.
796
819
  * @param input - untrusted message-port payload.
820
+ * @param image - Optional decoder for registered binding images.
797
821
  * @returns the detached JSON value, or `undefined` when the wire is invalid.
798
822
  */
799
- function decodePtcJsonWire(input) {
823
+ function decodePtcJsonWire(input, image) {
800
824
  try {
801
825
  if (!intrinsicArrayIsArray(input) || !isDenseArray(input) || input.length === 0) return void 0;
802
826
  const wire = input;
@@ -833,7 +857,7 @@ function decodePtcJsonWire(input) {
833
857
  value = token;
834
858
  } else {
835
859
  if (typeof token !== "object") return void 0;
836
- const marker = containerToken(token);
860
+ const marker = parseWireToken(token);
837
861
  if (!marker) return void 0;
838
862
  const remainingTokens = wire.length - tokenIndex - 1;
839
863
  if (marker.kind === "array") {
@@ -846,7 +870,7 @@ function decodePtcJsonWire(input) {
846
870
  length: marker.length,
847
871
  index: 0
848
872
  };
849
- } else {
873
+ } else if (marker.kind === "object") {
850
874
  if (marker.keys.length > remainingTokens) return void 0;
851
875
  const target = {};
852
876
  value = target;
@@ -856,6 +880,9 @@ function decodePtcJsonWire(input) {
856
880
  keys: marker.keys,
857
881
  index: 0
858
882
  };
883
+ } else {
884
+ if (image === void 0) return void 0;
885
+ value = image(marker);
859
886
  }
860
887
  }
861
888
  if (!attach(value)) return void 0;
@@ -880,23 +907,47 @@ function decodePtcJsonWire(input) {
880
907
  * @module @deepseek-ai/dsh-ptc-runtime-node/src/bootstrap
881
908
  */
882
909
  const CapturedError = Error;
883
- const isNativeError = types.isNativeError;
884
- const capturedObjectCreate = Object.create;
885
- const capturedObjectDefineProperty = Object.defineProperty;
910
+ const { isNativeError, isProxy } = types;
911
+ const { create: capturedObjectCreate$1, defineProperty: capturedObjectDefineProperty$1, getOwnPropertyDescriptor: capturedObjectGetOwnPropertyDescriptor, getPrototypeOf: capturedObjectGetPrototypeOf, is: capturedObjectIs } = Object;
912
+ const capturedOwnKeys = Reflect.ownKeys;
913
+ /** Compare data properties without invoking accessors or traversing model-created proxies. */
914
+ function matchesInspection(value, snapshot, images) {
915
+ const pending = [[value, snapshot]];
916
+ let size = 1;
917
+ while (size > 0) {
918
+ const pair = pending[--size];
919
+ const current = pair[0];
920
+ const original = pair[1];
921
+ if (capturedObjectIs(current, original)) continue;
922
+ if (current === null || typeof current !== "object" || original === null || typeof original !== "object" || isProxy(current) || images.get(original) !== void 0 || capturedObjectGetPrototypeOf(current) !== capturedObjectGetPrototypeOf(original)) return false;
923
+ const keys = capturedOwnKeys(current);
924
+ if (keys.length !== capturedOwnKeys(original).length) return false;
925
+ for (let index = 0; index < keys.length; index++) {
926
+ const key = keys[index];
927
+ const actual = capturedObjectGetOwnPropertyDescriptor(current, key);
928
+ const expected = capturedObjectGetOwnPropertyDescriptor(original, key);
929
+ if (!expected || !("value" in actual) || actual.enumerable !== expected.enumerable) return false;
930
+ const slot = capturedObjectCreate$1(null);
931
+ slot.value = [actual.value, expected.value];
932
+ slot.configurable = true;
933
+ capturedObjectDefineProperty$1(pending, size++, slot);
934
+ }
935
+ }
936
+ return true;
937
+ }
886
938
  /** Define one public binding-error field without consulting mutable globals or descriptor prototypes. */
887
939
  function defineBindingErrorField(error, key, value) {
888
- const attributes = capturedObjectCreate(null);
940
+ const attributes = capturedObjectCreate$1(null);
889
941
  attributes.enumerable = true;
890
942
  attributes.value = value;
891
- capturedObjectDefineProperty(error, key, attributes);
943
+ capturedObjectDefineProperty$1(error, key, attributes);
892
944
  }
893
945
  /**
894
946
  * Ordered text capture under the shared outer JSON-byte budget, delivered to
895
947
  * a sink as each item lands (the real sink sends text to the host eagerly,
896
948
  * so captured output survives a mid-run termination). It includes the log
897
949
  * array syntax and string escaping in its accounting. Once exhausted it emits
898
- * the fitting prefix and reports the limit once; the host turns that condition
899
- * into an explicit `output-limit` run failure.
950
+ * the fitting prefix and reports truncation once; execution continues.
900
951
  */
901
952
  var LogBuffer = class {
902
953
  bytes = 2;
@@ -937,35 +988,78 @@ var LogBuffer = class {
937
988
  this.entries += 1;
938
989
  this.sink(text);
939
990
  }
940
- /** Remaining exact JSON-byte budget for the completion value or failure message. */
941
- remainingOutputBytes() {
942
- return this.maxBytes - this.bytes;
991
+ /** Discard further output after the host exhausts the combined text and image budget. */
992
+ discard() {
993
+ this.truncated = true;
994
+ }
995
+ /** Whether captured text has exceeded the shared output budget. */
996
+ get overflowed() {
997
+ return this.truncated;
943
998
  }
944
999
  };
945
- /** The five console methods the shim captures, in the seam's level vocabulary. */
946
- const CONSOLE_LEVELS = [
947
- "log",
948
- "info",
949
- "warn",
950
- "error",
951
- "debug"
952
- ];
953
1000
  /**
954
- * A `console` replacement whose five leveled methods render their arguments
955
- * `util.inspect`-style (matching real console formatting closely enough for
956
- * a model to recognize its own output) into the buffer. Only these five
957
- * exist — the program gets a deliberately small console, not Node's full
958
- * console API.
1001
+ * Render arguments without depth, array-length or string-length previews and emit registered images in order.
959
1002
  * @param logs - the buffer every rendered line is pushed into.
960
- * @returns the five-method console object handed to the program.
1003
+ * @param images - Image identities owned by the execution process.
1004
+ * @param emitImage - Emits a registered image in the current evaluation.
1005
+ * @param inspections - Process-owned text associated with original binding result identities.
1006
+ * @returns The program's inspect function and its matching Image collection hook.
1007
+ * @throws If object formatting fails; preceding arguments remain visible.
961
1008
  */
962
- function makeConsoleShim(logs) {
963
- const render = (args) => args.map((arg) => typeof arg === "string" ? arg : inspect(arg, INSPECT_OPTIONS)).join(" ");
964
- const shim = Object.create(null);
965
- for (const level of CONSOLE_LEVELS) shim[level] = (...args) => {
966
- logs.push(render(args));
1009
+ function makeInspect(logs, images, emitImage, inspections) {
1010
+ const collectors = /* @__PURE__ */ new Map();
1011
+ const programInspect = (...args) => {
1012
+ const pending = [];
1013
+ const flush = () => {
1014
+ if (pending.length === 0) return;
1015
+ logs.push(pending.join(" ") + "\n");
1016
+ pending.length = 0;
1017
+ };
1018
+ for (const arg of args) {
1019
+ if (logs.overflowed) break;
1020
+ const inspection = arg !== null && typeof arg === "object" ? inspections?.get(arg) : void 0;
1021
+ if (inspection !== void 0 && matchesInspection(arg, inspection.snapshot, images)) {
1022
+ flush();
1023
+ if (inspection.text.length > 0) logs.push(inspection.text.endsWith("\n") ? inspection.text : inspection.text + "\n");
1024
+ continue;
1025
+ }
1026
+ const directImage = arg !== null && typeof arg === "object" ? images.get(arg) : void 0;
1027
+ if (directImage !== void 0) {
1028
+ flush();
1029
+ emitImage(directImage);
1030
+ continue;
1031
+ }
1032
+ const nested = [];
1033
+ const collector = Symbol();
1034
+ const options = {
1035
+ depth: null,
1036
+ maxArrayLength: null,
1037
+ maxStringLength: null,
1038
+ ptcImageCollector: collector
1039
+ };
1040
+ collectors.set(collector, nested);
1041
+ try {
1042
+ pending.push(typeof arg === "string" ? arg : inspect(arg, options));
1043
+ } catch (error) {
1044
+ flush();
1045
+ throw error;
1046
+ } finally {
1047
+ collectors.delete(collector);
1048
+ }
1049
+ if (nested.length === 0) continue;
1050
+ flush();
1051
+ for (const id of nested) emitImage(id);
1052
+ }
1053
+ flush();
1054
+ if (args.length === 0) logs.push("\n");
1055
+ };
1056
+ return {
1057
+ inspect: programInspect,
1058
+ collectImage(image, options) {
1059
+ const id = images.get(image);
1060
+ if (id !== void 0 && options.ptcImageCollector !== void 0) collectors.get(options.ptcImageCollector)?.push(id);
1061
+ }
967
1062
  };
968
- return shim;
969
1063
  }
970
1064
  /**
971
1065
  * Redirect a stream's `write` into the log buffer (the program-visible
@@ -993,24 +1087,18 @@ function captureStreamWrites(logs, stream) {
993
1087
  stream.write = original;
994
1088
  };
995
1089
  }
996
- /** Bounded inspect options: deep enough to be useful, bounded so a pathological value cannot explode the rendering. */
997
- const INSPECT_OPTIONS = {
998
- depth: 4,
999
- maxArrayLength: 100,
1000
- maxStringLength: 1e4
1001
- };
1002
1090
  /**
1003
1091
  * Prepare the program's completion value for the run result. Only lossless
1004
- * JSON crosses, and a value that does not fit the remaining combined outer
1005
- * budget reports `output-limit`; the host revalidates hostile traffic and
1092
+ * JSON crosses, and a value that does not fit even without captured output
1093
+ * reports `output-limit`; the host revalidates hostile traffic and
1006
1094
  * remains authoritative for native pipe writes the program shim cannot observe.
1007
1095
  *
1008
1096
  * @param value - the program's completion value.
1009
- * @param remainingOutputBytes - exact bytes left after captured logs.
1097
+ * @param availableBytes - bytes available to the completion or diagnostic.
1010
1098
  * @param maxOutputBytes - the configured cap named in an overflow diagnostic.
1011
1099
  * @returns the result fragment: `{}` for `undefined`, else a flat wire `{ value }`.
1012
1100
  */
1013
- function prepareCompletion(value, remainingOutputBytes, maxOutputBytes = remainingOutputBytes) {
1101
+ function prepareCompletion(value, availableBytes, maxOutputBytes = availableBytes) {
1014
1102
  if (value === void 0) return {};
1015
1103
  let snapshot;
1016
1104
  try {
@@ -1018,34 +1106,32 @@ function prepareCompletion(value, remainingOutputBytes, maxOutputBytes = remaini
1018
1106
  } catch {
1019
1107
  snapshot = void 0;
1020
1108
  }
1021
- if (snapshot === void 0) return prepareFailure("invalid-output", "program completion must be lossless JSON", remainingOutputBytes, maxOutputBytes);
1022
- if (jsonValueBytesUpTo(snapshot, remainingOutputBytes) === void 0) return outputLimit(maxOutputBytes);
1023
- return { value: encodePtcJsonWire(snapshot) };
1024
- }
1025
- /** Build the fixed overflow fragment without carrying rejected variable bytes. */
1026
- function outputLimit(maxOutputBytes) {
1027
- return { error: {
1109
+ if (snapshot === void 0) return prepareFailure("invalid-output", "program completion must be lossless JSON", availableBytes);
1110
+ if (jsonValueBytesUpTo(snapshot, availableBytes) === void 0) return { error: {
1028
1111
  kind: "output-limit",
1029
- message: `outer output exceeded ${maxOutputBytes} bytes`
1112
+ message: `completion value exceeded ${maxOutputBytes} bytes`
1030
1113
  } };
1114
+ return { value: encodePtcJsonWire(snapshot) };
1031
1115
  }
1032
- /** Admit one bounded failure message or replace it with the fixed overflow diagnostic. */
1033
- function prepareFailure(kind, message, remainingOutputBytes, maxOutputBytes) {
1034
- if (jsonStringBytesUpTo(message, remainingOutputBytes) === void 0) return outputLimit(maxOutputBytes);
1035
- return { error: {
1036
- kind,
1037
- message
1038
- } };
1116
+ /** Truncate diagnostic text while preserving its failure kind. */
1117
+ function prepareFailure(kind, message, availableBytes) {
1118
+ const retained = truncateJsonStringBytes(message, availableBytes);
1119
+ return {
1120
+ error: {
1121
+ kind,
1122
+ message: retained
1123
+ },
1124
+ ...retained !== message ? { outputTruncated: true } : {}
1125
+ };
1039
1126
  }
1040
1127
  /**
1041
1128
  * Prepare a thrown program value, including cross-realm errors, without sending
1042
1129
  * an unbounded stack or string across the process channel.
1043
1130
  * @param error - the value thrown by the program.
1044
- * @param remainingOutputBytes - exact bytes left after captured logs.
1045
- * @param maxOutputBytes - the configured cap named in an overflow diagnostic.
1046
- * @returns a bounded exception or fixed output-limit fragment.
1131
+ * @param availableBytes - bytes available to the completion or diagnostic.
1132
+ * @returns a bounded exception preserving its kind and indicating truncated diagnostics.
1047
1133
  */
1048
- function prepareException(error, remainingOutputBytes, maxOutputBytes = remainingOutputBytes) {
1134
+ function prepareException(error, availableBytes) {
1049
1135
  let message;
1050
1136
  try {
1051
1137
  const detail = isNativeError(error) ? error.stack ?? error.message : error;
@@ -1053,7 +1139,7 @@ function prepareException(error, remainingOutputBytes, maxOutputBytes = remainin
1053
1139
  } catch {
1054
1140
  message = "program threw an unrenderable value";
1055
1141
  }
1056
- return prepareFailure("exception", message, remainingOutputBytes, maxOutputBytes);
1142
+ return prepareFailure("exception", message, availableBytes);
1057
1143
  }
1058
1144
  /**
1059
1145
  * Materialize the real error constructor declared by one namespace.
@@ -1078,9 +1164,12 @@ function bindingFailure(errorClass, memberName, message) {
1078
1164
  * @param data - Namespace declarations injected into the program.
1079
1165
  * @param host - Evaluation-scoped remote binding calls.
1080
1166
  * @param errorClasses - Constructors shared with program globals, resolved per invocation.
1081
- * @returns One namespace object per declaration; arguments and results must be lossless JSON.
1167
+ * @param inspections - Required process-owned inspection text indexed by decoded result identity.
1168
+ * @param decodeImage - Optional decoder for host-issued images; image tokens are rejected when absent.
1169
+ * @param isImage - Optional recognition of decoded images; omission restricts inspection snapshots to JSON data.
1170
+ * @returns One namespace object per declaration.
1082
1171
  */
1083
- function makeNamespaces(data, host, errorClasses) {
1172
+ function makeNamespaces(data, host, errorClasses, inspections, decodeImage, isImage) {
1084
1173
  return data.namespaces.map(({ global, names }) => {
1085
1174
  const namespace = Object.create(null);
1086
1175
  for (const name of names) Object.defineProperty(namespace, name, {
@@ -1095,8 +1184,21 @@ function makeNamespaces(data, host, errorClasses) {
1095
1184
  detached = void 0;
1096
1185
  }
1097
1186
  if (detached === void 0) throw new CapturedError("binding arguments must be lossless JSON");
1098
- const result = decodePtcJsonWire(await host.invoke(global, name, encodePtcJsonWire(detached)));
1187
+ const resolution = await host.invoke(global, name, encodePtcJsonWire(detached));
1188
+ if (resolution === null || typeof resolution !== "object" || Array.isArray(resolution) || !("value" in resolution)) throw new CapturedError("binding resolution must be lossless JSON");
1189
+ const inspection = "inspection" in resolution ? resolution.inspection : void 0;
1190
+ if (inspection !== void 0 && typeof inspection !== "string") throw new CapturedError("binding resolution must be lossless JSON");
1191
+ const result = decodePtcJsonWire(resolution.value, decodeImage);
1099
1192
  if (result === void 0) throw new CapturedError("binding resolution must be lossless JSON");
1193
+ if (inspection !== void 0) {
1194
+ if (result === null || typeof result !== "object") throw new CapturedError("binding inspection requires an object or array");
1195
+ const snapshot = snapshotPtcJsonValue(result, isImage);
1196
+ if (snapshot === void 0) throw new CapturedError("binding inspection requires lossless JSON data");
1197
+ inspections.set(result, {
1198
+ snapshot,
1199
+ text: inspection
1200
+ });
1201
+ }
1100
1202
  return result;
1101
1203
  } catch (error) {
1102
1204
  throw bindingFailure(errorClass, name, error instanceof CapturedError ? error.message : String(error));
@@ -1118,6 +1220,22 @@ const STARTUP_ENVIRONMENT_NAMES = new Set([
1118
1220
  "TEMP",
1119
1221
  "TMP"
1120
1222
  ]);
1223
+ /** Warnings that the runtime's own use of experimental Node features emits once per process. */
1224
+ const RUNTIME_WARNINGS = new Set(["vm.USE_MAIN_CONTEXT_DEFAULT_LOADER is an experimental feature and might change at any time", "stripTypeScriptTypes is an experimental feature and might change at any time"]);
1225
+ function withoutRuntimeWarning(emitWarning) {
1226
+ return function(warning, ...rest) {
1227
+ const message = typeof warning === "string" ? warning : warning instanceof Error ? warning.message : void 0;
1228
+ if (message !== void 0 && RUNTIME_WARNINGS.has(message)) return;
1229
+ Reflect.apply(emitWarning, this, [warning, ...rest]);
1230
+ };
1231
+ }
1232
+ /**
1233
+ * Drop warnings that the runtime itself triggers in the child, which would otherwise appear in program output; other warnings still print.
1234
+ * @param state - Child process whose `emitWarning` is wrapped; structural test doubles without it stay unchanged.
1235
+ */
1236
+ function filterRuntimeWarnings(state) {
1237
+ if (state.emitWarning !== void 0) state.emitWarning = withoutRuntimeWarning(state.emitWarning);
1238
+ }
1121
1239
  /**
1122
1240
  * Clear inherited credentials while preserving native child-process startup paths.
1123
1241
  * With the native child process, preloaded node:process exports observe the replacement.
@@ -6675,6 +6793,403 @@ Parser.acorn = {
6675
6793
  lineBreakG,
6676
6794
  nonASCIIwhitespace
6677
6795
  };
6796
+ function parse(input, options) {
6797
+ return Parser.parse(input, options);
6798
+ }
6799
+ //#endregion
6800
+ //#region lib/types/evaluators/scoped-repl.js
6801
+ /** Scope chain for scoped REPL programs: acorn scanning, copied bindings between programs, and Script compilation. */
6802
+ /** Prefix of every generated name; programs that contain it anywhere are rejected. */
6803
+ const RESERVED_PREFIX = "__$binding_";
6804
+ /** Generated parameter receiving the values copied from earlier programs. */
6805
+ const BINDING_VALUES = `${RESERVED_PREFIX}vals`;
6806
+ /** Generated parameter receiving one read function per binding, in binding order. */
6807
+ const BINDING_GETTERS = `${RESERVED_PREFIX}getters`;
6808
+ /**
6809
+ * Parse a program once and list its own top-level bindings, leading strict directive, and final expression.
6810
+ * Every program uses script rules with top-level await: strictness comes from the generated Script or the program's directive,
6811
+ * and V8 reports strict-mode violations when compiling. Script rules reject top-level `using` and static `import`.
6812
+ * Top-level declarations are read, and so are var declarations inside blocks and other statements, which hoist to the program's scope;
6813
+ * declarations inside nested functions and classes are not read.
6814
+ * @param code - Type-stripped JavaScript submitted for one evaluation.
6815
+ * @param options - Filename shown by syntax errors.
6816
+ * @returns Declarations in source order, whether a "use strict" directive leads, and the final expression offsets.
6817
+ * @throws {SyntaxError} Laid out like V8's for parse errors, top-level return, a hashbang, and any occurrence of {@link RESERVED_PREFIX}.
6818
+ */
6819
+ function scanProgram(code, options) {
6820
+ if (code.startsWith("#!")) throw programSyntaxError(code, options.filename, 0, "Hashbang lines are not supported");
6821
+ const reserved = code.indexOf(RESERVED_PREFIX);
6822
+ if (reserved >= 0) throw programSyntaxError(code, options.filename, reserved, `Names starting with '${RESERVED_PREFIX}' are reserved`);
6823
+ let program;
6824
+ try {
6825
+ program = parse(code, {
6826
+ ecmaVersion: "latest",
6827
+ sourceType: "script",
6828
+ allowAwaitOutsideFunction: true
6829
+ });
6830
+ } catch (error) {
6831
+ throw parseFailure(code, options.filename, error);
6832
+ }
6833
+ const declarations = /* @__PURE__ */ new Map();
6834
+ const declare = (identifier, kind) => {
6835
+ if (kind === "var" && declarations.get(identifier.name) === "function") return;
6836
+ declarations.set(identifier.name, kind);
6837
+ };
6838
+ const collectVar = (statement) => {
6839
+ switch (statement.type) {
6840
+ case "VariableDeclaration":
6841
+ if (statement.kind === "var") for (const declarator of statement.declarations) bindingNames(declarator.id, (identifier) => {
6842
+ declare(identifier, "var");
6843
+ });
6844
+ break;
6845
+ case "BlockStatement":
6846
+ statement.body.forEach(collectVar);
6847
+ break;
6848
+ case "IfStatement":
6849
+ collectVar(statement.consequent);
6850
+ if (statement.alternate) collectVar(statement.alternate);
6851
+ break;
6852
+ case "ForStatement":
6853
+ if (statement.init?.type === "VariableDeclaration") collectVar(statement.init);
6854
+ collectVar(statement.body);
6855
+ break;
6856
+ case "ForInStatement":
6857
+ case "ForOfStatement":
6858
+ if (statement.left.type === "VariableDeclaration") collectVar(statement.left);
6859
+ collectVar(statement.body);
6860
+ break;
6861
+ case "WhileStatement":
6862
+ case "DoWhileStatement":
6863
+ case "LabeledStatement":
6864
+ case "WithStatement":
6865
+ collectVar(statement.body);
6866
+ break;
6867
+ case "TryStatement":
6868
+ collectVar(statement.block);
6869
+ if (statement.handler) collectVar(statement.handler.body);
6870
+ if (statement.finalizer) collectVar(statement.finalizer);
6871
+ break;
6872
+ case "SwitchStatement":
6873
+ for (const branch of statement.cases) branch.consequent.forEach(collectVar);
6874
+ break;
6875
+ default: break;
6876
+ }
6877
+ };
6878
+ for (const statement of program.body) switch (statement.type) {
6879
+ case "VariableDeclaration": {
6880
+ const kind = statement.kind === "var" || statement.kind === "let" ? statement.kind : "const";
6881
+ for (const declarator of statement.declarations) bindingNames(declarator.id, (identifier) => {
6882
+ declare(identifier, kind);
6883
+ });
6884
+ break;
6885
+ }
6886
+ case "FunctionDeclaration":
6887
+ declare(statement.id, "function");
6888
+ break;
6889
+ case "ClassDeclaration":
6890
+ declare(statement.id, "class");
6891
+ break;
6892
+ default: collectVar(statement);
6893
+ }
6894
+ let useStrict = false;
6895
+ for (const statement of program.body) {
6896
+ if (statement.type !== "ExpressionStatement" || statement.directive === void 0) break;
6897
+ if (statement.directive === "use strict") useStrict = true;
6898
+ }
6899
+ const last = program.body.findLast((statement) => statement.type !== "EmptyStatement");
6900
+ if (last?.type !== "ExpressionStatement") return {
6901
+ declarations,
6902
+ useStrict
6903
+ };
6904
+ const finalExpression = {
6905
+ statementStart: last.start,
6906
+ expressionStart: last.expression.start,
6907
+ expressionEnd: last.expression.end
6908
+ };
6909
+ return {
6910
+ declarations,
6911
+ useStrict,
6912
+ finalExpression
6913
+ };
6914
+ }
6915
+ /**
6916
+ * Build the Script source that copies earlier bindings, exposes read functions, and runs the program.
6917
+ * The generated prefix occupies line 0, so compiling with `lineOffset: -1` reports program line N as line N.
6918
+ * A copy exists exactly for each carried binding. A name the program declares again starts from its earlier value through a `var` copy,
6919
+ * other `var` bindings are copied as `var`, and all others as `let`.
6920
+ * With `strict` off, a program whose directives include "use strict" gets that directive at the start of its function body.
6921
+ * @param code - Program text that produced `scan`.
6922
+ * @param scan - Result of {@link scanProgram} for `code`.
6923
+ * @param carried - Earlier bindings to copy, in the order of the copied values: names the program does not declare,
6924
+ * and names it declares again only with `var`.
6925
+ * @param options - Whether the whole Script is strict, and whether the final expression becomes the completion value.
6926
+ * @returns Source evaluating to a factory, and every binding in the order of the read functions it pushes.
6927
+ */
6928
+ function buildProgramSource(code, scan, carried, options) {
6929
+ const bindings = [...carried.filter(({ name }) => !scan.declarations.has(name)), ...Array.from(scan.declarations, ([name, kind]) => ({
6930
+ name,
6931
+ kind
6932
+ }))];
6933
+ const copies = carried.map(({ name, kind }, index) => {
6934
+ return ` ${kind === "var" || scan.declarations.has(name) ? "var" : "let"} ${name} = ${BINDING_VALUES}[${index}];`;
6935
+ }).join("");
6936
+ const getters = bindings.length === 0 ? "" : ` ${BINDING_GETTERS}.push(${bindings.map(({ name }) => `() => ${name}`).join(", ")});`;
6937
+ const final = options.finalExpression ? scan.finalExpression : void 0;
6938
+ const body = final === void 0 ? code : `${code.slice(0, final.statementStart)}return ${code.slice(final.statementStart, final.expressionStart)}{ value: (${code.slice(final.expressionStart, final.expressionEnd)}) }${code.slice(final.expressionEnd)}`;
6939
+ const directive = !options.strict && scan.useStrict ? "\"use strict\";" : "";
6940
+ return {
6941
+ source: `${`${options.strict ? "\"use strict\";" : ""}(function (${BINDING_VALUES}, ${BINDING_GETTERS}) { return async function () {${directive}${copies}${getters}`}\n${body}\n} })`,
6942
+ bindings
6943
+ };
6944
+ }
6945
+ /**
6946
+ * Compile programs that each run in their own scope and start with copies of the top-level bindings earlier programs left.
6947
+ * A program reads earlier bindings when it is compiled: values earlier code assigns afterwards stay with that code.
6948
+ * A var redeclaration starts from the earlier value. An earlier name whose let, const, or class redeclaration never finished initializing
6949
+ * keeps the value it had before; an uninitialized new name is dropped.
6950
+ */
6951
+ var ScopedReplScopes = class {
6952
+ options;
6953
+ bindings = /* @__PURE__ */ new Map();
6954
+ replaced = /* @__PURE__ */ new Map();
6955
+ compiled;
6956
+ /**
6957
+ * Start an empty scope chain.
6958
+ * @param options - Strictness and the redeclaration observer shared by every program.
6959
+ */
6960
+ constructor(options) {
6961
+ this.options = options;
6962
+ }
6963
+ /**
6964
+ * Scan and compile one program against the bindings current at this moment.
6965
+ * Bindings of the previously compiled program apply once its body has started; a syntax error leaves the chain unchanged.
6966
+ * @param code - Type-stripped JavaScript of the program.
6967
+ * @param options - Filename, shared context, completion choice, and import handling.
6968
+ * @returns The program, which the caller runs once.
6969
+ * @throws {SyntaxError} From scanning or V8 compilation, with its location and caret and without compiler frames.
6970
+ */
6971
+ compile(code, options) {
6972
+ this.adoptCompiled();
6973
+ const strict = this.options.strict;
6974
+ const scan = scanProgram(code, { filename: options.filename });
6975
+ const carried = [];
6976
+ const values = [];
6977
+ const replaced = /* @__PURE__ */ new Map();
6978
+ const redeclarations = [];
6979
+ for (const [name, binding] of this.bindings) {
6980
+ const current = this.currentValue(name, binding);
6981
+ if (current === void 0) continue;
6982
+ const kind = scan.declarations.get(name);
6983
+ if (kind === void 0 || kind === "var") {
6984
+ carried.push({
6985
+ name,
6986
+ kind: current.kind
6987
+ });
6988
+ values.push(current.value);
6989
+ }
6990
+ if (kind !== void 0) {
6991
+ replaced.set(name, current);
6992
+ redeclarations.push({
6993
+ name,
6994
+ previous: current.kind,
6995
+ current: kind
6996
+ });
6997
+ }
6998
+ }
6999
+ const { source, bindings } = buildProgramSource(code, scan, carried, {
7000
+ strict,
7001
+ finalExpression: options.finalExpression
7002
+ });
7003
+ const scriptOptions = {
7004
+ filename: options.filename,
7005
+ lineOffset: -1,
7006
+ ...options.importModuleDynamically === void 0 ? {} : { importModuleDynamically: options.importModuleDynamically }
7007
+ };
7008
+ let factory;
7009
+ try {
7010
+ factory = new Script(source, scriptOptions).runInContext(options.context);
7011
+ } catch (error) {
7012
+ throw withoutCompilerFrames(error);
7013
+ }
7014
+ if (redeclarations.length > 0) this.options.onRedeclaration?.(redeclarations);
7015
+ const getters = [];
7016
+ const program = factory(values, getters);
7017
+ this.compiled = {
7018
+ bindings,
7019
+ getters,
7020
+ replaced
7021
+ };
7022
+ return program;
7023
+ }
7024
+ adoptCompiled() {
7025
+ const program = this.compiled;
7026
+ this.compiled = void 0;
7027
+ if (program === void 0 || program.getters.length < program.bindings.length) return;
7028
+ const { getters } = program;
7029
+ this.bindings = new Map(program.bindings.map(({ name, kind }, index) => [name, {
7030
+ kind,
7031
+ read: getters[index]
7032
+ }]));
7033
+ this.replaced = program.replaced;
7034
+ }
7035
+ currentValue(name, binding) {
7036
+ try {
7037
+ return {
7038
+ kind: binding.kind,
7039
+ value: binding.read()
7040
+ };
7041
+ } catch (_error) {
7042
+ return this.replaced.get(name);
7043
+ }
7044
+ }
7045
+ };
7046
+ /** Drop the compiler frames V8 appends after a compile error's heading; the location and caret precede the heading. */
7047
+ function withoutCompilerFrames(error) {
7048
+ /* v8 ignore next -- V8 reports every compile failure of the generated source as a SyntaxError. */
7049
+ if (!(error instanceof SyntaxError)) return error;
7050
+ const heading = `\n${error.name}: ${error.message}`;
7051
+ error.stack = `${String(error.stack).split(heading, 1).join("")}${heading}`;
7052
+ return error;
7053
+ }
7054
+ /** Collect identifiers bound by a declaration pattern. */
7055
+ function bindingNames(pattern, visit) {
7056
+ switch (pattern.type) {
7057
+ case "Identifier":
7058
+ visit(pattern);
7059
+ break;
7060
+ case "ObjectPattern":
7061
+ for (const property of pattern.properties) bindingNames(property.type === "RestElement" ? property.argument : property.value, visit);
7062
+ break;
7063
+ case "ArrayPattern":
7064
+ for (const element of pattern.elements) if (element !== null) bindingNames(element, visit);
7065
+ break;
7066
+ case "RestElement":
7067
+ bindingNames(pattern.argument, visit);
7068
+ break;
7069
+ case "AssignmentPattern":
7070
+ bindingNames(pattern.left, visit);
7071
+ break;
7072
+ /* v8 ignore next -- Declaration patterns never bind member expressions; acorn rejects them first. */
7073
+ case "MemberExpression": break;
7074
+ }
7075
+ }
7076
+ /** Convert an acorn parse error to a positioned program SyntaxError. */
7077
+ function parseFailure(code, filename, error) {
7078
+ /* v8 ignore next -- acorn raises every parse failure, including exhausted parser stack, as a positioned SyntaxError. */
7079
+ if (!(error instanceof SyntaxError) || !("pos" in error) || typeof error.pos !== "number") return error;
7080
+ const detail = error.message.replace(/ \(\d+:\d+\)$/, "");
7081
+ const message = detail === "'return' outside of function" ? "Illegal return statement" : detail === "Unexpected token" && error.pos >= code.length ? "Unexpected end of input" : detail;
7082
+ return programSyntaxError(code, filename, error.pos, message);
7083
+ }
7084
+ /** Create a SyntaxError whose stack shows the location, source line, and caret like V8's. */
7085
+ function programSyntaxError(code, filename, offset, message) {
7086
+ const { line, column } = getLineInfo(code, offset);
7087
+ const rest = code.slice(offset - column);
7088
+ const end = rest.search(/[\n\r\u2028\u2029]/);
7089
+ const error = new SyntaxError(message);
7090
+ error.stack = `${filename}:${line}\n${end < 0 ? rest : rest.slice(0, end)}\n${" ".repeat(column)}^\n\n${error.name}: ${message}`;
7091
+ return error;
7092
+ }
7093
+ //#endregion
7094
+ //#region lib/types/evaluators/scoped-repl-evaluator.js
7095
+ /** Scoped REPL evaluation for the child loop: context, dynamic imports, completion, and REPL-style asynchronous failures. */
7096
+ /**
7097
+ * Create an evaluator whose programs see copies of earlier top-level bindings and may declare any of them again.
7098
+ * Each program is a separate Script in one retained context; the scope chain lives in {@link ScopedReplScopes}.
7099
+ * Programs load modules only with dynamic `import()`; there is no `require`, `module`, or built-in module global.
7100
+ * Relative specifiers resolve from the working directory at creation, also after later calls change directory.
7101
+ * A final Promise is returned without being awaited. Asynchronous program failures go to `reportError` through a domain,
7102
+ * as in Node's REPL, instead of terminating the process.
7103
+ * @param options - Runner diagnostics, optional import handling, and environment choices.
7104
+ * @returns Context globals, sequential evaluation, and resource cleanup.
7105
+ */
7106
+ function createScopedReplEvaluator(options) {
7107
+ const finalExpression = options.finalExpression ?? true;
7108
+ const baseDirectory = process.cwd();
7109
+ const sandbox = Object.create(null);
7110
+ const context = createContext(sandbox, options.codeGeneration === true ? {} : { codeGeneration: {
7111
+ strings: false,
7112
+ wasm: false
7113
+ } });
7114
+ const realm = new Script("globalThis").runInContext(context);
7115
+ for (const key of Reflect.ownKeys(globalThis)) if (key !== "global" && !Object.hasOwn(realm, key)) Object.defineProperty(sandbox, key, Object.getOwnPropertyDescriptor(globalThis, key));
7116
+ sandbox.global = realm;
7117
+ const imports = options.importHandler === void 0 ? void 0 : new VmModuleImportLoader(options.importHandler, context);
7118
+ const programDomain = process.getBuiltinModule("node:domain").create();
7119
+ programDomain.on("error", (error) => {
7120
+ options.reportError(`Uncaught ${describeThrown(error)}`);
7121
+ });
7122
+ const scopes = new ScopedReplScopes({
7123
+ strict: options.strict ?? true,
7124
+ onRedeclaration: reportRedeclarations
7125
+ });
7126
+ let submissions = 0;
7127
+ let closed = false;
7128
+ return {
7129
+ globals: sandbox,
7130
+ evaluate(code, finish) {
7131
+ if (closed) throw new Error("PTC evaluator is closed");
7132
+ const filename = resolve(baseDirectory, `.ptc-repl-${++submissions}.js`);
7133
+ let program;
7134
+ try {
7135
+ program = scopes.compile(code, {
7136
+ filename,
7137
+ context,
7138
+ finalExpression,
7139
+ importModuleDynamically: imports?.forFile(filename) ?? constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
7140
+ });
7141
+ } catch (error) {
7142
+ finish({
7143
+ ok: false,
7144
+ error
7145
+ });
7146
+ return;
7147
+ }
7148
+ const start = Reflect.apply.bind(void 0, program, void 0, []);
7149
+ programDomain.run(() => Promise.resolve().then(start)).then((completion) => {
7150
+ finish({
7151
+ ok: true,
7152
+ value: completion?.value
7153
+ });
7154
+ }, (error) => {
7155
+ finish({
7156
+ ok: false,
7157
+ error
7158
+ });
7159
+ });
7160
+ },
7161
+ close() {
7162
+ closed = true;
7163
+ imports?.close();
7164
+ }
7165
+ };
7166
+ }
7167
+ /**
7168
+ * Describe a value thrown by asynchronous program work without ever throwing.
7169
+ * A throw escaping the domain error listener would end the process, and programs control the values they throw.
7170
+ * @param error - Value the program threw or rejected with.
7171
+ * @returns The error's string stack or `name: message`, the inspected value without domain markers, or a fixed description.
7172
+ */
7173
+ function describeThrown(error) {
7174
+ try {
7175
+ if (types.isNativeError(error)) {
7176
+ const stack = error.stack;
7177
+ return typeof stack === "string" ? stack : `${error.name}: ${error.message}`;
7178
+ }
7179
+ if (typeof error === "object" && error !== null && Reflect.get(error, "domainThrown") === true) {
7180
+ Reflect.deleteProperty(error, "domain");
7181
+ Reflect.deleteProperty(error, "domainThrown");
7182
+ }
7183
+ return inspect(error);
7184
+ } catch (_failure) {
7185
+ return "program threw an unrenderable value";
7186
+ }
7187
+ }
7188
+ /**
7189
+ * Report names declared again after an earlier program bound them.
7190
+ * @param _redeclarations - Each redeclared name with its earlier and current keyword.
7191
+ */
7192
+ function reportRedeclarations(_redeclarations) {}
6678
7193
  //#endregion
6679
7194
  //#region ../../../node_modules/.pnpm/acorn-walk@8.3.5/node_modules/acorn-walk/dist/walk.mjs
6680
7195
  function recursive(node, state, funcs, baseVisitor, override) {
@@ -7211,7 +7726,8 @@ function compileScript(code, options) {
7211
7726
  const evaluators = {
7212
7727
  "function-body": createAsyncFunctionEvaluator,
7213
7728
  repl: createReplEvaluator,
7214
- script: createVmScriptEvaluator
7729
+ script: createVmScriptEvaluator,
7730
+ "scoped-repl": createScopedReplEvaluator
7215
7731
  };
7216
7732
  /**
7217
7733
  * Create the selected evaluator for either a fresh or retained process.
@@ -7229,6 +7745,10 @@ function createProgramEvaluator(format, reportError, importHandler) {
7229
7745
  //#endregion
7230
7746
  //#region lib/types/process.js
7231
7747
  /** Node child evaluation over typed RPC; the host owns process lifetime. */
7748
+ const capturedObjectCreate = Object.create;
7749
+ const capturedObjectDefineProperty = Object.defineProperty;
7750
+ const capturedObjectFreeze = Object.freeze;
7751
+ const nativeConsole = globalThis.console;
7232
7752
  /**
7233
7753
  * Serve sequential evaluations until the host closes the control channel.
7234
7754
  * @param stream - Inherited, already-adopted control endpoint.
@@ -7241,6 +7761,7 @@ function createProgramEvaluator(format, reportError, importHandler) {
7241
7761
  async function runNodeMain(stream, maxMessageBytes, processState, defaultFormat = "function-body", importHandler) {
7242
7762
  if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes <= 0) throw new Error("invalid control message limit");
7243
7763
  clearProgramEnvironment(processState);
7764
+ filterRuntimeWarnings(processState);
7244
7765
  const context = new AsyncLocalStorage();
7245
7766
  const closed = Promise.withResolvers();
7246
7767
  const errors = /* @__PURE__ */ new Map();
@@ -7264,10 +7785,48 @@ async function runNodeMain(stream, maxMessageBytes, processState, defaultFormat
7264
7785
  if (!acceptsCalls(evaluation)) throw new Error("PTC evaluation canceled");
7265
7786
  return value;
7266
7787
  } };
7267
- const logSink = { push(text) {
7788
+ const images = /* @__PURE__ */ new WeakMap();
7789
+ const inspections = /* @__PURE__ */ new WeakMap();
7790
+ class Image {
7791
+ constructor() {
7792
+ throw new Error("Images are created by image-producing tools");
7793
+ }
7794
+ [inspect.custom](_depth, options) {
7795
+ collectImage(this, options);
7796
+ return this;
7797
+ }
7798
+ }
7799
+ const decodeImage = (wire) => {
7800
+ const image = capturedObjectCreate(Image.prototype);
7801
+ for (const key of [
7802
+ "attachmentId",
7803
+ "path",
7804
+ "width",
7805
+ "height"
7806
+ ]) {
7807
+ const descriptor = capturedObjectCreate(null);
7808
+ descriptor.enumerable = true;
7809
+ descriptor.value = wire[key];
7810
+ capturedObjectDefineProperty(image, key, descriptor);
7811
+ }
7812
+ capturedObjectFreeze(image);
7813
+ images.set(image, wire.id);
7814
+ return image;
7815
+ };
7816
+ const imageSink = (id) => {
7268
7817
  const evaluation = context.getStore();
7269
- if (evaluation && acceptsCalls(evaluation)) evaluation.logs.push(text);
7270
- } };
7818
+ if (evaluation && acceptsCalls(evaluation) && !evaluation.logs.overflowed) connection.image(id);
7819
+ };
7820
+ const logSink = {
7821
+ get overflowed() {
7822
+ return context.getStore()?.logs.overflowed ?? true;
7823
+ },
7824
+ push(text) {
7825
+ const evaluation = context.getStore();
7826
+ if (evaluation && acceptsCalls(evaluation)) evaluation.logs.push(text);
7827
+ }
7828
+ };
7829
+ const { inspect: programInspect, collectImage } = makeInspect(logSink, images, imageSink, inspections);
7271
7830
  captureStreamWrites(logSink, processState.stdout);
7272
7831
  captureStreamWrites(logSink, processState.stderr);
7273
7832
  const connection = createProcessRpc(stream, maxMessageBytes, {
@@ -7295,13 +7854,19 @@ async function runNodeMain(stream, maxMessageBytes, processState, defaultFormat
7295
7854
  }
7296
7855
  };
7297
7856
  current = evaluation;
7298
- context.run(evaluation, () => {
7857
+ const canContinue = () => {
7858
+ if (!evaluation.active) return false;
7859
+ if (!evaluation.revoked) return true;
7860
+ evaluation.finish({});
7861
+ return false;
7862
+ };
7863
+ context.run(evaluation, async () => {
7299
7864
  try {
7300
7865
  processState.chdir(cwd);
7301
7866
  if (evaluator === void 0) {
7302
7867
  evaluator = createProgramEvaluator(format, (error) => {
7303
7868
  const active = context.getStore();
7304
- if (active?.active && error) active.finish(prepareException(error, active.logs.remainingOutputBytes(), active.maxOutputBytes));
7869
+ if (active?.active && error) active.finish(prepareException(error, active.maxOutputBytes - 2));
7305
7870
  }, importHandler === void 0 ? void 0 : (request) => {
7306
7871
  const active = context.getStore();
7307
7872
  if (!active?.active) throw new ImportEvaluationEndedError(active?.reusable ?? true);
@@ -7315,12 +7880,27 @@ async function runNodeMain(stream, maxMessageBytes, processState, defaultFormat
7315
7880
  throw error;
7316
7881
  }) : checkActive(result);
7317
7882
  });
7318
- evaluator.globals.console = makeConsoleShim(logSink);
7319
7883
  Object.defineProperty(evaluator.globals, "process", {
7320
7884
  configurable: true,
7321
7885
  writable: true,
7322
7886
  value: processState
7323
7887
  });
7888
+ Object.defineProperty(evaluator.globals, "inspect", {
7889
+ configurable: true,
7890
+ enumerable: true,
7891
+ value: programInspect
7892
+ });
7893
+ Object.defineProperty(evaluator.globals, "Image", {
7894
+ configurable: true,
7895
+ enumerable: true,
7896
+ value: Image
7897
+ });
7898
+ if (format !== "function-body") Object.defineProperty(evaluator.globals, "console", {
7899
+ configurable: true,
7900
+ enumerable: true,
7901
+ writable: true,
7902
+ value: nativeConsole
7903
+ });
7324
7904
  }
7325
7905
  for (const namespace of data.namespaces) {
7326
7906
  const descriptor = namespace.errorClass;
@@ -7337,7 +7917,7 @@ async function runNodeMain(stream, maxMessageBytes, processState, defaultFormat
7337
7917
  constructor
7338
7918
  });
7339
7919
  }
7340
- const namespaces = makeNamespaces(data, host, errorLookup);
7920
+ const namespaces = makeNamespaces(data, host, errorLookup, inspections, decodeImage, (image) => images.has(image));
7341
7921
  for (const [index, namespace] of data.namespaces.entries()) {
7342
7922
  Object.defineProperty(evaluator.globals, namespace.global, {
7343
7923
  configurable: true,
@@ -7350,20 +7930,32 @@ async function runNodeMain(stream, maxMessageBytes, processState, defaultFormat
7350
7930
  value: errorLookup.get(namespace.global)
7351
7931
  });
7352
7932
  }
7353
- evaluator.evaluate(data.code, (result) => {
7354
- if (!evaluation.active) return;
7355
- if (evaluation.revoked) {
7356
- evaluation.finish({});
7357
- return;
7358
- }
7359
- evaluation.finish(result.ok ? prepareCompletion(result.value, logs.remainingOutputBytes(), data.maxOutputBytes) : prepareException(result.error, logs.remainingOutputBytes(), data.maxOutputBytes));
7933
+ const programEvaluator = evaluator;
7934
+ const initialization = data.initialization;
7935
+ if (initialization !== void 0) {
7936
+ await new Promise((resolve, reject) => {
7937
+ programEvaluator.evaluate(initialization, (result) => {
7938
+ if (result.ok) resolve();
7939
+ else reject(result.error);
7940
+ });
7941
+ });
7942
+ if (!canContinue()) return;
7943
+ await connection.initialized();
7944
+ }
7945
+ if (!canContinue()) return;
7946
+ programEvaluator.evaluate(data.code, (result) => {
7947
+ if (!canContinue()) return;
7948
+ evaluation.finish(result.ok ? data.discardCompletion ? {} : prepareCompletion(result.value, data.maxOutputBytes - 2, data.maxOutputBytes) : prepareException(result.error, data.maxOutputBytes - 2));
7360
7949
  });
7361
7950
  } catch (error) {
7362
- evaluation.finish(prepareException(error, logs.remainingOutputBytes(), data.maxOutputBytes));
7951
+ if (canContinue()) evaluation.finish(prepareException(error, data.maxOutputBytes - 2));
7363
7952
  }
7364
7953
  });
7365
7954
  return await completion.promise;
7366
7955
  },
7956
+ discardOutput() {
7957
+ current?.logs.discard();
7958
+ },
7367
7959
  revoke() {
7368
7960
  const evaluation = current;
7369
7961
  if (!evaluation?.active) return;
@@ -7375,6 +7967,7 @@ async function runNodeMain(stream, maxMessageBytes, processState, defaultFormat
7375
7967
  }, [
7376
7968
  "ready",
7377
7969
  "log",
7970
+ "image",
7378
7971
  "outputLimit"
7379
7972
  ], (_error, kind) => {
7380
7973
  if (current?.active || kind === "protocol") processState.exitCode = 1;
@@ -7382,7 +7975,7 @@ async function runNodeMain(stream, maxMessageBytes, processState, defaultFormat
7382
7975
  closed.resolve();
7383
7976
  });
7384
7977
  try {
7385
- await connection.ready(2);
7978
+ await connection.ready(5);
7386
7979
  await closed.promise;
7387
7980
  } finally {
7388
7981
  evaluator?.close();