@floydous/pi-agent-kernel 0.6.1 → 0.6.2

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,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.6.2] - 2026-12-03
4
+
5
+ ### Added
6
+
7
+ - **`syntax_gate` CLI & Settings Modal Support**: Exposed `editing.syntax_gate` (`warn`, `block`, `off`) in `/agent-kernel set syntax_gate`, the `/agent-kernel` Kernel Settings tab, and `config.example.toml`.
8
+ - **Hardening & Correctness Regression Suite**: Added `tests/audit-verification/hardening_regressions.test.ts` covering Epistemic Guard Tier-2 search-only blocks, shell paging/redirection parsing, atomic evidence batching, cached footer/`/pi-docs` config, warm-start snapshot reuse, embedder retry cooldown, edit ambiguity line numbers, `read` argument coercion, `code_search` budget caps, and single-parse JS/TS test chunking.
9
+
10
+ ### Changed
11
+
12
+ - **Host-Provided Peer Dependencies**: Moved `typebox` out of `dependencies` and declared `@earendil-works/pi-coding-agent` and `typebox` in `peerDependencies` with `"*"` ranges (keeping `typebox` in `devDependencies` for local development and tests) to satisfy Pi's extension loader and prevent duplicate runtime modules.
13
+ - **Bounded `code_search` `mode: "full"` Output**: Capped `code_search` `mode: "full"` output at 12 KB (`FULL_OUTPUT_BUDGET`) and summarized bonus `separateTests` test hits in `mode: "full"` when tests are not targeted.
14
+ - **Single-Pass JS/TS Test Chunking & Warm-Start Indexing**: Moved JS/TS test block extraction into `TreeSitterEngine.extractTags()` under a `finally { tree.delete(); }` guard (eliminating duplicate parsing and WASM tree leaks), skipped unused AST reference collection during chunking, reused warm-start search snapshots, wrote compact `index.json`, and updated `fileBytes` incrementally in `updateFile()`.
15
+ - **README Refresh**: Updated `README.md` with light and dark brand marks (`static/mark-light.svg`, `static/mark-dark.svg`) and a refreshed layout.
16
+
17
+ ### Fixed
18
+
19
+ - **Epistemic Guard & Shell Evidence Parsing**: Prevented search-only evidence from bypassing Tier-2 edit checks, hardened shell flag, POSIX `head`/`tail`, compound `sed`, and redirection parsing, and batched multi-file evidence persistence atomically via `withBatchPersist`.
20
+ - **`code_search` `mixed`-Mode Header Clipping**: Subtracted the `mixed`-mode header prefix length from the 8 KB `AUTO_OUTPUT_BUDGET` before budgeting so `decorateResult()` no longer clips trailing summaries and wipes intact preview `visibleRanges`.
21
+ - **Edit, Read, Verification, and Embedder Resilience**: Reported candidate line numbers on ambiguous edit matches, coerced stringified numeric `offset`/`limit` in `read` `prepareArguments()`, plumbed `exec_timeout_ms` into post-edit syntax verification, used cached trusted config in footer rendering and `/pi-docs`, and reset `LocalEmbedder`'s `initPromise` with a retry cooldown after initialization failures.
22
+
3
23
  ## [0.6.1] - 2026-11-21
4
24
 
5
25
  ### Added
package/README.md CHANGED
@@ -1,97 +1,107 @@
1
- # pi-agent-kernel
2
-
3
- ![Comparison Demonstration](https://raw.githubusercontent.com/floydous/pi-agent-kernel/master/static/comparison.gif)
4
-
5
- Coding agents waste context when they read entire files to inspect one function, dump thousands of lines of terminal output, or rewrite whole files for small edits. `pi-agent-kernel` is an extension for Pi that keeps sessions compact by clamping command outputs, capping file reads, and verifying edits before saving.
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="static/mark-dark.svg" />
4
+ <source media="(prefers-color-scheme: light)" srcset="static/mark-light.svg" />
5
+ <img src="static/mark-light.svg" width="56" height="46" alt="pi-agent-kernel mark" />
6
+ </picture>
7
+ </p>
8
+
9
+ <h1 align="center">pi-agent-kernel</h1>
10
+
11
+ <p align="center">
12
+ A <a href="https://github.com/badlogic/pi-mono">Pi</a> extension that replaces the default file, edit, and shell tools with source-first code search, read-before-edit checks, and failure-focused output.
13
+ </p>
14
+
15
+ <p align="center">
16
+ <a href="https://www.npmjs.com/package/@floydous/pi-agent-kernel"><img src="https://img.shields.io/npm/v/@floydous/pi-agent-kernel?style=flat-square&color=15803d&labelColor=18181b" alt="npm version" /></a>
17
+ <a href="https://github.com/floydous/pi-agent-kernel/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/floydous/pi-agent-kernel/ci.yml?branch=master&style=flat-square&label=ci&labelColor=18181b" alt="CI status" /></a>
18
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-ISC-3f3f46?style=flat-square&labelColor=18181b" alt="ISC license" /></a>
19
+ <img src="https://img.shields.io/badge/node-%3E%3D20-3f3f46?style=flat-square&labelColor=18181b" alt="Node >= 20" />
20
+ </p>
21
+
22
+ <p align="center">
23
+ <a href="#what-it-does">What it does</a> ·
24
+ <a href="#quick-start">Quick start</a> ·
25
+ <a href="#configuration">Configuration</a> ·
26
+ <a href="#tools">Tools</a> ·
27
+ <a href="#documentation">Docs</a>
28
+ </p>
29
+
30
+ <p align="center">
31
+ <img src="static/comparison.gif" alt="Side-by-side terminal recording comparing Pi, OMP, and Pi with Agent Kernel on the same codebase question" />
32
+ </p>
33
+
34
+ <p align="center">
35
+ <sub>Same codebase question across three sessions: unguided runs spend turns listing folders and grepping, while Pi with Agent Kernel finds the file with <code>code_search</code> and reads the exact lines.</sub>
36
+ </p>
6
37
 
7
38
  ---
8
39
 
9
- ## Benchmarks
40
+ ## What it does
41
+
42
+ `pi-agent-kernel` is a runtime harness extension for the Pi coding agent. Without guardrails, coding agents often grep into test files instead of source implementations, patch lines they only skimmed, or lose the actual assertion failure inside thousands of lines of build logs.
10
43
 
11
- Evaluating 6 coding agent harnesses across 8 bug fixes (`hono`, `ky`, `zod`, `ufo`, `picomatch`, `fastify`, `uuid`, `p-limit`) with `cx/gpt-6-luna-high` (OmniRoute, concurrency 4, 360s timeout). Pi harnesses report mean values across 3 repeated runs (N=3):
44
+ `pi-agent-kernel` fixes those failure modes at the tool layer:
12
45
 
13
- ![Benchmark Comparison](static/benchmark-comparison.png)
46
+ - Local `code_search` indexes functions and classes with Tree-sitter across 14 languages and ranks source code ahead of tests in about 20 ms.
47
+ - `edit` blocks changes to lines the agent has not read yet, runs an immediate syntax check after saving, and rolls back multi-file patches atomically on failure.
48
+ - `bash` trims long output down to the command start, exit summary, and failing assertion lines, while `read` streams large spillover logs without loading the whole file.
49
+ - `/agent-kernel` adds an in-Pi settings screen to toggle guards, switch between keyword and semantic search, and exclude generated folders from indexing.
14
50
 
15
51
  ---
16
52
 
17
53
  ## Quick start
18
54
 
19
- ### 1. Install
20
-
21
- Install the extension through Pi's package manager:
55
+ Requires [Pi](https://github.com/badlogic/pi-mono) and Node.js 20 or newer.
22
56
 
23
57
  ```bash
24
- # Global install
25
- pi install npm:@floydous/pi-agent-kernel
26
-
27
- # Local install for the current workspace only
28
- pi install -l npm:@floydous/pi-agent-kernel
58
+ pi install npm:@floydous/pi-agent-kernel # global install
59
+ pi install -l npm:@floydous/pi-agent-kernel # project-local install
29
60
  ```
30
61
 
31
- Restart Pi or start a new session.
62
+ 1. **Restart Pi** (or start a new session). Background keyword indexing (`lean` profile) starts automatically on launch.
63
+ 2. **Run `/agent-kernel status`** to verify the extension loaded and check where global (`~/.pi/agent/config.toml`) and project (`.pi/config.toml`) settings live.
64
+ 3. **Optional setup:** run `/agent-kernel engine` to enable local semantic embeddings (`full` profile, ~147 MB download on first use), `/agent-kernel scope` to uncheck noisy folders from indexing, or `/pi-docs off` when working outside Pi extension projects.
32
65
 
33
66
  ---
34
67
 
35
- ### 2. Settings and configuration (`/agent-kernel`)
68
+ ## Configuration
36
69
 
37
- Run `/agent-kernel` to open the unified 3-tab interactive controller:
70
+ Run `/agent-kernel` in Pi to open the three-tab settings UI (Kernel Settings, Retrieval Engine, and File Index Scope), or configure it from the prompt:
38
71
 
39
72
  ```text
40
- /agent-kernel
73
+ /agent-kernel status # Active settings and config paths
74
+ /agent-kernel engine # Open the Retrieval Engine tab
75
+ /agent-kernel scope # Open the File Index Scope tab
76
+ /agent-kernel set <key> <val> # Set a global option (e.g. set profile full, set max_lines 200)
77
+ /agent-kernel reset # Reset global settings to defaults
41
78
  ```
42
79
 
43
- The modal lets you manage:
44
- - **`[1] Kernel Settings`**: Toggle the Epistemic Guard, reading anchor modes, output clamping ceilings (`40`, `100`, `200` lines), dot normalization, and prompt guidance.
45
- - **`[2] Retrieval Engine`**: Configure the code search profile (`auto`, `lean`, `full`, `off`) and trigger full workspace re-indexing.
46
- - **`[3] File Index Scope`**: Browse the repository tree, toggle folder and file exclusions, and inspect live code chunk counts.
47
-
48
- You can also manage settings and retrieval directly from the command line:
49
- ```text
50
- /agent-kernel status # Print current configuration and file locations
51
- /agent-kernel engine # Open directly to Retrieval Engine controls
52
- /agent-kernel scope # Open directly to File Index Scope tree
53
- /agent-kernel reindex # Force full workspace re-indexing
54
- /agent-kernel set <key> <val> # Update a setting (e.g. set profile full, set max_lines 200)
55
- /agent-kernel reset # Reset global configuration to defaults
56
- ```
57
-
58
- ---
80
+ Use `/pi-docs off` (or `/pi-docs on`) to hide Pi's built-in extension manual when working on ordinary repositories.
59
81
 
60
- ### 3. Retrieval engine profiles
61
-
62
- `pi-agent-kernel` includes an in-memory retrieval engine for code search:
63
-
64
- - `lean` (default): AST-indexed BM25 keyword search with sub-millisecond retrieval and zero extra memory footprint.
65
- - `full`: Lexical BM25 search fused with 768-dimension code embeddings from `Alibaba-NLP/gte-modernbert-base` (~147 MB, downloaded on first use) via Reciprocal Rank Fusion. `hybrid` is accepted as an alias.
66
- - `auto`: Automatically selects `lean` on machines with fewer than 4 CPU cores and `full` on machines with 4 or more cores.
67
- - `off`: Disables local indexing completely.
68
-
69
- ---
70
-
71
- ### 4. Disable Pi documentation for external projects
72
-
73
- Pi injects reference documentation for building Pi extensions into every session. When working on ordinary codebases, you can hide those docs to save prompt space:
74
-
75
- ```text
76
- /pi-docs off
77
- ```
82
+ ### Retrieval profiles
78
83
 
79
- Use `/pi-docs on` when returning to work on Pi extensions.
84
+ | Profile | Engine | Use when |
85
+ | --- | --- | --- |
86
+ | `lean` (default) | AST-chunked BM25 keyword search | You want fast startup with zero model downloads |
87
+ | `full` | BM25 merged with `gte-modernbert-base` vectors via RRF (`hybrid` alias) | You are searching by behavior without knowing symbol names |
88
+ | `auto` | `lean` below 4 CPU cores, `full` on 4+ cores | You want profile selection tied to machine hardware |
89
+ | `off` | Disables indexing (`code_search` tells the model to use `rg`) | You want to rely on shell search only |
80
90
 
81
91
  ---
82
92
 
83
- ## Tool reference
93
+ ## Tools
84
94
 
85
- | Tool | Description |
86
- |---|---|
87
- | `read` | Reads file contents with 50 KB / 2,000-line caps and bounded line-windowing (`offset`/`limit`). |
88
- | `edit` | Applies search-and-replace patches with automatic delimiter healing and optional `line_hint` line coordinates. |
89
- | `write` | Creates new files or replaces complete files. |
90
- | `bash` | Runs shell commands with clamped output and spillover logging. |
91
- | `code_search` | Combines AST BM25 keyword matching and semantic embeddings with symbol breadcrumbs. |
95
+ | Tool | Role | Key behavior |
96
+ | --- | --- | --- |
97
+ | `code_search` | Local code search | Ranks source chunks ahead of tests; supports `mode` (`auto`, `full`, `preview`, `summary`), path filters, and `rrf_k` (1-200). |
98
+ | `read` | Bounded file reader | Caps reads at 50 KB / 2,000 lines (250 lines by default), batches `paths`, and streams spillover logs up to 50 MB. |
99
+ | `edit` | Guarded code patcher | Enforces read-before-edit checks, preserves CRLF/LF, checks syntax after edits, and supports `line_hint` and atomic `files[]`. |
100
+ | `write` | Atomic file writer | Writes via temp file and atomic rename while preserving permissions and rejecting symlinks. |
101
+ | `bash` | Clamped shell runner | Keeps head/tail context centered on test failure diffs and links cleanly to deduplicated spillover logs. |
92
102
 
93
103
  ---
94
104
 
95
- ## License
105
+ ## Documentation
96
106
 
97
- ISC
107
+ [Architecture](docs/architecture.md) · [Retrieval & Indexing](docs/retrieval.md) · [Editing & Syntax Verification](docs/editing-and-verification.md) · [Configuration Reference](docs/configuration.md) · [Testing & Verification](docs/testing.md) · [Changelog](CHANGELOG.md) · [ISC License](LICENSE)
@@ -3,10 +3,11 @@
3
3
  # All fields are optional; defaults apply when omitted.
4
4
 
5
5
  [retrieval]
6
- # "auto" (VPS=lean, laptop=hybrid, desktop=full), "lean" (BM25 only),
7
- # "hybrid" (BM25 + 256d vectors), "full" (768d dense vectors), or "off"
6
+ # "lean" (BM25 only, default), "full" (BM25 + 768d embeddings),
7
+ # "auto" (lean below 4 CPU cores, full otherwise), or "off"
8
8
  default_profile = "lean"
9
9
  max_search_results = 5
10
+ excluded_paths = []
10
11
 
11
12
  [safety]
12
13
  enable_epistemic_guard = true
@@ -17,8 +18,9 @@ exec_timeout_ms = 5000
17
18
 
18
19
  [editing]
19
20
  mode = "smart_anchor"
20
- default_anchors = true
21
- read_mode = "auto"
21
+ default_anchors = false
22
+ read_mode = "plain"
23
+ syntax_gate = "warn"
22
24
  normalize_fullwidth_dots = true
23
25
 
24
26
  [ui]
@@ -27,3 +29,4 @@ enable_pastel_footer = true
27
29
  [instructions]
28
30
  enabled = true
29
31
  pi_docs = true
32
+ host_environment = true
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floydous/pi-agent-kernel",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "Focused code retrieval, editing, and safety checks for Pi.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -22,13 +22,17 @@
22
22
  "cross-spawn": "^7.0.6",
23
23
  "diff": "^9.0.0",
24
24
  "ignore": "^7.0.5",
25
- "typebox": "^1.3.16",
26
25
  "typescript": "^7.0.2",
27
26
  "web-tree-sitter": "0.26.12"
28
27
  },
28
+ "peerDependencies": {
29
+ "@earendil-works/pi-coding-agent": "*",
30
+ "typebox": "*"
31
+ },
29
32
  "devDependencies": {
30
33
  "@earendil-works/pi-coding-agent": "0.84.3",
31
- "tsx": "^4.23.13"
34
+ "tsx": "^4.23.13",
35
+ "typebox": "^1.3.16"
32
36
  },
33
37
  "overrides": {
34
38
  "adm-zip": "^0.6.1",
@@ -43,6 +43,7 @@ export function formatConfigDashboard(cwd: string, config: KernelConfig): string
43
43
  ` • Engine Mode : ${config.editing.mode} (smart_anchor | standard)`,
44
44
  ` • Read Mode : ${config.editing.read_mode} (plain | anchored | auto)`,
45
45
  ` • Default Anchors : ${config.editing.default_anchors ? "true" : "false"}`,
46
+ ` • Syntax Gate : ${config.editing.syntax_gate ?? "warn"} (warn | block)`,
46
47
  ` • Fullwidth Dot Normalization : ${config.editing.normalize_fullwidth_dots !== false ? "ENABLED" : "DISABLED"}`,
47
48
  ``,
48
49
  `[System & UI]`,
@@ -77,6 +78,7 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
77
78
  { value: "set epistemic", label: "set epistemic <on|off> - Toggle Epistemic Guard" },
78
79
  { value: "set editing", label: "set editing <smart_anchor|standard> - Editing engine mode" },
79
80
  { value: "set read_mode", label: "set read_mode <plain|anchored|auto> - Reading anchor mode" },
81
+ { value: "set syntax_gate", label: "set syntax_gate <warn|block> - Post-edit syntax gate behavior" },
80
82
  { value: "set guidance", label: "set guidance <on|off> - Toggle kernel system prompt guidance" },
81
83
  { value: "set host_environment", label: "set host_environment <on|off> - Toggle host environment info in system prompt" },
82
84
  { value: "set pi_docs", label: "set pi_docs <on|off> - Toggle Pi documentation guide in system prompt" },
@@ -180,6 +182,17 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
180
182
  }
181
183
  break;
182
184
  }
185
+ case "syntax_gate":
186
+ case "syntax-gate": {
187
+ if (val === "warn" || val === "block") {
188
+ updates.editing = { syntax_gate: val };
189
+ desc = `Syntax gate set to '${val}'`;
190
+ } else {
191
+ ctx.ui?.notify?.("Invalid syntax gate. Options: warn | block", "error");
192
+ return;
193
+ }
194
+ break;
195
+ }
183
196
  case "fullwidth_dots":
184
197
  case "normalize_fullwidth_dots":
185
198
  case "normalize_dots": {
@@ -202,11 +202,13 @@ function applySingleBlock(
202
202
  targetRange: lineRangeFromOffsets(contentNorm, start, searchNorm.length),
203
203
  };
204
204
  }
205
+ const matchLines = exactMatches.map((offset) => contentNorm.slice(0, offset).split("\n").length);
206
+ const shownLines = matchLines.slice(0, 5).join(", ") + (matchLines.length > 5 ? `, +${matchLines.length - 5} more` : "");
205
207
  return {
206
208
  success: false,
207
209
  newContent: content,
208
210
  strategy: "none",
209
- error: `SEARCH block is ambiguous: found ${exactMatches.length} exact matches.`,
211
+ error: `SEARCH block is ambiguous: found ${exactMatches.length} exact matches (lines ${shownLines}). Pass line_hint or include more surrounding context.`,
210
212
  };
211
213
  }
212
214
 
@@ -275,11 +277,13 @@ function applySingleBlock(
275
277
  },
276
278
  };
277
279
  }
280
+ const matchLines = normalizedMatches.map((idx) => idx + 1);
281
+ const shownLines = matchLines.slice(0, 5).join(", ") + (matchLines.length > 5 ? `, +${matchLines.length - 5} more` : "");
278
282
  return {
279
283
  success: false,
280
284
  newContent: content,
281
285
  strategy: "none",
282
- error: `SEARCH block is ambiguous: found ${normalizedMatches.length} whitespace-normalized matches.`,
286
+ error: `SEARCH block is ambiguous: found ${normalizedMatches.length} whitespace-normalized matches (lines ${shownLines}). Pass line_hint or include more surrounding context.`,
283
287
  };
284
288
  }
285
289
 
@@ -308,7 +312,7 @@ function applySingleBlock(
308
312
  success: false,
309
313
  newContent: content,
310
314
  strategy: "none",
311
- error: `SEARCH block is ambiguous: fuzzy candidates are too close (${(best.score * 100).toFixed(1)}% best).`,
315
+ error: `SEARCH block is ambiguous: fuzzy candidates are too close (${(best.score * 100).toFixed(1)}% best; lines ${best.index + 1}, ${second.index + 1}). Pass line_hint or include more surrounding context.`,
312
316
  };
313
317
  }
314
318
  return {
@@ -468,6 +472,7 @@ export function applySurgicalPatch(
468
472
  line_hint?: number;
469
473
  autoHeal?: boolean;
470
474
  syntaxGate?: "warn" | "block";
475
+ execTimeoutMs?: number;
471
476
  },
472
477
  ): PatchResult {
473
478
  const resolvedPath = resolvePatchPath(filePath);
@@ -486,7 +491,7 @@ export function applySurgicalPatch(
486
491
  }
487
492
 
488
493
  let candidateContent = result.newContent;
489
- let syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
494
+ let syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent, options?.execTimeoutMs);
490
495
  let autoHealed = false;
491
496
 
492
497
  // Delimiter & Bracket Auto-Healing:
@@ -496,7 +501,7 @@ export function applySurgicalPatch(
496
501
  const healedJson = healJsonContent(candidateContent);
497
502
  if (healedJson) {
498
503
  candidateContent = healedJson;
499
- syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
504
+ syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent, options?.execTimeoutMs);
500
505
  autoHealed = syntax.valid;
501
506
  }
502
507
  } else if (options?.autoHeal !== false) {
@@ -507,7 +512,7 @@ export function applySurgicalPatch(
507
512
  const retryReplace = replace + appendDelims;
508
513
  const reResult = applySingleBlock(originalContent, search, retryReplace, options);
509
514
  if (reResult.success) {
510
- const reSyntax = checkSyntaxContent(resolvedPath, reResult.newContent, originalContent);
515
+ const reSyntax = checkSyntaxContent(resolvedPath, reResult.newContent, originalContent, options?.execTimeoutMs);
511
516
  if (reSyntax.valid) {
512
517
  candidateContent = reResult.newContent;
513
518
  syntax = reSyntax;
@@ -564,7 +569,7 @@ export function applySurgicalPatch(
564
569
  export function applyMultiBlockPatch(
565
570
  filePath: string,
566
571
  blocks: PatchBlock[],
567
- options: { autoHeal?: boolean; syntaxGate?: "warn" | "block" } = {},
572
+ options: { autoHeal?: boolean; syntaxGate?: "warn" | "block"; execTimeoutMs?: number } = {},
568
573
  ): PatchResult {
569
574
  const resolvedPath = resolvePatchPath(filePath);
570
575
  const target = readPatchTarget(resolvedPath);
@@ -670,7 +675,7 @@ export function applyMultiBlockPatch(
670
675
  }
671
676
 
672
677
  let candidateContent = currentContent;
673
- let syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
678
+ let syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent, options.execTimeoutMs);
674
679
  let autoHealed = false;
675
680
 
676
681
  if (!syntax.valid) {
@@ -679,7 +684,7 @@ export function applyMultiBlockPatch(
679
684
  const healedJson = healJsonContent(candidateContent);
680
685
  if (healedJson) {
681
686
  candidateContent = healedJson;
682
- syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
687
+ syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent, options.execTimeoutMs);
683
688
  autoHealed = syntax.valid;
684
689
  }
685
690
  }
@@ -165,8 +165,9 @@ export async function verifyEditedFile(
165
165
  diagnostics?: () => Promise<DiagnosticCheck>,
166
166
  /** The verdict the patch already reached on the written content; skips checking it again. */
167
167
  precomputedSyntax?: VerificationResult,
168
+ execTimeoutMs?: number,
168
169
  ): Promise<PostEditVerification> {
169
- const syntax = precomputedSyntax ?? checkSyntax(filePath);
170
+ const syntax = precomputedSyntax ?? checkSyntax(filePath, execTimeoutMs);
170
171
  if (!syntax.valid) {
171
172
  return {
172
173
  edit: "applied",
@@ -308,7 +308,7 @@ export function preflightSmartAnchorEdits(
308
308
  export function applySmartAnchorEdits(
309
309
  filePath: string,
310
310
  edits: SmartAnchorEditBlock[],
311
- options: { syntaxGate?: "warn" | "block" } = {},
311
+ options: { syntaxGate?: "warn" | "block"; execTimeoutMs?: number } = {},
312
312
  ): PatchResult {
313
313
  const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath);
314
314
  if (!fs.existsSync(resolvedPath)) {
@@ -365,7 +365,7 @@ export function applySmartAnchorEdits(
365
365
  : candidateContentNorm;
366
366
 
367
367
  // Syntax validation gate
368
- const syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
368
+ const syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent, options.execTimeoutMs);
369
369
  if (!syntax.valid && options.syntaxGate !== "warn") {
370
370
  return {
371
371
  success: false,
@@ -64,7 +64,7 @@ export function resolveTypeScriptCompiler(): string {
64
64
  }
65
65
  }
66
66
 
67
- function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
67
+ function validateSyntaxAtPath(resolvedPath: string, timeoutMs = 5000): VerificationResult {
68
68
  if (!fs.existsSync(resolvedPath)) {
69
69
  return { valid: true, status: "clean" };
70
70
  }
@@ -76,7 +76,7 @@ function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
76
76
  try {
77
77
  execFileSync("python", ["-m", "py_compile", resolvedPath], {
78
78
  stdio: "pipe",
79
- timeout: 5000,
79
+ timeout: timeoutMs,
80
80
  });
81
81
  } catch (error: any) {
82
82
  const unavailable = error?.code === "ENOENT" || error?.status === 9009;
@@ -84,7 +84,7 @@ function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
84
84
  try {
85
85
  execFileSync("python3", ["-m", "py_compile", resolvedPath], {
86
86
  stdio: "pipe",
87
- timeout: 5000,
87
+ timeout: timeoutMs,
88
88
  });
89
89
  } catch (fallbackError: any) {
90
90
  if (fallbackError?.code === "ENOENT" || fallbackError?.status === 9009) {
@@ -112,7 +112,7 @@ function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
112
112
  try {
113
113
  execFileSync(nodeExec.bin, ["--check", resolvedPath], {
114
114
  stdio: ["ignore", "pipe", "pipe"],
115
- timeout: 5000,
115
+ timeout: timeoutMs,
116
116
  env: nodeExec.env ? { ...process.env, ...nodeExec.env } : process.env,
117
117
  });
118
118
  } catch (error: any) {
@@ -173,7 +173,7 @@ function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
173
173
  try {
174
174
  execFileSync(nodeExec.bin, [compiler, ...compilerArgs], {
175
175
  stdio: ["ignore", "pipe", "pipe"],
176
- timeout: 5000,
176
+ timeout: timeoutMs,
177
177
  env: nodeExec.env ? { ...process.env, ...nodeExec.env } : process.env,
178
178
  });
179
179
  } catch (error: any) {
@@ -213,7 +213,7 @@ function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
213
213
  }
214
214
  }
215
215
 
216
- export function checkSyntax(filePath: string): VerificationResult {
216
+ export function checkSyntax(filePath: string, timeoutMs?: number): VerificationResult {
217
217
  const resolvedPath = path.isAbsolute(filePath)
218
218
  ? filePath
219
219
  : path.resolve(process.cwd(), filePath);
@@ -230,7 +230,7 @@ export function checkSyntax(filePath: string): VerificationResult {
230
230
  error: `Syntax validation could not read ${path.basename(resolvedPath)}: ${err.message || String(err)}`,
231
231
  };
232
232
  }
233
- return checkSyntaxContent(resolvedPath, content);
233
+ return checkSyntaxContent(resolvedPath, content, undefined, timeoutMs);
234
234
  }
235
235
 
236
236
  // Checked by their own parser in validateSyntaxAtPath; tree-sitter only speeds up the TypeScript family.
@@ -262,6 +262,7 @@ export function checkSyntaxContent(
262
262
  filePath: string,
263
263
  content: string,
264
264
  original?: string,
265
+ timeoutMs?: number,
265
266
  ): VerificationResult {
266
267
  const resolvedPath = path.isAbsolute(filePath)
267
268
  ? filePath
@@ -287,7 +288,7 @@ export function checkSyntaxContent(
287
288
  : [path.extname(resolvedPath) || ".tmp"];
288
289
  let result: VerificationResult | undefined;
289
290
  for (const extension of extensions) {
290
- const res = validateCandidate(content, extension);
291
+ const res = validateCandidate(content, extension, timeoutMs);
291
292
  if (res.valid) return res;
292
293
  result ??= res;
293
294
  }
@@ -295,7 +296,7 @@ export function checkSyntaxContent(
295
296
  }
296
297
 
297
298
  /** Run the file-oriented validators on a temporary copy, so the target is never touched. */
298
- function validateCandidate(content: string, extension: string): VerificationResult {
299
+ function validateCandidate(content: string, extension: string, timeoutMs?: number): VerificationResult {
299
300
  let tempDir: string | undefined;
300
301
 
301
302
  try {
@@ -304,7 +305,7 @@ function validateCandidate(content: string, extension: string): VerificationResu
304
305
  tempDir = fs.mkdtempSync(path.join(os.tmpdir(), ".pi-agent-kernel-validate-"));
305
306
  const candidatePath = path.join(tempDir, `candidate${extension}`);
306
307
  fs.writeFileSync(candidatePath, content, "utf8");
307
- const res = validateSyntaxAtPath(candidatePath);
308
+ const res = validateSyntaxAtPath(candidatePath, timeoutMs);
308
309
  if (!res.valid && res.error) {
309
310
  // Clean up leaked temporary directory and candidate filenames
310
311
  let cleanErr = res.error
package/src/index.ts CHANGED
@@ -96,11 +96,14 @@ function withoutPiDocumentation(systemPrompt: string): string {
96
96
  return before + after;
97
97
  }
98
98
 
99
- function piDocsEnabled(ctx: any): boolean {
99
+ function piDocsEnabled(
100
+ ctx: any,
101
+ resolveConfig: (cwd: string) => ReturnType<typeof loadKernelConfig> = (cwd) => loadKernelConfig(cwd),
102
+ ): boolean {
100
103
  const sessionVal = piDocsEnabledBySession.get(getSessionId(ctx));
101
104
  if (sessionVal !== undefined) return sessionVal;
102
105
  const cwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
103
- return loadKernelConfig(cwd).instructions.pi_docs ?? true;
106
+ return resolveConfig(cwd).instructions.pi_docs ?? true;
104
107
  }
105
108
 
106
109
  export function renderKernelGuidance(guidance: string, availableTools: ReadonlySet<string>): string {
@@ -316,8 +319,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
316
319
  return {
317
320
  dispose: () => unsubBranch?.(),
318
321
  invalidate: () => {},
319
- render: (width: number) =>
320
- renderFooter(ctx, theme, footerData, width, currentIndex),
322
+ render: (width: number) => {
323
+ const renderCwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
324
+ return renderFooter(ctx, theme, footerData, width, currentIndex, getConfig(renderCwd));
325
+ },
321
326
  };
322
327
  });
323
328
  }
@@ -423,7 +428,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
423
428
  return;
424
429
  }
425
430
 
426
- const enabled = piDocsEnabled(ctx);
431
+ const enabled = piDocsEnabled(ctx, getConfig);
427
432
  const message = `Pi documentation guidance: ${enabled ? "on" : "off"}`;
428
433
  ctx.ui?.notify?.(message, "info");
429
434
  if (!ctx.hasUI) console.log(message);
@@ -666,7 +671,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
666
671
  }
667
672
 
668
673
  await TreeSitterEngine.getInstance().loadLanguages([path.extname(resolvedPath).toLowerCase()]);
669
- const syntaxRes = checkSyntax(resolvedPath);
674
+ const syntaxRes = checkSyntax(resolvedPath, getConfig(resultCwd).safety.exec_timeout_ms);
670
675
 
671
676
  if (!syntaxRes.valid && syntaxRes.status === "failed") {
672
677
  const warning = `\n\n[SYNTAX WARNING] ${syntaxRes.error}\nPlease fix this syntax error.`;
@@ -693,7 +698,7 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
693
698
  const kernelConfig = getConfig(currentCwd);
694
699
 
695
700
  const basePrompt = event.systemPrompt || "";
696
- const includePiDocs = piDocsEnabled(ctx);
701
+ const includePiDocs = piDocsEnabled(ctx, getConfig);
697
702
  if (!includePiDocs && event.systemPromptOptions?.sections?.docs !== undefined) {
698
703
  delete event.systemPromptOptions.sections.docs;
699
704
  }