@floydous/pi-agent-kernel 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,237 @@
1
+ import * as path from "node:path";
2
+ import type { SearchHit } from "../retrieval/search_index";
3
+ import { tokenizeCode } from "../retrieval/search_bm25";
4
+
5
+ export const CODE_SEARCH_MODES = ["auto", "full", "preview", "summary"] as const;
6
+ export type CodeSearchMode = (typeof CODE_SEARCH_MODES)[number];
7
+
8
+ /** Maximum automatic response size in characters (before the tool footer). */
9
+ export const AUTO_OUTPUT_BUDGET = 8_000;
10
+
11
+ const PREVIEW_LINE_LIMIT = 12;
12
+ const PREVIEW_CHAR_LIMIT = 1_400;
13
+ const AUTO_FULL_CHAR_LIMIT = 6_000;
14
+ const AUTO_PREVIEW_HIT_LIMIT = 3;
15
+
16
+ export interface FormattedCodeSearchResults {
17
+ text: string;
18
+ mode: Exclude<CodeSearchMode, "auto"> | "mixed";
19
+ truncated: boolean;
20
+ }
21
+
22
+ function normalizePath(filePath: string): string {
23
+ return filePath.replace(/\\/g, "/");
24
+ }
25
+
26
+ function languageFor(filePath: string): string {
27
+ return path.extname(filePath).slice(1) || "text";
28
+ }
29
+
30
+ function compactSignature(signature: string): string {
31
+ const normalized = signature.replace(/\s+/g, " ").trim();
32
+ return normalized.length > 220 ? `${normalized.slice(0, 217)}...` : normalized;
33
+ }
34
+
35
+ function hitHeader(hit: SearchHit): string {
36
+ const chunk = hit.chunk;
37
+ const signature = compactSignature(chunk.signature || "");
38
+ const signal = hit.signal ? ` [${hit.signal}]` : "";
39
+ const matches = hit.matches.length > 0
40
+ ? `; matches: ${hit.matches.slice(0, 5).join(", ")}`
41
+ : "";
42
+ const headline = signature && signature !== chunk.symbolName ? ` — ${signature}` : "";
43
+ return `${normalizePath(chunk.filePath)}:${chunk.startLine}-${chunk.endLine} [${chunk.kind}] ${chunk.symbolName}${headline}${signal}${matches}`;
44
+ }
45
+
46
+ function fullHit(hit: SearchHit): string {
47
+ const chunk = hit.chunk;
48
+ return `${normalizePath(chunk.filePath)}:${chunk.startLine}-${chunk.endLine} [${chunk.kind}] ${chunk.symbolName} (${chunk.breadcrumb}):\n\`\`\`${languageFor(chunk.filePath)}\n${chunk.content}\n\`\`\``;
49
+ }
50
+
51
+ function summaryHit(hit: SearchHit): string {
52
+ return hitHeader(hit);
53
+ }
54
+
55
+ function bestMatchingLine(lines: string[], queryTerms: string[]): number {
56
+ if (lines.length === 0 || queryTerms.length === 0) return 0;
57
+
58
+ let bestIndex = 0;
59
+ let bestScore = 0;
60
+ for (let index = 0; index < lines.length; index++) {
61
+ const lowerLine = lines[index].toLowerCase();
62
+ const score = queryTerms.reduce(
63
+ (total, term) => total + (lowerLine.includes(term) ? 1 : 0),
64
+ 0,
65
+ );
66
+ if (score > bestScore) {
67
+ bestScore = score;
68
+ bestIndex = index;
69
+ }
70
+ }
71
+ return bestIndex;
72
+ }
73
+
74
+ /**
75
+ * Return a bounded excerpt around the query-bearing line rather than always
76
+ * returning the beginning of a large AST chunk. This preserves evidence for
77
+ * the search decision while avoiding a forced full-file read in the common
78
+ * multi-result case.
79
+ */
80
+ function queryPreview(hit: SearchHit, query: string): string {
81
+ const lines = hit.chunk.content.split("\n");
82
+ const terms = Array.from(new Set(tokenizeCode(query)));
83
+ const bestLine = bestMatchingLine(lines, terms);
84
+ const halfBefore = 2;
85
+ let start = Math.max(0, bestLine - halfBefore);
86
+ if (start + PREVIEW_LINE_LIMIT > lines.length) {
87
+ start = Math.max(0, lines.length - PREVIEW_LINE_LIMIT);
88
+ }
89
+ const end = Math.min(lines.length, start + PREVIEW_LINE_LIMIT);
90
+ const excerpt = lines.slice(start, end).join("\n");
91
+ const lineStart = hit.chunk.startLine + start;
92
+ const lineEnd = hit.chunk.startLine + end - 1;
93
+ const before = start > 0 ? `... lines ${hit.chunk.startLine}-${lineStart - 1} omitted ...\n` : "";
94
+ const after = end < lines.length ? `\n... lines ${lineEnd + 1}-${hit.chunk.endLine} omitted ...` : "";
95
+ const boundedExcerpt = `${before}${excerpt}${after}`;
96
+ const clipped = boundedExcerpt.length > PREVIEW_CHAR_LIMIT
97
+ ? `${boundedExcerpt.slice(0, PREVIEW_CHAR_LIMIT)}\n... preview clipped ...`
98
+ : boundedExcerpt;
99
+ return `${hitHeader(hit)}\n\`\`\`${languageFor(hit.chunk.filePath)}\n${clipped}\n\`\`\``;
100
+ }
101
+
102
+ function clipToBudget(text: string, budget: number): string {
103
+ if (text.length <= budget) return text;
104
+ if (budget <= 40) return text.slice(0, budget);
105
+ return `${text.slice(0, budget - 27)}\n... output clipped ...`;
106
+ }
107
+
108
+ function applyBudget(entries: string[], budget: number): { text: string; truncated: boolean } {
109
+ const selected: string[] = [];
110
+ let used = 0;
111
+ let omitted = 0;
112
+ let truncated = false;
113
+
114
+ for (let index = 0; index < entries.length; index++) {
115
+ const separator = selected.length > 0 ? "\n\n" : "";
116
+ const candidateLength = separator.length + entries[index].length;
117
+ if (used + candidateLength <= budget) {
118
+ selected.push(entries[index]);
119
+ used += candidateLength;
120
+ continue;
121
+ }
122
+
123
+ if (selected.length === 0) {
124
+ const clipped = clipToBudget(entries[index], budget);
125
+ selected.push(clipped);
126
+ used = clipped.length;
127
+ truncated = clipped.length < entries[index].length;
128
+ // The first entry is present (possibly clipped), so only entries after
129
+ // it are "additional" matches omitted from the response.
130
+ omitted = entries.length - index - 1;
131
+ } else {
132
+ omitted = entries.length - index;
133
+ truncated = true;
134
+ }
135
+ break;
136
+ }
137
+
138
+ if (omitted > 0) {
139
+ const notice = `... ${omitted} additional match${omitted === 1 ? "" : "es"} omitted; use mode: "full" or a narrower query to inspect them ...`;
140
+ const separator = selected.length > 0 ? "\n\n" : "";
141
+ const remaining = Math.max(0, budget - used - separator.length);
142
+ if (remaining > 0) {
143
+ const clippedNotice = clipToBudget(notice, remaining);
144
+ selected.push(clippedNotice);
145
+ truncated = truncated || clippedNotice.length < notice.length;
146
+ }
147
+ }
148
+
149
+ return { text: selected.join("\n\n"), truncated };
150
+ }
151
+
152
+ function resolveAutoMode(hits: SearchHit[]): Exclude<CodeSearchMode, "auto"> | "mixed" {
153
+ if (hits.length === 1 && hits[0].chunk.content.length <= AUTO_FULL_CHAR_LIMIT) {
154
+ return "full";
155
+ }
156
+ if (hits.length <= 3) return "preview";
157
+ return "mixed";
158
+ }
159
+
160
+ /**
161
+ * Format search hits for the model. Explicit full mode preserves the legacy
162
+ * response. Automatic mode is context-preserving: it previews a small number
163
+ * of top hits, summarizes the rest, and enforces a total response budget.
164
+ */
165
+ function decorateResult(
166
+ result: FormattedCodeSearchResults,
167
+ requestedMode: CodeSearchMode,
168
+ hitCount: number,
169
+ ): FormattedCodeSearchResults {
170
+ const header = `[code_search mode=${requestedMode}->${result.mode}; matches=${hitCount}]`;
171
+ // Explicit full mode is the compatibility escape hatch: preserve the
172
+ // pre-change body exactly so callers that parse the legacy output do not
173
+ // need to change. Auto-full still gets the diagnostic header below.
174
+ if (result.mode === "full" && requestedMode === "full") {
175
+ return result;
176
+ }
177
+ if (result.mode === "full") {
178
+ return { ...result, text: `${header}\n\n${result.text}` };
179
+ }
180
+
181
+ const available = Math.max(0, AUTO_OUTPUT_BUDGET - header.length - 2);
182
+ const boundedText = clipToBudget(result.text, available);
183
+ return {
184
+ ...result,
185
+ text: `${header}\n\n${boundedText}`,
186
+ truncated: result.truncated || boundedText.length < result.text.length,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Format search hits for the model. Explicit full mode preserves the legacy
192
+ * response. Automatic mode is context-preserving: it previews a small number
193
+ * of top hits, summarizes the rest, and enforces a total response budget.
194
+ */
195
+ export function formatCodeSearchResults(
196
+ hits: SearchHit[],
197
+ query: string,
198
+ requestedMode: CodeSearchMode = "auto",
199
+ ): FormattedCodeSearchResults {
200
+ const autoMode = requestedMode === "auto" ? resolveAutoMode(hits) : requestedMode;
201
+
202
+ if (autoMode === "full") {
203
+ return decorateResult(
204
+ {
205
+ text: hits.map(fullHit).join("\n\n"),
206
+ mode: "full",
207
+ truncated: false,
208
+ },
209
+ requestedMode,
210
+ hits.length,
211
+ );
212
+ }
213
+
214
+ if (autoMode === "summary") {
215
+ const bounded = applyBudget(hits.map(summaryHit), AUTO_OUTPUT_BUDGET);
216
+ return decorateResult({ ...bounded, mode: "summary" }, requestedMode, hits.length);
217
+ }
218
+
219
+ if (autoMode === "preview") {
220
+ const bounded = applyBudget(
221
+ hits.map((hit) => queryPreview(hit, query)),
222
+ AUTO_OUTPUT_BUDGET,
223
+ );
224
+ return decorateResult({ ...bounded, mode: "preview" }, requestedMode, hits.length);
225
+ }
226
+
227
+ // Automatic mode for many results: preserve useful body context for the
228
+ // highest-ranked few hits and keep the rest as cheap navigational metadata.
229
+ const topPreview = hits
230
+ .slice(0, AUTO_PREVIEW_HIT_LIMIT)
231
+ .map((hit) => queryPreview(hit, query));
232
+ const remainingSummary = hits
233
+ .slice(AUTO_PREVIEW_HIT_LIMIT)
234
+ .map(summaryHit);
235
+ const bounded = applyBudget([...topPreview, ...remainingSummary], AUTO_OUTPUT_BUDGET);
236
+ return decorateResult({ ...bounded, mode: "mixed" }, requestedMode, hits.length);
237
+ }
@@ -1,8 +1,8 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
3
  import { Text, makeOutputText } from "../ui/tui_utils";
4
- import * as path from "node:path";
5
4
  import { globalEpistemicGuard } from "../safety/epistemic_guard";
5
+ import { formatCodeSearchResults, CODE_SEARCH_MODES, type CodeSearchMode } from "./code_search_output";
6
6
  import type { SearchDeps } from "./context";
7
7
 
8
8
  /** Extracted from index.ts — registers the `code_search` tool. */
@@ -15,32 +15,38 @@ export function registerCodeSearchTool(
15
15
  name: "code_search",
16
16
  label: "Codebase Search",
17
17
  description:
18
- "Search the codebase using hybrid BM25 and semantic ranking across AST-bounded code chunks with hierarchical breadcrumbs. Ideal for conceptual queries, keywords, and finding relevant functions.",
19
- promptSnippet:
20
- "Search codebase conceptually or by keywords via hybrid AST index",
18
+ "Search codebase using BM25 and semantic ranking across code chunks. Default scope is 'code' (use 'all' for prose).",
19
+ promptSnippet: "Search codebase conceptually or by keywords via hybrid AST index",
21
20
  renderShell: "default",
22
21
  parameters: Type.Object({
23
22
  query: Type.String({
24
- description:
25
- "Search query: natural language concepts, variable names, error messages, or task descriptions",
23
+ description: "Search query keywords, symbols, or concepts",
26
24
  }),
27
25
  file_pattern: Type.Optional(
28
26
  Type.String({
29
- description:
30
- "Optional normalized relative path substring (e.g. 'src/auth', '.py', 'test')",
27
+ description: "Optional relative path substring filter",
31
28
  }),
32
29
  ),
33
30
  limit: Type.Optional(
34
31
  Type.Number({
35
- description:
36
- "Maximum number of code chunks to return (default: 5, max: 15)",
32
+ description: "Max results (default: 5, max: 15)",
37
33
  }),
38
34
  ),
39
35
  rrf_k: Type.Optional(
40
36
  Type.Number({
41
- description: "Optional RRF smoothing constant from 1 to 200 (default: 60)",
37
+ description: "RRF constant (default: 60)",
42
38
  }),
43
39
  ),
40
+ mode: Type.Optional(
41
+ Type.Union(CODE_SEARCH_MODES.map((mode) => Type.Literal(mode))),
42
+ ),
43
+ scope: Type.Optional(
44
+ Type.Union([
45
+ Type.Literal("code"),
46
+ Type.Literal("all"),
47
+ Type.Literal("prose"),
48
+ ]),
49
+ ),
44
50
  }),
45
51
  async execute(
46
52
  _toolCallId: string,
@@ -58,6 +64,30 @@ export function registerCodeSearchTool(
58
64
  };
59
65
  }
60
66
 
67
+ const requestedMode = params.mode ?? "auto";
68
+ if (!(CODE_SEARCH_MODES as readonly string[]).includes(requestedMode)) {
69
+ return {
70
+ content: [{
71
+ type: "text",
72
+ text: `[ERROR] Invalid mode "${String(requestedMode)}". Use auto, full, preview, or summary.`,
73
+ }],
74
+ details: { count: 0 },
75
+ isError: true,
76
+ };
77
+ }
78
+
79
+ const scope = params.scope ?? "code";
80
+ if (!["code", "all", "prose"].includes(scope)) {
81
+ return {
82
+ content: [{
83
+ type: "text",
84
+ text: `[ERROR] Invalid scope "${String(scope)}". Use code, all, or prose.`,
85
+ }],
86
+ details: { count: 0 },
87
+ isError: true,
88
+ };
89
+ }
90
+
61
91
  onUpdate?.({
62
92
  content: [{ type: "text", text: `Searching code for "${query}"...` }],
63
93
  });
@@ -72,6 +102,7 @@ export function registerCodeSearchTool(
72
102
  limit,
73
103
  filePattern: params.file_pattern,
74
104
  rrfK: params.rrf_k,
105
+ scope,
75
106
  });
76
107
 
77
108
  const sessionId = deps.getSessionId(ctx);
@@ -100,22 +131,25 @@ export function registerCodeSearchTool(
100
131
  };
101
132
  }
102
133
 
103
- const formatted = hits.map((hit) => {
104
- const chunk = hit.chunk;
105
- const normPath = chunk.filePath.replace(/\\/g, "/");
106
- const lang = path.extname(chunk.filePath).slice(1) || "text";
107
- return `${normPath}:${chunk.startLine}-${chunk.endLine} [${chunk.kind}] ${chunk.symbolName} (${chunk.breadcrumb}):\n\`\`\`${lang}\n${chunk.content}\n\`\`\``;
108
- });
134
+ const formatted = formatCodeSearchResults(
135
+ hits,
136
+ query,
137
+ requestedMode as CodeSearchMode,
138
+ );
109
139
 
110
140
  return {
111
141
  content: [
112
142
  {
113
143
  type: "text",
114
- text: formatted.join("\n\n"),
144
+ text: formatted.text,
115
145
  },
116
146
  ],
117
147
  details: {
118
148
  count: hits.length,
149
+ mode: formatted.mode,
150
+ requestedMode,
151
+ scope,
152
+ truncated: formatted.truncated,
119
153
  hits: hits.map((h) => ({
120
154
  id: h.chunk.id,
121
155
  score: h.rrfScore,
@@ -1,20 +1,20 @@
1
- /**
2
- * Shared dependencies injected from the kernel entry point into tool modules.
3
- * Keeps tool registration pure: no hidden singletons, everything flows through
4
- * these explicit contracts.
5
- */
6
- export interface SessionDeps {
7
- /** Resolve stable session id for epistemic-guard bookkeeping. */
8
- getSessionId: (ctx: any) => string;
9
- /** Load runtime settings for the active workspace. */
10
- getConfig?: (cwd: string) => import("../config").KernelConfig;
11
- /** Mark a successfully mutated file stale in the workspace index. */
12
- invalidateSearchFile?: (cwd: string, filePath: string) => void;
13
- }
14
-
15
- export interface SearchDeps extends SessionDeps {
16
- /** Lazily create/access the workspace hybrid search index singleton. */
17
- getSearchIndex: (
18
- cwd: string,
19
- ) => import("../retrieval/search_index").HybridSearchIndex;
20
- }
1
+ /**
2
+ * Shared dependencies injected from the kernel entry point into tool modules.
3
+ * Keeps tool registration pure: no hidden singletons, everything flows through
4
+ * these explicit contracts.
5
+ */
6
+ export interface SessionDeps {
7
+ /** Resolve stable session id for epistemic-guard bookkeeping. */
8
+ getSessionId: (ctx: any) => string;
9
+ /** Load runtime settings for the active workspace. */
10
+ getConfig?: (cwd: string) => import("../config").KernelConfig;
11
+ /** Mark a successfully mutated file stale in the workspace index. */
12
+ invalidateSearchFile?: (cwd: string, filePath: string) => void;
13
+ }
14
+
15
+ export interface SearchDeps extends SessionDeps {
16
+ /** Lazily create/access the workspace hybrid search index singleton. */
17
+ getSearchIndex: (
18
+ cwd: string,
19
+ ) => import("../retrieval/search_index").HybridSearchIndex;
20
+ }
@@ -30,21 +30,20 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
30
30
  name: "edit",
31
31
  label: "Surgical Code Editor",
32
32
  description:
33
- "Surgically edit code using search/replace blocks with multi-strategy fuzzy matching and automatic syntax verification. Supports single search/replace and multi-block edits.",
34
- promptSnippet:
35
- "Surgically edit code using search/replace blocks with automatic syntax verification",
33
+ "Surgically edit code using search/replace blocks with syntax verification. Supports single or multi-block edits.",
34
+ promptSnippet: "Edit code using search/replace blocks",
36
35
  renderShell: "default",
37
36
  parameters: Type.Object({
38
37
  path: Type.String({
39
- description: "File path (absolute or relative) to the file to edit",
38
+ description: "File path to edit",
40
39
  }),
41
40
  search: Type.Optional(
42
41
  Type.String({
43
- description: "Exact or near-exact lines of code to replace (single block)",
42
+ description: "Lines of code to replace (single block)",
44
43
  }),
45
44
  ),
46
45
  replace: Type.Optional(
47
- Type.String({ description: "New replacement code lines (single block)" }),
46
+ Type.String({ description: "Replacement code lines (single block)" }),
48
47
  ),
49
48
  edits: Type.Optional(
50
49
  Type.Array(
@@ -54,7 +53,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
54
53
  }),
55
54
  {
56
55
  description:
57
- "Optional list of multiple disjoint search/replace blocks to apply atomically",
56
+ "List of multiple disjoint search/replace blocks to apply atomically",
58
57
  },
59
58
  ),
60
59
  ),