pi-braid 0.43.37 → 0.43.39

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.
package/docs/SETUP.md CHANGED
@@ -292,7 +292,7 @@ braid reads configuration from the standard pi locations, with a dedicated `brai
292
292
  ~/.pi/agent/braid/projects/<project>/module-overrides.json # braid-owned module toggles
293
293
  ```
294
294
 
295
- The user-global file always exists; the project one is optional and belongs to pi (braid neither creates it nor writes it, and does not read its `braid.modules` block: pi applies that file only for a trusted project, and braid cannot ask pi that while extensions load). `braid.modules` is read from two sources, later source wins per key: the user-global file and braid's own `module-overrides.json` store, which is where `/modules-toggle` and friends persist. Every other `braid.*` reader reads the user-global file only. Copy-ready examples live in the repo's [`examples/`](../../../examples) directory.
295
+ The user-global file always exists; the project one is optional and belongs to pi (braid neither creates it nor writes it, and does not read its `braid.modules` block: pi applies that file only for a trusted project, and braid cannot ask pi that while extensions load). `braid.modules` is read from two sources, later source wins per key: the user-global file and braid's own `module-overrides.json` store, which is where the `/modules` toggle verbs persist. Every other `braid.*` reader reads the user-global file only. Copy-ready examples live in the repo's [`examples/`](../../../examples) directory.
296
296
 
297
297
  ### Schema
298
298
 
@@ -378,11 +378,26 @@ First match wins - a match is the profile `cwd` itself or any directory under it
378
378
 
379
379
  braid's loader follows a four-tier precedence (high → low):
380
380
 
381
- 1. **Runtime API** - `/modules-toggle`, `/modules-enable`, `/modules-disable` (in-session)
382
- 2. **Settings** - `braid.modules`, later source wins per id: `~/.pi/agent/settings.json`, then braid's own `~/.pi/agent/braid/projects/<project>/module-overrides.json`, where the toggle commands persist. A project-scoped `<cwd>/.pi/settings.json` stays pi's file: pi applies it only for a project it trusts, and braid cannot ask pi that while extensions load, so braid does not read it.
381
+ 1. **Runtime API** - `/modules` verbs `on`, `off`, `toggle`, `reset`, `all on|off` (in-session)
382
+ 2. **Settings** - `braid.modules`, later source wins per id: `~/.pi/agent/settings.json`, then braid's own `~/.pi/agent/braid/projects/<project>/module-overrides.json`, where the toggle verbs persist. A project-scoped `<cwd>/.pi/settings.json` stays pi's file: pi applies it only for a project it trusts, and braid cannot ask pi that while extensions load, so braid does not read it.
383
383
  3. **Env var** - `BRAID_MODULES=...`
384
384
  4. **Defaults** - all extensions whose manifest does not have `disabledByDefault: true`
385
385
 
386
+ ### In-session commands
387
+
388
+ `/modules` takes a verb as its first argument; with no argument it opens a list of every extension in the TUI and prints the same rows as text in RPC mode.
389
+
390
+ | Command | Effect |
391
+ | ------------------------- | -------------------------------------------------------------------- |
392
+ | `/modules on <ref>` | Enable an extension id or module group |
393
+ | `/modules off <ref>` | Disable an extension id or module group |
394
+ | `/modules toggle <ref>` | Flip the effective state |
395
+ | `/modules all on` / `off` | Apply to every extension in the manifest |
396
+ | `/modules list` | Print every extension, its description and where its state came from |
397
+ | `/modules reset` | Clear in-process overrides (persisted `braid.modules` stays) |
398
+
399
+ The six former names (`/modules-enable`, `/modules-disable`, `/modules-toggle`, `/modules-reset`, `/modules-list`, `/modules-status`) forward to the equivalent verb for one release.
400
+
386
401
  ### `BRAID_MODULES` syntax
387
402
 
388
403
  ```bash
@@ -496,7 +511,7 @@ ls node_modules/@earendil-works/ 2>/dev/null
496
511
 
497
512
  ### Disabling and restarts
498
513
 
499
- The in-session `/modules-disable` persists the choice to braid's own `braid.modules` store (`~/.pi/agent/braid/projects/<project>/module-overrides.json`); the change takes effect at the next session start (already-loaded extensions keep running). A persisted `false` entry removes a default-enabled extension at boot, so the choice survives restarts. The equivalent env-var route is `export BRAID_MODULES="-<id>"` (module values are real JSON booleans - `false`, not `0` or `"off"`).
514
+ The in-session `/modules off <ref>` persists the choice to braid's own `braid.modules` store (`~/.pi/agent/braid/projects/<project>/module-overrides.json`); the change takes effect at the next session start (already-loaded extensions keep running). A persisted `false` entry removes a default-enabled extension at boot, so the choice survives restarts. The equivalent env-var route is `export BRAID_MODULES="-<id>"` (module values are real JSON booleans - `false`, not `0` or `"off"`).
500
515
 
501
516
  ---
502
517
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.43.37",
3
+ "version": "0.43.39",
4
4
  "description": "🥨 Braid - Metacognitive extension suite for pi coding agent: Adds memory, plan tracking, structured cognitive signals and completion checks on top of pi core loop, so long sessions keep their context and stop claiming unfinished work.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * Three concerns:
5
5
  * 1. Model selection: /utility-model (the merged role) opens the
6
- * ModelSelectorComponent UI. Model resolution is handled by
6
+ * ModelSelectorComponent UI in the TUI and prints the current setting as
7
+ * text elsewhere. Model resolution is handled by
7
8
  * src/lib/ai/model-resolver.ts (used by vision/metacognition tools
8
9
  * directly).
9
10
  * 2. Session manager patches: context_navigate and context_compress tools
@@ -28,7 +29,8 @@ import type {
28
29
  ExtensionCommandContext,
29
30
  ModelRuntime,
30
31
  } from "@earendil-works/pi-coding-agent";
31
- import { ModelSelectorComponent, SettingsManager } from "@earendil-works/pi-coding-agent";
32
+ import { ModelSelectorComponent } from "@earendil-works/pi-coding-agent";
33
+ import type { AutocompleteItem } from "@earendil-works/pi-tui";
32
34
  import type { Model, Api } from "@earendil-works/pi-ai";
33
35
  import { resolveUtilityModel, normaliseRoleSetting } from "../../../lib/ai/model-resolver.js";
34
36
  import {
@@ -43,6 +45,32 @@ import { createLogger } from "../../../lib/core/logger.js";
43
45
 
44
46
  const log = createLogger("polyfill");
45
47
 
48
+ /**
49
+ * The last context a run or a command handed the extension. Argument
50
+ * completion receives only the typed prefix - no ctx - so the model list it
51
+ * offers comes from here. Captured on session start and before each run, the
52
+ * points where the registry is bound.
53
+ */
54
+ let completionCtx: ExtensionContext | undefined;
55
+
56
+ /** Complete /utility-model's argument: the clear verb and the available
57
+ * catalogue as provider/model patterns. Only models the registry reports as
58
+ * available are named, so a completion cannot suggest a model the resolver
59
+ * would then refuse. */
60
+ function completeUtilityModel(prefix: string): AutocompleteItem[] | null {
61
+ const typed = (prefix ?? "").toLowerCase();
62
+ const items: AutocompleteItem[] = [];
63
+ if ("clear".startsWith(typed)) {
64
+ items.push({ value: "clear", label: "clear", description: "Use the session model" });
65
+ }
66
+ for (const model of completionCtx?.modelRegistry.getAvailable() ?? []) {
67
+ const value = `${model.provider}/${model.id}`;
68
+ if (!value.toLowerCase().startsWith(typed)) continue;
69
+ items.push({ value, label: value, description: "Set the utility model" });
70
+ }
71
+ return items.length > 0 ? items : null;
72
+ }
73
+
46
74
  /** Custom settings keys managed by the model commands */
47
75
  import {
48
76
  getCustomModelKey,
@@ -143,8 +171,9 @@ async function setRoleSettingFromArgs(
143
171
  * vision analysis falls back to, so there is no separate vision command.
144
172
  */
145
173
  async function runUtilityModelCommand(args: string, ctx: ExtensionCommandContext): Promise<void> {
174
+ completionCtx = ctx;
146
175
  if (!args || args.trim() === "") {
147
- if (ctx.hasUI) {
176
+ if (ctx.mode === "tui" && ctx.hasUI) {
148
177
  await openModelSelectorUI(ctx, UTILITY_MODEL_KEY, "Utility", resolveUtilityModel);
149
178
  } else {
150
179
  const model = resolveUtilityModel(ctx);
@@ -238,6 +267,7 @@ export default function polyfillExtension(pi: ExtensionAPI) {
238
267
  // here makes display and enforcement agree before the first run, not only
239
268
  // at the next agent turn. No-op when the setting is unset.
240
269
  pi.on(SESSION_START, (_event, ctx) => {
270
+ completionCtx = ctx;
241
271
  applyConfiguredContextWindow(ctx);
242
272
  // Pair the window with the reserve it implies: pi-core decides WHEN to
243
273
  // compact from its own `compaction.reserveTokens` (a fixed token count),
@@ -260,6 +290,7 @@ export default function polyfillExtension(pi: ExtensionAPI) {
260
290
 
261
291
  // Patch session manager methods on before_agent_start (fires for --no-session mode)
262
292
  pi.on("before_agent_start", async (_event, ctx) => {
293
+ completionCtx = ctx;
263
294
  patchSessionManagerMethods(pi, ctx);
264
295
 
265
296
  // Re-apply the configured window per run so a mid-session model switch
@@ -291,9 +322,10 @@ export default function polyfillExtension(pi: ExtensionAPI) {
291
322
  "Set or show the utility model for classification tasks. " +
292
323
  "Accepts one model or an ordered list (comma-separated), tried in order " +
293
324
  "until the provider layer reports a route usable. " +
294
- "No args = show current setting. Smaller/faster models preferred. " +
295
- "Examples: /utility-model provider/model-id, /utility-model a/b,c/d, " +
296
- "/utility-model clear",
325
+ "No args shows the current setting (the TUI opens the selector). " +
326
+ "Smaller/faster models preferred. Examples: /utility-model provider/model-id, " +
327
+ "/utility-model a/b,c/d, /utility-model clear",
328
+ getArgumentCompletions: completeUtilityModel,
297
329
  handler: (args, ctx) => runUtilityModelCommand(args, ctx),
298
330
  });
299
331
  }
@@ -335,13 +367,12 @@ function resolveModelPattern(
335
367
  /**
336
368
  * Open ModelSelectorComponent via ctx.ui.custom() for model selection.
337
369
  *
338
- * Approach:
339
- * - Use SettingsManager.inMemory() for ModelSelectorComponent (its
340
- * setDefaultModelAndProvider is a no-op for disk persistence - that's fine
341
- * since we call pi.setModel() afterwards which goes through AgentSession
342
- * and persists via the real settings manager).
343
- * - Capture the selected model in the onSelect callback.
344
- * - After ctx.ui.custom() resolves, call pi.setModel() and setModelSetting().
370
+ * The component reads and writes models through the ModelRuntime and the
371
+ * scoped list it is handed; persistence is this extension's job, so the
372
+ * selected pattern is written to the role setting after the dialog resolves.
373
+ * The selection callback stores the model before the dialog closes, which is
374
+ * the only state the handler keeps from it: choosing a role model must not
375
+ * change the session's default model.
345
376
  */
346
377
  async function openModelSelectorUI(
347
378
  ctx: ExtensionCommandContext,
@@ -351,17 +382,9 @@ async function openModelSelectorUI(
351
382
  ): Promise<void> {
352
383
  const modelRegistry = ctx.modelRegistry;
353
384
 
354
- // ModelSelectorComponent writes through an in-memory SettingsManager:
355
- // setDefaultModelAndProvider() sets fields in memory but never persists,
356
- // so pi.setModel() below does the real persistence.
357
- const settingsManager = SettingsManager.inMemory();
358
-
359
- // ModelSelectorComponent's 4th parameter is the ModelRuntime. The extension
360
- // context exposes only the ModelRegistry facade, which holds the runtime as
361
- // a private field (`runtime`); read it directly. The retired
362
- // getAvailableSnapshot probe tested the registry for a method that exists
363
- // only on ModelRuntime, so it was false by construction on every supported
364
- // build.
385
+ // The extension context exposes only the ModelRegistry facade, which holds
386
+ // the runtime as a private field (`runtime`); the selector's 1.5.0
387
+ // signature takes that runtime directly.
365
388
  const modelRuntime = (modelRegistry as unknown as { runtime?: ModelRuntime }).runtime;
366
389
 
367
390
  // Priority: selected model first, then same provider, then others
@@ -392,40 +415,18 @@ async function openModelSelectorUI(
392
415
  };
393
416
  const onCancel = () => done(undefined as unknown);
394
417
 
395
- // 0.80.8: (tui, currentModel, settingsManager, modelRuntime, scopedModels,
396
- // onSelect, onCancel) — ctor.length 7. 0.84.4: (tui, currentModel,
397
- // modelRuntime, scopedModels, onSelect, onCancel, initialSearchInput?,
398
- // onSelectAsDefault?, defaultModel?) — SettingsManager dropped; the
399
- // compiled ctor declares 9 plain params (no defaults) → length 9. NB:
400
- // function.length counts params BEFORE the first default — the d.ts's
401
- // "optional" suffixes don't exist in compiled JS. So length !== 7 = new. The installed
402
- // devDependency types may lag the running pi dist (0.82.1 d.ts vs 0.84.4
403
- // runtime), so the new-signature branch is typed loosely on purpose.
404
- const isNewSelector = ModelSelectorComponent.length !== 7;
405
- // structural component — pi renders it via ctx.ui.custom. Return type is
406
- // `object` (not {}): the new-signature branch is typed loosely on purpose.
407
- const SelectorCtor = ModelSelectorComponent as unknown as new (...args: unknown[]) => object;
408
- const selector = isNewSelector
409
- ? new (SelectorCtor as any)(
410
- tui,
411
- currentRoleModel,
412
- modelRuntime,
413
- scopedModels,
414
- onSelect,
415
- onCancel,
416
- )
417
- : // 0.85.1 devDep types carry only the new signature (3rd param
418
- // ModelRuntime), so the legacy branch can no longer type against
419
- // them — same deliberate loose typing as the new branch above.
420
- new (SelectorCtor as any)(
421
- tui,
422
- currentRoleModel,
423
- settingsManager,
424
- modelRuntime,
425
- scopedModels,
426
- onSelect,
427
- onCancel,
428
- );
418
+ // Installed 1.5.0 signature: (tui, currentModel, modelRuntime,
419
+ // scopedModels, onSelect, onCancel, initialSearchInput?,
420
+ // onSelectAsDefault?, defaultModel?). The runtime is read off the registry
421
+ // above; the types ship with the package, so no arity probe is needed.
422
+ const selector = new ModelSelectorComponent(
423
+ tui,
424
+ currentRoleModel,
425
+ modelRuntime as ModelRuntime,
426
+ scopedModels,
427
+ onSelect,
428
+ onCancel,
429
+ );
429
430
 
430
431
  return selector;
431
432
  });
@@ -76,8 +76,8 @@ per-source caps are enforced in `injection-tracker.ts`.
76
76
  - **Default-on**: the manifest entry carries no `disabledByDefault`, so the
77
77
  scheduler loads like every other default extension. Turn it off per
78
78
  extension (`braid.modules["heartbeat-scheduler"]: false`, or
79
- `/modules-disable heartbeat-scheduler`) or by its module group
80
- (`/modules-disable heartbeat`, which also covers `analytics`); the
79
+ `/modules off heartbeat-scheduler`) or by its module group
80
+ (`/modules off heartbeat`, which also covers `analytics`); the
81
81
  in-process toggle changes the current session's set without a restart.
82
82
  - **First-tick timing**: the first heartbeat fires 5 turns after
83
83
  session_start, not on session_start itself. This avoids racing
@@ -573,7 +573,17 @@ async function queueProposal(
573
573
  // measured deliveries). The source must be the TRUE family, so the
574
574
  // envelope says context-lifecycle.
575
575
  applyWhisperEnvelope(proposalContent, "context-lifecycle/proposal");
576
- sm?.appendCustomMessageEntry?.(PROPOSAL_CUSTOM_TYPE, proposalContent, true, proposal);
576
+ // A custom message rendered into an exported session prints its content
577
+ // as JSON when the content is an array of parts (pi-core's export template
578
+ // falls back to JSON.stringify for a non-string). The proposal is text, so
579
+ // it is stored as text: one string, envelope first and marker last, which
580
+ // is also what the agent reads on resume.
581
+ sm?.appendCustomMessageEntry?.(
582
+ PROPOSAL_CUSTOM_TYPE,
583
+ proposalContent.map((part) => part.text).join("\n"),
584
+ true,
585
+ proposal,
586
+ );
577
587
  // Record the suggestion class so a repeat re-fire is suppressed while
578
588
  // this one is still actionable (gate + dedupe rely on this map).
579
589
  state(ctx).proposalKeys.set(
@@ -1,6 +1,7 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
2
  import { Type } from "typebox";
3
3
  import type { AgentToolResult, ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ import type { AutocompleteItem } from "@earendil-works/pi-tui";
4
5
 
5
6
  import {
6
7
  getConfig,
@@ -249,6 +250,7 @@ export default function healthMaintenanceExtension(pi: ExtensionAPI) {
249
250
  // than "none" will corrupt the TUI rendering.
250
251
  pi.registerCommand("logs", {
251
252
  description: "Show/clear the in-memory log buffer (TUI-safe default: no console writes)",
253
+ getArgumentCompletions: completeLogs,
252
254
  handler: async (args: string | undefined, ctx) => {
253
255
  const trimmed = (args ?? "").trim();
254
256
  const parts = trimmed.split(/\s+/);
@@ -298,6 +300,33 @@ export default function healthMaintenanceExtension(pi: ExtensionAPI) {
298
300
  }
299
301
 
300
302
  // Action Handlers
303
+
304
+ const LOG_LEVELS = ["none", "error", "warn", "info", "debug"];
305
+
306
+ /** Complete /logs: its two verbs, then the level values after `level`. */
307
+ function completeLogs(prefix: string): AutocompleteItem[] | null {
308
+ const text = prefix ?? "";
309
+ const space = text.indexOf(" ");
310
+ if (space === -1) {
311
+ const typed = text.toLowerCase();
312
+ const verbs: AutocompleteItem[] = [
313
+ { value: "clear", label: "clear", description: "Clear the in-memory buffer" },
314
+ { value: "level", label: "level", description: "Set the console log level" },
315
+ ];
316
+ const matches = verbs.filter((item) => item.value.startsWith(typed));
317
+ return matches.length > 0 ? matches : null;
318
+ }
319
+ const verb = text.slice(0, space).toLowerCase();
320
+ if (verb !== "level") return null;
321
+ const typed = text.slice(space + 1).toLowerCase();
322
+ const matches = LOG_LEVELS.filter((level) => level.startsWith(typed)).map((level) => ({
323
+ value: `level ${level}`,
324
+ label: level,
325
+ description: level === "none" ? "TUI-safe (no console writes)" : "Writes to the console",
326
+ }));
327
+ return matches.length > 0 ? matches : null;
328
+ }
329
+
301
330
  async function executeHealthMaintenanceAction(
302
331
  params: any,
303
332
  _pi: ExtensionAPI,
package/src/index.ts CHANGED
@@ -16,9 +16,10 @@
16
16
  * Reference targets: extension IDs ("enforcement") or module groups ("heartbeat").
17
17
  *
18
18
  * Subagent API:
19
- * Researcher subagents can call `/modules-enable`, `/modules-disable`,
20
- * `/modules-toggle`, `/modules-list`, `/modules-status`, `/modules-reset`
21
- * to control extension loading during benchmark experiments.
19
+ * Researcher subagents can call `/modules` (verbs: on, off, toggle, reset,
20
+ * all on|off, list) to control extension loading during benchmark experiments.
21
+ * The six former names (modules-enable, modules-disable, modules-toggle,
22
+ * modules-reset, modules-list, modules-status) forward to it for one release.
22
23
  */
23
24
 
24
25
  import { readFileSync } from "node:fs";
@@ -13,9 +13,9 @@ that it contains the **loader** (and the related subagent API), not
13
13
  ## Files
14
14
 
15
15
  | File | Purpose |
16
- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
16
+ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
17
17
  | `loader.ts` | Resolves `BRAID_MODULES` / `braid.modules` (pi global, pi project, braid's store) / runtime overrides into an enabled set, topologically sorts by dependency, and invokes each factory. |
18
- | `api.ts` | Registers `/modules-enable`, `/modules-disable`, `/modules-toggle`, `/modules-list`, `/modules-status`, `/modules-reset` commands for the subagent API. |
18
+ | `api.ts` | Registers `/modules` (verbs: `on`, `off`, `toggle`, `reset`, `all on | off`, `list`) for the subagent API, plus the six former command names as forwarding aliases. |
19
19
 
20
20
  ## Layer position
21
21