piroboros 0.1.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/NOTICE +12 -0
  3. package/README.md +91 -167
  4. package/dist/chat/compactor.js +5 -4
  5. package/dist/chat/log.js +3 -2
  6. package/dist/chat/plan.js +1 -0
  7. package/dist/chat/tree.js +1 -0
  8. package/dist/chat/turn.js +0 -15
  9. package/dist/conclave/pipeline.js +222 -19
  10. package/dist/config.js +127 -12
  11. package/dist/diff.js +90 -0
  12. package/dist/durable.js +69 -4
  13. package/dist/guard.js +170 -14
  14. package/dist/learn.js +938 -0
  15. package/dist/main.js +3 -9
  16. package/dist/memory/akashic/tools.js +25 -28
  17. package/dist/memory/mnemosia/conflicts.js +0 -4
  18. package/dist/memory/mnemosia/orchestrator.js +1 -11
  19. package/dist/memory/mnemosia/policy.js +0 -3
  20. package/dist/memory/mnemosia/rank.js +0 -4
  21. package/dist/memory/mnemosia/rerank.js +3 -30
  22. package/dist/memory/mnemosia/rollback.js +1 -149
  23. package/dist/memory/mnemosia/tokens.js +1 -11
  24. package/dist/memory/mnemosia/tools.js +0 -10
  25. package/dist/memory/mnemosia/types.js +0 -2
  26. package/dist/runtime.js +80 -11
  27. package/dist/search.js +25 -12
  28. package/dist/shell.js +2 -2
  29. package/dist/telemetry.js +84 -0
  30. package/dist/tui/app.js +17 -3
  31. package/dist/tui/commands.js +6 -2
  32. package/dist/tui/settings.js +4 -1
  33. package/dist/tui/thinking/parse.js +0 -3
  34. package/dist/ws/apply.js +817 -0
  35. package/dist/ws/cas.js +144 -0
  36. package/dist/ws/confine.js +194 -0
  37. package/dist/ws/docker.js +151 -0
  38. package/dist/ws/git.js +162 -0
  39. package/dist/ws/lww.js +48 -0
  40. package/dist/ws/merge.js +129 -0
  41. package/dist/ws/workspace.js +1596 -0
  42. package/dist/ws/wsl.js +259 -0
  43. package/docs/conclave.md +35 -0
  44. package/docs/configuration.md +54 -0
  45. package/docs/development.md +25 -0
  46. package/docs/interface.md +33 -0
  47. package/docs/memory.md +11 -0
  48. package/docs/privacy.md +15 -0
  49. package/docs/tools.md +62 -0
  50. package/docs/web.md +38 -0
  51. package/package.json +23 -10
  52. package/settings.json.example +4 -1
package/dist/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) {
@@ -169,7 +295,7 @@ export function createGuard(deps) {
169
295
  if (harness === undefined)
170
296
  return "the guard is not bound to a harness, so a live Conclave pipeline cannot be ruled out";
171
297
  if (await isTaskLive(harness, state.taskId))
172
- return "a Conclave pipeline is running; use /conclave cancel to stop it before writing from the root";
298
+ return "a Conclave pipeline is running or paused; use /conclave cancel to stop it before writing from the root";
173
299
  }
174
300
  // F3: reports are untrusted data. A turn made only of reports may not write or run commands until the user sends something.
175
301
  try {
@@ -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
  }