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