@floydous/pi-agent-kernel 0.3.3 → 0.4.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.
@@ -0,0 +1,834 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import {
5
+ Container,
6
+ fuzzyFilter,
7
+ getKeybindings,
8
+ Input,
9
+ Spacer,
10
+ Text,
11
+ truncateToWidth,
12
+ visibleWidth,
13
+ wrapTextWithAnsi,
14
+ } from "@earendil-works/pi-tui";
15
+ import {
16
+ loadKernelConfig,
17
+ saveGlobalKernelConfig,
18
+ removeGlobalKernelConfigKey,
19
+ saveProjectKernelConfig,
20
+ mergeDeep,
21
+ getGlobalConfigPath,
22
+ getGlobalRawConfig,
23
+ getProjectConfigPath,
24
+ type KernelConfig,
25
+ type KernelConfigOverrides,
26
+ } from "./kernel_config";
27
+ import { kernelDebug } from "../safety/kernel_debug";
28
+
29
+ export interface AgentKernelCommandDeps {
30
+ getConfig: (cwd: string) => KernelConfig;
31
+ invalidateConfig: (cwd: string, ctx?: any) => void;
32
+ clearCaches?: () => void;
33
+ }
34
+
35
+ export function formatConfigDashboard(cwd: string, config: KernelConfig): string {
36
+ const globalPath = getGlobalConfigPath();
37
+ const projectPath = getProjectConfigPath(cwd);
38
+ const globalExists = fs.existsSync(globalPath);
39
+ const projectExists = projectPath ? fs.existsSync(projectPath) : false;
40
+
41
+ const lines = [
42
+ `=== Pi Agent Kernel Configuration ===`,
43
+ `Global Config : ${globalPath} [${globalExists ? "FOUND" : "DEFAULT"}]`,
44
+ `Project Config: ${projectPath ?? "none"} [${projectExists ? "ACTIVE" : "NONE"}]`,
45
+ ``,
46
+ `[Retrieval & Tools]`,
47
+ ` • Profile (Engine) : ${config.retrieval.default_profile} (auto | lean | hybrid | full | off)`,
48
+ ` • Passive Shield : ${config.retrieval.enable_tools ? "all (6 tools exposed)" : "gated (core 3 tools default)"}`,
49
+ ` • Repo Map Budget : ${config.retrieval.repo_map_budget} tokens`,
50
+ ` • Max Search Results : ${config.retrieval.max_search_results}`,
51
+ ``,
52
+ `[Safety & Interception]`,
53
+ ` • Epistemic Guard : ${config.safety.enable_epistemic_guard ? "ENABLED (read-before-write)" : "DISABLED"}`,
54
+ ` • Output Clamping Lines : ${config.safety.max_lines} lines (head+tail)`,
55
+ ` • Output Clamping Bytes : ${Math.round(config.safety.max_total_bytes / 1024)} KB ceiling`,
56
+ ` • Max Line Width : ${config.safety.max_line_length} chars`,
57
+ ``,
58
+ `[Editing & Anchors]`,
59
+ ` • Engine Mode : ${config.editing.mode} (smart_anchor | standard)`,
60
+ ` • Read Mode : ${config.editing.read_mode} (plain | anchored | auto)`,
61
+ ` • Default Anchors : ${config.editing.default_anchors ? "true" : "false"}`,
62
+ ``,
63
+ `[System & UI]`,
64
+ ` • Kernel Guidance Prompt: ${config.instructions.enabled ? "ENABLED" : "DISABLED"}`,
65
+ ` • Pi Docs System Guidance : ${config.instructions.pi_docs ? "ENABLED" : "DISABLED"}`,
66
+ ` • Pastel Status Footer : ${config.ui.enable_pastel_footer ? "ENABLED" : "DISABLED"}`,
67
+ ``,
68
+ `Interactive UI: run '/agent-kernel' in TUI mode`,
69
+ `Modify setting: run '/agent-kernel set <key> <value>'`,
70
+ `Reset to defaults: run '/agent-kernel reset'`,
71
+ ];
72
+
73
+ return lines.join("\n");
74
+ }
75
+
76
+ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCommandDeps): void {
77
+ pi.registerCommand("agent-kernel", {
78
+ description: "Configure all Pi Agent Kernel global settings interactively or via CLI",
79
+ getArgumentCompletions: (prefix: string) => {
80
+ const subcommands = [
81
+ { value: "status", label: "status - Display full configuration status" },
82
+ { value: "set", label: "set <key> <val> - Update a setting globally" },
83
+ { value: "reset", label: "reset - Reset global configuration to defaults" },
84
+ ];
85
+
86
+ const keys = [
87
+ { value: "set tools", label: "set tools <gated|all> - Toggle Passive Shield tool gating" },
88
+ { value: "set profile", label: "set profile <auto|lean|hybrid|full|off> - Retrieval engine profile" },
89
+ { value: "set epistemic", label: "set epistemic <on|off> - Toggle Epistemic Guard" },
90
+ { value: "set editing", label: "set editing <smart_anchor|standard> - Editing engine mode" },
91
+ { value: "set read_mode", label: "set read_mode <plain|anchored|auto> - Reading anchor mode" },
92
+ { value: "set guidance", label: "set guidance <on|off> - Toggle kernel system prompt guidance" },
93
+ { value: "set pi_docs", label: "set pi_docs <on|off> - Toggle Pi documentation guide in system prompt" },
94
+ { value: "set footer", label: "set footer <on|off> - Toggle pastel status footer" },
95
+ { value: "set max_lines", label: "set max_lines <40|100|200> - Output clamping line ceiling" },
96
+ ];
97
+
98
+ const allOptions = [...subcommands, ...keys];
99
+ const filtered = allOptions.filter((o) => o.value.startsWith(prefix.toLowerCase()));
100
+ return filtered.length > 0 ? filtered : null;
101
+ },
102
+ handler: async (args: string, ctx: ExtensionContext) => {
103
+ const raw = (args || "").trim();
104
+ const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
105
+ const config = deps.getConfig(currentCwd);
106
+
107
+ // 1. Handle CLI commands (status, set, reset)
108
+ if (raw.startsWith("status")) {
109
+ const statusText = formatConfigDashboard(currentCwd, config);
110
+ if (ctx.hasUI && ctx.ui?.notify) {
111
+ ctx.ui.notify("Displayed Agent Kernel configuration.", "info");
112
+ }
113
+ console.log("\n" + statusText + "\n");
114
+ return;
115
+ }
116
+
117
+ if (raw.startsWith("reset")) {
118
+ const globalPath = getGlobalConfigPath();
119
+ try {
120
+ if (fs.existsSync(globalPath)) {
121
+ fs.unlinkSync(globalPath);
122
+ }
123
+ const legacySettings = path.join(path.dirname(globalPath), "search_settings.json");
124
+ if (fs.existsSync(legacySettings)) {
125
+ try { fs.unlinkSync(legacySettings); } catch {}
126
+ }
127
+ deps.invalidateConfig(currentCwd, ctx);
128
+ deps.clearCaches?.();
129
+ const msg = "Reset global Agent Kernel configuration to defaults.";
130
+ ctx.ui?.notify?.(msg, "info");
131
+ console.log(msg);
132
+ } catch (e: any) {
133
+ ctx.ui?.notify?.(`Failed to reset: ${e.message}`, "error");
134
+ }
135
+ return;
136
+ }
137
+
138
+ if (raw.startsWith("set ")) {
139
+ const parts = raw.slice(4).trim().split(/\s+/);
140
+ const key = (parts[0] || "").toLowerCase();
141
+ const val = (parts[1] || "").toLowerCase();
142
+
143
+ const updates: KernelConfigOverrides = {};
144
+ let desc = "";
145
+
146
+ switch (key) {
147
+ case "tools":
148
+ case "passive_shield": {
149
+ const enable = val === "all" || val === "true" || val === "1";
150
+ updates.retrieval = { enable_tools: enable };
151
+ desc = `Passive Shield tools set to '${enable ? "all (6 tools)" : "gated (core 3 tools)"}' (takes effect on reload)`;
152
+ break;
153
+ }
154
+ case "profile":
155
+ case "engine": {
156
+ if (val === "auto" || val === "lean" || val === "hybrid" || val === "full" || val === "off") {
157
+ updates.retrieval = { default_profile: val };
158
+ desc = `Retrieval profile set to '${val}'`;
159
+ } else {
160
+ ctx.ui?.notify?.("Invalid profile. Options: auto | lean | hybrid | full | off", "error");
161
+ return;
162
+ }
163
+ break;
164
+ }
165
+ case "epistemic":
166
+ case "epistemic_guard": {
167
+ const enable = val === "on" || val === "true" || val === "1" || val === "enabled";
168
+ updates.safety = { enable_epistemic_guard: enable };
169
+ desc = `Epistemic Guard set to ${enable ? "ENABLED" : "DISABLED"}`;
170
+ break;
171
+ }
172
+ case "editing":
173
+ case "editing_mode": {
174
+ if (val === "smart_anchor" || val === "standard") {
175
+ updates.editing = { mode: val };
176
+ desc = `Editing mode set to '${val}'`;
177
+ } else {
178
+ ctx.ui?.notify?.("Invalid editing mode. Options: smart_anchor | standard", "error");
179
+ return;
180
+ }
181
+ break;
182
+ }
183
+ case "read_mode": {
184
+ if (val === "plain" || val === "anchored" || val === "auto") {
185
+ updates.editing = { read_mode: val };
186
+ desc = `Read mode set to '${val}'`;
187
+ } else {
188
+ ctx.ui?.notify?.("Invalid read mode. Options: plain | anchored | auto", "error");
189
+ return;
190
+ }
191
+ break;
192
+ }
193
+ case "guidance":
194
+ case "instructions": {
195
+ const enable = val === "on" || val === "true" || val === "1" || val === "enabled";
196
+ updates.instructions = { enabled: enable };
197
+ desc = `Kernel guidance prompt set to ${enable ? "ENABLED" : "DISABLED"}`;
198
+ break;
199
+ }
200
+ case "pi_docs":
201
+ case "pi-docs":
202
+ case "docs": {
203
+ const enable = val === "on" || val === "true" || val === "1" || val === "enabled";
204
+ updates.instructions = { pi_docs: enable };
205
+ desc = `Pi documentation guidance set to ${enable ? "ENABLED" : "DISABLED"}`;
206
+ break;
207
+ }
208
+ case "footer":
209
+ case "pastel_footer": {
210
+ const enable = val === "on" || val === "true" || val === "1" || val === "enabled";
211
+ updates.ui = { enable_pastel_footer: enable };
212
+ desc = `Pastel status footer set to ${enable ? "ENABLED" : "DISABLED"}`;
213
+ break;
214
+ }
215
+ case "max_lines": {
216
+ const num = parseInt(val, 10);
217
+ if (!isNaN(num) && num >= 10 && num <= 1000) {
218
+ updates.safety = { max_lines: num };
219
+ desc = `Output clamping lines set to ${num}`;
220
+ } else {
221
+ ctx.ui?.notify?.("Invalid line limit (must be 10-1000)", "error");
222
+ return;
223
+ }
224
+ break;
225
+ }
226
+ default:
227
+ ctx.ui?.notify?.(`Unknown setting key: '${key}'. Run '/agent-kernel' for options.`, "error");
228
+ return;
229
+ }
230
+
231
+ saveGlobalKernelConfig(updates);
232
+ deps.invalidateConfig(currentCwd, ctx);
233
+ deps.clearCaches?.();
234
+ ctx.ui?.notify?.(`Saved to ~/.pi/agent/config.toml: ${desc}`, "info");
235
+ console.log(`[agent-kernel] ${desc} (persisted globally)`);
236
+ return;
237
+ }
238
+
239
+ // 2. Interactive TUI Settings Screen
240
+ if (ctx.mode !== "tui" || !ctx.hasUI) {
241
+ const statusText = formatConfigDashboard(currentCwd, config);
242
+ console.log("\n" + statusText + "\n");
243
+ return;
244
+ }
245
+
246
+ // TUI Interactive Modal with categorized layout and built-in search
247
+ await ctx.ui.custom((tui: any, theme: any, _kb: any, done: (res?: any) => void) => {
248
+ const currentConfig = deps.getConfig(currentCwd);
249
+
250
+ interface CategorizedSettingItem {
251
+ category: string;
252
+ id: string;
253
+ label: string;
254
+ currentValue: string;
255
+ values: string[];
256
+ descriptions: Record<string, string>;
257
+ isGlobal: boolean;
258
+ }
259
+
260
+ const CATEGORY_ORDER = [
261
+ "Retrieval & Exploration",
262
+ "Safety & Verification",
263
+ "Editing Engine",
264
+ "System Guidance & UI",
265
+ ];
266
+
267
+ const globalRaw = getGlobalRawConfig();
268
+ function checkIsGlobal(id: string): boolean {
269
+ if (id === "tools") return globalRaw.retrieval?.enable_tools !== undefined;
270
+ if (id === "profile") return globalRaw.retrieval?.default_profile !== undefined;
271
+ if (id === "epistemic") return globalRaw.safety?.enable_epistemic_guard !== undefined;
272
+ if (id === "max_lines") return globalRaw.safety?.max_lines !== undefined;
273
+ if (id === "editing") return globalRaw.editing?.mode !== undefined;
274
+ if (id === "read_mode") return globalRaw.editing?.read_mode !== undefined;
275
+ if (id === "guidance") return globalRaw.instructions?.enabled !== undefined;
276
+ if (id === "pi_docs") return globalRaw.instructions?.pi_docs !== undefined;
277
+ if (id === "footer") return globalRaw.ui?.enable_pastel_footer !== undefined;
278
+ return false;
279
+ }
280
+
281
+ function createPatchForSetting(id: string, value: string): { patch: KernelConfigOverrides; desc: string } {
282
+ const patch: KernelConfigOverrides = {};
283
+ let desc = "";
284
+ if (id === "tools") {
285
+ const enable = value.startsWith("all");
286
+ patch.retrieval = { enable_tools: enable };
287
+ desc = `Passive Shield tools = ${enable ? "all (6 tools)" : "gated (core 3)"}`;
288
+ } else if (id === "profile") {
289
+ patch.retrieval = { default_profile: value as any };
290
+ desc = `Retrieval profile = ${value}`;
291
+ } else if (id === "epistemic") {
292
+ const enable = value === "enabled";
293
+ patch.safety = { enable_epistemic_guard: enable };
294
+ desc = `Epistemic Guard = ${enable ? "enabled" : "disabled"}`;
295
+ } else if (id === "editing") {
296
+ patch.editing = { mode: value as any };
297
+ desc = `Editing mode = ${value}`;
298
+ } else if (id === "read_mode") {
299
+ patch.editing = { read_mode: value as any };
300
+ desc = `Reading anchor protocol = ${value}`;
301
+ } else if (id === "guidance") {
302
+ const enable = value === "enabled";
303
+ patch.instructions = { enabled: enable };
304
+ desc = `Kernel guidance prompt = ${enable ? "enabled" : "disabled"}`;
305
+ } else if (id === "pi_docs") {
306
+ const enable = value === "enabled";
307
+ patch.instructions = { pi_docs: enable };
308
+ desc = `Pi documentation guidance = ${enable ? "enabled" : "disabled"}`;
309
+ } else if (id === "footer") {
310
+ const enable = value === "enabled";
311
+ patch.ui = { enable_pastel_footer: enable };
312
+ desc = `Pastel status footer = ${enable ? "enabled" : "disabled"}`;
313
+ } else if (id === "max_lines") {
314
+ const num = parseInt(value, 10);
315
+ if (!isNaN(num)) {
316
+ patch.safety = { max_lines: num };
317
+ desc = `Output clamping = ${num} lines`;
318
+ }
319
+ }
320
+ return { patch, desc };
321
+ }
322
+
323
+ function getSettingSectionAndKey(id: string): { section: string; key: string } | null {
324
+ switch (id) {
325
+ case "tools":
326
+ return { section: "retrieval", key: "enable_tools" };
327
+ case "profile":
328
+ return { section: "retrieval", key: "default_profile" };
329
+ case "epistemic":
330
+ return { section: "safety", key: "enable_epistemic_guard" };
331
+ case "max_lines":
332
+ return { section: "safety", key: "max_lines" };
333
+ case "editing":
334
+ return { section: "editing", key: "mode" };
335
+ case "read_mode":
336
+ return { section: "editing", key: "read_mode" };
337
+ case "guidance":
338
+ return { section: "instructions", key: "enabled" };
339
+ case "pi_docs":
340
+ return { section: "instructions", key: "pi_docs" };
341
+ case "footer":
342
+ return { section: "ui", key: "enable_pastel_footer" };
343
+ default:
344
+ return null;
345
+ }
346
+ }
347
+
348
+ const items: CategorizedSettingItem[] = [
349
+ // 1. Retrieval & Exploration
350
+ {
351
+ category: "Retrieval & Exploration",
352
+ id: "tools",
353
+ label: "Passive Shield (Tool Gating)",
354
+ currentValue: currentConfig.retrieval.enable_tools ? "all (6 tools)" : "gated (core 3)",
355
+ values: ["gated (core 3)", "all (6 tools)"],
356
+ isGlobal: checkIsGlobal("tools"),
357
+ descriptions: {
358
+ "gated (core 3)":
359
+ "Passive Shield active: Only core tools (read, edit, code_search) are exposed. Gates exploratory tools to save ~3,400 prompt tokens per turn.",
360
+ "all (6 tools)":
361
+ "Passive Shield disabled: All 6 tools (including ast_search, get_repo_map, lsp) are exposed simultaneously. Higher token overhead.",
362
+ },
363
+ },
364
+ {
365
+ category: "Retrieval & Exploration",
366
+ id: "profile",
367
+ label: "Retrieval Engine Profile",
368
+ currentValue: currentConfig.retrieval.default_profile,
369
+ values: ["auto", "lean", "hybrid", "full", "off"],
370
+ isGlobal: checkIsGlobal("profile"),
371
+ descriptions: {
372
+ auto: "Auto profile: Dynamically selects lean (VPS), hybrid (laptop), or full (desktop) based on system specs.",
373
+ lean: "Lean profile: BM25 keyword index + AST code chunking. Zero RAM overhead, sub-millisecond retrieval, ideal for VPS and standard tasks.",
374
+ hybrid:
375
+ "Hybrid profile: BM25 keyword matching blended with Matryoshka sub-vector embeddings for balanced lexical and semantic retrieval.",
376
+ full: "Full profile: Dense 768d embeddings + BM25 keyword index. Maximum semantic recall, ideal for large workstations.",
377
+ off: "Off profile: Retrieval subsystem disabled. Searches return empty results.",
378
+ },
379
+ },
380
+
381
+ // 2. Safety & Verification
382
+ {
383
+ category: "Safety & Verification",
384
+ id: "epistemic",
385
+ label: "Epistemic Guard (Read-before-write)",
386
+ currentValue: currentConfig.safety.enable_epistemic_guard ? "enabled" : "disabled",
387
+ values: ["enabled", "disabled"],
388
+ isGlobal: checkIsGlobal("epistemic"),
389
+ descriptions: {
390
+ enabled:
391
+ "Epistemic Guard active: Enforces strict read-before-write validation, preventing hallucinated edits, missing imports, and blind patch failures.",
392
+ disabled:
393
+ "Epistemic Guard inactive: Allows unconstrained edits without prior read operations. May lead to blind mutations or syntax breakages.",
394
+ },
395
+ },
396
+ {
397
+ category: "Safety & Verification",
398
+ id: "max_lines",
399
+ label: "Output Clamping Line Limit",
400
+ currentValue: `${currentConfig.safety.max_lines} lines`,
401
+ values: ["40 lines", "100 lines", "200 lines"],
402
+ isGlobal: checkIsGlobal("max_lines"),
403
+ descriptions: {
404
+ "40 lines":
405
+ "40 lines: Conservative head/tail output clamping with 0o600 /tmp spillover logging. Maximizes token conservation on long test/build runs.",
406
+ "100 lines":
407
+ "100 lines: Balanced output ceiling. Displays up to 50 head and 50 tail lines before generating secure disk spillover logs.",
408
+ "200 lines":
409
+ "200 lines: Extended output ceiling for large compilation logs and verbose test runner summaries.",
410
+ },
411
+ },
412
+
413
+ // 3. Editing Engine
414
+ {
415
+ category: "Editing Engine",
416
+ id: "editing",
417
+ label: "Editing Mode (Smart Anchors)",
418
+ currentValue: currentConfig.editing.mode === "smart_anchor" ? "smart_anchor" : "standard",
419
+ values: ["smart_anchor", "standard"],
420
+ isGlobal: checkIsGlobal("editing"),
421
+ descriptions: {
422
+ smart_anchor:
423
+ "Smart Anchors: Deterministic Tree-sitter WASM validation (<2ms), lexical delimiter balancing, and line-hint disambiguation.",
424
+ standard:
425
+ "Standard editing: Standard exact string replacement without delimiter auto-healing or Tree-sitter syntax verification.",
426
+ },
427
+ },
428
+ {
429
+ category: "Editing Engine",
430
+ id: "read_mode",
431
+ label: "Reading Anchor Protocol",
432
+ currentValue: currentConfig.editing.read_mode,
433
+ values: ["plain", "anchored", "auto"],
434
+ isGlobal: checkIsGlobal("read_mode"),
435
+ descriptions: {
436
+ plain:
437
+ "Plain text reads: Clean, unanchored reading protocol. Reduces token consumption by ~84% compared to rigid line-hash anchor systems.",
438
+ anchored:
439
+ "Anchored reads: Injects LINE#HASH prefixes on every line for strict positional pinning. Increases context token consumption.",
440
+ auto: "Adaptive reading: Defaults to clean plain text, automatically falling back to anchored reads when resolving ambiguous edit targets.",
441
+ },
442
+ },
443
+
444
+ // 4. System Guidance & UI
445
+ {
446
+ category: "System Guidance & UI",
447
+ id: "guidance",
448
+ label: "Agent Guidance Prompt",
449
+ currentValue: currentConfig.instructions.enabled ? "enabled" : "disabled",
450
+ values: ["enabled", "disabled"],
451
+ isGlobal: checkIsGlobal("guidance"),
452
+ descriptions: {
453
+ enabled:
454
+ "Kernel guidance active: Injects empirical tool discipline, grounding rules, and search strategies into the model system prompt.",
455
+ disabled:
456
+ "Kernel guidance inactive: Omits kernel prompt injection, running the agent with default model system prompt instructions.",
457
+ },
458
+ },
459
+ {
460
+ category: "System Guidance & UI",
461
+ id: "pi_docs",
462
+ label: "Pi Docs System Guidance (pi-docs)",
463
+ currentValue: currentConfig.instructions.pi_docs ? "enabled" : "disabled",
464
+ values: ["enabled", "disabled"],
465
+ isGlobal: checkIsGlobal("pi_docs"),
466
+ descriptions: {
467
+ enabled:
468
+ "Pi docs included: Injects the complete Pi documentation guidance block into system prompt for Pi extensions, tools, and theme authoring.",
469
+ disabled:
470
+ "Pi docs omitted: Strips the ~1,200 token Pi documentation block to optimize prompt cache hit rate and token consumption.",
471
+ },
472
+ },
473
+ {
474
+ category: "System Guidance & UI",
475
+ id: "footer",
476
+ label: "Pastel Status Footer",
477
+ currentValue: currentConfig.ui.enable_pastel_footer ? "enabled" : "disabled",
478
+ values: ["enabled", "disabled"],
479
+ isGlobal: checkIsGlobal("footer"),
480
+ descriptions: {
481
+ enabled:
482
+ "Pastel footer active: Displays terminal statusline at bottom showing active model, search index state, and memory metrics.",
483
+ disabled:
484
+ "Pastel footer inactive: Disables the bottom statusline widget for an uncluttered minimal terminal workspace.",
485
+ },
486
+ },
487
+ ];
488
+
489
+ class DynamicBorder {
490
+ color: (s: string) => string;
491
+ constructor(color?: (s: string) => string) {
492
+ this.color = color || ((s) => s);
493
+ }
494
+ invalidate() {}
495
+ render(width: number): string[] {
496
+ return [this.color("─".repeat(Math.max(1, width)))];
497
+ }
498
+ }
499
+
500
+ class CategorizedSettingsList {
501
+ items: CategorizedSettingItem[];
502
+ filteredItems: CategorizedSettingItem[];
503
+ theme: any;
504
+ selectedIndex = 0;
505
+ onCancel: () => void;
506
+ searchInput: Input;
507
+ categoryOrder: string[];
508
+ private initialStates = new Map<string, { value: string; isGlobal: boolean }>();
509
+
510
+ constructor(
511
+ items: CategorizedSettingItem[],
512
+ theme: any,
513
+ onCancel: () => void,
514
+ categoryOrder: string[],
515
+ ) {
516
+ this.items = items;
517
+ this.filteredItems = items;
518
+ this.theme = theme;
519
+ this.onCancel = onCancel;
520
+ this.categoryOrder = categoryOrder;
521
+ this.searchInput = new Input();
522
+
523
+ for (const item of items) {
524
+ this.initialStates.set(item.id, {
525
+ value: item.currentValue,
526
+ isGlobal: !!item.isGlobal,
527
+ });
528
+ }
529
+ }
530
+
531
+ applyFilter(query: string) {
532
+ if (query) {
533
+ const matches = fuzzyFilter(
534
+ this.items,
535
+ query,
536
+ (item: CategorizedSettingItem) => {
537
+ const descAll = item.descriptions ? Object.values(item.descriptions).join(" ") : "";
538
+ return `${item.category} ${item.label} ${descAll} ${item.id}`;
539
+ },
540
+ );
541
+ const catGroups = new Map<string, CategorizedSettingItem[]>();
542
+ for (const item of matches) {
543
+ const list = catGroups.get(item.category) || [];
544
+ list.push(item);
545
+ catGroups.set(item.category, list);
546
+ }
547
+ const result: CategorizedSettingItem[] = [];
548
+ for (const cat of this.categoryOrder) {
549
+ const list = catGroups.get(cat);
550
+ if (list) result.push(...list);
551
+ }
552
+ this.filteredItems = result;
553
+ } else {
554
+ this.filteredItems = this.items;
555
+ }
556
+ this.selectedIndex = 0;
557
+ }
558
+
559
+ activateItem() {
560
+ const item = this.filteredItems[this.selectedIndex];
561
+ if (!item || !item.values || item.values.length === 0) return;
562
+ const curIdx = item.values.indexOf(item.currentValue);
563
+ const nextIdx = (curIdx + 1) % item.values.length;
564
+ item.currentValue = item.values[nextIdx];
565
+ }
566
+
567
+ toggleGlobalSetting() {
568
+ const item = this.filteredItems[this.selectedIndex];
569
+ if (!item) return;
570
+ item.isGlobal = !item.isGlobal;
571
+ }
572
+
573
+ closeAndApply() {
574
+ let hasChanges = false;
575
+ const globalUpdates: KernelConfigOverrides = {};
576
+ const projectUpdates: KernelConfigOverrides = {};
577
+ const revertedGlobals: Array<{ section: string; key: string }> = [];
578
+
579
+ for (const item of this.items) {
580
+ const initial = this.initialStates.get(item.id);
581
+ if (!initial) continue;
582
+
583
+ const valueChanged = item.currentValue !== initial.value;
584
+ const scopeChanged = !!item.isGlobal !== initial.isGlobal;
585
+
586
+ if (valueChanged || scopeChanged) {
587
+ hasChanges = true;
588
+ const { patch } = createPatchForSetting(item.id, item.currentValue);
589
+
590
+ if (item.isGlobal) {
591
+ mergeDeep(globalUpdates, patch);
592
+ } else {
593
+ if (initial.isGlobal) {
594
+ const meta = getSettingSectionAndKey(item.id);
595
+ if (meta) revertedGlobals.push(meta);
596
+ }
597
+ mergeDeep(projectUpdates, patch);
598
+ }
599
+ }
600
+ }
601
+
602
+ if (hasChanges) {
603
+ for (const { section, key } of revertedGlobals) {
604
+ removeGlobalKernelConfigKey(section, key);
605
+ }
606
+ if (Object.keys(globalUpdates).length > 0) {
607
+ saveGlobalKernelConfig(globalUpdates);
608
+ }
609
+ if (Object.keys(projectUpdates).length > 0) {
610
+ saveProjectKernelConfig(currentCwd, projectUpdates);
611
+ }
612
+
613
+ deps.invalidateConfig(currentCwd, ctx);
614
+ deps.clearCaches?.();
615
+ ctx.ui?.notify?.("Applied Agent Kernel configuration changes.", "info");
616
+ }
617
+
618
+ this.onCancel();
619
+ }
620
+
621
+ jumpCategory(forward = true) {
622
+ if (this.filteredItems.length === 0) return;
623
+ const curCat = this.filteredItems[this.selectedIndex]?.category;
624
+ if (forward) {
625
+ const nextIdx = this.filteredItems.findIndex(
626
+ (item, idx) => idx > this.selectedIndex && item.category !== curCat,
627
+ );
628
+ if (nextIdx !== -1) {
629
+ this.selectedIndex = nextIdx;
630
+ } else {
631
+ this.selectedIndex = 0;
632
+ }
633
+ } else {
634
+ let prevIdx = -1;
635
+ for (let i = this.selectedIndex - 1; i >= 0; i--) {
636
+ if (this.filteredItems[i].category !== curCat) {
637
+ prevIdx = i;
638
+ break;
639
+ }
640
+ }
641
+ if (prevIdx !== -1) {
642
+ const prevCat = this.filteredItems[prevIdx].category;
643
+ const firstOfPrev = this.filteredItems.findIndex((item) => item.category === prevCat);
644
+ this.selectedIndex = firstOfPrev !== -1 ? firstOfPrev : prevIdx;
645
+ } else {
646
+ this.selectedIndex = Math.max(0, this.filteredItems.length - 1);
647
+ }
648
+ }
649
+ }
650
+
651
+ handleInput(data: string) {
652
+ const kb = getKeybindings();
653
+ if (kb.matches(data, "tui.select.up")) {
654
+ if (this.filteredItems.length === 0) return;
655
+ this.selectedIndex =
656
+ this.selectedIndex === 0 ? this.filteredItems.length - 1 : this.selectedIndex - 1;
657
+ } else if (kb.matches(data, "tui.select.down")) {
658
+ if (this.filteredItems.length === 0) return;
659
+ this.selectedIndex =
660
+ this.selectedIndex === this.filteredItems.length - 1 ? 0 : this.selectedIndex + 1;
661
+ } else if (data === "\t") {
662
+ this.jumpCategory(true);
663
+ } else if (data === "\x1b[Z") {
664
+ this.jumpCategory(false);
665
+ } else if (data === "G" || data === "\x07") {
666
+ // Hotkey G toggles global application for currently selected single setting
667
+ this.toggleGlobalSetting();
668
+ } else if (
669
+ kb.matches(data, "tui.select.confirm") ||
670
+ (data === " " && this.searchInput.getValue().length === 0)
671
+ ) {
672
+ this.activateItem();
673
+ } else if (kb.matches(data, "tui.select.cancel") || data === "q") {
674
+ this.closeAndApply();
675
+ } else {
676
+ this.searchInput.handleInput(data);
677
+ this.applyFilter(this.searchInput.getValue());
678
+ }
679
+ }
680
+
681
+ invalidate() {}
682
+
683
+ render(width: number): string[] {
684
+ const lines: string[] = [];
685
+ lines.push(...this.searchInput.render(width));
686
+ lines.push("");
687
+
688
+ if (this.filteredItems.length === 0) {
689
+ lines.push(this.theme.hint(" No matching settings"));
690
+ lines.push("");
691
+ lines.push(
692
+ this.theme.hint(" Type to search · Enter/Space to change · Esc to cancel"),
693
+ );
694
+ return lines;
695
+ }
696
+
697
+ const maxLabelWidth = Math.min(
698
+ 38,
699
+ Math.max(...this.filteredItems.map((i) => visibleWidth(i.label))),
700
+ );
701
+ let currentCat: string | null = null;
702
+
703
+ for (let i = 0; i < this.filteredItems.length; i++) {
704
+ const item = this.filteredItems[i];
705
+ if (item.category !== currentCat) {
706
+ currentCat = item.category;
707
+ if (lines.length > 2) lines.push("");
708
+ lines.push(` ${this.theme.category(`[${currentCat}]`)}`);
709
+ }
710
+ const isSelected = i === this.selectedIndex;
711
+ const prefix = isSelected ? this.theme.cursor : " ";
712
+ const prefixWidth = visibleWidth(prefix);
713
+ const labelPadded =
714
+ item.label + " ".repeat(Math.max(0, maxLabelWidth - visibleWidth(item.label)));
715
+ const labelText = this.theme.label(labelPadded, isSelected);
716
+ const separator = " ";
717
+ const usedWidth = prefixWidth + maxLabelWidth + visibleWidth(separator);
718
+ const valueMaxWidth = Math.max(10, width - usedWidth - 2);
719
+ const truncatedVal = truncateToWidth(item.currentValue, valueMaxWidth, "");
720
+
721
+ // The right side of the text is YELLOW as the indicator that it is applied globally
722
+ let valueText: string;
723
+ if (item.isGlobal) {
724
+ const yellowStr = theme?.fg
725
+ ? theme.fg("warning", truncatedVal)
726
+ : `\x1b[33m${truncatedVal}\x1b[0m`;
727
+ valueText = isSelected
728
+ ? theme?.fg
729
+ ? theme.bold(yellowStr)
730
+ : `\x1b[1;33m${truncatedVal}\x1b[0m`
731
+ : yellowStr;
732
+ } else {
733
+ valueText = this.theme.value(truncatedVal, isSelected);
734
+ }
735
+
736
+ lines.push(truncateToWidth(prefix + labelText + separator + valueText, width));
737
+ }
738
+
739
+ const selectedItem = this.filteredItems[this.selectedIndex];
740
+ const currentDesc = selectedItem?.descriptions?.[selectedItem.currentValue] || "";
741
+ if (currentDesc) {
742
+ lines.push("");
743
+ const wrapped = wrapTextWithAnsi(currentDesc, width - 6);
744
+ for (const line of wrapped) {
745
+ lines.push(this.theme.description(` ${line}`));
746
+ }
747
+ }
748
+
749
+ lines.push("");
750
+ lines.push(
751
+ this.theme.hint(
752
+ " Type to search · Enter/Space cycle · G toggle global · Tab category · Esc close & apply",
753
+ ),
754
+ );
755
+ return lines;
756
+ }
757
+ }
758
+
759
+ const container = new Container();
760
+ const borderColor = (s: string) => (theme?.fg ? theme.fg("border", s) : `\x1b[38;5;240m${s}\x1b[0m`);
761
+
762
+ // Top border (identical to thinking/settings selector)
763
+ container.addChild(new DynamicBorder(borderColor));
764
+ container.addChild(new Spacer(1));
765
+ container.addChild(
766
+ new Text(
767
+ theme?.fg ? theme.fg("accent", theme.bold("Agent Kernel Settings")) : "Agent Kernel Settings",
768
+ 0,
769
+ 0,
770
+ ),
771
+ );
772
+ container.addChild(new Spacer(1));
773
+ container.addChild(
774
+ new Text(
775
+ theme?.fg
776
+ ? theme.fg(
777
+ "muted",
778
+ "Yellow text indicates global settings (~/.pi/agent/config.toml) · Press G to toggle",
779
+ )
780
+ : "Yellow text indicates global settings (~/.pi/agent/config.toml) · Press G to toggle",
781
+ 0,
782
+ 0,
783
+ ),
784
+ );
785
+ container.addChild(new Spacer(1));
786
+
787
+ const listTheme = {
788
+ category: (text: string) =>
789
+ theme?.fg ? theme.fg("accent", theme.bold(text)) : `\x1b[1;34m${text}\x1b[0m`,
790
+ label: (text: string, selected: boolean) =>
791
+ selected ? (theme?.fg ? theme.fg("accent", text) : `\x1b[36m${text}\x1b[0m`) : text,
792
+ value: (text: string, selected: boolean) =>
793
+ selected
794
+ ? theme?.fg
795
+ ? theme.fg("accent", text)
796
+ : `\x1b[36m${text}\x1b[0m`
797
+ : theme?.fg
798
+ ? theme.fg("muted", text)
799
+ : `\x1b[90m${text}\x1b[0m`,
800
+ scope: (text: string) => (theme?.fg ? theme.fg("muted", text) : `\x1b[90m${text}\x1b[0m`),
801
+ description: (text: string) => (theme?.fg ? theme.fg("dim", text) : `\x1b[2m${text}\x1b[0m`),
802
+ cursor: theme?.fg ? ` ${theme.fg("accent", "→ ")}` : " \x1b[36m→ \x1b[0m",
803
+ hint: (text: string) => (theme?.fg ? theme.fg("dim", text) : `\x1b[2m${text}\x1b[0m`),
804
+ };
805
+
806
+ const settingsList = new CategorizedSettingsList(
807
+ items,
808
+ listTheme,
809
+ () => {
810
+ done(undefined);
811
+ },
812
+ CATEGORY_ORDER,
813
+ );
814
+
815
+ container.addChild(settingsList);
816
+ // Bottom border (identical to thinking/settings selector)
817
+ container.addChild(new DynamicBorder(borderColor));
818
+
819
+ return {
820
+ render(width: number) {
821
+ return container.render(width);
822
+ },
823
+ invalidate() {
824
+ settingsList.invalidate();
825
+ },
826
+ handleInput(data: string) {
827
+ settingsList.handleInput(data);
828
+ tui.requestRender();
829
+ },
830
+ };
831
+ });
832
+ },
833
+ });
834
+ }