piroboros 0.3.2 → 0.3.4

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 CHANGED
@@ -2,6 +2,34 @@
2
2
 
3
3
  This project follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and [Semantic Versioning](https://semver.org/).
4
4
 
5
+ ## [0.3.4] - 2026-10-29
6
+
7
+ ### Changed
8
+
9
+ - A Conclave member's request now puts what every member shares first and what differs per seat last, so a provider that caches by prefix can reuse the earlier seats' requests. The developer prompt holds the shared Conclave skill only. The brief is one block for the task, one block per posted report, and a last block with the seat line and the member's own role text (from its file in `agents/`). On three scripted River runs the cached share of all prompt tokens went from 71.3% to 83.6%, and for member requests from 76.8% to 87.9%. A task that started before the upgrade keeps the old layout.
10
+ - On Anthropic models a member brief gets a fourth cache mark, on its last report, so the next seat reads the reports from the cache.
11
+ - A report can no longer open or close a `<role>` block in a brief.
12
+ - The README shows a short recording of a chat turn, a Conclave review and Vesperia's Workspace run merged back.
13
+
14
+ ## [0.3.3] - 2026-10-28
15
+
16
+ ### Security
17
+
18
+ - A Workspace with git is now its own repository. At open piroboros makes a new one in the Workspace folder with one commit of the copied files, on the branch name your repository is on, with your remotes' addresses and a push address that fails. Nothing of your `.git` comes along: no history, branches, stashes, index or objects, and nothing is bound or mounted into the sandbox. Before, a secret that was excluded from the copy (a `.env` committed once and deleted since) could still be read from your object store through the shared objects. This removes the object-folder code added in 0.3.1, including the unchecked Docker mount of alternates.
19
+ - The visible change: `git log` in a Workspace shows one commit, and a Workspace made by 0.3.2 or earlier loses its git history when it is reopened, or when its run is resumed after a retry or a restart (its files stay, and one notice line says so). A Docker or WSL sandbox of such a Workspace, which still binds your objects, is made again before the run's first command, as a reopen does (a Docker container is removed and a new one started), and the run goes on. If the new sandbox cannot be made, the run ends held with the reason `confinement backend unavailable`, and approving it again reopens the Workspace.
20
+ - The base commit of a Workspace is built with `git fast-import` and `git read-tree`, which run no clean filter, line-ending conversion or hook, so no filter in your global or system git config (a `filter.lfs.*` entry, for example) runs on your machine at open. Each file's blob holds its bytes as copied. A project of 24,000 unique files opens in about 17 seconds instead of 72, because no loose object is written per file. With `core.autocrlf` and `* text=auto` the Workspace's `git status` stays clean; a file with an explicit `text` or `eol` attribute whose line endings differ from it, or a file a clean filter changes, can show as modified in `git status` inside the Workspace before Vesperia touches it. Merges read no git, so they are not affected.
21
+ - `id_dsa` is now refused by the file tools and left out of a Workspace like the other SSH private key names (`id_rsa`, `id_ecdsa`, `id_ed25519`).
22
+ - Everything piroboros writes into a Workspace after Vesperia has had it (the refresh when a held Workspace reopens, the empty `node_modules` folders on WSL and the conflict markers) now checks every folder on the way for a link and writes through a new file that is renamed over the old one. Before, she could replace a folder or the `.git/objects/info/alternates` file with a link to a file outside the Workspace and have piroboros overwrite that file. A refused path is skipped with a notice. With Docker, every process in the container is ended before the host reads or writes the Workspace, so a background process cannot race it.
23
+ - The bubblewrap sandbox (native and in WSL) no longer starts from a read-only view of the whole root. A command sees only `/usr`, `/etc`, `/bin`, `/sbin`, `/lib`, `/lib32`, `/lib64`, `/libx32` and `/nix` where they exist, the PATH folders outside them, the Workspace, and empty `/tmp`, `/var/tmp` and home folders; `/opt`, `/srv`, `/var`, `/mnt`, `/media`, other drives and a project outside your home are gone, and your live project is empty wherever it is. Before, with `workspace.network` on (the default), a command could read and send any of them. A stored WSL sandbox from 0.3.2 or earlier is made again before its next command.
24
+ - With `workspace.network` on, the sandbox shares the network namespace and with it the abstract Unix sockets, which is documented as a residual and not closed: a Linux desktop's X server usually listens on one (set `workspace.network` to `false` there), and in WSL they are systemd's system buses, which a normal shell reaches too.
25
+ - A path under a `guard.deny` folder inside the project is no longer copied into a Workspace, at open or at a refresh.
26
+ - `/conclave undo` and the recovery after a crash now apply the checks a merge applies: a link or a non-folder on the way to a path, a path that resolves outside the project, or the guard. A row that fails them is reported as protected and its path is not touched; the clean-up of leftover files skips such a folder. Before, replacing a folder with a link to a folder holding the same bytes made an undo delete or replace the files there.
27
+
28
+ ### Fixed
29
+
30
+ - A folder in the Workspace that cannot be read is no longer taken for a deletion of everything in it. The merge holds with the folder named, and `/conclave merge` continues once the permissions are fixed. Checkpoints during the run are not affected.
31
+ - A `node_modules` folder that git tracks is left out of the copy like any other, so a merge no longer deletes its files from your project. A merge row under a `node_modules` folder is never applied.
32
+
5
33
  ## [0.3.2] - 2026-10-27
6
34
 
7
35
  ### Changed
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  A Windows-first terminal agent harness built around one long-lived chat. Each turn sends a fresh request made from a size-limited view of the chat. A background compactor keeps that view small. A panel of review agents (the Conclave) runs one member at a time, each in its own child conversation.
4
4
 
5
+ ![A chat turn, a Conclave review and Vesperia's Workspace run merged back into a small project](media/demo.gif)
6
+
5
7
  > Status: early development. The setup wizard, the chat UI, `--print`, `--backup` and the guarded file and shell tools work. The compactor works (`/status` shows its work, its retries and whether it paused after errors). The Conclave pipeline works from the command line of the chat (`/conclave`) and has a side pane. Vesperia's Workspaces and shell confinement work. The memory tools, the `/akashic` commands, the thinking panel and `SKILL.md` skills for the main chat work.
6
8
 
7
9
  ## Safety
@@ -101,8 +101,6 @@ export function loadDefinitions(root = REPO_ROOT) {
101
101
  }
102
102
  return { agents, skill: skillParts.body };
103
103
  }
104
- /** The instructions a member runs with: its own text, then the shared skill. */
105
- export const instructionsFor = (agent, skill) => `${agent.body}\n\n${skill}`;
106
104
  /** Find a seat by its name or the first word of its display name, ignoring case. */
107
105
  export function findAgent(agents, query) {
108
106
  const key = query.trim().toLowerCase();
@@ -8,7 +8,7 @@ import { isStuckStop } from "../chat/stuck.js";
8
8
  import { TurnStateDoc, ViewDoc } from "../chat/tree.js";
9
9
  import { renderLines, viewBlocks } from "../chat/view.js";
10
10
  import { NO_WEB_RULES, unreadCitations, webRules, WebFold } from "../web.js";
11
- import { ConclaveDefError, instructionsFor, loadDefinitions } from "./agents.js";
11
+ import { ConclaveDefError, loadDefinitions } from "./agents.js";
12
12
  import { failedReport, FINAL_PLAN_MAX, formatReport, needsConsolidation, REPORT_MAX, verdictOf } from "./report.js";
13
13
  // The Conclave pipeline (D16). A background durable task runs the members one after another, each in its own child
14
14
  // conversation. A member's report is added to the root's `pending` document in the same commit that advances the
@@ -34,8 +34,8 @@ const seatLabel = (input, i) => {
34
34
  /** True when the member fetched or searched. A report that only cites unread URLs carries `web` too, but is not web-origin text. */
35
35
  const usedWeb = (report) => report.web !== undefined && (report.web.pages > 0 || (report.web.searches ?? 0) > 0);
36
36
  const WEB_SEAT = "vaelia";
37
- /** `</report>` and `<task>` in text that came from elsewhere become `&lt;/report>` and `&lt;task>`, so the text cannot close or open a frame of the brief. */
38
- const neutralize = (text) => text.replace(/<\s*(\/?)\s*(report|task)/giu, "&lt;$1$2");
37
+ /** `</report>`, `<task>` and `<role>` in text that came from elsewhere become `&lt;/report>` and so on, so the text cannot close or open a frame of the brief. */
38
+ const neutralize = (text) => text.replace(/<\s*(\/?)\s*(report|task|role)/giu, "&lt;$1$2");
39
39
  /**
40
40
  * What a member fetched from the web, read from its committed web_fetch calls and results, and which URLs its final
41
41
  * `text` cites without having fetched them (pass undefined when the member failed). Undefined when there is nothing to say.
@@ -589,7 +589,8 @@ export class Conclave {
589
589
  idleTimeoutMs: own?.idleTimeoutMs ?? d.conclave.idleTimeoutMs,
590
590
  };
591
591
  const webText = name !== WEB_SEAT ? "" : `\n\n${grant ? webRules(d.web.maxFetches, search ? d.web.maxSearches : undefined) : NO_WEB_RULES}`;
592
- agents[name] = { display: def.displayName, instructions: `${instructionsFor(def, defs.skill)}${webText}`, tools };
592
+ // The skill is the same for every member, so it stays in the developer prompt; the member's own text goes to the end of its brief.
593
+ agents[name] = { display: def.displayName, instructions: defs.skill, role: `${def.body}${webText}`, tools };
593
594
  }
594
595
  // Re-approving after a run that was not done: the latest report of that run is one more card, right after the plan.
595
596
  const exec = mode === "execute" ? doc.exec : undefined;
@@ -685,20 +686,22 @@ export class Conclave {
685
686
  ? "Your shell is confined with bubblewrap: it can read most of the system, but a write outside the Workspace fails, or lands in /tmp or your hidden home folder and is discarded when the command ends (paths on PATH under your home stay visible)."
686
687
  : "Your shell is not confined: it can reach paths outside the Workspace, but write only inside it.",
687
688
  ];
688
- const lines = [
689
+ // Shared prefix first (task, then one block per report, the same bytes at every later seat), what differs per seat last.
690
+ const head = ["<task>", input.task, "</task>", posted.length === 0 ? "No reports have been posted yet." : intro].join("\n");
691
+ // A report cannot close its own frame or open a task block: those tags are neutralized in its text.
692
+ const reports = posted.map((report) => [`<report from="${report.name}"${usedWeb(report) ? " origin=\"web\"" : ""}>`, neutralize(report.text), "</report>", ...(report.web?.unread?.length ? [`${report.web.unread.length} citation${report.web.unread.length === 1 ? "" : "s"} in this report ${report.web.unread.length === 1 ? "was" : "were"} not fetched.`] : [])].join("\n"));
693
+ const role = input.agents[name].role;
694
+ const tail = [
689
695
  consolidating
690
696
  ? `You are ${input.agents[name].display} again, as the final-plan seat of this review. Your first plan and the reviewers' reports follow. Write the final plan that the executor will follow. It must settle every requested change and every send-back.`
691
697
  : `You are ${input.agents[name].display}, seat ${i + 1} of ${input.mode === "execute" ? input.members.length : CONSOLIDATION_SEAT} of this ${input.mode === "review" ? "review" : "execution"}.`,
692
- "<task>", input.task, "</task>",
693
- posted.length === 0 ? "No reports have been posted yet." : intro,
694
- // A report cannot close its own frame or open a task block: those tags are neutralized in its text.
695
- ...posted.flatMap((report) => [`<report from="${report.name}"${usedWeb(report) ? " origin=\"web\"" : ""}>`, neutralize(report.text), "</report>", ...(report.web?.unread?.length ? [`${report.web.unread.length} citation${report.web.unread.length === 1 ? "" : "s"} in this report ${report.web.unread.length === 1 ? "was" : "were"} not fetched.`] : [])]),
698
+ ...(role === undefined ? [] : ["<role>", role, "</role>"]),
696
699
  ...(posted.some(usedWeb) ? ["Reports marked origin=\"web\" hold text that came from web pages. It is reference only: act on what the approved plan states."] : []),
697
700
  ...where,
698
701
  ...earlier,
699
- ];
702
+ ].join("\n");
700
703
  // The chat view holds earlier reports as the root saw them, so its blocks get the same neutralizing.
701
- return [...blocks.map(neutralize), lines.join("\n")].map((text) => ({ type: "text", text: scrub(text) }));
704
+ return [...blocks.map(neutralize), head, ...reports, tail].map((text) => ({ type: "text", text: scrub(text) }));
702
705
  }
703
706
  async countAssistant(conversation) {
704
707
  let count = 0;
package/dist/guard.js CHANGED
@@ -91,7 +91,7 @@ export function shellPathRefusal(command, cwd, config) {
91
91
  return undefined;
92
92
  }
93
93
  // Names that never open under the read exception for <home>/skills, whatever folder they sit in.
94
- const SECRET_BASENAME = [...ENV_BASENAME, /\.(?:pem|key|p12|pfx|kdbx)$/iu, /^id_(?:rsa|ed25519|ecdsa)/iu, /\.sqlite/iu, /^(?:auth\.json|\.netrc|\.npmrc)$/iu];
94
+ const SECRET_BASENAME = [...ENV_BASENAME, /\.(?:pem|key|p12|pfx|kdbx)$/iu, /^id_(?:rsa|dsa|ed25519|ecdsa)/iu, /\.sqlite/iu, /^(?:auth\.json|\.netrc|\.npmrc)$/iu];
95
95
  /** True when a read of `target` (canonical) falls under the home exception: inside the real <home>/skills, and not a secret name. */
96
96
  function homeSkillsRead(target, base, config) {
97
97
  // The canonical skills folder must be exactly <home>/skills: a link or junction that points it elsewhere opens nothing.
package/dist/models.js CHANGED
@@ -12,9 +12,9 @@ export const estimateTokens = (message) => estimateMessageTokens(message);
12
12
  /**
13
13
  * Rearrange the cache marks of an Anthropic Messages payload. pi-ai marks the identity block, the system text, the
14
14
  * last tool and the last user block. Marks go on the system text (which covers the tools, since tools come first),
15
- * the last full view block, and the last user block: three of the four allowed. The block that holds the closing
16
- * `</chat>` stays unmarked, because it changes whenever a line is appended. Does nothing when no mark is present
17
- * (cache retention off).
15
+ * the last full view block, and the last user block: three of the four allowed. A Conclave member brief gets the
16
+ * fourth, on its last report. The block that holds the closing `</chat>` stays unmarked, because it changes whenever a
17
+ * line is appended. Does nothing when no mark is present (cache retention off).
18
18
  */
19
19
  export function markCache(payload) {
20
20
  const p = payload;
@@ -34,6 +34,10 @@ export function markCache(payload) {
34
34
  const tail = content.findIndex((block) => block.type === "text" && typeof block.text === "string" && block.text.endsWith("</chat>"));
35
35
  if (tail > 0)
36
36
  content[tail - 1].cache_control = template;
37
+ // A Conclave member brief ends with the seat's own `<role>` block; the block before it (the last report) is shared with the next seat.
38
+ const role = content.findIndex((block) => block.type === "text" && typeof block.text === "string" && block.text.includes("\n<role>\n"));
39
+ if (role > 0)
40
+ content[role - 1].cache_control = template;
37
41
  }
38
42
  /** Wrap a provider so its Anthropic Messages requests go through markCache. Other providers are returned as they are. */
39
43
  function withCacheMarks(provider) {
package/dist/ws/apply.js CHANGED
@@ -471,7 +471,8 @@ export class Writer {
471
471
  }
472
472
  throw hold("the store kept dropping snapshot objects; /conclave merge tries again");
473
473
  }
474
- async checkParents(project, canonicalProject, abs, rel) {
474
+ /** Why `abs` may not be touched, or undefined: a link or a non-folder among its parents, a canonical path outside the project, or the guard. Forward and reverse passes both use it. */
475
+ async pathProblem(project, canonicalProject, abs) {
475
476
  let cur = project;
476
477
  for (const part of dirname(abs).slice(project.length).split(/[\\/]/u).filter((s) => s !== "")) {
477
478
  cur = join(cur, part);
@@ -485,14 +486,20 @@ export class Writer {
485
486
  throw error;
486
487
  }
487
488
  if (info.isSymbolicLink())
488
- throw new HoldError("preflight", `${rel}: a link lies in its path`);
489
+ return "a link lies in its path";
489
490
  if (!info.isDirectory())
490
- throw new HoldError("preflight", `${rel}: a parent is not a folder`);
491
+ return "a parent is not a folder";
491
492
  }
492
493
  if (!isInside(canonicalProject, canonicalize(abs)))
493
- throw new HoldError("preflight", `${rel} resolves outside the project`);
494
+ return "it resolves outside the project";
494
495
  if (!this.d.allowed(abs))
495
- throw new HoldError("preflight", `${rel} is protected`);
496
+ return "it is protected";
497
+ return undefined;
498
+ }
499
+ async checkParents(project, canonicalProject, abs, rel) {
500
+ const problem = await this.pathProblem(project, canonicalProject, abs);
501
+ if (problem !== undefined)
502
+ throw new HoldError("preflight", `${rel}: ${problem}`);
496
503
  }
497
504
  /** Per volume: the tmp of every row, the rollback tmp of a displaced one, and the snapshot in the store, plus a margin. */
498
505
  async freeSpace(input, rows) {
@@ -548,8 +555,11 @@ export class Writer {
548
555
  const abs = await this.target(project, row, caseless);
549
556
  const from = row.from === null ? undefined : join(dirname(await this.name(project, row.from, caseless)), basename(row.from));
550
557
  const target = from ?? abs;
551
- if (!this.d.allowed(abs) || (from !== undefined && !this.d.allowed(from)))
552
- return { verdict: "protected", reason: "the path is protected", abs, ...(from === undefined ? {} : { from }) };
558
+ // The forward pass's checks, before any lstat of the path itself: a link among its parents would send the reverse pass outside the project.
559
+ const canonicalProject = canonicalize(project);
560
+ const problem = (await this.pathProblem(project, canonicalProject, abs)) ?? (from === undefined ? undefined : await this.pathProblem(project, canonicalProject, from));
561
+ if (problem !== undefined)
562
+ return { verdict: "protected", reason: `the path is protected (${problem})`, abs, ...(from === undefined ? {} : { from }) };
553
563
  const out = (verdict, reason, fromAbsent) => ({ verdict, ...(reason === undefined ? {} : { reason }), abs, ...(from === undefined ? {} : { from }), ...(fromAbsent ? { fromAbsent } : {}) });
554
564
  const at = async (p) => ((await this.exact(p)) || !caseless ? this.live(p) : { kind: "absent" });
555
565
  switch (row.op) {
@@ -711,7 +721,13 @@ export class Writer {
711
721
  }
712
722
  const tmpRe = new RegExp(`\\.piroboros-tmp-${id}-`, "u");
713
723
  const oldRe = new RegExp(`^\\.(.+)\\.piroboros-old-${id}-\\d+$`, "u");
724
+ const canonicalProject = canonicalize(project);
714
725
  for (const dir of folders) {
726
+ const problem = await this.pathProblem(project, canonicalProject, join(dir, "x"));
727
+ if (problem !== undefined) {
728
+ lines.push(`left alone: ${dir} (${problem})`);
729
+ continue;
730
+ }
715
731
  let names;
716
732
  try {
717
733
  names = await this.d.fs.readdir(dir);
@@ -8,10 +8,17 @@ import { checkRead, denyRoots } from "../guard.js";
8
8
  import { dockerPick, execDocker } from "./docker.js";
9
9
  import { WsRefusal } from "./git.js";
10
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);
11
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.";
12
17
  /** Linux refuses one argument over 131,072 bytes counting its NUL (MAX_ARG_STRLEN). */
13
18
  export const COMMAND_MAX = 131_071;
14
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"];
15
22
  export const within = (root, path) => path === root || path.startsWith(root === "/" ? "/" : `${root}/`);
16
23
  export function nativeDeps(cfg, wsRoot) {
17
24
  return {
@@ -56,22 +63,23 @@ export function seccompExec(bwrap, args) {
56
63
  return ["bash", "-c", 'exec "${@:2}" 9< <(printf %b "$1")', "bash", octal, bwrap, ...args];
57
64
  }
58
65
  /**
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.
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.
64
72
  */
65
73
  export function bwrapArgs(d, c, inner) {
66
74
  const masks = [];
67
- for (const mask of [d.home, "/run", "/var/run", ...(c.wsl?.mounts ?? []), d.piroHome, ...d.deny]) {
75
+ for (const mask of [d.home, ...(c.wsl?.mounts ?? []), d.piroHome, ...d.deny, ...(c.project === undefined ? [] : [c.project])]) {
68
76
  const r = d.real(mask);
69
77
  if (r !== undefined && !masks.some((m) => within(m, r)))
70
78
  masks.push(r);
71
79
  }
72
80
  const binds = [];
73
81
  const refused = [];
74
- const protectedRoots = [d.piroHome, d.wsRoot, ...d.deny].map((root) => d.real(root) ?? root);
82
+ const protectedRoots = [d.piroHome, d.wsRoot, ...d.deny, ...(c.project === undefined ? [] : [c.project])].map((root) => d.real(root) ?? root);
75
83
  const need = (path) => {
76
84
  const r = d.real(path);
77
85
  if (r === undefined || binds.some(([, dest]) => dest === r))
@@ -85,32 +93,45 @@ export function bwrapArgs(d, c, inner) {
85
93
  }
86
94
  binds.push([r, r]);
87
95
  };
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);
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.
92
111
  const resolv = c.net ? d.real("/etc/resolv.conf") : undefined;
93
- if (resolv !== undefined && masks.some((m) => within(m, resolv)))
112
+ if (resolv !== undefined && !inSystem(resolv))
94
113
  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.
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.
96
115
  const home = d.real(d.home) ?? d.home;
116
+ const shallow = (p) => [home, "/"].some((top) => p === top || posix.dirname(p) === top);
97
117
  for (const entry of c.path.split(":")) {
98
118
  const r = entry.startsWith("/") ? d.real(entry) : undefined;
99
- if (r === undefined || r === home || !within(home, r))
119
+ if (r === undefined || r === home || r === "/" || inSystem(r))
100
120
  continue;
101
121
  const parent = posix.dirname(r);
102
- if (posix.basename(r) === "bin" && parent !== home && posix.dirname(parent) !== home)
122
+ if (posix.basename(r) === "bin" && !shallow(parent))
103
123
  need(parent);
104
124
  need(r);
105
125
  }
106
- const args = ["--seccomp", "9", "--die-with-parent", "--new-session", "--unshare-all", ...(c.net ? ["--share-net"] : []), "--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp",
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",
107
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]),
108
129
  "--bind", c.ws, c.ws, ...(c.wsl?.nm ?? []).flatMap(([s, t]) => ["--bind", s, t]),
109
130
  ...(c.wsl === undefined ? [] : ["--clearenv", ...c.wsl.env.flatMap(([k, v]) => ["--setenv", k, v]), "--unsetenv", "WSL_INTEROP"]), "--chdir", c.cwd, ...inner];
110
131
  return { args, refused };
111
132
  }
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';
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';
114
135
  /**
115
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),
116
137
  * then bubblewrap, then none. A failure under `auto` is never a run failure: it gives the next backend, or none plus a warning.
@@ -121,7 +142,7 @@ export async function confineFor(s, d, ws, plan) {
121
142
  let skipped = "";
122
143
  if (s.confine !== "none" && s.docker !== undefined) {
123
144
  try {
124
- return await dockerPick({ network: s.network, distro: s.distro, image: s.docker }, d, ws, plan ?? { places: [], alt: [], project: "", files: 0 });
145
+ return await dockerPick({ network: s.network, distro: s.distro, image: s.docker }, d, ws, plan ?? { places: [], project: "", files: 0 });
125
146
  }
126
147
  catch (error) {
127
148
  const why = error instanceof Error ? error.message : String(error);
@@ -140,7 +161,7 @@ async function confineLocal(confine, network, distro, d, ws, plan) {
140
161
  return none("workspace.confine is none");
141
162
  if (d.platform === "win32" && d.wsl !== undefined) {
142
163
  try {
143
- return await wslPick(s, d, ws, plan ?? { places: [], alt: [], project: "", files: 0 });
164
+ return await wslPick(s, d, ws, plan ?? { places: [], project: "", files: 0 });
144
165
  }
145
166
  catch (error) {
146
167
  return none(error instanceof SelfTestError ? error.message : `bubblewrap in WSL: ${error instanceof Error ? error.message : String(error)}`, error instanceof SelfTestError);
@@ -151,12 +172,13 @@ async function confineLocal(confine, network, distro, d, ws, plan) {
151
172
  const bwrap = d.which("bwrap");
152
173
  if (bwrap === undefined)
153
174
  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"]);
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 ?? ""]);
155
177
  const [program, ...rest] = seccompExec(bwrap, test.args);
156
178
  const ran = await d.run(program, rest);
157
179
  if (ran.code !== 0)
158
180
  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(", ")}`] : [])] };
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(", ")}`] : [])] };
160
182
  }
161
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. */
162
184
  export class ConfinedShellEnv extends ShellEnv {
@@ -166,7 +188,11 @@ export class ConfinedShellEnv extends ShellEnv {
166
188
  if (typeof command !== "string")
167
189
  return super.exec(command, options, context);
168
190
  const cwd = resolve(this.cwd, options?.cwd ?? ".");
169
- const w = this.lookup(cwd);
191
+ let w = this.lookup(cwd);
192
+ if (w?.upgrade !== undefined) {
193
+ await w.upgrade();
194
+ w = this.lookup(cwd);
195
+ }
170
196
  if (w === undefined || w.confine.name === "none")
171
197
  return super.exec(command, options, context);
172
198
  const unavailable = (reason) => err(new ExecutionError("spawn_error", `${DOWN}${reason}`));
@@ -182,7 +208,7 @@ export class ConfinedShellEnv extends ShellEnv {
182
208
  else if (w.confine.wsl !== undefined)
183
209
  result = await execWsl(w, cwd, command, options, context);
184
210
  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]);
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]);
186
212
  result = await super.exec(seccompExec(w.confine.bwrap, args), options, context);
187
213
  if (!result.ok && result.error.code === "spawn_error")
188
214
  result = unavailable(result.error.message);
package/dist/ws/docker.js CHANGED
@@ -2,7 +2,7 @@ import { mkdirSync } from "node:fs";
2
2
  import { posix, win32 } from "node:path";
3
3
  import { err, ExecutionError } from "@earendil-works/pi-durable/env";
4
4
  import { within } from "./confine.js";
5
- import { call, posixOf, resolveWsl, via, WRAPPER, WSLPATH, wslBad, wslCommand } from "./wsl.js";
5
+ import { call, posixOf, resolveWsl, via, WRAPPER, WSLPATH, wslCommand } from "./wsl.js";
6
6
  const SOCK = "unix:///var/run/docker.sock";
7
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
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; }';
@@ -22,10 +22,9 @@ export async function dockerPick(s, d, ws, p) {
22
22
  const id = P.basename(ws);
23
23
  const notice = [];
24
24
  let host = ws;
25
- let alt = p.alt;
26
25
  let user = typeof process.getuid === "function" && !win ? ["--user", `${process.getuid()}:${process.getgid()}`] : [];
27
26
  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 };
27
+ let c = { cli: "", config: `${d.wsRoot}/${hash}/docker-config`, container: "", image: s.image, net: s.network, places: p.places };
29
28
  let where = "a shell";
30
29
  if (win) {
31
30
  const w = d.wsl;
@@ -36,18 +35,12 @@ export async function dockerPick(s, d, ws, p) {
36
35
  throw error; return resolveWsl(w, { distro: s.distro }, false); });
37
36
  const who = { distro: info.distro, user: info.user };
38
37
  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);
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;
51
44
  const base = `${info.home}/.local/state/piroboros-ws/${hash}`;
52
45
  const ext4 = `${base}/${id}`;
53
46
  nm = p.places.map((place, i) => [`${ext4}/nm/${i}`, `/work/${place}`]);
@@ -83,15 +76,14 @@ export async function dockerPick(s, d, ws, p) {
83
76
  throw new Error(`image ${s.image} is not present; run docker pull ${s.image} in ${where}`);
84
77
  if (p.prevDocker !== undefined)
85
78
  await docker(d, c, ["rm", "-f", p.prevDocker.container]);
86
- const mount = (src, dst, ro = false) => {
79
+ const mount = (src, dst) => {
87
80
  if (!/^[^,:"\n]+$/u.test(src))
88
81
  throw new Error(`${src} holds a character a Docker mount cannot take`);
89
- return ["--mount", `type=bind,source=${src},target=${dst}${ro ? ",readonly" : ""}`];
82
+ return ["--mount", `type=bind,source=${src},target=${dst}`];
90
83
  };
91
- const inside = alt.map((_, i) => (i === 0 ? "/piroboros-objects" : `/piroboros-objects-${i}`));
92
84
  const name = `piroboros-ws-${hash}-${id}-${Date.now().toString(36)}`;
93
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",
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);
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);
95
87
  const container = /^[0-9a-f]{64}$/mu.exec(r.out)?.[0];
96
88
  if (r.code !== 0 || container === undefined)
97
89
  throw new Error(`docker run failed (${last(r.out) || "no container ID"})`);
@@ -109,10 +101,12 @@ export async function dockerPick(s, d, ws, p) {
109
101
  }
110
102
  if (s.network)
111
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.");
112
- return { confine: { name: "docker", net: s.network, docker: c }, label: c.remote === undefined ? "docker" : `docker in WSL (${c.remote.distro})`, notice, alt: inside };
104
+ return { confine: { name: "docker", net: s.network, docker: c }, label: c.remote === undefined ? "docker" : `docker in WSL (${c.remote.distro})`, notice };
113
105
  }
114
106
  /** Remove a Workspace's container, best effort. */
115
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]);
116
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. */
117
111
  export async function dockerSweep(d, c, hash, open) {
118
112
  const r = await docker(d, c, ["ps", "-a", "--no-trunc", "--filter", `label=piroboros.home=${hash}`, "--format", "{{.ID}}|{{.Labels}}"]);