@narumitw/pi-starship 0.63.0 → 0.64.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -4
- package/dist/chunks/{chunk-63R6R5DH.ts → chunk-DIHVBO5Z.ts} +2 -2
- package/dist/chunks/{chunk-Y24TJYG6.ts → chunk-UIKPE4UC.ts} +1 -1
- package/dist/chunks/{chunk-Y24TJYG6.ts.map → chunk-UIKPE4UC.ts.map} +2 -2
- package/dist/chunks/{command-configuration-menu-YOLN2SPR.ts → command-configuration-menu-ZN2VXU4L.ts} +2 -2
- package/dist/chunks/{command-settings-chat-5AHP3JGV.ts → command-settings-chat-KLUVZXMO.ts} +580 -227
- package/dist/chunks/command-settings-chat-KLUVZXMO.ts.map +7 -0
- package/dist/chunks/{commands-IOG2PL67.ts → commands-UAUSSHVS.ts} +7 -6
- package/dist/chunks/commands-UAUSSHVS.ts.map +7 -0
- package/dist/index.ts +3 -2
- package/dist/index.ts.map +2 -2
- package/package.json +1 -1
- package/src/command-configuration.ts +2 -0
- package/src/command-settings-chat.ts +17 -5
- package/src/commands.ts +1 -0
- package/src/pi-starship.ts +1 -0
- package/src/settings-chat-display.ts +11 -0
- package/src/settings-chat-fullscreen.ts +264 -0
- package/src/settings-chat-scroll.ts +17 -0
- package/src/settings-chat-tools.ts +207 -0
- package/src/settings-chat-transcript.ts +91 -72
- package/src/settings-chat-ui.ts +94 -183
- package/dist/chunks/command-settings-chat-5AHP3JGV.ts.map +0 -7
- package/dist/chunks/commands-IOG2PL67.ts.map +0 -7
- /package/dist/chunks/{chunk-63R6R5DH.ts.map → chunk-DIHVBO5Z.ts.map} +0 -0
- /package/dist/chunks/{command-configuration-menu-YOLN2SPR.ts.map → command-configuration-menu-ZN2VXU4L.ts.map} +0 -0
package/package.json
CHANGED
|
@@ -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 {
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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.
|
package/src/pi-starship.ts
CHANGED
|
@@ -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,264 @@
|
|
|
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 type { WorkflowOwner } from "./command-configuration.js";
|
|
12
|
+
|
|
13
|
+
export type SettingsChatFullscreenComponent = Component & {
|
|
14
|
+
dispose?(): void;
|
|
15
|
+
waitForPending?(): Promise<void>;
|
|
16
|
+
getFullscreenLayout?(): Component;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export interface SettingsChatFullscreenOptions<Value> {
|
|
20
|
+
tui: TUI;
|
|
21
|
+
theme: Theme;
|
|
22
|
+
keybindings: KeybindingsManager;
|
|
23
|
+
signal: AbortSignal;
|
|
24
|
+
complete(value: Value): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface SettingsChatFullscreenDependencies {
|
|
28
|
+
createTui?(parent: TUI, createDefault: () => TuiAltScreen): TuiAltScreen;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type Outcome<Value> = { value: Value } | { error: unknown };
|
|
32
|
+
|
|
33
|
+
// The base constructor registers the native viewport listener through this public
|
|
34
|
+
// method. Install the guard first, without reading or changing Pi's listener set.
|
|
35
|
+
class SettingsChatTui extends TuiAltScreen {
|
|
36
|
+
declare private guardInstalled: boolean | undefined;
|
|
37
|
+
declare guard: TuiInputListener | undefined;
|
|
38
|
+
|
|
39
|
+
override addInputListener(listener: TuiInputListener): () => void {
|
|
40
|
+
if (!this.guardInstalled) {
|
|
41
|
+
this.guardInstalled = true;
|
|
42
|
+
super.addInputListener((data) => this.guard?.(data));
|
|
43
|
+
}
|
|
44
|
+
return super.addInputListener(listener);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Pi recommends one renderer. This isolated chat intentionally transfers the
|
|
50
|
+
* shared terminal to a native fullscreen viewport, then returns it before review.
|
|
51
|
+
* The parent custom overlay owns only the handoff lifetime, never child layout.
|
|
52
|
+
*/
|
|
53
|
+
export async function runSettingsChatFullscreen<Value>(
|
|
54
|
+
ctx: ExtensionCommandContext,
|
|
55
|
+
owner: WorkflowOwner,
|
|
56
|
+
create: (options: SettingsChatFullscreenOptions<Value>) => SettingsChatFullscreenComponent,
|
|
57
|
+
cancelledValue: Value,
|
|
58
|
+
dependencies: SettingsChatFullscreenDependencies = {},
|
|
59
|
+
): Promise<Value> {
|
|
60
|
+
const current = () => !owner.signal.aborted && !ctx.signal?.aborted && owner.isCurrent();
|
|
61
|
+
const canRestoreTerminal = () => (owner.canRestoreTerminal ?? owner.isSessionCurrent ?? owner.isCurrent)();
|
|
62
|
+
if (ctx.mode !== "tui" || !current()) return cancelledValue;
|
|
63
|
+
|
|
64
|
+
let mount: ((handle: OverlayHandle) => void) | undefined;
|
|
65
|
+
let releaseHost: (() => Promise<void>) | undefined;
|
|
66
|
+
let completedOutcome: Outcome<Value> | undefined;
|
|
67
|
+
const outcome = await ctx.ui
|
|
68
|
+
.custom<Outcome<Value>>(
|
|
69
|
+
(parent, theme, keybindings, done) => {
|
|
70
|
+
const controller = new AbortController();
|
|
71
|
+
let child: TuiAltScreen | undefined;
|
|
72
|
+
let component: SettingsChatFullscreenComponent | undefined;
|
|
73
|
+
let overlay: OverlayHandle | undefined;
|
|
74
|
+
let parentStopped = false;
|
|
75
|
+
let entry: Promise<void> | undefined;
|
|
76
|
+
let entryDrainStarted = false;
|
|
77
|
+
let finished = false;
|
|
78
|
+
let closing = false;
|
|
79
|
+
let cleanup: Promise<void> | undefined;
|
|
80
|
+
let pasting = false;
|
|
81
|
+
let result: Outcome<Value> = { value: cancelledValue };
|
|
82
|
+
const errors: unknown[] = [];
|
|
83
|
+
const removers: (() => void)[] = [];
|
|
84
|
+
const attempt = (action: () => void) => {
|
|
85
|
+
try {
|
|
86
|
+
action();
|
|
87
|
+
} catch (error) {
|
|
88
|
+
errors.push(error);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const finish = (next: Outcome<Value>) => {
|
|
93
|
+
if (closing) return cleanup;
|
|
94
|
+
closing = true;
|
|
95
|
+
result = next;
|
|
96
|
+
// Root work must stop synchronously, even when a nested overlay has focus.
|
|
97
|
+
controller.abort();
|
|
98
|
+
cleanup = Promise.resolve().then(async () => {
|
|
99
|
+
// Do not stop the terminal or start a second drain while entry still
|
|
100
|
+
// owns the native drain. Its finally block restores the input handler.
|
|
101
|
+
await entry;
|
|
102
|
+
if (parentStopped) {
|
|
103
|
+
try {
|
|
104
|
+
await parent.terminal.drainInput?.();
|
|
105
|
+
} catch (error) {
|
|
106
|
+
errors.push(error);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (entryDrainStarted && !parentStopped) {
|
|
110
|
+
// Native drain disables keyboard protocols even if entry is then
|
|
111
|
+
// cancelled or fails. Reset them through the normal stop/start path.
|
|
112
|
+
parentStopped = true;
|
|
113
|
+
attempt(() => parent.stop({ preserveScreen: true }));
|
|
114
|
+
}
|
|
115
|
+
for (const remove of removers.splice(0)) attempt(remove);
|
|
116
|
+
attempt(() => component?.dispose?.());
|
|
117
|
+
if (child) attempt(() => child?.stop({ preserveScreen: true }));
|
|
118
|
+
// Only this interaction's handle can be hidden. Pi's done callback
|
|
119
|
+
// removes it; calling hide() here would bypass custom's lifecycle.
|
|
120
|
+
if (parentStopped) {
|
|
121
|
+
attempt(() => overlay?.setHidden(true));
|
|
122
|
+
attempt(() => {
|
|
123
|
+
// Session/tree replacement can keep this physical TUI alive.
|
|
124
|
+
// Restore its input without calling any stale context UI methods.
|
|
125
|
+
if (canRestoreTerminal()) {
|
|
126
|
+
attempt(() => parent.start());
|
|
127
|
+
attempt(() => parent.renderNow(false));
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
// Return input ownership promptly, then join cancelled root work.
|
|
132
|
+
// A late stream must settle before the owning command releases its draft.
|
|
133
|
+
try {
|
|
134
|
+
await component?.waitForPending?.();
|
|
135
|
+
} catch (error) {
|
|
136
|
+
errors.push(error);
|
|
137
|
+
}
|
|
138
|
+
attempt(() => {
|
|
139
|
+
if (!current() && !("error" in result)) result = { value: cancelledValue };
|
|
140
|
+
});
|
|
141
|
+
finished = true;
|
|
142
|
+
if ("error" in result) errors.unshift(result.error);
|
|
143
|
+
completedOutcome = errors.length
|
|
144
|
+
? { error: errors.length === 1 ? errors[0] : new AggregateError(errors, "Fullscreen cleanup failed") }
|
|
145
|
+
: result;
|
|
146
|
+
done(completedOutcome);
|
|
147
|
+
});
|
|
148
|
+
return cleanup;
|
|
149
|
+
};
|
|
150
|
+
releaseHost = () => finish({ value: cancelledValue }) ?? Promise.resolve();
|
|
151
|
+
const cancel = () => finish({ value: cancelledValue });
|
|
152
|
+
const guard: TuiInputListener = (data) => {
|
|
153
|
+
if (closing) return { consume: true };
|
|
154
|
+
if (!current()) {
|
|
155
|
+
cancel();
|
|
156
|
+
return { consume: true };
|
|
157
|
+
}
|
|
158
|
+
// A terminal can deliver bracketed paste as one packet or separate
|
|
159
|
+
// packets. Ctrl+C in either form is text, not a screen shortcut.
|
|
160
|
+
const wasPasting = pasting;
|
|
161
|
+
for (const part of data.split("\x1b").slice(1)) {
|
|
162
|
+
if (part.startsWith("[200~")) pasting = true;
|
|
163
|
+
else if (part.startsWith("[201~")) pasting = false;
|
|
164
|
+
}
|
|
165
|
+
if (wasPasting || pasting || data.includes("\x1b[200~") || data.includes("\x1b[201~")) {
|
|
166
|
+
try {
|
|
167
|
+
// Paste belongs to the focused editor or native search overlay,
|
|
168
|
+
// not necessarily to the root chat. Bypass viewport shortcuts only.
|
|
169
|
+
child?.getFocusedComponent()?.handleInput?.(data);
|
|
170
|
+
child?.requestRender();
|
|
171
|
+
} catch (error) {
|
|
172
|
+
finish({ error });
|
|
173
|
+
}
|
|
174
|
+
return { consume: true };
|
|
175
|
+
}
|
|
176
|
+
if (!isKeyRelease(data) && matchesKey(data, "ctrl+c")) {
|
|
177
|
+
cancel();
|
|
178
|
+
return { consume: true };
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
for (const signal of new Set([owner.signal, ctx.signal])) {
|
|
183
|
+
if (!signal) continue;
|
|
184
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
185
|
+
removers.push(() => signal.removeEventListener("abort", cancel));
|
|
186
|
+
}
|
|
187
|
+
const host: SettingsChatFullscreenComponent = {
|
|
188
|
+
render: () => [],
|
|
189
|
+
invalidate() {},
|
|
190
|
+
dispose() {
|
|
191
|
+
if (!finished) cancel();
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
mount = (handle) => {
|
|
195
|
+
overlay = handle;
|
|
196
|
+
// The custom factory and any active terminal callback must unwind before
|
|
197
|
+
// terminal ownership changes. onHandle runs only after Pi mounts host.
|
|
198
|
+
queueMicrotask(() => {
|
|
199
|
+
if (closing) return;
|
|
200
|
+
entry = (async () => {
|
|
201
|
+
try {
|
|
202
|
+
if (!current()) {
|
|
203
|
+
cancel();
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
entryDrainStarted = parent.terminal.drainInput !== undefined;
|
|
207
|
+
await parent.terminal.drainInput?.();
|
|
208
|
+
if (closing) return;
|
|
209
|
+
if (!current()) {
|
|
210
|
+
cancel();
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
parentStopped = true;
|
|
214
|
+
parent.stop({ preserveScreen: true });
|
|
215
|
+
if (closing) return;
|
|
216
|
+
const createDefault = () =>
|
|
217
|
+
new SettingsChatTui(parent.terminal, parent.getShowHardwareCursor(), undefined, { mouse: true });
|
|
218
|
+
child = dependencies.createTui?.(parent, createDefault) ?? createDefault();
|
|
219
|
+
if (child instanceof SettingsChatTui) child.guard = guard;
|
|
220
|
+
else removers.push(child.addInputListener(guard));
|
|
221
|
+
component = create({
|
|
222
|
+
tui: child,
|
|
223
|
+
theme,
|
|
224
|
+
keybindings,
|
|
225
|
+
signal: controller.signal,
|
|
226
|
+
complete: (value) => finish({ value }),
|
|
227
|
+
});
|
|
228
|
+
if (closing) return;
|
|
229
|
+
if (!current()) {
|
|
230
|
+
cancel();
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
child.setLayoutRoot(component.getFullscreenLayout?.() ?? component);
|
|
234
|
+
child.setFocus(component);
|
|
235
|
+
child.start();
|
|
236
|
+
} catch (error) {
|
|
237
|
+
if (closing) errors.push(error);
|
|
238
|
+
else finish({ error });
|
|
239
|
+
}
|
|
240
|
+
})();
|
|
241
|
+
});
|
|
242
|
+
};
|
|
243
|
+
if (!current()) cancel();
|
|
244
|
+
return host;
|
|
245
|
+
},
|
|
246
|
+
{ overlay: true, onHandle: (handle) => mount?.(handle) },
|
|
247
|
+
)
|
|
248
|
+
.catch(async (error: unknown) => {
|
|
249
|
+
// Pi can reject while mounting the custom overlay without disposing the
|
|
250
|
+
// factory result. Release upstream listeners even when onHandle never ran.
|
|
251
|
+
await releaseHost?.();
|
|
252
|
+
if (completedOutcome && "error" in completedOutcome) {
|
|
253
|
+
throw new AggregateError([error, completedOutcome.error], "Fullscreen mount and cleanup failed");
|
|
254
|
+
}
|
|
255
|
+
throw error;
|
|
256
|
+
});
|
|
257
|
+
// External custom disposal can resolve undefined before host.dispose finishes.
|
|
258
|
+
// Terminal restoration and cleanup failures still belong to this command.
|
|
259
|
+
await releaseHost?.();
|
|
260
|
+
const completion = completedOutcome ?? outcome;
|
|
261
|
+
if (!completion) return cancelledValue;
|
|
262
|
+
if ("error" in completion) throw completion.error;
|
|
263
|
+
return completion.value;
|
|
264
|
+
}
|
|
@@ -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
|
+
}
|