@floydous/pi-agent-kernel 0.5.0 → 0.6.1

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