forked from nicobailon/pi-subagents
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
351 lines (317 loc) · 11.2 KB
/
utils.ts
File metadata and controls
351 lines (317 loc) · 11.2 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
/**
* General utility functions for the subagent extension
*/
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import type { Message } from "@mariozechner/pi-ai";
import type { AsyncStatus, DisplayItem, ErrorInfo } from "./types.js";
// ============================================================================
// File System Utilities
// ============================================================================
// Cache for status file reads - avoid re-reading unchanged files
const statusCache = new Map<string, { mtime: number; status: AsyncStatus }>();
/**
* Read async job status from disk (with mtime-based caching)
*/
export function readStatus(asyncDir: string): AsyncStatus | null {
const statusPath = path.join(asyncDir, "status.json");
try {
const stat = fs.statSync(statusPath);
const cached = statusCache.get(statusPath);
if (cached && cached.mtime === stat.mtimeMs) {
return cached.status;
}
const content = fs.readFileSync(statusPath, "utf-8");
const status = JSON.parse(content) as AsyncStatus;
statusCache.set(statusPath, { mtime: stat.mtimeMs, status });
// Limit cache size to prevent memory leaks
if (statusCache.size > 50) {
const firstKey = statusCache.keys().next().value;
if (firstKey) statusCache.delete(firstKey);
}
return status;
} catch {
return null;
}
}
// Cache for output tail reads - avoid re-reading unchanged files
const outputTailCache = new Map<string, { mtime: number; size: number; lines: string[] }>();
/**
* Get the last N lines from an output file (with mtime/size-based caching)
*/
export function getOutputTail(outputFile: string | undefined, maxLines: number = 3): string[] {
if (!outputFile) return [];
let fd: number | null = null;
try {
const stat = fs.statSync(outputFile);
if (stat.size === 0) return [];
// Check cache using both mtime and size (size changes more frequently during writes)
const cached = outputTailCache.get(outputFile);
if (cached && cached.mtime === stat.mtimeMs && cached.size === stat.size) {
return cached.lines;
}
const tailBytes = 4096;
const start = Math.max(0, stat.size - tailBytes);
fd = fs.openSync(outputFile, "r");
const buffer = Buffer.alloc(Math.min(tailBytes, stat.size));
fs.readSync(fd, buffer, 0, buffer.length, start);
const content = buffer.toString("utf-8");
const allLines = content.split("\n").filter((l) => l.trim());
const lines = allLines.slice(-maxLines).map((l) => l.slice(0, 120) + (l.length > 120 ? "..." : ""));
// Cache the result
outputTailCache.set(outputFile, { mtime: stat.mtimeMs, size: stat.size, lines });
// Limit cache size
if (outputTailCache.size > 20) {
const firstKey = outputTailCache.keys().next().value;
if (firstKey) outputTailCache.delete(firstKey);
}
return lines;
} catch {
return [];
} finally {
if (fd !== null) {
try {
fs.closeSync(fd);
} catch {}
}
}
}
/**
* Get human-readable last activity time for a file
*/
export function getLastActivity(outputFile: string | undefined): string {
if (!outputFile) return "";
try {
// Single stat call - throws if file doesn't exist
const stat = fs.statSync(outputFile);
const ago = Date.now() - stat.mtimeMs;
if (ago < 1000) return "active now";
if (ago < 60000) return `active ${Math.floor(ago / 1000)}s ago`;
return `active ${Math.floor(ago / 60000)}m ago`;
} catch {
return "";
}
}
/**
* Find a file/directory by prefix in a directory
*/
export function findByPrefix(dir: string, prefix: string, suffix?: string): string | null {
if (!fs.existsSync(dir)) return null;
const entries = fs.readdirSync(dir).filter((entry) => entry.startsWith(prefix));
if (suffix) {
const withSuffix = entries.filter((entry) => entry.endsWith(suffix));
return withSuffix.length > 0 ? path.join(dir, withSuffix.sort()[0]) : null;
}
if (entries.length === 0) return null;
return path.join(dir, entries.sort()[0]);
}
/**
* Find the latest session file in a directory
*/
export function findLatestSessionFile(sessionDir: string): string | null {
if (!fs.existsSync(sessionDir)) return null;
const files = fs.readdirSync(sessionDir)
.filter((f) => f.endsWith(".jsonl"))
.map((f) => {
const filePath = path.join(sessionDir, f);
return {
path: filePath,
mtime: fs.statSync(filePath).mtimeMs,
};
})
.sort((a, b) => b.mtime - a.mtime);
return files.length > 0 ? files[0].path : null;
}
/**
* Write a prompt to a temporary file
*/
export function writePrompt(agent: string, prompt: string): { dir: string; path: string } {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
const p = path.join(dir, `${agent.replace(/[^\w.-]/g, "_")}.md`);
fs.writeFileSync(p, prompt, { mode: 0o600 });
return { dir, path: p };
}
// ============================================================================
// Message Parsing Utilities
// ============================================================================
/**
* Get the final text output from a list of messages
*/
export function getFinalOutput(messages: Message[]): string {
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
if (msg.role === "assistant") {
for (const part of msg.content) {
if (part.type === "text") return part.text;
}
}
}
return "";
}
/**
* Extract display items (text and tool calls) from messages
*/
export function getDisplayItems(messages: Message[]): DisplayItem[] {
const items: DisplayItem[] = [];
for (const msg of messages) {
if (msg.role === "assistant") {
for (const part of msg.content) {
if (part.type === "text") items.push({ type: "text", text: part.text });
else if (part.type === "toolCall") items.push({ type: "tool", name: part.name, args: part.arguments });
}
}
}
return items;
}
/**
* Detect errors in subagent execution from messages (only errors with no subsequent success)
*/
export function detectSubagentError(messages: Message[]): ErrorInfo {
// Step 1: Find the last assistant message with text content.
// If the agent produced a text response after encountering errors,
// it had a chance to recover — only errors AFTER this point matter.
let lastAssistantTextIndex = -1;
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
if (msg.role === "assistant") {
const hasText = Array.isArray(msg.content) && msg.content.some(
(c) => c.type === "text" && "text" in c && (c.text as string).trim().length > 0,
);
if (hasText) {
lastAssistantTextIndex = i;
break;
}
}
}
// Step 2: Only scan tool results AFTER the last assistant text message.
// Errors before the agent's final response are implicitly recovered.
const scanStart = lastAssistantTextIndex >= 0 ? lastAssistantTextIndex + 1 : 0;
// Step 3: Check tool results in the post-response window
for (let i = messages.length - 1; i >= scanStart; i--) {
const msg = messages[i];
if (msg.role !== "toolResult") continue;
if ((msg as any).isError) {
const text = msg.content.find((c) => c.type === "text");
const details = text && "text" in text ? text.text : undefined;
const exitMatch = details?.match(/exit(?:ed)?\s*(?:with\s*)?(?:code|status)?\s*[:\s]?\s*(\d+)/i);
return {
hasError: true,
exitCode: exitMatch ? parseInt(exitMatch[1], 10) : 1,
errorType: (msg as any).toolName || "tool",
details: details?.slice(0, 200),
};
}
const toolName = (msg as any).toolName;
if (toolName !== "bash") continue;
const text = msg.content.find((c) => c.type === "text");
if (!text || !("text" in text)) continue;
const output = text.text;
const exitMatch = output.match(/exit(?:ed)?\s*(?:with\s*)?(?:code|status)?\s*[:\s]?\s*(\d+)/i);
if (exitMatch) {
const code = parseInt(exitMatch[1], 10);
if (code !== 0) {
return { hasError: true, exitCode: code, errorType: "bash", details: output.slice(0, 200) };
}
}
// NOTE: These patterns can match legitimate output (grep results, logs,
// testing). With the assistant-message check above, most false positives
// are mitigated since the agent will have responded after routine errors.
const fatalPatterns = [
/command not found/i,
/permission denied/i,
/no such file or directory/i,
/segmentation fault/i,
/killed|terminated/i,
/out of memory/i,
/connection refused/i,
/timeout/i,
];
for (const pattern of fatalPatterns) {
if (pattern.test(output)) {
return { hasError: true, exitCode: 1, errorType: "bash", details: output.slice(0, 200) };
}
}
}
return { hasError: false };
}
/**
* Extract a preview of tool arguments for display
*/
export function extractToolArgsPreview(args: Record<string, unknown>): string {
// Handle MCP tool calls - show server/tool info
if (args.tool && typeof args.tool === "string") {
const server = args.server && typeof args.server === "string" ? `${args.server}/` : "";
const toolArgs = args.args && typeof args.args === "string" ? ` ${args.args.slice(0, 40)}` : "";
return `${server}${args.tool}${toolArgs}`;
}
const previewKeys = ["command", "path", "file_path", "pattern", "query", "url", "task", "describe", "search"];
for (const key of previewKeys) {
if (args[key] && typeof args[key] === "string") {
const value = args[key] as string;
return value.length > 60 ? `${value.slice(0, 57)}...` : value;
}
}
// Fallback: show first string value found
for (const [key, value] of Object.entries(args)) {
if (typeof value === "string" && value.length > 0) {
const preview = value.length > 50 ? `${value.slice(0, 47)}...` : value;
return `${key}=${preview}`;
}
}
return "";
}
/**
* Extract text content from various message content formats
*/
export function extractTextFromContent(content: unknown): string {
if (!content) return "";
// Handle string content directly
if (typeof content === "string") return content;
// Handle array content
if (!Array.isArray(content)) return "";
const texts: string[] = [];
for (const part of content) {
if (part && typeof part === "object") {
// Handle { type: "text", text: "..." }
if ("type" in part && part.type === "text" && "text" in part) {
texts.push(String(part.text));
}
// Handle { type: "tool_result", content: "..." }
else if ("type" in part && part.type === "tool_result" && "content" in part) {
const inner = extractTextFromContent(part.content);
if (inner) texts.push(inner);
}
// Handle { text: "..." } without type
else if ("text" in part) {
texts.push(String(part.text));
}
}
}
return texts.join("\n");
}
// ============================================================================
// Concurrency Utilities
// ============================================================================
/**
* Map over items with limited concurrency
*/
export async function mapConcurrent<T, R>(
items: T[],
limit: number,
fn: (item: T, i: number) => Promise<R>,
): Promise<R[]> {
// Clamp to at least 1; NaN/undefined/0/negative all become 1
const safeLimit = Math.max(1, Math.floor(limit) || 1);
const results: R[] = new Array(items.length);
let next = 0;
async function worker(): Promise<void> {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i], i);
}
}
const workers = Array.from({ length: Math.min(safeLimit, items.length) }, () => worker());
await Promise.all(workers);
return results;
}