@floydous/pi-agent-kernel 0.2.0 → 0.3.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.
@@ -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
+ }
@@ -261,7 +261,12 @@ export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
261
261
  const refs = findSymbolReferences(ctx.cwd, targetSym);
262
262
  if (refs.length > 0) {
263
263
  const formatted = refs
264
- .map((r) => `${r.filePath}:${r.line}:${r.column}`)
264
+ .map((r) => {
265
+ const col0 = Math.max(0, r.column - 1);
266
+ const endCol0 = col0 + targetSym.length;
267
+ const snippet = windowAround(r.lineText, col0, endCol0, 50);
268
+ return `${r.filePath}:${r.line}:${r.column}: ${snippet}`;
269
+ })
265
270
  .join("\n");
266
271
  return {
267
272
  content: [
@@ -412,8 +417,14 @@ export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
412
417
  ],
413
418
  };
414
419
  }
420
+ const relPath = path.relative(ctx.cwd, absPath).replace(/\\/g, "/") || absPath;
415
421
  return {
416
- content: [],
422
+ content: [
423
+ {
424
+ type: "text",
425
+ text: `${relPath} clean`,
426
+ },
427
+ ],
417
428
  };
418
429
  }
419
430
 
@@ -1,278 +1,278 @@
1
- /**
2
- * Zero-Dependency TUI Helper Utilities
3
- * Works across standalone test suites and live Pi TUI environments.
4
- */
5
-
6
- export interface Focusable {
7
- focused: boolean;
8
- handleInput?(data: string): Promise<void> | void;
9
- render(width: number): string[];
10
- invalidate?(): void;
11
- dispose?(): void;
12
- }
13
-
14
- export const ANSI_REGEX =
15
- /(?:\x1B\][^\x07\x1B]*(?:\x07|\x1B\\|\x9C))|(?:\x1B\[[0-9;?]*[ -/]*[@-~])/g;
16
-
17
- export function stripAnsi(text: string): string {
18
- if (!text) return "";
19
- if (!text.includes("\x1b")) return text;
20
- return text.replace(ANSI_REGEX, "");
21
- }
22
-
23
- export function visibleWidth(text: string): number {
24
- if (!text) return 0;
25
- if (!text.includes("\x1b")) return text.length;
26
- return stripAnsi(text).length;
27
- }
28
-
29
- export function truncateToWidth(
30
- text: string,
31
- maxWidth: number,
32
- ellipsis = "...",
33
- ): string {
34
- maxWidth = Math.max(0, Math.floor(maxWidth));
35
- const vis = visibleWidth(text);
36
- if (vis <= maxWidth) return text;
37
- const ellVis = visibleWidth(ellipsis);
38
- if (maxWidth <= ellVis) return ellipsis.slice(0, maxWidth);
39
-
40
- const raw = stripAnsi(text);
41
- return raw.slice(0, maxWidth - ellVis) + ellipsis;
42
- }
43
-
44
- export function wrapTextWithAnsi(text: string, width: number): string[] {
45
- width = Math.max(1, Math.floor(width));
46
- if (!text) return [""];
47
- const inputLines = text.split(/\r\n|\r|\n/);
48
- const result: string[] = [];
49
-
50
- for (const inputLine of inputLines) {
51
- if (visibleWidth(inputLine) <= width) {
52
- result.push(inputLine);
53
- continue;
54
- }
55
-
56
- if (!inputLine.includes("\x1b")) {
57
- for (let i = 0; i < inputLine.length; i += width) {
58
- result.push(inputLine.slice(i, i + width));
59
- }
60
- continue;
61
- }
62
-
63
- // Tokenize into words and ansi escapes
64
- const tokens: string[] = [];
65
- let currentToken = "";
66
- let inWhitespace = false;
67
- let i = 0;
68
-
69
- while (i < inputLine.length) {
70
- ANSI_REGEX.lastIndex = i;
71
- const match = ANSI_REGEX.exec(inputLine);
72
- if (match && match.index === i) {
73
- currentToken += match[0];
74
- i += match[0].length;
75
- continue;
76
- }
77
-
78
- const char = inputLine[i];
79
- const isWs = /\s/.test(char);
80
- if (
81
- currentToken.length > 0 &&
82
- isWs !== inWhitespace &&
83
- !currentToken.endsWith("\x1b")
84
- ) {
85
- tokens.push(currentToken);
86
- currentToken = "";
87
- }
88
- inWhitespace = isWs;
89
- currentToken += char;
90
- i++;
91
- }
92
- if (currentToken.length > 0) tokens.push(currentToken);
93
-
94
- let curLine = "";
95
- let curWidth = 0;
96
-
97
- for (const token of tokens) {
98
- const tokenWidth = visibleWidth(token);
99
- if (tokenWidth === 0) {
100
- curLine += token;
101
- continue;
102
- }
103
-
104
- if (curWidth + tokenWidth <= width) {
105
- curLine += token;
106
- curWidth += tokenWidth;
107
- } else {
108
- if (tokenWidth > width) {
109
- // Break excessively long token character by character
110
- let j = 0;
111
- while (j < token.length) {
112
- ANSI_REGEX.lastIndex = j;
113
- const m = ANSI_REGEX.exec(token);
114
- if (m && m.index === j) {
115
- curLine += m[0];
116
- j += m[0].length;
117
- continue;
118
- }
119
- const ch = token[j];
120
- if (curWidth + 1 > width) {
121
- if (curLine) result.push(curLine);
122
- curLine = ch;
123
- curWidth = 1;
124
- } else {
125
- curLine += ch;
126
- curWidth += 1;
127
- }
128
- j++;
129
- }
130
- } else {
131
- if (curLine) result.push(curLine);
132
- curLine = token;
133
- curWidth = tokenWidth;
134
- }
135
- }
136
- }
137
- if (curLine) result.push(curLine);
138
- }
139
-
140
- return result.length > 0 ? result : [""];
141
- }
142
-
143
- /**
144
- * Get a safe per-line width for tool output rendering.
145
- *
146
- * The pi runtime does not pass the terminal width to a tool's `renderResult`.
147
- * We read `process.stdout.columns` (the Node TTY width, shared with pi's
148
- * `terminal.columns` in the same process) and subtract a safety margin for
149
- * the parent Box's `paddingX=1` on each side plus a small additional buffer.
150
- *
151
- * If `process.stdout.columns` is undefined (non-TTY: pipes, redirects,
152
- * `--print` mode, RPC mode without a TTY), fall back to 200 columns, which
153
- * is narrower than typical interactive terminals but always fits the parent
154
- * Box's wrap.
155
- *
156
- * The safety margin is conservative (4 columns) so a downstream renderer
157
- * that adds an additional paddingX layer or a border will not overflow.
158
- */
159
- export function getSafeLineWidth(): number {
160
- const cols = process.stdout.columns;
161
- const base = typeof cols === "number" && cols > 0 ? cols : 200;
162
- return Math.max(40, base - 4);
163
- }
164
-
165
- /**
166
- * Build a `Text` component suitable for use in a tool's `renderCall` or
167
- * `renderResult` that is guaranteed not to render a line wider than the
168
- * terminal, regardless of the parent's `paddingX`.
169
- *
170
- * Why a fresh `Text` instead of reusing `context.lastComponent`:
171
- * The previous implementation did `context.lastComponent ?? new Text("", 0, 0)`
172
- * and called `setText` on it. The returned component then became a child of
173
- * pi's `contentBox` (a `Box` with `paddingX=1`). When the runtime passed
174
- * back a `lastComponent` that already had `paddingX=1` (pi's `contentText`
175
- * default), the child Text's own `render(width)` reserved `paddingX*2` of
176
- * width on top of the parent's, producing a line that exceeded the available
177
- * width by a few cells. The pi TUI's hard width assertion then crashed the
178
- * process with "Rendered line N exceeds terminal width".
179
- *
180
- * Always creating a fresh `Text` with `paddingX=0` makes the parent's
181
- * `paddingX` the only source of padding, eliminating the double-padding
182
- * path. The per-line truncation in `setText` is a defense-in-depth measure:
183
- * even if a future renderer adds another padding layer, the lines stored
184
- * in the Text are already within bounds.
185
- */
186
- export function makeOutputText(content: string, paddingX = 0): Text {
187
- const safeWidth = getSafeLineWidth();
188
- // Match Pi's native Text renderer: tabs occupy three spaces there.
189
- const normalizedContent = content.replace(/\t/g, " ");
190
- const safeContent = normalizedContent
191
- .split(/\r\n|\r|\n/)
192
- .map((line) => truncateToWidth(line, safeWidth, "…"))
193
- .join("\n");
194
- return new Text(safeContent, paddingX, 0);
195
- }
196
-
197
- export class Text {
198
- private text: string;
199
- public paddingX: number;
200
- public paddingY: number;
201
-
202
- constructor(text = "", paddingX = 0, paddingY = 0) {
203
- this.text = text;
204
- this.paddingX = paddingX;
205
- this.paddingY = paddingY;
206
- }
207
-
208
- setText(text: string) {
209
- this.text = text;
210
- }
211
-
212
- getText(): string {
213
- return this.text;
214
- }
215
-
216
- /** Satisfies the pi-tui `Component` contract (no cached state to invalidate). */
217
- invalidate(): void {}
218
-
219
- render(width: number): string[] {
220
- width = Math.max(1, Math.floor(width));
221
- if (!this.text || this.text.trim() === "") return [];
222
- const paddingX = Math.min(
223
- this.paddingX,
224
- Math.max(0, Math.floor((width - 1) / 2)),
225
- );
226
- const normalizedText = this.text.replace(/\t/g, " ");
227
- const contentWidth = Math.max(1, width - paddingX * 2);
228
- const wrappedLines = wrapTextWithAnsi(normalizedText, contentWidth);
229
- const leftMargin = " ".repeat(paddingX);
230
- const rightMargin = " ".repeat(paddingX);
231
- const contentLines = wrappedLines.map(
232
- (line) => leftMargin + line + rightMargin,
233
- );
234
- // The width argument is authoritative: Pi hard-fails if any returned
235
- // line exceeds it, regardless of the width available during formatting.
236
- const safeContentLines = contentLines.map((line) =>
237
- truncateToWidth(line, width, ""),
238
- );
239
- const emptyLine = " ".repeat(width);
240
- const emptyLines: string[] = [];
241
- for (let i = 0; i < this.paddingY; i++) {
242
- emptyLines.push(emptyLine);
243
- }
244
- return [...emptyLines, ...safeContentLines, ...emptyLines];
245
- }
246
- }
247
-
248
- export function matchesKey(data: string, key: string): boolean {
249
- switch (key.toLowerCase()) {
250
- case "escape":
251
- return data === "\x1b" || data === "\x1b\x1b";
252
- case "q":
253
- return data === "q" || data === "Q";
254
- case "ctrl+c":
255
- return data === "\x03";
256
- case "up":
257
- return data === "\x1b[A" || data === "\x1bOA";
258
- case "down":
259
- return data === "\x1b[B" || data === "\x1bOB";
260
- case "left":
261
- return data === "\x1b[D" || data === "\x1bOD";
262
- case "right":
263
- return data === "\x1b[C" || data === "\x1bOC";
264
- case "k":
265
- return data === "k" || data === "K";
266
- case "j":
267
- return data === "j" || data === "J";
268
- case "return":
269
- case "enter":
270
- return data === "\r" || data === "\n";
271
- case "space":
272
- return data === " ";
273
- case "tab":
274
- return data === "\t";
275
- default:
276
- return data === key;
277
- }
278
- }
1
+ /**
2
+ * Zero-Dependency TUI Helper Utilities
3
+ * Works across standalone test suites and live Pi TUI environments.
4
+ */
5
+
6
+ export interface Focusable {
7
+ focused: boolean;
8
+ handleInput?(data: string): Promise<void> | void;
9
+ render(width: number): string[];
10
+ invalidate?(): void;
11
+ dispose?(): void;
12
+ }
13
+
14
+ export const ANSI_REGEX =
15
+ /(?:\x1B\][^\x07\x1B]*(?:\x07|\x1B\\|\x9C))|(?:\x1B\[[0-9;?]*[ -/]*[@-~])/g;
16
+
17
+ export function stripAnsi(text: string): string {
18
+ if (!text) return "";
19
+ if (!text.includes("\x1b")) return text;
20
+ return text.replace(ANSI_REGEX, "");
21
+ }
22
+
23
+ export function visibleWidth(text: string): number {
24
+ if (!text) return 0;
25
+ if (!text.includes("\x1b")) return text.length;
26
+ return stripAnsi(text).length;
27
+ }
28
+
29
+ export function truncateToWidth(
30
+ text: string,
31
+ maxWidth: number,
32
+ ellipsis = "...",
33
+ ): string {
34
+ maxWidth = Math.max(0, Math.floor(maxWidth));
35
+ const vis = visibleWidth(text);
36
+ if (vis <= maxWidth) return text;
37
+ const ellVis = visibleWidth(ellipsis);
38
+ if (maxWidth <= ellVis) return ellipsis.slice(0, maxWidth);
39
+
40
+ const raw = stripAnsi(text);
41
+ return raw.slice(0, maxWidth - ellVis) + ellipsis;
42
+ }
43
+
44
+ export function wrapTextWithAnsi(text: string, width: number): string[] {
45
+ width = Math.max(1, Math.floor(width));
46
+ if (!text) return [""];
47
+ const inputLines = text.split(/\r\n|\r|\n/);
48
+ const result: string[] = [];
49
+
50
+ for (const inputLine of inputLines) {
51
+ if (visibleWidth(inputLine) <= width) {
52
+ result.push(inputLine);
53
+ continue;
54
+ }
55
+
56
+ if (!inputLine.includes("\x1b")) {
57
+ for (let i = 0; i < inputLine.length; i += width) {
58
+ result.push(inputLine.slice(i, i + width));
59
+ }
60
+ continue;
61
+ }
62
+
63
+ // Tokenize into words and ansi escapes
64
+ const tokens: string[] = [];
65
+ let currentToken = "";
66
+ let inWhitespace = false;
67
+ let i = 0;
68
+
69
+ while (i < inputLine.length) {
70
+ ANSI_REGEX.lastIndex = i;
71
+ const match = ANSI_REGEX.exec(inputLine);
72
+ if (match && match.index === i) {
73
+ currentToken += match[0];
74
+ i += match[0].length;
75
+ continue;
76
+ }
77
+
78
+ const char = inputLine[i];
79
+ const isWs = /\s/.test(char);
80
+ if (
81
+ currentToken.length > 0 &&
82
+ isWs !== inWhitespace &&
83
+ !currentToken.endsWith("\x1b")
84
+ ) {
85
+ tokens.push(currentToken);
86
+ currentToken = "";
87
+ }
88
+ inWhitespace = isWs;
89
+ currentToken += char;
90
+ i++;
91
+ }
92
+ if (currentToken.length > 0) tokens.push(currentToken);
93
+
94
+ let curLine = "";
95
+ let curWidth = 0;
96
+
97
+ for (const token of tokens) {
98
+ const tokenWidth = visibleWidth(token);
99
+ if (tokenWidth === 0) {
100
+ curLine += token;
101
+ continue;
102
+ }
103
+
104
+ if (curWidth + tokenWidth <= width) {
105
+ curLine += token;
106
+ curWidth += tokenWidth;
107
+ } else {
108
+ if (tokenWidth > width) {
109
+ // Break excessively long token character by character
110
+ let j = 0;
111
+ while (j < token.length) {
112
+ ANSI_REGEX.lastIndex = j;
113
+ const m = ANSI_REGEX.exec(token);
114
+ if (m && m.index === j) {
115
+ curLine += m[0];
116
+ j += m[0].length;
117
+ continue;
118
+ }
119
+ const ch = token[j];
120
+ if (curWidth + 1 > width) {
121
+ if (curLine) result.push(curLine);
122
+ curLine = ch;
123
+ curWidth = 1;
124
+ } else {
125
+ curLine += ch;
126
+ curWidth += 1;
127
+ }
128
+ j++;
129
+ }
130
+ } else {
131
+ if (curLine) result.push(curLine);
132
+ curLine = token;
133
+ curWidth = tokenWidth;
134
+ }
135
+ }
136
+ }
137
+ if (curLine) result.push(curLine);
138
+ }
139
+
140
+ return result.length > 0 ? result : [""];
141
+ }
142
+
143
+ /**
144
+ * Get a safe per-line width for tool output rendering.
145
+ *
146
+ * The pi runtime does not pass the terminal width to a tool's `renderResult`.
147
+ * We read `process.stdout.columns` (the Node TTY width, shared with pi's
148
+ * `terminal.columns` in the same process) and subtract a safety margin for
149
+ * the parent Box's `paddingX=1` on each side plus a small additional buffer.
150
+ *
151
+ * If `process.stdout.columns` is undefined (non-TTY: pipes, redirects,
152
+ * `--print` mode, RPC mode without a TTY), fall back to 200 columns, which
153
+ * is narrower than typical interactive terminals but always fits the parent
154
+ * Box's wrap.
155
+ *
156
+ * The safety margin is conservative (4 columns) so a downstream renderer
157
+ * that adds an additional paddingX layer or a border will not overflow.
158
+ */
159
+ export function getSafeLineWidth(): number {
160
+ const cols = process.stdout.columns;
161
+ const base = typeof cols === "number" && cols > 0 ? cols : 200;
162
+ return Math.max(40, base - 4);
163
+ }
164
+
165
+ /**
166
+ * Build a `Text` component suitable for use in a tool's `renderCall` or
167
+ * `renderResult` that is guaranteed not to render a line wider than the
168
+ * terminal, regardless of the parent's `paddingX`.
169
+ *
170
+ * Why a fresh `Text` instead of reusing `context.lastComponent`:
171
+ * The previous implementation did `context.lastComponent ?? new Text("", 0, 0)`
172
+ * and called `setText` on it. The returned component then became a child of
173
+ * pi's `contentBox` (a `Box` with `paddingX=1`). When the runtime passed
174
+ * back a `lastComponent` that already had `paddingX=1` (pi's `contentText`
175
+ * default), the child Text's own `render(width)` reserved `paddingX*2` of
176
+ * width on top of the parent's, producing a line that exceeded the available
177
+ * width by a few cells. The pi TUI's hard width assertion then crashed the
178
+ * process with "Rendered line N exceeds terminal width".
179
+ *
180
+ * Always creating a fresh `Text` with `paddingX=0` makes the parent's
181
+ * `paddingX` the only source of padding, eliminating the double-padding
182
+ * path. The per-line truncation in `setText` is a defense-in-depth measure:
183
+ * even if a future renderer adds another padding layer, the lines stored
184
+ * in the Text are already within bounds.
185
+ */
186
+ export function makeOutputText(content: string, paddingX = 0): Text {
187
+ const safeWidth = getSafeLineWidth();
188
+ // Match Pi's native Text renderer: tabs occupy three spaces there.
189
+ const normalizedContent = content.replace(/\t/g, " ");
190
+ const safeContent = normalizedContent
191
+ .split(/\r\n|\r|\n/)
192
+ .map((line) => truncateToWidth(line, safeWidth, "…"))
193
+ .join("\n");
194
+ return new Text(safeContent, paddingX, 0);
195
+ }
196
+
197
+ export class Text {
198
+ private text: string;
199
+ public paddingX: number;
200
+ public paddingY: number;
201
+
202
+ constructor(text = "", paddingX = 0, paddingY = 0) {
203
+ this.text = text;
204
+ this.paddingX = paddingX;
205
+ this.paddingY = paddingY;
206
+ }
207
+
208
+ setText(text: string) {
209
+ this.text = text;
210
+ }
211
+
212
+ getText(): string {
213
+ return this.text;
214
+ }
215
+
216
+ /** Satisfies the pi-tui `Component` contract (no cached state to invalidate). */
217
+ invalidate(): void {}
218
+
219
+ render(width: number): string[] {
220
+ width = Math.max(1, Math.floor(width));
221
+ if (!this.text || this.text.trim() === "") return [];
222
+ const paddingX = Math.min(
223
+ this.paddingX,
224
+ Math.max(0, Math.floor((width - 1) / 2)),
225
+ );
226
+ const normalizedText = this.text.replace(/\t/g, " ");
227
+ const contentWidth = Math.max(1, width - paddingX * 2);
228
+ const wrappedLines = wrapTextWithAnsi(normalizedText, contentWidth);
229
+ const leftMargin = " ".repeat(paddingX);
230
+ const rightMargin = " ".repeat(paddingX);
231
+ const contentLines = wrappedLines.map(
232
+ (line) => leftMargin + line + rightMargin,
233
+ );
234
+ // The width argument is authoritative: Pi hard-fails if any returned
235
+ // line exceeds it, regardless of the width available during formatting.
236
+ const safeContentLines = contentLines.map((line) =>
237
+ truncateToWidth(line, width, ""),
238
+ );
239
+ const emptyLine = " ".repeat(width);
240
+ const emptyLines: string[] = [];
241
+ for (let i = 0; i < this.paddingY; i++) {
242
+ emptyLines.push(emptyLine);
243
+ }
244
+ return [...emptyLines, ...safeContentLines, ...emptyLines];
245
+ }
246
+ }
247
+
248
+ export function matchesKey(data: string, key: string): boolean {
249
+ switch (key.toLowerCase()) {
250
+ case "escape":
251
+ return data === "\x1b" || data === "\x1b\x1b";
252
+ case "q":
253
+ return data === "q" || data === "Q";
254
+ case "ctrl+c":
255
+ return data === "\x03";
256
+ case "up":
257
+ return data === "\x1b[A" || data === "\x1bOA";
258
+ case "down":
259
+ return data === "\x1b[B" || data === "\x1bOB";
260
+ case "left":
261
+ return data === "\x1b[D" || data === "\x1bOD";
262
+ case "right":
263
+ return data === "\x1b[C" || data === "\x1bOC";
264
+ case "k":
265
+ return data === "k" || data === "K";
266
+ case "j":
267
+ return data === "j" || data === "J";
268
+ case "return":
269
+ case "enter":
270
+ return data === "\r" || data === "\n";
271
+ case "space":
272
+ return data === " ";
273
+ case "tab":
274
+ return data === "\t";
275
+ default:
276
+ return data === key;
277
+ }
278
+ }
Binary file
Binary file
Binary file
Binary file