@rulvar/planner 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,204 @@
1
+ import { ScriptRejected } from "@rulvar/core";
2
+ //#region src/compile.ts
3
+ /**
4
+ * The exact curated sandbox global set, in docs order (docs/06, 8.2).
5
+ * The worker binds the ctx methods as bare globals under these names and
6
+ * the API card teaches exactly this list.
7
+ */
8
+ const SANDBOX_GLOBALS = [
9
+ "agent",
10
+ "parallel",
11
+ "pipeline",
12
+ "step",
13
+ "phase",
14
+ "log",
15
+ "budget",
16
+ "workflow",
17
+ "awaitExternal",
18
+ "now",
19
+ "random",
20
+ "uuid"
21
+ ];
22
+ /** Marker reaching the AsyncFunction constructor; never invoked. */
23
+ const asyncMarker = async () => void 0;
24
+ /** The async-function constructor; building one compiles without running. */
25
+ const AsyncFunctionCtor = Object.getPrototypeOf(asyncMarker).constructor;
26
+ /**
27
+ * Replaces string literals (single, double, template) and comments with
28
+ * spaces of equal length so token scans never match inside them. Template
29
+ * interpolations `${...}` are KEPT as code (a disallowed import inside an
30
+ * interpolation must still be caught). Regex literals are not stripped:
31
+ * a regex containing a banned word may false-positive, which errs on the
32
+ * rejecting side for machine-generated source.
33
+ */
34
+ function blankLiterals(source) {
35
+ const out = source.split("");
36
+ const blank = (index) => {
37
+ if (out[index] !== "\n") out[index] = " ";
38
+ };
39
+ const templateStack = [];
40
+ let i = 0;
41
+ let mode = "code";
42
+ while (i < source.length) {
43
+ const ch = source[i];
44
+ const next = source[i + 1];
45
+ if (mode === "code") {
46
+ if (ch === "'") {
47
+ mode = "single";
48
+ blank(i);
49
+ } else if (ch === "\"") {
50
+ mode = "double";
51
+ blank(i);
52
+ } else if (ch === "`") {
53
+ mode = "template";
54
+ blank(i);
55
+ } else if (ch === "/" && next === "/") {
56
+ mode = "line";
57
+ blank(i);
58
+ } else if (ch === "/" && next === "*") {
59
+ mode = "block";
60
+ blank(i);
61
+ } else if (ch === "}" && templateStack.length > 0) {
62
+ templateStack.pop();
63
+ mode = "template";
64
+ blank(i);
65
+ }
66
+ } else if (mode === "single" || mode === "double") {
67
+ if (ch === "\\") {
68
+ blank(i);
69
+ i += 1;
70
+ if (i < source.length) blank(i);
71
+ i += 1;
72
+ continue;
73
+ }
74
+ if (mode === "single" && ch === "'" || mode === "double" && ch === "\"") mode = "code";
75
+ blank(i);
76
+ } else if (mode === "template") {
77
+ if (ch === "\\") {
78
+ blank(i);
79
+ i += 1;
80
+ if (i < source.length) blank(i);
81
+ i += 1;
82
+ continue;
83
+ }
84
+ if (ch === "$" && next === "{") {
85
+ templateStack.push(true);
86
+ blank(i);
87
+ i += 1;
88
+ blank(i);
89
+ i += 1;
90
+ mode = "code";
91
+ continue;
92
+ }
93
+ if (ch === "`") mode = "code";
94
+ blank(i);
95
+ } else if (mode === "line") if (ch === "\n") mode = "code";
96
+ else blank(i);
97
+ else {
98
+ if (ch === "*" && next === "/") {
99
+ blank(i);
100
+ i += 1;
101
+ blank(i);
102
+ mode = "code";
103
+ i += 1;
104
+ continue;
105
+ }
106
+ blank(i);
107
+ }
108
+ i += 1;
109
+ }
110
+ return out.join("");
111
+ }
112
+ function positionAt(source, index) {
113
+ let line = 1;
114
+ let column = 1;
115
+ for (let i = 0; i < index && i < source.length; i += 1) if (source[i] === "\n") {
116
+ line += 1;
117
+ column = 1;
118
+ } else column += 1;
119
+ return {
120
+ line,
121
+ column
122
+ };
123
+ }
124
+ const DYNAMIC_IMPORT = /^import\s*\(\s*(['"`])([^'"`]*)\1\s*\)/;
125
+ function scanImports(source, blanked, allowImports) {
126
+ const diagnostics = [];
127
+ const word = /\b(import|require|export)\b/g;
128
+ for (let match = word.exec(blanked); match !== null; match = word.exec(blanked)) {
129
+ const token = match[1];
130
+ const at = positionAt(source, match.index);
131
+ if (token === "require") {
132
+ const tail = blanked.slice(match.index + token.length);
133
+ if (/^\s*\(/.test(tail)) diagnostics.push({
134
+ ruleId: "no-require",
135
+ message: "require() is not available in the sandbox; the dialect has no module access",
136
+ ...at
137
+ });
138
+ continue;
139
+ }
140
+ if (token === "export") {
141
+ diagnostics.push({
142
+ ruleId: "no-export",
143
+ message: "export declarations are not part of the sandbox dialect; return a value instead",
144
+ ...at
145
+ });
146
+ continue;
147
+ }
148
+ const original = source.slice(match.index);
149
+ const dynamic = DYNAMIC_IMPORT.exec(original);
150
+ if (dynamic === null) {
151
+ diagnostics.push({
152
+ ruleId: "no-import",
153
+ message: "import is not available in the sandbox dialect (static imports, import.meta, and non-literal dynamic specifiers are always rejected)",
154
+ ...at
155
+ });
156
+ continue;
157
+ }
158
+ const specifier = dynamic[2];
159
+ if (!allowImports.includes(specifier)) diagnostics.push({
160
+ ruleId: "disallowed-import",
161
+ message: `import('${specifier}') is not in allowImports (allowed: ${allowImports.length === 0 ? "none" : allowImports.join(", ")})`,
162
+ ...at
163
+ });
164
+ }
165
+ return diagnostics;
166
+ }
167
+ /**
168
+ * Validates and compiles planner-generated source into a CompiledWorkflow
169
+ * (docs/06, 8.3). The source is an async function body over the sandbox
170
+ * globals; its `return` value is the workflow result. The compiled form is
171
+ * pure data (the source is evaluated only inside the worker sandbox);
172
+ * machine scripts run under errorPolicy 'lenient' (docs/06, Appendix A).
173
+ */
174
+ function compileScript(source, o) {
175
+ const allowImports = o?.allowImports ?? [];
176
+ const diagnostics = [];
177
+ if (typeof source !== "string" || source.trim() === "") throw new ScriptRejected("compileScript: source must be a non-empty string", { data: { diagnostics: [{
178
+ ruleId: "empty-source",
179
+ message: "source is empty"
180
+ }] } });
181
+ const blanked = blankLiterals(source);
182
+ diagnostics.push(...scanImports(source, blanked, allowImports));
183
+ try {
184
+ new AsyncFunctionCtor(...SANDBOX_GLOBALS, source);
185
+ } catch (error) {
186
+ diagnostics.push({
187
+ ruleId: "syntax",
188
+ message: error instanceof Error ? error.message : String(error)
189
+ });
190
+ }
191
+ if (diagnostics.length > 0) throw new ScriptRejected(`compileScript: source rejected with ${String(diagnostics.length)} diagnostic(s): ` + diagnostics.map((d) => d.ruleId).join(", "), { data: { diagnostics: diagnostics.map((d) => ({ ...d })) } });
192
+ return {
193
+ kind: "compiled-workflow",
194
+ name: "compiled",
195
+ source,
196
+ errorPolicy: "lenient"
197
+ };
198
+ }
199
+ /** Typed accessor for the diagnostics carried on a ScriptRejected. */
200
+ function scriptDiagnosticsOf(error) {
201
+ return error.data?.diagnostics ?? [];
202
+ }
203
+ //#endregion
204
+ export { compileScript as n, scriptDiagnosticsOf as r, SANDBOX_GLOBALS as t };
@@ -0,0 +1,153 @@
1
+ import { CompiledWorkflow, Ctx, Engine, InMemoryStore, JournalEntry, Json, ModelSpec, RunHandle, ScriptRejected, ScriptRunner } from "@rulvar/core";
2
+
3
+ //#region src/compile.d.ts
4
+ /**
5
+ * The exact curated sandbox global set, in docs order (docs/06, 8.2).
6
+ * The worker binds the ctx methods as bare globals under these names and
7
+ * the API card teaches exactly this list.
8
+ */
9
+ declare const SANDBOX_GLOBALS: readonly string[];
10
+ /** One machine-readable compileScript diagnostic (docs/02, ScriptRejected row). */
11
+ interface ScriptDiagnostic {
12
+ ruleId: string;
13
+ message: string;
14
+ line?: number;
15
+ column?: number;
16
+ }
17
+ interface CompileScriptOptions {
18
+ /** Dynamic-import specifiers permitted in the source; default [] (none). */
19
+ allowImports?: string[];
20
+ }
21
+ /**
22
+ * Validates and compiles planner-generated source into a CompiledWorkflow
23
+ * (docs/06, 8.3). The source is an async function body over the sandbox
24
+ * globals; its `return` value is the workflow result. The compiled form is
25
+ * pure data (the source is evaluated only inside the worker sandbox);
26
+ * machine scripts run under errorPolicy 'lenient' (docs/06, Appendix A).
27
+ */
28
+ declare function compileScript(source: string, o?: CompileScriptOptions): CompiledWorkflow;
29
+ /** Typed accessor for the diagnostics carried on a ScriptRejected. */
30
+ declare function scriptDiagnosticsOf(error: ScriptRejected): ScriptDiagnostic[];
31
+ //#endregion
32
+ //#region src/api-card.d.ts
33
+ /** Renders the sandbox-dialect API card; pure and byte-stable. */
34
+ declare function apiCard(): string;
35
+ //#endregion
36
+ //#region src/plan.d.ts
37
+ /** One repair-loop diagnostic: lint and compile findings share the shape. */
38
+ interface PlanDiagnostic {
39
+ ruleId: string;
40
+ message: string;
41
+ line?: number;
42
+ column?: number;
43
+ severity: "error" | "warning";
44
+ }
45
+ interface PlanOptions {
46
+ /** The planner model; otherwise the chain resolves role 'plan'. */
47
+ model?: ModelSpec;
48
+ /** Registered profile names to advertise; default: every profile. */
49
+ profiles?: string[];
50
+ /** Self-repair rounds from JSON diagnostics; default 3 (Appendix A). */
51
+ repairRounds?: number;
52
+ }
53
+ interface PlanResult {
54
+ source: string;
55
+ workflow: CompiledWorkflow;
56
+ /** Diagnostics of the ACCEPTED draft: advisories only, never errors. */
57
+ lint: PlanDiagnostic[];
58
+ }
59
+ /** The deterministic planner runId: one goal, one journal (docs/06, 9.2). */
60
+ declare function planRunIdOf(goal: string): string;
61
+ /**
62
+ * The model may fence the script; the extractor takes the first fenced
63
+ * block when one exists, else the whole reply, and is deterministic.
64
+ */
65
+ declare function extractScript(reply: string): string;
66
+ /**
67
+ * Lints a script BODY with the workflows preset plus compileScript.
68
+ * The body is wrapped in an async function for parsing (top-level
69
+ * return/await are legal in the dialect); reported lines shift back so
70
+ * they index into the body source.
71
+ */
72
+ declare function lintScript(source: string): {
73
+ diagnostics: PlanDiagnostic[];
74
+ errors: PlanDiagnostic[];
75
+ workflow?: CompiledWorkflow;
76
+ };
77
+ declare function plan(engine: Engine, goal: string, o?: PlanOptions): Promise<PlanResult>;
78
+ /**
79
+ * plan-then-run in one call (docs/06, section 9; amended during M6-T05:
80
+ * the composition is async because planning itself is a run).
81
+ */
82
+ declare function runPlanned(engine: Engine, goal: string, args?: Json): Promise<RunHandle<unknown>>;
83
+ //#endregion
84
+ //#region src/cassettes.d.ts
85
+ /** The M3-convention cassette normalization: wall clock and spans only. */
86
+ declare function normalizeCassetteEntries(entries: readonly JournalEntry[]): JournalEntry[];
87
+ declare const SANDBOX_DETERMINISM_RUN_ID = "m6-sandbox-determinism";
88
+ /** A script exercising agents, parallel, step, and every seeded shim. */
89
+ declare const SANDBOX_DETERMINISM_SOURCE: string;
90
+ /**
91
+ * One fresh sandbox-determinism run on a fresh store; two invocations
92
+ * with the same worker produce byte-identical normalized journals (the
93
+ * cassette assertion). The adapter factory keeps @rulvar/testing out of
94
+ * the planner's dependency graph.
95
+ */
96
+ declare function runSandboxDeterminism(options: {
97
+ workerUrl: URL;
98
+ makeAdapter: () => unknown;
99
+ modelRef: string;
100
+ }): Promise<JournalEntry[]>;
101
+ declare const SELF_REPAIR_GOAL = "m6 cassette: summarize the corpus";
102
+ /** The failing first draft: bare Date.now trips rulvar/no-bare-date. */
103
+ declare const SELF_REPAIR_BAD_DRAFT: string;
104
+ /** The repaired draft the fake planner returns once diagnostics arrive. */
105
+ declare const SELF_REPAIR_GOOD_DRAFT: string;
106
+ declare const SELF_REPAIR_RUN_ID: string;
107
+ /**
108
+ * One planner-self-repair run: the first draft fails lint, the JSON
109
+ * diagnostics ride the repair prompt, the second draft compiles. Returns
110
+ * the normalized planning journal plus the plan result.
111
+ */
112
+ declare function runPlannerSelfRepair(options: {
113
+ makeAdapter: () => unknown;
114
+ modelRef: string;
115
+ store?: InMemoryStore;
116
+ seedEntries?: JournalEntry[];
117
+ }): Promise<{
118
+ entries: JournalEntry[];
119
+ planned: PlanResult;
120
+ engine: Engine;
121
+ }>;
122
+ /** The cassette file shape shared with the M3 sets. */
123
+ interface M6CassetteFixture {
124
+ id: string;
125
+ note: string;
126
+ entries: JournalEntry[];
127
+ extra?: Json;
128
+ }
129
+ //#endregion
130
+ //#region src/sandbox-runner.d.ts
131
+ declare const DEFAULT_SANDBOX_TIMEOUT_MS = 3e5;
132
+ declare const DEFAULT_SANDBOX_MEMORY_MB = 512;
133
+ interface WorkerSandboxRunnerOptions {
134
+ /** Wall-clock ceiling for one execution; default 300000 (Appendix A). */
135
+ timeoutMs?: number;
136
+ /** Worker old-generation heap ceiling; default 512 (Appendix A). */
137
+ memoryMb?: number;
138
+ /**
139
+ * The worker entry module; defaults to the built sandbox-worker.js next
140
+ * to this module. Tests running from source point at the built dist.
141
+ */
142
+ workerUrl?: URL;
143
+ }
144
+ /** Accepts CompiledWorkflow ONLY: feeding a closure is a type error (docs/06, 8). */
145
+ declare class WorkerSandboxRunner implements ScriptRunner {
146
+ private readonly timeoutMs;
147
+ private readonly memoryMb;
148
+ private readonly workerUrl;
149
+ constructor(options?: WorkerSandboxRunnerOptions);
150
+ execute<A, R>(wf: CompiledWorkflow, ctx: Ctx<never>, args: A): Promise<R>;
151
+ }
152
+ //#endregion
153
+ export { type CompileScriptOptions, DEFAULT_SANDBOX_MEMORY_MB, DEFAULT_SANDBOX_TIMEOUT_MS, type M6CassetteFixture, type PlanDiagnostic, type PlanOptions, type PlanResult, SANDBOX_DETERMINISM_RUN_ID, SANDBOX_DETERMINISM_SOURCE, SANDBOX_GLOBALS, SELF_REPAIR_BAD_DRAFT, SELF_REPAIR_GOAL, SELF_REPAIR_GOOD_DRAFT, SELF_REPAIR_RUN_ID, type ScriptDiagnostic, WorkerSandboxRunner, type WorkerSandboxRunnerOptions, apiCard, compileScript, extractScript, lintScript, normalizeCassetteEntries, plan, planRunIdOf, runPlanned, runPlannerSelfRepair, runSandboxDeterminism, scriptDiagnosticsOf };
package/dist/index.js ADDED
@@ -0,0 +1,398 @@
1
+ import { n as compileScript, r as scriptDiagnosticsOf, t as SANDBOX_GLOBALS } from "./compile-CfWgGVyz.js";
2
+ import { ConfigError, InMemoryStore, SandboxError, ScriptRejected, createEngine, createSandboxBridge, defineWorkflow, toJournalValue } from "@rulvar/core";
3
+ import { createHash } from "node:crypto";
4
+ import { Linter } from "eslint";
5
+ import { toJsonDiagnostics, workflowsConfig } from "eslint-plugin-rulvar";
6
+ import { MessageChannel, Worker } from "node:worker_threads";
7
+ //#region src/api-card.ts
8
+ /**
9
+ * The API card (M6-T04): teaches the planner model EXACTLY the sandbox
10
+ * dialect and global set (docs/06, sections 8.2 and 8.3). The card is a
11
+ * pure constant, byte-stable across runs; plan() (M6-T05) composes it
12
+ * with profileCard(registry) and the goal. The usage examples are
13
+ * distilled from the runnable examples/ corpus (M5-T09).
14
+ */
15
+ const CARD = [
16
+ "You write ONE JavaScript async-function BODY (the workflow script).",
17
+ "It runs in a deterministic sandbox. The `return` value is the workflow result.",
18
+ "",
19
+ "Available globals (the COMPLETE list; nothing else exists):",
20
+ "- agent(prompt, opts?) -> Promise<value>: one subagent call.",
21
+ " opts (JSON only): { agentType?, model?, effort?, schema?, tools?, onError?, label?, key?, estCost?, limits?, escalation?, fallback?, result? }",
22
+ " - schema: a JSON Schema LITERAL (never a library value); the result is the validated object.",
23
+ " - tools: an array of registered profile NAMES (strings only).",
24
+ " - onError: 'throw' | 'null' (default 'null'; a failed call yields null and the loss is recorded).",
25
+ " - model: a string; agentType: a registered profile name from the profile card.",
26
+ "- parallel(fns, opts?) -> Promise<values[]>: concurrent branches; fns is an array of async functions.",
27
+ " opts: { settle?: true } returns settled outcomes instead of throwing on the first failure.",
28
+ "- pipeline(items, ...stageFns, opts?) -> Promise<results[]>: streams items through stages.",
29
+ " opts: { onItemError?: 'drop' | 'throw' | 'collect' } (default 'drop').",
30
+ "- step(label, fn, opts?) -> Promise<json>: journals a computation so it never re-runs on resume.",
31
+ " opts: { deps?: json[], key?: string }. fn must return JSON.",
32
+ "- phase(name, fn) -> Promise<value>: cosmetic grouping for progress and cost reports.",
33
+ "- log(level, msg, data?): telemetry; level is 'debug' | 'info' | 'warn' | 'error'.",
34
+ "- budget.spent() and budget.remaining(): ASYNC here; always `await budget.spent()`.",
35
+ "- workflow(name, args?, opts?) -> Promise<value>: runs a REGISTERED child workflow by name.",
36
+ "- awaitExternal(key, opts?) -> Promise<value>: suspends until an operator provides the value.",
37
+ " opts: { schema?, prompt? }.",
38
+ "- now() -> number, random(key?) -> number, uuid() -> string: deterministic seeded shims.",
39
+ "",
40
+ "Hard rules:",
41
+ "- No import, require, or export. No fetch. No process. No Node APIs.",
42
+ "- Date.now() and Math.random() ARE the seeded shims; still prefer now() and random().",
43
+ "- Never put functions inside option objects; options are pure JSON.",
44
+ "- Policies are declarative JSON rule tables; ladders are JSON.",
45
+ "- Identical calls with identical arguments journal as ONE result; pass { key } to repeat deliberately.",
46
+ "",
47
+ "Patterns (from the runnable corpus):",
48
+ "- Adversarial panel:",
49
+ " const votes = await parallel([() => agent('refute: ' + claim), () => agent('refute: ' + claim, { key: 'second-skeptic' })]);",
50
+ "- Judge over drafts:",
51
+ " const drafts = await parallel(angles.map((a) => () => agent('draft from angle ' + a)));",
52
+ " const winner = await agent('pick the best draft: ' + JSON.stringify(drafts), { schema: { type: 'object', properties: { index: { type: 'integer' } }, required: ['index'], additionalProperties: false } });",
53
+ "- Fold results without re-paying:",
54
+ " const digest = await step('fold', () => drafts.join(' | '));"
55
+ ].join("\n");
56
+ /** Renders the sandbox-dialect API card; pure and byte-stable. */
57
+ function apiCard() {
58
+ return CARD;
59
+ }
60
+ //#endregion
61
+ //#region src/plan.ts
62
+ /**
63
+ * The plan agent and the self-repair loop (M6-T05): mode (b), the
64
+ * flagship hybrid (docs/06, section 9.2). plan() asks a planner model
65
+ * (role 'plan') to write a script against the API card and the profile
66
+ * card, lints it with eslint-plugin-rulvar, self-repairs up to
67
+ * repairRounds rounds from the JSON diagnostics, and compiles the
68
+ * accepted draft with compileScript. runPlanned composes plan-then-run.
69
+ *
70
+ * Determinism: the planner conversation itself is an ordinary journaled
71
+ * run whose runId derives from the goal, so re-planning the same goal
72
+ * against the same store REPLAYS the unchanged prefix for free
73
+ * (invariant I1; the M6-T05 acceptance).
74
+ */
75
+ /** The deterministic planner runId: one goal, one journal (docs/06, 9.2). */
76
+ function planRunIdOf(goal) {
77
+ return `plan-${createHash("sha256").update(goal, "utf8").digest("hex").slice(0, 24)}`;
78
+ }
79
+ /**
80
+ * The model may fence the script; the extractor takes the first fenced
81
+ * block when one exists, else the whole reply, and is deterministic.
82
+ */
83
+ function extractScript(reply) {
84
+ return (/```(?:[a-zA-Z]*)?\n([\s\S]*?)```/.exec(reply)?.[1] ?? reply).trim();
85
+ }
86
+ /**
87
+ * Lints a script BODY with the workflows preset plus compileScript.
88
+ * The body is wrapped in an async function for parsing (top-level
89
+ * return/await are legal in the dialect); reported lines shift back so
90
+ * they index into the body source.
91
+ */
92
+ function lintScript(source) {
93
+ const diagnostics = [];
94
+ const linter = new Linter();
95
+ const wrapped = `async function rulvarWorkflowBody() {\n${source}\n}\n`;
96
+ const messages = linter.verify(wrapped, [{ languageOptions: {
97
+ ecmaVersion: 2024,
98
+ sourceType: "module"
99
+ } }, workflowsConfig], { filename: "workflow-body.js" });
100
+ for (const lint of toJsonDiagnostics(messages)) {
101
+ const diagnostic = {
102
+ ruleId: lint.ruleId,
103
+ message: lint.message,
104
+ severity: lint.severity,
105
+ line: Math.max(1, lint.line - 1),
106
+ column: lint.column
107
+ };
108
+ diagnostics.push(diagnostic);
109
+ }
110
+ let workflow;
111
+ try {
112
+ workflow = compileScript(source);
113
+ } catch (error) {
114
+ if (!(error instanceof ScriptRejected)) throw error;
115
+ for (const rejection of scriptDiagnosticsOf(error)) diagnostics.push({
116
+ ruleId: `compile/${rejection.ruleId}`,
117
+ message: rejection.message,
118
+ severity: "error",
119
+ ...rejection.line === void 0 ? {} : { line: rejection.line },
120
+ ...rejection.column === void 0 ? {} : { column: rejection.column }
121
+ });
122
+ }
123
+ const errors = diagnostics.filter((diagnostic) => diagnostic.severity === "error");
124
+ const result = {
125
+ diagnostics,
126
+ errors
127
+ };
128
+ if (errors.length === 0 && workflow !== void 0) result.workflow = workflow;
129
+ return result;
130
+ }
131
+ function draftPrompt(goal, cards) {
132
+ return [
133
+ "Write the workflow script body for this goal.",
134
+ "",
135
+ `GOAL: ${goal}`,
136
+ "",
137
+ cards,
138
+ "",
139
+ "Reply with ONLY the script body (a fenced code block is accepted)."
140
+ ].join("\n");
141
+ }
142
+ function repairPrompt(goal, source, diagnostics) {
143
+ return [
144
+ "Your previous workflow script was rejected by the linter.",
145
+ "",
146
+ `GOAL: ${goal}`,
147
+ "",
148
+ "PREVIOUS SCRIPT:",
149
+ source,
150
+ "",
151
+ "DIAGNOSTICS (JSON):",
152
+ JSON.stringify(diagnostics, null, 2),
153
+ "",
154
+ "Fix every error and reply with ONLY the corrected script body."
155
+ ].join("\n");
156
+ }
157
+ /** The planner conversation as an ordinary journaled workflow. */
158
+ const planWorkflow = defineWorkflow({ name: "rulvar-plan" }, async (ctx, args) => {
159
+ let source = "";
160
+ let lastDiagnostics = [];
161
+ for (let round = 0; round <= args.repairRounds; round += 1) {
162
+ const prompt = round === 0 ? draftPrompt(args.goal, args.cards) : repairPrompt(args.goal, source, lastDiagnostics);
163
+ const reply = await ctx.agent(prompt, {
164
+ role: "plan",
165
+ onError: "throw",
166
+ ...args.model === void 0 ? {} : { model: args.model }
167
+ });
168
+ source = extractScript(String(reply));
169
+ const outcome = lintScript(source);
170
+ if (outcome.errors.length === 0) return {
171
+ source,
172
+ lint: outcome.diagnostics,
173
+ rounds: round + 1
174
+ };
175
+ lastDiagnostics = outcome.diagnostics;
176
+ }
177
+ throw new ScriptRejected(`plan: self-repair exhausted after ${String(args.repairRounds + 1)} drafts; the last diagnostics ride in data`, { data: { diagnostics: lastDiagnostics.map((d) => ({ ...d })) } });
178
+ });
179
+ async function plan(engine, goal, o) {
180
+ const repairRounds = o?.repairRounds ?? 3;
181
+ const args = {
182
+ goal,
183
+ cards: [
184
+ apiCard(),
185
+ "",
186
+ engine.profileCard(o?.profiles)
187
+ ].join("\n"),
188
+ repairRounds,
189
+ ...o?.model === void 0 ? {} : { model: o.model }
190
+ };
191
+ const outcome = await engine.resume(planRunIdOf(goal), planWorkflow, { args }).result;
192
+ if (outcome.status !== "ok" || outcome.value === void 0) {
193
+ const wire = outcome.error;
194
+ throw new ScriptRejected(`plan: the planner run settled '${outcome.status}'${wire === void 0 ? "" : `: ${wire.message}`}`, { data: {
195
+ status: outcome.status,
196
+ ...wire === void 0 ? {} : { error: wire }
197
+ } });
198
+ }
199
+ const value = outcome.value;
200
+ const workflow = compileScript(value.source);
201
+ return {
202
+ source: value.source,
203
+ workflow,
204
+ lint: value.lint
205
+ };
206
+ }
207
+ /**
208
+ * plan-then-run in one call (docs/06, section 9; amended during M6-T05:
209
+ * the composition is async because planning itself is a run).
210
+ */
211
+ async function runPlanned(engine, goal, args) {
212
+ const planned = await plan(engine, goal);
213
+ return engine.run(planned.workflow, args ?? null);
214
+ }
215
+ //#endregion
216
+ //#region src/sandbox-runner.ts
217
+ /**
218
+ * WorkerSandboxRunner (M6-T02): the mandatory runner for machine-generated
219
+ * scripts, mode (b). Owns the worker lifecycle and the dedicated
220
+ * MessageChannel; every primitive call is served by the core sandbox
221
+ * bridge against the canonical run ctx (docs/06, 8.2).
222
+ *
223
+ * Port lifecycle: one channel per run; the worker end rides the init
224
+ * transfer list; the host end is referenced while the worker computes and
225
+ * unreferenced while every worker frame is blocked on a host call, so a
226
+ * suspended run lets the process exit (docs/06, 2.7) and a computing
227
+ * worker keeps it alive. Breaching timeoutMs or memoryMb terminates the
228
+ * worker and the run completes with outcome 'error' carrying the typed
229
+ * SandboxError (docs/02, error taxonomy).
230
+ */
231
+ const DEFAULT_SANDBOX_TIMEOUT_MS = 3e5;
232
+ const DEFAULT_SANDBOX_MEMORY_MB = 512;
233
+ /** Accepts CompiledWorkflow ONLY: feeding a closure is a type error (docs/06, 8). */
234
+ var WorkerSandboxRunner = class {
235
+ timeoutMs;
236
+ memoryMb;
237
+ workerUrl;
238
+ constructor(options) {
239
+ this.timeoutMs = options?.timeoutMs ?? 3e5;
240
+ this.memoryMb = options?.memoryMb ?? 512;
241
+ this.workerUrl = options?.workerUrl ?? new URL("./sandbox-worker.js", import.meta.url);
242
+ }
243
+ async execute(wf, ctx, args) {
244
+ if (wf.kind !== "compiled-workflow") throw new ConfigError("WorkerSandboxRunner executes CompiledWorkflow values only; closures run in process (docs/06, section \"Script runners\")");
245
+ const argsJson = toJournalValue(args ?? null, "sandbox workflow args");
246
+ const channel = new MessageChannel();
247
+ const worker = new Worker(this.workerUrl, { resourceLimits: { maxOldGenerationSizeMb: this.memoryMb } });
248
+ const bridge = createSandboxBridge(ctx, { post: (message) => channel.port1.postMessage(message) });
249
+ return new Promise((resolve, reject) => {
250
+ let settled = false;
251
+ const cleanup = () => {
252
+ clearTimeout(timer);
253
+ bridge.close();
254
+ channel.port1.close();
255
+ worker.terminate();
256
+ };
257
+ const settleOk = (value) => {
258
+ if (!settled) {
259
+ settled = true;
260
+ cleanup();
261
+ resolve(value);
262
+ }
263
+ };
264
+ const settleErr = (error) => {
265
+ if (!settled) {
266
+ settled = true;
267
+ cleanup();
268
+ reject(error);
269
+ }
270
+ };
271
+ const timer = setTimeout(() => {
272
+ settleErr(new SandboxError(`sandbox timeoutMs ${String(this.timeoutMs)} breached; the worker was terminated`, { data: {
273
+ reason: "timeout",
274
+ limit: this.timeoutMs
275
+ } }));
276
+ }, this.timeoutMs);
277
+ channel.port1.on("message", (message) => {
278
+ if (message.t === "done") {
279
+ settleOk(message.value);
280
+ return;
281
+ }
282
+ if (message.t === "fail") {
283
+ const wire = message.error;
284
+ const rebuilt = new Error(wire.message);
285
+ rebuilt.name = wire.code;
286
+ settleErr(rebuilt);
287
+ return;
288
+ }
289
+ if (message.t === "state") if (message.busy === true) channel.port1.ref();
290
+ else channel.port1.unref();
291
+ bridge.onMessage(message);
292
+ });
293
+ worker.on("error", (error) => {
294
+ if (error.code === "ERR_WORKER_OUT_OF_MEMORY") {
295
+ settleErr(new SandboxError(`sandbox memoryMb ${String(this.memoryMb)} breached; the worker was terminated`, { data: {
296
+ reason: "memory",
297
+ limit: this.memoryMb
298
+ } }));
299
+ return;
300
+ }
301
+ settleErr(error);
302
+ });
303
+ worker.on("exit", (code) => {
304
+ if (!settled) settleErr(new ConfigError(`sandbox worker exited unexpectedly with code ${String(code)}`));
305
+ });
306
+ worker.unref();
307
+ worker.postMessage({
308
+ t: "init",
309
+ port: channel.port2,
310
+ source: wf.source,
311
+ args: argsJson,
312
+ runId: bridge.runId
313
+ }, [channel.port2]);
314
+ });
315
+ }
316
+ };
317
+ //#endregion
318
+ //#region src/cassettes.ts
319
+ /** The M3-convention cassette normalization: wall clock and spans only. */
320
+ function normalizeCassetteEntries(entries) {
321
+ return entries.map((entry) => ({
322
+ ...entry,
323
+ spanId: "fixture-span",
324
+ startedAt: "2026-02-01T00:00:00.000Z",
325
+ ...entry.endedAt === void 0 ? {} : { endedAt: "2026-02-01T00:00:00.000Z" }
326
+ }));
327
+ }
328
+ const SANDBOX_DETERMINISM_RUN_ID = "m6-sandbox-determinism";
329
+ /** A script exercising agents, parallel, step, and every seeded shim. */
330
+ const SANDBOX_DETERMINISM_SOURCE = [
331
+ "const first = await agent('probe alpha');",
332
+ "const both = await parallel([() => agent('branch zero'), () => agent('branch one')]);",
333
+ "const folded = await step('fold', () => [first, ...both].join(' | '), { deps: [now()] });",
334
+ "log('info', 'progress ' + random());",
335
+ "return { folded, id: uuid(), at: now() };"
336
+ ].join("\n");
337
+ /**
338
+ * One fresh sandbox-determinism run on a fresh store; two invocations
339
+ * with the same worker produce byte-identical normalized journals (the
340
+ * cassette assertion). The adapter factory keeps @rulvar/testing out of
341
+ * the planner's dependency graph.
342
+ */
343
+ async function runSandboxDeterminism(options) {
344
+ const store = new InMemoryStore();
345
+ const engine = createEngine({
346
+ adapters: [options.makeAdapter()],
347
+ stores: { journal: store },
348
+ defaults: { routing: {
349
+ loop: options.modelRef,
350
+ extract: options.modelRef
351
+ } },
352
+ runners: { sandbox: new WorkerSandboxRunner({ workerUrl: options.workerUrl }) }
353
+ });
354
+ const workflow = compileScript(SANDBOX_DETERMINISM_SOURCE);
355
+ const outcome = await engine.run(workflow, null, { runId: SANDBOX_DETERMINISM_RUN_ID }).result;
356
+ if (outcome.status !== "ok") throw new Error(`sandbox-determinism run settled '${outcome.status}'`);
357
+ return normalizeCassetteEntries(await store.load(SANDBOX_DETERMINISM_RUN_ID));
358
+ }
359
+ const SELF_REPAIR_GOAL = "m6 cassette: summarize the corpus";
360
+ /** The failing first draft: bare Date.now trips rulvar/no-bare-date. */
361
+ const SELF_REPAIR_BAD_DRAFT = [
362
+ "```js",
363
+ "const startedAt = Date.now();",
364
+ "const summary = await agent('summarize the corpus');",
365
+ "return { startedAt, summary };",
366
+ "```"
367
+ ].join("\n");
368
+ /** The repaired draft the fake planner returns once diagnostics arrive. */
369
+ const SELF_REPAIR_GOOD_DRAFT = [
370
+ "```js",
371
+ "const startedAt = now();",
372
+ "const summary = await agent('summarize the corpus');",
373
+ "return { startedAt, summary };",
374
+ "```"
375
+ ].join("\n");
376
+ const SELF_REPAIR_RUN_ID = planRunIdOf(SELF_REPAIR_GOAL);
377
+ /**
378
+ * One planner-self-repair run: the first draft fails lint, the JSON
379
+ * diagnostics ride the repair prompt, the second draft compiles. Returns
380
+ * the normalized planning journal plus the plan result.
381
+ */
382
+ async function runPlannerSelfRepair(options) {
383
+ const store = options.store ?? new InMemoryStore();
384
+ if (options.seedEntries !== void 0) for (const entry of options.seedEntries) await store.append(SELF_REPAIR_RUN_ID, entry);
385
+ const engine = createEngine({
386
+ adapters: [options.makeAdapter()],
387
+ stores: { journal: store },
388
+ defaults: { routing: { plan: options.modelRef } }
389
+ });
390
+ const planned = await plan(engine, SELF_REPAIR_GOAL);
391
+ return {
392
+ entries: normalizeCassetteEntries(await store.load(SELF_REPAIR_RUN_ID)),
393
+ planned,
394
+ engine
395
+ };
396
+ }
397
+ //#endregion
398
+ export { DEFAULT_SANDBOX_MEMORY_MB, DEFAULT_SANDBOX_TIMEOUT_MS, SANDBOX_DETERMINISM_RUN_ID, SANDBOX_DETERMINISM_SOURCE, SANDBOX_GLOBALS, SELF_REPAIR_BAD_DRAFT, SELF_REPAIR_GOAL, SELF_REPAIR_GOOD_DRAFT, SELF_REPAIR_RUN_ID, WorkerSandboxRunner, apiCard, compileScript, extractScript, lintScript, normalizeCassetteEntries, plan, planRunIdOf, runPlanned, runPlannerSelfRepair, runSandboxDeterminism, scriptDiagnosticsOf };
@@ -0,0 +1,21 @@
1
+ import { Json, WireError } from "@rulvar/core";
2
+
3
+ //#region src/sandbox-worker.d.ts
4
+ /** Runner-to-worker bootstrap message; the port rides the transfer list. */
5
+ interface SandboxInitMessage {
6
+ t: "init";
7
+ port: unknown;
8
+ source: string;
9
+ args: Json;
10
+ runId: string;
11
+ }
12
+ /** Worker lifecycle messages the RUNNER consumes (the bridge never sees them). */
13
+ type SandboxLifecycleMessage = {
14
+ t: "done";
15
+ value: Json;
16
+ } | {
17
+ t: "fail";
18
+ error: WireError;
19
+ };
20
+ //#endregion
21
+ export { SandboxInitMessage, SandboxLifecycleMessage };
@@ -0,0 +1,295 @@
1
+ import { t as SANDBOX_GLOBALS } from "./compile-CfWgGVyz.js";
2
+ import { NonSerializableValueError, toJournalValue } from "@rulvar/core";
3
+ import { createHash } from "node:crypto";
4
+ import { parentPort } from "node:worker_threads";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ //#region src/sandbox-worker.ts
7
+ /**
8
+ * The worker half of the sandbox contract (M6-T02): evaluates a
9
+ * CompiledWorkflow source inside a worker_threads realm with the curated
10
+ * global scope and proxies every primitive call as JSON-RPC over the
11
+ * dedicated MessagePort to the host bridge (docs/06, 8.2).
12
+ *
13
+ * Determinism: now, random, uuid, and the Date.now/Math.random realm
14
+ * replacements all draw from ONE seeded stream (seed = sha256(runId)), so
15
+ * two runs with the same runId generate identical values; every generated
16
+ * value is mirrored to the host and journaled as an ordinary kind 'rand'
17
+ * entry (match-first on resume). import, fetch, and process are absent
18
+ * from the scope; values crossing the boundary are validated
19
+ * journal-compatible JSON, never raw structured clone.
20
+ */
21
+ function wireOf(thrown) {
22
+ if (thrown instanceof NonSerializableValueError) return thrown.toWire();
23
+ if (thrown instanceof Error) return {
24
+ code: thrown.name !== "" && thrown.name !== "Error" ? thrown.name : "error",
25
+ message: thrown.message,
26
+ retryable: false
27
+ };
28
+ return {
29
+ code: "error",
30
+ message: String(thrown),
31
+ retryable: false
32
+ };
33
+ }
34
+ /** mulberry32 over the first four bytes of sha256(runId). */
35
+ function seededStream(runId) {
36
+ const digest = createHash("sha256").update(runId, "utf8").digest();
37
+ let state = digest.readUInt32LE(0) ^ digest.readUInt32LE(4);
38
+ return () => {
39
+ state = state + 1831565813 | 0;
40
+ let t = state;
41
+ t = Math.imul(t ^ t >>> 15, t | 1);
42
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
43
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
44
+ };
45
+ }
46
+ function main(port, init) {
47
+ const next = seededStream(init.runId);
48
+ let logicalNow = 17e11 + Math.floor(next() * 1e9);
49
+ const frameToken = new AsyncLocalStorage();
50
+ const currentToken = () => frameToken.getStore() ?? 0;
51
+ let busyFrames = 0;
52
+ let lastReportedBusy;
53
+ const reportState = () => {
54
+ const busy = busyFrames > 0;
55
+ if (busy !== lastReportedBusy) {
56
+ lastReportedBusy = busy;
57
+ post({
58
+ t: "state",
59
+ busy
60
+ });
61
+ }
62
+ };
63
+ const enterFrame = () => {
64
+ busyFrames += 1;
65
+ reportState();
66
+ };
67
+ const exitFrame = () => {
68
+ busyFrames -= 1;
69
+ reportState();
70
+ };
71
+ function post(message) {
72
+ port.postMessage(message);
73
+ }
74
+ let nextCallId = 1;
75
+ const pendingCalls = /* @__PURE__ */ new Map();
76
+ function callHost(method, params) {
77
+ const validated = toJournalValue(params, `sandbox ${method} params`);
78
+ const id = nextCallId;
79
+ nextCallId += 1;
80
+ const token = currentToken();
81
+ return new Promise((resolve, reject) => {
82
+ pendingCalls.set(id, {
83
+ resolve,
84
+ reject
85
+ });
86
+ exitFrame();
87
+ post({
88
+ t: "call",
89
+ id,
90
+ token,
91
+ method,
92
+ params: validated
93
+ });
94
+ });
95
+ }
96
+ let nextFnId = 1;
97
+ const fns = /* @__PURE__ */ new Map();
98
+ const registerFns = (candidates, what) => candidates.map((candidate) => {
99
+ if (typeof candidate !== "function") throw new TypeError(`${what} accepts functions only`);
100
+ const fnId = nextFnId;
101
+ nextFnId += 1;
102
+ fns.set(fnId, candidate);
103
+ return fnId;
104
+ });
105
+ const mirrorRand = (subtype, value) => {
106
+ post({
107
+ t: "rand",
108
+ token: currentToken(),
109
+ subtype,
110
+ value
111
+ });
112
+ };
113
+ const shimNow = () => {
114
+ logicalNow += 1 + Math.floor(next() * 7);
115
+ const value = logicalNow;
116
+ mirrorRand("now", value);
117
+ return value;
118
+ };
119
+ const shimRandom = () => {
120
+ const value = next();
121
+ mirrorRand("random", value);
122
+ return value;
123
+ };
124
+ const shimUuid = () => {
125
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
126
+ for (let i = 0; i < 16; i += 1) bytes[i] = Math.floor(next() * 256);
127
+ bytes[6] = bytes[6] & 15 | 64;
128
+ bytes[8] = bytes[8] & 63 | 128;
129
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
130
+ const value = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
131
+ mirrorRand("uuid", value);
132
+ return value;
133
+ };
134
+ Date.now = shimNow;
135
+ Math.random = shimRandom;
136
+ Reflect.set(globalThis, "fetch", void 0);
137
+ Reflect.set(globalThis, "process", void 0);
138
+ const sandboxGlobals = {
139
+ agent: (prompt, opts) => callHost("agent", {
140
+ prompt,
141
+ ...opts === void 0 ? {} : { opts }
142
+ }),
143
+ parallel: (tasks, opts) => {
144
+ if (!Array.isArray(tasks)) throw new TypeError("parallel takes an array of functions");
145
+ const fnIds = registerFns(tasks, "parallel");
146
+ return callHost("parallel", opts?.settle === true ? {
147
+ fnIds,
148
+ settle: true
149
+ } : { fnIds });
150
+ },
151
+ pipeline: (items, ...rest) => {
152
+ if (!Array.isArray(items)) throw new TypeError("pipeline takes an items array first");
153
+ const last = rest[rest.length - 1];
154
+ const hasOpts = typeof last === "object" && last !== null;
155
+ const stages = hasOpts ? rest.slice(0, -1) : rest;
156
+ const stageFnIds = registerFns(stages, "pipeline stages");
157
+ const onItemError = hasOpts ? last.onItemError : void 0;
158
+ return callHost("pipeline", {
159
+ items,
160
+ stageFnIds,
161
+ ...onItemError === void 0 ? {} : { onItemError }
162
+ });
163
+ },
164
+ step: (label, fn, opts) => {
165
+ const [fnId] = registerFns([fn], "step");
166
+ const o = opts ?? {};
167
+ return callHost("step", {
168
+ label,
169
+ fnId,
170
+ ...o.deps === void 0 ? {} : { deps: o.deps },
171
+ ...o.key === void 0 ? {} : { key: o.key }
172
+ });
173
+ },
174
+ phase: (name, fn) => {
175
+ const [fnId] = registerFns([fn], "phase");
176
+ return callHost("phase", {
177
+ name,
178
+ fnId
179
+ });
180
+ },
181
+ log: (level, msg, data) => {
182
+ post({
183
+ t: "log",
184
+ token: currentToken(),
185
+ level,
186
+ msg: String(msg),
187
+ ...data === void 0 ? {} : { data: toJournalValue(data, "sandbox log data") }
188
+ });
189
+ },
190
+ budget: {
191
+ spent: () => callHost("budget.spent", {}),
192
+ remaining: () => callHost("budget.remaining", {})
193
+ },
194
+ workflow: (name, args, opts) => callHost("workflow", {
195
+ name,
196
+ ...args === void 0 ? {} : { args },
197
+ ...opts?.key === void 0 ? {} : { key: opts.key }
198
+ }),
199
+ awaitExternal: (key, opts) => {
200
+ const o = opts ?? {};
201
+ return callHost("awaitExternal", {
202
+ key,
203
+ ...o.schema === void 0 ? {} : { schema: o.schema },
204
+ ...o.prompt === void 0 ? {} : { prompt: o.prompt }
205
+ });
206
+ },
207
+ now: shimNow,
208
+ random: (key) => {
209
+ if (key !== void 0 && typeof key !== "string") throw new TypeError("random(key) takes a string discriminator");
210
+ const value = next();
211
+ post({
212
+ t: "rand",
213
+ token: currentToken(),
214
+ subtype: "random",
215
+ value,
216
+ ...key === void 0 ? {} : { key }
217
+ });
218
+ return value;
219
+ },
220
+ uuid: shimUuid
221
+ };
222
+ port.on("message", (raw) => {
223
+ switch (raw.t) {
224
+ case "result": {
225
+ const pending = pendingCalls.get(raw.id);
226
+ pendingCalls.delete(raw.id);
227
+ if (pending !== void 0) {
228
+ enterFrame();
229
+ pending.resolve(raw.value);
230
+ }
231
+ return;
232
+ }
233
+ case "error": {
234
+ const pending = pendingCalls.get(raw.id);
235
+ pendingCalls.delete(raw.id);
236
+ if (pending !== void 0) {
237
+ enterFrame();
238
+ const rebuilt = new Error(raw.error.message);
239
+ rebuilt.name = raw.error.code;
240
+ pending.reject(rebuilt);
241
+ }
242
+ return;
243
+ }
244
+ case "thunk:run": {
245
+ const fn = fns.get(raw.fnId);
246
+ enterFrame();
247
+ (async () => {
248
+ try {
249
+ if (fn === void 0) throw new Error(`unknown sandbox thunk ${String(raw.fnId)}`);
250
+ const value = await frameToken.run(raw.token, () => fn(...raw.args));
251
+ post({
252
+ t: "thunk:result",
253
+ id: raw.id,
254
+ value: toJournalValue(value ?? null, "sandbox thunk result")
255
+ });
256
+ } catch (thrown) {
257
+ post({
258
+ t: "thunk:error",
259
+ id: raw.id,
260
+ error: wireOf(thrown)
261
+ });
262
+ } finally {
263
+ exitFrame();
264
+ }
265
+ })();
266
+ return;
267
+ }
268
+ default: return;
269
+ }
270
+ });
271
+ const AsyncFunctionCtor = Object.getPrototypeOf(shimAsyncMarker).constructor;
272
+ enterFrame();
273
+ (async () => {
274
+ try {
275
+ post({
276
+ t: "done",
277
+ value: toJournalValue(await new AsyncFunctionCtor(...SANDBOX_GLOBALS, init.source)(...SANDBOX_GLOBALS.map((name) => sandboxGlobals[name])) ?? null, "sandbox script result")
278
+ });
279
+ } catch (thrown) {
280
+ post({
281
+ t: "fail",
282
+ error: wireOf(thrown)
283
+ });
284
+ } finally {
285
+ exitFrame();
286
+ }
287
+ })();
288
+ }
289
+ /** Marker reaching the AsyncFunction constructor; never invoked. */
290
+ const shimAsyncMarker = async () => void 0;
291
+ parentPort?.once("message", (init) => {
292
+ main(init.port, init);
293
+ });
294
+ //#endregion
295
+ export {};
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@rulvar/planner",
3
+ "version": "1.0.0",
4
+ "description": "rulvar flagship hybrid mode: plan agent, compileScript, WorkerSandboxRunner, self-repair loop.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "engines": {
8
+ "node": ">=22.12.0"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "sideEffects": false,
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "dependencies": {
25
+ "eslint": "^9.39.4",
26
+ "@rulvar/core": "1.0.0",
27
+ "eslint-plugin-rulvar": "1.0.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^22.20.0",
31
+ "tsdown": "^0.22.3",
32
+ "typescript": "~6.0.3",
33
+ "@rulvar/testing": "1.0.0"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/o-stepper/rulvar.git",
38
+ "directory": "packages/planner"
39
+ },
40
+ "homepage": "https://rulvar.com",
41
+ "bugs": {
42
+ "url": "https://github.com/o-stepper/rulvar/issues"
43
+ },
44
+ "scripts": {
45
+ "build": "tsdown",
46
+ "typecheck": "tsc --noEmit",
47
+ "lint": "eslint .",
48
+ "pack-check": "publint --pack pnpm && attw --pack . --profile esm-only"
49
+ }
50
+ }