@notrico/pi-fold 0.0.0-stage → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/LICENSE +21 -0
  3. package/README.md +71 -2
  4. package/docs/implementation.md +47 -0
  5. package/docs/performance.md +118 -0
  6. package/docs/renderer-reference.md +110 -0
  7. package/index.ts +53 -0
  8. package/package.json +55 -4
  9. package/scripts/performance-review.mjs +273 -0
  10. package/scripts/preview-inspection.mjs +9 -0
  11. package/scripts/preview-work-strip.mjs +101 -0
  12. package/scripts/preview.mjs +232 -0
  13. package/scripts/retained-memory-review.mjs +46 -0
  14. package/scripts/test.mjs +21 -0
  15. package/src/action-intent.ts +93 -0
  16. package/src/display-card.ts +66 -0
  17. package/src/display-line-cache.ts +26 -0
  18. package/src/display-mode.ts +33 -0
  19. package/src/fold-command.ts +61 -0
  20. package/src/inspection.ts +87 -0
  21. package/src/modern-code-content.ts +131 -0
  22. package/src/modern-code-pane.ts +103 -0
  23. package/src/modern-native-tools.ts +79 -0
  24. package/src/modern-prompts-adapter.ts +41 -0
  25. package/src/modern-prompts.ts +185 -0
  26. package/src/modern-recorded-pane.ts +68 -0
  27. package/src/modern-rich-text.ts +48 -0
  28. package/src/modern-skill-prompts.ts +152 -0
  29. package/src/modern-subagent-groups.ts +158 -0
  30. package/src/modern-subagent-messages.ts +176 -0
  31. package/src/modern-subagent-spacing.ts +35 -0
  32. package/src/modern-subagents.ts +52 -0
  33. package/src/modern-thinking-adapter.ts +85 -0
  34. package/src/modern-thinking.ts +258 -0
  35. package/src/modern-tool-content.ts +28 -0
  36. package/src/modern-tool-images.ts +63 -0
  37. package/src/modern-tool-pane.ts +219 -0
  38. package/src/modern-tools.ts +509 -0
  39. package/src/modern-workflows.ts +212 -0
  40. package/src/native-method-chain.ts +31 -0
  41. package/src/permission-presentation.ts +280 -0
  42. package/src/recorded-summary.ts +13 -0
  43. package/src/work-strip-subagents.ts +221 -0
  44. package/src/work-strip-view.ts +112 -0
  45. package/src/work-strip.ts +443 -0
  46. package/tests/action-intent.test.mjs +44 -0
  47. package/tests/codemode.test.mjs +388 -0
  48. package/tests/display-cache-lifecycle.test.mjs +55 -0
  49. package/tests/display-line-cache.test.mjs +48 -0
  50. package/tests/display-mode.test.mjs +25 -0
  51. package/tests/fixtures/preview-fixture.ts +81 -0
  52. package/tests/fold-command.test.mjs +150 -0
  53. package/tests/fold-shortcut.test.mjs +143 -0
  54. package/tests/input-focus.test.mjs +95 -0
  55. package/tests/inspection-wheel.test.mjs +73 -0
  56. package/tests/inspection.test.mjs +50 -0
  57. package/tests/mixed-thinking.test.mjs +371 -0
  58. package/tests/modern-prompts.test.mjs +84 -0
  59. package/tests/modern-skill-prompts.test.mjs +174 -0
  60. package/tests/modern-subagent-groups.test.mjs +132 -0
  61. package/tests/modern-subagent-messages.test.mjs +137 -0
  62. package/tests/modern-thinking.test.mjs +202 -0
  63. package/tests/modern-tools.test.mjs +961 -0
  64. package/tests/modern-workflows.test.mjs +189 -0
  65. package/tests/ordinary-prompts.test.mjs +167 -0
  66. package/tests/permission-presentation.test.mjs +257 -0
  67. package/tests/preview-example.test.mjs +171 -0
  68. package/tests/reload-lifecycle.test.mjs +161 -0
  69. package/tests/subagent-spacing.test.mjs +34 -0
  70. package/tests/test-runtime.mjs +58 -0
  71. package/tests/work-strip-final-surface.test.mjs +321 -0
  72. package/tests/work-strip-hierarchy.test.mjs +258 -0
  73. package/tests/work-strip-preview.test.mjs +120 -0
  74. package/tests/work-strip-spacing.test.mjs +208 -0
  75. package/tests/work-strip-subagents.test.mjs +236 -0
  76. package/tests/work-strip.test.mjs +148 -0
@@ -0,0 +1,35 @@
1
+ import { CustomMessageComponent, VERSION } from '@earendil-works/pi-coding-agent';
2
+ import { Container } from '@earendil-works/pi-tui';
3
+
4
+ const hidden = Symbol.for('compact-renderer:subagent-hidden:v1');
5
+
6
+ /** Pi owns the spacer outside custom renderers. Suppress that spacer only for
7
+ * our marked grouped followers; an empty unrelated renderer keeps native layout.
8
+ * CustomEntryComponent is not exported by Pi, so this guarded inherited-method
9
+ * seam avoids importing private modules or replacing the transcript container. */
10
+ export function installSubagentSpacingAdapter(version = VERSION): (() => void) | undefined {
11
+ const proto = Container.prototype as any;
12
+ if (version !== '1.3.0' || typeof proto.render !== 'function') return;
13
+ const owner = Symbol.for('compact-renderer:subagent-spacing:v1');
14
+ proto[owner]?.();
15
+ const original = proto.render;
16
+ let disposed = false;
17
+ const wrapped = function(this: any, width: number) {
18
+ const component = this.customComponent;
19
+ const message = this instanceof CustomMessageComponent && this.message?.role === 'custom';
20
+ const entry = this.constructor?.name === 'CustomEntryComponent' && this.entry?.type === 'custom' && typeof this.renderer === 'function';
21
+ if (!disposed && (message || entry) && Array.isArray(this.children) && this.children.includes(component) && typeof component?.[hidden] === 'function') {
22
+ // The marker is owned by Pi Fold, not supplied by transcript data.
23
+ try { if (component[hidden]() === true) return []; } catch { /* Preserve native layout on incompatible state. */ }
24
+ }
25
+ return original.call(this, width);
26
+ };
27
+ const dispose = () => {
28
+ if (disposed) return;
29
+ disposed = true;
30
+ if (proto.render === wrapped) proto.render = original;
31
+ if (proto[owner] === dispose) delete proto[owner];
32
+ };
33
+ proto.render = wrapped; proto[owner] = dispose;
34
+ return dispose;
35
+ }
@@ -0,0 +1,52 @@
1
+ const shortName = (name: string) => name.split("__").at(-1) || name;
2
+ const label = (value: unknown) => typeof value === "string" ? value.slice(0, 72).replace(/[\uD800-\uDBFF]$/, "").replace(/[\x00-\x1f\x7f-\x9f]|\p{Cf}/gu, " ").trim() : "";
3
+ export const compactSubagent = (name: string) => /^(?:subagents?(?:_|$)|contact_supervisor$)/i.test(shortName(name));
4
+ export const subagentDecision = (name: string, args: any) => shortName(name) === "contact_supervisor" && ["need_decision", "interview_request"].includes(args?.reason);
5
+
6
+ /** Summarize only recorded contracts. Tool completion does not establish child completion. */
7
+ export function subagentTitle(name: string, args: any, result: any, status: string): string {
8
+ const short = shortName(name), details = result?.details;
9
+ const failed = status === "failed" || result?.isError;
10
+ const waiting = !result || status === "running" || status === "pending";
11
+ const phase = status === "pending" ? "Preparing" : "Running";
12
+ if (short === "contact_supervisor") {
13
+ const decision = subagentDecision(name, args);
14
+ const title = decision ? "Supervisor decision" : "Supervisor update";
15
+ const state = failed ? "✗ Failed" : waiting ? decision ? "Pending" : phase
16
+ : details?.reason === "progress_update" && details?.delivered === true ? "Queued"
17
+ : ["need_decision", "interview_request"].includes(details?.reason) && typeof details?.requestId === "string" ? "Reply recorded" : "Result recorded";
18
+ return `${title} · ${state}`;
19
+ }
20
+ const supervisor = short === "subagent_supervisor";
21
+ const action = label(args?.action) || (supervisor ? "request" : ["subagent", "subagents"].includes(short) ? "launch" : label(short.replace(/^subagents?_/, "")));
22
+ // Targets such as run/request UUIDs and arbitrary messages belong in Details.
23
+ const agent = label(details?.agent ?? args?.agent);
24
+ const topic = action === "guide" ? label(args?.options?.topic) : "";
25
+ const title = `${supervisor ? "Supervisor" : "Subagent"} · ${action}${topic ? ` · ${topic}` : agent ? ` · ${agent}` : ""}`;
26
+ if (failed) return `${title} · ✗ Failed · ${action === "steer" ? details?.steering ? "Steering failed" : "Steering rejected" : action === "launch" ? details?.activeAsyncCapacity ? "Capacity reached" : "Launch failed" : "Request failed"}`;
27
+ if (waiting) return `${title} · ${phase}`;
28
+ if (action === "guide") return title;
29
+ if (supervisor && action === "reply" && typeof details?.replyTo === "string") return `${title} · Reply recorded`;
30
+ if (action === "steer") {
31
+ const steering = details?.steering;
32
+ const state = steering?.state;
33
+ // Keep partial, scheduled and recovered receipts distinct from delivery.
34
+ const states: Record<string, string> = { failed: "Steering failed", partial: "Partial steering result", scheduled: "Scheduled", recovered: "Recovered", delivered: "Delivered" };
35
+ const receipt = typeof state === "string" && Object.hasOwn(states, state) ? states[state] : undefined;
36
+ return `${title} · ${receipt ?? (steering?.deliveryStatus === "queued" ? "Queued" : "Result recorded")}`;
37
+ }
38
+ if (["status", "pending", "list"].includes(action)) return `${title} · Status recorded`;
39
+ if (action === "launch" || action === "resume") {
40
+ const results = details?.results;
41
+ const launchMode = ["single", "parallel", "chain", "workflow"].includes(details?.mode);
42
+ if (launchMode && Array.isArray(results)) {
43
+ if (!results.length && typeof details?.asyncId === "string" && details.asyncId) return `${title} · Started asynchronously`;
44
+ if (results.some((item: any) => item?.detached === true)) return `${title} · Detached`;
45
+ if (results.some((item: any) => item?.interrupted === true)) return `${title} · Interrupted`;
46
+ if (results.some((item: any) => item?.timedOut === true)) return `${title} · Timed out`;
47
+ if (results.some((item: any) => item?.stopped === true)) return `${title} · Stopped`;
48
+ if (results.length && results.every((item: any) => item && item.exitCode === 0 && !item.error && !item.outputPartial && !item.turnBudgetExceeded && !item.toolBudgetBlocked && !item.structuredOutputFailed && (!item.execution || item.execution.status === "completed"))) return `${title} · Completed`;
49
+ }
50
+ }
51
+ return `${title} · Result recorded`;
52
+ }
@@ -0,0 +1,85 @@
1
+ import { AssistantMessageComponent, VERSION } from "@earendil-works/pi-coding-agent";
2
+ import { Markdown, MouseRegion, Spacer, Text } from "@earendil-works/pi-tui";
3
+ import { chainNativeMethod } from "./native-method-chain.ts";
4
+
5
+ /** Private Pi 1.3.0 seam: only pure hidden-thinking assistant containers qualify.
6
+ * Native Ctrl+T/per-run expansion and unknown component shapes always win. */
7
+ export function hiddenThinkingShape(component: any, message: any): boolean {
8
+ if (component.lastMessage !== message || component.hideThinkingBlock !== true || !(component.thinkingVisibilityOverrides instanceof Map)) return false;
9
+ if ([...component.thinkingVisibilityOverrides.values()].some(value => value === false)) return false;
10
+ const children = component.contentContainer?.children;
11
+ let expected = 0, inRun = false, nonempty = false;
12
+ for (const block of message?.content || []) {
13
+ if (block.type !== "thinking") { inRun = false; nonempty = false; continue; }
14
+ if (!inRun) { inRun = true; nonempty = false; }
15
+ if (!nonempty && typeof block.thinking === "string" && block.thinking.trim()) { expected++; nonempty = true; }
16
+ }
17
+ return Array.isArray(children) && children.filter((c: any) => c instanceof MouseRegion).length === expected && children.every((c: any) => c instanceof Spacer || c instanceof MouseRegion && c.child instanceof Text);
18
+ }
19
+ /** One hidden run beside native reply text. Validate the exact native sequence;
20
+ * interleaved runs and unfamiliar/error layouts retain their native rendering. */
21
+ export function mixedThinkingRegion(component: any, message: any): any | undefined {
22
+ if (component.lastMessage !== message || component.hideThinkingBlock !== true || !(component.thinkingVisibilityOverrides instanceof Map)
23
+ || [...component.thinkingVisibilityOverrides.values()].some(value => value === false)
24
+ || ["error", "aborted", "length"].includes(message?.stopReason)) return;
25
+ const expected: string[] = [], visible: string[] = [];
26
+ let inRun = false, nonempty = false;
27
+ for (const block of message?.content || []) {
28
+ if (block.type === "thinking") {
29
+ if (!inRun) { inRun = true; nonempty = false; }
30
+ if (!nonempty && typeof block.thinking === "string" && block.thinking.trim()) { visible.push("thinking"); nonempty = true; }
31
+ } else {
32
+ inRun = false;
33
+ if (block.type === "text" && block.text?.trim()) visible.push("text");
34
+ else if (block.type !== "text" && block.type !== "toolCall") return;
35
+ }
36
+ }
37
+ if (visible.filter(kind => kind === "thinking").length !== 1 || !visible.includes("text")) return;
38
+ expected.push("space");
39
+ visible.forEach((kind, index) => { expected.push(kind); if (kind === "thinking" && index < visible.length - 1) expected.push("space"); });
40
+ const children = component.contentContainer?.children;
41
+ if (!Array.isArray(children) || children.length !== expected.length || !children.every((child: any, index: number) =>
42
+ expected[index] === "space" ? child instanceof Spacer : expected[index] === "text" ? child instanceof Markdown : child instanceof MouseRegion && child.child instanceof Text)) return;
43
+ return children.find((child: any) => child instanceof MouseRegion);
44
+ }
45
+ export function installModernThinkingAdapter(hooks: {
46
+ associate(component: any, message: any): void;
47
+ render(component: any, width: number): string[] | undefined;
48
+ mouse(component: any, event: any): any;
49
+ clear(): void;
50
+ }, version = VERSION): (() => void) | undefined {
51
+ const proto = AssistantMessageComponent.prototype as any;
52
+ if (version !== "1.3.0" || !["updateContent", "render", "setHideThinkingBlock"].every(key => typeof proto[key] === "function")) return;
53
+ const owner = Symbol.for("compact-renderer:thinking-adapter:v1");
54
+ proto[owner]?.();
55
+ let disposed = false;
56
+ const regions = new Map<any, () => void>();
57
+ const detachUpdate = chainNativeMethod(proto, "updateContent", function(this: any, update, ...args: any[]) {
58
+ regions.get(this)?.(); regions.delete(this);
59
+ const value = update.apply(this, args);
60
+ if (!disposed) {
61
+ hooks.associate(this, args[0]);
62
+ const region = mixedThinkingRegion(this, args[0]);
63
+ if (region) {
64
+ const component = this, render = region.render, mouse = region.handleMouse;
65
+ region.render = (width: number) => hooks.render(component, width)?.slice(1) ?? render.call(region, width);
66
+ region.handleMouse = (event: any) => hooks.mouse(component, { ...event, y: event.y + 1 }) || mouse.call(region, event);
67
+ regions.set(this, () => { region.render = render; region.handleMouse = mouse; });
68
+ }
69
+ }
70
+ return value;
71
+ });
72
+ const detachRender = chainNativeMethod(proto, "render", function(this: any, render, width: number) { return !disposed && hiddenThinkingShape(this, this.lastMessage) && hooks.render(this, width) || render.call(this, width); });
73
+ const detachMouse = chainNativeMethod(proto, "handleMouse", function(this: any, mouse, event: any) { const result = !disposed && hiddenThinkingShape(this, this.lastMessage) && hooks.mouse(this, event); return result || mouse?.call(this, event); });
74
+ const dispose = () => {
75
+ if (disposed) return;
76
+ disposed = true;
77
+ for (const restore of regions.values()) restore();
78
+ regions.clear();
79
+ detachMouse(); detachRender(); detachUpdate();
80
+ if (proto[owner] === dispose) delete proto[owner];
81
+ hooks.clear();
82
+ };
83
+ proto[owner] = dispose;
84
+ return dispose;
85
+ }
@@ -0,0 +1,258 @@
1
+ import type { DisplayMode } from './display-mode.ts';
2
+ import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
4
+ import { hiddenThinkingShape, mixedThinkingRegion, installModernThinkingAdapter } from "./modern-thinking-adapter.ts";
5
+ import { recordedPaneHeight } from "./modern-recorded-pane.ts";
6
+ import { ToolPane, type PaneAction } from "./modern-tool-pane.ts";
7
+
8
+ type Round = { id: number; sources?: string[]; action?: PaneAction; message: any; hasThinking: boolean; joinsPrevious: boolean; component?: any; kind: "round" | "bridge" | "boundary"; group?: ThinkingGroup };
9
+ type ThinkingGroup = { members: Round[]; pane: ToolPane; activeEpoch?: number; activeResult?: boolean };
10
+ /** The label is an extract from recorded text, never a generated summary.
11
+ * Limit work even when the first line has millions of characters. */
12
+ export function recordedThinkingLabel(sources: readonly string[]): string {
13
+ const sample = Array.from((sources[0] || "").slice(0, 1024).replace(/[\uD800-\uDBFF]$/, "")).slice(0, 512).join("");
14
+ const heading = sample.match(/^ {0,3}#{1,6}[ \t]+([^\r\n]+)/m)?.[1];
15
+ const first = sample.trimStart().match(/^[^\r\n]+/)?.[0] || "";
16
+ const sentence = first.match(/^.*?[.!?。!?](?:\s|$)/u)?.[0] || first;
17
+ const extract = (heading || sentence).replace(/\*\*([^*]+)\*\*|__([^_]+)__/g, (_match, bold, underlined) => bold || underlined).replace(/`([^`]+)`/g, "$1").replace(/[\p{Cc}\p{Cf}]/gu, char => `\\u${char.codePointAt(0)!.toString(16).padStart(4, "0")}`).trim();
18
+ return truncateToWidth(extract || "Recorded thinking", 80, "…");
19
+ }
20
+
21
+ const hasThinking = (message: any) => (message?.content || []).some((b: any) => b.type === "thinking" && typeof b.thinking === "string" && b.thinking.trim());
22
+ // A leading run can join earlier rounds only before the first visible reply.
23
+ // Track this separately from the broad boundary kind during streaming updates.
24
+ const joinsPreviousThinking = (message: any): boolean => {
25
+ if (["error", "aborted", "length"].includes(message?.stopReason)) return false;
26
+ let runs = 0, inRun = false, firstVisible: string | undefined, hasText = false;
27
+ for (const block of message?.content || []) {
28
+ if (!["thinking", "text", "toolCall"].includes(block.type) || block.type === "toolCall" && ["ask_user_question", "question"].includes(block.name)) return false;
29
+ if (block.type !== "thinking") inRun = false;
30
+ if (block.type === "thinking" && block.thinking?.trim()) {
31
+ firstVisible ??= "thinking";
32
+ if (!inRun) { runs++; inRun = true; }
33
+ } else if (block.type === "text" && block.text?.trim()) { firstVisible ??= "text"; hasText = true; }
34
+ }
35
+ return hasText && firstVisible === "thinking" && runs === 1;
36
+ };
37
+ const supportedThinking = (component: any, message: any) => hiddenThinkingShape(component, message) || !!mixedThinkingRegion(component, message);
38
+ const classify = (message: any): Round["kind"] => {
39
+ if (["error", "aborted", "length"].includes(message?.stopReason) || (message?.content || []).some((b: any) => b.type === "text" && b.text?.trim() || b.type === "toolCall" && ["ask_user_question", "question"].includes(b.name))) return "boundary";
40
+ return hasThinking(message) ? "round" : "bridge";
41
+ };
42
+ const boundary = (m: any) => m?.role === "toolResult" ? !!m.isError || ["ask_user_question", "question"].includes(m.toolName) || ["cancelled", "unavailable"].includes(m.details?.status) && m.toolName === "ask_user_question" : !["system"].includes(m?.role) && !(m?.role === "custom" && m.display === false);
43
+
44
+ /** Recorded object identity and public event order determine membership. No content
45
+ * matching, generated summaries, transcript writes, or model calls. */
46
+ export class ModernThinkingGroups {
47
+ private records: (Round | null)[] = [];
48
+ private aliases = new WeakMap<object, Round>();
49
+ private components = new WeakMap<object, Round>();
50
+ private boundaries = new WeakSet<object>();
51
+ private live?: Round;
52
+ private dirty = true;
53
+ private epoch = 0;
54
+ private groups: ThinkingGroup[] = [];
55
+ private selected?: ThinkingGroup;
56
+ private layouts = new WeakMap<object, { width: number; height: number }>();
57
+ focused = false;
58
+ constructor(private enabled: () => boolean, private theme: () => any, private focus: (inspection?: { target: (component: any) => boolean; label: string }) => void, private inspectionEnded: () => void = () => {}) {}
59
+ clear() { this.records = []; this.aliases = new WeakMap(); this.components = new WeakMap(); this.boundaries = new WeakSet(); this.layouts = new WeakMap(); this.live = undefined; this.groups = []; this.selected = undefined; this.focused = false; this.dirty = true; this.epoch++; }
60
+ rebuild(entries: readonly any[]) {
61
+ this.clear();
62
+ for (const entry of entries) {
63
+ if (entry.type === "message") this.observe("end", entry.message);
64
+ else if (["compaction", "branch_summary"].includes(entry.type) || entry.type === "custom_message" && entry.display !== false) this.records.push(null);
65
+ }
66
+ }
67
+ observe(phase: "start" | "update" | "end", message: any) {
68
+ if (!message || typeof message !== "object") return;
69
+ this.epoch++;
70
+ if (message.role !== "assistant") {
71
+ if (boundary(message) && !this.boundaries.has(message)) { this.records.push(null); this.boundaries.add(message); this.live = undefined; this.dirty = true; }
72
+ return;
73
+ }
74
+ let record = this.aliases.get(message) || (phase === "start" ? undefined : this.live);
75
+ if (!record) { record = { id: this.records.length, message, hasThinking: hasThinking(message), joinsPrevious: joinsPreviousThinking(message), kind: classify(message) }; this.records.push(record); this.dirty = true; }
76
+ // Native streaming messages can share a mutated content array.
77
+ const thinking = hasThinking(message);
78
+ if (record.hasThinking !== thinking) { record.hasThinking = thinking; this.dirty = true; }
79
+ const joinsPrevious = joinsPreviousThinking(message);
80
+ if (record.joinsPrevious !== joinsPrevious) { record.joinsPrevious = joinsPrevious; this.dirty = true; }
81
+ record.message = message; this.aliases.set(message, record);
82
+ const kind = classify(message);
83
+ if (record.kind !== kind) { record.kind = kind; this.dirty = true; }
84
+ this.live = phase === "end" ? undefined : record;
85
+ }
86
+ associate(component: any, message: any) {
87
+ this.epoch++;
88
+ const previous = this.components.get(component), record = this.aliases.get(message);
89
+ if (previous && previous !== record && previous.component === component) previous.component = undefined;
90
+ if (!record) { this.components.delete(component); return; }
91
+ if (record.component && record.component !== component) this.components.delete(record.component);
92
+ record.component = component; this.components.set(component, record);
93
+ }
94
+ private regroup() {
95
+ if (!this.dirty) return;
96
+ this.dirty = false;
97
+ const previous = new Map(this.groups.map(group => [group.members[0], group]));
98
+ this.groups = [];
99
+ let members: Round[] = [];
100
+ const flush = () => {
101
+ if (!members.length) return;
102
+ const group = previous.get(members[0]) || { members: [], pane: new ToolPane([], "", recordedPaneHeight) };
103
+ group.members = members;
104
+ for (const record of members) record.group = group;
105
+ this.groups.push(group); members = [];
106
+ };
107
+ for (const record of this.records) {
108
+ if (record) record.group = undefined;
109
+ if (!record || record.kind === "boundary") {
110
+ const message = record?.message;
111
+ const mixed = record && hasThinking(message) && message.content.some((block: any) => block.type === "text" && block.text?.trim());
112
+ // Leading thinking precedes this reply boundary and belongs with the
113
+ // previous rounds. Text-first runs and failed/question messages stay separate.
114
+ if (!record?.joinsPrevious) flush();
115
+ if (mixed) members.push(record);
116
+ flush();
117
+ }
118
+ else if (record.kind === "round") members.push(record);
119
+ }
120
+ flush();
121
+ if (this.selected && !this.groups.includes(this.selected)) { this.selected = undefined; this.focused = false; }
122
+ }
123
+ private active(group?: ThinkingGroup): group is ThinkingGroup {
124
+ if (!group || !this.enabled()) return false;
125
+ if (group.activeEpoch !== this.epoch) {
126
+ group.activeResult = group.members.every(record => record.component && this.components.get(record.component) === record && hasThinking(record.message)
127
+ && (record.kind === "round" ? hiddenThinkingShape(record.component, record.message) : !!mixedThinkingRegion(record.component, record.message)));
128
+ group.activeEpoch = this.epoch;
129
+ }
130
+ return group.activeResult === true;
131
+ }
132
+ association(component: any) {
133
+ this.regroup();
134
+ const record = this.components.get(component);
135
+ if (record && !supportedThinking(component, record.message)) this.epoch++;
136
+ return record && record.component === component && this.active(record.group) ? { record, group: record.group } : undefined;
137
+ }
138
+ private choose(group: ThinkingGroup) {
139
+ this.selected = group; this.focused = true;
140
+ const component = group.members.at(-1)?.component;
141
+ this.focus({ target: candidate => candidate === component, label: `Thinking · ${group.members.length} round${group.members.length === 1 ? "" : "s"}` });
142
+ }
143
+ private release() { this.focused = false; this.inspectionEnded(); }
144
+ private sources(group: ThinkingGroup) {
145
+ let changed = group.pane.actions.length !== group.members.length || group.pane.actions.some((action, index) => action.id !== String(group.members[index]?.id));
146
+ group.pane.actions = group.members.map(record => {
147
+ const sources = record.message.content.filter((block: any) => block.type === "thinking" && typeof block.thinking === "string" && block.thinking.trim()).map((block: any) => block.thinking);
148
+ if (!record.sources || sources.length !== record.sources.length || sources.some((source: string, index: number) => source !== record.sources![index])) {
149
+ record.sources = sources;
150
+ record.action = { id: String(record.id), label: recordedThinkingLabel(sources), repeatedSummary: recordedThinkingLabel(sources), sections: () => record.sources!.map(text => ({ text, format: "markdown" as const })) };
151
+ changed = true;
152
+ }
153
+ return record.action!;
154
+ });
155
+ if (changed) group.pane.reset();
156
+ }
157
+ disclosures(request: any) {
158
+ this.regroup();
159
+ for (const group of this.groups) if (this.active(group)) request?.add?.((component: any) => group.members.some(record => record.component === component), group.pane.open, () => {
160
+ if (this.selected === group) { this.selected = undefined; this.focused = false; }
161
+ group.pane.collapse();
162
+ });
163
+ }
164
+ inspectionChoices() {
165
+ this.regroup();
166
+ return this.groups.filter(group => this.active(group)).map(group => {
167
+ this.sources(group);
168
+ return {
169
+ id: `thinking:${group.members[0].id}`, kind: "Thinking" as const,
170
+ label: `Thinking · ${group.members.length} round${group.members.length === 1 ? "" : "s"} · ${group.pane.actions[0]?.label || ""}`,
171
+ focus: () => { if (this.active(group)) { group.pane.open = true; this.choose(group); } },
172
+ target: () => group.members.at(-1)?.component,
173
+ };
174
+ });
175
+ }
176
+ render(component: any, width: number): string[] | undefined {
177
+ const match = this.association(component);
178
+ if (!match) return;
179
+ const { record, group } = match;
180
+ if (group.members.at(-1) !== record) return [];
181
+ const pane = group.pane, theme = this.theme();
182
+ this.sources(group);
183
+ pane.title = group.members.length === 1 ? `Thinking · ${pane.actions[0]?.label || "Recorded thinking"}` : `Thinking · ${group.members.length} rounds`;
184
+ pane.directContent = group.members.length === 1;
185
+ pane.focused = this.focused && this.selected === group;
186
+ pane.theme = theme; pane.headingTone = "thinkingText"; pane.itemName = "round";
187
+ pane.styleHeader = text => theme.fg("thinkingText", text);
188
+ const rows = ["", ...pane.render(Math.max(1, width))];
189
+ this.layouts.set(component, { width, height: rows.length });
190
+ return rows;
191
+ }
192
+ mouse(component: any, event: any) {
193
+ const match = this.association(component), layout = this.layouts.get(component);
194
+ if (!match || match.group.members.at(-1) !== match.record || !layout || event.x < 0 || event.x >= layout.width || event.y < 1 || event.y >= layout.height) return;
195
+ // Mouse inspection never takes keyboard focus from the native editor.
196
+ const handled = match.group.pane.handleMouse({ ...event, y: event.y - 1 });
197
+ if (handled) { this.focused = false; match.group.pane.focused = false; this.focus(); }
198
+ return handled;
199
+ }
200
+ input(data: string): boolean {
201
+ if (!this.enabled()) { this.focused = false; return false; }
202
+ this.regroup();
203
+ if (matchesKey(data, "alt+t")) {
204
+ const active = this.groups.filter(group => this.active(group));
205
+ if (!active.length) return false;
206
+ const index = this.focused ? active.indexOf(this.selected!) : -1;
207
+ this.choose(index < 0 ? active.at(-1)! : active[(index + active.length - 1) % active.length]);
208
+ return true;
209
+ }
210
+ if (!this.focused || !this.active(this.selected)) { this.focused = false; return false; }
211
+ if (matchesKey(data, "escape")) { this.release(); return true; }
212
+ if (this.selected.pane.handle(data)) return true;
213
+ this.release();
214
+ return false;
215
+ }
216
+ }
217
+
218
+ export function registerModernThinking(pi: ExtensionAPI, mode: DisplayMode): () => void {
219
+ const owner = Symbol.for("compact-renderer:thinking-registration:v1"), shared = globalThis as any;
220
+ shared[owner]?.();
221
+ let groups: ModernThinkingGroups | undefined, adapter: (() => void) | undefined, input: (() => void) | undefined;
222
+ let redraw: (() => void) | undefined, disposed = false;
223
+ const stop = () => { input?.(); input = undefined; adapter?.(); adapter = undefined; groups?.clear(); groups = undefined; redraw = undefined; };
224
+ const rebuild = (_event: unknown, ctx: any) => {
225
+ if (disposed) return;
226
+ stop();
227
+ if (ctx.mode !== "tui" || typeof ctx.ui.setHiddenThinkingLabel !== "function") return;
228
+ const ui = ctx.ui, theme = ui.theme;
229
+ groups = new ModernThinkingGroups(() => mode.isEnabled(), () => theme, inspection => {
230
+ redraw?.();
231
+ pi.events.emit("compact-renderer:focus:v1", { owner: inspection ? "thinking" : "editor", ...inspection });
232
+ }, () => pi.events.emit("compact-renderer:inspection-ended:v1", { owner: "thinking" }));
233
+ // Match the native transcript sequence, including retained compaction entries.
234
+ const sessions = ctx.sessionManager;
235
+ groups.rebuild(typeof sessions.buildContextEntries === "function" ? sessions.buildContextEntries() : sessions.getBranch());
236
+ adapter = installModernThinkingAdapter({ associate: (c, m) => groups?.associate(c, m), render: (c, w) => groups?.render(c, w), mouse: (c, e) => groups?.mouse(c, e), clear: () => groups?.clear() });
237
+ if (!adapter) { groups.clear(); groups = undefined; return; }
238
+ redraw = () => ui.setHiddenThinkingLabel();
239
+ input = ui.onTerminalInput?.((data: string) => {
240
+ const wasFocused = groups?.focused;
241
+ if (groups?.input(data)) { redraw?.(); return { consume: true }; }
242
+ if (wasFocused && !groups?.focused) redraw?.();
243
+ });
244
+ redraw();
245
+ };
246
+ const subscriptions: (() => void)[] = [];
247
+ for (const event of ["session_start", "session_tree", "session_compact"] as const) subscriptions.push(pi.on(event, rebuild));
248
+ for (const [event, phase] of [["message_start", "start"], ["message_update", "update"], ["message_end", "end"]] as const) subscriptions.push(pi.on(event, (event: any) => groups?.observe(phase, event.message)));
249
+ subscriptions.push(pi.on("ui_prompt_start", () => { if (groups) groups.focused = false; }));
250
+ subscriptions.push(pi.on("session_shutdown", stop));
251
+ subscriptions.push(pi.events.on("compact-renderer:disclosures:v1", (request: any) => groups?.disclosures(request)));
252
+ subscriptions.push(pi.events.on("compact-renderer:inspect:v1", (event: any) => { for (const choice of groups?.inspectionChoices() || []) event?.add?.(choice); }));
253
+ subscriptions.push(pi.events.on("compact-renderer:focus:v1", (event: any) => { if (event?.owner !== "thinking" && groups) groups.focused = false; }));
254
+ subscriptions.push(mode.onChange(() => { if (groups) groups.focused = false; redraw?.(); }));
255
+ const dispose = () => { if (disposed) return; disposed = true; for (const unsub of subscriptions) unsub?.(); const repaint = redraw; stop(); if (shared[owner] === dispose) delete shared[owner]; repaint?.(); };
256
+ shared[owner] = dispose;
257
+ return dispose;
258
+ }
@@ -0,0 +1,28 @@
1
+ import type { PaneContent } from "./modern-tool-pane.ts";
2
+
3
+ const scalar = (value: any) => value === undefined ? "undefined" : typeof value === "bigint" ? `${value}n` : JSON.stringify(value) ?? String(value);
4
+
5
+ /** Local field names keep structure readable without constructing a serialized payload.
6
+ * Strings remain separate, lazy chunks; no traversal of later fields occurs before painting them. */
7
+ export function* recordedValues(value: any, indent = 0, ancestors = new Set<object>(), languages: Record<string, string | undefined> = {}, language?: string): Generator<PaneContent> {
8
+ if (typeof value === "string") { yield { text: value.length ? value : '""', indent, ...(language ? { format: "code" as const, language } : {}) }; return; }
9
+ if (value === null || typeof value !== "object") { yield { text: scalar(value), indent, format: "code", language: "json" }; return; }
10
+ if (ancestors.has(value)) { yield { text: "[circular reference]", indent }; return; }
11
+ ancestors.add(value);
12
+ let count = 0;
13
+ for (const key in value) if (Object.prototype.hasOwnProperty.call(value, key)) {
14
+ count++;
15
+ const field = value[key];
16
+ const label = Array.isArray(value) ? `[${key}]` : key;
17
+ if (field === null || typeof field !== "object" && typeof field !== "string") yield { text: `${label}: ${scalar(field)}`, indent, kind: "field", format: "code", language: "json" };
18
+ else if (typeof field === "string" && !languages[key] && field.length <= 160 && !/[\r\n\p{Cc}\p{Cf}]/u.test(field)) {
19
+ yield { text: `${label}: ${JSON.stringify(field)}`, indent, kind: "field", format: "code", language: "json" };
20
+ }
21
+ else {
22
+ yield { text: `${label}:`, indent, kind: "field" };
23
+ yield* recordedValues(field, indent + 2, ancestors, languages, languages[key]);
24
+ }
25
+ }
26
+ if (!count) yield { text: Array.isArray(value) ? "[]" : "{}", indent };
27
+ ancestors.delete(value);
28
+ }
@@ -0,0 +1,63 @@
1
+ import { ToolExecutionComponent, VERSION } from "@earendil-works/pi-coding-agent";
2
+ import { getCapabilities, Image, imageFallback, truncateToWidth } from "@earendil-works/pi-tui";
3
+ import { chainNativeMethod } from "./native-method-chain.ts";
4
+ import { activityRow, cardContentWidth, cardPadding } from "./display-card.ts";
5
+
6
+ export const compactToolImages = Symbol.for("compact-renderer:tool-images:v1");
7
+ export type ToolImageView = { open: boolean; count: number; bodyIndent: number; source?: string; theme?: any };
8
+
9
+ /** Pi 1.3.0 appends images outside renderShell:self. Borrow those same native
10
+ * objects during render only; never change image sources, settings or ownership. */
11
+ export function installModernToolImages(version = VERSION): (() => void) | undefined {
12
+ const proto = ToolExecutionComponent.prototype as any;
13
+ if (version !== "1.3.0" || typeof proto.render !== "function" || typeof proto.updateDisplay !== "function") return;
14
+ const owner = Symbol.for("compact-renderer:tool-image-adapter:v1");
15
+ proto[owner]?.();
16
+ let disposed = false;
17
+ const detach = chainNativeMethod(proto, "render", function(this: any, nativeRender, width: number) {
18
+ const view: ToolImageView | undefined = !disposed && this.toolDefinition?.[compactToolImages]?.(this, width);
19
+ if (!view?.count || this.getRenderShell?.() !== "self" || !Array.isArray(this.imageComponents) ||
20
+ !Array.isArray(this.imageSpacers) || !this.imageComponents.every((image: any) => image instanceof Image && image.options && typeof image.invalidate === "function")) return nativeRender.call(this, width);
21
+ const images = this.imageComponents, spacers = this.imageSpacers;
22
+ let lines: string[];
23
+ // The host uses these arrays only to append images after its text shell.
24
+ // Keep native children, sources and reusable decoder/transcoder state intact.
25
+ this.imageComponents = []; this.imageSpacers = [];
26
+ try { lines = nativeRender.call(this, width); }
27
+ finally { this.imageComponents = images; this.imageSpacers = spacers; }
28
+ if (!view.open || this.hideComponent) return lines;
29
+ const indent = " ".repeat(cardPadding(width) + view.bodyIndent);
30
+ const imageWidth = Math.max(1, width - indent.length - cardPadding(width));
31
+ const fallback = (reason: string, mime?: string, dimensions?: any) => {
32
+ const safeMime = mime?.slice(0, 120).replace(/[\p{Cc}\p{Cf}]/gu, " ");
33
+ const description = safeMime ? imageFallback(safeMime, dimensions, view.source) : `${view.count} image${view.count === 1 ? "" : "s"}${view.source ? ` · ${imageFallback("image", undefined, view.source)}` : ""}`;
34
+ const message = `Inline preview unavailable: ${reason}`;
35
+ const text = truncateToWidth(view.source ? `${description} · ${message}` : `${message} · ${description}`, Math.max(1, cardContentWidth(width) - view.bodyIndent), "");
36
+ return activityRow(" ".repeat(view.bodyIndent) + (view.theme?.fg("muted", text) ?? text), width, view.theme);
37
+ };
38
+ if (!this.showImages) return [...lines, fallback("images are disabled")];
39
+ if (!getCapabilities().images) return [...lines, fallback("terminal has no image protocol")];
40
+ if (!images.length) return [...lines, fallback("image data is unavailable")];
41
+ const maxHeight = Math.max(1, Math.min(12, Math.floor((process.stdout.rows || 24) / 2)));
42
+ for (let index = 0; index < images.length; index++) {
43
+ const image = images[index], options = image.options;
44
+ let preview: string[];
45
+ image.options = { ...options, maxWidthCells: Math.min(60, options.maxWidthCells ?? 60), maxHeightCells: Math.min(maxHeight, options.maxHeightCells ?? maxHeight) };
46
+ image.invalidate();
47
+ try { preview = image.render(imageWidth); }
48
+ finally { image.options = options; image.invalidate(); }
49
+ // Image.render owns protocol encoding and conversion. Its plain fallback
50
+ // means the format/conversion could not produce protocol output this time.
51
+ if (preview.some(line => line.includes("\x1b_G") || line.includes("\x1b]1337;File="))) {
52
+ // Keep image protocol bytes intact; prefix the same gutter as expanded
53
+ // text, including iTerm2's cursor-up row and Kitty's image anchor.
54
+ lines.push(...(spacers[index]?.render(width) ?? [""]), ...preview.map(row => indent + row));
55
+ } else lines.push(fallback("image format was not rendered", image.mimeType, image.dimensions));
56
+ }
57
+ if (images.length < view.count) lines.push(fallback("some image data is unavailable"));
58
+ return lines;
59
+ });
60
+ const dispose = () => { if (disposed) return; disposed = true; detach(); if (proto[owner] === dispose) delete proto[owner]; };
61
+ proto[owner] = dispose;
62
+ return dispose;
63
+ }