@each1024/pi-mini-mode 2.0.9 → 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,292 +1,11 @@
1
- import { Markdown, Text, truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
2
- import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { diagramMarkdown, isMarkdownProse, renderMinimalMarkdown } from "./minimal-markdown.ts";
4
- import { stripVTControlCharacters } from "node:util";
1
+ import type { Component } from "@earendil-works/pi-tui";
5
2
  import { attachStickyTool } from "./sticky-tool.ts";
6
3
  import { attachImageRedraw } from "./image-placement.ts";
4
+ import { createTurnNoticeRenderer, type NoticeOptions, type NoticeRows, type TurnNotices } from "./transcript-notice-render.ts";
7
5
 
8
- const record = (value: unknown): Record<string, unknown> | undefined => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
9
- const clean = (text: string) => stripVTControlCharacters(text).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
10
- const renderMarkdownBody = (body: string, width: number, theme?: ExtensionContext["ui"]["theme"]) => isMarkdownProse(body)
11
- ? renderMinimalMarkdown(body, Math.max(1, width), getMarkdownTheme(), theme?.getBgAnsi?.("userMessageBg") ?? "", undefined, diagramMarkdown)
12
- : new Text(body, 0, 0).render(Math.max(1, width));
13
- const isSupervisorReply = (message: unknown) => record(message)?.customType === "subagent_supervisor_reply";
14
-
15
- /** Structured interview questions are the prompt; IDs and reply hints stay out. */
16
- export function formatInterview(interview: unknown): string {
17
- const data = record(interview);
18
- if (!data) return typeof interview === "string" ? clean(interview) : "";
19
- const lines: string[] = [];
20
- if (typeof data.title === "string" && data.title.trim()) lines.push(clean(data.title));
21
- const questions = Array.isArray(data.questions) ? data.questions : [];
22
- questions.forEach((question, index) => {
23
- if (typeof question === "string") {
24
- if (question.trim()) lines.push(`${index + 1}. ${clean(question)}`);
25
- return;
26
- }
27
- const item = record(question);
28
- if (!item) return;
29
- const prompt = [item.prompt, item.question, item.text, item.label].find(value => typeof value === "string" && String(value).trim());
30
- if (typeof prompt === "string") lines.push(`${index + 1}. ${clean(prompt)}`);
31
- const options = Array.isArray(item.options) ? item.options : Array.isArray(item.choices) ? item.choices : [];
32
- for (const option of options) {
33
- const label = typeof option === "string" ? option : typeof record(option)?.label === "string" ? String(record(option)!.label) : "";
34
- if (label.trim()) lines.push(` - ${clean(label)}`);
35
- }
36
- });
37
- return lines.join("\n");
38
- }
39
-
40
- function withInterview(body: string, interview: unknown): string {
41
- const questions = formatInterview(interview);
42
- if (!questions) return body;
43
- return body ? `${body}\n${questions}` : questions;
44
- }
45
-
46
- export function extractNoticeBody(message: unknown): string {
47
- const item = record(message);
48
- if (!item) return typeof message === "string" ? clean(message) : "";
49
- const details = record(item.details);
50
- const interview = details?.interview;
51
- if (details) {
52
- const event = record(details.event);
53
- const body = typeof details.requestBody === "string"
54
- ? details.requestBody
55
- : typeof event?.message === "string"
56
- ? event.message
57
- : typeof details.message === "string"
58
- ? details.message
59
- : undefined;
60
- if (body) {
61
- let cleanBody = stripVTControlCharacters(body).replace(/^UPDATE:\s*/i, "").trim();
62
- const failureReason = typeof event?.reason === "string" && ["tool_failures", "completion_guard"].includes(event.reason)
63
- ? event.reason === "tool_failures" ? "工具执行失败" : "任务完成受阻"
64
- : undefined;
65
- if (failureReason && !cleanBody.includes(failureReason)) cleanBody = `[${failureReason}] ${cleanBody}`;
66
- return withInterview(cleanBody, interview);
67
- }
68
- const questions = formatInterview(interview);
69
- if (questions) return questions;
70
- }
71
- const raw = typeof item.content === "string" ? item.content : "";
72
- if (raw) {
73
- const filtered = stripVTControlCharacters(raw)
74
- .split(/\r?\n/)
75
- .map(line => line.trim())
76
- .filter(line => line
77
- && !/^(?:Subagent (?:progress update|needs a supervisor decision|control notice)|Supervisor (?:progress update|decision request|interview request))\b/i.test(line)
78
- && !/^(?:Run|Agent|Child index|Child target|Request ID|Live guidance|Reply with|Request|Interview shape):\s*/i.test(line)
79
- && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(line)
80
- )
81
- .join("\n")
82
- .replace(/^UPDATE:\s*/i, "")
83
- .trim();
84
- if (filtered) return withInterview(filtered, interview);
85
- }
86
- const questions = formatInterview(interview);
87
- if (questions) return questions;
88
- return typeof item.content === "string" ? item.content : JSON.stringify(item.content ?? item, null, 2);
89
- }
90
-
91
- /** Only pi-subagents' known envelopes carry state; prose is never a status signal. */
92
- export function supervisorNotice(message: unknown) {
93
- const item = record(message);
94
- if (item?.customType === "subagent_supervisor_reply") {
95
- const data = record(item.data);
96
- if (item.type !== "custom" || !data
97
- || typeof data.requestId !== "string" || typeof data.runId !== "string"
98
- || typeof data.agent !== "string" || typeof data.message !== "string"
99
- || typeof data.childIndex !== "number" || !Number.isFinite(data.childIndex)
100
- || typeof data.createdAt !== "number" || !Number.isFinite(data.createdAt)
101
- || (data.reason !== undefined && (typeof data.reason !== "string" || !["need_decision", "interview_request", "progress_update"].includes(data.reason)))
102
- || (data.childTarget !== undefined && typeof data.childTarget !== "string")) return;
103
- return {
104
- key: data.runId && Number.isInteger(data.childIndex) && data.childIndex >= 0
105
- && !data.nestedRunId && !data.nestingPath ? JSON.stringify([data.runId, data.childIndex]) : undefined,
106
- runId: data.runId || undefined,
107
- agent: data.agent,
108
- internal: true,
109
- alert: false,
110
- state: "内部协作",
111
- color: "muted" as const,
112
- summary: "代理间沟通已收纳",
113
- body: stripVTControlCharacters(data.message).trim(),
114
- };
115
- }
116
- if (item?.type === "custom") return;
117
- if (item?.customType === "subagent-incremental-child-notify") {
118
- const content = typeof item.content === "string" ? item.content : undefined;
119
- const header = content?.match(/^Workflow child (completed|failed):\s+\*\*([^*\n]+)\*\*\s*$/m);
120
- if (!content || !header) return;
121
- const failed = header[1] === "failed";
122
- const error = content.match(/^Error:\s*([\s\S]*?)(?=^Status:|(?![\s\S]))/m)?.[1]
123
- .split(/\r?\n/)
124
- .map(line => line.trim())
125
- .filter(line => line && !/^Run fan-out:/i.test(line))
126
- .join(" ");
127
- const workflowRunId = content.match(/^Workflow run:\s*([0-9a-f-]{36})\s*$/mi)?.[1];
128
- const childRunId = content.match(/^Child run:\s*([0-9a-f-]{36})\s*$/mi)?.[1];
129
- const runIds = [...new Set([childRunId, workflowRunId].filter((id): id is string => !!id))];
130
- return {
131
- key: childRunId ? JSON.stringify(["incremental-child", childRunId])
132
- : workflowRunId ? JSON.stringify(["incremental-child", workflowRunId, header[2]]) : undefined,
133
- runId: childRunId || workflowRunId,
134
- runIds,
135
- internal: false,
136
- alert: failed,
137
- state: failed ? "执行失败" : "已完成",
138
- color: failed ? "error" as const : "muted" as const,
139
- summary: error || (failed ? "子任务失败" : "子任务已完成"),
140
- label: clean(header[2]),
141
- showLabel: true,
142
- body: content,
143
- };
144
- }
145
- if (item?.customType === "subagent-notify") {
146
- const content = typeof item.content === "string" ? item.content : undefined;
147
- const header = content?.match(/^(?:Background task|Detached foreground task) (completed|failed|paused|stopped):\s+\*\*([^\*\n]+)\*\*/m);
148
- if (!content || !header) return;
149
- const status = header[1];
150
- const failed = status === "failed" || status === "stopped"
151
- || /^- key=\S+ run=[0-9a-f-]{36} status=failed\s*$/mi.test(content)
152
- || /^Child runs:.*\(failed\)/mi.test(content);
153
- const attention = status === "paused";
154
- const workflowRunId = content.match(/^Workflow run:\s*([0-9a-f-]{36})\s*$/mi)?.[1]
155
- ?? content.match(/^Workflow receipt:\s*.*?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/mi)?.[1];
156
- const childRunIds = content.match(/^Child runs:\s*(.+)$/mi)?.[1]
157
- ?.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) ?? [];
158
- const directoryRunId = content.match(/^Retention-managed async directory:[ \t]*(?:\r?\n)?[^\r\n]*\/async-subagent-runs\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/?[ \t]*\r?$/mi)?.[1];
159
- const runIds = [...new Set([workflowRunId, directoryRunId, ...childRunIds].filter((id): id is string => !!id))];
160
- const runId = workflowRunId || directoryRunId || childRunIds[0];
161
- const metadata = /^(?:Workflow (?:receipt|run):|Child runs:|Session(?: file| share error)?:|Retention-managed|Reconciled detached|Parallel handoff:|Watchdog blockers:)/i;
162
- let preview = "";
163
- for (const line of content.split("\n").slice(1)) {
164
- const text = line.trim();
165
- if (!text || text === `${header[2]}:` || text.startsWith("Workflow receipt:")) continue;
166
- if (metadata.test(text)) break;
167
- preview = text;
168
- break;
169
- }
170
- return {
171
- key: runId ? JSON.stringify(["subagent-notify", runId]) : undefined,
172
- runId,
173
- runIds,
174
- internal: false,
175
- alert: failed || attention,
176
- state: failed ? "执行失败" : attention ? "需要关注" : "已完成",
177
- color: failed ? "error" as const : attention ? "warning" as const : "muted" as const,
178
- summary: failed && status === "completed" ? "工作流包含失败子任务"
179
- : clean(preview) || (failed ? "子任务失败" : attention ? "等待回复" : "子任务已完成"),
180
- label: clean(header[2]),
181
- showLabel: true,
182
- body: content,
183
- };
184
- }
185
- const details = record(item?.details);
186
- if (!details) return;
187
- const event = record(details.event);
188
- const request = item?.customType === "subagent_supervisor_request";
189
- if (request ? !["progress_update", "need_decision", "interview_request"].includes(String(details.reason))
190
- : item?.customType !== "subagent_control_notice" || !event || !["needs_attention", "active_long_running"].includes(String(event.type))) return;
191
- const data = request ? details : event!;
192
- const body = request
193
- ? (typeof details.requestBody === "string" ? details.requestBody : "")
194
- : data.message;
195
- if (typeof body !== "string" || typeof data.agent !== "string") return;
196
- const ask = request && (details.reason === "need_decision" || details.reason === "interview_request");
197
- // Replies and duplicate "waiting for supervisor" control notices stay compact.
198
- // Blocking asks are the main-session prompt; progress remains a status line.
199
- const internal = request
200
- ? (!ask && (details.reason !== "progress_update" || details.expectsReply === true))
201
- : data.reason === "supervisor_request";
202
- const failed = !request && ["completion_guard", "tool_failures"].includes(String(data.reason));
203
- const attention = ask || (!request && data.type === "needs_attention" && !internal);
204
- const question = clean(body).replace(/^UPDATE:\s*/i, "");
205
- const interviewTitle = typeof record(details.interview)?.title === "string" ? clean(String(record(details.interview)!.title)) : "";
206
- const index = request ? data.childIndex : data.index;
207
- const runId = typeof data.runId === "string" && data.runId ? data.runId : undefined;
208
- // ponytail: aggregate only unambiguous run+child envelopes; nested/missing
209
- // addresses stay separate until the producer provides a shared child identity.
210
- const key = runId && Number.isInteger(index) && Number(index) >= 0
211
- && !data.nestedRunId && !data.nestingPath ? JSON.stringify([runId, index]) : undefined;
212
- return { key, runId, internal, alert: failed || attention,
213
- state: failed ? "执行失败" : ask ? (details.reason === "interview_request" ? "需要提问" : "需要裁决")
214
- : attention ? "需要关注" : internal ? "内部协作" : "进度",
215
- color: failed ? "error" as const : attention ? "warning" as const : "muted" as const,
216
- summary: internal ? "代理间沟通已收纳" : question || (ask ? interviewTitle || "等待回复" : "暂无摘要"),
217
- label: typeof data.label === "string" ? clean(data.label) : typeof data.taskPreview === "string" ? clean(data.taskPreview) : undefined,
218
- body: question,
219
- agent: typeof data.agent === "string" ? data.agent : undefined,
220
- };
221
- }
222
-
223
- /** Progress is a status preview, not detail prose; decisions and failures remain inspectable. */
224
- export function supervisorNoticeBody(message: unknown): string {
225
- const item = record(message);
226
- if (item?.customType === "subagent_supervisor_request" && record(item.details)?.reason === "progress_update") return "";
227
- const notice = supervisorNotice(message);
228
- if (item?.type === "custom" && item.customType === "subagent_supervisor_reply") return notice?.body ?? "";
229
- return notice?.alert || notice?.internal ? extractNoticeBody(message) : "";
230
- }
231
-
232
- export function compactGoalCard(entry: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean): string[] | undefined {
233
- const item = record(entry);
234
- if (item?.customType !== "pi-codex-goal") return;
235
- const data = record(item.data);
236
- const goal = record(data?.goal);
237
- const objective = typeof goal?.objective === "string" ? clean(goal.objective) : undefined;
238
- // Usage snapshots are rendered by the goal extension too, but are not cards
239
- // worth adding to the compact transcript.
240
- if (!objective || width <= 0) return;
241
- const status = typeof goal?.status === "string" ? clean(goal.status) : "active";
242
- const control = truncateToWidth(expanded ? "[收起]" : "[详情]", width, "");
243
- const title = theme.fg(expanded ? "accent" : "muted", `${control} ◉ Goal · ${status}`);
244
- const hint = theme.fg(expanded ? "accent" : "muted", " · Ctrl+O");
245
- const summary = truncateToWidth(objective, Math.max(0, width - visibleWidth(title) - visibleWidth(hint) - 3), "…");
246
- const rows = [truncateToWidth(`${title} · ${theme.fg(expanded ? "accent" : "text", summary)}${hint}`, width, "")];
247
- if (expanded) rows.push(...renderMarkdownBody(objective, width, theme));
248
- return rows;
249
- }
250
-
251
- export function compactSupervisorNotice(message: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean, label = "", history: unknown[] = [message]): string[] | undefined {
252
- const notice = supervisorNotice(message);
253
- if (!notice) return;
254
- if (width <= 0) return [];
255
- const { state, color, summary } = notice;
256
- const effectiveLabel = label || (notice.showLabel ? notice.label ?? "" : "");
257
- const control = truncateToWidth(expanded ? "[收起]" : "[详情]", width, "");
258
- const hint = " · Ctrl+O";
259
- let heading: string;
260
- let summaryText: string;
261
- if (expanded) {
262
- const statusGlyph = color === "error" ? theme.fg("error", "× " + state)
263
- : color === "warning" ? theme.fg("warning", "⚠ " + state)
264
- : theme.fg("accent", "ℹ " + state);
265
- const taskLabel = effectiveLabel ? theme.fg("accent", ` · ${truncateToWidth(effectiveLabel, 20)}`) : "";
266
- heading = theme.fg("accent", control) + " " + statusGlyph + taskLabel;
267
- summaryText = theme.fg("accent", summary);
268
- } else {
269
- const title = theme.fg(color, `${color === "error" ? "×" : color === "warning" ? "⚠" : "ℹ"} ${state}${effectiveLabel ? ` · ${truncateToWidth(effectiveLabel, 20)}` : ""}`);
270
- heading = theme.fg("muted", control) + " " + title;
271
- summaryText = theme.fg(color, summary);
272
- }
273
- const hintStyled = theme.fg(expanded ? "accent" : "muted", hint);
274
- const available = width - visibleWidth(heading) - visibleWidth(hint) - 3;
275
- const rows = available >= 24
276
- ? [heading + " · " + truncateToWidth(summaryText, available) + hintStyled]
277
- : [truncateToWidth(heading, width, ""), truncateToWidth(summaryText, Math.max(0, width - visibleWidth(hint)), "") + truncateToWidth(hintStyled, width, "")];
278
- if (expanded) {
279
- const bodies: string[] = [];
280
- for (const original of history) {
281
- const body = supervisorNoticeBody(original);
282
- if (body && !bodies.includes(body)) bodies.push(body);
283
- }
284
- for (const body of bodies) {
285
- rows.push(...renderMarkdownBody(body, width, theme));
286
- }
287
- }
288
- return rows;
289
- }
6
+ export { formatInterview, extractNoticeBody, supervisorNotice, supervisorNoticeBody, cacheMissLine } from "./transcript-notices.ts";
7
+ export { compactGoalCard, compactSupervisorNotice } from "./transcript-cards.ts";
8
+ export type { NoticeRows, TurnNotices } from "./transcript-notice-render.ts";
290
9
 
291
10
  interface ContainerLike extends Component { children: Component[] }
292
11
  function isContainer(value: unknown): value is ContainerLike {
@@ -294,36 +13,6 @@ function isContainer(value: unknown): value is ContainerLike {
294
13
  return !!node && Array.isArray(node.children) && typeof node.render === "function" && typeof node.invalidate === "function";
295
14
  }
296
15
 
297
- function supervisorEnvelope(child: Component): unknown {
298
- if (child.constructor.name === "CustomMessageComponent") return (child as unknown as { message?: unknown }).message;
299
- if (child.constructor.name === "CustomEntryComponent") {
300
- const entry = record((child as unknown as { entry?: unknown }).entry);
301
- if (entry?.type === "custom" && entry.customType === "subagent_supervisor_reply") return entry;
302
- }
303
- }
304
-
305
- /** Pi 0.85.x private layout adapter. Never mutates the stored messages or child tree. */
306
- export type NoticeRows = string[] & {
307
- handleMouse?: Component["handleMouse"];
308
-
309
- };
310
- export type TurnNotices = ReadonlyMap<number, NoticeRows>;
311
-
312
- /** Pi writes one warning line per miss (`Cache miss…: N tokens re-billed`). */
313
- export function cacheMissLine(text: string): { label: string; tokens: number } | undefined {
314
- const plain = stripVTControlCharacters(text).replace(/\s+/g, " ").trim();
315
- const match = plain.match(/^(Cache miss\b.*?):\s*([\d,.]+)\s*([kKmM])?\s*tokens re-billed\b/);
316
- if (!match) return;
317
- const scale = match[3]?.toLowerCase() === "m" ? 1_000_000 : match[3]?.toLowerCase() === "k" ? 1_000 : 1;
318
- const tokens = Math.round(Number(match[2].replace(/,/g, "")) * scale);
319
- return Number.isFinite(tokens) ? { label: match[1], tokens } : undefined;
320
- }
321
-
322
- function formatCacheTokens(value: number): string {
323
- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
324
- if (value >= 1_000) return `${Math.round(value / 1_000)}k`;
325
- return String(value);
326
- }
327
16
  interface TranscriptView extends Component {
328
17
  render(width: number, notices?: TurnNotices): string[];
329
18
  clearHover?(): boolean;
@@ -336,27 +25,7 @@ interface TranscriptView extends Component {
336
25
  unpinSubagent?(): void;
337
26
  toggleSubagent?(id: string): void;
338
27
  }
339
- interface NoticeOptions {
340
- turnCount?: () => number;
341
- supervisor?: {
342
- theme: ExtensionContext["ui"]["theme"];
343
- expanded: () => boolean;
344
- handledRunIds?: () => Set<string>;
345
- onNotices?: (groups: Map<string | Component, { first: Component; messages: unknown[]; selected: unknown; notice: NonNullable<ReturnType<typeof supervisorNotice>> }>) => void;
346
- };
347
- /** Blocking extension prompts are native UI, never auto-expiring notices. */
348
- isPrompt?: (text: string) => boolean;
349
- isTransient?: (text: string) => boolean;
350
- /** Drop individual startup diagnostic lines, such as an unmatched model pattern. */
351
- hideStartupLine?: (line: string) => boolean;
352
- /** When false, Pi's per-turn cache-miss lines stay in the transcript. Default: fold them. */
353
- foldCacheMiss?: () => boolean;
354
- now?: () => number;
355
- schedule?: (callback: () => void, delay: number) => () => void;
356
- }
357
28
 
358
- // Keep expiry across minimal-mode remounts without retaining discarded sessions.
359
- const noticeTimes = new WeakMap<Component, { text: string; until: number }>();
360
29
  export function attachTranscript(tui: unknown, view: TranscriptView, options: NoticeOptions = {}): (() => void) | undefined {
361
30
  const host = tui as { children?: unknown[]; mode?: string; viewportTop?: number };
362
31
  // Regular mode owns terminal scrollback. Replacing its whole document means a
@@ -384,8 +53,14 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
384
53
  return () => clearTimeout(timer);
385
54
  });
386
55
  let cancelExpiry: (() => void) | undefined;
387
- const expandedNotices = new Map<string | Component, boolean>();
388
- let globalExpanded = options.supervisor?.expanded() ?? false;
56
+ const renderNotices = createTurnNoticeRenderer(chat, options, now, (nextExpiry, time) => {
57
+ if (Number.isFinite(nextExpiry)) {
58
+ cancelExpiry = schedule(() => {
59
+ cancelExpiry = undefined;
60
+ (tui as { requestRender?: () => void }).requestRender?.();
61
+ }, Math.max(0, nextExpiry - time));
62
+ }
63
+ });
389
64
  let prefixNotices: NoticeRows = [];
390
65
  let prefixNoticeOffset = 0;
391
66
  let viewOffset = 0;
@@ -395,174 +70,13 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
395
70
  const render: Component["render"] = (width) => {
396
71
  cancelExpiry?.();
397
72
  cancelExpiry = undefined;
398
- const notices = new Map<number, NoticeRows>();
399
- const expanded = options.supervisor?.expanded() ?? false;
400
- if (expanded !== globalExpanded) { expandedNotices.clear(); globalExpanded = expanded; }
401
- const groups = new Map<string | Component, { first: Component; messages: unknown[]; selected: unknown; notice: NonNullable<ReturnType<typeof supervisorNotice>> }>();
402
- if (options.supervisor) for (const child of chat.children) {
403
- const message = supervisorEnvelope(child);
404
- const notice = supervisorNotice(message);
405
- if (!notice) continue;
406
- const key = notice.key ?? child;
407
- const group = groups.get(key);
408
- if (!group) groups.set(key, { first: child, messages: [message], selected: message, notice });
409
- else {
410
- group.messages.push(message);
411
- // Failures stay sticky. A matching supervisor reply is the only
412
- // resolution for a blocking ask; progress and duplicate wait notices
413
- // must not bury the prompt or clear a failure.
414
- const resolved = isSupervisorReply(message) && group.notice.alert && group.notice.color !== "error";
415
- if (notice.color === "error" || (notice.alert && group.notice.color !== "error") || resolved
416
- || (!group.notice.alert && (!notice.internal || group.notice.internal))) {
417
- group.selected = message;
418
- group.notice = notice;
419
- }
420
- }
421
- }
422
- // String keys belong to aggregated supervisor notices; component keys belong
423
- // to independently rendered custom entries such as pi-codex-goal.
424
- for (const key of expandedNotices.keys()) if (typeof key === "string" && !groups.has(key)) expandedNotices.delete(key);
425
- options.supervisor?.onNotices?.(groups);
426
- const groupKeys = [...groups.keys()];
427
- const controls = new Map<number, Array<{ y: number; width: number; key: string | Component; expanded: boolean }>>();
428
- const nativeTurns = chat.children.filter(child => child.constructor.name === "UserMessageComponent").length;
429
- const totalTurns = options.turnCount?.() ?? nativeTurns;
430
- // ponytail: Pi rebuilds a retained suffix after compaction; explicit entry IDs
431
- // are needed if native history ever becomes a non-contiguous projection.
432
- if (!Number.isInteger(totalTurns) || totalTurns < nativeTurns) {
73
+ const notices = renderNotices(width);
74
+ if (!notices) {
433
75
  prefixNotices = [];
434
76
  prefixNoticeOffset = viewOffset = viewHeight = 0;
435
77
  view.clearHover?.();
436
78
  return originalRender.call(document, width);
437
79
  }
438
- let turn = totalTurns - nativeTurns - 1;
439
- let nextExpiry = Infinity;
440
- const time = now();
441
- const cacheMisses = new Map<number, { label: string; tokens: number; count: number; rows: string[] }>();
442
- const flushCache = (index: number) => {
443
- const miss = cacheMisses.get(index);
444
- if (!miss) return;
445
- cacheMisses.delete(index);
446
- const rows = notices.get(index) ?? [];
447
- // ponytail: first styled line carries the color; token text is plain digits so one replace is enough.
448
- const summary = miss.count === 1
449
- ? miss.rows[0]
450
- : miss.rows[0].replace(/[\d,.]+\s*[kKmM]?\s*tokens re-billed/, `${miss.count} misses, ${formatCacheTokens(miss.tokens)} tokens re-billed`);
451
- rows.push(summary);
452
- notices.set(index, rows);
453
- };
454
- for (const child of chat.children) {
455
- if (child.constructor.name === "UserMessageComponent") flushCache(turn);
456
- if (child.constructor.name === "UserMessageComponent") turn++;
457
- // Goal state is stored as a custom entry, not a user message. Adapt only
458
- // the known pi-codex-goal envelope so ordinary extension cards stay native.
459
- // Pi rebuilds this collapsed native component after every successful compaction.
460
- // Keep its one-line success marker at the current user turn without persisting another entry.
461
- if (child.constructor.name === "CompactionSummaryMessageComponent") {
462
- const rows = notices.get(turn) ?? [];
463
- rows.push(...child.render(width));
464
- notices.set(turn, rows);
465
- continue;
466
- }
467
- if (child.constructor.name === "CustomEntryComponent"
468
- && !(options.supervisor && supervisorNotice(supervisorEnvelope(child)))) {
469
- const goalRows = options.supervisor && compactGoalCard((child as unknown as { entry?: unknown }).entry, options.supervisor.theme, width, expandedNotices.get(child) ?? false);
470
- const rows = notices.get(turn) ?? [];
471
- if (!goalRows) {
472
- rows.push(...child.render(width));
473
- notices.set(turn, rows);
474
- continue;
475
- }
476
- const open = expandedNotices.get(child) ?? false;
477
- const targets = controls.get(turn) ?? [];
478
- targets.push({ y: rows.length, width, key: child, expanded: open });
479
- controls.set(turn, targets);
480
- rows.push(...goalRows);
481
- notices.set(turn, rows);
482
- continue;
483
- }
484
- // Known reply entries share notice grouping; unknown cards retain Pi's renderer.
485
- if (child.constructor.name === "CustomMessageComponent" || child.constructor.name === "CustomEntryComponent") {
486
- const rows = notices.get(turn) ?? [];
487
- const message = supervisorEnvelope(child);
488
- const notice = options.supervisor && supervisorNotice(message);
489
- const key = notice ? notice.key ?? child : child;
490
- const group = groups.get(key);
491
- if (group && group.first !== child) continue;
492
- if (group && options.supervisor) {
493
- const handled = options.supervisor.handledRunIds?.();
494
- const noticeIds = [notice?.runId, ...((notice as { runIds?: string[] } | undefined)?.runIds ?? [])].filter((id): id is string => !!id);
495
- if (handled && noticeIds.some(id => handled.has(id))) continue;
496
- const open = expandedNotices.get(key) ?? expanded;
497
- const label = group.notice.showLabel
498
- ? group.notice.label ?? ""
499
- : groups.size > 1 ? group.notice.label || `任务 ${groupKeys.indexOf(key) + 1}` : "";
500
- const targets = controls.get(turn) ?? [];
501
- targets.push({ y: rows.length, width, key, expanded: open });
502
- controls.set(turn, targets);
503
- rows.push(...compactSupervisorNotice(group.selected, options.supervisor.theme, width, open, label, group.messages)!);
504
- } else rows.push(...child.render(width));
505
- notices.set(turn, rows);
506
- continue;
507
- }
508
- // Pi 1.x renders command information (/session, /hotkeys) lazily for theme changes.
509
- if (child.constructor.name === "ThemedText") {
510
- const rows = notices.get(turn) ?? [];
511
- rows.push(...child.render(width));
512
- notices.set(turn, rows);
513
- continue;
514
- }
515
- // Tool images are step attachments, represented by hover links in the
516
- // compact view. Only assistant replies own inline image rows.
517
- if (child.constructor.name === "ToolExecutionComponent") continue;
518
- if (child.constructor.name !== "Text") continue;
519
- // Pi 0.85 Text stores the unwrapped styled source in text. Width changes
520
- // must not restart the timeout; setText updates must restart it.
521
- const source = (child as unknown as { text?: unknown }).text;
522
- const miss = options.foldCacheMiss?.() !== false && typeof source === "string" ? cacheMissLine(source) : undefined;
523
- if (miss) {
524
- const current = cacheMisses.get(turn) ?? { label: miss.label, tokens: 0, count: 0, rows: [] as string[] };
525
- current.tokens += miss.tokens;
526
- current.count++;
527
- current.rows.push(...child.render(width));
528
- cacheMisses.set(turn, current);
529
- continue;
530
- }
531
- if (typeof source === "string" && !options.isPrompt?.(source)) {
532
- if (options.hideStartupLine?.(source)) continue;
533
- if (options.isTransient?.(source)) {
534
- let state = noticeTimes.get(child);
535
- if (!state || state.text !== source) {
536
- state = { text: source, until: time + 5000 };
537
- noticeTimes.set(child, state);
538
- }
539
- if (time >= state.until) continue;
540
- nextExpiry = Math.min(nextExpiry, state.until);
541
- }
542
- }
543
- const rows = notices.get(turn) ?? [];
544
- rows.push(...child.render(width));
545
- notices.set(turn, rows);
546
- }
547
- flushCache(turn);
548
- if (Number.isFinite(nextExpiry)) {
549
- cancelExpiry = schedule(() => {
550
- cancelExpiry = undefined;
551
- (tui as { requestRender?: () => void }).requestRender?.();
552
- }, Math.max(0, nextExpiry - time));
553
- }
554
- for (const [turnIndex, targets] of controls) {
555
- notices.get(turnIndex)!.handleMouse = event => {
556
- if (event.button !== "left" || event.shift || event.ctrl || event.alt || (event.clickCount ?? 1) !== 1) return;
557
- const target = targets.find(target => event.y === target.y && event.x >= 0 && event.x < target.width);
558
- if (!target) return;
559
- if (event.type === "press") return { handled: true };
560
- if (event.type === "click") {
561
- expandedNotices.set(target.key, !target.expanded);
562
- return { handled: true, render: true };
563
- }
564
- };
565
- }
566
80
  const startupLine = options.hideStartupLine;
567
81
  const resourceRows = startupLine
568
82
  ? resources.render(width).filter(line => !startupLine(line))
@@ -0,0 +1,67 @@
1
+ import { Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { diagramMarkdown, isMarkdownProse, renderMinimalMarkdown } from "./minimal-markdown.ts";
4
+ import { clean, record, supervisorNotice, supervisorNoticeBody } from "./transcript-notices.ts";
5
+
6
+ const renderMarkdownBody = (body: string, width: number, theme?: ExtensionContext["ui"]["theme"]) => isMarkdownProse(body)
7
+ ? renderMinimalMarkdown(body, Math.max(1, width), getMarkdownTheme(), theme?.getBgAnsi?.("userMessageBg") ?? "", undefined, diagramMarkdown)
8
+ : new Text(body, 0, 0).render(Math.max(1, width));
9
+
10
+ export function compactGoalCard(entry: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean): string[] | undefined {
11
+ const item = record(entry);
12
+ if (item?.customType !== "pi-codex-goal") return;
13
+ const data = record(item.data);
14
+ const goal = record(data?.goal);
15
+ const objective = typeof goal?.objective === "string" ? clean(goal.objective) : undefined;
16
+ // Usage snapshots are rendered by the goal extension too, but are not cards
17
+ // worth adding to the compact transcript.
18
+ if (!objective || width <= 0) return;
19
+ const status = typeof goal?.status === "string" ? clean(goal.status) : "active";
20
+ const control = truncateToWidth(expanded ? "[收起]" : "[详情]", width, "");
21
+ const title = theme.fg(expanded ? "accent" : "muted", `${control} ◉ Goal · ${status}`);
22
+ const hint = theme.fg(expanded ? "accent" : "muted", " · Ctrl+O");
23
+ const summary = truncateToWidth(objective, Math.max(0, width - visibleWidth(title) - visibleWidth(hint) - 3), "…");
24
+ const rows = [truncateToWidth(`${title} · ${theme.fg(expanded ? "accent" : "text", summary)}${hint}`, width, "")];
25
+ if (expanded) rows.push(...renderMarkdownBody(objective, width, theme));
26
+ return rows;
27
+ }
28
+
29
+ export function compactSupervisorNotice(message: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean, label = "", history: unknown[] = [message]): string[] | undefined {
30
+ const notice = supervisorNotice(message);
31
+ if (!notice) return;
32
+ if (width <= 0) return [];
33
+ const { state, color, summary } = notice;
34
+ const effectiveLabel = label || (notice.showLabel ? notice.label ?? "" : "");
35
+ const control = truncateToWidth(expanded ? "[收起]" : "[详情]", width, "");
36
+ const hint = " · Ctrl+O";
37
+ let heading: string;
38
+ let summaryText: string;
39
+ if (expanded) {
40
+ const statusGlyph = color === "error" ? theme.fg("error", "× " + state)
41
+ : color === "warning" ? theme.fg("warning", "⚠ " + state)
42
+ : theme.fg("accent", "ℹ " + state);
43
+ const taskLabel = effectiveLabel ? theme.fg("accent", ` · ${truncateToWidth(effectiveLabel, 20)}`) : "";
44
+ heading = theme.fg("accent", control) + " " + statusGlyph + taskLabel;
45
+ summaryText = theme.fg("accent", summary);
46
+ } else {
47
+ const title = theme.fg(color, `${color === "error" ? "×" : color === "warning" ? "⚠" : "ℹ"} ${state}${effectiveLabel ? ` · ${truncateToWidth(effectiveLabel, 20)}` : ""}`);
48
+ heading = theme.fg("muted", control) + " " + title;
49
+ summaryText = theme.fg(color, summary);
50
+ }
51
+ const hintStyled = theme.fg(expanded ? "accent" : "muted", hint);
52
+ const available = width - visibleWidth(heading) - visibleWidth(hint) - 3;
53
+ const rows = available >= 24
54
+ ? [heading + " · " + truncateToWidth(summaryText, available) + hintStyled]
55
+ : [truncateToWidth(heading, width, ""), truncateToWidth(summaryText, Math.max(0, width - visibleWidth(hint)), "") + truncateToWidth(hintStyled, width, "")];
56
+ if (expanded) {
57
+ const bodies: string[] = [];
58
+ for (const original of history) {
59
+ const body = supervisorNoticeBody(original);
60
+ if (body && !bodies.includes(body)) bodies.push(body);
61
+ }
62
+ for (const body of bodies) {
63
+ rows.push(...renderMarkdownBody(body, width, theme));
64
+ }
65
+ }
66
+ return rows;
67
+ }