@evoke-build/evoke 0.6.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 2026 Radhi Guennichi
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.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ evoke
2
+ Copyright 2026 Radhi Guennichi
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # @evoke-build/evoke
2
+
3
+ You invoke a function; you evoke a reflex. A reflex is a small program a classifier selects and calls. The SDK
4
+ loads a project of reflexes, decides what an input asks for, and runs it. The classifier is
5
+ [Jev](https://typesafe.ai), TypeSafe AI's System One model. It answers closed questions with calibrated
6
+ probabilities. `jev()` reaches it through TypeSafe AI's own API and `openjev()` through OpenJEV, an independent
7
+ service; the core is bound to neither. The rules run in `core.wasm`, the same core as the `evoke` CLI. The SDK adds files, the network
8
+ and a process.
9
+
10
+ Six things to learn, in order: `reflex()` · `load()` · `handle()` · a `Decision` · `run()` · `replay()`. Each is
11
+ explained in full in [the manual](https://evoke.build/manual/sdk/getting-started.html).
12
+
13
+ ## The first hour
14
+
15
+ ```ts
16
+ // app.ts · npm i @evoke-build/evoke · export TYPESAFE_API_KEY=… · node app.ts "timer for 10 minutes"
17
+ import { load, reflex } from "@evoke-build/evoke"
18
+ import { jev } from "@evoke-build/evoke/jev"
19
+
20
+ const timer = reflex({
21
+ description: "Start a countdown timer.",
22
+ effect: "write",
23
+ confirm: "Start a {duration} timer?",
24
+ args: { duration: { ask: "How long?", pick: "duration" } },
25
+ examples: { "timer for 10 minutes": { duration: "10 minutes" } },
26
+ }, async ({ duration }) => { // duration: number — seconds, typed from the manifest
27
+ setTimeout(() => console.log("ring"), duration * 1000)
28
+ return `ringing in ${duration} s`
29
+ })
30
+
31
+ const project = await load({ reflexes: { timer }, adapter: jev() })
32
+
33
+ const handled = await project.handle(process.argv[2] ?? "", {
34
+ confirm: async d => { console.log(d.prompt.template); return true }, // "Start a 10 minutes timer?"
35
+ ask: async d => ({ duration: "10 minutes" }), // d.missing says what is missing and why
36
+ })
37
+ console.log(handled.outcome === "ran" ? handled.result.text : handled.outcome)
38
+ ```
39
+
40
+ A `Decision` is a union. Narrow it by `outcome`, one of `run`, `confirm`, `ask` and `abstain`, then by `reflex`.
41
+ It carries `args` as the classifier read them, `values` as the body receives them, `call` as one line,
42
+ `confidence`, the `prompt` of a confirm, the `missing` of an ask, and the `trace` of every adapter call.
43
+
44
+ ## With files
45
+
46
+ `evoke add evoke-build/reflexes` next to the app writes `evoke.toml`, `evoke.lock` and `evoke.d.ts`. Overlays and
47
+ vocabularies under the same root tune the wording. That includes a reflex handed as code.
48
+
49
+ ```ts
50
+ import type { Reflexes } from "./evoke.d.ts"
51
+
52
+ const project = await load<Reflexes>({ root: import.meta.dirname }) // the adapter evoke.toml names
53
+ const tenant = project.with({ vocab: { rooms: await db.rooms(user) } }) // a tenant's words, a tenant's plan; milliseconds
54
+ const d = await tenant.decide("kill the lights in the den")
55
+ if (d.outcome === "run" && d.reflex === "lights") console.log(d.values.room, d.values.state) // typed by evoke.d.ts
56
+ ```
57
+
58
+ ## Tests
59
+
60
+ ```ts
61
+ import { replay } from "@evoke-build/evoke/testing"
62
+
63
+ const record = process.env.RECORD ? jev() : undefined // RECORD=1 asks Jev once and writes the file
64
+ const project = await load({ reflexes: { timer }, adapter: replay("answers.toml", { record }) })
65
+ ```
66
+
67
+ Every run after the first is offline, and always gives the same answers. The file is the CLI's own `answers.toml`.
68
+
69
+ ## Errors
70
+
71
+ Every error ends in what to do: `lights: vocabulary "rooms" is empty → evoke vocab rooms add <word> "<meaning>"`.
72
+ `DiagnosticError` is something a person fixes. `FaultError` is the adapter. `FailureError` is a body or the
73
+ machine. Each carries the structured value, and the fixing line as `command`. Aborts reject with the signal's own
74
+ reason.
package/core.wasm ADDED
Binary file
@@ -0,0 +1,24 @@
1
+ import type { Gate, Limits, Question, Raw, Request, State } from "./types.ts";
2
+ /** An adapter: what it declares, and one stateless `answer` over any subset of a plan's questions. */
3
+ export interface Adapter {
4
+ /** Opaque; changes whenever answers could. */
5
+ readonly id: string;
6
+ readonly limits?: Limits | undefined;
7
+ /** The floors, each meaning P(correct); none means every decision confirms. */
8
+ readonly gate?: Gate | undefined;
9
+ /** The plan digest a recording stands for; a project over another plan refuses it. */
10
+ readonly plan?: string | undefined;
11
+ /** A distribution per question asked, keys among those offered; `signal` aborts at the deadline. */
12
+ answer(state: State, questions: Record<string, Question>, signal: AbortSignal): Promise<Raw>;
13
+ }
14
+ /** One call as the SDK saw it: which adapter, how many questions, how long. */
15
+ export interface Trace {
16
+ adapter: string;
17
+ questions: number;
18
+ ms: number;
19
+ }
20
+ /** The adapter asked within the deadline, its answers timed. */
21
+ export declare function answered(adapter: Adapter, request: Request, deadline: number, signal: AbortSignal | undefined, invoked: string): Promise<{
22
+ raw: Raw;
23
+ trace: Trace;
24
+ }>;
@@ -0,0 +1,74 @@
1
+ // Who answers: the contract every adapter meets — one object, the design's — and what the SDK does around one
2
+ // call: the deadline as a signal joined with the caller's, the answer raced against it so an adapter that ignores
3
+ // it still ends, the call timed, a throw that is not evoke's own turned into a transport fault. In: an adapter,
4
+ // a request, a deadline, a signal. Out: the raw answers with one trace entry, or a FaultError; the caller's abort
5
+ // passes through as its own reason.
6
+ import { faulted } from "./core.js";
7
+ import { EvokeError, FaultError } from "./errors.js";
8
+ /** The adapter asked within the deadline, its answers timed. */
9
+ export async function answered(adapter, request, deadline, signal, invoked) {
10
+ signal?.throwIfAborted();
11
+ // A referenced timer, so a hung adapter that holds no handle cannot let the process exit before the deadline.
12
+ const timeout = new AbortController();
13
+ const timer = setTimeout(() => timeout.abort(new DOMException(`no answer within ${deadline} ms`, "TimeoutError")), deadline);
14
+ const own = signal === undefined ? timeout.signal : AbortSignal.any([signal, timeout.signal]);
15
+ const started = performance.now();
16
+ try {
17
+ const raw = await Promise.race([adapter.answer(request.state, request.questions, own), aborted(own)]);
18
+ const ms = Math.round(performance.now() - started);
19
+ return { raw: checked(raw, request, invoked), trace: { adapter: adapter.id, questions: Object.keys(request.questions).length, ms } };
20
+ }
21
+ catch (error) {
22
+ if (signal?.aborted)
23
+ throw signal.reason;
24
+ // An adapter that could not name the call renders its fault again with it; one that knew better stands.
25
+ if (error instanceof FaultError)
26
+ throw error.command === "" ? faulted(error.fault, invoked) : error;
27
+ if (error instanceof EvokeError)
28
+ throw error;
29
+ const message = timeout.signal.aborted
30
+ ? `did not answer within ${deadline} ms`
31
+ : error instanceof Error
32
+ ? error.message
33
+ : String(error);
34
+ throw faulted({ type: "transport", message }, invoked);
35
+ }
36
+ finally {
37
+ clearTimeout(timer);
38
+ }
39
+ }
40
+ /** The answer as the core reads it — a distribution per question, every probability a finite number — or the
41
+ * adapter's fault, named before the boundary: `NaN` and `undefined` cross as nothing, and would read as a bug. */
42
+ function checked(raw, request, invoked) {
43
+ const first = Object.keys(request.questions)[0] ?? "route";
44
+ const malformed = (question, message) => faulted({ type: "malformed", question, message }, invoked);
45
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
46
+ throw malformed(first, `the answer is ${kind(raw)}, not an object`);
47
+ for (const [question, answer] of Object.entries(raw)) {
48
+ if (answer === null || typeof answer !== "object" || Array.isArray(answer))
49
+ throw malformed(question, `${kind(answer)}, not a distribution`);
50
+ for (const [key, p] of Object.entries(answer)) {
51
+ if (typeof p !== "number" || !Number.isFinite(p))
52
+ throw malformed(question, `${key} is ${kind(p)}, not a probability`);
53
+ }
54
+ }
55
+ return raw;
56
+ }
57
+ function kind(value) {
58
+ if (value === null)
59
+ return "null";
60
+ if (Array.isArray(value))
61
+ return "an array";
62
+ if (typeof value === "number")
63
+ return Number.isNaN(value) ? "NaN" : "infinite";
64
+ return typeof value;
65
+ }
66
+ /** A promise that rejects with the signal's reason, at once when it is already aborted. */
67
+ function aborted(signal) {
68
+ return new Promise((_, reject) => {
69
+ if (signal.aborted)
70
+ reject(signal.reason);
71
+ else
72
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
73
+ });
74
+ }
@@ -0,0 +1,34 @@
1
+ import type { Contained, Facts, NeedsKey, Place, Policy, Program } from "./types.ts";
2
+ /** What the machine lacks that the declaration names: a path, or a program `PATH` does not hold. */
3
+ export type Missing = {
4
+ place: Place;
5
+ key: NeedsKey;
6
+ } | {
7
+ program: Program;
8
+ };
9
+ /** The policy and the facts a body runs under. */
10
+ export interface Layers {
11
+ policy: Policy;
12
+ facts: Facts;
13
+ }
14
+ /** Whether this machine holds a whole declaration: macOS through Seatbelt, when `sandbox-exec` is there; Linux
15
+ * through Node's layer alone, which holds a file body's files and programs, and the network from Node 25, never
16
+ * what a program reaches, and holds nothing of an argv body. */
17
+ export declare function status(body: "file" | "argv"): Contained;
18
+ /** A private temporary folder for one run, under the system's, readable by its owner alone, by its real path;
19
+ * removed after the run. */
20
+ export declare function scratch(): {
21
+ path: string;
22
+ remove(): void;
23
+ };
24
+ /** The facts the core's rules need: each declared path's real form and kind, each program's place, and for a
25
+ * file body this process's own runtime; a path or a program the machine lacks is the miss, before anything runs. */
26
+ export declare function facts(policy: Policy, body: "file" | "argv", bodyDir: string, tmp: string): Facts | Missing;
27
+ /** Node's flags for a file body, from the core. */
28
+ export declare function flags(layers: Layers): string[];
29
+ /** The command that runs a program under the layers: on macOS `sandbox-exec -p` with the core's profile in front;
30
+ * on Linux the program itself, Node's flags being the one layer the SDK has. */
31
+ export declare function under(program: string, args: string[], layers: Layers): {
32
+ file: string;
33
+ args: string[];
34
+ };
@@ -0,0 +1,146 @@
1
+ // The layers around a body in the SDK: Node's permission flags on both systems, and on macOS `sandbox-exec -p`
2
+ // with the core's profile in front of the command; on Linux the kernel layer needs native code the SDK does not
3
+ // carry, so the status says so. The facts the core's rules take, gathered here: this process's runtime as it runs
4
+ // and whether it holds the network, each declared path's real form and kind, each program's place on PATH and the
5
+ // interpreters it runs through, a private temporary folder for the run. In: a policy, the body's directory. Out:
6
+ // the facts or what is missing, the command that runs a program under the layers, the status.
7
+ import { accessSync, closeSync, constants, mkdtempSync, openSync, readSync, realpathSync, rmSync, statSync } from "node:fs";
8
+ import { homedir, tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { call } from "./core.js";
11
+ const PLATFORM = process.platform === "linux" ? "linux" : "macos";
12
+ const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
13
+ /** Whether this runtime's permission model holds the network: from Node 25, the first to know `--allow-net`. */
14
+ const HOLDS_NETWORK = process.allowedNodeEnvironmentFlags.has("--allow-net");
15
+ /** Whether this machine holds a whole declaration: macOS through Seatbelt, when `sandbox-exec` is there; Linux
16
+ * through Node's layer alone, which holds a file body's files and programs, and the network from Node 25, never
17
+ * what a program reaches, and holds nothing of an argv body. */
18
+ export function status(body) {
19
+ if (PLATFORM === "linux") {
20
+ if (body === "argv")
21
+ return { type: "none", why: "an argv body runs under no layer here; the kernel's needs native code the package does not carry" };
22
+ if (HOLDS_NETWORK)
23
+ return { type: "partial", why: "Node holds files, programs and the network; what a program reaches is not held" };
24
+ return { type: "partial", why: "Node holds files and programs; the network and what a program reaches are not held" };
25
+ }
26
+ return runs(SANDBOX_EXEC) ? { type: "full" } : { type: "none", why: "sandbox-exec is missing" };
27
+ }
28
+ /** A private temporary folder for one run, under the system's, readable by its owner alone, by its real path;
29
+ * removed after the run. */
30
+ export function scratch() {
31
+ const path = realpathSync(mkdtempSync(join(tmpdir(), "evoke-")));
32
+ return { path, remove: () => rmSync(path, { recursive: true, force: true }) };
33
+ }
34
+ /** The facts the core's rules need: each declared path's real form and kind, each program's place, and for a
35
+ * file body this process's own runtime; a path or a program the machine lacks is the miss, before anything runs. */
36
+ export function facts(policy, body, bodyDir, tmp) {
37
+ const found = {};
38
+ for (const [key, places] of [
39
+ ["reads", policy.reads ?? []],
40
+ ["writes", policy.writes ?? []],
41
+ ]) {
42
+ for (const place of places) {
43
+ let stats;
44
+ try {
45
+ stats = statSync(place.path);
46
+ }
47
+ catch {
48
+ return { place, key };
49
+ }
50
+ found[place.path] = { real: realpathSync(place.path), dir: stats.isDirectory() };
51
+ }
52
+ }
53
+ const programs = {};
54
+ for (const program of policy.runs ?? []) {
55
+ const path = locate(program);
56
+ if (path === undefined)
57
+ return { program };
58
+ programs[program] = executable(path);
59
+ }
60
+ return {
61
+ platform: PLATFORM,
62
+ ...(body === "argv" ? {} : { runtime: own() }),
63
+ body_dir: bodyDir,
64
+ tmp,
65
+ home: homedir(),
66
+ ...(Object.keys(found).length === 0 ? {} : { found }),
67
+ ...(Object.keys(programs).length === 0 ? {} : { programs }),
68
+ };
69
+ }
70
+ /** Node's flags for a file body, from the core. */
71
+ export function flags(layers) {
72
+ return call("contain.node_flags", layers);
73
+ }
74
+ /** The command that runs a program under the layers: on macOS `sandbox-exec -p` with the core's profile in front;
75
+ * on Linux the program itself, Node's flags being the one layer the SDK has. */
76
+ export function under(program, args, layers) {
77
+ if (PLATFORM === "macos")
78
+ return { file: SANDBOX_EXEC, args: ["-p", call("contain.seatbelt", layers), program, ...args] };
79
+ return { file: program, args };
80
+ }
81
+ /** This process's runtime, which runs every file body: its program, and whether it holds the network. */
82
+ function own() {
83
+ return { ...executable(process.execPath), ...(HOLDS_NETWORK ? { holds_network: true } : {}) };
84
+ }
85
+ /** A program by its absolute path, or the first executable of its name on `PATH`. */
86
+ function locate(program) {
87
+ if (program.startsWith("/"))
88
+ return runs(program) ? program : undefined;
89
+ for (const dir of (process.env.PATH ?? "").split(":")) {
90
+ if (dir === "")
91
+ continue;
92
+ const candidate = join(dir, program);
93
+ if (runs(candidate))
94
+ return candidate;
95
+ }
96
+ return undefined;
97
+ }
98
+ function runs(path) {
99
+ try {
100
+ accessSync(path, constants.X_OK);
101
+ return statSync(path).isFile();
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ }
107
+ /** A program as the kernel runs it: its real path, and on macOS the interpreters a script runs through — its
108
+ * shebang's, and the program `env` hands over to, found on `PATH`. */
109
+ function executable(path) {
110
+ const real = realpathSync(path);
111
+ const interpreters = PLATFORM === "macos" ? viaShebang(real) : [];
112
+ return { path: real, ...(interpreters.length === 0 ? {} : { interpreters }) };
113
+ }
114
+ function viaShebang(program) {
115
+ let first;
116
+ try {
117
+ first = head(program);
118
+ }
119
+ catch {
120
+ return [];
121
+ }
122
+ if (!first.startsWith("#!"))
123
+ return [];
124
+ const [interpreter, argument] = (first.slice(2).split("\n")[0] ?? "").trim().split(/\s+/);
125
+ if (interpreter === undefined || !interpreter.startsWith("/"))
126
+ return [];
127
+ const interpreters = [realpathSync(interpreter)];
128
+ if (interpreter.endsWith("/env") && argument !== undefined && !argument.startsWith("-")) {
129
+ const handed = locate(argument);
130
+ if (handed !== undefined)
131
+ interpreters.push(realpathSync(handed));
132
+ }
133
+ return interpreters;
134
+ }
135
+ /** A program's first bytes, where a script names its interpreter: never the whole of a binary. */
136
+ function head(program) {
137
+ const fd = openSync(program, "r");
138
+ try {
139
+ const buffer = Buffer.alloc(256);
140
+ const read = readSync(fd, buffer, 0, buffer.length, 0);
141
+ return buffer.toString("latin1", 0, read);
142
+ }
143
+ finally {
144
+ closeSync(fd);
145
+ }
146
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { DiagnosticError, FaultError, type Problem } from "./errors.ts";
2
+ import type { Op, Ops } from "./ops.ts";
3
+ import type { Diagnostic, Fault, Fix, Result } from "./types.ts";
4
+ /** What the op table answers: the result, the function's own error, or a bug in the call the SDK made. */
5
+ export type Reply = {
6
+ ok: unknown;
7
+ } | {
8
+ err: unknown;
9
+ } | {
10
+ bug: string;
11
+ };
12
+ /** One op on one input: the raw reply. A trap in the core is a bug in evoke, thrown as one. A lone surrogate in
13
+ * any string — `JSON.stringify` writes it as an escape, and no Rust string can hold it — crosses as U+FFFD. */
14
+ export declare function reply(op: string, input: object): Reply;
15
+ /** An op's value: what it answers under `ok`, the Result unwrapped where the function returns one. */
16
+ export type Ok<O extends Op> = Ops[O]["output"] extends Result<infer T, infer _E> ? T : Ops[O]["output"];
17
+ /**
18
+ * One op, typed: the value, or the op's own error thrown as the CLI would print it — a `DiagnosticError` for
19
+ * diagnostics, a `FaultError` for a fault. `invoked` names the SDK call for a fix that says to try again.
20
+ */
21
+ export declare function call<O extends Op>(op: O, input: Ops[O]["input"], invoked?: string): Ok<O>;
22
+ /** The command that fixes a problem, rendered by the core. */
23
+ export declare function command(fix: Fix, invoked?: string): string;
24
+ /** A diagnostic with its command rendered. */
25
+ export declare function problem(diagnostic: Diagnostic, invoked?: string): Problem;
26
+ /** Diagnostics over something given in code — a manifest, words, a gate — where the core's `evoke check`, meant
27
+ * for a file, cannot apply: the fix is the call itself. */
28
+ export declare function fromCode(diagnostics: readonly Diagnostic[], invoked: string): DiagnosticError;
29
+ /** A fault as the error it is, its words and command rendered by the core. */
30
+ export declare function faulted(fault: Fault, invoked?: string): FaultError;
31
+ /** Why a text is no local or vocabulary name by the core's grammar, or nothing when it is one. */
32
+ export declare function misnamed(text: string, kind: "local" | "vocab"): string | undefined;
33
+ /** A bug in evoke — never a user error. */
34
+ export declare function bug(message: string): Error;