@floydous/pi-agent-kernel 0.3.3 → 0.3.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,53 +1,10 @@
1
1
  # Changelog
2
2
 
3
- ## [0.3.3] - 2026-09-20
3
+ ## [0.3.31] - 2026-09-22
4
4
 
5
5
  ### Added
6
- - **Multi-File Atomic Edits**: Extended the `edit` tool with `files: { path, search, replace, line_hint, edits }[]` payload (with resilient per-item `path` normalization in `edits`). Implemented a 2-stage atomic commit with preflight validation, duplicate path detection, in-memory snapshot backups, and automatic rollback across all targets if any file fails patch application or syntax verification.
7
- - **Batch Multi-File `read`**: Extended the `read` tool to accept `paths: string[]` (and resilient alias `path: string[]`), allowing the model to inspect multiple files in one turn while authorizing all targets in `EpistemicGuard`.
8
- - **Automatic Turn 1 Reproduction Diff Grounding**: In `before_agent_start`, automatically detects unstaged/staged git diffs and injects a sanitized, clamped (max 25 lines, 2KB hard ceiling) reproduction status into initial context with session caching, eliminating redundant Turn 1 exploratory `git status` / `git diff` commands.
6
+ - **Unified `/agent-kernel` Settings**: Added interactive modal and CLI commands (`status`, `set`, `reset`) for managing extension settings across workspace (`.pi/config.toml`) and global (`~/.pi/agent/config.toml`) scopes.
7
+ - **Spillover Hardening**: Enforced restrictive `0o600` permissions on temporary command output logs in `/tmp` with automated 20-file bounded rotation.
9
8
 
10
9
  ### Changed
11
- - **Read Tool Budgeting & Anchor Guardrails**: Bounded batch reading to 150 lines per file and a 24KB aggregate ceiling with explicit continuation markers (`[truncated: <file>, returned lines 1-150 of <N>. Continue with read(path, offset=151)]`). Added a 100-line cap on explicit `anchors: true` requests (`MAX_ANCHOR_LINES = 100`) to prevent models from generating expensive `#HASH│` line hashes on large files.
12
- - **Targeted Reading Workflow Guidance**: Updated `AGENT_KERNEL_SYS_PROMPT.md` to emphasize targeted sequential reads (`read(path, offset, limit)`) centered on search coordinates as the primary inspection workflow, reserving batch `paths` for short files or known regions.
13
- - **Search Specificity Guidance**: Directed agents toward exact identifiers, error symbols, and test phrases, preventing noisy broad single-word searches from polluting conversation context.
14
-
15
- ### Validated
16
- - Verified 38 test suites passing (`npm test`) with 0 regressions.
17
- - Multi-harness benchmarks on `cx/gpt-5.6-luna:high` across all 8 standard tasks demonstrate:
18
- - **100% Solve Rate (8 / 8 tasks solved)**.
19
- - **Aggregate task time cut in half**: **600s (10.0m) vs 1,223s (20.4m)** (-50.9% time reduction, **2.04× faster**).
20
- - **Uncached input tokens reduced by -18.4%**: **270k vs 331k** (-60.8k tokens saved across the suite).
21
- - **Tool calls reduced**: **107 calls vs 112 calls**.
22
- - Consistent speedup across all repositories: UFO (36s vs 119s), Fastify (47s vs 177s), p-limit (60s vs 176s), Ky (89s vs 253s), Zod (135s vs 212s), Hono (64s vs 96s), UUID (53s vs 64s), and Picomatch (116s vs 126s).
23
-
24
- ## [0.3.2] - 2026-09-16
25
-
26
- ### Added
27
- - **Statusline Retrieval Indicator & Extension Row Integration**: Relocated the retrieval profile tag from Line 1 to Line 2 (extension statusline via `ctx.ui.setStatus("retrieval", ...)`) alongside external extensions (such as Ponytail), preserving individual extension ANSI colors.
28
- - **Profile Semantic Glyphs**: Added distinct visual tier glyphs: `🌿 retrieval:bm25` (AST lexical), `◈ retrieval:hybrid-256d` (Matryoshka hybrid), and `🧠 retrieval:dense-768d` (Full semantic).
29
- - **Live Embedding Throughput & Stream Arrow Status**: Added real-time chunk processing throughput (`chunk/s`) with a static Stream Arrow indicator during workspace indexing (`🧠 retrieval:dense-768d ⇢ 45% (22/48 • 14.2 chunk/s)`).
30
- - **Automatic Kernel Guidance Injection**: Bundled `AGENT_KERNEL_SYS_PROMPT.md` is injected through Pi's `before_agent_start` lifecycle hook, enabled by default and configurable with `[instructions] enabled = false`.
31
- - **Benchmark Comparison Chart**: Added the latest aggregate harness comparison graphic at `static/benchmark-comparison.png` for display in the project README.
32
- - **Six-Harness Cross-Agent Benchmark**: Integrated comprehensive multi-harness comparison runner supporting Pi Kernel, Pi Vanilla, Claude Code, Codex CLI, OMP, and OpenCode across 8 real-world tasks.
33
- - **Passive Shield Architecture**: Gated exploratory tools (`ast_search`, `get_repo_map`, `lsp`) behind `enable_tools: false` / `PI_ENABLE_ALL_RETRIEVAL_TOOLS=1`, keeping the active tool interface lean (`read`, `edit`, `write`, `bash`, and compact `code_search`) to eliminate per-turn schema overhead and tool distraction loops.
34
- - **Deterministic Delimiter Auto-Healing**: Added patch-scoped lexical delimiter balancing and Tree-sitter AST repair (`MISSING` node detection) to automatically recover truncated closing braces/brackets (`})`, `};`, `]}`) pre-write.
35
- - **Line-Hinted Range Disambiguation & Multi-Block Line Deltas**: Added optional `line_hint`, `start_line`, and `end_line` parameters (supporting both camelCase and snake_case) to `edit` with sequential delta tracking to disambiguate identical search blocks without line-hash bloat.
36
- - **Capped Plain-Text Reads**: Enforced 50KB / 2,000-line caps on broad reads with continuation hints (`offset`) and oversized line detection, recording precise exposure ranges in `EpistemicGuard`.
37
- - **Model Property Aliasing & Epistemic Confirmation**: Supported model convention drift across parameter names (`search`/`replace`, `old`/`new`, `old_text`/`new_text`) and emitted concise positive confirmation strings (`Successfully applied edit to <file>.`) to prevent paranoid agent verification loops.
38
-
39
- ### Changed
40
- - Included `AGENT_KERNEL_SYS_PROMPT.md` in the published package so automatic guidance works after installation.
41
- - Added lifecycle coverage for guidance injection, duplicate prevention, and the disabled configuration path.
42
- - **Tool Description Optimization**: Completely redesigned tool descriptions for `read` and `edit` to explicitly declare clean plain-text defaults and precision parameter expectations, dropping 10k+ prompt inflation tokens on real benchmarks.
43
- - **Diagnostic Benchmark**: Cut token consumption by 50.6% (762k vs 1.54M total turn tokens) and reduced tool calls by 24.8% (112 vs 149) compared to unguided Pi Vanilla on the 8-task Luna High diagnostic suite.
44
- - **Historical Benchmark**: In the initial v0.3.1-to-v0.4.0 Passive Shield evaluation, token consumption dropped from 1,214,112 tokens down to 465,139 tokens (-61.7%) across 8 real-world repositories.
45
- - **Persistent Vector Profiles**: Preserved dimension-specific binary caches (`vectors-256d.bin`, `vectors-768d.bin`) on disk across profile switches, preventing cache loss when toggling to BM25.
46
- - **On-Demand Embedder Loading**: Removed premature model preloading on startup; weights load on-demand only when unindexed chunks are detected.
47
-
48
- ### Fixed
49
- - **Startup Background Indexing Visibility**: Fixed a bug where workspace indexing on `session_start` ran silently in the background without updating the UI statusline on cold or unindexed workspaces.
50
- - **Companion Symbol Token Inflation**: Deduplicated companion symbols and clamped surrounding context lines during targeted symbol reads to eliminate token bloat.
51
-
52
- ### Removed
53
- - Removed the obsolete `AGENT_KERNEL_PROPMPTS.md` prompt document.
10
+ - Removed repository-level `AGENTS.md` from git tracking.
package/README.md CHANGED
@@ -122,7 +122,30 @@ To install a language server directly:
122
122
 
123
123
  ---
124
124
 
125
- ### 5. Disable Pi documentation for external projects
125
+ ### 5. Unified settings & configuration (`/agent-kernel`)
126
+
127
+ Manage all Agent Kernel settings interactively or from the command line:
128
+
129
+ ```text
130
+ /agent-kernel
131
+ ```
132
+
133
+ - **Interactive TUI Modal**: Mirrors native Pi component layouts (`/thinking` and `/settings`) with 4 categorized domains (`Retrieval & Exploration`, `Safety & Verification`, `Editing Engine`, `System Guidance & UI`).
134
+ - **Interactive Search**: Type to filter across setting IDs, labels, categories, and descriptions in real time.
135
+ - **Dynamic Descriptions**: Updates in real time to explain the active option value.
136
+ - **Global Scope Toggle (`G`)**: Press `G` (or `Ctrl+G`) on any setting to toggle applying it globally (`~/.pi/agent/config.toml`) vs. workspace-local (`.pi/config.toml`). Global settings are highlighted in **yellow**.
137
+ - **Tab Navigation**: Jump between categories with `Tab` / `Shift+Tab`.
138
+
139
+ Headless CLI commands:
140
+ ```text
141
+ /agent-kernel status # Print current configuration and file paths
142
+ /agent-kernel set <key> <val> # Update a specific setting globally
143
+ /agent-kernel reset # Reset global configuration to defaults
144
+ ```
145
+
146
+ ---
147
+
148
+ ### 6. Disable Pi documentation for external projects
126
149
 
127
150
  Pi loads instructions for developing Pi extensions, skills, and themes by default. When working on standard application code, you can disable those instructions to free up prompt space:
128
151
 
package/config.toml CHANGED
@@ -28,3 +28,4 @@ enable_pastel_footer = true
28
28
 
29
29
  [instructions]
30
30
  enabled = true
31
+ pi_docs = true
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floydous/pi-agent-kernel",
3
- "version": "0.3.3",
3
+ "version": "0.3.31",
4
4
  "description": "Focused code retrieval, editing, safety checks, and language-server support for Pi.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -0,0 +1,849 @@
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
+ getGlobalConfigPath,
21
+ getGlobalRawConfig,
22
+ getProjectConfigPath,
23
+ type KernelConfig,
24
+ type KernelConfigOverrides,
25
+ type CodebaseProfile,
26
+ } from "./kernel_config";
27
+
28
+ export interface AgentKernelCommandDeps {
29
+ getConfig: (cwd: string) => KernelConfig;
30
+ invalidateConfig: (cwd: string) => void;
31
+ clearCaches?: () => void;
32
+ }
33
+
34
+ export function formatConfigDashboard(cwd: string, config: KernelConfig): string {
35
+ const globalPath = getGlobalConfigPath();
36
+ const projectPath = getProjectConfigPath(cwd);
37
+ const globalExists = fs.existsSync(globalPath);
38
+ const projectExists = projectPath ? fs.existsSync(projectPath) : false;
39
+
40
+ const lines = [
41
+ `=== Pi Agent Kernel Configuration ===`,
42
+ `Global Config : ${globalPath} [${globalExists ? "FOUND" : "DEFAULT"}]`,
43
+ `Project Config: ${projectPath ?? "none"} [${projectExists ? "ACTIVE" : "NONE"}]`,
44
+ ``,
45
+ `[Retrieval & Tools]`,
46
+ ` • Profile (Engine) : ${config.retrieval.default_profile} (lean | hybrid | full)`,
47
+ ` • Codebase Scale : ${config.retrieval.codebase_profile} (auto | light | heavy)`,
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 <lean|hybrid|full> - Retrieval engine profile" },
89
+ { value: "set codebase", label: "set codebase <auto|light|heavy> - Codebase scale profile" },
90
+ { value: "set epistemic", label: "set epistemic <on|off> - Toggle Epistemic Guard" },
91
+ { value: "set editing", label: "set editing <smart_anchor|standard> - Editing engine mode" },
92
+ { value: "set read_mode", label: "set read_mode <plain|anchored|auto> - Reading anchor mode" },
93
+ { value: "set guidance", label: "set guidance <on|off> - Toggle kernel system prompt guidance" },
94
+ { value: "set pi_docs", label: "set pi_docs <on|off> - Toggle Pi documentation guide in system prompt" },
95
+ { value: "set footer", label: "set footer <on|off> - Toggle pastel status footer" },
96
+ { value: "set max_lines", label: "set max_lines <40|100|200> - Output clamping line ceiling" },
97
+ ];
98
+
99
+ const allOptions = [...subcommands, ...keys];
100
+ const filtered = allOptions.filter((o) => o.value.startsWith(prefix.toLowerCase()));
101
+ return filtered.length > 0 ? filtered : null;
102
+ },
103
+ handler: async (args: string, ctx: ExtensionContext) => {
104
+ const raw = (args || "").trim();
105
+ const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
106
+ const config = deps.getConfig(currentCwd);
107
+
108
+ // 1. Handle CLI commands (status, set, reset)
109
+ if (raw.startsWith("status")) {
110
+ const statusText = formatConfigDashboard(currentCwd, config);
111
+ if (ctx.hasUI && ctx.ui?.notify) {
112
+ ctx.ui.notify("Displayed Agent Kernel configuration.", "info");
113
+ }
114
+ console.log("\n" + statusText + "\n");
115
+ return;
116
+ }
117
+
118
+ if (raw.startsWith("reset")) {
119
+ const globalPath = getGlobalConfigPath();
120
+ try {
121
+ if (fs.existsSync(globalPath)) {
122
+ fs.unlinkSync(globalPath);
123
+ }
124
+ deps.invalidateConfig(currentCwd);
125
+ deps.clearCaches?.();
126
+ const msg = "Reset global Agent Kernel configuration to defaults.";
127
+ ctx.ui?.notify?.(msg, "info");
128
+ console.log(msg);
129
+ } catch (e: any) {
130
+ ctx.ui?.notify?.(`Failed to reset: ${e.message}`, "error");
131
+ }
132
+ return;
133
+ }
134
+
135
+ if (raw.startsWith("set ")) {
136
+ const parts = raw.slice(4).trim().split(/\s+/);
137
+ const key = (parts[0] || "").toLowerCase();
138
+ const val = (parts[1] || "").toLowerCase();
139
+
140
+ const updates: KernelConfigOverrides = {};
141
+ let desc = "";
142
+
143
+ switch (key) {
144
+ case "tools":
145
+ case "passive_shield": {
146
+ const enable = val === "all" || val === "true" || val === "1";
147
+ updates.retrieval = { enable_tools: enable };
148
+ desc = `Passive Shield tools set to '${enable ? "all (6 tools)" : "gated (core 3 tools)"}'`;
149
+ break;
150
+ }
151
+ case "profile":
152
+ case "engine": {
153
+ if (val === "lean" || val === "hybrid" || val === "full") {
154
+ updates.retrieval = { default_profile: val };
155
+ desc = `Retrieval profile set to '${val}'`;
156
+ } else {
157
+ ctx.ui?.notify?.("Invalid profile. Options: lean | hybrid | full", "error");
158
+ return;
159
+ }
160
+ break;
161
+ }
162
+ case "codebase":
163
+ case "codebase_profile": {
164
+ if (val === "auto" || val === "light" || val === "heavy") {
165
+ updates.retrieval = { codebase_profile: val };
166
+ desc = `Codebase scale profile set to '${val}'`;
167
+ } else {
168
+ ctx.ui?.notify?.("Invalid codebase profile. Options: auto | light | heavy", "error");
169
+ return;
170
+ }
171
+ break;
172
+ }
173
+ case "epistemic":
174
+ case "epistemic_guard": {
175
+ const enable = val === "on" || val === "true" || val === "1" || val === "enabled";
176
+ updates.safety = { enable_epistemic_guard: enable };
177
+ desc = `Epistemic Guard set to ${enable ? "ENABLED" : "DISABLED"}`;
178
+ break;
179
+ }
180
+ case "editing":
181
+ case "editing_mode": {
182
+ if (val === "smart_anchor" || val === "standard") {
183
+ updates.editing = { mode: val };
184
+ desc = `Editing mode set to '${val}'`;
185
+ } else {
186
+ ctx.ui?.notify?.("Invalid editing mode. Options: smart_anchor | standard", "error");
187
+ return;
188
+ }
189
+ break;
190
+ }
191
+ case "read_mode": {
192
+ if (val === "plain" || val === "anchored" || val === "auto") {
193
+ updates.editing = { read_mode: val };
194
+ desc = `Read mode set to '${val}'`;
195
+ } else {
196
+ ctx.ui?.notify?.("Invalid read mode. Options: plain | anchored | auto", "error");
197
+ return;
198
+ }
199
+ break;
200
+ }
201
+ case "guidance":
202
+ case "instructions": {
203
+ const enable = val === "on" || val === "true" || val === "1" || val === "enabled";
204
+ updates.instructions = { enabled: enable };
205
+ desc = `Kernel guidance prompt set to ${enable ? "ENABLED" : "DISABLED"}`;
206
+ break;
207
+ }
208
+ case "pi_docs":
209
+ case "pi-docs":
210
+ case "docs": {
211
+ const enable = val === "on" || val === "true" || val === "1" || val === "enabled";
212
+ updates.instructions = { pi_docs: enable };
213
+ desc = `Pi documentation guidance set to ${enable ? "ENABLED" : "DISABLED"}`;
214
+ break;
215
+ }
216
+ case "footer":
217
+ case "pastel_footer": {
218
+ const enable = val === "on" || val === "true" || val === "1" || val === "enabled";
219
+ updates.ui = { enable_pastel_footer: enable };
220
+ desc = `Pastel status footer set to ${enable ? "ENABLED" : "DISABLED"}`;
221
+ break;
222
+ }
223
+ case "max_lines": {
224
+ const num = parseInt(val, 10);
225
+ if (!isNaN(num) && num >= 10 && num <= 1000) {
226
+ updates.safety = { max_lines: num };
227
+ desc = `Output clamping lines set to ${num}`;
228
+ } else {
229
+ ctx.ui?.notify?.("Invalid line limit (must be 10-1000)", "error");
230
+ return;
231
+ }
232
+ break;
233
+ }
234
+ default:
235
+ ctx.ui?.notify?.(`Unknown setting key: '${key}'. Run '/agent-kernel' for options.`, "error");
236
+ return;
237
+ }
238
+
239
+ saveGlobalKernelConfig(updates);
240
+ deps.invalidateConfig(currentCwd);
241
+ deps.clearCaches?.();
242
+ ctx.ui?.notify?.(`Saved to ~/.pi/agent/config.toml: ${desc}`, "info");
243
+ console.log(`[agent-kernel] ${desc} (persisted globally)`);
244
+ return;
245
+ }
246
+
247
+ // 2. Interactive TUI Settings Screen
248
+ if (ctx.mode !== "tui" || !ctx.hasUI) {
249
+ const statusText = formatConfigDashboard(currentCwd, config);
250
+ console.log("\n" + statusText + "\n");
251
+ return;
252
+ }
253
+
254
+ // TUI Interactive Modal with categorized layout and built-in search
255
+ await ctx.ui.custom((tui: any, theme: any, _kb: any, done: (res?: any) => void) => {
256
+ const currentConfig = deps.getConfig(currentCwd);
257
+
258
+ interface CategorizedSettingItem {
259
+ category: string;
260
+ id: string;
261
+ label: string;
262
+ currentValue: string;
263
+ values: string[];
264
+ descriptions: Record<string, string>;
265
+ isGlobal: boolean;
266
+ }
267
+
268
+ const CATEGORY_ORDER = [
269
+ "Retrieval & Exploration",
270
+ "Safety & Verification",
271
+ "Editing Engine",
272
+ "System Guidance & UI",
273
+ ];
274
+
275
+ const globalRaw = getGlobalRawConfig();
276
+ function checkIsGlobal(id: string): boolean {
277
+ if (id === "tools") return globalRaw.retrieval?.enable_tools !== undefined;
278
+ if (id === "profile") return globalRaw.retrieval?.default_profile !== undefined;
279
+ if (id === "codebase") return globalRaw.retrieval?.codebase_profile !== undefined;
280
+ if (id === "epistemic") return globalRaw.safety?.enable_epistemic_guard !== undefined;
281
+ if (id === "max_lines") return globalRaw.safety?.max_lines !== undefined;
282
+ if (id === "editing") return globalRaw.editing?.mode !== undefined;
283
+ if (id === "read_mode") return globalRaw.editing?.read_mode !== undefined;
284
+ if (id === "guidance") return globalRaw.instructions?.enabled !== undefined;
285
+ if (id === "pi_docs") return globalRaw.instructions?.pi_docs !== undefined;
286
+ if (id === "footer") return globalRaw.ui?.enable_pastel_footer !== undefined;
287
+ return false;
288
+ }
289
+
290
+ function createPatchForSetting(id: string, value: string): { patch: KernelConfigOverrides; desc: string } {
291
+ const patch: KernelConfigOverrides = {};
292
+ let desc = "";
293
+ if (id === "tools") {
294
+ const enable = value.startsWith("all");
295
+ patch.retrieval = { enable_tools: enable };
296
+ desc = `Passive Shield tools = ${enable ? "all (6 tools)" : "gated (core 3)"}`;
297
+ } else if (id === "profile") {
298
+ patch.retrieval = { default_profile: value as any };
299
+ desc = `Retrieval profile = ${value}`;
300
+ } else if (id === "codebase") {
301
+ patch.retrieval = { codebase_profile: value as any };
302
+ desc = `Codebase scale profile = ${value}`;
303
+ } else if (id === "epistemic") {
304
+ const enable = value === "enabled";
305
+ patch.safety = { enable_epistemic_guard: enable };
306
+ desc = `Epistemic Guard = ${enable ? "enabled" : "disabled"}`;
307
+ } else if (id === "editing") {
308
+ patch.editing = { mode: value as any };
309
+ desc = `Editing mode = ${value}`;
310
+ } else if (id === "read_mode") {
311
+ patch.editing = { read_mode: value as any };
312
+ desc = `Reading anchor protocol = ${value}`;
313
+ } else if (id === "guidance") {
314
+ const enable = value === "enabled";
315
+ patch.instructions = { enabled: enable };
316
+ desc = `Kernel guidance prompt = ${enable ? "enabled" : "disabled"}`;
317
+ } else if (id === "pi_docs") {
318
+ const enable = value === "enabled";
319
+ patch.instructions = { pi_docs: enable };
320
+ desc = `Pi documentation guidance = ${enable ? "enabled" : "disabled"}`;
321
+ } else if (id === "footer") {
322
+ const enable = value === "enabled";
323
+ patch.ui = { enable_pastel_footer: enable };
324
+ desc = `Pastel status footer = ${enable ? "enabled" : "disabled"}`;
325
+ } else if (id === "max_lines") {
326
+ const num = parseInt(value, 10);
327
+ if (!isNaN(num)) {
328
+ patch.safety = { max_lines: num };
329
+ desc = `Output clamping = ${num} lines`;
330
+ }
331
+ }
332
+ return { patch, desc };
333
+ }
334
+
335
+ function getSettingSectionAndKey(id: string): { section: string; key: string } | null {
336
+ switch (id) {
337
+ case "tools":
338
+ return { section: "retrieval", key: "enable_tools" };
339
+ case "profile":
340
+ return { section: "retrieval", key: "default_profile" };
341
+ case "codebase":
342
+ return { section: "retrieval", key: "codebase_profile" };
343
+ case "epistemic":
344
+ return { section: "safety", key: "enable_epistemic_guard" };
345
+ case "max_lines":
346
+ return { section: "safety", key: "max_lines" };
347
+ case "editing":
348
+ return { section: "editing", key: "mode" };
349
+ case "read_mode":
350
+ return { section: "editing", key: "read_mode" };
351
+ case "guidance":
352
+ return { section: "instructions", key: "enabled" };
353
+ case "pi_docs":
354
+ return { section: "instructions", key: "pi_docs" };
355
+ case "footer":
356
+ return { section: "ui", key: "enable_pastel_footer" };
357
+ default:
358
+ return null;
359
+ }
360
+ }
361
+
362
+ const items: CategorizedSettingItem[] = [
363
+ // 1. Retrieval & Exploration
364
+ {
365
+ category: "Retrieval & Exploration",
366
+ id: "tools",
367
+ label: "Passive Shield (Tool Gating)",
368
+ currentValue: currentConfig.retrieval.enable_tools ? "all (6 tools)" : "gated (core 3)",
369
+ values: ["gated (core 3)", "all (6 tools)"],
370
+ isGlobal: checkIsGlobal("tools"),
371
+ descriptions: {
372
+ "gated (core 3)":
373
+ "Passive Shield active: Only core tools (read, edit, code_search) are exposed. Gates exploratory tools to save ~3,400 prompt tokens per turn.",
374
+ "all (6 tools)":
375
+ "Passive Shield disabled: All 6 tools (including ast_search, get_repo_map, lsp) are exposed simultaneously. Higher token overhead.",
376
+ },
377
+ },
378
+ {
379
+ category: "Retrieval & Exploration",
380
+ id: "profile",
381
+ label: "Retrieval Engine Profile",
382
+ currentValue: currentConfig.retrieval.default_profile,
383
+ values: ["lean", "hybrid", "full"],
384
+ isGlobal: checkIsGlobal("profile"),
385
+ descriptions: {
386
+ lean: "Lean profile: BM25 keyword index + AST code chunking. Zero RAM overhead, sub-millisecond retrieval, ideal for VPS and standard tasks.",
387
+ hybrid:
388
+ "Hybrid profile: BM25 keyword matching blended with Matryoshka sub-vector embeddings for balanced lexical and semantic retrieval.",
389
+ full: "Full profile: Dense 768-dim embeddings with deep semantic chunking. Maximizes recall on complex multi-repository conceptual queries.",
390
+ },
391
+ },
392
+ {
393
+ category: "Retrieval & Exploration",
394
+ id: "codebase",
395
+ label: "Codebase Scale Profile",
396
+ currentValue: currentConfig.retrieval.codebase_profile,
397
+ values: ["auto", "light", "heavy"],
398
+ isGlobal: checkIsGlobal("codebase"),
399
+ descriptions: {
400
+ auto: "Auto scale mode: Automatically analyzes repository file count and git metrics to dynamically size AST repo-mapping token budget.",
401
+ light:
402
+ "Light scale mode: Enforces minimal indexing and suppresses automatic repo-map injection for small repos and resource-tight environments.",
403
+ heavy:
404
+ "Heavy scale mode: Always injects full PageRank AST repository map for large multi-package enterprise codebases.",
405
+ },
406
+ },
407
+
408
+ // 2. Safety & Verification
409
+ {
410
+ category: "Safety & Verification",
411
+ id: "epistemic",
412
+ label: "Epistemic Guard (Read-before-write)",
413
+ currentValue: currentConfig.safety.enable_epistemic_guard ? "enabled" : "disabled",
414
+ values: ["enabled", "disabled"],
415
+ isGlobal: checkIsGlobal("epistemic"),
416
+ descriptions: {
417
+ enabled:
418
+ "Epistemic Guard active: Enforces strict read-before-write validation, preventing hallucinated edits, missing imports, and blind patch failures.",
419
+ disabled:
420
+ "Epistemic Guard inactive: Allows unconstrained edits without prior read operations. May lead to blind mutations or syntax breakages.",
421
+ },
422
+ },
423
+ {
424
+ category: "Safety & Verification",
425
+ id: "max_lines",
426
+ label: "Output Clamping Line Limit",
427
+ currentValue: `${currentConfig.safety.max_lines} lines`,
428
+ values: ["40 lines", "100 lines", "200 lines"],
429
+ isGlobal: checkIsGlobal("max_lines"),
430
+ descriptions: {
431
+ "40 lines":
432
+ "40 lines: Conservative head/tail output clamping with 0o600 /tmp spillover logging. Maximizes token conservation on long test/build runs.",
433
+ "100 lines":
434
+ "100 lines: Balanced output ceiling. Displays up to 50 head and 50 tail lines before generating secure disk spillover logs.",
435
+ "200 lines":
436
+ "200 lines: Extended output ceiling for large compilation logs and verbose test runner summaries.",
437
+ },
438
+ },
439
+
440
+ // 3. Editing Engine
441
+ {
442
+ category: "Editing Engine",
443
+ id: "editing",
444
+ label: "Editing Mode (Smart Anchors)",
445
+ currentValue: currentConfig.editing.mode === "smart_anchor" ? "smart_anchor" : "standard",
446
+ values: ["smart_anchor", "standard"],
447
+ isGlobal: checkIsGlobal("editing"),
448
+ descriptions: {
449
+ smart_anchor:
450
+ "Smart Anchors: Deterministic Tree-sitter WASM validation (<2ms), lexical delimiter balancing, and line-hint disambiguation.",
451
+ standard:
452
+ "Standard editing: Standard exact string replacement without delimiter auto-healing or Tree-sitter syntax verification.",
453
+ },
454
+ },
455
+ {
456
+ category: "Editing Engine",
457
+ id: "read_mode",
458
+ label: "Reading Anchor Protocol",
459
+ currentValue: currentConfig.editing.read_mode,
460
+ values: ["plain", "anchored", "auto"],
461
+ isGlobal: checkIsGlobal("read_mode"),
462
+ descriptions: {
463
+ plain:
464
+ "Plain text reads: Clean, unanchored reading protocol. Reduces token consumption by ~84% compared to rigid line-hash anchor systems.",
465
+ anchored:
466
+ "Anchored reads: Injects LINE#HASH prefixes on every line for strict positional pinning. Increases context token consumption.",
467
+ auto: "Adaptive reading: Defaults to clean plain text, automatically falling back to anchored reads when resolving ambiguous edit targets.",
468
+ },
469
+ },
470
+
471
+ // 4. System Guidance & UI
472
+ {
473
+ category: "System Guidance & UI",
474
+ id: "guidance",
475
+ label: "Agent Guidance Prompt",
476
+ currentValue: currentConfig.instructions.enabled ? "enabled" : "disabled",
477
+ values: ["enabled", "disabled"],
478
+ isGlobal: checkIsGlobal("guidance"),
479
+ descriptions: {
480
+ enabled:
481
+ "Kernel guidance active: Injects empirical tool discipline, grounding rules, and search strategies into the model system prompt.",
482
+ disabled:
483
+ "Kernel guidance inactive: Omits kernel prompt injection, running the agent with default model system prompt instructions.",
484
+ },
485
+ },
486
+ {
487
+ category: "System Guidance & UI",
488
+ id: "pi_docs",
489
+ label: "Pi Docs System Guidance (pi-docs)",
490
+ currentValue: currentConfig.instructions.pi_docs ? "enabled" : "disabled",
491
+ values: ["enabled", "disabled"],
492
+ isGlobal: checkIsGlobal("pi_docs"),
493
+ descriptions: {
494
+ enabled:
495
+ "Pi docs included: Injects the complete Pi documentation guidance block into system prompt for Pi extensions, tools, and theme authoring.",
496
+ disabled:
497
+ "Pi docs omitted: Strips the ~1,200 token Pi documentation block to optimize prompt cache hit rate and token consumption.",
498
+ },
499
+ },
500
+ {
501
+ category: "System Guidance & UI",
502
+ id: "footer",
503
+ label: "Pastel Status Footer",
504
+ currentValue: currentConfig.ui.enable_pastel_footer ? "enabled" : "disabled",
505
+ values: ["enabled", "disabled"],
506
+ isGlobal: checkIsGlobal("footer"),
507
+ descriptions: {
508
+ enabled:
509
+ "Pastel footer active: Displays terminal statusline at bottom showing active model, search index state, and memory metrics.",
510
+ disabled:
511
+ "Pastel footer inactive: Disables the bottom statusline widget for an uncluttered minimal terminal workspace.",
512
+ },
513
+ },
514
+ ];
515
+
516
+ class DynamicBorder {
517
+ color: (s: string) => string;
518
+ constructor(color?: (s: string) => string) {
519
+ this.color = color || ((s) => s);
520
+ }
521
+ invalidate() {}
522
+ render(width: number): string[] {
523
+ return [this.color("─".repeat(Math.max(1, width)))];
524
+ }
525
+ }
526
+
527
+ class CategorizedSettingsList {
528
+ items: CategorizedSettingItem[];
529
+ filteredItems: CategorizedSettingItem[];
530
+ theme: any;
531
+ selectedIndex = 0;
532
+ onCancel: () => void;
533
+ searchInput: Input;
534
+ categoryOrder: string[];
535
+
536
+ constructor(
537
+ items: CategorizedSettingItem[],
538
+ theme: any,
539
+ onCancel: () => void,
540
+ categoryOrder: string[],
541
+ ) {
542
+ this.items = items;
543
+ this.filteredItems = items;
544
+ this.theme = theme;
545
+ this.onCancel = onCancel;
546
+ this.categoryOrder = categoryOrder;
547
+ this.searchInput = new Input();
548
+ }
549
+
550
+ applyFilter(query: string) {
551
+ if (query) {
552
+ const matches = fuzzyFilter(
553
+ this.items,
554
+ query,
555
+ (item: CategorizedSettingItem) => {
556
+ const descAll = item.descriptions ? Object.values(item.descriptions).join(" ") : "";
557
+ return `${item.category} ${item.label} ${descAll} ${item.id}`;
558
+ },
559
+ );
560
+ const catGroups = new Map<string, CategorizedSettingItem[]>();
561
+ for (const item of matches) {
562
+ const list = catGroups.get(item.category) || [];
563
+ list.push(item);
564
+ catGroups.set(item.category, list);
565
+ }
566
+ const result: CategorizedSettingItem[] = [];
567
+ for (const cat of this.categoryOrder) {
568
+ const list = catGroups.get(cat);
569
+ if (list) result.push(...list);
570
+ }
571
+ this.filteredItems = result;
572
+ } else {
573
+ this.filteredItems = this.items;
574
+ }
575
+ this.selectedIndex = 0;
576
+ }
577
+
578
+ activateItem() {
579
+ const item = this.filteredItems[this.selectedIndex];
580
+ if (!item || !item.values || item.values.length === 0) return;
581
+ const curIdx = item.values.indexOf(item.currentValue);
582
+ const nextIdx = (curIdx + 1) % item.values.length;
583
+ item.currentValue = item.values[nextIdx];
584
+
585
+ const { patch } = createPatchForSetting(item.id, item.currentValue);
586
+ if (item.isGlobal) {
587
+ saveGlobalKernelConfig(patch);
588
+ ctx.ui?.notify?.(
589
+ `Saved '${item.label}' = '${item.currentValue}' globally (~/.pi/agent/config.toml)`,
590
+ "info",
591
+ );
592
+ } else {
593
+ saveProjectKernelConfig(currentCwd, patch);
594
+ ctx.ui?.notify?.(
595
+ `Saved '${item.label}' = '${item.currentValue}' to project (.pi/config.toml)`,
596
+ "info",
597
+ );
598
+ }
599
+ deps.invalidateConfig(currentCwd);
600
+ deps.clearCaches?.();
601
+ }
602
+
603
+ toggleGlobalSetting() {
604
+ const item = this.filteredItems[this.selectedIndex];
605
+ if (!item) return;
606
+
607
+ const meta = getSettingSectionAndKey(item.id);
608
+ if (!meta) return;
609
+
610
+ if (item.isGlobal) {
611
+ // Revert/remove single setting from global config
612
+ removeGlobalKernelConfigKey(meta.section, meta.key);
613
+ item.isGlobal = false;
614
+ deps.invalidateConfig(currentCwd);
615
+ deps.clearCaches?.();
616
+
617
+ ctx.ui?.notify?.(
618
+ `Reverted '${item.label}' from global (now using workspace/default)`,
619
+ "info",
620
+ );
621
+ } else {
622
+ // Apply single setting to global config
623
+ const { patch } = createPatchForSetting(item.id, item.currentValue);
624
+ saveGlobalKernelConfig(patch);
625
+ item.isGlobal = true;
626
+ deps.invalidateConfig(currentCwd);
627
+ deps.clearCaches?.();
628
+
629
+ ctx.ui?.notify?.(
630
+ `Applied '${item.label}' = '${item.currentValue}' globally to ~/.pi/agent/config.toml`,
631
+ "info",
632
+ );
633
+ }
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")) {
689
+ this.onCancel();
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 change · G toggle global · Tab category · Esc cancel",
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);
826
+ },
827
+ CATEGORY_ORDER,
828
+ );
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
+ });
847
+ },
848
+ });
849
+ }
@@ -1,2 +1,3 @@
1
1
  export * from "./toml";
2
2
  export * from "./kernel_config";
3
+ export * from "./agent_kernel_command";
@@ -54,6 +54,7 @@ export interface UiConfig {
54
54
 
55
55
  export interface InstructionsConfig {
56
56
  enabled: boolean;
57
+ pi_docs: boolean;
57
58
  }
58
59
 
59
60
  export interface KernelConfig {
@@ -99,6 +100,7 @@ const DEFAULT_CONFIG: KernelConfig = {
99
100
  },
100
101
  instructions: {
101
102
  enabled: true,
103
+ pi_docs: true,
102
104
  },
103
105
  };
104
106
 
@@ -235,6 +237,77 @@ export function saveGlobalKernelConfig(updates: KernelConfigOverrides): void {
235
237
  writeFileSyncAtomic(globalPath, tomlString);
236
238
  }
237
239
 
240
+ /**
241
+ * Remove a single setting key from global configuration file (~/.pi/agent/config.toml)
242
+ */
243
+ export function removeGlobalKernelConfigKey(section: string, key: string): void {
244
+ const globalPath = getGlobalConfigPath();
245
+ if (!fs.existsSync(globalPath)) return;
246
+
247
+ try {
248
+ const existing: any = parseToml(fs.readFileSync(globalPath, "utf-8"));
249
+ if (existing && existing[section] && existing[section][key] !== undefined) {
250
+ delete existing[section][key];
251
+ if (Object.keys(existing[section]).length === 0) {
252
+ delete existing[section];
253
+ }
254
+ const tomlString = stringifyToml(existing);
255
+ writeFileSyncAtomic(globalPath, tomlString);
256
+ }
257
+ } catch (e) {
258
+ kernelDebug(e);
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Read raw global configuration TOML if it exists
264
+ */
265
+ export function getGlobalRawConfig(): Record<string, any> {
266
+ const globalPath = getGlobalConfigPath();
267
+ if (fs.existsSync(globalPath)) {
268
+ try {
269
+ return parseToml(fs.readFileSync(globalPath, "utf-8")) as any;
270
+ } catch (e) {
271
+ kernelDebug(e);
272
+ }
273
+ }
274
+ return {};
275
+ }
276
+
277
+ /**
278
+ * Determine the target path for saving project-local configuration
279
+ */
280
+ export function getTargetProjectConfigPath(cwd = process.cwd()): string {
281
+ const existing = getProjectConfigPath(cwd);
282
+ if (existing) return existing;
283
+ return path.join(path.resolve(cwd), ".pi", "config.toml");
284
+ }
285
+
286
+ /**
287
+ * Save user overrides to project-local configuration file (.pi/config.toml)
288
+ */
289
+ export function saveProjectKernelConfig(cwd: string, updates: KernelConfigOverrides): string {
290
+ const projectPath = getTargetProjectConfigPath(cwd);
291
+ const parentDir = path.dirname(projectPath);
292
+ if (!fs.existsSync(parentDir)) {
293
+ fs.mkdirSync(parentDir, { recursive: true });
294
+ }
295
+
296
+ let existing: Record<string, TomlValue> = {};
297
+ if (fs.existsSync(projectPath)) {
298
+ try {
299
+ existing = parseToml(fs.readFileSync(projectPath, "utf-8"));
300
+ } catch (e) {
301
+ kernelDebug(e);
302
+ }
303
+ }
304
+
305
+ mergeDeep(existing, updates);
306
+ const tomlString = stringifyToml(existing);
307
+ writeFileSyncAtomic(projectPath, tomlString);
308
+ return projectPath;
309
+ }
310
+
238
311
  function mergeDeep(target: any, source: any) {
239
312
  if (!source || typeof source !== "object") return;
240
313
  for (const key of Object.keys(source)) {
package/src/index.ts CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  globalEpistemicGuard,
12
12
  resolveUserPath,
13
13
  } from "./safety/epistemic_guard";
14
- import { loadKernelConfig } from "./config";
14
+ import { loadKernelConfig, registerAgentKernelCommand } from "./config";
15
15
  import { kernelDebug } from "./safety/kernel_debug";
16
16
  import { registerRepoMapTool } from "./tools/repo_map_tool";
17
17
  import { registerAstSearchTool } from "./tools/ast_search_tool";
@@ -66,7 +66,10 @@ function withoutPiDocumentation(systemPrompt: string): string {
66
66
  }
67
67
 
68
68
  function piDocsEnabled(ctx: any): boolean {
69
- return piDocsEnabledBySession.get(getSessionId(ctx)) ?? true;
69
+ const sessionVal = piDocsEnabledBySession.get(getSessionId(ctx));
70
+ if (sessionVal !== undefined) return sessionVal;
71
+ const cwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
72
+ return loadKernelConfig(cwd).instructions.pi_docs ?? true;
70
73
  }
71
74
 
72
75
  function loadKernelGuidance(): string {
@@ -255,6 +258,16 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
255
258
  }
256
259
  };
257
260
 
261
+ registerAgentKernelCommand(pi, {
262
+ getConfig,
263
+ invalidateConfig: (cwd) => {
264
+ configByWorkspace.delete(path.resolve(cwd));
265
+ },
266
+ clearCaches: () => {
267
+ cachedRepoMap = "";
268
+ },
269
+ });
270
+
258
271
  pi.registerCommand("pi-docs", {
259
272
  description: "Toggle Pi documentation guidance in the system prompt",
260
273
  getArgumentCompletions: (prefix: string) => {
@@ -55,6 +55,10 @@ export function isDiscoveryCommand(command: string): boolean {
55
55
  * Clamps output lines horizontally and vertically to prevent context bloat
56
56
  * from single-line minified files, lockfiles, or massive multi-file matches.
57
57
  * Preserves 100% of raw output in an OS temp spillover file when truncation occurs.
58
+ *
59
+ * Adheres strictly to the language-agnostic conservative head/tail architecture:
60
+ * never uses language-specific regex guessing to discard intermediate lines,
61
+ * guaranteeing zero false-negative diagnostic suppression across arbitrary runtimes.
58
62
  */
59
63
  export function clampCommandOutput(
60
64
  rawText: string,
@@ -136,14 +140,16 @@ export function clampCommandOutput(
136
140
  if (files.length > 20) {
137
141
  const toDelete = files.slice(0, files.length - 20);
138
142
  for (const item of toDelete) {
139
- try { fs.unlinkSync(item.full); } catch {}
143
+ try {
144
+ fs.unlinkSync(item.full);
145
+ } catch {}
140
146
  }
141
147
  }
142
148
  } catch {}
143
149
 
144
150
  const hash = crypto.randomBytes(4).toString("hex");
145
151
  const candidatePath = path.join(tempDir, `pi_bash_spillover_${hash}.log`);
146
- fs.writeFileSync(candidatePath, rawText, "utf8");
152
+ fs.writeFileSync(candidatePath, rawText, { encoding: "utf8", mode: 0o600 });
147
153
  spilloverPath = candidatePath;
148
154
  } catch (e) {
149
155
  kernelDebug(e);
@@ -156,7 +162,11 @@ export function clampCommandOutput(
156
162
  if (line.length > maxLineLength) {
157
163
  let end = Math.max(10, maxLineLength - 60);
158
164
  // Do not split a valid UTF-16 surrogate pair.
159
- if (/[\uD800-\uDBFF]/.test(line.charAt(end - 1)) && /[\uDC00-\uDFFF]/.test(line.charAt(end))) end--;
165
+ if (
166
+ /[\uD800-\uDBFF]/.test(line.charAt(end - 1)) &&
167
+ /[\uDC00-\uDFFF]/.test(line.charAt(end))
168
+ )
169
+ end--;
160
170
  const kept = line.slice(0, end);
161
171
  const omitted = line.length - kept.length;
162
172
  return `${kept}... <line ${idx + 1} truncated: ${omitted.toLocaleString()} chars omitted>`;
@@ -205,15 +215,26 @@ export function clampCommandOutput(
205
215
  }
206
216
 
207
217
  if (Buffer.byteLength(resultText + footer, "utf8") > maxTotalBytes) {
208
- const marker = clampedLines.findIndex(line => /^\n\[\.\.\. /.test(line));
218
+ const marker = clampedLines.findIndex((line) => /^\n\[\.\.\. /.test(line));
209
219
  if (marker !== -1) clampedLines.splice(marker, 1);
210
220
  }
211
221
  // Enforce the byte budget on the complete returned text: retain whole lines,
212
222
  // removing from the middle first so head and tail context survive.
213
- while (clampedLines.length && Buffer.byteLength(clampedLines.join("\n") + footer, "utf8") > maxTotalBytes) {
214
- const [removed] = clampedLines.splice(Math.floor(clampedLines.length / 2), 1);
223
+ while (
224
+ clampedLines.length &&
225
+ Buffer.byteLength(clampedLines.join("\n") + footer, "utf8") > maxTotalBytes
226
+ ) {
227
+ const [removed] = clampedLines.splice(
228
+ Math.floor(clampedLines.length / 2),
229
+ 1,
230
+ );
215
231
  if (!removed.startsWith("\n[... ")) shownLines--;
216
- footer = "\n\n[Truncated: " + shownLines + "/" + totalLines + " lines." +
232
+ footer =
233
+ "\n\n[Truncated: " +
234
+ shownLines +
235
+ "/" +
236
+ totalLines +
237
+ " lines." +
217
238
  (spilloverPath ? " Full: " + spilloverPath + "]" : "]");
218
239
  }
219
240
  resultText = clampedLines.join("\n") + footer;