@howaboua/pi-durable-js-notebook 0.0.0-stage → 0.9.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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +39 -0
  3. package/README.md +38 -2
  4. package/dist/execution/src/cell-contract.d.ts +49 -0
  5. package/dist/execution/src/cell-observation.d.ts +7 -0
  6. package/dist/execution/src/cell-progress.d.ts +4 -0
  7. package/dist/execution/src/cell-task.d.ts +17 -0
  8. package/dist/execution/src/cell-tools.d.ts +8 -0
  9. package/dist/execution/src/cells.d.ts +14 -0
  10. package/dist/execution/src/command-backend.d.ts +22 -0
  11. package/dist/execution/src/controls.d.ts +3 -0
  12. package/dist/execution/src/custom-command-config.d.ts +21 -0
  13. package/dist/execution/src/custom-commands.d.ts +62 -0
  14. package/dist/execution/src/exec-source.d.ts +21 -0
  15. package/dist/execution/src/forwarded-tools.d.ts +21 -0
  16. package/dist/execution/src/forwarding-hook.d.ts +6 -0
  17. package/dist/execution/src/forwarding.d.ts +15 -0
  18. package/dist/execution/src/index.d.ts +6 -0
  19. package/dist/execution/src/invocation-state.d.ts +26 -0
  20. package/dist/execution/src/invocation.d.ts +35 -0
  21. package/dist/execution/src/native-tools.d.ts +11 -0
  22. package/dist/execution/src/nested-call.d.ts +26 -0
  23. package/dist/execution/src/nested-result.d.ts +8 -0
  24. package/dist/execution/src/nested.d.ts +3 -0
  25. package/dist/execution/src/output.d.ts +48 -0
  26. package/dist/execution/src/presentation.d.ts +59 -0
  27. package/dist/execution/src/progress.d.ts +23 -0
  28. package/dist/execution/src/projection.d.ts +5 -0
  29. package/dist/execution/src/shell/backend.d.ts +28 -0
  30. package/dist/execution/src/shell/format.d.ts +2 -0
  31. package/dist/execution/src/shell/node-backend.d.ts +9 -0
  32. package/dist/execution/src/shell/output.d.ts +19 -0
  33. package/dist/execution/src/shell/process-session.d.ts +50 -0
  34. package/dist/execution/src/shell/results.d.ts +14 -0
  35. package/dist/execution/src/shell/session-manager.d.ts +46 -0
  36. package/dist/execution/src/shell/session-store.d.ts +53 -0
  37. package/dist/execution/src/shell/shell-args.d.ts +4 -0
  38. package/dist/execution/src/shell/shell.d.ts +14 -0
  39. package/dist/execution/src/shell/wait.d.ts +7 -0
  40. package/dist/execution/src/shell.d.ts +14 -0
  41. package/dist/execution/src/tool-contract.d.ts +34 -0
  42. package/dist/execution/src/tool-origin.d.ts +11 -0
  43. package/dist/execution/src/tool-source.d.ts +6 -0
  44. package/dist/execution/src/tool-value.d.ts +3 -0
  45. package/dist/execution/src/wait-session.d.ts +6 -0
  46. package/dist/index.js +6338 -0
  47. package/dist/js-notebook/src/bindings.d.ts +6 -0
  48. package/dist/js-notebook/src/client.d.ts +34 -0
  49. package/dist/js-notebook/src/data-state.d.ts +20 -0
  50. package/dist/js-notebook/src/data-storage.d.ts +17 -0
  51. package/dist/js-notebook/src/engine.d.ts +16 -0
  52. package/dist/js-notebook/src/index.d.ts +53 -0
  53. package/dist/js-notebook/src/kernel.d.ts +25 -0
  54. package/dist/js-notebook/src/managed-bindings.d.ts +20 -0
  55. package/dist/js-notebook/src/managed-source.d.ts +9 -0
  56. package/dist/js-notebook/src/notebook-control.d.ts +7 -0
  57. package/dist/js-notebook/src/portable-state.d.ts +79 -0
  58. package/dist/js-notebook/src/prelude.d.ts +1 -0
  59. package/dist/js-notebook/src/project.d.ts +67 -0
  60. package/dist/js-notebook/src/protocol.d.ts +115 -0
  61. package/dist/js-notebook/src/runtime-cache.d.ts +2 -0
  62. package/dist/js-notebook/src/runtime-contract.d.ts +117 -0
  63. package/dist/js-notebook/src/runtime.d.ts +8 -0
  64. package/dist/js-notebook/src/state-validation.d.ts +2 -0
  65. package/dist/js-notebook/src/storage.d.ts +18 -0
  66. package/dist/js-notebook/src/support.d.ts +12 -0
  67. package/dist/js-notebook/src/tool-calls.d.ts +11 -0
  68. package/dist/js-notebook/src/worker.d.ts +1 -0
  69. package/dist/notebook/src/cell.d.ts +34 -0
  70. package/dist/notebook/src/checkpoint-activity.d.ts +7 -0
  71. package/dist/notebook/src/checkpoint-format.d.ts +32 -0
  72. package/dist/notebook/src/checkpoint-store.d.ts +8 -0
  73. package/dist/notebook/src/command-output.d.ts +1 -0
  74. package/dist/notebook/src/deno-syntax-diagnostics.d.ts +1 -0
  75. package/dist/notebook/src/directory-lock.d.ts +10 -0
  76. package/dist/notebook/src/glob.d.ts +1 -0
  77. package/dist/notebook/src/jupyter-connection.d.ts +17 -0
  78. package/dist/notebook/src/jupyter-execution.d.ts +29 -0
  79. package/dist/notebook/src/jupyter-kernel.d.ts +43 -0
  80. package/dist/notebook/src/jupyter-output.d.ts +32 -0
  81. package/dist/notebook/src/jupyter-shell.d.ts +18 -0
  82. package/dist/notebook/src/jupyter-socket.d.ts +17 -0
  83. package/dist/notebook/src/jupyter-wire.d.ts +16 -0
  84. package/dist/notebook/src/profile-state-format.d.ts +36 -0
  85. package/dist/notebook/src/project-identity.d.ts +1 -0
  86. package/dist/notebook/src/project-state-format.d.ts +80 -0
  87. package/dist/notebook/src/project-state-lock.d.ts +1 -0
  88. package/dist/notebook/src/runtime-contract.d.ts +117 -0
  89. package/dist/notebook/src/runtime-health.d.ts +9 -0
  90. package/dist/notebook/src/storage-retention.d.ts +21 -0
  91. package/dist/notebook/src/tool-observation.d.ts +21 -0
  92. package/dist/worker.js +1545 -0
  93. package/package.json +51 -5
package/dist/worker.js ADDED
@@ -0,0 +1,1545 @@
1
+ // packages/js-notebook/src/worker.ts
2
+ import { parentPort, workerData } from "node:worker_threads";
3
+
4
+ // packages/js-notebook/src/bindings.ts
5
+ import { parse } from "acorn";
6
+
7
+ // packages/notebook/src/glob.ts
8
+ function globMatcher(glob) {
9
+ const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
10
+ const expression = new RegExp(`^${escaped}$`, "i");
11
+ return (value) => expression.test(value);
12
+ }
13
+
14
+ // packages/js-notebook/src/bindings.ts
15
+ function jsDeclarations(source) {
16
+ const program = parse(source, {
17
+ ecmaVersion: "latest",
18
+ sourceType: "script",
19
+ allowAwaitOutsideFunction: true
20
+ });
21
+ const declarations = [];
22
+ const names = (pattern) => {
23
+ switch (pattern.type) {
24
+ case "Identifier":
25
+ return [pattern.name];
26
+ case "RestElement":
27
+ return names(pattern.argument);
28
+ case "AssignmentPattern":
29
+ return names(pattern.left);
30
+ case "ArrayPattern":
31
+ return pattern.elements.flatMap((value) => value ? names(value) : []);
32
+ case "ObjectPattern":
33
+ return pattern.properties.flatMap((value) => names(value.type === "RestElement" ? value.argument : value.value));
34
+ default:
35
+ return [];
36
+ }
37
+ };
38
+ for (const statement of program.body) {
39
+ if (statement.type === "VariableDeclaration") {
40
+ for (const declaration of statement.declarations)
41
+ for (const name of names(declaration.id))
42
+ declarations.push({ name, kind: statement.kind });
43
+ } else if ((statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") && statement.id) {
44
+ declarations.push({
45
+ name: statement.id.name,
46
+ kind: statement.type === "FunctionDeclaration" ? "function" : "class"
47
+ });
48
+ }
49
+ }
50
+ return declarations;
51
+ }
52
+ function inspectJsBindings(vm, inventory, query = "*", managed) {
53
+ const matches = globMatcher(query), baseline = new Set(inventory.baseline);
54
+ const state = managed?.inspect(), retained = new Map(state?.bindings.map((binding) => [binding.name, binding]));
55
+ for (const name of state?.masked ?? [])
56
+ baseline.add(name);
57
+ const declarations = new Map((state?.bindings ?? inventory.declarations).map((binding) => [
58
+ binding.name,
59
+ binding.kind
60
+ ]));
61
+ for (const name of vm.global.getOwnPropertyNames())
62
+ if (!baseline.has(name) && !declarations.has(name))
63
+ declarations.set(name, "global");
64
+ return [...declarations].filter(([name]) => matches(name)).sort(([a], [b]) => a.localeCompare(b)).map(([name, kind]) => {
65
+ const current = retained.get(name);
66
+ if (current)
67
+ return current;
68
+ try {
69
+ if (kind === "global" || kind === "var" || kind === "function") {
70
+ const descriptor = vm.global.getOwnPropertyDescriptor(name);
71
+ try {
72
+ return {
73
+ name,
74
+ kind,
75
+ type: descriptor ? descriptor.value?.typeof ?? "accessor" : "unavailable"
76
+ };
77
+ } finally {
78
+ descriptor?.value?.dispose();
79
+ descriptor?.get?.dispose();
80
+ descriptor?.set?.dispose();
81
+ }
82
+ }
83
+ return {
84
+ name,
85
+ kind,
86
+ type: vm.evalCode(name).consume((value) => value.typeof)
87
+ };
88
+ } catch (error) {
89
+ if (error && typeof error === "object" && "dispose" in error && typeof error.dispose === "function")
90
+ error.dispose();
91
+ return { name, kind, type: "unavailable" };
92
+ }
93
+ });
94
+ }
95
+ function validJsBindingName(name) {
96
+ try {
97
+ const bindings = jsDeclarations(`let ${name};`);
98
+ return bindings.length === 1 && bindings[0]?.name === name;
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ // packages/js-notebook/src/portable-state.ts
105
+ function emptyState() {
106
+ return {
107
+ version: 1,
108
+ roots: {},
109
+ nodes: {},
110
+ bindings: {},
111
+ pins: [],
112
+ imports: []
113
+ };
114
+ }
115
+
116
+ // packages/js-notebook/src/state-validation.ts
117
+ function record(value) {
118
+ return typeof value === "object" && value !== null && !Array.isArray(value);
119
+ }
120
+ function assertPortableState(value) {
121
+ if (!record(value) || value["version"] !== 1 || !record(value["roots"]) || !record(value["nodes"]) || !record(value["bindings"]) || !Array.isArray(value["pins"]) || !value["pins"].every((item) => typeof item === "string") || !Array.isArray(value["imports"]) || !value["imports"].every((item) => typeof item === "string"))
122
+ throw new Error("Invalid TS state; use notebook reset to start clean");
123
+ const roots = value["roots"];
124
+ const nodes = value["nodes"];
125
+ const bindings = value["bindings"];
126
+ const isValue = (item) => item === null || item === undefined || ["string", "number", "boolean", "bigint"].includes(typeof item) || record(item) && typeof item["ref"] === "string" && Object.hasOwn(nodes, item["ref"]);
127
+ for (const [name, binding] of Object.entries(value["bindings"])) {
128
+ if (!/^[$_\p{ID_Start}][$_\u200c\u200d\p{ID_Continue}]*$/u.test(name) || !record(binding) || binding["name"] !== name || ![
129
+ "let",
130
+ "const",
131
+ "function",
132
+ "class",
133
+ "enum",
134
+ "namespace",
135
+ "type",
136
+ "import"
137
+ ].includes(String(binding["kind"])) || typeof binding["declaration"] !== "string" || binding["source"] !== undefined && typeof binding["source"] !== "string")
138
+ throw new Error(`Invalid TS binding ${name}`);
139
+ if (binding["references"] !== undefined && (!Array.isArray(binding["references"]) || !binding["references"].every((item) => typeof item === "string")))
140
+ throw new Error(`Invalid TS references for ${name}`);
141
+ if (binding["checkpoint"] !== undefined && (!record(binding["checkpoint"]) || ![
142
+ binding["checkpoint"]["snapshot"],
143
+ binding["checkpoint"]["restore"]
144
+ ].every((helper) => typeof helper === "string" && Object.hasOwn(bindings, helper))))
145
+ throw new Error(`Invalid TS checkpoint helpers for ${name}`);
146
+ if (binding["hook"] !== undefined && (!["startup", "tool_result"].includes(String(binding["hook"])) || binding["kind"] !== "function" || !value["pins"].includes(name)))
147
+ throw new Error(`Invalid TS hook ${name}; hooks require pinned functions`);
148
+ if (binding["module"] !== undefined && (!record(binding["module"]) || typeof binding["module"]["specifier"] !== "string" || typeof binding["module"]["imported"] !== "string"))
149
+ throw new Error(`Invalid TS module recipe ${name}`);
150
+ }
151
+ if (!Object.values(roots).every(isValue))
152
+ throw new Error("Invalid TS root reference");
153
+ for (const node of Object.values(nodes)) {
154
+ if (!record(node))
155
+ throw new Error("Invalid TS graph node");
156
+ switch (node["kind"]) {
157
+ case "checkpoint":
158
+ if (![node["snapshot"], node["restore"]].every((helper) => typeof helper === "string" && Object.hasOwn(bindings, helper)) || !isValue(node["data"]))
159
+ throw new Error("Invalid TS checkpoint node");
160
+ break;
161
+ case "recipe":
162
+ if (typeof node["name"] !== "string" || !Object.hasOwn(value["bindings"], node["name"]) || !record(node["properties"]) || !Object.values(node["properties"]).every(isValue))
163
+ throw new Error("Invalid TS recipe");
164
+ break;
165
+ case "module":
166
+ if (typeof node["specifier"] !== "string" || typeof node["imported"] !== "string" || node["attributes"] !== undefined && (!record(node["attributes"]) || !Object.values(node["attributes"]).every((item) => typeof item === "string")))
167
+ throw new Error("Invalid TS module recipe");
168
+ break;
169
+ case "binary":
170
+ if (!(node["bytes"] instanceof Uint8Array))
171
+ throw new Error("Invalid TS binary value");
172
+ break;
173
+ case "date":
174
+ if (typeof node["time"] !== "number")
175
+ throw new Error("Invalid TS date");
176
+ break;
177
+ case "regexp":
178
+ if (typeof node["source"] !== "string" || typeof node["flags"] !== "string" || typeof node["lastIndex"] !== "number")
179
+ throw new Error("Invalid TS regexp");
180
+ break;
181
+ case "view":
182
+ if (typeof node["constructor"] !== "string" || !isValue(node["buffer"]) || !Number.isSafeInteger(node["byteOffset"]) || !Number.isSafeInteger(node["length"]))
183
+ throw new Error("Invalid TS typed array");
184
+ break;
185
+ case "object":
186
+ case "array":
187
+ if (!record(node["properties"]) || !Object.values(node["properties"]).every(isValue) || node["kind"] === "array" && (!Number.isSafeInteger(node["length"]) || Number(node["length"]) < 0) || node["kind"] === "object" && typeof node["nullPrototype"] !== "boolean")
188
+ throw new Error("Invalid TS object node");
189
+ break;
190
+ case "map":
191
+ if (!Array.isArray(node["entries"]) || !node["entries"].every((entry) => Array.isArray(entry) && entry.length === 2 && entry.every(isValue)))
192
+ throw new Error("Invalid TS map");
193
+ break;
194
+ case "set":
195
+ if (!Array.isArray(node["entries"]) || !node["entries"].every(isValue))
196
+ throw new Error("Invalid TS set");
197
+ break;
198
+ default:
199
+ throw new Error("Unknown TS graph node");
200
+ }
201
+ }
202
+ }
203
+
204
+ // packages/js-notebook/src/data-state.ts
205
+ function assertJsData(value) {
206
+ try {
207
+ if (!value || typeof value !== "object" || !("bindings" in value) || !value.bindings || typeof value.bindings !== "object")
208
+ throw new Error;
209
+ const bindings = Object.fromEntries(Object.entries(value.bindings).map(([name, binding]) => {
210
+ if (!binding || typeof binding !== "object" || !("kind" in binding) || !["const", "let", "var"].includes(String(binding.kind)) || !validJsBindingName(name))
211
+ throw new Error;
212
+ return [
213
+ name,
214
+ { ...binding, kind: binding.kind === "var" ? "let" : binding.kind }
215
+ ];
216
+ }));
217
+ assertPortableState({ ...value, bindings });
218
+ const state = value;
219
+ if (state.imports.length || Object.values(state.nodes).some((node) => node.kind !== "object" && node.kind !== "array") || Object.values(state.bindings).some((binding) => binding.source || binding.hook || binding.checkpoint || binding.module) || Object.keys(state.roots).some((name) => !Object.hasOwn(bindings, name)) || Object.keys(bindings).some((name) => !Object.hasOwn(state.roots, name)) || state.pins.some((name) => !Object.hasOwn(bindings, name)))
220
+ throw new Error;
221
+ } catch {
222
+ throw new Error("Saved JS data is invalid or unsupported; it was not loaded");
223
+ }
224
+ }
225
+ function captureJsData(vm, support, inventory, names, bindings) {
226
+ const state = emptyState();
227
+ const known = new Map(inspectJsBindings(vm, inventory, "*", bindings).map((binding) => [
228
+ binding.name,
229
+ binding
230
+ ]));
231
+ const object = vm.newObject(), array = vm.newArray();
232
+ const objectPrototype = object.getPrototypeOf(), arrayPrototype = array.getPrototypeOf();
233
+ object.dispose();
234
+ array.dispose();
235
+ const visit = (value, path) => {
236
+ if (value.isNull)
237
+ return null;
238
+ if (value.isUndefined)
239
+ return;
240
+ if (value.isString)
241
+ return value.toString();
242
+ if (value.isNumber)
243
+ return value.toNumber();
244
+ if (value.isBool)
245
+ return value.toBoolean();
246
+ if (value.isBigInt)
247
+ return value.toBigInt();
248
+ const reject = () => {
249
+ throw new Error(`${path}: selective JS state supports primitives, plain objects and arrays; save a whole-notebook profile for this value`);
250
+ };
251
+ if (!value.isObject || value.isFunction || value.isProxy || !(value.isArray || value.className === "Object"))
252
+ return reject();
253
+ const prototype = value.getPrototypeOf();
254
+ let nullPrototype;
255
+ try {
256
+ nullPrototype = prototype.isNull;
257
+ if (value.isArray ? prototype.identity !== arrayPrototype.identity : !nullPrototype && prototype.identity !== objectPrototype.identity)
258
+ return reject();
259
+ } finally {
260
+ prototype.dispose();
261
+ }
262
+ if (!support.isExtensible(value))
263
+ return reject();
264
+ const id = support.identity(value);
265
+ if (Object.hasOwn(state.nodes, id))
266
+ return { ref: id };
267
+ const properties = Object.create(null);
268
+ state.nodes[id] = value.isArray ? { kind: "array", length: value.length, properties } : { kind: "object", nullPrototype, properties };
269
+ const keys = value.getOwnPropertyKeys();
270
+ try {
271
+ for (const key of keys) {
272
+ if (typeof key !== "string")
273
+ return reject();
274
+ const descriptor = value.getOwnPropertyDescriptor(key);
275
+ try {
276
+ if (!descriptor?.value || !descriptor.writable)
277
+ return reject();
278
+ if (value.isArray && key === "length")
279
+ continue;
280
+ if (!descriptor.enumerable || !descriptor.configurable)
281
+ return reject();
282
+ properties[key] = visit(descriptor.value, `${path}.${key}`);
283
+ } finally {
284
+ descriptor?.value?.dispose();
285
+ descriptor?.get?.dispose();
286
+ descriptor?.set?.dispose();
287
+ }
288
+ }
289
+ } finally {
290
+ for (const key of keys)
291
+ if (typeof key !== "string")
292
+ key.dispose();
293
+ }
294
+ return { ref: id };
295
+ };
296
+ try {
297
+ for (const name of [...new Set(names)].sort()) {
298
+ const binding = known.get(name);
299
+ if (!validJsBindingName(name) || !binding || binding.type === "unavailable")
300
+ throw new Error(`JS binding ${name} is unavailable for selective saving`);
301
+ let value;
302
+ if (bindings.has(name))
303
+ value = bindings.read(name);
304
+ else if (["global", "var", "function"].includes(binding.kind)) {
305
+ const descriptor = vm.global.getOwnPropertyDescriptor(name);
306
+ descriptor?.get?.dispose();
307
+ descriptor?.set?.dispose();
308
+ if (!descriptor?.value)
309
+ throw new Error(`${name}: accessors cannot be saved as selected data`);
310
+ value = descriptor.value;
311
+ } else
312
+ value = vm.evalCode(name);
313
+ try {
314
+ Object.defineProperty(state.roots, name, {
315
+ value: visit(value, name),
316
+ enumerable: true,
317
+ writable: true,
318
+ configurable: true
319
+ });
320
+ } finally {
321
+ value.dispose();
322
+ }
323
+ const kind = binding.kind === "var" ? "var" : binding.kind === "let" || binding.kind === "global" ? "let" : "const";
324
+ Object.defineProperty(state.bindings, name, {
325
+ value: { name, kind, declaration: `${kind} ${name}` },
326
+ enumerable: true,
327
+ writable: true,
328
+ configurable: true
329
+ });
330
+ }
331
+ return state;
332
+ } finally {
333
+ objectPrototype.dispose();
334
+ arrayPrototype.dispose();
335
+ }
336
+ }
337
+ function restoreJsData(vm, support, inventory, state, bindings) {
338
+ assertJsData(state);
339
+ const existing = new Set(inspectJsBindings(vm, inventory, "*", bindings).map((binding) => binding.name));
340
+ const names = Object.keys(state.bindings);
341
+ const collisions = names.filter((name) => existing.has(name) || vm.global.hasOwnProperty(name) && !bindings.isMasked(name));
342
+ if (collisions.length)
343
+ throw new Error(`JS data conflicts with existing bindings: ${collisions.join(", ")}; use a fresh notebook or rename the source bindings`);
344
+ const objects = new Map;
345
+ const primitives = [];
346
+ const read = (value) => {
347
+ if (value !== null && typeof value === "object") {
348
+ const object = objects.get(value.ref);
349
+ if (!object)
350
+ throw new Error("Saved JS data contains a missing reference");
351
+ return object;
352
+ }
353
+ const handle = vm.hostToHandle(value);
354
+ primitives.push(handle);
355
+ return handle;
356
+ };
357
+ try {
358
+ for (const [id, node] of Object.entries(state.nodes)) {
359
+ const value = node.kind === "array" ? vm.newArray() : node.kind === "object" && node.nullPrototype ? vm.evalCode("({__proto__:null})") : vm.newObject();
360
+ objects.set(id, value);
361
+ support.identity(value, id);
362
+ }
363
+ for (const [id, node] of Object.entries(state.nodes)) {
364
+ const value = objects.get(id);
365
+ if (node.kind !== "object" && node.kind !== "array")
366
+ throw new Error("Unsupported saved JS data");
367
+ for (const [key, item] of Object.entries(node.properties))
368
+ value.defineProp(key, read(item), {
369
+ writable: true,
370
+ enumerable: true,
371
+ configurable: true
372
+ });
373
+ if (node.kind === "array")
374
+ value.setProp("length", read(node.length));
375
+ }
376
+ for (const name of names)
377
+ bindings.add(name, state.bindings[name].kind, read(state.roots[name]));
378
+ } finally {
379
+ for (const value of objects.values())
380
+ value.dispose();
381
+ for (const value of primitives)
382
+ value.dispose();
383
+ }
384
+ }
385
+ function releaseJsData(vm, inventory, names, protectedNames, bindings) {
386
+ const known = new Map(inspectJsBindings(vm, inventory, "*", bindings).map((binding) => [
387
+ binding.name,
388
+ binding
389
+ ]));
390
+ const result = {
391
+ released: [],
392
+ legacyRetained: [],
393
+ skipped: []
394
+ };
395
+ for (const name of [...new Set(names)]) {
396
+ const binding = known.get(name);
397
+ if (!binding || !validJsBindingName(name)) {
398
+ result.skipped.push({ name, reason: "binding unavailable" });
399
+ continue;
400
+ }
401
+ const protection = protectedNames.get(name);
402
+ if (protection) {
403
+ result.skipped.push({ name, reason: protection });
404
+ continue;
405
+ }
406
+ if (bindings.has(name)) {
407
+ if (bindings.remove(name))
408
+ result.legacyRetained.push(name);
409
+ inventory.declarations = inventory.declarations.filter((binding) => binding.name !== name);
410
+ result.released.push(name);
411
+ } else {
412
+ const descriptor = vm.global.getOwnPropertyDescriptor(name);
413
+ try {
414
+ if (descriptor?.configurable) {
415
+ vm.evalCode(`delete this[${JSON.stringify(name)}]`).dispose();
416
+ result.released.push(name);
417
+ } else
418
+ result.skipped.push({
419
+ name,
420
+ reason: "non-configurable global property"
421
+ });
422
+ } finally {
423
+ descriptor?.value?.dispose();
424
+ descriptor?.get?.dispose();
425
+ descriptor?.set?.dispose();
426
+ }
427
+ }
428
+ }
429
+ return result;
430
+ }
431
+
432
+ // packages/js-notebook/src/managed-source.ts
433
+ import { randomUUID } from "node:crypto";
434
+ import {
435
+ parse as parse2
436
+ } from "acorn";
437
+
438
+ class Scope {
439
+ parent;
440
+ names = new Set;
441
+ lexical = new Set;
442
+ functionScope;
443
+ strict;
444
+ constructor(parent, functionScope, strict = parent?.strict ?? false) {
445
+ this.parent = parent;
446
+ this.functionScope = functionScope ?? this;
447
+ this.strict = strict;
448
+ }
449
+ }
450
+ function managedCell(source, existing) {
451
+ const program = parse2(source, {
452
+ ecmaVersion: "latest",
453
+ sourceType: "script",
454
+ allowAwaitOutsideFunction: true
455
+ });
456
+ const scopes = new WeakMap, declarations = new Map;
457
+ const bindingIds = new WeakSet, variables = new Map, functions = [];
458
+ const blockFunctions = [];
459
+ const reusedBlockFunctions = [];
460
+ const reused = new Set;
461
+ const strictBody = (body) => body.some((statement) => statement.type === "ExpressionStatement" && statement.directive === "use strict");
462
+ const root = new Scope(undefined, undefined, strictBody(program.body));
463
+ const children = (node, visit) => {
464
+ for (const [key, value] of Object.entries(node)) {
465
+ if (key === "loc" || key === "range")
466
+ continue;
467
+ const items = Array.isArray(value) ? value : [value];
468
+ for (const item of items)
469
+ if (item && typeof item === "object" && "type" in item && typeof item.type === "string" && "start" in item)
470
+ visit(item, key);
471
+ }
472
+ };
473
+ const names = (pattern) => {
474
+ switch (pattern.type) {
475
+ case "Identifier":
476
+ return [pattern.name];
477
+ case "RestElement":
478
+ return names(pattern.argument);
479
+ case "AssignmentPattern":
480
+ return names(pattern.left);
481
+ case "ArrayPattern":
482
+ return pattern.elements.flatMap((item) => item ? names(item) : []);
483
+ case "ObjectPattern":
484
+ return pattern.properties.flatMap((item) => names(item.type === "RestElement" ? item.argument : item.value));
485
+ default:
486
+ return [];
487
+ }
488
+ };
489
+ const declare = (name, kind) => {
490
+ const previous = existing.get(name);
491
+ if (previous !== undefined) {
492
+ if (!["var", "function"].includes(kind) || !["var", "function"].includes(previous))
493
+ throw new Error(`JS binding ${name} already exists; release it before redeclaring`);
494
+ reused.add(name);
495
+ } else
496
+ declarations.set(name, { name, kind });
497
+ };
498
+ const pattern = (node, scope, target, topKind) => {
499
+ scopes.set(node, scope);
500
+ switch (node.type) {
501
+ case "Identifier":
502
+ if (topKind)
503
+ declare(node.name, topKind);
504
+ if (target !== root || !reused.has(node.name)) {
505
+ target.names.add(node.name);
506
+ bindingIds.add(node);
507
+ }
508
+ break;
509
+ case "RestElement":
510
+ pattern(node.argument, scope, target, topKind);
511
+ break;
512
+ case "AssignmentPattern":
513
+ pattern(node.left, scope, target, topKind);
514
+ scan(node.right, scope);
515
+ break;
516
+ case "ArrayPattern":
517
+ for (const item of node.elements)
518
+ if (item)
519
+ pattern(item, scope, target, topKind);
520
+ break;
521
+ case "ObjectPattern":
522
+ for (const item of node.properties) {
523
+ scopes.set(item, scope);
524
+ if (item.type === "RestElement")
525
+ pattern(item.argument, scope, target, topKind);
526
+ else {
527
+ if (item.computed)
528
+ scan(item.key, scope);
529
+ pattern(item.value, scope, target, topKind);
530
+ }
531
+ }
532
+ break;
533
+ default:
534
+ scan(node, scope);
535
+ }
536
+ };
537
+ const scan = (node, outer, parent) => {
538
+ let scope = outer;
539
+ scopes.set(node, scope);
540
+ switch (node.type) {
541
+ case "WithStatement":
542
+ throw new Error("JS Notebook does not support with statements; use explicit object properties");
543
+ case "FunctionDeclaration":
544
+ case "FunctionExpression":
545
+ case "ArrowFunctionExpression": {
546
+ if (node.type === "FunctionDeclaration" && node.id) {
547
+ if (parent === program) {
548
+ declare(node.id.name, "function");
549
+ functions.push(node);
550
+ } else if (outer !== outer.functionScope && !node.async && !node.generator)
551
+ blockFunctions.push({ node, scope: outer });
552
+ if (outer !== root || !reused.has(node.id.name)) {
553
+ outer.names.add(node.id.name);
554
+ bindingIds.add(node.id);
555
+ }
556
+ }
557
+ const parameters = new Scope(outer, undefined, outer.strict || node.body.type === "BlockStatement" && strictBody(node.body.body));
558
+ if (node.type === "FunctionExpression" && node.id) {
559
+ parameters.names.add(node.id.name);
560
+ bindingIds.add(node.id);
561
+ }
562
+ if (node.type !== "ArrowFunctionExpression")
563
+ parameters.names.add("arguments");
564
+ for (const parameter of node.params)
565
+ pattern(parameter, parameters, parameters);
566
+ const body = new Scope(parameters);
567
+ scopes.set(node.body, body);
568
+ if (node.body.type === "BlockStatement")
569
+ for (const statement of node.body.body)
570
+ scan(statement, body, node.body);
571
+ else
572
+ scan(node.body, parameters, node);
573
+ return;
574
+ }
575
+ case "ClassDeclaration":
576
+ case "ClassExpression": {
577
+ if (node.type === "ClassDeclaration" && node.id) {
578
+ outer.names.add(node.id.name);
579
+ outer.lexical.add(node.id.name);
580
+ bindingIds.add(node.id);
581
+ if (parent === program)
582
+ declare(node.id.name, "class");
583
+ }
584
+ scope = new Scope(outer, outer.functionScope, true);
585
+ if (node.id) {
586
+ scope.names.add(node.id.name);
587
+ bindingIds.add(node.id);
588
+ }
589
+ if (node.superClass)
590
+ scan(node.superClass, scope, node);
591
+ scan(node.body, scope, node);
592
+ return;
593
+ }
594
+ case "BlockStatement":
595
+ case "CatchClause":
596
+ case "ForStatement":
597
+ case "ForInStatement":
598
+ case "ForOfStatement":
599
+ scope = new Scope(outer, outer.functionScope);
600
+ scopes.set(node, scope);
601
+ if (node.type === "CatchClause" && node.param)
602
+ pattern(node.param, scope, scope);
603
+ break;
604
+ case "StaticBlock":
605
+ scope = new Scope(outer);
606
+ scopes.set(node, scope);
607
+ break;
608
+ case "SwitchStatement": {
609
+ scan(node.discriminant, outer, node);
610
+ scope = new Scope(outer, outer.functionScope);
611
+ for (const branch of node.cases)
612
+ scan(branch, scope, node);
613
+ return;
614
+ }
615
+ case "VariableDeclaration": {
616
+ const target = node.kind === "var" ? scope.functionScope : scope;
617
+ const top = target === root && (node.kind === "var" || parent === program);
618
+ if (top && node.kind === "var")
619
+ variables.set(node, parent?.type === "ForInStatement" || parent?.type === "ForOfStatement");
620
+ for (const declaration of node.declarations) {
621
+ scopes.set(declaration, scope);
622
+ if (node.kind !== "var")
623
+ for (const name of names(declaration.id))
624
+ target.lexical.add(name);
625
+ pattern(declaration.id, scope, target, top ? node.kind : undefined);
626
+ if (declaration.init)
627
+ scan(declaration.init, scope, declaration);
628
+ }
629
+ return;
630
+ }
631
+ }
632
+ children(node, (child, key) => {
633
+ if (!(node.type === "CatchClause" && key === "param"))
634
+ scan(child, scope, node);
635
+ });
636
+ };
637
+ scan(program, root);
638
+ for (const { node, scope } of blockFunctions) {
639
+ if (scope.strict)
640
+ continue;
641
+ const name = node.id.name, target = scope.functionScope;
642
+ let blocked = false;
643
+ for (let current = scope.parent;current; current = current.parent) {
644
+ if (current.lexical.has(name))
645
+ blocked = true;
646
+ if (current === target)
647
+ break;
648
+ }
649
+ if (blocked || target === root && existing.has(name) && !["var", "function"].includes(existing.get(name)))
650
+ continue;
651
+ if (target === root && !declarations.has(name) && !reused.has(name))
652
+ declare(name, "var");
653
+ if (target !== root || !reused.has(name))
654
+ target.names.add(name);
655
+ else
656
+ reusedBlockFunctions.push(node);
657
+ }
658
+ const prefix = `__nb_${randomUUID().replaceAll("-", "")}`, api = `${prefix}_api`;
659
+ const references = new Map, edits = [];
660
+ const referenceNames = [], strictReferences = [];
661
+ const referenceFor = (name, strict = false) => {
662
+ const key = strict ? `strict:${name}` : name;
663
+ let reference = references.get(key);
664
+ if (!reference) {
665
+ reference = `${prefix}_${references.size}`;
666
+ references.set(key, reference);
667
+ referenceNames.push(name);
668
+ if (strict && name !== "arguments" && name !== "eval")
669
+ strictReferences.push({ name, reference });
670
+ }
671
+ return reference;
672
+ };
673
+ const free = (name, scope) => {
674
+ for (let current = scope;current; current = current.parent)
675
+ if (current.names.has(name))
676
+ return false;
677
+ return true;
678
+ };
679
+ const visit = (node, parent, key, grandparent) => {
680
+ if (node.type === "Identifier" && !bindingIds.has(node)) {
681
+ const propertyKey = (parent?.type === "Property" || parent?.type === "MethodDefinition" || parent?.type === "PropertyDefinition") && key === "key" && !parent.computed;
682
+ const syntaxName = propertyKey || parent?.type === "MemberExpression" && key === "property" && !parent.computed || parent?.type === "LabeledStatement" && key === "label" || parent?.type === "BreakStatement" || parent?.type === "ContinueStatement" || parent?.type === "MetaProperty" || key === "id" && (parent?.type === "FunctionDeclaration" || parent?.type === "FunctionExpression" || parent?.type === "ClassDeclaration" || parent?.type === "ClassExpression");
683
+ const scope = scopes.get(node) ?? root;
684
+ if (!syntaxName && free(node.name, scope)) {
685
+ if ((node.name === "eval" || node.name === "Function") && !existing.has(node.name))
686
+ throw new Error("Dynamic code evaluation cannot access managed notebook bindings; write the JavaScript directly in a cell");
687
+ {
688
+ const reference = referenceFor(node.name, scope.strict);
689
+ let text = `${reference}.value`;
690
+ if (parent?.type === "UnaryExpression" && parent.operator === "typeof") {
691
+ edits.push({
692
+ start: parent.start,
693
+ end: parent.end,
694
+ text: `${reference}.type`
695
+ });
696
+ return;
697
+ }
698
+ if (parent?.type === "UnaryExpression" && parent.operator === "delete") {
699
+ edits.push({
700
+ start: parent.start,
701
+ end: parent.end,
702
+ text: `${reference}.delete()`
703
+ });
704
+ return;
705
+ }
706
+ if (parent?.type === "CallExpression" && key === "callee" || parent?.type === "TaggedTemplateExpression" && key === "tag")
707
+ text = `(0,${text})`;
708
+ const property = parent?.type === "Property" ? parent : parent?.type === "AssignmentPattern" ? grandparent : undefined;
709
+ if (property?.type === "Property" && property.shorthand && property.value.start === node.start)
710
+ text = `${JSON.stringify(node.name)}:${text}`;
711
+ edits.push({ start: node.start, end: node.end, text });
712
+ }
713
+ }
714
+ }
715
+ children(node, (child, field) => visit(child, node, field, parent));
716
+ };
717
+ visit(program);
718
+ for (const node of reusedBlockFunctions) {
719
+ const reference = referenceFor(node.id.name);
720
+ edits.push({
721
+ start: node.end,
722
+ end: node.end,
723
+ text: `;${reference}.value=${node.id.name};`
724
+ });
725
+ }
726
+ const render = (start, end) => {
727
+ let text = source.slice(start, end);
728
+ for (const edit of edits.filter((edit) => edit.start >= start && edit.end <= end).sort((a, b) => b.start - a.start))
729
+ text = text.slice(0, edit.start - start) + edit.text + text.slice(edit.end - start);
730
+ return text;
731
+ };
732
+ const replace = (node, text) => {
733
+ for (let i = edits.length - 1;i >= 0; i--)
734
+ if (edits[i].start >= node.start && edits[i].end <= node.end)
735
+ edits.splice(i, 1);
736
+ edits.push({ start: node.start, end: node.end, text });
737
+ };
738
+ for (const [declaration, iterationTarget] of variables) {
739
+ const parts = declaration.declarations.flatMap((item) => item.init ? [
740
+ `(${render(item.id.start, item.id.end)}=${render(item.init.start, item.init.end)})`
741
+ ] : []);
742
+ const tail = source.slice(declaration.start, declaration.end).endsWith(";") ? ";" : "";
743
+ if (iterationTarget) {
744
+ const item = declaration.declarations[0];
745
+ replace(declaration, render(item.id.start, item.id.end));
746
+ } else
747
+ replace(declaration, (parts.join(",") || "void 0") + tail);
748
+ }
749
+ const hoisted = [];
750
+ for (const declaration of functions)
751
+ if (reused.has(declaration.id.name)) {
752
+ const reference = referenceFor(declaration.id.name, root.strict);
753
+ const header = source.slice(declaration.start, declaration.id.start), rest = render(declaration.id.end, declaration.end);
754
+ hoisted.push(`${reference}.value=${header}${rest};`);
755
+ replace(declaration, ";");
756
+ }
757
+ const fresh = [...declarations.values()];
758
+ const vars = fresh.filter((binding) => binding.kind === "var").map((binding) => binding.name);
759
+ const strict = root.strict ? `"use strict";
760
+ ` : "";
761
+ const record = `${prefix}_record`, value = `${prefix}_value`;
762
+ const captureStrict = strictReferences.map(({ name, reference }) => `${reference}=(${record}=>({
763
+ get value(){return ${record}.value},
764
+ set value(${value}){"use strict";if(${record}.kind||${api}.masked(${JSON.stringify(name)}))${record}.value=${value};else ${name}=${value}},
765
+ get type(){return ${record}.type}
766
+ }))(${reference});`).join(`
767
+ `);
768
+ const registration = fresh.map(({ name, kind }) => `${api}.install(${JSON.stringify(name)},${JSON.stringify(kind)},()=>${name},${["const", "using", "await using"].includes(kind) ? "void 0" : `${prefix}_value=>${name}=${prefix}_value`});`).join(`
769
+ `);
770
+ return {
771
+ source: `(async (${[api, ...references.values()].join(",")})=>{
772
+ ${strict}${vars.length ? `var ${vars.join(",")};
773
+ ` : ""}${captureStrict}
774
+ ${registration}
775
+ ${hoisted.join(`
776
+ `)}
777
+ ${render(0, source.length)}
778
+ })`,
779
+ declarations: fresh,
780
+ references: referenceNames
781
+ };
782
+ }
783
+
784
+ // packages/js-notebook/src/managed-bindings.ts
785
+ var JS_BINDINGS_SOURCE = String.raw`(() => {
786
+ const records = new Map(), pending = new Map(), masked = new Set(), global = globalThis, nativeEval = eval;
787
+ const define = Object.defineProperty, descriptor = Object.getOwnPropertyDescriptor;
788
+ const stringify = JSON.stringify;
789
+ const missing = name => { throw new ReferenceError(name + ' is not defined'); };
790
+ const nativeRead = name => masked.has(name) ? missing(name) : descriptor(global,name) ? global[name] : nativeEval(name);
791
+ const nativeType = name => masked.has(name) ? 'undefined' : descriptor(global,name) ? typeof global[name] : nativeEval('typeof '+name);
792
+ const create = name => {
793
+ let assign;
794
+ const record = {kind:undefined,get:()=>nativeRead(name),set:value=>{
795
+ if(masked.has(name))return missing(name);
796
+ if(!assign){const parameter=name==='__notebook_value'?'__notebook_next':'__notebook_value';assign=nativeEval('('+parameter+')=>'+name+'='+parameter)}
797
+ return assign(value);
798
+ }};
799
+ define(record,'value',{get:()=>record.get(),set:value=>{
800
+ if(!record.set)throw new TypeError('Assignment to constant binding '+name);
801
+ return record.set(value);
802
+ }});
803
+ define(record,'type',{get:()=>record.kind ? typeof record.get() : nativeType(name)});
804
+ record.delete=()=>record.kind ? false : masked.has(name) ? true : nativeEval('delete '+name);
805
+ return record;
806
+ };
807
+ return {
808
+ install(name, kind, get, set, legacy = false) {
809
+ if (records.has(name)) throw new SyntaxError('Binding already exists: ' + name);
810
+ const record = pending.get(name) || create(name); pending.delete(name);
811
+ record.kind=kind;record.get=get;record.set=set;record.legacy=legacy;
812
+ records.set(name, record);
813
+ if (!legacy && (kind === 'var' || kind === 'function') && !(masked.has(name) && descriptor(global,name)?.configurable === false)) define(global, name, {get, set: record.set, enumerable:true, configurable:true});
814
+ },
815
+ add(name, kind, value) { this.install(name, kind, () => value, kind === 'const' ? undefined : next => { value = next; }); },
816
+ validate(json) {
817
+ for (const {name,kind} of JSON.parse(json)) {
818
+ if (records.has(name)) throw new SyntaxError('Binding already exists: ' + name);
819
+ if ((kind === 'var' || kind === 'function') && !masked.has(name) && descriptor(global,name)?.configurable === false) throw new SyntaxError('Global name is reserved: ' + name);
820
+ }
821
+ },
822
+ ref(name) { let record=records.get(name)||pending.get(name);if(!record){record=create(name);pending.set(name,record)}return record; },
823
+ has(name) { return records.has(name); },
824
+ masked(name) { return masked.has(name); },
825
+ read(name) { const value = records.get(name); return value ? value.get() : missing(name); },
826
+ remove(name) {
827
+ const record = records.get(name);
828
+ if (!record) return false;
829
+ if (record.legacy) masked.add(name);
830
+ const current = descriptor(global,name);
831
+ if (!record.legacy && current?.get === record.get && current.configurable) delete global[name];
832
+ records.delete(name); return record.legacy;
833
+ },
834
+ metadata() { return stringify({declarations:[...records].map(([name,r])=>({name,kind:r.kind})),masked:[...masked]}); },
835
+ inspect() { return stringify({bindings:[...records].map(([name,r])=>{let type;try{type=typeof r.get()}catch{type='unavailable'}return {name,kind:r.kind,type}}),masked:[...masked]}); },
836
+ legacyGlobal(name) { const item=descriptor(global,name); if (!item || !('value' in item)) throw new ReferenceError(name+' is unavailable'); return item.value; }
837
+ };
838
+ })()`;
839
+
840
+ class JsBindings {
841
+ token;
842
+ vm;
843
+ constructor(vm, inventory, token) {
844
+ this.vm = vm;
845
+ if (token !== undefined) {
846
+ this.token = token;
847
+ return;
848
+ }
849
+ this.token = vm.exportHandle(vm.evalCode(JS_BINDINGS_SOURCE, "js-notebook-bindings.js"));
850
+ for (const { name, kind } of inventory.declarations) {
851
+ const key = vm.newString(name), type = vm.newString(kind), legacy = vm.true;
852
+ let getter, setter;
853
+ try {
854
+ if (kind === "var" || kind === "function") {
855
+ const root = vm.importHandle(this.token), factory = vm.evalCode(`root=>()=>root.legacyGlobal(${JSON.stringify(name)})`);
856
+ try {
857
+ getter = vm.callFunction(factory, vm.undefined, root);
858
+ } finally {
859
+ root.dispose();
860
+ factory.dispose();
861
+ }
862
+ } else
863
+ getter = vm.evalCode(`()=>${name}`);
864
+ const parameter = name === "__notebook_value" ? "__notebook_next" : "__notebook_value";
865
+ setter = ["const", "using", "await using"].includes(kind) ? vm.undefined : vm.evalCode(`${parameter}=>${name}=${parameter}`);
866
+ this.call("install", key, type, getter, setter, legacy).dispose();
867
+ } finally {
868
+ key.dispose();
869
+ type.dispose();
870
+ legacy.dispose();
871
+ getter?.dispose();
872
+ setter?.dispose();
873
+ }
874
+ }
875
+ }
876
+ call(name, ...args) {
877
+ const root = this.vm.importHandle(this.token), fn = root.getProp(name);
878
+ try {
879
+ return this.vm.callFunction(fn, root, ...args);
880
+ } finally {
881
+ fn.dispose();
882
+ root.dispose();
883
+ }
884
+ }
885
+ named(name, action) {
886
+ const key = this.vm.newString(name);
887
+ try {
888
+ return this.call(action, key);
889
+ } finally {
890
+ key.dispose();
891
+ }
892
+ }
893
+ has(name) {
894
+ return this.named(name, "has").consume((value) => value.toBoolean());
895
+ }
896
+ isMasked(name) {
897
+ return this.named(name, "masked").consume((value) => value.toBoolean());
898
+ }
899
+ read(name) {
900
+ return this.named(name, "read");
901
+ }
902
+ remove(name) {
903
+ return this.named(name, "remove").consume((value) => value.toBoolean());
904
+ }
905
+ inspect() {
906
+ return this.call("inspect").consume((value) => JSON.parse(value.toString()));
907
+ }
908
+ add(name, kind, value) {
909
+ const key = this.vm.newString(name), type = this.vm.newString(kind);
910
+ try {
911
+ this.call("add", key, type, value).dispose();
912
+ } finally {
913
+ key.dispose();
914
+ type.dispose();
915
+ }
916
+ }
917
+ execute(source) {
918
+ const metadata = this.call("metadata").consume((value) => JSON.parse(value.toString()));
919
+ const compiled = managedCell(source, new Map(metadata.declarations.map((binding) => [binding.name, binding.kind])));
920
+ const fn = this.vm.evalCode(compiled.source, "js-notebook-cell.js");
921
+ const root = this.vm.importHandle(this.token), references = [], json = this.vm.newString(JSON.stringify(compiled.declarations));
922
+ try {
923
+ this.call("validate", json).dispose();
924
+ for (const name of compiled.references)
925
+ references.push(this.named(name, "ref"));
926
+ return this.vm.callFunction(fn, this.vm.undefined, root, ...references);
927
+ } finally {
928
+ fn.dispose();
929
+ root.dispose();
930
+ json.dispose();
931
+ for (const value of references)
932
+ value.dispose();
933
+ }
934
+ }
935
+ }
936
+
937
+ // packages/notebook/src/command-output.ts
938
+ var commandOutputFormatterSource = `(value, plain) => {
939
+ const metadata = Object.fromEntries(Object.entries(value).filter(([key]) =>
940
+ key !== "output" && key !== "chunk_id" && key !== "wall_time_seconds"
941
+ && (key !== "original_token_count" || value.truncated)));
942
+ const projected = plain ? metadata : { output: value.output, ...metadata };
943
+ let text;
944
+ try { text = JSON.stringify(projected); } catch { text = String(projected); }
945
+ return plain ? text + "\\nOutput:\\n" + value.output : text;
946
+ }`;
947
+
948
+ // packages/js-notebook/src/prelude.ts
949
+ var JS_PRELUDE = String.raw`(bridge => {
950
+ const parse = JSON.parse, stringify = JSON.stringify;
951
+ const then = Function.prototype.call.bind(Promise.prototype.then);
952
+ const formatCommand = ${commandOutputFormatterSource};
953
+ const pending = new Map(), stored = new Map(), outputs = new WeakMap();
954
+ const EXIT = Object.freeze({});
955
+ let next = 0, done = false, failure, tools = Object.freeze({}), metadata = [];
956
+ const describe = e => { try { return e instanceof Error ? String(e.name) + ': ' + String(e.message) : String(e); } catch { return 'The cell threw a value that cannot be described'; } };
957
+ const format = value => {
958
+ if (typeof value === 'string') return value;
959
+ if (value instanceof Error) return describe(value);
960
+ try { return stringify(value, (_, v) => typeof v === 'bigint' ? String(v) + 'n' : v, 2) ?? String(value); }
961
+ catch { return String(value); }
962
+ };
963
+ const text = value => bridge('text', outputs.has(value) && typeof value.output === 'string' ? formatCommand(value, outputs.get(value)) : format(value));
964
+ const image = (value, detail) => {
965
+ let url = typeof value === 'string' ? value : value?.image_url;
966
+ if (!url && value?.type === 'image' && typeof value.data === 'string' && typeof value.mimeType === 'string')
967
+ url = value.data.startsWith('data:') ? value.data : 'data:' + value.mimeType + ';base64,' + value.data;
968
+ if (typeof url !== 'string' || !/^data:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[a-z0-9+/=]+$/i.test(url)) throw new TypeError('image expects base64 image data; remote image URLs are unavailable');
969
+ detail ??= value?.detail ?? value?._meta?.['codex/imageDetail'] ?? 'high';
970
+ if (!['auto','low','high','original'].includes(detail)) throw new TypeError('Invalid image detail');
971
+ bridge('image', stringify({ type: 'input_image', image_url: url, detail }));
972
+ };
973
+ const helpers = {
974
+ text, image,
975
+ generatedImage: value => { image(value); if (value?.output_hint !== undefined) text(value.output_hint); },
976
+ notify: value => bridge('notify', format(value)),
977
+ yield_control: async () => { bridge('yield', ''); },
978
+ exit: () => { throw EXIT; },
979
+ store: (key, value) => { if (typeof key !== 'string') throw new TypeError('store key must be a string'); stored.set(key, value); },
980
+ load: key => stored.get(key),
981
+ console: Object.freeze(Object.fromEntries(['log','info','warn','error','debug'].map(name => [name, (...args) => text(args.map(format).join(' '))])))
982
+ };
983
+ for (const [name, value] of Object.entries(helpers)) Object.defineProperty(globalThis, name, { value, configurable: false, writable: false });
984
+ Object.defineProperty(globalThis, 'tools', { get: () => tools });
985
+ Object.defineProperty(globalThis, 'ALL_TOOLS', { get: () => metadata });
986
+ return Object.freeze({
987
+ configure(json) {
988
+ done = false; failure = undefined;
989
+ const definitions = parse(json), table = Object.create(null);
990
+ for (const tool of definitions) table[tool.exposed] = (...args) => new Promise((resolve, reject) => {
991
+ const value = args.length <= 1 ? args[0] : args;
992
+ const json = value === undefined ? '' : stringify(value);
993
+ const id = ++next;
994
+ pending.set(id, { resolve, reject, output: tool.output });
995
+ try { bridge('call', stringify({ id, name: tool.name, json })); }
996
+ catch (e) { pending.delete(id); reject(e); }
997
+ });
998
+ tools = Object.freeze(table);
999
+ metadata = Object.freeze(definitions.filter(t => t.description !== undefined).map(t => Object.freeze({ name: t.exposed, description: t.description })));
1000
+ },
1001
+ observe(promise) { then(promise, () => { done = true; }, error => { done = true; if (error !== EXIT) failure = describe(error); }); },
1002
+ settle(id, json, error) {
1003
+ const request = pending.get(id); if (!request) throw new Error('Unknown tool result');
1004
+ pending.delete(id);
1005
+ if (error !== undefined) request.reject(new Error(error));
1006
+ else {
1007
+ const value = json === '' ? undefined : parse(json);
1008
+ if (request.output && value !== null && typeof value === 'object') outputs.set(value, request.output === 'plain-command');
1009
+ request.resolve(value);
1010
+ }
1011
+ },
1012
+ status() { return stringify({ done, error: failure, pending: pending.size }); }
1013
+ });
1014
+ })`;
1015
+
1016
+ // packages/js-notebook/src/support.ts
1017
+ import { randomUUID as randomUUID2 } from "node:crypto";
1018
+ var JS_SUPPORT_SOURCE = String.raw`(namespace => {
1019
+ const ids = new WeakMap(), hooks = new Map(), extensible = Object.isExtensible, parse = JSON.parse;
1020
+ const queue = [], settlements = [];
1021
+ let next = 0, depth = 0, failure, pumping = false;
1022
+ const describe = e => { try { return String(e); } catch { return 'unknown error'; } };
1023
+ return {
1024
+ isExtensible(value) { return extensible(value); },
1025
+ event(json) { return parse(json); },
1026
+ identity(value, supplied) {
1027
+ if ((typeof value !== 'object' || value === null) && typeof value !== 'function') throw new TypeError('Graph identity requires an object');
1028
+ let id = ids.get(value);
1029
+ if (supplied !== undefined) { if (id !== undefined && id !== supplied) throw new Error('Graph identity conflict'); id = supplied; }
1030
+ if (id === undefined) id = namespace + ':' + (++next);
1031
+ ids.set(value, id); return id;
1032
+ },
1033
+ register(name, event, fn) { if (event === false) hooks.delete(name); else { if (typeof fn !== 'function') throw new TypeError('Hook requires an existing function'); hooks.set(name, {event, fn}); } },
1034
+ list() { return JSON.stringify([...hooks].sort(([a],[b]) => a < b ? -1 : a > b ? 1 : 0).map(([name,h]) => ({name,event:h.event}))); },
1035
+ depth() { return depth; },
1036
+ failure() { const result = failure; failure = undefined; return result; },
1037
+ async dispatch(event) {
1038
+ const kind = event.type;
1039
+ depth++;
1040
+ try { for (const [name,h] of [...hooks].sort(([a],[b]) => a < b ? -1 : a > b ? 1 : 0)) if (h.event === kind) {
1041
+ try { await h.fn(event); } catch (e) { throw new Error('Notebook ' + kind + ' hook ' + name + ' failed: ' + describe(e) + '. Remove it with notebook hook event:false; live state was retained'); }
1042
+ } } finally { depth--; }
1043
+ },
1044
+ settle(control, id, json, error, event) {
1045
+ queue.push({control,id,json,error,event});
1046
+ if (pumping) return;
1047
+ pumping = true;
1048
+ const pump = async () => {
1049
+ while (queue.length) {
1050
+ const request = queue.shift();
1051
+ try { await this.dispatch(request.event); }
1052
+ catch (e) { failure = describe(e); request.json = ''; request.error = failure; }
1053
+ settlements.push(request);
1054
+ }
1055
+ // No user continuation resumes inside another event's hooks. Together
1056
+ // with the fully drained VM job queue this makes depth hook-local,
1057
+ // without patching Promise or replacing the immutable tools helpers.
1058
+ pumping = false;
1059
+ for (const request of settlements.splice(0)) request.control.settle(request.id,request.json,request.error);
1060
+ };
1061
+ pump();
1062
+ }
1063
+ };
1064
+ })`;
1065
+
1066
+ class JsSupport {
1067
+ token;
1068
+ vm;
1069
+ constructor(vm, token) {
1070
+ this.vm = vm;
1071
+ if (token !== undefined) {
1072
+ this.token = token;
1073
+ return;
1074
+ }
1075
+ const factory = vm.evalCode(JS_SUPPORT_SOURCE, "js-notebook-support.js"), namespace = vm.newString(randomUUID2());
1076
+ try {
1077
+ const root = vm.callFunction(factory, vm.undefined, namespace);
1078
+ this.token = vm.exportHandle(root);
1079
+ } finally {
1080
+ factory.dispose();
1081
+ namespace.dispose();
1082
+ }
1083
+ }
1084
+ call(name, ...args) {
1085
+ const root = this.vm.importHandle(this.token), fn = root.getProp(name);
1086
+ try {
1087
+ return this.vm.callFunction(fn, root, ...args);
1088
+ } finally {
1089
+ fn.dispose();
1090
+ root.dispose();
1091
+ }
1092
+ }
1093
+ identity(value, suppliedId) {
1094
+ const supplied = suppliedId === undefined ? this.vm.undefined : this.vm.newString(suppliedId);
1095
+ try {
1096
+ return this.call("identity", value, supplied).consume((id) => id.toString());
1097
+ } finally {
1098
+ supplied.dispose();
1099
+ }
1100
+ }
1101
+ isExtensible(value) {
1102
+ return this.call("isExtensible", value).consume((result) => result.toBoolean());
1103
+ }
1104
+ register(name, event, fn) {
1105
+ if (!validJsBindingName(name))
1106
+ throw new Error("Hook name must be a binding identifier");
1107
+ const key = this.vm.newString(name), kind = event === false ? this.vm.false : this.vm.newString(event);
1108
+ try {
1109
+ this.call("register", key, kind, fn).dispose();
1110
+ } finally {
1111
+ key.dispose();
1112
+ kind.dispose();
1113
+ }
1114
+ }
1115
+ }
1116
+
1117
+ // packages/js-notebook/src/worker.ts
1118
+ var data = workerData;
1119
+ var { JSException, QuickJS } = await import(data.moduleUrl);
1120
+ var interrupt = new Int32Array(data.interrupt);
1121
+ var vm;
1122
+ var controlToken;
1123
+ var inventory;
1124
+ var support;
1125
+ var bindings;
1126
+ var pins = data.snapshot?.pins ?? [];
1127
+ var startup = "pending";
1128
+ var startupFailure;
1129
+ var userInput;
1130
+ var calls = new Map;
1131
+ var active;
1132
+ var outputChars = 0;
1133
+ var outputItems = 0;
1134
+ var truncated = false;
1135
+ var rejections = new Map;
1136
+ function send(message) {
1137
+ const bytes = message.kind === "done" ? message.outcome.snapshot?.bytes : undefined;
1138
+ parentPort?.postMessage(message, bytes?.buffer instanceof ArrayBuffer ? [bytes.buffer] : []);
1139
+ }
1140
+ function bridge(kind, payload) {
1141
+ if (active === undefined)
1142
+ throw new Error("Start this operation in an active cell");
1143
+ const value = payload.toString();
1144
+ switch (kind.toString()) {
1145
+ case "call": {
1146
+ if (startup === "running")
1147
+ throw new Error("Tools are unavailable during startup hooks");
1148
+ const call = JSON.parse(value);
1149
+ if (!record2(call) || !Number.isSafeInteger(call["id"]) || typeof call["name"] !== "string" || typeof call["json"] !== "string")
1150
+ throw new Error("Invalid tool call");
1151
+ calls.set(Number(call["id"]), {
1152
+ name: call["name"],
1153
+ json: call["json"],
1154
+ hooked: support.call("depth").consume((value) => value.toNumber()) > 0
1155
+ });
1156
+ send({
1157
+ run: active,
1158
+ kind: "call",
1159
+ id: Number(call["id"]),
1160
+ name: call["name"],
1161
+ json: call["json"]
1162
+ });
1163
+ break;
1164
+ }
1165
+ case "text":
1166
+ case "image": {
1167
+ if (truncated)
1168
+ break;
1169
+ outputChars += value.length;
1170
+ outputItems++;
1171
+ if (outputChars > 33554432 || outputItems > 1e4) {
1172
+ truncated = true;
1173
+ send({
1174
+ run: active,
1175
+ kind: "output",
1176
+ items: [
1177
+ { type: "input_text", text: "[JS Notebook output truncated]" }
1178
+ ]
1179
+ });
1180
+ break;
1181
+ }
1182
+ if (kind.toString() === "text")
1183
+ send({
1184
+ run: active,
1185
+ kind: "output",
1186
+ items: [{ type: "input_text", text: value }]
1187
+ });
1188
+ else {
1189
+ const item = JSON.parse(value);
1190
+ if (!record2(item) || typeof item["image_url"] !== "string" || !["auto", "low", "high", "original"].includes(String(item["detail"])))
1191
+ throw new Error("Invalid image output");
1192
+ send({
1193
+ run: active,
1194
+ kind: "output",
1195
+ items: [
1196
+ {
1197
+ type: "input_image",
1198
+ image_url: item["image_url"],
1199
+ detail: item["detail"]
1200
+ }
1201
+ ]
1202
+ });
1203
+ }
1204
+ break;
1205
+ }
1206
+ case "notify":
1207
+ send({ run: active, kind: "notify", text: value });
1208
+ break;
1209
+ case "yield":
1210
+ send({ run: active, kind: "yield" });
1211
+ break;
1212
+ default:
1213
+ throw new Error("Unknown notebook operation");
1214
+ }
1215
+ return vm.undefined;
1216
+ }
1217
+ function call(name, ...args) {
1218
+ const control = vm.importHandle(controlToken);
1219
+ const fn = control.getProp(name);
1220
+ try {
1221
+ return vm.callFunction(fn, control, ...args);
1222
+ } finally {
1223
+ fn.dispose();
1224
+ control.dispose();
1225
+ }
1226
+ }
1227
+ function errorMessage(error) {
1228
+ try {
1229
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1230
+ } finally {
1231
+ if (error instanceof JSException)
1232
+ error.dispose();
1233
+ }
1234
+ }
1235
+ function finish(outcome) {
1236
+ if (active === undefined)
1237
+ return;
1238
+ send({
1239
+ run: active,
1240
+ kind: "done",
1241
+ outcome: {
1242
+ bindings: inspectJsBindings(vm, inventory, "*", bindings),
1243
+ inventoryComplete: inventory.complete,
1244
+ hooks: hooks(),
1245
+ pins,
1246
+ ...outcome,
1247
+ heapBytes: vm.getMemoryUsage().memoryUsedSize
1248
+ }
1249
+ });
1250
+ active = undefined;
1251
+ }
1252
+ function snapshot() {
1253
+ return {
1254
+ bytes: QuickJS.serializeSnapshot(vm.snapshot()),
1255
+ controller: controlToken,
1256
+ inventory,
1257
+ support: support.token,
1258
+ bindings: bindings.token,
1259
+ pins,
1260
+ startup: {
1261
+ status: startup === "running" ? "pending" : startup,
1262
+ ...startupFailure === undefined ? {} : { error: startupFailure }
1263
+ }
1264
+ };
1265
+ }
1266
+ function hooks() {
1267
+ return support.call("list").consume((value) => JSON.parse(value.toString()));
1268
+ }
1269
+ function captured(extra = {}) {
1270
+ let pinState, pinError;
1271
+ try {
1272
+ if (pins.length) {
1273
+ pinState = captureJsData(vm, support, inventory, pins, bindings);
1274
+ pinState.pins = [...pins];
1275
+ }
1276
+ } catch (error) {
1277
+ pinError = errorMessage(error);
1278
+ }
1279
+ return {
1280
+ ...extra,
1281
+ ...pinState ? { pinState } : {},
1282
+ ...pinError ? { pinError } : {},
1283
+ snapshot: snapshot()
1284
+ };
1285
+ }
1286
+ function manage(input) {
1287
+ const operation = input.data;
1288
+ if (!operation)
1289
+ return;
1290
+ if (operation.action === "export") {
1291
+ finish({
1292
+ data: captureJsData(vm, support, inventory, operation.names, bindings)
1293
+ });
1294
+ return;
1295
+ }
1296
+ if (operation.action === "import") {
1297
+ restoreJsData(vm, support, inventory, operation.state, bindings);
1298
+ if (operation.pins)
1299
+ pins = [...operation.pins];
1300
+ } else if (operation.action === "pin") {
1301
+ const selected = [...new Set([...pins, ...operation.names])].sort();
1302
+ captureJsData(vm, support, inventory, selected, bindings);
1303
+ pins = selected;
1304
+ } else if (operation.action === "unpin")
1305
+ pins = pins.filter((name) => !operation.names.includes(name));
1306
+ else {
1307
+ const protectedNames = new Map(pins.map((name) => [name, "project pin; unpin first"]));
1308
+ for (const hook of hooks())
1309
+ protectedNames.set(hook.name, "registered hook; remove its registration first");
1310
+ const release = releaseJsData(vm, inventory, operation.names, protectedNames, bindings);
1311
+ vm.runGC();
1312
+ finish(captured({ release }));
1313
+ return;
1314
+ }
1315
+ finish(captured());
1316
+ }
1317
+ function drain() {
1318
+ vm.executePendingJobs();
1319
+ const status = call("status").consume((value) => JSON.parse(value.toString()));
1320
+ if (!record2(status) || typeof status["done"] !== "boolean" || typeof status["pending"] !== "number")
1321
+ throw new Error("Invalid cell completion");
1322
+ if (!status["done"] && status["pending"] > 0 && calls.size > 0)
1323
+ return;
1324
+ if (!status["done"] || status["pending"] > 0) {
1325
+ finish({
1326
+ fatal: true,
1327
+ error: status["done"] ? "The cell finished with outstanding tool calls. Await every tool call before the cell ends" : "The cell is waiting on a promise with no pending tool call to resume it"
1328
+ });
1329
+ return;
1330
+ }
1331
+ const hookFailure = support.call("failure").consume((value) => value.typeof === "undefined" ? undefined : value.toString());
1332
+ const error = hookFailure ?? (typeof status["error"] === "string" ? status["error"] : rejections.values().next().value);
1333
+ if (startup === "running") {
1334
+ if (error !== undefined) {
1335
+ startup = "failed";
1336
+ startupFailure = error;
1337
+ finish({ error });
1338
+ return;
1339
+ }
1340
+ startup = "done";
1341
+ const input = userInput;
1342
+ userInput = undefined;
1343
+ if (!input)
1344
+ throw new Error("Missing user cell after startup");
1345
+ configure(input);
1346
+ startUser(input);
1347
+ return;
1348
+ }
1349
+ if (error !== undefined)
1350
+ finish({ error });
1351
+ else
1352
+ finish(captured());
1353
+ }
1354
+ function configure(input) {
1355
+ const tools = vm.newString(JSON.stringify(input.tools));
1356
+ try {
1357
+ call("configure", tools).dispose();
1358
+ } finally {
1359
+ tools.dispose();
1360
+ }
1361
+ }
1362
+ function hookEvent(value) {
1363
+ const json = vm.newString(JSON.stringify(value));
1364
+ try {
1365
+ return support.call("event", json);
1366
+ } finally {
1367
+ json.dispose();
1368
+ }
1369
+ }
1370
+ function startUser(input) {
1371
+ let result;
1372
+ try {
1373
+ result = bindings.execute(input.source ?? "");
1374
+ } catch (error) {
1375
+ finish({ error: errorMessage(error) });
1376
+ return;
1377
+ }
1378
+ try {
1379
+ call("observe", result).dispose();
1380
+ } finally {
1381
+ result.dispose();
1382
+ }
1383
+ drain();
1384
+ }
1385
+ async function main() {
1386
+ const options = {
1387
+ wasm: data.wasm,
1388
+ memoryLimit: data.heapBytes,
1389
+ interruptHandler: () => Atomics.load(interrupt, 0) !== 0,
1390
+ onUnhandledRejection: (promise, reason, handled) => {
1391
+ if (handled)
1392
+ rejections.delete(promise.identity);
1393
+ else {
1394
+ try {
1395
+ rejections.set(promise.identity, reason.toString());
1396
+ } catch {
1397
+ rejections.set(promise.identity, "Unhandled promise rejection");
1398
+ }
1399
+ }
1400
+ }
1401
+ };
1402
+ if (data.snapshot) {
1403
+ vm = await QuickJS.restore(QuickJS.deserializeSnapshot(data.snapshot.bytes), options);
1404
+ vm.registerHostCallback("js-notebook.bridge", bridge);
1405
+ controlToken = data.snapshot.controller;
1406
+ } else {
1407
+ vm = await QuickJS.create(options);
1408
+ const init = vm.evalCode(JS_PRELUDE, "js-notebook-prelude.js");
1409
+ const fn = vm.newFunction("js-notebook.bridge", bridge);
1410
+ try {
1411
+ const control = vm.callFunction(init, vm.undefined, fn);
1412
+ controlToken = vm.exportHandle(control);
1413
+ } finally {
1414
+ init.dispose();
1415
+ fn.dispose();
1416
+ }
1417
+ }
1418
+ inventory = data.snapshot?.inventory ?? {
1419
+ declarations: [],
1420
+ baseline: vm.global.getOwnPropertyNames(),
1421
+ complete: !data.snapshot
1422
+ };
1423
+ support = new JsSupport(vm, data.snapshot?.support);
1424
+ bindings = new JsBindings(vm, inventory, data.snapshot?.bindings);
1425
+ startup = data.snapshot?.startup?.status ?? "pending";
1426
+ startupFailure = data.snapshot?.startup?.error;
1427
+ parentPort?.on("message", (message) => {
1428
+ try {
1429
+ if (message.kind === "run") {
1430
+ if (active !== undefined)
1431
+ throw new Error("A cell is already running");
1432
+ active = message.run;
1433
+ outputChars = 0;
1434
+ outputItems = 0;
1435
+ truncated = false;
1436
+ rejections.clear();
1437
+ configure(message.input);
1438
+ if (message.input.hook) {
1439
+ try {
1440
+ const { name, event } = message.input.hook;
1441
+ const fn = event === false ? vm.undefined : bindings.has(name) ? bindings.read(name) : vm.evalCode(name);
1442
+ try {
1443
+ support.register(name, event, fn);
1444
+ } finally {
1445
+ fn.dispose();
1446
+ }
1447
+ if (startup === "failed") {
1448
+ startup = "pending";
1449
+ startupFailure = undefined;
1450
+ }
1451
+ finish(captured());
1452
+ } catch (error) {
1453
+ finish({ error: errorMessage(error) });
1454
+ }
1455
+ return;
1456
+ }
1457
+ if (message.input.inspect !== undefined) {
1458
+ finish({
1459
+ bindings: inspectJsBindings(vm, inventory, message.input.inspect, bindings)
1460
+ });
1461
+ return;
1462
+ }
1463
+ if (message.input.data) {
1464
+ try {
1465
+ manage(message.input);
1466
+ } catch (error) {
1467
+ finish({ error: errorMessage(error) });
1468
+ }
1469
+ return;
1470
+ }
1471
+ if (message.input.management && message.input.source === undefined) {
1472
+ finish(captured());
1473
+ return;
1474
+ }
1475
+ if (startup === "failed") {
1476
+ finish({
1477
+ error: startupFailure ?? "Startup hooks failed; remove the hook with notebook hook event:false"
1478
+ });
1479
+ return;
1480
+ }
1481
+ if (message.input.source === undefined) {
1482
+ finish(captured());
1483
+ return;
1484
+ }
1485
+ if (startup === "pending") {
1486
+ startup = "running";
1487
+ userInput = message.input;
1488
+ const event = hookEvent({ type: "startup" });
1489
+ try {
1490
+ const result = support.call("dispatch", event);
1491
+ try {
1492
+ call("observe", result).dispose();
1493
+ } finally {
1494
+ result.dispose();
1495
+ }
1496
+ } finally {
1497
+ event.dispose();
1498
+ }
1499
+ } else {
1500
+ startUser(message.input);
1501
+ return;
1502
+ }
1503
+ } else {
1504
+ if (active !== message.run)
1505
+ return;
1506
+ const id = vm.newNumber(message.id), json = vm.newString(message.json ?? ""), error = message.error === undefined ? vm.undefined : vm.newString(message.error);
1507
+ const request = calls.get(message.id);
1508
+ calls.delete(message.id);
1509
+ try {
1510
+ if (!request || request.hooked)
1511
+ call("settle", id, json, error).dispose();
1512
+ else {
1513
+ const event = hookEvent({
1514
+ type: "tool_result",
1515
+ toolName: request.name,
1516
+ input: request.json === "" ? undefined : JSON.parse(request.json),
1517
+ status: message.error === undefined ? "success" : "error",
1518
+ ...message.error === undefined ? {
1519
+ result: message.json === "" || message.json === undefined ? undefined : JSON.parse(message.json)
1520
+ } : { error: message.error }
1521
+ });
1522
+ const control = vm.importHandle(controlToken);
1523
+ try {
1524
+ support.call("settle", control, id, json, error, event).dispose();
1525
+ } finally {
1526
+ control.dispose();
1527
+ event.dispose();
1528
+ }
1529
+ }
1530
+ } finally {
1531
+ id.dispose();
1532
+ json.dispose();
1533
+ error.dispose();
1534
+ }
1535
+ }
1536
+ drain();
1537
+ } catch (error) {
1538
+ finish({ error: errorMessage(error), fatal: true });
1539
+ }
1540
+ });
1541
+ }
1542
+ function record2(value) {
1543
+ return typeof value === "object" && value !== null;
1544
+ }
1545
+ await main();