@each1024/pi-mini-mode 1.3.1

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.
@@ -0,0 +1,1027 @@
1
+ import { agentCall, attachAgentWidgets, type AgentCall } from "../lib/agent-view.ts";
2
+ import { CONFIG_DIR_NAME, getSettingsListTheme, getMarkdownTheme, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { attachTranscript, type TurnNotices } from "../lib/transcript-adapter.ts";
4
+ import { diagramMarkdown } from "../lib/minimal-markdown.ts";
5
+ import { minimalSurface } from "../lib/minimal-theme.ts";
6
+ import { Container, Markdown, matchesKey, isKeyRelease, isKeyRepeat, type SettingItem, SettingsList, Text, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { dirname, join } from "node:path";
10
+
11
+ export const SETTINGS_FILE_NAME = "mini-lens.json";
12
+
13
+ export interface MiniLensSettings {
14
+ "mini-lens-model-show": boolean;
15
+ "mini-lens-thinking-show": boolean;
16
+ "mini-lens-ch-show": boolean;
17
+ "mini-lens-session-tokens-show": boolean;
18
+ "mini-lens-cache-tokens-show": boolean;
19
+ "mini-lens-cost-show": boolean;
20
+ "mini-lens-mcp-show": boolean;
21
+ "mini-lens-context-show": boolean;
22
+ "mini-lens-context-dots-show": boolean;
23
+ "mini-lens-context-percent-show": boolean;
24
+ "mini-lens-speed-show": boolean;
25
+ "mini-lens-speed-unit-show": boolean;
26
+ "mini-lens-minimal-show": boolean;
27
+ "mini-lens-minimal-thinking-show": boolean;
28
+ "mini-lens-minimal-tools-show": boolean;
29
+ "mini-lens-minimal-output-show": boolean;
30
+ "mini-lens-minimal-skills-show": boolean;
31
+ "mini-lens-agent-usage-show": boolean;
32
+ "mini-lens-agent-shortcut-show": boolean;
33
+ onboardingCompleted: boolean;
34
+ }
35
+
36
+ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
37
+ "mini-lens-model-show": true,
38
+ "mini-lens-thinking-show": true,
39
+ "mini-lens-ch-show": true,
40
+ "mini-lens-session-tokens-show": true,
41
+ "mini-lens-cache-tokens-show": true,
42
+ "mini-lens-cost-show": true,
43
+ "mini-lens-mcp-show": false,
44
+ "mini-lens-context-show": true,
45
+ "mini-lens-context-dots-show": false,
46
+ "mini-lens-context-percent-show": true,
47
+ "mini-lens-speed-show": true,
48
+ "mini-lens-speed-unit-show": true,
49
+ "mini-lens-minimal-show": true,
50
+ "mini-lens-minimal-thinking-show": true,
51
+ "mini-lens-minimal-tools-show": true,
52
+ "mini-lens-minimal-output-show": true,
53
+ "mini-lens-minimal-skills-show": true,
54
+ "mini-lens-agent-usage-show": true,
55
+ "mini-lens-agent-shortcut-show": true,
56
+ onboardingCompleted: false,
57
+ };
58
+
59
+ const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<keyof MiniLensSettings>;
60
+
61
+ export function settingsPath(agentDir = process.env.MINI_LENS_AGENT_DIR ?? join(homedir(), CONFIG_DIR_NAME, "agent")): string {
62
+ return join(agentDir, SETTINGS_FILE_NAME);
63
+ }
64
+
65
+ function isBoolean(value: unknown): value is boolean {
66
+ return typeof value === "boolean";
67
+ }
68
+
69
+ export function parseSettings(value: unknown): MiniLensSettings {
70
+ const candidate = value && typeof value === "object" ? value as Record<string, unknown> : {};
71
+ return Object.fromEntries(SETTING_IDS.map((id) => [id, isBoolean(candidate[id]) ? candidate[id] : DEFAULT_SETTINGS[id]])) as unknown as MiniLensSettings;
72
+ }
73
+
74
+ export async function loadSettings(path = settingsPath()): Promise<{ settings: MiniLensSettings; exists: boolean }> {
75
+ try {
76
+ return { settings: parseSettings(JSON.parse(await readFile(path, "utf8"))), exists: true };
77
+ } catch {
78
+ return { settings: { ...DEFAULT_SETTINGS }, exists: false };
79
+ }
80
+ }
81
+
82
+ export async function saveSettings(settings: MiniLensSettings, path = settingsPath()): Promise<void> {
83
+ await mkdir(dirname(path), { recursive: true });
84
+ const temporaryPath = `${path}.tmp`;
85
+ await writeFile(temporaryPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
86
+ await rename(temporaryPath, path);
87
+ }
88
+
89
+ function enabledMcpServerCount(value: unknown): number | undefined {
90
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
91
+ const snapshot = value as { version?: unknown; servers?: unknown };
92
+ if (snapshot.version !== 1 || !Array.isArray(snapshot.servers)) return undefined;
93
+ let count = 0;
94
+ for (const server of snapshot.servers) {
95
+ if (!server || typeof server !== "object" || Array.isArray(server)
96
+ || typeof server.name !== "string"
97
+ || (server.disabled !== undefined && typeof server.disabled !== "boolean")) return undefined;
98
+ if (server.disabled !== true) count++;
99
+ }
100
+ return count;
101
+ }
102
+
103
+ function formatTokens(value: number): string {
104
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
105
+ if (value >= 1_000) return `${Math.round(value / 1_000)}K`;
106
+ return String(Math.round(value));
107
+ }
108
+
109
+ function finiteNumber(value: unknown): number | undefined {
110
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
111
+ }
112
+
113
+ function nonNegative(value: unknown): number {
114
+ return Math.max(0, finiteNumber(value) ?? 0);
115
+ }
116
+
117
+ function formatUsd(value: number): string {
118
+ if (value < 0.01) return `$${value.toFixed(4)}`;
119
+ if (value < 1) return `$${value.toFixed(3)}`;
120
+ return `$${value.toFixed(2)}`;
121
+ }
122
+
123
+ interface UsageLike {
124
+ input?: unknown;
125
+ output?: unknown;
126
+ cacheRead?: unknown;
127
+ cacheWrite?: unknown;
128
+ totalTokens?: unknown;
129
+ cost?: { total?: unknown };
130
+ }
131
+
132
+ export interface SessionUsage {
133
+ totalTokens: number;
134
+ input: number;
135
+ output: number;
136
+ cacheRead: number;
137
+ cacheWrite: number;
138
+ cost: number;
139
+ }
140
+
141
+ const EMPTY_USAGE: SessionUsage = { totalTokens: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
142
+
143
+ function addUsage(total: SessionUsage, usage: UsageLike | undefined): SessionUsage {
144
+ if (!usage) return total;
145
+ const input = nonNegative(usage.input);
146
+ const output = nonNegative(usage.output);
147
+ const cacheRead = nonNegative(usage.cacheRead);
148
+ const cacheWrite = nonNegative(usage.cacheWrite);
149
+ // totalTokens is the provider's authoritative count. Older/custom tool results
150
+ // sometimes omit it, so only then derive a complete count from its components.
151
+ const reportedTotal = finiteNumber(usage.totalTokens);
152
+ return {
153
+ totalTokens: total.totalTokens + Math.max(0, reportedTotal ?? input + output + cacheRead + cacheWrite),
154
+ input: total.input + input,
155
+ output: total.output + output,
156
+ cacheRead: total.cacheRead + cacheRead,
157
+ cacheWrite: total.cacheWrite + cacheWrite,
158
+ cost: total.cost + nonNegative(usage.cost?.total),
159
+ };
160
+ }
161
+
162
+ /** Aggregate persisted, finalized usage once per active-branch entry. */
163
+ export function sessionUsage(ctx: ExtensionContext): SessionUsage {
164
+ return ctx.sessionManager.getBranch().reduce((total, entry) => {
165
+ if (entry.type !== "message") return total;
166
+ const message = entry.message as { role?: unknown; usage?: UsageLike };
167
+ return message.role === "assistant" || message.role === "toolResult"
168
+ ? addUsage(total, message.usage)
169
+ : total;
170
+ }, { ...EMPTY_USAGE });
171
+ }
172
+
173
+ function cacheHit(usage: SessionUsage): number | undefined {
174
+ const cacheBase = usage.input + usage.cacheRead;
175
+ return cacheBase === 0 ? undefined : 100 * usage.cacheRead / cacheBase;
176
+ }
177
+
178
+ export type SpeedColor = "success" | "warning" | "error" | "muted";
179
+
180
+ export function speedColor(speed: number | undefined): SpeedColor {
181
+ if (speed === undefined) return "muted";
182
+ if (speed >= 30) return "success";
183
+ if (speed >= 10) return "warning";
184
+ return "error";
185
+ }
186
+
187
+ export function formatSpeed(speed: number, showUnit: boolean): string {
188
+ const value = speed.toFixed(speed >= 100 ? 0 : 1);
189
+ return showUnit ? `${value} tok/s` : value;
190
+ }
191
+
192
+ function renderRight(
193
+ theme: ExtensionContext["ui"]["theme"],
194
+ settings: MiniLensSettings,
195
+ percentText: string,
196
+ speed: number | undefined,
197
+ highlighted?: keyof MiniLensSettings,
198
+ ): string {
199
+ const fields: string[] = [];
200
+ if (settings["mini-lens-context-percent-show"] && percentText) fields.push(highlighted === "mini-lens-context-percent-show" ? theme.bg("selectedBg", theme.fg("accent", theme.bold(percentText))) : theme.fg("accent", percentText));
201
+ if (settings["mini-lens-speed-show"] && speed !== undefined) {
202
+ const text = formatSpeed(speed, settings["mini-lens-speed-unit-show"]);
203
+ fields.push(highlighted === "mini-lens-speed-show" || highlighted === "mini-lens-speed-unit-show"
204
+ ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text)))
205
+ : theme.fg(speedColor(speed), text));
206
+ }
207
+ return fields.join(" ");
208
+ }
209
+
210
+ const SETTINGS_PREVIEW_CONTEXT = {
211
+ model: { id: "deepseek-v4-flash" },
212
+ thinkingLevel: "high",
213
+ getContextUsage: () => ({ tokens: 500, contextWindow: 1_000_000, percent: 1 }),
214
+ } as unknown as ExtensionContext;
215
+
216
+ const SETTINGS_PREVIEW_USAGE: SessionUsage = {
217
+ totalTokens: 45_000,
218
+ input: 15_000,
219
+ output: 5_000,
220
+ cacheRead: 10_000,
221
+ cacheWrite: 15_000,
222
+ cost: 0.012,
223
+ };
224
+
225
+ export function settingsPreviewLine(
226
+ theme: ExtensionContext["ui"]["theme"],
227
+ settings: MiniLensSettings,
228
+ width = 140,
229
+ highlighted?: keyof MiniLensSettings,
230
+ ): string {
231
+ return statusLine(SETTINGS_PREVIEW_CONTEXT, theme, width, SETTINGS_PREVIEW_USAGE, settings, 120, highlighted, 3);
232
+ }
233
+
234
+ export function statusLine(
235
+ ctx: ExtensionContext,
236
+ theme: ExtensionContext["ui"]["theme"],
237
+ width: number,
238
+ usageTotals: SessionUsage,
239
+ settings: MiniLensSettings,
240
+ speed: number | undefined,
241
+ highlighted?: keyof MiniLensSettings,
242
+ mcpCount?: number,
243
+ ): string {
244
+ if (highlighted === "mini-lens-context-dots-show") highlighted = "mini-lens-context-show";
245
+ const field = (id: keyof MiniLensSettings, color: Parameters<typeof theme.fg>[0], text: string) =>
246
+ id === highlighted ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text))) : theme.fg(color, text);
247
+ if (width <= 0) return "";
248
+ const model = ctx.model?.id ?? "";
249
+ const thinking = ctx.thinkingLevel ?? "";
250
+ const hit = cacheHit(usageTotals);
251
+ const hitText = hit === undefined ? "" : `CH ${hit.toFixed(1)}%`;
252
+ const cachedTokens = usageTotals.cacheRead + usageTotals.cacheWrite;
253
+ const price = usageTotals.cost > 0 ? formatUsd(usageTotals.cost) : "";
254
+ const contextUsage = ctx.getContextUsage();
255
+ const tokens = finiteNumber(contextUsage?.tokens);
256
+ const contextWindow = finiteNumber(contextUsage?.contextWindow);
257
+ const rawPercent = finiteNumber(contextUsage?.percent);
258
+ const percent = rawPercent === undefined ? undefined : Math.max(0, Math.min(100, rawPercent));
259
+ const percentText = percent === undefined ? "" : `${Math.round(percent)}%`;
260
+ const tokenText = tokens === undefined || contextWindow === undefined ? "" : `${formatTokens(Math.max(0, tokens))}/${formatTokens(Math.max(0, contextWindow))}`;
261
+ const showContext = settings["mini-lens-context-show"] && Boolean(tokenText);
262
+ const mcpText = settings["mini-lens-mcp-show"] && mcpCount !== undefined ? `◇ MCP ${mcpCount}` : "";
263
+
264
+ const right = renderRight(theme, settings, percentText, speed, highlighted);
265
+ const rightWidth = visibleWidth(right);
266
+ if (right && width <= rightWidth) {
267
+ const compactRight = settings["mini-lens-speed-show"] && speed !== undefined
268
+ ? theme.fg(speedColor(speed), formatSpeed(speed, settings["mini-lens-speed-unit-show"]))
269
+ : right;
270
+ return truncateToWidth(compactRight, width, "");
271
+ }
272
+
273
+ const leftParts = [
274
+ settings["mini-lens-model-show"] && model && field("mini-lens-model-show", "accent", model),
275
+ settings["mini-lens-thinking-show"] && thinking && field("mini-lens-thinking-show", "muted", thinking),
276
+ settings["mini-lens-session-tokens-show"] && field("mini-lens-session-tokens-show", "text", `Total ${formatTokens(usageTotals.totalTokens)}`),
277
+ settings["mini-lens-cache-tokens-show"] && field("mini-lens-cache-tokens-show", "text", `Cached ${formatTokens(cachedTokens)}`),
278
+ settings["mini-lens-ch-show"] && hitText && field("mini-lens-ch-show", "text", hitText),
279
+ settings["mini-lens-cost-show"] && price && field("mini-lens-cost-show", "muted", price),
280
+ mcpText && field("mini-lens-mcp-show", "muted", mcpText),
281
+ ].filter((part): part is string => Boolean(part));
282
+ const unstyledLeft = [
283
+ settings["mini-lens-model-show"] && model,
284
+ settings["mini-lens-thinking-show"] && thinking,
285
+ settings["mini-lens-session-tokens-show"] && `Total ${formatTokens(usageTotals.totalTokens)}`,
286
+ settings["mini-lens-cache-tokens-show"] && `Cached ${formatTokens(cachedTokens)}`,
287
+ settings["mini-lens-ch-show"] && hitText,
288
+ settings["mini-lens-cost-show"] && price,
289
+ mcpText,
290
+ ].filter(Boolean).join(" ");
291
+ const leftBudget = Math.min(visibleWidth(unstyledLeft), Math.max(1, width - rightWidth - (showContext ? 20 : 1)), Math.max(0, width - rightWidth - 1));
292
+ const left = leftParts.length > 0 ? truncateToWidth(leftParts.join(" "), leftBudget, "…") : "";
293
+ const leftWidth = visibleWidth(left);
294
+ const middleBudget = showContext ? Math.max(0, width - leftWidth - rightWidth - (left && right ? 4 : left || right ? 1 : 0)) : 0;
295
+
296
+ let middle = "";
297
+ if (middleBudget > 0) {
298
+ const visibleToken = truncateToWidth(tokenText, middleBudget, "…");
299
+ const visibleTokenWidth = visibleWidth(visibleToken);
300
+ const barWidth = middleBudget - visibleTokenWidth - 1;
301
+ const filledCell = settings["mini-lens-context-dots-show"] ? "⣿" : "█";
302
+ const emptyCell = settings["mini-lens-context-dots-show"] ? "⣀" : "░";
303
+ const bar = barWidth >= 2 && percent !== undefined
304
+ ? `${field("mini-lens-context-show", "accent", filledCell.repeat(Math.round(barWidth * percent / 100)))}${field("mini-lens-context-show", "borderMuted", emptyCell.repeat(barWidth - Math.round(barWidth * percent / 100)))}`
305
+ : "";
306
+ middle = `${field("mini-lens-context-show", "muted", visibleToken)}${bar ? ` ${bar}` : ""}`;
307
+ }
308
+
309
+ const content = [left, middle].filter(Boolean).join(" ");
310
+ if (!right) return truncateToWidth(content, width, "");
311
+ const gap = " ".repeat(Math.max(1, width - visibleWidth(content) - rightWidth));
312
+ return truncateToWidth(`${content}${content ? gap : ""}${right}`, width, "");
313
+ }
314
+
315
+ function settingsItems(settings: MiniLensSettings): SettingItem[] {
316
+ const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted">, string> = {
317
+ "mini-lens-model-show": "Show model",
318
+ "mini-lens-thinking-show": "Show thinking level",
319
+ "mini-lens-session-tokens-show": "Show total session tokens",
320
+ "mini-lens-cache-tokens-show": "Show session cache tokens",
321
+ "mini-lens-ch-show": "Show cache hit rate (CH)",
322
+ "mini-lens-cost-show": "Show session price",
323
+ "mini-lens-mcp-show": "Show enabled MCP servers",
324
+ "mini-lens-context-show": "Show context tokens and progress bar",
325
+ "mini-lens-context-dots-show": "↳ Use dot-matrix progress bar",
326
+ "mini-lens-context-percent-show": "Show context percentage",
327
+ "mini-lens-speed-show": "Show latest generation speed",
328
+ "mini-lens-speed-unit-show": "↳ Show tok/s unit",
329
+ "mini-lens-minimal-show": "启用极简模式",
330
+ "mini-lens-minimal-thinking-show": "显示思考",
331
+ "mini-lens-minimal-tools-show": "显示工具调用",
332
+ "mini-lens-minimal-output-show": "显示执行输出",
333
+ "mini-lens-minimal-skills-show": "显示 skill",
334
+ "mini-lens-agent-usage-show": "显示 Agent Token 用量",
335
+ "mini-lens-agent-shortcut-show": "新 Agent 显示 Ctrl+O 提示(6 秒)",
336
+ };
337
+ return (Object.keys(labels) as Array<Exclude<keyof MiniLensSettings, "onboardingCompleted">>).map((id) => ({
338
+ id,
339
+ label: labels[id],
340
+ description: id === "mini-lens-session-tokens-show"
341
+ ? "Total: all tokens used on the current session branch, including tool-reported LLM usage."
342
+ : id === "mini-lens-cache-tokens-show"
343
+ ? "Cached: cumulative cache-read + cache-write tokens (part of Total)."
344
+ : id === "mini-lens-ch-show"
345
+ ? "CH (cache hit): cache-read / (input + cache-read). Cache writes are not included in this rate."
346
+ : undefined,
347
+ currentValue: settings[id] ? "on" : "off",
348
+ values: ["on", "off"],
349
+ }));
350
+ }
351
+
352
+ interface ActiveGeneration {
353
+ startedAt: number;
354
+ output: number;
355
+ lastSampleAt: number;
356
+ }
357
+
358
+ function outputSpeed(output: unknown, startedAt: number, endedAt = Date.now()): number | undefined {
359
+ const tokenCount = finiteNumber(output);
360
+ const elapsedMs = endedAt - startedAt;
361
+ if (tokenCount === undefined || tokenCount <= 0 || elapsedMs <= 0) return undefined;
362
+ return tokenCount / (elapsedMs / 1_000);
363
+ }
364
+
365
+ export interface MinimalTurn {
366
+ question: string;
367
+ shortcutHintUntil?: number;
368
+ usage?: SessionUsage;
369
+ pendingUsage?: UsageLike;
370
+ agentCalls?: AgentCall[];
371
+ process: string[];
372
+ final?: string;
373
+ running?: boolean;
374
+ waitingTools?: Array<{ id: string; name: string; startedAt: number }>;
375
+ }
376
+
377
+ const PROCESS_PREVIEW_LIMIT = 180;
378
+
379
+ function contentText(content: unknown): string {
380
+ if (typeof content === "string") return content.trim();
381
+ if (content && typeof content === "object" && "content" in content) return contentText(content.content);
382
+ if (!Array.isArray(content)) return "";
383
+ return content
384
+ .filter((item): item is { type?: string; text?: string } => Boolean(item && typeof item === "object"))
385
+ .filter((item) => item.type === "text" && typeof item.text === "string")
386
+ .map((item) => item.text!.trim())
387
+ .filter(Boolean)
388
+ .join("\n");
389
+ }
390
+
391
+ function preview(value: unknown): string {
392
+ let raw = contentText(value);
393
+ if (!raw && value !== undefined) {
394
+ try { raw = JSON.stringify(value) ?? ""; } catch { raw = String(value); }
395
+ }
396
+ const text = raw.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "").replace(/\s+/g, " ").trim();
397
+ return text.length > PROCESS_PREVIEW_LIMIT ? `${text.slice(0, PROCESS_PREVIEW_LIMIT - 1)}…` : text;
398
+ }
399
+
400
+ function processText(value: unknown): string {
401
+ return contentText(value) || (value === undefined ? "" : JSON.stringify(value) ?? "");
402
+ }
403
+
404
+ function pushProcess(turn: MinimalTurn | undefined, kind: string, value: unknown): void {
405
+ if (!turn) return;
406
+ const text = processText(value);
407
+ const line = text ? `${kind} ${text}` : kind;
408
+ if (turn.process.at(-1) !== line) turn.process.push(line);
409
+ }
410
+
411
+ function skillNames(text: string): string[] {
412
+ const names = new Set<string>();
413
+ for (const match of text.matchAll(/\/skill:([\w.-]+)/g)) names.add(match[1]);
414
+ for (const match of text.matchAll(/<skill[^>]*?(?:name=["']([^"']+)["']|>\s*<name>([^<]+))/gi)) names.add((match[1] ?? match[2]).trim());
415
+ return [...names];
416
+ }
417
+
418
+ /** Rebuild turns on the selected session branch. */
419
+ export function minimalTurnsFromBranch(branch: readonly unknown[]): MinimalTurn[] {
420
+ const turns: MinimalTurn[] = [];
421
+ let turn: MinimalTurn | undefined;
422
+ for (const rawEntry of branch) {
423
+ const entry = rawEntry as { type?: string; message?: { role?: string; content?: unknown; usage?: UsageLike; stopReason?: string; errorMessage?: string } } | null;
424
+ if (entry?.type !== "message" || !entry.message) continue;
425
+ const { role, content } = entry.message;
426
+ if (role === "user") {
427
+ const question = contentText(content);
428
+ turn = { question: question || "[附件]", process: [], running: false };
429
+ for (const name of skillNames(question)) pushProcess(turn, "skill", name);
430
+ turns.push(turn);
431
+ continue;
432
+ }
433
+ if (!turn) continue;
434
+ if (role === "assistant" || role === "toolResult") turn.usage = addUsage(turn.usage ?? EMPTY_USAGE, entry.message.usage);
435
+ if (role === "toolResult") {
436
+ const result = entry.message as { toolCallId?: string; isError?: boolean };
437
+ const call = turn.agentCalls?.find(call => call.id === result.toolCallId);
438
+ if (call) {
439
+ call.state = result.isError ? "error" : "done";
440
+ call.output = contentText(content) || "调用已返回(无文本输出)";
441
+ continue;
442
+ }
443
+ pushProcess(turn, "output", content);
444
+ continue;
445
+ }
446
+ if (role !== "assistant" || !Array.isArray(content)) continue;
447
+ for (const item of content as Array<Record<string, unknown>>) {
448
+ if (!item || typeof item !== "object") continue;
449
+ if (item.type === "thinking") pushProcess(turn, "thinking", item.thinking ?? item.text);
450
+ else if (item.type === "toolCall") {
451
+ if (item.name) {
452
+ (turn.agentCalls ??= []).push(agentCall(String(item.id), String(item.name), item.arguments ?? item.input));
453
+ pushProcess(turn, "call", String(item.id));
454
+ const path = (item.arguments as { path?: string })?.path;
455
+ if (path && /(?:^|\/)SKILL\.md$/i.test(path)) pushProcess(turn, "skill", path.split("/").at(-2));
456
+ continue;
457
+ }
458
+ pushProcess(turn, `tool ${String(item.name ?? "")}`.trim(), item.arguments ?? item.input);
459
+ const path = (item.arguments as { path?: unknown })?.path;
460
+ if (typeof path === "string" && /(?:^|\/)SKILL\.md$/i.test(path)) pushProcess(turn, "skill", path.split("/").at(-2) ?? path);
461
+ }
462
+ }
463
+ const text = contentText(content);
464
+ const hasTools = content.some((item) => item?.type === "toolCall");
465
+ if (hasTools) {
466
+ if (text) pushProcess(turn, "output", text);
467
+ turn.final = undefined;
468
+ } else turn.final = text || undefined;
469
+ if (entry.message.stopReason === "error" || entry.message.stopReason === "aborted") {
470
+ turn.final = [entry.message.stopReason === "aborted" ? "执行已中止" : "执行失败", entry.message.errorMessage, turn.final].filter(Boolean).join("\n");
471
+ }
472
+ }
473
+ return turns;
474
+ }
475
+
476
+ function visibleMinimalTurns(settings: MiniLensSettings, turns: MinimalTurn[]): MinimalTurn[] {
477
+ return turns.map((turn) => ({
478
+ ...turn,
479
+ agentCalls: settings["mini-lens-minimal-tools-show"] ? turn.agentCalls : [],
480
+ process: turn.process.filter((line) => {
481
+ if (line.startsWith("thinking ")) return settings["mini-lens-minimal-thinking-show"];
482
+ if (line.startsWith("tool ")) return settings["mini-lens-minimal-tools-show"];
483
+ if (line.startsWith("output ")) return settings["mini-lens-minimal-output-show"];
484
+ if (line.startsWith("skill ")) return settings["mini-lens-minimal-skills-show"];
485
+ return true;
486
+ }),
487
+ }));
488
+ }
489
+
490
+ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showShortcut: (turn: MinimalTurn) => boolean = () => true, showUsage: () => boolean = () => true) {
491
+ const markdown = (text: string, width: number) => new Markdown(text, 0, 0, getMarkdownTheme(),
492
+ { color: (value) => theme.fg("text", value) }, { transform: (source, available) => diagramMarkdown(source, available) }).render(width);
493
+ const surface = (rows: string[], width: number, user: boolean) => {
494
+ const padding = Math.min(2, Math.floor((width - 1) / 2));
495
+ return ["", ...rows, ""].map((row) => {
496
+ const line = truncateToWidth(" ".repeat(padding) + row, width, "");
497
+ return minimalSurface(theme, line + " ".repeat(Math.max(0, width - visibleWidth(line))), user);
498
+ });
499
+ };
500
+ return {
501
+ invalidate() {},
502
+ render(width: number, notices?: TurnNotices): string[] {
503
+ if (width <= 0) return [];
504
+ const inner = Math.max(1, width - 2 * Math.min(2, Math.floor((width - 1) / 2)));
505
+ const lines: string[] = [];
506
+ for (const [index, turn] of getTurns().entries()) {
507
+ if (index > 0) lines.push("");
508
+ lines.push(...surface(markdown(turn.question, inner), width, true));
509
+ const entries = turn.process.flatMap((entry) => {
510
+ if (entry.startsWith("call ")) {
511
+ const call = turn.agentCalls?.find(call => call.id === entry.slice(5));
512
+ return call ? [{ title: `${call.name} ${call.output ?? call.task}`.trim(), detail: [call.task, call.output].filter(Boolean).join("\n\n"), state: call.state, id: call.id, thinking: false }] : [];
513
+ }
514
+ const part = entry.match(/^(tool|output|thinking|skill)(?:\s+|$)([\s\S]*)/);
515
+ const label = ({ tool: "工具", output: "输出", thinking: "思考", skill: "Skill" } as Record<string, string>)[part?.[1] ?? ""] ?? "过程";
516
+ return [{ title: `${label} ${part?.[2] ?? entry}`, detail: part?.[2] ?? entry, state: part?.[1] === "thinking" && turn.running ? "running" : "done", id: "", thinking: part?.[1] === "thinking" }];
517
+ });
518
+ // Older in-memory turns may predate call markers.
519
+ for (const call of turn.agentCalls ?? []) {
520
+ if (!entries.some(entry => entry.id === call.id)) entries.push({ title: `${call.name} ${call.task}`, detail: [call.task, call.output].filter(Boolean).join("\n\n"), state: call.state, id: call.id, thinking: false });
521
+ }
522
+ if (entries.length || turn.running || turn.usage) {
523
+ const expanded = isExpanded();
524
+ const shown = expanded ? entries : entries.slice(-6);
525
+ const done = entries.filter(entry => entry.state === "done").length;
526
+ const header = theme.bold(theme.fg("accent", "Agent")) + theme.fg("muted", ` · ${done}/${entries.length}${showShortcut(turn) ? " · Ctrl+O" : ""}`);
527
+ const usage = addUsage(turn.usage ?? EMPTY_USAGE, turn.pendingUsage);
528
+ const totals = theme.fg("accent", "S") + theme.fg("muted", ` ${formatTokens(usage.totalTokens)} / `)
529
+ + theme.fg("accent", "C") + theme.fg("muted", ` ${formatTokens(usage.cacheRead)}`);
530
+ const totalsWidth = visibleWidth(totals);
531
+ if (showUsage() && width >= totalsWidth + visibleWidth("Agent") + 1) {
532
+ const left = truncateToWidth(header, width - totalsWidth - 1, "");
533
+ lines.push("", left + " ".repeat(width - visibleWidth(left) - totalsWidth) + totals);
534
+ } else {
535
+ lines.push("", truncateToWidth(header, width));
536
+ }
537
+ if (!shown.length) lines.push(truncateToWidth(theme.fg("accent", "└─ ●") + theme.fg("muted", " 思考中…"), width));
538
+ shown.forEach((entry, row) => {
539
+ const waiting = turn.waitingTools?.find(tool => tool.id === entry.id);
540
+ const title = waiting ? `正在执行 ${waiting.name} · 已等待 ${Math.max(0, Math.floor((Date.now() - waiting.startedAt) / 1000))} 秒` : entry.title;
541
+ const text = title.replace(/\s+/g, " ").trim();
542
+ const summary = entry.thinking
543
+ ? new Markdown(text, 0, 0, getMarkdownTheme(), { color: value => theme.fg("accent", value) })
544
+ .render(Math.max(1, visibleWidth(text) + 1)).join(" ").replace(/\s+/g, " ").trim()
545
+ : theme.fg("accent", text);
546
+ const color = entry.state === "error" ? "error" : "accent";
547
+ const glyph = entry.state === "error" ? "✗" : entry.state === "running" ? "●" : "✓";
548
+ lines.push(truncateToWidth(theme.fg("accent", row === shown.length - 1 ? "└─ " : "├─ ") + theme.fg(color, glyph) + " " + summary, width));
549
+ if (expanded && entry.detail) {
550
+ const rail = row === shown.length - 1 ? " " : theme.fg("accent", "│ ");
551
+ lines.push(...markdown(entry.detail, Math.max(1, width - 3)).map(line => truncateToWidth(`${rail}${line}`, width, "")));
552
+ }
553
+ });
554
+ }
555
+ if (turn.final) lines.push("", ...markdown(turn.final, width));
556
+ lines.push(...(notices?.get(index) ?? []));
557
+ }
558
+ return lines;
559
+ },
560
+ };
561
+ }
562
+
563
+ export default function (pi: ExtensionAPI) {
564
+ let refreshFooter: (() => void) | undefined;
565
+ let refreshMinimal: (() => void) | undefined;
566
+ let processExpanded = false;
567
+ let subAgentsExpanded = false;
568
+ let shortcutTimer: ReturnType<typeof setTimeout> | undefined;
569
+ let waitingTimer: ReturnType<typeof setInterval> | undefined;
570
+ let unsubscribeMinimalInput: (() => void) | undefined;
571
+ let restoreAgentWidgets: (() => void) | undefined;
572
+ let restoreTranscript: (() => void) | undefined;
573
+ let minimalTurns: MinimalTurn[] = [];
574
+ let activeMinimalTurn: MinimalTurn | undefined;
575
+ let pendingMinimalFinal = "";
576
+ const minimalMessageIndices = new Map<number, number>();
577
+ let speed: number | undefined;
578
+ let mcpCount: number | undefined;
579
+ let activeGeneration: ActiveGeneration | undefined;
580
+ const toolStarts = new Map<string, number>();
581
+ const minimalToolOutputIndices = new Map<string, number>();
582
+ let speedTimer: ReturnType<typeof setInterval> | undefined;
583
+ let settings: MiniLensSettings = { ...DEFAULT_SETTINGS };
584
+ let saveChain: Promise<void> = Promise.resolve();
585
+ const configPath = settingsPath();
586
+
587
+ const refresh = () => refreshFooter?.();
588
+ const refreshMinimalOutput = () => refreshMinimal?.();
589
+ const mountMinimalOutput = (ctx: ExtensionContext) => {
590
+ if (shortcutTimer) clearTimeout(shortcutTimer);
591
+ shortcutTimer = undefined;
592
+ if (waitingTimer) clearInterval(waitingTimer);
593
+ waitingTimer = undefined;
594
+ unsubscribeMinimalInput?.();
595
+ unsubscribeMinimalInput = undefined;
596
+ restoreAgentWidgets?.();
597
+ restoreAgentWidgets = undefined;
598
+ restoreTranscript?.();
599
+ restoreTranscript = undefined;
600
+ if (!settings["mini-lens-minimal-show"] || ctx.mode !== "tui") {
601
+ ctx.ui.setWidget?.("mini-lens-minimal-output", undefined);
602
+ refreshMinimal = undefined;
603
+ return;
604
+ }
605
+ ctx.ui.setWidget("mini-lens-minimal-output", (tui, theme) => {
606
+ refreshMinimal = () => tui.requestRender();
607
+ const view = minimalOutputComponent(theme, () => visibleMinimalTurns(settings, minimalTurns), () => processExpanded, turn => settings["mini-lens-agent-shortcut-show"] && Date.now() < (turn.shortcutHintUntil ?? 0), () => settings["mini-lens-agent-usage-show"]);
608
+ const hintRemaining = (activeMinimalTurn?.shortcutHintUntil ?? 0) - Date.now();
609
+ if (hintRemaining > 0) {
610
+ shortcutTimer = setTimeout(() => tui.requestRender(), hintRemaining);
611
+ shortcutTimer.unref();
612
+ }
613
+ // Native info notifications use dim; warning/error notifications retain
614
+ // their position in the transcript. No plugin names or message matching.
615
+ const dimPrefix = theme.fg("dim", "\u0000").split("\u0000")[0];
616
+ restoreTranscript = attachTranscript(tui, view, {
617
+ isTransient: text => !!dimPrefix && text.startsWith(dimPrefix),
618
+ });
619
+ if (!restoreTranscript) {
620
+ ctx.ui.notify("无法识别 Pi 消息区布局,极简模式未启用;保留原生输出。", "warning");
621
+ }
622
+ if (restoreTranscript) {
623
+ restoreAgentWidgets = attachAgentWidgets(tui, theme, () => subAgentsExpanded);
624
+ waitingTimer = setInterval(() => {
625
+ if (activeMinimalTurn?.running && activeMinimalTurn.waitingTools?.length) tui.requestRender();
626
+ }, 1000);
627
+ waitingTimer.unref();
628
+ unsubscribeMinimalInput = ctx.ui.onTerminalInput?.((data) => {
629
+ const subAgentKey = matchesKey(data, "ctrl+s");
630
+ if (!subAgentKey && !matchesKey(data, "ctrl+o")) return;
631
+ // Input listeners run before Pi filters Kitty release events.
632
+ // Consume release/repeat without toggling the same key twice.
633
+ if (isKeyRelease(data) || isKeyRepeat(data)) return { consume: true };
634
+ if (subAgentKey) subAgentsExpanded = !subAgentsExpanded;
635
+ else processExpanded = !processExpanded;
636
+ tui.requestRender();
637
+ return { consume: true };
638
+ });
639
+ }
640
+ tui.requestRender();
641
+ // Factory acquires the renderer only; never duplicate content in the dock.
642
+ return { render: () => [], invalidate() {} };
643
+ });
644
+ };
645
+ // All factories run before session_start; retain startup broadcasts until the footer mounts.
646
+ const unsubscribeMcpStatus = pi.events.on("pi-mcp-adapter/status/v1", (value: unknown) => {
647
+ const count = enabledMcpServerCount(value);
648
+ if (count === undefined) return;
649
+ mcpCount = count;
650
+ refresh();
651
+ });
652
+ const stopSpeedTimer = () => {
653
+ if (speedTimer) clearInterval(speedTimer);
654
+ speedTimer = undefined;
655
+ };
656
+ const refreshStreamingSpeed = () => {
657
+ if (!activeGeneration) return;
658
+ const nextSpeed = outputSpeed(activeGeneration.output, activeGeneration.startedAt);
659
+ if (nextSpeed !== undefined) speed = nextSpeed;
660
+ refresh();
661
+ };
662
+ const startSpeedTimer = () => {
663
+ stopSpeedTimer();
664
+ speedTimer = setInterval(refreshStreamingSpeed, 250);
665
+ };
666
+ const persistSettings = (ctx: ExtensionContext) => {
667
+ const snapshot = { ...settings };
668
+ saveChain = saveChain
669
+ .catch(() => undefined)
670
+ .then(() => saveSettings(snapshot, configPath))
671
+ .catch(() => ctx.ui.notify("Could not save Mini Lens settings", "error"));
672
+ return saveChain;
673
+ };
674
+ const openSettings = async (ctx: ExtensionContext) => {
675
+ if (ctx.mode !== "tui") {
676
+ ctx.ui.notify("/mini-lens-settings requires TUI mode", "error");
677
+ return;
678
+ }
679
+ await ctx.ui.custom((tui, theme, _keybindings, done) => {
680
+ const container = new Container();
681
+ const preview = new Text(settingsPreviewLine(theme, settings), 1, 1);
682
+ container.addChild(new Text(theme.fg("accent", theme.bold("Mini Lens settings")), 1, 1));
683
+ container.addChild(new Text(theme.fg("muted", "Preview (example data)"), 1, 0));
684
+ container.addChild(preview);
685
+ const items = settingsItems(settings);
686
+ let highlighted: keyof MiniLensSettings | undefined;
687
+ const onChange = (id: string, value: string) => {
688
+ settings = { ...settings, [id]: value === "on", onboardingCompleted: true };
689
+ preview.setText(settingsPreviewLine(theme, settings));
690
+ mountMinimalOutput(ctx);
691
+ void persistSettings(ctx);
692
+ refresh();
693
+ refreshMinimalOutput();
694
+ };
695
+ const settingsTheme = {
696
+ ...getSettingsListTheme(),
697
+ cursor: theme.bg("selectedBg", theme.fg("accent", theme.bold("→ "))),
698
+ label: (text: string, selected: boolean) => {
699
+ if (selected) highlighted = items.find((item) => item.label === text.trimEnd())?.id as keyof MiniLensSettings | undefined;
700
+ return selected ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text))) : theme.fg("text", text);
701
+ },
702
+ value: (text: string, selected: boolean) => selected ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text))) : theme.fg("muted", text),
703
+ };
704
+ const groups: SettingItem[] = [
705
+ { id: "lens", label: "Lens", currentValue: "›", submenu: (_value, back) => new SettingsList(settingsItems(settings).filter((item) => !item.id.includes("-minimal-")), 12, settingsTheme, onChange, () => back(), { enableSearch: true }) },
706
+ { id: "minimal", label: "极简输出", currentValue: "›", submenu: (_value, back) => new SettingsList(settingsItems(settings).filter((item) => item.id.includes("-minimal-")), 8, settingsTheme, onChange, () => back(), { enableSearch: true }) },
707
+ ];
708
+ const settingsList = new SettingsList(
709
+ groups,
710
+ 12,
711
+ settingsTheme,
712
+ onChange,
713
+ () => done(undefined),
714
+ { enableSearch: true },
715
+ );
716
+ container.addChild(settingsList);
717
+ return {
718
+ render: (width: number) => {
719
+ // SettingsList exposes selection through its theme callback, including search and mouse navigation.
720
+ highlighted = undefined;
721
+ settingsList.render(width);
722
+ preview.setText(settingsPreviewLine(theme, settings, Math.max(0, width - 2), highlighted));
723
+ return container.render(width);
724
+ },
725
+ invalidate: () => container.invalidate(),
726
+ handleMouse: (event: TuiMouseEvent) => container.handleMouse(event),
727
+ handleInput: (data: string) => {
728
+ settingsList.handleInput(data);
729
+ tui.requestRender();
730
+ },
731
+ };
732
+ });
733
+ };
734
+
735
+ pi.registerCommand("mini-lens-settings", {
736
+ description: "Configure the Lens and Minimal output groups",
737
+ handler: async (_args, ctx) => openSettings(ctx),
738
+ });
739
+ pi.registerCommand("mini-lens-history", {
740
+ description: "View collapsed process entries for a conversation turn",
741
+ handler: async (_args, ctx) => {
742
+ if (ctx.mode !== "tui" || minimalTurns.length === 0) return;
743
+ const labels = minimalTurns.map((turn, index) => `${index + 1}. ${preview(turn.question)}`);
744
+ const selected = await ctx.ui.select("选择执行过程(不改变折叠视图)", labels);
745
+ const index = selected === undefined ? -1 : labels.indexOf(selected);
746
+ if (index < 0) return;
747
+ const snapshot = [...minimalTurns[index].process];
748
+ await ctx.ui.custom((tui, theme, _keys, done) => {
749
+ let offset = 0;
750
+ return {
751
+ invalidate() {},
752
+ render(width: number) {
753
+ const page = snapshot.slice(offset, offset + 5);
754
+ return [
755
+ truncateToWidth(theme.fg("accent", `执行过程 ${offset + 1}–${Math.min(offset + 5, snapshot.length)} / ${snapshot.length} · ↑↓ 翻阅 · Esc 关闭`), width),
756
+ ...page.flatMap((line) => new Markdown(line, 0, 0, getMarkdownTheme(), undefined, { transform: diagramMarkdown }).render(Math.max(1, width))),
757
+ ];
758
+ },
759
+ handleInput(data: string) {
760
+ if (data === "\u001b" || data === "q") done(undefined);
761
+ else if (data === "\u001b[B" || data === "j") offset = Math.min(Math.max(0, snapshot.length - 5), offset + 1);
762
+ else if (data === "\u001b[A" || data === "k") offset = Math.max(0, offset - 1);
763
+ tui.requestRender();
764
+ },
765
+ };
766
+ });
767
+ },
768
+ });
769
+ pi.registerCommand("mini-lens-minimal", {
770
+ description: "Toggle minimal output (collapsed single-line process per turn)",
771
+ handler: async (args, ctx) => {
772
+ const normalized = args.trim().toLowerCase();
773
+ if (ctx.mode !== "tui") {
774
+ ctx.ui.notify("/mini-lens-minimal requires TUI mode", "error");
775
+ return;
776
+ }
777
+ if (normalized && normalized !== "on" && normalized !== "off") {
778
+ ctx.ui.notify("Usage: /mini-lens-minimal [on|off]", "warning");
779
+ return;
780
+ }
781
+ settings = {
782
+ ...settings,
783
+ "mini-lens-minimal-show": normalized === "on" ? true : normalized === "off" ? false : !settings["mini-lens-minimal-show"],
784
+ onboardingCompleted: true,
785
+ };
786
+ mountMinimalOutput(ctx);
787
+ await persistSettings(ctx);
788
+ ctx.ui.notify(`Mini Lens minimal output: ${settings["mini-lens-minimal-show"] ? "on" : "off"}`, "info");
789
+ },
790
+ });
791
+
792
+ pi.on("session_start", async (_event, ctx) => {
793
+ const loaded = await loadSettings(configPath);
794
+ settings = loaded.settings;
795
+ minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
796
+ activeMinimalTurn = undefined;
797
+ pendingMinimalFinal = "";
798
+ minimalToolOutputIndices.clear();
799
+ mountMinimalOutput(ctx);
800
+ ctx.ui.setFooter((tui, theme) => {
801
+ refreshFooter = () => tui.requestRender();
802
+ return {
803
+ invalidate() {},
804
+ render(width: number): string[] {
805
+ return [statusLine(ctx, theme, width, sessionUsage(ctx), settings, speed, undefined, mcpCount)];
806
+ },
807
+ };
808
+ });
809
+ refresh();
810
+ if (!loaded.exists && ctx.mode === "tui" && ctx.hasUI) {
811
+ const choice = await ctx.ui.select(
812
+ "Mini Lens preview\n\n deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 500/1.0M █░░░░░░░░░ 1% 120 tok/s\n\nMCP count and dot-matrix style are off by default; other fields are on.",
813
+ ["Keep defaults", "Configure now"],
814
+ );
815
+ settings = { ...settings, onboardingCompleted: true };
816
+ try {
817
+ await persistSettings(ctx);
818
+ } catch {
819
+ ctx.ui.notify(`Could not save Mini Lens settings in ${CONFIG_DIR_NAME}`, "error");
820
+ }
821
+ if (choice === "Configure now") await openSettings(ctx);
822
+ }
823
+ });
824
+ const syncMinimalBranch = (_event: unknown, ctx: ExtensionContext) => {
825
+ minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
826
+ activeMinimalTurn = undefined;
827
+ pendingMinimalFinal = "";
828
+ minimalMessageIndices.clear();
829
+ minimalToolOutputIndices.clear();
830
+ mountMinimalOutput(ctx);
831
+ refreshMinimalOutput();
832
+ };
833
+ // New/switch/fork emit session_start; tree navigation has its own event.
834
+ pi.on("session_tree", syncMinimalBranch);
835
+ pi.on("session_compact", (event, ctx) => {
836
+ // Compaction during execution must not discard the in-flight turn or indexes.
837
+ if (activeMinimalTurn) { refreshMinimalOutput(); return; }
838
+ syncMinimalBranch(event, ctx);
839
+ });
840
+ pi.on("before_agent_start", (event) => {
841
+ if (!activeMinimalTurn) return;
842
+ for (const name of skillNames(event.prompt)) pushProcess(activeMinimalTurn, "skill", name);
843
+ refreshMinimalOutput();
844
+ });
845
+ pi.on("model_select", refresh);
846
+ pi.on("thinking_level_select", refresh);
847
+ pi.on("message_start", (event) => {
848
+ if (event.message.role === "user") {
849
+ if (activeMinimalTurn) {
850
+ activeMinimalTurn.final = pendingMinimalFinal;
851
+ }
852
+ const question = contentText(event.message.content) || "[附件]";
853
+ processExpanded = false;
854
+ activeMinimalTurn = { question, process: [], running: true, shortcutHintUntil: Date.now() + 6_000 };
855
+ if (shortcutTimer) clearTimeout(shortcutTimer);
856
+ shortcutTimer = setTimeout(() => refreshMinimalOutput(), 6_000);
857
+ shortcutTimer.unref();
858
+ for (const name of skillNames(question)) pushProcess(activeMinimalTurn, "skill", name);
859
+ pendingMinimalFinal = "";
860
+ minimalToolOutputIndices.clear();
861
+ minimalTurns.push(activeMinimalTurn);
862
+ refreshMinimalOutput();
863
+ }
864
+ if (event.message.role !== "assistant") return;
865
+ minimalMessageIndices.clear();
866
+ pendingMinimalFinal = "";
867
+ // Keep the last completed speed visible until this response produces tokens.
868
+ // Tool-call-only assistant messages therefore cannot erase a useful rate.
869
+ const startedAt = Date.now();
870
+ activeGeneration = { startedAt, output: 0, lastSampleAt: startedAt };
871
+ startSpeedTimer();
872
+ });
873
+ pi.on("message_update", (event) => {
874
+ const partial = (event.assistantMessageEvent as { partial?: { usage?: UsageLike; content?: Array<Record<string, unknown>> } }).partial;
875
+ if (activeMinimalTurn && partial?.content) {
876
+ for (const [blockIndex, item] of partial.content.entries()) {
877
+ if (item.type !== "thinking") continue;
878
+ const line = `${item.type === "thinking" ? "thinking" : "output"} ${processText(item.thinking ?? item.text)}`;
879
+ const index = minimalMessageIndices.get(blockIndex);
880
+ if (index === undefined) {
881
+ minimalMessageIndices.set(blockIndex, activeMinimalTurn.process.length);
882
+ activeMinimalTurn.process.push(line);
883
+ } else activeMinimalTurn.process[index] = line;
884
+ }
885
+ activeMinimalTurn.final = contentText(partial.content) || undefined;
886
+ refreshMinimalOutput();
887
+ }
888
+ if (activeMinimalTurn && partial?.usage) {
889
+ activeMinimalTurn.pendingUsage = partial.usage;
890
+ refreshMinimalOutput();
891
+ }
892
+ const usage = partial?.usage;
893
+ const output = finiteNumber(usage?.output);
894
+ const timestamp = Date.now();
895
+ if (activeGeneration && output !== undefined && output >= activeGeneration.output && timestamp >= activeGeneration.lastSampleAt) {
896
+ activeGeneration.output = output;
897
+ activeGeneration.lastSampleAt = timestamp;
898
+ refreshStreamingSpeed();
899
+ }
900
+ });
901
+ pi.on("message_end", (event) => {
902
+ if (event.message.role === "assistant") {
903
+ if (activeMinimalTurn) {
904
+ activeMinimalTurn.usage = addUsage(activeMinimalTurn.usage ?? EMPTY_USAGE, event.message.usage as UsageLike | undefined);
905
+ activeMinimalTurn.pendingUsage = undefined;
906
+ }
907
+ if (activeGeneration) {
908
+ const finalSpeed = outputSpeed((event.message.usage as UsageLike | undefined)?.output, activeGeneration.startedAt);
909
+ if (finalSpeed !== undefined) speed = finalSpeed;
910
+ activeGeneration = undefined;
911
+ stopSpeedTimer();
912
+ }
913
+ const content = (event.message as { content?: unknown }).content;
914
+ if (activeMinimalTurn && Array.isArray(content)) {
915
+ for (const [blockIndex, item] of (content as Array<Record<string, unknown>>).entries()) {
916
+ if (item.type !== "thinking" && !(item.type === "text" && content.some((block) => block.type === "toolCall"))) continue;
917
+ const line = `${item.type === "thinking" ? "thinking" : "output"} ${processText(item.thinking ?? item.text)}`;
918
+ const index = minimalMessageIndices.get(blockIndex);
919
+ if (index === undefined) activeMinimalTurn.process.push(line);
920
+ else activeMinimalTurn.process[index] = line;
921
+ }
922
+ const text = contentText(content);
923
+ const message = event.message as { stopReason?: string; errorMessage?: string };
924
+ activeMinimalTurn.final = undefined;
925
+ pendingMinimalFinal = content.some((item) => item?.type === "toolCall") ? "" : text;
926
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
927
+ pendingMinimalFinal = [message.stopReason === "aborted" ? "执行已中止" : "执行失败", message.errorMessage, pendingMinimalFinal].filter(Boolean).join("\n");
928
+ }
929
+ activeMinimalTurn.final = pendingMinimalFinal || undefined;
930
+ }
931
+ }
932
+ refresh();
933
+ refreshMinimalOutput();
934
+ });
935
+ pi.on("tool_execution_start", (event) => {
936
+ toolStarts.set(event.toolCallId, Date.now());
937
+ if (activeMinimalTurn) {
938
+ (activeMinimalTurn.agentCalls ??= []).push(agentCall(event.toolCallId, event.toolName, event.args));
939
+ pushProcess(activeMinimalTurn, "call", event.toolCallId);
940
+ (activeMinimalTurn.waitingTools ??= []).push({ id: event.toolCallId, name: event.toolName, startedAt: Date.now() });
941
+ }
942
+ const path = (event.args as { path?: unknown })?.path;
943
+ if (typeof path === "string" && /(?:^|\/)SKILL\.md$/i.test(path)) {
944
+ pushProcess(activeMinimalTurn, "skill", path.split("/").at(-2) ?? path);
945
+ }
946
+ refreshMinimalOutput();
947
+ });
948
+ pi.on("tool_execution_update", (event) => {
949
+ if (!activeMinimalTurn) return;
950
+ // Pi emits an empty content array before starting bash. It is a heartbeat,
951
+ // not output: keep the tool status (and any existing output) intact.
952
+ const text = contentText(event.partialResult);
953
+ if (!text) return;
954
+ const call = activeMinimalTurn.agentCalls?.find(call => call.id === event.toolCallId);
955
+ if (call) { call.output = text; activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter(tool => tool.id !== event.toolCallId); refreshMinimalOutput(); return; }
956
+ activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter((tool) => tool.id !== event.toolCallId);
957
+ const line = `output ${text}`;
958
+ const index = minimalToolOutputIndices.get(event.toolCallId);
959
+ if (index === undefined) {
960
+ minimalToolOutputIndices.set(event.toolCallId, activeMinimalTurn.process.length);
961
+ activeMinimalTurn.process.push(line);
962
+ } else {
963
+ activeMinimalTurn.process[index] = line;
964
+ }
965
+ refreshMinimalOutput();
966
+ });
967
+ pi.on("tool_execution_end", (event) => {
968
+ const startedAt = toolStarts.get(event.toolCallId);
969
+ toolStarts.delete(event.toolCallId);
970
+ const nestedUsage = (event.result as { usage?: UsageLike } | undefined)?.usage;
971
+ if (activeMinimalTurn) activeMinimalTurn.usage = addUsage(activeMinimalTurn.usage ?? EMPTY_USAGE, nestedUsage);
972
+ if (startedAt !== undefined) {
973
+ const nestedSpeed = outputSpeed(nestedUsage?.output, startedAt);
974
+ if (nestedSpeed !== undefined) speed = nestedSpeed;
975
+ }
976
+ const call = activeMinimalTurn?.agentCalls?.find(call => call.id === event.toolCallId);
977
+ if (call) {
978
+ if (activeMinimalTurn) activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter(tool => tool.id !== event.toolCallId);
979
+ call.state = event.isError ? "error" : "done";
980
+ call.output = contentText(event.result) || (event.isError ? "调用失败(无文本详情)" : "调用已返回(后台任务状态见下方)");
981
+ refresh();
982
+ refreshMinimalOutput();
983
+ return;
984
+ }
985
+ if (activeMinimalTurn) {
986
+ activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter((tool) => tool.id !== event.toolCallId);
987
+ const text = contentText(event.result) || (event.isError ? "工具执行失败(无文本详情)" : "工具执行完成(无文本输出)");
988
+ const line = `${event.isError ? "output error" : "output"} ${text}`;
989
+ const index = minimalToolOutputIndices.get(event.toolCallId);
990
+ if (index === undefined) activeMinimalTurn.process.push(line);
991
+ else activeMinimalTurn.process[index] = line;
992
+ }
993
+ minimalToolOutputIndices.delete(event.toolCallId);
994
+ refresh();
995
+ refreshMinimalOutput();
996
+ });
997
+ pi.on("agent_start", refresh);
998
+ pi.on("agent_end", refresh);
999
+ pi.on("agent_settled", () => {
1000
+ if (!activeMinimalTurn) return;
1001
+ for (const turn of minimalTurns) turn.running = false;
1002
+ activeMinimalTurn.final = pendingMinimalFinal;
1003
+ activeMinimalTurn = undefined;
1004
+ pendingMinimalFinal = "";
1005
+ minimalToolOutputIndices.clear();
1006
+ refreshMinimalOutput();
1007
+ });
1008
+ pi.on("session_shutdown", () => {
1009
+ if (shortcutTimer) clearTimeout(shortcutTimer);
1010
+ shortcutTimer = undefined;
1011
+ unsubscribeMcpStatus();
1012
+ refreshFooter = undefined;
1013
+ activeGeneration = undefined;
1014
+ toolStarts.clear();
1015
+ minimalToolOutputIndices.clear();
1016
+ refreshMinimal = undefined;
1017
+ if (waitingTimer) clearInterval(waitingTimer);
1018
+ waitingTimer = undefined;
1019
+ unsubscribeMinimalInput?.();
1020
+ unsubscribeMinimalInput = undefined;
1021
+ restoreAgentWidgets?.();
1022
+ restoreAgentWidgets = undefined;
1023
+ restoreTranscript?.();
1024
+ restoreTranscript = undefined;
1025
+ stopSpeedTimer();
1026
+ });
1027
+ }