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/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().
@@ -26,6 +26,7 @@ export function homePaths(home) {
26
26
  chat: join(home, "chat.sqlite"),
27
27
  integrity: join(home, "config-integrity.json"),
28
28
  skillsTrust: join(home, "skills-trust.json"),
29
+ telemetry: join(home, "telemetry.sqlite"),
29
30
  };
30
31
  }
31
32
  /** The home piroboros would use with no override. Tests must never touch it. */
@@ -141,12 +142,15 @@ export const CONCLAVE_MEMBERS = ["samaela", "nytheria", "elaria", "raskreia", "a
141
142
  export const SETTINGS_DEFAULTS = {
142
143
  thinking: "medium",
143
144
  compactor: { enabled: true, thinking: "off", maxConcurrent: 8, allowThirdParty: false },
145
+ learning: { thinking: "low", everyTurns: 10, allowThirdParty: false },
144
146
  conclave: { maxTurns: 64, idleTimeoutMs: 600_000, reportMaxChars: 4_000 },
145
147
  gateTimeoutMs: 120_000,
146
148
  cacheRetention: "short",
147
149
  shellEnvAllow: [],
148
150
  shellTimeoutMs: 600_000,
149
151
  tui: { thinkingSteps: "summary" },
152
+ telemetry: true,
153
+ workspace: { enabled: true, nested: "ask", confine: "auto", network: true },
150
154
  web: { enabled: false, maxFetches: 10, maxSearches: 5 },
151
155
  };
152
156
  /** A host name for web.allowHosts and web.queryHosts: lower case DNS labels, no scheme, port, path or wildcard. */
@@ -191,7 +195,7 @@ export function validateSettings(value) {
191
195
  issues.push(`${path}: must be an integer from ${min}${max === Number.MAX_SAFE_INTEGER ? " up" : ` to ${max}`}`);
192
196
  },
193
197
  };
194
- known(value, ["main", "thinking", "compactor", "conclave", "gateTimeoutMs", "cacheRetention", "shellEnvAllow", "shellTimeoutMs", "guard", "tui", "planning", "web"], "");
198
+ known(value, ["main", "thinking", "compactor", "learning", "conclave", "gateTimeoutMs", "cacheRetention", "shellEnvAllow", "shellTimeoutMs", "guard", "workspace", "tui", "planning", "telemetry", "web"], "");
195
199
  check.ref(value.main, "main");
196
200
  check.level(value.thinking, "thinking");
197
201
  if (value.compactor !== undefined) {
@@ -206,6 +210,17 @@ export function validateSettings(value) {
206
210
  check.bool(value.compactor.allowThirdParty, "compactor.allowThirdParty");
207
211
  }
208
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
+ }
209
224
  if (value.conclave !== undefined) {
210
225
  if (!isObj(value.conclave))
211
226
  issues.push("conclave: must be an object");
@@ -247,13 +262,56 @@ export function validateSettings(value) {
247
262
  check.int(value.shellTimeoutMs, "shellTimeoutMs", 1_000);
248
263
  if (value.planning !== undefined && typeof value.planning !== "boolean")
249
264
  issues.push("planning: must be true or false");
265
+ if (value.telemetry !== undefined && typeof value.telemetry !== "boolean")
266
+ issues.push("telemetry: must be true or false");
250
267
  if (value.guard !== undefined) {
251
268
  if (!isObj(value.guard))
252
269
  issues.push("guard: must be an object");
253
270
  else {
254
- known(value.guard, ["deny"], "guard");
271
+ known(value.guard, ["deny", "allow"], "guard");
255
272
  if (value.guard.deny !== undefined && !(Array.isArray(value.guard.deny) && value.guard.deny.every((item) => typeof item === "string" && isAbsolute(item))))
256
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
+ }
257
315
  }
258
316
  }
259
317
  if (value.web !== undefined) {
@@ -300,13 +358,17 @@ export function withDefaults(settings) {
300
358
  main: settings.main,
301
359
  thinking: settings.thinking ?? SETTINGS_DEFAULTS.thinking,
302
360
  compactor: { ...SETTINGS_DEFAULTS.compactor, ...settings.compactor },
361
+ learning: { ...SETTINGS_DEFAULTS.learning, ...settings.learning },
303
362
  conclave: { ...SETTINGS_DEFAULTS.conclave, ...settings.conclave },
304
363
  gateTimeoutMs: settings.gateTimeoutMs ?? SETTINGS_DEFAULTS.gateTimeoutMs,
305
364
  cacheRetention: settings.cacheRetention ?? SETTINGS_DEFAULTS.cacheRetention,
306
365
  shellEnvAllow: settings.shellEnvAllow ?? [],
307
366
  shellTimeoutMs: settings.shellTimeoutMs ?? SETTINGS_DEFAULTS.shellTimeoutMs,
308
367
  guardDeny: settings.guard?.deny ?? [],
368
+ guardAllow: settings.guard?.allow ?? [],
369
+ workspace: { ...SETTINGS_DEFAULTS.workspace, ...settings.workspace },
309
370
  planning: settings.planning ?? true,
371
+ telemetry: settings.telemetry ?? SETTINGS_DEFAULTS.telemetry,
310
372
  web: {
311
373
  enabled: settings.web?.enabled ?? SETTINGS_DEFAULTS.web.enabled,
312
374
  maxFetches: settings.web?.maxFetches ?? SETTINGS_DEFAULTS.web.maxFetches,
@@ -342,7 +404,7 @@ export const SETTINGS_CHANGED = "settings.json changed outside piroboros; run /r
342
404
  * The only settings write. It refuses when the file is not what piroboros last wrote (or was never recorded),
343
405
  * then applies `edit`, validates, writes atomically and records the hash of the string it wrote.
344
406
  */
345
- function checkedWrite(home, edit) {
407
+ function checkedWrite(home, edit, profile) {
346
408
  const path = homePaths(home).settings;
347
409
  let text;
348
410
  try {
@@ -361,7 +423,7 @@ function checkedWrite(home, edit) {
361
423
  catch (error) {
362
424
  throw new ConfigError("json_invalid", `${path} is not valid JSON: ${error.message}`);
363
425
  }
364
- const merged = validateSettings(edit(isObj(current) ? current : {}));
426
+ const merged = checkAllow(validateSettings(edit(isObj(current) ? current : {})), isObj(current) ? current : undefined, profile, home);
365
427
  const written = `${JSON.stringify(merged, null, 2)}\n`;
366
428
  writeTextAtomic(path, written, 0o600);
367
429
  const record = readIntegrity(home);
@@ -369,9 +431,42 @@ function checkedWrite(home, edit) {
369
431
  writeJsonFile(homePaths(home).integrity, record);
370
432
  return merged;
371
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
+ }
372
467
  /** Merges only the patched keys through the checked write. */
373
- export function mergeSettings(home, patch) {
374
- return checkedWrite(home, (current) => mergeDeep(current, patch));
468
+ export function mergeSettings(home, patch, profile = profileDir()) {
469
+ return checkedWrite(home, (current) => mergeDeep(current, patch), profile);
375
470
  }
376
471
  function unsetPath(obj, parts) {
377
472
  const [head, ...rest] = parts;
@@ -390,12 +485,12 @@ function unsetPath(obj, parts) {
390
485
  return out;
391
486
  }
392
487
  /** Removes one key by its dotted path, such as "tui.thinkingSteps", and any parent object left empty. */
393
- export function unsetSettings(home, path) {
394
- 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);
395
490
  }
396
491
  /** The settings a change would produce, validated. Throws SettingsError when the result is invalid. Nothing is written. */
397
- export function previewSettings(current, change) {
398
- 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);
399
494
  }
400
495
  /** The value at a dotted path such as "web.search.provider", or undefined. */
401
496
  export function getSetting(settings, path) {
@@ -425,11 +520,21 @@ function securityKeys(settings) {
425
520
  main: settings.main,
426
521
  "compactor.model": isObj(settings.compactor) ? settings.compactor.model : undefined,
427
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,
428
525
  "conclave.defaultModel": isObj(settings.conclave) ? settings.conclave.defaultModel : undefined,
429
526
  "conclave.members.models": members,
430
527
  shellEnvAllow: settings.shellEnvAllow,
431
528
  shellTimeoutMs: settings.shellTimeoutMs,
432
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,
433
538
  "web.enabled": isObj(settings.web) ? settings.web.enabled : undefined,
434
539
  "web.maxFetches": isObj(settings.web) ? settings.web.maxFetches : undefined,
435
540
  "web.maxSearches": isObj(settings.web) ? settings.web.maxSearches : undefined,
@@ -483,7 +588,7 @@ export function securityChanges(current, change) {
483
588
  const field = (path, type, applies, extra = {}) => ({
484
589
  path, type, applies, security: SECURITY_KEYS.includes(path) || /^conclave\.members\.[a-z]+\.model$/u.test(path), ...extra,
485
590
  });
486
- /** 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. */
487
592
  export const SETTING_FIELDS = [
488
593
  field("main", "ref", "turn", { role: "main" }),
489
594
  field("thinking", "enum", "turn", { values: THINKING_LEVELS }),
@@ -492,6 +597,10 @@ export const SETTING_FIELDS = [
492
597
  field("compactor.thinking", "enum", "now", { values: THINKING_LEVELS }),
493
598
  field("compactor.maxConcurrent", "int", "now", { min: 1, max: 8 }),
494
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"),
495
604
  field("conclave.defaultModel", "ref", "run", { role: "main" }),
496
605
  field("conclave.maxTurns", "int", "run", { min: 1 }),
497
606
  field("conclave.idleTimeoutMs", "int", "run", { min: 1_000 }),
@@ -507,8 +616,14 @@ export const SETTING_FIELDS = [
507
616
  field("shellEnvAllow", "list", "now", { entry: "env" }),
508
617
  field("shellTimeoutMs", "int", "now", { min: 1_000 }),
509
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"),
510
624
  field("tui.thinkingSteps", "enum", "now", { values: THINKING_STEP_MODES }),
511
625
  field("planning", "bool", "start"),
626
+ field("telemetry", "bool", "start"),
512
627
  field("web.enabled", "bool", "run"),
513
628
  field("web.maxFetches", "int", "now", { min: 1, max: 100 }),
514
629
  field("web.maxSearches", "int", "now", { min: 1, max: 100 }),
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
@@ -1,3 +1,6 @@
1
+ import { existsSync, renameSync, rmSync } from "node:fs";
2
+ import { DatabaseSync } from "node:sqlite";
3
+ import { dirname, join } from "node:path";
1
4
  import { BACKGROUND_CONTEXT, withCancel } from "@earendil-works/chord/context";
2
5
  import { AgentDoc, CompactionTask, configure, createRegistry, defineDoc, defineDocFamily, defineEntry, defineTask, defineTool, defineExtension, GenerationTask, Harness, hook, InboxDoc, LiveDoc, MemoryStorage, ROOT_CONVERSATION_ID, section, SessionFailed, ToolTask, watchEvents, wrapTool, } from "@earendil-works/pi-durable";
3
6
  import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
@@ -18,7 +21,7 @@ export function onSessionFailed(harness, listener) {
18
21
  listener(end.error); });
19
22
  }
20
23
  /** Runs shell commands with the bash that findBash located, and stores their output without color codes. */
21
- class ShellEnv extends NodeExecutionEnv {
24
+ export class ShellEnv extends NodeExecutionEnv {
22
25
  async exec(command, options, context) {
23
26
  // H2: the bash tool asks for a spill file once output passes its limits. Nothing is spilled: the file would
24
27
  // hold a full copy of the output (and any secret in it) in %TEMP%. shell.ts clips oversized output instead.
@@ -42,15 +45,76 @@ class ShellEnv extends NodeExecutionEnv {
42
45
  }
43
46
  }
44
47
  export async function openHarness(options) {
45
- const storage = options.storage ?? (options.path === undefined ? new MemoryStorage() : await openNodeSqliteStorage(options.path));
48
+ const storage = options.storage ?? (options.path === undefined ? new MemoryStorage() : (backupBeforeSchema2(options.path), await openNodeSqliteStorage(options.path)));
46
49
  return Harness.open(storage, {
47
50
  models: options.models,
51
+ ...(options.identity === undefined ? {} : { identity: options.identity }),
48
52
  registry: options.registry,
49
53
  settings: options.settings,
50
54
  env: (target) => (options.env ? options.env(target.cwd) : new ShellEnv({ cwd: target.cwd ?? process.cwd(), shellPath: findBash() })),
51
55
  onReport: options.onReport ?? (() => { }),
56
+ ...(options.telemetry === undefined ? {} : { telemetry: options.telemetry }),
52
57
  }, ctx);
53
58
  }
59
+ /** Copy a SQLite database through `<target>.tmp`, checked by quick_check, so a partial copy never has the final name. The caller rules out an existing target. */
60
+ export function backupDatabase(source, target) {
61
+ const tmp = `${target}.tmp`;
62
+ rmSync(tmp, { force: true });
63
+ try {
64
+ const db = new DatabaseSync(source);
65
+ try {
66
+ db.prepare("VACUUM INTO ?").run(tmp);
67
+ }
68
+ finally {
69
+ db.close();
70
+ }
71
+ const copy = new DatabaseSync(tmp, { readOnly: true });
72
+ try {
73
+ const rows = copy.prepare("PRAGMA quick_check").all();
74
+ if (rows.length !== 1 || rows[0].quick_check !== "ok")
75
+ throw new Error(`the copy failed quick_check: ${rows.map((r) => r.quick_check).join("; ")}`);
76
+ }
77
+ finally {
78
+ copy.close();
79
+ }
80
+ renameSync(tmp, target);
81
+ }
82
+ catch (error) {
83
+ rmSync(tmp, { force: true });
84
+ throw error;
85
+ }
86
+ }
87
+ /** ponytail: one-time guard for the schema 1 to 2 migration of pi-durable main, after which 0.1.0 cannot open the chat database. Delete after 0.3.0. */
88
+ function backupBeforeSchema2(path) {
89
+ const target = join(dirname(path), "chat.schema1.sqlite");
90
+ if (target === path)
91
+ throw new Error(`invariant: the chat database may not be named ${target}`);
92
+ if (!existsSync(path))
93
+ return;
94
+ const db = new DatabaseSync(path);
95
+ let version;
96
+ try {
97
+ const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'durable_schema'").get();
98
+ version = table === undefined ? undefined : db.prepare("SELECT version FROM durable_schema WHERE singleton = 1").get()?.version;
99
+ }
100
+ finally {
101
+ db.close();
102
+ }
103
+ if (version !== 1)
104
+ return; // no table (new or empty file) or already schema 2: nothing to back up
105
+ if (existsSync(target))
106
+ throw new Error(`${target} is from an earlier upgrade and ${path} is schema 1 again; move ${target} somewhere else, then start piroboros again`);
107
+ try {
108
+ backupDatabase(path, target);
109
+ }
110
+ catch (error) {
111
+ throw new Error(`could not back up the chat database before its schema 2 migration (if the disk is full, free space): ${error instanceof Error ? error.message : String(error)}`);
112
+ }
113
+ }
114
+ /** Tasks the restart limit parked (pi-durable main). They stay parked across starts until aborted or retried. */
115
+ export async function parkedTasks(harness) {
116
+ return (await harness.inspect(ctx)).tasks.filter((t) => t.state.kind === "blocked" && t.state.reason === "restart_limit").map((t) => t.record);
117
+ }
54
118
  /* --- named behaviors ---------------------------------------------------------------------------------- */
55
119
  export const MARKER_KIND = "piroboros.turn";
56
120
  /** True when the root has no run in progress. */
@@ -88,7 +152,8 @@ export function submitInput(root, content, requestId) {
88
152
  export function submitSteer(root, content, requestId) {
89
153
  return root.submit({ type: "input", content, whenBusy: "steer", requestId }, ctx);
90
154
  }
91
- const LIVE_STATUSES = new Set(["pending", "running", "waiting", "completing"]);
155
+ /** Every status but "terminal" is live: pending, running, waiting, sleeping, completing. A status this code does not know, or a missing one, counts as live (fails closed). */
156
+ export const isLiveStatus = (status) => status !== "terminal";
92
157
  /**
93
158
  * Whether a task is live. Fails closed: a task that cannot be read, is absent, or reports a status this
94
159
  * code does not know counts as live.
@@ -99,7 +164,7 @@ export async function isTaskLive(harness, taskId) {
99
164
  if (record === undefined)
100
165
  return true;
101
166
  const status = record.state.status;
102
- return status === undefined || LIVE_STATUSES.has(status);
167
+ return isLiveStatus(status);
103
168
  }
104
169
  catch {
105
170
  return true;