piroboros 0.1.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/NOTICE +12 -0
  3. package/README.md +91 -167
  4. package/dist/chat/compactor.js +5 -4
  5. package/dist/chat/log.js +3 -2
  6. package/dist/chat/plan.js +1 -0
  7. package/dist/chat/tree.js +1 -0
  8. package/dist/chat/turn.js +0 -15
  9. package/dist/conclave/pipeline.js +222 -19
  10. package/dist/config.js +127 -12
  11. package/dist/diff.js +90 -0
  12. package/dist/durable.js +69 -4
  13. package/dist/guard.js +170 -14
  14. package/dist/learn.js +938 -0
  15. package/dist/main.js +3 -9
  16. package/dist/memory/akashic/tools.js +25 -28
  17. package/dist/memory/mnemosia/conflicts.js +0 -4
  18. package/dist/memory/mnemosia/orchestrator.js +1 -11
  19. package/dist/memory/mnemosia/policy.js +0 -3
  20. package/dist/memory/mnemosia/rank.js +0 -4
  21. package/dist/memory/mnemosia/rerank.js +3 -30
  22. package/dist/memory/mnemosia/rollback.js +1 -149
  23. package/dist/memory/mnemosia/tokens.js +1 -11
  24. package/dist/memory/mnemosia/tools.js +0 -10
  25. package/dist/memory/mnemosia/types.js +0 -2
  26. package/dist/runtime.js +80 -11
  27. package/dist/search.js +25 -12
  28. package/dist/shell.js +2 -2
  29. package/dist/telemetry.js +84 -0
  30. package/dist/tui/app.js +17 -3
  31. package/dist/tui/commands.js +6 -2
  32. package/dist/tui/settings.js +4 -1
  33. package/dist/tui/thinking/parse.js +0 -3
  34. package/dist/ws/apply.js +817 -0
  35. package/dist/ws/cas.js +144 -0
  36. package/dist/ws/confine.js +194 -0
  37. package/dist/ws/docker.js +151 -0
  38. package/dist/ws/git.js +162 -0
  39. package/dist/ws/lww.js +48 -0
  40. package/dist/ws/merge.js +129 -0
  41. package/dist/ws/workspace.js +1596 -0
  42. package/dist/ws/wsl.js +259 -0
  43. package/docs/conclave.md +35 -0
  44. package/docs/configuration.md +54 -0
  45. package/docs/development.md +25 -0
  46. package/docs/interface.md +33 -0
  47. package/docs/memory.md +11 -0
  48. package/docs/privacy.md +15 -0
  49. package/docs/tools.md +62 -0
  50. package/docs/web.md +38 -0
  51. package/package.json +23 -10
  52. package/settings.json.example +4 -1
package/dist/runtime.js CHANGED
@@ -2,16 +2,23 @@ import { readFileSync } from "node:fs";
2
2
  import { FileCredentialStore } from "./auth.js";
3
3
  import { createBase } from "./base.js";
4
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, ROOT, SessionFailed } from "./durable.js";
5
+ import { configure, createRegistry, ctx, defineExtension, onSessionFailed, openHarness, parkedTasks, ROOT, SessionFailed } from "./durable.js";
6
+ import { openTelemetry } from "./telemetry.js";
6
7
  import { MemoryHost } from "./memory/host.js";
7
8
  import { createAkashicTool } from "./memory/akashic/tools.js";
8
9
  import { createMnemosiaTools } from "./memory/mnemosia/tools.js";
9
- import { checkRead, conversationsWithoutGuardFirst, createGuard } from "./guard.js";
10
+ import { checkAllowEntries, checkRead, conversationsWithoutGuardFirst, createGuard } from "./guard.js";
10
11
  import { createSearch } from "./search.js";
12
+ import { ConfinedShellEnv } from "./ws/confine.js";
13
+ import { findBash } from "./shell.js";
14
+ import { Workspaces } from "./ws/workspace.js";
15
+ import { isInside, canonicalize } from "./paths.js";
16
+ import { join } from "node:path";
11
17
  import { createSkills } from "./skills.js";
12
18
  import { contextCheck, createAppModels, resolveModel } from "./models.js";
13
19
  import { CompactLoop } from "./chat/compactloop.js";
14
20
  import { Compactor } from "./chat/compactor.js";
21
+ import { Learner, LearnLoop } from "./learn.js";
15
22
  import { budget, chat, createStuck, planning, viewtools } from "./chat/extension.js";
16
23
  import { checkMappingVersion } from "./chat/log.js";
17
24
  import { TurnLoop, enqueueMessage } from "./chat/turn.js";
@@ -24,9 +31,12 @@ import { ThinkingState } from "./tui/thinking/state.js";
24
31
  /** 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). */
25
32
  export const ROOT_IDLE_TIMEOUT_MS = 600_000;
26
33
  export const idleStopText = (ms) => `stopped (idle): no output for ${Math.round(ms / 1000)} s.`;
27
- function reportMessage(error) {
28
- return error instanceof Error ? error.message : String(error);
34
+ function reportMessage(error, info) {
35
+ const text = error instanceof Error ? error.message : String(error);
36
+ const source = info === undefined ? undefined : "task" in info && info.task !== undefined ? info.task.kind : "extension" in info ? info.extension : undefined;
37
+ return source === undefined ? text : `${source}: ${text}`;
29
38
  }
39
+ 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`;
30
40
  export async function openRuntime(options) {
31
41
  const paths = homePaths(options.home);
32
42
  // A storage error fails the whole session (pi-durable 1.2.0). Reports once the session is closing are noise.
@@ -50,11 +60,13 @@ export async function openRuntime(options) {
50
60
  const PLANNING_NOTE = "planning applies at the next start, because the tool list stays fixed while piroboros runs";
51
61
  // Throws on a refused or invalid write. `planningOn` and `loop` are set by the time a chat command calls this.
52
62
  const applySettings = (change) => {
53
- settings = "unset" in change ? unsetSettings(options.home, change.unset) : mergeSettings(options.home, change.set);
63
+ const profile = options.profile ?? profileDir();
64
+ settings = "unset" in change ? unsetSettings(options.home, change.unset, profile) : mergeSettings(options.home, change.set, profile);
54
65
  // A new global thinking-steps value replaces the session choice, so it shows at once.
55
66
  if ("unset" in change ? change.unset === "tui.thinkingSteps" : change.set.tui?.thinkingSteps !== undefined)
56
67
  thinking.clearSession();
57
68
  loop.wake();
69
+ learnLoop.wake();
58
70
  return withDefaults(settings).planning !== planningOn ? PLANNING_NOTE : undefined;
59
71
  };
60
72
  const checkMain = (ref) => {
@@ -75,18 +87,34 @@ export async function openRuntime(options) {
75
87
  return { ok: false, error: reportMessage(error) };
76
88
  }
77
89
  };
90
+ const allowWarned = new Set();
78
91
  const guardConfig = () => {
79
92
  const d = withDefaults(settings);
80
- return { home: options.home, profile: options.profile ?? profileDir(), deny: d.guardDeny, shellTimeoutMs: d.shellTimeoutMs, shellEnvAllow: d.shellEnvAllow };
93
+ return { home: options.home, profile: options.profile ?? profileDir(), deny: d.guardDeny, allow: d.guardAllow, warn: (message) => { if (!allowWarned.has(message)) {
94
+ allowWarned.add(message);
95
+ options.onStatus?.({ kind: "notice", message });
96
+ } }, shellTimeoutMs: d.shellTimeoutMs, shellEnvAllow: d.shellEnvAllow };
81
97
  };
98
+ const notice = (message) => options.onStatus?.({ kind: "notice", message });
99
+ const workspaces = new Workspaces({
100
+ home: options.home, guard: guardConfig, notice, ...options.workspace,
101
+ settings: () => { const w = withDefaults(settings).workspace; return { enabled: w.enabled, nested: w.nested, confine: w.confine, network: w.network, wslDistro: w.wsl?.distro, dockerImage: w.docker?.image }; },
102
+ });
82
103
  // F7: liveness comes from the pipeline task through the harness (isTaskLive). F3: the turn's origin is read from the turn state.
83
104
  const guard = createGuard({
84
105
  config: guardConfig,
106
+ workspace: { has: (c) => workspaces.has(c), after: (c, t, p, cwd) => workspaces.after(c, t, p, cwd), ceiling: (cwd) => workspaces.ceilingFor(cwd) },
85
107
  pipeline: options.pipeline ?? (() => conclave.pipelineState()),
86
108
  reportOnly: async () => (await harness.snapshot(TurnStateDoc, ctx))?.reportOnly === true,
87
109
  warn: (message) => options.onStatus?.({ kind: "notice", message }),
88
110
  });
89
- const search = createSearch({ home: options.home, guard: guardConfig, ...(options.search ?? {}) });
111
+ checkAllowEntries(guardConfig());
112
+ const search = createSearch({ home: options.home, guard: guardConfig, inWorkspace: (cwd) => { try {
113
+ return isInside(join(workspaces.wsRoot, workspaces.hash), canonicalize(cwd));
114
+ }
115
+ catch {
116
+ return false;
117
+ } }, ...(options.search ?? {}) });
90
118
  const base = createBase([...guard.tools(), ...search.tools]);
91
119
  // 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.
92
120
  // Under node --test without an explicit profile the real profile is never scanned (tests must not read the user's own skills).
@@ -101,7 +129,9 @@ export async function openRuntime(options) {
101
129
  const role = Object.entries(members).find(([, id]) => id === conversation)?.[0] ?? "root";
102
130
  // Vesperia's records wait for /akashic accept, like writes made in a report-only turn.
103
131
  const reportOnly = role === "vesperia" || (conversation === ROOT && (await api.snapshot(TurnStateDoc, ctx))?.reportOnly === true);
104
- return { role, cwd: (await api.agent(ctx)).cwd ?? cwd, reportOnly };
132
+ // A cwd (or explicit project) inside a Workspace folder is the live project it copies.
133
+ const there = (await api.agent(ctx)).cwd ?? cwd;
134
+ return { role, cwd: workspaces.projectOf(there) ?? there, reportOnly, project: (path) => workspaces.projectOf(path) ?? path };
105
135
  };
106
136
  const mnemosia = createMnemosiaTools(memory.foundations, caller);
107
137
  // Tools only, no hooks and no sections, so where it sits changes the order of the tool list and nothing else.
@@ -127,6 +157,8 @@ export async function openRuntime(options) {
127
157
  }
128
158
  };
129
159
  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 }) });
160
+ // The learner reads the chat and the skills, and writes memories as QUARANTINED; its task lives in the registry only.
161
+ const learner = new Learner({ home: options.home, cwd, settings: effective, models, compactor, memory, skills, notice: (message) => options.onStatus?.({ kind: "notice", message }), ...options.learn });
130
162
  const registry = createRegistry();
131
163
  // web_fetch lives in its own extension, which the root never selects. The tool also checks the caller's seat and web.enabled itself.
132
164
  const webKey = (provider) => searchKey(provider, paths.auth, options.env ?? process.env);
@@ -150,9 +182,10 @@ export async function openRuntime(options) {
150
182
  webKey,
151
183
  onNotice: (message) => options.onStatus?.({ kind: "notice", message }),
152
184
  onVesperia: (run) => { ensureRun(options.home, run); },
185
+ workspaces,
153
186
  });
154
187
  // The compactor and conclave extensions carry only their tasks, which any conversation's tasks resolve by name.
155
- for (const extension of [guard.extension, base, viewtools, planning, memoryExtension, webExtension, stuck, chat, skills.extension, budget, compactor.extension, conclave.extension])
188
+ for (const extension of [guard.extension, base, viewtools, planning, memoryExtension, webExtension, stuck, chat, skills.extension, budget, compactor.extension, learner.extension, conclave.extension])
156
189
  registry.install(extension);
157
190
  // D12: the root selects the chat extensions explicitly, and the budget extension is last everywhere. The plan
158
191
  // tool is part of the selection unless settings.planning is false; that is read at start, so the tool list
@@ -161,18 +194,36 @@ export async function openRuntime(options) {
161
194
  // The skills section is the last static section: after chat, before budget. It renders nothing without skills.
162
195
  const planningOn = withDefaults(settings).planning;
163
196
  const rootExtensions = [guard.extension, base, viewtools, ...(planningOn ? [planning] : []), memoryExtension, stuck, chat, skills.extension, budget];
197
+ // Merge records a crash left are rolled back or finished before the scheduler can replay any run (the home lock is held).
198
+ for (const line of await workspaces.recover().catch((error) => [`workspace recovery: ${reportMessage(error)}`]))
199
+ notice(line);
200
+ // A failure to open the store turns telemetry off, visibly; the run goes on without it.
201
+ let telemetry;
202
+ if (withDefaults(settings).telemetry) {
203
+ try {
204
+ telemetry = await openTelemetry(paths.telemetry);
205
+ }
206
+ catch (error) {
207
+ report(`telemetry off: ${reportMessage(error)}`);
208
+ }
209
+ }
164
210
  const harness = await openHarness({
165
211
  path: options.persistent === false ? undefined : paths.chat,
166
212
  storage: options.storage,
213
+ telemetry: telemetry?.recorder,
167
214
  models,
215
+ identity: { attribution: null },
168
216
  registry,
169
217
  settings: {
170
218
  extensions: [guard.extension, base, viewtools, budget], steeringMode: "all", followUpMode: "all", compaction: { enabled: false, backgroundTokens: 0 },
171
219
  // A getter: pi-durable reads it at every request, so /reload applies a changed cacheRetention at the next turn.
172
220
  get stream() { return { cacheRetention: withDefaults(effective()).cacheRetention }; },
173
221
  },
174
- onReport: (error) => report(reportMessage(error)),
175
- }).catch((error) => {
222
+ env: (cwd) => new ConfinedShellEnv({ cwd: cwd ?? process.cwd(), shellPath: findBash() }, (c) => workspaces.shellFor(c)),
223
+ onReport: (error, info) => { if (info.type !== "task_parked")
224
+ report(reportMessage(error, info)); },
225
+ }).catch(async (error) => {
226
+ await telemetry?.close().catch(() => undefined);
176
227
  memory.close();
177
228
  throw error;
178
229
  });
@@ -202,9 +253,11 @@ export async function openRuntime(options) {
202
253
  }
203
254
  catch (error) {
204
255
  await harness.close(ctx);
256
+ await telemetry?.close().catch(() => undefined);
205
257
  memory.close();
206
258
  throw error;
207
259
  }
260
+ learner.bind(harness, root);
208
261
  harness.resume();
209
262
  // Root idle watchdog: a MemberWatch fed by the root's commits. Its timer runs only while a run is in progress.
210
263
  const idleMs = options.rootIdleTimeoutMs ?? ROOT_IDLE_TIMEOUT_MS;
@@ -225,7 +278,15 @@ export async function openRuntime(options) {
225
278
  });
226
279
  // pi-durable resumes a live pipeline by itself. Say so, and forget one that ended while piroboros was closed.
227
280
  await conclave.recover().catch((error) => report(reportMessage(error)));
281
+ const parked = await parkedTasks(harness);
282
+ // Workspace state rules: an `open` Workspace of an ended or parked task is held, and a parked task of a finished Workspace is ended.
283
+ const wsStart = await workspaces.startup(parked.filter((t) => t.kind === "piroboros.conclave").map((t) => String(t.id))).catch((error) => { report(reportMessage(error)); return { abort: [] }; });
284
+ for (const id of wsStart.abort)
285
+ await harness.abortTask((/^\d+$/u.test(id) ? Number(id) : id), ctx).catch(() => undefined);
286
+ if (parked.length > 0)
287
+ options.onStatus?.({ kind: "notice", message: pausedText(parked.length) });
228
288
  const compact = new CompactLoop({ harness, root, compactor, onAlarm: (text) => report(`alarm: ${text}`), onReport: (error) => report(reportMessage(error)) });
289
+ const learnLoop = new LearnLoop({ harness, learner, onReport: (error) => report(reportMessage(error)) });
229
290
  const loop = new TurnLoop({
230
291
  harness,
231
292
  root,
@@ -246,6 +307,7 @@ export async function openRuntime(options) {
246
307
  });
247
308
  if (options.autostart !== false) {
248
309
  compact.start();
310
+ learnLoop.start();
249
311
  loop.start();
250
312
  }
251
313
  return {
@@ -255,7 +317,9 @@ export async function openRuntime(options) {
255
317
  root,
256
318
  loop,
257
319
  compactor,
320
+ learner,
258
321
  guard,
322
+ workspaces,
259
323
  conclave,
260
324
  search,
261
325
  skills,
@@ -289,6 +353,7 @@ export async function openRuntime(options) {
289
353
  if (changes.tampered)
290
354
  recordIntegrity(options.home);
291
355
  loop.wake();
356
+ learnLoop.wake();
292
357
  const warnings = [...(custom?.ok && custom.warnings ? custom.warnings : []), ...(withDefaults(next).planning !== planningOn ? [PLANNING_NOTE] : [])];
293
358
  return { ok: true, ...(warnings.length > 0 ? { warnings } : {}) };
294
359
  }
@@ -321,6 +386,7 @@ export async function openRuntime(options) {
321
386
  throw error;
322
387
  }
323
388
  },
389
+ telemetry: async () => (telemetry === undefined ? "telemetry is off; /settings telemetry turns it on at the next start" : telemetry.summary()),
324
390
  fatal,
325
391
  async close() {
326
392
  // Every step runs even when an earlier one throws; the errors are reported together.
@@ -336,8 +402,11 @@ export async function openRuntime(options) {
336
402
  await step(() => { unwatch(); clearInterval(idleTimer); idleTimer = undefined; });
337
403
  await step(() => loop.stop());
338
404
  await step(() => compact.stop());
405
+ await step(() => learnLoop.stop());
339
406
  await step(() => search.close());
340
407
  await step(() => harness.close(ctx));
408
+ await step(() => workspaces.close());
409
+ await step(() => telemetry?.close());
341
410
  // Flush the briefing traces, then close the store. The tools can no longer run.
342
411
  await step(() => mnemosia.close());
343
412
  await step(() => memory.close());
package/dist/search.js CHANGED
@@ -81,21 +81,31 @@ export async function probeSearch(options = {}) {
81
81
  export function createSearch(deps) {
82
82
  const rg = deps.rg ?? "rg";
83
83
  let fffPromise;
84
- let holder;
84
+ // Two indexes, least recently used first: the root's and Vesperia's Workspace, so alternating searches build each once.
85
+ let holders = [];
85
86
  let creating = Promise.resolve();
86
87
  const loadFff = () => (fffPromise ??= (deps.loadFff ?? (() => import("@ff-labs/fff-node")))());
87
88
  const allowed = (path, cwd) => checkPath(path, cwd, deps.guard()).allowed;
89
+ // Ignore files above a Workspace (and the global one) never describe the project, whose own rules already decided what was copied.
90
+ const wsFlags = (cwd) => (deps.inWorkspace?.(cwd) ? ["--no-ignore-parent", "--no-ignore-global"] : []);
91
+ const drop = (h) => { if (!h.finder.isDestroyed)
92
+ h.finder.destroy(); };
88
93
  const destroy = () => {
89
- if (holder !== undefined && !holder.finder.isDestroyed)
90
- holder.finder.destroy();
91
- holder = undefined;
94
+ for (const h of holders)
95
+ drop(h);
96
+ holders = [];
92
97
  };
93
- /** One index per working directory; a different directory replaces it. Creation is serialized. */
98
+ /** One index per working directory, at most two; the least recently used goes when a third is needed. Creation is serialized. */
94
99
  const finderFor = (cwd) => {
95
100
  const next = creating.then(async () => {
96
- if (holder !== undefined && holder.cwd === cwd && !holder.finder.isDestroyed)
97
- return holder;
98
- destroy();
101
+ const hit = holders.find((h) => h.cwd === cwd && !h.finder.isDestroyed);
102
+ if (hit !== undefined) {
103
+ holders = [...holders.filter((h) => h !== hit), hit];
104
+ return hit;
105
+ }
106
+ holders = holders.filter((h) => !h.finder.isDestroyed);
107
+ while (holders.length >= 2)
108
+ drop(holders.shift());
99
109
  const fff = await loadFff();
100
110
  const base = { basePath: cwd, aiMode: true, enableHomeDirScanning: false, enableFsRootScanning: false };
101
111
  mkdirSync(join(deps.home, "fff"), { recursive: true });
@@ -110,7 +120,10 @@ export function createSearch(deps) {
110
120
  made.value.destroy();
111
121
  throw new Error(waited.error);
112
122
  }
113
- return (holder = { cwd, finder: made.value, cursors: new Map() });
123
+ deps.holderBuilt?.(cwd);
124
+ const built = { cwd, finder: made.value, cursors: new Map() };
125
+ holders.push(built);
126
+ return built;
114
127
  });
115
128
  creating = next.catch(() => undefined);
116
129
  return next;
@@ -146,7 +159,7 @@ export function createSearch(deps) {
146
159
  return { text: notes.length > 0 ? `${formatted.output}\n\n[${notes.join(". ")}]` : formatted.output, backend: "fff", total: totalMatched, page };
147
160
  }
148
161
  async function findRg(cwd, query, constraint, page, reason) {
149
- const argv = ["--no-config", "--no-messages", "--no-require-git", "--files", "--sort", "path", "--glob", "!.git", ...(constraint === undefined ? [] : ["--glob", rgGlob(constraint)]), "--", "."];
162
+ const argv = ["--no-config", "--no-messages", "--no-require-git", ...wsFlags(cwd), "--files", "--sort", "path", "--glob", "!.git", ...(constraint === undefined ? [] : ["--glob", rgGlob(constraint)]), "--", "."];
150
163
  const words = query.toLowerCase().split(/\s+/u).filter((word) => word !== "");
151
164
  const hits = [];
152
165
  let run;
@@ -217,7 +230,7 @@ export function createSearch(deps) {
217
230
  }
218
231
  async function grepRg(cwd, a, reason) {
219
232
  const argv = [
220
- "--no-config", "--no-messages", "--no-require-git", "--json", "--smart-case", "--max-count", "200", "--max-filesize", "1M", "--glob", "!.git",
233
+ "--no-config", "--no-messages", "--no-require-git", ...wsFlags(cwd), "--json", "--smart-case", "--max-count", "200", "--max-filesize", "1M", "--glob", "!.git",
221
234
  ...(a.constraint === undefined ? [] : ["--glob", rgGlob(a.constraint)]),
222
235
  ...(a.context > 0 ? ["-C", String(a.context)] : []),
223
236
  ...(a.mode === "regex" ? [] : ["--fixed-strings"]),
@@ -345,7 +358,7 @@ export function createSearch(deps) {
345
358
  return {
346
359
  tools: [findTool, grepTool],
347
360
  close: destroy,
348
- indexCwd: () => holder?.cwd,
361
+ indexCwd: () => holders[holders.length - 1]?.cwd,
349
362
  status: () => probeSearch({ rg, loadFff: deps.loadFff }),
350
363
  };
351
364
  }
package/dist/shell.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { delimiter, join } from "node:path";
3
- // The shell is bash on every platform. On Windows that is Git Bash. The WSL launcher in System32 is never used.
3
+ // The shell is bash on every platform. On Windows that is Git Bash. The WSL launchers (System32, Sysnative and the WindowsApps alias) are never used.
4
4
  export const BASH_HINT = "Install Git for Windows (https://git-scm.com/download/win), which includes Git Bash. On Linux and macOS install bash from your package manager.";
5
- const isWslLauncher = (path) => /[\\/](?:system32|sysnative)[\\/]bash\.exe$/iu.test(path);
5
+ export const isWslLauncher = (path) => /[\\/](?:system32|sysnative|microsoft[\\/]windowsapps)[\\/]bash\.exe$/iu.test(path);
6
6
  /** The bash executable to run commands with, or undefined when none is installed. */
7
7
  export function findBash(env = process.env, platform = process.platform) {
8
8
  if (platform !== "win32")
@@ -0,0 +1,84 @@
1
+ import { openNodeSqliteDatabase } from "@earendil-works/chord/sqlite/node";
2
+ import { createSqliteTelemetry } from "@earendil-works/chord/telemetry-sqlite";
3
+ /**
4
+ * ponytail: error text (status.error.message of a span: a provider's reply, a thrown fault) can echo prompt text or
5
+ * paths, so a connection-local TEMP trigger removes it from every inserted span; the error name stays. secure_delete
6
+ * keeps the removed text out of the WAL. If upstream moves error text to another column this misses it: rerun the
7
+ * canary probe on every pi-durable, chord or pi-ai upgrade.
8
+ */
9
+ const DROP_ERROR_TEXT = `PRAGMA secure_delete = ON;
10
+ CREATE TEMP TRIGGER drop_error_text AFTER INSERT ON main.telemetry_spans
11
+ WHEN json_extract(NEW.status, '$.error.message') IS NOT NULL
12
+ BEGIN UPDATE telemetry_spans SET status = json_remove(NEW.status, '$.error.message') WHERE id = NEW.id; END;`;
13
+ export async function openTelemetry(path) {
14
+ const db = await openNodeSqliteDatabase(path);
15
+ let recorder;
16
+ try {
17
+ recorder = await createSqliteTelemetry(db);
18
+ await db.exec(DROP_ERROR_TEXT);
19
+ }
20
+ catch (error) {
21
+ await recorder?.close().catch(() => undefined);
22
+ await db.close().catch(() => undefined);
23
+ throw error;
24
+ }
25
+ const rec = recorder;
26
+ return {
27
+ recorder: rec,
28
+ async summary(now = Date.now()) {
29
+ let head = "";
30
+ try {
31
+ await rec.flush();
32
+ }
33
+ catch (error) {
34
+ head = `telemetry recording stopped: ${error instanceof Error ? error.message : String(error)} (the numbers below are up to then)\n`;
35
+ }
36
+ const startMin = now - 86_400_000;
37
+ const [duration, tokens, cost] = await Promise.all(["pi.ai.request.duration", "pi.ai.tokens", "pi.ai.cost"].map((name) => rec.findMetrics({ name, startMin })));
38
+ const rows = new Map();
39
+ const row = (m) => {
40
+ const key = `${m.attributes.provider}/${m.attributes.model}`;
41
+ if (!rows.has(key))
42
+ rows.set(key, { n: 0, failed: 0, ms: 0, input: 0, output: 0, cost: 0 });
43
+ return rows.get(key);
44
+ };
45
+ for (const m of duration) {
46
+ const r = row(m);
47
+ r.n += m.count;
48
+ r.ms += m.sum;
49
+ if (m.attributes.stop === "error")
50
+ r.failed += m.count;
51
+ }
52
+ for (const m of tokens) {
53
+ const r = row(m);
54
+ if (m.attributes.kind === "input")
55
+ r.input += m.sum;
56
+ else if (m.attributes.kind === "output")
57
+ r.output += m.sum;
58
+ }
59
+ for (const m of cost)
60
+ row(m).cost += m.sum;
61
+ const lines = [...rows].filter(([, r]) => r.n > 0).map(([model, r]) => `${model}: ${r.n} requests, ${r.failed} failed, ${(r.ms / r.n / 1000).toFixed(1)} s average, ${r.input} in / ${r.output} out tokens, $${r.cost.toFixed(4)}`);
62
+ return `${head}${lines.length === 0 ? "no model requests recorded in the last 24 hours" : `model requests, last 24 hours (the last 10 seconds may not show yet)\n${lines.join("\n")}`}`;
63
+ },
64
+ async close() {
65
+ const errors = [];
66
+ try {
67
+ await rec.close();
68
+ }
69
+ catch (error) {
70
+ errors.push(error);
71
+ }
72
+ try {
73
+ await db.close();
74
+ }
75
+ catch (error) {
76
+ errors.push(error);
77
+ }
78
+ if (errors.length === 1)
79
+ throw errors[0];
80
+ if (errors.length > 1)
81
+ throw new AggregateError(errors, "telemetry close failed in more than one step");
82
+ },
83
+ };
84
+ }
package/dist/tui/app.js CHANGED
@@ -416,8 +416,12 @@ export function missingKeyCheck(authPath, env = process.env) {
416
416
  }
417
417
  /** /conclave undo: list what it would do, ask, then restore the pre-images of the last Vesperia run. */
418
418
  async function undoCommand(rt, ask) {
419
- if (await rt.conclave.live())
420
- return "undo not run: a pipeline is running; /conclave cancel stops it";
419
+ const blocked = await rt.conclave.undoBlocked();
420
+ if (blocked !== undefined)
421
+ return blocked;
422
+ const workspace = await rt.conclave.undoWorkspace(ask);
423
+ if (workspace !== undefined)
424
+ return workspace;
421
425
  const home = rt.guard.config().home;
422
426
  const folder = loadRun(home);
423
427
  if (folder === undefined)
@@ -498,13 +502,23 @@ export function runCommand(rt, text, ask, flow) {
498
502
  return rt.conclave.status();
499
503
  if (sub === "undo")
500
504
  return ask === undefined ? "undo not run: this needs a confirmation, which only the chat screen can ask" : undoCommand(rt, ask);
501
- const started = sub === "approve" ? rt.conclave.approve() : rt.conclave.start(text.slice("/conclave".length));
505
+ if (sub === "merge")
506
+ return rt.conclave.merge(ask);
507
+ if (sub === "discard")
508
+ return rt.conclave.discard(ask);
509
+ if (sub === "retry")
510
+ return rt.conclave.retry();
511
+ const started = sub === "approve" ? rt.conclave.approve(ask) : rt.conclave.start(text.slice("/conclave".length));
502
512
  return started.then((result) => (result.ok ? result.message : `not started: ${result.error}`));
503
513
  }
514
+ if (name === "telemetry")
515
+ return rt.telemetry();
504
516
  if (name === "skills")
505
517
  return skillsReport(rt.skills.state(), COMMANDS.map((command) => command.name));
506
518
  if (name === "akashic")
507
519
  return rt.akashic(rest.join(" "));
520
+ if (name === "learn")
521
+ return rt.learner.command(rest.filter((word) => word !== ""), ask);
508
522
  if (name === "thinking-steps")
509
523
  return thinkingStepsCommand(rt, rest);
510
524
  return undefined;
@@ -7,10 +7,12 @@ export const COMMANDS = [
7
7
  { name: "login", description: "sign in to a provider", args: "[provider]" },
8
8
  { name: "settings", description: "show or change a setting", args: "[key]" },
9
9
  { name: "status", description: "show the chat and compactor status" },
10
- { name: "conclave", description: "run the review pipeline on a task", args: "<task> | approve | cancel | status | undo" },
10
+ { name: "conclave", description: "run the review pipeline on a task", args: "<task> | approve | cancel | status | undo | merge | discard | retry" },
11
11
  { name: "akashic", description: "memory status, accept and vault", args: "[status | accept | vault ...]" },
12
12
  { name: "thinking-steps", description: "choose how thinking steps are shown", args: "[mode | global <mode | clear>]" },
13
13
  { name: "skills", description: "list the skills the chat can use" },
14
+ { name: "learn", description: "the learning loop: status, proposals, undo", args: "[now | accept <name> | reject <name|all> | undo <name> | retry | skip]" },
15
+ { name: "telemetry", description: "model requests, latency and cost of the last 24 hours" },
14
16
  ];
15
17
  /** The skills that are commands: a name that starts with a letter, and no built-in command of the same name (that one wins). */
16
18
  const commandSkills = (skills) => skills.filter((skill) => /^[a-z]/u.test(skill.name) && !COMMANDS.some((command) => command.name === skill.name));
@@ -92,12 +94,14 @@ export function suggest(value, models = [], logins = [], skills = []) {
92
94
  return models.filter((model) => model.ref.toLowerCase().includes(needle)).map((model) => ({ complete: `/model ${model.ref}`, label: model.ref, ...(model.disabled === undefined ? {} : { disabled: model.disabled }) }));
93
95
  }
94
96
  if (name === "conclave")
95
- return tokens.length > 1 ? [] : words(lead, last, ["approve", "cancel", "status", "undo"]);
97
+ return tokens.length > 1 ? [] : words(lead, last, ["approve", "cancel", "status", "undo", "merge", "discard", "retry"]);
96
98
  if (name === "thinking-steps") {
97
99
  if (tokens.length === 1)
98
100
  return words(lead, last, [...MODES, "global"], ["global"]);
99
101
  return tokens.length === 2 && tokens[0] === "global" ? words(lead, last, [...MODES, "clear"]) : [];
100
102
  }
103
+ if (name === "learn")
104
+ return tokens.length > 1 ? [] : words(lead, last, ["now", "accept", "reject", "undo", "retry", "skip"]);
101
105
  if (name === "akashic") {
102
106
  if (tokens.length === 1)
103
107
  return words(lead, last, ["status", "accept", "vault"], ["vault"]);
@@ -13,7 +13,10 @@ const APPLIES = {
13
13
  run: "applies at the next Conclave run",
14
14
  start: "applies at the next start",
15
15
  };
16
+ // An allowed pi extensions folder is code that pi runs with your credentials.
17
+ const ALLOW_WARNING = "An allowed folder inside the pi extensions folder holds code that pi runs with your credentials: review edits and merges there like code you install, and merge while pi is not running (or reload pi after).";
16
18
  const FIELD_HELP = {
19
+ "guard.allow": " A project folder opened inside a protected location, at or inside the pi extensions folder or strictly inside a guard.deny root. Credential file names stay refused inside it.",
17
20
  cacheRetention: ' "short" keeps the prompt cache for about 5 minutes. "long" keeps it for an hour and costs more per cache write, so it pays off when you pause longer than 5 minutes between turns.',
18
21
  };
19
22
  const ENTRY_HELP = { env: "an environment variable name such as GIT_SSH_COMMAND", host: 'a lower case host name such as "docs.example.org"', path: "an absolute path" };
@@ -186,7 +189,7 @@ async function commit(rt, io, f, change) {
186
189
  throw error;
187
190
  }
188
191
  if (lines.length > 0) {
189
- io.notify("warn", lines.join("\n"));
192
+ io.notify("warn", (f.path === "guard.allow" ? [...lines, ALLOW_WARNING] : lines).join("\n"));
190
193
  if (!(await io.confirm(SECURITY_CONFIRM, false)))
191
194
  return `${f.path} not changed`;
192
195
  }
@@ -939,9 +939,6 @@ function summarizeThinkingTextDetailed(text, fallback = "Reasoning is hidden by
939
939
  hasExplicitSuccess: visibleMetadata.hasExplicitSuccess,
940
940
  };
941
941
  }
942
- export function summarizeThinkingText(text, fallback = "Reasoning is hidden by the provider.") {
943
- return summarizeThinkingTextDetailed(text, fallback).summary;
944
- }
945
942
  export function inferThinkingRole(text) {
946
943
  const haystack = ` ${normalizeNewlines(text).toLowerCase()} `;
947
944
  const referenceOnlyFailureCue = FAILURE_REFERENCE_CONTEXT_RE.test(haystack)