@opencode/codemode 0.0.0-dev-892 → 0.0.0-dev-900

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 (117) hide show
  1. package/README.md +3 -0
  2. package/dist/codemode.d.ts +2 -0
  3. package/dist/codemode.js +10 -4
  4. package/dist/vm/async.d.ts +78 -0
  5. package/dist/vm/async.js +335 -0
  6. package/dist/vm/code.d.ts +122 -0
  7. package/dist/vm/code.js +407 -0
  8. package/dist/vm/compiler/compile.d.ts +13 -0
  9. package/dist/vm/compiler/compile.js +1477 -0
  10. package/dist/vm/compiler/scope.d.ts +74 -0
  11. package/dist/vm/compiler/scope.js +515 -0
  12. package/dist/vm/data.d.ts +7 -0
  13. package/dist/vm/data.js +13 -0
  14. package/dist/vm/generators.d.ts +42 -0
  15. package/dist/vm/generators.js +413 -0
  16. package/dist/vm/host.d.ts +103 -0
  17. package/dist/vm/host.js +226 -0
  18. package/dist/vm/index.d.ts +3 -0
  19. package/dist/vm/index.js +3 -0
  20. package/dist/vm/internal-prelude.d.ts +45 -0
  21. package/dist/vm/internal-prelude.js +534 -0
  22. package/dist/vm/opcodes.d.ts +222 -0
  23. package/dist/vm/opcodes.js +235 -0
  24. package/dist/vm/prelude/bytecode.d.ts +18 -0
  25. package/dist/vm/prelude/bytecode.js +31 -0
  26. package/dist/vm/prelude/bytecode.json +1 -0
  27. package/dist/vm/prelude/helpers.d.ts +8 -0
  28. package/dist/vm/prelude/helpers.js +258 -0
  29. package/dist/vm/prelude/prelude.d.ts +21 -0
  30. package/dist/vm/prelude/prelude.js +53 -0
  31. package/dist/vm/prelude/source.d.ts +1 -0
  32. package/dist/vm/prelude/source.js +652 -0
  33. package/dist/vm/runtime/callback.d.ts +25 -0
  34. package/dist/vm/runtime/callback.js +51 -0
  35. package/dist/vm/runtime/driver.d.ts +41 -0
  36. package/dist/vm/runtime/driver.js +142 -0
  37. package/dist/vm/runtime/errors.d.ts +23 -0
  38. package/dist/vm/runtime/errors.js +169 -0
  39. package/dist/vm/runtime/execute.d.ts +22 -0
  40. package/dist/vm/runtime/execute.js +278 -0
  41. package/dist/vm/runtime/extensions.d.ts +16 -0
  42. package/dist/vm/runtime/extensions.js +270 -0
  43. package/dist/vm/runtime/generators.d.ts +6 -0
  44. package/dist/vm/runtime/generators.js +44 -0
  45. package/dist/vm/runtime/globals.d.ts +6 -0
  46. package/dist/vm/runtime/globals.js +137 -0
  47. package/dist/vm/runtime/interpreter.d.ts +50 -0
  48. package/dist/vm/runtime/interpreter.js +94 -0
  49. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  50. package/dist/vm/runtime/intrinsic-names.js +166 -0
  51. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  52. package/dist/vm/runtime/intrinsics.js +111 -0
  53. package/dist/vm/runtime/limits.d.ts +10 -0
  54. package/dist/vm/runtime/limits.js +19 -0
  55. package/dist/vm/runtime/model.d.ts +58 -0
  56. package/dist/vm/runtime/model.js +57 -0
  57. package/dist/vm/runtime/modules.d.ts +4 -0
  58. package/dist/vm/runtime/modules.js +33 -0
  59. package/dist/vm/runtime/native.d.ts +19 -0
  60. package/dist/vm/runtime/native.js +41 -0
  61. package/dist/vm/runtime/objects.d.ts +403 -0
  62. package/dist/vm/runtime/objects.js +784 -0
  63. package/dist/vm/runtime/operations.d.ts +49 -0
  64. package/dist/vm/runtime/operations.js +288 -0
  65. package/dist/vm/runtime/promises.d.ts +55 -0
  66. package/dist/vm/runtime/promises.js +232 -0
  67. package/dist/vm/runtime/references.d.ts +8 -0
  68. package/dist/vm/runtime/references.js +51 -0
  69. package/dist/vm/runtime/signals.d.ts +69 -0
  70. package/dist/vm/runtime/signals.js +68 -0
  71. package/dist/vm/runtime/source.d.ts +29 -0
  72. package/dist/vm/runtime/source.js +63 -0
  73. package/dist/vm/runtime/table.d.ts +43 -0
  74. package/dist/vm/runtime/table.js +132 -0
  75. package/dist/vm/scheduler.d.ts +178 -0
  76. package/dist/vm/scheduler.js +63 -0
  77. package/dist/vm/snapshot/codec.d.ts +88 -0
  78. package/dist/vm/snapshot/codec.js +752 -0
  79. package/dist/vm/snapshot/snapshot.d.ts +39 -0
  80. package/dist/vm/snapshot/snapshot.js +69 -0
  81. package/dist/vm/snapshot.d.ts +29 -0
  82. package/dist/vm/snapshot.js +304 -0
  83. package/dist/vm/stdlib/array.d.ts +16 -0
  84. package/dist/vm/stdlib/array.js +311 -0
  85. package/dist/vm/stdlib/bytes.d.ts +11 -0
  86. package/dist/vm/stdlib/bytes.js +222 -0
  87. package/dist/vm/stdlib/collections.d.ts +7 -0
  88. package/dist/vm/stdlib/collections.js +188 -0
  89. package/dist/vm/stdlib/console.d.ts +6 -0
  90. package/dist/vm/stdlib/console.js +93 -0
  91. package/dist/vm/stdlib/date.d.ts +2 -0
  92. package/dist/vm/stdlib/date.js +123 -0
  93. package/dist/vm/stdlib/headers.d.ts +2 -0
  94. package/dist/vm/stdlib/headers.js +92 -0
  95. package/dist/vm/stdlib/iterator.d.ts +2 -0
  96. package/dist/vm/stdlib/iterator.js +30 -0
  97. package/dist/vm/stdlib/json.d.ts +3 -0
  98. package/dist/vm/stdlib/json.js +42 -0
  99. package/dist/vm/stdlib/math.d.ts +3 -0
  100. package/dist/vm/stdlib/math.js +73 -0
  101. package/dist/vm/stdlib/number.d.ts +3 -0
  102. package/dist/vm/stdlib/number.js +72 -0
  103. package/dist/vm/stdlib/object.d.ts +6 -0
  104. package/dist/vm/stdlib/object.js +201 -0
  105. package/dist/vm/stdlib/regexp.d.ts +8 -0
  106. package/dist/vm/stdlib/regexp.js +119 -0
  107. package/dist/vm/stdlib/string.d.ts +2 -0
  108. package/dist/vm/stdlib/string.js +272 -0
  109. package/dist/vm/stdlib/url.d.ts +25 -0
  110. package/dist/vm/stdlib/url.js +255 -0
  111. package/dist/vm/stdlib/value.d.ts +6 -0
  112. package/dist/vm/stdlib/value.js +32 -0
  113. package/dist/vm/stdlib/web.d.ts +5 -0
  114. package/dist/vm/stdlib/web.js +97 -0
  115. package/dist/vm/vm.d.ts +224 -0
  116. package/dist/vm/vm.js +2921 -0
  117. package/package.json +5 -2
@@ -0,0 +1,51 @@
1
+ import { ToolReference } from "../../tool-runtime.js";
2
+ import { invalidData } from "./model.js";
3
+ import { Callable, getOwn, isRuntimeReference, Obj, Opaque, ownKeys } from "./objects.js";
4
+ /** Interpreter machinery that is never data, unlike a Date or Map, which cross some boundaries as copies. */
5
+ export const isOpaque = (value) => value instanceof Opaque || value instanceof ToolReference;
6
+ // Depth-first search over a value tree. `match` stops the walk; `skip` prunes a subtree without matching it.
7
+ const find = (value, match, skip, seen) => {
8
+ const pending = [[value].values()];
9
+ while (pending.length > 0) {
10
+ const next = pending.at(-1).next();
11
+ if (next.done) {
12
+ pending.pop();
13
+ continue;
14
+ }
15
+ const current = next.value;
16
+ if (match(current))
17
+ return true;
18
+ if (!(current instanceof Obj) || skip(current) || seen.has(current))
19
+ continue;
20
+ seen.add(current);
21
+ pending.push(ownKeys(current)
22
+ .map((key) => getOwn(current, key))
23
+ .values());
24
+ }
25
+ return false;
26
+ };
27
+ const never = () => false;
28
+ export const containsRuntimeReference = (value) => find(value, isRuntimeReference, never, new Set());
29
+ export const containsOpaqueReference = (value) => find(value, isOpaque, (current) => isRuntimeReference(current) && !isOpaque(current), new Set());
30
+ // Reject cycles before mutation so later boundary walks remain safe.
31
+ export const rejectCircularInsertion = (container, value, label, seen = new Set()) => {
32
+ if (find(value, (current) => current === container, isRuntimeReference, seen)) {
33
+ throw invalidData(`${label} contains a circular value.`);
34
+ }
35
+ };
36
+ export const describeValue = (value) => {
37
+ if (value === null || value === undefined)
38
+ return String(value);
39
+ if (value instanceof Obj)
40
+ return value.describe;
41
+ if (value instanceof ToolReference)
42
+ return "a tool reference";
43
+ return `a ${typeof value}`;
44
+ };
45
+ export const typeofValue = (value) => {
46
+ if (value instanceof Callable)
47
+ return "function";
48
+ if (value instanceof ToolReference)
49
+ return value.path.length > 0 ? "function" : "object";
50
+ return typeof value;
51
+ };
@@ -0,0 +1,69 @@
1
+ import type { Cause } from "effect";
2
+ import type { AstNode, GeneratorRequestKind } from "./model.js";
3
+ import type { GeneratorObj, Value } from "./objects.js";
4
+ export type Completion = {
5
+ readonly ok: true;
6
+ readonly value: unknown;
7
+ } | {
8
+ readonly ok: false;
9
+ readonly error: unknown;
10
+ };
11
+ export declare const normal: (value: unknown) => Completion;
12
+ export declare const abrupt: (error: unknown) => Completion;
13
+ /**
14
+ * Work a built-in hands to the VM, by name, with its arguments: VM-side TS or a prelude function runs it at the call,
15
+ * and its result is the call's (see `Vm.settleNativeResult`).
16
+ */
17
+ export declare class Push {
18
+ readonly kind: PushKind;
19
+ readonly slots: Array<unknown>;
20
+ constructor(kind: PushKind, slots: Array<unknown>);
21
+ }
22
+ export type PushKind = "JSON.stringify" | "AsyncFromSyncIterator" | "Promise executor" | "Promise.try" | "Promise combinator" | "search" | "extension call";
23
+ /** Continue a suspended generator's frame with `request`: what `next`/`return`/`throw` return once it can run. */
24
+ export declare class Resume {
25
+ readonly generator: GeneratorObj;
26
+ readonly request: GeneratorRequest;
27
+ constructor(generator: GeneratorObj, request: GeneratorRequest);
28
+ }
29
+ /**
30
+ * A built-in needs `values` converted to primitives (ToPrimitive with `hints`, in order) before it can go on: the
31
+ * conversions run as prelude code, then the built-in runs again from the start, and its `ordinal`-th conversion
32
+ * receives them. See `withPrimitives`.
33
+ */
34
+ export declare class Convert {
35
+ readonly hints: Hints;
36
+ readonly values: ReadonlyArray<Value>;
37
+ readonly ordinal: number;
38
+ /** Also apply ToNumber or ToString to each one before converting the next. */
39
+ readonly coerce: boolean;
40
+ constructor(hints: Hints, values: ReadonlyArray<Value>, ordinal: number,
41
+ /** Also apply ToNumber or ToString to each one before converting the next. */
42
+ coerce: boolean);
43
+ }
44
+ export type Hint = "number" | "string" | "default";
45
+ export type Hints = Hint | ReadonlyArray<Hint>;
46
+ /**
47
+ * Host work that was interrupted on its own. It settles its promise like a rejection, but program code cannot catch
48
+ * it: handlers, `catch`, and `finally` are skipped, an unobserved one is not reported, and one that reaches the
49
+ * program's body interrupts the execution.
50
+ */
51
+ export declare class Interruption {
52
+ readonly cause: Cause.Cause<unknown>;
53
+ constructor(cause: Cause.Cause<unknown>);
54
+ }
55
+ /** A call a built-in hands on (`Function.prototype.call`, say): the VM makes it as the built-in's own result. */
56
+ export declare class Invoke {
57
+ readonly callable: Value;
58
+ readonly thisValue: Value;
59
+ readonly args: Array<Value>;
60
+ readonly site: AstNode | undefined;
61
+ constructor(callable: Value, thisValue: Value, args: Array<Value>, site: AstNode | undefined);
62
+ }
63
+ /** What a generator body continues with: the `next`, `return`, or `throw` call that resumed it. */
64
+ export type GeneratorRequest = {
65
+ readonly kind: GeneratorRequestKind;
66
+ readonly value: Value;
67
+ };
68
+ /** Most activations one stack may hold, as the call-stack limit. */
69
+ export declare const MAX_CALL_DEPTH = 10000;
@@ -0,0 +1,68 @@
1
+ export const normal = (value) => ({ ok: true, value });
2
+ export const abrupt = (error) => ({ ok: false, error });
3
+ /**
4
+ * Work a built-in hands to the VM, by name, with its arguments: VM-side TS or a prelude function runs it at the call,
5
+ * and its result is the call's (see `Vm.settleNativeResult`).
6
+ */
7
+ export class Push {
8
+ kind;
9
+ slots;
10
+ constructor(kind, slots) {
11
+ this.kind = kind;
12
+ this.slots = slots;
13
+ }
14
+ }
15
+ /** Continue a suspended generator's frame with `request`: what `next`/`return`/`throw` return once it can run. */
16
+ export class Resume {
17
+ generator;
18
+ request;
19
+ constructor(generator, request) {
20
+ this.generator = generator;
21
+ this.request = request;
22
+ }
23
+ }
24
+ /**
25
+ * A built-in needs `values` converted to primitives (ToPrimitive with `hints`, in order) before it can go on: the
26
+ * conversions run as prelude code, then the built-in runs again from the start, and its `ordinal`-th conversion
27
+ * receives them. See `withPrimitives`.
28
+ */
29
+ export class Convert {
30
+ hints;
31
+ values;
32
+ ordinal;
33
+ coerce;
34
+ constructor(hints, values, ordinal,
35
+ /** Also apply ToNumber or ToString to each one before converting the next. */
36
+ coerce) {
37
+ this.hints = hints;
38
+ this.values = values;
39
+ this.ordinal = ordinal;
40
+ this.coerce = coerce;
41
+ }
42
+ }
43
+ /**
44
+ * Host work that was interrupted on its own. It settles its promise like a rejection, but program code cannot catch
45
+ * it: handlers, `catch`, and `finally` are skipped, an unobserved one is not reported, and one that reaches the
46
+ * program's body interrupts the execution.
47
+ */
48
+ export class Interruption {
49
+ cause;
50
+ constructor(cause) {
51
+ this.cause = cause;
52
+ }
53
+ }
54
+ /** A call a built-in hands on (`Function.prototype.call`, say): the VM makes it as the built-in's own result. */
55
+ export class Invoke {
56
+ callable;
57
+ thisValue;
58
+ args;
59
+ site;
60
+ constructor(callable, thisValue, args, site) {
61
+ this.callable = callable;
62
+ this.thisValue = thisValue;
63
+ this.args = args;
64
+ this.site = site;
65
+ }
66
+ }
67
+ /** Most activations one stack may hold, as the call-stack limit. */
68
+ export const MAX_CALL_DEPTH = 10_000;
@@ -0,0 +1,29 @@
1
+ import type { Program } from "acorn";
2
+ import type { AstNode } from "./model.js";
3
+ /** A stable reference to one AST node: its source and its index in a pre-order walk of that source's tree. */
4
+ export type NodeId = {
5
+ readonly source: string;
6
+ readonly index: number;
7
+ };
8
+ /**
9
+ * One parsed program text with every node numbered in pre-order, so a node can be named and found again. A built-in
10
+ * source whose bytecode was compiled ahead of time is parsed only once something asks for its nodes.
11
+ */
12
+ export declare class Source {
13
+ readonly id: string;
14
+ readonly code: string;
15
+ private tree;
16
+ private numbered;
17
+ constructor(id: string, code: string, program: Program | (() => Program));
18
+ get program(): Program;
19
+ /** Nodes by pre-order index. */
20
+ get nodes(): ReadonlyArray<AstNode>;
21
+ /** The node `id` names, when it belongs to this source. */
22
+ node(id: NodeId): AstNode | undefined;
23
+ }
24
+ /** The id of a node from a numbered source; nodes built outside one (none today) have none. */
25
+ export declare const nodeId: (node: AstNode) => NodeId | undefined;
26
+ /** The source a numbered node belongs to. */
27
+ export declare const sourceOf: (node: AstNode) => Source | undefined;
28
+ /** Whether `node` is the prelude's: it is parsed without locations, so a failure there is located at the program's call. */
29
+ export declare const inPrelude: (node: AstNode) => boolean;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * One parsed program text with every node numbered in pre-order, so a node can be named and found again. A built-in
3
+ * source whose bytecode was compiled ahead of time is parsed only once something asks for its nodes.
4
+ */
5
+ export class Source {
6
+ id;
7
+ code;
8
+ tree;
9
+ numbered;
10
+ constructor(id, code, program) {
11
+ this.id = id;
12
+ this.code = code;
13
+ this.tree = program;
14
+ if (typeof program !== "function")
15
+ this.numbered = numberNodes(program, this);
16
+ }
17
+ get program() {
18
+ if (typeof this.tree === "function")
19
+ this.tree = this.tree();
20
+ return this.tree;
21
+ }
22
+ /** Nodes by pre-order index. */
23
+ get nodes() {
24
+ return (this.numbered ??= numberNodes(this.program, this));
25
+ }
26
+ /** The node `id` names, when it belongs to this source. */
27
+ node(id) {
28
+ return id.source === this.id ? this.nodes[id.index] : undefined;
29
+ }
30
+ }
31
+ const numbering = new WeakMap();
32
+ /** The id of a node from a numbered source; nodes built outside one (none today) have none. */
33
+ export const nodeId = (node) => {
34
+ const entry = numbering.get(node);
35
+ return entry === undefined ? undefined : { source: entry.source.id, index: entry.index };
36
+ };
37
+ /** The source a numbered node belongs to. */
38
+ export const sourceOf = (node) => numbering.get(node)?.source;
39
+ const isNode = (value) => typeof value === "object" && value !== null && typeof value.type === "string";
40
+ // Acorn creates node fields in a fixed order, so walking own keys in order gives the same numbering on every parse.
41
+ const numberNodes = (root, source) => {
42
+ const nodes = [];
43
+ const pending = [root];
44
+ for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
45
+ numbering.set(node, { source, index: nodes.length });
46
+ nodes.push(node);
47
+ const children = [];
48
+ for (const key in node) {
49
+ if (key === "loc")
50
+ continue;
51
+ const child = node[key];
52
+ if (Array.isArray(child))
53
+ children.push(...child.filter(isNode));
54
+ else if (isNode(child))
55
+ children.push(child);
56
+ }
57
+ for (let index = children.length - 1; index >= 0; index--)
58
+ pending.push(children[index]);
59
+ }
60
+ return nodes;
61
+ };
62
+ /** Whether `node` is the prelude's: it is parsed without locations, so a failure there is located at the program's call. */
63
+ export const inPrelude = (node) => node.loc === undefined || node.loc === null;
@@ -0,0 +1,43 @@
1
+ import type { Value } from "./objects.js";
2
+ /** The key of a deleted entry. */
3
+ export declare const deleted: unique symbol;
4
+ /** A position in a table's entries, kept by the table so compaction can move it. */
5
+ export type TableCursor = {
6
+ index: number;
7
+ done: boolean;
8
+ };
9
+ /**
10
+ * The storage behind Map and Set: entries in insertion order with tombstones, as V8's OrderedHashTable. An entry keeps
11
+ * its index until the table compacts, and the table moves every live cursor when it does, so an iterator's position is
12
+ * a plain integer. Iteration is live: entries added before a cursor reaches the end are visited, deleted ones skipped,
13
+ * and after `clear()` a cursor continues with whatever is added next. Keys compare by SameValueZero.
14
+ */
15
+ export declare class OrderedTable {
16
+ readonly keys: Array<Value | typeof deleted>;
17
+ readonly values: Array<Value>;
18
+ private readonly index;
19
+ private cursors;
20
+ private tombstones;
21
+ private pruneAt;
22
+ get size(): number;
23
+ has(key: Value): boolean;
24
+ get(key: Value): Value;
25
+ set(key: Value, value: Value): void;
26
+ add(key: Value): void;
27
+ delete(key: Value): boolean;
28
+ clear(): void;
29
+ /** A cursor at the first entry, moved along by `advance`. */
30
+ cursor(): TableCursor;
31
+ /** Starts keeping `cursor` in place across compaction. */
32
+ track<C extends TableCursor>(cursor: C): C;
33
+ /** The index of the cursor's next live entry, moving past it; -1 once the cursor is done, which is for good. */
34
+ advance(cursor: TableCursor): number;
35
+ /**
36
+ * Live entries in order, through a tracked cursor, so host code may change the table (or run program code that does)
37
+ * between steps. Stopping early releases the cursor.
38
+ */
39
+ entries(): Generator<[Value, Value]>;
40
+ [Symbol.iterator](): Generator<[Value, Value]>;
41
+ liveKeys(): Generator<Value>;
42
+ private compact;
43
+ }
@@ -0,0 +1,132 @@
1
+ /** The key of a deleted entry. */
2
+ export const deleted = Symbol("codemode.deleted");
3
+ /**
4
+ * The storage behind Map and Set: entries in insertion order with tombstones, as V8's OrderedHashTable. An entry keeps
5
+ * its index until the table compacts, and the table moves every live cursor when it does, so an iterator's position is
6
+ * a plain integer. Iteration is live: entries added before a cursor reaches the end are visited, deleted ones skipped,
7
+ * and after `clear()` a cursor continues with whatever is added next. Keys compare by SameValueZero.
8
+ */
9
+ export class OrderedTable {
10
+ keys = [];
11
+ values = [];
12
+ // Derived from `keys`: where each live key is.
13
+ index = new Map();
14
+ cursors = [];
15
+ tombstones = 0;
16
+ pruneAt = 16;
17
+ get size() {
18
+ return this.index.size;
19
+ }
20
+ has(key) {
21
+ return this.index.has(key);
22
+ }
23
+ get(key) {
24
+ const at = this.index.get(key);
25
+ return at === undefined ? undefined : this.values[at];
26
+ }
27
+ set(key, value) {
28
+ const at = this.index.get(key);
29
+ if (at !== undefined) {
30
+ this.values[at] = value;
31
+ return;
32
+ }
33
+ // -0 is stored as +0, as Map and Set do.
34
+ const stored = key === 0 ? 0 : key;
35
+ this.index.set(stored, this.keys.length);
36
+ this.keys.push(stored);
37
+ this.values.push(value);
38
+ }
39
+ add(key) {
40
+ if (!this.index.has(key))
41
+ this.set(key, undefined);
42
+ }
43
+ delete(key) {
44
+ const at = this.index.get(key);
45
+ if (at === undefined)
46
+ return false;
47
+ this.index.delete(key);
48
+ this.keys[at] = deleted;
49
+ this.values[at] = undefined;
50
+ this.tombstones++;
51
+ if (this.tombstones >= 16 && this.tombstones * 2 >= this.keys.length)
52
+ this.compact();
53
+ return true;
54
+ }
55
+ clear() {
56
+ this.keys.fill(deleted);
57
+ this.values.fill(undefined);
58
+ this.index.clear();
59
+ this.tombstones = this.keys.length;
60
+ this.compact();
61
+ }
62
+ /** A cursor at the first entry, moved along by `advance`. */
63
+ cursor() {
64
+ return this.track({ index: 0, done: false });
65
+ }
66
+ /** Starts keeping `cursor` in place across compaction. */
67
+ track(cursor) {
68
+ if (this.cursors.length >= this.pruneAt) {
69
+ this.cursors = this.cursors.filter((item) => !item.done);
70
+ this.pruneAt = Math.max(16, this.cursors.length * 2);
71
+ }
72
+ this.cursors.push(cursor);
73
+ return cursor;
74
+ }
75
+ /** The index of the cursor's next live entry, moving past it; -1 once the cursor is done, which is for good. */
76
+ advance(cursor) {
77
+ if (cursor.done)
78
+ return -1;
79
+ for (let at = cursor.index; at < this.keys.length; at++) {
80
+ if (this.keys[at] === deleted)
81
+ continue;
82
+ cursor.index = at + 1;
83
+ return at;
84
+ }
85
+ cursor.done = true;
86
+ return -1;
87
+ }
88
+ /**
89
+ * Live entries in order, through a tracked cursor, so host code may change the table (or run program code that does)
90
+ * between steps. Stopping early releases the cursor.
91
+ */
92
+ *entries() {
93
+ const cursor = this.cursor();
94
+ try {
95
+ for (let at = this.advance(cursor); at >= 0; at = this.advance(cursor)) {
96
+ yield [this.keys[at], this.values[at]];
97
+ }
98
+ }
99
+ finally {
100
+ cursor.done = true;
101
+ }
102
+ }
103
+ [Symbol.iterator]() {
104
+ return this.entries();
105
+ }
106
+ *liveKeys() {
107
+ for (const [key] of this.entries())
108
+ yield key;
109
+ }
110
+ // Drops the tombstones; a cursor moves to the count of live entries before it, which is where it now points.
111
+ compact() {
112
+ const before = [];
113
+ let live = 0;
114
+ for (let at = 0; at < this.keys.length; at++) {
115
+ before.push(live);
116
+ const key = this.keys[at];
117
+ if (key === deleted)
118
+ continue;
119
+ this.keys[live] = key;
120
+ this.values[live] = this.values[at];
121
+ this.index.set(key, live);
122
+ live++;
123
+ }
124
+ before.push(live);
125
+ this.keys.length = live;
126
+ this.values.length = live;
127
+ this.tombstones = 0;
128
+ this.cursors = this.cursors.filter((cursor) => !cursor.done);
129
+ for (const cursor of this.cursors)
130
+ cursor.index = before[Math.min(cursor.index, before.length - 1)];
131
+ }
132
+ }
@@ -0,0 +1,178 @@
1
+ import type { Json } from "./data.js";
2
+ import type { ExtensionInvocation } from "../tool-runtime.js";
3
+ import type { AstNode } from "./runtime/model.js";
4
+ import type { Callable, Cursor, GeneratorObj, Obj, PromiseObj, Value } from "./runtime/objects.js";
5
+ import type { Completion } from "./runtime/signals.js";
6
+ import type { Frame } from "./vm.js";
7
+ /** What the member reactions of one `Promise.all`/`allSettled`/`race`/`any` share. */
8
+ export type Combination = {
9
+ readonly name: "all" | "allSettled" | "race" | "any";
10
+ /** Settles the combinator's result. */
11
+ readonly made: Resolving;
12
+ readonly values: Array<Value>;
13
+ readonly reasons: Array<Value>;
14
+ /** Members still to settle, plus one until iteration ends. */
15
+ remaining: number;
16
+ /** Every member's reaction, detached once the result is decided. */
17
+ readonly attached: Array<readonly [PromiseObj, Reaction]>;
18
+ };
19
+ /**
20
+ * A settled promise's reaction, as data. It runs as a job (see `react` in promises.ts) and either finishes at once or
21
+ * starts a frame that calls program code. The kinds:
22
+ * - `await`: resume the frames parked on the promise, cut off the job stack at an `await`.
23
+ * - `settle`: pass the outcome on to `target`.
24
+ * - `handler`: `then`/`catch` handlers; the handler's result settles `derived`.
25
+ * - `combinator`: one member of a `Promise` combinator.
26
+ * - `finally`, `finallyCleaned`, `finallyOutcome`: the steps of `Promise.prototype.finally` with a cleanup.
27
+ * - `awaitReturn`: an async generator's `return(value)` once `value` settles.
28
+ * - `asyncFromSync`: an async-from-sync iterator method's result value settled: answer `made` with it, closing the
29
+ * synchronous iterator `close` first on a rejection when one is given.
30
+ */
31
+ export type Reaction = {
32
+ readonly kind: "await";
33
+ readonly frames: Array<Frame>;
34
+ } | {
35
+ readonly kind: "settle";
36
+ readonly target: Resolving;
37
+ } | {
38
+ readonly kind: "handler";
39
+ readonly onFulfilled: Callable | undefined;
40
+ readonly onRejected: Callable | undefined;
41
+ readonly derived: Resolving;
42
+ } | {
43
+ readonly kind: "combinator";
44
+ readonly combination: Combination;
45
+ readonly index: number;
46
+ called: boolean;
47
+ } | {
48
+ readonly kind: "finally";
49
+ readonly cleanup: Callable;
50
+ readonly target: Resolving;
51
+ readonly site: AstNode | undefined;
52
+ } | {
53
+ readonly kind: "finallyCleaned";
54
+ readonly target: Resolving;
55
+ } | {
56
+ readonly kind: "finallyOutcome";
57
+ readonly target: Resolving;
58
+ readonly outcome: Completion;
59
+ } | {
60
+ readonly kind: "awaitReturn";
61
+ readonly generator: GeneratorObj;
62
+ } | {
63
+ readonly kind: "asyncFromSync";
64
+ readonly made: Resolving;
65
+ readonly done: boolean;
66
+ readonly close: Cursor | undefined;
67
+ readonly site: AstNode;
68
+ };
69
+ /** One queued job, as data: run a settled promise's reaction (resuming parked frames, say), or adopt a thenable. */
70
+ export type Job = {
71
+ readonly kind: "reaction";
72
+ readonly reaction: Reaction;
73
+ readonly settled: Completion;
74
+ } | {
75
+ readonly kind: "thenable";
76
+ readonly promise: PromiseObj;
77
+ readonly thenable: Obj;
78
+ readonly then: Value;
79
+ };
80
+ /**
81
+ * What host work a call asks for, as data the driver turns into an Effect: a tool call, a search, or a step of an
82
+ * extension function's call (see `ExtensionRequest`).
83
+ */
84
+ export type HostRequest = {
85
+ readonly kind: "tool";
86
+ readonly path: ReadonlyArray<string>;
87
+ readonly args: Array<Json | undefined>;
88
+ } | {
89
+ readonly kind: "search";
90
+ readonly args: Array<Json | undefined>;
91
+ } | {
92
+ readonly kind: "extension";
93
+ readonly call: ExtensionRequest;
94
+ };
95
+ /**
96
+ * One step of a call to an extension function: its `extension.before` hook (`before`), settling what the host function
97
+ * returned or threw (`settle`: `host` is that), or calling an async host function and settling its result (`run`:
98
+ * `host` is the function). `invocation` is what the hooks see, for a global or a global object's function. The host
99
+ * function and what it returns are live host values with no data form, dropped once the call completes.
100
+ */
101
+ export type ExtensionRequest = {
102
+ readonly stage: "before" | "settle" | "run";
103
+ readonly label: string;
104
+ invocation: ExtensionInvocation | undefined;
105
+ host: unknown;
106
+ args: ReadonlyArray<unknown>;
107
+ readonly threw: boolean;
108
+ };
109
+ /**
110
+ * Host work the program waits on. The VM queues it and hands it to the driver at its next stop; the driver runs it and
111
+ * reports how it ended with `Vm.complete`. A concurrent call's outcome waits in the inbox and settles its promise in a
112
+ * later job; a blocking call stops the VM, and no other job runs until it ends.
113
+ */
114
+ export declare class HostCall {
115
+ readonly id: number;
116
+ readonly request: HostRequest;
117
+ /** What runs: a tool path, or an extension function's label. */
118
+ readonly label: string;
119
+ /** The running job waits for it: its outcome continues the frame that asked, before any other job. */
120
+ readonly blocking: boolean;
121
+ /** How a concurrent call's result becomes a program value: a tool's crosses as JSON, an extension's is one. */
122
+ readonly result: "json" | "value";
123
+ /** Settles a concurrent call's promise. */
124
+ readonly resolving: Resolving | undefined;
125
+ /** The call that started the work, where a defect it raises is located. */
126
+ readonly site: AstNode | undefined;
127
+ /** Where the call is: `queued` (written ahead, not started), `running`, or `completed`. */
128
+ status: "queued" | "running" | "completed";
129
+ constructor(id: number, request: HostRequest,
130
+ /** What runs: a tool path, or an extension function's label. */
131
+ label: string,
132
+ /** The running job waits for it: its outcome continues the frame that asked, before any other job. */
133
+ blocking: boolean,
134
+ /** How a concurrent call's result becomes a program value: a tool's crosses as JSON, an extension's is one. */
135
+ result: "json" | "value",
136
+ /** Settles a concurrent call's promise. */
137
+ resolving: Resolving | undefined,
138
+ /** The call that started the work, where a defect it raises is located. */
139
+ site: AstNode | undefined);
140
+ }
141
+ /**
142
+ * CreateResolvingFunctions as data: settles one promise at most once, however many `Resolver`s share it. `reject` takes
143
+ * the failure as thrown; one without a location is located at `site`, the call that created the promise.
144
+ */
145
+ export declare class Resolving {
146
+ private readonly scheduler;
147
+ readonly promise: PromiseObj;
148
+ readonly site: AstNode | undefined;
149
+ done: boolean;
150
+ constructor(scheduler: Settles, promise: PromiseObj, site: AstNode | undefined);
151
+ resolve(resolution: Value): void;
152
+ reject(reason: unknown): void;
153
+ }
154
+ type Settles = {
155
+ resolveWith(promise: PromiseObj, resolution: Value, site?: AstNode): void;
156
+ reject(promise: PromiseObj, reason: unknown): void;
157
+ };
158
+ /**
159
+ * Why `Vm.run` stopped:
160
+ * - `done`: the program's body ended, with its completion.
161
+ * - `host`: start `calls`, newly queued host work, in order (a blocking call is last, and the VM continues only once
162
+ * it completes). With no calls, the VM waits for host work already running to complete.
163
+ * - `slice`: the step budget is used up; let the host run, then continue.
164
+ * - `stuck`: nothing can run or settle any more; `node` is the `await` that waits forever, when one is known.
165
+ */
166
+ export type Stop = {
167
+ readonly kind: "done";
168
+ readonly completion: Completion;
169
+ } | {
170
+ readonly kind: "host";
171
+ readonly calls: ReadonlyArray<HostCall>;
172
+ } | {
173
+ readonly kind: "slice";
174
+ } | {
175
+ readonly kind: "stuck";
176
+ readonly node: AstNode | undefined;
177
+ };
178
+ export {};