@narumitw/pi-starship 0.63.0 → 0.64.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 (27) hide show
  1. package/README.md +15 -4
  2. package/dist/chunks/{chunk-63R6R5DH.ts → chunk-D563JANR.ts} +10 -5
  3. package/dist/chunks/{chunk-63R6R5DH.ts.map → chunk-D563JANR.ts.map} +2 -2
  4. package/dist/chunks/{chunk-Y24TJYG6.ts → chunk-UIKPE4UC.ts} +1 -1
  5. package/dist/chunks/{chunk-Y24TJYG6.ts.map → chunk-UIKPE4UC.ts.map} +2 -2
  6. package/dist/chunks/{command-configuration-menu-YOLN2SPR.ts → command-configuration-menu-ZN2VXU4L.ts} +2 -2
  7. package/dist/chunks/{command-settings-chat-5AHP3JGV.ts → command-settings-chat-B2FCDVBH.ts} +563 -227
  8. package/dist/chunks/command-settings-chat-B2FCDVBH.ts.map +7 -0
  9. package/dist/chunks/{commands-IOG2PL67.ts → commands-SVLRVXUW.ts} +7 -6
  10. package/dist/chunks/commands-SVLRVXUW.ts.map +7 -0
  11. package/dist/index.ts +3 -2
  12. package/dist/index.ts.map +2 -2
  13. package/package.json +5 -5
  14. package/src/command-configuration.ts +2 -0
  15. package/src/command-profiles.ts +10 -3
  16. package/src/command-settings-chat.ts +17 -5
  17. package/src/commands.ts +1 -0
  18. package/src/pi-starship.ts +1 -0
  19. package/src/settings-chat-display.ts +11 -0
  20. package/src/settings-chat-fullscreen.ts +241 -0
  21. package/src/settings-chat-scroll.ts +17 -0
  22. package/src/settings-chat-tools.ts +207 -0
  23. package/src/settings-chat-transcript.ts +91 -72
  24. package/src/settings-chat-ui.ts +94 -183
  25. package/dist/chunks/command-settings-chat-5AHP3JGV.ts.map +0 -7
  26. package/dist/chunks/commands-IOG2PL67.ts.map +0 -7
  27. /package/dist/chunks/{command-configuration-menu-YOLN2SPR.ts.map → command-configuration-menu-ZN2VXU4L.ts.map} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-starship",
3
- "version": "0.63.0",
3
+ "version": "0.64.1",
4
4
  "description": "Native Starship-style TOML statusline and configuration skill for Pi.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -39,7 +39,7 @@
39
39
  "typecheck": "tsc --noEmit"
40
40
  },
41
41
  "dependencies": {
42
- "@narumitw/pi-tui-kit": "^0.66.0",
42
+ "@narumitw/pi-tui-kit": "^0.67.0",
43
43
  "re2js": "^2.9.0",
44
44
  "semver": "^7.8.5",
45
45
  "smol-toml": "^1.9.1",
@@ -51,9 +51,9 @@
51
51
  "@earendil-works/pi-tui": "*"
52
52
  },
53
53
  "devDependencies": {
54
- "@earendil-works/pi-agent-core": "1.3.0",
55
- "@earendil-works/pi-coding-agent": "1.3.0",
56
- "@earendil-works/pi-tui": "1.3.0",
54
+ "@earendil-works/pi-agent-core": "1.4.0",
55
+ "@earendil-works/pi-coding-agent": "1.4.0",
56
+ "@earendil-works/pi-tui": "1.4.0",
57
57
  "@types/node": "26.6.5",
58
58
  "esbuild": "0.28.2",
59
59
  "typescript": "7.0.2"
@@ -22,6 +22,8 @@ export interface WorkflowOwner {
22
22
  isCurrent(): boolean;
23
23
  /** Session ownership independent of command cancellation and candidate/revision guards. */
24
24
  isSessionCurrent?(): boolean;
25
+ /** The shared parent terminal can remain live after its session context changes. */
26
+ canRestoreTerminal?(): boolean;
25
27
  }
26
28
 
27
29
  export interface ConfigurationCommandOptions {
@@ -216,6 +216,7 @@ async function documentActions(
216
216
  const profile = document.kind === "profile";
217
217
  const activeInvalid = profile && options.getLoaded().diagnostics.some((item) => item.severity === "error");
218
218
  const action = await actionScreen(ctx, flow, {
219
+ kind: document.kind,
219
220
  title: `${profile ? "Profile" : "Recovery copy"}: ${safe(document.name)}`,
220
221
  lines: [
221
222
  `Path: ${safe(document.path)}`,
@@ -242,8 +243,8 @@ async function documentActions(
242
243
  ...(profile
243
244
  ? [
244
245
  { id: "edit", label: "Edit TOML…" },
245
- { id: "rename", label: "Rename…" },
246
246
  { id: "duplicate", label: "Duplicate…" },
247
+ { id: "rename", label: "Rename…" },
247
248
  ]
248
249
  : [
249
250
  {
@@ -445,7 +446,7 @@ async function saveNamedCopy(
445
446
  async function actionScreen(
446
447
  ctx: ExtensionCommandContext,
447
448
  flow: ReturnType<typeof createFlow>,
448
- screen: { title: string; lines: string[]; actions: Action[]; raw: string | undefined },
449
+ screen: { kind?: Document["kind"]; title: string; lines: string[]; actions: Action[]; raw: string | undefined },
449
450
  ): Promise<string> {
450
451
  let selected: string | undefined;
451
452
  const menu = defineMenu<undefined, "actions" | "document", "select">({
@@ -456,6 +457,9 @@ async function actionScreen(
456
457
  title: screen.title,
457
458
  lines: screen.lines,
458
459
  items: [
460
+ ...(screen.kind === "profile"
461
+ ? screen.actions.slice(0, 1).map((action) => ({ ...action, action: "select" as const }))
462
+ : []),
459
463
  {
460
464
  id: "review",
461
465
  label: "Review TOML",
@@ -463,7 +467,10 @@ async function actionScreen(
463
467
  disabled: screen.raw === undefined,
464
468
  disabledReason: "The document is not valid UTF-8",
465
469
  },
466
- ...screen.actions.map((action) => ({ ...action, action: "select" as const })),
470
+ ...(screen.kind === "profile" ? screen.actions.slice(1) : screen.actions).map((action) => ({
471
+ ...action,
472
+ action: "select" as const,
473
+ })),
467
474
  ],
468
475
  hint: "back",
469
476
  }),
@@ -8,7 +8,7 @@ import { saveAsProfile } from "./command-profiles.js";
8
8
  import type { StarshipCommandOptions } from "./commands.js";
9
9
  import { assertProfileUnchanged } from "./profile-store.js";
10
10
  import { createSettingsAgent, starshipPackageRoot } from "./settings-agent.js";
11
- import { type ChatViewState, showSettingsChat } from "./settings-chat-ui.js";
11
+ import { type ChatViewState, type SettingsChatAction, showSettingsChat } from "./settings-chat-ui.js";
12
12
  import { createSettingsDraft } from "./settings-draft.js";
13
13
  import { settingsSnapshots } from "./settings-snapshots.js";
14
14
 
@@ -23,10 +23,12 @@ export async function showSettingsAgentChat(
23
23
  return captureCommitExpectation(options);
24
24
  });
25
25
  if (!expected || base.signal.aborted || !base.isCurrent()) return "close";
26
+ const chatLifetime = new AbortController();
26
27
  const owner: WorkflowOwner = {
27
- signal: base.signal,
28
- isCurrent: () => commitOwnerCurrent(options, base, expected),
28
+ signal: AbortSignal.any([base.signal, chatLifetime.signal]),
29
+ isCurrent: () => !chatLifetime.signal.aborted && commitOwnerCurrent(options, base, expected),
29
30
  isSessionCurrent: base.isSessionCurrent ?? base.isCurrent,
31
+ canRestoreTerminal: base.canRestoreTerminal,
30
32
  };
31
33
  const packageRoot = starshipPackageRoot();
32
34
  const draft = createSettingsDraft({
@@ -41,12 +43,16 @@ export async function showSettingsAgentChat(
41
43
  });
42
44
  let agent: ReturnType<typeof createSettingsAgent> | undefined;
43
45
  let closing: Promise<void> | undefined;
46
+ let activeChat: Promise<SettingsChatAction> | undefined;
44
47
  const cleanup = () => {
45
48
  if (closing) return closing;
49
+ chatLifetime.abort();
46
50
  agent?.abort();
51
+ const pendingChat = activeChat;
47
52
  closing = (async () => {
48
53
  try {
49
- await agent?.waitForIdle();
54
+ // Shutdown must join terminal teardown, not only the model request.
55
+ await Promise.all([agent?.waitForIdle(), pendingChat]);
50
56
  } finally {
51
57
  agent?.reset();
52
58
  draft.dispose();
@@ -70,7 +76,13 @@ export async function showSettingsAgentChat(
70
76
  if (!owner.isCurrent()) return "close";
71
77
  agent = createSettingsAgent(ctx, draft, packageRoot);
72
78
  while (owner.isCurrent()) {
73
- const action = await showSettingsChat(ctx, agent, draft, state, owner, preview);
79
+ activeChat = showSettingsChat(ctx, agent, draft, state, owner, preview);
80
+ let action: SettingsChatAction;
81
+ try {
82
+ action = await activeChat;
83
+ } finally {
84
+ activeChat = undefined;
85
+ }
74
86
  if (!owner.isCurrent() || action === "discard") return "close";
75
87
  if (!draft.candidate) continue;
76
88
  const candidate = draft.candidate;
package/src/commands.ts CHANGED
@@ -81,6 +81,7 @@ export async function handleStarshipCommand(
81
81
  signal,
82
82
  isCurrent: () => !signal.aborted && base.isCurrent(),
83
83
  isSessionCurrent: () => base.isSessionCurrent?.() ?? base.isCurrent(),
84
+ canRestoreTerminal: base.canRestoreTerminal,
84
85
  };
85
86
  // Pi delivers bracketed paste as one framed packet. Exact key matching does
86
87
  // not treat controls inside pasted text as cancellation or consume native input.
@@ -448,6 +448,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
448
448
  return {
449
449
  signal: menuController.signal,
450
450
  isCurrent: () => generation === sessionGeneration && !menuController.signal.aborted,
451
+ canRestoreTerminal: () => sessionOwner !== undefined,
451
452
  };
452
453
  },
453
454
  apply(next, ctx) {
@@ -0,0 +1,11 @@
1
+ import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
2
+
3
+ /** Keep terminal controls out of native renderers without changing agent payloads. */
4
+ export function settingsChatDisplayValue<T>(value: T): T {
5
+ if (typeof value === "string") return sanitizeTerminalDocument(value) as T;
6
+ if (Array.isArray(value)) return value.map(settingsChatDisplayValue) as T;
7
+ if (value && typeof value === "object") {
8
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, settingsChatDisplayValue(item)])) as T;
9
+ }
10
+ return value;
11
+ }
@@ -0,0 +1,241 @@
1
+ import type { ExtensionCommandContext, KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type Component,
4
+ isKeyRelease,
5
+ matchesKey,
6
+ type OverlayHandle,
7
+ type TUI,
8
+ TuiAltScreen,
9
+ type TuiInputListener,
10
+ } from "@earendil-works/pi-tui";
11
+ import { createFullscreenHandoff } from "@narumitw/pi-tui-kit/fullscreen-handoff";
12
+ import type { WorkflowOwner } from "./command-configuration.js";
13
+
14
+ export type SettingsChatFullscreenComponent = Component & {
15
+ dispose?(): void;
16
+ waitForPending?(): Promise<void>;
17
+ getFullscreenLayout?(): Component;
18
+ };
19
+
20
+ export interface SettingsChatFullscreenOptions<Value> {
21
+ tui: TUI;
22
+ theme: Theme;
23
+ keybindings: KeybindingsManager;
24
+ signal: AbortSignal;
25
+ complete(value: Value): void;
26
+ }
27
+
28
+ export interface SettingsChatFullscreenDependencies {
29
+ createTui?(parent: TUI, createDefault: () => TuiAltScreen): TuiAltScreen;
30
+ }
31
+
32
+ type Outcome<Value> = { value: Value } | { error: unknown };
33
+
34
+ // The base constructor registers the native viewport listener through this public
35
+ // method. Install the guard first, without reading or changing Pi's listener set.
36
+ class SettingsChatTui extends TuiAltScreen {
37
+ declare private guardInstalled: boolean | undefined;
38
+ declare guard: TuiInputListener | undefined;
39
+
40
+ override addInputListener(listener: TuiInputListener): () => void {
41
+ if (!this.guardInstalled) {
42
+ this.guardInstalled = true;
43
+ super.addInputListener((data) => this.guard?.(data));
44
+ }
45
+ return super.addInputListener(listener);
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Pi recommends one renderer. This isolated chat intentionally transfers the
51
+ * shared terminal to a native fullscreen viewport, then returns it before review.
52
+ * The parent custom overlay owns only the handoff lifetime, never child layout.
53
+ */
54
+ export async function runSettingsChatFullscreen<Value>(
55
+ ctx: ExtensionCommandContext,
56
+ owner: WorkflowOwner,
57
+ create: (options: SettingsChatFullscreenOptions<Value>) => SettingsChatFullscreenComponent,
58
+ cancelledValue: Value,
59
+ dependencies: SettingsChatFullscreenDependencies = {},
60
+ ): Promise<Value> {
61
+ const current = () => !owner.signal.aborted && !ctx.signal?.aborted && owner.isCurrent();
62
+ const canRestoreTerminal = () => (owner.canRestoreTerminal ?? owner.isSessionCurrent ?? owner.isCurrent)();
63
+ if (ctx.mode !== "tui" || !current()) return cancelledValue;
64
+
65
+ let mount: ((handle: OverlayHandle) => void) | undefined;
66
+ let releaseHost: (() => Promise<void>) | undefined;
67
+ let completedOutcome: Outcome<Value> | undefined;
68
+ const outcome = await ctx.ui
69
+ .custom<Outcome<Value>>(
70
+ (parent, theme, keybindings, done) => {
71
+ const controller = new AbortController();
72
+ let child: TuiAltScreen | undefined;
73
+ let component: SettingsChatFullscreenComponent | undefined;
74
+ let entry: Promise<void> | undefined;
75
+ let finished = false;
76
+ let closing = false;
77
+ let cleanup: Promise<void> | undefined;
78
+ let pasting = false;
79
+ let result: Outcome<Value> = { value: cancelledValue };
80
+ const errors: unknown[] = [];
81
+ const handoff = createFullscreenHandoff<TuiAltScreen>(parent, {
82
+ isCurrent: () => !closing && current(),
83
+ canRestoreParent: canRestoreTerminal,
84
+ });
85
+ const removers: (() => void)[] = [];
86
+ const attempt = (action: () => void) => {
87
+ try {
88
+ action();
89
+ } catch (error) {
90
+ errors.push(error);
91
+ }
92
+ };
93
+
94
+ const finish = (next: Outcome<Value>) => {
95
+ if (closing) return cleanup;
96
+ closing = true;
97
+ result = next;
98
+ // Root work must stop synchronously, even when a nested overlay has focus.
99
+ controller.abort();
100
+ cleanup = Promise.resolve().then(async () => {
101
+ await entry;
102
+ for (const remove of removers.splice(0)) attempt(remove);
103
+ attempt(() => component?.dispose?.());
104
+ try {
105
+ await handoff.restore();
106
+ } catch (error) {
107
+ errors.push(error);
108
+ }
109
+ // Return input ownership promptly, then join cancelled root work.
110
+ // A late stream must settle before the owning command releases its draft.
111
+ try {
112
+ await component?.waitForPending?.();
113
+ } catch (error) {
114
+ errors.push(error);
115
+ }
116
+ attempt(() => {
117
+ if (!current() && !("error" in result)) result = { value: cancelledValue };
118
+ });
119
+ finished = true;
120
+ if ("error" in result) errors.unshift(result.error);
121
+ completedOutcome = errors.length
122
+ ? { error: errors.length === 1 ? errors[0] : new AggregateError(errors, "Fullscreen cleanup failed") }
123
+ : result;
124
+ done(completedOutcome);
125
+ });
126
+ return cleanup;
127
+ };
128
+ releaseHost = () => finish({ value: cancelledValue }) ?? Promise.resolve();
129
+ const cancel = () => finish({ value: cancelledValue });
130
+ const guard: TuiInputListener = (data) => {
131
+ if (closing) return { consume: true };
132
+ if (!current()) {
133
+ cancel();
134
+ return { consume: true };
135
+ }
136
+ // A terminal can deliver bracketed paste as one packet or separate
137
+ // packets. Ctrl+C in either form is text, not a screen shortcut.
138
+ const wasPasting = pasting;
139
+ for (const part of data.split("\x1b").slice(1)) {
140
+ if (part.startsWith("[200~")) pasting = true;
141
+ else if (part.startsWith("[201~")) pasting = false;
142
+ }
143
+ if (wasPasting || pasting || data.includes("\x1b[200~") || data.includes("\x1b[201~")) {
144
+ try {
145
+ // Paste belongs to the focused editor or native search overlay,
146
+ // not necessarily to the root chat. Bypass viewport shortcuts only.
147
+ child?.getFocusedComponent()?.handleInput?.(data);
148
+ child?.requestRender();
149
+ } catch (error) {
150
+ finish({ error });
151
+ }
152
+ return { consume: true };
153
+ }
154
+ if (!isKeyRelease(data) && matchesKey(data, "ctrl+c")) {
155
+ cancel();
156
+ return { consume: true };
157
+ }
158
+ };
159
+
160
+ for (const signal of new Set([owner.signal, ctx.signal])) {
161
+ if (!signal) continue;
162
+ signal.addEventListener("abort", cancel, { once: true });
163
+ removers.push(() => signal.removeEventListener("abort", cancel));
164
+ }
165
+ const host: SettingsChatFullscreenComponent = {
166
+ render: () => [],
167
+ invalidate() {},
168
+ dispose() {
169
+ if (!finished) cancel();
170
+ },
171
+ };
172
+ mount = (handle) => {
173
+ handoff.setOverlayHandle(handle);
174
+ // The custom factory and any active terminal callback must unwind before
175
+ // terminal ownership changes. onHandle runs only after Pi mounts host.
176
+ queueMicrotask(() => {
177
+ if (closing) return;
178
+ entry = (async () => {
179
+ try {
180
+ child = await handoff.enter(() => {
181
+ const createDefault = () =>
182
+ new SettingsChatTui(parent.terminal, parent.getShowHardwareCursor(), undefined, { mouse: true });
183
+ const created = dependencies.createTui?.(parent, createDefault) ?? createDefault();
184
+ child = created;
185
+ try {
186
+ if (created instanceof SettingsChatTui) created.guard = guard;
187
+ else removers.push(created.addInputListener(guard));
188
+ component = create({
189
+ tui: created,
190
+ theme,
191
+ keybindings,
192
+ signal: controller.signal,
193
+ complete: (value) => finish({ value }),
194
+ });
195
+ if (!closing && current()) {
196
+ created.setLayoutRoot(component.getFullscreenLayout?.() ?? component);
197
+ created.setFocus(component);
198
+ }
199
+ return created;
200
+ } catch (error) {
201
+ controller.abort();
202
+ // Kit cannot own a child the factory did not return. Native
203
+ // layout setup can schedule rendering before start().
204
+ try {
205
+ created.stop({ preserveScreen: true });
206
+ } catch (cleanupError) {
207
+ throw new AggregateError([error, cleanupError], "Fullscreen child factory cleanup failed");
208
+ }
209
+ throw error;
210
+ }
211
+ });
212
+ if (!child && !closing) cancel();
213
+ } catch (error) {
214
+ if (closing) errors.push(error);
215
+ else finish({ error });
216
+ }
217
+ })();
218
+ });
219
+ };
220
+ if (!current()) cancel();
221
+ return host;
222
+ },
223
+ { overlay: true, onHandle: (handle) => mount?.(handle) },
224
+ )
225
+ .catch(async (error: unknown) => {
226
+ // Pi can reject while mounting the custom overlay without disposing the
227
+ // factory result. Release upstream listeners even when onHandle never ran.
228
+ await releaseHost?.();
229
+ if (completedOutcome && "error" in completedOutcome) {
230
+ throw new AggregateError([error, completedOutcome.error], "Fullscreen mount and cleanup failed");
231
+ }
232
+ throw error;
233
+ });
234
+ // External custom disposal can resolve undefined before host.dispose finishes.
235
+ // Terminal restoration and cleanup failures still belong to this command.
236
+ await releaseHost?.();
237
+ const completion = completedOutcome ?? outcome;
238
+ if (!completion) return cancelledValue;
239
+ if ("error" in completion) throw completion.error;
240
+ return completion.value;
241
+ }
@@ -0,0 +1,17 @@
1
+ import { ScrollView } from "@earendil-works/pi-tui";
2
+ import type { SettingsChatAnchor } from "./settings-chat-transcript.js";
3
+
4
+ /** Native layout owns clipping; this adapter retains message identity across history changes. */
5
+ export class SettingsChatScrollView extends ScrollView {
6
+ anchor: SettingsChatAnchor | undefined;
7
+ restoreAnchor?: (anchor: SettingsChatAnchor) => number;
8
+
9
+ override updateLayout(contentHeight: number, viewportHeight: number, requestRender: () => void): void {
10
+ const manual = !this.isFollowingEnd;
11
+ const target = manual && this.anchor ? this.restoreAnchor?.(this.anchor) : undefined;
12
+ super.updateLayout(contentHeight, viewportHeight, requestRender);
13
+ // Resizing or collapsing output can temporarily make the content fit. That must
14
+ // not silently enable follow-end after the user chose an older message.
15
+ if (manual) this.scrollTo(target ?? this.scrollTop, { disableFollow: true });
16
+ }
17
+ }
@@ -0,0 +1,207 @@
1
+ import { resolve } from "node:path";
2
+ import type { AgentEvent, AgentMessage } from "@earendil-works/pi-agent-core";
3
+ import type { AssistantMessage, ToolCall, ToolResultMessage } from "@earendil-works/pi-ai";
4
+ import {
5
+ createEditToolDefinition,
6
+ createReadToolDefinition,
7
+ createWriteToolDefinition,
8
+ ToolExecutionComponent,
9
+ } from "@earendil-works/pi-coding-agent";
10
+ import type { TUI, TuiMouseEvent } from "@earendil-works/pi-tui";
11
+ import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
12
+ import { settingsChatDisplayValue } from "./settings-chat-display.js";
13
+
14
+ type ToolResult = Parameters<ToolExecutionComponent["updateResult"]>[0];
15
+ interface ToolRow {
16
+ name: string;
17
+ args: Record<string, unknown>;
18
+ component?: ToolExecutionComponent;
19
+ complete: boolean;
20
+ started: boolean;
21
+ result?: ToolResult;
22
+ partial: boolean;
23
+ historyResult?: AgentMessage;
24
+ expanded?: boolean;
25
+ }
26
+
27
+ /** Follow Pi's message and tool execution branches with native built-in renderers. */
28
+ export function createSettingsChatTools(tui: TUI, cwd: string, initialExpanded: boolean, editablePath?: string) {
29
+ const rows = new Map<string, ToolRow>();
30
+ const pending = new Set<string>();
31
+ const edit = createEditToolDefinition(cwd);
32
+ const renderEditCall = edit.renderCall;
33
+ if (renderEditCall) {
34
+ edit.renderCall = (args, theme, context) => {
35
+ const path =
36
+ typeof args?.path === "string" ? args.path : args && "file_path" in args ? args.file_path : undefined;
37
+ const allowed =
38
+ editablePath !== undefined && typeof path === "string" && resolve(cwd, path) === resolve(editablePath);
39
+ // Native previews read the target before tool execution. Do not let that
40
+ // display-only read bypass this chat's draft-only edit permission.
41
+ return renderEditCall(args, theme, { ...context, argsComplete: context.argsComplete && allowed });
42
+ };
43
+ }
44
+ const definitions = {
45
+ read: createReadToolDefinition(cwd),
46
+ write: createWriteToolDefinition(cwd),
47
+ edit,
48
+ };
49
+ let disposed = false;
50
+ let expanded = initialExpanded;
51
+ const ensure = (id: string, name: string, args: Record<string, unknown>) => {
52
+ let row = rows.get(id);
53
+ if (!row) {
54
+ row = { name, args, complete: false, started: false, partial: true };
55
+ rows.set(id, row);
56
+ }
57
+ if (!row.component) {
58
+ const toolName = row.name;
59
+ const definition =
60
+ toolName === "read" || toolName === "write" || toolName === "edit" ? definitions[toolName] : undefined;
61
+ const ownedRow = row;
62
+ const toolUi = new Proxy(tui, {
63
+ get(target, property) {
64
+ if (property === "requestRender")
65
+ return () => {
66
+ // Pi's edit-preview read has no cancellation API. Its late completion
67
+ // can invalidate its old component, but must not redraw a closed chat.
68
+ if (!disposed && rows.get(id) === ownedRow && ownedRow.component === component) target.requestRender();
69
+ };
70
+ const value: unknown = Reflect.get(target, property, target);
71
+ return typeof value === "function" ? value.bind(target) : value;
72
+ },
73
+ });
74
+ // Native result clicks call setExpanded(). Keep that local preference
75
+ // when themed components are rebuilt, without reading private Pi state.
76
+ const Component = class extends ToolExecutionComponent {
77
+ override setExpanded(value: boolean) {
78
+ ownedRow.expanded = value;
79
+ super.setExpanded(value);
80
+ }
81
+ };
82
+ const component = new Component(
83
+ sanitizeTerminalDocument(toolName),
84
+ sanitizeTerminalDocument(id),
85
+ settingsChatDisplayValue(row.args),
86
+ { showImages: false, outputPad: 1 },
87
+ definition,
88
+ toolUi,
89
+ sanitizeTerminalDocument(cwd),
90
+ );
91
+ row.component = component;
92
+ component.setExpanded(row.expanded ?? expanded);
93
+ // Historical final results already contain the authoritative edit diff.
94
+ // Do not reread a mutated file to compute another preview after a rebuild.
95
+ if (row.complete && (!row.result || row.partial)) component.setArgsComplete();
96
+ if (row.started) component.markExecutionStarted();
97
+ if (row.result) component.updateResult(settingsChatDisplayValue(row.result), row.partial);
98
+ }
99
+ return row;
100
+ };
101
+ const updateArgs = (call: ToolCall) => {
102
+ const row = ensure(call.id, call.name, call.arguments);
103
+ row.args = call.arguments;
104
+ row.component?.updateArgs(settingsChatDisplayValue(call.arguments));
105
+ return row;
106
+ };
107
+ const completeArgs = (row: ToolRow) => {
108
+ if (row.complete) return;
109
+ row.complete = true;
110
+ row.component?.setArgsComplete();
111
+ };
112
+ const result = (row: ToolRow, value: ToolResult, partial = false) => {
113
+ row.result = value;
114
+ row.partial = partial;
115
+ row.component?.updateResult(settingsChatDisplayValue(value), partial);
116
+ };
117
+ const failure = (message: AssistantMessage): ToolResult => ({
118
+ content: [
119
+ { type: "text", text: message.stopReason === "aborted" ? "Operation aborted" : message.errorMessage || "Error" },
120
+ ],
121
+ isError: true,
122
+ });
123
+ return {
124
+ onEvent(event: AgentEvent) {
125
+ if (disposed) return;
126
+ if (event.type === "message_update" && event.message.role === "assistant") {
127
+ for (const call of event.message.content) {
128
+ if (call.type !== "toolCall") continue;
129
+ updateArgs(call);
130
+ pending.add(call.id);
131
+ }
132
+ }
133
+ if (event.type === "message_end" && event.message.role === "assistant") {
134
+ const failed = event.message.stopReason === "aborted" || event.message.stopReason === "error";
135
+ // A provider can finalize tool calls without an intermediate update.
136
+ for (const call of event.message.content) {
137
+ if (call.type !== "toolCall") continue;
138
+ updateArgs(call);
139
+ pending.add(call.id);
140
+ }
141
+ for (const id of pending) {
142
+ const row = rows.get(id);
143
+ if (!row) continue;
144
+ if (failed) result(row, failure(event.message));
145
+ else completeArgs(row);
146
+ }
147
+ if (failed) pending.clear();
148
+ }
149
+ if (event.type === "tool_execution_start" && !("parentToolCallId" in event && event.parentToolCallId)) {
150
+ const row = ensure(event.toolCallId, event.toolName, event.args);
151
+ pending.add(event.toolCallId);
152
+ row.started = true;
153
+ row.component?.markExecutionStarted();
154
+ }
155
+ if (event.type === "tool_execution_update") {
156
+ const row = pending.has(event.toolCallId) ? rows.get(event.toolCallId) : undefined;
157
+ if (row) result(row, { ...event.partialResult, isError: false }, true);
158
+ }
159
+ if (event.type === "tool_execution_end") {
160
+ const row = pending.has(event.toolCallId) ? rows.get(event.toolCallId) : undefined;
161
+ if (row) result(row, { ...event.result, isError: event.isError, durationMs: event.durationMs });
162
+ pending.delete(event.toolCallId);
163
+ }
164
+ if (event.type === "agent_end") pending.clear();
165
+ },
166
+ render(call: ToolCall, message: AssistantMessage, historyResult: ToolResultMessage | undefined, width: number) {
167
+ const row = ensure(call.id, call.name, call.arguments);
168
+ if (historyResult && row.historyResult !== historyResult) {
169
+ row.historyResult = historyResult;
170
+ result(row, historyResult);
171
+ }
172
+ if (!historyResult && !row.result && (message.stopReason === "aborted" || message.stopReason === "error"))
173
+ result(row, failure(message));
174
+ return row.component?.render(width) ?? [];
175
+ },
176
+ handleMouse(id: string, event: TuiMouseEvent) {
177
+ if (disposed) return undefined;
178
+ return rows.get(id)?.component?.handleMouse(event);
179
+ },
180
+ retain(ids: Set<string>) {
181
+ for (const id of rows.keys())
182
+ if (!ids.has(id)) {
183
+ rows.delete(id);
184
+ pending.delete(id);
185
+ }
186
+ },
187
+ toggle() {
188
+ if (!disposed) {
189
+ expanded = !expanded;
190
+ for (const row of rows.values()) {
191
+ row.expanded = expanded;
192
+ row.component?.setExpanded(expanded);
193
+ }
194
+ tui.requestRender();
195
+ }
196
+ return expanded;
197
+ },
198
+ invalidate() {
199
+ for (const row of rows.values()) row.component = undefined;
200
+ },
201
+ dispose() {
202
+ disposed = true;
203
+ pending.clear();
204
+ rows.clear();
205
+ },
206
+ };
207
+ }