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,43 @@
1
+ // How a member's final text becomes the item posted to the root (D16, Elaria M6). A report up to `max` code points is
2
+ // posted whole; a longer one keeps its first 60% and its last 35% of `max` (2,400 and 1,400 at the default 4,000) with
3
+ // one marker between them. When the first Verdict line of the full text lies in the omitted part (it starts before the kept tail and does not end inside the kept head), one line `Verdict: <value as written> (from the omitted part)` follows the marker, so verdictOf still finds it; that line does not count against `max`. A Verdict line that straddles the head cut is dropped from the head whole and restated the same way. The marker spells out "code points omitted" and has no ellipsis glyphs, which differs on purpose from PLAN.md D16. Every item carries exactly one pointer to the member's whole chat. Cuts are made on code
4
+ // points, so a character outside the basic plane is never split into lone surrogates.
5
+ export const REPORT_MAX = 4_000;
6
+ /** The final-plan seat is the executor's only brief, so it may exceed a reviewer's cap. */
7
+ export const FINAL_PLAN_MAX = 12_000;
8
+ export const pointer = (name) => `full: zoom("${name}")`;
9
+ export const cutSizes = (max) => ({ head: Math.floor(max * 0.6), tail: Math.floor(max * 0.35) });
10
+ export function formatReport(name, text, max = REPORT_MAX) {
11
+ const points = Array.from(text);
12
+ if (points.length <= max)
13
+ return `${text}\n${pointer(name)}`;
14
+ const { head, tail } = cutSizes(max);
15
+ let kept = points.slice(0, head).join("");
16
+ const m = VERDICT.exec(text);
17
+ // A first Verdict line that starts in the head but ends after it is cut off at its line start, so no cut copy of it stays.
18
+ if (m !== null && m.index < kept.length && m.index + m[0].length > kept.length)
19
+ kept = text.slice(0, m.index);
20
+ const tailText = points.slice(points.length - tail).join("");
21
+ const omitted = points.length - Array.from(kept).length - tail;
22
+ // By position: a first Verdict line that does not end inside the kept head and starts before the tail gets restated after the marker, before the tail.
23
+ const verdict = m !== null && m.index + m[0].length > kept.length && m.index < text.length - tailText.length ? `\nVerdict: ${m[1].trim()} (from the omitted part)` : "";
24
+ return `${kept}\n[${omitted} code points omitted; ${pointer(name)}]${verdict}\n${tailText}`;
25
+ }
26
+ const VERDICT = /^[\s*_#>-]*verdict[\s*_]*:[\s*_]*(.+)$/imu;
27
+ /** The first Verdict line of a report, anywhere in it, lower case; undefined when there is none. The scan is linear and a report is at most a few thousand characters. */
28
+ export function verdictOf(text) {
29
+ return VERDICT.exec(text)?.[1]?.trim().toLowerCase();
30
+ }
31
+ /** True when a reviewer's verdict asks for changes or sends the plan back, or a report gives no verdict at all (it cannot be trusted to mean proceed), so Samaela writes the final plan. */
32
+ export function needsConsolidation(texts) {
33
+ return texts.some((text) => {
34
+ const verdict = verdictOf(text);
35
+ return verdict === undefined || verdict.startsWith("proceed with changes") || verdict.startsWith("send back");
36
+ });
37
+ }
38
+ /** A report that says the member did not finish. `reason` is one of: no report, turn limit, idle, stuck, cancelled, error. */
39
+ export function failedReport(name, reason, detail) {
40
+ const extra = detail === undefined || detail.trim() === "" ? "" : `: ${detail.trim().replace(/\s+/gu, " ").slice(0, 300)}`;
41
+ const head = reason === "no report" ? "FAILED: no report produced" : `FAILED (${reason})`;
42
+ return `${head}${extra}\n${pointer(name)}`;
43
+ }
package/dist/config.js ADDED
@@ -0,0 +1,614 @@
1
+ import { randomUUID, createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { isAbsolute, join, parse } from "node:path";
5
+ import { canonicalize, isInside, samePath, segments } from "./paths.js";
6
+ // Home directory, config files, settings schema and config integrity. Every filesystem path piroboros
7
+ // owns is derived from the validated home returned by resolveHome().
8
+ export class ConfigError extends Error {
9
+ code;
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.name = "ConfigError";
13
+ this.code = code;
14
+ }
15
+ }
16
+ export function homePaths(home) {
17
+ return {
18
+ home,
19
+ auth: join(home, "auth.json"),
20
+ authLock: join(home, "auth.lock.sqlite"),
21
+ settings: join(home, "settings.json"),
22
+ models: join(home, "models.json"),
23
+ instructions: join(home, "instructions.md"),
24
+ deviceId: join(home, "device-id"),
25
+ lock: join(home, "lock.sqlite"),
26
+ chat: join(home, "chat.sqlite"),
27
+ integrity: join(home, "config-integrity.json"),
28
+ skillsTrust: join(home, "skills-trust.json"),
29
+ telemetry: join(home, "telemetry.sqlite"),
30
+ };
31
+ }
32
+ /** The home piroboros would use with no override. Tests must never touch it. */
33
+ export function defaultHome(profile = homedir()) {
34
+ return join(profile, ".piroboros");
35
+ }
36
+ /**
37
+ * Validate and canonicalize the home directory once. It must be absolute, must not be a filesystem root or
38
+ * the profile root, and must not be, contain or sit inside the profile's `.ssh` directory.
39
+ */
40
+ export function resolveHome(env = process.env, profile = homedir()) {
41
+ const raw = env.PIROBOROS_HOME !== undefined && env.PIROBOROS_HOME !== "" ? env.PIROBOROS_HOME : defaultHome(profile);
42
+ if (!isAbsolute(raw))
43
+ throw new ConfigError("home_invalid", `PIROBOROS_HOME must be an absolute path (got a relative path)`);
44
+ let home;
45
+ try {
46
+ home = canonicalize(raw);
47
+ }
48
+ catch (error) {
49
+ throw new ConfigError("home_invalid", `PIROBOROS_HOME cannot be used: ${error.message}`);
50
+ }
51
+ if (parse(home).root === home)
52
+ throw new ConfigError("home_invalid", "PIROBOROS_HOME must not be a filesystem root");
53
+ const profileRoot = canonicalize(profile);
54
+ if (samePath(home, profileRoot))
55
+ throw new ConfigError("home_invalid", "PIROBOROS_HOME must not be the profile directory");
56
+ const ssh = canonicalize(join(profile, ".ssh"));
57
+ if (isInside(home, ssh))
58
+ throw new ConfigError("home_invalid", "PIROBOROS_HOME must not contain the .ssh directory");
59
+ if (segments(home).includes(".ssh"))
60
+ throw new ConfigError("home_invalid", "PIROBOROS_HOME must not be inside a .ssh directory");
61
+ return home;
62
+ }
63
+ /** Refuses to run automated tests against the real default home. */
64
+ export function assertNotRealHomeInTests(home, env = process.env, profile = homedir()) {
65
+ const underTest = env.NODE_TEST_CONTEXT !== undefined || env.PIROBOROS_TEST === "1";
66
+ if (underTest && samePath(home, canonicalize(defaultHome(profile))))
67
+ throw new ConfigError("test_real_home", "refusing to run tests against the real PIROBOROS_HOME");
68
+ }
69
+ export function ensureHome(home, env = process.env) {
70
+ assertNotRealHomeInTests(home, env);
71
+ try {
72
+ mkdirSync(home, { recursive: true });
73
+ if (!statSync(home).isDirectory())
74
+ throw new Error("not a directory");
75
+ }
76
+ catch (error) {
77
+ throw new ConfigError("home_unwritable", `PIROBOROS_HOME is not usable: ${error.message}`);
78
+ }
79
+ }
80
+ /* --- JSON files ---------------------------------------------------------------------------------------- */
81
+ /** Read a JSON file. Missing file: undefined. A UTF-8 BOM is tolerated. A parse failure names the file. */
82
+ export function readJsonFile(path) {
83
+ if (!existsSync(path))
84
+ return undefined;
85
+ const text = readFileSync(path, "utf8").replace(/^\u{FEFF}/u, "");
86
+ try {
87
+ return JSON.parse(text);
88
+ }
89
+ catch (error) {
90
+ throw new ConfigError("json_invalid", `${path} is not valid JSON: ${error.message}`);
91
+ }
92
+ }
93
+ /** Write JSON without a BOM through a temp file and rename, retrying on EPERM (Windows virus scanners). */
94
+ export function writeJsonFile(path, value, mode = 0o600) {
95
+ writeTextAtomic(path, `${JSON.stringify(value, null, 2)}\n`, mode);
96
+ }
97
+ export function writeTextAtomic(path, text, mode = 0o600) {
98
+ const tmp = `${path}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
99
+ writeFileSync(tmp, text, { encoding: "utf8", mode });
100
+ let lastError;
101
+ for (let attempt = 0; attempt < 10; attempt += 1) {
102
+ try {
103
+ renameSync(tmp, path);
104
+ return;
105
+ }
106
+ catch (error) {
107
+ lastError = error;
108
+ if (error.code !== "EPERM" && error.code !== "EBUSY")
109
+ break;
110
+ const until = Date.now() + 20 * (attempt + 1);
111
+ while (Date.now() < until) { /* short synchronous backoff; the file is small */ }
112
+ }
113
+ }
114
+ throw lastError;
115
+ }
116
+ /* --- device id ------------------------------------------------------------------------------------------ */
117
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
118
+ /**
119
+ * A stable installation id. Created with the exclusive flag and read back, so two processes racing on the
120
+ * first run agree. A file that is not a UUID is a named error rather than a silent replacement.
121
+ */
122
+ export function getDeviceId(home) {
123
+ const path = homePaths(home).deviceId;
124
+ if (!existsSync(path)) {
125
+ try {
126
+ writeFileSync(path, `${randomUUID()}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
127
+ }
128
+ catch (error) {
129
+ if (error.code !== "EEXIST")
130
+ throw error;
131
+ }
132
+ }
133
+ const value = readFileSync(path, "utf8").trim();
134
+ if (!UUID.test(value))
135
+ throw new ConfigError("device_id_corrupt", `${path} does not hold a valid device id; delete the file to create a new one`);
136
+ return value;
137
+ }
138
+ /* --- settings schema -------------------------------------------------------------------------------------- */
139
+ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
140
+ export const THINKING_STEP_MODES = ["collapsed", "summary", "expanded"];
141
+ export const CONCLAVE_MEMBERS = ["samaela", "nytheria", "elaria", "raskreia", "avaritia", "vaelia", "astrelia", "vesperia"];
142
+ export const SETTINGS_DEFAULTS = {
143
+ thinking: "medium",
144
+ compactor: { enabled: true, thinking: "off", maxConcurrent: 8, allowThirdParty: false },
145
+ conclave: { maxTurns: 64, idleTimeoutMs: 600_000, reportMaxChars: 4_000 },
146
+ gateTimeoutMs: 120_000,
147
+ cacheRetention: "short",
148
+ shellEnvAllow: [],
149
+ shellTimeoutMs: 600_000,
150
+ tui: { thinkingSteps: "summary" },
151
+ telemetry: true,
152
+ web: { enabled: false, maxFetches: 10, maxSearches: 5 },
153
+ };
154
+ /** A host name for web.allowHosts and web.queryHosts: lower case DNS labels, no scheme, port, path or wildcard. */
155
+ export const WEB_HOST = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/u;
156
+ export class SettingsError extends ConfigError {
157
+ issues;
158
+ constructor(issues) {
159
+ super("settings_invalid", `settings.json is invalid:\n${issues.map((issue) => ` ${issue}`).join("\n")}`);
160
+ this.issues = issues;
161
+ }
162
+ }
163
+ const isObj = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
164
+ export function isModelRef(value) {
165
+ if (typeof value !== "string")
166
+ return false;
167
+ const slash = value.indexOf("/");
168
+ return slash > 0 && slash < value.length - 1;
169
+ }
170
+ export function splitModelRef(ref) {
171
+ const slash = ref.indexOf("/");
172
+ return { provider: ref.slice(0, slash), modelId: ref.slice(slash + 1) };
173
+ }
174
+ /** Validate settings. Unknown keys are rejected with the key path named. Throws SettingsError listing every issue. */
175
+ export function validateSettings(value) {
176
+ const issues = [];
177
+ if (!isObj(value))
178
+ throw new SettingsError(["the file must hold a JSON object"]);
179
+ const known = (obj, allowed, path) => {
180
+ for (const key of Object.keys(obj))
181
+ if (!allowed.includes(key))
182
+ issues.push(`${path ? `${path}.` : ""}${key}: unknown key`);
183
+ };
184
+ const check = {
185
+ ref: (v, path) => { if (v !== undefined && !isModelRef(v))
186
+ issues.push(`${path}: must be "provider/model"`); },
187
+ level: (v, path) => { if (v !== undefined && !THINKING_LEVELS.includes(v))
188
+ issues.push(`${path}: must be one of ${THINKING_LEVELS.join(", ")}`); },
189
+ bool: (v, path) => { if (v !== undefined && typeof v !== "boolean")
190
+ issues.push(`${path}: must be true or false`); },
191
+ int: (v, path, min, max = Number.MAX_SAFE_INTEGER) => {
192
+ if (v !== undefined && (typeof v !== "number" || !Number.isInteger(v) || v < min || v > max))
193
+ issues.push(`${path}: must be an integer from ${min}${max === Number.MAX_SAFE_INTEGER ? " up" : ` to ${max}`}`);
194
+ },
195
+ };
196
+ known(value, ["main", "thinking", "compactor", "conclave", "gateTimeoutMs", "cacheRetention", "shellEnvAllow", "shellTimeoutMs", "guard", "tui", "planning", "telemetry", "web"], "");
197
+ check.ref(value.main, "main");
198
+ check.level(value.thinking, "thinking");
199
+ if (value.compactor !== undefined) {
200
+ if (!isObj(value.compactor))
201
+ issues.push("compactor: must be an object");
202
+ else {
203
+ known(value.compactor, ["enabled", "model", "thinking", "maxConcurrent", "allowThirdParty"], "compactor");
204
+ check.bool(value.compactor.enabled, "compactor.enabled");
205
+ check.ref(value.compactor.model, "compactor.model");
206
+ check.level(value.compactor.thinking, "compactor.thinking");
207
+ check.int(value.compactor.maxConcurrent, "compactor.maxConcurrent", 1, 8);
208
+ check.bool(value.compactor.allowThirdParty, "compactor.allowThirdParty");
209
+ }
210
+ }
211
+ if (value.conclave !== undefined) {
212
+ if (!isObj(value.conclave))
213
+ issues.push("conclave: must be an object");
214
+ else {
215
+ known(value.conclave, ["defaultModel", "maxTurns", "idleTimeoutMs", "reportMaxChars", "members"], "conclave");
216
+ check.ref(value.conclave.defaultModel, "conclave.defaultModel");
217
+ check.int(value.conclave.maxTurns, "conclave.maxTurns", 1);
218
+ check.int(value.conclave.idleTimeoutMs, "conclave.idleTimeoutMs", 1_000);
219
+ check.int(value.conclave.reportMaxChars, "conclave.reportMaxChars", 1_000);
220
+ if (value.conclave.members !== undefined) {
221
+ if (!isObj(value.conclave.members))
222
+ issues.push("conclave.members: must be an object");
223
+ else {
224
+ for (const [name, member] of Object.entries(value.conclave.members)) {
225
+ const path = `conclave.members.${name}`;
226
+ if (!CONCLAVE_MEMBERS.includes(name)) {
227
+ issues.push(`${path}: unknown member (expected one of ${CONCLAVE_MEMBERS.join(", ")})`);
228
+ continue;
229
+ }
230
+ if (!isObj(member)) {
231
+ issues.push(`${path}: must be an object`);
232
+ continue;
233
+ }
234
+ known(member, ["model", "thinking", "maxTurns", "idleTimeoutMs"], path);
235
+ check.ref(member.model, `${path}.model`);
236
+ check.level(member.thinking, `${path}.thinking`);
237
+ check.int(member.maxTurns, `${path}.maxTurns`, 1);
238
+ check.int(member.idleTimeoutMs, `${path}.idleTimeoutMs`, 1_000);
239
+ }
240
+ }
241
+ }
242
+ }
243
+ }
244
+ check.int(value.gateTimeoutMs, "gateTimeoutMs", 1);
245
+ if (value.cacheRetention !== undefined && value.cacheRetention !== "short" && value.cacheRetention !== "long")
246
+ issues.push('cacheRetention: must be "short" or "long"');
247
+ if (value.shellEnvAllow !== undefined && !(Array.isArray(value.shellEnvAllow) && value.shellEnvAllow.every((item) => typeof item === "string" && /^[A-Za-z_][A-Za-z0-9_()]*$/u.test(item))))
248
+ issues.push("shellEnvAllow: must be an array of environment variable names");
249
+ check.int(value.shellTimeoutMs, "shellTimeoutMs", 1_000);
250
+ if (value.planning !== undefined && typeof value.planning !== "boolean")
251
+ issues.push("planning: must be true or false");
252
+ if (value.telemetry !== undefined && typeof value.telemetry !== "boolean")
253
+ issues.push("telemetry: must be true or false");
254
+ if (value.guard !== undefined) {
255
+ if (!isObj(value.guard))
256
+ issues.push("guard: must be an object");
257
+ else {
258
+ known(value.guard, ["deny"], "guard");
259
+ if (value.guard.deny !== undefined && !(Array.isArray(value.guard.deny) && value.guard.deny.every((item) => typeof item === "string" && isAbsolute(item))))
260
+ issues.push("guard.deny: must be an array of absolute paths");
261
+ }
262
+ }
263
+ if (value.web !== undefined) {
264
+ if (!isObj(value.web))
265
+ issues.push("web: must be an object");
266
+ else {
267
+ known(value.web, ["enabled", "maxFetches", "maxSearches", "search", "allowHosts", "queryHosts"], "web");
268
+ check.bool(value.web.enabled, "web.enabled");
269
+ check.int(value.web.maxFetches, "web.maxFetches", 1, 100);
270
+ check.int(value.web.maxSearches, "web.maxSearches", 1, 100);
271
+ if (value.web.search !== undefined) {
272
+ if (!isObj(value.web.search))
273
+ issues.push("web.search: must be an object");
274
+ else {
275
+ known(value.web.search, ["provider"], "web.search");
276
+ const provider = value.web.search.provider;
277
+ if (provider !== undefined && provider !== "tinyfish" && provider !== "exa")
278
+ issues.push('web.search.provider: must be "tinyfish" or "exa"');
279
+ }
280
+ }
281
+ for (const key of ["allowHosts", "queryHosts"]) {
282
+ const list = value.web[key];
283
+ if (list !== undefined && !(Array.isArray(list) && list.every((item) => typeof item === "string" && WEB_HOST.test(item))))
284
+ issues.push(`web.${key}: must be an array of lower case host names such as "docs.example.org" (no scheme, port or path)`);
285
+ }
286
+ }
287
+ }
288
+ if (value.tui !== undefined) {
289
+ if (!isObj(value.tui))
290
+ issues.push("tui: must be an object");
291
+ else {
292
+ known(value.tui, ["thinkingSteps"], "tui");
293
+ if (value.tui.thinkingSteps !== undefined && !THINKING_STEP_MODES.includes(value.tui.thinkingSteps))
294
+ issues.push(`tui.thinkingSteps: must be one of ${THINKING_STEP_MODES.join(", ")}`);
295
+ }
296
+ }
297
+ if (issues.length > 0)
298
+ throw new SettingsError(issues);
299
+ return value;
300
+ }
301
+ /** Settings with defaults applied (read only; the file keeps only what the user or the wizard wrote). */
302
+ export function withDefaults(settings) {
303
+ return {
304
+ main: settings.main,
305
+ thinking: settings.thinking ?? SETTINGS_DEFAULTS.thinking,
306
+ compactor: { ...SETTINGS_DEFAULTS.compactor, ...settings.compactor },
307
+ conclave: { ...SETTINGS_DEFAULTS.conclave, ...settings.conclave },
308
+ gateTimeoutMs: settings.gateTimeoutMs ?? SETTINGS_DEFAULTS.gateTimeoutMs,
309
+ cacheRetention: settings.cacheRetention ?? SETTINGS_DEFAULTS.cacheRetention,
310
+ shellEnvAllow: settings.shellEnvAllow ?? [],
311
+ shellTimeoutMs: settings.shellTimeoutMs ?? SETTINGS_DEFAULTS.shellTimeoutMs,
312
+ guardDeny: settings.guard?.deny ?? [],
313
+ planning: settings.planning ?? true,
314
+ telemetry: settings.telemetry ?? SETTINGS_DEFAULTS.telemetry,
315
+ web: {
316
+ enabled: settings.web?.enabled ?? SETTINGS_DEFAULTS.web.enabled,
317
+ maxFetches: settings.web?.maxFetches ?? SETTINGS_DEFAULTS.web.maxFetches,
318
+ maxSearches: settings.web?.maxSearches ?? SETTINGS_DEFAULTS.web.maxSearches,
319
+ provider: settings.web?.search?.provider,
320
+ allowHosts: settings.web?.allowHosts ?? [],
321
+ queryHosts: settings.web?.queryHosts ?? [],
322
+ },
323
+ thinkingSteps: settings.tui?.thinkingSteps ?? SETTINGS_DEFAULTS.tui.thinkingSteps,
324
+ };
325
+ }
326
+ /** `compactor: not configured` means no model; `compactor: disabled` means enabled is false. */
327
+ export function compactorStatus(settings) {
328
+ if (settings.compactor?.model === undefined)
329
+ return "not configured";
330
+ return settings.compactor.enabled === false ? "disabled" : "configured";
331
+ }
332
+ export function readSettings(home) {
333
+ const raw = readJsonFile(homePaths(home).settings);
334
+ return raw === undefined ? {} : validateSettings(raw);
335
+ }
336
+ function mergeDeep(base, patch) {
337
+ const out = { ...base };
338
+ for (const [key, value] of Object.entries(patch)) {
339
+ if (value === undefined)
340
+ continue;
341
+ out[key] = isObj(value) && isObj(out[key]) ? mergeDeep(out[key], value) : value;
342
+ }
343
+ return out;
344
+ }
345
+ export const SETTINGS_CHANGED = "settings.json changed outside piroboros; run /reload first";
346
+ /**
347
+ * The only settings write. It refuses when the file is not what piroboros last wrote (or was never recorded),
348
+ * then applies `edit`, validates, writes atomically and records the hash of the string it wrote.
349
+ */
350
+ function checkedWrite(home, edit) {
351
+ const path = homePaths(home).settings;
352
+ let text;
353
+ try {
354
+ text = readFileSync(path, "utf8");
355
+ }
356
+ catch (error) {
357
+ if (error.code !== "ENOENT")
358
+ throw error;
359
+ }
360
+ if (text !== undefined && readIntegrity(home).settings?.sha256 !== sha(text))
361
+ throw new ConfigError("settings_changed", SETTINGS_CHANGED);
362
+ let current;
363
+ try {
364
+ current = text === undefined ? undefined : JSON.parse(text.replace(/^\u{FEFF}/u, ""));
365
+ }
366
+ catch (error) {
367
+ throw new ConfigError("json_invalid", `${path} is not valid JSON: ${error.message}`);
368
+ }
369
+ const merged = validateSettings(edit(isObj(current) ? current : {}));
370
+ const written = `${JSON.stringify(merged, null, 2)}\n`;
371
+ writeTextAtomic(path, written, 0o600);
372
+ const record = readIntegrity(home);
373
+ record.settings = recordOf("settings", written);
374
+ writeJsonFile(homePaths(home).integrity, record);
375
+ return merged;
376
+ }
377
+ /** Merges only the patched keys through the checked write. */
378
+ export function mergeSettings(home, patch) {
379
+ return checkedWrite(home, (current) => mergeDeep(current, patch));
380
+ }
381
+ function unsetPath(obj, parts) {
382
+ const [head, ...rest] = parts;
383
+ if (head === undefined || !(head in obj))
384
+ return obj;
385
+ const out = { ...obj };
386
+ if (rest.length === 0)
387
+ delete out[head];
388
+ else if (isObj(out[head])) {
389
+ const child = unsetPath(out[head], rest);
390
+ if (Object.keys(child).length === 0)
391
+ delete out[head];
392
+ else
393
+ out[head] = child;
394
+ }
395
+ return out;
396
+ }
397
+ /** 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(".")));
400
+ }
401
+ /** 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));
404
+ }
405
+ /** The value at a dotted path such as "web.search.provider", or undefined. */
406
+ export function getSetting(settings, path) {
407
+ let at = settings;
408
+ for (const part of path.split("."))
409
+ at = isObj(at) ? at[part] : undefined;
410
+ return at;
411
+ }
412
+ /** The patch that sets one dotted path: ("web.maxFetches", 3) gives { web: { maxFetches: 3 } }. */
413
+ export function settingPatch(path, value) {
414
+ return path.split(".").reduceRight((inner, part) => ({ [part]: inner }), value);
415
+ }
416
+ /* --- config integrity (F5) -------------------------------------------------------------------------------- */
417
+ const FILES = ["settings", "models", "instructions", "skills-trust"];
418
+ function fileFor(home, name) {
419
+ const paths = homePaths(home);
420
+ return name === "settings" ? paths.settings : name === "models" ? paths.models : name === "skills-trust" ? paths.skillsTrust : paths.instructions;
421
+ }
422
+ const sha = (text) => createHash("sha256").update(text).digest("hex");
423
+ function securityKeys(settings) {
424
+ if (!isObj(settings))
425
+ return {};
426
+ // Only members that have a model: a member with just a thinking level or a limit is not a security change.
427
+ const withModel = isObj(settings.conclave) && isObj(settings.conclave.members) ? Object.entries(settings.conclave.members).flatMap(([name, member]) => (isObj(member) && member.model !== undefined ? [[name, member.model]] : [])) : [];
428
+ const members = withModel.length === 0 ? undefined : Object.fromEntries(withModel);
429
+ return {
430
+ main: settings.main,
431
+ "compactor.model": isObj(settings.compactor) ? settings.compactor.model : undefined,
432
+ "compactor.allowThirdParty": isObj(settings.compactor) ? settings.compactor.allowThirdParty : undefined,
433
+ "conclave.defaultModel": isObj(settings.conclave) ? settings.conclave.defaultModel : undefined,
434
+ "conclave.members.models": members,
435
+ shellEnvAllow: settings.shellEnvAllow,
436
+ shellTimeoutMs: settings.shellTimeoutMs,
437
+ "guard.deny": isObj(settings.guard) ? settings.guard.deny : undefined,
438
+ "web.enabled": isObj(settings.web) ? settings.web.enabled : undefined,
439
+ "web.maxFetches": isObj(settings.web) ? settings.web.maxFetches : undefined,
440
+ "web.maxSearches": isObj(settings.web) ? settings.web.maxSearches : undefined,
441
+ "web.search.provider": isObj(settings.web) && isObj(settings.web.search) ? settings.web.search.provider : undefined,
442
+ "web.allowHosts": isObj(settings.web) ? settings.web.allowHosts : undefined,
443
+ "web.queryHosts": isObj(settings.web) ? settings.web.queryHosts : undefined,
444
+ };
445
+ }
446
+ function readIntegrity(home) {
447
+ try {
448
+ const raw = readJsonFile(homePaths(home).integrity);
449
+ return isObj(raw) ? raw : {};
450
+ }
451
+ catch {
452
+ return {};
453
+ }
454
+ }
455
+ function recordOf(name, text) {
456
+ let keys;
457
+ if (name === "settings") {
458
+ try {
459
+ keys = securityKeys(JSON.parse(text.replace(/^\u{FEFF}/u, "")));
460
+ }
461
+ catch {
462
+ keys = undefined;
463
+ }
464
+ }
465
+ return { sha256: sha(text), ...(keys ? { keys } : {}) };
466
+ }
467
+ /** `key: old -> new` lines for the keys that differ between two security-key maps. */
468
+ function diffKeys(before, after) {
469
+ const lines = [];
470
+ for (const key of new Set([...Object.keys(before ?? {}), ...Object.keys(after)])) {
471
+ const a = JSON.stringify(before?.[key]);
472
+ const b = JSON.stringify(after[key]);
473
+ if (a !== b)
474
+ lines.push(`${key}: ${a ?? "unset"} -> ${b ?? "unset"}`);
475
+ }
476
+ return lines;
477
+ }
478
+ /** The security-relevant changes between two settings objects, as `key: old -> new` lines. */
479
+ export function diffSecurityKeys(before, after) {
480
+ return diffKeys(securityKeys(before), securityKeys(after));
481
+ }
482
+ /** The keys a chat command must confirm before it changes them. They are the keys of securityKeys(), the single source. */
483
+ export const SECURITY_KEYS = Object.keys(securityKeys({}));
484
+ /** The security-relevant changes `change` would make to `current`, as `key: old -> new` lines. Every chat write path asks about a non-empty result. */
485
+ export function securityChanges(current, change) {
486
+ return diffSecurityKeys(current, previewSettings(current, change));
487
+ }
488
+ const field = (path, type, applies, extra = {}) => ({
489
+ path, type, applies, security: SECURITY_KEYS.includes(path) || /^conclave\.members\.[a-z]+\.model$/u.test(path), ...extra,
490
+ });
491
+ /** Every leaf key of settings.json (56). A test checks it against validateSettings, securityKeys and the defaults. */
492
+ export const SETTING_FIELDS = [
493
+ field("main", "ref", "turn", { role: "main" }),
494
+ field("thinking", "enum", "turn", { values: THINKING_LEVELS }),
495
+ field("compactor.enabled", "bool", "now"),
496
+ field("compactor.model", "ref", "now", { role: "compactor" }),
497
+ field("compactor.thinking", "enum", "now", { values: THINKING_LEVELS }),
498
+ field("compactor.maxConcurrent", "int", "now", { min: 1, max: 8 }),
499
+ field("compactor.allowThirdParty", "bool", "now"),
500
+ field("conclave.defaultModel", "ref", "run", { role: "main" }),
501
+ field("conclave.maxTurns", "int", "run", { min: 1 }),
502
+ field("conclave.idleTimeoutMs", "int", "run", { min: 1_000 }),
503
+ field("conclave.reportMaxChars", "int", "run", { min: 1_000 }),
504
+ ...CONCLAVE_MEMBERS.flatMap((name) => [
505
+ field(`conclave.members.${name}.model`, "ref", "run", { role: "main" }),
506
+ field(`conclave.members.${name}.thinking`, "enum", "run", { values: THINKING_LEVELS }),
507
+ field(`conclave.members.${name}.maxTurns`, "int", "run", { min: 1 }),
508
+ field(`conclave.members.${name}.idleTimeoutMs`, "int", "run", { min: 1_000 }),
509
+ ]),
510
+ field("gateTimeoutMs", "int", "turn", { min: 1 }),
511
+ field("cacheRetention", "enum", "turn", { values: ["short", "long"] }),
512
+ field("shellEnvAllow", "list", "now", { entry: "env" }),
513
+ field("shellTimeoutMs", "int", "now", { min: 1_000 }),
514
+ field("guard.deny", "list", "now", { entry: "path" }),
515
+ field("tui.thinkingSteps", "enum", "now", { values: THINKING_STEP_MODES }),
516
+ field("planning", "bool", "start"),
517
+ field("telemetry", "bool", "start"),
518
+ field("web.enabled", "bool", "run"),
519
+ field("web.maxFetches", "int", "now", { min: 1, max: 100 }),
520
+ field("web.maxSearches", "int", "now", { min: 1, max: 100 }),
521
+ field("web.search.provider", "enum", "run", { values: ["tinyfish", "exa"] }),
522
+ field("web.allowHosts", "list", "now", { entry: "host" }),
523
+ field("web.queryHosts", "list", "now", { entry: "host" }),
524
+ ];
525
+ /** The default of a key, or undefined when it has none (the key then means "not set"). */
526
+ export function settingDefault(path) {
527
+ return path === "planning" ? true : getSetting(SETTINGS_DEFAULTS, path);
528
+ }
529
+ /** Record the current hash (and security-relevant keys) of the named files. Called after piroboros writes them. */
530
+ export function recordIntegrity(home, names = FILES) {
531
+ const record = readIntegrity(home);
532
+ for (const name of names) {
533
+ const path = fileFor(home, name);
534
+ if (!existsSync(path)) {
535
+ delete record[name];
536
+ continue;
537
+ }
538
+ record[name] = recordOf(name, readFileSync(path, "utf8"));
539
+ }
540
+ writeJsonFile(homePaths(home).integrity, record);
541
+ }
542
+ /**
543
+ * Compare each config file with the hash recorded at piroboros's last write. A file with no record is
544
+ * treated as unrecorded, not tampered: it is recorded by the caller after the first successful load.
545
+ */
546
+ export function checkIntegrity(home) {
547
+ const record = readIntegrity(home);
548
+ const changes = [];
549
+ for (const name of FILES) {
550
+ const entry = record[name];
551
+ const path = fileFor(home, name);
552
+ if (entry === undefined)
553
+ continue;
554
+ const present = existsSync(path);
555
+ const text = present ? readFileSync(path, "utf8") : "";
556
+ if (present && sha(text) === entry.sha256)
557
+ continue;
558
+ const lines = [];
559
+ if (!present)
560
+ lines.push("file was removed");
561
+ else if (name === "settings") {
562
+ let now = {};
563
+ try {
564
+ now = securityKeys(JSON.parse(text.replace(/^\u{FEFF}/u, "")));
565
+ }
566
+ catch {
567
+ lines.push("file no longer parses as JSON");
568
+ }
569
+ lines.push(...diffKeys(entry.keys, now));
570
+ if (lines.length === 0)
571
+ lines.push("other keys changed");
572
+ }
573
+ else
574
+ lines.push("content changed");
575
+ changes.push({ file: name, lines });
576
+ }
577
+ return { tampered: changes.length > 0, changes };
578
+ }
579
+ /** The changes as text, one block per file. */
580
+ export function describeIntegrity(report) {
581
+ return report.changes.map((change) => `${change.file}:\n${change.lines.map((line) => ` ${line}`).join("\n")}`).join("\n");
582
+ }
583
+ /**
584
+ * What /reload has to ask about: everything checkIntegrity reports, plus files that exist but were never recorded.
585
+ * At startup an unrecorded file is recorded silently. A file that appears while piroboros runs was not written by
586
+ * piroboros, so it needs the same confirmation as an edit.
587
+ */
588
+ export function reloadChanges(home) {
589
+ const report = checkIntegrity(home);
590
+ const record = readIntegrity(home);
591
+ for (const name of FILES) {
592
+ if (record[name] === undefined && existsSync(fileFor(home, name)))
593
+ report.changes.push({ file: name, lines: ["file was added outside piroboros"] });
594
+ }
595
+ return { tampered: report.changes.length > 0, changes: report.changes };
596
+ }
597
+ /** Record files that exist but have no record yet (first run, or a hand-written settings.json). */
598
+ export function recordUnrecorded(home) {
599
+ const record = readIntegrity(home);
600
+ const missing = FILES.filter((name) => record[name] === undefined && existsSync(fileFor(home, name)));
601
+ if (missing.length > 0)
602
+ recordIntegrity(home, missing);
603
+ }
604
+ /**
605
+ * Warning text when the home lies outside the user profile, where other local accounts may be able to
606
+ * read auth.json. piroboros only warns; it does not change permissions.
607
+ */
608
+ export function homeOutsideProfileWarning(home, profile = homedir()) {
609
+ return isInside(canonicalize(profile), home) ? undefined : "The data directory is outside your user profile, so auth.json may be readable by other local users. Move it into your profile or restrict access yourself.";
610
+ }
611
+ /** The user profile directory. The only place besides the guard that asks the operating system for it. */
612
+ export function profileDir() {
613
+ return homedir();
614
+ }