piroboros 0.2.0 → 0.3.3
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/CHANGELOG.md +65 -0
- package/NOTICE +12 -0
- package/README.md +11 -8
- package/dist/chat/log.js +1 -1
- package/dist/chat/turn.js +0 -15
- package/dist/conclave/pipeline.js +216 -13
- package/dist/config.js +121 -12
- package/dist/diff.js +90 -0
- package/dist/durable.js +1 -1
- package/dist/guard.js +170 -14
- package/dist/learn.js +938 -0
- package/dist/memory/akashic/tools.js +25 -28
- package/dist/memory/mnemosia/conflicts.js +0 -4
- package/dist/memory/mnemosia/orchestrator.js +1 -11
- package/dist/memory/mnemosia/policy.js +0 -3
- package/dist/memory/mnemosia/rank.js +0 -4
- package/dist/memory/mnemosia/rerank.js +3 -30
- package/dist/memory/mnemosia/rollback.js +1 -149
- package/dist/memory/mnemosia/tokens.js +1 -11
- package/dist/memory/mnemosia/tools.js +0 -10
- package/dist/memory/mnemosia/types.js +0 -2
- package/dist/runtime.js +51 -6
- package/dist/search.js +25 -12
- package/dist/shell.js +2 -2
- package/dist/tui/app.js +15 -3
- package/dist/tui/commands.js +5 -2
- package/dist/tui/settings.js +4 -1
- package/dist/tui/thinking/parse.js +0 -3
- package/dist/ws/apply.js +833 -0
- package/dist/ws/cas.js +144 -0
- package/dist/ws/confine.js +220 -0
- package/dist/ws/docker.js +145 -0
- package/dist/ws/git.js +235 -0
- package/dist/ws/lww.js +48 -0
- package/dist/ws/merge.js +129 -0
- package/dist/ws/workspace.js +1736 -0
- package/dist/ws/wsl.js +247 -0
- package/docs/conclave.md +14 -0
- package/docs/configuration.md +10 -4
- package/docs/privacy.md +3 -1
- package/docs/tools.md +43 -1
- package/package.json +1 -2
- package/settings.json.example +3 -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,220 @@
|
|
|
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
|
+
/**
|
|
12
|
+
* A stored sandbox that must be picked again before the run's first command (`Found.upgrade`): a record made by 0.3.1 or 0.3.2 may hold `alt` (the live repository's object folders, bound or mounted;
|
|
13
|
+
* the stored WSL argv and a Docker container still bind or mount them), and a stored WSL argv made before 0.3.3 binds the whole root (`--ro-bind / /`), where a new one binds only the system folders.
|
|
14
|
+
*/
|
|
15
|
+
export const needsRepick = (c) => [c.wsl, c.docker].some((x) => (x?.alt?.length ?? 0) > 0) || (c.wsl?.argv.some((a, i, v) => a === "--ro-bind" && v[i + 1] === "/" && v[i + 2] === "/") ?? false);
|
|
16
|
+
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.";
|
|
17
|
+
/** Linux refuses one argument over 131,072 bytes counting its NUL (MAX_ARG_STRLEN). */
|
|
18
|
+
export const COMMAND_MAX = 131_071;
|
|
19
|
+
const DOWN = "confinement backend unavailable: ";
|
|
20
|
+
/** The top-level folders a sandbox gets from the machine (read-only); /nix is where NixOS keeps what PATH points at. */
|
|
21
|
+
const SYSTEM = ["/usr", "/etc", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32", "/nix"];
|
|
22
|
+
export const within = (root, path) => path === root || path.startsWith(root === "/" ? "/" : `${root}/`);
|
|
23
|
+
export function nativeDeps(cfg, wsRoot) {
|
|
24
|
+
return {
|
|
25
|
+
platform: process.platform, home: cfg.profile ?? homedir(), piroHome: cfg.home, wsRoot, deny: denyRoots(cfg), wsl: process.platform === "win32" ? wslDeps() : undefined,
|
|
26
|
+
allowed: (path) => checkRead(path, undefined, cfg).allowed,
|
|
27
|
+
real: (path) => { try {
|
|
28
|
+
return realpathSync(path);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
} },
|
|
33
|
+
read: (path) => { try {
|
|
34
|
+
return readFileSync(path, "utf8");
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
} },
|
|
39
|
+
which: (name) => (process.env.PATH ?? "").split(delimiter).map((dir) => posix.join(dir, name)).find((p) => existsSync(p)),
|
|
40
|
+
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}` }))),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* 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
|
|
45
|
+
* 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
|
|
46
|
+
* aarch64 and x32 numbers are killed, everything else is allowed. struct seccomp_data: nr at 0, arch at 4, arg0 at 16.
|
|
47
|
+
*/
|
|
48
|
+
export function seccompFilter() {
|
|
49
|
+
const ERRNO = 0x00050000, ALLOW = 0x7fff0000, KILL = 0x80000000;
|
|
50
|
+
const i = (code, jt, jf, k) => [code & 0xff, code >> 8, jt, jf, k & 0xff, (k >>> 8) & 0xff, (k >>> 16) & 0xff, k >>> 24];
|
|
51
|
+
const LD = 0x20, JEQ = 0x15, JGT = 0x25, JGE = 0x35, JA = 0x05, RET = 0x06;
|
|
52
|
+
return Buffer.from([
|
|
53
|
+
...i(LD, 0, 0, 4), ...i(JEQ, 6, 0, 0xC00000B7), ...i(JEQ, 0, 15, 0xC000003E), // 0-2 arch
|
|
54
|
+
...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
|
|
55
|
+
...i(LD, 0, 0, 0), ...i(JEQ, 4, 0, 198), ...i(JEQ, 3, 0, 199), // 8-10 aarch64 numbers
|
|
56
|
+
...i(JGE, 0, 5, 425), ...i(JGT, 4, 0, 427), ...i(RET, 0, 0, ERRNO | 1), // 11-13 io_uring
|
|
57
|
+
...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
|
|
58
|
+
]);
|
|
59
|
+
}
|
|
60
|
+
/** `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. */
|
|
61
|
+
export function seccompExec(bwrap, args) {
|
|
62
|
+
const octal = [...seccompFilter()].map((b) => `\\0${b.toString(8).padStart(3, "0")}`).join("");
|
|
63
|
+
return ["bash", "-c", 'exec "${@:2}" 9< <(printf %b "$1")', "bash", octal, bwrap, ...args];
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The bwrap arguments for `inner` run in the Workspace `c.ws` from `c.cwd`. The root is not bound: a command sees the SYSTEM folders read-only, the PATH
|
|
67
|
+
* folders outside them, the Workspace, and empty /tmp, /var/tmp and masks. Options apply in order: masks first, binds after. A mask
|
|
68
|
+
* path (the home, PIROBOROS_HOME, the deny roots and the live project `c.project`, so they stay empty even under a bound folder) is resolved first; one that does not exist, or lies inside an earlier mask, is dropped.
|
|
69
|
+
* `refused` names needed paths left 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):
|
|
70
|
+
* the Windows-backed mounts are masked, `/init` is emptied (no Windows program starts), `nm` binds ext4 folders over Workspace folders, `env` is the whole environment and `extra` are more read-only binds.
|
|
71
|
+
* Nothing of the live repository is bound: a git Workspace holds its own repository.
|
|
72
|
+
*/
|
|
73
|
+
export function bwrapArgs(d, c, inner) {
|
|
74
|
+
const masks = [];
|
|
75
|
+
for (const mask of [d.home, ...(c.wsl?.mounts ?? []), d.piroHome, ...d.deny, ...(c.project === undefined ? [] : [c.project])]) {
|
|
76
|
+
const r = d.real(mask);
|
|
77
|
+
if (r !== undefined && !masks.some((m) => within(m, r)))
|
|
78
|
+
masks.push(r);
|
|
79
|
+
}
|
|
80
|
+
const binds = [];
|
|
81
|
+
const refused = [];
|
|
82
|
+
const protectedRoots = [d.piroHome, d.wsRoot, ...d.deny, ...(c.project === undefined ? [] : [c.project])].map((root) => d.real(root) ?? root);
|
|
83
|
+
const need = (path) => {
|
|
84
|
+
const r = d.real(path);
|
|
85
|
+
if (r === undefined || binds.some(([, dest]) => dest === r))
|
|
86
|
+
return;
|
|
87
|
+
// A path that is, or holds, a mask or a protected root never binds: that would put back what the mask hid.
|
|
88
|
+
const holds = masks.some((m) => within(r, m));
|
|
89
|
+
if (holds || !d.allowed(r) || protectedRoots.some((root) => within(r, root))) {
|
|
90
|
+
if (holds || masks.some((m) => within(m, r)))
|
|
91
|
+
refused.push(path);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
binds.push([r, r]);
|
|
95
|
+
};
|
|
96
|
+
// The system folders that exist are all a command sees of the machine: a real folder is bound read-only, a link (merged /usr: /bin -> usr/bin) is made again.
|
|
97
|
+
const system = [];
|
|
98
|
+
const links = [];
|
|
99
|
+
for (const name of SYSTEM) {
|
|
100
|
+
const r = d.real(name);
|
|
101
|
+
if (r === name)
|
|
102
|
+
system.push(r);
|
|
103
|
+
else if (r !== undefined)
|
|
104
|
+
links.push([r, name]);
|
|
105
|
+
}
|
|
106
|
+
const inSystem = (p) => system.some((s) => within(s, p));
|
|
107
|
+
for (const [target] of links)
|
|
108
|
+
if (!inSystem(target))
|
|
109
|
+
need(target);
|
|
110
|
+
// A resolv.conf that is a link out of /etc (systemd-resolved, WSL) needs its target.
|
|
111
|
+
const resolv = c.net ? d.real("/etc/resolv.conf") : undefined;
|
|
112
|
+
if (resolv !== undefined && !inSystem(resolv))
|
|
113
|
+
need(c.wsl === undefined ? posix.dirname(resolv) : resolv);
|
|
114
|
+
// PATH entries outside the system folders: the entry, and its parent only for `<parent>/bin` where the parent is neither the home, nor the root, nor a direct child of either.
|
|
115
|
+
const home = d.real(d.home) ?? d.home;
|
|
116
|
+
const shallow = (p) => [home, "/"].some((top) => p === top || posix.dirname(p) === top);
|
|
117
|
+
for (const entry of c.path.split(":")) {
|
|
118
|
+
const r = entry.startsWith("/") ? d.real(entry) : undefined;
|
|
119
|
+
if (r === undefined || r === home || r === "/" || inSystem(r))
|
|
120
|
+
continue;
|
|
121
|
+
const parent = posix.dirname(r);
|
|
122
|
+
if (posix.basename(r) === "bin" && !shallow(parent))
|
|
123
|
+
need(parent);
|
|
124
|
+
need(r);
|
|
125
|
+
}
|
|
126
|
+
const args = ["--seccomp", "9", "--die-with-parent", "--new-session", "--unshare-all", ...(c.net ? ["--share-net"] : []), ...system.flatMap((s) => ["--ro-bind", s, s]), ...links.flatMap(([target, name]) => ["--symlink", target, name]),
|
|
127
|
+
"--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp", "--tmpfs", "/var/tmp",
|
|
128
|
+
...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]),
|
|
129
|
+
"--bind", c.ws, c.ws, ...(c.wsl?.nm ?? []).flatMap(([s, t]) => ["--bind", s, t]),
|
|
130
|
+
...(c.wsl === undefined ? [] : ["--clearenv", ...c.wsl.env.flatMap(([k, v]) => ["--setenv", k, v]), "--unsetenv", "WSL_INTEROP"]), "--chdir", c.cwd, ...inner];
|
|
131
|
+
return { args, refused };
|
|
132
|
+
}
|
|
133
|
+
// Runs inside the sandbox: write and remove a file in the Workspace, no auth.json beside the home, (network on) a readable resolv.conf, and nothing listed in the live project's folder.
|
|
134
|
+
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; }; [ -z "$4" ] || [ -z "$(ls -A -- "$4" 2>/dev/null)" ] || { echo "the live project is visible"; 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';
|
|
135
|
+
/**
|
|
136
|
+
* 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),
|
|
137
|
+
* then bubblewrap, then none. A failure under `auto` is never a run failure: it gives the next backend, or none plus a warning.
|
|
138
|
+
*/
|
|
139
|
+
export async function confineFor(s, d, ws, plan) {
|
|
140
|
+
if (s.confine === "docker" && s.docker === undefined)
|
|
141
|
+
throw new WsRefusal('workspace.confine is "docker" but workspace.docker.image is not set');
|
|
142
|
+
let skipped = "";
|
|
143
|
+
if (s.confine !== "none" && s.docker !== undefined) {
|
|
144
|
+
try {
|
|
145
|
+
return await dockerPick({ network: s.network, distro: s.distro, image: s.docker }, d, ws, plan ?? { places: [], project: "", files: 0 });
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
149
|
+
if (s.confine === "docker")
|
|
150
|
+
throw new WsRefusal(`workspace.confine is "docker" but ${why}`);
|
|
151
|
+
skipped = why;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const picked = await confineLocal(s.confine === "docker" ? "auto" : s.confine, s.network, s.distro, d, ws, plan);
|
|
155
|
+
return skipped === "" ? picked : { ...picked, notice: [...picked.notice, `Docker was not used: ${skipped}.`] };
|
|
156
|
+
}
|
|
157
|
+
async function confineLocal(confine, network, distro, d, ws, plan) {
|
|
158
|
+
const s = { confine, network, distro };
|
|
159
|
+
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}.`] });
|
|
160
|
+
if (s.confine === "none")
|
|
161
|
+
return none("workspace.confine is none");
|
|
162
|
+
if (d.platform === "win32" && d.wsl !== undefined) {
|
|
163
|
+
try {
|
|
164
|
+
return await wslPick(s, d, ws, plan ?? { places: [], project: "", files: 0 });
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
return none(error instanceof SelfTestError ? error.message : `bubblewrap in WSL: ${error instanceof Error ? error.message : String(error)}`, error instanceof SelfTestError);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (d.platform !== "linux")
|
|
171
|
+
return none(`bubblewrap needs Linux; this is ${d.platform}`);
|
|
172
|
+
const bwrap = d.which("bwrap");
|
|
173
|
+
if (bwrap === undefined)
|
|
174
|
+
return none("bubblewrap is not installed (package bubblewrap)");
|
|
175
|
+
const project = plan?.project === "" ? undefined : plan?.project;
|
|
176
|
+
const test = bwrapArgs(d, { ws, cwd: ws, net: s.network, path: process.env.PATH ?? "", project }, ["sh", "-c", SELF_TEST, "sh", ws, d.piroHome, s.network ? "1" : "0", project ?? ""]);
|
|
177
|
+
const [program, ...rest] = seccompExec(bwrap, test.args);
|
|
178
|
+
const ran = await d.run(program, rest);
|
|
179
|
+
if (ran.code !== 0)
|
|
180
|
+
return none(ran.out.trim().split("\n")[0] || "bwrap did not start", true);
|
|
181
|
+
return { confine: { name: "bubblewrap", bwrap, net: s.network }, 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(", ")}`] : [])] };
|
|
182
|
+
}
|
|
183
|
+
/** 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. */
|
|
184
|
+
export class ConfinedShellEnv extends ShellEnv {
|
|
185
|
+
lookup;
|
|
186
|
+
constructor(options, lookup) { super(options); this.lookup = lookup; }
|
|
187
|
+
async exec(command, options, context) {
|
|
188
|
+
if (typeof command !== "string")
|
|
189
|
+
return super.exec(command, options, context);
|
|
190
|
+
const cwd = resolve(this.cwd, options?.cwd ?? ".");
|
|
191
|
+
let w = this.lookup(cwd);
|
|
192
|
+
if (w?.upgrade !== undefined) {
|
|
193
|
+
await w.upgrade();
|
|
194
|
+
w = this.lookup(cwd);
|
|
195
|
+
}
|
|
196
|
+
if (w === undefined || w.confine.name === "none")
|
|
197
|
+
return super.exec(command, options, context);
|
|
198
|
+
const unavailable = (reason) => err(new ExecutionError("spawn_error", `${DOWN}${reason}`));
|
|
199
|
+
// 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).
|
|
200
|
+
if (w.down !== undefined)
|
|
201
|
+
return unavailable(w.down);
|
|
202
|
+
const bytes = Buffer.byteLength(command);
|
|
203
|
+
if (command.includes("\0") || bytes > COMMAND_MAX)
|
|
204
|
+
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`));
|
|
205
|
+
let result;
|
|
206
|
+
if (w.confine.docker !== undefined)
|
|
207
|
+
result = await execDocker(w, cwd, command, options, context, (argv, o) => super.exec(argv, o, context));
|
|
208
|
+
else if (w.confine.wsl !== undefined)
|
|
209
|
+
result = await execWsl(w, cwd, command, options, context);
|
|
210
|
+
else {
|
|
211
|
+
const { args } = bwrapArgs(w.deps, { ws: w.ws, cwd, net: w.confine.net !== false, path: options?.env?.PATH ?? "", project: w.project }, ["bash", "-c", command]);
|
|
212
|
+
result = await super.exec(seccompExec(w.confine.bwrap, args), options, context);
|
|
213
|
+
if (!result.ok && result.error.code === "spawn_error")
|
|
214
|
+
result = unavailable(result.error.message);
|
|
215
|
+
}
|
|
216
|
+
if (w.confine.docker !== undefined && !result.ok && result.error.code === "spawn_error" && result.error.message.startsWith(DOWN))
|
|
217
|
+
w.mark?.(result.error.message.slice(DOWN.length));
|
|
218
|
+
return result;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
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, 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 user = typeof process.getuid === "function" && !win ? ["--user", `${process.getuid()}:${process.getgid()}`] : [];
|
|
26
|
+
let nm = [];
|
|
27
|
+
let c = { cli: "", config: `${d.wsRoot}/${hash}/docker-config`, container: "", image: s.image, net: s.network, places: p.places };
|
|
28
|
+
let where = "a shell";
|
|
29
|
+
if (win) {
|
|
30
|
+
const w = d.wsl;
|
|
31
|
+
if (w === undefined)
|
|
32
|
+
throw new Error("WSL is not available");
|
|
33
|
+
const prev = p.prevDocker?.remote;
|
|
34
|
+
const info = await resolveWsl(w, prev === undefined ? { distro: s.distro } : { distro: prev.distro, user: prev.user }, false).catch((error) => { if (prev === undefined)
|
|
35
|
+
throw error; return resolveWsl(w, { distro: s.distro }, false); });
|
|
36
|
+
const who = { distro: info.distro, user: info.user };
|
|
37
|
+
where = `the ${info.distro} distro`;
|
|
38
|
+
if (!/^[A-Za-z]:[\\/]/u.test(ws))
|
|
39
|
+
throw new Error(`${ws} is not on a local Windows drive`);
|
|
40
|
+
const lin = (await call(w, who, "translating paths", WSLPATH, [win32.resolve(ws)])).split("\n")[0];
|
|
41
|
+
if (!info.mounts.some((m) => within(m, lin)))
|
|
42
|
+
throw new Error(`${lin} is not on a local Windows drive`);
|
|
43
|
+
host = lin;
|
|
44
|
+
const base = `${info.home}/.local/state/piroboros-ws/${hash}`;
|
|
45
|
+
const ext4 = `${base}/${id}`;
|
|
46
|
+
nm = p.places.map((place, i) => [`${ext4}/nm/${i}`, `/work/${place}`]);
|
|
47
|
+
c = { ...c, cli: "/usr/bin/docker", config: `${base}/docker-config`, remote: { ...who, ext4 } };
|
|
48
|
+
user = ["--user", `${info.uid}:${info.gid}`];
|
|
49
|
+
await call(w, who, "creating the Docker folders", 'mkdir -p -m 0700 -- "$@"', [c.config, ...nm.map(([src]) => src)]);
|
|
50
|
+
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");
|
|
51
|
+
if (has !== "1")
|
|
52
|
+
throw new Error(`the Docker socket /var/run/docker.sock does not exist in ${info.distro}`);
|
|
53
|
+
if (bin === "" || info.mounts.some((m) => within(m, bin)))
|
|
54
|
+
throw new Error(`/usr/bin/docker is missing in ${info.distro} or is not the distro's own`);
|
|
55
|
+
if (info.mounts.some((m) => within(m, sock)))
|
|
56
|
+
throw new Error(`the Docker socket in ${info.distro} belongs to Docker Desktop (${sock})`);
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
const cli = d.which("docker");
|
|
60
|
+
if (cli === undefined)
|
|
61
|
+
throw new Error("docker is not installed or not on PATH");
|
|
62
|
+
mkdirSync(c.config, { recursive: true, mode: 0o700 });
|
|
63
|
+
c = { ...c, cli };
|
|
64
|
+
}
|
|
65
|
+
let r = await docker(d, c, ["info", "--format", "{{.OperatingSystem}}|{{.SecurityOptions}}"]);
|
|
66
|
+
if (r.code !== 0)
|
|
67
|
+
r = await docker(d, c, ["info", "--format", "{{.OperatingSystem}}|{{.SecurityOptions}}"]);
|
|
68
|
+
if (r.code !== 0)
|
|
69
|
+
throw new Error(`docker did not answer (${last(r.out) || "no reply"})`);
|
|
70
|
+
const [os = "", sec = ""] = last(r.out).split("|");
|
|
71
|
+
if (/^Docker Desktop/u.test(os))
|
|
72
|
+
throw new Error("the engine is Docker Desktop's, which is not supported");
|
|
73
|
+
if (!/seccomp/u.test(sec))
|
|
74
|
+
throw new Error("the engine has no seccomp, so its default profile cannot block AF_VSOCK and io_uring");
|
|
75
|
+
if ((await docker(d, c, ["image", "inspect", "--format", "{{.Id}}", s.image])).code !== 0)
|
|
76
|
+
throw new Error(`image ${s.image} is not present; run docker pull ${s.image} in ${where}`);
|
|
77
|
+
if (p.prevDocker !== undefined)
|
|
78
|
+
await docker(d, c, ["rm", "-f", p.prevDocker.container]);
|
|
79
|
+
const mount = (src, dst) => {
|
|
80
|
+
if (!/^[^,:"\n]+$/u.test(src))
|
|
81
|
+
throw new Error(`${src} holds a character a Docker mount cannot take`);
|
|
82
|
+
return ["--mount", `type=bind,source=${src},target=${dst}`];
|
|
83
|
+
};
|
|
84
|
+
const name = `piroboros-ws-${hash}-${id}-${Date.now().toString(36)}`;
|
|
85
|
+
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",
|
|
86
|
+
"--network", s.network ? "bridge" : "none", "-e", "HOME=/tmp", ...mount(host, "/work"), ...nm.flatMap(([src, dst]) => mount(src, dst)), "-w", "/work", ...user, s.image, "sleep", "infinity"], 30_000);
|
|
87
|
+
const container = /^[0-9a-f]{64}$/mu.exec(r.out)?.[0];
|
|
88
|
+
if (r.code !== 0 || container === undefined)
|
|
89
|
+
throw new Error(`docker run failed (${last(r.out) || "no container ID"})`);
|
|
90
|
+
c = { ...c, container };
|
|
91
|
+
try {
|
|
92
|
+
const t = await docker(d, c, ["exec", container, "sh", "-c", SELF_TEST]);
|
|
93
|
+
if (t.code !== 0)
|
|
94
|
+
throw new Error(`the container self-test failed (${last(t.out) || `exit ${t.code}`})`);
|
|
95
|
+
if (/^skipped$/mu.test(t.out))
|
|
96
|
+
notice.push("The container self-test skipped the seccomp checks: the image has no perl.");
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
await docker(d, c, ["rm", "-f", container]);
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
if (s.network)
|
|
103
|
+
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.");
|
|
104
|
+
return { confine: { name: "docker", net: s.network, docker: c }, label: c.remote === undefined ? "docker" : `docker in WSL (${c.remote.distro})`, notice };
|
|
105
|
+
}
|
|
106
|
+
/** Remove a Workspace's container, best effort. */
|
|
107
|
+
export const dockerRemove = (d, c) => docker(d, c, ["rm", "-f", c.container]);
|
|
108
|
+
/** End every process in a Workspace's container, best effort: `docker exec` processes outlive their command, and the host must not read or write the folder beside one. */
|
|
109
|
+
export const dockerKill = (d, c) => docker(d, c, ["kill", c.container]);
|
|
110
|
+
/** 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. */
|
|
111
|
+
export async function dockerSweep(d, c, hash, open) {
|
|
112
|
+
const r = await docker(d, c, ["ps", "-a", "--no-trunc", "--filter", `label=piroboros.home=${hash}`, "--format", "{{.ID}}|{{.Labels}}"]);
|
|
113
|
+
for (const line of r.out.split("\n")) {
|
|
114
|
+
const [cid = "", labels = ""] = line.trim().split("|");
|
|
115
|
+
if (/^[0-9a-f]{64}$/u.test(cid) && !open.has(/piroboros\.ws=(\d+)/u.exec(labels)?.[1] ?? ""))
|
|
116
|
+
await docker(d, c, ["rm", "-f", cid]);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** 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. */
|
|
120
|
+
export async function execDocker(w, cwd, command, options, context, run) {
|
|
121
|
+
const c = w.confine.docker;
|
|
122
|
+
const rel = c.remote === undefined ? posix.relative(w.ws, cwd) : posixOf(win32.relative(w.ws, cwd));
|
|
123
|
+
const wd = rel === "" ? "/work" : `/work/${rel}`;
|
|
124
|
+
// A plain Workspace's ceiling is the container root, whatever the host guard computed.
|
|
125
|
+
const ceiling = options?.env?.GIT_CEILING_DIRECTORIES !== undefined;
|
|
126
|
+
const stop = async () => { await docker(w.deps, c, ["restart", "-t", "0", c.container]); };
|
|
127
|
+
let result;
|
|
128
|
+
if (c.remote === undefined) {
|
|
129
|
+
const env = { ...options?.env, ...(ceiling ? { GIT_CEILING_DIRECTORIES: "/" } : {}) };
|
|
130
|
+
const names = Object.keys(env).filter((n) => !["PATH", "HOME", "TMPDIR"].includes(n));
|
|
131
|
+
result = await run([c.cli, "--config", c.config, "exec", "-w", wd, ...names.flatMap((n) => ["-e", n]), c.container, "bash", "-c", command], { ...options, env });
|
|
132
|
+
if (!result.ok && (result.error.code === "timeout" || result.error.code === "aborted"))
|
|
133
|
+
await stop();
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
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,
|
|
137
|
+
"-e", "NO_COLOR", "-e", "TERM", "-e", "LANG", ...(ceiling ? ["-e", "GIT_CEILING_DIRECTORIES"] : []), c.container, "bash", "-c", WRAPPER]);
|
|
138
|
+
result = await wslCommand(w.deps.wsl, args, command, options, context, stop, () => undefined, `distro ${c.remote.distro} or user ${c.remote.user} not found`);
|
|
139
|
+
}
|
|
140
|
+
// ponytail: one extra inspect (about 0.6 s) per failing command; narrow it by exit code if that cost shows up.
|
|
141
|
+
if (!result.ok || result.value.exitCode === 0)
|
|
142
|
+
return result;
|
|
143
|
+
const r = await docker(w.deps, c, ["inspect", "--format", "{{.State.Running}}", c.container]);
|
|
144
|
+
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"}`));
|
|
145
|
+
}
|