@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.
- package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
- package/CHANGELOG.md +87 -0
- package/README.md +6 -54
- package/config.example.toml +1 -8
- package/docs/README.md +1 -2
- package/docs/architecture.md +2 -3
- package/docs/configuration.md +11 -10
- package/docs/editing-and-verification.md +21 -8
- package/docs/podman-linux-checks.md +24 -0
- package/docs/release-discipline.md +10 -0
- package/docs/retrieval.md +21 -23
- package/docs/testing.md +3 -3
- package/grammars/tree-sitter-html.wasm +0 -0
- package/package.json +5 -3
- package/src/config/agent_kernel_command.ts +60 -625
- package/src/config/kernel_config.ts +53 -69
- package/src/config/toml.ts +6 -1
- package/src/editing/auto_heal.ts +1 -1
- package/src/editing/patch.ts +75 -37
- package/src/editing/post_edit_verification.ts +20 -14
- package/src/editing/smart_anchor.ts +9 -6
- package/src/editing/syntax-verify.ts +79 -222
- package/src/index.ts +36 -453
- package/src/retrieval/html_chunker.ts +526 -0
- package/src/retrieval/search_bm25.ts +39 -28
- package/src/retrieval/search_chunker.ts +69 -7
- package/src/retrieval/search_config.ts +21 -40
- package/src/retrieval/search_embedder.ts +14 -31
- package/src/retrieval/search_index.ts +338 -129
- package/src/retrieval/search_modal.ts +1208 -222
- package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
- package/src/retrieval/tree_sitter_engine.ts +171 -36
- package/src/retrieval/workspace_walker.ts +78 -2
- package/src/safety/atomic_write.ts +1 -1
- package/src/safety/epistemic_guard.ts +105 -31
- package/src/safety/host_environment.ts +180 -0
- package/src/safety/output_clamper.ts +97 -27
- package/src/tools/code_search_output.ts +11 -2
- package/src/tools/code_search_tool.ts +25 -13
- package/src/tools/context.ts +11 -10
- package/src/tools/edit_tool.ts +243 -154
- package/src/tools/read_tool.ts +285 -214
- package/src/tools/stream_reader.ts +206 -0
- package/src/ui/footer.ts +7 -7
- package/docs/lsp.md +0 -31
- package/src/lsp/adapters/base.ts +0 -42
- package/src/lsp/adapters/index.ts +0 -21
- package/src/lsp/adapters/python.ts +0 -37
- package/src/lsp/adapters/rust.ts +0 -35
- package/src/lsp/adapters/typescript.ts +0 -40
- package/src/lsp/index.ts +0 -13
- package/src/lsp/lsp_client.ts +0 -765
- package/src/lsp/lsp_detector.ts +0 -52
- package/src/lsp/lsp_formatter.ts +0 -323
- package/src/lsp/lsp_installer.ts +0 -320
- package/src/lsp/lsp_manager.ts +0 -202
- package/src/lsp/lsp_modal.ts +0 -675
- package/src/lsp/lsp_registry.ts +0 -600
- package/src/lsp/lsp_types.ts +0 -143
- package/src/retrieval/ast_search.ts +0 -999
- package/src/retrieval/symbol_reader.ts +0 -228
- package/src/tools/ast_search_formatter.ts +0 -161
- package/src/tools/ast_search_tool.ts +0 -146
- package/src/tools/lsp_tool.ts +0 -794
- package/src/tools/repo_map_tool.ts +0 -56
|
@@ -10,6 +10,7 @@ import * as fs from "node:fs";
|
|
|
10
10
|
import * as os from "node:os";
|
|
11
11
|
import * as path from "node:path";
|
|
12
12
|
import { kernelDebug } from "./kernel_debug";
|
|
13
|
+
import { writeFileSyncAtomic } from "./atomic_write";
|
|
13
14
|
import { getPiHomeDir } from "../config/kernel_config";
|
|
14
15
|
|
|
15
16
|
/**
|
|
@@ -158,9 +159,7 @@ export type EvidenceProvenance =
|
|
|
158
159
|
| "read"
|
|
159
160
|
| "symbol"
|
|
160
161
|
| "search"
|
|
161
|
-
| "lsp"
|
|
162
162
|
| "bash"
|
|
163
|
-
| "ast_search"
|
|
164
163
|
| "code_search"
|
|
165
164
|
| "edit"
|
|
166
165
|
| "write";
|
|
@@ -575,6 +574,78 @@ export function getInspectionStateFilePath(sessionId: string, cwd = process.cwd(
|
|
|
575
574
|
return path.join(baseDir, "inspection-state.json");
|
|
576
575
|
}
|
|
577
576
|
|
|
577
|
+
interface PersistedSearchHit {
|
|
578
|
+
line: number;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
interface PersistedInspectionRecord {
|
|
582
|
+
kind: "read" | "search";
|
|
583
|
+
fingerprint: string;
|
|
584
|
+
coverage?: unknown;
|
|
585
|
+
provenance?: string;
|
|
586
|
+
query?: string;
|
|
587
|
+
searchHits?: PersistedSearchHit[];
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function isSafeWorkspaceRelPath(rel: string): boolean {
|
|
591
|
+
const normalized = rel.replace(/\\/g, "/");
|
|
592
|
+
return normalized !== ".." && !normalized.startsWith("../") && !path.isAbsolute(normalized);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function isSafePersistedRecord(rec: unknown): rec is PersistedInspectionRecord {
|
|
596
|
+
if (!rec || typeof rec !== "object" || Array.isArray(rec)) return false;
|
|
597
|
+
const r = rec as Record<string, unknown>;
|
|
598
|
+
if (r.kind !== "read" && r.kind !== "search") return false;
|
|
599
|
+
if (typeof r.fingerprint !== "string" || !/^[0-9a-f]{64}$/i.test(r.fingerprint)) return false;
|
|
600
|
+
if (r.provenance !== undefined && (typeof r.provenance !== "string" || r.provenance.length > 128)) return false;
|
|
601
|
+
if (r.query !== undefined && (typeof r.query !== "string" || r.query.length > 1024)) return false;
|
|
602
|
+
if (r.searchHits !== undefined) {
|
|
603
|
+
if (!Array.isArray(r.searchHits) || r.searchHits.length > 1000) return false;
|
|
604
|
+
for (const h of r.searchHits) {
|
|
605
|
+
if (!h || typeof h !== "object" || typeof (h as any).line !== "number" || !Number.isSafeInteger((h as any).line) || (h as any).line < 1) {
|
|
606
|
+
return false;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
return true;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
function parsePersistedCoverage(coverage: unknown, kind: "read" | "search"): EvidenceCoverage {
|
|
614
|
+
if (!coverage || typeof coverage !== "object") {
|
|
615
|
+
return { complete: false, ranges: [] };
|
|
616
|
+
}
|
|
617
|
+
const c = coverage as Record<string, unknown>;
|
|
618
|
+
const complete = kind === "read" && c.complete === true;
|
|
619
|
+
const totalLines =
|
|
620
|
+
typeof c.totalLines === "number" && Number.isSafeInteger(c.totalLines) && c.totalLines >= 0
|
|
621
|
+
? c.totalLines
|
|
622
|
+
: undefined;
|
|
623
|
+
const rawRanges = Array.isArray(c.ranges) ? c.ranges : [];
|
|
624
|
+
const validRanges: EvidenceRange[] = [];
|
|
625
|
+
for (const r of rawRanges.slice(0, 1000)) {
|
|
626
|
+
if (
|
|
627
|
+
r &&
|
|
628
|
+
typeof r === "object" &&
|
|
629
|
+
typeof (r as any).startLine === "number" &&
|
|
630
|
+
typeof (r as any).endLine === "number" &&
|
|
631
|
+
Number.isSafeInteger((r as any).startLine) &&
|
|
632
|
+
Number.isSafeInteger((r as any).endLine) &&
|
|
633
|
+
(r as any).startLine >= 1 &&
|
|
634
|
+
(r as any).endLine >= (r as any).startLine
|
|
635
|
+
) {
|
|
636
|
+
validRanges.push({
|
|
637
|
+
startLine: (r as any).startLine,
|
|
638
|
+
endLine: (r as any).endLine,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
return {
|
|
643
|
+
complete,
|
|
644
|
+
ranges: normalizeRanges(validRanges, totalLines),
|
|
645
|
+
...(totalLines !== undefined ? { totalLines } : {}),
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
|
|
578
649
|
export function saveSessionInspectionState(
|
|
579
650
|
sessionId: string,
|
|
580
651
|
evidenceMap: Map<string, InspectionEvidence>,
|
|
@@ -587,10 +658,10 @@ export function saveSessionInspectionState(
|
|
|
587
658
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
588
659
|
|
|
589
660
|
const canonicalWorkspace = fs.existsSync(cwd) ? fs.realpathSync(cwd) : path.resolve(cwd);
|
|
590
|
-
const records: Record<string,
|
|
661
|
+
const records: Record<string, PersistedInspectionRecord> = {};
|
|
591
662
|
for (const [absPath, ev] of evidenceMap.entries()) {
|
|
592
663
|
const rel = path.relative(canonicalWorkspace, absPath).replace(/\\/g, "/");
|
|
593
|
-
if (
|
|
664
|
+
if (!isSafeWorkspaceRelPath(rel)) continue;
|
|
594
665
|
records[rel] = {
|
|
595
666
|
kind: ev.kind,
|
|
596
667
|
fingerprint: ev.fingerprint,
|
|
@@ -601,13 +672,10 @@ export function saveSessionInspectionState(
|
|
|
601
672
|
};
|
|
602
673
|
}
|
|
603
674
|
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
tmpPath,
|
|
675
|
+
writeFileSyncAtomic(
|
|
676
|
+
filePath,
|
|
607
677
|
JSON.stringify({ version: 1, workspace: canonicalWorkspace, records }, null, 2),
|
|
608
|
-
{ encoding: "utf8", mode: 0o600 },
|
|
609
678
|
);
|
|
610
|
-
fs.renameSync(tmpPath, filePath);
|
|
611
679
|
} catch (err) {
|
|
612
680
|
kernelDebug(err);
|
|
613
681
|
}
|
|
@@ -626,44 +694,51 @@ export function loadSessionInspectionState(
|
|
|
626
694
|
if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return result;
|
|
627
695
|
|
|
628
696
|
const raw = fs.readFileSync(filePath, "utf8");
|
|
629
|
-
let data:
|
|
697
|
+
let data: { version?: unknown; records?: unknown };
|
|
630
698
|
try {
|
|
631
699
|
data = JSON.parse(raw);
|
|
632
700
|
} catch {
|
|
633
701
|
return result;
|
|
634
702
|
}
|
|
635
|
-
if (!data || data.version !== 1 || !data.records || typeof data.records !== "object")
|
|
703
|
+
if (!data || data.version !== 1 || !data.records || typeof data.records !== "object" || Array.isArray(data.records)) {
|
|
704
|
+
return result;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
const entries = Object.entries(data.records as Record<string, unknown>);
|
|
708
|
+
if (entries.length > 1000) return result;
|
|
636
709
|
|
|
637
710
|
const canonicalWorkspace = fs.existsSync(cwd) ? fs.realpathSync(cwd) : path.resolve(cwd);
|
|
638
|
-
for (const [relPath,
|
|
639
|
-
if (!relPath || typeof relPath !== "string" || relPath.includes("\0")) continue;
|
|
711
|
+
for (const [relPath, rawRec] of entries) {
|
|
712
|
+
if (!relPath || typeof relPath !== "string" || relPath.length > 512 || relPath.includes("\0")) continue;
|
|
713
|
+
if (!isSafeWorkspaceRelPath(relPath)) continue;
|
|
714
|
+
if (!isSafePersistedRecord(rawRec)) continue;
|
|
715
|
+
|
|
640
716
|
const absPath = path.resolve(canonicalWorkspace, relPath);
|
|
641
|
-
const relCheck = path.relative(canonicalWorkspace, absPath)
|
|
642
|
-
if (
|
|
717
|
+
const relCheck = path.relative(canonicalWorkspace, absPath);
|
|
718
|
+
if (!isSafeWorkspaceRelPath(relCheck)) continue;
|
|
643
719
|
|
|
644
720
|
if (!fs.existsSync(absPath) || !fs.statSync(absPath).isFile()) continue;
|
|
645
721
|
// Ensure symlinks pointing outside workspace root are rejected
|
|
646
722
|
const canonicalFile = fs.realpathSync(absPath);
|
|
647
|
-
const realRelCheck = path.relative(canonicalWorkspace, canonicalFile)
|
|
648
|
-
if (
|
|
723
|
+
const realRelCheck = path.relative(canonicalWorkspace, canonicalFile);
|
|
724
|
+
if (!isSafeWorkspaceRelPath(realRelCheck)) continue;
|
|
649
725
|
|
|
650
726
|
const content = fs.readFileSync(absPath);
|
|
651
727
|
const currentFingerprint = crypto.createHash("sha256").update(content).digest("hex");
|
|
652
|
-
if (currentFingerprint !==
|
|
728
|
+
if (currentFingerprint !== rawRec.fingerprint) continue;
|
|
653
729
|
|
|
654
730
|
const normalized = process.platform === "win32" ? absPath.toLowerCase() : absPath;
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
.map((h: any) => ({ line: Math.floor(h.line) }))
|
|
731
|
+
if (result.has(normalized)) continue; // Prevent later duplicate entries from weakening prior verified evidence
|
|
732
|
+
const hits = Array.isArray(rawRec.searchHits)
|
|
733
|
+
? rawRec.searchHits.map((h) => ({ line: Math.floor(h.line) }))
|
|
659
734
|
: undefined;
|
|
660
735
|
|
|
661
736
|
result.set(normalized, {
|
|
662
|
-
kind:
|
|
663
|
-
fingerprint:
|
|
664
|
-
coverage:
|
|
665
|
-
provenance:
|
|
666
|
-
query:
|
|
737
|
+
kind: rawRec.kind,
|
|
738
|
+
fingerprint: rawRec.fingerprint,
|
|
739
|
+
coverage: parsePersistedCoverage(rawRec.coverage, rawRec.kind),
|
|
740
|
+
provenance: (rawRec.provenance || "read") as any,
|
|
741
|
+
query: rawRec.query,
|
|
667
742
|
searchHits: hits,
|
|
668
743
|
});
|
|
669
744
|
}
|
|
@@ -937,9 +1012,6 @@ export class EpistemicGuard {
|
|
|
937
1012
|
outputComplete: boolean,
|
|
938
1013
|
outputText = "",
|
|
939
1014
|
): void {
|
|
940
|
-
const isGrepOrRg =
|
|
941
|
-
/^\s*(?:grep|rg)(?:\.exe)?(?:\s|$)/i.test(command) ||
|
|
942
|
-
/\b(grep|rg)\b/i.test(command);
|
|
943
1015
|
const isPaging = /\b(head|tail|sed)\b/i.test(command);
|
|
944
1016
|
const isCat = /\bcat\b/i.test(command);
|
|
945
1017
|
|
|
@@ -1213,7 +1285,9 @@ export class EpistemicGuard {
|
|
|
1213
1285
|
ranges: [range],
|
|
1214
1286
|
});
|
|
1215
1287
|
isAuthorized = true;
|
|
1216
|
-
} catch {
|
|
1288
|
+
} catch (err) {
|
|
1289
|
+
kernelDebug(err);
|
|
1290
|
+
}
|
|
1217
1291
|
}
|
|
1218
1292
|
}
|
|
1219
1293
|
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
|
|
4
|
+
export interface HostEnvironmentOptions {
|
|
5
|
+
platform?: string;
|
|
6
|
+
arch?: string;
|
|
7
|
+
osReleaseContent?: string;
|
|
8
|
+
isWsl?: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
let memoizedHostEnv: string | null = null;
|
|
12
|
+
|
|
13
|
+
function unquote(val: string): string {
|
|
14
|
+
const trimmed = val.trim();
|
|
15
|
+
if (trimmed.length >= 2) {
|
|
16
|
+
const first = trimmed.charAt(0);
|
|
17
|
+
const last = trimmed.charAt(trimmed.length - 1);
|
|
18
|
+
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
|
|
19
|
+
const inside = trimmed.slice(1, -1);
|
|
20
|
+
return first === '"' ? inside.replace(/\\([\\"$`])/g, "$1") : inside;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return trimmed;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function parseOSRelease(text: string): Record<string, string> {
|
|
27
|
+
const result = Object.create(null) as Record<string, string>;
|
|
28
|
+
for (const line of text.split(/\r?\n/)) {
|
|
29
|
+
const trimmed = line.trim();
|
|
30
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
31
|
+
const idx = trimmed.indexOf("=");
|
|
32
|
+
if (idx < 1) continue;
|
|
33
|
+
const key = trimmed.slice(0, idx);
|
|
34
|
+
if (/^[A-Z0-9_]+$/.test(key)) {
|
|
35
|
+
result[key] = unquote(trimmed.slice(idx + 1));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function getWindowsVersion(): string {
|
|
42
|
+
const rel = os.release();
|
|
43
|
+
const match = rel.match(/(\d+)\.(\d+)\.(\d+)/);
|
|
44
|
+
if (match) {
|
|
45
|
+
const build = parseInt(match[3], 10);
|
|
46
|
+
return build >= 22000 ? "Windows 11" : "Windows 10";
|
|
47
|
+
}
|
|
48
|
+
return "Windows";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface LinuxDistroInfo {
|
|
52
|
+
name: string;
|
|
53
|
+
id?: string;
|
|
54
|
+
idLike?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function resolveLinuxDistro(options?: HostEnvironmentOptions): LinuxDistroInfo {
|
|
58
|
+
if (options?.osReleaseContent) {
|
|
59
|
+
const parsed = parseOSRelease(options.osReleaseContent);
|
|
60
|
+
const name = parsed.PRETTY_NAME || parsed.NAME || parsed.ID || "Linux";
|
|
61
|
+
return { name, id: parsed.ID?.toLowerCase(), idLike: parsed.ID_LIKE?.toLowerCase() };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
for (const p of ["/etc/os-release", "/usr/lib/os-release"]) {
|
|
65
|
+
try {
|
|
66
|
+
if (fs.existsSync(p)) {
|
|
67
|
+
const content = fs.readFileSync(p, "utf8");
|
|
68
|
+
const parsed = parseOSRelease(content);
|
|
69
|
+
const name = parsed.PRETTY_NAME || parsed.NAME || parsed.ID || "Linux";
|
|
70
|
+
return { name, id: parsed.ID?.toLowerCase(), idLike: parsed.ID_LIKE?.toLowerCase() };
|
|
71
|
+
}
|
|
72
|
+
} catch {}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return { name: "Linux" };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function checkIsWsl(options?: HostEnvironmentOptions): boolean {
|
|
79
|
+
if (options?.isWsl !== undefined) return options.isWsl;
|
|
80
|
+
if (process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP) return true;
|
|
81
|
+
try {
|
|
82
|
+
if (fs.existsSync("/proc/version")) {
|
|
83
|
+
const version = fs.readFileSync("/proc/version", "utf8");
|
|
84
|
+
return /microsoft|wsl/i.test(version);
|
|
85
|
+
}
|
|
86
|
+
} catch {}
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Reset in-memory memoized host environment (useful for tests).
|
|
92
|
+
*/
|
|
93
|
+
export function resetHostEnvironmentCache(): void {
|
|
94
|
+
memoizedHostEnv = null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Render concise factual host environment block.
|
|
99
|
+
* Safe from prompt injection: contains only trusted OS, shell, and platform guidance.
|
|
100
|
+
*/
|
|
101
|
+
export function renderHostEnvironment(options?: HostEnvironmentOptions): string {
|
|
102
|
+
if (!options && memoizedHostEnv) {
|
|
103
|
+
return memoizedHostEnv;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const platform = options?.platform ?? process.platform;
|
|
107
|
+
const arch = options?.arch ?? process.arch;
|
|
108
|
+
const isWin = platform === "win32";
|
|
109
|
+
const isMac = platform === "darwin";
|
|
110
|
+
|
|
111
|
+
if (isWin) {
|
|
112
|
+
const osName = getWindowsVersion();
|
|
113
|
+
const lines = [
|
|
114
|
+
"<host_environment>",
|
|
115
|
+
`Platform: ${osName} (${platform} ${arch})`,
|
|
116
|
+
"Shell: bash (Git Bash / MSYS2)",
|
|
117
|
+
"Line Endings: Preserved per-file (auto-detects CRLF / LF)",
|
|
118
|
+
"Platform Guidance:",
|
|
119
|
+
"- Terminal commands run through Git Bash: use POSIX syntax (ls, grep, cat, find, &&, 2>/dev/null).",
|
|
120
|
+
"- Paths: Use forward slashes (C:/Users/...) for native Windows tools (node, cargo, python).",
|
|
121
|
+
"- Python binary: invoke as 'python' ('python3' is Windows Store stub).",
|
|
122
|
+
"- Non-profile PowerShell: prefer .NET ([System.Security.Cryptography.SHA256]) or certutil over autoloaded cmdlets like Get-FileHash.",
|
|
123
|
+
"</host_environment>",
|
|
124
|
+
];
|
|
125
|
+
const result = lines.join("\n");
|
|
126
|
+
if (!options) memoizedHostEnv = result;
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (isMac) {
|
|
131
|
+
const lines = [
|
|
132
|
+
"<host_environment>",
|
|
133
|
+
`Platform: macOS (${platform} ${arch})`,
|
|
134
|
+
"Shell: bash (macOS /bin/bash v3.2)",
|
|
135
|
+
"Line Endings: Preserved per-file (auto-detects CRLF / LF)",
|
|
136
|
+
"Platform Guidance:",
|
|
137
|
+
"- Stock /bin/bash is Bash 3.2: avoid Bash 4+ features (declare -A, mapfile/readarray, ${var^^}).",
|
|
138
|
+
"- BSD userland: use portable POSIX flags (e.g. sed -i '' for in-place edit, not GNU sed -i).",
|
|
139
|
+
"</host_environment>",
|
|
140
|
+
];
|
|
141
|
+
const result = lines.join("\n");
|
|
142
|
+
if (!options) memoizedHostEnv = result;
|
|
143
|
+
return result;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Linux
|
|
147
|
+
const distro = resolveLinuxDistro(options);
|
|
148
|
+
const isWsl = checkIsWsl(options);
|
|
149
|
+
const hostDisplay = isWsl ? `${distro.name} on WSL` : distro.name;
|
|
150
|
+
|
|
151
|
+
const rules: string[] = [];
|
|
152
|
+
const id = distro.id || "";
|
|
153
|
+
const idLike = distro.idLike || "";
|
|
154
|
+
|
|
155
|
+
if (id === "alpine") {
|
|
156
|
+
rules.push("- Alpine Linux (musl libc): package manager is 'apk'; glibc-linked binaries are incompatible without gcompat.");
|
|
157
|
+
} else if (id === "arch") {
|
|
158
|
+
rules.push("- Arch Linux (glibc): package manager is 'pacman'.");
|
|
159
|
+
} else if (id === "fedora" || id === "rhel" || id === "centos" || idLike.includes("fedora") || idLike.includes("rhel")) {
|
|
160
|
+
rules.push("- Fedora/RHEL Linux (glibc): package manager is 'dnf' / 'yum'.");
|
|
161
|
+
} else if (id === "debian" || id === "ubuntu" || idLike.includes("debian")) {
|
|
162
|
+
rules.push("- Debian/Ubuntu Linux (glibc): package manager is 'apt'.");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const lines = [
|
|
166
|
+
"<host_environment>",
|
|
167
|
+
`Platform: ${hostDisplay} (${platform} ${arch})`,
|
|
168
|
+
"Shell: bash",
|
|
169
|
+
"Line Endings: Preserved per-file (auto-detects CRLF / LF)",
|
|
170
|
+
];
|
|
171
|
+
|
|
172
|
+
if (rules.length > 0) {
|
|
173
|
+
lines.push("Platform Guidance:", ...rules);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
lines.push("</host_environment>");
|
|
177
|
+
const result = lines.join("\n");
|
|
178
|
+
if (!options) memoizedHostEnv = result;
|
|
179
|
+
return result;
|
|
180
|
+
}
|
|
@@ -27,7 +27,61 @@ export interface ClampingResult {
|
|
|
27
27
|
|
|
28
28
|
const SPILL_PREFIX = "pi_bash_spillover_";
|
|
29
29
|
const DEFAULT_SPILL_FILES = 20;
|
|
30
|
-
const DEFAULT_SPILL_BYTES = 50 * 1024 * 1024;
|
|
30
|
+
export const DEFAULT_SPILL_BYTES = 50 * 1024 * 1024;
|
|
31
|
+
|
|
32
|
+
function isWithinDir(candidatePath: string, parentDir: string): boolean {
|
|
33
|
+
const isWindows = process.platform === "win32";
|
|
34
|
+
const parent = isWindows ? parentDir.toLowerCase() : parentDir;
|
|
35
|
+
const candidate = isWindows ? candidatePath.toLowerCase() : candidatePath;
|
|
36
|
+
const rel = path.relative(parent, candidate);
|
|
37
|
+
return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Validate whether a resolved file path is an authenticated spillover log.
|
|
42
|
+
* Supports both Agent Kernel spillover logs and host harness temporary logs.
|
|
43
|
+
* Canonicalizes directories via realpathSync to resolve symlinks and Windows short paths.
|
|
44
|
+
*/
|
|
45
|
+
export function isSpilloverFilePath(candidatePath: string, cwd = process.cwd()): boolean {
|
|
46
|
+
try {
|
|
47
|
+
const trimmed = candidatePath.trim().replace(/^["']|["']$/g, "");
|
|
48
|
+
if (trimmed.startsWith("\\\\") || trimmed.startsWith("//")) return false;
|
|
49
|
+
|
|
50
|
+
const resolved = path.resolve(trimmed);
|
|
51
|
+
if (!fs.existsSync(resolved)) return false;
|
|
52
|
+
|
|
53
|
+
const lstat = fs.lstatSync(resolved);
|
|
54
|
+
if (lstat.isSymbolicLink() || !lstat.isFile()) return false;
|
|
55
|
+
|
|
56
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
|
|
57
|
+
if (uid !== undefined && lstat.uid !== uid) return false;
|
|
58
|
+
if (lstat.size > DEFAULT_SPILL_BYTES) return false;
|
|
59
|
+
|
|
60
|
+
const base = path.basename(resolved);
|
|
61
|
+
const isKernel = /^pi_bash_spillover_[a-f0-9]+\.log$/i.test(base);
|
|
62
|
+
const isHost = /^pi-(?:bash|powershell|output)-[a-f0-9]+\.log$/i.test(base);
|
|
63
|
+
if (!isKernel && !isHost) return false;
|
|
64
|
+
|
|
65
|
+
const realResolved = fs.realpathSync(resolved);
|
|
66
|
+
const realParent = path.dirname(realResolved);
|
|
67
|
+
|
|
68
|
+
const realTemp = fs.realpathSync(os.tmpdir());
|
|
69
|
+
if (isWithinDir(realParent, realTemp)) return true;
|
|
70
|
+
|
|
71
|
+
const kernelRoot = path.resolve(getSpilloverRoot(cwd));
|
|
72
|
+
if (fs.existsSync(kernelRoot)) {
|
|
73
|
+
const realKernelRoot = fs.realpathSync(kernelRoot);
|
|
74
|
+
if (isWithinDir(realParent, realKernelRoot)) return true;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const realCwd = fs.realpathSync(path.resolve(cwd));
|
|
78
|
+
if (isWithinDir(realParent, realCwd)) return true;
|
|
79
|
+
|
|
80
|
+
return false;
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
31
85
|
|
|
32
86
|
export function getSpilloverRoot(cwd = process.cwd()): string {
|
|
33
87
|
const base = getPiHomeDir();
|
|
@@ -62,17 +116,17 @@ function isOwnedRegularFile(filePath: string): boolean {
|
|
|
62
116
|
function pruneSpillovers(directory: string, maxFiles: number, maxBytes: number): void {
|
|
63
117
|
const files = fs
|
|
64
118
|
.readdirSync(directory)
|
|
65
|
-
.
|
|
66
|
-
|
|
119
|
+
.flatMap((name) => {
|
|
120
|
+
if (!name.startsWith(SPILL_PREFIX)) return [];
|
|
67
121
|
const full = path.join(directory, name);
|
|
68
122
|
try {
|
|
69
123
|
const stat = fs.lstatSync(full);
|
|
70
|
-
|
|
124
|
+
if (!isOwnedRegularFile(full)) return [];
|
|
125
|
+
return [{ full, size: stat.size, mtime: stat.mtimeMs }];
|
|
71
126
|
} catch {
|
|
72
|
-
return
|
|
127
|
+
return [];
|
|
73
128
|
}
|
|
74
129
|
})
|
|
75
|
-
.filter((item) => item.owned)
|
|
76
130
|
.sort((a, b) => a.mtime - b.mtime);
|
|
77
131
|
let totalBytes = files.reduce((sum, file) => sum + file.size, 0);
|
|
78
132
|
let remainingFiles = files.length;
|
|
@@ -145,11 +199,14 @@ export function isExecutionOrTestCommand(command: string): boolean {
|
|
|
145
199
|
return /\b(test|vitest|jest|pytest|ava|mocha|cargo|tsc|build|check)\b/.test(trimmed);
|
|
146
200
|
}
|
|
147
201
|
|
|
202
|
+
const HOST_STATUS_REGEX =
|
|
203
|
+
/(?:\r?\n){1,2}((?:Command (?:exited with code -?\d+|timed out after \d+(?:\.\d+)? seconds?)|(?:Process|Command) terminated[^\r\n]*))[ \t\r\n]*$/;
|
|
204
|
+
|
|
148
205
|
const HOST_TRUNCATION_REGEX =
|
|
149
|
-
/(?:\r?\n){1,2}\[(?:Showing (?:lines \d+-\d+ of \d+(?: \([^)]+\))?|last [
|
|
206
|
+
/(?:\r?\n){1,2}\[(?:Showing (?:lines \d+-\d+ of \d+(?: \([^)]+\))?|last [^\]\r\n]+?)\.[ \t]*Full output:|Truncated by host harness\.[ \t]*Full:|Full output:[ \t]*|(?:Output truncated\.[ \t]*)?Full output:[ \t]*)([^\]\r\n]+?)(?:\.[ \t]*Truncated:[^\]\r\n]*|[ \t]+\(use offset\/limit[^)]*\)|[ \t]+\(read (?:it )?with offset\/limit\))?\][ \t\r\n]*$/;
|
|
150
207
|
|
|
151
208
|
const KERNEL_TRUNCATION_REGEX =
|
|
152
|
-
/(?:\r?\n){2}\[Truncated[^\r\n\]]*?(?:\.[ \t]*(?:Full|Spillover):[ \t]*([^\]\r\n]+?)(?:[ \t]+\(use offset\/limit[^)]*\)|[ \t]+\(received fragment only\))?)?\][ \t\r\n]*$/;
|
|
209
|
+
/(?:\r?\n){2}\[Truncated[^\r\n\]]*?(?:\.[ \t]*(?:Full|Spillover):[ \t]*([^\]\r\n]+?)(?:[ \t]+\(use offset\/limit[^)]*\)|[ \t]+\(received fragment only\))?)?\](?:\r?\nTo inspect omitted lines[^\r\n]*)?(?:\r?\n\r?\n(?:Command (?:exited with code -?\d+|timed out after \d+(?:\.\d+)? seconds?)|(?:Process|Command) terminated[^\r\n]*))?[ \t\r\n]*$/;
|
|
153
210
|
|
|
154
211
|
function validateHostSpilloverPath(candidatePath: string): string | undefined {
|
|
155
212
|
try {
|
|
@@ -175,11 +232,7 @@ function validateHostSpilloverPath(candidatePath: string): string | undefined {
|
|
|
175
232
|
const realTempDir = fs.realpathSync(os.tmpdir());
|
|
176
233
|
const parentDir = path.dirname(realResolved);
|
|
177
234
|
|
|
178
|
-
|
|
179
|
-
? parentDir.toLowerCase() === realTempDir.toLowerCase()
|
|
180
|
-
: parentDir === realTempDir;
|
|
181
|
-
|
|
182
|
-
if (!isSameDir) {
|
|
235
|
+
if (!isWithinDir(parentDir, realTempDir)) {
|
|
183
236
|
return undefined;
|
|
184
237
|
}
|
|
185
238
|
|
|
@@ -218,18 +271,28 @@ export function clampCommandOutput(
|
|
|
218
271
|
let priorKernelTruncated = false;
|
|
219
272
|
let hostSpilloverPath: string | undefined;
|
|
220
273
|
let priorSpilloverPath: string | undefined;
|
|
274
|
+
let hostStatusTrailer: string | undefined;
|
|
221
275
|
|
|
222
|
-
|
|
276
|
+
// Strip and remember host command status trailer if present (e.g. "Command exited with code 1")
|
|
277
|
+
const statusMatch = textToProcess.match(HOST_STATUS_REGEX);
|
|
278
|
+
if (statusMatch && statusMatch.index !== undefined) {
|
|
279
|
+
hostStatusTrailer = statusMatch[1].trim();
|
|
280
|
+
textToProcess = textToProcess.slice(0, statusMatch.index);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const hostMatch = textToProcess.match(HOST_TRUNCATION_REGEX);
|
|
223
284
|
if (hostMatch && hostMatch.index !== undefined) {
|
|
224
285
|
hostTruncated = true;
|
|
225
|
-
textToProcess =
|
|
286
|
+
textToProcess = textToProcess.slice(0, hostMatch.index);
|
|
226
287
|
const candidate = hostMatch[1].trim();
|
|
227
288
|
hostSpilloverPath = validateHostSpilloverPath(candidate);
|
|
228
|
-
}
|
|
229
|
-
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (!hostTruncated) {
|
|
292
|
+
const kernelMatch = textToProcess.match(KERNEL_TRUNCATION_REGEX);
|
|
230
293
|
if (kernelMatch && kernelMatch.index !== undefined) {
|
|
231
294
|
priorKernelTruncated = true;
|
|
232
|
-
textToProcess =
|
|
295
|
+
textToProcess = textToProcess.slice(0, kernelMatch.index);
|
|
233
296
|
const candidate = kernelMatch[1]?.trim();
|
|
234
297
|
if (candidate) {
|
|
235
298
|
const cleanCandidate = candidate.replace(/\s*\(use offset\/limit.*\)$/i, "").trim();
|
|
@@ -240,7 +303,9 @@ export function clampCommandOutput(
|
|
|
240
303
|
if (!lstat.isSymbolicLink() && lstat.isFile()) {
|
|
241
304
|
priorSpilloverPath = path.resolve(cleanCandidate);
|
|
242
305
|
}
|
|
243
|
-
} catch {
|
|
306
|
+
} catch (e) {
|
|
307
|
+
kernelDebug(e);
|
|
308
|
+
}
|
|
244
309
|
}
|
|
245
310
|
}
|
|
246
311
|
}
|
|
@@ -250,11 +315,15 @@ export function clampCommandOutput(
|
|
|
250
315
|
if (hostSpilloverPath) {
|
|
251
316
|
try {
|
|
252
317
|
originalBytes = fs.statSync(hostSpilloverPath).size;
|
|
253
|
-
} catch {
|
|
318
|
+
} catch (e) {
|
|
319
|
+
kernelDebug(e);
|
|
320
|
+
}
|
|
254
321
|
} else if (priorSpilloverPath) {
|
|
255
322
|
try {
|
|
256
323
|
originalBytes = fs.statSync(priorSpilloverPath).size;
|
|
257
|
-
} catch {
|
|
324
|
+
} catch (e) {
|
|
325
|
+
kernelDebug(e);
|
|
326
|
+
}
|
|
258
327
|
}
|
|
259
328
|
|
|
260
329
|
// If the entire output is small, within bounds, and host did not truncate, return as-is
|
|
@@ -309,7 +378,7 @@ export function clampCommandOutput(
|
|
|
309
378
|
const directory = options?.spilloverDir || getSpilloverRoot();
|
|
310
379
|
const maxFiles = options?.maxSpilloverFiles ?? DEFAULT_SPILL_FILES;
|
|
311
380
|
const maxBytes = options?.maxSpilloverBytes ?? DEFAULT_SPILL_BYTES;
|
|
312
|
-
spilloverPath = writeSpillover(
|
|
381
|
+
spilloverPath = writeSpillover(rawText, directory, maxFiles, maxBytes);
|
|
313
382
|
} catch (e) {
|
|
314
383
|
kernelDebug(e);
|
|
315
384
|
}
|
|
@@ -450,17 +519,18 @@ export function clampCommandOutput(
|
|
|
450
519
|
let resultText = clampedLines.join("\n");
|
|
451
520
|
|
|
452
521
|
const makeFooter = (linesShown: number): string => {
|
|
522
|
+
const statusSuffix = hostStatusTrailer ? `\n\n${hostStatusTrailer}` : "";
|
|
453
523
|
if (hostTruncated || (priorKernelTruncated && hostSpilloverPath)) {
|
|
454
524
|
if (hostSpilloverPath) {
|
|
455
525
|
if (linesShown < totalLines) {
|
|
456
|
-
return `\n\n[Truncated: ${linesShown} lines shown (host truncated). Full: ${hostSpilloverPath} (use offset/limit with read if needed)]`;
|
|
526
|
+
return `\n\n[Truncated: ${linesShown} lines shown (host truncated). Full: ${hostSpilloverPath} (use offset/limit with read if needed)]${statusSuffix}`;
|
|
457
527
|
}
|
|
458
|
-
return `\n\n[Truncated by host harness. Full: ${hostSpilloverPath} (use offset/limit with read if needed)]`;
|
|
528
|
+
return `\n\n[Truncated by host harness. Full: ${hostSpilloverPath} (use offset/limit with read if needed)]${statusSuffix}`;
|
|
459
529
|
}
|
|
460
530
|
if (spilloverPath) {
|
|
461
|
-
return `\n\n[Truncated by host harness. Spillover: ${spilloverPath} (received fragment only)]`;
|
|
531
|
+
return `\n\n[Truncated by host harness. Spillover: ${spilloverPath} (received fragment only)]${statusSuffix}`;
|
|
462
532
|
}
|
|
463
|
-
return `\n\n[Truncated by host harness]`;
|
|
533
|
+
return `\n\n[Truncated by host harness]${statusSuffix}`;
|
|
464
534
|
}
|
|
465
535
|
let f = `\n\n[Truncated: ${linesShown}/${totalLines} lines.`;
|
|
466
536
|
if (spilloverPath) {
|
|
@@ -472,7 +542,7 @@ export function clampCommandOutput(
|
|
|
472
542
|
} else {
|
|
473
543
|
f += `]`;
|
|
474
544
|
}
|
|
475
|
-
return f
|
|
545
|
+
return `${f}${statusSuffix}`;
|
|
476
546
|
};
|
|
477
547
|
|
|
478
548
|
// Append concise footer with spillover pointer
|
|
@@ -11,7 +11,9 @@ export const AUTO_OUTPUT_BUDGET = 8_000;
|
|
|
11
11
|
const PREVIEW_LINE_LIMIT = 12;
|
|
12
12
|
const PREVIEW_CHAR_LIMIT = 1_400;
|
|
13
13
|
const AUTO_FULL_CHAR_LIMIT = 6_000;
|
|
14
|
-
const AUTO_PREVIEW_HIT_LIMIT =
|
|
14
|
+
const AUTO_PREVIEW_HIT_LIMIT = 5;
|
|
15
|
+
/** A previewed chunk this small is shown whole: a 12-line window often misses the relevant lines of a mid-size body. */
|
|
16
|
+
const PREVIEW_WHOLE_CHUNK_CHAR_LIMIT = 2_000;
|
|
15
17
|
|
|
16
18
|
export interface VisibleCodeRange {
|
|
17
19
|
chunkId: string;
|
|
@@ -88,6 +90,12 @@ function queryPreview(
|
|
|
88
90
|
hit: SearchHit,
|
|
89
91
|
query: string,
|
|
90
92
|
): { text: string; visibleRange?: VisibleCodeRange } {
|
|
93
|
+
if (hit.chunk.content.length <= PREVIEW_WHOLE_CHUNK_CHAR_LIMIT) {
|
|
94
|
+
return {
|
|
95
|
+
text: `${hitHeader(hit)}\n\`\`\`${languageFor(hit.chunk.filePath)}\n${hit.chunk.content}\n\`\`\``,
|
|
96
|
+
visibleRange: { chunkId: hit.chunk.id, startLine: hit.chunk.startLine, endLine: hit.chunk.endLine },
|
|
97
|
+
};
|
|
98
|
+
}
|
|
91
99
|
const lines = hit.chunk.content.split("\n");
|
|
92
100
|
const terms = Array.from(new Set(tokenizeCode(query)));
|
|
93
101
|
const bestLine = bestMatchingLine(lines, terms);
|
|
@@ -139,7 +147,8 @@ function applyBudget(
|
|
|
139
147
|
let truncated = false;
|
|
140
148
|
|
|
141
149
|
for (let index = 0; index < entries.length; index++) {
|
|
142
|
-
const entry = entries[index]
|
|
150
|
+
const entry = entries[index];
|
|
151
|
+
if (!entry) continue;
|
|
143
152
|
const separator = selected.length > 0 ? "\n\n" : "";
|
|
144
153
|
const candidateLength = separator.length + entry.text.length;
|
|
145
154
|
if (used + candidateLength <= budget) {
|