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
package/dist/paths.js ADDED
@@ -0,0 +1,103 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, parse, relative, resolve, sep, win32 } from "node:path";
3
+ // Path helpers shared by the home validator (config.ts) and the guard. No pi imports.
4
+ const WINDOWS = process.platform === "win32";
5
+ /** Names that make a path unsafe to evaluate. Returned instead of throwing so callers can fail closed. */
6
+ export class PathRefused extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "PathRefused";
10
+ }
11
+ }
12
+ function realNative(path) {
13
+ return realpathSync.native(path);
14
+ }
15
+ /**
16
+ * Canonical form used for every containment test: absolute, with the nearest existing ancestor resolved
17
+ * through the filesystem (links, junctions and 8.3 names) and the remaining tail re-joined. The tail does
18
+ * not need to exist, so deny roots that are absent on this machine still work.
19
+ *
20
+ * Refused (PathRefused): alternate data stream syntax, UNC paths other than local admin shares, and
21
+ * device paths other than the `\\?\` drive form.
22
+ */
23
+ export function canonicalize(input, cwd = process.cwd()) {
24
+ if (typeof input !== "string" || input.length === 0 || input.includes("\0"))
25
+ throw new PathRefused("empty or invalid path");
26
+ let value = input;
27
+ if (WINDOWS) {
28
+ if (/^\\\\[?.]\\UNC\\/iu.test(value))
29
+ value = `\\\\${value.slice(8)}`;
30
+ else if (/^\\\\[?.]\\[a-z]:/iu.test(value))
31
+ value = value.slice(4);
32
+ else if (/^\\\\[?.]\\/u.test(value))
33
+ throw new PathRefused("device path refused");
34
+ value = value.replace(/^\/\/[?.]\//u, "");
35
+ const unc = /^[\\/]{2}([^\\/]+)[\\/]+([a-z])\$(?:[\\/]|$)/iu.exec(value);
36
+ if (/^[\\/]{2}[^\\/]/u.test(value)) {
37
+ if (unc === null || !isLocalHost(unc[1]))
38
+ throw new PathRefused("UNC path refused");
39
+ value = `${unc[2].toUpperCase()}:${value.slice(unc[0].length - 1)}`;
40
+ }
41
+ // An alternate data stream (`file:stream`) or a colon anywhere but the drive letter.
42
+ if (value.replace(/^[a-z]:/iu, "").includes(":"))
43
+ throw new PathRefused("alternate data stream syntax refused");
44
+ }
45
+ let absolute = isAbsolute(value) ? resolve(value) : resolve(cwd, value);
46
+ if (WINDOWS)
47
+ absolute = win32.normalize(absolute).split(win32.sep).map(stripTrailing).join(win32.sep);
48
+ // Resolve the nearest existing ancestor through the filesystem, then re-join the tail.
49
+ let head = absolute;
50
+ const tail = [];
51
+ while (!existsSyncSafe(head)) {
52
+ const parent = dirname(head);
53
+ if (parent === head)
54
+ break;
55
+ tail.unshift(parse(head).base);
56
+ head = parent;
57
+ }
58
+ let base = head;
59
+ try {
60
+ base = existsSyncSafe(head) ? realNative(head) : head;
61
+ }
62
+ catch {
63
+ throw new PathRefused("path could not be resolved");
64
+ }
65
+ return tail.length === 0 ? base : join(base, ...tail);
66
+ }
67
+ function existsSyncSafe(path) {
68
+ try {
69
+ return existsSync(path);
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
75
+ /** Windows ignores trailing dots and spaces on a path component. */
76
+ function stripTrailing(component) {
77
+ if (component === "." || component === ".." || component === "")
78
+ return component;
79
+ const stripped = component.replace(/[. ]+$/u, "");
80
+ return stripped.length === 0 ? component : stripped;
81
+ }
82
+ function isLocalHost(name) {
83
+ const n = name.toLowerCase();
84
+ return n === "localhost" || n === "127.0.0.1" || n === "::1" || n === (process.env.COMPUTERNAME ?? "").toLowerCase();
85
+ }
86
+ const fold = (value) => (WINDOWS ? value.toLowerCase() : value);
87
+ /** True when `candidate` is `root` or lies below it. Both must already be canonical. */
88
+ export function isInside(root, candidate) {
89
+ const rel = relative(fold(root), fold(candidate));
90
+ if (rel === "")
91
+ return true;
92
+ if (isAbsolute(rel))
93
+ return false; // another drive
94
+ return rel !== ".." && !rel.startsWith(`..${sep}`);
95
+ }
96
+ /** Case-insensitive path equality on canonical paths. */
97
+ export function samePath(a, b) {
98
+ return fold(a) === fold(b);
99
+ }
100
+ /** Segments of a canonical path, folded for comparison. */
101
+ export function segments(path) {
102
+ return fold(path).split(/[\\/]+/u).filter((part) => part.length > 0);
103
+ }
package/dist/redact.js ADDED
@@ -0,0 +1,79 @@
1
+ // Ported from akashic-forge/store.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ // Pure credential scrub (no imports, no I/O). Re-exported by src/memory/akashic/store.ts.
3
+ export const REDACTION_MARKER = "[REDACTED]";
4
+ /** Remove common credentials before anything is persisted or injected. */
5
+ export function redactSensitive(value) {
6
+ const markerToken = "__AKASHIC_FORGE_REDACTED__";
7
+ let result = value.replaceAll(REDACTION_MARKER, markerToken);
8
+ result = result.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/gi, REDACTION_MARKER);
9
+ result = result.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, `Bearer ${REDACTION_MARKER}`);
10
+ result = result.replace(/([?&](?:api[_-]?key|api[_-]?token|access[_-]?token|password|secret|token)=)[^&#\s]+/gi, `$1${REDACTION_MARKER}`);
11
+ result = result.replace(/\b(?:sk|rk)-[A-Za-z0-9_-]{12,}\b/g, REDACTION_MARKER);
12
+ result = result.replace(/\bAKIA[0-9A-Z]{16}\b/g, REDACTION_MARKER);
13
+ // GitHub tokens (fine-grained and classic) and JWT-shaped values such as the `"access":"eyJ..."` of an OAuth blob.
14
+ result = result.replace(/\b(?:github_pat_|gh[pousr]_)[A-Za-z0-9_]{20,}/g, REDACTION_MARKER);
15
+ result = result.replace(/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g, REDACTION_MARKER);
16
+ // URL userinfo credentials (CAPTURE1 entry precondition, Raskreia R1/R3 via Elaria E1): redact the
17
+ // `user:password` portion of `scheme://user:pass@host`, keep scheme + host readable so URLs stay
18
+ // searchable. Requires a colon inside the userinfo, so bare `user@host` (email-like) is untouched.
19
+ // Anchored on `://` rather than on a scheme pattern, so a scheme of any length is covered and the scan stays linear.
20
+ result = result.replace(/(:\/\/)[^\s\/@:]+:[^\s\/@]+@/g, `$1${REDACTION_MARKER}@`);
21
+ // The value class excludes `[` too (G3/Raskreia one-char fix): the query-param pattern above
22
+ // creates a fresh `[REDACTED]` mid-stream AFTER the pre-existing-marker swap protected it, and the
23
+ // old class matched `[REDACTED` (stopping at the excluded `]`), re-redacting it into a stray
24
+ // `password=[REDACTED]]`. Excluding `[` leaves the inserted marker alone. Accepted cost: a labeled
25
+ // value literally starting with `[` is no longer redacted — vanishingly rare, over-redaction
26
+ // direction only, never a leak.
27
+ // The closing quote of a JSON label (`"password": "x"`) may sit between the label and the colon.
28
+ result = result.replace(/(\b(?:api[-_ ]?key|api[-_ ]?token|access[-_ ]?token|refresh[-_ ]?token|client[-_ ]?secret|authorization|password|passwd|secret|token|private[-_ ]?key)\b["']?\s*[:=]\s*)(["']?)([^\s"',;}\]\[]{4,})/gi, `$1$2${REDACTION_MARKER}`);
29
+ // Environment-variable and connection-string labels that the word-boundary rule above cannot see, because `_`
30
+ // joins them to the word: AWS_SECRET_ACCESS_KEY=..., AccountKey=.... The value must be 8 or more characters, so
31
+ // constants such as `MAX_TOKENS = 72_000` in source text are left alone.
32
+ result = result.replace(/(\b(?:[A-Z][A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_?KEY|ACCESS_?KEY|ACCOUNT_?KEY|PRIVATE_?KEY)[A-Z0-9_]*|(?:Account|SharedAccess)Key)\s*[:=]\s*)(["']?)([^\s"',;}\]\[]{8,})/g, `$1$2${REDACTION_MARKER}`);
33
+ // A phrase such as `the admin <label> is <value> for the box`: the value must hold a non-letter, so plain prose stays.
34
+ result = result.replace(/(\b(?:password|passphrase|passwd)\b[^\n.]{0,40}?\b(?:is|was|are)\s+)(["']?)(?=[^\s"',;]*[^A-Za-z\s"',;])([^\s"',;]{6,})/gi, `$1$2${REDACTION_MARKER}`);
35
+ // Unlabeled high-entropy tokens (same entry precondition), deliberately CONSERVATIVE — the goal's
36
+ // §15 retrieval targets include commit hashes and URLs, so this must never over-redact:
37
+ // - 32–64 chars, word-boundary delimited, mixed case WITH a digit (real secrets are; prose is not);
38
+ // - pure hex of any case is skipped (40-char commit hashes, digests, ids stay intact);
39
+ // - all-lower/all-upper runs are skipped (normal identifiers); contiguous base64 blobs longer
40
+ // than 64 chars never match (no interior word boundary), and `=`-padded base64 is skipped by
41
+ // checking the characters immediately after the candidate.
42
+ // Residual false-positive posture (documented in the contract doc §10): an UNPADDED, unlabeled
43
+ // 32–64-char mixed-case base64url fragment inside tool output would match. That window is kept
44
+ // short on purpose; longer credential material is caught by the labeled/format patterns above.
45
+ result = result.replace(/\b[A-Za-z0-9_-]{32,64}\b/g, (token, offset, full) => {
46
+ if (/^[0-9a-f]+$/i.test(token))
47
+ return token;
48
+ if (!/[a-z]/.test(token) || !/[A-Z]/.test(token) || !/[0-9]/.test(token))
49
+ return token;
50
+ if (/^={1,2}/.test(full.slice(offset + token.length, offset + token.length + 2)))
51
+ return token;
52
+ return REDACTION_MARKER;
53
+ });
54
+ return result.replaceAll(markerToken, REDACTION_MARKER);
55
+ }
56
+ /** Replace every occurrence of each literal value. Longest first, so a value that contains another is removed whole. */
57
+ export function redactLiterals(value, literals) {
58
+ let result = value;
59
+ for (const literal of [...new Set(literals)].filter((item) => item.length >= 8).sort((a, b) => b.length - a.length))
60
+ result = result.replaceAll(literal, REDACTION_MARKER);
61
+ return result;
62
+ }
63
+ /** The scrub for text that leaves the machine (F9): literal values first, then the patterns, then strict hex runs. */
64
+ export function redactOutbound(value, options) {
65
+ let result = redactSensitive(redactLiterals(value, options.literals));
66
+ if (options.strict === true)
67
+ result = result.replace(/\b[0-9a-fA-F]{32,}\b/g, REDACTION_MARKER);
68
+ return result;
69
+ }
70
+ /** Redact string leaves before serializing, so redaction can never break the surrounding JSON. */
71
+ export function redactJsonValue(value) {
72
+ if (typeof value === "string")
73
+ return redactSensitive(value);
74
+ if (Array.isArray(value))
75
+ return value.map((item) => redactJsonValue(item));
76
+ if (value && typeof value === "object")
77
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactJsonValue(item)]));
78
+ return value;
79
+ }
@@ -0,0 +1,378 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { FileCredentialStore } from "./auth.js";
3
+ import { createBase } from "./base.js";
4
+ import { checkIntegrity, compactorStatus, describeIntegrity, ensureHome, getDeviceId, homePaths, isModelRef, profileDir, mergeSettings, readSettings, recordIntegrity, recordUnrecorded, reloadChanges, splitModelRef, unsetSettings, withDefaults, } from "./config.js";
5
+ import { configure, createRegistry, ctx, defineExtension, onSessionFailed, openHarness, parkedTasks, ROOT, SessionFailed } from "./durable.js";
6
+ import { openTelemetry } from "./telemetry.js";
7
+ import { MemoryHost } from "./memory/host.js";
8
+ import { createAkashicTool } from "./memory/akashic/tools.js";
9
+ import { createMnemosiaTools } from "./memory/mnemosia/tools.js";
10
+ import { checkRead, conversationsWithoutGuardFirst, createGuard } from "./guard.js";
11
+ import { createSearch } from "./search.js";
12
+ import { createSkills } from "./skills.js";
13
+ import { contextCheck, createAppModels, resolveModel } from "./models.js";
14
+ import { CompactLoop } from "./chat/compactloop.js";
15
+ import { Compactor } from "./chat/compactor.js";
16
+ import { budget, chat, createStuck, planning, viewtools } from "./chat/extension.js";
17
+ import { checkMappingVersion } from "./chat/log.js";
18
+ import { TurnLoop, enqueueMessage } from "./chat/turn.js";
19
+ import { TurnStateDoc } from "./chat/tree.js";
20
+ import { ensureRun } from "./undo.js";
21
+ import { Conclave, ConclaveDoc, MemberWatch, feedWatch } from "./conclave/pipeline.js";
22
+ import { createWeb, createWebSearch, searchKey } from "./web.js";
23
+ import { ThinkingState } from "./tui/thinking/state.js";
24
+ // Composition root: the credential store, models, guard, harness, root conversation and turn loop.
25
+ /** The root stops when its run shows no output and no running tool for this long (the provider SDK stops its own timer once headers arrive). */
26
+ export const ROOT_IDLE_TIMEOUT_MS = 600_000;
27
+ export const idleStopText = (ms) => `stopped (idle): no output for ${Math.round(ms / 1000)} s.`;
28
+ function reportMessage(error, info) {
29
+ const text = error instanceof Error ? error.message : String(error);
30
+ const source = info === undefined ? undefined : "task" in info && info.task !== undefined ? info.task.kind : "extension" in info ? info.extension : undefined;
31
+ return source === undefined ? text : `${source}: ${text}`;
32
+ }
33
+ const pausedText = (n) => `${n === 1 ? "1 task" : `${n} tasks`} stopped without finishing on several starts in a row and ${n === 1 ? "is" : "are"} paused: Esc stops a paused reply, /conclave cancel a paused pipeline`;
34
+ export async function openRuntime(options) {
35
+ const paths = homePaths(options.home);
36
+ // A storage error fails the whole session (pi-durable 1.2.0). Reports once the session is closing are noise.
37
+ let failed = false;
38
+ let fail = () => { };
39
+ const fatal = new Promise((resolve) => { fail = resolve; });
40
+ const report = (message) => { if (!failed)
41
+ options.onReport?.(message); };
42
+ ensureHome(options.home, options.env);
43
+ recordUnrecorded(options.home);
44
+ const integrity = checkIntegrity(options.home);
45
+ const store = new FileCredentialStore(paths.auth, paths.authLock, report);
46
+ const models = options.models ?? createAppModels(store, options.extraProviders);
47
+ let settings = readSettings(options.home);
48
+ const cwd = options.cwd ?? process.cwd();
49
+ const effective = () => (options.main === undefined ? settings : { ...settings, main: options.main });
50
+ const thinking = new ThinkingState({
51
+ global: () => withDefaults(settings).thinkingSteps,
52
+ write: (value) => { applySettings(value === "clear" ? { unset: "tui.thinkingSteps" } : { set: { tui: { thinkingSteps: value } } }); },
53
+ });
54
+ const PLANNING_NOTE = "planning applies at the next start, because the tool list stays fixed while piroboros runs";
55
+ // Throws on a refused or invalid write. `planningOn` and `loop` are set by the time a chat command calls this.
56
+ const applySettings = (change) => {
57
+ settings = "unset" in change ? unsetSettings(options.home, change.unset) : mergeSettings(options.home, change.set);
58
+ // A new global thinking-steps value replaces the session choice, so it shows at once.
59
+ if ("unset" in change ? change.unset === "tui.thinkingSteps" : change.set.tui?.thinkingSteps !== undefined)
60
+ thinking.clearSession();
61
+ loop.wake();
62
+ return withDefaults(settings).planning !== planningOn ? PLANNING_NOTE : undefined;
63
+ };
64
+ const checkMain = (ref) => {
65
+ if (!isModelRef(ref))
66
+ return { ok: false, error: 'the model must be written as "provider/model"' };
67
+ const model = resolveModel(models, ref);
68
+ if (model === undefined)
69
+ return { ok: false, error: `unknown model ${ref}` };
70
+ const check = contextCheck(model, "main");
71
+ return check.ok ? { ok: true } : { ok: false, error: check.reason ?? "model rejected" };
72
+ };
73
+ const update = (change) => {
74
+ try {
75
+ const note = applySettings(change);
76
+ return { ok: true, ...(note === undefined ? {} : { note }) };
77
+ }
78
+ catch (error) {
79
+ return { ok: false, error: reportMessage(error) };
80
+ }
81
+ };
82
+ const guardConfig = () => {
83
+ const d = withDefaults(settings);
84
+ return { home: options.home, profile: options.profile ?? profileDir(), deny: d.guardDeny, shellTimeoutMs: d.shellTimeoutMs, shellEnvAllow: d.shellEnvAllow };
85
+ };
86
+ // F7: liveness comes from the pipeline task through the harness (isTaskLive). F3: the turn's origin is read from the turn state.
87
+ const guard = createGuard({
88
+ config: guardConfig,
89
+ pipeline: options.pipeline ?? (() => conclave.pipelineState()),
90
+ reportOnly: async () => (await harness.snapshot(TurnStateDoc, ctx))?.reportOnly === true,
91
+ warn: (message) => options.onStatus?.({ kind: "notice", message }),
92
+ });
93
+ const search = createSearch({ home: options.home, guard: guardConfig, ...(options.search ?? {}) });
94
+ const base = createBase([...guard.tools(), ...search.tools]);
95
+ // Skills are scanned once here and again on /reload. A skill file is opened only if the guard would let the read tool open it.
96
+ // Under node --test without an explicit profile the real profile is never scanned (tests must not read the user's own skills).
97
+ const skillsProfile = options.profile ?? (process.env.NODE_TEST_CONTEXT !== undefined || process.env.PIROBOROS_TEST === "1" ? undefined : profileDir());
98
+ const skills = createSkills({ home: options.home, profile: skillsProfile, cwd, allow: (path) => checkRead(path, cwd, guardConfig()).allowed });
99
+ // Memory: the store and vault under ${home}/akashic, briefing traces under ${home}/mnemosia. The tools tell the
100
+ // callers apart through the Conclave doc (a member's role) and the turn state (a report-only turn, F3).
101
+ const memory = new MemoryHost({ home: options.home, warn: (message) => options.onStatus?.({ kind: "notice", message }), runner: options.vaultRunner });
102
+ const caller = async (api) => {
103
+ const conversation = api.conversationId;
104
+ const members = (await api.snapshot(ConclaveDoc, ctx))?.runs ?? {};
105
+ const role = Object.entries(members).find(([, id]) => id === conversation)?.[0] ?? "root";
106
+ // Vesperia's records wait for /akashic accept, like writes made in a report-only turn.
107
+ const reportOnly = role === "vesperia" || (conversation === ROOT && (await api.snapshot(TurnStateDoc, ctx))?.reportOnly === true);
108
+ return { role, cwd: (await api.agent(ctx)).cwd ?? cwd, reportOnly };
109
+ };
110
+ const mnemosia = createMnemosiaTools(memory.foundations, caller);
111
+ // Tools only, no hooks and no sections, so where it sits changes the order of the tool list and nothing else.
112
+ const memoryExtension = defineExtension({ name: "memory", tools: [createAkashicTool(memory, caller), mnemosia.brief, mnemosia.feedback] });
113
+ // H3: the hook names the reason and asks for the stop; the abort runs unawaited, because it waits for the
114
+ // round that is still finishing. The turn loop takes the reason when the aborted run settles.
115
+ let stopReason;
116
+ // A Conclave member that gets stuck is aborted the same way; the pipeline finds the stop in the member's entries and posts FAILED (stuck).
117
+ const stopRun = (id, message) => {
118
+ if (id === ROOT)
119
+ stopReason = message;
120
+ void harness.conversation(id, ctx).then((conversation) => conversation?.abort(ctx)).catch((error) => { if (id === ROOT)
121
+ stopReason = undefined; report(reportMessage(error)); });
122
+ };
123
+ const stuck = createStuck(stopRun);
124
+ const readInstructions = () => {
125
+ try {
126
+ const text = readFileSync(paths.instructions, "utf8").replace(/^\u{FEFF}/u, "").trim();
127
+ return text === "" ? undefined : text;
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ };
133
+ const compactor = new Compactor({ settings: effective, models, authPath: paths.auth, env: options.env ?? process.env, instructions: readInstructions, ...(options.compactorBackoffMs === undefined ? {} : { backoffMs: options.compactorBackoffMs }), ...(options.compactorTimeoutMs === undefined ? {} : { requestTimeoutMs: options.compactorTimeoutMs }) });
134
+ const registry = createRegistry();
135
+ // web_fetch lives in its own extension, which the root never selects. The tool also checks the caller's seat and web.enabled itself.
136
+ const webKey = (provider) => searchKey(provider, paths.auth, options.env ?? process.env);
137
+ // The URLs a Vaelia run may open at the start: the task and the reports posted before her seat (the chat view is not used).
138
+ const webSeed = async (api) => {
139
+ const doc = await api.snapshot(ConclaveDoc, ctx);
140
+ return doc === undefined ? [] : [doc.task, ...doc.review.reports.map((report) => report.text)];
141
+ };
142
+ const webDeps = { caller, seed: webSeed, settings: () => withDefaults(settings).web, scrub: () => compactor.scrubFor(true), searchKey: webKey, ...options.web };
143
+ const webExtension = defineExtension({
144
+ name: "web",
145
+ tools: [createWeb(webDeps), createWebSearch(webDeps)],
146
+ });
147
+ const conclave = new Conclave({
148
+ settings: effective,
149
+ models,
150
+ registry,
151
+ cwd,
152
+ ...options.conclave,
153
+ scrub: () => compactor.scrubFor(false),
154
+ webKey,
155
+ onNotice: (message) => options.onStatus?.({ kind: "notice", message }),
156
+ onVesperia: (run) => { ensureRun(options.home, run); },
157
+ });
158
+ // The compactor and conclave extensions carry only their tasks, which any conversation's tasks resolve by name.
159
+ for (const extension of [guard.extension, base, viewtools, planning, memoryExtension, webExtension, stuck, chat, skills.extension, budget, compactor.extension, conclave.extension])
160
+ registry.install(extension);
161
+ // D12: the root selects the chat extensions explicitly, and the budget extension is last everywhere. The plan
162
+ // tool is part of the selection unless settings.planning is false; that is read at start, so the tool list
163
+ // stays the same for the life of the process. The memory extension follows the other tool extensions: it has
164
+ // no hooks and no sections, so its place only orders the tool list, and stuck, chat and budget keep theirs.
165
+ // The skills section is the last static section: after chat, before budget. It renders nothing without skills.
166
+ const planningOn = withDefaults(settings).planning;
167
+ const rootExtensions = [guard.extension, base, viewtools, ...(planningOn ? [planning] : []), memoryExtension, stuck, chat, skills.extension, budget];
168
+ // A failure to open the store turns telemetry off, visibly; the run goes on without it.
169
+ let telemetry;
170
+ if (withDefaults(settings).telemetry) {
171
+ try {
172
+ telemetry = await openTelemetry(paths.telemetry);
173
+ }
174
+ catch (error) {
175
+ report(`telemetry off: ${reportMessage(error)}`);
176
+ }
177
+ }
178
+ const harness = await openHarness({
179
+ path: options.persistent === false ? undefined : paths.chat,
180
+ storage: options.storage,
181
+ telemetry: telemetry?.recorder,
182
+ models,
183
+ identity: { attribution: null },
184
+ registry,
185
+ settings: {
186
+ extensions: [guard.extension, base, viewtools, budget], steeringMode: "all", followUpMode: "all", compaction: { enabled: false, backgroundTokens: 0 },
187
+ // A getter: pi-durable reads it at every request, so /reload applies a changed cacheRetention at the next turn.
188
+ get stream() { return { cacheRetention: withDefaults(effective()).cacheRetention }; },
189
+ },
190
+ onReport: (error, info) => { if (info.type !== "task_parked")
191
+ report(reportMessage(error, info)); },
192
+ }).catch(async (error) => {
193
+ await telemetry?.close().catch(() => undefined);
194
+ memory.close();
195
+ throw error;
196
+ });
197
+ // The session starts closing the moment storage throws, before the failing call's error reaches its caller.
198
+ harness.subscribeClose(() => { failed = true; });
199
+ onSessionFailed(harness, fail);
200
+ guard.bindHarness(harness);
201
+ compactor.bind(harness);
202
+ conclave.bind(harness);
203
+ const agent = (() => {
204
+ const main = effective().main !== undefined && isModelRef(effective().main) ? splitModelRef(effective().main) : undefined;
205
+ return { extensions: rootExtensions, cwd, ...(main ? { model: { provider: main.provider, modelId: main.modelId } } : {}) };
206
+ })();
207
+ let root;
208
+ try {
209
+ await checkMappingVersion(harness, [guard.extension, base, viewtools, planning, memoryExtension, stuck, chat, skills.extension, budget].map((e) => e.name)); // a stored index from another mapping is never remapped
210
+ root = await harness.root(ctx, { agent });
211
+ // Every stored selection must list guard first. The root is repaired; anything else is refused. Any other
212
+ // difference between the stored root selection and the code's is migrated by the first turn commit (turn.ts).
213
+ const offenders = await conversationsWithoutGuardFirst(harness);
214
+ for (const id of offenders) {
215
+ if (id !== ROOT)
216
+ throw new Error(`conversation ${id} does not select the guard first; refusing to open`);
217
+ }
218
+ if (offenders.length > 0)
219
+ await root.configure({ extensions: rootExtensions }, ctx);
220
+ }
221
+ catch (error) {
222
+ await harness.close(ctx);
223
+ await telemetry?.close().catch(() => undefined);
224
+ memory.close();
225
+ throw error;
226
+ }
227
+ harness.resume();
228
+ // Root idle watchdog: a MemberWatch fed by the root's commits. Its timer runs only while a run is in progress.
229
+ const idleMs = options.rootIdleTimeoutMs ?? ROOT_IDLE_TIMEOUT_MS;
230
+ const rootWatch = new MemberWatch({ maxTurns: Infinity, idleTimeoutMs: idleMs }, () => stopRun(ROOT, idleStopText(idleMs)));
231
+ let idleTimer;
232
+ const unwatch = feedWatch(harness, ROOT, rootWatch, (running) => {
233
+ if (!running) {
234
+ clearInterval(idleTimer);
235
+ idleTimer = undefined;
236
+ stuck.endRun();
237
+ }
238
+ else if (idleTimer === undefined) {
239
+ rootWatch.reason = undefined; // one watch serves every run
240
+ rootWatch.activity(); // the tool state was just set from this same change
241
+ idleTimer = setInterval(() => rootWatch.tick(), Math.max(10, Math.min(250, idleMs / 4)));
242
+ idleTimer.unref();
243
+ }
244
+ });
245
+ // pi-durable resumes a live pipeline by itself. Say so, and forget one that ended while piroboros was closed.
246
+ await conclave.recover().catch((error) => report(reportMessage(error)));
247
+ const parked = await parkedTasks(harness);
248
+ if (parked.length > 0)
249
+ options.onStatus?.({ kind: "notice", message: pausedText(parked.length) });
250
+ const compact = new CompactLoop({ harness, root, compactor, onAlarm: (text) => report(`alarm: ${text}`), onReport: (error) => report(reportMessage(error)) });
251
+ const loop = new TurnLoop({
252
+ harness,
253
+ root,
254
+ models,
255
+ settings: () => ({ main: effective().main, thinking: withDefaults(settings).thinking, cwd }),
256
+ onStatus: options.onStatus,
257
+ onRestore: options.onRestore,
258
+ onReport: (error) => report(reportMessage(error)),
259
+ takeStop: () => { const reason = stopReason; stopReason = undefined; return reason; },
260
+ index: compact,
261
+ compactor: () => compactor.state().label,
262
+ gate: (T, signal) => compactor.gate(T, signal),
263
+ instructions: readInstructions,
264
+ holdReports: () => conclave.live(),
265
+ // One chat runs for the life of the process, so the briefing breaker is reset at each turn instead of at a session start.
266
+ memory: (turnCwd) => { mnemosia.newSession(); return memory.snapshot(turnCwd); },
267
+ selection: rootExtensions,
268
+ });
269
+ if (options.autostart !== false) {
270
+ compact.start();
271
+ loop.start();
272
+ }
273
+ return {
274
+ paths,
275
+ models,
276
+ harness,
277
+ root,
278
+ loop,
279
+ compactor,
280
+ guard,
281
+ conclave,
282
+ search,
283
+ skills,
284
+ memory,
285
+ memoryStatus: () => memory.status(),
286
+ akashic: (args) => memory.command(args, cwd),
287
+ settings: effective,
288
+ thinking,
289
+ integrity,
290
+ acceptIntegrity: () => recordIntegrity(options.home),
291
+ async reload(confirm) {
292
+ try {
293
+ // Both files are validated before either is applied. A file that no longer matches the hash piroboros
294
+ // recorded is shown to the user first; the new hash is recorded only after they confirm (F5).
295
+ const next = readSettings(options.home);
296
+ const checked = options.customProviders?.check();
297
+ if (checked?.ok === false)
298
+ return { ok: false, error: checked.error };
299
+ const changes = reloadChanges(options.home);
300
+ if (changes.tampered) {
301
+ const summary = describeIntegrity(changes);
302
+ if (!confirm || !(await confirm(summary)))
303
+ return { ok: false, declined: true, error: `config files changed outside piroboros, so nothing was reloaded:\n${summary}` };
304
+ }
305
+ const custom = options.customProviders?.reload();
306
+ if (custom?.ok === false)
307
+ return { ok: false, error: custom.error };
308
+ if (withDefaults(next).thinkingSteps !== withDefaults(settings).thinkingSteps)
309
+ thinking.clearSession();
310
+ settings = next;
311
+ if (changes.tampered)
312
+ recordIntegrity(options.home);
313
+ loop.wake();
314
+ const warnings = [...(custom?.ok && custom.warnings ? custom.warnings : []), ...(withDefaults(next).planning !== planningOn ? [PLANNING_NOTE] : [])];
315
+ return { ok: true, ...(warnings.length > 0 ? { warnings } : {}) };
316
+ }
317
+ catch (error) {
318
+ return { ok: false, error: reportMessage(error) };
319
+ }
320
+ },
321
+ updateSettings: update,
322
+ stored: () => settings,
323
+ setupEnv: () => ({ home: options.home, models, store, deviceId: deviceIdFor(options.home), existing: settings, env: options.env ?? process.env, ...(options.customProviders === undefined ? {} : { custom: options.customProviders }) }),
324
+ checkMain,
325
+ setMain(ref) {
326
+ const checked = checkMain(ref);
327
+ if (!checked.ok)
328
+ return checked;
329
+ const result = update({ set: { main: ref } });
330
+ return result.ok ? { ok: true } : result;
331
+ },
332
+ send: async (text) => {
333
+ try {
334
+ return await enqueueMessage(harness, text);
335
+ }
336
+ catch (error) {
337
+ // The call that hits a storage error rejects with the raw error while the session closes. Callers expect SessionFailed.
338
+ if (failed && !(error instanceof SessionFailed)) {
339
+ const end = await harness.closed;
340
+ if (end.reason === "failed")
341
+ throw new SessionFailed(end.error);
342
+ }
343
+ throw error;
344
+ }
345
+ },
346
+ telemetry: async () => (telemetry === undefined ? "telemetry is off; /settings telemetry turns it on at the next start" : telemetry.summary()),
347
+ fatal,
348
+ async close() {
349
+ // Every step runs even when an earlier one throws; the errors are reported together.
350
+ const errors = [];
351
+ const step = async (run) => {
352
+ try {
353
+ await run();
354
+ }
355
+ catch (error) {
356
+ errors.push(error);
357
+ }
358
+ };
359
+ await step(() => { unwatch(); clearInterval(idleTimer); idleTimer = undefined; });
360
+ await step(() => loop.stop());
361
+ await step(() => compact.stop());
362
+ await step(() => search.close());
363
+ await step(() => harness.close(ctx));
364
+ await step(() => telemetry?.close());
365
+ // Flush the briefing traces, then close the store. The tools can no longer run.
366
+ await step(() => mnemosia.close());
367
+ await step(() => memory.close());
368
+ if (errors.length === 1)
369
+ throw errors[0];
370
+ if (errors.length > 1)
371
+ throw new AggregateError(errors, "close failed in more than one step");
372
+ },
373
+ };
374
+ }
375
+ export function deviceIdFor(home) {
376
+ return () => getDeviceId(home);
377
+ }
378
+ export { compactorStatus, configure };
@@ -0,0 +1,102 @@
1
+ // Output formatting for find and grep, ported from @ff-labs/pi-fff 0.11.0 (MIT, by dmtrKovalenko; see NOTICE):
2
+ // file annotations, compact grep lines, the weak-match detector and the path-constraint normalizer. The
3
+ // rules are the same; the types are the structural subset piroboros uses. Native frecency order is kept:
4
+ // the source warns that re-sorting only confuses models.
5
+ // Definition-first: pi-fff asks the engine to classify definition lines (classifyDefinitions) and does no
6
+ // ordering of its own, so piroboros does the same and exposes the flag through the backend.
7
+ import { isAbsolute, relative, sep } from "node:path";
8
+ export const GREP_MAX_LINE_LENGTH = 500;
9
+ export const GREP_CONTEXT_MAX = 20;
10
+ export const FIND_WEAK_SAMPLE_SIZE = 5;
11
+ const HOT_FRECENCY = 25;
12
+ const WARM_FRECENCY = 20;
13
+ export function truncateLine(line, max = GREP_MAX_LINE_LENGTH) {
14
+ const trimmed = line.trim();
15
+ return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max)} [cut]`;
16
+ }
17
+ /** A non-negative whole number no larger than the cap, so a large value cannot multiply the output. */
18
+ export function clampContext(context) {
19
+ if (!context || context < 0)
20
+ return 0;
21
+ return Math.min(Math.floor(context), GREP_CONTEXT_MAX);
22
+ }
23
+ /** At most one tag per file. A file with uncommitted changes outranks a frequently used one. */
24
+ export function fileAnnotation(item) {
25
+ const git = item.gitStatus;
26
+ if (git && git !== "clean" && git !== "unknown" && git !== "")
27
+ return ` [${git} in git]`;
28
+ const frecency = item.totalFrecencyScore ?? item.accessFrecencyScore ?? 0;
29
+ if (frecency >= HOT_FRECENCY)
30
+ return " [VERY often touched file]";
31
+ if (frecency >= WARM_FRECENCY)
32
+ return " [often touched file]";
33
+ return "";
34
+ }
35
+ /** Matches grouped by file in the order the engine returned them; context lines use `-`, match lines use `:`. */
36
+ export function formatGrep(items) {
37
+ if (items.length === 0)
38
+ return "No matches found";
39
+ const lines = [];
40
+ let current = "";
41
+ for (const match of items) {
42
+ if (match.relativePath !== current) {
43
+ if (lines.length > 0)
44
+ lines.push("");
45
+ current = match.relativePath;
46
+ lines.push(`${current}${fileAnnotation(match)}`);
47
+ }
48
+ const before = match.contextBefore ?? [];
49
+ before.forEach((line, i) => lines.push(` ${match.lineNumber - before.length + i}- ${truncateLine(line)}`));
50
+ lines.push(` ${match.lineNumber}: ${truncateLine(match.lineContent)}`);
51
+ (match.contextAfter ?? []).forEach((line, i) => lines.push(` ${match.lineNumber + 1 + i}- ${truncateLine(line)}`));
52
+ }
53
+ return lines.join("\n");
54
+ }
55
+ /** A perfect match scores 12 per query character in the engine; under half of that is scattered fuzzy noise. */
56
+ export const weakScoreThreshold = (query) => Math.floor((query.length * 12 * 50) / 100);
57
+ /** Both backends skip what .gitignore lists, so an empty result must not read as "the file does not exist". */
58
+ export const NO_FILES_FOUND = "No files found. Paths ignored by .gitignore, such as node_modules, were not searched.";
59
+ /** A weak top score trims the list to a small sample instead of filling the context with noise. */
60
+ export function formatFind(items, topScore, limit, query) {
61
+ if (items.length === 0)
62
+ return { output: NO_FILES_FOUND, weak: false, shown: 0 };
63
+ const weak = topScore < weakScoreThreshold(query);
64
+ const shown = items.slice(0, weak ? Math.min(FIND_WEAK_SAMPLE_SIZE, limit) : limit);
65
+ return { output: shown.map((item) => `${item.relativePath}${fileAnnotation(item)}`).join("\n"), weak, shown: shown.length };
66
+ }
67
+ /** A pattern made only of wildcards matches every line. */
68
+ export const isWildcardOnly = (pattern) => /^(?:[.^$]*(?:[.][*+?]|\*|\+)[.^$]*|[.^$\s]*|\.\*\??|\.\*[+?]?|\.\+\??|\.|\*|\?)$/u.test(pattern.trim());
69
+ /**
70
+ * Turn a path or glob argument into the constraint syntax the fff query parser reads. A path inside the working
71
+ * directory becomes relative; one outside it is refused. Returns undefined for "the whole tree".
72
+ */
73
+ export function normalizeConstraint(value, cwd) {
74
+ let text = value.trim();
75
+ if (text === "")
76
+ return undefined;
77
+ if (isAbsolute(text)) {
78
+ const rel = relative(cwd, text).split(sep).join("/");
79
+ if (rel === "")
80
+ return undefined;
81
+ if (rel.startsWith("../") || rel === ".." || isAbsolute(rel))
82
+ throw new Error(`glob must stay inside the working directory: ${value}`);
83
+ text = rel;
84
+ }
85
+ if (text === "." || text === "./")
86
+ return undefined;
87
+ if (text.startsWith("./"))
88
+ text = text.slice(2);
89
+ if (text === "**" || text === "**/" || text === "**/*")
90
+ return undefined;
91
+ // a trailing recursive directory glob means "inside this directory"
92
+ const dir = /^(.*)\/\*\*(?:\/\*)?$/u.exec(text)?.[1];
93
+ if (dir && !/[*?[{]/u.test(dir))
94
+ return `${dir}/`;
95
+ if (text.startsWith("/") || text.endsWith("/"))
96
+ return text;
97
+ if (/[*?[{]/u.test(text))
98
+ return text;
99
+ if (/\.[a-zA-Z][a-zA-Z0-9]{0,9}$/u.test(text.split("/").pop() ?? ""))
100
+ return text;
101
+ return `${text}/`;
102
+ }