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/src/loader/api.ts CHANGED
@@ -1,138 +1,379 @@
1
1
  /**
2
- * Subagent API for module/toggle.
2
+ * Subagent API for extension toggling.
3
3
  *
4
- * Registers commands that a researcher subagent can call during benchmarks
5
- * to enable/disable extensions (or module groups) and query their state:
4
+ * One command, `/modules`, with a verb as its first argument:
6
5
  *
7
- * modules-enable <id> - Enable an extension or module group
8
- * modules-disable <id> - Disable an extension or module group
9
- * modules-toggle <id> - Toggle an extension or module group
10
- * modules-list - Show all extensions and their state
11
- * modules-status - Show current session extension state
12
- * modules-reset - Reset all runtime overrides
6
+ * /modules - TUI: open the extension list; RPC: print its rows as text
7
+ * /modules on <ref> - Enable an extension or module group
8
+ * /modules off <ref> - Disable an extension or module group
9
+ * /modules toggle <ref> - Flip the effective state
10
+ * /modules all on|off - Apply to every extension in the manifest
11
+ * /modules reset - Clear in-process overrides (persisted state stays)
12
+ * /modules list - Print the rows as text in every mode
13
13
  *
14
- * Reference targets can be individual extension IDs (e.g. "enforcement")
15
- * or module group names (e.g. "memory" expands to all memory extensions).
14
+ * Reference targets are extension IDs (e.g. "enforcement") or module group
15
+ * names (e.g. "memory", which expands to every extension in the group). A
16
+ * reference the resolver does not know is refused with the offending text
17
+ * alone; argument completion and `list` are the places that enumerate what is
18
+ * accepted.
19
+ *
20
+ * The six command names this file used to register remain as forwarding
21
+ * aliases for one release: modules-enable, modules-disable, modules-toggle,
22
+ * modules-reset, modules-list, modules-status. Each maps its whole argument
23
+ * onto the equivalent argv, so a script written against the old names keeps
24
+ * working until it is pointed at `/modules`.
16
25
  */
17
26
 
18
27
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
28
+ import { getSettingsListTheme } from "@earendil-works/pi-coding-agent";
29
+ import {
30
+ Container,
31
+ type AutocompleteItem,
32
+ type SettingItem,
33
+ SettingsList,
34
+ } from "@earendil-works/pi-tui";
19
35
 
20
36
  import { createLogger } from "../lib/core/logger.js";
21
37
  import {
22
- enableModule,
23
- disableModule,
24
- toggleModule,
25
38
  getModuleStates,
39
+ getModuleRefs,
26
40
  resetModuleOverrides,
27
- getAllRefNames,
41
+ setModuleEnabled,
42
+ toggleModule,
43
+ type ModuleOrigin,
28
44
  } from "./loader.js";
29
45
 
30
46
  const log = createLogger("modules-api");
31
47
 
48
+ /** One extension as both the TUI list and the text rows present it. */
49
+ interface ModuleRow {
50
+ id: string;
51
+ description: string;
52
+ value: "on" | "off";
53
+ values: ["on", "off"];
54
+ }
55
+
56
+ /** The verb table, shared by the handler's usage lines and completion. */
57
+ const VERBS: Record<string, string> = {
58
+ on: "Enable an extension or module group",
59
+ off: "Disable an extension or module group",
60
+ toggle: "Flip the effective state",
61
+ all: "Apply on or off to every extension",
62
+ reset: "Clear in-process overrides (persisted state stays)",
63
+ list: "Print every extension as text",
64
+ };
65
+
66
+ const USAGE =
67
+ "Usage: /modules [on|off|toggle|reset|all|list] <ref>\n" +
68
+ "A ref is an extension id or a module group name. Tab completes both.";
69
+
32
70
  export default async function modulesApiExtension(pi: ExtensionAPI): Promise<void> {
33
- // ── enable ──────────────────────────────────────────────────────────
34
- pi.registerCommand("modules-enable", {
35
- description: "Enable an extension or module group. Usage: modules-enable <id>",
36
- handler: async (_args: string, ctx: ExtensionCommandContext) => {
37
- const name = _args.trim().toLowerCase();
38
- const refs = getAllRefNames();
39
- if (!name || !refs.includes(name)) {
40
- ctx.ui.notify?.(`Usage: modules-enable <id>\nAvailable: ${refs.join(", ")}`, "warning");
41
- return;
71
+ const run = async (argv: string[], ctx: ExtensionCommandContext): Promise<void> => {
72
+ const notify = (message: string, type: "info" | "warning" | "error" = "info"): void => {
73
+ ctx.ui.notify?.(message, type);
74
+ };
75
+ const verb = (argv[0] ?? "").toLowerCase();
76
+
77
+ if (argv.length === 0) {
78
+ if (ctx.mode === "tui") {
79
+ await openModuleList(ctx);
80
+ } else {
81
+ notify(renderRows(), "info");
42
82
  }
43
- const ok = enableModule(name, ctx);
44
- ctx.ui.notify?.(
45
- ok ? `"${name}" enabled (next session startup).` : `Cannot enable "${name}".`,
46
- ok ? "info" : "error",
47
- );
48
- },
49
- });
83
+ return;
84
+ }
50
85
 
51
- // ── disable ─────────────────────────────────────────────────────────
52
- pi.registerCommand("modules-disable", {
53
- description: "Disable an extension or module group. Usage: modules-disable <id>",
54
- handler: async (_args: string, ctx: ExtensionCommandContext) => {
55
- const name = _args.trim().toLowerCase();
56
- if (!name) {
57
- ctx.ui.notify?.("Usage: modules-disable <id>", "warning");
86
+ switch (verb) {
87
+ case "list": {
88
+ notify(renderRows(), "info");
58
89
  return;
59
90
  }
60
- const ok = disableModule(name, ctx);
61
- ctx.ui.notify?.(
62
- ok
63
- ? `"${name}" disabled (next session).`
64
- : `Cannot disable "${name}" - it may be a core extension.`,
65
- ok ? "info" : "error",
66
- );
67
- },
68
- });
69
-
70
- // ── toggle ──────────────────────────────────────────────────────────
71
- pi.registerCommand("modules-toggle", {
72
- description: "Toggle an extension or module group. Usage: modules-toggle <id>",
73
- handler: async (_args: string, ctx: ExtensionCommandContext) => {
74
- const name = _args.trim().toLowerCase();
75
- if (!name) {
76
- ctx.ui.notify?.("Usage: modules-toggle <id>", "warning");
91
+ case "on":
92
+ case "off": {
93
+ const ref = argv[1]?.trim().toLowerCase();
94
+ if (!ref) {
95
+ notify(`Usage: /modules ${verb} <ref>\n${USAGE}`, "warning");
96
+ return;
97
+ }
98
+ const on = verb === "on";
99
+ if (!setModuleEnabled(ref, on)) {
100
+ notify(refusal(ref, verb), "error");
101
+ return;
102
+ }
103
+ notify(`"${ref}" ${on ? "enabled" : "disabled"} (applies at the next start).`, "info");
77
104
  return;
78
105
  }
79
- const state = toggleModule(name, ctx);
80
- if (state === null) ctx.ui.notify?.(`"${name}" not found.`, "error");
81
- else ctx.ui.notify?.(`"${name}" toggled ${state ? "ON" : "OFF"} (next session).`, "info");
82
- },
106
+ case "toggle": {
107
+ const ref = argv[1]?.trim().toLowerCase();
108
+ if (!ref) {
109
+ notify(`Usage: /modules toggle <ref>\n${USAGE}`, "warning");
110
+ return;
111
+ }
112
+ const before = getModuleStates();
113
+ const state = toggleModule(ref, ctx);
114
+ if (state === null) {
115
+ notify(refusal(ref, "toggle"), "error");
116
+ return;
117
+ }
118
+ const after = getModuleStates();
119
+ const changed = Object.keys(after).some((id) => before[id].enabled !== after[id].enabled);
120
+ if (!changed) {
121
+ notify(`"${ref}" is always on and cannot be changed.`, "error");
122
+ return;
123
+ }
124
+ notify(`"${ref}" toggled ${state ? "ON" : "OFF"} (applies at the next start).`, "info");
125
+ return;
126
+ }
127
+ case "all": {
128
+ const mode = argv[1]?.trim().toLowerCase();
129
+ if (mode !== "on" && mode !== "off") {
130
+ notify("Usage: /modules all <on|off>", "warning");
131
+ return;
132
+ }
133
+ const on = mode === "on";
134
+ let applied = 0;
135
+ let refused = 0;
136
+ for (const id of Object.keys(getModuleStates())) {
137
+ if (setModuleEnabled(id, on)) applied++;
138
+ else refused++;
139
+ }
140
+ notify(
141
+ `"${on ? "on" : "off"}" applied to ${applied} extension(s)` +
142
+ (refused > 0
143
+ ? `; ${refused} always-on extension(s) cannot be disabled.`
144
+ : " (applies at the next start)."),
145
+ refused > 0 ? "warning" : "info",
146
+ );
147
+ return;
148
+ }
149
+ case "reset": {
150
+ resetModuleOverrides(ctx);
151
+ notify(
152
+ "Runtime overrides reset. Persisted braid.modules entries (if any) still apply.",
153
+ "info",
154
+ );
155
+ return;
156
+ }
157
+ default: {
158
+ notify(`Unknown verb "${verb}".\n${USAGE}`, "warning");
159
+ }
160
+ }
161
+ };
162
+
163
+ pi.registerCommand("modules", {
164
+ description:
165
+ "Enable or disable extensions. No argument opens the list (text in RPC mode). " +
166
+ "Usage: /modules on|off|toggle <ref>, /modules all on|off, /modules reset, /modules list",
167
+ getArgumentCompletions: completeModules,
168
+ handler: (args, ctx) => run(splitArgs(args), ctx),
83
169
  });
84
170
 
85
- // ── list ────────────────────────────────────────────────────────────
171
+ pi.registerCommand("modules-enable", {
172
+ description: "Alias of /modules on <ref>. Retained for one release.",
173
+ getArgumentCompletions: completeRefs("on"),
174
+ handler: (args, ctx) => run([...forwarded("on", args)], ctx),
175
+ });
176
+ pi.registerCommand("modules-disable", {
177
+ description: "Alias of /modules off <ref>. Retained for one release.",
178
+ getArgumentCompletions: completeRefs("off"),
179
+ handler: (args, ctx) => run([...forwarded("off", args)], ctx),
180
+ });
181
+ pi.registerCommand("modules-toggle", {
182
+ description: "Alias of /modules toggle <ref>. Retained for one release.",
183
+ getArgumentCompletions: completeRefs("toggle"),
184
+ handler: (args, ctx) => run([...forwarded("toggle", args)], ctx),
185
+ });
186
+ pi.registerCommand("modules-reset", {
187
+ description: "Alias of /modules reset. Retained for one release.",
188
+ handler: async (_args, ctx) => run(["reset"], ctx),
189
+ });
86
190
  pi.registerCommand("modules-list", {
87
- description: "List all extensions with state, load status, and config source.",
88
- handler: async (_args: string, ctx: ExtensionCommandContext) => {
89
- const states = getModuleStates(ctx);
90
- const lines: string[] = [];
91
- const source = Object.values(states)[0]?.source ?? "?";
92
- lines.push(`Extensions (config: ${source}):`);
93
- for (const [id, info] of Object.entries(states)) {
94
- const status = info.enabled ? (info.loaded ? "●" : "○ pending") : "- disabled";
95
- lines.push(` ${status.padEnd(12)} ${id}`);
96
- lines.push(` ${info.desc}`);
97
- }
98
- lines.push("");
99
- lines.push("Toggle: /modules-toggle <id>");
100
- lines.push("Enable: /modules-enable <id> Disable: /modules-disable <id>");
101
- lines.push("Reset: /modules-reset");
102
- ctx.ui.notify?.(lines.join("\n"), "info");
103
- },
191
+ description: "Alias of /modules list. Retained for one release.",
192
+ handler: async (_args, ctx) => run(["list"], ctx),
104
193
  });
105
-
106
- // ── status ──────────────────────────────────────────────────────────
107
194
  pi.registerCommand("modules-status", {
108
- description: "Show current runtime overrides and load state.",
109
- handler: async (_args: string, ctx: ExtensionCommandContext) => {
110
- const states = getModuleStates(ctx);
111
- const loaded = Object.values(states).filter((s) => s.loaded).length;
112
- const enabled = Object.values(states).filter((s) => s.enabled).length;
113
- const lines: string[] = [
114
- `Extensions: ${loaded} loaded, ${enabled} enabled` +
115
- ` (config: ${Object.values(states)[0]?.source ?? "?"})`,
116
- ];
117
- for (const [id, info] of Object.entries(states)) {
118
- const status = info.enabled ? (info.loaded ? "●" : "○ pending") : "- disabled";
119
- lines.push(` ${status.padEnd(12)} ${id}`);
120
- }
121
- ctx.ui.notify?.(lines.join("\n"), "info");
122
- },
195
+ description: "Alias of /modules list. Retained for one release.",
196
+ handler: async (_args, ctx) => run(["list"], ctx),
123
197
  });
124
198
 
125
- // ── reset ──────────────────────────────────────────────────────────
126
- pi.registerCommand("modules-reset", {
127
- description: "Reset all runtime overrides (restore defaults).",
128
- handler: async (_args: string, ctx: ExtensionCommandContext) => {
129
- resetModuleOverrides(ctx);
130
- ctx.ui.notify?.(
131
- "Runtime overrides reset. Persisted braid.modules entries (if any) still apply.",
132
- "info",
133
- );
134
- },
135
- });
199
+ log.info("Module API registered: /modules (+ six forwarding aliases)");
200
+ }
201
+
202
+ // ── Argument parsing ────────────────────────────────────────────────────────
203
+
204
+ /** Split a command's argument string into argv; quoted runs stay one token. */
205
+ function splitArgs(args: string | undefined): string[] {
206
+ const text = (args ?? "").trim();
207
+ if (!text) return [];
208
+ const argv: string[] = [];
209
+ const pattern = /"([^"]*)"|'([^']*)'|(\S+)/g;
210
+ let match: RegExpExecArray | null;
211
+ while ((match = pattern.exec(text)) !== null) {
212
+ argv.push(match[1] ?? match[2] ?? match[3]);
213
+ }
214
+ return argv;
215
+ }
216
+
217
+ /** The argv an old name forwards: its whole argument is the ref. */
218
+ function forwarded(verb: string, args: string | undefined): string[] {
219
+ return [verb, (args ?? "").trim()];
220
+ }
221
+
222
+ /** Why a reference was refused, naming the rule instead of listing refs. */
223
+ function refusal(ref: string, verb: string): string {
224
+ if (!getModuleRefs().includes(ref)) {
225
+ return (
226
+ `Unknown reference "${ref}". Tab completes extension ids and module groups; ` +
227
+ "/modules list shows every extension."
228
+ );
229
+ }
230
+ if (verb === "off") return `Cannot disable "${ref}": every extension it names is always on.`;
231
+ return `Nothing to ${verb} for "${ref}".`;
232
+ }
233
+
234
+ // ── Completion ──────────────────────────────────────────────────────────────
235
+
236
+ /** Complete the first token with verbs, later tokens with references. */
237
+ function completeModules(prefix: string): AutocompleteItem[] | null {
238
+ const text = prefix ?? "";
239
+ const space = text.indexOf(" ");
240
+ if (space === -1) {
241
+ const typed = text.toLowerCase();
242
+ return Object.entries(VERBS)
243
+ .filter(([verb]) => verb.startsWith(typed))
244
+ .map(([verb, description]) => ({ value: verb, label: verb, description }));
245
+ }
246
+ const verb = text.slice(0, space).toLowerCase();
247
+ const tail = text.slice(space + 1);
248
+ if (verb === "all") return completeValues(tail, ["on", "off"]);
249
+ if (verb === "on" || verb === "off" || verb === "toggle") {
250
+ const typed = tail.toLowerCase();
251
+ return getModuleRefs()
252
+ .filter((ref) => ref.startsWith(typed))
253
+ .map((ref) => ({ value: `${verb} ${ref}`, label: ref }));
254
+ }
255
+ return null;
256
+ }
136
257
 
137
- log.info("Module API registered: enable/disable/toggle/list/status/reset");
258
+ /** Completion for an old name: the whole argument text is the reference. */
259
+ function completeRefs(verb: string) {
260
+ return (prefix: string): AutocompleteItem[] | null => {
261
+ const typed = (prefix ?? "").toLowerCase();
262
+ return getModuleRefs()
263
+ .filter((ref) => ref.startsWith(typed))
264
+ .map((ref) => ({ value: ref, label: ref, description: `Forwarded to /modules ${verb}` }));
265
+ };
266
+ }
267
+
268
+ function completeValues(prefix: string, values: string[]): AutocompleteItem[] {
269
+ const typed = (prefix ?? "").toLowerCase();
270
+ return values
271
+ .filter((value) => value.startsWith(typed))
272
+ .map((value) => ({ value, label: value }));
273
+ }
274
+
275
+ // ── Rows ────────────────────────────────────────────────────────────────────
276
+
277
+ /** Every extension as one row, plus the config source that resolved them. */
278
+ function moduleRows(): { rows: ModuleRow[]; source: string } {
279
+ const states = getModuleStates();
280
+ const rows = Object.entries(states).map(([id, info]) => ({
281
+ id,
282
+ description: describe(info.desc, info.origin, info.enabled, info.loaded),
283
+ value: (info.enabled ? "on" : "off") as ModuleRow["value"],
284
+ values: ["on", "off"] as ModuleRow["values"],
285
+ }));
286
+ return { rows, source: Object.values(states)[0]?.source ?? "?" };
287
+ }
288
+
289
+ /** The one description both surfaces show: what it does, where its state came
290
+ * from, and whether a restart is still owed. */
291
+ function describe(desc: string, origin: ModuleOrigin, enabled: boolean, loaded: boolean): string {
292
+ const tail = enabled === loaded ? origin : `${origin}; restart to apply`;
293
+ return `${desc} (${tail})`;
294
+ }
295
+
296
+ /** The rows as text, for RPC mode and the `list` verb. */
297
+ function renderRows(): string {
298
+ const { rows, source } = moduleRows();
299
+ const lines = [`Extensions (${rows.length}, config: ${source}):`];
300
+ const width = Math.min(28, Math.max(...rows.map((row) => row.id.length)));
301
+ for (const row of rows) {
302
+ lines.push(` ${row.value.padEnd(3)} ${row.id.padEnd(width)} ${row.description}`);
303
+ }
304
+ lines.push("");
305
+ lines.push(
306
+ "Toggle: /modules toggle <ref> Enable: /modules on <ref> Disable: /modules off <ref>",
307
+ );
308
+ lines.push("Reset: /modules reset All: /modules all on|off");
309
+ return lines.join("\n");
310
+ }
311
+
312
+ // ── TUI ─────────────────────────────────────────────────────────────────────
313
+
314
+ /** The TUI list: one toggle per extension, written through the same resolver
315
+ * the verbs use. */
316
+ async function openModuleList(ctx: ExtensionCommandContext): Promise<void> {
317
+ await ctx.ui.custom((tui, theme, _kb, done) => {
318
+ const container = new Container();
319
+ container.addChild(
320
+ new (class {
321
+ render(_width: number) {
322
+ return [theme.fg("accent", theme.bold("Extensions"))];
323
+ }
324
+ invalidate() {}
325
+ })(),
326
+ );
327
+
328
+ const rows = moduleRows().rows;
329
+ const items: SettingItem[] = rows.map((row) => ({
330
+ id: row.id,
331
+ label: row.id,
332
+ description: row.description,
333
+ currentValue: row.value,
334
+ values: [...row.values],
335
+ }));
336
+
337
+ const list = new SettingsList(
338
+ items,
339
+ Math.min(items.length + 2, 18),
340
+ getSettingsListTheme(),
341
+ (id, newValue) => {
342
+ const on = newValue === "on";
343
+ if (!setModuleEnabled(id, on)) {
344
+ // The list already flipped its own value; put it back so the row
345
+ // never claims a state the resolver refused.
346
+ list.updateValue(id, "on");
347
+ ctx.ui.notify?.(`"${id}" is always on and cannot be disabled.`, "error");
348
+ tui.requestRender();
349
+ return;
350
+ }
351
+ const info = getModuleStates()[id];
352
+ const item = items.find((candidate) => candidate.id === id);
353
+ if (info && item) item.description = describe(info.desc, info.origin, on, info.loaded);
354
+ tui.requestRender();
355
+ },
356
+ () => done(undefined),
357
+ { enableSearch: true },
358
+ );
359
+ container.addChild(list);
360
+
361
+ return {
362
+ render(width: number) {
363
+ return container.render(width);
364
+ },
365
+ invalidate() {
366
+ container.invalidate();
367
+ },
368
+ handleInput(data: string) {
369
+ list.handleInput?.(data);
370
+ tui.requestRender();
371
+ },
372
+ handleMouse(event: Parameters<SettingsList["handleMouse"]>[0]) {
373
+ const result = list.handleMouse?.(event);
374
+ tui.requestRender();
375
+ return result;
376
+ },
377
+ };
378
+ });
138
379
  }
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * Config layers (applied high -> low; runtime and settings override the
5
5
  * layers below per-id, the env var is a complete spec over the defaults):
6
- * 1. Runtime overrides - /modules-toggle, /modules-enable, /modules-disable
7
- * (in-session; the toggle commands also persist them into `braid.modules`)
6
+ * 1. Runtime overrides - /modules on|off|toggle|all|reset (in-session; the
7
+ * toggle verbs also persist them into `braid.modules`)
8
8
  * 2. `braid.modules` settings - two sources, later wins per id: pi's
9
9
  * agent-directory settings file (`<agent dir>/settings.json`) and braid's
10
10
  * own module-overrides store, which is where toggles persist
@@ -483,28 +483,31 @@ function resolveIds(ref: string): string[] | null {
483
483
  return null;
484
484
  }
485
485
 
486
- /** Enable an extension (or module group). Persists to settings.json. */
487
- export function enableModule(name: string, _ctx?: ExtensionContext): boolean {
488
- const ids = resolveIds(name);
486
+ /**
487
+ * Enable or disable an extension (or module group), persisting the choice.
488
+ * Returns false when the reference is unknown, or when the request would
489
+ * disable an always-on extension: always-on entries are loaded regardless of
490
+ * config, so a `false` for one would be a stored lie.
491
+ */
492
+ export function setModuleEnabled(ref: string, on: boolean): boolean {
493
+ const ids = resolveIds(ref);
489
494
  if (!ids) return false;
495
+ const mutable = ids.filter((id) => !getEntry(id)?.alwaysOn);
496
+ if (mutable.length === 0) return on;
490
497
  const state = getLoaderState();
491
- const nonAlwaysOn = ids.filter((id) => !getEntry(id)?.alwaysOn);
492
- if (nonAlwaysOn.length === 0) return true;
493
- for (const id of nonAlwaysOn) state.runtimeConfig.set(id, true);
498
+ for (const id of mutable) state.runtimeConfig.set(id, on);
494
499
  saveModuleOverridesToFile(state.runtimeConfig);
495
500
  return true;
496
501
  }
497
502
 
498
- /** Disable an extension (or module group). Persists to settings.json. */
503
+ /** Enable an extension (or module group). Persists to braid's override store. */
504
+ export function enableModule(name: string, _ctx?: ExtensionContext): boolean {
505
+ return setModuleEnabled(name, true);
506
+ }
507
+
508
+ /** Disable an extension (or module group). Persists to braid's override store. */
499
509
  export function disableModule(name: string, _ctx?: ExtensionContext): boolean {
500
- const ids = resolveIds(name);
501
- if (!ids) return false;
502
- const nonAlwaysOn = ids.filter((id) => !getEntry(id)?.alwaysOn);
503
- if (nonAlwaysOn.length === 0) return false;
504
- const state = getLoaderState();
505
- for (const id of nonAlwaysOn) state.runtimeConfig.set(id, false);
506
- saveModuleOverridesToFile(state.runtimeConfig);
507
- return true;
510
+ return setModuleEnabled(name, false);
508
511
  }
509
512
 
510
513
  /** Toggle an extension (or module group). Returns the new state or null. */
@@ -524,15 +527,69 @@ export function toggleModule(name: string, _ctx?: ExtensionContext): boolean | n
524
527
  return next;
525
528
  }
526
529
 
530
+ /**
531
+ * The layer that decides each extension's enabled state. Later layers win,
532
+ * matching resolveFromSources: manifest default, env spec, agent settings,
533
+ * braid's store, runtime override.
534
+ */
535
+ export type ModuleOrigin =
536
+ | "manifest"
537
+ | "environment"
538
+ | "agent settings"
539
+ | "module toggles"
540
+ | "runtime override";
541
+
542
+ /** The settings layer that names each extension, when one does. */
543
+ function settingsOrigins(): Map<string, ModuleOrigin> {
544
+ const origins = new Map<string, ModuleOrigin>();
545
+ const storePath = getModuleStorePath();
546
+ const layers: [ModuleOrigin, Record<string, unknown>][] = [
547
+ ["agent settings", readSettingsFile(GLOBAL_SETTINGS)],
548
+ ["module toggles", storePath ? readSettingsFile(storePath) : {}],
549
+ ];
550
+ for (const [origin, doc] of layers) {
551
+ const modules = (doc[BRAID_KEY] as BraidSettings)?.modules ?? {};
552
+ for (const ref of Object.keys(modules)) {
553
+ for (const id of expandRef(ref)) origins.set(id, origin);
554
+ }
555
+ }
556
+ return origins;
557
+ }
558
+
559
+ /** Where every extension's effective state comes from, one entry each. */
560
+ function resolveOrigins(): Map<string, ModuleOrigin> {
561
+ const origins = new Map<string, ModuleOrigin>();
562
+ for (const entry of MANIFEST) origins.set(entry.id, "manifest");
563
+
564
+ const env = process.env.BRAID_MODULES;
565
+ if (env && env.trim()) {
566
+ for (const part of env
567
+ .split(",")
568
+ .map((s) => s.trim())
569
+ .filter(Boolean)) {
570
+ const ref = part.startsWith("+") || part.startsWith("-") ? part.slice(1) : part;
571
+ for (const id of expandRef(ref)) origins.set(id, "environment");
572
+ }
573
+ }
574
+
575
+ for (const [id, origin] of settingsOrigins()) origins.set(id, origin);
576
+ for (const id of getLoaderState().runtimeConfig.keys()) origins.set(id, "runtime override");
577
+ return origins;
578
+ }
579
+
527
580
  /** Get the current state of all extensions with loading status. */
528
581
  export function getModuleStates(
529
582
  _ctx?: ExtensionContext,
530
- ): Record<string, { enabled: boolean; loaded: boolean; source: string; desc: string }> {
583
+ ): Record<
584
+ string,
585
+ { enabled: boolean; loaded: boolean; source: string; desc: string; origin: ModuleOrigin }
586
+ > {
531
587
  const state = getLoaderState();
532
588
  const { enabled, source } = resolveEnabledExtensions();
589
+ const origins = resolveOrigins();
533
590
  const result: Record<
534
591
  string,
535
- { enabled: boolean; loaded: boolean; source: string; desc: string }
592
+ { enabled: boolean; loaded: boolean; source: string; desc: string; origin: ModuleOrigin }
536
593
  > = {};
537
594
  for (const entry of MANIFEST) {
538
595
  // One resolution path: the resolver already applies runtime overrides,
@@ -544,6 +601,7 @@ export function getModuleStates(
544
601
  loaded: state.loaded.includes(entry.id),
545
602
  source,
546
603
  desc: entry.desc,
604
+ origin: origins.get(entry.id) ?? "manifest",
547
605
  };
548
606
  }
549
607
  return result;
@@ -595,6 +653,11 @@ function topologicalSort(extIds: string[]): string[] {
595
653
  }
596
654
 
597
655
  /** Get all valid config reference names for API completion/docs. */
598
- export function getAllRefNames(): string[] {
656
+ export function getModuleRefs(): string[] {
599
657
  return allConfigRefs();
600
658
  }
659
+
660
+ /** @deprecated Use getModuleRefs. Kept as an alias for existing callers. */
661
+ export function getAllRefNames(): string[] {
662
+ return getModuleRefs();
663
+ }