Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
369 lines (318 loc) · 11.3 KB
/
Copy pathindex.ts
File metadata and controls
369 lines (318 loc) · 11.3 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import { randomBytes } from "node:crypto";
import { createWriteStream, mkdirSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { spawn } from "node:child_process";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import {
createLocalBashOperations,
DEFAULT_MAX_BYTES,
DEFAULT_MAX_LINES,
formatSize,
truncateTail,
getShellConfig,
} from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const LOG_DIR = join(tmpdir(), "ppb");
// ---------------------------------------------------------------------------
// Background process tracking
// ---------------------------------------------------------------------------
const trackedPids = new Set<number>();
function killProcessTree(pid: number): void {
if (process.platform === "win32") {
try {
spawn("taskkill", ["/F", "/T", "/PID", String(pid)], {
stdio: "ignore",
detached: true,
windowsHide: true,
});
} catch {
/* ignore */
}
} else {
try {
process.kill(-pid, "SIGKILL");
} catch {
try {
process.kill(pid, "SIGKILL");
} catch {
/* already dead */
}
}
}
}
function killAllTracked(): void {
for (const pid of trackedPids) {
killProcessTree(pid);
}
trackedPids.clear();
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function generateId(): string {
return randomBytes(3).toString("hex");
}
function ensureLogDir(): void {
mkdirSync(LOG_DIR, { recursive: true });
}
function logPath(id: string): string {
return join(LOG_DIR, `${id}.log`);
}
// ---------------------------------------------------------------------------
// Simple output collector (foreground mode)
// ---------------------------------------------------------------------------
interface SnapshotResult {
content: string;
truncated: boolean;
truncatedBy: "lines" | "bytes" | null;
totalLines: number;
totalBytes: number;
fullOutputPath: string | undefined;
}
class SimpleCollector {
private chunks: Buffer[] = [];
private text = "";
private totalBytes = 0;
private totalLines = 0;
private finished = false;
private tempFilePath: string | undefined;
private tempFileStream: ReturnType<typeof createWriteStream> | undefined;
private decoder = new TextDecoder();
append(data: Buffer): void {
if (this.finished) return;
this.totalBytes += data.length;
this.text += this.decoder.decode(data, { stream: true });
this.countLines(data);
this.chunks.push(data);
this.ensureTempFileIfNeeded();
}
finish(): void {
this.finished = true;
this.text += this.decoder.decode();
this.ensureTempFileIfNeeded();
}
snapshot(): SnapshotResult {
const truncation = truncateTail(this.text, {
maxLines: DEFAULT_MAX_LINES,
maxBytes: DEFAULT_MAX_BYTES,
});
const truncated =
this.totalLines > DEFAULT_MAX_LINES || this.totalBytes > DEFAULT_MAX_BYTES;
return {
content: truncation.content,
truncated,
truncatedBy: truncation.truncated
? (truncation.truncatedBy ??
(this.totalBytes > DEFAULT_MAX_BYTES ? "bytes" : "lines"))
: null,
totalLines: this.totalLines,
totalBytes: this.totalBytes,
fullOutputPath: this.tempFilePath,
};
}
async close(): Promise<void> {
if (!this.tempFileStream) return;
const stream = this.tempFileStream;
this.tempFileStream = undefined;
await new Promise<void>((resolve, reject) => {
stream.once("error", reject);
stream.once("finish", resolve);
stream.end();
});
}
private countLines(data: Buffer): void {
for (let i = 0; i < data.length; i++) {
if (data[i] === 0x0a) this.totalLines++;
}
}
private ensureTempFileIfNeeded(): void {
if (this.tempFilePath || this.totalBytes <= DEFAULT_MAX_BYTES) return;
this.tempFilePath = join(tmpdir(), `pi-bash-${randomBytes(8).toString("hex")}.log`);
this.tempFileStream = createWriteStream(this.tempFilePath);
for (const chunk of this.chunks) {
this.tempFileStream.write(chunk);
}
this.chunks = [];
}
private writeTemp(data: Buffer): void {
if (this.tempFileStream) {
this.tempFileStream.write(data);
}
}
}
// ---------------------------------------------------------------------------
// Schema
// ---------------------------------------------------------------------------
const bashSchema = Type.Object({
command: Type.String({ description: "Bash command to execute" }),
timeout: Type.Optional(
Type.Number({
description: "Timeout in seconds (optional, no default timeout)",
}),
),
background: Type.Optional(
Type.Boolean({
description:
"If true, run the command in the background. Returns immediately with PID and log file path. The timeout is still respected — the process is killed when it expires.",
}),
),
});
// ---------------------------------------------------------------------------
// Tool definition
// ---------------------------------------------------------------------------
export default function (pi: ExtensionAPI) {
const ops = createLocalBashOperations();
pi.on("session_shutdown", () => killAllTracked());
pi.registerTool({
name: "bash",
label: "bash",
description: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.
When background is true, the command runs in the background. The tool returns immediately with the PID and log file path (/tmp/ppb/{id}.log). Use the PID to manage the process (kill, check status) and read the log file to inspect output. The timeout parameter is still respected — the process is automatically killed when it expires.`,
promptSnippet: "Execute bash commands (ls, grep, find, etc.); supports background mode",
parameters: bashSchema,
async execute(_toolCallId, { command, timeout, background }, signal, onUpdate, ctx) {
// Resolve the working directory per execution from the extension context.
// ctx.cwd is the session's cwd, which is correct both in the pi TUI and
// in multi-session hosts like pi-web (where process.cwd() is the server
// launch directory, not the session's project).
const cwd = ctx?.cwd ?? process.cwd();
if (background) {
return executeBackground(command, cwd, timeout);
}
return executeForeground(command, cwd, ops, timeout, signal, onUpdate);
},
});
}
// ---------------------------------------------------------------------------
// Foreground execution
// ---------------------------------------------------------------------------
async function executeForeground(
command: string,
cwd: string,
ops: ReturnType<typeof createLocalBashOperations>,
timeout: number | undefined,
signal: AbortSignal | undefined,
onUpdate: ((r: { content: Array<{ type: string; text?: string }>; details?: object }) => void) | undefined,
): Promise<{ content: Array<{ type: string; text: string }>; details?: object }> {
const collector = new SimpleCollector();
const handleData = (data: Buffer) => {
collector.append(data);
if (onUpdate) {
const snap = collector.snapshot();
onUpdate({ content: [{ type: "text", text: snap.content || "" }] });
}
};
try {
const result = await ops.exec(command, cwd, {
onData: handleData,
signal,
timeout,
});
collector.finish();
const snap = collector.snapshot();
await collector.close();
let text = snap.content || "(no output)";
if (snap.truncated) {
const startLine = snap.totalLines - DEFAULT_MAX_LINES + 1;
if (snap.truncatedBy === "lines") {
text += `\n\n[Showing lines ${startLine}-${snap.totalLines} of ${snap.totalLines}. Full output: ${snap.fullOutputPath}]`;
} else {
text += `\n\n[Showing ${DEFAULT_MAX_LINES} lines (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snap.fullOutputPath}]`;
}
}
if (result.exitCode !== 0 && result.exitCode !== null) {
throw new Error(
`${text ? `${text}\n\n` : ""}Command exited with code ${result.exitCode}`,
);
}
const details = snap.truncated
? {
truncation: {
truncated: snap.truncated,
truncatedBy: snap.truncatedBy,
totalLines: snap.totalLines,
outputLines: DEFAULT_MAX_LINES,
},
fullOutputPath: snap.fullOutputPath,
}
: undefined;
return { content: [{ type: "text", text }], details };
} catch (err) {
collector.finish();
await collector.close();
const snap = collector.snapshot();
let text = snap.content || "";
if (err instanceof Error && err.message === "aborted") {
throw new Error(`${text ? `${text}\n\n` : ""}Command aborted`);
}
if (err instanceof Error && err.message.startsWith("timeout:")) {
const timeoutSecs = err.message.split(":")[1];
throw new Error(
`${text ? `${text}\n\n` : ""}Command timed out after ${timeoutSecs} seconds`,
);
}
throw err;
}
}
// ---------------------------------------------------------------------------
// Background execution
// ---------------------------------------------------------------------------
function executeBackground(
command: string,
cwd: string,
timeout: number | undefined,
): { content: Array<{ type: string; text: string }>; details?: object } {
ensureLogDir();
const id = generateId();
const filePath = logPath(id);
const stream = createWriteStream(filePath, { flags: "w" });
const shellConfig = getShellConfig();
const commandFromStdin = shellConfig.commandTransport === "stdin";
const child = spawn(
shellConfig.shell,
commandFromStdin ? shellConfig.args : [...shellConfig.args, command],
{
cwd,
detached: process.platform !== "win32",
env: process.env,
stdio: [commandFromStdin ? "pipe" : "ignore", "pipe", "pipe"],
windowsHide: true,
},
);
if (commandFromStdin) {
child.stdin?.on("error", () => {});
child.stdin?.end(command);
}
const pid = child.pid;
if (pid) trackedPids.add(pid);
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
if (timeout !== undefined) {
timeoutHandle = setTimeout(() => {
if (pid) killProcessTree(pid);
}, timeout * 1000);
}
// Stream output to log file.
child.stdout?.on("data", (chunk: Buffer) => stream.write(chunk));
child.stderr?.on("data", (chunk: Buffer) => stream.write(chunk));
// Cleanup on exit or error.
const cleanup = () => {
trackedPids.delete(pid!);
if (timeoutHandle) clearTimeout(timeoutHandle);
stream.end();
};
child.on("exit", cleanup);
child.on("error", cleanup);
const timeoutInfo = timeout ? `\nTimeout: ${timeout}s (auto-kill)` : "";
return {
content: [
{
type: "text",
text: `Process started in background.\nPID: ${pid}\nLog: ${filePath}${timeoutInfo}`,
},
],
};
}