@opencode/codemode 2.2.5 → 2.2.6

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 (133) hide show
  1. package/README.md +70 -1
  2. package/dist/codemode.d.ts +55 -4
  3. package/dist/codemode.js +63 -8
  4. package/dist/extension.d.ts +14 -9
  5. package/dist/extension.js +2 -2
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/interpreter/execute.d.ts +1 -1
  9. package/dist/interpreter/execute.js +16 -4
  10. package/dist/interpreter/extensions.d.ts +3 -3
  11. package/dist/interpreter/extensions.js +17 -11
  12. package/dist/interpreter/globals.js +10 -0
  13. package/dist/interpreter/interpreter.d.ts +11 -1
  14. package/dist/interpreter/interpreter.js +86 -2
  15. package/dist/interpreter/modules.d.ts +4 -0
  16. package/dist/interpreter/modules.js +33 -0
  17. package/dist/suspend-error.d.ts +23 -0
  18. package/dist/suspend-error.js +25 -0
  19. package/dist/tool-runtime.d.ts +4 -1
  20. package/dist/vm/async.d.ts +78 -0
  21. package/dist/vm/async.js +335 -0
  22. package/dist/vm/code.d.ts +122 -0
  23. package/dist/vm/code.js +407 -0
  24. package/dist/vm/compiler/compile.d.ts +13 -0
  25. package/dist/vm/compiler/compile.js +1477 -0
  26. package/dist/vm/compiler/scope.d.ts +74 -0
  27. package/dist/vm/compiler/scope.js +515 -0
  28. package/dist/vm/data.d.ts +7 -0
  29. package/dist/vm/data.js +13 -0
  30. package/dist/vm/generators.d.ts +42 -0
  31. package/dist/vm/generators.js +413 -0
  32. package/dist/vm/host.d.ts +103 -0
  33. package/dist/vm/host.js +226 -0
  34. package/dist/vm/index.d.ts +6 -0
  35. package/dist/vm/index.js +6 -0
  36. package/dist/vm/internal-prelude.d.ts +45 -0
  37. package/dist/vm/internal-prelude.js +534 -0
  38. package/dist/vm/opcodes.d.ts +222 -0
  39. package/dist/vm/opcodes.js +235 -0
  40. package/dist/vm/prelude/bytecode.d.ts +18 -0
  41. package/dist/vm/prelude/bytecode.js +31 -0
  42. package/dist/vm/prelude/bytecode.json +1 -0
  43. package/dist/vm/prelude/helpers.d.ts +8 -0
  44. package/dist/vm/prelude/helpers.js +258 -0
  45. package/dist/vm/prelude/prelude.d.ts +21 -0
  46. package/dist/vm/prelude/prelude.js +53 -0
  47. package/dist/vm/prelude/source.d.ts +1 -0
  48. package/dist/vm/prelude/source.js +652 -0
  49. package/dist/vm/runtime/callback.d.ts +25 -0
  50. package/dist/vm/runtime/callback.js +51 -0
  51. package/dist/vm/runtime/driver.d.ts +58 -0
  52. package/dist/vm/runtime/driver.js +184 -0
  53. package/dist/vm/runtime/errors.d.ts +23 -0
  54. package/dist/vm/runtime/errors.js +169 -0
  55. package/dist/vm/runtime/execute.d.ts +80 -0
  56. package/dist/vm/runtime/execute.js +414 -0
  57. package/dist/vm/runtime/extensions.d.ts +16 -0
  58. package/dist/vm/runtime/extensions.js +270 -0
  59. package/dist/vm/runtime/generators.d.ts +6 -0
  60. package/dist/vm/runtime/generators.js +44 -0
  61. package/dist/vm/runtime/globals.d.ts +6 -0
  62. package/dist/vm/runtime/globals.js +137 -0
  63. package/dist/vm/runtime/interpreter.d.ts +50 -0
  64. package/dist/vm/runtime/interpreter.js +94 -0
  65. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  66. package/dist/vm/runtime/intrinsic-names.js +166 -0
  67. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  68. package/dist/vm/runtime/intrinsics.js +111 -0
  69. package/dist/vm/runtime/limits.d.ts +10 -0
  70. package/dist/vm/runtime/limits.js +19 -0
  71. package/dist/vm/runtime/model.d.ts +58 -0
  72. package/dist/vm/runtime/model.js +57 -0
  73. package/dist/vm/runtime/modules.d.ts +4 -0
  74. package/dist/vm/runtime/modules.js +33 -0
  75. package/dist/vm/runtime/native.d.ts +19 -0
  76. package/dist/vm/runtime/native.js +41 -0
  77. package/dist/vm/runtime/objects.d.ts +403 -0
  78. package/dist/vm/runtime/objects.js +784 -0
  79. package/dist/vm/runtime/operations.d.ts +49 -0
  80. package/dist/vm/runtime/operations.js +288 -0
  81. package/dist/vm/runtime/promises.d.ts +55 -0
  82. package/dist/vm/runtime/promises.js +232 -0
  83. package/dist/vm/runtime/references.d.ts +8 -0
  84. package/dist/vm/runtime/references.js +51 -0
  85. package/dist/vm/runtime/signals.d.ts +69 -0
  86. package/dist/vm/runtime/signals.js +68 -0
  87. package/dist/vm/runtime/source.d.ts +29 -0
  88. package/dist/vm/runtime/source.js +63 -0
  89. package/dist/vm/runtime/table.d.ts +43 -0
  90. package/dist/vm/runtime/table.js +132 -0
  91. package/dist/vm/scheduler.d.ts +178 -0
  92. package/dist/vm/scheduler.js +63 -0
  93. package/dist/vm/snapshot/codec.d.ts +87 -0
  94. package/dist/vm/snapshot/codec.js +751 -0
  95. package/dist/vm/snapshot/snapshot.d.ts +49 -0
  96. package/dist/vm/snapshot/snapshot.js +70 -0
  97. package/dist/vm/snapshot.d.ts +32 -0
  98. package/dist/vm/snapshot.js +306 -0
  99. package/dist/vm/stdlib/array.d.ts +16 -0
  100. package/dist/vm/stdlib/array.js +311 -0
  101. package/dist/vm/stdlib/bytes.d.ts +11 -0
  102. package/dist/vm/stdlib/bytes.js +222 -0
  103. package/dist/vm/stdlib/collections.d.ts +7 -0
  104. package/dist/vm/stdlib/collections.js +188 -0
  105. package/dist/vm/stdlib/console.d.ts +6 -0
  106. package/dist/vm/stdlib/console.js +93 -0
  107. package/dist/vm/stdlib/date.d.ts +2 -0
  108. package/dist/vm/stdlib/date.js +123 -0
  109. package/dist/vm/stdlib/headers.d.ts +2 -0
  110. package/dist/vm/stdlib/headers.js +92 -0
  111. package/dist/vm/stdlib/iterator.d.ts +2 -0
  112. package/dist/vm/stdlib/iterator.js +30 -0
  113. package/dist/vm/stdlib/json.d.ts +3 -0
  114. package/dist/vm/stdlib/json.js +42 -0
  115. package/dist/vm/stdlib/math.d.ts +3 -0
  116. package/dist/vm/stdlib/math.js +73 -0
  117. package/dist/vm/stdlib/number.d.ts +3 -0
  118. package/dist/vm/stdlib/number.js +72 -0
  119. package/dist/vm/stdlib/object.d.ts +6 -0
  120. package/dist/vm/stdlib/object.js +201 -0
  121. package/dist/vm/stdlib/regexp.d.ts +8 -0
  122. package/dist/vm/stdlib/regexp.js +119 -0
  123. package/dist/vm/stdlib/string.d.ts +2 -0
  124. package/dist/vm/stdlib/string.js +272 -0
  125. package/dist/vm/stdlib/url.d.ts +25 -0
  126. package/dist/vm/stdlib/url.js +255 -0
  127. package/dist/vm/stdlib/value.d.ts +6 -0
  128. package/dist/vm/stdlib/value.js +32 -0
  129. package/dist/vm/stdlib/web.d.ts +5 -0
  130. package/dist/vm/stdlib/web.js +97 -0
  131. package/dist/vm/vm.d.ts +225 -0
  132. package/dist/vm/vm.js +2931 -0
  133. package/package.json +6 -3
@@ -0,0 +1,49 @@
1
+ import type { Interpreter } from "../runtime/interpreter.js";
2
+ import type { ToolCall } from "../../tool-runtime.js";
3
+ import { fromBytes, SnapshotError, toBytes } from "../../suspend-error.js";
4
+ import type { Encoded, Record } from "./codec.js";
5
+ export { fromBytes, SnapshotError, toBytes };
6
+ /** The snapshot format this build writes and reads: the bytecode VM's (see `src/vm/snapshot.ts`). */
7
+ export declare const FORMAT = 2;
8
+ /**
9
+ * A suspended run's whole state as JSON: a header that says which build and sources it belongs to and what budget it
10
+ * has used, and the graph of records (see codec.ts) rooted at the VM, the interpreter, and the global scope, then
11
+ * every built-in or host global the run changed.
12
+ */
13
+ export type Snapshot = {
14
+ readonly format: typeof FORMAT;
15
+ readonly header: Header;
16
+ readonly roots: ReadonlyArray<Encoded>;
17
+ readonly records: ReadonlyArray<Record>;
18
+ };
19
+ export type Header = {
20
+ /** The build that wrote it: the package version, and a hash of the opcodes, the prelude's bytecode, codecs, and built-ins. */
21
+ readonly build: string;
22
+ /** A hash of the host's globals (extensions, a test harness), which the restoring runtime must have too. */
23
+ readonly hosts: string;
24
+ /** The program texts, re-parsed and recompiled on restore, and checked against their hashes and bytecode hashes. */
25
+ readonly sources: ReadonlyArray<{
26
+ readonly id: string;
27
+ readonly code: string;
28
+ readonly hash: string;
29
+ readonly bytecode: string;
30
+ }>;
31
+ readonly limits: {
32
+ readonly timeoutMs: number | null;
33
+ readonly maxToolCalls: number | null;
34
+ readonly maxOutputBytes: number | null;
35
+ };
36
+ /** What the run has used so far, across every resume: active milliseconds, and tool calls admitted. */
37
+ readonly budget: {
38
+ readonly activeMs: number;
39
+ readonly toolCalls: number;
40
+ };
41
+ /** The tool calls admitted so far. */
42
+ readonly toolCalls: ReadonlyArray<ToolCall>;
43
+ };
44
+ export type SnapshotHeader = Header;
45
+ export declare const hostsId: (ctx: Interpreter<unknown>) => string;
46
+ /** A saved state's header, checked in full, before anything is restored. */
47
+ export declare const header: (saved: unknown) => Header;
48
+ export declare const validate: (saved: unknown) => Snapshot;
49
+ export declare const hash: (text: string) => string;
@@ -0,0 +1,70 @@
1
+ import { fromBytes, SnapshotError, toBytes } from "../../suspend-error.js";
2
+ export { fromBytes, SnapshotError, toBytes };
3
+ /** The snapshot format this build writes and reads: the bytecode VM's (see `src/vm/snapshot.ts`). */
4
+ export const FORMAT = 2;
5
+ export const hostsId = (ctx) => hash(ctx.intrinsics.hosts().join("\n"));
6
+ // --- Validation ---
7
+ const fail = (message) => {
8
+ throw new SnapshotError(`Invalid snapshot: ${message}`);
9
+ };
10
+ const object = (value, what) => typeof value === "object" && value !== null && !Array.isArray(value)
11
+ ? value
12
+ : fail(`${what} is not an object.`);
13
+ const array = (value, what) => Array.isArray(value) ? value : fail(`${what} is not a list.`);
14
+ const string = (value, what) => typeof value === "string" ? value : fail(`${what} is not text.`);
15
+ const number = (value, what) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fail(`${what} is not a number.`);
16
+ const limit = (value, what) => (value === null ? null : number(value, what));
17
+ /** A saved state's header, checked in full, before anything is restored. */
18
+ export const header = (saved) => validate(saved).header;
19
+ // The header is checked in full; records are checked as they are decoded.
20
+ export const validate = (saved) => {
21
+ const root = object(saved, "the snapshot");
22
+ if (root.format !== FORMAT)
23
+ fail(`format ${String(root.format)} is not ${FORMAT}.`);
24
+ const header = object(root.header, "the header");
25
+ const limits = object(header.limits, "the limits");
26
+ const budget = object(header.budget, "the budget");
27
+ const checked = {
28
+ build: string(header.build, "the build"),
29
+ hosts: string(header.hosts, "the host globals"),
30
+ sources: array(header.sources, "the sources").map((item) => {
31
+ const source = object(item, "a source");
32
+ return {
33
+ id: string(source.id, "a source id"),
34
+ code: string(source.code, "a source"),
35
+ hash: string(source.hash, "a source hash"),
36
+ bytecode: string(source.bytecode, "a bytecode hash"),
37
+ };
38
+ }),
39
+ limits: {
40
+ timeoutMs: limit(limits.timeoutMs, "timeoutMs"),
41
+ maxToolCalls: limit(limits.maxToolCalls, "maxToolCalls"),
42
+ maxOutputBytes: limit(limits.maxOutputBytes, "maxOutputBytes"),
43
+ },
44
+ budget: { activeMs: number(budget.activeMs, "the active time"), toolCalls: number(budget.toolCalls, "tool calls") },
45
+ toolCalls: array(header.toolCalls, "the tool calls").map((item) => ({
46
+ name: string(object(item, "a tool call").name, "a tool name"),
47
+ })),
48
+ };
49
+ const roots = array(root.roots, "the roots");
50
+ if (roots.length < 3)
51
+ fail("there are fewer than three roots.");
52
+ return {
53
+ format: FORMAT,
54
+ header: checked,
55
+ roots: roots,
56
+ records: array(root.records, "the records"),
57
+ };
58
+ };
59
+ // --- Helpers ---
60
+ // FNV-1a over UTF-16 code units, twice with different offsets: a fingerprint, not a security check.
61
+ export const hash = (text) => {
62
+ let a = 0x811c9dc5;
63
+ let b = 0x01000193 ^ 0x9e3779b9;
64
+ for (let at = 0; at < text.length; at++) {
65
+ const code = text.charCodeAt(at);
66
+ a = Math.imul(a ^ code, 0x01000193);
67
+ b = Math.imul(b ^ code, 0x01000193) ^ (b >>> 13);
68
+ }
69
+ return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
70
+ };
@@ -0,0 +1,32 @@
1
+ import type { Interruption } from "./runtime/signals.js";
2
+ import { type Source } from "./runtime/source.js";
3
+ import { type Header, type Snapshot } from "./snapshot/snapshot.js";
4
+ import { Vm } from "./vm.js";
5
+ export type CaptureOptions = {
6
+ readonly limits?: Header["limits"];
7
+ /** Active milliseconds used so far, across every resume. */
8
+ readonly activeMs?: number;
9
+ /** Throw on the first value with no data form, instead of reporting it in `lost`. */
10
+ readonly strict: boolean;
11
+ };
12
+ export type RestoreOptions = {
13
+ /** Parses a saved program source (cached by text). */
14
+ readonly parse: (code: string) => Source;
15
+ readonly interruption: () => Interruption;
16
+ };
17
+ /**
18
+ * The VM build a snapshot belongs to: the package version, and a hash of the format, the opcode table, the frame
19
+ * modes, the compiler version, the prelude's and the internal helpers' bytecode, the static intrinsic names, and the
20
+ * codec's shape. A runtime must have been made first (the intrinsic names come from it).
21
+ */
22
+ export declare const buildId: () => string;
23
+ /** Saves a VM's state as it is now, with every built-in or host global the run changed. Changes nothing. */
24
+ export declare const captureVm: (vm: Vm, options: CaptureOptions) => {
25
+ readonly snapshot: Snapshot;
26
+ readonly lost: ReadonlyArray<string>;
27
+ };
28
+ /**
29
+ * Restores a saved state into `vm`, a fresh one made for a new runtime with the same host globals and no bindings,
30
+ * after checking the snapshot belongs to this build, these host globals, its own sources and their bytecode.
31
+ */
32
+ export declare const restoreVm: (vm: Vm, saved: unknown, options: RestoreOptions) => Snapshot;
@@ -0,0 +1,306 @@
1
+ import packageJson from "../../package.json" with { type: "json" };
2
+ import { staticNames, unchanged } from "./runtime/intrinsic-names.js";
3
+ import { Fn, Obj } from "./runtime/objects.js";
4
+ import { nodeId } from "./runtime/source.js";
5
+ import { codecShape, decode, encode, SnapshotError } from "./snapshot/codec.js";
6
+ import { FORMAT, hash, hostsId, validate } from "./snapshot/snapshot.js";
7
+ import { AsyncFromSyncCloseTarget, FinallyTarget, VmScheduler } from "./async.js";
8
+ import { Code, hashOf } from "./code.js";
9
+ import { COMPILER_VERSION, compileSource } from "./compiler/compile.js";
10
+ import { HostCalls } from "./host.js";
11
+ import { getInternalPrelude } from "./internal-prelude.js";
12
+ import { compiledPrelude } from "./prelude/prelude.js";
13
+ import { Cell, CodeFlags, EMPTY_CELLS, HOLE, Op } from "./opcodes.js";
14
+ import { CustomIter, Frame, Mode, Vm, VmInternalFn } from "./vm.js";
15
+ let specs;
16
+ // Built on first use: this module and vm.ts import each other, so the classes aren't there at load time.
17
+ const vmSpecs = () => (specs ??= [
18
+ {
19
+ name: "Vm",
20
+ ctor: Vm,
21
+ anchor: "vm",
22
+ fields: ["frames", "templates", "scheduler", "hosts", "depth", "sliced", "outcome"],
23
+ skip: ["ctx", "pool", "sourceCodes", "intrinsics", "fuel", "sliceStart", "tripEvery"],
24
+ reset: restoreStack,
25
+ },
26
+ {
27
+ name: "VmScheduler",
28
+ ctor: VmScheduler,
29
+ anchor: "scheduler",
30
+ fields: ["intrinsicThen", "parked", "queue", "head", "pending", "nextID", "unhandled"],
31
+ skip: ["vm"],
32
+ },
33
+ {
34
+ name: "HostCalls",
35
+ ctor: HostCalls,
36
+ anchor: "hosts",
37
+ fields: ["queued", "running", "inbox", "nextID", "blocked", "input"],
38
+ skip: ["ctx", "promises", "extension", "extensionResume"],
39
+ },
40
+ {
41
+ name: "Frame",
42
+ ctor: Frame,
43
+ fields: ["fn", "code", "pc", "sp", "regs", "thisValue", "args", "mode", "target", "answer", "origin", "counted"],
44
+ view: (frame) => [
45
+ frame.fn,
46
+ frame.code,
47
+ frame.pc,
48
+ frame.sp,
49
+ frame.regs.slice(0, frame.sp),
50
+ frame.thisValue,
51
+ frame.args,
52
+ frame.mode,
53
+ frame.target,
54
+ frame.answer,
55
+ frame.origin,
56
+ frame.counted,
57
+ ],
58
+ reset: restoreFrame,
59
+ },
60
+ {
61
+ name: "Fn",
62
+ ctor: Fn,
63
+ fields: ["code", "cells"],
64
+ skip: ["length"],
65
+ obj: true,
66
+ constants: { tag: "Function" },
67
+ reset: restoreFn,
68
+ },
69
+ { name: "VmInternalFn", ctor: VmInternalFn, fields: ["code", "boundArgs"] },
70
+ { name: "FinallyTarget", ctor: FinallyTarget, fields: ["vm", "made", "site", "outcome"] },
71
+ { name: "AsyncFromSyncCloseTarget", ctor: AsyncFromSyncCloseTarget, fields: ["made", "reason"] },
72
+ { name: "Cell", ctor: Cell, fields: ["v"] },
73
+ { name: "CustomIter", ctor: CustomIter, fields: ["done", "rawGen", "iterator", "next"] },
74
+ ]);
75
+ let build;
76
+ /**
77
+ * The VM build a snapshot belongs to: the package version, and a hash of the format, the opcode table, the frame
78
+ * modes, the compiler version, the prelude's and the internal helpers' bytecode, the static intrinsic names, and the
79
+ * codec's shape. A runtime must have been made first (the intrinsic names come from it).
80
+ */
81
+ export const buildId = () => (build ??= `${packageJson.version}+${hash([
82
+ FORMAT,
83
+ JSON.stringify(Object.entries(Op)),
84
+ JSON.stringify(Object.entries(Mode)),
85
+ COMPILER_VERSION,
86
+ hashOf(compiledPrelude().codes),
87
+ hashOf(getInternalPrelude().codes),
88
+ staticNames().join("\n"),
89
+ codecShape(vmSpecs()),
90
+ ].join("\n"))}`);
91
+ /** Saves a VM's state as it is now, with every built-in or host global the run changed. Changes nothing. */
92
+ export const captureVm = (vm, options) => {
93
+ vm.compact();
94
+ const ctx = vm.ctx;
95
+ const lost = [];
96
+ const names = ctx.intrinsics;
97
+ const programs = [...ctx.sources.values()];
98
+ const sources = sourcesOf(vm);
99
+ const anchors = new Map(anchorsOf(vm));
100
+ const internals = new Map();
101
+ for (const [name, value] of vm.intrinsics)
102
+ if (!(value instanceof Obj))
103
+ internals.set(value, name);
104
+ const encoded = encode([vm, ctx, ctx.globalScope, ...names.changed()], {
105
+ nameOf: (value) => names.nameOf(value),
106
+ unchanged,
107
+ anchorOf: (value) => anchors.get(value),
108
+ nodeId: (node) => {
109
+ const id = nodeId(node);
110
+ return id !== undefined && sources.get(id.source)?.nodes[id.index] === node ? [id.source, id.index] : undefined;
111
+ },
112
+ lost,
113
+ strict: options.strict,
114
+ specs: vmSpecs(),
115
+ external: (value) => {
116
+ if (value === HOLE)
117
+ return "hole";
118
+ if (typeof value === "symbol" || value instanceof Obj)
119
+ return undefined;
120
+ const internal = internals.get(value);
121
+ if (internal !== undefined)
122
+ return ["intrinsic", internal];
123
+ return codeRef(vm, value);
124
+ },
125
+ });
126
+ const snapshot = {
127
+ format: FORMAT,
128
+ header: {
129
+ build: buildId(),
130
+ hosts: hostsId(ctx),
131
+ sources: programs.map((source) => ({
132
+ id: source.id,
133
+ code: source.code,
134
+ hash: hash(source.code),
135
+ bytecode: vm.sourceCodes.get(source.id)[0].source.hash,
136
+ })),
137
+ limits: options.limits ?? { timeoutMs: null, maxToolCalls: null, maxOutputBytes: null },
138
+ budget: { activeMs: options.activeMs ?? 0, toolCalls: ctx.tools.calls.length },
139
+ toolCalls: ctx.tools.calls.map((call) => ({ name: call.name })),
140
+ },
141
+ roots: encoded.roots,
142
+ records: encoded.records,
143
+ };
144
+ return { snapshot, lost };
145
+ };
146
+ /**
147
+ * Restores a saved state into `vm`, a fresh one made for a new runtime with the same host globals and no bindings,
148
+ * after checking the snapshot belongs to this build, these host globals, its own sources and their bytecode.
149
+ */
150
+ export const restoreVm = (vm, saved, options) => {
151
+ const snapshot = validate(saved);
152
+ const header = snapshot.header;
153
+ const ctx = vm.ctx;
154
+ const expected = buildId();
155
+ if (snapshot.format !== FORMAT || header.build !== expected) {
156
+ throw new SnapshotError(`This state was saved by another Code Mode build (${header.build}); this runtime is ${expected}, so it can't resume it.`);
157
+ }
158
+ if (header.hosts !== hostsId(ctx)) {
159
+ throw new SnapshotError("This state was saved by a runtime with other host globals (extensions); resume it with the same ones.");
160
+ }
161
+ for (const source of header.sources) {
162
+ if (hash(source.code) !== source.hash)
163
+ throw new SnapshotError(`Source ${source.id} does not match its hash.`);
164
+ const parsed = options.parse(source.code);
165
+ if (parsed.id !== source.id || vm.sourceCodes.has(source.id)) {
166
+ throw new SnapshotError(`Source ${source.id} is not a program source.`);
167
+ }
168
+ const codes = compileSource(parsed);
169
+ if (codes[0].source.hash !== source.bytecode) {
170
+ throw new SnapshotError(`Source ${source.id} compiles to other bytecode in this build, so it can't resume.`);
171
+ }
172
+ ctx.sources.set(source.id, parsed);
173
+ vm.sourceCodes.set(source.id, codes);
174
+ }
175
+ const sources = sourcesOf(vm);
176
+ const anchors = new Map(anchorsOf(vm).map(([object, name]) => [name, object]));
177
+ decode(snapshot, {
178
+ named: (name) => ctx.intrinsics.valueOf(name),
179
+ anchor: (name) => anchors.get(name),
180
+ node: (source, index) => sources.get(source)?.nodes[index],
181
+ interruption: options.interruption,
182
+ specs: vmSpecs(),
183
+ external: (data) => {
184
+ if (data === "hole")
185
+ return HOLE;
186
+ if (!Array.isArray(data))
187
+ return undefined;
188
+ if (data[0] === "intrinsic" && typeof data[1] === "string") {
189
+ const value = vm.intrinsics.get(data[1]);
190
+ return value instanceof Obj ? undefined : value;
191
+ }
192
+ if (data[0] === "code" && typeof data[1] === "string" && typeof data[2] === "number") {
193
+ return vm.sourceCodes.get(data[1])?.[data[2]];
194
+ }
195
+ return undefined;
196
+ },
197
+ });
198
+ ctx.tools.calls.push(...header.toolCalls.map((call) => ({ name: call.name })));
199
+ return snapshot;
200
+ };
201
+ // --- Helpers ---
202
+ // The objects a fresh runtime already has, saved by name and filled in place on restore.
203
+ const anchorsOf = (vm) => [
204
+ [vm, "vm"],
205
+ [vm.scheduler, "scheduler"],
206
+ [vm.hosts, "hosts"],
207
+ [vm.ctx, "ctx"],
208
+ [vm.ctx.globalScope, "globals"],
209
+ ];
210
+ // Every source a saved node can belong to: the programs, and the prelude's and the internal helpers' sources.
211
+ const sourcesOf = (vm) => {
212
+ const sources = new Map(vm.ctx.sources);
213
+ for (const codes of vm.sourceCodes.values()) {
214
+ const source = codes[0]?.sourceObj;
215
+ if (source !== undefined)
216
+ sources.set(source.id, source);
217
+ }
218
+ return sources;
219
+ };
220
+ const codeRef = (vm, code) => {
221
+ if (!(code instanceof Code))
222
+ return undefined;
223
+ if (vm.sourceCodes.get(code.source.id)?.[code.index] !== code) {
224
+ throw new SnapshotError(`Codec gap: function ${code.index} of ${code.source.id} is not this run's code.`);
225
+ }
226
+ return ["code", code.source.id, code.index];
227
+ };
228
+ const invalid = (message) => {
229
+ throw new SnapshotError(`Invalid snapshot: ${message}`);
230
+ };
231
+ // A frame as saved, checked against its code before anything runs (§6.5): pc on an instruction, sp within the
232
+ // frame's registers, holes only in locals, finally tags in range, a mode it can complete by. Then its registers are
233
+ // padded to the code's size and its cells taken from its function.
234
+ function restoreFrame(frame) {
235
+ const code = frame.code;
236
+ if (!(code instanceof Code))
237
+ return invalid("a frame has no code.");
238
+ const regs = frame.regs;
239
+ if (!Array.isArray(regs))
240
+ return invalid("a frame's registers are not a list.");
241
+ const pc = frame.pc;
242
+ if (!Number.isSafeInteger(pc) || pc < 0 || pc >= code.code.length)
243
+ return invalid(`a frame's pc ${pc} is out of range.`);
244
+ const sp = frame.sp;
245
+ if (!Number.isSafeInteger(sp) || sp < code.locals || sp > code.locals + code.maxStack || regs.length !== sp) {
246
+ return invalid(`a frame's stack pointer ${sp} is out of range.`);
247
+ }
248
+ for (let at = code.locals; at < sp; at++)
249
+ if (regs[at] === HOLE)
250
+ invalid("a hole is on a frame's operand stack.");
251
+ for (let level = 0; level < code.finallyOffsets.length; level++) {
252
+ const offset = code.finallyOffsets[level];
253
+ const tag = regs[code.finallies[offset]];
254
+ const targets = code.finallies[offset + 3];
255
+ if (tag !== HOLE &&
256
+ tag !== undefined &&
257
+ !(Number.isSafeInteger(tag) && tag >= 0 && tag < targets)) {
258
+ invalid(`a frame's finally tag ${String(tag)} is out of range.`);
259
+ }
260
+ }
261
+ if (!Object.values(Mode).includes(frame.mode))
262
+ invalid(`a frame's mode ${String(frame.mode)} is unknown.`);
263
+ if (frame.mode === Mode.PROGRAM && (code.flags & CodeFlags.PROGRAM) === 0)
264
+ invalid("a frame's mode does not fit its code.");
265
+ const settles = frame.mode !== Mode.CALLER && frame.mode !== Mode.PROGRAM && frame.mode !== Mode.BOUNDARY_OUT;
266
+ if (!settles && frame.target !== undefined)
267
+ invalid("a frame that settles nothing has a target.");
268
+ const fn = frame.fn;
269
+ if (fn !== null && !(fn instanceof Fn))
270
+ invalid("a frame's function is not a function.");
271
+ if (fn instanceof Fn && fn.code !== code)
272
+ invalid("a frame's function does not run its code.");
273
+ if (typeof frame.counted !== "boolean")
274
+ invalid("a frame's call depth flag is not a boolean.");
275
+ if (frame.args !== undefined && !Array.isArray(frame.args))
276
+ invalid("a frame's arguments are not a list.");
277
+ for (let at = sp, size = code.locals + code.maxStack; at < size; at++)
278
+ regs.push(HOLE);
279
+ frame.cells = fn instanceof Fn ? fn.cells : EMPTY_CELLS;
280
+ }
281
+ // The job stack, checked: frames only, the program's frame only at the bottom, and a caller under every `CALLER` one.
282
+ function restoreStack(vm) {
283
+ const frames = vm.frames;
284
+ if (!Array.isArray(frames) || frames.some((frame) => !(frame instanceof Frame)))
285
+ invalid("the job stack is not frames.");
286
+ vm.frames.forEach((frame, at) => {
287
+ const bottomOnly = frame.mode === Mode.PROGRAM || frame.mode === Mode.BOUNDARY_OUT;
288
+ if ((at === 0 && frame.mode === Mode.CALLER) || (at > 0 && bottomOnly))
289
+ invalid("a frame is out of place on the job stack.");
290
+ });
291
+ if (!Number.isSafeInteger(vm.depth) || vm.depth < 0)
292
+ invalid("the call depth is not a count.");
293
+ }
294
+ // A closure's code and cells, checked; its length comes from its code.
295
+ function restoreFn(fn) {
296
+ const code = fn.code;
297
+ if (!(code instanceof Code))
298
+ return invalid("a closure has no code.");
299
+ const cells = fn.cells;
300
+ if (!Array.isArray(cells) ||
301
+ cells.length !== code.captures.length >>> 1 ||
302
+ cells.some((cell) => !(cell instanceof Cell))) {
303
+ invalid("a closure's cells do not match its captures.");
304
+ }
305
+ Object.assign(fn, { length: code.length });
306
+ }
@@ -0,0 +1,16 @@
1
+ import { Invoke } from "../runtime/signals.js";
2
+ import type { Builtins } from "../runtime/intrinsics.js";
3
+ import { Arr, Bytes, type Value } from "../runtime/objects.js";
4
+ import type { Interpreter } from "../runtime/interpreter.js";
5
+ /** Where a sort puts its result: back into an array or bytes, or into a new array. */
6
+ export type SortInto = "Array.sort" | "Array.toSorted" | "Uint8Array.sort";
7
+ /** The most values the default sort sorts in one native call; more sort in bounded steps (see `sortDefault`). */
8
+ export declare const SORT_RUN = 4096;
9
+ /**
10
+ * Sorts `target`'s values: at once without a comparator, unless there are many, otherwise in the prelude
11
+ * (`sortWith`), which calls it. The merges of a top-down merge sort are planned here, in post-order, so the prelude
12
+ * compares in the same order as the recursive sort. Holes and undefined values sort last without being compared.
13
+ */
14
+ export declare const sortArray: <R>(ctx: Interpreter<R>, target: Arr | Bytes, comparator: Value, into: SortInto) => Value | Invoke;
15
+ export declare const sorted: (builtins: Builtins, target: Arr | Bytes, into: SortInto, holes: number, result: Array<Value>) => Arr | Bytes;
16
+ export declare const arrayGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;