piroboros 0.0.0-stage → 0.2.0

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 (118) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +39 -0
  4. package/README.md +140 -2
  5. package/agents/astrelia.md +31 -0
  6. package/agents/avaritia.md +31 -0
  7. package/agents/elaria.md +31 -0
  8. package/agents/nytheria.md +32 -0
  9. package/agents/raskreia.md +32 -0
  10. package/agents/samaela.md +40 -0
  11. package/agents/vaelia.md +35 -0
  12. package/agents/vesperia.md +45 -0
  13. package/bin/piroboros.mjs +17 -0
  14. package/dist/auth.js +105 -0
  15. package/dist/base.js +19 -0
  16. package/dist/chat/budget.js +87 -0
  17. package/dist/chat/compactloop.js +63 -0
  18. package/dist/chat/compactor.js +530 -0
  19. package/dist/chat/extension.js +36 -0
  20. package/dist/chat/hook.js +40 -0
  21. package/dist/chat/log.js +317 -0
  22. package/dist/chat/outbound.js +114 -0
  23. package/dist/chat/plan.js +64 -0
  24. package/dist/chat/prompt.js +115 -0
  25. package/dist/chat/status.js +37 -0
  26. package/dist/chat/stuck.js +83 -0
  27. package/dist/chat/tools.js +163 -0
  28. package/dist/chat/tree.js +73 -0
  29. package/dist/chat/turn.js +305 -0
  30. package/dist/chat/view.js +163 -0
  31. package/dist/conclave/agents.js +113 -0
  32. package/dist/conclave/pipeline.js +715 -0
  33. package/dist/conclave/report.js +43 -0
  34. package/dist/config.js +614 -0
  35. package/dist/durable.js +177 -0
  36. package/dist/guard.js +346 -0
  37. package/dist/lock.js +56 -0
  38. package/dist/main.js +348 -0
  39. package/dist/memory/akashic/api.js +121 -0
  40. package/dist/memory/akashic/confusables.js +41 -0
  41. package/dist/memory/akashic/scanner.js +67 -0
  42. package/dist/memory/akashic/snapshot.js +31 -0
  43. package/dist/memory/akashic/store.js +1254 -0
  44. package/dist/memory/akashic/tools.js +168 -0
  45. package/dist/memory/akashic/vault.js +984 -0
  46. package/dist/memory/host.js +124 -0
  47. package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
  48. package/dist/memory/mnemosia/adapters/contract.js +219 -0
  49. package/dist/memory/mnemosia/agents.js +387 -0
  50. package/dist/memory/mnemosia/brief.js +890 -0
  51. package/dist/memory/mnemosia/claims.js +609 -0
  52. package/dist/memory/mnemosia/conflicts.js +769 -0
  53. package/dist/memory/mnemosia/escalation.js +257 -0
  54. package/dist/memory/mnemosia/feedback.js +108 -0
  55. package/dist/memory/mnemosia/filters.js +248 -0
  56. package/dist/memory/mnemosia/intent.js +221 -0
  57. package/dist/memory/mnemosia/open.js +34 -0
  58. package/dist/memory/mnemosia/orchestrator.js +926 -0
  59. package/dist/memory/mnemosia/plan.js +266 -0
  60. package/dist/memory/mnemosia/policy.js +426 -0
  61. package/dist/memory/mnemosia/progressive.js +550 -0
  62. package/dist/memory/mnemosia/provenance.js +458 -0
  63. package/dist/memory/mnemosia/qualifiers.js +428 -0
  64. package/dist/memory/mnemosia/rank.js +525 -0
  65. package/dist/memory/mnemosia/relations.js +156 -0
  66. package/dist/memory/mnemosia/requirements.js +138 -0
  67. package/dist/memory/mnemosia/rerank.js +253 -0
  68. package/dist/memory/mnemosia/retention.js +174 -0
  69. package/dist/memory/mnemosia/rollback.js +337 -0
  70. package/dist/memory/mnemosia/select.js +607 -0
  71. package/dist/memory/mnemosia/similarity.js +164 -0
  72. package/dist/memory/mnemosia/situation.js +251 -0
  73. package/dist/memory/mnemosia/task.js +418 -0
  74. package/dist/memory/mnemosia/temporal.js +136 -0
  75. package/dist/memory/mnemosia/tokens.js +66 -0
  76. package/dist/memory/mnemosia/tools.js +160 -0
  77. package/dist/memory/mnemosia/trace.js +306 -0
  78. package/dist/memory/mnemosia/types.js +298 -0
  79. package/dist/models.js +360 -0
  80. package/dist/paths.js +103 -0
  81. package/dist/redact.js +79 -0
  82. package/dist/runtime.js +378 -0
  83. package/dist/search-format.js +102 -0
  84. package/dist/search.js +351 -0
  85. package/dist/setup.js +366 -0
  86. package/dist/shell.js +110 -0
  87. package/dist/skills.js +311 -0
  88. package/dist/telemetry.js +84 -0
  89. package/dist/tui/app.js +1011 -0
  90. package/dist/tui/commands.js +121 -0
  91. package/dist/tui/keys.js +83 -0
  92. package/dist/tui/pane.js +387 -0
  93. package/dist/tui/panel.js +60 -0
  94. package/dist/tui/picker.js +25 -0
  95. package/dist/tui/sanitize.js +59 -0
  96. package/dist/tui/settings.js +198 -0
  97. package/dist/tui/setup.js +256 -0
  98. package/dist/tui/theme.js +26 -0
  99. package/dist/tui/thinking/parse.js +1094 -0
  100. package/dist/tui/thinking/select.js +86 -0
  101. package/dist/tui/thinking/state.js +137 -0
  102. package/dist/tui/thinking/types.js +3 -0
  103. package/dist/tui/thinking/view.js +74 -0
  104. package/dist/tui/viewport.js +208 -0
  105. package/dist/undo.js +258 -0
  106. package/dist/web.js +933 -0
  107. package/docs/conclave.md +21 -0
  108. package/docs/configuration.md +48 -0
  109. package/docs/development.md +25 -0
  110. package/docs/interface.md +33 -0
  111. package/docs/memory.md +11 -0
  112. package/docs/privacy.md +13 -0
  113. package/docs/tools.md +20 -0
  114. package/docs/web.md +38 -0
  115. package/models.json.example +34 -0
  116. package/package.json +76 -4
  117. package/settings.json.example +29 -0
  118. package/skills/conclave/SKILL.md +76 -0
@@ -0,0 +1,177 @@
1
+ import { existsSync, renameSync, rmSync } from "node:fs";
2
+ import { DatabaseSync } from "node:sqlite";
3
+ import { dirname, join } from "node:path";
4
+ import { BACKGROUND_CONTEXT, withCancel } from "@earendil-works/chord/context";
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";
6
+ import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
7
+ import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
8
+ import { createEditTool, createReadTool, createWriteTool, createBashTool } from "@earendil-works/pi-durable/tools";
9
+ import { findBash, sgrStripper } from "./shell.js";
10
+ // The only module that imports pi-durable. It re-exports what the rest of piroboros uses and holds the
11
+ // named behaviors that the durable-contract test pins, so a version bump is one edit plus that test.
12
+ export { AgentDoc, BACKGROUND_CONTEXT, CompactionTask, configure, createBashTool, createEditTool, createReadTool, createRegistry, createWriteTool, defineDoc, defineDocFamily, defineEntry, defineExtension, defineTask, defineTool, GenerationTask, hook, InboxDoc, LiveDoc, MemoryStorage, NodeExecutionEnv, openNodeSqliteStorage, ROOT_CONVERSATION_ID, section, SessionFailed, ToolTask, watchEvents, withCancel, wrapTool, };
13
+ export const ctx = BACKGROUND_CONTEXT;
14
+ export const ROOT = ROOT_CONVERSATION_ID;
15
+ /**
16
+ * pi-durable 1.2.0 fails the whole Session on any storage error: it closes itself and every later call rejects with
17
+ * SessionFailed. This calls `listener` once with the storage error; a normal close() never calls it.
18
+ */
19
+ export function onSessionFailed(harness, listener) {
20
+ void harness.closed.then((end) => { if (end.reason === "failed")
21
+ listener(end.error); });
22
+ }
23
+ /** Runs shell commands with the bash that findBash located, and stores their output without color codes. */
24
+ class ShellEnv extends NodeExecutionEnv {
25
+ async exec(command, options, context) {
26
+ // H2: the bash tool asks for a spill file once output passes its limits. Nothing is spilled: the file would
27
+ // hold a full copy of the output (and any secret in it) in %TEMP%. shell.ts clips oversized output instead.
28
+ const { spill: _spill, ...plain } = options ?? {};
29
+ options = plain;
30
+ const onOutput = options?.onOutput;
31
+ if (onOutput === undefined)
32
+ return super.exec(command, options, context);
33
+ const strip = sgrStripper();
34
+ const result = await super.exec(command, { ...options, onOutput: (text, ctx, info) => {
35
+ const clean = strip.push(text, info.stream);
36
+ if (clean !== "" || info.skipped)
37
+ onOutput(clean, ctx, info);
38
+ } }, context);
39
+ for (const stream of ["stdout", "stderr"]) {
40
+ const rest = strip.flush(stream);
41
+ if (rest !== "")
42
+ onOutput(rest, context, { stream });
43
+ }
44
+ return result;
45
+ }
46
+ }
47
+ export async function openHarness(options) {
48
+ const storage = options.storage ?? (options.path === undefined ? new MemoryStorage() : (backupBeforeSchema2(options.path), await openNodeSqliteStorage(options.path)));
49
+ return Harness.open(storage, {
50
+ models: options.models,
51
+ ...(options.identity === undefined ? {} : { identity: options.identity }),
52
+ registry: options.registry,
53
+ settings: options.settings,
54
+ env: (target) => (options.env ? options.env(target.cwd) : new ShellEnv({ cwd: target.cwd ?? process.cwd(), shellPath: findBash() })),
55
+ onReport: options.onReport ?? (() => { }),
56
+ ...(options.telemetry === undefined ? {} : { telemetry: options.telemetry }),
57
+ }, ctx);
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
+ }
118
+ /* --- named behaviors ---------------------------------------------------------------------------------- */
119
+ export const MARKER_KIND = "piroboros.turn";
120
+ /** True when the root has no run in progress. */
121
+ export async function isIdle(harness, conversationId = ROOT) {
122
+ const live = await harness.snapshot(LiveDoc, conversationId, ctx);
123
+ return live?.run === undefined;
124
+ }
125
+ /**
126
+ * Submit the head marker of a turn on an idle root. A write on an idle conversation settles `done` at once; any
127
+ * other status means the root was busy, which would turn a post-tools boundary into a final one, so it throws.
128
+ */
129
+ export async function submitTurn(root, data, requestId) {
130
+ const submission = await root.submit({ type: "write", entry: { kind: MARKER_KIND, head: "self", data: data }, requestId }, ctx);
131
+ const record = await submission.status(ctx);
132
+ if (record.status !== "done")
133
+ throw new Error(`invariant: marker ${requestId} did not settle done (status ${record.status}); markers are only submitted when the root is idle`);
134
+ return submission;
135
+ }
136
+ export const NOTE_KIND = "piroboros.note";
137
+ /**
138
+ * Append a memory snapshot note to an idle root, with no head: it joins the log and the index, not the context of a
139
+ * turn. Like the marker it settles `done` at once on an idle conversation, and any other status is a bug.
140
+ */
141
+ export async function submitNote(root, data, requestId) {
142
+ const submission = await root.submit({ type: "write", entry: { kind: NOTE_KIND, data: data }, requestId }, ctx);
143
+ const record = await submission.status(ctx);
144
+ if (record.status !== "done")
145
+ throw new Error(`invariant: note ${requestId} did not settle done (status ${record.status}); notes are only submitted when the root is idle`);
146
+ return submission;
147
+ }
148
+ /** Submit user input. `steer` places it at the next boundary of a running turn; plain input starts a run on an idle root. */
149
+ export function submitInput(root, content, requestId) {
150
+ return root.submit({ type: "input", content, requestId }, ctx);
151
+ }
152
+ export function submitSteer(root, content, requestId) {
153
+ return root.submit({ type: "input", content, whenBusy: "steer", requestId }, ctx);
154
+ }
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";
157
+ /**
158
+ * Whether a task is live. Fails closed: a task that cannot be read, is absent, or reports a status this
159
+ * code does not know counts as live.
160
+ */
161
+ export async function isTaskLive(harness, taskId) {
162
+ try {
163
+ const record = await harness.getTask((/^\d+$/u.test(taskId) ? Number(taskId) : taskId), ctx);
164
+ if (record === undefined)
165
+ return true;
166
+ const status = record.state.status;
167
+ return isLiveStatus(status);
168
+ }
169
+ catch {
170
+ return true;
171
+ }
172
+ }
173
+ /** Committed entries of a conversation, newest first. */
174
+ export async function recentEntries(conversation, limit) {
175
+ const page = await conversation.entries({}, limit, undefined, ctx);
176
+ return page.items;
177
+ }
package/dist/guard.js ADDED
@@ -0,0 +1,346 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ 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 { clipShellOutput } from "./shell.js";
8
+ import { capture, captureLost, countBash, recordPost } from "./undo.js";
9
+ const WRITE_TOOLS = new Set(["write", "edit"]);
10
+ const SHELL_TOOLS = new Set(["bash"]);
11
+ const PATH_TOOLS = new Set(["read", "write", "edit"]);
12
+ // Variables a bash child may inherit. Everything else, including every secret, is dropped.
13
+ // PATH: finds programs. HOME, USER, LOGNAME: identity that tools like git expect. LANG, LC_ALL: text encoding.
14
+ // TMPDIR: scratch space on Linux and macOS.
15
+ export const ENV_ALLOW = ["PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TMPDIR"];
16
+ // Windows only. SystemRoot: Windows programs and Git Bash will not start without it. TEMP, TMP: scratch space.
17
+ // USERPROFILE: Git Bash derives HOME from it when HOME is unset.
18
+ export const ENV_ALLOW_WINDOWS = ["SystemRoot", "TEMP", "TMP", "USERPROFILE"];
19
+ // Always set: colors off, so tool output reads as plain text.
20
+ const ENV_FIXED = { NO_COLOR: "1", TERM: "dumb" };
21
+ const ENV_BASENAME = [/^\.env$/iu, /^\.env\.local$/iu, /^\.env\..+\.local$/iu];
22
+ export function denyRoots(config) {
23
+ const profile = config.profile ?? homedir();
24
+ return [config.home, join(profile, ".pi"), join(profile, ".ssh"), join(profile, ".claude"), ...config.deny];
25
+ }
26
+ // A verb counts when no word character or hyphen touches it on either side, so `skill`, `killer` and `kill-port` pass
27
+ // while `kill -9`, `/bin/kill` and `taskkill.exe` match. Even `echo kill` is blocked: simple beats exact here.
28
+ const KILL_VERB = /(?<![\w-])(?:taskkill|tskill|stop-process|spps|pkill|killall|kill)(?![\w-])/iu;
29
+ const WMIC_KILL = /\bwmic\b[^\n]*\bprocess\b[^\n]*\b(?:delete|terminate)\b/iu;
30
+ /**
31
+ * True for a shell command that kills processes. This is a tripwire against accidents (taskkill /IM node.exe would
32
+ * end piroboros and every other node process), not confinement: bash is not sandboxed and can be worded around it.
33
+ */
34
+ export function killsProcess(command) {
35
+ return typeof command === "string" && (KILL_VERB.test(command) || WMIC_KILL.test(command));
36
+ }
37
+ // Names that never open under the read exception for <home>/skills, whatever folder they sit in.
38
+ const SECRET_BASENAME = [...ENV_BASENAME, /\.(?:pem|key|p12|pfx|kdbx)$/iu, /^id_(?:rsa|ed25519|ecdsa)/iu, /\.sqlite/iu, /^(?:auth\.json|\.netrc|\.npmrc)$/iu];
39
+ /** True when a read of `target` (canonical) falls under the home exception: inside the real <home>/skills, and not a secret name. */
40
+ function homeSkillsRead(target, base, config) {
41
+ // The canonical skills folder must be exactly <home>/skills: a link or junction that points it elsewhere opens nothing.
42
+ const skills = canonicalize(join(config.home, "skills"));
43
+ return samePath(skills, join(canonicalize(config.home), "skills")) && isInside(skills, target) && !SECRET_BASENAME.some((pattern) => pattern.test(base));
44
+ }
45
+ function evaluate(path, cwd, config, read) {
46
+ try {
47
+ if (typeof path !== "string")
48
+ return { allowed: false, reason: "the path argument is missing or not text" };
49
+ const target = canonicalize(path, cwd);
50
+ const base = target.split(/[\\/]/u).pop() ?? "";
51
+ if (ENV_BASENAME.some((pattern) => pattern.test(base)))
52
+ return { allowed: false, reason: "environment files (.env) are not accessible to tools" };
53
+ for (const [at, root] of denyRoots(config).entries()) {
54
+ let canonicalRoot;
55
+ try {
56
+ canonicalRoot = canonicalize(root);
57
+ }
58
+ catch {
59
+ return { allowed: false, reason: "a protected location could not be evaluated" };
60
+ }
61
+ // 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)))
63
+ return { allowed: false, reason: "that location holds credentials or application data and is protected" };
64
+ }
65
+ return { allowed: true };
66
+ }
67
+ catch (error) {
68
+ return { allowed: false, reason: error instanceof PathRefused ? `path refused: ${error.message}` : "the path could not be evaluated" };
69
+ }
70
+ }
71
+ /** 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);
74
+ }
75
+ /** checkPath for reading: also allows files under <home>/skills (the user's installed skills), secrets excluded. Writes never use it. */
76
+ export function checkRead(path, cwd, config) {
77
+ return evaluate(path, cwd, config, true);
78
+ }
79
+ /** The environment a shell child receives: the allowlist only, nothing inherited. */
80
+ export function shellEnv(config, source = process.env) {
81
+ const names = [...ENV_ALLOW, ...(process.platform === "win32" ? ENV_ALLOW_WINDOWS : []), ...config.shellEnvAllow];
82
+ const env = {};
83
+ for (const name of names) {
84
+ const value = source[name];
85
+ if (value !== undefined)
86
+ env[name] = value;
87
+ }
88
+ return { ...env, ...ENV_FIXED };
89
+ }
90
+ const hashFile = (path) => createHash("sha256").update(readFileSync(path)).digest("hex");
91
+ // Bounds on the read records. Dropping one only means a later write asks for a fresh read, so it fails closed.
92
+ export const MAX_PATHS = 2_000;
93
+ export const MAX_CONVERSATIONS = 64;
94
+ export const MAX_PENDING = 256;
95
+ /** Drop the oldest entries of a Map until at most `max` remain. */
96
+ export function trim(map, max) {
97
+ for (const key of map.keys()) {
98
+ if (map.size <= max)
99
+ return;
100
+ map.delete(key);
101
+ }
102
+ }
103
+ export function createGuard(deps) {
104
+ let harness;
105
+ // conversation -> path key -> content hash at the last read or own write
106
+ const seen = new Map();
107
+ // hash taken before a read runs, recorded only if the read succeeds, so a change during the read is caught later
108
+ const pending = new Map();
109
+ const keyOf = (path, cwd) => {
110
+ const key = canonicalize(String(path), cwd);
111
+ return process.platform === "win32" ? key.toLowerCase() : key;
112
+ };
113
+ const hashIfFile = (path) => {
114
+ try {
115
+ return statSync(path).isFile() ? hashFile(path) : undefined;
116
+ }
117
+ catch {
118
+ return undefined;
119
+ }
120
+ };
121
+ const remember = (id, key, hash) => {
122
+ const map = seen.get(id) ?? new Map();
123
+ seen.delete(id);
124
+ seen.set(id, map); // most recently used last
125
+ map.delete(key);
126
+ map.set(key, hash);
127
+ trim(map, MAX_PATHS);
128
+ trim(seen, MAX_CONVERSATIONS);
129
+ };
130
+ /** Why a write or edit to this path must wait for a read; undefined when it may go ahead. */
131
+ const readFirst = (id, path, cwd) => {
132
+ const target = canonicalize(String(path), cwd);
133
+ let isFile = false;
134
+ try {
135
+ isFile = statSync(target).isFile();
136
+ }
137
+ catch {
138
+ return undefined;
139
+ } // does not exist: a new file
140
+ if (!isFile)
141
+ return undefined;
142
+ const known = seen.get(id)?.get(keyOf(path, cwd));
143
+ if (known === undefined)
144
+ return "that file exists and has not been read in this conversation; read it first";
145
+ return hashIfFile(target) === known ? undefined : "that file changed since it was read; read it again";
146
+ };
147
+ /** True when the recorded Vesperia child is this conversation. An unreadable record means no. */
148
+ const isVesperia = async (id) => {
149
+ try {
150
+ return (await deps.pipeline?.())?.vesperia === id;
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ };
156
+ const writerDenied = async (conversationId) => {
157
+ let state;
158
+ try {
159
+ state = deps.pipeline ? await deps.pipeline() : undefined;
160
+ }
161
+ catch {
162
+ return "the Conclave state could not be read, so writes are paused (fail closed)";
163
+ }
164
+ if (state?.vesperia !== undefined && conversationId === state.vesperia)
165
+ return undefined;
166
+ if (conversationId !== ROOT)
167
+ return "only the root conversation or the Vesperia child may write or run commands";
168
+ if (state?.taskId !== undefined) {
169
+ if (harness === undefined)
170
+ return "the guard is not bound to a harness, so a live Conclave pipeline cannot be ruled out";
171
+ if (await isTaskLive(harness, state.taskId))
172
+ return "a Conclave pipeline is running or paused; use /conclave cancel to stop it before writing from the root";
173
+ }
174
+ // F3: reports are untrusted data. A turn made only of reports may not write or run commands until the user sends something.
175
+ try {
176
+ if (deps.reportOnly && (await deps.reportOnly()))
177
+ return "this turn was started by Conclave reports, which are untrusted data; send a message to allow writes and commands";
178
+ }
179
+ catch {
180
+ return "the turn's origin could not be read, so writes are paused (fail closed)";
181
+ }
182
+ return undefined;
183
+ };
184
+ // Child conversations (Conclave members) may only touch files under their working directory.
185
+ const contained = (path, cwd) => {
186
+ try {
187
+ if (cwd === undefined || cwd === "")
188
+ return { allowed: false, reason: "this conversation has no working directory, so file access is refused" };
189
+ if (typeof path !== "string")
190
+ 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" };
192
+ }
193
+ catch {
194
+ return { allowed: false, reason: "the path could not be evaluated" };
195
+ }
196
+ };
197
+ const shellPrepare = (execution) => {
198
+ execution.inheritEnv = false;
199
+ execution.env = shellEnv(deps.config());
200
+ };
201
+ const beforeTool = async (call, api) => {
202
+ const config = deps.config();
203
+ const args = (call.arguments ?? {});
204
+ const id = api.conversationId;
205
+ let cwd;
206
+ if (PATH_TOOLS.has(call.name)) {
207
+ try {
208
+ cwd = (await api.snapshot(AgentDoc, api.conversationId, ctx))?.cwd;
209
+ }
210
+ catch {
211
+ cwd = undefined;
212
+ }
213
+ const verdict = call.name === "read" ? checkRead(args.path, cwd, config) : checkPath(args.path, cwd, config);
214
+ if (!verdict.allowed)
215
+ return { block: `blocked by guard: ${verdict.reason}` };
216
+ if (id !== ROOT) {
217
+ const inside = contained(args.path, cwd);
218
+ if (!inside.allowed)
219
+ return { block: `blocked by guard: ${inside.reason}` };
220
+ }
221
+ }
222
+ if (WRITE_TOOLS.has(call.name) || SHELL_TOOLS.has(call.name)) {
223
+ const denied = await writerDenied(id);
224
+ if (denied !== undefined)
225
+ return { block: `blocked by guard: ${denied}` };
226
+ }
227
+ if (SHELL_TOOLS.has(call.name) && killsProcess(args.command))
228
+ return { block: "blocked by guard: process-kill commands are not allowed from the agent" };
229
+ if (WRITE_TOOLS.has(call.name)) {
230
+ const refusal = readFirst(id, args.path, cwd);
231
+ if (refusal !== undefined)
232
+ return { block: `blocked by guard: ${refusal}` };
233
+ }
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))) {
236
+ const key = keyOf(args.path, cwd);
237
+ const path = canonicalize(String(args.path), cwd);
238
+ try {
239
+ capture(config.home, id, key, path, cwd);
240
+ }
241
+ catch (error) {
242
+ // Fail open: the write goes ahead. Try to list the file as not restorable; if that fails too, warn.
243
+ try {
244
+ captureLost(config.home, id, key, path, cwd, error);
245
+ }
246
+ catch {
247
+ deps.warn?.(`undo: could not save a copy of ${path}; /conclave undo will not list it`);
248
+ }
249
+ }
250
+ }
251
+ // 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))) {
253
+ try {
254
+ countBash(config.home, id);
255
+ }
256
+ catch { /* fail open */ }
257
+ }
258
+ if (call.name === "read" && call.id !== undefined) {
259
+ const hash = hashIfFile(canonicalize(String(args.path), cwd));
260
+ if (hash !== undefined) {
261
+ pending.set(call.id, { id, key: keyOf(args.path, cwd), hash });
262
+ trim(pending, MAX_PENDING);
263
+ }
264
+ }
265
+ if (SHELL_TOOLS.has(call.name)) {
266
+ const cap = Math.max(1, Math.ceil(config.shellTimeoutMs / 1000));
267
+ const asked = typeof args.timeout === "number" && Number.isFinite(args.timeout) && args.timeout > 0 ? args.timeout : cap;
268
+ return { arguments: { ...args, timeout: Math.min(asked, cap) } };
269
+ }
270
+ return undefined;
271
+ };
272
+ const afterTool = async (call, result, api) => {
273
+ const entry = call.id === undefined ? undefined : pending.get(call.id);
274
+ if (call.id !== undefined)
275
+ pending.delete(call.id);
276
+ if (result.isError)
277
+ return undefined;
278
+ if (entry !== undefined)
279
+ remember(entry.id, entry.key, entry.hash);
280
+ if (WRITE_TOOLS.has(call.name)) {
281
+ const args = (call.arguments ?? {});
282
+ let cwd;
283
+ try {
284
+ cwd = (await api.snapshot(AgentDoc, api.conversationId, ctx))?.cwd;
285
+ }
286
+ catch {
287
+ cwd = undefined;
288
+ }
289
+ const hash = hashIfFile(canonicalize(String(args.path), cwd));
290
+ if (hash !== undefined) {
291
+ remember(api.conversationId, keyOf(args.path, cwd), hash);
292
+ if (await isVesperia(api.conversationId))
293
+ try {
294
+ recordPost(deps.config().home, api.conversationId, keyOf(args.path, cwd), hash);
295
+ }
296
+ catch {
297
+ deps.warn?.("undo: could not record the final state of a written file; /conclave undo may skip it");
298
+ }
299
+ }
300
+ }
301
+ return undefined;
302
+ };
303
+ const read = createReadTool();
304
+ const extension = defineExtension({
305
+ name: "guard",
306
+ wraps: [wrapTool(read, (tool) => ({ ...tool, replay: "safe" }))],
307
+ hooks: [hook(ToolTask, { beforeTool, afterTool })],
308
+ });
309
+ return {
310
+ extension,
311
+ bindHarness(h) { harness = h; },
312
+ shellPrepare,
313
+ config: deps.config,
314
+ tools() {
315
+ return [read, createWriteTool(), createEditTool(), clipShellOutput(createBashTool({ prepare: shellPrepare }))];
316
+ },
317
+ };
318
+ }
319
+ /**
320
+ * Every stored selection must list `guard` first. Returns the conversations that do not. The caller reconfigures
321
+ * the root and refuses to use any other offender.
322
+ */
323
+ export async function conversationsWithoutGuardFirst(harness) {
324
+ const ids = await harness.commit(async (tx) => {
325
+ const found = [];
326
+ let cursor;
327
+ for (;;) {
328
+ const page = await tx.scanConversations({}, 100, cursor);
329
+ for (const conversation of page.items)
330
+ found.push(conversation.id);
331
+ if (page.next === undefined)
332
+ break;
333
+ cursor = page.next;
334
+ }
335
+ return found;
336
+ }, ctx);
337
+ const bad = [];
338
+ for (const id of ids) {
339
+ const selection = (await harness.snapshot(AgentDoc, id, ctx))?.extensions;
340
+ if (Array.isArray(selection) && selection[0] !== "guard")
341
+ bad.push(id);
342
+ if (selection !== undefined && !Array.isArray(selection) && selection.remove?.includes("guard"))
343
+ bad.push(id);
344
+ }
345
+ return bad;
346
+ }
package/dist/lock.js ADDED
@@ -0,0 +1,56 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ // Process-wide exclusive lock (D13). One piroboros process per home: the lock database is opened with
3
+ // locking_mode=EXCLUSIVE and a BEGIN EXCLUSIVE transaction that stays open for the life of the process.
4
+ // The operating system releases it when the process ends, however it ends.
5
+ export const EXIT_LOCK_BUSY = 3;
6
+ export class LockBusyError extends Error {
7
+ exitCode = EXIT_LOCK_BUSY;
8
+ constructor(path) {
9
+ super(`another piroboros process is using this home (lock held on ${path}); close it and try again`);
10
+ this.name = "LockBusyError";
11
+ }
12
+ }
13
+ // SQLITE_BUSY is 5 and SQLITE_LOCKED is 6; node:sqlite reports them in `errcode`.
14
+ function isBusy(error) {
15
+ const e = error;
16
+ return e.errcode === 5 || e.errcode === 6 || /database is locked|SQLITE_BUSY/iu.test(e.message ?? "");
17
+ }
18
+ /**
19
+ * Take the exclusive lock or throw LockBusyError (exit code 3). Any other failure is rethrown unchanged,
20
+ * so an unwritable home is not reported as "busy".
21
+ */
22
+ export function acquireLock(path) {
23
+ let db;
24
+ try {
25
+ db = new DatabaseSync(path);
26
+ db.exec("PRAGMA busy_timeout = 0");
27
+ db.exec("PRAGMA locking_mode = EXCLUSIVE");
28
+ db.exec("BEGIN EXCLUSIVE");
29
+ }
30
+ catch (error) {
31
+ try {
32
+ db?.close();
33
+ }
34
+ catch { /* the failed handle is discarded */ }
35
+ if (isBusy(error))
36
+ throw new LockBusyError(path);
37
+ throw error;
38
+ }
39
+ const held = db;
40
+ let released = false;
41
+ return {
42
+ release() {
43
+ if (released)
44
+ return;
45
+ released = true;
46
+ try {
47
+ held.exec("ROLLBACK");
48
+ }
49
+ catch { /* already closed */ }
50
+ try {
51
+ held.close();
52
+ }
53
+ catch { /* already closed */ }
54
+ },
55
+ };
56
+ }