@each1024/pi-mini-mode 2.0.18 → 2.0.20

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,6 +1,7 @@
1
1
  import { readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import { join, resolve } from "node:path";
3
3
  import { tmpdir } from "node:os";
4
+ import { addUsage, EMPTY_USAGE, finiteNumber, type SessionUsage, type UsageLike } from "./usage.ts";
4
5
 
5
6
  export const plain = (text: string) => text.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").trim();
6
7
 
@@ -12,10 +13,43 @@ export function stripAcceptanceReport(output: string): string {
12
13
  .trimEnd();
13
14
  }
14
15
 
16
+ export interface ChildSessionStep {
17
+ at: number;
18
+ name: string;
19
+ value: string;
20
+ input: number;
21
+ }
22
+
23
+ export interface ChildSessionInfo {
24
+ stamp: string;
25
+ sessionId: string;
26
+ model: string;
27
+ thinking: string;
28
+ finalOutput: string;
29
+ latestText: string;
30
+ inputs: Array<{ name: string; value: string }>;
31
+ usage: SessionUsage;
32
+ turns: number;
33
+ steps: ChildSessionStep[];
34
+ startedAt?: number;
35
+ endedAt?: number;
36
+ terminalState?: "complete" | "failed";
37
+ }
38
+
39
+ function entryTimestampMs(entry: { timestamp?: unknown }, message?: { timestamp?: unknown }): number | undefined {
40
+ if (typeof entry.timestamp === "number" && Number.isFinite(entry.timestamp)) return entry.timestamp;
41
+ if (typeof entry.timestamp === "string") {
42
+ const parsed = Date.parse(entry.timestamp);
43
+ if (Number.isFinite(parsed)) return parsed;
44
+ }
45
+ if (typeof message?.timestamp === "number" && Number.isFinite(message.timestamp)) return message.timestamp;
46
+ return undefined;
47
+ }
48
+
15
49
  /** Recover the child's own prose and raw tool inputs from its session, never from activity previews. */
16
- const childSessionCache = new Map<string, { stamp: string; thinking: string; finalOutput: string; latestText: string; inputs: Array<{ name: string; value: string }> }>();
50
+ const childSessionCache = new Map<string, ChildSessionInfo>();
17
51
  const singleLine = (value: string) => plain(value).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ");
18
- export function childSessionData(sessionFile: unknown) {
52
+ export function childSessionData(sessionFile: unknown): ChildSessionInfo | undefined {
19
53
  if (typeof sessionFile !== "string") return undefined;
20
54
  try {
21
55
  const stat = statSync(sessionFile);
@@ -23,36 +57,105 @@ export function childSessionData(sessionFile: unknown) {
23
57
  let cached = childSessionCache.get(sessionFile);
24
58
  if (!cached || cached.stamp !== stamp) {
25
59
  const inputs: Array<{ name: string; value: string }> = [];
60
+ const steps: ChildSessionStep[] = [];
61
+ let sessionId = "";
62
+ let model = "";
26
63
  let thinking = "";
27
64
  let finalOutput = "";
28
65
  let latestText = "";
66
+ let usage: SessionUsage = { ...EMPTY_USAGE };
67
+ let turns = 0;
68
+ let startedAt: number | undefined;
69
+ let endedAt: number | undefined;
70
+ let terminalState: "complete" | "failed" | undefined;
29
71
  for (const line of readFileSync(sessionFile, "utf8").split(/\r?\n/)) {
30
72
  try {
31
- const entry = JSON.parse(line) as { type?: string; thinkingLevel?: string; message?: { role?: string; stopReason?: string; channel?: string; content?: Array<{ type?: string; text?: string; name?: string; input?: Record<string, unknown>; arguments?: Record<string, unknown> } | null> } };
73
+ const entry = JSON.parse(line) as {
74
+ type?: string;
75
+ id?: string;
76
+ timestamp?: unknown;
77
+ provider?: string;
78
+ modelId?: string;
79
+ thinkingLevel?: string;
80
+ usage?: UsageLike;
81
+ message?: {
82
+ role?: string;
83
+ provider?: string;
84
+ model?: string;
85
+ thinkingLevel?: string;
86
+ timestamp?: unknown;
87
+ usage?: UsageLike;
88
+ stopReason?: string;
89
+ channel?: string;
90
+ content?: Array<{ type?: string; text?: string; name?: string; input?: Record<string, unknown>; arguments?: Record<string, unknown> } | null>;
91
+ };
92
+ };
93
+ const entryAt = entryTimestampMs(entry, entry.message);
94
+ if (entryAt !== undefined) {
95
+ startedAt ??= entryAt;
96
+ endedAt = Math.max(endedAt ?? entryAt, entryAt);
97
+ }
98
+ if (entry.type === "session" && typeof entry.id === "string") sessionId = entry.id;
99
+ if (entry.type === "model_change" && typeof entry.modelId === "string" && entry.modelId) {
100
+ model = typeof entry.provider === "string" && entry.provider && !entry.modelId.startsWith(`${entry.provider}/`)
101
+ ? `${entry.provider}/${entry.modelId}` : entry.modelId;
102
+ }
32
103
  if (entry.type === "thinking_level_change" && /^(off|minimal|low|medium|high|xhigh|max)$/.test(entry.thinkingLevel ?? "")) thinking = entry.thinkingLevel!;
104
+ if (entry.type === "usage") usage = addUsage(usage, (entry.usage ?? entry) as UsageLike);
105
+ if (entry.message?.role === "user") {
106
+ terminalState = undefined;
107
+ continue;
108
+ }
109
+ if (entry.message?.role === "toolResult") {
110
+ terminalState = undefined;
111
+ if (entry.message.usage) usage = addUsage(usage, entry.message.usage);
112
+ continue;
113
+ }
33
114
  if (entry.message?.role !== "assistant") continue;
34
115
  const message = entry.message;
116
+ turns++;
117
+ usage = addUsage(usage, message.usage);
118
+ if (typeof message.model === "string" && message.model) {
119
+ model = typeof message.provider === "string" && message.provider && !message.model.startsWith(`${message.provider}/`)
120
+ ? `${message.provider}/${message.model}` : message.model;
121
+ }
122
+ if (!thinking && typeof message.thinkingLevel === "string" && /^(off|minimal|low|medium|high|xhigh|max)$/.test(message.thinkingLevel)) {
123
+ thinking = message.thinkingLevel;
124
+ }
125
+ const msgInput = Math.max(0, (finiteNumber(message.usage?.input) ?? 0) + (finiteNumber(message.usage?.cacheRead) ?? 0) + (finiteNumber(message.usage?.cacheWrite) ?? 0));
126
+ const stepAt = entryAt ?? startedAt ?? stat.mtimeMs;
35
127
  const content = Array.isArray(message.content) ? message.content : [];
128
+ const hasToolCall = content.some(block => block?.type === "toolCall");
36
129
  const text = content.filter(block => block?.type === "text" && typeof block.text === "string").map(block => block!.text).join("\n\n").trim();
37
130
  // Pi persists no channel: only a stopped assistant text reply is a final answer.
38
131
  finalOutput = entry.type === "message" && message.stopReason === "stop"
39
132
  && (message.channel === undefined || message.channel === "final")
40
- && !content.some(block => block?.type === "toolCall")
133
+ && !hasToolCall
41
134
  ? text : "";
135
+ terminalState = !hasToolCall && message.stopReason === "stop" ? "complete"
136
+ : /^(error|aborted)$/.test(message.stopReason ?? "") ? "failed"
137
+ : undefined;
42
138
  // Narration attached to a tool call is still the child's own prose; it
43
139
  // is the only body a running or tool-ended child has.
44
140
  if (entry.type === "message" && text) latestText = text;
141
+ let turnInputAssigned = false;
45
142
  for (const call of content) {
46
143
  if (!call) continue;
47
144
  if (call.type !== "toolCall" || typeof call.name !== "string") continue;
48
145
  const input = call.arguments ?? call.input ?? {};
49
146
  const value = [input.path, input.command, input.pattern, input.query, input.task, input.prompt]
50
147
  .find((candidate): candidate is string => typeof candidate === "string") ?? "";
51
- if (value) inputs.push({ name: call.name, value: singleLine(value) });
148
+ const cleanValue = value ? singleLine(value) : "";
149
+ if (cleanValue) inputs.push({ name: call.name, value: cleanValue });
150
+ const stepVal = call.name === "grep" && typeof input.pattern === "string" && typeof input.path === "string"
151
+ ? `${singleLine(input.pattern)} ${singleLine(input.path)}`
152
+ : cleanValue;
153
+ steps.push({ at: stepAt, name: call.name, value: stepVal, input: turnInputAssigned ? 0 : msgInput });
154
+ turnInputAssigned = true;
52
155
  }
53
156
  } catch { /* A concurrently written session can end with a partial line. */ }
54
157
  }
55
- cached = { stamp, thinking, finalOutput, latestText, inputs };
158
+ cached = { stamp, sessionId, model, thinking, finalOutput, latestText, inputs, usage, turns, steps, startedAt, endedAt, terminalState };
56
159
  childSessionCache.set(sessionFile, cached);
57
160
  }
58
161
  return cached;
@@ -84,14 +187,16 @@ export function retainAgentStatuses(previous: Record<string, unknown>[], current
84
187
  const retained = new Map(previous.map(status => [String(status.runId), status]));
85
188
  for (const status of new Map([...previous, ...current].map(status => [String(status.runId), status])).values()) {
86
189
  const saved = retained.get(String(status.runId));
87
- const children = agentChildren([status]).map(child => {
88
- const previous = saved && agentChildren([saved]).find(item => item.displayId === child.displayId);
190
+ const children = agentChildren([status]);
191
+ const previousChildren = saved && saved !== status ? agentChildren([saved]) : saved ? children : undefined;
192
+ const merged = children.map(child => {
193
+ const previous = previousChildren?.find(item => item.displayId === child.displayId);
89
194
  const sameAttempt = previous?.sessionFile === child.sessionFile && previous?.startedAt === child.startedAt;
90
195
  const finalOutput = childSessionData(child.sessionFile)?.finalOutput ?? child.finalOutput ?? (sameAttempt ? previous?.finalOutput : undefined);
91
196
  return { ...child, finalOutput, notice: child.notice ?? previous?.notice, noticeMessages: child.noticeMessages ?? previous?.noticeMessages };
92
197
  });
93
- retained.set(String(status.runId), children.length
94
- ? { ...status, steps: children, workflowChildren: undefined, children: undefined } : status);
198
+ retained.set(String(status.runId), merged.length
199
+ ? { ...status, steps: merged, workflowChildren: undefined, children: undefined } : status);
95
200
  }
96
201
  return [...retained.values()];
97
202
  }
@@ -115,38 +220,173 @@ export function readAgentStatuses(sessionId: string, root = process.env.PI_SUBAG
115
220
  } catch { return previous.filter(status => status.sessionId === sessionId); }
116
221
  }
117
222
 
118
- export function currentAgentStatuses(statuses: Record<string, unknown>[], callsOrIds: unknown[]): Record<string, unknown>[] {
223
+ // Frames re-read every call output unless the source values are unchanged. Object calls
224
+ // keep their extracted run ids in a WeakMap (collected with the call); short string ids use
225
+ // a bounded LRU. Any edited source rescans that call. An append can create or destroy a
226
+ // UUID word boundary, so a tail increment is not reused.
227
+ const RUN_ID_PATTERN = /\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/gi;
228
+ const STRING_RUN_CACHE_LIMIT = 256;
229
+ const STRING_RUN_CACHE_MAX_LENGTH = 128;
230
+ const stringRunCache = new Map<string, string | null>();
231
+ type SourceSnap = { ref: unknown; text?: string };
232
+ type CallSnap = { id: SourceSnap; output: SourceSnap; task: SourceSnap; action: SourceSnap; callId?: string; runIds: string[] };
233
+ const callSnaps = new WeakMap<object, CallSnap>();
234
+
235
+ function sourceSnap(value: unknown): SourceSnap {
236
+ if (typeof value === "string" || value == null) return { ref: value };
237
+ return { ref: value, text: String(value) };
238
+ }
239
+ function sourceText(snap: SourceSnap): string {
240
+ if (typeof snap.ref === "string") return snap.ref;
241
+ if (snap.ref == null) return "";
242
+ return snap.text ?? "";
243
+ }
244
+ function sameSource(value: unknown, snap: SourceSnap): boolean {
245
+ if (typeof value === "string" || value == null) return value === snap.ref;
246
+ return String(value) === snap.text;
247
+ }
248
+ function collectRunIds(text: string, seen: Set<string>, into: string[]) {
249
+ if (text.length < 36) return;
250
+ RUN_ID_PATTERN.lastIndex = 0;
251
+ let match: RegExpExecArray | null;
252
+ while ((match = RUN_ID_PATTERN.exec(text))) {
253
+ if (seen.has(match[1])) continue;
254
+ seen.add(match[1]);
255
+ into.push(match[1]);
256
+ }
257
+ RUN_ID_PATTERN.lastIndex = 0;
258
+ }
259
+ function firstRunId(text: string): string | null {
260
+ if (text.length < 36) return null;
261
+ RUN_ID_PATTERN.lastIndex = 0;
262
+ const match = RUN_ID_PATTERN.exec(text);
263
+ RUN_ID_PATTERN.lastIndex = 0;
264
+ return match?.[1] ?? null;
265
+ }
266
+ function cachedStringRunId(item: string): string | null {
267
+ if (item.length > STRING_RUN_CACHE_MAX_LENGTH) return firstRunId(item);
268
+ const cached = stringRunCache.get(item);
269
+ if (cached !== undefined) {
270
+ stringRunCache.delete(item);
271
+ stringRunCache.set(item, cached);
272
+ return cached;
273
+ }
274
+ const found = firstRunId(item);
275
+ stringRunCache.set(item, found);
276
+ if (stringRunCache.size > STRING_RUN_CACHE_LIMIT) {
277
+ const oldest = stringRunCache.keys().next().value;
278
+ if (oldest !== undefined) stringRunCache.delete(oldest);
279
+ }
280
+ return found;
281
+ }
282
+ function callSnap(item: object): CallSnap {
283
+ const call = item as Record<string, unknown>;
284
+ const cached = callSnaps.get(item);
285
+ if (cached && sameSource(call.id, cached.id) && sameSource(call.output, cached.output)
286
+ && sameSource(call.task, cached.task) && sameSource(call.action, cached.action)) return cached;
287
+ const output = sourceSnap(call.output);
288
+ const task = sourceSnap(call.task);
289
+ const action = sourceSnap(call.action);
290
+ const runIds: string[] = [];
291
+ const seen = new Set<string>();
292
+ collectRunIds(sourceText(output), seen, runIds);
293
+ collectRunIds(sourceText(task), seen, runIds);
294
+ collectRunIds(sourceText(action), seen, runIds);
295
+ const next: CallSnap = {
296
+ id: sourceSnap(call.id), output, task, action,
297
+ callId: typeof call.id === "string" ? call.id : undefined, runIds,
298
+ };
299
+ callSnaps.set(item, next);
300
+ return next;
301
+ }
302
+ type CallKeys = { callIds: Set<string>; runIds: Set<string> };
303
+ function collectCallKeys(items: unknown[]): CallKeys {
119
304
  const callIds = new Set<string>();
120
305
  const runIds = new Set<string>();
121
- for (const item of callsOrIds) {
306
+ for (const item of items) {
122
307
  if (typeof item === "string") {
123
308
  callIds.add(item);
124
- const match = item.match(/\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/i);
125
- if (match) runIds.add(match[1]);
309
+ const runId = cachedStringRunId(item);
310
+ if (runId) runIds.add(runId);
126
311
  } else if (item && typeof item === "object") {
127
- const call = item as Record<string, unknown>;
128
- if (typeof call.id === "string") callIds.add(call.id);
129
- const text = `${call.output ?? ""} ${call.task ?? ""} ${call.action ?? ""}`;
130
- const matches = text.matchAll(/\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/gi);
131
- for (const m of matches) runIds.add(m[1]);
312
+ const snap = callSnap(item);
313
+ if (snap.callId) callIds.add(snap.callId);
314
+ for (const runId of snap.runIds) runIds.add(runId);
132
315
  }
133
316
  }
134
- const selected = new Set<string>();
135
- for (const status of statuses) {
136
- const runId = String(status.runId ?? "");
317
+ return { callIds, runIds };
318
+ }
319
+
320
+ type StatusHit = { status: Record<string, unknown>; index: number };
321
+ type StatusIndex = { byRun: Map<string, StatusHit[]>; byTool: Map<string, string[]>; children: Map<string, string[]> };
322
+ function indexStatuses(statuses: Record<string, unknown>[]): StatusIndex {
323
+ const byRun = new Map<string, StatusHit[]>();
324
+ const byTool = new Map<string, string[]>();
325
+ const children = new Map<string, string[]>();
326
+ for (let index = 0; index < statuses.length; index++) {
327
+ const status = statuses[index];
328
+ const selectKey = String(status.runId);
329
+ const bucket = byRun.get(selectKey);
330
+ if (bucket) bucket.push({ status, index });
331
+ else byRun.set(selectKey, [{ status, index }]);
332
+ const directKey = String(status.runId ?? "");
137
333
  const toolCallId = String(status.toolCallId ?? "");
138
- if ((toolCallId && callIds.has(toolCallId)) || (runId && runIds.has(runId))) {
139
- if (runId) selected.add(runId);
334
+ if (toolCallId && directKey) {
335
+ const tools = byTool.get(toolCallId);
336
+ if (tools) tools.push(directKey);
337
+ else byTool.set(toolCallId, [directKey]);
338
+ }
339
+ const parentId = String(status.parentWorkflowRunId ?? "");
340
+ if (parentId) {
341
+ const kids = children.get(parentId);
342
+ if (kids) kids.push(selectKey);
343
+ else children.set(parentId, [selectKey]);
344
+ }
345
+ }
346
+ return { byRun, byTool, children };
347
+ }
348
+ function selectRunIds(index: StatusIndex, keys: CallKeys): Set<string> {
349
+ const selected = new Set<string>();
350
+ for (const id of keys.callIds) {
351
+ const runs = index.byTool.get(id);
352
+ if (runs) for (const runId of runs) selected.add(runId);
353
+ }
354
+ for (const runId of keys.runIds) if (index.byRun.has(runId)) selected.add(runId);
355
+ if (selected.size === 0) return selected;
356
+ const queue = [...selected];
357
+ for (let i = 0; i < queue.length; i++) {
358
+ const kids = index.children.get(queue[i]);
359
+ if (!kids) continue;
360
+ for (const runId of kids) if (!selected.has(runId)) {
361
+ selected.add(runId);
362
+ queue.push(runId);
140
363
  }
141
364
  }
142
- for (let size = -1; size !== selected.size;) {
143
- size = selected.size;
144
- for (const status of statuses) {
145
- const parentId = String(status.parentWorkflowRunId ?? "");
146
- if (parentId && selected.has(parentId)) selected.add(String(status.runId));
365
+ return selected;
366
+ }
367
+ function takeStatuses(index: StatusIndex, selected: Set<string>, claimed?: Set<string>): Record<string, unknown>[] {
368
+ const hits: StatusHit[] = [];
369
+ for (const runId of selected) {
370
+ const bucket = index.byRun.get(runId);
371
+ if (!bucket) continue;
372
+ for (const hit of bucket) {
373
+ const key = String(hit.status.runId ?? "");
374
+ if (claimed && key && claimed.has(key)) continue;
375
+ hits.push(hit);
147
376
  }
148
377
  }
149
- return statuses.filter(status => selected.has(String(status.runId)));
378
+ if (hits.length > 1) hits.sort((a, b) => a.index - b.index);
379
+ if (claimed) for (const hit of hits) {
380
+ const key = String(hit.status.runId ?? "");
381
+ if (key) claimed.add(key);
382
+ }
383
+ return hits.map(hit => hit.status);
384
+ }
385
+
386
+ export function currentAgentStatuses(statuses: Record<string, unknown>[], callsOrIds: unknown[]): Record<string, unknown>[] {
387
+ if (statuses.length === 0 || callsOrIds.length === 0) return [];
388
+ const index = indexStatuses(statuses);
389
+ return takeStatuses(index, selectRunIds(index, collectCallKeys(callsOrIds)));
150
390
  }
151
391
 
152
392
  /** Associate each status only with the user turn that dispatched its tool call.
@@ -154,22 +394,21 @@ export function currentAgentStatuses(statuses: Record<string, unknown>[], callsO
154
394
  */
155
395
  export function agentStatusesByTurn(statuses: Record<string, unknown>[], turns: Array<{ agentCalls?: unknown[] }>): Map<number, Record<string, unknown>[]> {
156
396
  const assigned = new Map<number, Record<string, unknown>[]>();
397
+ if (statuses.length === 0) {
398
+ for (let index = 0; index < turns.length; index++) assigned.set(index, []);
399
+ return assigned;
400
+ }
401
+ const indexed = indexStatuses(statuses);
157
402
  const claimed = new Set<string>();
158
- for (const [index, turn] of turns.entries()) {
159
- const matched = currentAgentStatuses(statuses, turn.agentCalls ?? []).filter(status => {
160
- const runId = String(status.runId ?? "");
161
- return !runId || !claimed.has(runId);
162
- });
163
- assigned.set(index, matched);
164
- for (const status of matched) {
165
- const runId = String(status.runId ?? "");
166
- if (runId) claimed.add(runId);
167
- }
403
+ for (let index = 0; index < turns.length; index++) {
404
+ const calls = turns[index]?.agentCalls ?? [];
405
+ assigned.set(index, calls.length === 0 ? [] : takeStatuses(indexed, selectRunIds(indexed, collectCallKeys(calls)), claimed));
168
406
  }
169
407
  return assigned;
170
408
  }
171
409
 
172
410
  export function agentChildren(statuses: Record<string, unknown>[]): Record<string, unknown>[] {
411
+ if (statuses.length === 0) return [];
173
412
  const children = new Map<string, Record<string, unknown>>();
174
413
  const visit = (value: unknown, key: string) => {
175
414
  if (!value || typeof value !== "object") return;
package/lib/agent-view.ts CHANGED
@@ -1,6 +1,9 @@
1
1
 
2
2
  /** Public agent view API; persistence and terminal rendering have separate lifecycles. */
3
- export { AGENT_STATUS_ENTRY, stripAcceptanceReport, savedAgentStatuses, retainAgentStatuses, readAgentStatuses, currentAgentStatuses, agentStatusesByTurn, agentChildren } from "./agent-state.ts";
3
+ export { AGENT_STATUS_ENTRY, stripAcceptanceReport, savedAgentStatuses, retainAgentStatuses, readAgentStatuses, currentAgentStatuses, agentStatusesByTurn, agentChildren, childSessionData } from "./agent-state.ts";
4
+ export type { ChildSessionStep, ChildSessionInfo } from "./agent-state.ts";
4
5
  export { RUNNING_FRAMES, runningGlyph, agentCallDisplay, isAgentTool, agentCall, agentCallRows, liveAgentView, liveAgentRows } from "./agent-render.ts";
5
6
  export type { AgentCall, AgentDeadlines } from "./agent-render.ts";
7
+ export { parsePrintInvocations, locatePrintSession, printAgentStatuses, isPrintAgentCall } from "./print-agent.ts";
8
+ export type { PrintInvocation } from "./print-agent.ts";
6
9
  export { restyleAgentWidget, attachAgentWidgets } from "./agent-widgets.ts";
@@ -1,6 +1,7 @@
1
1
  import { diagramMarkdown, renderMinimalMarkdown } from "./minimal-markdown.ts";
2
2
  import { plain } from "./agent-state.ts";
3
3
  import { agentSummary, liveAgentRows, runningGlyph, type AgentDeadlines } from "./agent-render.ts";
4
+ import type { UiLanguage } from "./settings.ts";
4
5
  import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
6
  import { truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
6
7
 
@@ -64,7 +65,7 @@ const isAgentFleetSummary = (lines: string[]) => {
64
65
  };
65
66
 
66
67
  /** Pi 0.85 widget containers: preserve unrelated widgets and their lifecycle. */
67
- export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => boolean, statuses?: () => Record<string, unknown>[], inline = false): () => void {
68
+ export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => boolean, statuses?: () => Record<string, unknown>[], inline = false, language: () => UiLanguage = () => "zh"): () => void {
68
69
  const host = tui as { children?: Array<Component & { children?: Component[] }> };
69
70
  if (host.children?.length !== 7) return () => {};
70
71
  const restores: Array<() => void> = [];
@@ -75,7 +76,8 @@ export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => b
75
76
  const descriptor = Object.getOwnPropertyDescriptor(container, "render");
76
77
  const mouseDescriptor = Object.getOwnPropertyDescriptor(container, "handleMouse");
77
78
  const render = (width: number) => {
78
- const live = !inline && statuses ? liveAgentRows(statuses(), theme, width, expanded(), deadlines) : [];
79
+ const lang = language();
80
+ const live = !inline && statuses ? liveAgentRows(statuses(), theme, width, expanded(), deadlines, lang) : [];
79
81
  let inserted = false;
80
82
  const rows = container.children!.flatMap(child => {
81
83
  const original = child.render(width);
@@ -96,7 +98,8 @@ export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => b
96
98
  const mouse: NonNullable<Component["handleMouse"]> = (event) => {
97
99
  let y = 0;
98
100
  let inserted = false;
99
- const live = !inline && statuses ? liveAgentRows(statuses(), theme, event.width, expanded(), deadlines) : [];
101
+ const lang = language();
102
+ const live = !inline && statuses ? liveAgentRows(statuses(), theme, event.width, expanded(), deadlines, lang) : [];
100
103
 
101
104
  for (const child of container.children!) {
102
105
  const original = child.render(event.width);
@@ -8,8 +8,20 @@ import { commitImageCursor } from "./image-placement.ts";
8
8
  const parser = new Marked();
9
9
  export interface AssistantImageSpan { start: number; end: number; path: string }
10
10
 
11
+ const spansCache = new Map<string, AssistantImageSpan[]>();
12
+ const placeholdersCache = new Map<string, string>();
13
+ const IMAGE_CACHE_MAX = 800;
14
+
15
+ export function clearAssistantImageCaches(): void {
16
+ spansCache.clear();
17
+ placeholdersCache.clear();
18
+ }
19
+
11
20
  /** Parse image syntax before bare paths, retaining source offsets for placement. */
12
21
  export function assistantImageSpans(source: string, cwd: string, allowMissing = false): AssistantImageSpan[] {
22
+ const cacheKey = `${allowMissing ? 1 : 0}|${cwd}|${source}`;
23
+ const cached = spansCache.get(cacheKey);
24
+ if (cached !== undefined) return cached;
13
25
  const spans: AssistantImageSpan[] = [];
14
26
  let cursor = 0;
15
27
  let offset = 0;
@@ -40,20 +52,35 @@ export function assistantImageSpans(source: string, cwd: string, allowMissing =
40
52
  spans.push({ start: match.start, end: match.end, path: localPath(match.path, cwd) });
41
53
  }
42
54
  }
43
- return spans.filter(span => existsSync(span.path) || (allowMissing
55
+ const result = spans.filter(span => existsSync(span.path) || (allowMissing
44
56
  && !/[*?]/.test(span.path)
45
57
  && /^(?:!\[|\/|~\/|\.{1,2}\/|[a-z]:[\\/])/i.test(source.slice(span.start, span.end))))
46
58
  .sort((a, b) => a.start - b.start);
59
+ if (spansCache.size >= IMAGE_CACHE_MAX) {
60
+ const first = spansCache.keys().next().value;
61
+ if (first !== undefined) spansCache.delete(first);
62
+ }
63
+ spansCache.set(cacheKey, result);
64
+ return result;
47
65
  }
48
66
 
49
67
  /** Keep explicit image references compact even after clipboard files have expired. */
50
68
  export function imagePlaceholders(source: string, cwd: string): string {
69
+ const cacheKey = `${cwd}|${source}`;
70
+ const cached = placeholdersCache.get(cacheKey);
71
+ if (cached !== undefined) return cached;
72
+ let out = source;
51
73
  const spans = assistantImageSpans(source, cwd, true);
52
74
  for (let index = spans.length - 1; index >= 0; index--) {
53
75
  const span = spans[index];
54
- source = source.slice(0, span.start) + fileLink(` 图片 ${index + 1}`, span.path, false) + source.slice(span.end);
76
+ out = out.slice(0, span.start) + fileLink(` #${index + 1}`, span.path, false) + out.slice(span.end);
77
+ }
78
+ if (placeholdersCache.size >= IMAGE_CACHE_MAX) {
79
+ const first = placeholdersCache.keys().next().value;
80
+ if (first !== undefined) placeholdersCache.delete(first);
55
81
  }
56
- return source;
82
+ placeholdersCache.set(cacheKey, out);
83
+ return out;
57
84
  }
58
85
 
59
86
  /** Load once outside render, then reuse Pi's Image IDs and complete height rows. */
package/lib/file-links.ts CHANGED
@@ -65,14 +65,24 @@ export function filePaths(text: string) {
65
65
  // BEL survives Markdown's backslash-escape parsing, unlike the ST terminator.
66
66
  export const fileLink = (text: string, path: string, underline = true) => `\x1b]8;;${pathToFileURL(path).href}\x07${underline ? `\x1b[4m${text}\x1b[24m` : text}\x1b]8;;\x07`;
67
67
 
68
+ const linkToolFilesCache = new Map<string, string>();
69
+ const FILE_LINK_CACHE_MAX = 800;
70
+
71
+ export function clearFileLinkCaches(): void {
72
+ linkToolFilesCache.clear();
73
+ }
74
+
68
75
  /** Shorten only visible tool labels; OSC 8 targets retain the complete original path. */
69
76
  export function linkToolFiles(text: string, cwd: string, compact: boolean): string {
77
+ const hyperlinks = inputCapabilities().hyperlinks;
78
+ const cacheKey = `${compact ? 1 : 0}|${hyperlinks ? 1 : 0}|${cwd}|${text}`;
79
+ const cached = linkToolFilesCache.get(cacheKey);
80
+ if (cached !== undefined) return cached;
70
81
  const shorten = (label: string) => compact ? label
71
82
  .replace(/\/var\/folders\/[^\s]*\/otty-paste\//g, "…/otty-paste/")
72
83
  .replace(/node_modules\/@earendil-works\//g, "…/") : label;
73
- const hyperlinks = inputCapabilities().hyperlinks;
74
84
  // Image chips already carry a complete target; never shorten or relink it.
75
- return text.split(/(\x1b\]8;[^\x07]*\x07[\s\S]*?\x1b\]8;;\x07)/g).map((part, index) => {
85
+ const out = text.split(/(\x1b\]8;[^\x07]*\x07[\s\S]*?\x1b\]8;;\x07)/g).map((part, index) => {
76
86
  if (index % 2) return part;
77
87
  if (!hyperlinks) return shorten(part);
78
88
  // A path tool's entire argument can contain spaces or punctuation without quotes.
@@ -89,6 +99,12 @@ export function linkToolFiles(text: string, cwd: string, compact: boolean): stri
89
99
  }
90
100
  return result + shorten(part.slice(offset));
91
101
  }).join("");
102
+ if (linkToolFilesCache.size >= FILE_LINK_CACHE_MAX) {
103
+ const first = linkToolFilesCache.keys().next().value;
104
+ if (first !== undefined) linkToolFilesCache.delete(first);
105
+ }
106
+ linkToolFilesCache.set(cacheKey, out);
107
+ return out;
92
108
  }
93
109
 
94
110
  /** Display-only: normalize local targets without changing persisted messages or remote URLs. */
@@ -2,6 +2,7 @@ import type { spawn } from "node:child_process";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import type { EditorComponent, OverlayHandle, OverlayOptions, renderImage, TUI } from "@earendil-works/pi-tui";
4
4
  import type { Preview } from "./input-image-paths.ts";
5
+ import type { UiLanguage } from "./settings.ts";
5
6
 
6
7
  export interface PreviewState {
7
8
  path?: string;
@@ -38,6 +39,7 @@ export interface Enhancements {
38
39
  hoverLink?: { row: number; start: number; end: number; path: string };
39
40
  previewOptions?: OverlayOptions;
40
41
  previewMode: () => "hover" | "inline";
42
+ language?: () => UiLanguage;
41
43
  inlineImages: Map<string, Preview | undefined>;
42
44
  inlinePending: Map<string, Promise<Preview | undefined>>;
43
45
  inlineGraphics: Map<string, { layout: string } & NonNullable<ReturnType<typeof renderImage>>>;
@@ -18,6 +18,7 @@ import { installEditor, liveUI } from "./input-editor.ts";
18
18
  import { handleTerminalInput, requestPreview, setPointer } from "./input-hover-preview.ts";
19
19
  import { clearInlineGraphics, syncInlineImages } from "./input-inline-images.ts";
20
20
  import { createSkillAutocompleteProvider, handleInput, readSkillCommands } from "./input-skill-completion.ts";
21
+ import type { UiLanguage } from "./settings.ts";
21
22
 
22
23
  export { MAX_PREVIEW_BYTES, imagePathsInLine, imagePathAtCursor, imageDirectoryUrl, readPreview } from "./input-image-paths.ts";
23
24
  export type { ImagePathMatch, PreviewImage, PreviewNote, Preview } from "./input-image-paths.ts";
@@ -31,12 +32,13 @@ export const INPUT_ENHANCEMENTS_SETTING = "pi-mini-mode-input-enhancements";
31
32
 
32
33
  let installed: Enhancements | undefined;
33
34
 
34
- export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean), previewMode: () => "hover" | "inline" = () => "hover"): InputEnhancementsCleanup {
35
+ export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean), previewMode: () => "hover" | "inline" = () => "hover", language: () => UiLanguage = () => "zh"): InputEnhancementsCleanup {
35
36
  const enabled = typeof isEnabled === "function" ? isEnabled : () => isEnabled;
36
37
  if (installed && installed.pi !== pi) installed.cleanup();
37
38
  const state = installed?.pi === pi ? installed : (installed = createEnhancements(pi));
38
39
  state.enabled = enabled;
39
40
  state.previewMode = previewMode;
41
+ state.language = language;
40
42
  state.ctx = ctx;
41
43
  state.cwd = ctx.cwd;
42
44
  state.theme = ctx.hasUI ? ctx.ui.theme : undefined;
@@ -85,10 +85,11 @@ export async function requestPreview(state: Enhancements, path: string | undefin
85
85
  return;
86
86
  }
87
87
  const cells = getCellDimensions();
88
+ const lang = state.language?.() ?? "zh";
88
89
  const preview = await readPreview(path, state.cwd ?? process.cwd(), {
89
90
  widthPx: Math.max(1, (state.tui?.terminal.columns ?? 80) - 2) * cells.widthPx,
90
91
  heightPx: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2) * cells.heightPx,
91
- });
92
+ }, lang);
92
93
  if (token !== state.previewToken || !state.enabled()) return;
93
94
  setPreview(state, preview);
94
95
  }
@@ -107,9 +108,10 @@ function setPreview(state: Enhancements, preview: Preview | undefined): void {
107
108
  maxHeightCells: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2),
108
109
  imageId: allocateImageId(), moveCursor: false,
109
110
  }) ?? undefined : undefined;
111
+ const lang = state.language?.() ?? "zh";
110
112
  state.preview = {
111
113
  path: preview?.path, graphic,
112
- note: preview?.kind === "note" ? preview.note : graphic ? undefined : "终端未能生成图片预览",
114
+ note: preview?.kind === "note" ? preview.note : graphic ? undefined : (lang === "en" ? "Terminal cannot render image preview" : "终端未能生成图片预览"),
113
115
  };
114
116
  if (state.preview.path && !state.overlayReady) showOverlay(state);
115
117
  positionPreview(state);
@@ -123,7 +125,7 @@ function showOverlay(state: Enhancements): void {
123
125
  state.previewHandle = state.tui.showOverlay({
124
126
  render: width => {
125
127
  if (state.previewLayout !== imageLayoutKey()) setPreview(state, state.previewSource);
126
- return previewLines(state.preview, state.theme!, width);
128
+ return previewLines(state.preview, state.theme!, width, state.language?.() ?? "zh");
127
129
  },
128
130
  invalidate: () => {},
129
131
  }, state.previewOptions);
@@ -133,7 +135,7 @@ export function positionPreview(state: Enhancements): void {
133
135
  if (!state.previewOptions || !state.tui || !state.theme) return;
134
136
  const { rows, columns } = state.tui.terminal;
135
137
  const width = Math.max(3, Math.min((state.preview.graphic?.columns ?? 26) + 2, columns || 80));
136
- const height = Math.min(rows, previewLines(state.preview, state.theme, width).length);
138
+ const height = Math.min(rows, previewLines(state.preview, state.theme, width, state.language?.() ?? "zh").length);
137
139
  const { x, y } = state.previewAnchor ?? { x: 0, y: rows - 2 };
138
140
  const previewRow = y + 1 + height <= rows ? y + 1 : Math.max(0, y - height);
139
141
  // Keep hover previews out of the draft attachment band. If there is no safe