piroboros 0.1.0 → 0.3.2

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 (52) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/NOTICE +12 -0
  3. package/README.md +91 -167
  4. package/dist/chat/compactor.js +5 -4
  5. package/dist/chat/log.js +3 -2
  6. package/dist/chat/plan.js +1 -0
  7. package/dist/chat/tree.js +1 -0
  8. package/dist/chat/turn.js +0 -15
  9. package/dist/conclave/pipeline.js +222 -19
  10. package/dist/config.js +127 -12
  11. package/dist/diff.js +90 -0
  12. package/dist/durable.js +69 -4
  13. package/dist/guard.js +170 -14
  14. package/dist/learn.js +938 -0
  15. package/dist/main.js +3 -9
  16. package/dist/memory/akashic/tools.js +25 -28
  17. package/dist/memory/mnemosia/conflicts.js +0 -4
  18. package/dist/memory/mnemosia/orchestrator.js +1 -11
  19. package/dist/memory/mnemosia/policy.js +0 -3
  20. package/dist/memory/mnemosia/rank.js +0 -4
  21. package/dist/memory/mnemosia/rerank.js +3 -30
  22. package/dist/memory/mnemosia/rollback.js +1 -149
  23. package/dist/memory/mnemosia/tokens.js +1 -11
  24. package/dist/memory/mnemosia/tools.js +0 -10
  25. package/dist/memory/mnemosia/types.js +0 -2
  26. package/dist/runtime.js +80 -11
  27. package/dist/search.js +25 -12
  28. package/dist/shell.js +2 -2
  29. package/dist/telemetry.js +84 -0
  30. package/dist/tui/app.js +17 -3
  31. package/dist/tui/commands.js +6 -2
  32. package/dist/tui/settings.js +4 -1
  33. package/dist/tui/thinking/parse.js +0 -3
  34. package/dist/ws/apply.js +817 -0
  35. package/dist/ws/cas.js +144 -0
  36. package/dist/ws/confine.js +194 -0
  37. package/dist/ws/docker.js +151 -0
  38. package/dist/ws/git.js +162 -0
  39. package/dist/ws/lww.js +48 -0
  40. package/dist/ws/merge.js +129 -0
  41. package/dist/ws/workspace.js +1596 -0
  42. package/dist/ws/wsl.js +259 -0
  43. package/docs/conclave.md +35 -0
  44. package/docs/configuration.md +54 -0
  45. package/docs/development.md +25 -0
  46. package/docs/interface.md +33 -0
  47. package/docs/memory.md +11 -0
  48. package/docs/privacy.md +15 -0
  49. package/docs/tools.md +62 -0
  50. package/docs/web.md +38 -0
  51. package/package.json +23 -10
  52. package/settings.json.example +4 -1
package/dist/ws/cas.js ADDED
@@ -0,0 +1,144 @@
1
+ import { createHash } from "node:crypto";
2
+ import { DatabaseSync } from "node:sqlite";
3
+ import zlib from "node:zlib";
4
+ // The content-addressed history store behind Workspaces: objects by sha256, commits and entries of each Workspace,
5
+ // merge records with the snapshot of every live file a merge displaces. One node:sqlite file, one connection per
6
+ // process (the home lock makes one process per store). The decision model it serves is ported from LayerFS (MIT; NOTICE).
7
+ /** Objects per put batch. */
8
+ export const OPEN_BATCH = 500;
9
+ /** Raw bytes a put batch holds before it is inserted; bounds memory at about twice this (the bytes and their compressed form). */
10
+ export const BATCH_BYTES = 64 * 1024 * 1024;
11
+ /** The largest live file a merge snapshots. */
12
+ export const SNAPSHOT_MAX = 64 * 1024 * 1024;
13
+ /** An object younger than this is never collected, referenced or not, so puts whose rows are not written yet survive a GC. */
14
+ export const GC_GRACE = 60 * 60 * 1000;
15
+ export const KEEP_RUNS = 3;
16
+ const SCHEMA = `
17
+ CREATE TABLE IF NOT EXISTS objects(id TEXT PRIMARY KEY, size INTEGER, codec TEXT, data BLOB, at INTEGER);
18
+ CREATE TABLE IF NOT EXISTS commits(id INTEGER PRIMARY KEY, workspace INTEGER, parent INTEGER, kind TEXT, at INTEGER, note TEXT);
19
+ CREATE TABLE IF NOT EXISTS entries("commit" INTEGER, path TEXT, object TEXT, hash TEXT, size INTEGER, kind TEXT);
20
+ CREATE INDEX IF NOT EXISTS entries_path ON entries("commit", path);
21
+ CREATE INDEX IF NOT EXISTS entries_object ON entries(object);
22
+ CREATE TABLE IF NOT EXISTS workspaces(id INTEGER PRIMARY KEY, key TEXT UNIQUE, project TEXT, project_dev TEXT, project_ino TEXT, mode TEXT, git_head TEXT, refs TEXT, plan TEXT, base INTEGER, head INTEGER, folder TEXT, ws_caseless INTEGER, live_caseless INTEGER, confine TEXT, state TEXT, hold TEXT, hold_detail TEXT, conv INTEGER, created INTEGER);
23
+ CREATE TABLE IF NOT EXISTS ws_stat(workspace INTEGER, path TEXT, size INTEGER, mtime INTEGER, hash TEXT, PRIMARY KEY(workspace, path));
24
+ CREATE TABLE IF NOT EXISTS conflicts(workspace INTEGER, path TEXT, kind TEXT, ours TEXT, theirs TEXT, PRIMARY KEY(workspace, path));
25
+ CREATE TABLE IF NOT EXISTS merges(id INTEGER PRIMARY KEY, workspace INTEGER, run TEXT, project TEXT, state TEXT, at INTEGER, pass INTEGER, summary TEXT, cleaned INTEGER);
26
+ CREATE INDEX IF NOT EXISTS merges_run ON merges(workspace, run);
27
+ CREATE TABLE IF NOT EXISTS merge_paths(merge INTEGER, seq INTEGER, path TEXT, from_path TEXT, op TEXT, pre TEXT, post TEXT, mode INTEGER, PRIMARY KEY(merge, seq));
28
+ CREATE TABLE IF NOT EXISTS projects(project TEXT PRIMARY KEY, nested TEXT, at INTEGER);
29
+ `;
30
+ /** Hash and compress outside any transaction. zstd is experimental in Node, so a missing or failing zstd stores the bytes raw. */
31
+ export function pack(bytes) {
32
+ const id = createHash("sha256").update(bytes).digest("hex");
33
+ try {
34
+ const z = zlib.zstdCompressSync(bytes, { params: { [zlib.constants.ZSTD_c_compressionLevel]: 1 } });
35
+ if (z.length < bytes.length)
36
+ return { id, size: bytes.length, codec: "zstd", data: z };
37
+ }
38
+ catch { /* stored raw */ }
39
+ return { id, size: bytes.length, codec: "raw", data: bytes };
40
+ }
41
+ export class Cas {
42
+ db;
43
+ now;
44
+ /** `now` is injectable so a probe can age objects past GC_GRACE. */
45
+ constructor(path, now = Date.now) {
46
+ this.now = now;
47
+ this.db = new DatabaseSync(path);
48
+ // auto_vacuum is fixed at file creation: set it before any table and before WAL, and fail loudly on a file that has another mode.
49
+ this.db.exec("PRAGMA auto_vacuum = INCREMENTAL");
50
+ const pragma = (name) => Number(this.db.prepare(`PRAGMA ${name}`).get()[name]);
51
+ if (pragma("auto_vacuum") !== 2)
52
+ throw new Error(`workspace store ${path} is not incremental auto_vacuum`);
53
+ this.db.exec("PRAGMA journal_mode = WAL");
54
+ // FULL flushes the WAL at each commit: a merge record and its snapshot are on disk before the first live change they cover.
55
+ this.db.exec("PRAGMA synchronous = FULL");
56
+ if (pragma("synchronous") !== 2)
57
+ throw new Error(`workspace store ${path} is not synchronous=FULL`);
58
+ this.db.exec(SCHEMA);
59
+ // 0.3.1: `cleaned` marks a done merge whose cleanup finished (recover skips it). A store from 0.3.0 gets the column, its done rows read NULL and are cleaned once more.
60
+ if (!this.db.prepare("PRAGMA table_info(merges)").all().some((c) => c.name === "cleaned"))
61
+ this.db.exec("ALTER TABLE merges ADD COLUMN cleaned INTEGER");
62
+ }
63
+ close() {
64
+ this.db.close();
65
+ }
66
+ /**
67
+ * Run `fn` in one transaction (BEGIN IMMEDIATE, COMMIT; a thrown error rolls back and rethrows). `fn` must be
68
+ * synchronous: an await inside would let other chains' statements run inside it. An async function is refused before
69
+ * BEGIN, and a function that returns a promise is rolled back and refused.
70
+ */
71
+ tx(fn) {
72
+ if (fn.constructor.name === "AsyncFunction")
73
+ throw new TypeError("Cas.tx takes a synchronous function");
74
+ this.db.exec("BEGIN IMMEDIATE");
75
+ try {
76
+ const out = fn();
77
+ if (typeof out?.then === "function") {
78
+ out.then(undefined, () => undefined);
79
+ throw new TypeError("Cas.tx function returned a promise; a transaction holds only synchronous calls");
80
+ }
81
+ this.db.exec("COMMIT");
82
+ return out;
83
+ }
84
+ catch (error) {
85
+ try {
86
+ this.db.exec("ROLLBACK");
87
+ }
88
+ catch { /* the failed commit already ended it */ }
89
+ throw error;
90
+ }
91
+ }
92
+ /** Insert packed objects; statements only, so it runs inside `tx` or alone. A put of an id already stored refreshes `at` and writes nothing else. */
93
+ insert(objects) {
94
+ const stmt = this.db.prepare("INSERT INTO objects VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET at = excluded.at");
95
+ const at = this.now();
96
+ for (const o of objects)
97
+ stmt.run(o.id, o.size, o.codec, o.data, at);
98
+ }
99
+ /** Store one object in its own transaction and return its id. */
100
+ put(bytes) {
101
+ const p = pack(bytes);
102
+ this.tx(() => this.insert([p]));
103
+ return p.id;
104
+ }
105
+ /** The bytes of an object, or undefined when it is not stored. */
106
+ get(id) {
107
+ const row = this.db.prepare("SELECT codec, data FROM objects WHERE id = ?").get(id);
108
+ if (!row)
109
+ return undefined;
110
+ return row.codec === "zstd" ? zlib.zstdDecompressSync(row.data) : Buffer.from(row.data);
111
+ }
112
+ /** The ids of the list that have no row in `objects`: one synchronous query, usable inside `tx` or outside it. */
113
+ missing(ids) {
114
+ const rows = this.db.prepare("SELECT value FROM json_each(?) WHERE value NOT IN (SELECT id FROM objects)").all(JSON.stringify(ids));
115
+ return rows.map((r) => r.value);
116
+ }
117
+ /**
118
+ * Drop what no kept record needs, in one transaction. Kept: every Workspace in open, held or conflicted and the newest
119
+ * KEEP_RUNS per project (their commits, entries and conflict objects); the newest done or undone merge per project, every
120
+ * failed record and every non-terminal one (their merge_paths and snapshot objects). An object younger than GC_GRACE is
121
+ * never deleted, referenced or not. Returns the number of objects deleted.
122
+ */
123
+ gc() {
124
+ const keptWs = `SELECT id FROM workspaces WHERE state IN ('open', 'held', 'conflicted')
125
+ OR id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY project ORDER BY created DESC, id DESC) AS rn FROM workspaces) WHERE rn <= ${KEEP_RUNS})`;
126
+ const keptMerges = `SELECT id FROM merges WHERE state IN ('planned', 'writing', 'undoing', 'rollback failed', 'undo failed')
127
+ OR id IN (SELECT MAX(id) FROM merges WHERE state IN ('done', 'undone') GROUP BY project)`;
128
+ return this.tx(() => {
129
+ this.db.exec(`DELETE FROM entries WHERE "commit" IN (SELECT id FROM commits WHERE workspace NOT IN (${keptWs}))`);
130
+ this.db.exec(`DELETE FROM commits WHERE workspace NOT IN (${keptWs})`);
131
+ this.db.exec(`DELETE FROM merge_paths WHERE merge NOT IN (${keptMerges})`);
132
+ const r = this.db.prepare(`DELETE FROM objects WHERE at < ? AND id NOT IN (
133
+ SELECT object FROM entries WHERE object IS NOT NULL
134
+ UNION SELECT pre FROM merge_paths WHERE pre IS NOT NULL
135
+ UNION SELECT ours FROM conflicts WHERE ours IS NOT NULL AND workspace IN (${keptWs})
136
+ UNION SELECT theirs FROM conflicts WHERE theirs IS NOT NULL AND workspace IN (${keptWs}))`).run(this.now() - GC_GRACE);
137
+ return Number(r.changes);
138
+ });
139
+ }
140
+ /** Give free pages back to the file, a slice at a time; run it at an idle moment, never at startup. */
141
+ vacuum(pages) {
142
+ this.db.exec(`PRAGMA incremental_vacuum(${Math.trunc(pages)})`);
143
+ }
144
+ }
@@ -0,0 +1,194 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, posix, resolve } from "node:path";
5
+ import { err, ExecutionError } from "@earendil-works/pi-durable/env";
6
+ import { ShellEnv } from "../durable.js";
7
+ import { checkRead, denyRoots } from "../guard.js";
8
+ import { dockerPick, execDocker } from "./docker.js";
9
+ import { WsRefusal } from "./git.js";
10
+ import { execWsl, SelfTestError, wslDeps, wslPick } from "./wsl.js";
11
+ export const UNCONFINED = "WARNING: shell commands are not confined on this system. Vesperia's commands run in the Workspace folder but can still read and write any path your account can, including your live project.";
12
+ /** Linux refuses one argument over 131,072 bytes counting its NUL (MAX_ARG_STRLEN). */
13
+ export const COMMAND_MAX = 131_071;
14
+ const DOWN = "confinement backend unavailable: ";
15
+ export const within = (root, path) => path === root || path.startsWith(root === "/" ? "/" : `${root}/`);
16
+ export function nativeDeps(cfg, wsRoot) {
17
+ return {
18
+ platform: process.platform, home: cfg.profile ?? homedir(), piroHome: cfg.home, wsRoot, deny: denyRoots(cfg), wsl: process.platform === "win32" ? wslDeps() : undefined,
19
+ allowed: (path) => checkRead(path, undefined, cfg).allowed,
20
+ real: (path) => { try {
21
+ return realpathSync(path);
22
+ }
23
+ catch {
24
+ return undefined;
25
+ } },
26
+ read: (path) => { try {
27
+ return readFileSync(path, "utf8");
28
+ }
29
+ catch {
30
+ return undefined;
31
+ } },
32
+ which: (name) => (process.env.PATH ?? "").split(delimiter).map((dir) => posix.join(dir, name)).find((p) => existsSync(p)),
33
+ run: (program, args, ms = 10_000) => new Promise((done) => execFile(program, args, { timeout: ms, env: { PATH: process.env.PATH ?? "" } }, (e, out, errs) => done({ code: e === null ? 0 : typeof e.code === "number" ? e.code : null, out: `${out}${errs}` }))),
34
+ };
35
+ }
36
+ /**
37
+ * The seccomp filter every bwrap loads (`--seccomp 9`, P27e2): classic BPF, no dependency. `socket` and `socketpair` with domain AF_VSOCK (40, low 32 bits of arg0) give
38
+ * EAFNOSUPPORT (vsock is not namespaced, and the WSL host answers on it), io_uring_setup, io_uring_enter and io_uring_register give EPERM, an arch other than x86_64 or
39
+ * aarch64 and x32 numbers are killed, everything else is allowed. struct seccomp_data: nr at 0, arch at 4, arg0 at 16.
40
+ */
41
+ export function seccompFilter() {
42
+ const ERRNO = 0x00050000, ALLOW = 0x7fff0000, KILL = 0x80000000;
43
+ const i = (code, jt, jf, k) => [code & 0xff, code >> 8, jt, jf, k & 0xff, (k >>> 8) & 0xff, (k >>> 16) & 0xff, k >>> 24];
44
+ const LD = 0x20, JEQ = 0x15, JGT = 0x25, JGE = 0x35, JA = 0x05, RET = 0x06;
45
+ return Buffer.from([
46
+ ...i(LD, 0, 0, 4), ...i(JEQ, 6, 0, 0xC00000B7), ...i(JEQ, 0, 15, 0xC000003E), // 0-2 arch
47
+ ...i(LD, 0, 0, 0), ...i(JGE, 13, 0, 0x40000000), ...i(JEQ, 8, 0, 41), ...i(JEQ, 7, 0, 53), ...i(JA, 0, 0, 3), // 3-7 x86_64 numbers
48
+ ...i(LD, 0, 0, 0), ...i(JEQ, 4, 0, 198), ...i(JEQ, 3, 0, 199), // 8-10 aarch64 numbers
49
+ ...i(JGE, 0, 5, 425), ...i(JGT, 4, 0, 427), ...i(RET, 0, 0, ERRNO | 1), // 11-13 io_uring
50
+ ...i(LD, 0, 0, 16), ...i(JEQ, 0, 1, 40), ...i(RET, 0, 0, ERRNO | 97), ...i(RET, 0, 0, ALLOW), ...i(RET, 0, 0, KILL), // 14-18 AF_VSOCK, allow, kill
51
+ ]);
52
+ }
53
+ /** `exec bwrap args` with the filter on fd 9; a missing or bad fd makes bwrap refuse to start. Every bwrap call site goes through this. */
54
+ export function seccompExec(bwrap, args) {
55
+ const octal = [...seccompFilter()].map((b) => `\\0${b.toString(8).padStart(3, "0")}`).join("");
56
+ return ["bash", "-c", 'exec "${@:2}" 9< <(printf %b "$1")', "bash", octal, bwrap, ...args];
57
+ }
58
+ /**
59
+ * The bwrap arguments for `inner` run in the Workspace `c.ws` from `c.cwd`. Options apply in order: masks first, binds after. A mask
60
+ * path is resolved first; one that does not exist, or lies inside an earlier mask, is dropped. `refused` names needed paths left
61
+ * masked because they lie in a deny root outside every guard.allow folder, or are, or contain, a protected folder. `c.wsl` is bubblewrap in WSL (4.3.4):
62
+ * the Windows-backed mounts are masked, `/init` is emptied, the live objects come in `alt` (already checked and translated), `nm` binds ext4 folders over
63
+ * Workspace folders, `env` is the whole environment and `extra` are more read-only binds.
64
+ */
65
+ export function bwrapArgs(d, c, inner) {
66
+ const masks = [];
67
+ for (const mask of [d.home, "/run", "/var/run", ...(c.wsl?.mounts ?? []), d.piroHome, ...d.deny]) {
68
+ const r = d.real(mask);
69
+ if (r !== undefined && !masks.some((m) => within(m, r)))
70
+ masks.push(r);
71
+ }
72
+ const binds = [];
73
+ const refused = [];
74
+ const protectedRoots = [d.piroHome, d.wsRoot, ...d.deny].map((root) => d.real(root) ?? root);
75
+ const need = (path) => {
76
+ const r = d.real(path);
77
+ if (r === undefined || binds.some(([, dest]) => dest === r))
78
+ return;
79
+ // A path that is, or holds, a mask or a protected root never binds: that would put back what the mask hid.
80
+ const holds = masks.some((m) => within(r, m));
81
+ if (holds || !d.allowed(r) || protectedRoots.some((root) => within(r, root))) {
82
+ if (holds || masks.some((m) => within(m, r)))
83
+ refused.push(path);
84
+ return;
85
+ }
86
+ binds.push([r, r]);
87
+ };
88
+ // The object folders come from the stored record (`c.alt`, built from the live repository), never from the Workspace's own alternates file, which Vesperia can write.
89
+ for (const line of c.wsl?.alt ?? c.alt ?? [])
90
+ if (line.startsWith("/") && posix.basename(d.real(line) ?? "") === "objects")
91
+ need(line);
92
+ const resolv = c.net ? d.real("/etc/resolv.conf") : undefined;
93
+ if (resolv !== undefined && masks.some((m) => within(m, resolv)))
94
+ need(c.wsl === undefined ? posix.dirname(resolv) : resolv);
95
+ // PATH entries under the home: the entry, and its parent only for `<parent>/bin` where the parent is neither the home nor a direct child of it.
96
+ const home = d.real(d.home) ?? d.home;
97
+ for (const entry of c.path.split(":")) {
98
+ const r = entry.startsWith("/") ? d.real(entry) : undefined;
99
+ if (r === undefined || r === home || !within(home, r))
100
+ continue;
101
+ const parent = posix.dirname(r);
102
+ if (posix.basename(r) === "bin" && parent !== home && posix.dirname(parent) !== home)
103
+ need(parent);
104
+ need(r);
105
+ }
106
+ const args = ["--seccomp", "9", "--die-with-parent", "--new-session", "--unshare-all", ...(c.net ? ["--share-net"] : []), "--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp",
107
+ ...masks.flatMap((m) => ["--tmpfs", m]), ...(c.wsl === undefined ? [] : ["--ro-bind", "/dev/null", "/init"]), ...binds.flatMap(([s, t]) => ["--ro-bind", s, t]), ...(c.wsl?.extra ?? []).flatMap((p) => ["--ro-bind", p, p]),
108
+ "--bind", c.ws, c.ws, ...(c.wsl?.nm ?? []).flatMap(([s, t]) => ["--bind", s, t]),
109
+ ...(c.wsl === undefined ? [] : ["--clearenv", ...c.wsl.env.flatMap(([k, v]) => ["--setenv", k, v]), "--unsetenv", "WSL_INTEROP"]), "--chdir", c.cwd, ...inner];
110
+ return { args, refused };
111
+ }
112
+ // Runs inside the sandbox: write and remove a file in the Workspace, no auth.json beside the home, and (network on) a readable resolv.conf.
113
+ const SELF_TEST = 'm="$1/.piroboros-selftest"; : > "$m" || { echo "the Workspace is not writable"; exit 1; }; rm -f "$m"; [ ! -e "$2/auth.json" ] || { echo "auth.json is visible"; exit 1; }; [ "$3" = 0 ] || [ -r /etc/resolv.conf ] || { echo "resolv.conf is not readable"; exit 1; }; command -v perl >/dev/null && { perl -e \'socket(S,40,1,0) and exit 1; exit($!+0==97?0:2)\' || { echo "an AF_VSOCK socket can be created"; exit 1; }; }; true';
114
+ /**
115
+ * Pick the backend for a Workspace folder (4.3.1): Docker first when an image is set (and always for `docker`, which refuses the run when Docker is not usable),
116
+ * then bubblewrap, then none. A failure under `auto` is never a run failure: it gives the next backend, or none plus a warning.
117
+ */
118
+ export async function confineFor(s, d, ws, plan) {
119
+ if (s.confine === "docker" && s.docker === undefined)
120
+ throw new WsRefusal('workspace.confine is "docker" but workspace.docker.image is not set');
121
+ let skipped = "";
122
+ if (s.confine !== "none" && s.docker !== undefined) {
123
+ try {
124
+ return await dockerPick({ network: s.network, distro: s.distro, image: s.docker }, d, ws, plan ?? { places: [], alt: [], project: "", files: 0 });
125
+ }
126
+ catch (error) {
127
+ const why = error instanceof Error ? error.message : String(error);
128
+ if (s.confine === "docker")
129
+ throw new WsRefusal(`workspace.confine is "docker" but ${why}`);
130
+ skipped = why;
131
+ }
132
+ }
133
+ const picked = await confineLocal(s.confine === "docker" ? "auto" : s.confine, s.network, s.distro, d, ws, plan);
134
+ return skipped === "" ? picked : { ...picked, notice: [...picked.notice, `Docker was not used: ${skipped}.`] };
135
+ }
136
+ async function confineLocal(confine, network, distro, d, ws, plan) {
137
+ const s = { confine, network, distro };
138
+ const none = (why, test = false) => ({ confine: { name: "none", why }, label: "none", notice: [test ? `WARNING: confinement failed its self-test (${why}). Shell commands are not confined: Vesperia's commands run in the Workspace folder but can still read and write any path your account can, including your live project.` : `${UNCONFINED} Not used: ${why}.`] });
139
+ if (s.confine === "none")
140
+ return none("workspace.confine is none");
141
+ if (d.platform === "win32" && d.wsl !== undefined) {
142
+ try {
143
+ return await wslPick(s, d, ws, plan ?? { places: [], alt: [], project: "", files: 0 });
144
+ }
145
+ catch (error) {
146
+ return none(error instanceof SelfTestError ? error.message : `bubblewrap in WSL: ${error instanceof Error ? error.message : String(error)}`, error instanceof SelfTestError);
147
+ }
148
+ }
149
+ if (d.platform !== "linux")
150
+ return none(`bubblewrap needs Linux; this is ${d.platform}`);
151
+ const bwrap = d.which("bwrap");
152
+ if (bwrap === undefined)
153
+ return none("bubblewrap is not installed (package bubblewrap)");
154
+ const test = bwrapArgs(d, { ws, cwd: ws, net: s.network, path: process.env.PATH ?? "", alt: plan?.alt }, ["sh", "-c", SELF_TEST, "sh", ws, d.piroHome, s.network ? "1" : "0"]);
155
+ const [program, ...rest] = seccompExec(bwrap, test.args);
156
+ const ran = await d.run(program, rest);
157
+ if (ran.code !== 0)
158
+ return none(ran.out.trim().split("\n")[0] || "bwrap did not start", true);
159
+ return { confine: { name: "bubblewrap", bwrap, net: s.network, alt: plan?.alt ?? [] }, label: "bubblewrap", notice: [...(s.network ? ["Network: on. Confined commands can reach your network, and can send any file they can see."] : []), ...(test.refused.length > 0 ? [`Left hidden in the sandbox because they are protected: ${test.refused.join(", ")}`] : [])] };
160
+ }
161
+ /** Wraps each command of a Workspace whose row says bubblewrap; every other command runs as before. A command a chosen backend cannot start is an error, never a rerun. */
162
+ export class ConfinedShellEnv extends ShellEnv {
163
+ lookup;
164
+ constructor(options, lookup) { super(options); this.lookup = lookup; }
165
+ async exec(command, options, context) {
166
+ if (typeof command !== "string")
167
+ return super.exec(command, options, context);
168
+ const cwd = resolve(this.cwd, options?.cwd ?? ".");
169
+ const w = this.lookup(cwd);
170
+ if (w === undefined || w.confine.name === "none")
171
+ return super.exec(command, options, context);
172
+ const unavailable = (reason) => err(new ExecutionError("spawn_error", `${DOWN}${reason}`));
173
+ // A Docker backend found unavailable stays so for the run: nothing spawns, nothing runs unconfined (bubblewrap has no such state: its start failure is per command).
174
+ if (w.down !== undefined)
175
+ return unavailable(w.down);
176
+ const bytes = Buffer.byteLength(command);
177
+ if (command.includes("\0") || bytes > COMMAND_MAX)
178
+ return err(new ExecutionError("spawn_error", command.includes("\0") ? "this command holds a NUL byte, which a confined shell cannot take; write it to a script file in the Workspace and run that" : `this command is too long for a confined shell (${bytes} bytes, limit 128 KiB); write it to a script file in the Workspace and run that`));
179
+ let result;
180
+ if (w.confine.docker !== undefined)
181
+ result = await execDocker(w, cwd, command, options, context, (argv, o) => super.exec(argv, o, context));
182
+ else if (w.confine.wsl !== undefined)
183
+ result = await execWsl(w, cwd, command, options, context);
184
+ else {
185
+ const { args } = bwrapArgs(w.deps, { ws: w.ws, cwd, net: w.confine.net !== false, path: options?.env?.PATH ?? "", alt: w.confine.alt }, ["bash", "-c", command]);
186
+ result = await super.exec(seccompExec(w.confine.bwrap, args), options, context);
187
+ if (!result.ok && result.error.code === "spawn_error")
188
+ result = unavailable(result.error.message);
189
+ }
190
+ if (w.confine.docker !== undefined && !result.ok && result.error.code === "spawn_error" && result.error.message.startsWith(DOWN))
191
+ w.mark?.(result.error.message.slice(DOWN.length));
192
+ return result;
193
+ }
194
+ }
@@ -0,0 +1,151 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { posix, win32 } from "node:path";
3
+ import { err, ExecutionError } from "@earendil-works/pi-durable/env";
4
+ import { within } from "./confine.js";
5
+ import { call, posixOf, resolveWsl, via, WRAPPER, WSLPATH, wslBad, wslCommand } from "./wsl.js";
6
+ const SOCK = "unix:///var/run/docker.sock";
7
+ // Runs in the container: the Workspace is writable, and (with perl) an AF_VSOCK socket cannot be created and io_uring_setup fails with EPERM.
8
+ const SELF_TEST = 'm=/work/.piroboros-selftest; : > "$m" || { echo "the Workspace is not writable"; exit 1; }; rm -f "$m"; command -v perl >/dev/null || { echo skipped; exit 0; }; perl -e \'socket(S,40,1,0) and exit 1\' || { echo "an AF_VSOCK socket can be created"; exit 1; }; perl -e \'syscall(425,0,0)==-1 && $!==1 and exit 0; exit 1\' || { echo "io_uring_setup is not blocked"; exit 1; }';
9
+ /** One docker call: `args` follow the fixed `--config <folder>` (and on Windows the fixed socket); only code constants and computed paths and IDs appear in them. */
10
+ export async function docker(d, c, args, ms = 10_000) {
11
+ if (c.remote === undefined)
12
+ return d.run(c.cli, ["--config", c.config, ...args], ms);
13
+ const r = await d.wsl.run(via(c.remote, ["/usr/bin/docker", "--config", c.config, "-H", SOCK, ...args]), { timeoutMs: ms });
14
+ return { code: r.timedOut ? null : r.code, out: `${r.out.toString("utf8")}${r.err}` };
15
+ }
16
+ const last = (out) => out.trim().split("\n").at(-1) ?? "";
17
+ /** Choose Docker for the Workspace folder `ws`: the checks, the container and its self-test. A refusal throws with the reason. */
18
+ export async function dockerPick(s, d, ws, p) {
19
+ const win = d.platform === "win32";
20
+ const P = win ? win32 : posix;
21
+ const hash = P.basename(P.dirname(ws));
22
+ const id = P.basename(ws);
23
+ const notice = [];
24
+ let host = ws;
25
+ let alt = p.alt;
26
+ let user = typeof process.getuid === "function" && !win ? ["--user", `${process.getuid()}:${process.getgid()}`] : [];
27
+ let nm = [];
28
+ let c = { cli: "", config: `${d.wsRoot}/${hash}/docker-config`, container: "", image: s.image, net: s.network, alt: p.alt, places: p.places };
29
+ let where = "a shell";
30
+ if (win) {
31
+ const w = d.wsl;
32
+ if (w === undefined)
33
+ throw new Error("WSL is not available");
34
+ const prev = p.prevDocker?.remote;
35
+ const info = await resolveWsl(w, prev === undefined ? { distro: s.distro } : { distro: prev.distro, user: prev.user }, false).catch((error) => { if (prev === undefined)
36
+ throw error; return resolveWsl(w, { distro: s.distro }, false); });
37
+ const who = { distro: info.distro, user: info.user };
38
+ where = `the ${info.distro} distro`;
39
+ for (const x of [ws, ...p.alt])
40
+ if (!/^[A-Za-z]:[\\/]/u.test(x))
41
+ throw new Error(`${x} is not on a local Windows drive`);
42
+ alt = p.alt.filter((a) => !wslBad(d, a));
43
+ if (alt.length < p.alt.length)
44
+ notice.push(`Left hidden in the sandbox because they are protected: ${p.alt.filter((a) => !alt.includes(a)).join(", ")}`);
45
+ const lin = (await call(w, who, "translating paths", WSLPATH, [ws, ...alt].map((x) => win32.resolve(x)))).split("\n");
46
+ for (const x of lin.slice(0, alt.length + 1))
47
+ if (!info.mounts.some((m) => within(m, x)))
48
+ throw new Error(`${x} is not on a local Windows drive`);
49
+ host = lin[0];
50
+ alt = lin.slice(1, alt.length + 1);
51
+ const base = `${info.home}/.local/state/piroboros-ws/${hash}`;
52
+ const ext4 = `${base}/${id}`;
53
+ nm = p.places.map((place, i) => [`${ext4}/nm/${i}`, `/work/${place}`]);
54
+ c = { ...c, cli: "/usr/bin/docker", config: `${base}/docker-config`, remote: { ...who, ext4 } };
55
+ user = ["--user", `${info.uid}:${info.gid}`];
56
+ await call(w, who, "creating the Docker folders", 'mkdir -p -m 0700 -- "$@"', [c.config, ...nm.map(([src]) => src)]);
57
+ const [sock = "", bin = "", has = ""] = (await call(w, who, "checking the Docker socket", 'printf "%s\\n" "$(readlink -f /var/run/docker.sock)" "$(readlink -f /usr/bin/docker)" "$([ -S /var/run/docker.sock ] && echo 1)"')).split("\n");
58
+ if (has !== "1")
59
+ throw new Error(`the Docker socket /var/run/docker.sock does not exist in ${info.distro}`);
60
+ if (bin === "" || info.mounts.some((m) => within(m, bin)))
61
+ throw new Error(`/usr/bin/docker is missing in ${info.distro} or is not the distro's own`);
62
+ if (info.mounts.some((m) => within(m, sock)))
63
+ throw new Error(`the Docker socket in ${info.distro} belongs to Docker Desktop (${sock})`);
64
+ }
65
+ else {
66
+ const cli = d.which("docker");
67
+ if (cli === undefined)
68
+ throw new Error("docker is not installed or not on PATH");
69
+ mkdirSync(c.config, { recursive: true, mode: 0o700 });
70
+ c = { ...c, cli };
71
+ }
72
+ let r = await docker(d, c, ["info", "--format", "{{.OperatingSystem}}|{{.SecurityOptions}}"]);
73
+ if (r.code !== 0)
74
+ r = await docker(d, c, ["info", "--format", "{{.OperatingSystem}}|{{.SecurityOptions}}"]);
75
+ if (r.code !== 0)
76
+ throw new Error(`docker did not answer (${last(r.out) || "no reply"})`);
77
+ const [os = "", sec = ""] = last(r.out).split("|");
78
+ if (/^Docker Desktop/u.test(os))
79
+ throw new Error("the engine is Docker Desktop's, which is not supported");
80
+ if (!/seccomp/u.test(sec))
81
+ throw new Error("the engine has no seccomp, so its default profile cannot block AF_VSOCK and io_uring");
82
+ if ((await docker(d, c, ["image", "inspect", "--format", "{{.Id}}", s.image])).code !== 0)
83
+ throw new Error(`image ${s.image} is not present; run docker pull ${s.image} in ${where}`);
84
+ if (p.prevDocker !== undefined)
85
+ await docker(d, c, ["rm", "-f", p.prevDocker.container]);
86
+ const mount = (src, dst, ro = false) => {
87
+ if (!/^[^,:"\n]+$/u.test(src))
88
+ throw new Error(`${src} holds a character a Docker mount cannot take`);
89
+ return ["--mount", `type=bind,source=${src},target=${dst}${ro ? ",readonly" : ""}`];
90
+ };
91
+ const inside = alt.map((_, i) => (i === 0 ? "/piroboros-objects" : `/piroboros-objects-${i}`));
92
+ const name = `piroboros-ws-${hash}-${id}-${Date.now().toString(36)}`;
93
+ r = await docker(d, c, ["run", "-d", "--pull", "never", "--init", "--name", name, "--label", `piroboros.home=${hash}`, "--label", `piroboros.ws=${id}`, "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--pids-limit", "1024",
94
+ "--network", s.network ? "bridge" : "none", "-e", "HOME=/tmp", ...mount(host, "/work"), ...nm.flatMap(([src, dst]) => mount(src, dst)), ...alt.flatMap((a, i) => mount(a, inside[i], true)), "-w", "/work", ...user, s.image, "sleep", "infinity"], 30_000);
95
+ const container = /^[0-9a-f]{64}$/mu.exec(r.out)?.[0];
96
+ if (r.code !== 0 || container === undefined)
97
+ throw new Error(`docker run failed (${last(r.out) || "no container ID"})`);
98
+ c = { ...c, container };
99
+ try {
100
+ const t = await docker(d, c, ["exec", container, "sh", "-c", SELF_TEST]);
101
+ if (t.code !== 0)
102
+ throw new Error(`the container self-test failed (${last(t.out) || `exit ${t.code}`})`);
103
+ if (/^skipped$/mu.test(t.out))
104
+ notice.push("The container self-test skipped the seccomp checks: the image has no perl.");
105
+ }
106
+ catch (error) {
107
+ await docker(d, c, ["rm", "-f", container]);
108
+ throw error;
109
+ }
110
+ if (s.network)
111
+ notice.push(win ? "Network: on. Confined commands can reach the WSL VM's network, which includes the Windows host, and can send any file they can see." : "Network: on. Confined commands can reach your network, and can send any file they can see.");
112
+ return { confine: { name: "docker", net: s.network, docker: c }, label: c.remote === undefined ? "docker" : `docker in WSL (${c.remote.distro})`, notice, alt: inside };
113
+ }
114
+ /** Remove a Workspace's container, best effort. */
115
+ export const dockerRemove = (d, c) => docker(d, c, ["rm", "-f", c.container]);
116
+ /** Remove every container of this home hash whose Workspace id is not open in this store; another home's containers carry another hash and are never listed. */
117
+ export async function dockerSweep(d, c, hash, open) {
118
+ const r = await docker(d, c, ["ps", "-a", "--no-trunc", "--filter", `label=piroboros.home=${hash}`, "--format", "{{.ID}}|{{.Labels}}"]);
119
+ for (const line of r.out.split("\n")) {
120
+ const [cid = "", labels = ""] = line.trim().split("|");
121
+ if (/^[0-9a-f]{64}$/u.test(cid) && !open.has(/piroboros\.ws=(\d+)/u.exec(labels)?.[1] ?? ""))
122
+ await docker(d, c, ["rm", "-f", cid]);
123
+ }
124
+ }
125
+ /** One command in the container: natively `docker exec` as a child (names only in argv, values in the CLI's own environment), on Windows through the runner with the command on stdin. */
126
+ export async function execDocker(w, cwd, command, options, context, run) {
127
+ const c = w.confine.docker;
128
+ const rel = c.remote === undefined ? posix.relative(w.ws, cwd) : posixOf(win32.relative(w.ws, cwd));
129
+ const wd = rel === "" ? "/work" : `/work/${rel}`;
130
+ // A plain Workspace's ceiling is the container root, whatever the host guard computed.
131
+ const ceiling = options?.env?.GIT_CEILING_DIRECTORIES !== undefined;
132
+ const stop = async () => { await docker(w.deps, c, ["restart", "-t", "0", c.container]); };
133
+ let result;
134
+ if (c.remote === undefined) {
135
+ const env = { ...options?.env, ...(ceiling ? { GIT_CEILING_DIRECTORIES: "/" } : {}) };
136
+ const names = Object.keys(env).filter((n) => !["PATH", "HOME", "TMPDIR"].includes(n));
137
+ result = await run([c.cli, "--config", c.config, "exec", "-w", wd, ...names.flatMap((n) => ["-e", n]), c.container, "bash", "-c", command], { ...options, env });
138
+ if (!result.ok && (result.error.code === "timeout" || result.error.code === "aborted"))
139
+ await stop();
140
+ }
141
+ else {
142
+ const args = via(c.remote, ["/usr/bin/env", "NO_COLOR=1", "TERM=dumb", "LANG=C.UTF-8", ...(ceiling ? ["GIT_CEILING_DIRECTORIES=/"] : []), "/usr/bin/docker", "--config", c.config, "-H", SOCK, "exec", "-i", "-w", wd,
143
+ "-e", "NO_COLOR", "-e", "TERM", "-e", "LANG", ...(ceiling ? ["-e", "GIT_CEILING_DIRECTORIES"] : []), c.container, "bash", "-c", WRAPPER]);
144
+ result = await wslCommand(w.deps.wsl, args, command, options, context, stop, () => undefined, `distro ${c.remote.distro} or user ${c.remote.user} not found`);
145
+ }
146
+ // ponytail: one extra inspect (about 0.6 s) per failing command; narrow it by exit code if that cost shows up.
147
+ if (!result.ok || result.value.exitCode === 0)
148
+ return result;
149
+ const r = await docker(w.deps, c, ["inspect", "--format", "{{.State.Running}}", c.container]);
150
+ return last(r.out) === "true" && r.code === 0 ? result : err(new ExecutionError("spawn_error", `confinement backend unavailable: ${r.code === 0 ? "the container is not running" : last(r.out) || "docker did not answer"}`));
151
+ }