@each1024/pi-mini-mode 0.9.0
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/LICENSE +21 -0
- package/README.md +214 -0
- package/README.zh-CN.md +210 -0
- package/extensions/footer-status.ts +1612 -0
- package/lib/agent-view.ts +518 -0
- package/lib/file-links.ts +80 -0
- package/lib/footer-tidy.ts +75 -0
- package/lib/input-enhancements.ts +622 -0
- package/lib/minimal-markdown.ts +181 -0
- package/lib/minimal-theme.ts +48 -0
- package/lib/settings-web.ts +119 -0
- package/lib/settings.html +209 -0
- package/lib/sticky-tool.ts +100 -0
- package/lib/title-plain.ts +57 -0
- package/lib/transcript-adapter.ts +578 -0
- package/package.json +61 -0
- package/themes/README.md +5 -0
- package/themes/cc-dark.json +91 -0
- package/themes/cc-light.json +91 -0
|
@@ -0,0 +1,1612 @@
|
|
|
1
|
+
import { AGENT_STATUS_ENTRY, savedAgentStatuses, retainAgentStatuses, agentChildren, agentCall, agentCallDisplay, agentStatusesByTurn, attachAgentWidgets, isAgentTool, liveAgentView, readAgentStatuses, runningGlyph, type AgentCall } from "../lib/agent-view.ts";
|
|
2
|
+
import { CONFIG_DIR_NAME, getAgentDir, getMarkdownTheme, SettingsManager, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { attachTranscript, type NoticeRows, type TurnNotices } from "../lib/transcript-adapter.ts";
|
|
4
|
+
import { diagramMarkdown, isFencedMarkdown, renderMinimalMarkdown } from "../lib/minimal-markdown.ts";
|
|
5
|
+
import { minimalSurface, paintExpandedHeading } from "../lib/minimal-theme.ts";
|
|
6
|
+
import { Markdown, matchesKey, isKeyRelease, isKeyRepeat, sliceByColumn, type SettingItem, Text, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
7
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
8
|
+
import type { InputEnhancementsCleanup } from "../lib/input-enhancements.ts";
|
|
9
|
+
import { linkMessageFiles } from "../lib/file-links.ts";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { stripVTControlCharacters } from "node:util";
|
|
12
|
+
import { basename, dirname, join } from "node:path";
|
|
13
|
+
import attachFooterTidy from "../lib/footer-tidy.ts";
|
|
14
|
+
import attachTitlePlain from "../lib/title-plain.ts";
|
|
15
|
+
|
|
16
|
+
export const SETTINGS_FILE_NAME = "pi-mini-mode.json";
|
|
17
|
+
|
|
18
|
+
export interface MiniLensSettings {
|
|
19
|
+
"pi-mini-mode-model-show": boolean;
|
|
20
|
+
"pi-mini-mode-thinking-show": boolean;
|
|
21
|
+
"pi-mini-mode-project-branch-show": boolean;
|
|
22
|
+
"pi-mini-mode-branch-show": boolean;
|
|
23
|
+
"pi-mini-mode-ch-show": boolean;
|
|
24
|
+
"pi-mini-mode-session-tokens-show": boolean;
|
|
25
|
+
"pi-mini-mode-cache-tokens-show": boolean;
|
|
26
|
+
"pi-mini-mode-cost-show": boolean;
|
|
27
|
+
"pi-mini-mode-mcp-show": boolean;
|
|
28
|
+
"pi-mini-mode-context-show": boolean;
|
|
29
|
+
"pi-mini-mode-context-dots-show": boolean;
|
|
30
|
+
"pi-mini-mode-context-percent-show": boolean;
|
|
31
|
+
"pi-mini-mode-speed-show": boolean;
|
|
32
|
+
"pi-mini-mode-speed-unit-show": boolean;
|
|
33
|
+
"pi-mini-mode-minimal-show": boolean;
|
|
34
|
+
"pi-mini-mode-input-enhancements": boolean;
|
|
35
|
+
"pi-mini-mode-minimal-thinking-show": boolean;
|
|
36
|
+
"pi-mini-mode-minimal-tools-show": boolean;
|
|
37
|
+
"pi-mini-mode-minimal-output-show": boolean;
|
|
38
|
+
"pi-mini-mode-minimal-skills-show": boolean;
|
|
39
|
+
"pi-mini-mode-agent-usage-show": boolean;
|
|
40
|
+
"pi-mini-mode-agent-shortcut-show": boolean;
|
|
41
|
+
onboardingCompleted: boolean;
|
|
42
|
+
footerOrder?: string[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
|
|
46
|
+
"pi-mini-mode-model-show": true,
|
|
47
|
+
"pi-mini-mode-thinking-show": true,
|
|
48
|
+
"pi-mini-mode-project-branch-show": true,
|
|
49
|
+
"pi-mini-mode-branch-show": false,
|
|
50
|
+
"pi-mini-mode-ch-show": true,
|
|
51
|
+
"pi-mini-mode-session-tokens-show": true,
|
|
52
|
+
"pi-mini-mode-cache-tokens-show": true,
|
|
53
|
+
"pi-mini-mode-cost-show": true,
|
|
54
|
+
"pi-mini-mode-mcp-show": false,
|
|
55
|
+
"pi-mini-mode-context-show": true,
|
|
56
|
+
"pi-mini-mode-context-dots-show": false,
|
|
57
|
+
"pi-mini-mode-context-percent-show": true,
|
|
58
|
+
"pi-mini-mode-speed-show": true,
|
|
59
|
+
"pi-mini-mode-speed-unit-show": true,
|
|
60
|
+
"pi-mini-mode-minimal-show": true,
|
|
61
|
+
"pi-mini-mode-input-enhancements": true,
|
|
62
|
+
"pi-mini-mode-minimal-thinking-show": true,
|
|
63
|
+
"pi-mini-mode-minimal-tools-show": true,
|
|
64
|
+
"pi-mini-mode-minimal-output-show": true,
|
|
65
|
+
"pi-mini-mode-minimal-skills-show": true,
|
|
66
|
+
"pi-mini-mode-agent-usage-show": true,
|
|
67
|
+
"pi-mini-mode-agent-shortcut-show": true,
|
|
68
|
+
onboardingCompleted: false,
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<Exclude<keyof MiniLensSettings, "footerOrder">>;
|
|
72
|
+
export const FOOTER_FIELDS = ["project-branch", "model", "thinking", "branch", "session-tokens", "cache-tokens", "ch", "cost", "mcp", "context", "context-percent", "speed"] as const;
|
|
73
|
+
|
|
74
|
+
const COPY = {
|
|
75
|
+
title: "Pi Mini Mode 设置", preview: "预览(示例数据)", lens: "设置", minimal: "极简输出",
|
|
76
|
+
model: "显示模型", thinking: "显示思考等级", total: "显示会话总 token", cached: "显示会话缓存 token", totalLabel: "Total", cachedLabel: "Cached", cacheHitLabel: "CH", cacheHit: "显示缓存命中率 (CH)", price: "显示会话价格", mcp: "显示已启用 MCP 服务器", context: "显示上下文 token 与进度条", dots: "↳ 使用点阵进度条", percent: "显示上下文百分比", speed: "显示最近生成速度", speedUnit: "↳ 显示 tok/s 单位", inputEnhancements: "输入增强", showThinking: "显示思考", tools: "显示工具调用", output: "显示过程输出", skills: "显示技能", agentUsage: "显示 Agent token 用量", shortcut: "新 Agent 显示 Ctrl+O 提示(6 秒)",
|
|
77
|
+
totalDescription: "Total:当前会话分支上的全部 token,含工具上报的 LLM 用量。", cachedDescription: "Cached:累计 cache-read + cache-write token(包含在 Total 中)。", cacheHitDescription: "CH(cache hit):cache-read / (input + cache-read)。Cache write 不计入此比率。",
|
|
78
|
+
enableMinimalDescription: "开启统一折叠思考、工具和技能过程;关闭恢复 Pi 默认会话历史。",
|
|
79
|
+
inputEnhancementsDescription: "原生 Ctrl+V 粘贴图片(Windows/WSL:Alt+V);图片显示为 [image1] 标签,光标移入或全屏悬停可预览。空白后 / 选择技能并在光标处插入。Cmd+点击带下划线的图片标签或消息文件路径,用系统默认应用打开;预览及点击需终端支持。关闭仅恢复原生行为。",
|
|
80
|
+
tuiRequired: "/pi-mini-mode-settings 需要 TUI 模式", saveFailed: "无法保存 Pi Mini Mode 设置", minimalRequired: "/pi-mini-mode-minimal 需要 TUI 模式", minimalUsage: "用法:/pi-mini-mode-minimal [on|off]", minimalState: "Pi Mini Mode 极简输出:", onboarding: "MCP 数量、点阵样式和仅显示分支默认关闭;项目名称和分支默认开启,与仅显示分支互斥。", keepDefaults: "保留默认", configureNow: "立即配置", applyRecommended: "应用推荐配置", chooseTheme: "选择 Pi Mini Mode 主题(将保存全局主题和全屏模式;重启后生效)", themeSaved: "已保存推荐主题和全屏模式。请重启 Pi;项目设置或命令行参数可能覆盖全局设置。", themeSaveFailed: "无法保存推荐的 Pi 主题和全屏模式;未完成首次配置。", themeApplyFailed: "推荐设置已保存,但当前主题未能立即应用;请重启 Pi。",
|
|
81
|
+
} as const;
|
|
82
|
+
|
|
83
|
+
const RECOMMENDED_THEMES = ["cc-dark", "cc-light"] as const;
|
|
84
|
+
type RecommendedTheme = typeof RECOMMENDED_THEMES[number];
|
|
85
|
+
|
|
86
|
+
export function settingsPath(agentDir = process.env.PI_MINI_MODE_AGENT_DIR ?? join(homedir(), CONFIG_DIR_NAME, "agent")): string {
|
|
87
|
+
return join(agentDir, SETTINGS_FILE_NAME);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function isBoolean(value: unknown): value is boolean {
|
|
91
|
+
return typeof value === "boolean";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function parseSettings(value: unknown): MiniLensSettings {
|
|
95
|
+
const candidate = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
|
96
|
+
const settings = { ...DEFAULT_SETTINGS };
|
|
97
|
+
for (const id of SETTING_IDS) {
|
|
98
|
+
if (isBoolean(candidate[id])) settings[id] = candidate[id];
|
|
99
|
+
}
|
|
100
|
+
if (Array.isArray(candidate.footerOrder)) {
|
|
101
|
+
settings.footerOrder = [...new Set(candidate.footerOrder.filter((id): id is typeof FOOTER_FIELDS[number] =>
|
|
102
|
+
typeof id === "string" && (FOOTER_FIELDS as readonly string[]).includes(id)))];
|
|
103
|
+
for (const id of FOOTER_FIELDS) if (!settings.footerOrder.includes(id)) settings.footerOrder.push(id);
|
|
104
|
+
}
|
|
105
|
+
if (settings["pi-mini-mode-branch-show"]) settings["pi-mini-mode-project-branch-show"] = false;
|
|
106
|
+
// 折叠回复的旧细项已合并进极简输出总开关:旧值不再暗中过滤内容,始终按默认全开。
|
|
107
|
+
for (const id of LEGACY_MINIMAL_SETTING_IDS) settings[id] = true;
|
|
108
|
+
return settings;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Pi /model and other selectors own Ctrl+S; the editor exposes getText. */
|
|
112
|
+
export function focusedSelectorOwnsKeys(tui?: { getFocusedComponent?(): unknown } | null): boolean {
|
|
113
|
+
const focused = tui?.getFocusedComponent?.();
|
|
114
|
+
return !!focused && typeof focused === "object" && typeof (focused as { getText?: unknown }).getText !== "function";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function loadSettings(path = settingsPath()): Promise<{ settings: MiniLensSettings; exists: boolean }> {
|
|
118
|
+
try {
|
|
119
|
+
return { settings: parseSettings(JSON.parse(await readFile(path, "utf8"))), exists: true };
|
|
120
|
+
} catch {
|
|
121
|
+
return { settings: { ...DEFAULT_SETTINGS }, exists: false };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function saveSettings(settings: MiniLensSettings, path = settingsPath()): Promise<void> {
|
|
126
|
+
await mkdir(dirname(path), { recursive: true });
|
|
127
|
+
const temporaryPath = `${path}.tmp`;
|
|
128
|
+
await writeFile(temporaryPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
|
|
129
|
+
await rename(temporaryPath, path);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function enabledMcpServerCount(value: unknown): number | undefined {
|
|
133
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
134
|
+
const snapshot = value as { version?: unknown; servers?: unknown };
|
|
135
|
+
if (snapshot.version !== 1 || !Array.isArray(snapshot.servers)) return undefined;
|
|
136
|
+
let count = 0;
|
|
137
|
+
for (const server of snapshot.servers) {
|
|
138
|
+
if (!server || typeof server !== "object" || Array.isArray(server)
|
|
139
|
+
|| typeof server.name !== "string"
|
|
140
|
+
|| (server.disabled !== undefined && typeof server.disabled !== "boolean")) return undefined;
|
|
141
|
+
if (server.disabled !== true) count++;
|
|
142
|
+
}
|
|
143
|
+
return count;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function formatTokens(value: number): string {
|
|
147
|
+
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
|
|
148
|
+
if (value >= 1_000) return `${Math.round(value / 1_000)}K`;
|
|
149
|
+
return String(Math.round(value));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function finiteNumber(value: unknown): number | undefined {
|
|
153
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function nonNegative(value: unknown): number {
|
|
157
|
+
return Math.max(0, finiteNumber(value) ?? 0);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function formatUsd(value: number): string {
|
|
161
|
+
if (value < 0.01) return `$${value.toFixed(4)}`;
|
|
162
|
+
if (value < 1) return `$${value.toFixed(3)}`;
|
|
163
|
+
return `$${value.toFixed(2)}`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
interface UsageLike {
|
|
167
|
+
input?: unknown;
|
|
168
|
+
output?: unknown;
|
|
169
|
+
cacheRead?: unknown;
|
|
170
|
+
cacheWrite?: unknown;
|
|
171
|
+
totalTokens?: unknown;
|
|
172
|
+
cost?: { total?: unknown };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export interface SessionUsage {
|
|
176
|
+
totalTokens: number;
|
|
177
|
+
input: number;
|
|
178
|
+
output: number;
|
|
179
|
+
cacheRead: number;
|
|
180
|
+
cacheWrite: number;
|
|
181
|
+
cost: number;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const EMPTY_USAGE: SessionUsage = { totalTokens: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
185
|
+
|
|
186
|
+
function addUsage(total: SessionUsage, usage: UsageLike | undefined): SessionUsage {
|
|
187
|
+
if (!usage) return total;
|
|
188
|
+
const input = nonNegative(usage.input);
|
|
189
|
+
const output = nonNegative(usage.output);
|
|
190
|
+
const cacheRead = nonNegative(usage.cacheRead);
|
|
191
|
+
const cacheWrite = nonNegative(usage.cacheWrite);
|
|
192
|
+
// totalTokens is the provider's authoritative count. Older/custom tool results
|
|
193
|
+
// sometimes omit it, so only then derive a complete count from its components.
|
|
194
|
+
const reportedTotal = finiteNumber(usage.totalTokens);
|
|
195
|
+
return {
|
|
196
|
+
totalTokens: total.totalTokens + Math.max(0, reportedTotal ?? input + output + cacheRead + cacheWrite),
|
|
197
|
+
input: total.input + input,
|
|
198
|
+
output: total.output + output,
|
|
199
|
+
cacheRead: total.cacheRead + cacheRead,
|
|
200
|
+
cacheWrite: total.cacheWrite + cacheWrite,
|
|
201
|
+
cost: total.cost + nonNegative(usage.cost?.total),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Aggregate persisted, finalized usage once per active-branch entry. */
|
|
206
|
+
export function sessionUsage(ctx: ExtensionContext): SessionUsage {
|
|
207
|
+
return ctx.sessionManager.getBranch().reduce((total, entry) => {
|
|
208
|
+
if (entry.type !== "message") return total;
|
|
209
|
+
const message = entry.message as { role?: unknown; usage?: UsageLike };
|
|
210
|
+
return message.role === "assistant" || message.role === "toolResult"
|
|
211
|
+
? addUsage(total, message.usage)
|
|
212
|
+
: total;
|
|
213
|
+
}, { ...EMPTY_USAGE });
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function cacheHit(usage: SessionUsage): number | undefined {
|
|
217
|
+
const cacheBase = usage.input + usage.cacheRead;
|
|
218
|
+
return cacheBase === 0 ? undefined : 100 * usage.cacheRead / cacheBase;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export type SpeedColor = "success" | "warning" | "error" | "muted";
|
|
222
|
+
|
|
223
|
+
export function speedColor(speed: number | undefined): SpeedColor {
|
|
224
|
+
if (speed === undefined) return "muted";
|
|
225
|
+
if (speed >= 30) return "success";
|
|
226
|
+
if (speed >= 10) return "warning";
|
|
227
|
+
return "error";
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function formatSpeed(speed: number, showUnit: boolean): string {
|
|
231
|
+
const value = speed.toFixed(speed >= 100 ? 0 : 1);
|
|
232
|
+
return showUnit ? `${value} tok/s` : value;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const PLANNOTATOR_STATUS_KEY = "plannotator";
|
|
236
|
+
const PLANNOTATOR_PLANNING_LABEL = "⏸ plan";
|
|
237
|
+
const PLAN_CAP_LEFT = "\uE0B6";
|
|
238
|
+
const PLAN_CAP_RIGHT = "\uE0B4";
|
|
239
|
+
const PLAN_BG = "250;204;21";
|
|
240
|
+
const PLAN_FG = "19;18;23";
|
|
241
|
+
|
|
242
|
+
function plannotatorStatusText(text: string | undefined): string {
|
|
243
|
+
return stripVTControlCharacters(text ?? "").replace(/\s+/g, " ").trim();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Exact plannotator planning label from @plannotator/pi-extension (`⏸ plan`). */
|
|
247
|
+
export function isPlannotatorPlanningStatus(text: string | undefined): boolean {
|
|
248
|
+
return plannotatorStatusText(text) === PLANNOTATOR_PLANNING_LABEL;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Scheme B PLAN capsule. visibleWidth===1 only protects columns; it is not a font check. */
|
|
252
|
+
export function planCapsule(): string {
|
|
253
|
+
const paint = (text: string) => `\x1b[48;2;${PLAN_BG}m\x1b[38;2;${PLAN_FG}m${text}\x1b[39m\x1b[49m`;
|
|
254
|
+
if (visibleWidth(PLAN_CAP_LEFT) === 1 && visibleWidth(PLAN_CAP_RIGHT) === 1) {
|
|
255
|
+
const cap = (ch: string) => `\x1b[38;2;${PLAN_BG}m${ch}\x1b[39m`;
|
|
256
|
+
return `${cap(PLAN_CAP_LEFT)}${paint("PLAN")}${cap(PLAN_CAP_RIGHT)}`;
|
|
257
|
+
}
|
|
258
|
+
return paint(" PLAN ");
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function plannotatorPlanTag(statuses: ReadonlyMap<string, string> | undefined): string {
|
|
262
|
+
const text = statuses?.get(PLANNOTATOR_STATUS_KEY);
|
|
263
|
+
return isPlannotatorPlanningStatus(text) ? planCapsule() : "";
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function progressBar(percent: number, dots: boolean, width: number): string {
|
|
267
|
+
const filled = Math.round(width * Math.max(0, Math.min(100, percent)) / 100);
|
|
268
|
+
return (dots ? "⣿" : "█").repeat(filled) + (dots ? "⣀" : "░").repeat(width - filled);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function renderRight(
|
|
272
|
+
theme: ExtensionContext["ui"]["theme"],
|
|
273
|
+
settings: MiniLensSettings,
|
|
274
|
+
percentText: string,
|
|
275
|
+
speed: number | undefined,
|
|
276
|
+
highlighted?: keyof MiniLensSettings,
|
|
277
|
+
): string {
|
|
278
|
+
const fields: string[] = [];
|
|
279
|
+
if (settings["pi-mini-mode-context-percent-show"] && percentText) fields.push(highlighted === "pi-mini-mode-context-percent-show" ? theme.bg("selectedBg", theme.fg("accent", theme.bold(percentText))) : theme.fg("accent", percentText));
|
|
280
|
+
if (settings["pi-mini-mode-speed-show"] && speed !== undefined) {
|
|
281
|
+
const text = formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]);
|
|
282
|
+
fields.push(highlighted === "pi-mini-mode-speed-show" || highlighted === "pi-mini-mode-speed-unit-show"
|
|
283
|
+
? theme.bg("selectedBg", theme.fg("accent", theme.bold(text)))
|
|
284
|
+
: theme.fg(speedColor(speed), text));
|
|
285
|
+
}
|
|
286
|
+
return fields.join(" ");
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const SETTINGS_PREVIEW_CONTEXT = {
|
|
290
|
+
cwd: "/work/pi-mini-mode",
|
|
291
|
+
model: { id: "deepseek-v4-flash" },
|
|
292
|
+
thinkingLevel: "high",
|
|
293
|
+
getContextUsage: () => ({ tokens: 500, contextWindow: 1_000_000, percent: 1 }),
|
|
294
|
+
} as unknown as ExtensionContext;
|
|
295
|
+
|
|
296
|
+
const SETTINGS_PREVIEW_USAGE: SessionUsage = {
|
|
297
|
+
totalTokens: 45_000,
|
|
298
|
+
input: 15_000,
|
|
299
|
+
output: 5_000,
|
|
300
|
+
cacheRead: 10_000,
|
|
301
|
+
cacheWrite: 15_000,
|
|
302
|
+
cost: 0.012,
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
export function settingsPreviewLine(
|
|
306
|
+
theme: ExtensionContext["ui"]["theme"],
|
|
307
|
+
settings: MiniLensSettings,
|
|
308
|
+
width = 140,
|
|
309
|
+
highlighted?: keyof MiniLensSettings,
|
|
310
|
+
): string {
|
|
311
|
+
return statusLine(SETTINGS_PREVIEW_CONTEXT, theme, width, SETTINGS_PREVIEW_USAGE, settings, 120, highlighted, 3, undefined, "main");
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export function statusLine(
|
|
315
|
+
ctx: ExtensionContext,
|
|
316
|
+
theme: ExtensionContext["ui"]["theme"],
|
|
317
|
+
width: number,
|
|
318
|
+
usageTotals: SessionUsage,
|
|
319
|
+
settings: MiniLensSettings,
|
|
320
|
+
speed: number | undefined,
|
|
321
|
+
highlighted?: keyof MiniLensSettings,
|
|
322
|
+
mcpCount?: number,
|
|
323
|
+
statuses?: ReadonlyMap<string, string>,
|
|
324
|
+
gitBranch?: string | null,
|
|
325
|
+
): string {
|
|
326
|
+
if (highlighted === "pi-mini-mode-context-dots-show") highlighted = "pi-mini-mode-context-show";
|
|
327
|
+
const field = (id: keyof MiniLensSettings, color: Parameters<typeof theme.fg>[0], text: string) =>
|
|
328
|
+
id === highlighted ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text))) : theme.fg(color, text);
|
|
329
|
+
if (width <= 0) return "";
|
|
330
|
+
const model = ctx.model?.id ?? "";
|
|
331
|
+
const thinking = ctx.thinkingLevel ?? "";
|
|
332
|
+
const hit = cacheHit(usageTotals);
|
|
333
|
+
const hitText = hit === undefined ? "" : `${COPY.cacheHitLabel} ${hit.toFixed(1)}%`;
|
|
334
|
+
const cachedTokens = usageTotals.cacheRead + usageTotals.cacheWrite;
|
|
335
|
+
const price = usageTotals.cost > 0 ? formatUsd(usageTotals.cost) : "";
|
|
336
|
+
const contextUsage = ctx.getContextUsage();
|
|
337
|
+
const tokens = finiteNumber(contextUsage?.tokens);
|
|
338
|
+
const contextWindow = finiteNumber(contextUsage?.contextWindow);
|
|
339
|
+
const rawPercent = finiteNumber(contextUsage?.percent);
|
|
340
|
+
const percent = rawPercent === undefined ? undefined : Math.max(0, Math.min(100, rawPercent));
|
|
341
|
+
const percentText = percent === undefined ? "" : `${Math.round(percent)}%`;
|
|
342
|
+
const tokenText = tokens === undefined || contextWindow === undefined ? "" : `${formatTokens(Math.max(0, tokens))}/${formatTokens(Math.max(0, contextWindow))}`;
|
|
343
|
+
const showContext = settings["pi-mini-mode-context-show"] && Boolean(tokenText);
|
|
344
|
+
const mcpText = settings["pi-mini-mode-mcp-show"] && mcpCount !== undefined ? `◇ MCP ${mcpCount}` : "";
|
|
345
|
+
const planTag = plannotatorPlanTag(statuses);
|
|
346
|
+
const branchOnly = settings["pi-mini-mode-branch-show"];
|
|
347
|
+
const branchSetting = branchOnly ? "pi-mini-mode-branch-show" : "pi-mini-mode-project-branch-show";
|
|
348
|
+
const branchText = gitBranch && settings[branchSetting]
|
|
349
|
+
? stripVTControlCharacters(branchOnly ? gitBranch : `${basename(ctx.cwd)}(${gitBranch})`).replace(/[\x00-\x1f\x7f-\x9f]/g, "") : "";
|
|
350
|
+
|
|
351
|
+
if (settings.footerOrder) {
|
|
352
|
+
const values: Record<string, string> = {
|
|
353
|
+
"project-branch": !branchOnly ? branchText : "", branch: branchOnly ? branchText : "",
|
|
354
|
+
model, thinking,
|
|
355
|
+
"session-tokens": usageTotals.totalTokens > 0 ? `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}` : "",
|
|
356
|
+
"cache-tokens": cachedTokens > 0 ? `${COPY.cachedLabel} ${formatTokens(cachedTokens)}` : "",
|
|
357
|
+
ch: hitText, cost: price, mcp: mcpText,
|
|
358
|
+
context: tokenText,
|
|
359
|
+
"context-percent": percentText, speed: speed === undefined ? "" : formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]),
|
|
360
|
+
};
|
|
361
|
+
const visible = settings.footerOrder.filter(id => settings[`pi-mini-mode-${id}-show` as keyof MiniLensSettings] && values[id]);
|
|
362
|
+
const usedWidth = visibleWidth([planTag, ...visible.map(id => values[id])].filter(Boolean).join(" "));
|
|
363
|
+
const barWidth = Math.max(0, width - usedWidth - 1);
|
|
364
|
+
if (visible.includes("context") && percent !== undefined && barWidth > 0) {
|
|
365
|
+
values.context += ` ${progressBar(percent, settings["pi-mini-mode-context-dots-show"], barWidth)}`;
|
|
366
|
+
}
|
|
367
|
+
return truncateToWidth([planTag, ...settings.footerOrder.map(id => {
|
|
368
|
+
const key = `pi-mini-mode-${id}-show` as keyof MiniLensSettings;
|
|
369
|
+
const color = id === "speed" ? speedColor(speed) : id === "model" || id === "context-percent" ? "accent" : "muted";
|
|
370
|
+
return settings[key] && values[id] ? field(key, color, values[id]) : "";
|
|
371
|
+
})].filter(Boolean).join(" "), width, "…");
|
|
372
|
+
}
|
|
373
|
+
const right = renderRight(theme, settings, percentText, speed, highlighted);
|
|
374
|
+
const rightWidth = visibleWidth(right);
|
|
375
|
+
if (right && width <= rightWidth) {
|
|
376
|
+
const compactRight = settings["pi-mini-mode-speed-show"] && speed !== undefined
|
|
377
|
+
? theme.fg(speedColor(speed), formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]))
|
|
378
|
+
: right;
|
|
379
|
+
return truncateToWidth(compactRight, width, "");
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const leftParts = [
|
|
383
|
+
planTag,
|
|
384
|
+
!branchOnly && branchText && field(branchSetting, "muted", branchText),
|
|
385
|
+
settings["pi-mini-mode-model-show"] && model && field("pi-mini-mode-model-show", "accent", model),
|
|
386
|
+
settings["pi-mini-mode-thinking-show"] && thinking && field("pi-mini-mode-thinking-show", "muted", thinking),
|
|
387
|
+
branchOnly && branchText && field(branchSetting, "muted", branchText),
|
|
388
|
+
settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && field("pi-mini-mode-session-tokens-show", "text", `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`),
|
|
389
|
+
settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && field("pi-mini-mode-cache-tokens-show", "text", `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`),
|
|
390
|
+
settings["pi-mini-mode-ch-show"] && hitText && field("pi-mini-mode-ch-show", "text", hitText),
|
|
391
|
+
settings["pi-mini-mode-cost-show"] && price && field("pi-mini-mode-cost-show", "muted", price),
|
|
392
|
+
mcpText && field("pi-mini-mode-mcp-show", "muted", mcpText),
|
|
393
|
+
].filter((part): part is string => Boolean(part));
|
|
394
|
+
const unstyledLeft = [
|
|
395
|
+
planTag && stripVTControlCharacters(planTag),
|
|
396
|
+
!branchOnly && branchText,
|
|
397
|
+
settings["pi-mini-mode-model-show"] && model,
|
|
398
|
+
settings["pi-mini-mode-thinking-show"] && thinking,
|
|
399
|
+
branchOnly && branchText,
|
|
400
|
+
settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`,
|
|
401
|
+
settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`,
|
|
402
|
+
settings["pi-mini-mode-ch-show"] && hitText,
|
|
403
|
+
settings["pi-mini-mode-cost-show"] && price,
|
|
404
|
+
mcpText,
|
|
405
|
+
].filter(Boolean).join(" ");
|
|
406
|
+
const leftBudget = Math.min(visibleWidth(unstyledLeft), Math.max(1, width - rightWidth - (showContext ? 20 : 1)), Math.max(0, width - rightWidth - 1));
|
|
407
|
+
const left = leftParts.length > 0 ? truncateToWidth(leftParts.join(" "), leftBudget, "…") : "";
|
|
408
|
+
const leftWidth = visibleWidth(left);
|
|
409
|
+
const middleBudget = showContext ? Math.max(0, width - leftWidth - rightWidth - (left && right ? 4 : left || right ? 1 : 0)) : 0;
|
|
410
|
+
|
|
411
|
+
let middle = "";
|
|
412
|
+
if (middleBudget > 0) {
|
|
413
|
+
const visibleToken = truncateToWidth(tokenText, middleBudget, "…");
|
|
414
|
+
const visibleTokenWidth = visibleWidth(visibleToken);
|
|
415
|
+
const barWidth = middleBudget - visibleTokenWidth - 1;
|
|
416
|
+
const filledCell = settings["pi-mini-mode-context-dots-show"] ? "⣿" : "█";
|
|
417
|
+
const emptyCell = settings["pi-mini-mode-context-dots-show"] ? "⣀" : "░";
|
|
418
|
+
const bar = barWidth >= 2 && percent !== undefined
|
|
419
|
+
? `${field("pi-mini-mode-context-show", "accent", filledCell.repeat(Math.round(barWidth * percent / 100)))}${field("pi-mini-mode-context-show", "borderMuted", emptyCell.repeat(barWidth - Math.round(barWidth * percent / 100)))}`
|
|
420
|
+
: "";
|
|
421
|
+
middle = `${field("pi-mini-mode-context-show", "muted", visibleToken)}${bar ? ` ${bar}` : ""}`;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const content = [left, middle].filter(Boolean).join(" ");
|
|
425
|
+
if (!right) return truncateToWidth(content, width, "");
|
|
426
|
+
const gap = " ".repeat(Math.max(1, width - visibleWidth(content) - rightWidth));
|
|
427
|
+
return truncateToWidth(`${content}${content ? gap : ""}${right}`, width, "");
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const LEGACY_MINIMAL_SETTING_IDS = [
|
|
431
|
+
"pi-mini-mode-minimal-thinking-show", "pi-mini-mode-minimal-tools-show", "pi-mini-mode-minimal-output-show",
|
|
432
|
+
"pi-mini-mode-minimal-skills-show", "pi-mini-mode-agent-usage-show", "pi-mini-mode-agent-shortcut-show",
|
|
433
|
+
] as const satisfies ReadonlyArray<keyof MiniLensSettings>;
|
|
434
|
+
|
|
435
|
+
export function isCollapsedReplyChildSetting(id: string): boolean {
|
|
436
|
+
return (LEGACY_MINIMAL_SETTING_IDS as readonly string[]).includes(id);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
export function settingsItems(settings: MiniLensSettings): SettingItem[] {
|
|
440
|
+
const values = ["on", "off"];
|
|
441
|
+
const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder">, string> = {
|
|
442
|
+
"pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
|
|
443
|
+
"pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
|
|
444
|
+
"pi-mini-mode-model-show": COPY.model, "pi-mini-mode-thinking-show": COPY.thinking, "pi-mini-mode-session-tokens-show": COPY.total, "pi-mini-mode-cache-tokens-show": COPY.cached, "pi-mini-mode-ch-show": COPY.cacheHit, "pi-mini-mode-cost-show": COPY.price, "pi-mini-mode-mcp-show": COPY.mcp, "pi-mini-mode-context-show": COPY.context, "pi-mini-mode-context-dots-show": COPY.dots, "pi-mini-mode-context-percent-show": COPY.percent, "pi-mini-mode-speed-show": COPY.speed, "pi-mini-mode-speed-unit-show": COPY.speedUnit, "pi-mini-mode-minimal-show": COPY.minimal, "pi-mini-mode-input-enhancements": COPY.inputEnhancements, "pi-mini-mode-minimal-thinking-show": COPY.showThinking, "pi-mini-mode-minimal-tools-show": COPY.tools, "pi-mini-mode-minimal-output-show": COPY.output, "pi-mini-mode-minimal-skills-show": COPY.skills, "pi-mini-mode-agent-usage-show": COPY.agentUsage, "pi-mini-mode-agent-shortcut-show": COPY.shortcut,
|
|
445
|
+
};
|
|
446
|
+
return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
|
|
447
|
+
id, label: labels[id],
|
|
448
|
+
description: id === "pi-mini-mode-minimal-show" ? COPY.enableMinimalDescription : id === "pi-mini-mode-input-enhancements" ? COPY.inputEnhancementsDescription : id === "pi-mini-mode-session-tokens-show" ? COPY.totalDescription : id === "pi-mini-mode-cache-tokens-show" ? COPY.cachedDescription : id === "pi-mini-mode-ch-show" ? COPY.cacheHitDescription : undefined,
|
|
449
|
+
currentValue: settings[id] ? values[0] : values[1], values,
|
|
450
|
+
}));
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
interface ActiveGeneration {
|
|
454
|
+
firstTokenAt?: number;
|
|
455
|
+
output: number;
|
|
456
|
+
lastSampleAt: number;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** Hide sub-100ms bursts (batched usage) and 1-token completions; they are not a decode rate. */
|
|
460
|
+
export const DECODE_SPEED_MIN_ELAPSED_MS = 100;
|
|
461
|
+
export const DECODE_SPEED_MIN_OUTPUT = 2;
|
|
462
|
+
|
|
463
|
+
/** Decode TPS: provider `usage.output` / seconds after the first output token (excludes TTFT). */
|
|
464
|
+
export function outputSpeed(output: unknown, firstTokenAt: number | undefined, endedAt = Date.now()): number | undefined {
|
|
465
|
+
const tokenCount = finiteNumber(output);
|
|
466
|
+
if (firstTokenAt === undefined || tokenCount === undefined || tokenCount < DECODE_SPEED_MIN_OUTPUT) return undefined;
|
|
467
|
+
const elapsedMs = endedAt - firstTokenAt;
|
|
468
|
+
if (elapsedMs < DECODE_SPEED_MIN_ELAPSED_MS) return undefined;
|
|
469
|
+
const rate = tokenCount / (elapsedMs / 1_000);
|
|
470
|
+
return Number.isFinite(rate) ? rate : undefined;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export interface MinimalTurn {
|
|
474
|
+
question: string;
|
|
475
|
+
shortcutHintUntil?: number;
|
|
476
|
+
usage?: SessionUsage;
|
|
477
|
+
pendingUsage?: UsageLike;
|
|
478
|
+
agentCalls?: AgentCall[];
|
|
479
|
+
subAgents?: Record<string, unknown>[];
|
|
480
|
+
process: string[];
|
|
481
|
+
final?: string;
|
|
482
|
+
replies?: string[];
|
|
483
|
+
running?: boolean;
|
|
484
|
+
/** Wall-clock start of this user-request execution; retained across tool and thinking turns. */
|
|
485
|
+
startedAt?: number;
|
|
486
|
+
thinking?: number;
|
|
487
|
+
awaitingResponse?: boolean;
|
|
488
|
+
waitingTools?: Array<{ id: string; name: string; startedAt: number }>;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const PROCESS_PREVIEW_LIMIT = 180;
|
|
492
|
+
const THINKING_SCROLL_INTERVAL_MS = 80;
|
|
493
|
+
|
|
494
|
+
function contentText(content: unknown): string {
|
|
495
|
+
if (typeof content === "string") return content.trim();
|
|
496
|
+
if (content && typeof content === "object" && "content" in content) return contentText(content.content);
|
|
497
|
+
if (!Array.isArray(content)) return "";
|
|
498
|
+
return content
|
|
499
|
+
.filter((item): item is { type?: string; text?: string } => Boolean(item && typeof item === "object"))
|
|
500
|
+
.filter((item) => item.type === "text" && typeof item.text === "string")
|
|
501
|
+
.map((item) => item.text!.trim())
|
|
502
|
+
.filter(Boolean)
|
|
503
|
+
.join("\n");
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function preview(value: unknown): string {
|
|
507
|
+
let raw = contentText(value);
|
|
508
|
+
if (!raw && value !== undefined) {
|
|
509
|
+
try { raw = JSON.stringify(value) ?? ""; } catch { raw = String(value); }
|
|
510
|
+
}
|
|
511
|
+
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();
|
|
512
|
+
return text.length > PROCESS_PREVIEW_LIMIT ? `${text.slice(0, PROCESS_PREVIEW_LIMIT - 1)}…` : text;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function processText(value: unknown): string {
|
|
516
|
+
return contentText(value) || (value === undefined ? "" : JSON.stringify(value) ?? "");
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** Format an execution duration without losing hours once a long run crosses one. */
|
|
520
|
+
export function formatElapsed(startedAt: number | undefined, now = Date.now()): string {
|
|
521
|
+
const seconds = Math.max(0, Math.floor((now - (startedAt ?? now)) / 1_000));
|
|
522
|
+
const minutes = Math.floor(seconds / 60);
|
|
523
|
+
const remainder = String(seconds % 60).padStart(2, "0");
|
|
524
|
+
return minutes >= 60 ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${remainder}` : `${minutes}:${remainder}`;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
function pushProcess(turn: MinimalTurn | undefined, kind: string, value: unknown): void {
|
|
528
|
+
if (!turn) return;
|
|
529
|
+
const text = processText(value);
|
|
530
|
+
const line = text ? `${kind} ${text}` : kind;
|
|
531
|
+
if (turn.process.at(-1) !== line) turn.process.push(line);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function skillNames(text: string): string[] {
|
|
535
|
+
const names = new Set<string>();
|
|
536
|
+
for (const match of text.matchAll(/\/skill:([\w.-]+)/g)) names.add(match[1]);
|
|
537
|
+
for (const match of text.matchAll(/<skill[^>]*?(?:name=["']([^"']+)["']|>\s*<name>([^<]+))/gi)) names.add((match[1] ?? match[2]).trim());
|
|
538
|
+
return [...names];
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** pi-loop injects its wakeup as a user message; keep its boilerplate out of the compact card. */
|
|
542
|
+
function piLoopSummary(question: string): string | undefined {
|
|
543
|
+
if (!question.startsWith("[pi-loop]")) return;
|
|
544
|
+
const lines = question.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
|
|
545
|
+
const title = lines[0] ?? "[pi-loop]";
|
|
546
|
+
const prompt = lines.find(line => line !== title && !line.startsWith("[Self-paced loop:"));
|
|
547
|
+
return prompt ? `${title} · ${prompt}` : title;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** Rebuild turns on the selected session branch. */
|
|
551
|
+
export function minimalTurnsFromBranch(branch: readonly unknown[]): MinimalTurn[] {
|
|
552
|
+
const turns: MinimalTurn[] = [];
|
|
553
|
+
let turn: MinimalTurn | undefined;
|
|
554
|
+
for (const rawEntry of branch) {
|
|
555
|
+
const entry = rawEntry as { type?: string; message?: { role?: string; content?: unknown; usage?: UsageLike; stopReason?: string; errorMessage?: string } } | null;
|
|
556
|
+
if (entry?.type !== "message" || !entry.message) continue;
|
|
557
|
+
const { role, content } = entry.message;
|
|
558
|
+
if (role === "user") {
|
|
559
|
+
const question = contentText(content);
|
|
560
|
+
turn = { question: question || "[Attachment]", process: [], running: false };
|
|
561
|
+
for (const name of skillNames(question)) pushProcess(turn, "skill", name);
|
|
562
|
+
turns.push(turn);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
if (!turn) continue;
|
|
566
|
+
if (role === "assistant" || role === "toolResult") turn.usage = addUsage(turn.usage ?? EMPTY_USAGE, entry.message.usage);
|
|
567
|
+
if (role === "toolResult") {
|
|
568
|
+
const result = entry.message as { toolCallId?: string; isError?: boolean };
|
|
569
|
+
const call = turn.agentCalls?.find(call => call.id === result.toolCallId);
|
|
570
|
+
if (call) {
|
|
571
|
+
call.state = result.isError ? "error" : "done";
|
|
572
|
+
call.output = contentText(content) || "Call returned (no text output)";
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
pushProcess(turn, "output", content);
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
if (role !== "assistant" || !Array.isArray(content)) continue;
|
|
579
|
+
if (turn.final) (turn.replies ??= []).push(turn.final);
|
|
580
|
+
turn.final = undefined;
|
|
581
|
+
for (const item of content as Array<Record<string, unknown>>) {
|
|
582
|
+
if (!item || typeof item !== "object") continue;
|
|
583
|
+
if (item.type === "thinking") pushProcess(turn, "thinking", item.thinking ?? item.text);
|
|
584
|
+
else if (item.type === "toolCall") {
|
|
585
|
+
if (item.name) {
|
|
586
|
+
(turn.agentCalls ??= []).push(agentCall(String(item.id), String(item.name), item.arguments ?? item.input));
|
|
587
|
+
pushProcess(turn, "call", String(item.id));
|
|
588
|
+
const path = (item.arguments as { path?: string })?.path;
|
|
589
|
+
if (path && /(?:^|\/)SKILL\.md$/i.test(path)) pushProcess(turn, "skill", path.split("/").at(-2));
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
pushProcess(turn, `tool ${String(item.name ?? "")}`.trim(), item.arguments ?? item.input);
|
|
593
|
+
const path = (item.arguments as { path?: unknown })?.path;
|
|
594
|
+
if (typeof path === "string" && /(?:^|\/)SKILL\.md$/i.test(path)) pushProcess(turn, "skill", path.split("/").at(-2) ?? path);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
const text = contentText(content);
|
|
598
|
+
const hasTools = content.some((item) => item?.type === "toolCall");
|
|
599
|
+
if (hasTools) {
|
|
600
|
+
if (text) pushProcess(turn, "output", text);
|
|
601
|
+
turn.final = undefined;
|
|
602
|
+
} else turn.final = text || undefined;
|
|
603
|
+
if (entry.message.stopReason === "error" || entry.message.stopReason === "aborted") {
|
|
604
|
+
turn.final = [entry.message.stopReason === "aborted" ? "Execution aborted" : "Execution failed", entry.message.errorMessage, turn.final].filter(Boolean).join("\n");
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return turns;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function visibleMinimalTurns(settings: MiniLensSettings, turns: MinimalTurn[]): MinimalTurn[] {
|
|
611
|
+
return turns.map((turn) => {
|
|
612
|
+
let thinking: number | undefined;
|
|
613
|
+
let visibleCount = 0;
|
|
614
|
+
const process = turn.process.filter((line, index) => {
|
|
615
|
+
const visible = line.startsWith("thinking ") ? settings["pi-mini-mode-minimal-thinking-show"]
|
|
616
|
+
: /^(tool|call) /.test(line) ? settings["pi-mini-mode-minimal-tools-show"]
|
|
617
|
+
: line.startsWith("output ") ? settings["pi-mini-mode-minimal-output-show"]
|
|
618
|
+
: line.startsWith("skill ") ? settings["pi-mini-mode-minimal-skills-show"] : true;
|
|
619
|
+
if (visible) {
|
|
620
|
+
if (index === turn.thinking) thinking = visibleCount;
|
|
621
|
+
visibleCount++;
|
|
622
|
+
}
|
|
623
|
+
return visible;
|
|
624
|
+
});
|
|
625
|
+
return {
|
|
626
|
+
...turn,
|
|
627
|
+
thinking,
|
|
628
|
+
awaitingResponse: turn.awaitingResponse && settings["pi-mini-mode-minimal-thinking-show"],
|
|
629
|
+
agentCalls: settings["pi-mini-mode-minimal-tools-show"] ? turn.agentCalls : [],
|
|
630
|
+
process,
|
|
631
|
+
};
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showShortcut: (turn: MinimalTurn) => boolean = () => true, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text) {
|
|
636
|
+
const markdown = (text: string, width: number, process = false) => renderMinimalMarkdown(text, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
|
|
637
|
+
{ color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(diagramMarkdown(source, available)));
|
|
638
|
+
const surface = (rows: string[], width: number, user: boolean, selected = -1, expanded = false) => {
|
|
639
|
+
const padding = Math.min(2, Math.floor((width - 1) / 2));
|
|
640
|
+
return ["", ...rows, ""].map((row, index) => {
|
|
641
|
+
const line = truncateToWidth(" ".repeat(padding) + row, width, "");
|
|
642
|
+
return minimalSurface(theme, line + " ".repeat(Math.max(0, width - visibleWidth(line))), user, expanded && index === selected);
|
|
643
|
+
});
|
|
644
|
+
};
|
|
645
|
+
let agentExpiry = Infinity;
|
|
646
|
+
const expandedPrompts = new Map<number, string>();
|
|
647
|
+
const expandedSubagents = new Set<string>();
|
|
648
|
+
const expandedTools = new Set<string>();
|
|
649
|
+
const expandedThinking = new Set<string>();
|
|
650
|
+
let pinnedToolId: string | undefined;
|
|
651
|
+
let pinnedTool: { id: string; y: number; line: string } | undefined;
|
|
652
|
+
let pinnedSubagentId: string | undefined;
|
|
653
|
+
let pinnedSubagent: { id: string; y: number; line: string; autoScroll?: boolean } | undefined;
|
|
654
|
+
let toolControls: Array<{ id: string; y: number; width: number; title: string }> = [];
|
|
655
|
+
let hoveredTool: typeof toolControls[number] | undefined;
|
|
656
|
+
const clearHover = () => { const changed = !!hoveredTool; hoveredTool = undefined; return changed; };
|
|
657
|
+
const toggleTool = (id: string) => {
|
|
658
|
+
if (id.startsWith("thinking:")) {
|
|
659
|
+
const present = getTurns().some((turn, turnIndex) => turn.process.some((entry, processIndex) =>
|
|
660
|
+
entry.startsWith("thinking") && `thinking:${turnIndex}:${processIndex}` === id));
|
|
661
|
+
if (!present) return;
|
|
662
|
+
if (expandedThinking.has(id)) expandedThinking.delete(id);
|
|
663
|
+
else expandedThinking.add(id);
|
|
664
|
+
clearHover();
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
if (!getTurns().some(turn => turn.agentCalls?.some(call => call.id === id && !isAgentTool(call.tool ?? call.name)))) return;
|
|
668
|
+
if (expandedTools.has(id)) {
|
|
669
|
+
expandedTools.delete(id);
|
|
670
|
+
if (pinnedToolId === id) pinnedToolId = undefined;
|
|
671
|
+
} else {
|
|
672
|
+
expandedTools.add(id);
|
|
673
|
+
// Only the latest opened tool owns the sticky heading; others stay open.
|
|
674
|
+
pinnedToolId = id;
|
|
675
|
+
}
|
|
676
|
+
clearHover();
|
|
677
|
+
};
|
|
678
|
+
const toggleSubagent = (runId: string) => {
|
|
679
|
+
if (!subagentControls.some(control => control.runId === runId)) return;
|
|
680
|
+
if (expandedSubagents.has(runId)) {
|
|
681
|
+
expandedSubagents.delete(runId);
|
|
682
|
+
if (pinnedSubagentId === runId) pinnedSubagentId = undefined;
|
|
683
|
+
} else {
|
|
684
|
+
expandedSubagents.add(runId);
|
|
685
|
+
// SubAgent details open in place; sticky heading engages only after scrolling.
|
|
686
|
+
pinnedSubagentId = runId;
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
let promptControls: Array<{ index: number; question: string; y: number; x: number; width: number; label: string }> = [];
|
|
690
|
+
let subagentControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
|
|
691
|
+
let noticeRegions: Array<{ y: number; rows: NoticeRows }> = [];
|
|
692
|
+
const togglePrompt = (index: number, question: string) => {
|
|
693
|
+
if (getTurns()[index]?.question !== question) return;
|
|
694
|
+
if (expandedPrompts.get(index) === question) expandedPrompts.delete(index);
|
|
695
|
+
else expandedPrompts.set(index, question);
|
|
696
|
+
};
|
|
697
|
+
return {
|
|
698
|
+
invalidate() { clearHover(); },
|
|
699
|
+
clearHover,
|
|
700
|
+
pinnedTool: () => pinnedTool,
|
|
701
|
+
unpinTool: () => { pinnedToolId = undefined; pinnedTool = undefined; },
|
|
702
|
+
pinnedSubagent: () => pinnedSubagent,
|
|
703
|
+
unpinSubagent: () => { pinnedSubagentId = undefined; pinnedSubagent = undefined; },
|
|
704
|
+
toolChoices: () => toolControls.map(control => ({ ...control, expanded: expandedTools.has(control.id) || expandedThinking.has(control.id) })),
|
|
705
|
+
toggleTool,
|
|
706
|
+
toggleSubagent,
|
|
707
|
+
agentExpiry: () => agentExpiry,
|
|
708
|
+
promptChoices: () => promptControls.map(control => ({ ...control })),
|
|
709
|
+
togglePrompt,
|
|
710
|
+
handleMouse(event: TuiMouseEvent) {
|
|
711
|
+
const tool = toolControls.find(control => event.y === control.y && event.x >= 2 && event.x < Math.min(5, control.width));
|
|
712
|
+
if (event.type === "move") {
|
|
713
|
+
const next = !event.shift && !event.ctrl && !event.alt ? tool : undefined;
|
|
714
|
+
if (hoveredTool?.id !== next?.id) {
|
|
715
|
+
hoveredTool = next;
|
|
716
|
+
return { handled: true, render: true };
|
|
717
|
+
}
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
if (event.type === "wheel" || event.type === "drag") { clearHover(); return; }
|
|
721
|
+
if (tool && event.button === "left" && !event.shift && !event.ctrl && !event.alt) {
|
|
722
|
+
if (event.type === "press") return { handled: true };
|
|
723
|
+
if (event.type === "click") {
|
|
724
|
+
toggleTool(tool.id);
|
|
725
|
+
return { handled: true, render: true };
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
if (event.button !== "left" || event.shift || event.ctrl || event.alt) return;
|
|
729
|
+
const control = promptControls.find(control => event.y === control.y && event.x >= control.x && event.x < control.x + control.width);
|
|
730
|
+
if (control && (event.clickCount ?? 1) === 1) {
|
|
731
|
+
if (event.type === "press") return { handled: true };
|
|
732
|
+
if (event.type === "click") {
|
|
733
|
+
togglePrompt(control.index, control.question);
|
|
734
|
+
return { handled: true, render: true };
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
const sub = subagentControls.find(control => event.y === control.y && event.x >= 0 && event.x < control.width);
|
|
738
|
+
if (sub) {
|
|
739
|
+
if (event.type === "press") return { handled: true };
|
|
740
|
+
if (event.type === "click") {
|
|
741
|
+
toggleSubagent(sub.runId);
|
|
742
|
+
return { handled: true, render: true };
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if ((event.clickCount ?? 1) !== 1) return;
|
|
746
|
+
const region = noticeRegions.find(region => event.y >= region.y && event.y < region.y + region.rows.length);
|
|
747
|
+
return region?.rows.handleMouse?.({ ...event, y: event.y - region.y });
|
|
748
|
+
},
|
|
749
|
+
render(width: number, notices?: TurnNotices): string[] {
|
|
750
|
+
promptControls = [];
|
|
751
|
+
toolControls = [];
|
|
752
|
+
pinnedTool = undefined;
|
|
753
|
+
pinnedSubagent = undefined;
|
|
754
|
+
subagentControls = [];
|
|
755
|
+
noticeRegions = [];
|
|
756
|
+
agentExpiry = Infinity;
|
|
757
|
+
if (width <= 0) { clearHover(); return []; }
|
|
758
|
+
const turns = getTurns();
|
|
759
|
+
const toolIds = new Set(turns.flatMap(turn => (turn.agentCalls ?? []).map(call => call.id)));
|
|
760
|
+
for (const id of expandedTools) if (!toolIds.has(id)) expandedTools.delete(id);
|
|
761
|
+
const thinkingIds = new Set(turns.flatMap((turn, turnIndex) => turn.process.flatMap((entry, processIndex) =>
|
|
762
|
+
entry.startsWith("thinking") ? [`thinking:${turnIndex}:${processIndex}`] : [])));
|
|
763
|
+
for (const id of expandedThinking) if (!thinkingIds.has(id)) expandedThinking.delete(id);
|
|
764
|
+
const inner = Math.max(1, width - 2 * Math.min(2, Math.floor((width - 1) / 2)));
|
|
765
|
+
const lines: string[] = [];
|
|
766
|
+
// An open heading wears the same full-width selectedBg band as an expanded SubAgent row.
|
|
767
|
+
const bandHeading = (row: string, open: boolean) => open
|
|
768
|
+
? paintExpandedHeading(theme, row + " ".repeat(Math.max(0, width - visibleWidth(row)))) : row;
|
|
769
|
+
for (const [index, turn] of turns.entries()) {
|
|
770
|
+
if (index > 0) lines.push("");
|
|
771
|
+
if (expandedPrompts.has(index) && expandedPrompts.get(index) !== turn.question) expandedPrompts.delete(index);
|
|
772
|
+
const questionRows = markdown(turn.question, inner);
|
|
773
|
+
const loopSummary = piLoopSummary(turn.question);
|
|
774
|
+
const expanded = expandedPrompts.get(index) === turn.question;
|
|
775
|
+
// A fence is one visual unit; slicing it mid-block looks like raw source.
|
|
776
|
+
const keepFence = !loopSummary && isFencedMarkdown(turn.question);
|
|
777
|
+
// Loop wakeups are system-generated user messages. Collapse them even when
|
|
778
|
+
// their short prompt would otherwise fit the normal four-row allowance.
|
|
779
|
+
const userRows = expanded || keepFence ? [...questionRows] : loopSummary ? markdown(loopSummary, inner) : questionRows.slice(0, 4);
|
|
780
|
+
let controlIndex = -1;
|
|
781
|
+
if (!keepFence && (loopSummary || questionRows.length > 4)) {
|
|
782
|
+
const label = expanded ? "▴ 收起" : loopSummary ? "▾ 展开" : `▾ 展开 (${questionRows.length} 行)`;
|
|
783
|
+
const control = truncateToWidth(label, inner, "");
|
|
784
|
+
promptControls.push({ index, question: turn.question, y: lines.length + 1 + userRows.length,
|
|
785
|
+
x: 0, width, label });
|
|
786
|
+
userRows.push(theme.fg("accent", control) + theme.fg("muted", truncateToWidth(" · /pi-mini-mode-prompts", Math.max(0, inner - visibleWidth(control)), "")));
|
|
787
|
+
// The expanded control is this message's heading, so it keeps the band in place of the user surface.
|
|
788
|
+
controlIndex = userRows.length;
|
|
789
|
+
}
|
|
790
|
+
lines.push(...surface(userRows, width, true, controlIndex, expanded));
|
|
791
|
+
const entries = turn.process.flatMap((entry, processIndex) => {
|
|
792
|
+
if (entry.startsWith("call ")) {
|
|
793
|
+
const call = turn.agentCalls?.find(call => call.id === entry.slice(5));
|
|
794
|
+
if (call && isAgentTool(call.tool ?? call.name) && !isExpanded()) return [];
|
|
795
|
+
const display = call && agentCallDisplay(call);
|
|
796
|
+
return call && display ? [{ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`.trim(), detail: display.detail, state: call.state, id: call.id, thinking: false }] : [];
|
|
797
|
+
}
|
|
798
|
+
const part = entry.match(/^(tool|output|thinking|skill)(?:\s+|$)([\s\S]*)/);
|
|
799
|
+
const thinking = part?.[1] === "thinking";
|
|
800
|
+
const activeThinking = thinking && turn.running && turn.thinking === processIndex;
|
|
801
|
+
const label = ({ tool: "Tool", output: "Output", thinking: "Thinking", skill: "Skill" } as Record<string, string>)[part?.[1] ?? ""] ?? "Process";
|
|
802
|
+
return [{ title: `${label} ${part?.[2] ?? entry}`, detail: part?.[2] ?? entry, state: activeThinking ? "running" : "done", id: thinking ? `thinking:${index}:${processIndex}` : "", thinking }];
|
|
803
|
+
});
|
|
804
|
+
// Older in-memory turns may predate call markers.
|
|
805
|
+
for (const call of turn.agentCalls ?? []) {
|
|
806
|
+
if (isAgentTool(call.tool ?? call.name) && !isExpanded()) continue;
|
|
807
|
+
const display = agentCallDisplay(call);
|
|
808
|
+
if (!entries.some(entry => entry.id === call.id)) entries.push({ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`, detail: display.detail, state: call.state, id: call.id, thinking: false });
|
|
809
|
+
}
|
|
810
|
+
const agentTurnControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
|
|
811
|
+
const agents = liveAgentView(turn.subAgents ?? [], theme, width, subAgentsExpanded(), true, agentDeadlines, Date.now(), expandedSubagents, agentTurnControls);
|
|
812
|
+
if (entries.length || turn.running || turn.usage || agents.total) {
|
|
813
|
+
const expanded = isExpanded();
|
|
814
|
+
const shown = expanded ? entries : entries.filter(entry => !entry.thinking || entry.state === "running" || expandedThinking.has(entry.id)).slice(-6);
|
|
815
|
+
const done = entries.filter(entry => entry.state === "done").length;
|
|
816
|
+
const progressHeader = theme.bold(theme.fg("text", "Agent")) + (entries.length ? theme.fg("muted", ` · ${done}/${entries.length}`) : "")
|
|
817
|
+
+ (agents.total ? theme.bold(theme.fg("text", " Subagent")) + theme.fg("muted", ` ${agents.done + agents.errors}/${agents.total}`)
|
|
818
|
+
+ (agents.errors ? theme.fg("error", ` · ${agents.errors} failed`) : "") : "");
|
|
819
|
+
const header = progressHeader + theme.fg("muted", showShortcut(turn) ? " · Ctrl+O" : "");
|
|
820
|
+
const usage = addUsage({ ...EMPTY_USAGE, ...turn.usage, cost: turn.usage?.cost ?? 0 }, turn.pendingUsage);
|
|
821
|
+
const hasUsage = usage.totalTokens > 0 || usage.cacheRead > 0;
|
|
822
|
+
const totals = hasUsage
|
|
823
|
+
? theme.fg("text", "S") + theme.fg("muted", ` ${formatTokens(usage.totalTokens)} / `)
|
|
824
|
+
+ theme.fg("text", "C") + theme.fg("muted", ` ${formatTokens(usage.cacheRead)}`)
|
|
825
|
+
: "";
|
|
826
|
+
const totalsWidth = visibleWidth(totals);
|
|
827
|
+
if (hasUsage && showUsage() && width >= totalsWidth + visibleWidth(agents.total ? progressHeader : "Agent") + 1) {
|
|
828
|
+
const left = truncateToWidth(header, width - totalsWidth - 1, "");
|
|
829
|
+
lines.push("", left + " ".repeat(width - visibleWidth(left) - totalsWidth) + totals);
|
|
830
|
+
} else {
|
|
831
|
+
lines.push("", truncateToWidth(header, width));
|
|
832
|
+
}
|
|
833
|
+
if (!shown.length && turn.running && turn.awaitingResponse && !turn.final) {
|
|
834
|
+
const prefix = theme.fg("dim", `${agents.rows.length ? "├─" : "└─"} `) + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold("Thinking")) + theme.fg("success", ` ${formatElapsed(turn.startedAt)}`) + " ";
|
|
835
|
+
lines.push(truncateToWidth(prefix + theme.fg("text", "…"), width, ""));
|
|
836
|
+
}
|
|
837
|
+
shown.forEach((entry, row) => {
|
|
838
|
+
const waiting = turn.waitingTools?.find(tool => tool.id === entry.id);
|
|
839
|
+
const title = waiting && !entry.title.startsWith("Control ") ? `${waiting.name} running · waiting ${Math.max(0, Math.floor((Date.now() - waiting.startedAt) / 1000))}s` : entry.title;
|
|
840
|
+
const text = title.split(/\r?\n/).find(line => line.trim())?.replace(/\s+/g, " ").trim() ?? "";
|
|
841
|
+
const split = text.indexOf(" ");
|
|
842
|
+
const label = split < 0 ? text : text.slice(0, split);
|
|
843
|
+
const body = split < 0 ? "" : text.slice(split + 1);
|
|
844
|
+
const activeThinking = entry.thinking && entry.state === "running";
|
|
845
|
+
const thinkingElapsed = entry.thinking ? theme.fg(activeThinking ? "success" : "muted", ` ${formatElapsed(turn.startedAt)}`) : "";
|
|
846
|
+
const call = turn.agentCalls?.find(call => call.id === entry.id && !isAgentTool(call.tool ?? call.name));
|
|
847
|
+
const controlId = call?.id ?? (entry.thinking ? entry.id : "");
|
|
848
|
+
const open = call ? expandedTools.has(call.id) : !!(entry.thinking && expandedThinking.has(entry.id));
|
|
849
|
+
const identity = open ? "accent" : "text";
|
|
850
|
+
const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + " ";
|
|
851
|
+
if (controlId && width >= 4) toolControls.push({ id: controlId, y: lines.length, width, title: text });
|
|
852
|
+
if (hoveredTool?.id === controlId && (hoveredTool.y !== lines.length || hoveredTool.width !== width)) clearHover();
|
|
853
|
+
const status = entry.state === "error" ? "✕" : entry.state === "running" ? runningGlyph() : "●";
|
|
854
|
+
const arrow = !!controlId && (open || hoveredTool?.id === controlId);
|
|
855
|
+
const keepStatus = entry.state === "running" || (open && entry.state === "error");
|
|
856
|
+
const glyph = arrow ? (open ? "▼" : "▶") + (keepStatus ? ` ${status}` : "") : status;
|
|
857
|
+
const glyphColor = entry.state === "error" ? "error" : entry.state === "running" || arrow ? "accent" : "muted";
|
|
858
|
+
const last = row === shown.length - 1 && !agents.rows.length;
|
|
859
|
+
const prefix = theme.fg(open ? "accent" : "dim", last ? "└─ " : "├─ ") + theme.fg(glyphColor, glyph) + " " + summary;
|
|
860
|
+
if (activeThinking) {
|
|
861
|
+
const renderedBody = markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim();
|
|
862
|
+
const bodyWidth = Math.max(0, width - visibleWidth(prefix));
|
|
863
|
+
const overflow = Math.max(0, visibleWidth(renderedBody) - bodyWidth);
|
|
864
|
+
const offset = overflow ? Math.max(0, Math.floor((Date.now() - (turn.startedAt ?? Date.now())) / THINKING_SCROLL_INTERVAL_MS) % (overflow + 9) - 4) : 0;
|
|
865
|
+
lines.push(bandHeading(truncateToWidth(prefix + (bodyWidth ? sliceByColumn(renderedBody, Math.min(overflow, offset), bodyWidth, true) : ""), width, ""), open));
|
|
866
|
+
} else if (label === "Output") {
|
|
867
|
+
// Wrapped output hangs under the body column and keeps the tree rail to the next sibling.
|
|
868
|
+
const indent = visibleWidth(prefix);
|
|
869
|
+
const wrapped = markdown(body, Math.max(1, width - indent), true);
|
|
870
|
+
const rail = !last && indent > 0 ? theme.fg("dim", "│") + " ".repeat(indent - 1) : " ".repeat(indent);
|
|
871
|
+
lines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
|
|
872
|
+
for (const extra of wrapped.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
|
|
873
|
+
} else {
|
|
874
|
+
lines.push(bandHeading(truncateToWidth(prefix + (entry.thinking ? markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim() : theme.fg(open ? "accent" : "muted", body)), width, controlId ? "" : "…"), open));
|
|
875
|
+
}
|
|
876
|
+
if (open && call && call.id === pinnedToolId) pinnedTool = { id: call.id, y: lines.length - 1, line: lines.at(-1)! };
|
|
877
|
+
if (open && call) {
|
|
878
|
+
// ponytail: saved text only; native view retains images, args and custom renderers.
|
|
879
|
+
const output = stripVTControlCharacters(call.output ?? "").replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
|
|
880
|
+
const rail = width > 5 ? (last ? " " : theme.fg("accent", "│ ")) : "";
|
|
881
|
+
const detailWidth = Math.max(1, width - visibleWidth(rail));
|
|
882
|
+
const details = new Text(output || (entry.state === "running" ? "等待工具文本结果…" : "无文本结果"), 0, 0).render(detailWidth);
|
|
883
|
+
lines.push(...details.map(line => truncateToWidth(rail + theme.fg("muted", line), width, "")));
|
|
884
|
+
} else if (open && entry.thinking) {
|
|
885
|
+
const rail = width > 5 ? (last ? " " : theme.fg("accent", "│ ")) : "";
|
|
886
|
+
const detailWidth = Math.max(1, width - visibleWidth(rail));
|
|
887
|
+
lines.push(...markdown(entry.detail, detailWidth, true).map(line => truncateToWidth(rail + line, width, "")));
|
|
888
|
+
} else if (expanded && entry.state === "error" && entry.detail) {
|
|
889
|
+
const rail = last ? " " : theme.fg("dim", "│ ");
|
|
890
|
+
const details = entry.detail.split(/\r?\n/).filter(line => line.trim());
|
|
891
|
+
// ponytail: four diagnostic lines; full output remains in the native transcript.
|
|
892
|
+
lines.push(...details.slice(1, 5).map(line => truncateToWidth(rail + theme.fg("muted", line), width)));
|
|
893
|
+
if (details.length > 5) lines.push(truncateToWidth(rail + theme.fg("muted", `… +${details.length - 5} lines · /pi-mini-mode-minimal off`), width));
|
|
894
|
+
}
|
|
895
|
+
});
|
|
896
|
+
const agentStartY = lines.length;
|
|
897
|
+
for (const c of agentTurnControls) {
|
|
898
|
+
const control = { ...c, y: agentStartY + c.y };
|
|
899
|
+
subagentControls.push(control);
|
|
900
|
+
if (c.runId === pinnedSubagentId) pinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
|
|
901
|
+
}
|
|
902
|
+
lines.push(...agents.rows);
|
|
903
|
+
}
|
|
904
|
+
for (const reply of turn.replies ?? []) lines.push("", ...markdown(reply, width));
|
|
905
|
+
if (turn.final) lines.push("", ...markdown(turn.final, width));
|
|
906
|
+
const noticeRows = notices?.get(index) ?? [];
|
|
907
|
+
noticeRegions.push({ y: lines.length, rows: noticeRows });
|
|
908
|
+
lines.push(...noticeRows);
|
|
909
|
+
}
|
|
910
|
+
if (hoveredTool && !toolControls.some(control => control.id === hoveredTool!.id)) clearHover();
|
|
911
|
+
for (const deadline of agentDeadlines.values()) if (deadline > Date.now()) agentExpiry = Math.min(agentExpiry, deadline);
|
|
912
|
+
return lines;
|
|
913
|
+
},
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
export default function (pi: ExtensionAPI) {
|
|
918
|
+
attachFooterTidy(pi);
|
|
919
|
+
attachTitlePlain(pi);
|
|
920
|
+
let refreshFooter: (() => void) | undefined;
|
|
921
|
+
let refreshMinimal: (() => void) | undefined;
|
|
922
|
+
let processExpanded = false;
|
|
923
|
+
let nativeOutput = false;
|
|
924
|
+
let subAgentsExpanded = false;
|
|
925
|
+
let shortcutTimer: ReturnType<typeof setTimeout> | undefined;
|
|
926
|
+
let waitingTimer: ReturnType<typeof setInterval> | undefined;
|
|
927
|
+
let unsubscribeMinimalInput: (() => void) | undefined;
|
|
928
|
+
let minimalTui: { getFocusedComponent?(): unknown } | undefined;
|
|
929
|
+
let restoreAgentWidgets: (() => void) | undefined;
|
|
930
|
+
let restoreTranscript: (() => void) | undefined;
|
|
931
|
+
let persistAgentStatuses: (() => void) | undefined;
|
|
932
|
+
let promptView: ReturnType<typeof minimalOutputComponent> | undefined;
|
|
933
|
+
let lastAttachMode: string | undefined;
|
|
934
|
+
let remountQueued = false;
|
|
935
|
+
let settingsWeb: Awaited<ReturnType<typeof import("../lib/settings-web.ts").startSettingsWeb>> | undefined;
|
|
936
|
+
let settingsWebOpening: Promise<void> | undefined;
|
|
937
|
+
let settingsWebGeneration = 0;
|
|
938
|
+
const agentDeadlines = new Map<string, number>();
|
|
939
|
+
let minimalTurns: MinimalTurn[] = [];
|
|
940
|
+
let activeMinimalTurn: MinimalTurn | undefined;
|
|
941
|
+
let pendingMinimalFinal = "";
|
|
942
|
+
const minimalMessageIndices = new Map<number, number>();
|
|
943
|
+
let speed: number | undefined;
|
|
944
|
+
let mcpCount: number | undefined;
|
|
945
|
+
let activeGeneration: ActiveGeneration | undefined;
|
|
946
|
+
let activeUIPrompt: { kind: string; title?: string } | undefined;
|
|
947
|
+
const toolStarts = new Map<string, number>();
|
|
948
|
+
const minimalToolOutputIndices = new Map<string, number>();
|
|
949
|
+
let speedTimer: ReturnType<typeof setInterval> | undefined;
|
|
950
|
+
let settings: MiniLensSettings = { ...DEFAULT_SETTINGS };
|
|
951
|
+
let cleanupInputEnhancements: InputEnhancementsCleanup | undefined;
|
|
952
|
+
let messageCwd = process.cwd();
|
|
953
|
+
const messageLinks = (text: string) => settings["pi-mini-mode-input-enhancements"] ? linkMessageFiles(text, messageCwd) : text;
|
|
954
|
+
pi.registerMarkdownTransformer?.(messageLinks);
|
|
955
|
+
let saveChain: Promise<void> = Promise.resolve();
|
|
956
|
+
const configPath = settingsPath();
|
|
957
|
+
|
|
958
|
+
const refresh = () => refreshFooter?.();
|
|
959
|
+
const refreshMinimalOutput = () => refreshMinimal?.();
|
|
960
|
+
const mountMinimalOutput = (ctx: ExtensionContext) => {
|
|
961
|
+
persistAgentStatuses = undefined;
|
|
962
|
+
if (shortcutTimer) clearTimeout(shortcutTimer);
|
|
963
|
+
shortcutTimer = undefined;
|
|
964
|
+
if (waitingTimer) clearInterval(waitingTimer);
|
|
965
|
+
waitingTimer = undefined;
|
|
966
|
+
unsubscribeMinimalInput?.();
|
|
967
|
+
unsubscribeMinimalInput = undefined;
|
|
968
|
+
restoreTranscript?.();
|
|
969
|
+
restoreTranscript = undefined;
|
|
970
|
+
restoreAgentWidgets?.();
|
|
971
|
+
restoreAgentWidgets = undefined;
|
|
972
|
+
promptView = undefined;
|
|
973
|
+
if (settings["pi-mini-mode-minimal-show"] && ctx.mode === "tui") unsubscribeMinimalInput = ctx.ui.onTerminalInput?.((data) => {
|
|
974
|
+
const nativeKey = matchesKey(data, "ctrl+alt+o");
|
|
975
|
+
const subAgentKey = matchesKey(data, "ctrl+s");
|
|
976
|
+
if (!nativeKey && focusedSelectorOwnsKeys(minimalTui)) return;
|
|
977
|
+
if (!nativeKey && (!restoreTranscript || (!subAgentKey && !matchesKey(data, "ctrl+o")))) return;
|
|
978
|
+
// Input listeners run before Pi filters Kitty release/repeat events.
|
|
979
|
+
if (isKeyRelease(data) || isKeyRepeat(data)) return { consume: true };
|
|
980
|
+
if (nativeKey) {
|
|
981
|
+
nativeOutput = !nativeOutput;
|
|
982
|
+
mountMinimalOutput(ctx);
|
|
983
|
+
} else if (subAgentKey) subAgentsExpanded = !subAgentsExpanded;
|
|
984
|
+
else processExpanded = !processExpanded;
|
|
985
|
+
refreshMinimalOutput();
|
|
986
|
+
return { consume: true };
|
|
987
|
+
});
|
|
988
|
+
if (nativeOutput || !settings["pi-mini-mode-minimal-show"] || ctx.mode !== "tui") {
|
|
989
|
+
minimalTui = undefined;
|
|
990
|
+
lastAttachMode = undefined;
|
|
991
|
+
ctx.ui.setWidget?.("pi-mini-mode-minimal-output", undefined);
|
|
992
|
+
refreshMinimalOutput();
|
|
993
|
+
refreshMinimal = undefined;
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
ctx.ui.setWidget("pi-mini-mode-minimal-output", (tui, theme) => {
|
|
997
|
+
minimalTui = tui as unknown as { getFocusedComponent?(): unknown };
|
|
998
|
+
refreshMinimal = () => tui.requestRender();
|
|
999
|
+
// Retain children under their originating user turn, including while idle,
|
|
1000
|
+
// after a follow-up user message, and when rebuilding a saved session.
|
|
1001
|
+
const sessionKey = ctx.sessionManager.getSessionFile?.() ?? ctx.sessionManager.getSessionId?.() ?? "";
|
|
1002
|
+
let statuses = savedAgentStatuses(ctx.sessionManager.getBranch());
|
|
1003
|
+
const persisted = new Map(statuses.map(status => [String(status.runId), JSON.stringify(status)]));
|
|
1004
|
+
const saveStatuses = () => {
|
|
1005
|
+
for (const status of statuses) {
|
|
1006
|
+
const value = JSON.stringify(status);
|
|
1007
|
+
const key = String(status.runId);
|
|
1008
|
+
if (persisted.get(key) === value) continue;
|
|
1009
|
+
pi.appendEntry(AGENT_STATUS_ENTRY, status);
|
|
1010
|
+
persisted.set(key, value);
|
|
1011
|
+
}
|
|
1012
|
+
};
|
|
1013
|
+
statuses = retainAgentStatuses(statuses, readAgentStatuses(sessionKey));
|
|
1014
|
+
persistAgentStatuses = saveStatuses;
|
|
1015
|
+
saveStatuses();
|
|
1016
|
+
let lastStatusRead = Date.now();
|
|
1017
|
+
const supervisorNotices = new Map<string, { notice: any; messages: any[] }>();
|
|
1018
|
+
const handledRunIds = new Set<string>();
|
|
1019
|
+
const turnsWithAgents = () => {
|
|
1020
|
+
// A status directory is session-wide. Never attach an unclaimed snapshot
|
|
1021
|
+
// to the newest turn: an older async child may report after a follow-up.
|
|
1022
|
+
const assigned = agentStatusesByTurn(statuses, minimalTurns);
|
|
1023
|
+
handledRunIds.clear();
|
|
1024
|
+
return minimalTurns.map((turn, index) => {
|
|
1025
|
+
const turnAgents = assigned.get(index) ?? [];
|
|
1026
|
+
for (const status of turnAgents) {
|
|
1027
|
+
if (status.runId) handledRunIds.add(String(status.runId));
|
|
1028
|
+
if (status.parentWorkflowRunId) handledRunIds.add(String(status.parentWorkflowRunId));
|
|
1029
|
+
}
|
|
1030
|
+
const withNotices = agentChildren(turnAgents).map(sub => {
|
|
1031
|
+
if (sub.runId) handledRunIds.add(String(sub.runId));
|
|
1032
|
+
if (sub.parentWorkflowRunId) handledRunIds.add(String(sub.parentWorkflowRunId));
|
|
1033
|
+
const n = supervisorNotices.get(String(sub.runId));
|
|
1034
|
+
return n ? { ...sub, notice: n.notice, noticeMessages: n.messages } : sub;
|
|
1035
|
+
});
|
|
1036
|
+
return { ...turn, subAgents: withNotices };
|
|
1037
|
+
});
|
|
1038
|
+
};
|
|
1039
|
+
const view = minimalOutputComponent(theme, () => visibleMinimalTurns(settings, turnsWithAgents()), () => processExpanded, turn => settings["pi-mini-mode-agent-shortcut-show"] && Date.now() < (turn.shortcutHintUntil ?? 0), () => settings["pi-mini-mode-agent-usage-show"], () => subAgentsExpanded, agentDeadlines, messageLinks);
|
|
1040
|
+
const hintRemaining = (activeMinimalTurn?.shortcutHintUntil ?? 0) - Date.now();
|
|
1041
|
+
if (hintRemaining > 0) {
|
|
1042
|
+
shortcutTimer = setTimeout(() => tui.requestRender(), hintRemaining);
|
|
1043
|
+
shortcutTimer.unref();
|
|
1044
|
+
}
|
|
1045
|
+
// Native info notifications use dim; warning/error notifications retain
|
|
1046
|
+
// their position in the transcript. No plugin names or message matching.
|
|
1047
|
+
const dimPrefix = theme.fg("dim", "\u0000").split("\u0000")[0];
|
|
1048
|
+
// Transcript hover wrappers must surround the compact widget handlers;
|
|
1049
|
+
// unmount in reverse order so neither adapter resurrects stale handlers.
|
|
1050
|
+
restoreAgentWidgets = attachAgentWidgets(tui, theme, () => subAgentsExpanded, undefined, true);
|
|
1051
|
+
restoreTranscript = attachTranscript(tui, view, {
|
|
1052
|
+
turnCount: () => minimalTurns.length,
|
|
1053
|
+
supervisor: {
|
|
1054
|
+
theme,
|
|
1055
|
+
expanded: () => processExpanded,
|
|
1056
|
+
handledRunIds: () => handledRunIds,
|
|
1057
|
+
onNotices: groups => {
|
|
1058
|
+
let changed = false;
|
|
1059
|
+
for (const group of groups.values()) {
|
|
1060
|
+
const runId = String(group.notice.runId ?? "");
|
|
1061
|
+
if (runId) {
|
|
1062
|
+
const prev = supervisorNotices.get(runId);
|
|
1063
|
+
if (!prev || JSON.stringify(prev) !== JSON.stringify({ notice: group.notice, messages: group.messages })) {
|
|
1064
|
+
supervisorNotices.set(runId, { notice: group.notice, messages: group.messages });
|
|
1065
|
+
changed = true;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
if (changed) {
|
|
1070
|
+
// Preserve notices inside their owning snapshot as well as Pi's original message.
|
|
1071
|
+
statuses = statuses.map(status => {
|
|
1072
|
+
const children = agentChildren([status]).map(child => {
|
|
1073
|
+
const notice = supervisorNotices.get(String(child.runId));
|
|
1074
|
+
return notice ? { ...child, notice: notice.notice, noticeMessages: notice.messages } : child;
|
|
1075
|
+
});
|
|
1076
|
+
return children.length ? { ...status, steps: children, workflowChildren: undefined, children: undefined } : status;
|
|
1077
|
+
});
|
|
1078
|
+
tui.requestRender();
|
|
1079
|
+
}
|
|
1080
|
+
},
|
|
1081
|
+
},
|
|
1082
|
+
isPrompt: text => !!activeUIPrompt && (!activeUIPrompt.title || text.includes(activeUIPrompt.title)),
|
|
1083
|
+
isTransient: text => !!dimPrefix && text.startsWith(dimPrefix),
|
|
1084
|
+
});
|
|
1085
|
+
lastAttachMode = typeof tui.mode === "string" ? tui.mode : undefined;
|
|
1086
|
+
if (!restoreTranscript) {
|
|
1087
|
+
restoreAgentWidgets?.();
|
|
1088
|
+
restoreAgentWidgets = undefined;
|
|
1089
|
+
// Settings overlay replaces the transcript; remount after it closes instead of warning.
|
|
1090
|
+
ctx.ui.notify(tui.mode === "regular"
|
|
1091
|
+
? "Minimal output needs the fullscreen renderer. Quit and restart Pi — /reload does not switch TUI mode. Or set TUI mode to fullscreen in /settings."
|
|
1092
|
+
: "Pi transcript layout not recognized; minimal mode disabled, native output preserved.", "warning");
|
|
1093
|
+
}
|
|
1094
|
+
if (restoreTranscript) {
|
|
1095
|
+
promptView = view;
|
|
1096
|
+
waitingTimer = setInterval(() => {
|
|
1097
|
+
let changed = false;
|
|
1098
|
+
if (Date.now() - lastStatusRead >= 1000) {
|
|
1099
|
+
const next = retainAgentStatuses(statuses, readAgentStatuses(sessionKey, undefined, statuses));
|
|
1100
|
+
changed = JSON.stringify(next) !== JSON.stringify(statuses);
|
|
1101
|
+
statuses = next;
|
|
1102
|
+
saveStatuses();
|
|
1103
|
+
lastStatusRead = Date.now();
|
|
1104
|
+
}
|
|
1105
|
+
if (changed || Date.now() >= view.agentExpiry() || activeMinimalTurn?.running || statuses.some(status => /^(running|active|starting|queued|pending)$/.test(String(status.state)))) tui.requestRender();
|
|
1106
|
+
}, 100);
|
|
1107
|
+
waitingTimer.unref();
|
|
1108
|
+
}
|
|
1109
|
+
tui.requestRender();
|
|
1110
|
+
// Factory acquires the renderer only; never duplicate content in the dock.
|
|
1111
|
+
return { render: () => [], invalidate() {} };
|
|
1112
|
+
});
|
|
1113
|
+
};
|
|
1114
|
+
// All factories run before session_start; retain startup broadcasts until the footer mounts.
|
|
1115
|
+
const unsubscribeMcpStatus = pi.events.on("pi-mcp-adapter/status/v1", (value: unknown) => {
|
|
1116
|
+
const count = enabledMcpServerCount(value);
|
|
1117
|
+
if (count === undefined) return;
|
|
1118
|
+
mcpCount = count;
|
|
1119
|
+
refresh();
|
|
1120
|
+
});
|
|
1121
|
+
const stopSpeedTimer = () => {
|
|
1122
|
+
if (speedTimer) clearInterval(speedTimer);
|
|
1123
|
+
speedTimer = undefined;
|
|
1124
|
+
};
|
|
1125
|
+
const refreshStreamingSpeed = () => {
|
|
1126
|
+
if (!activeGeneration) return;
|
|
1127
|
+
const nextSpeed = outputSpeed(activeGeneration.output, activeGeneration.firstTokenAt);
|
|
1128
|
+
if (nextSpeed !== undefined) speed = nextSpeed;
|
|
1129
|
+
refresh();
|
|
1130
|
+
};
|
|
1131
|
+
const startSpeedTimer = () => {
|
|
1132
|
+
stopSpeedTimer();
|
|
1133
|
+
speedTimer = setInterval(refreshStreamingSpeed, 250);
|
|
1134
|
+
};
|
|
1135
|
+
const persistSettings = (ctx: ExtensionContext) => {
|
|
1136
|
+
const snapshot = { ...settings };
|
|
1137
|
+
saveChain = saveChain
|
|
1138
|
+
.catch(() => undefined)
|
|
1139
|
+
.then(() => saveSettings(snapshot, configPath))
|
|
1140
|
+
.catch(() => ctx.ui.notify(COPY.saveFailed, "error"));
|
|
1141
|
+
return saveChain;
|
|
1142
|
+
};
|
|
1143
|
+
const applyRecommendedHostSettings = async (ctx: ExtensionContext, themeName: RecommendedTheme): Promise<boolean> => {
|
|
1144
|
+
const theme = ctx.ui.getTheme(themeName);
|
|
1145
|
+
if (!theme) {
|
|
1146
|
+
ctx.ui.notify(`找不到主题 ${themeName};请先确认 Pi 已发现本包主题。`, "error");
|
|
1147
|
+
return false;
|
|
1148
|
+
}
|
|
1149
|
+
try {
|
|
1150
|
+
const manager = SettingsManager.create(ctx.cwd, getAgentDir(), { projectTrusted: ctx.isProjectTrusted?.() ?? false });
|
|
1151
|
+
const initialErrors = manager.drainErrors();
|
|
1152
|
+
if (initialErrors.length) {
|
|
1153
|
+
ctx.ui.notify(`${COPY.themeSaveFailed} Pi 设置读取失败:${initialErrors.map(error => error.error.message).join(";")}`, "error");
|
|
1154
|
+
return false;
|
|
1155
|
+
}
|
|
1156
|
+
const projectSettings = manager.getProjectSettings();
|
|
1157
|
+
const projectOverrides = [
|
|
1158
|
+
typeof projectSettings.theme === "string" ? "主题" : undefined,
|
|
1159
|
+
projectSettings.tuiMode !== undefined ? "TUI 模式" : undefined,
|
|
1160
|
+
].filter((value): value is string => value !== undefined);
|
|
1161
|
+
manager.setTheme(themeName);
|
|
1162
|
+
manager.setTuiMode("fullscreen");
|
|
1163
|
+
await manager.flush();
|
|
1164
|
+
const errors = manager.drainErrors();
|
|
1165
|
+
if (errors.length) {
|
|
1166
|
+
ctx.ui.notify(`${COPY.themeSaveFailed} Pi 设置可能已部分保存:${errors.map(error => error.error.message).join(";")}`, "error");
|
|
1167
|
+
return false;
|
|
1168
|
+
}
|
|
1169
|
+
const applied = ctx.ui.setTheme(theme);
|
|
1170
|
+
if (!applied.success) {
|
|
1171
|
+
ctx.ui.notify(`${COPY.themeApplyFailed}${applied.error ? ` ${applied.error}` : ""}`, "warning");
|
|
1172
|
+
return false;
|
|
1173
|
+
}
|
|
1174
|
+
mountMinimalOutput(ctx);
|
|
1175
|
+
refresh();
|
|
1176
|
+
ctx.ui.notify(projectOverrides.length
|
|
1177
|
+
? `${COPY.themeSaved} 项目设置中的${projectOverrides.join("、")}优先级更高。`
|
|
1178
|
+
: COPY.themeSaved, "info");
|
|
1179
|
+
return true;
|
|
1180
|
+
} catch (error) {
|
|
1181
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1182
|
+
ctx.ui.notify(`${COPY.themeSaveFailed} ${detail}`, "error");
|
|
1183
|
+
return false;
|
|
1184
|
+
}
|
|
1185
|
+
};
|
|
1186
|
+
const openSettings = async (ctx: ExtensionContext) => {
|
|
1187
|
+
const generation = settingsWebGeneration;
|
|
1188
|
+
if (ctx.mode !== "tui") { ctx.ui.notify(COPY.tuiRequired, "error"); return; }
|
|
1189
|
+
try {
|
|
1190
|
+
if (settingsWeb && !settingsWeb.closed) settingsWeb.touch();
|
|
1191
|
+
else settingsWebOpening ??= (async () => {
|
|
1192
|
+
const { startSettingsWeb } = await import("../lib/settings-web.ts");
|
|
1193
|
+
const server = await startSettingsWeb(() => ({
|
|
1194
|
+
settings, defaults: DEFAULT_SETTINGS, order: FOOTER_FIELDS,
|
|
1195
|
+
items: settingsItems(settings).filter(item => !isCollapsedReplyChildSetting(item.id)),
|
|
1196
|
+
// "regular" means minimal output is saved but cannot mount; the page offers a Pi prompt.
|
|
1197
|
+
tuiMode: lastAttachMode ?? null,
|
|
1198
|
+
}), async value => {
|
|
1199
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Invalid settings");
|
|
1200
|
+
const input = value as Record<string, unknown>;
|
|
1201
|
+
for (const [key, entry] of Object.entries(input)) {
|
|
1202
|
+
if (key === "footerOrder") {
|
|
1203
|
+
if (!Array.isArray(entry) || entry.length !== FOOTER_FIELDS.length || new Set(entry).size !== entry.length
|
|
1204
|
+
|| entry.some(id => !(FOOTER_FIELDS as readonly unknown[]).includes(id))) throw new TypeError("Invalid order");
|
|
1205
|
+
} else if (!SETTING_IDS.includes(key as typeof SETTING_IDS[number]) || typeof entry !== "boolean") throw new TypeError("Invalid setting");
|
|
1206
|
+
}
|
|
1207
|
+
const next = parseSettings({ ...settings, ...input, onboardingCompleted: true });
|
|
1208
|
+
await saveSettings(next, configPath);
|
|
1209
|
+
settings = next;
|
|
1210
|
+
cleanupInputEnhancements?.refresh();
|
|
1211
|
+
refresh();
|
|
1212
|
+
mountMinimalOutput(ctx);
|
|
1213
|
+
refreshMinimalOutput();
|
|
1214
|
+
}, { onClose: () => { if (settingsWeb === server) settingsWeb = undefined; } });
|
|
1215
|
+
if (generation !== settingsWebGeneration) { server.close(); return; }
|
|
1216
|
+
settingsWeb = server;
|
|
1217
|
+
})().finally(() => { if (generation === settingsWebGeneration) settingsWebOpening = undefined; });
|
|
1218
|
+
await settingsWebOpening;
|
|
1219
|
+
if (generation !== settingsWebGeneration || !settingsWeb || settingsWeb.closed) return;
|
|
1220
|
+
const url = settingsWeb.url;
|
|
1221
|
+
const result = process.platform === "darwin" ? await pi.exec("open", [url])
|
|
1222
|
+
: process.platform === "win32" ? await pi.exec("rundll32.exe", ["url.dll,FileProtocolHandler", url])
|
|
1223
|
+
: await pi.exec("xdg-open", [url]);
|
|
1224
|
+
if (result.code !== 0) ctx.ui.notify(`请在本机浏览器打开:${url}`, "warning");
|
|
1225
|
+
} catch (error) {
|
|
1226
|
+
if (!settingsWeb) settingsWebOpening = undefined;
|
|
1227
|
+
ctx.ui.notify(`无法打开设置:${error instanceof Error ? error.message : String(error)}${settingsWeb ? `\n${settingsWeb.url}` : ""}`, "error");
|
|
1228
|
+
}
|
|
1229
|
+
};
|
|
1230
|
+
|
|
1231
|
+
const runOnboarding = async (ctx: ExtensionContext) => {
|
|
1232
|
+
if (ctx.mode !== "tui" || !ctx.hasUI) return;
|
|
1233
|
+
let choice: string | undefined;
|
|
1234
|
+
try {
|
|
1235
|
+
choice = await ctx.ui.select(
|
|
1236
|
+
`Pi Mini Mode ${COPY.preview}\n\n deepseek-v4-flash high ${COPY.totalLabel} 45K ${COPY.cachedLabel} 25K ${COPY.cacheHitLabel} 40.0% $0.012 500/1.0M █░░░░░░░░░ 1% 120 tok/s\n\n${COPY.onboarding}`,
|
|
1237
|
+
[COPY.keepDefaults, COPY.configureNow, COPY.applyRecommended],
|
|
1238
|
+
);
|
|
1239
|
+
} catch (error) {
|
|
1240
|
+
ctx.ui.notify(`首次配置未完成:${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
if (!choice) return;
|
|
1244
|
+
if (choice === COPY.applyRecommended) {
|
|
1245
|
+
let themeName: string | undefined;
|
|
1246
|
+
try {
|
|
1247
|
+
const available = RECOMMENDED_THEMES.filter(name => ctx.ui.getTheme(name));
|
|
1248
|
+
if (!available.length) {
|
|
1249
|
+
ctx.ui.notify("未发现 cc-dark 或 cc-light 主题;请确认本包主题已加载。", "error");
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
themeName = await ctx.ui.select(COPY.chooseTheme, available);
|
|
1253
|
+
} catch (error) {
|
|
1254
|
+
ctx.ui.notify(`推荐配置未完成:${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1255
|
+
return;
|
|
1256
|
+
}
|
|
1257
|
+
if (!themeName || !RECOMMENDED_THEMES.includes(themeName as RecommendedTheme)) return;
|
|
1258
|
+
if (!await applyRecommendedHostSettings(ctx, themeName as RecommendedTheme)) return;
|
|
1259
|
+
}
|
|
1260
|
+
settings = { ...settings, onboardingCompleted: true };
|
|
1261
|
+
await persistSettings(ctx);
|
|
1262
|
+
if (choice === COPY.configureNow) await openSettings(ctx);
|
|
1263
|
+
};
|
|
1264
|
+
pi.registerCommand("pi-mini-mode-minimal", {
|
|
1265
|
+
description: "Toggle minimal output (off keeps Pi's default conversation history)",
|
|
1266
|
+
handler: async (args, ctx) => {
|
|
1267
|
+
const normalized = args.trim().toLowerCase();
|
|
1268
|
+
if (ctx.mode !== "tui") {
|
|
1269
|
+
ctx.ui.notify(COPY.minimalRequired, "error");
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
if (normalized && normalized !== "on" && normalized !== "off") {
|
|
1273
|
+
ctx.ui.notify(COPY.minimalUsage, "warning");
|
|
1274
|
+
return;
|
|
1275
|
+
}
|
|
1276
|
+
settings = {
|
|
1277
|
+
...settings,
|
|
1278
|
+
"pi-mini-mode-minimal-show": normalized === "on" ? true : normalized === "off" ? false : !settings["pi-mini-mode-minimal-show"],
|
|
1279
|
+
onboardingCompleted: true,
|
|
1280
|
+
};
|
|
1281
|
+
if (settings["pi-mini-mode-minimal-show"]) nativeOutput = false;
|
|
1282
|
+
mountMinimalOutput(ctx);
|
|
1283
|
+
await persistSettings(ctx);
|
|
1284
|
+
if (settings["pi-mini-mode-minimal-show"] && !restoreTranscript) return;
|
|
1285
|
+
ctx.ui.notify(`${COPY.minimalState}${settings["pi-mini-mode-minimal-show"] ? "on" : "off"}`, "info");
|
|
1286
|
+
},
|
|
1287
|
+
});
|
|
1288
|
+
pi.registerCommand("pi-mini-mode-prompts", {
|
|
1289
|
+
description: "Expand or collapse a user prompt in fullscreen minimal output",
|
|
1290
|
+
handler: async (_args, ctx) => {
|
|
1291
|
+
if (ctx.mode !== "tui" || !restoreTranscript || !promptView) {
|
|
1292
|
+
if (ctx.hasUI) ctx.ui.notify("Prompt folding requires fullscreen minimal output.", "info");
|
|
1293
|
+
return;
|
|
1294
|
+
}
|
|
1295
|
+
const view = promptView;
|
|
1296
|
+
const choices = view.promptChoices();
|
|
1297
|
+
if (!choices.length) { ctx.ui.notify("No user prompts exceed four lines at this width.", "info"); return; }
|
|
1298
|
+
const labels = choices.map(choice => `${choice.index + 1}. ${choice.label} · ${preview(choice.question)}`);
|
|
1299
|
+
const selected = await ctx.ui.select("User prompts · Enter to toggle · Esc to cancel", labels);
|
|
1300
|
+
const choice = choices[labels.indexOf(selected ?? "")];
|
|
1301
|
+
if (choice && promptView === view) { view.togglePrompt(choice.index, choice.question); refreshMinimalOutput(); }
|
|
1302
|
+
},
|
|
1303
|
+
});
|
|
1304
|
+
pi.registerCommand("pi-mini-mode-tools", {
|
|
1305
|
+
description: "Expand or collapse a tool's saved text or thinking in fullscreen minimal output",
|
|
1306
|
+
handler: async (_args, ctx) => {
|
|
1307
|
+
if (ctx.mode !== "tui" || !restoreTranscript || !promptView) {
|
|
1308
|
+
if (ctx.hasUI) ctx.ui.notify("Tool folding requires fullscreen minimal output.", "info");
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
const view = promptView;
|
|
1312
|
+
const choices = view.toolChoices();
|
|
1313
|
+
if (!choices.length) { ctx.ui.notify("No visible tool calls. Ctrl+O shows older calls.", "info"); return; }
|
|
1314
|
+
const labels = choices.map((choice, index) => `${index + 1}. ${choice.expanded ? "收起" : "展开"} · ${preview(choice.title)}`);
|
|
1315
|
+
const selected = await ctx.ui.select("Tool results · Enter to toggle · Esc to cancel", labels);
|
|
1316
|
+
const choice = choices[labels.indexOf(selected ?? "")];
|
|
1317
|
+
if (choice && promptView === view) { view.toggleTool(choice.id); refreshMinimalOutput(); }
|
|
1318
|
+
},
|
|
1319
|
+
});
|
|
1320
|
+
pi.registerCommand("pi-mini-mode-settings", {
|
|
1321
|
+
description: "Open HTML settings in the browser",
|
|
1322
|
+
handler: async (_args, ctx) => openSettings(ctx),
|
|
1323
|
+
});
|
|
1324
|
+
pi.registerCommand("pi-mini-mode-setup", {
|
|
1325
|
+
description: "Set up Pi Mini Mode theme and fullscreen mode",
|
|
1326
|
+
handler: async (_args, ctx) => runOnboarding(ctx),
|
|
1327
|
+
});
|
|
1328
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1329
|
+
const loaded = await loadSettings(configPath);
|
|
1330
|
+
settings = loaded.settings;
|
|
1331
|
+
messageCwd = ctx.cwd;
|
|
1332
|
+
// 输入增强只在会话中生效,会话开始时再加载;传 getter 让开关变更即时生效,重复调用是幂等的。
|
|
1333
|
+
const { installInputEnhancements } = await import("../lib/input-enhancements.ts");
|
|
1334
|
+
cleanupInputEnhancements = installInputEnhancements(pi, ctx, () => settings["pi-mini-mode-input-enhancements"]);
|
|
1335
|
+
minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
|
|
1336
|
+
activeMinimalTurn = undefined;
|
|
1337
|
+
pendingMinimalFinal = "";
|
|
1338
|
+
minimalToolOutputIndices.clear();
|
|
1339
|
+
mountMinimalOutput(ctx);
|
|
1340
|
+
ctx.ui.setFooter((tui, theme, footerData) => {
|
|
1341
|
+
refreshFooter = () => tui.requestRender();
|
|
1342
|
+
return {
|
|
1343
|
+
dispose: footerData?.onBranchChange?.(() => tui.requestRender()),
|
|
1344
|
+
invalidate() {},
|
|
1345
|
+
render(width: number): string[] {
|
|
1346
|
+
// switchTuiMode does not re-run setWidget; remount once the live renderer is fullscreen.
|
|
1347
|
+
if (settings["pi-mini-mode-minimal-show"] && !nativeOutput && ctx.mode === "tui" && !restoreTranscript
|
|
1348
|
+
&& tui.mode !== "regular" && lastAttachMode === "regular" && !remountQueued) {
|
|
1349
|
+
remountQueued = true;
|
|
1350
|
+
queueMicrotask(() => {
|
|
1351
|
+
remountQueued = false;
|
|
1352
|
+
mountMinimalOutput(ctx);
|
|
1353
|
+
});
|
|
1354
|
+
}
|
|
1355
|
+
return [statusLine(ctx, theme, width, sessionUsage(ctx), settings, speed, undefined, mcpCount, footerData?.getExtensionStatuses?.(), footerData?.getGitBranch?.())];
|
|
1356
|
+
},
|
|
1357
|
+
};
|
|
1358
|
+
});
|
|
1359
|
+
refresh();
|
|
1360
|
+
if (!loaded.exists && ctx.mode === "tui" && ctx.hasUI) await runOnboarding(ctx);
|
|
1361
|
+
});
|
|
1362
|
+
const syncMinimalBranch = (_event: unknown, ctx: ExtensionContext) => {
|
|
1363
|
+
minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
|
|
1364
|
+
activeMinimalTurn = undefined;
|
|
1365
|
+
pendingMinimalFinal = "";
|
|
1366
|
+
minimalMessageIndices.clear();
|
|
1367
|
+
minimalToolOutputIndices.clear();
|
|
1368
|
+
mountMinimalOutput(ctx);
|
|
1369
|
+
refreshMinimalOutput();
|
|
1370
|
+
};
|
|
1371
|
+
// New/switch/fork emit session_start; tree navigation has its own event.
|
|
1372
|
+
pi.on("session_tree", syncMinimalBranch);
|
|
1373
|
+
pi.on("session_compact", (event, ctx) => {
|
|
1374
|
+
// Compaction during execution must not discard the in-flight turn or indexes.
|
|
1375
|
+
if (activeMinimalTurn) { refreshMinimalOutput(); return; }
|
|
1376
|
+
syncMinimalBranch(event, ctx);
|
|
1377
|
+
});
|
|
1378
|
+
pi.on("before_agent_start", (event) => {
|
|
1379
|
+
if (!activeMinimalTurn) return;
|
|
1380
|
+
for (const name of skillNames(event.prompt)) pushProcess(activeMinimalTurn, "skill", name);
|
|
1381
|
+
refreshMinimalOutput();
|
|
1382
|
+
});
|
|
1383
|
+
pi.on("ui_prompt_start", (event) => {
|
|
1384
|
+
activeUIPrompt = event;
|
|
1385
|
+
refreshMinimalOutput();
|
|
1386
|
+
});
|
|
1387
|
+
pi.on("ui_prompt_end", () => {
|
|
1388
|
+
activeUIPrompt = undefined;
|
|
1389
|
+
refreshMinimalOutput();
|
|
1390
|
+
});
|
|
1391
|
+
pi.on("model_select", refresh);
|
|
1392
|
+
pi.on("thinking_level_select", refresh);
|
|
1393
|
+
pi.on("message_start", (event) => {
|
|
1394
|
+
if (event.message.role === "user") {
|
|
1395
|
+
if (activeMinimalTurn) {
|
|
1396
|
+
activeMinimalTurn.final = pendingMinimalFinal;
|
|
1397
|
+
activeMinimalTurn.running = false;
|
|
1398
|
+
activeMinimalTurn.thinking = undefined;
|
|
1399
|
+
}
|
|
1400
|
+
const question = contentText(event.message.content) || "[Attachment]";
|
|
1401
|
+
processExpanded = false;
|
|
1402
|
+
subAgentsExpanded = false;
|
|
1403
|
+
activeMinimalTurn = { question, process: [], running: true, startedAt: Date.now(), awaitingResponse: true, shortcutHintUntil: Date.now() + 6_000 };
|
|
1404
|
+
if (shortcutTimer) clearTimeout(shortcutTimer);
|
|
1405
|
+
shortcutTimer = setTimeout(() => refreshMinimalOutput(), 6_000);
|
|
1406
|
+
shortcutTimer.unref();
|
|
1407
|
+
for (const name of skillNames(question)) pushProcess(activeMinimalTurn, "skill", name);
|
|
1408
|
+
pendingMinimalFinal = "";
|
|
1409
|
+
minimalToolOutputIndices.clear();
|
|
1410
|
+
minimalTurns.push(activeMinimalTurn);
|
|
1411
|
+
refreshMinimalOutput();
|
|
1412
|
+
}
|
|
1413
|
+
if (event.message.role !== "assistant") return;
|
|
1414
|
+
// Background completions can start a new assistant turn without a user message.
|
|
1415
|
+
activeMinimalTurn ??= minimalTurns.at(-1);
|
|
1416
|
+
if (activeMinimalTurn) {
|
|
1417
|
+
if (activeMinimalTurn.final) (activeMinimalTurn.replies ??= []).push(activeMinimalTurn.final);
|
|
1418
|
+
activeMinimalTurn.final = undefined;
|
|
1419
|
+
activeMinimalTurn.running = true;
|
|
1420
|
+
activeMinimalTurn.awaitingResponse = true;
|
|
1421
|
+
activeMinimalTurn.thinking = undefined;
|
|
1422
|
+
}
|
|
1423
|
+
minimalMessageIndices.clear();
|
|
1424
|
+
pendingMinimalFinal = "";
|
|
1425
|
+
// Keep the last completed speed visible until this response produces tokens.
|
|
1426
|
+
// Tool-call-only assistant messages therefore cannot erase a useful rate.
|
|
1427
|
+
// Decode clock starts on the first output token, not message_start (TTFT).
|
|
1428
|
+
const sampledAt = Date.now();
|
|
1429
|
+
activeGeneration = { output: 0, lastSampleAt: sampledAt };
|
|
1430
|
+
startSpeedTimer();
|
|
1431
|
+
});
|
|
1432
|
+
pi.on("message_update", (event) => {
|
|
1433
|
+
const partial = (event.assistantMessageEvent as { partial?: { usage?: UsageLike; content?: Array<Record<string, unknown>> } }).partial;
|
|
1434
|
+
if (activeMinimalTurn && partial?.content) {
|
|
1435
|
+
activeMinimalTurn.thinking = undefined;
|
|
1436
|
+
if (partial.content.length) activeMinimalTurn.awaitingResponse = false;
|
|
1437
|
+
for (const [blockIndex, item] of partial.content.entries()) {
|
|
1438
|
+
if (item.type !== "thinking") continue;
|
|
1439
|
+
const line = `${item.type === "thinking" ? "thinking" : "output"} ${processText(item.thinking ?? item.text)}`;
|
|
1440
|
+
const index = minimalMessageIndices.get(blockIndex);
|
|
1441
|
+
if (index === undefined) {
|
|
1442
|
+
minimalMessageIndices.set(blockIndex, activeMinimalTurn.process.length);
|
|
1443
|
+
activeMinimalTurn.process.push(line);
|
|
1444
|
+
} else activeMinimalTurn.process[index] = line;
|
|
1445
|
+
if (blockIndex === partial.content.length - 1 && event.assistantMessageEvent.type !== "thinking_end") activeMinimalTurn.thinking = minimalMessageIndices.get(blockIndex);
|
|
1446
|
+
}
|
|
1447
|
+
activeMinimalTurn.final = contentText(partial.content) || undefined;
|
|
1448
|
+
refreshMinimalOutput();
|
|
1449
|
+
}
|
|
1450
|
+
if (activeMinimalTurn && partial?.usage) {
|
|
1451
|
+
activeMinimalTurn.pendingUsage = partial.usage;
|
|
1452
|
+
refreshMinimalOutput();
|
|
1453
|
+
}
|
|
1454
|
+
const usage = partial?.usage;
|
|
1455
|
+
const output = finiteNumber(usage?.output);
|
|
1456
|
+
const timestamp = Date.now();
|
|
1457
|
+
const hasOutputContent = Array.isArray(partial?.content) && partial.content.length > 0;
|
|
1458
|
+
if (activeGeneration && timestamp >= activeGeneration.lastSampleAt) {
|
|
1459
|
+
if (activeGeneration.firstTokenAt === undefined && (hasOutputContent || (output !== undefined && output > 0))) {
|
|
1460
|
+
activeGeneration.firstTokenAt = timestamp;
|
|
1461
|
+
}
|
|
1462
|
+
if (output !== undefined && output >= activeGeneration.output) {
|
|
1463
|
+
activeGeneration.output = output;
|
|
1464
|
+
activeGeneration.lastSampleAt = timestamp;
|
|
1465
|
+
refreshStreamingSpeed();
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
});
|
|
1469
|
+
pi.on("message_end", (event) => {
|
|
1470
|
+
if (event.message.role === "assistant") {
|
|
1471
|
+
if (activeMinimalTurn) {
|
|
1472
|
+
activeMinimalTurn.thinking = undefined;
|
|
1473
|
+
activeMinimalTurn.awaitingResponse = false;
|
|
1474
|
+
activeMinimalTurn.usage = addUsage(activeMinimalTurn.usage ?? EMPTY_USAGE, event.message.usage as UsageLike | undefined);
|
|
1475
|
+
activeMinimalTurn.pendingUsage = undefined;
|
|
1476
|
+
}
|
|
1477
|
+
if (activeGeneration) {
|
|
1478
|
+
const finalSpeed = outputSpeed((event.message.usage as UsageLike | undefined)?.output, activeGeneration.firstTokenAt);
|
|
1479
|
+
if (finalSpeed !== undefined) speed = finalSpeed;
|
|
1480
|
+
activeGeneration = undefined;
|
|
1481
|
+
stopSpeedTimer();
|
|
1482
|
+
}
|
|
1483
|
+
const content = (event.message as { content?: unknown }).content;
|
|
1484
|
+
if (activeMinimalTurn && Array.isArray(content)) {
|
|
1485
|
+
for (const [blockIndex, item] of (content as Array<Record<string, unknown>>).entries()) {
|
|
1486
|
+
if (item.type !== "thinking" && !(item.type === "text" && content.some((block) => block.type === "toolCall"))) continue;
|
|
1487
|
+
const line = `${item.type === "thinking" ? "thinking" : "output"} ${processText(item.thinking ?? item.text)}`;
|
|
1488
|
+
const index = minimalMessageIndices.get(blockIndex);
|
|
1489
|
+
if (index === undefined) activeMinimalTurn.process.push(line);
|
|
1490
|
+
else activeMinimalTurn.process[index] = line;
|
|
1491
|
+
}
|
|
1492
|
+
const text = contentText(content);
|
|
1493
|
+
const message = event.message as { stopReason?: string; errorMessage?: string };
|
|
1494
|
+
activeMinimalTurn.final = undefined;
|
|
1495
|
+
pendingMinimalFinal = content.some((item) => item?.type === "toolCall") ? "" : text;
|
|
1496
|
+
if (message.stopReason === "error" || message.stopReason === "aborted") {
|
|
1497
|
+
pendingMinimalFinal = [message.stopReason === "aborted" ? "Execution aborted" : "Execution failed", message.errorMessage, pendingMinimalFinal].filter(Boolean).join("\n");
|
|
1498
|
+
}
|
|
1499
|
+
activeMinimalTurn.final = pendingMinimalFinal || undefined;
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
refresh();
|
|
1503
|
+
refreshMinimalOutput();
|
|
1504
|
+
});
|
|
1505
|
+
pi.on("tool_execution_start", (event) => {
|
|
1506
|
+
toolStarts.set(event.toolCallId, Date.now());
|
|
1507
|
+
if (activeMinimalTurn) {
|
|
1508
|
+
activeMinimalTurn.thinking = undefined;
|
|
1509
|
+
activeMinimalTurn.awaitingResponse = false;
|
|
1510
|
+
(activeMinimalTurn.agentCalls ??= []).push(agentCall(event.toolCallId, event.toolName, event.args));
|
|
1511
|
+
pushProcess(activeMinimalTurn, "call", event.toolCallId);
|
|
1512
|
+
(activeMinimalTurn.waitingTools ??= []).push({ id: event.toolCallId, name: event.toolName, startedAt: Date.now() });
|
|
1513
|
+
}
|
|
1514
|
+
const path = (event.args as { path?: unknown })?.path;
|
|
1515
|
+
if (typeof path === "string" && /(?:^|\/)SKILL\.md$/i.test(path)) {
|
|
1516
|
+
pushProcess(activeMinimalTurn, "skill", path.split("/").at(-2) ?? path);
|
|
1517
|
+
}
|
|
1518
|
+
refreshMinimalOutput();
|
|
1519
|
+
});
|
|
1520
|
+
pi.on("tool_execution_update", (event) => {
|
|
1521
|
+
if (!activeMinimalTurn) return;
|
|
1522
|
+
// Pi emits an empty content array before starting bash. It is a heartbeat,
|
|
1523
|
+
// not output: keep the tool status (and any existing output) intact.
|
|
1524
|
+
const text = contentText(event.partialResult);
|
|
1525
|
+
if (!text) return;
|
|
1526
|
+
const call = activeMinimalTurn.agentCalls?.find(call => call.id === event.toolCallId);
|
|
1527
|
+
if (call) { call.output = text; activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter(tool => tool.id !== event.toolCallId); refreshMinimalOutput(); return; }
|
|
1528
|
+
activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter((tool) => tool.id !== event.toolCallId);
|
|
1529
|
+
const line = `output ${text}`;
|
|
1530
|
+
const index = minimalToolOutputIndices.get(event.toolCallId);
|
|
1531
|
+
if (index === undefined) {
|
|
1532
|
+
minimalToolOutputIndices.set(event.toolCallId, activeMinimalTurn.process.length);
|
|
1533
|
+
activeMinimalTurn.process.push(line);
|
|
1534
|
+
} else {
|
|
1535
|
+
activeMinimalTurn.process[index] = line;
|
|
1536
|
+
}
|
|
1537
|
+
refreshMinimalOutput();
|
|
1538
|
+
});
|
|
1539
|
+
pi.on("tool_execution_end", (event) => {
|
|
1540
|
+
const startedAt = toolStarts.get(event.toolCallId);
|
|
1541
|
+
toolStarts.delete(event.toolCallId);
|
|
1542
|
+
const nestedUsage = (event.result as { usage?: UsageLike } | undefined)?.usage;
|
|
1543
|
+
if (activeMinimalTurn) activeMinimalTurn.usage = addUsage(activeMinimalTurn.usage ?? EMPTY_USAGE, nestedUsage);
|
|
1544
|
+
// Nested tool LLM completions must not overwrite a measured main-turn decode rate.
|
|
1545
|
+
if (startedAt !== undefined && speed === undefined) {
|
|
1546
|
+
const nestedSpeed = outputSpeed(nestedUsage?.output, startedAt);
|
|
1547
|
+
if (nestedSpeed !== undefined) speed = nestedSpeed;
|
|
1548
|
+
}
|
|
1549
|
+
const call = activeMinimalTurn?.agentCalls?.find(call => call.id === event.toolCallId);
|
|
1550
|
+
if (call) {
|
|
1551
|
+
if (activeMinimalTurn) activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter(tool => tool.id !== event.toolCallId);
|
|
1552
|
+
call.state = event.isError ? "error" : "done";
|
|
1553
|
+
call.output = contentText(event.result) || (event.isError ? "Call failed (no text details)" : "Call returned (background task status below)");
|
|
1554
|
+
refresh();
|
|
1555
|
+
refreshMinimalOutput();
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
if (activeMinimalTurn) {
|
|
1559
|
+
activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter((tool) => tool.id !== event.toolCallId);
|
|
1560
|
+
const text = contentText(event.result) || (event.isError ? "Tool failed (no text details)" : "Tool completed (no text output)");
|
|
1561
|
+
const line = `${event.isError ? "output error" : "output"} ${text}`;
|
|
1562
|
+
const index = minimalToolOutputIndices.get(event.toolCallId);
|
|
1563
|
+
if (index === undefined) activeMinimalTurn.process.push(line);
|
|
1564
|
+
else activeMinimalTurn.process[index] = line;
|
|
1565
|
+
}
|
|
1566
|
+
minimalToolOutputIndices.delete(event.toolCallId);
|
|
1567
|
+
refresh();
|
|
1568
|
+
refreshMinimalOutput();
|
|
1569
|
+
});
|
|
1570
|
+
pi.on("agent_start", refresh);
|
|
1571
|
+
pi.on("agent_end", refresh);
|
|
1572
|
+
pi.on("agent_settled", () => {
|
|
1573
|
+
if (!activeMinimalTurn) return;
|
|
1574
|
+
for (const turn of minimalTurns) { turn.running = false; turn.thinking = undefined; }
|
|
1575
|
+
activeMinimalTurn.final = pendingMinimalFinal;
|
|
1576
|
+
activeMinimalTurn = undefined;
|
|
1577
|
+
pendingMinimalFinal = "";
|
|
1578
|
+
minimalToolOutputIndices.clear();
|
|
1579
|
+
refreshMinimalOutput();
|
|
1580
|
+
});
|
|
1581
|
+
pi.on("session_shutdown", () => {
|
|
1582
|
+
// In-flight startup checks this generation before installing its server.
|
|
1583
|
+
settingsWebGeneration++;
|
|
1584
|
+
settingsWeb?.close();
|
|
1585
|
+
settingsWeb = undefined;
|
|
1586
|
+
settingsWebOpening = undefined;
|
|
1587
|
+
cleanupInputEnhancements?.();
|
|
1588
|
+
cleanupInputEnhancements = undefined;
|
|
1589
|
+
persistAgentStatuses?.();
|
|
1590
|
+
persistAgentStatuses = undefined;
|
|
1591
|
+
agentDeadlines.clear();
|
|
1592
|
+
promptView = undefined;
|
|
1593
|
+
if (shortcutTimer) clearTimeout(shortcutTimer);
|
|
1594
|
+
shortcutTimer = undefined;
|
|
1595
|
+
unsubscribeMcpStatus();
|
|
1596
|
+
refreshFooter = undefined;
|
|
1597
|
+
activeGeneration = undefined;
|
|
1598
|
+
activeUIPrompt = undefined;
|
|
1599
|
+
toolStarts.clear();
|
|
1600
|
+
minimalToolOutputIndices.clear();
|
|
1601
|
+
refreshMinimal = undefined;
|
|
1602
|
+
if (waitingTimer) clearInterval(waitingTimer);
|
|
1603
|
+
waitingTimer = undefined;
|
|
1604
|
+
unsubscribeMinimalInput?.();
|
|
1605
|
+
unsubscribeMinimalInput = undefined;
|
|
1606
|
+
restoreTranscript?.();
|
|
1607
|
+
restoreTranscript = undefined;
|
|
1608
|
+
restoreAgentWidgets?.();
|
|
1609
|
+
restoreAgentWidgets = undefined;
|
|
1610
|
+
stopSpeedTimer();
|
|
1611
|
+
});
|
|
1612
|
+
}
|