piroboros 0.2.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 (43) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/NOTICE +12 -0
  3. package/README.md +11 -8
  4. package/dist/chat/log.js +1 -1
  5. package/dist/chat/turn.js +0 -15
  6. package/dist/conclave/pipeline.js +216 -13
  7. package/dist/config.js +121 -12
  8. package/dist/diff.js +90 -0
  9. package/dist/durable.js +1 -1
  10. package/dist/guard.js +169 -13
  11. package/dist/learn.js +938 -0
  12. package/dist/memory/akashic/tools.js +25 -28
  13. package/dist/memory/mnemosia/conflicts.js +0 -4
  14. package/dist/memory/mnemosia/orchestrator.js +1 -11
  15. package/dist/memory/mnemosia/policy.js +0 -3
  16. package/dist/memory/mnemosia/rank.js +0 -4
  17. package/dist/memory/mnemosia/rerank.js +3 -30
  18. package/dist/memory/mnemosia/rollback.js +1 -149
  19. package/dist/memory/mnemosia/tokens.js +1 -11
  20. package/dist/memory/mnemosia/tools.js +0 -10
  21. package/dist/memory/mnemosia/types.js +0 -2
  22. package/dist/runtime.js +51 -6
  23. package/dist/search.js +25 -12
  24. package/dist/shell.js +2 -2
  25. package/dist/tui/app.js +15 -3
  26. package/dist/tui/commands.js +5 -2
  27. package/dist/tui/settings.js +4 -1
  28. package/dist/tui/thinking/parse.js +0 -3
  29. package/dist/ws/apply.js +817 -0
  30. package/dist/ws/cas.js +144 -0
  31. package/dist/ws/confine.js +194 -0
  32. package/dist/ws/docker.js +151 -0
  33. package/dist/ws/git.js +162 -0
  34. package/dist/ws/lww.js +48 -0
  35. package/dist/ws/merge.js +129 -0
  36. package/dist/ws/workspace.js +1596 -0
  37. package/dist/ws/wsl.js +259 -0
  38. package/docs/conclave.md +14 -0
  39. package/docs/configuration.md +10 -4
  40. package/docs/privacy.md +3 -1
  41. package/docs/tools.md +43 -1
  42. package/package.json +1 -2
  43. package/settings.json.example +3 -1
package/dist/config.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomUUID, createHash } from "node:crypto";
2
2
  import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { isAbsolute, join, parse } from "node:path";
4
+ import { isAbsolute, join, parse, resolve } from "node:path";
5
5
  import { canonicalize, isInside, samePath, segments } from "./paths.js";
6
6
  // Home directory, config files, settings schema and config integrity. Every filesystem path piroboros
7
7
  // owns is derived from the validated home returned by resolveHome().
@@ -142,6 +142,7 @@ export const CONCLAVE_MEMBERS = ["samaela", "nytheria", "elaria", "raskreia", "a
142
142
  export const SETTINGS_DEFAULTS = {
143
143
  thinking: "medium",
144
144
  compactor: { enabled: true, thinking: "off", maxConcurrent: 8, allowThirdParty: false },
145
+ learning: { thinking: "low", everyTurns: 10, allowThirdParty: false },
145
146
  conclave: { maxTurns: 64, idleTimeoutMs: 600_000, reportMaxChars: 4_000 },
146
147
  gateTimeoutMs: 120_000,
147
148
  cacheRetention: "short",
@@ -149,6 +150,7 @@ export const SETTINGS_DEFAULTS = {
149
150
  shellTimeoutMs: 600_000,
150
151
  tui: { thinkingSteps: "summary" },
151
152
  telemetry: true,
153
+ workspace: { enabled: true, nested: "ask", confine: "auto", network: true },
152
154
  web: { enabled: false, maxFetches: 10, maxSearches: 5 },
153
155
  };
154
156
  /** A host name for web.allowHosts and web.queryHosts: lower case DNS labels, no scheme, port, path or wildcard. */
@@ -193,7 +195,7 @@ export function validateSettings(value) {
193
195
  issues.push(`${path}: must be an integer from ${min}${max === Number.MAX_SAFE_INTEGER ? " up" : ` to ${max}`}`);
194
196
  },
195
197
  };
196
- known(value, ["main", "thinking", "compactor", "conclave", "gateTimeoutMs", "cacheRetention", "shellEnvAllow", "shellTimeoutMs", "guard", "tui", "planning", "telemetry", "web"], "");
198
+ known(value, ["main", "thinking", "compactor", "learning", "conclave", "gateTimeoutMs", "cacheRetention", "shellEnvAllow", "shellTimeoutMs", "guard", "workspace", "tui", "planning", "telemetry", "web"], "");
197
199
  check.ref(value.main, "main");
198
200
  check.level(value.thinking, "thinking");
199
201
  if (value.compactor !== undefined) {
@@ -208,6 +210,17 @@ export function validateSettings(value) {
208
210
  check.bool(value.compactor.allowThirdParty, "compactor.allowThirdParty");
209
211
  }
210
212
  }
213
+ if (value.learning !== undefined) {
214
+ if (!isObj(value.learning))
215
+ issues.push("learning: must be an object");
216
+ else {
217
+ known(value.learning, ["model", "thinking", "everyTurns", "allowThirdParty"], "learning");
218
+ check.ref(value.learning.model, "learning.model");
219
+ check.level(value.learning.thinking, "learning.thinking");
220
+ check.int(value.learning.everyTurns, "learning.everyTurns", 3, 100);
221
+ check.bool(value.learning.allowThirdParty, "learning.allowThirdParty");
222
+ }
223
+ }
211
224
  if (value.conclave !== undefined) {
212
225
  if (!isObj(value.conclave))
213
226
  issues.push("conclave: must be an object");
@@ -255,9 +268,50 @@ export function validateSettings(value) {
255
268
  if (!isObj(value.guard))
256
269
  issues.push("guard: must be an object");
257
270
  else {
258
- known(value.guard, ["deny"], "guard");
271
+ known(value.guard, ["deny", "allow"], "guard");
259
272
  if (value.guard.deny !== undefined && !(Array.isArray(value.guard.deny) && value.guard.deny.every((item) => typeof item === "string" && isAbsolute(item))))
260
273
  issues.push("guard.deny: must be an array of absolute paths");
274
+ // Structural only: the profile-dependent rules (allowEntryProblem) run on save and at use, so a settings.json moved between machines still loads.
275
+ const { allow, deny } = value.guard;
276
+ if (allow !== undefined && !(Array.isArray(allow) && allow.every((item) => typeof item === "string" && isAbsolute(item))))
277
+ issues.push("guard.allow: must be an array of absolute paths");
278
+ else if (Array.isArray(allow) && Array.isArray(deny) && allow.some((item) => deny.some((root) => typeof root === "string" && isAbsolute(root) && samePath(resolve(root), resolve(item)))))
279
+ issues.push("guard.allow: an entry equals a guard.deny entry");
280
+ }
281
+ }
282
+ if (value.workspace !== undefined) {
283
+ if (!isObj(value.workspace))
284
+ issues.push("workspace: must be an object");
285
+ else {
286
+ known(value.workspace, ["enabled", "nested", "confine", "network", "wsl", "docker"], "workspace");
287
+ check.bool(value.workspace.enabled, "workspace.enabled");
288
+ check.bool(value.workspace.network, "workspace.network");
289
+ if (value.workspace.confine !== undefined && !["auto", "none", "docker"].includes(value.workspace.confine))
290
+ issues.push('workspace.confine: must be "auto", "none" or "docker"');
291
+ const docker = value.workspace.docker;
292
+ if (docker !== undefined) {
293
+ if (!isObj(docker))
294
+ issues.push("workspace.docker: must be an object");
295
+ else {
296
+ known(docker, ["image"], "workspace.docker");
297
+ if (docker.image !== undefined && !(typeof docker.image === "string" && /^[a-z0-9][a-z0-9._/:@-]{0,254}$/u.test(docker.image)))
298
+ issues.push("workspace.docker.image: must be an image reference such as node:26.12.1-trixie@sha256:<digest>");
299
+ }
300
+ }
301
+ if (value.workspace.confine === "docker" && !(isObj(docker) && typeof docker.image === "string"))
302
+ issues.push('workspace.confine "docker" needs workspace.docker.image');
303
+ if (value.workspace.nested !== undefined && !["ask", "copy", "inplace"].includes(value.workspace.nested))
304
+ issues.push('workspace.nested: must be "ask", "copy" or "inplace"');
305
+ const wsl = value.workspace.wsl;
306
+ if (wsl !== undefined) {
307
+ if (!isObj(wsl))
308
+ issues.push("workspace.wsl: must be an object");
309
+ else {
310
+ known(wsl, ["distro"], "workspace.wsl");
311
+ if (wsl.distro !== undefined && !(typeof wsl.distro === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(wsl.distro) && !/^docker-desktop/iu.test(wsl.distro)))
312
+ issues.push("workspace.wsl.distro: must be a WSL distribution name (letters, digits, . _ -), not docker-desktop");
313
+ }
314
+ }
261
315
  }
262
316
  }
263
317
  if (value.web !== undefined) {
@@ -304,12 +358,15 @@ export function withDefaults(settings) {
304
358
  main: settings.main,
305
359
  thinking: settings.thinking ?? SETTINGS_DEFAULTS.thinking,
306
360
  compactor: { ...SETTINGS_DEFAULTS.compactor, ...settings.compactor },
361
+ learning: { ...SETTINGS_DEFAULTS.learning, ...settings.learning },
307
362
  conclave: { ...SETTINGS_DEFAULTS.conclave, ...settings.conclave },
308
363
  gateTimeoutMs: settings.gateTimeoutMs ?? SETTINGS_DEFAULTS.gateTimeoutMs,
309
364
  cacheRetention: settings.cacheRetention ?? SETTINGS_DEFAULTS.cacheRetention,
310
365
  shellEnvAllow: settings.shellEnvAllow ?? [],
311
366
  shellTimeoutMs: settings.shellTimeoutMs ?? SETTINGS_DEFAULTS.shellTimeoutMs,
312
367
  guardDeny: settings.guard?.deny ?? [],
368
+ guardAllow: settings.guard?.allow ?? [],
369
+ workspace: { ...SETTINGS_DEFAULTS.workspace, ...settings.workspace },
313
370
  planning: settings.planning ?? true,
314
371
  telemetry: settings.telemetry ?? SETTINGS_DEFAULTS.telemetry,
315
372
  web: {
@@ -347,7 +404,7 @@ export const SETTINGS_CHANGED = "settings.json changed outside piroboros; run /r
347
404
  * The only settings write. It refuses when the file is not what piroboros last wrote (or was never recorded),
348
405
  * then applies `edit`, validates, writes atomically and records the hash of the string it wrote.
349
406
  */
350
- function checkedWrite(home, edit) {
407
+ function checkedWrite(home, edit, profile) {
351
408
  const path = homePaths(home).settings;
352
409
  let text;
353
410
  try {
@@ -366,7 +423,7 @@ function checkedWrite(home, edit) {
366
423
  catch (error) {
367
424
  throw new ConfigError("json_invalid", `${path} is not valid JSON: ${error.message}`);
368
425
  }
369
- const merged = validateSettings(edit(isObj(current) ? current : {}));
426
+ const merged = checkAllow(validateSettings(edit(isObj(current) ? current : {})), isObj(current) ? current : undefined, profile, home);
370
427
  const written = `${JSON.stringify(merged, null, 2)}\n`;
371
428
  writeTextAtomic(path, written, 0o600);
372
429
  const record = readIntegrity(home);
@@ -374,9 +431,42 @@ function checkedWrite(home, edit) {
374
431
  writeJsonFile(homePaths(home).integrity, record);
375
432
  return merged;
376
433
  }
434
+ /** The pi agent dir: PI_CODING_AGENT_DIR when it is set and absolute, otherwise <profile>/.pi/agent. */
435
+ export function piAgentDir(profile, env = process.env) {
436
+ const set = env.PI_CODING_AGENT_DIR;
437
+ return set !== undefined && isAbsolute(set) ? resolve(set) : join(profile, ".pi", "agent");
438
+ }
439
+ /**
440
+ * Why `entry` may not be a guard.allow entry, or undefined. Lexical after path.resolve (no filesystem access): it must be
441
+ * at or inside <agent dir>/extensions, or strictly inside a guard.deny root, and never at or inside the piroboros home,
442
+ * ~/.ssh or ~/.claude. The guard repeats the check at use and adds the link test.
443
+ */
444
+ export function allowEntryProblem(entry, deny, profile, home) {
445
+ if (!isAbsolute(entry))
446
+ return "must be an absolute path";
447
+ const at = resolve(entry);
448
+ if ([home, join(profile, ".ssh"), join(profile, ".claude")].some((root) => isInside(resolve(root), at)))
449
+ return "must not be inside the piroboros data directory, ~/.ssh or ~/.claude";
450
+ if (deny.some((root) => samePath(resolve(root), at)))
451
+ return "equals a guard.deny entry";
452
+ if (isInside(join(piAgentDir(profile), "extensions"), at))
453
+ return undefined;
454
+ return deny.some((root) => isInside(resolve(root), at)) ? undefined : "must be at or inside the pi extensions folder, or strictly inside a guard.deny root";
455
+ }
456
+ /** `settings` unchanged, or a SettingsError naming each guard.allow entry that is new in it (against `before`) and fails allowEntryProblem. Old entries stay so any other key can still be saved. */
457
+ function checkAllow(settings, before, profile, home) {
458
+ const old = before?.guard?.allow ?? [];
459
+ const issues = (settings.guard?.allow ?? []).filter((entry) => !old.includes(entry)).flatMap((entry) => {
460
+ const problem = allowEntryProblem(entry, settings.guard?.deny ?? [], profile, home);
461
+ return problem === undefined ? [] : [`guard.allow: ${entry} ${problem}`];
462
+ });
463
+ if (issues.length > 0)
464
+ throw new SettingsError(issues);
465
+ return settings;
466
+ }
377
467
  /** Merges only the patched keys through the checked write. */
378
- export function mergeSettings(home, patch) {
379
- return checkedWrite(home, (current) => mergeDeep(current, patch));
468
+ export function mergeSettings(home, patch, profile = profileDir()) {
469
+ return checkedWrite(home, (current) => mergeDeep(current, patch), profile);
380
470
  }
381
471
  function unsetPath(obj, parts) {
382
472
  const [head, ...rest] = parts;
@@ -395,12 +485,12 @@ function unsetPath(obj, parts) {
395
485
  return out;
396
486
  }
397
487
  /** Removes one key by its dotted path, such as "tui.thinkingSteps", and any parent object left empty. */
398
- export function unsetSettings(home, path) {
399
- return checkedWrite(home, (current) => unsetPath(current, path.split(".")));
488
+ export function unsetSettings(home, path, profile = profileDir()) {
489
+ return checkedWrite(home, (current) => unsetPath(current, path.split(".")), profile);
400
490
  }
401
491
  /** The settings a change would produce, validated. Throws SettingsError when the result is invalid. Nothing is written. */
402
- export function previewSettings(current, change) {
403
- return validateSettings("unset" in change ? unsetPath(current, change.unset.split(".")) : mergeDeep(current, change.set));
492
+ export function previewSettings(current, change, profile = profileDir(), home = process.env.PIROBOROS_HOME || defaultHome(profile)) {
493
+ return checkAllow(validateSettings("unset" in change ? unsetPath(current, change.unset.split(".")) : mergeDeep(current, change.set)), current, profile, home);
404
494
  }
405
495
  /** The value at a dotted path such as "web.search.provider", or undefined. */
406
496
  export function getSetting(settings, path) {
@@ -430,11 +520,21 @@ function securityKeys(settings) {
430
520
  main: settings.main,
431
521
  "compactor.model": isObj(settings.compactor) ? settings.compactor.model : undefined,
432
522
  "compactor.allowThirdParty": isObj(settings.compactor) ? settings.compactor.allowThirdParty : undefined,
523
+ "learning.model": isObj(settings.learning) ? settings.learning.model : undefined,
524
+ "learning.allowThirdParty": isObj(settings.learning) ? settings.learning.allowThirdParty : undefined,
433
525
  "conclave.defaultModel": isObj(settings.conclave) ? settings.conclave.defaultModel : undefined,
434
526
  "conclave.members.models": members,
435
527
  shellEnvAllow: settings.shellEnvAllow,
436
528
  shellTimeoutMs: settings.shellTimeoutMs,
437
529
  "guard.deny": isObj(settings.guard) ? settings.guard.deny : undefined,
530
+ "guard.allow": isObj(settings.guard) ? settings.guard.allow : undefined,
531
+ // Whether Vesperia writes live files directly (in place) is a trust decision.
532
+ "workspace.enabled": isObj(settings.workspace) ? settings.workspace.enabled : undefined,
533
+ "workspace.nested": isObj(settings.workspace) ? settings.workspace.nested : undefined,
534
+ "workspace.confine": isObj(settings.workspace) ? settings.workspace.confine : undefined,
535
+ "workspace.network": isObj(settings.workspace) ? settings.workspace.network : undefined,
536
+ "workspace.wsl.distro": isObj(settings.workspace) && isObj(settings.workspace.wsl) ? settings.workspace.wsl.distro : undefined,
537
+ "workspace.docker.image": isObj(settings.workspace) && isObj(settings.workspace.docker) ? settings.workspace.docker.image : undefined,
438
538
  "web.enabled": isObj(settings.web) ? settings.web.enabled : undefined,
439
539
  "web.maxFetches": isObj(settings.web) ? settings.web.maxFetches : undefined,
440
540
  "web.maxSearches": isObj(settings.web) ? settings.web.maxSearches : undefined,
@@ -488,7 +588,7 @@ export function securityChanges(current, change) {
488
588
  const field = (path, type, applies, extra = {}) => ({
489
589
  path, type, applies, security: SECURITY_KEYS.includes(path) || /^conclave\.members\.[a-z]+\.model$/u.test(path), ...extra,
490
590
  });
491
- /** Every leaf key of settings.json (56). A test checks it against validateSettings, securityKeys and the defaults. */
591
+ /** Every leaf key of settings.json (66). A test checks it against validateSettings, securityKeys and the defaults. */
492
592
  export const SETTING_FIELDS = [
493
593
  field("main", "ref", "turn", { role: "main" }),
494
594
  field("thinking", "enum", "turn", { values: THINKING_LEVELS }),
@@ -497,6 +597,10 @@ export const SETTING_FIELDS = [
497
597
  field("compactor.thinking", "enum", "now", { values: THINKING_LEVELS }),
498
598
  field("compactor.maxConcurrent", "int", "now", { min: 1, max: 8 }),
499
599
  field("compactor.allowThirdParty", "bool", "now"),
600
+ field("learning.model", "ref", "now", { role: "main" }),
601
+ field("learning.thinking", "enum", "now", { values: THINKING_LEVELS }),
602
+ field("learning.everyTurns", "int", "now", { min: 3, max: 100 }),
603
+ field("learning.allowThirdParty", "bool", "now"),
500
604
  field("conclave.defaultModel", "ref", "run", { role: "main" }),
501
605
  field("conclave.maxTurns", "int", "run", { min: 1 }),
502
606
  field("conclave.idleTimeoutMs", "int", "run", { min: 1_000 }),
@@ -512,6 +616,11 @@ export const SETTING_FIELDS = [
512
616
  field("shellEnvAllow", "list", "now", { entry: "env" }),
513
617
  field("shellTimeoutMs", "int", "now", { min: 1_000 }),
514
618
  field("guard.deny", "list", "now", { entry: "path" }),
619
+ field("guard.allow", "list", "now", { entry: "path" }),
620
+ field("workspace.enabled", "bool", "run"),
621
+ field("workspace.nested", "enum", "run", { values: ["ask", "copy", "inplace"] }),
622
+ field("workspace.confine", "enum", "run", { values: ["auto", "none", "docker"] }),
623
+ field("workspace.network", "bool", "run"),
515
624
  field("tui.thinkingSteps", "enum", "now", { values: THINKING_STEP_MODES }),
516
625
  field("planning", "bool", "start"),
517
626
  field("telemetry", "bool", "start"),
package/dist/diff.js ADDED
@@ -0,0 +1,90 @@
1
+ /** Line cells (unchanged-prefix-and-suffix-trimmed old lines times new lines) that diffChunks will fill; a bigger pair is refused. */
2
+ export const LCS_CELLS = 4_000_000;
3
+ /**
4
+ * The edit script from `a` to `b`, one op per step in order: " " keeps the next line of both, "-" drops the next line of `a`,
5
+ * "+" adds the next line of `b`. The common prefix and suffix are kept without a table; the middle gets a dense LCS in a
6
+ * Uint32Array. A middle over LCS_CELLS cells gives null (the caller decides what a refusal means).
7
+ */
8
+ export function diffChunks(a, b) {
9
+ let lo = 0;
10
+ while (lo < a.length && lo < b.length && a[lo] === b[lo])
11
+ lo += 1;
12
+ let ea = a.length;
13
+ let eb = b.length;
14
+ while (ea > lo && eb > lo && a[ea - 1] === b[eb - 1]) {
15
+ ea -= 1;
16
+ eb -= 1;
17
+ }
18
+ const n = ea - lo;
19
+ const m = eb - lo;
20
+ if (n * m > LCS_CELLS)
21
+ return null;
22
+ const ops = new Array(lo).fill(" ");
23
+ // ponytail: dense table, bounded by LCS_CELLS (16 MB); Myers' O(ND) diff if a changed middle ever needs to be bigger
24
+ const w = m + 1;
25
+ const t = new Uint32Array((n + 1) * w);
26
+ for (let i = n - 1; i >= 0; i -= 1)
27
+ for (let j = m - 1; j >= 0; j -= 1)
28
+ t[i * w + j] = a[lo + i] === b[lo + j] ? t[(i + 1) * w + j + 1] + 1 : Math.max(t[(i + 1) * w + j], t[i * w + j + 1]);
29
+ let i = 0;
30
+ let j = 0;
31
+ while (i < n || j < m) {
32
+ if (i < n && j < m && a[lo + i] === b[lo + j]) {
33
+ ops.push(" ");
34
+ i += 1;
35
+ j += 1;
36
+ }
37
+ else if (j < m && (i === n || t[i * w + j + 1] >= t[(i + 1) * w + j])) {
38
+ ops.push("+");
39
+ j += 1;
40
+ }
41
+ else {
42
+ ops.push("-");
43
+ i += 1;
44
+ }
45
+ }
46
+ for (let k = ea; k < a.length; k += 1)
47
+ ops.push(" ");
48
+ return ops;
49
+ }
50
+ /**
51
+ * A line diff of two texts as `+`, `-` and two-space lines, with at most `context` unchanged lines kept around each
52
+ * change. Equal texts give "". Texts too large for diffChunks give every old line removed, then every new line added.
53
+ */
54
+ export function lineDiff(before, after, context = 2) {
55
+ const a = before.split("\n");
56
+ const b = after.split("\n");
57
+ if (before === after)
58
+ return "";
59
+ const ops = diffChunks(a, b);
60
+ if (!ops)
61
+ return [...a.map((line) => `- ${line}`), ...b.map((line) => `+ ${line}`)].join("\n");
62
+ let i = 0;
63
+ let j = 0;
64
+ const rows = ops.map((op) => {
65
+ if (op === "+")
66
+ return `+ ${b[j++]}`;
67
+ if (op === "-")
68
+ return `- ${a[i++]}`;
69
+ j += 1;
70
+ return ` ${a[i++]}`;
71
+ });
72
+ // Keep only the changed lines and `context` lines around them; a gap is marked once.
73
+ const keep = rows.map((row) => row[0] !== " ");
74
+ const out = [];
75
+ let gap = false;
76
+ rows.forEach((row, k) => {
77
+ let near = false;
78
+ for (let d = -context; d <= context && !near; d += 1)
79
+ near = keep[k + d] === true;
80
+ if (near) {
81
+ gap = false;
82
+ out.push(row);
83
+ }
84
+ else if (!gap) {
85
+ gap = true;
86
+ out.push(" [unchanged lines]");
87
+ }
88
+ });
89
+ return out.join("\n");
90
+ }
package/dist/durable.js CHANGED
@@ -21,7 +21,7 @@ export function onSessionFailed(harness, listener) {
21
21
  listener(end.error); });
22
22
  }
23
23
  /** Runs shell commands with the bash that findBash located, and stores their output without color codes. */
24
- class ShellEnv extends NodeExecutionEnv {
24
+ export class ShellEnv extends NodeExecutionEnv {
25
25
  async exec(command, options, context) {
26
26
  // H2: the bash tool asks for a spill file once output passes its limits. Nothing is spilled: the file would
27
27
  // hold a full copy of the output (and any secret in it) in %TEMP%. shell.ts clips oversized output instead.
package/dist/guard.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFileSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { join } from "node:path";
4
+ import { join, relative, resolve } from "node:path";
5
+ import { allowEntryProblem, piAgentDir } from "./config.js";
5
6
  import { AgentDoc, createEditTool, createReadTool, createWriteTool, createBashTool, ctx, defineExtension, hook, isTaskLive, ROOT, ToolTask, wrapTool, } from "./durable.js";
6
- import { canonicalize, isInside, PathRefused, samePath } from "./paths.js";
7
+ import { canonicalize, isInside, PathRefused, samePath, segments } from "./paths.js";
7
8
  import { clipShellOutput } from "./shell.js";
8
9
  import { capture, captureLost, countBash, recordPost } from "./undo.js";
9
10
  const WRITE_TOOLS = new Set(["write", "edit"]);
@@ -21,7 +22,10 @@ const ENV_FIXED = { NO_COLOR: "1", TERM: "dumb" };
21
22
  const ENV_BASENAME = [/^\.env$/iu, /^\.env\.local$/iu, /^\.env\..+\.local$/iu];
22
23
  export function denyRoots(config) {
23
24
  const profile = config.profile ?? homedir();
24
- return [config.home, join(profile, ".pi"), join(profile, ".ssh"), join(profile, ".claude"), ...config.deny];
25
+ const pi = join(profile, ".pi");
26
+ // A PI_CODING_AGENT_DIR outside <profile>/.pi holds the same credentials, so it is a deny root too.
27
+ const agent = piAgentDir(profile);
28
+ return [config.home, pi, join(profile, ".ssh"), join(profile, ".claude"), ...(isInside(resolve(pi), agent) ? [] : [agent]), ...config.deny];
25
29
  }
26
30
  // A verb counts when no word character or hyphen touches it on either side, so `skill`, `killer` and `kill-port` pass
27
31
  // while `kill -9`, `/bin/kill` and `taskkill.exe` match. Even `echo kill` is blocked: simple beats exact here.
@@ -34,6 +38,58 @@ const WMIC_KILL = /\bwmic\b[^\n]*\bprocess\b[^\n]*\b(?:delete|terminate)\b/iu;
34
38
  export function killsProcess(command) {
35
39
  return typeof command === "string" && (KILL_VERB.test(command) || WMIC_KILL.test(command));
36
40
  }
41
+ const CREDENTIAL_NAME = /^(?:auth\.json|mcp-auth\.json|\.git-credentials|\.netrc|_netrc|\.pypirc|id_(?:rsa|dsa|ecdsa|ed25519)(?!.*\.pub$).*)$/iu;
42
+ const WORD_BREAK = /[\s'"`;|&<>()]/u;
43
+ /**
44
+ * A reason when a shell command plainly reaches a protected location, else undefined. Like killsProcess this is a
45
+ * tripwire against accidents (an agent in an allowed folder climbing out of it), not confinement: bash is not
46
+ * sandboxed and a command can be worded around it with variables, globs or a script. It matches text, not a parsed shell.
47
+ * Rules: a deny root named in any common spelling (unless inside a guard.allow folder and not a credential name),
48
+ * a credential file name, and a `..` that leaves the allowed folder the working directory sits in.
49
+ */
50
+ export function shellPathRefusal(command, cwd, config) {
51
+ if (typeof command !== "string")
52
+ return undefined;
53
+ const hint = "; use the file tools for files inside the allowed folder (this check is a tripwire, not confinement)";
54
+ const win = process.platform === "win32";
55
+ const text = (win ? command.toLowerCase() : command).replaceAll("\\", "/");
56
+ const folders = allowedFolders(config);
57
+ const profile = config.profile ?? homedir();
58
+ for (const root of denyRoots(config)) {
59
+ const abs = resolve(root);
60
+ const fwd = abs.replaceAll("\\", "/");
61
+ const drive = /^([a-z]):/iu.exec(fwd)?.[1];
62
+ const home = isInside(profile, abs) ? relative(profile, abs).replaceAll("\\", "/") : undefined;
63
+ const forms = [fwd, ...(drive ? [`/${drive}${fwd.slice(2)}`, `/mnt/${drive}${fwd.slice(2)}`] : []), ...(home ? ["~/", "$HOME/", "${HOME}/", "%USERPROFILE%/", "$env:USERPROFILE/"].map((p) => p + home) : [])];
64
+ for (const form of forms) {
65
+ const needle = win ? form.toLowerCase() : form;
66
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + 1)) {
67
+ const end = at + needle.length;
68
+ if (/[\w.-]/u.test(text[end] ?? ""))
69
+ continue; // `~/.pine` is not `~/.pi`
70
+ const target = resolve(fwd + text.slice(end).split(WORD_BREAK, 1)[0]);
71
+ let real = target;
72
+ try {
73
+ real = canonicalize(target);
74
+ }
75
+ catch { /* keep the lexical path */ }
76
+ if (!folders.some((f) => isInside(f.entry, real)) || WIDE_SECRET.some((p) => p.test(real.split(/[\\/]/u).pop() ?? "")))
77
+ return `the command names a protected location${hint}`;
78
+ }
79
+ }
80
+ }
81
+ const tokens = command.split(/[\s'"`;|&<>()=]+/u).filter(Boolean);
82
+ if (tokens.some((t) => CREDENTIAL_NAME.test(t.split(/[\\/]/u).pop() ?? "")))
83
+ return `the command names a credential file${hint}`;
84
+ try {
85
+ const here = cwd ? canonicalize(cwd) : undefined;
86
+ const folder = here === undefined ? undefined : folders.find((f) => isInside(f.entry, here));
87
+ if (here !== undefined && folder && tokens.some((t) => t.split(/[\\/]/u).includes("..") && !isInside(folder.entry, resolve(here, t))))
88
+ return `the command leaves the allowed folder${hint}`;
89
+ }
90
+ catch { /* an unreadable cwd leaves rules 1 and 2 only */ }
91
+ return undefined;
92
+ }
37
93
  // Names that never open under the read exception for <home>/skills, whatever folder they sit in.
38
94
  const SECRET_BASENAME = [...ENV_BASENAME, /\.(?:pem|key|p12|pfx|kdbx)$/iu, /^id_(?:rsa|ed25519|ecdsa)/iu, /\.sqlite/iu, /^(?:auth\.json|\.netrc|\.npmrc)$/iu];
39
95
  /** True when a read of `target` (canonical) falls under the home exception: inside the real <home>/skills, and not a secret name. */
@@ -42,7 +98,67 @@ function homeSkillsRead(target, base, config) {
42
98
  const skills = canonicalize(join(config.home, "skills"));
43
99
  return samePath(skills, join(canonicalize(config.home), "skills")) && isInside(skills, target) && !SECRET_BASENAME.some((pattern) => pattern.test(base));
44
100
  }
45
- function evaluate(path, cwd, config, read) {
101
+ // Names refused inside an allowed folder: the secret names above plus whole-basename credential files (source files such as tokenizer.ts stay open).
102
+ export const WIDE_SECRET = [
103
+ ...SECRET_BASENAME,
104
+ /^\.env\.(?!(?:example|sample|template)$).+/iu, /^\.envrc$/iu, /^_netrc$/iu, /^\.git-credentials$/iu, /^\.pypirc$/iu, /\.db$/iu, /^mcp-auth\.json$/iu,
105
+ /^credentials(?:\.(?:json|yaml|yml|toml|ini|csv|xml))?$/iu, /^tokens?(?:\.(?:json|txt|yaml|yml))?$/iu, /^secrets?(?:\.(?:json|yaml|yml|toml|env|txt))?$/iu, /^service-account.*\.json$/iu,
106
+ ];
107
+ const SECRET_DIRS = new Set([".aws", ".ssh", ".gnupg"]);
108
+ /** An allow entry that counts: its canonical entry and the index of the one deny root it lifts. Others are ignored with a notice. */
109
+ function allowedFolders(config) {
110
+ if (config.allow.length === 0)
111
+ return [];
112
+ const profile = config.profile ?? homedir();
113
+ const roots = denyRoots(config);
114
+ const barred = [config.home, join(profile, ".ssh"), join(profile, ".claude")];
115
+ const out = [];
116
+ for (const entry of config.allow) {
117
+ const ignore = (why) => config.warn?.(`guard.allow: ${entry} is ignored: ${why}`);
118
+ const problem = allowEntryProblem(entry, config.deny, profile, config.home);
119
+ if (problem !== undefined) {
120
+ ignore(problem);
121
+ continue;
122
+ }
123
+ const lexical = resolve(entry);
124
+ const at = roots.findIndex((root) => isInside(resolve(root), lexical) && !samePath(resolve(root), lexical));
125
+ if (at < 0)
126
+ continue;
127
+ try {
128
+ // No link or junction anywhere below the deny root: the canonical entry is the lexical one resolved against the canonical root.
129
+ const entryReal = canonicalize(lexical);
130
+ if (!samePath(entryReal, join(canonicalize(roots[at]), relative(resolve(roots[at]), lexical)))) {
131
+ ignore("a link or junction lies in its path");
132
+ continue;
133
+ }
134
+ if (barred.some((root) => isInside(canonicalize(root), entryReal))) {
135
+ ignore("it resolves into the piroboros data directory, ~/.ssh or ~/.claude");
136
+ continue;
137
+ }
138
+ out.push({ entry: entryReal, at });
139
+ }
140
+ catch {
141
+ ignore("it could not be evaluated");
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+ /** The notices for allow entries that do not count; the runtime calls it at start so the user sees them before the first tool call. */
147
+ export function checkAllowEntries(config) {
148
+ allowedFolders(config);
149
+ }
150
+ // Names refused inside an allowed folder `entry`, or undefined.
151
+ function allowedNameRefusal(entry, target, base, write) {
152
+ const below = segments(relative(entry, target));
153
+ if (WIDE_SECRET.some((pattern) => pattern.test(base)))
154
+ return "that file name looks like a credential file";
155
+ if (below.some((part) => SECRET_DIRS.has(part)))
156
+ return "that folder holds credentials";
157
+ if (write && below.includes(".git"))
158
+ return "the .git folder is not writable by tools";
159
+ return undefined;
160
+ }
161
+ function evaluate(path, cwd, config, read, write = false) {
46
162
  try {
47
163
  if (typeof path !== "string")
48
164
  return { allowed: false, reason: "the path argument is missing or not text" };
@@ -50,6 +166,7 @@ function evaluate(path, cwd, config, read) {
50
166
  const base = target.split(/[\\/]/u).pop() ?? "";
51
167
  if (ENV_BASENAME.some((pattern) => pattern.test(base)))
52
168
  return { allowed: false, reason: "environment files (.env) are not accessible to tools" };
169
+ const folders = allowedFolders(config);
53
170
  for (const [at, root] of denyRoots(config).entries()) {
54
171
  let canonicalRoot;
55
172
  try {
@@ -58,9 +175,18 @@ function evaluate(path, cwd, config, read) {
58
175
  catch {
59
176
  return { allowed: false, reason: "a protected location could not be evaluated" };
60
177
  }
178
+ if (!isInside(canonicalRoot, target))
179
+ continue;
61
180
  // The exception is for the home root only (the first deny root), per root: every other deny root still refuses a path inside it.
62
- if (isInside(canonicalRoot, target) && !(read && at === 0 && homeSkillsRead(target, base, config)))
181
+ if (read && at === 0 && homeSkillsRead(target, base, config))
182
+ continue;
183
+ // An allowed folder lifts the one root it sits in; any other root that holds the target, or sits inside the folder, still refuses.
184
+ const folder = folders.find((f) => f.at === at && isInside(f.entry, target));
185
+ if (folder === undefined)
63
186
  return { allowed: false, reason: "that location holds credentials or application data and is protected" };
187
+ const refusal = allowedNameRefusal(folder.entry, target, base, write);
188
+ if (refusal !== undefined)
189
+ return { allowed: false, reason: refusal };
64
190
  }
65
191
  return { allowed: true };
66
192
  }
@@ -69,8 +195,8 @@ function evaluate(path, cwd, config, read) {
69
195
  }
70
196
  }
71
197
  /** Decide whether a tool may touch `path`. Any failure to evaluate the path is a refusal. */
72
- export function checkPath(path, cwd, config) {
73
- return evaluate(path, cwd, config, false);
198
+ export function checkPath(path, cwd, config, write = false) {
199
+ return evaluate(path, cwd, config, false, write);
74
200
  }
75
201
  /** checkPath for reading: also allows files under <home>/skills (the user's installed skills), secrets excluded. Writes never use it. */
76
202
  export function checkRead(path, cwd, config) {
@@ -188,7 +314,9 @@ export function createGuard(deps) {
188
314
  return { allowed: false, reason: "this conversation has no working directory, so file access is refused" };
189
315
  if (typeof path !== "string")
190
316
  return { allowed: false, reason: "the path argument is missing or not text" };
191
- return isInside(canonicalize(cwd), canonicalize(path, cwd)) ? { allowed: true } : { allowed: false, reason: "this conversation may only touch files under its working directory" };
317
+ // A shell in WSL shows a Windows path as /mnt/<drive>/...; file tools want the Windows form.
318
+ const wsl = process.platform === "win32" ? /^\/mnt\/([a-z])\/(.*)$/iu.exec(path) : null;
319
+ return isInside(canonicalize(cwd), canonicalize(path, cwd)) ? { allowed: true } : { allowed: false, reason: `this conversation may only touch files under its working directory${wsl === null ? "" : `; ${path} is the Linux view of ${wsl[1].toUpperCase()}:\\${wsl[2].replaceAll("/", "\\")}, use that form`}` };
192
320
  }
193
321
  catch {
194
322
  return { allowed: false, reason: "the path could not be evaluated" };
@@ -197,6 +325,10 @@ export function createGuard(deps) {
197
325
  const shellPrepare = (execution) => {
198
326
  execution.inheritEnv = false;
199
327
  execution.env = shellEnv(deps.config());
328
+ // A plain Workspace has no repository: git must not find the one above it.
329
+ const ceiling = deps.workspace?.ceiling(execution.cwd);
330
+ if (ceiling !== undefined)
331
+ execution.env.GIT_CEILING_DIRECTORIES = ceiling;
200
332
  };
201
333
  const beforeTool = async (call, api) => {
202
334
  const config = deps.config();
@@ -210,7 +342,7 @@ export function createGuard(deps) {
210
342
  catch {
211
343
  cwd = undefined;
212
344
  }
213
- const verdict = call.name === "read" ? checkRead(args.path, cwd, config) : checkPath(args.path, cwd, config);
345
+ const verdict = call.name === "read" ? checkRead(args.path, cwd, config) : checkPath(args.path, cwd, config, WRITE_TOOLS.has(call.name));
214
346
  if (!verdict.allowed)
215
347
  return { block: `blocked by guard: ${verdict.reason}` };
216
348
  if (id !== ROOT) {
@@ -226,13 +358,25 @@ export function createGuard(deps) {
226
358
  }
227
359
  if (SHELL_TOOLS.has(call.name) && killsProcess(args.command))
228
360
  return { block: "blocked by guard: process-kill commands are not allowed from the agent" };
361
+ if (SHELL_TOOLS.has(call.name)) {
362
+ try {
363
+ cwd = (await api.snapshot(AgentDoc, api.conversationId, ctx))?.cwd;
364
+ }
365
+ catch {
366
+ cwd = undefined;
367
+ }
368
+ const refusal = shellPathRefusal(args.command, cwd, config);
369
+ if (refusal !== undefined)
370
+ return { block: `blocked by guard: ${refusal}` };
371
+ }
229
372
  if (WRITE_TOOLS.has(call.name)) {
230
373
  const refusal = readFirst(id, args.path, cwd);
231
374
  if (refusal !== undefined)
232
375
  return { block: `blocked by guard: ${refusal}` };
233
376
  }
234
- // Every block check has passed. A Vesperia write or edit saves the pre-image first; a storage error never stops the call.
235
- if (WRITE_TOOLS.has(call.name) && cwd !== undefined && (await isVesperia(id))) {
377
+ // Every block check has passed. In place, a Vesperia write or edit saves the pre-image first (a Workspace run has the CAS instead); a storage error never stops the call.
378
+ const inPlace = !deps.workspace?.has(id);
379
+ if (WRITE_TOOLS.has(call.name) && cwd !== undefined && inPlace && (await isVesperia(id))) {
236
380
  const key = keyOf(args.path, cwd);
237
381
  const path = canonicalize(String(args.path), cwd);
238
382
  try {
@@ -249,7 +393,7 @@ export function createGuard(deps) {
249
393
  }
250
394
  }
251
395
  // countBash failing stays silent: a missing count only understates the bash calls in the undo preview.
252
- if (SHELL_TOOLS.has(call.name) && (await isVesperia(id))) {
396
+ if (SHELL_TOOLS.has(call.name) && inPlace && (await isVesperia(id))) {
253
397
  try {
254
398
  countBash(config.home, id);
255
399
  }
@@ -273,6 +417,18 @@ export function createGuard(deps) {
273
417
  const entry = call.id === undefined ? undefined : pending.get(call.id);
274
418
  if (call.id !== undefined)
275
419
  pending.delete(call.id);
420
+ // A failing bash command may have written files, so the Workspace checkpoint runs before the error return.
421
+ const id = api.conversationId;
422
+ if (deps.workspace?.has(id) && (WRITE_TOOLS.has(call.name) || SHELL_TOOLS.has(call.name))) {
423
+ let cwd;
424
+ try {
425
+ cwd = (await api.snapshot(AgentDoc, api.conversationId, ctx))?.cwd;
426
+ }
427
+ catch {
428
+ cwd = undefined;
429
+ }
430
+ await deps.workspace.after(id, call.name, (call.arguments ?? {}).path, cwd);
431
+ }
276
432
  if (result.isError)
277
433
  return undefined;
278
434
  if (entry !== undefined)
@@ -289,7 +445,7 @@ export function createGuard(deps) {
289
445
  const hash = hashIfFile(canonicalize(String(args.path), cwd));
290
446
  if (hash !== undefined) {
291
447
  remember(api.conversationId, keyOf(args.path, cwd), hash);
292
- if (await isVesperia(api.conversationId))
448
+ if (!deps.workspace?.has(id) && (await isVesperia(id)))
293
449
  try {
294
450
  recordPost(deps.config().home, api.conversationId, keyOf(args.path, cwd), hash);
295
451
  }