-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpi-codegraph.ts
More file actions
309 lines (274 loc) · 10 KB
/
Copy pathpi-codegraph.ts
File metadata and controls
309 lines (274 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/**
* pi-codegraph: Standalone copyable single-file Pi extension.
*
* Provides the `codegraph_explore` tool for structural code exploration
* using an existing CodeGraph index in the active workspace.
*
* Requirements: Node.js 22+, CodeGraph CLI on PATH.
*/
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { spawn, execFile, type ChildProcess } from "node:child_process";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
const DEFAULT_TIMEOUT_MS = 30_000;
const MAX_STDOUT_BYTES = 50 * 1024; // 50 KB
const MAX_STDOUT_LINES = 2_000;
const MAX_STDERR_BYTES = 4 * 1024; // 4 KB
const TRUNCATION_MARKER =
"\n\n[Warning: CodeGraph output exceeded limit and was truncated. Refine query for specific results.]";
export const PROMPT_GUIDELINES = `
# CodeGraph Exploration Guidelines
Use \`codegraph_explore\` first when understanding:
- High-level system, module, or service architecture
- Feature implementations across multiple files
- Symbol relationships (who defines, uses, or implements a symbol)
- Call paths, execution flow, and request lifecycles
- Cross-file dependencies and change blast radius
- Relevant code by concept rather than exact text
Prefer \`grep\` / \`find\` / \`read\` when:
- Searching for an exact literal string or pattern
- Reading a known file with known line numbers
- Inspecting documentation, configuration files, or build scripts
- Inspecting generated files or dependencies
Avoid immediately re-reading all source files returned by CodeGraph unless specific details are missing.
`.trim();
export const PROMPT_SNIPPET = "Use codegraph_explore for structural code understanding and symbol relationships.";
async function hasCodeGraphIndex(workspaceDir: string): Promise<boolean> {
try {
const stat = await fs.stat(path.join(workspaceDir, ".codegraph"));
return stat.isDirectory();
} catch {
return false;
}
}
async function detectCodeGraphExecutable(options: { pathEnv?: string; platform?: string } = {}) {
const platform = options.platform ?? process.platform;
const rawPath = options.pathEnv ?? process.env.PATH ?? "";
const delimiter = platform === "win32" && rawPath.includes(";") ? ";" : path.delimiter;
const pathDirs = rawPath.split(delimiter).filter(Boolean);
const candidateNames = platform === "win32"
? ["codegraph", "codegraph.cmd", "codegraph.exe", "codegraph.bat"]
: ["codegraph"];
for (const dir of pathDirs) {
for (const name of candidateNames) {
const fullPath = path.join(dir, name);
try {
const stat = await fs.stat(fullPath);
if (stat.isFile() || stat.isSymbolicLink()) {
let version: string | undefined;
try {
const isCmd = platform === "win32" && (fullPath.endsWith(".cmd") || fullPath.endsWith(".bat"));
const { stdout } = await execFileAsync(fullPath, ["--version"], {
timeout: 10000,
shell: isCmd
});
version = stdout.trim();
} catch {}
return { available: true, executablePath: fullPath, version };
}
} catch {}
}
}
return { available: false };
}
function terminateProcess(child: ChildProcess): void {
try {
if (child.pid && !child.killed) {
child.kill("SIGTERM");
const killTimer = setTimeout(() => {
try {
if (!child.killed) child.kill("SIGKILL");
} catch {}
}, 1000);
killTimer.unref?.();
}
} catch {}
}
async function runCodeGraph(options: {
args: string[];
cwd: string;
executablePath?: string;
signal?: AbortSignal;
timeoutMs?: number;
env?: Record<string, string>;
}) {
const executablePath = options.executablePath ?? "codegraph";
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
if (options.signal?.aborted) {
throw new Error("[CODEGRAPH_ABORTED] CodeGraph execution was cancelled before starting.");
}
return new Promise<{ stdout: string; truncated: boolean }>((resolve, reject) => {
let child: ChildProcess;
const isWin = process.platform === "win32";
const isCmdOrBat = isWin && (executablePath.endsWith(".cmd") || executablePath.endsWith(".bat"));
try {
if (isCmdOrBat) {
const comSpec = process.env.ComSpec || "cmd.exe";
const formattedArgs = options.args.map((arg) => {
if (arg.includes(" ") || arg.includes('"') || arg.includes("'") || arg.includes("\n")) {
return `"${arg.replace(/"/g, '""')}"`;
}
return arg;
});
const cmdLine = `""${executablePath}" ${formattedArgs.join(" ")}"`;
child = spawn(comSpec, ["/d", "/s", "/c", cmdLine], {
cwd: options.cwd,
env: options.env ? { ...process.env, ...options.env } : process.env,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
windowsVerbatimArguments: true
});
} else {
child = spawn(executablePath, options.args, {
cwd: options.cwd,
env: options.env ? { ...process.env, ...options.env } : process.env,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true
});
}
} catch (err: any) {
if (err.code === "ENOENT") {
return reject(
new Error(`[CODEGRAPH_NOT_FOUND] CodeGraph executable '${executablePath}' not found on PATH.`)
);
}
return reject(err);
}
let stdoutText = "";
let stdoutBytes = 0;
let stdoutLines = 0;
let truncated = false;
let stderrBuffer = "";
let timedOut = false;
let aborted = false;
const timeoutTimer = setTimeout(() => {
timedOut = true;
terminateProcess(child);
}, timeoutMs);
const onAbort = () => {
aborted = true;
terminateProcess(child);
};
if (options.signal) {
options.signal.addEventListener("abort", onAbort, { once: true });
}
child.stdout?.on("data", (chunk: Buffer) => {
if (truncated) return;
const str = chunk.toString("utf-8");
const nextBytes = stdoutBytes + Buffer.byteLength(str, "utf-8");
let lines = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === "\n") lines++;
}
if (nextBytes > MAX_STDOUT_BYTES || stdoutLines + lines > MAX_STDOUT_LINES) {
truncated = true;
const remain = Math.max(0, MAX_STDOUT_BYTES - stdoutBytes);
if (remain > 0) stdoutText += str.slice(0, remain);
} else {
stdoutText += str;
stdoutBytes = nextBytes;
stdoutLines += lines;
}
});
child.stderr?.on("data", (chunk: Buffer) => {
stderrBuffer += chunk.toString("utf-8");
if (Buffer.byteLength(stderrBuffer, "utf-8") > MAX_STDERR_BYTES) {
const excess = Buffer.byteLength(stderrBuffer, "utf-8") - MAX_STDERR_BYTES;
stderrBuffer = stderrBuffer.slice(excess);
}
});
child.on("error", (err: any) => {
clearTimeout(timeoutTimer);
if (options.signal) options.signal.removeEventListener("abort", onAbort);
if (err.code === "ENOENT") {
reject(new Error(`[CODEGRAPH_NOT_FOUND] CodeGraph executable '${executablePath}' not found on PATH.`));
} else {
reject(err);
}
});
child.on("close", (code) => {
clearTimeout(timeoutTimer);
if (options.signal) options.signal.removeEventListener("abort", onAbort);
if (aborted) {
return reject(new Error("[CODEGRAPH_ABORTED] CodeGraph execution was cancelled by agent."));
}
if (timedOut) {
return reject(
new Error(`[CODEGRAPH_TIMEOUT] CodeGraph execution timed out after ${timeoutMs / 1000}s.`)
);
}
if (code !== 0) {
return reject(
new Error(`[CODEGRAPH_COMMAND_FAILED] CodeGraph exited with code ${code}.\n${stderrBuffer.trim()}`)
);
}
let finalStdout = stdoutText;
if (truncated) finalStdout += TRUNCATION_MARKER;
resolve({ stdout: finalStdout, truncated });
});
});
}
export function createExploreTool() {
return {
name: "codegraph_explore",
description:
"Explore code structure, symbols, relationships, implementations, and call paths using the current project's CodeGraph index.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description:
"Natural-language question about code architecture, symbols, relationships, implementation, or execution flow."
}
},
required: ["query"]
},
async execute(args: { query: string }, context: { workspacePath?: string; cwd?: string; signal?: AbortSignal; env?: Record<string, string> } = {}) {
const workspaceDir = context.workspacePath ?? context.cwd ?? process.cwd();
const hasIndex = await hasCodeGraphIndex(workspaceDir);
if (!hasIndex) {
throw new Error(
"[CODEGRAPH_NOT_INITIALIZED] CodeGraph is not initialized for the active workspace.\nRemediation: Run 'codegraph init' in the workspace directory."
);
}
const detection = await detectCodeGraphExecutable({
pathEnv: context.env?.PATH ?? process.env.PATH
});
if (!detection.available || !detection.executablePath) {
throw new Error(
"[CODEGRAPH_NOT_FOUND] CodeGraph CLI is not available on PATH.\nRemediation: Install CodeGraph and ensure 'codegraph' is on PATH."
);
}
const result = await runCodeGraph({
executablePath: detection.executablePath,
args: ["explore", args.query],
cwd: workspaceDir,
signal: context.signal,
env: context.env
});
return {
content: [
{
type: "text",
text: result.stdout
}
]
};
}
};
}
export function registerPiExtension(pi: any): void {
const tool = createExploreTool();
if (typeof pi.registerTool === "function") {
pi.registerTool(tool);
}
if (typeof pi.addPromptGuidelines === "function") {
pi.addPromptGuidelines(PROMPT_GUIDELINES);
}
if (typeof pi.addPromptSnippet === "function") {
pi.addPromptSnippet(PROMPT_SNIPPET);
}
}
export default registerPiExtension;