pi-subagent-manager 0.8.0 → 0.9.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 +2 -2
- package/docs/tools-and-ui.md +36 -4
- package/package.json +1 -1
- package/src/index.ts +54 -5
- package/src/orch/manager.ts +96 -0
- package/src/orch/runtime.ts +27 -0
- package/src/orch/transcript.ts +186 -0
- package/src/types.ts +30 -0
- package/src/ui/agent-navigation-editor.ts +198 -0
- package/src/ui/dialog.ts +14 -13
- package/src/ui/live-agent-view.ts +361 -0
- package/src/ui/status-ui.ts +279 -46
- package/src/ui/ui.ts +13 -7
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CustomEditor,
|
|
3
|
+
type CustomEditorOptions,
|
|
4
|
+
type KeybindingsManager,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import {
|
|
7
|
+
getKeybindings,
|
|
8
|
+
Key,
|
|
9
|
+
matchesKey,
|
|
10
|
+
type EditorTheme,
|
|
11
|
+
type Keybinding,
|
|
12
|
+
type TUI,
|
|
13
|
+
} from "@earendil-works/pi-tui";
|
|
14
|
+
|
|
15
|
+
export interface AgentNavigationEditorOptions {
|
|
16
|
+
/** Must return the whole navigation interaction, so repeated Down cannot reopen it. */
|
|
17
|
+
openTree(): void | Promise<void>;
|
|
18
|
+
canOpen(): boolean;
|
|
19
|
+
/** Root ownership token; changing it invalidates queued transitions. */
|
|
20
|
+
generation(): unknown;
|
|
21
|
+
onError?(error: unknown): void;
|
|
22
|
+
/**
|
|
23
|
+
* Chronological user prompts for reload/new/resume/fork. Omit on startup:
|
|
24
|
+
* Pi hydrates the installed editor after the startup session_start event.
|
|
25
|
+
*/
|
|
26
|
+
initialHistory?: readonly string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Physical Down boundary adapter. It owns no session/history internals and never
|
|
31
|
+
* changes the draft. Install once per root UI lifecycle, not for tree navigation.
|
|
32
|
+
* Another custom editor occupies the same host slot; opt out rather than stack.
|
|
33
|
+
*/
|
|
34
|
+
export class AgentNavigationEditor extends CustomEditor {
|
|
35
|
+
private pending = false;
|
|
36
|
+
private disposed = false;
|
|
37
|
+
private dispatchDepth = 0;
|
|
38
|
+
private inputEpoch = 0;
|
|
39
|
+
private pastePending = false;
|
|
40
|
+
private jumpPending = false;
|
|
41
|
+
|
|
42
|
+
constructor(
|
|
43
|
+
tui: TUI,
|
|
44
|
+
theme: EditorTheme,
|
|
45
|
+
private navigationKeys: KeybindingsManager,
|
|
46
|
+
private navigation: AgentNavigationEditorOptions,
|
|
47
|
+
options?: CustomEditorOptions,
|
|
48
|
+
) {
|
|
49
|
+
super(tui, theme, navigationKeys, options);
|
|
50
|
+
// SessionStartEvent.reason distinguishes startup (host hydrates AFTER
|
|
51
|
+
// installation) from reload/replacement (explicit public hydration needed).
|
|
52
|
+
// Never infer replay from prompt text: intentional repetitions are valid.
|
|
53
|
+
for (const text of navigation.initialHistory ?? []) this.addToHistory(text);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Invalidates queued work without resetting a competing extension's editor. */
|
|
57
|
+
dispose(): void {
|
|
58
|
+
this.disposed = true;
|
|
59
|
+
this.inputEpoch++;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private ordinaryDown(data: string): boolean {
|
|
63
|
+
if (!matchesKey(data, Key.down)) return false;
|
|
64
|
+
// Editor uses the global TUI bindings; CustomEditor uses the injected app
|
|
65
|
+
// manager. Both must agree, and a conflicting remap wins conservatively.
|
|
66
|
+
for (const keys of [this.navigationKeys, getKeybindings()]) {
|
|
67
|
+
if (!keys.matches(data, "tui.editor.cursorDown")) return false;
|
|
68
|
+
for (const action of Object.keys(keys.getResolvedBindings())) {
|
|
69
|
+
if (
|
|
70
|
+
action !== "tui.editor.cursorDown" &&
|
|
71
|
+
(action.startsWith("tui.editor.") ||
|
|
72
|
+
action.startsWith("tui.input.") ||
|
|
73
|
+
action.startsWith("tui.altScreen.") ||
|
|
74
|
+
action.startsWith("app.")) &&
|
|
75
|
+
keys.matches(data, action as Keybinding)
|
|
76
|
+
)
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
override handleInput(data: string): void {
|
|
84
|
+
const outer = this.dispatchDepth === 0;
|
|
85
|
+
const down = this.ordinaryDown(data);
|
|
86
|
+
if (outer && !down) this.inputEpoch++;
|
|
87
|
+
const previousPaste = this.pastePending;
|
|
88
|
+
const wasPaste = previousPaste || data.includes("\x1b[200~");
|
|
89
|
+
// Update before dispatch: Pi recursively sends a suffix after the end
|
|
90
|
+
// marker through this.handleInput, and that suffix is no longer paste.
|
|
91
|
+
if (data.includes("\x1b[200~")) this.pastePending = true;
|
|
92
|
+
if (wasPaste && data.includes("\x1b[201~")) this.pastePending = false;
|
|
93
|
+
const wasJump = this.jumpPending;
|
|
94
|
+
const cursor = this.getCursor();
|
|
95
|
+
const lines = this.getLines();
|
|
96
|
+
const text = this.getText();
|
|
97
|
+
const eligible =
|
|
98
|
+
outer &&
|
|
99
|
+
down &&
|
|
100
|
+
this.focused &&
|
|
101
|
+
!this.disposed &&
|
|
102
|
+
!wasPaste &&
|
|
103
|
+
!wasJump &&
|
|
104
|
+
!this.isShowingAutocomplete() &&
|
|
105
|
+
cursor.line === lines.length - 1 &&
|
|
106
|
+
cursor.col === (lines.at(-1)?.length ?? 0);
|
|
107
|
+
const generation = eligible ? this.navigation.generation() : undefined;
|
|
108
|
+
let changed = false;
|
|
109
|
+
let consumed = false;
|
|
110
|
+
const originalChange = this.onChange;
|
|
111
|
+
const originalShortcut = this.onExtensionShortcut;
|
|
112
|
+
const observeChange = (value: string) => {
|
|
113
|
+
changed = true;
|
|
114
|
+
originalChange?.call(this, value);
|
|
115
|
+
};
|
|
116
|
+
const observeShortcut = (value: string) => {
|
|
117
|
+
const handled = originalShortcut?.call(this, value) ?? false;
|
|
118
|
+
consumed ||= handled && value === data;
|
|
119
|
+
return handled;
|
|
120
|
+
};
|
|
121
|
+
this.onChange = observeChange;
|
|
122
|
+
this.onExtensionShortcut = observeShortcut;
|
|
123
|
+
this.dispatchDepth++;
|
|
124
|
+
try {
|
|
125
|
+
// Exactly one stock dispatch, preserving host-wired application controls.
|
|
126
|
+
super.handleInput(data);
|
|
127
|
+
} finally {
|
|
128
|
+
this.dispatchDepth--;
|
|
129
|
+
if (this.onChange === observeChange) this.onChange = originalChange;
|
|
130
|
+
if (this.onExtensionShortcut === observeShortcut) this.onExtensionShortcut = originalShortcut;
|
|
131
|
+
if (consumed) this.pastePending = previousPaste;
|
|
132
|
+
if (!consumed) {
|
|
133
|
+
// Track only public input; over-suppress when precedence is ambiguous.
|
|
134
|
+
// Recursive paste suffix dispatch updates guards, but never opens UI.
|
|
135
|
+
if (!wasPaste) {
|
|
136
|
+
const keys = getKeybindings();
|
|
137
|
+
const jump =
|
|
138
|
+
keys.matches(data, "tui.editor.jumpForward") ||
|
|
139
|
+
keys.matches(data, "tui.editor.jumpBackward");
|
|
140
|
+
this.jumpPending = !wasJump && jump;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const after = this.getCursor();
|
|
145
|
+
if (
|
|
146
|
+
eligible &&
|
|
147
|
+
!consumed &&
|
|
148
|
+
!changed &&
|
|
149
|
+
!this.isShowingAutocomplete() &&
|
|
150
|
+
this.getText() === text &&
|
|
151
|
+
after.line === cursor.line &&
|
|
152
|
+
after.col === cursor.col
|
|
153
|
+
) {
|
|
154
|
+
this.queueOpen(text, cursor, generation);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
private queueOpen(
|
|
159
|
+
text: string,
|
|
160
|
+
cursor: { line: number; col: number },
|
|
161
|
+
generation: unknown,
|
|
162
|
+
): void {
|
|
163
|
+
if (this.pending || !this.navigation.canOpen()) return;
|
|
164
|
+
this.pending = true;
|
|
165
|
+
const epoch = this.inputEpoch;
|
|
166
|
+
queueMicrotask(() => {
|
|
167
|
+
const after = this.getCursor();
|
|
168
|
+
if (
|
|
169
|
+
this.disposed ||
|
|
170
|
+
!this.focused ||
|
|
171
|
+
this.inputEpoch !== epoch ||
|
|
172
|
+
this.navigation.generation() !== generation ||
|
|
173
|
+
!this.navigation.canOpen() ||
|
|
174
|
+
this.isShowingAutocomplete() ||
|
|
175
|
+
this.getText() !== text ||
|
|
176
|
+
after.line !== cursor.line ||
|
|
177
|
+
after.col !== cursor.col
|
|
178
|
+
) {
|
|
179
|
+
this.pending = false;
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
// The host must guard tree input handoff; legacy terminals have no
|
|
183
|
+
// reliable key-release signal for a held Down.
|
|
184
|
+
try {
|
|
185
|
+
// Call within the checked microtask: an extra Promise.then would leave
|
|
186
|
+
// a gap in which root ownership could change after validation.
|
|
187
|
+
void Promise.resolve(this.navigation.openTree())
|
|
188
|
+
.catch((error: unknown) => this.navigation.onError?.(error))
|
|
189
|
+
.finally(() => {
|
|
190
|
+
this.pending = false;
|
|
191
|
+
});
|
|
192
|
+
} catch (error) {
|
|
193
|
+
this.pending = false;
|
|
194
|
+
this.navigation.onError?.(error);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
package/src/ui/dialog.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type {
|
|
2
|
-
|
|
2
|
+
ExtensionContext,
|
|
3
3
|
ExtensionUIContext,
|
|
4
4
|
KeybindingsManager,
|
|
5
5
|
Theme,
|
|
@@ -167,7 +167,7 @@ export class DialogEditor {
|
|
|
167
167
|
}
|
|
168
168
|
|
|
169
169
|
export function dialogEditor(
|
|
170
|
-
ctx:
|
|
170
|
+
ctx: ExtensionContext,
|
|
171
171
|
title: string,
|
|
172
172
|
prefill: string,
|
|
173
173
|
): Promise<string | undefined> {
|
|
@@ -273,7 +273,7 @@ export class DialogMenu {
|
|
|
273
273
|
}
|
|
274
274
|
}
|
|
275
275
|
|
|
276
|
-
export function canOpenDialog(ctx:
|
|
276
|
+
export function canOpenDialog(ctx: ExtensionContext): boolean {
|
|
277
277
|
if (!ctx.hasUI) return false;
|
|
278
278
|
if (ctx.mode && ctx.mode !== "tui") {
|
|
279
279
|
ctx.ui.notify("Agents dialogs require interactive TUI mode.", "warning");
|
|
@@ -283,7 +283,7 @@ export function canOpenDialog(ctx: ExtensionCommandContext): boolean {
|
|
|
283
283
|
}
|
|
284
284
|
|
|
285
285
|
export async function dialogMenu(
|
|
286
|
-
ctx:
|
|
286
|
+
ctx: ExtensionContext,
|
|
287
287
|
title: string,
|
|
288
288
|
rows: DialogRow[],
|
|
289
289
|
options: { selectedId?: string; footer?: string; saveId?: string } = {},
|
|
@@ -305,7 +305,7 @@ export async function dialogMenu(
|
|
|
305
305
|
}
|
|
306
306
|
|
|
307
307
|
export async function dialogInput(
|
|
308
|
-
ctx:
|
|
308
|
+
ctx: ExtensionContext,
|
|
309
309
|
title: string,
|
|
310
310
|
initial: string,
|
|
311
311
|
help: string,
|
|
@@ -366,7 +366,7 @@ interface PendingView {
|
|
|
366
366
|
resolve: (value: unknown) => void;
|
|
367
367
|
}
|
|
368
368
|
|
|
369
|
-
const dialogScopes = new WeakSet<
|
|
369
|
+
const dialogScopes = new WeakSet<ExtensionContext>();
|
|
370
370
|
|
|
371
371
|
function isPromise<T>(value: T | Promise<T>): value is Promise<T> {
|
|
372
372
|
return (
|
|
@@ -512,6 +512,7 @@ export class DialogSession {
|
|
|
512
512
|
this.disposed = true;
|
|
513
513
|
this.closed = true;
|
|
514
514
|
this.inputLocked = true;
|
|
515
|
+
this.resolvePending();
|
|
515
516
|
const child = this.child;
|
|
516
517
|
this.child = undefined;
|
|
517
518
|
safeDispose(child);
|
|
@@ -567,10 +568,10 @@ export class DialogSession {
|
|
|
567
568
|
}
|
|
568
569
|
}
|
|
569
570
|
|
|
570
|
-
function scopeDialogContext(
|
|
571
|
-
ctx:
|
|
571
|
+
export function scopeDialogContext<T extends ExtensionContext>(
|
|
572
|
+
ctx: T,
|
|
572
573
|
session: DialogSession,
|
|
573
|
-
):
|
|
574
|
+
): T {
|
|
574
575
|
const source = ctx.ui;
|
|
575
576
|
const originalCustom = source.custom.bind(source);
|
|
576
577
|
const ui = Object.create(source) as ExtensionUIContext;
|
|
@@ -584,16 +585,16 @@ function scopeDialogContext(
|
|
|
584
585
|
// Define an own property while keeping the remaining context getters live.
|
|
585
586
|
return Object.create(ctx, {
|
|
586
587
|
ui: { value: ui, writable: true, enumerable: true, configurable: true },
|
|
587
|
-
}) as
|
|
588
|
+
}) as T;
|
|
588
589
|
}
|
|
589
590
|
|
|
590
591
|
/**
|
|
591
592
|
* Run a dialog workflow inside one ctx.ui.custom overlay.
|
|
592
593
|
* Nested calls on the scoped context reuse that overlay instead of opening another.
|
|
593
594
|
*/
|
|
594
|
-
export async function withDialogSession(
|
|
595
|
-
ctx:
|
|
596
|
-
run: (ctx:
|
|
595
|
+
export async function withDialogSession<T extends ExtensionContext>(
|
|
596
|
+
ctx: T,
|
|
597
|
+
run: (ctx: T) => Promise<void>,
|
|
597
598
|
): Promise<void> {
|
|
598
599
|
if (dialogScopes.has(ctx)) {
|
|
599
600
|
await run(ctx);
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import {
|
|
4
|
+
Key,
|
|
5
|
+
matchesKey,
|
|
6
|
+
ScrollView,
|
|
7
|
+
stripTerminalSequences,
|
|
8
|
+
truncateToWidth,
|
|
9
|
+
visibleWidth,
|
|
10
|
+
wrapTextWithAnsi,
|
|
11
|
+
} from "@earendil-works/pi-tui";
|
|
12
|
+
import type { ThreadService, TranscriptSnapshot } from "../types.ts";
|
|
13
|
+
import { dialogText, type DialogHost } from "./dialog.ts";
|
|
14
|
+
|
|
15
|
+
export interface AgentViewportState {
|
|
16
|
+
scrollTop: number;
|
|
17
|
+
follow: boolean;
|
|
18
|
+
showInherited?: boolean;
|
|
19
|
+
showThinking?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Fully cover main, including at very small sizes; style sequences originate only from our theme. */
|
|
23
|
+
export function fillViewport(lines: string[], width: number, height: number): string[] {
|
|
24
|
+
width = Math.max(0, Math.floor(width));
|
|
25
|
+
height = Math.max(1, Math.floor(height));
|
|
26
|
+
const result = lines.slice(0, height).map((line) => {
|
|
27
|
+
const clipped = truncateToWidth(line, width, "", true);
|
|
28
|
+
return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
|
|
29
|
+
});
|
|
30
|
+
while (result.length < height) result.push(" ".repeat(width));
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function text(value: string): string {
|
|
35
|
+
return stripTerminalSequences(value)
|
|
36
|
+
.replace(/\r\n?/g, "\n")
|
|
37
|
+
.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function object(value: unknown): Record<string, unknown> | undefined {
|
|
41
|
+
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function json(value: unknown): string {
|
|
45
|
+
try {
|
|
46
|
+
return JSON.stringify(value, null, 2) ?? "";
|
|
47
|
+
} catch {
|
|
48
|
+
return "[unrenderable data]";
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** V1 is text-only. Never feed a watched tool's custom renderer or control sequences into main. */
|
|
53
|
+
export class LiveAgentView {
|
|
54
|
+
private snapshot: TranscriptSnapshot | undefined;
|
|
55
|
+
private error: string | undefined;
|
|
56
|
+
private disposed = false;
|
|
57
|
+
private attachment = 0;
|
|
58
|
+
private unsubscribe: (() => void) | undefined;
|
|
59
|
+
private renderTimer: ReturnType<typeof setTimeout> | undefined;
|
|
60
|
+
private cache = new WeakMap<object, { width: number; thinking: boolean; lines: string[] }>();
|
|
61
|
+
private scroll: ScrollView;
|
|
62
|
+
private content: string[] = [];
|
|
63
|
+
private restoreViewport = true;
|
|
64
|
+
|
|
65
|
+
constructor(
|
|
66
|
+
private host: DialogHost,
|
|
67
|
+
private theme: Theme,
|
|
68
|
+
private service: ThreadService,
|
|
69
|
+
readonly path: string,
|
|
70
|
+
private viewport: AgentViewportState,
|
|
71
|
+
private done: (result: "back" | "main") => void,
|
|
72
|
+
) {
|
|
73
|
+
this.scroll = new ScrollView(
|
|
74
|
+
{ render: () => this.content, invalidate() {} },
|
|
75
|
+
{ follow: "end", overscroll: "contain", scrollbar: "hidden" },
|
|
76
|
+
);
|
|
77
|
+
void this.attach();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private async attach(): Promise<void> {
|
|
81
|
+
const attachment = ++this.attachment;
|
|
82
|
+
this.unsubscribe?.();
|
|
83
|
+
this.unsubscribe = undefined;
|
|
84
|
+
this.error = undefined;
|
|
85
|
+
this.scheduleRender();
|
|
86
|
+
try {
|
|
87
|
+
if (!this.service.observeTranscript)
|
|
88
|
+
throw new Error("Live observation is unavailable for this service.");
|
|
89
|
+
let latest: TranscriptSnapshot | undefined;
|
|
90
|
+
const observation = await this.service.observeTranscript(this.path, (snapshot) => {
|
|
91
|
+
latest = snapshot;
|
|
92
|
+
if (this.disposed || attachment !== this.attachment) return;
|
|
93
|
+
this.accept(snapshot);
|
|
94
|
+
});
|
|
95
|
+
if (this.disposed || attachment !== this.attachment) {
|
|
96
|
+
observation.unsubscribe();
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
this.unsubscribe = observation.unsubscribe;
|
|
100
|
+
this.accept(latest ?? observation.snapshot);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (this.disposed || attachment !== this.attachment) return;
|
|
103
|
+
this.error = error instanceof Error ? error.message : String(error);
|
|
104
|
+
this.scheduleRender();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
private accept(snapshot: TranscriptSnapshot): void {
|
|
109
|
+
if (
|
|
110
|
+
this.snapshot &&
|
|
111
|
+
(snapshot.generation < this.snapshot.generation ||
|
|
112
|
+
(snapshot.generation === this.snapshot.generation &&
|
|
113
|
+
snapshot.revision < this.snapshot.revision))
|
|
114
|
+
)
|
|
115
|
+
return;
|
|
116
|
+
this.snapshot = snapshot;
|
|
117
|
+
this.error = snapshot.error;
|
|
118
|
+
this.scheduleRender();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private scheduleRender(): void {
|
|
122
|
+
if (this.disposed || this.renderTimer) return;
|
|
123
|
+
this.renderTimer = setTimeout(() => {
|
|
124
|
+
this.renderTimer = undefined;
|
|
125
|
+
if (!this.disposed) this.host.requestRender();
|
|
126
|
+
}, 16);
|
|
127
|
+
this.renderTimer.unref?.();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
invalidate(): void {
|
|
131
|
+
this.cache = new WeakMap();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
dispose(): void {
|
|
135
|
+
if (this.disposed) return;
|
|
136
|
+
this.disposed = true;
|
|
137
|
+
++this.attachment;
|
|
138
|
+
this.unsubscribe?.();
|
|
139
|
+
this.unsubscribe = undefined;
|
|
140
|
+
if (this.renderTimer) clearTimeout(this.renderTimer);
|
|
141
|
+
this.renderTimer = undefined;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
handleInput(data: string): void {
|
|
145
|
+
if (this.disposed) return;
|
|
146
|
+
if (matchesKey(data, Key.escape)) return this.done("back");
|
|
147
|
+
if (matchesKey(data, Key.ctrl("q")) || matchesKey(data, Key.ctrl("c")))
|
|
148
|
+
return this.done("main");
|
|
149
|
+
if (data === "r" && this.error) {
|
|
150
|
+
void this.attach();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (data === "c") {
|
|
154
|
+
this.viewport.showInherited = !this.viewport.showInherited;
|
|
155
|
+
this.invalidate();
|
|
156
|
+
} else if (data === "t") {
|
|
157
|
+
this.viewport.showThinking = !this.viewport.showThinking;
|
|
158
|
+
this.invalidate();
|
|
159
|
+
} else if (matchesKey(data, Key.up)) this.scroll.scrollBy(-1);
|
|
160
|
+
else if (matchesKey(data, Key.down)) this.scroll.scrollBy(1);
|
|
161
|
+
else if (matchesKey(data, Key.pageUp))
|
|
162
|
+
this.scroll.scrollBy(-Math.max(1, this.scroll.viewportHeight));
|
|
163
|
+
else if (matchesKey(data, Key.pageDown))
|
|
164
|
+
this.scroll.scrollBy(Math.max(1, this.scroll.viewportHeight));
|
|
165
|
+
else if (matchesKey(data, Key.home)) this.scroll.scrollTo(0, { disableFollow: true });
|
|
166
|
+
else if (matchesKey(data, Key.end) || data === "l") this.scroll.scrollToEnd();
|
|
167
|
+
else return; // Read-only: text/Enter never routes into either agent's editor.
|
|
168
|
+
this.saveViewport();
|
|
169
|
+
this.host.requestRender();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private saveViewport(): void {
|
|
173
|
+
this.viewport.scrollTop = this.scroll.scrollTop;
|
|
174
|
+
this.viewport.follow = this.scroll.isFollowingEnd;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private wrap(value: string, width: number): string[] {
|
|
178
|
+
return text(value)
|
|
179
|
+
.split("\n")
|
|
180
|
+
.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Tool/metadata previews are bounded by rendered rows, not just source newlines. */
|
|
184
|
+
private preview(content: unknown, width: number): string[] {
|
|
185
|
+
const values = Array.isArray(content) ? content : [content];
|
|
186
|
+
const lines: string[] = [];
|
|
187
|
+
for (const value of values) {
|
|
188
|
+
const block = object(value);
|
|
189
|
+
const valueText =
|
|
190
|
+
typeof value === "string"
|
|
191
|
+
? value
|
|
192
|
+
: block?.type === "text"
|
|
193
|
+
? String(block.text ?? "")
|
|
194
|
+
: block?.type === "image"
|
|
195
|
+
? "[Image — text-only observer]"
|
|
196
|
+
: json(value);
|
|
197
|
+
// Avoid wrapping megabytes of tool output just to display its first three rows.
|
|
198
|
+
const safe = text(valueText);
|
|
199
|
+
const bounded = safe.slice(0, 32768);
|
|
200
|
+
for (const line of bounded.split("\n")) {
|
|
201
|
+
lines.push(...wrapTextWithAnsi(line, Math.max(1, width)));
|
|
202
|
+
if (lines.length > 3) return [...lines.slice(0, 3), this.theme.fg("dim", "...")];
|
|
203
|
+
}
|
|
204
|
+
if (safe.length > bounded.length) return [...lines.slice(0, 3), this.theme.fg("dim", "...")];
|
|
205
|
+
}
|
|
206
|
+
return lines;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private blocks(content: unknown, width: number): string[] {
|
|
210
|
+
if (typeof content === "string") return this.wrap(content, width);
|
|
211
|
+
if (!Array.isArray(content)) return this.wrap(json(content), width);
|
|
212
|
+
return content.flatMap((value) => {
|
|
213
|
+
const block = object(value);
|
|
214
|
+
if (!block) return this.wrap(json(value), width);
|
|
215
|
+
if (block.type === "text") return this.wrap(String(block.text ?? ""), width);
|
|
216
|
+
if (block.type === "image") return ["[Image — text-only observer]"];
|
|
217
|
+
if (block.type === "thinking")
|
|
218
|
+
return this.viewport.showThinking
|
|
219
|
+
? this.wrap(String(block.thinking ?? "[redacted thinking]"), width).map((line) =>
|
|
220
|
+
this.theme.fg("muted", line),
|
|
221
|
+
)
|
|
222
|
+
: [this.theme.fg("dim", "[Thinking hidden · t show]")];
|
|
223
|
+
if (block.type === "toolCall")
|
|
224
|
+
return [
|
|
225
|
+
this.theme.fg(
|
|
226
|
+
"accent",
|
|
227
|
+
dialogText(`Tool call: ${String(block.name)} (${String(block.id)})`),
|
|
228
|
+
),
|
|
229
|
+
...this.preview(json(block.arguments), width),
|
|
230
|
+
];
|
|
231
|
+
return this.preview(json(block), width);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private message(message: AgentMessage, width: number): string[] {
|
|
236
|
+
const cached = this.cache.get(message);
|
|
237
|
+
if (cached && cached.width === width && cached.thinking === !!this.viewport.showThinking)
|
|
238
|
+
return cached.lines;
|
|
239
|
+
const data = message as unknown as Record<string, unknown>;
|
|
240
|
+
const label =
|
|
241
|
+
message.role === "toolResult"
|
|
242
|
+
? `Tool result: ${String(data.toolName)}${data.isError ? " — error" : ""}`
|
|
243
|
+
: message.role;
|
|
244
|
+
const collapsed = !["user", "assistant", "custom"].includes(message.role);
|
|
245
|
+
const content = data.content ?? data.summary ?? data.output ?? data;
|
|
246
|
+
const lines = [
|
|
247
|
+
this.theme.fg(data.isError ? "error" : "accent", dialogText(label)),
|
|
248
|
+
...(collapsed ? this.preview(content, width) : this.blocks(content, width)),
|
|
249
|
+
...(data.errorMessage
|
|
250
|
+
? (collapsed
|
|
251
|
+
? this.preview(String(data.errorMessage), width)
|
|
252
|
+
: this.wrap(String(data.errorMessage), width)
|
|
253
|
+
).map((line) => this.theme.fg("error", line))
|
|
254
|
+
: []),
|
|
255
|
+
"",
|
|
256
|
+
];
|
|
257
|
+
this.cache.set(message, { width, thinking: !!this.viewport.showThinking, lines });
|
|
258
|
+
return lines;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
render(width: number): string[] {
|
|
262
|
+
const height = Math.max(1, this.host.terminal?.rows ?? 24);
|
|
263
|
+
const columns = Math.max(1, width);
|
|
264
|
+
const snapshot = this.snapshot;
|
|
265
|
+
const thread = snapshot?.thread;
|
|
266
|
+
const header = this.theme.fg(
|
|
267
|
+
"accent",
|
|
268
|
+
dialogText(
|
|
269
|
+
`${this.path} · ${thread?.type ?? "agent"} · ${thread?.state ?? "attaching"} — Watching — main continues`,
|
|
270
|
+
),
|
|
271
|
+
);
|
|
272
|
+
const body: string[] = [];
|
|
273
|
+
if (this.error)
|
|
274
|
+
body.push(
|
|
275
|
+
this.theme.fg("error", dialogText(`Attachment error: ${this.error}`)),
|
|
276
|
+
"r Retry · Esc Back · Ctrl+Q Back to main",
|
|
277
|
+
);
|
|
278
|
+
if (!snapshot) {
|
|
279
|
+
if (!this.error) body.push("Attaching to retained live session…");
|
|
280
|
+
} else {
|
|
281
|
+
if (snapshot.inheritedCount)
|
|
282
|
+
body.push(
|
|
283
|
+
this.theme.fg(
|
|
284
|
+
"dim",
|
|
285
|
+
`${snapshot.inheritedCount} inherited messages ${this.viewport.showInherited ? "shown" : "collapsed"} · c toggle`,
|
|
286
|
+
),
|
|
287
|
+
);
|
|
288
|
+
const start = this.viewport.showInherited ? 0 : snapshot.inheritedCount;
|
|
289
|
+
for (const message of snapshot.messages.slice(start))
|
|
290
|
+
body.push(...this.message(message, columns));
|
|
291
|
+
if (snapshot.assistant)
|
|
292
|
+
body.push(
|
|
293
|
+
this.theme.fg("warning", "Assistant streaming…"),
|
|
294
|
+
...this.message(snapshot.assistant, columns),
|
|
295
|
+
);
|
|
296
|
+
const committedResults = new Set(
|
|
297
|
+
snapshot.messages
|
|
298
|
+
.filter((message) => message.role === "toolResult")
|
|
299
|
+
.map((message) => (message.role === "toolResult" ? message.toolCallId : "")),
|
|
300
|
+
);
|
|
301
|
+
for (const tool of snapshot.tools) {
|
|
302
|
+
if (committedResults.has(tool.toolCallId)) continue;
|
|
303
|
+
body.push(
|
|
304
|
+
this.theme.fg(
|
|
305
|
+
tool.isError ? "error" : "warning",
|
|
306
|
+
dialogText(
|
|
307
|
+
`Tool ${tool.toolName} — ${tool.state}${tool.isError ? " (error)" : ""}${tool.parentToolCallId ? " (nested)" : ""}`,
|
|
308
|
+
),
|
|
309
|
+
),
|
|
310
|
+
...this.preview(json(tool.args), columns),
|
|
311
|
+
);
|
|
312
|
+
if (tool.result !== undefined)
|
|
313
|
+
body.push(...this.preview(object(tool.result)?.content ?? tool.result, columns));
|
|
314
|
+
body.push("");
|
|
315
|
+
}
|
|
316
|
+
if (!body.length)
|
|
317
|
+
body.push(
|
|
318
|
+
thread?.state === "starting"
|
|
319
|
+
? "Starting — waiting for transcript attachment…"
|
|
320
|
+
: "No retained messages yet.",
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
this.content = body;
|
|
324
|
+
const bodyHeight = Math.max(0, height - 3);
|
|
325
|
+
this.scroll.updateLayout(body.length, bodyHeight, () => this.scheduleRender());
|
|
326
|
+
if (this.restoreViewport) {
|
|
327
|
+
if (this.viewport.follow) this.scroll.scrollToEnd();
|
|
328
|
+
else this.scroll.scrollTo(this.viewport.scrollTop, { disableFollow: true });
|
|
329
|
+
this.restoreViewport = false;
|
|
330
|
+
}
|
|
331
|
+
const visible = this.scroll
|
|
332
|
+
.render(columns)
|
|
333
|
+
.slice(this.scroll.scrollTop, this.scroll.scrollTop + bodyHeight);
|
|
334
|
+
while (visible.length < bodyHeight) visible.push("");
|
|
335
|
+
this.saveViewport();
|
|
336
|
+
const footer = this.error
|
|
337
|
+
? "r Retry · Esc Back · Ctrl+Q Back to main"
|
|
338
|
+
: `Esc tree · Ctrl+Q Back to main · ↑↓/PgUp/PgDn scroll · End latest · c context · t thinking · ${this.viewport.follow ? "following" : "scrolled"}`;
|
|
339
|
+
const lines =
|
|
340
|
+
height === 1
|
|
341
|
+
? [header]
|
|
342
|
+
: height === 2
|
|
343
|
+
? [header, this.theme.fg("dim", footer)]
|
|
344
|
+
: [
|
|
345
|
+
header,
|
|
346
|
+
this.theme.fg(
|
|
347
|
+
this.error ? "error" : "muted",
|
|
348
|
+
dialogText(
|
|
349
|
+
this.error
|
|
350
|
+
? `Attachment error: ${this.error}`
|
|
351
|
+
: thread
|
|
352
|
+
? `${thread.task} · ${thread.status}`
|
|
353
|
+
: "Read-only observer",
|
|
354
|
+
),
|
|
355
|
+
),
|
|
356
|
+
...visible,
|
|
357
|
+
this.theme.fg("dim", footer),
|
|
358
|
+
];
|
|
359
|
+
return fillViewport(lines, width, height);
|
|
360
|
+
}
|
|
361
|
+
}
|