@each1024/pi-mini-mode 2.0.17 → 2.0.19
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/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/extensions/footer-status.ts +70 -11
- package/lib/agent-render.ts +352 -14
- package/lib/agent-state.ts +109 -6
- package/lib/agent-view.ts +4 -1
- package/lib/assistant-images.ts +30 -3
- package/lib/file-links.ts +24 -3
- package/lib/input-editor.ts +26 -5
- package/lib/minimal-output.ts +417 -83
- package/lib/minimal-turns.ts +18 -2
- package/lib/print-agent.ts +712 -0
- package/lib/settings.ts +6 -2
- package/lib/token-speed.ts +219 -30
- package/lib/update-banner.ts +161 -0
- package/lib/usage.ts +41 -8
- package/package.json +2 -1
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
import { existsSync, openSync, readSync, closeSync, readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { childSessionData, plain } from "./agent-state.ts";
|
|
5
|
+
import type { AgentCall } from "./agent-render.ts";
|
|
6
|
+
|
|
7
|
+
export interface PrintInvocation {
|
|
8
|
+
prompt: string;
|
|
9
|
+
model?: string;
|
|
10
|
+
provider?: string;
|
|
11
|
+
thinking?: string;
|
|
12
|
+
sessionId?: string;
|
|
13
|
+
session?: string;
|
|
14
|
+
sessionDir?: string;
|
|
15
|
+
noSession?: boolean;
|
|
16
|
+
cwd?: string;
|
|
17
|
+
env?: Record<string, string>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const VALUE_FLAGS = new Set([
|
|
21
|
+
"--mode", "--provider", "--model", "-m", "--api-key", "--system-prompt", "--append-system-prompt",
|
|
22
|
+
"--name", "-n", "--session", "--session-id", "--fork", "--session-dir", "--models",
|
|
23
|
+
"--tools", "-t", "--exclude-tools", "-xt", "--thinking", "--export", "--extension", "-e",
|
|
24
|
+
"--skill", "--prompt-template", "--theme", "--use-theme", "--tui-mode", "--cwd", "-C",
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
const BOOLEAN_FLAGS = new Set([
|
|
28
|
+
"--continue", "-c", "--resume", "-r", "--no-session", "--no-tools", "-nt", "--no-builtin-tools", "-nbt",
|
|
29
|
+
"--no-extensions", "-ne", "--no-skills", "-ns", "--no-prompt-templates", "-np", "--no-themes",
|
|
30
|
+
"--no-context-files", "-nc", "--verbose", "--approve", "-a", "--no-approve", "-na", "--offline",
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
const REJECT_FLAGS = new Set(["--help", "-h", "--version", "-v", "--list-models", "--export"]);
|
|
34
|
+
const SUBCOMMANDS = new Set(["install", "remove", "update", "list", "auth", "config", "client", "server", "help"]);
|
|
35
|
+
const PIPE_FILTERS = new Set(["cat", "head", "tail", "tee", "grep", "rg", "sed", "awk", "jq", "wc", "cut", "tr", "sort"]);
|
|
36
|
+
|
|
37
|
+
function expandTilde(path: string): string {
|
|
38
|
+
if (path === "~") return homedir();
|
|
39
|
+
if (path.startsWith("~/") || path.startsWith("~\\")) return join(homedir(), path.slice(2));
|
|
40
|
+
return path;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function unescapeAnsiC(raw: string): string {
|
|
44
|
+
return raw.replace(/\\([abefnrtv\\'"]|x[0-9a-fA-F]{1,2}|u[0-9a-fA-F]{1,4}|[0-7]{1,3})/g, (_, seq: string) => {
|
|
45
|
+
switch (seq) {
|
|
46
|
+
case "a": return "\x07";
|
|
47
|
+
case "b": return "\b";
|
|
48
|
+
case "e": return "\x1b";
|
|
49
|
+
case "f": return "\f";
|
|
50
|
+
case "n": return "\n";
|
|
51
|
+
case "r": return "\r";
|
|
52
|
+
case "t": return "\t";
|
|
53
|
+
case "v": return "\v";
|
|
54
|
+
case "\\": return "\\";
|
|
55
|
+
case "'": return "'";
|
|
56
|
+
case '"': return '"';
|
|
57
|
+
default:
|
|
58
|
+
if (seq.startsWith("x") || seq.startsWith("u")) return String.fromCodePoint(parseInt(seq.slice(1), 16));
|
|
59
|
+
return String.fromCodePoint(parseInt(seq, 8));
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface RawSegment {
|
|
65
|
+
text: string;
|
|
66
|
+
opBefore: string;
|
|
67
|
+
heredocs: string[];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function splitShellSegments(command: string): RawSegment[] {
|
|
71
|
+
const lines = command.split(/\r?\n/);
|
|
72
|
+
const logicalLines: Array<{ text: string; heredocs: string[] }> = [];
|
|
73
|
+
for (let i = 0; i < lines.length; i++) {
|
|
74
|
+
let line = lines[i];
|
|
75
|
+
while (line.endsWith("\\") && i + 1 < lines.length) {
|
|
76
|
+
line = line.slice(0, -1) + lines[++i];
|
|
77
|
+
}
|
|
78
|
+
const heredocs: string[] = [];
|
|
79
|
+
// Detect unquoted <<EOF, <<'EOF', <<"EOF", <<-EOF on this line (excluding <<<).
|
|
80
|
+
const matcher = /(?:^|[^<])<<(-?)\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))/g;
|
|
81
|
+
let match: RegExpExecArray | null;
|
|
82
|
+
while ((match = matcher.exec(line)) !== null) {
|
|
83
|
+
const stripTabs = match[1] === "-";
|
|
84
|
+
const delim = match[2] ?? match[3] ?? match[4];
|
|
85
|
+
const bodyLines: string[] = [];
|
|
86
|
+
while (i + 1 < lines.length) {
|
|
87
|
+
const nextLine = lines[++i];
|
|
88
|
+
const check = stripTabs ? nextLine.replace(/^\t+/, "") : nextLine;
|
|
89
|
+
if (check.trim() === delim) break;
|
|
90
|
+
bodyLines.push(stripTabs ? check : nextLine);
|
|
91
|
+
}
|
|
92
|
+
heredocs.push(bodyLines.join("\n"));
|
|
93
|
+
}
|
|
94
|
+
logicalLines.push({ text: line, heredocs });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const segments: RawSegment[] = [];
|
|
98
|
+
for (const { text: line, heredocs } of logicalLines) {
|
|
99
|
+
let quote: "'" | '"' | "$'" | null = null;
|
|
100
|
+
let start = 0;
|
|
101
|
+
let opBefore = ";";
|
|
102
|
+
let usedHeredocs = false;
|
|
103
|
+
for (let i = 0; i < line.length; i++) {
|
|
104
|
+
const ch = line[i];
|
|
105
|
+
if (quote === "'") {
|
|
106
|
+
if (ch === "'") quote = null;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (quote === "$'") {
|
|
110
|
+
if (ch === "\\" && i + 1 < line.length) { i++; continue; }
|
|
111
|
+
if (ch === "'") quote = null;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (quote === '"') {
|
|
115
|
+
if (ch === "\\" && i + 1 < line.length) { i++; continue; }
|
|
116
|
+
if (ch === '"') quote = null;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (ch === "\\" && i + 1 < line.length) { i++; continue; }
|
|
120
|
+
if (ch === "$" && line[i + 1] === "'") { quote = "$'"; i++; continue; }
|
|
121
|
+
if (ch === "'" || ch === '"') { quote = ch; continue; }
|
|
122
|
+
if (ch === "#") {
|
|
123
|
+
// Comment to end of line if preceded by whitespace or start
|
|
124
|
+
if (i === start || /\s/.test(line[i - 1])) {
|
|
125
|
+
const piece = line.slice(start, i).trim();
|
|
126
|
+
if (piece) segments.push({ text: piece, opBefore, heredocs: usedHeredocs ? [] : heredocs });
|
|
127
|
+
start = line.length;
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (ch === ";") {
|
|
132
|
+
const piece = line.slice(start, i).trim();
|
|
133
|
+
if (piece) {
|
|
134
|
+
segments.push({ text: piece, opBefore, heredocs: usedHeredocs ? [] : heredocs });
|
|
135
|
+
usedHeredocs = true;
|
|
136
|
+
}
|
|
137
|
+
opBefore = ";";
|
|
138
|
+
start = i + 1;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (ch === "&") {
|
|
142
|
+
if (line[i - 1] === ">" || line[i + 1] === ">") continue;
|
|
143
|
+
const isAnd = line[i + 1] === "&";
|
|
144
|
+
const piece = line.slice(start, i).trim();
|
|
145
|
+
if (piece) {
|
|
146
|
+
segments.push({ text: piece, opBefore, heredocs: usedHeredocs ? [] : heredocs });
|
|
147
|
+
usedHeredocs = true;
|
|
148
|
+
}
|
|
149
|
+
opBefore = isAnd ? "&&" : "&";
|
|
150
|
+
if (isAnd) i++;
|
|
151
|
+
start = i + 1;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (ch === "|") {
|
|
155
|
+
const isOr = line[i + 1] === "|";
|
|
156
|
+
const piece = line.slice(start, i).trim();
|
|
157
|
+
if (piece) {
|
|
158
|
+
segments.push({ text: piece, opBefore, heredocs: usedHeredocs ? [] : heredocs });
|
|
159
|
+
usedHeredocs = true;
|
|
160
|
+
}
|
|
161
|
+
opBefore = isOr ? "||" : "|";
|
|
162
|
+
if (isOr) i++;
|
|
163
|
+
start = i + 1;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const tail = line.slice(start).trim();
|
|
168
|
+
if (tail) segments.push({ text: tail, opBefore, heredocs: usedHeredocs ? [] : heredocs });
|
|
169
|
+
}
|
|
170
|
+
return segments;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function tokenizeSegment(segment: string): { words: string[]; hereStrings: string[]; invalid: boolean } {
|
|
174
|
+
const words: string[] = [];
|
|
175
|
+
const hereStrings: string[] = [];
|
|
176
|
+
let i = 0;
|
|
177
|
+
const n = segment.length;
|
|
178
|
+
const readWord = (): { value: string; ok: boolean } => {
|
|
179
|
+
let value = "";
|
|
180
|
+
while (i < n && !/\s/.test(segment[i])) {
|
|
181
|
+
const ch = segment[i];
|
|
182
|
+
if (ch === "'") {
|
|
183
|
+
const end = segment.indexOf("'", i + 1);
|
|
184
|
+
if (end === -1) return { value, ok: false };
|
|
185
|
+
value += segment.slice(i + 1, end);
|
|
186
|
+
i = end + 1;
|
|
187
|
+
} else if (ch === "$" && segment[i + 1] === "'") {
|
|
188
|
+
i += 2;
|
|
189
|
+
let raw = "";
|
|
190
|
+
let closed = false;
|
|
191
|
+
while (i < n) {
|
|
192
|
+
if (segment[i] === "\\" && i + 1 < n) { raw += segment.slice(i, i + 2); i += 2; continue; }
|
|
193
|
+
if (segment[i] === "'") { closed = true; i++; break; }
|
|
194
|
+
raw += segment[i++];
|
|
195
|
+
}
|
|
196
|
+
if (!closed) return { value, ok: false };
|
|
197
|
+
value += unescapeAnsiC(raw);
|
|
198
|
+
} else if (ch === '"') {
|
|
199
|
+
i++;
|
|
200
|
+
let closed = false;
|
|
201
|
+
while (i < n) {
|
|
202
|
+
if (segment[i] === "\\" && i + 1 < n) {
|
|
203
|
+
const next = segment[i + 1];
|
|
204
|
+
if (next === '"' || next === "\\" || next === "$" || next === "`") { value += next; i += 2; continue; }
|
|
205
|
+
if (next === "\n") { i += 2; continue; }
|
|
206
|
+
}
|
|
207
|
+
if (segment[i] === '"') { closed = true; i++; break; }
|
|
208
|
+
value += segment[i++];
|
|
209
|
+
}
|
|
210
|
+
if (!closed) return { value, ok: false };
|
|
211
|
+
} else if (ch === "\\") {
|
|
212
|
+
if (i + 1 < n) { value += segment[i + 1]; i += 2; }
|
|
213
|
+
else i++;
|
|
214
|
+
} else {
|
|
215
|
+
value += segment[i++];
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return { value, ok: true };
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
while (i < n) {
|
|
222
|
+
while (i < n && /\s/.test(segment[i])) i++;
|
|
223
|
+
if (i >= n) break;
|
|
224
|
+
// Strip leading/trailing subshell parens
|
|
225
|
+
if (segment[i] === "(" || segment[i] === ")") { i++; continue; }
|
|
226
|
+
// Handle <<< here-string
|
|
227
|
+
if (segment.startsWith("<<<", i)) {
|
|
228
|
+
i += 3;
|
|
229
|
+
while (i < n && /\s/.test(segment[i])) i++;
|
|
230
|
+
const parsed = readWord();
|
|
231
|
+
if (!parsed.ok) return { words, hereStrings, invalid: true };
|
|
232
|
+
if (parsed.value) hereStrings.push(parsed.value);
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
// Handle << heredoc marker (body already extracted)
|
|
236
|
+
if (segment.startsWith("<<", i)) {
|
|
237
|
+
i += 2;
|
|
238
|
+
if (segment[i] === "-") i++;
|
|
239
|
+
while (i < n && /\s/.test(segment[i])) i++;
|
|
240
|
+
const parsed = readWord();
|
|
241
|
+
if (!parsed.ok) return { words, hereStrings, invalid: true };
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
// Handle redirections like 2>&1, >/tmp/out, 2>/dev/null, </dev/null
|
|
245
|
+
const redirMatch = segment.slice(i).match(/^(?:\d*>>?|\d*<&?\d*|&>>?)/);
|
|
246
|
+
if (redirMatch) {
|
|
247
|
+
i += redirMatch[0].length;
|
|
248
|
+
if (!redirMatch[0].includes("&") || redirMatch[0].startsWith("&>")) {
|
|
249
|
+
while (i < n && /\s/.test(segment[i])) i++;
|
|
250
|
+
if (i < n) readWord();
|
|
251
|
+
}
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const parsed = readWord();
|
|
255
|
+
if (!parsed.ok) return { words, hereStrings, invalid: true };
|
|
256
|
+
words.push(parsed.value);
|
|
257
|
+
}
|
|
258
|
+
return { words, hereStrings, invalid: false };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function isPiBinary(token: string): boolean {
|
|
262
|
+
return token === "pi" || /(?:^|[/\\])pi$/.test(token);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const parsePrintCache = new Map<string, PrintInvocation[]>();
|
|
266
|
+
const isPrintCallCache = new Map<string, boolean>();
|
|
267
|
+
const PRINT_CACHE_MAX = 800;
|
|
268
|
+
|
|
269
|
+
export function clearPrintAgentCaches(): void {
|
|
270
|
+
parsePrintCache.clear();
|
|
271
|
+
isPrintCallCache.clear();
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function parsePrintInvocationsUncached(command: string, baseCwd?: string): PrintInvocation[] {
|
|
275
|
+
if (typeof command !== "string" || !command.trim() || !/\bpi\b/.test(command)) return [];
|
|
276
|
+
const rawSegments = splitShellSegments(command);
|
|
277
|
+
if (!rawSegments.length) return [];
|
|
278
|
+
|
|
279
|
+
const invocations: PrintInvocation[] = [];
|
|
280
|
+
let currentCwd = baseCwd;
|
|
281
|
+
const globalEnv: Record<string, string> = {};
|
|
282
|
+
|
|
283
|
+
for (const [segIndex, seg] of rawSegments.entries()) {
|
|
284
|
+
const { words, hereStrings, invalid } = tokenizeSegment(seg.text);
|
|
285
|
+
if (invalid) return [];
|
|
286
|
+
if (!words.length) continue;
|
|
287
|
+
|
|
288
|
+
// Collect leading ENV=VALUE tokens
|
|
289
|
+
const localEnv: Record<string, string> = { ...globalEnv };
|
|
290
|
+
let idx = 0;
|
|
291
|
+
while (idx < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[idx])) {
|
|
292
|
+
const eq = words[idx].indexOf("=");
|
|
293
|
+
localEnv[words[idx].slice(0, eq)] = words[idx].slice(eq + 1);
|
|
294
|
+
idx++;
|
|
295
|
+
}
|
|
296
|
+
if (idx >= words.length) {
|
|
297
|
+
Object.assign(globalEnv, localEnv);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const head = words[idx];
|
|
302
|
+
if (head === "cd") {
|
|
303
|
+
const target = words[idx + 1];
|
|
304
|
+
if (target) {
|
|
305
|
+
const expanded = expandTilde(target);
|
|
306
|
+
currentCwd = currentCwd ? resolve(currentCwd, expanded) : expanded;
|
|
307
|
+
}
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
if (head === "export") {
|
|
311
|
+
for (let j = idx + 1; j < words.length; j++) {
|
|
312
|
+
const eq = words[j].indexOf("=");
|
|
313
|
+
if (eq > 0) globalEnv[words[j].slice(0, eq)] = words[j].slice(eq + 1);
|
|
314
|
+
}
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (head === "wait" || head === "true" || head === ":" || head === "echo" && seg.opBefore !== "|") {
|
|
318
|
+
if (head === "wait" || head === "true" || head === ":") continue;
|
|
319
|
+
}
|
|
320
|
+
if (seg.opBefore === "|" && invocations.length > 0 && PIPE_FILTERS.has(head)) {
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (head === "env") {
|
|
325
|
+
idx++;
|
|
326
|
+
while (idx < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[idx])) {
|
|
327
|
+
const eq = words[idx].indexOf("=");
|
|
328
|
+
localEnv[words[idx].slice(0, eq)] = words[idx].slice(eq + 1);
|
|
329
|
+
idx++;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (idx < words.length && (words[idx] === "npx" || words[idx] === "bunx" || words[idx] === "pnpx")) {
|
|
333
|
+
idx++;
|
|
334
|
+
while (idx < words.length && (words[idx] === "-y" || words[idx] === "--yes")) idx++;
|
|
335
|
+
if (idx < words.length && (words[idx] === "pi" || words[idx] === "@earendil-works/pi-coding-agent")) {
|
|
336
|
+
idx++;
|
|
337
|
+
} else {
|
|
338
|
+
return [];
|
|
339
|
+
}
|
|
340
|
+
} else if (idx < words.length && isPiBinary(words[idx])) {
|
|
341
|
+
idx++;
|
|
342
|
+
} else if (rawSegments[segIndex + 1]?.opBefore === "|") {
|
|
343
|
+
// A producer piped into pi (`git diff | pi -p ...`) is the child's input.
|
|
344
|
+
continue;
|
|
345
|
+
} else {
|
|
346
|
+
return [];
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const args = words.slice(idx);
|
|
350
|
+
if (args.length > 0 && SUBCOMMANDS.has(args[0])) return [];
|
|
351
|
+
|
|
352
|
+
let isPrint = false;
|
|
353
|
+
let model: string | undefined;
|
|
354
|
+
let provider: string | undefined;
|
|
355
|
+
let thinking: string | undefined;
|
|
356
|
+
let sessionId: string | undefined;
|
|
357
|
+
let session: string | undefined;
|
|
358
|
+
let sessionDir: string | undefined;
|
|
359
|
+
let noSession = false;
|
|
360
|
+
let invCwd = currentCwd;
|
|
361
|
+
const messages: string[] = [];
|
|
362
|
+
|
|
363
|
+
for (let i = 0; i < args.length; i++) {
|
|
364
|
+
const arg = args[i];
|
|
365
|
+
if (arg === "--") {
|
|
366
|
+
for (const pos of args.slice(i + 1)) {
|
|
367
|
+
if (!pos.startsWith("@")) messages.push(pos);
|
|
368
|
+
}
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
if (REJECT_FLAGS.has(arg)) return [];
|
|
372
|
+
if (arg === "-p" || arg === "--print") {
|
|
373
|
+
isPrint = true;
|
|
374
|
+
const next = args[i + 1];
|
|
375
|
+
if (next !== undefined && !next.startsWith("@") && (!next.startsWith("-") || next.startsWith("---"))) {
|
|
376
|
+
messages.push(next);
|
|
377
|
+
i++;
|
|
378
|
+
}
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
const eqIdx = arg.startsWith("--") ? arg.indexOf("=") : -1;
|
|
382
|
+
const flag = eqIdx !== -1 ? arg.slice(0, eqIdx) : arg;
|
|
383
|
+
const inlineVal = eqIdx !== -1 ? arg.slice(eqIdx + 1) : undefined;
|
|
384
|
+
const takeVal = (): string | undefined => inlineVal !== undefined ? inlineVal : args[++i];
|
|
385
|
+
|
|
386
|
+
if (flag === "--mode") {
|
|
387
|
+
const mode = takeVal();
|
|
388
|
+
if (mode === "json") isPrint = true;
|
|
389
|
+
else if (mode === "rpc") return [];
|
|
390
|
+
} else if (flag === "--model" || flag === "-m") {
|
|
391
|
+
model = takeVal();
|
|
392
|
+
} else if (flag === "--provider") {
|
|
393
|
+
provider = takeVal();
|
|
394
|
+
} else if (flag === "--thinking") {
|
|
395
|
+
thinking = takeVal();
|
|
396
|
+
} else if (flag === "--session-id") {
|
|
397
|
+
sessionId = takeVal();
|
|
398
|
+
} else if (flag === "--session") {
|
|
399
|
+
session = takeVal();
|
|
400
|
+
} else if (flag === "--session-dir") {
|
|
401
|
+
sessionDir = takeVal();
|
|
402
|
+
} else if (flag === "--no-session") {
|
|
403
|
+
noSession = true;
|
|
404
|
+
} else if (flag === "--cwd" || flag === "-C") {
|
|
405
|
+
const dir = takeVal();
|
|
406
|
+
if (dir) invCwd = currentCwd ? resolve(currentCwd, expandTilde(dir)) : expandTilde(dir);
|
|
407
|
+
} else if (VALUE_FLAGS.has(flag)) {
|
|
408
|
+
if (inlineVal === undefined && i + 1 < args.length) i++;
|
|
409
|
+
} else if (BOOLEAN_FLAGS.has(flag)) {
|
|
410
|
+
// boolean flag, no value
|
|
411
|
+
} else if (arg.startsWith("@")) {
|
|
412
|
+
// @file attachment
|
|
413
|
+
} else if (arg.startsWith("--")) {
|
|
414
|
+
if (inlineVal === undefined && i + 1 < args.length && !args[i + 1].startsWith("-") && !args[i + 1].startsWith("@")) {
|
|
415
|
+
i++;
|
|
416
|
+
}
|
|
417
|
+
} else if (!arg.startsWith("-")) {
|
|
418
|
+
messages.push(arg);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
for (const hs of hereStrings) if (hs.trim()) messages.push(hs);
|
|
423
|
+
for (const hd of seg.heredocs) if (hd.trim()) messages.push(hd);
|
|
424
|
+
|
|
425
|
+
const prompt = messages.join("\n").trim();
|
|
426
|
+
if (!isPrint || !prompt) return [];
|
|
427
|
+
|
|
428
|
+
invocations.push({
|
|
429
|
+
prompt,
|
|
430
|
+
model,
|
|
431
|
+
provider,
|
|
432
|
+
thinking,
|
|
433
|
+
sessionId,
|
|
434
|
+
session,
|
|
435
|
+
sessionDir,
|
|
436
|
+
noSession: noSession || undefined,
|
|
437
|
+
cwd: invCwd,
|
|
438
|
+
env: Object.keys(localEnv).length ? localEnv : undefined,
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return invocations;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
export function parsePrintInvocations(command: string, baseCwd?: string): PrintInvocation[] {
|
|
446
|
+
if (typeof command !== "string" || !command.trim() || !/\bpi\b/.test(command)) return [];
|
|
447
|
+
const key = `${baseCwd ?? ""}|${command}`;
|
|
448
|
+
const hit = parsePrintCache.get(key);
|
|
449
|
+
if (hit !== undefined) return hit;
|
|
450
|
+
const result = parsePrintInvocationsUncached(command, baseCwd);
|
|
451
|
+
if (parsePrintCache.size >= PRINT_CACHE_MAX) {
|
|
452
|
+
const first = parsePrintCache.keys().next().value;
|
|
453
|
+
if (first !== undefined) parsePrintCache.delete(first);
|
|
454
|
+
}
|
|
455
|
+
parsePrintCache.set(key, result);
|
|
456
|
+
return result;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const singleLine = (value: string) => plain(value).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
|
|
460
|
+
|
|
461
|
+
function readFirstUserMessage(filePath: string): { sessionId?: string; userText?: string; startedAt?: number } {
|
|
462
|
+
try {
|
|
463
|
+
const fd = openSync(filePath, "r");
|
|
464
|
+
try {
|
|
465
|
+
const buf = Buffer.allocUnsafe(65536);
|
|
466
|
+
const bytes = readSync(fd, buf, 0, buf.length, 0);
|
|
467
|
+
if (bytes <= 0) return {};
|
|
468
|
+
const chunk = buf.subarray(0, bytes).toString("utf8");
|
|
469
|
+
let sessionId: string | undefined;
|
|
470
|
+
let startedAt: number | undefined;
|
|
471
|
+
for (const line of chunk.split(/\r?\n/)) {
|
|
472
|
+
if (!line.trim()) continue;
|
|
473
|
+
try {
|
|
474
|
+
const entry = JSON.parse(line) as {
|
|
475
|
+
type?: string;
|
|
476
|
+
id?: string;
|
|
477
|
+
timestamp?: unknown;
|
|
478
|
+
message?: { role?: string; content?: unknown; timestamp?: unknown };
|
|
479
|
+
};
|
|
480
|
+
if (entry.type === "session") {
|
|
481
|
+
if (typeof entry.id === "string") sessionId = entry.id;
|
|
482
|
+
if (typeof entry.timestamp === "string") {
|
|
483
|
+
const t = Date.parse(entry.timestamp);
|
|
484
|
+
if (Number.isFinite(t)) startedAt = t;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (entry.type === "message" && entry.message?.role === "user") {
|
|
488
|
+
const content = entry.message.content;
|
|
489
|
+
const userText = typeof content === "string"
|
|
490
|
+
? content
|
|
491
|
+
: Array.isArray(content)
|
|
492
|
+
? content
|
|
493
|
+
.filter((b): b is { type?: string; text?: string } => Boolean(b && typeof b === "object"))
|
|
494
|
+
.filter(b => b.type === "text" && typeof b.text === "string")
|
|
495
|
+
.map(b => b.text!)
|
|
496
|
+
.join("\n")
|
|
497
|
+
: "";
|
|
498
|
+
return { sessionId, userText, startedAt };
|
|
499
|
+
}
|
|
500
|
+
} catch { /* partial line */ }
|
|
501
|
+
}
|
|
502
|
+
return { sessionId, startedAt };
|
|
503
|
+
} finally {
|
|
504
|
+
closeSync(fd);
|
|
505
|
+
}
|
|
506
|
+
} catch {
|
|
507
|
+
return {};
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function promptMatches(userText: string | undefined, prompt: string): boolean {
|
|
512
|
+
if (!userText) return false;
|
|
513
|
+
const trimmedUser = userText.trim();
|
|
514
|
+
const trimmedPrompt = prompt.trim();
|
|
515
|
+
if (!trimmedUser || !trimmedPrompt) return false;
|
|
516
|
+
const rawPrefixLen = Math.min(trimmedPrompt.length, 64);
|
|
517
|
+
if (trimmedUser.startsWith(trimmedPrompt.slice(0, rawPrefixLen))) return true;
|
|
518
|
+
const normUser = singleLine(trimmedUser);
|
|
519
|
+
const normPrompt = singleLine(trimmedPrompt);
|
|
520
|
+
if (!normUser || !normPrompt) return false;
|
|
521
|
+
const prefixLen = Math.min(normPrompt.length, 64);
|
|
522
|
+
return normUser.startsWith(normPrompt.slice(0, prefixLen)) || normPrompt.startsWith(normUser.slice(0, Math.min(normUser.length, 64)));
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const locatedBySegment = new Map<string, string>();
|
|
526
|
+
const lastScanBySegment = new Map<string, { at: number; terminalScanned: boolean }>();
|
|
527
|
+
|
|
528
|
+
export function defaultSessionDirForCwd(cwd: string, env?: Record<string, string>): string {
|
|
529
|
+
const resolvedCwd = resolve(expandTilde(cwd));
|
|
530
|
+
const agentEnv = env?.PI_CODING_AGENT_DIR || process.env.PI_CODING_AGENT_DIR;
|
|
531
|
+
const agentDir = agentEnv ? resolve(expandTilde(agentEnv)) : join(homedir(), ".pi", "agent");
|
|
532
|
+
const safePath = `--${resolvedCwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
|
|
533
|
+
return join(agentDir, "sessions", safePath);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export function locatePrintSession(
|
|
537
|
+
inv: PrintInvocation,
|
|
538
|
+
cwd = process.cwd(),
|
|
539
|
+
startedAt?: number,
|
|
540
|
+
claimed?: Set<string>,
|
|
541
|
+
cacheKey?: string,
|
|
542
|
+
terminal = false,
|
|
543
|
+
): string | undefined {
|
|
544
|
+
if (inv.noSession) return undefined;
|
|
545
|
+
if (cacheKey) {
|
|
546
|
+
const cached = locatedBySegment.get(cacheKey);
|
|
547
|
+
if (cached) {
|
|
548
|
+
claimed?.add(cached);
|
|
549
|
+
return cached;
|
|
550
|
+
}
|
|
551
|
+
const scanState = lastScanBySegment.get(cacheKey);
|
|
552
|
+
const now = Date.now();
|
|
553
|
+
if (scanState) {
|
|
554
|
+
if (scanState.terminalScanned) return undefined;
|
|
555
|
+
if (!terminal && now - scanState.at < 1000) return undefined;
|
|
556
|
+
}
|
|
557
|
+
lastScanBySegment.set(cacheKey, { at: now, terminalScanned: terminal });
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const baseCwd = cwd || process.cwd();
|
|
561
|
+
const effectiveCwd = inv.cwd ? resolve(baseCwd, expandTilde(inv.cwd)) : resolve(baseCwd);
|
|
562
|
+
|
|
563
|
+
if (inv.session) {
|
|
564
|
+
const explicitPath = resolve(effectiveCwd, expandTilde(inv.session));
|
|
565
|
+
if (existsSync(explicitPath) && explicitPath.endsWith(".jsonl") && !claimed?.has(explicitPath)) {
|
|
566
|
+
claimed?.add(explicitPath);
|
|
567
|
+
if (cacheKey) locatedBySegment.set(cacheKey, explicitPath);
|
|
568
|
+
return explicitPath;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const envSessionDir = inv.env?.PI_CODING_AGENT_SESSION_DIR || process.env.PI_CODING_AGENT_SESSION_DIR;
|
|
573
|
+
const sessionDir = inv.sessionDir
|
|
574
|
+
? resolve(effectiveCwd, expandTilde(inv.sessionDir))
|
|
575
|
+
: envSessionDir
|
|
576
|
+
? resolve(effectiveCwd, expandTilde(envSessionDir))
|
|
577
|
+
: defaultSessionDirForCwd(effectiveCwd, inv.env);
|
|
578
|
+
|
|
579
|
+
try {
|
|
580
|
+
const names = readdirSync(sessionDir).filter(name => name.endsWith(".jsonl"));
|
|
581
|
+
const targetId = inv.sessionId || (inv.session && !inv.session.endsWith(".jsonl") ? inv.session : undefined);
|
|
582
|
+
if (targetId) {
|
|
583
|
+
for (const name of names) {
|
|
584
|
+
if (name === `${targetId}.jsonl` || name.endsWith(`_${targetId}.jsonl`)) {
|
|
585
|
+
const full = join(sessionDir, name);
|
|
586
|
+
if (claimed?.has(full)) continue;
|
|
587
|
+
claimed?.add(full);
|
|
588
|
+
if (cacheKey) locatedBySegment.set(cacheKey, full);
|
|
589
|
+
return full;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
for (const name of names) {
|
|
593
|
+
const full = join(sessionDir, name);
|
|
594
|
+
if (claimed?.has(full)) continue;
|
|
595
|
+
const info = readFirstUserMessage(full);
|
|
596
|
+
if (info.sessionId === targetId) {
|
|
597
|
+
claimed?.add(full);
|
|
598
|
+
if (cacheKey) locatedBySegment.set(cacheKey, full);
|
|
599
|
+
return full;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
return undefined;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
const hasStart = typeof startedAt === "number" && Number.isFinite(startedAt) && startedAt > 0;
|
|
606
|
+
const candidates: Array<{ full: string; mtimeMs: number; birthtimeMs: number }> = [];
|
|
607
|
+
for (const name of names) {
|
|
608
|
+
const full = join(sessionDir, name);
|
|
609
|
+
if (claimed?.has(full)) continue;
|
|
610
|
+
try {
|
|
611
|
+
const st = statSync(full);
|
|
612
|
+
if (hasStart && st.mtimeMs < startedAt - 3000) continue;
|
|
613
|
+
candidates.push({ full, mtimeMs: st.mtimeMs, birthtimeMs: st.birthtimeMs || st.mtimeMs });
|
|
614
|
+
} catch { /* ignore */ }
|
|
615
|
+
}
|
|
616
|
+
candidates.sort((a, b) => hasStart
|
|
617
|
+
? Math.abs(a.birthtimeMs - startedAt) - Math.abs(b.birthtimeMs - startedAt)
|
|
618
|
+
: b.mtimeMs - a.mtimeMs);
|
|
619
|
+
|
|
620
|
+
for (const cand of candidates) {
|
|
621
|
+
const info = readFirstUserMessage(cand.full);
|
|
622
|
+
if (hasStart && info.startedAt !== undefined && info.startedAt < startedAt - 3000) continue;
|
|
623
|
+
if (promptMatches(info.userText, inv.prompt)) {
|
|
624
|
+
claimed?.add(cand.full);
|
|
625
|
+
if (cacheKey) locatedBySegment.set(cacheKey, cand.full);
|
|
626
|
+
return cand.full;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
} catch { /* directory missing or unreadable */ }
|
|
630
|
+
return undefined;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
export function isPrintAgentCall(call: Pick<AgentCall, "name" | "tool" | "task"> & { command?: string }): boolean {
|
|
634
|
+
const toolName = call.tool ?? call.name;
|
|
635
|
+
if (toolName !== "bash") return false;
|
|
636
|
+
const cmd = typeof call.command === "string" ? call.command : call.task;
|
|
637
|
+
if (typeof cmd !== "string" || !cmd) return false;
|
|
638
|
+
const hit = isPrintCallCache.get(cmd);
|
|
639
|
+
if (hit !== undefined) return hit;
|
|
640
|
+
const result = parsePrintInvocations(cmd).length > 0;
|
|
641
|
+
if (isPrintCallCache.size >= PRINT_CACHE_MAX) {
|
|
642
|
+
const first = isPrintCallCache.keys().next().value;
|
|
643
|
+
if (first !== undefined) isPrintCallCache.delete(first);
|
|
644
|
+
}
|
|
645
|
+
isPrintCallCache.set(cmd, result);
|
|
646
|
+
return result;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
const GENERIC_CALL_OUTPUT = /^(?:Call (?:returned|failed) \([^)]*\)|Tool (?:completed|failed) \([^)]*\))$/;
|
|
650
|
+
|
|
651
|
+
export function printAgentStatuses(
|
|
652
|
+
call: AgentCall & { command?: string },
|
|
653
|
+
cwd = process.cwd(),
|
|
654
|
+
claimed?: Set<string>,
|
|
655
|
+
): Record<string, unknown>[] {
|
|
656
|
+
const toolName = call.tool ?? call.name;
|
|
657
|
+
if (toolName !== "bash") return [];
|
|
658
|
+
const cmd = typeof call.command === "string" ? call.command : call.task;
|
|
659
|
+
const invocations = parsePrintInvocations(cmd, cwd);
|
|
660
|
+
if (!invocations.length) return [];
|
|
661
|
+
|
|
662
|
+
const terminal = call.state !== "running";
|
|
663
|
+
return invocations.map((inv, index) => {
|
|
664
|
+
const runId = `${call.id}#${index}`;
|
|
665
|
+
const sessionFile = locatePrintSession(inv, cwd, call.startedAt, claimed, runId, terminal);
|
|
666
|
+
const session = childSessionData(sessionFile);
|
|
667
|
+
const cliModel = inv.model
|
|
668
|
+
? (inv.provider && !inv.model.startsWith(`${inv.provider}/`) ? `${inv.provider}/${inv.model}` : inv.model)
|
|
669
|
+
: undefined;
|
|
670
|
+
const model = session?.model || cliModel;
|
|
671
|
+
const thinking = session?.thinking || inv.thinking;
|
|
672
|
+
const state = call.state === "error"
|
|
673
|
+
? (invocations.length > 1 && session?.terminalState === "complete" ? "complete" : "failed")
|
|
674
|
+
: call.state === "running"
|
|
675
|
+
? (session?.terminalState ?? "running")
|
|
676
|
+
: (session?.terminalState === "failed" ? "failed" : "complete");
|
|
677
|
+
const childTerminal = state !== "running";
|
|
678
|
+
const startedAt = session?.startedAt ?? call.startedAt;
|
|
679
|
+
const endedAt = childTerminal
|
|
680
|
+
? (invocations.length > 1 || call.state === "running"
|
|
681
|
+
? session?.endedAt ?? call.endedAt
|
|
682
|
+
: call.endedAt ?? session?.endedAt)
|
|
683
|
+
: undefined;
|
|
684
|
+
const rawOutput = call.output && !GENERIC_CALL_OUTPUT.test(call.output.trim()) ? call.output : undefined;
|
|
685
|
+
const finalOutput = session?.finalOutput || session?.latestText || (childTerminal && invocations.length === 1 ? rawOutput : undefined);
|
|
686
|
+
const error = state === "failed" ? (rawOutput || call.output || "Command failed") : undefined;
|
|
687
|
+
const recentTools = session?.steps.map(step => ({
|
|
688
|
+
tool: step.name,
|
|
689
|
+
args: step.value,
|
|
690
|
+
endMs: step.at,
|
|
691
|
+
})) ?? [];
|
|
692
|
+
return {
|
|
693
|
+
runId,
|
|
694
|
+
mode: "single",
|
|
695
|
+
agent: "pi -p",
|
|
696
|
+
source: "pi -p",
|
|
697
|
+
task: inv.prompt,
|
|
698
|
+
description: inv.prompt,
|
|
699
|
+
model,
|
|
700
|
+
thinking,
|
|
701
|
+
sessionFile,
|
|
702
|
+
startedAt,
|
|
703
|
+
endedAt,
|
|
704
|
+
state,
|
|
705
|
+
status: state,
|
|
706
|
+
finalOutput,
|
|
707
|
+
error,
|
|
708
|
+
recentTools,
|
|
709
|
+
toolCallId: call.id,
|
|
710
|
+
};
|
|
711
|
+
});
|
|
712
|
+
}
|