@floydous/pi-agent-kernel 0.1.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/LICENSE +15 -0
- package/README.md +108 -0
- package/config.toml +24 -0
- package/docs/README.md +22 -0
- package/docs/architecture.md +40 -0
- package/docs/configuration.md +43 -0
- package/docs/editing-and-verification.md +41 -0
- package/docs/lsp.md +31 -0
- package/docs/retrieval.md +42 -0
- package/docs/testing.md +32 -0
- package/package.json +48 -0
- package/src/config/index.ts +2 -0
- package/src/config/kernel_config.ts +218 -0
- package/src/config/toml.ts +237 -0
- package/src/context/session_repair.ts +99 -0
- package/src/dedup/content_store.ts +365 -0
- package/src/dedup/recall_tool.ts +157 -0
- package/src/editing/patch.ts +482 -0
- package/src/editing/post_edit_verification.ts +200 -0
- package/src/editing/syntax-verify.ts +353 -0
- package/src/index.ts +852 -0
- package/src/lsp/adapters/base.ts +42 -0
- package/src/lsp/adapters/index.ts +21 -0
- package/src/lsp/adapters/python.ts +37 -0
- package/src/lsp/adapters/rust.ts +35 -0
- package/src/lsp/adapters/typescript.ts +40 -0
- package/src/lsp/index.ts +13 -0
- package/src/lsp/lsp_client.ts +650 -0
- package/src/lsp/lsp_detector.ts +52 -0
- package/src/lsp/lsp_formatter.ts +284 -0
- package/src/lsp/lsp_installer.ts +604 -0
- package/src/lsp/lsp_manager.ts +202 -0
- package/src/lsp/lsp_modal.ts +675 -0
- package/src/lsp/lsp_registry.ts +539 -0
- package/src/lsp/lsp_types.ts +143 -0
- package/src/retrieval/ast_search.ts +926 -0
- package/src/retrieval/repomap.ts +779 -0
- package/src/retrieval/search_bm25.ts +190 -0
- package/src/retrieval/search_chunker.ts +251 -0
- package/src/retrieval/search_config.ts +162 -0
- package/src/retrieval/search_embedder.ts +362 -0
- package/src/retrieval/search_index.ts +753 -0
- package/src/retrieval/search_modal.ts +358 -0
- package/src/retrieval/symbol_reader.ts +200 -0
- package/src/safety/atomic_write.ts +26 -0
- package/src/safety/epistemic_guard.ts +733 -0
- package/src/safety/kernel_debug.ts +15 -0
- package/src/safety/output_clamper.ts +213 -0
- package/src/tools/ast_search_tool.ts +131 -0
- package/src/tools/code_search_tool.ts +147 -0
- package/src/tools/context.ts +20 -0
- package/src/tools/edit_tool.ts +288 -0
- package/src/tools/lsp_tool.ts +813 -0
- package/src/tools/read_tool.ts +348 -0
- package/src/tools/repo_map_tool.ts +57 -0
- package/src/ui/footer.ts +287 -0
- package/src/ui/tui_utils.ts +278 -0
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { Text, makeOutputText } from "../ui/tui_utils";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import { extractSymbolContent } from "../retrieval/symbol_reader";
|
|
7
|
+
import {
|
|
8
|
+
globalEpistemicGuard,
|
|
9
|
+
resolveUserPath,
|
|
10
|
+
} from "../safety/epistemic_guard";
|
|
11
|
+
import type { SessionDeps } from "./context";
|
|
12
|
+
|
|
13
|
+
function countFileLines(filePath: string): number {
|
|
14
|
+
return fs.readFileSync(filePath, "utf8").split("\n").length;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Extracted from index.ts — registers the `read` tool. */
|
|
18
|
+
export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
19
|
+
// 6. Tool: `read` (Unified File Reader with Surgical AST Symbol Extraction - Replaces stock read tool)
|
|
20
|
+
const readToolDefinition: any = {
|
|
21
|
+
name: "read",
|
|
22
|
+
label: "Read File / Symbol",
|
|
23
|
+
description:
|
|
24
|
+
"Read file contents (text/images) or surgically extract specific AST code symbols (function, class, method, interface, type). Supports optional pagination ('offset', 'limit') or direct surgical extraction via 'symbol'.",
|
|
25
|
+
promptSnippet:
|
|
26
|
+
"Read file contents or surgically extract specific AST code symbols via 'symbol'",
|
|
27
|
+
renderShell: "default",
|
|
28
|
+
parameters: Type.Object({
|
|
29
|
+
path: Type.String({
|
|
30
|
+
description: "Path to the file to read (relative or absolute)",
|
|
31
|
+
}),
|
|
32
|
+
symbol: Type.Optional(
|
|
33
|
+
Type.String({
|
|
34
|
+
description:
|
|
35
|
+
"Optional name of the function, class, method, or type to extract surgically from the file without paging",
|
|
36
|
+
}),
|
|
37
|
+
),
|
|
38
|
+
offset: Type.Optional(
|
|
39
|
+
Type.Number({
|
|
40
|
+
description:
|
|
41
|
+
"Line number to start reading from (1-indexed, for full file reading)",
|
|
42
|
+
}),
|
|
43
|
+
),
|
|
44
|
+
limit: Type.Optional(
|
|
45
|
+
Type.Number({
|
|
46
|
+
description: "Maximum number of lines to read (for full file reading)",
|
|
47
|
+
}),
|
|
48
|
+
),
|
|
49
|
+
surrounding_lines: Type.Optional(
|
|
50
|
+
Type.Number({
|
|
51
|
+
description:
|
|
52
|
+
"Optional extra lines of surrounding context when extracting a symbol (default: 0)",
|
|
53
|
+
}),
|
|
54
|
+
),
|
|
55
|
+
}),
|
|
56
|
+
async execute(
|
|
57
|
+
_toolCallId: string,
|
|
58
|
+
params: any,
|
|
59
|
+
_signal: any,
|
|
60
|
+
onUpdate: any,
|
|
61
|
+
ctx: any,
|
|
62
|
+
): Promise<any> {
|
|
63
|
+
if (!params || typeof params !== "object" || !params.path) {
|
|
64
|
+
return {
|
|
65
|
+
content: [
|
|
66
|
+
{ type: "text", text: "[READ ERROR] Missing required 'path' parameter." },
|
|
67
|
+
],
|
|
68
|
+
isError: true,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const resolvedPath = resolveUserPath(params.path, ctx.cwd);
|
|
73
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
74
|
+
return {
|
|
75
|
+
content: [{ type: "text", text: `File not found: ${params.path}` }],
|
|
76
|
+
isError: true,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Mode 1: Targeted AST symbol extraction
|
|
81
|
+
if (params.symbol && params.symbol.trim()) {
|
|
82
|
+
const sym = params.symbol.trim();
|
|
83
|
+
onUpdate?.({
|
|
84
|
+
content: [
|
|
85
|
+
{
|
|
86
|
+
type: "text",
|
|
87
|
+
text: `Extracting symbol '${sym}' from ${params.path}...`,
|
|
88
|
+
},
|
|
89
|
+
],
|
|
90
|
+
});
|
|
91
|
+
let symbolSnapshot: string;
|
|
92
|
+
try {
|
|
93
|
+
symbolSnapshot = fs.readFileSync(resolvedPath, "utf8");
|
|
94
|
+
} catch (error: any) {
|
|
95
|
+
return {
|
|
96
|
+
content: [
|
|
97
|
+
{ type: "text", text: `[READ ERROR] Unable to read ${params.path}: ${error.message}` },
|
|
98
|
+
],
|
|
99
|
+
isError: true,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const res = extractSymbolContent(
|
|
103
|
+
resolvedPath,
|
|
104
|
+
sym,
|
|
105
|
+
{ surroundingLines: params.surrounding_lines },
|
|
106
|
+
symbolSnapshot,
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
if (!res.found) {
|
|
110
|
+
return {
|
|
111
|
+
content: [
|
|
112
|
+
{
|
|
113
|
+
type: "text",
|
|
114
|
+
text:
|
|
115
|
+
res.error ||
|
|
116
|
+
`Symbol '${sym}' not found in ${params.path}. Use 'ast_search' to locate symbols or 'rg' in bash to search text.`,
|
|
117
|
+
},
|
|
118
|
+
],
|
|
119
|
+
isError: true,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Record the exact snapshot used for extraction only after a successful
|
|
124
|
+
// symbol result; failed extraction must not authorize a mutation.
|
|
125
|
+
globalEpistemicGuard.recordFileRead(
|
|
126
|
+
resolvedPath,
|
|
127
|
+
deps.getSessionId(ctx),
|
|
128
|
+
ctx.cwd,
|
|
129
|
+
symbolSnapshot,
|
|
130
|
+
{
|
|
131
|
+
coverage: {
|
|
132
|
+
complete: false,
|
|
133
|
+
ranges: res.symbols.map((symbol) => ({
|
|
134
|
+
startLine: symbol.startLine,
|
|
135
|
+
endLine: symbol.endLine,
|
|
136
|
+
})),
|
|
137
|
+
totalLines: countFileLines(resolvedPath),
|
|
138
|
+
},
|
|
139
|
+
provenance: "symbol",
|
|
140
|
+
query: sym,
|
|
141
|
+
},
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
const formatted = res.symbols
|
|
145
|
+
.map(
|
|
146
|
+
(s) =>
|
|
147
|
+
`// ${path.relative(ctx.cwd, s.filePath) || s.filePath}:${s.startLine}-${s.endLine} [${s.kind}] ${s.name}\n${s.content}`,
|
|
148
|
+
)
|
|
149
|
+
.join("\n\n");
|
|
150
|
+
|
|
151
|
+
return {
|
|
152
|
+
content: [{ type: "text", text: formatted }],
|
|
153
|
+
details: {
|
|
154
|
+
count: res.symbols.length,
|
|
155
|
+
symbols: res.symbols.map((s) => ({
|
|
156
|
+
name: s.name,
|
|
157
|
+
kind: s.kind,
|
|
158
|
+
lines: `${s.startLine}-${s.endLine}`,
|
|
159
|
+
})),
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Mode 2: Standard file reading
|
|
165
|
+
try {
|
|
166
|
+
const ext = path.extname(resolvedPath).toLowerCase();
|
|
167
|
+
const isImage = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"].includes(
|
|
168
|
+
ext,
|
|
169
|
+
);
|
|
170
|
+
if (isImage) {
|
|
171
|
+
const maxImageBytes =
|
|
172
|
+
deps.getConfig?.(ctx.cwd).safety.max_total_bytes ?? 20 * 1024;
|
|
173
|
+
const imageSize = fs.statSync(resolvedPath).size;
|
|
174
|
+
if (imageSize > maxImageBytes) {
|
|
175
|
+
return {
|
|
176
|
+
content: [
|
|
177
|
+
{
|
|
178
|
+
type: "text",
|
|
179
|
+
text: `[READ ERROR] Image is ${imageSize} bytes; maximum allowed is ${maxImageBytes} bytes.`,
|
|
180
|
+
},
|
|
181
|
+
],
|
|
182
|
+
details: { isImage: true, sizeBytes: imageSize, maxImageBytes },
|
|
183
|
+
isError: true,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const mimeMap: Record<string, string> = {
|
|
187
|
+
".png": "image/png",
|
|
188
|
+
".jpg": "image/jpeg",
|
|
189
|
+
".jpeg": "image/jpeg",
|
|
190
|
+
".gif": "image/gif",
|
|
191
|
+
".webp": "image/webp",
|
|
192
|
+
".bmp": "image/bmp",
|
|
193
|
+
};
|
|
194
|
+
const buffer = fs.readFileSync(resolvedPath);
|
|
195
|
+
globalEpistemicGuard.recordFileRead(
|
|
196
|
+
resolvedPath,
|
|
197
|
+
deps.getSessionId(ctx),
|
|
198
|
+
ctx.cwd,
|
|
199
|
+
buffer,
|
|
200
|
+
{
|
|
201
|
+
coverage: { complete: true, ranges: [] },
|
|
202
|
+
provenance: "read",
|
|
203
|
+
},
|
|
204
|
+
);
|
|
205
|
+
const base64 = buffer.toString("base64");
|
|
206
|
+
const mimeType = mimeMap[ext] || "image/png";
|
|
207
|
+
return {
|
|
208
|
+
content: [
|
|
209
|
+
{
|
|
210
|
+
type: "text",
|
|
211
|
+
text: `Read image file [${mimeType}] (${(buffer.length / 1024).toFixed(1)} KB)`,
|
|
212
|
+
},
|
|
213
|
+
{ type: "image", data: base64, mimeType },
|
|
214
|
+
],
|
|
215
|
+
details: { isImage: true, sizeBytes: buffer.length },
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const content = fs.readFileSync(resolvedPath, "utf-8");
|
|
220
|
+
const lines = content.split("\n");
|
|
221
|
+
const totalLines = lines.length;
|
|
222
|
+
|
|
223
|
+
// Validate pagination params explicitly. The previous truthiness
|
|
224
|
+
// check silently coerced offset=0 -> 1, clamped negatives, and
|
|
225
|
+
// treated limit=0 as "use the default 2000" — surprising behavior
|
|
226
|
+
// for an out-of-range request.
|
|
227
|
+
if (
|
|
228
|
+
params.offset !== undefined &&
|
|
229
|
+
(!Number.isFinite(params.offset) || params.offset < 1)
|
|
230
|
+
) {
|
|
231
|
+
return {
|
|
232
|
+
content: [
|
|
233
|
+
{
|
|
234
|
+
type: "text",
|
|
235
|
+
text: `[READ ERROR] Invalid offset=${params.offset}. 'offset' must be a number >= 1 (1-based line number).`,
|
|
236
|
+
},
|
|
237
|
+
],
|
|
238
|
+
details: { offset: params.offset },
|
|
239
|
+
isError: true,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
if (
|
|
243
|
+
params.limit !== undefined &&
|
|
244
|
+
(!Number.isFinite(params.limit) || params.limit < 1)
|
|
245
|
+
) {
|
|
246
|
+
return {
|
|
247
|
+
content: [
|
|
248
|
+
{
|
|
249
|
+
type: "text",
|
|
250
|
+
text: `[READ ERROR] Invalid limit=${params.limit}. 'limit' must be a number >= 1.`,
|
|
251
|
+
},
|
|
252
|
+
],
|
|
253
|
+
details: { limit: params.limit },
|
|
254
|
+
isError: true,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const offset = params.offset ?? 1;
|
|
259
|
+
const limit = params.limit ?? 2000;
|
|
260
|
+
const startIdx = offset - 1;
|
|
261
|
+
|
|
262
|
+
// Offset past the end of file: return a clean error instead of an
|
|
263
|
+
// empty slice with an inverted "Lines N-M" header and bogus hint.
|
|
264
|
+
if (startIdx >= totalLines) {
|
|
265
|
+
return {
|
|
266
|
+
content: [
|
|
267
|
+
{
|
|
268
|
+
type: "text",
|
|
269
|
+
text: `[READ ERROR] offset=${offset} is beyond the end of the file (${totalLines} line${totalLines === 1 ? "" : "s"}). Re-read without 'offset' to see the whole file.`,
|
|
270
|
+
},
|
|
271
|
+
],
|
|
272
|
+
details: { totalLines, offset },
|
|
273
|
+
isError: true,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const endIdx = Math.min(totalLines, startIdx + limit);
|
|
278
|
+
|
|
279
|
+
const selectedLines = lines.slice(startIdx, endIdx);
|
|
280
|
+
const isTruncated = endIdx < totalLines || startIdx > 0;
|
|
281
|
+
|
|
282
|
+
let output = selectedLines.join("\n");
|
|
283
|
+
if (isTruncated) {
|
|
284
|
+
output += `\n\n[Lines ${offset}-${endIdx}/${totalLines}. Next: offset=${endIdx + 1}]`;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Record only after all bounds and pagination checks have succeeded.
|
|
288
|
+
globalEpistemicGuard.recordFileRead(
|
|
289
|
+
resolvedPath,
|
|
290
|
+
deps.getSessionId(ctx),
|
|
291
|
+
ctx.cwd,
|
|
292
|
+
content,
|
|
293
|
+
{
|
|
294
|
+
coverage: {
|
|
295
|
+
complete: !isTruncated,
|
|
296
|
+
ranges: [{ startLine: offset, endLine: endIdx }],
|
|
297
|
+
totalLines,
|
|
298
|
+
},
|
|
299
|
+
provenance: "read",
|
|
300
|
+
},
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
return {
|
|
304
|
+
content: [{ type: "text", text: output }],
|
|
305
|
+
details: { totalLines, offset, limit, shownLines: selectedLines.length },
|
|
306
|
+
};
|
|
307
|
+
} catch (err: any) {
|
|
308
|
+
return {
|
|
309
|
+
content: [{ type: "text", text: `Failed to read file: ${err.message}` }],
|
|
310
|
+
isError: true,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
},
|
|
314
|
+
renderCall(args: any, theme: any, context: any) {
|
|
315
|
+
const rawPath = args?.path || "";
|
|
316
|
+
const relPath = rawPath
|
|
317
|
+
? path.relative(context.cwd, rawPath) || rawPath
|
|
318
|
+
: "";
|
|
319
|
+
if (args?.symbol) {
|
|
320
|
+
return makeOutputText(
|
|
321
|
+
`${theme.fg("toolTitle", theme.bold("read"))} ${theme.fg("accent", args.symbol)} in ${theme.fg("dim", relPath)}`,
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
const range =
|
|
325
|
+
args?.offset || args?.limit
|
|
326
|
+
? `:${args.offset ?? 1}${args.limit ? `-${(args.offset ?? 1) + args.limit - 1}` : ""}`
|
|
327
|
+
: "";
|
|
328
|
+
return makeOutputText(
|
|
329
|
+
`${theme.fg("toolTitle", theme.bold("read"))} ${theme.fg("accent", relPath)}${theme.fg("warning", range)}`,
|
|
330
|
+
);
|
|
331
|
+
},
|
|
332
|
+
renderResult(result: any, options: any, theme: any, context: any) {
|
|
333
|
+
if (context.isError) {
|
|
334
|
+
const errMsg =
|
|
335
|
+
result.content?.find((c: any) => c.type === "text")?.text || "Read failed";
|
|
336
|
+
return makeOutputText(`\n${theme.fg("error", errMsg)}`);
|
|
337
|
+
}
|
|
338
|
+
if (!options.expanded) {
|
|
339
|
+
return new Text("", 0, 0);
|
|
340
|
+
}
|
|
341
|
+
const output =
|
|
342
|
+
result.content?.find((c: any) => c.type === "text")?.text || "";
|
|
343
|
+
return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
|
|
344
|
+
},
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
pi.registerTool(readToolDefinition);
|
|
348
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { Text, makeOutputText } from "../ui/tui_utils";
|
|
4
|
+
import { computeRepoMap } from "../retrieval/repomap";
|
|
5
|
+
import { loadKernelConfig } from "../config";
|
|
6
|
+
|
|
7
|
+
/** Extracted from index.ts — registers the `repo_map` tool. */
|
|
8
|
+
export function registerRepoMapTool(pi: ExtensionAPI): void {
|
|
9
|
+
// 4. Tool: `get_repo_map` (Tree-sitter PageRank Map)
|
|
10
|
+
pi.registerTool({
|
|
11
|
+
name: "get_repo_map",
|
|
12
|
+
label: "Get Repository Map",
|
|
13
|
+
description:
|
|
14
|
+
"Get a concise, PageRank-ranked AST map of classes, functions, and symbols across the entire repository (~1k tokens).",
|
|
15
|
+
promptSnippet: "Inspect repository AST symbol graph and signatures",
|
|
16
|
+
renderShell: "default",
|
|
17
|
+
parameters: Type.Object({
|
|
18
|
+
budget_tokens: Type.Optional(
|
|
19
|
+
Type.Number({ description: "Target token budget (default: 1024)" }),
|
|
20
|
+
),
|
|
21
|
+
}),
|
|
22
|
+
async execute(
|
|
23
|
+
_toolCallId: string,
|
|
24
|
+
params: any,
|
|
25
|
+
_signal: any,
|
|
26
|
+
_onUpdate: any,
|
|
27
|
+
ctx: any,
|
|
28
|
+
) {
|
|
29
|
+
const configuredBudget = loadKernelConfig(ctx.cwd).retrieval.repo_map_budget;
|
|
30
|
+
const budget = params.budget_tokens ?? configuredBudget;
|
|
31
|
+
const repoMap = computeRepoMap(ctx.cwd, budget);
|
|
32
|
+
return {
|
|
33
|
+
content: [{ type: "text", text: repoMap }],
|
|
34
|
+
details: { budget, length: repoMap.length },
|
|
35
|
+
};
|
|
36
|
+
},
|
|
37
|
+
renderCall(args: any, theme: any, _context: any) {
|
|
38
|
+
return makeOutputText(
|
|
39
|
+
`${theme.fg("toolTitle", theme.bold("get_repo_map"))} (budget: ${args?.budget_tokens ?? 1024})`,
|
|
40
|
+
);
|
|
41
|
+
},
|
|
42
|
+
renderResult(result: any, options: any, theme: any, context: any) {
|
|
43
|
+
if (context.isError) {
|
|
44
|
+
const errMsg =
|
|
45
|
+
result.content?.find((c: any) => c.type === "text")?.text ||
|
|
46
|
+
"Repo map failed";
|
|
47
|
+
return makeOutputText(`\n${theme.fg("error", errMsg)}`);
|
|
48
|
+
}
|
|
49
|
+
if (!options.expanded) {
|
|
50
|
+
return new Text("", 0, 0);
|
|
51
|
+
}
|
|
52
|
+
const output =
|
|
53
|
+
result.content?.find((c: any) => c.type === "text")?.text || "";
|
|
54
|
+
return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
}
|
package/src/ui/footer.ts
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unified Integrated Footer Component
|
|
3
|
+
*
|
|
4
|
+
* Implements clean bullet-separated layout:
|
|
5
|
+
* `<workspace> (branch) • <search:profile> • <context_usage / context_window> • <token I/O> <model> • <thinking>`
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
9
|
+
import { getSearchConfig } from "../retrieval/search_config";
|
|
10
|
+
import { loadKernelConfig } from "../config";
|
|
11
|
+
import { truncateToWidth, visibleWidth } from "./tui_utils";
|
|
12
|
+
|
|
13
|
+
export { stripAnsi, truncateToWidth, visibleWidth } from "./tui_utils";
|
|
14
|
+
|
|
15
|
+
export interface FooterTheme {
|
|
16
|
+
fg(color: string, text: string): string;
|
|
17
|
+
bold(text: string): string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface FooterDataProvider {
|
|
21
|
+
getGitBranch(): string | null;
|
|
22
|
+
getExtensionStatuses(): ReadonlyMap<string, string>;
|
|
23
|
+
getAvailableProviderCount(): number;
|
|
24
|
+
onBranchChange(listener: () => void): () => void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Aesthetic Semantic Pastel Color Palette (TrueColor 24-bit ANSI)
|
|
29
|
+
* Designed for low visual fatigue and crisp semantic hierarchy.
|
|
30
|
+
*/
|
|
31
|
+
const RESET = "\x1b[0m";
|
|
32
|
+
export const Pastel = {
|
|
33
|
+
reset: RESET,
|
|
34
|
+
bullet: "\x1b[38;2;95;105;120m•\x1b[0m", // Muted slate delimiter (#5f6978)
|
|
35
|
+
|
|
36
|
+
// Workspace & Branch
|
|
37
|
+
path: (s: string) => `\x1b[38;2;140;185;215m${s}${RESET}`, // Soft Ice Cyan (#8cb9d7)
|
|
38
|
+
branch: (s: string) => `\x1b[38;2;185;165;225m${s}${RESET}`, // Soft Lavender (#b9a5e1)
|
|
39
|
+
|
|
40
|
+
// Search Engine Profiles
|
|
41
|
+
searchLean: (s: string) => `\x1b[38;2;135;205;195m${s}${RESET}`, // Pastel Seafoam (#87cdc3)
|
|
42
|
+
searchHybrid: (s: string) => `\x1b[38;2;195;165;215m${s}${RESET}`, // Pastel Lilac (#c3a5d7)
|
|
43
|
+
searchFull: (s: string) => `\x1b[38;2;165;175;235m${s}${RESET}`, // Pastel Periwinkle (#a5afeb)
|
|
44
|
+
searchOff: (s: string) => `\x1b[38;2;135;140;150m${s}${RESET}`, // Muted Slate (#878c96)
|
|
45
|
+
|
|
46
|
+
// Context Window Usage (Semantic Gauge)
|
|
47
|
+
contextGood: (s: string) => `\x1b[38;2;155;210;170m${s}${RESET}`, // Pastel Mint (#9bd2aa) < 70%
|
|
48
|
+
contextWarn: (s: string) => `\x1b[38;2;245;195;125m${s}${RESET}`, // Pastel Apricot (#f5c37d) 70-90%
|
|
49
|
+
contextCrit: (s: string) => `\x1b[38;2;240;140;145m${s}${RESET}`, // Pastel Soft Rose (#f08c91) > 90%
|
|
50
|
+
|
|
51
|
+
// Token I/O & Cost
|
|
52
|
+
tokenIO: (s: string) => `\x1b[38;2;170;180;195m${s}${RESET}`, // Pastel Slate Gray (#aab4c3)
|
|
53
|
+
tokenCost: (s: string) => `\x1b[38;2;225;215;140m${s}${RESET}`, // Pastel Pale Gold (#e1d78c)
|
|
54
|
+
|
|
55
|
+
// Model & Reasoning
|
|
56
|
+
provider: (s: string) => `\x1b[38;2;140;150;165m${s}${RESET}`, // Slate Dim
|
|
57
|
+
model: (s: string) => `\x1b[38;2;225;230;240m${s}${RESET}`, // Soft Pearl White (#e1e6f0)
|
|
58
|
+
thinking: (s: string) => `\x1b[38;2;180;170;220m${s}${RESET}`, // Pastel Wisteria (#b4aadc)
|
|
59
|
+
thinkingOff: (s: string) => `\x1b[38;2;135;140;150m${s}${RESET}`, // Muted Dim (#878c96)
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Format numbers into compact token strings (e.g. 1.2k, 45k, 1.2M)
|
|
64
|
+
*/
|
|
65
|
+
export function formatTokens(count: number): string {
|
|
66
|
+
if (isNaN(count) || count < 0) return "0";
|
|
67
|
+
if (count < 1000) return count.toString();
|
|
68
|
+
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
|
|
69
|
+
if (count < 1000000) return `${Math.round(count / 1000)}k`;
|
|
70
|
+
if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;
|
|
71
|
+
return `${Math.round(count / 1000000)}M`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Format working directory path using `~` shorthand
|
|
76
|
+
*/
|
|
77
|
+
export function formatCwd(
|
|
78
|
+
cwd: string,
|
|
79
|
+
home: string = process.env.HOME || process.env.USERPROFILE || "",
|
|
80
|
+
): string {
|
|
81
|
+
if (!home || !cwd) return cwd || ".";
|
|
82
|
+
try {
|
|
83
|
+
const resolvedCwd = resolve(cwd);
|
|
84
|
+
const resolvedHome = resolve(home);
|
|
85
|
+
const rel = relative(resolvedHome, resolvedCwd);
|
|
86
|
+
const isInsideHome =
|
|
87
|
+
rel === "" ||
|
|
88
|
+
(rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
89
|
+
if (!isInsideHome) return cwd;
|
|
90
|
+
return rel === "" ? "~" : `~${sep}${rel}`.replace(/\\/g, "/");
|
|
91
|
+
} catch {
|
|
92
|
+
return cwd;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Format search engine mode tag with technical naming and semantic pastel colors:
|
|
98
|
+
* - Lean -> `retrieval:bm25`
|
|
99
|
+
* - Hybrid -> `retrieval:hybrid-256d`
|
|
100
|
+
* - Full -> `retrieval:dense-768d`
|
|
101
|
+
* - Off -> `retrieval:off`
|
|
102
|
+
*/
|
|
103
|
+
export function formatSearchEngineTag(
|
|
104
|
+
searchIndexOrProfile?: any,
|
|
105
|
+
withColor = true,
|
|
106
|
+
): string {
|
|
107
|
+
let eff = "lean";
|
|
108
|
+
if (!searchIndexOrProfile) {
|
|
109
|
+
try {
|
|
110
|
+
eff = getSearchConfig().effectiveProfile;
|
|
111
|
+
} catch {
|
|
112
|
+
eff = "lean";
|
|
113
|
+
}
|
|
114
|
+
} else if (typeof searchIndexOrProfile === "string") {
|
|
115
|
+
eff = searchIndexOrProfile.toLowerCase();
|
|
116
|
+
} else if (typeof searchIndexOrProfile.getEffectiveProfile === "function") {
|
|
117
|
+
eff = searchIndexOrProfile.getEffectiveProfile();
|
|
118
|
+
} else if (typeof searchIndexOrProfile.getProfile === "function") {
|
|
119
|
+
eff = searchIndexOrProfile.getProfile();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
let label = "retrieval:bm25";
|
|
123
|
+
if (eff === "lean") {
|
|
124
|
+
label = "retrieval:bm25";
|
|
125
|
+
return withColor ? Pastel.searchLean(label) : label;
|
|
126
|
+
}
|
|
127
|
+
if (eff === "hybrid") {
|
|
128
|
+
label = "retrieval:hybrid-256d";
|
|
129
|
+
return withColor ? Pastel.searchHybrid(label) : label;
|
|
130
|
+
}
|
|
131
|
+
if (eff === "full") {
|
|
132
|
+
label = "retrieval:dense-768d";
|
|
133
|
+
return withColor ? Pastel.searchFull(label) : label;
|
|
134
|
+
}
|
|
135
|
+
label = `retrieval:${eff}`;
|
|
136
|
+
return withColor ? Pastel.searchOff(label) : label;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Render the unified footer lines with rich semantic pastel styling
|
|
141
|
+
*/
|
|
142
|
+
export function renderFooter(
|
|
143
|
+
ctx: any,
|
|
144
|
+
theme: FooterTheme,
|
|
145
|
+
footerData: FooterDataProvider,
|
|
146
|
+
width: number,
|
|
147
|
+
searchIndex?: any,
|
|
148
|
+
): string[] {
|
|
149
|
+
const parts: string[] = [];
|
|
150
|
+
const rawCwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
151
|
+
const config = loadKernelConfig(rawCwd);
|
|
152
|
+
if (!config.ui.enable_pastel_footer) {
|
|
153
|
+
return [truncateToWidth(formatCwd(rawCwd), width, "...")];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// 1. Workspace & Branch
|
|
157
|
+
const pwdStr = formatCwd(rawCwd);
|
|
158
|
+
const branch = footerData?.getGitBranch?.();
|
|
159
|
+
let workspaceFormatted = Pastel.path(pwdStr);
|
|
160
|
+
if (branch) {
|
|
161
|
+
workspaceFormatted += ` ${Pastel.branch(`(${branch})`)}`;
|
|
162
|
+
}
|
|
163
|
+
parts.push(workspaceFormatted);
|
|
164
|
+
|
|
165
|
+
// 2. Search Engine Mode
|
|
166
|
+
const searchTag = formatSearchEngineTag(searchIndex, true);
|
|
167
|
+
parts.push(searchTag);
|
|
168
|
+
|
|
169
|
+
// 3. Context Window Usage
|
|
170
|
+
const contextUsage = ctx.getContextUsage?.();
|
|
171
|
+
const model = ctx.model;
|
|
172
|
+
const contextWindow = contextUsage?.contextWindow ?? model?.contextWindow ?? 0;
|
|
173
|
+
const percentValue = contextUsage?.percent;
|
|
174
|
+
const tokensValue = contextUsage?.tokens;
|
|
175
|
+
|
|
176
|
+
if (contextWindow > 0) {
|
|
177
|
+
let rawContextStr: string;
|
|
178
|
+
if (tokensValue !== null && tokensValue !== undefined) {
|
|
179
|
+
const pctStr =
|
|
180
|
+
percentValue !== null && percentValue !== undefined
|
|
181
|
+
? ` (${percentValue.toFixed(0)}%)`
|
|
182
|
+
: "";
|
|
183
|
+
rawContextStr = `${formatTokens(tokensValue)}/${formatTokens(contextWindow)}${pctStr}`;
|
|
184
|
+
} else if (percentValue !== null && percentValue !== undefined) {
|
|
185
|
+
rawContextStr = `${percentValue.toFixed(1)}%/${formatTokens(contextWindow)}`;
|
|
186
|
+
} else {
|
|
187
|
+
rawContextStr = `0/${formatTokens(contextWindow)}`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Colorize semantically based on context window load
|
|
191
|
+
let formattedContext: string;
|
|
192
|
+
if (percentValue !== null && percentValue !== undefined) {
|
|
193
|
+
if (percentValue > 90) {
|
|
194
|
+
formattedContext = Pastel.contextCrit(rawContextStr);
|
|
195
|
+
} else if (percentValue > 70) {
|
|
196
|
+
formattedContext = Pastel.contextWarn(rawContextStr);
|
|
197
|
+
} else {
|
|
198
|
+
formattedContext = Pastel.contextGood(rawContextStr);
|
|
199
|
+
}
|
|
200
|
+
} else {
|
|
201
|
+
formattedContext = Pastel.contextGood(rawContextStr);
|
|
202
|
+
}
|
|
203
|
+
parts.push(formattedContext);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// 4. Cumulative Token I/O & Cost
|
|
207
|
+
let totalIn = 0;
|
|
208
|
+
let totalOut = 0;
|
|
209
|
+
let totalCost = 0;
|
|
210
|
+
const entries = ctx.sessionManager?.getEntries?.() || [];
|
|
211
|
+
for (const entry of entries) {
|
|
212
|
+
if (
|
|
213
|
+
entry.type === "message" &&
|
|
214
|
+
entry.message?.role === "assistant" &&
|
|
215
|
+
entry.message.usage
|
|
216
|
+
) {
|
|
217
|
+
totalIn += entry.message.usage.input || 0;
|
|
218
|
+
totalOut += entry.message.usage.output || 0;
|
|
219
|
+
totalCost += entry.message.usage.cost?.total || 0;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (totalIn > 0 || totalOut > 0) {
|
|
224
|
+
let ioFormatted = Pastel.tokenIO(
|
|
225
|
+
`↑${formatTokens(totalIn)} ↓${formatTokens(totalOut)}`,
|
|
226
|
+
);
|
|
227
|
+
if (totalCost > 0) {
|
|
228
|
+
const costStr = `$${totalCost.toFixed(3)}`;
|
|
229
|
+
ioFormatted += ` ${Pastel.tokenCost(costStr)}`;
|
|
230
|
+
}
|
|
231
|
+
parts.push(ioFormatted);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const left = parts.join(` ${Pastel.bullet} `);
|
|
235
|
+
|
|
236
|
+
// 5. Right Side: Model & Thinking Level
|
|
237
|
+
const modelName = model?.id || "no-model";
|
|
238
|
+
let rightFormatted = Pastel.model(modelName);
|
|
239
|
+
|
|
240
|
+
if (model?.reasoning) {
|
|
241
|
+
const thinking = ctx.thinkingLevel || "off";
|
|
242
|
+
const thinkingTag =
|
|
243
|
+
thinking === "off"
|
|
244
|
+
? `${Pastel.bullet} ${Pastel.thinkingOff("thinking off")}`
|
|
245
|
+
: `${Pastel.bullet} ${Pastel.thinking(thinking)}`;
|
|
246
|
+
rightFormatted += ` ${thinkingTag}`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (footerData?.getAvailableProviderCount?.() > 1 && model?.provider) {
|
|
250
|
+
rightFormatted = `${Pastel.provider(`(${model.provider})`)} ${rightFormatted}`;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Calculate widths and padding
|
|
254
|
+
const leftWidth = visibleWidth(left);
|
|
255
|
+
const rightWidth = visibleWidth(rightFormatted);
|
|
256
|
+
const minPadding = 2;
|
|
257
|
+
|
|
258
|
+
let mainLine: string;
|
|
259
|
+
if (leftWidth + minPadding + rightWidth <= width) {
|
|
260
|
+
const pad = " ".repeat(width - leftWidth - rightWidth);
|
|
261
|
+
mainLine = left + pad + rightFormatted;
|
|
262
|
+
} else if (leftWidth + minPadding <= width) {
|
|
263
|
+
const availForRight = width - leftWidth - minPadding;
|
|
264
|
+
const truncatedRight = truncateToWidth(rightFormatted, availForRight, "");
|
|
265
|
+
const pad = " ".repeat(
|
|
266
|
+
Math.max(1, width - leftWidth - visibleWidth(truncatedRight)),
|
|
267
|
+
);
|
|
268
|
+
mainLine = left + pad + truncatedRight;
|
|
269
|
+
} else {
|
|
270
|
+
mainLine = truncateToWidth(left, width, "...");
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const lines: string[] = [mainLine];
|
|
274
|
+
|
|
275
|
+
// Optional: Extension statuses (if any)
|
|
276
|
+
const extStatuses = footerData?.getExtensionStatuses?.();
|
|
277
|
+
if (extStatuses && extStatuses.size > 0) {
|
|
278
|
+
const statusTexts = Array.from(extStatuses.values()).filter(Boolean);
|
|
279
|
+
if (statusTexts.length > 0) {
|
|
280
|
+
lines.push(
|
|
281
|
+
truncateToWidth(theme.fg("dim", statusTexts.join(" • ")), width, "..."),
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return lines;
|
|
287
|
+
}
|