@each1024/pi-mini-mode 1.3.1 → 1.3.2

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,4 +1,247 @@
1
- import type { Component } from "@earendil-works/pi-tui";
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, minimalMarkdownTheme } from "./minimal-markdown.ts";
4
+ import { stripVTControlCharacters } from "node:util";
5
+ import { attachStickyTool } from "./sticky-tool.ts";
6
+
7
+ const record = (value: unknown): Record<string, unknown> | undefined => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
8
+ const clean = (text: string) => stripVTControlCharacters(text).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
9
+ const renderMarkdownBody = (body: string, width: number) => isMarkdownProse(body)
10
+ ? new Markdown(body, 0, 0, minimalMarkdownTheme(getMarkdownTheme()), undefined, { transform: diagramMarkdown }).render(Math.max(1, width))
11
+ : new Text(body, 0, 0).render(Math.max(1, width));
12
+ const isSupervisorReply = (message: unknown) => record(message)?.customType === "subagent_supervisor_reply";
13
+
14
+ /** Structured interview questions are the prompt; IDs and reply hints stay out. */
15
+ export function formatInterview(interview: unknown): string {
16
+ const data = record(interview);
17
+ if (!data) return typeof interview === "string" ? clean(interview) : "";
18
+ const lines: string[] = [];
19
+ if (typeof data.title === "string" && data.title.trim()) lines.push(clean(data.title));
20
+ const questions = Array.isArray(data.questions) ? data.questions : [];
21
+ questions.forEach((question, index) => {
22
+ if (typeof question === "string") {
23
+ if (question.trim()) lines.push(`${index + 1}. ${clean(question)}`);
24
+ return;
25
+ }
26
+ const item = record(question);
27
+ if (!item) return;
28
+ const prompt = [item.prompt, item.question, item.text, item.label].find(value => typeof value === "string" && String(value).trim());
29
+ if (typeof prompt === "string") lines.push(`${index + 1}. ${clean(prompt)}`);
30
+ const options = Array.isArray(item.options) ? item.options : Array.isArray(item.choices) ? item.choices : [];
31
+ for (const option of options) {
32
+ const label = typeof option === "string" ? option : typeof record(option)?.label === "string" ? String(record(option)!.label) : "";
33
+ if (label.trim()) lines.push(` - ${clean(label)}`);
34
+ }
35
+ });
36
+ return lines.join("\n");
37
+ }
38
+
39
+ function withInterview(body: string, interview: unknown): string {
40
+ const questions = formatInterview(interview);
41
+ if (!questions) return body;
42
+ return body ? `${body}\n${questions}` : questions;
43
+ }
44
+
45
+ export function extractNoticeBody(message: unknown): string {
46
+ const item = record(message);
47
+ if (!item) return typeof message === "string" ? clean(message) : "";
48
+ const details = record(item.details);
49
+ const interview = details?.interview;
50
+ if (details) {
51
+ const event = record(details.event);
52
+ const body = typeof details.requestBody === "string"
53
+ ? details.requestBody
54
+ : typeof event?.message === "string"
55
+ ? event.message
56
+ : typeof details.message === "string"
57
+ ? details.message
58
+ : undefined;
59
+ if (body) {
60
+ let cleanBody = stripVTControlCharacters(body).replace(/^UPDATE:\s*/i, "").trim();
61
+ const failureReason = typeof event?.reason === "string" && ["tool_failures", "completion_guard"].includes(event.reason)
62
+ ? event.reason === "tool_failures" ? "工具执行失败" : "任务完成受阻"
63
+ : undefined;
64
+ if (failureReason && !cleanBody.includes(failureReason)) cleanBody = `[${failureReason}] ${cleanBody}`;
65
+ return withInterview(cleanBody, interview);
66
+ }
67
+ const questions = formatInterview(interview);
68
+ if (questions) return questions;
69
+ }
70
+ const raw = typeof item.content === "string" ? item.content : "";
71
+ if (raw) {
72
+ const filtered = stripVTControlCharacters(raw)
73
+ .split(/\r?\n/)
74
+ .map(line => line.trim())
75
+ .filter(line => line
76
+ && !/^(?:Subagent (?:progress update|needs a supervisor decision|control notice)|Supervisor (?:progress update|decision request|interview request))\b/i.test(line)
77
+ && !/^(?:Run|Agent|Child index|Child target|Request ID|Live guidance|Reply with|Request|Interview shape):\s*/i.test(line)
78
+ && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(line)
79
+ )
80
+ .join("\n")
81
+ .replace(/^UPDATE:\s*/i, "")
82
+ .trim();
83
+ if (filtered) return withInterview(filtered, interview);
84
+ }
85
+ const questions = formatInterview(interview);
86
+ if (questions) return questions;
87
+ return typeof item.content === "string" ? item.content : JSON.stringify(item.content ?? item, null, 2);
88
+ }
89
+
90
+ /** Only pi-subagents' known envelopes carry state; prose is never a status signal. */
91
+ export function supervisorNotice(message: unknown) {
92
+ const item = record(message);
93
+ if (item?.customType === "subagent_supervisor_reply") {
94
+ const data = record(item.data);
95
+ if (item.type !== "custom" || !data
96
+ || typeof data.requestId !== "string" || typeof data.runId !== "string"
97
+ || typeof data.agent !== "string" || typeof data.message !== "string"
98
+ || typeof data.childIndex !== "number" || !Number.isFinite(data.childIndex)
99
+ || typeof data.createdAt !== "number" || !Number.isFinite(data.createdAt)
100
+ || (data.reason !== undefined && (typeof data.reason !== "string" || !["need_decision", "interview_request", "progress_update"].includes(data.reason)))
101
+ || (data.childTarget !== undefined && typeof data.childTarget !== "string")) return;
102
+ return {
103
+ key: data.runId && Number.isInteger(data.childIndex) && data.childIndex >= 0
104
+ && !data.nestedRunId && !data.nestingPath ? JSON.stringify([data.runId, data.childIndex]) : undefined,
105
+ runId: data.runId || undefined,
106
+ agent: data.agent,
107
+ internal: true,
108
+ alert: false,
109
+ state: "内部协作",
110
+ color: "muted" as const,
111
+ summary: "代理间沟通已收纳",
112
+ body: stripVTControlCharacters(data.message).trim(),
113
+ };
114
+ }
115
+ if (item?.type === "custom") return;
116
+ if (item?.customType === "subagent-incremental-child-notify") {
117
+ const content = typeof item.content === "string" ? item.content : undefined;
118
+ const header = content?.match(/^Workflow child (completed|failed):\s+\*\*([^*\n]+)\*\*\s*$/m);
119
+ if (!content || !header) return;
120
+ const failed = header[1] === "failed";
121
+ const error = content.match(/^Error:\s*([\s\S]*?)(?=^Status:|(?![\s\S]))/m)?.[1]
122
+ .split(/\r?\n/)
123
+ .map(line => line.trim())
124
+ .filter(line => line && !/^Run fan-out:/i.test(line))
125
+ .join(" ");
126
+ const childRunId = content.match(/^Child run:\s*([0-9a-f-]{36})\s*$/mi)?.[1];
127
+ return {
128
+ key: childRunId ? JSON.stringify(["incremental-child", childRunId]) : undefined,
129
+ runId: childRunId,
130
+ internal: false,
131
+ alert: failed,
132
+ state: failed ? "执行失败" : "已完成",
133
+ color: failed ? "error" as const : "muted" as const,
134
+ summary: error || (failed ? "子任务失败" : "子任务已完成"),
135
+ label: clean(header[2]),
136
+ showLabel: true,
137
+ body: content,
138
+ };
139
+ }
140
+ const details = record(item?.details);
141
+ if (!details) return;
142
+ const event = record(details.event);
143
+ const request = item?.customType === "subagent_supervisor_request";
144
+ if (request ? !["progress_update", "need_decision", "interview_request"].includes(String(details.reason))
145
+ : item?.customType !== "subagent_control_notice" || !event || !["needs_attention", "active_long_running"].includes(String(event.type))) return;
146
+ const data = request ? details : event!;
147
+ const body = request
148
+ ? (typeof details.requestBody === "string" ? details.requestBody : "")
149
+ : data.message;
150
+ if (typeof body !== "string" || typeof data.agent !== "string") return;
151
+ const ask = request && (details.reason === "need_decision" || details.reason === "interview_request");
152
+ // Replies and duplicate "waiting for supervisor" control notices stay compact.
153
+ // Blocking asks are the main-session prompt; progress remains a status line.
154
+ const internal = request
155
+ ? (!ask && (details.reason !== "progress_update" || details.expectsReply === true))
156
+ : data.reason === "supervisor_request";
157
+ const failed = !request && ["completion_guard", "tool_failures"].includes(String(data.reason));
158
+ const attention = ask || (!request && data.type === "needs_attention" && !internal);
159
+ const question = clean(body).replace(/^UPDATE:\s*/i, "");
160
+ const interviewTitle = typeof record(details.interview)?.title === "string" ? clean(String(record(details.interview)!.title)) : "";
161
+ const index = request ? data.childIndex : data.index;
162
+ const runId = typeof data.runId === "string" && data.runId ? data.runId : undefined;
163
+ // ponytail: aggregate only unambiguous run+child envelopes; nested/missing
164
+ // addresses stay separate until the producer provides a shared child identity.
165
+ const key = runId && Number.isInteger(index) && Number(index) >= 0
166
+ && !data.nestedRunId && !data.nestingPath ? JSON.stringify([runId, index]) : undefined;
167
+ return { key, runId, internal, alert: failed || attention,
168
+ state: failed ? "执行失败" : ask ? (details.reason === "interview_request" ? "需要提问" : "需要裁决")
169
+ : attention ? "需要关注" : internal ? "内部协作" : "进度",
170
+ color: failed ? "error" as const : attention ? "warning" as const : "muted" as const,
171
+ summary: internal ? "代理间沟通已收纳" : question || (ask ? interviewTitle || "等待回复" : "暂无摘要"),
172
+ label: typeof data.label === "string" ? clean(data.label) : typeof data.taskPreview === "string" ? clean(data.taskPreview) : undefined,
173
+ body: question,
174
+ agent: typeof data.agent === "string" ? data.agent : undefined,
175
+ };
176
+ }
177
+
178
+ /** Progress is a status preview, not detail prose; decisions and failures remain inspectable. */
179
+ export function supervisorNoticeBody(message: unknown): string {
180
+ const item = record(message);
181
+ if (item?.customType === "subagent_supervisor_request" && record(item.details)?.reason === "progress_update") return "";
182
+ const notice = supervisorNotice(message);
183
+ if (item?.type === "custom" && item.customType === "subagent_supervisor_reply") return notice?.body ?? "";
184
+ return notice?.alert || notice?.internal ? extractNoticeBody(message) : "";
185
+ }
186
+
187
+ export function compactGoalCard(entry: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean): string[] | undefined {
188
+ const item = record(entry);
189
+ if (item?.customType !== "pi-codex-goal") return;
190
+ const data = record(item.data);
191
+ const goal = record(data?.goal);
192
+ const objective = typeof goal?.objective === "string" ? clean(goal.objective) : undefined;
193
+ // Usage snapshots are rendered by the goal extension too, but are not cards
194
+ // worth adding to the compact transcript.
195
+ if (!objective || width <= 0) return;
196
+ const status = typeof goal?.status === "string" ? clean(goal.status) : "active";
197
+ const control = truncateToWidth(expanded ? "[收起]" : "[详情]", width, "");
198
+ const title = theme.fg(expanded ? "accent" : "muted", `${control} ◉ Goal · ${status}`);
199
+ const hint = theme.fg(expanded ? "accent" : "muted", " · Ctrl+O");
200
+ const summary = truncateToWidth(objective, Math.max(0, width - visibleWidth(title) - visibleWidth(hint) - 3), "…");
201
+ const rows = [truncateToWidth(`${title} · ${theme.fg(expanded ? "accent" : "text", summary)}${hint}`, width, "")];
202
+ if (expanded) rows.push(...renderMarkdownBody(objective, width));
203
+ return rows;
204
+ }
205
+
206
+ export function compactSupervisorNotice(message: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean, label = "", history: unknown[] = [message]): string[] | undefined {
207
+ const notice = supervisorNotice(message);
208
+ if (!notice) return;
209
+ if (width <= 0) return [];
210
+ const { state, color, summary } = notice;
211
+ const effectiveLabel = label || (notice.showLabel ? notice.label ?? "" : "");
212
+ const control = truncateToWidth(expanded ? "[收起]" : "[详情]", width, "");
213
+ const hint = " · Ctrl+O";
214
+ let heading: string;
215
+ let summaryText: string;
216
+ if (expanded) {
217
+ const statusGlyph = color === "error" ? theme.fg("error", "× " + state)
218
+ : color === "warning" ? theme.fg("warning", "⚠ " + state)
219
+ : theme.fg("accent", "ℹ " + state);
220
+ const taskLabel = effectiveLabel ? theme.fg("accent", ` · ${truncateToWidth(effectiveLabel, 20)}`) : "";
221
+ heading = theme.fg("accent", control) + " " + statusGlyph + taskLabel;
222
+ summaryText = theme.fg("accent", summary);
223
+ } else {
224
+ const title = theme.fg(color, `${color === "error" ? "×" : color === "warning" ? "⚠" : "ℹ"} ${state}${effectiveLabel ? ` · ${truncateToWidth(effectiveLabel, 20)}` : ""}`);
225
+ heading = theme.fg("muted", control) + " " + title;
226
+ summaryText = theme.fg(color, summary);
227
+ }
228
+ const hintStyled = theme.fg(expanded ? "accent" : "muted", hint);
229
+ const available = width - visibleWidth(heading) - visibleWidth(hint) - 3;
230
+ const rows = available >= 24
231
+ ? [heading + " · " + truncateToWidth(summaryText, available) + hintStyled]
232
+ : [truncateToWidth(heading, width, ""), truncateToWidth(summaryText, Math.max(0, width - visibleWidth(hint)), "") + truncateToWidth(hintStyled, width, "")];
233
+ if (expanded) {
234
+ const bodies: string[] = [];
235
+ for (const original of history) {
236
+ const body = supervisorNoticeBody(original);
237
+ if (body && !bodies.includes(body)) bodies.push(body);
238
+ }
239
+ for (const body of bodies) {
240
+ rows.push(...renderMarkdownBody(body, width));
241
+ }
242
+ }
243
+ return rows;
244
+ }
2
245
 
3
246
  interface ContainerLike extends Component { children: Component[] }
4
247
  function isContainer(value: unknown): value is ContainerLike {
@@ -6,12 +249,37 @@ function isContainer(value: unknown): value is ContainerLike {
6
249
  return !!node && Array.isArray(node.children) && typeof node.render === "function" && typeof node.invalidate === "function";
7
250
  }
8
251
 
252
+ function supervisorEnvelope(child: Component): unknown {
253
+ if (child.constructor.name === "CustomMessageComponent") return (child as unknown as { message?: unknown }).message;
254
+ if (child.constructor.name === "CustomEntryComponent") {
255
+ const entry = record((child as unknown as { entry?: unknown }).entry);
256
+ if (entry?.type === "custom" && entry.customType === "subagent_supervisor_reply") return entry;
257
+ }
258
+ }
259
+
9
260
  /** Pi 0.85.x private layout adapter. Never mutates the stored messages or child tree. */
10
- export type TurnNotices = ReadonlyMap<number, string[]>;
261
+ export type NoticeRows = string[] & { handleMouse?: Component["handleMouse"] };
262
+ export type TurnNotices = ReadonlyMap<number, NoticeRows>;
11
263
  interface TranscriptView extends Component {
12
264
  render(width: number, notices?: TurnNotices): string[];
265
+ clearHover?(): boolean;
266
+ pinnedTool?(): { id: string; y: number; line: string } | undefined;
267
+ unpinTool?(): void;
268
+ toggleTool?(id: string): void;
269
+ pinnedSubagent?(): { id: string; y: number; line: string; autoScroll?: boolean } | undefined;
270
+ unpinSubagent?(): void;
271
+ toggleSubagent?(id: string): void;
13
272
  }
14
273
  interface NoticeOptions {
274
+ turnCount?: () => number;
275
+ supervisor?: {
276
+ theme: ExtensionContext["ui"]["theme"];
277
+ expanded: () => boolean;
278
+ handledRunIds?: () => Set<string>;
279
+ onNotices?: (groups: Map<string | Component, { first: Component; messages: unknown[]; selected: unknown; notice: NonNullable<ReturnType<typeof supervisorNotice>> }>) => void;
280
+ };
281
+ /** Blocking extension prompts are native UI, never auto-expiring notices. */
282
+ isPrompt?: (text: string) => boolean;
15
283
  isTransient?: (text: string) => boolean;
16
284
  now?: () => number;
17
285
  schedule?: (callback: () => void, delay: number) => () => void;
@@ -20,9 +288,12 @@ interface NoticeOptions {
20
288
  // Keep expiry across minimal-mode remounts without retaining discarded sessions.
21
289
  const noticeTimes = new WeakMap<Component, { text: string; until: number }>();
22
290
  export function attachTranscript(tui: unknown, view: TranscriptView, options: NoticeOptions = {}): (() => void) | undefined {
23
- const host = tui as { children?: unknown[] };
24
- // Both regular and fullscreen retain this seven-container tree. Fullscreen's
25
- // ScrollView renders the same document instance. Fail closed on unknown layouts.
291
+ const host = tui as { children?: unknown[]; mode?: string; viewportTop?: number };
292
+ // Regular mode owns terminal scrollback. Replacing its whole document means a
293
+ // streamed update to an older row forces TuiMainScreen's scrollback-clearing redraw.
294
+ // Keep native transcript diffing there; fullscreen's ScrollView is safe to adapt.
295
+ if (host.mode === "regular") return;
296
+ // Both layouts retain this seven-container tree. Fail closed on unknown layouts.
26
297
  if (!Array.isArray(host.children) || host.children.length !== 7 || !host.children.every(isContainer)) return;
27
298
  const document = host.children[0] as ContainerLike;
28
299
  if (document.children.length !== 3 || !document.children.every(isContainer)) return;
@@ -42,20 +313,117 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
42
313
  return () => clearTimeout(timer);
43
314
  });
44
315
  let cancelExpiry: (() => void) | undefined;
316
+ const expandedNotices = new Map<string | Component, boolean>();
317
+ let globalExpanded = options.supervisor?.expanded() ?? false;
318
+ let prefixNotices: NoticeRows = [];
319
+ let prefixNoticeOffset = 0;
320
+ let viewOffset = 0;
321
+ let viewHeight = 0;
322
+ let stickyMinHeight = 0;
323
+ let viewportTop = host.viewportTop;
45
324
  const render: Component["render"] = (width) => {
46
325
  cancelExpiry?.();
47
326
  cancelExpiry = undefined;
48
- const notices = new Map<number, string[]>();
49
- let turn = -1;
327
+ const notices = new Map<number, NoticeRows>();
328
+ const expanded = options.supervisor?.expanded() ?? false;
329
+ if (expanded !== globalExpanded) { expandedNotices.clear(); globalExpanded = expanded; }
330
+ const groups = new Map<string | Component, { first: Component; messages: unknown[]; selected: unknown; notice: NonNullable<ReturnType<typeof supervisorNotice>> }>();
331
+ if (options.supervisor) for (const child of chat.children) {
332
+ const message = supervisorEnvelope(child);
333
+ const notice = supervisorNotice(message);
334
+ if (!notice) continue;
335
+ const key = notice.key ?? child;
336
+ const group = groups.get(key);
337
+ if (!group) groups.set(key, { first: child, messages: [message], selected: message, notice });
338
+ else {
339
+ group.messages.push(message);
340
+ // Failures stay sticky. A matching supervisor reply is the only
341
+ // resolution for a blocking ask; progress and duplicate wait notices
342
+ // must not bury the prompt or clear a failure.
343
+ const resolved = isSupervisorReply(message) && group.notice.alert && group.notice.color !== "error";
344
+ if (notice.color === "error" || (notice.alert && group.notice.color !== "error") || resolved
345
+ || (!group.notice.alert && (!notice.internal || group.notice.internal))) {
346
+ group.selected = message;
347
+ group.notice = notice;
348
+ }
349
+ }
350
+ }
351
+ // String keys belong to aggregated supervisor notices; component keys belong
352
+ // to independently rendered custom entries such as pi-codex-goal.
353
+ for (const key of expandedNotices.keys()) if (typeof key === "string" && !groups.has(key)) expandedNotices.delete(key);
354
+ options.supervisor?.onNotices?.(groups);
355
+ const groupKeys = [...groups.keys()];
356
+ const controls = new Map<number, Array<{ y: number; width: number; key: string | Component; expanded: boolean }>>();
357
+ const nativeTurns = chat.children.filter(child => child.constructor.name === "UserMessageComponent").length;
358
+ const totalTurns = options.turnCount?.() ?? nativeTurns;
359
+ // ponytail: Pi rebuilds a retained suffix after compaction; explicit entry IDs
360
+ // are needed if native history ever becomes a non-contiguous projection.
361
+ if (!Number.isInteger(totalTurns) || totalTurns < nativeTurns) {
362
+ prefixNotices = [];
363
+ prefixNoticeOffset = viewOffset = viewHeight = 0;
364
+ view.clearHover?.();
365
+ return originalRender.call(document, width);
366
+ }
367
+ let turn = totalTurns - nativeTurns - 1;
50
368
  let nextExpiry = Infinity;
51
369
  const time = now();
52
370
  for (const child of chat.children) {
53
371
  if (child.constructor.name === "UserMessageComponent") turn++;
372
+ // Goal state is stored as a custom entry, not a user message. Adapt only
373
+ // the known pi-codex-goal envelope so ordinary extension cards stay native.
374
+ // Pi rebuilds this collapsed native component after every successful compaction.
375
+ // Keep its one-line success marker at the current user turn without persisting another entry.
376
+ if (child.constructor.name === "CompactionSummaryMessageComponent") {
377
+ const rows = notices.get(turn) ?? [];
378
+ rows.push(...child.render(width));
379
+ notices.set(turn, rows);
380
+ continue;
381
+ }
382
+ if (child.constructor.name === "CustomEntryComponent"
383
+ && !(options.supervisor && supervisorNotice(supervisorEnvelope(child)))) {
384
+ const goalRows = options.supervisor && compactGoalCard((child as unknown as { entry?: unknown }).entry, options.supervisor.theme, width, expandedNotices.get(child) ?? false);
385
+ const rows = notices.get(turn) ?? [];
386
+ if (!goalRows) {
387
+ rows.push(...child.render(width));
388
+ notices.set(turn, rows);
389
+ continue;
390
+ }
391
+ const open = expandedNotices.get(child) ?? false;
392
+ const targets = controls.get(turn) ?? [];
393
+ targets.push({ y: rows.length, width, key: child, expanded: open });
394
+ controls.set(turn, targets);
395
+ rows.push(...goalRows);
396
+ notices.set(turn, rows);
397
+ continue;
398
+ }
399
+ // Known reply entries share notice grouping; unknown cards retain Pi's renderer.
400
+ if (child.constructor.name === "CustomMessageComponent" || child.constructor.name === "CustomEntryComponent") {
401
+ const rows = notices.get(turn) ?? [];
402
+ const message = supervisorEnvelope(child);
403
+ const notice = options.supervisor && supervisorNotice(message);
404
+ const key = notice ? notice.key ?? child : child;
405
+ const group = groups.get(key);
406
+ if (group && group.first !== child) continue;
407
+ if (group && options.supervisor) {
408
+ const handled = options.supervisor.handledRunIds?.();
409
+ if (handled && notice?.runId && handled.has(notice.runId)) continue;
410
+ const open = expandedNotices.get(key) ?? expanded;
411
+ const label = group.notice.showLabel
412
+ ? group.notice.label ?? ""
413
+ : groups.size > 1 ? group.notice.label || `任务 ${groupKeys.indexOf(key) + 1}` : "";
414
+ const targets = controls.get(turn) ?? [];
415
+ targets.push({ y: rows.length, width, key, expanded: open });
416
+ controls.set(turn, targets);
417
+ rows.push(...compactSupervisorNotice(group.selected, options.supervisor.theme, width, open, label, group.messages)!);
418
+ } else rows.push(...child.render(width));
419
+ notices.set(turn, rows);
420
+ continue;
421
+ }
54
422
  if (child.constructor.name !== "Text") continue;
55
423
  // Pi 0.85 Text stores the unwrapped styled source in text. Width changes
56
424
  // must not restart the timeout; setText updates must restart it.
57
425
  const source = (child as unknown as { text?: unknown }).text;
58
- if (typeof source === "string" && options.isTransient?.(source)) {
426
+ if (typeof source === "string" && !options.isPrompt?.(source) && options.isTransient?.(source)) {
59
427
  let state = noticeTimes.get(child);
60
428
  if (!state || state.text !== source) {
61
429
  state = { text: source, until: time + 5000 };
@@ -74,16 +442,85 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
74
442
  (tui as { requestRender?: () => void }).requestRender?.();
75
443
  }, Math.max(0, nextExpiry - time));
76
444
  }
77
- return [...header.render(width), ...resources.render(width),
78
- ...(notices.get(-1) ?? []), ...view.render(width, notices)];
445
+ for (const [turnIndex, targets] of controls) {
446
+ notices.get(turnIndex)!.handleMouse = event => {
447
+ if (event.button !== "left" || event.shift || event.ctrl || event.alt || (event.clickCount ?? 1) !== 1) return;
448
+ const target = targets.find(target => event.y === target.y && event.x >= 0 && event.x < target.width);
449
+ if (!target) return;
450
+ if (event.type === "press") return { handled: true };
451
+ if (event.type === "click") {
452
+ expandedNotices.set(target.key, !target.expanded);
453
+ return { handled: true, render: true };
454
+ }
455
+ };
456
+ }
457
+ const prefix = [...header.render(width), ...resources.render(width)];
458
+ prefixNoticeOffset = prefix.length;
459
+ prefixNotices = notices.get(-1) ?? [];
460
+ prefix.push(...prefixNotices);
461
+ if (viewportTop !== host.viewportTop || viewOffset !== prefix.length) view.clearHover?.();
462
+ viewportTop = host.viewportTop;
463
+ const rows = view.render(width, notices);
464
+ viewOffset = prefix.length;
465
+ viewHeight = rows.length;
466
+ const result = [...prefix, ...rows];
467
+ while (result.length < stickyMinHeight) result.push("");
468
+ return result;
79
469
  };
80
470
  // Do not dispatch pointer events into invisible native message components.
81
471
  // Unhandled events still reach the parent ScrollView / selection machinery.
82
- const mouse: NonNullable<Component["handleMouse"]> = () => undefined;
472
+ const mouse: NonNullable<Component["handleMouse"]> = event => {
473
+ const cleared = (event.type === "wheel" || event.y < viewOffset || event.y >= viewOffset + viewHeight) && view.clearHover?.();
474
+ if (cleared && event.type === "move") return { handled: true, render: true };
475
+ if (event.y >= prefixNoticeOffset && event.y < viewOffset) return prefixNotices.handleMouse?.({ ...event, y: event.y - prefixNoticeOffset });
476
+ if (event.y < viewOffset || event.y >= viewOffset + viewHeight) return;
477
+ return view.handleMouse?.({ ...event, y: event.y - viewOffset, height: viewHeight });
478
+ };
83
479
  document.render = render;
84
480
  document.handleMouse = mouse;
481
+ // Dock events never reach the document. Observe normalized events without
482
+ // stealing wheel/selection or changing Pi's mouse protocol/listener order.
483
+ const restoreDock = view.clearHover ? host.children.slice(1).map(child => {
484
+ const dock = child as Component;
485
+ const descriptor = Object.getOwnPropertyDescriptor(dock, "handleMouse");
486
+ const original = dock.handleMouse;
487
+ const handle: NonNullable<Component["handleMouse"]> = event => {
488
+ const cleared = view.clearHover?.();
489
+ const result = original?.call(dock, event);
490
+ if (result) return cleared ? { ...result, render: true } : result;
491
+ return cleared && event.type === "move" ? { handled: true, render: true } : undefined;
492
+ };
493
+ dock.handleMouse = handle;
494
+ return () => {
495
+ if (dock.handleMouse !== handle) return;
496
+ if (descriptor) Object.defineProperty(dock, "handleMouse", descriptor);
497
+ else delete dock.handleMouse;
498
+ };
499
+ }) : [];
500
+ const hasStickyTool = view.pinnedTool && view.unpinTool && view.toggleTool;
501
+ const hasStickySubagent = view.pinnedSubagent && view.unpinSubagent && view.toggleSubagent;
502
+ const restoreSticky = hasStickyTool || hasStickySubagent ? attachStickyTool(tui, document, {
503
+ pinnedTool: () => {
504
+ const target = view.pinnedSubagent?.() ?? view.pinnedTool?.();
505
+ if (!target) return;
506
+ const kind = view.pinnedSubagent?.() ? "subagent" : "tool";
507
+ return { ...target, id: `${kind}:${target.id}`, y: target.y + viewOffset };
508
+ },
509
+ unpinTool: () => {
510
+ view.unpinSubagent?.();
511
+ view.unpinTool?.();
512
+ },
513
+ toggleTool: id => {
514
+ const [kind, targetId] = id.split(":", 2);
515
+ if (kind === "subagent") view.toggleSubagent?.(targetId);
516
+ else if (kind === "tool") view.toggleTool?.(targetId);
517
+ },
518
+ }, height => { stickyMinHeight = height; }) : undefined;
85
519
  return () => {
520
+ restoreSticky?.();
86
521
  cancelExpiry?.();
522
+ view.clearHover?.();
523
+ for (const restore of restoreDock) restore();
87
524
  if (document.render === render) {
88
525
  if (renderDescriptor) Object.defineProperty(document, "render", renderDescriptor);
89
526
  else { delete (document as Partial<Component>).render; if (document.render !== originalRender) document.render = originalRender; }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@each1024/pi-mini-mode",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
4
4
  "description": "A compact Pi footer with live usage metrics, theme-aware settings previews, and configurable progress bars.",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "check": "tsc --noEmit -p tsconfig.json",
8
- "test": "node test/footer-status-self-check.mjs && node test/settings-interaction.mjs && node test/transcript-adapter.mjs && node test/minimal-markdown.mjs && node test/agent-view.mjs && node test/publish-self-check.mjs"
8
+ "test": "node test/footer-status-self-check.mjs && node test/settings-interaction.mjs && node test/transcript-adapter.mjs && node test/prompt-folding.mjs && node test/tool-folding.mjs && node test/sticky-tool.mjs && node test/minimal-markdown.mjs && node test/agent-view.mjs && node test/publish-self-check.mjs && node test/compaction-transcript.mjs"
9
9
  },
10
10
  "license": "MIT",
11
11
  "author": "eachann1024",
@@ -28,6 +28,10 @@
28
28
  "video": "https://raw.githubusercontent.com/eachann1024/pi-mini-mode/main/assets/mini-lens-settings.mp4",
29
29
  "extensions": [
30
30
  "./extensions/footer-status.ts"
31
+ ],
32
+ "themes": [
33
+ "./themes/cc-dark.json",
34
+ "./themes/cc-light.json"
31
35
  ]
32
36
  },
33
37
  "peerDependencies": {
@@ -37,8 +41,8 @@
37
41
  "files": [
38
42
  "extensions",
39
43
  "lib",
44
+ "themes",
40
45
  "README.md",
41
- "README.zh-CN.md",
42
46
  "LICENSE"
43
47
  ],
44
48
  "publishConfig": {
@@ -46,6 +50,7 @@
46
50
  },
47
51
  "devDependencies": {
48
52
  "@earendil-works/pi-coding-agent": "^0.85.0",
53
+ "@earendil-works/pi-server": "0.85.0",
49
54
  "@earendil-works/pi-tui": "^0.85.0",
50
55
  "@types/node": "^26.4.1",
51
56
  "typescript": "^5.9.3"
@@ -0,0 +1,5 @@
1
+ # Themes
2
+
3
+ `cc-dark` and `cc-light` are vendored from the npm package [pi-cc-extensions](https://github.com/minuque/pi-cc-extensions) (MIT).
4
+
5
+ They are included here so this package can provide the `cc-light/cc-dark` theme pair without depending on `pi-cc-extensions` at runtime.
@@ -0,0 +1,91 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
3
+ "name": "cc-dark",
4
+ "vars": {
5
+ "bg": "#131217",
6
+ "panel": "#1b1922",
7
+ "surface": "#211e2b",
8
+ "surfaceRaised": "#292533",
9
+ "border": "#36313f",
10
+ "borderMuted": "#292631",
11
+ "accent": "#5e9cff",
12
+ "accentBright": "#8ab4ff",
13
+ "purple": "#c084fc",
14
+ "pink": "#f472b6",
15
+ "cyan": "#67e8f9",
16
+ "blue": "#60a5fa",
17
+ "green": "#4ade80",
18
+ "red": "#fb7185",
19
+ "yellow": "#facc15",
20
+ "orange": "#fb923c",
21
+ "text": "#f5f5f5",
22
+ "muted": "#a1a1aa",
23
+ "dim": "#71717a",
24
+ "selectedBg": "#252035",
25
+ "userMessageBg": "#1e1e2e",
26
+ "toolPendingBg": "#1b1924",
27
+ "toolSuccessBg": "#1e1e2e",
28
+ "toolErrorBg": "#2a1b22",
29
+ "customMessageBg": "#211c30"
30
+ },
31
+ "colors": {
32
+ "accent": "accent",
33
+ "border": "border",
34
+ "borderAccent": "accent",
35
+ "borderMuted": "borderMuted",
36
+ "success": "green",
37
+ "error": "red",
38
+ "warning": "yellow",
39
+ "muted": "muted",
40
+ "dim": "dim",
41
+ "text": "text",
42
+ "thinkingText": "muted",
43
+ "selectedBg": "selectedBg",
44
+ "scrollbarThumb": "selectedBg",
45
+ "userMessageBg": "userMessageBg",
46
+ "userMessageText": "text",
47
+ "customMessageBg": "customMessageBg",
48
+ "customMessageText": "text",
49
+ "customMessageLabel": "purple",
50
+ "toolPendingBg": "toolPendingBg",
51
+ "toolSuccessBg": "toolSuccessBg",
52
+ "toolErrorBg": "toolErrorBg",
53
+ "toolTitle": "accentBright",
54
+ "toolOutput": "muted",
55
+ "mdHeading": "accentBright",
56
+ "mdLink": "cyan",
57
+ "mdLinkUrl": "muted",
58
+ "mdCode": "accentBright",
59
+ "mdCodeBlock": "text",
60
+ "mdCodeBlockBorder": "border",
61
+ "mdQuote": "muted",
62
+ "mdQuoteBorder": "accent",
63
+ "mdHr": "borderMuted",
64
+ "mdListBullet": "accent",
65
+ "toolDiffAdded": "green",
66
+ "toolDiffRemoved": "red",
67
+ "toolDiffContext": "muted",
68
+ "syntaxComment": "#6b7280",
69
+ "syntaxKeyword": "pink",
70
+ "syntaxFunction": "accentBright",
71
+ "syntaxVariable": "blue",
72
+ "syntaxString": "green",
73
+ "syntaxNumber": "orange",
74
+ "syntaxType": "cyan",
75
+ "syntaxOperator": "text",
76
+ "syntaxPunctuation": "muted",
77
+ "thinkingOff": "muted",
78
+ "thinkingMinimal": "dim",
79
+ "thinkingLow": "blue",
80
+ "thinkingMedium": "accent",
81
+ "thinkingHigh": "accentBright",
82
+ "thinkingXhigh": "#4db9cd",
83
+ "thinkingMax": "cyan",
84
+ "bashMode": "green"
85
+ },
86
+ "export": {
87
+ "pageBg": "bg",
88
+ "cardBg": "panel",
89
+ "infoBg": "surface"
90
+ }
91
+ }