pi-session-subagents 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +216 -2
- package/package.json +61 -5
- package/src/copy.ts +79 -0
- package/src/index.ts +63 -0
- package/src/model-resolver.ts +43 -0
- package/src/report.ts +143 -0
- package/src/roster.ts +198 -0
- package/src/text.ts +77 -0
- package/src/tools.ts +361 -0
- package/src/ui/conversation-viewer.ts +408 -0
- package/src/ui/widget.ts +119 -0
- package/src/worker-session.ts +146 -0
- package/src/worker.ts +242 -0
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { AssistantMessage, ToolResultMessage } from "@earendil-works/pi-ai";
|
|
3
|
+
import {
|
|
4
|
+
AssistantMessageComponent,
|
|
5
|
+
BranchSummaryMessageComponent,
|
|
6
|
+
CompactionSummaryMessageComponent,
|
|
7
|
+
CustomMessageComponent,
|
|
8
|
+
type ExtensionContext,
|
|
9
|
+
getMarkdownTheme,
|
|
10
|
+
type KeybindingsManager,
|
|
11
|
+
sessionEntryToContextMessages,
|
|
12
|
+
type Theme,
|
|
13
|
+
ToolExecutionComponent,
|
|
14
|
+
UserMessageComponent,
|
|
15
|
+
} from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import {
|
|
17
|
+
type Component,
|
|
18
|
+
Container,
|
|
19
|
+
matchesKey,
|
|
20
|
+
Text,
|
|
21
|
+
TruncatedText,
|
|
22
|
+
type TUI,
|
|
23
|
+
type TuiMouseEvent,
|
|
24
|
+
type TuiMouseEventResult,
|
|
25
|
+
truncateToWidth,
|
|
26
|
+
} from "@earendil-works/pi-tui";
|
|
27
|
+
import { clip, formatDuration, formatTokens, shortModelLabel } from "../text";
|
|
28
|
+
import type { Worker } from "../worker";
|
|
29
|
+
|
|
30
|
+
type ToolView = { component: ToolExecutionComponent; result?: unknown; durationMs?: number };
|
|
31
|
+
|
|
32
|
+
const VIEWPORT_TOP = 4;
|
|
33
|
+
const VIEWPORT_LEFT = 2;
|
|
34
|
+
const VIEWPORT_BOTTOM = 3;
|
|
35
|
+
|
|
36
|
+
export async function openInspector(ctx: ExtensionContext, workers: Worker[], name?: string): Promise<void> {
|
|
37
|
+
if (ctx.mode !== "tui") {
|
|
38
|
+
if (ctx.hasUI)
|
|
39
|
+
ctx.ui.notify("The subagent inspector needs the interactive TUI. Use inspect_subagent instead.", "warning");
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
let worker = name?.trim() ? workers.find((candidate) => candidate.name === name.trim()) : undefined;
|
|
43
|
+
if (name?.trim() && !worker) {
|
|
44
|
+
ctx.ui.notify(`Unknown subagent: ${name}`, "error");
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (!worker) {
|
|
48
|
+
if (workers.length === 0) {
|
|
49
|
+
ctx.ui.notify("No subagents", "info");
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const options = workers.map(
|
|
53
|
+
(candidate) => `${candidate.name} [${candidate.status}] — ${clip(candidate.task || "(idle)", 70)}`,
|
|
54
|
+
);
|
|
55
|
+
const choice = await ctx.ui.select("Inspect Subagent", options);
|
|
56
|
+
worker = choice ? workers[options.indexOf(choice)] : undefined;
|
|
57
|
+
if (!worker) return;
|
|
58
|
+
}
|
|
59
|
+
const selected = worker;
|
|
60
|
+
await ctx.ui.custom<void>(
|
|
61
|
+
(tui, theme, keybindings, done) => new ConversationViewer(tui, selected, theme, keybindings, () => done()),
|
|
62
|
+
{ overlay: true, overlayOptions: { anchor: "center", width: "90%", margin: 1 } },
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
class ConversationViewer implements Component {
|
|
67
|
+
private readonly history = new Container();
|
|
68
|
+
private readonly rows = new Map<string, Component>();
|
|
69
|
+
private readonly tools = new Map<string, ToolView>();
|
|
70
|
+
private readonly unsubscribe: () => void;
|
|
71
|
+
private leafId: string | null | undefined;
|
|
72
|
+
private streaming: AssistantMessageComponent | undefined;
|
|
73
|
+
private scrollOffset = 0;
|
|
74
|
+
private autoScroll = true;
|
|
75
|
+
private contentHeight = 0;
|
|
76
|
+
private historyHeight = 0;
|
|
77
|
+
private viewportHeight = 1;
|
|
78
|
+
private contentWidth = 0;
|
|
79
|
+
private expanded = false;
|
|
80
|
+
private hideThinking: boolean;
|
|
81
|
+
private disposed = false;
|
|
82
|
+
|
|
83
|
+
constructor(
|
|
84
|
+
private readonly tui: TUI,
|
|
85
|
+
private readonly worker: Worker,
|
|
86
|
+
private readonly theme: Theme,
|
|
87
|
+
private readonly keybindings: KeybindingsManager,
|
|
88
|
+
private readonly done: () => void,
|
|
89
|
+
) {
|
|
90
|
+
this.hideThinking = worker.session.settingsManager.getHideThinkingBlock();
|
|
91
|
+
const partial = worker.session.state.streamingMessage;
|
|
92
|
+
if (partial?.role === "assistant") this.updateStreaming(partial);
|
|
93
|
+
this.unsubscribe = worker.session.subscribe((event) => {
|
|
94
|
+
if (this.disposed) return;
|
|
95
|
+
switch (event.type) {
|
|
96
|
+
case "message_update":
|
|
97
|
+
if (event.message.role === "assistant") this.updateStreaming(event.message);
|
|
98
|
+
break;
|
|
99
|
+
case "message_end":
|
|
100
|
+
if (event.message.role === "assistant") this.streaming = undefined;
|
|
101
|
+
break;
|
|
102
|
+
case "tool_execution_start":
|
|
103
|
+
this.tool(event.toolName, event.toolCallId, event.args).component.markExecutionStarted();
|
|
104
|
+
break;
|
|
105
|
+
case "tool_execution_update":
|
|
106
|
+
this.tool(event.toolName, event.toolCallId, event.args).component.updateResult(
|
|
107
|
+
{ ...event.partialResult, isError: false },
|
|
108
|
+
true,
|
|
109
|
+
);
|
|
110
|
+
break;
|
|
111
|
+
case "tool_execution_end": {
|
|
112
|
+
const tool = this.tools.get(event.toolCallId);
|
|
113
|
+
if (tool) {
|
|
114
|
+
tool.durationMs = event.durationMs;
|
|
115
|
+
tool.component.updateResult({
|
|
116
|
+
...event.result,
|
|
117
|
+
isError: event.isError,
|
|
118
|
+
durationMs: event.durationMs,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
this.tui.requestRender();
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
handleInput(data: string): void {
|
|
129
|
+
if (matchesKey(data, "escape") || matchesKey(data, "q") || this.keybindings.matches(data, "tui.select.cancel")) {
|
|
130
|
+
this.done();
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (matchesKey(data, "t") || this.keybindings.matches(data, "app.tools.expand")) {
|
|
134
|
+
this.expanded = !this.expanded;
|
|
135
|
+
for (const tool of this.tools.values()) tool.component.setExpanded(this.expanded);
|
|
136
|
+
for (const row of this.rows.values()) {
|
|
137
|
+
if (
|
|
138
|
+
row instanceof CustomMessageComponent ||
|
|
139
|
+
row instanceof CompactionSummaryMessageComponent ||
|
|
140
|
+
row instanceof BranchSummaryMessageComponent
|
|
141
|
+
) {
|
|
142
|
+
row.setExpanded(this.expanded);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
} else if (this.keybindings.matches(data, "app.thinking.toggle")) {
|
|
146
|
+
this.hideThinking = !this.hideThinking;
|
|
147
|
+
for (const row of this.rows.values()) {
|
|
148
|
+
if (row instanceof AssistantMessageComponent) row.setHideThinkingBlock(this.hideThinking);
|
|
149
|
+
}
|
|
150
|
+
this.streaming?.setHideThinkingBlock(this.hideThinking);
|
|
151
|
+
} else if (matchesKey(data, "up") || matchesKey(data, "k") || this.keybindings.matches(data, "tui.select.up")) {
|
|
152
|
+
this.scrollBy(-1);
|
|
153
|
+
} else if (
|
|
154
|
+
matchesKey(data, "down") ||
|
|
155
|
+
matchesKey(data, "j") ||
|
|
156
|
+
this.keybindings.matches(data, "tui.select.down")
|
|
157
|
+
) {
|
|
158
|
+
this.scrollBy(1);
|
|
159
|
+
} else if (matchesKey(data, "pageUp") || this.keybindings.matches(data, "tui.altScreen.pageUp")) {
|
|
160
|
+
this.scrollBy(-this.viewportHeight);
|
|
161
|
+
} else if (matchesKey(data, "pageDown") || this.keybindings.matches(data, "tui.altScreen.pageDown")) {
|
|
162
|
+
this.scrollBy(this.viewportHeight);
|
|
163
|
+
} else if (matchesKey(data, "home") || this.keybindings.matches(data, "tui.altScreen.top")) {
|
|
164
|
+
this.scrollOffset = 0;
|
|
165
|
+
this.autoScroll = false;
|
|
166
|
+
} else if (matchesKey(data, "end") || this.keybindings.matches(data, "tui.altScreen.bottom")) {
|
|
167
|
+
this.autoScroll = true;
|
|
168
|
+
} else {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
this.tui.requestRender();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
175
|
+
if (event.type === "wheel") {
|
|
176
|
+
this.scrollBy(event.wheelDelta || 0);
|
|
177
|
+
this.tui.requestRender();
|
|
178
|
+
return { handled: true };
|
|
179
|
+
}
|
|
180
|
+
if (event.y < VIEWPORT_TOP || event.y >= VIEWPORT_TOP + this.viewportHeight) return undefined;
|
|
181
|
+
const x = event.x - VIEWPORT_LEFT;
|
|
182
|
+
const y = event.y - VIEWPORT_TOP + this.scrollOffset;
|
|
183
|
+
const result =
|
|
184
|
+
y < this.historyHeight
|
|
185
|
+
? this.history.handleMouse({ ...event, x, y, width: this.contentWidth, height: this.historyHeight })
|
|
186
|
+
: this.streaming?.handleMouse({
|
|
187
|
+
...event,
|
|
188
|
+
x,
|
|
189
|
+
y: y - this.historyHeight,
|
|
190
|
+
width: this.contentWidth,
|
|
191
|
+
height: this.contentHeight - this.historyHeight,
|
|
192
|
+
});
|
|
193
|
+
if (!result) return undefined;
|
|
194
|
+
this.tui.requestRender();
|
|
195
|
+
return { handled: true };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
render(width: number): string[] {
|
|
199
|
+
if (width < 20) return new TruncatedText("Widen terminal. Esc closes.", 0, 0).render(width);
|
|
200
|
+
this.syncHistory();
|
|
201
|
+
const inner = width - 2 * VIEWPORT_LEFT;
|
|
202
|
+
this.contentWidth = inner;
|
|
203
|
+
const height = Math.max(1, this.tui.terminal.rows - 2);
|
|
204
|
+
this.viewportHeight = Math.max(0, height - VIEWPORT_TOP - VIEWPORT_BOTTOM);
|
|
205
|
+
const content = this.history.render(inner);
|
|
206
|
+
this.historyHeight = content.length;
|
|
207
|
+
if (this.streaming) content.push(...this.streaming.render(inner));
|
|
208
|
+
if (content.length === 0) content.push(...new Text("(waiting for transcript...)", 0, 0).render(inner));
|
|
209
|
+
this.contentHeight = content.length;
|
|
210
|
+
const maxScroll = Math.max(0, this.contentHeight - this.viewportHeight);
|
|
211
|
+
this.scrollOffset = this.autoScroll ? maxScroll : Math.min(this.scrollOffset, maxScroll);
|
|
212
|
+
const run = this.worker.stats();
|
|
213
|
+
const stats = [
|
|
214
|
+
shortModelLabel(this.worker.info.modelLabel),
|
|
215
|
+
this.worker.status,
|
|
216
|
+
`⟳${run.turns}`,
|
|
217
|
+
`${run.toolUses} tools`,
|
|
218
|
+
formatTokens(run.tokens),
|
|
219
|
+
formatDuration(run.durationMs),
|
|
220
|
+
].join(" · ");
|
|
221
|
+
const border = (text: string) => this.theme.fg("borderAccent", text);
|
|
222
|
+
const rule = (left: string, right: string) => border(`${left}${"─".repeat(width - 2)}${right}`);
|
|
223
|
+
const row = (line: string) => `${border("│")} ${truncateToWidth(line, inner, "…", true)} ${border("│")}`;
|
|
224
|
+
return [
|
|
225
|
+
rule("╭", "╮"),
|
|
226
|
+
row(this.theme.bold(this.worker.name) + this.theme.fg("muted", ` · ${stats}`)),
|
|
227
|
+
row(this.theme.fg("muted", `Task: ${(this.worker.task || "(idle)").replace(/\s+/g, " ")}`)),
|
|
228
|
+
rule("├", "┤"),
|
|
229
|
+
...Array.from({ length: this.viewportHeight }, (_, i) => row(content[this.scrollOffset + i] || "")),
|
|
230
|
+
rule("├", "┤"),
|
|
231
|
+
row(
|
|
232
|
+
this.theme.fg(
|
|
233
|
+
"dim",
|
|
234
|
+
`Esc close · ↑↓/PgUp/PgDn scroll · t tools · ${this.autoScroll ? "live" : "End follows"}`,
|
|
235
|
+
),
|
|
236
|
+
),
|
|
237
|
+
rule("╰", "╯"),
|
|
238
|
+
].slice(0, height);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
invalidate(): void {
|
|
242
|
+
this.history.invalidate();
|
|
243
|
+
this.streaming?.invalidate();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
dispose(): void {
|
|
247
|
+
if (this.disposed) return;
|
|
248
|
+
this.disposed = true;
|
|
249
|
+
this.unsubscribe();
|
|
250
|
+
this.history.clear();
|
|
251
|
+
this.rows.clear();
|
|
252
|
+
this.tools.clear();
|
|
253
|
+
this.streaming = undefined;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private scrollBy(delta: number): void {
|
|
257
|
+
const maxScroll = Math.max(0, this.contentHeight - this.viewportHeight);
|
|
258
|
+
this.scrollOffset = Math.max(0, Math.min(maxScroll, this.scrollOffset + delta));
|
|
259
|
+
this.autoScroll = delta > 0 && this.scrollOffset === maxScroll;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private updateStreaming(message: AssistantMessage): void {
|
|
263
|
+
this.streaming ||= new AssistantMessageComponent(
|
|
264
|
+
undefined,
|
|
265
|
+
this.hideThinking,
|
|
266
|
+
getMarkdownTheme(),
|
|
267
|
+
undefined,
|
|
268
|
+
0,
|
|
269
|
+
this.worker.session.extensionRunner.getMarkdownTransformers(),
|
|
270
|
+
);
|
|
271
|
+
this.streaming.updateContent(message, true);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private tool(name: string, id: string, args: unknown): ToolView {
|
|
275
|
+
let tool = this.tools.get(id);
|
|
276
|
+
if (!tool) {
|
|
277
|
+
const session = this.worker.session;
|
|
278
|
+
const renderers = session.extensionRunner.resolveToolRenderers(name, () => session.getToolDefinition(name));
|
|
279
|
+
const component = new ToolExecutionComponent(
|
|
280
|
+
name,
|
|
281
|
+
id,
|
|
282
|
+
args,
|
|
283
|
+
{ showImages: false, outputPad: 0 },
|
|
284
|
+
renderers,
|
|
285
|
+
this.tui,
|
|
286
|
+
this.worker.info.cwd,
|
|
287
|
+
);
|
|
288
|
+
component.setArgsComplete();
|
|
289
|
+
component.setExpanded(this.expanded);
|
|
290
|
+
if (session.state.pendingToolCalls.has(id)) component.markExecutionStarted();
|
|
291
|
+
tool = { component };
|
|
292
|
+
this.tools.set(id, tool);
|
|
293
|
+
}
|
|
294
|
+
return tool;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
private syncHistory(): void {
|
|
298
|
+
const session = this.worker.session;
|
|
299
|
+
const leafId = session.sessionManager.getLeafId();
|
|
300
|
+
if (leafId === this.leafId) return;
|
|
301
|
+
this.leafId = leafId;
|
|
302
|
+
this.history.clear();
|
|
303
|
+
for (const entry of session.sessionManager.getBranch()) {
|
|
304
|
+
for (const [index, message] of sessionEntryToContextMessages(entry).entries()) {
|
|
305
|
+
if (message.role === "toolResult") {
|
|
306
|
+
this.showResult(message);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
const key = `${entry.id}:${index}`;
|
|
310
|
+
let component = this.rows.get(key);
|
|
311
|
+
if (!component) {
|
|
312
|
+
component = this.messageComponent(message, entry.id, entry.timestamp);
|
|
313
|
+
if (component) this.rows.set(key, component);
|
|
314
|
+
}
|
|
315
|
+
if (component) this.history.addChild(component);
|
|
316
|
+
if (message.role !== "assistant") continue;
|
|
317
|
+
for (const part of message.content) {
|
|
318
|
+
if (part.type !== "toolCall") continue;
|
|
319
|
+
const tool = this.tool(part.name, part.id, part.arguments);
|
|
320
|
+
this.history.addChild(tool.component);
|
|
321
|
+
if (!tool.result && (message.stopReason === "error" || message.stopReason === "aborted")) {
|
|
322
|
+
tool.result = message;
|
|
323
|
+
tool.component.updateResult({
|
|
324
|
+
content: [{ type: "text", text: message.errorMessage || message.stopReason }],
|
|
325
|
+
isError: true,
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private showResult(message: ToolResultMessage): void {
|
|
334
|
+
const tool = this.tool(message.toolName, message.toolCallId, {});
|
|
335
|
+
if (tool.result === message) return;
|
|
336
|
+
tool.result = message;
|
|
337
|
+
tool.component.markExecutionStarted();
|
|
338
|
+
tool.component.updateResult({ ...message, durationMs: tool.durationMs });
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
private messageComponent(message: AgentMessage, id: string, timestamp: string): Component | undefined {
|
|
342
|
+
const transformers = this.worker.session.extensionRunner.getMarkdownTransformers();
|
|
343
|
+
switch (message.role) {
|
|
344
|
+
case "assistant":
|
|
345
|
+
return new AssistantMessageComponent(
|
|
346
|
+
message,
|
|
347
|
+
this.hideThinking,
|
|
348
|
+
getMarkdownTheme(),
|
|
349
|
+
undefined,
|
|
350
|
+
0,
|
|
351
|
+
transformers,
|
|
352
|
+
id,
|
|
353
|
+
timestamp,
|
|
354
|
+
);
|
|
355
|
+
case "user":
|
|
356
|
+
return new UserMessageComponent(
|
|
357
|
+
typeof message.content === "string"
|
|
358
|
+
? message.content
|
|
359
|
+
: message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n"),
|
|
360
|
+
getMarkdownTheme(),
|
|
361
|
+
0,
|
|
362
|
+
transformers,
|
|
363
|
+
id,
|
|
364
|
+
timestamp,
|
|
365
|
+
);
|
|
366
|
+
case "custom": {
|
|
367
|
+
if (!message.display) return undefined;
|
|
368
|
+
const component = new CustomMessageComponent(
|
|
369
|
+
message,
|
|
370
|
+
this.worker.session.extensionRunner.getMessageRenderer(message.customType),
|
|
371
|
+
getMarkdownTheme(),
|
|
372
|
+
0,
|
|
373
|
+
transformers,
|
|
374
|
+
id,
|
|
375
|
+
timestamp,
|
|
376
|
+
);
|
|
377
|
+
component.setExpanded(this.expanded);
|
|
378
|
+
return component;
|
|
379
|
+
}
|
|
380
|
+
case "compactionSummary": {
|
|
381
|
+
const component = new CompactionSummaryMessageComponent(
|
|
382
|
+
message,
|
|
383
|
+
getMarkdownTheme(),
|
|
384
|
+
0,
|
|
385
|
+
transformers,
|
|
386
|
+
id,
|
|
387
|
+
timestamp,
|
|
388
|
+
);
|
|
389
|
+
component.setExpanded(this.expanded);
|
|
390
|
+
return component;
|
|
391
|
+
}
|
|
392
|
+
case "branchSummary": {
|
|
393
|
+
const component = new BranchSummaryMessageComponent(
|
|
394
|
+
message,
|
|
395
|
+
getMarkdownTheme(),
|
|
396
|
+
0,
|
|
397
|
+
transformers,
|
|
398
|
+
id,
|
|
399
|
+
timestamp,
|
|
400
|
+
);
|
|
401
|
+
component.setExpanded(this.expanded);
|
|
402
|
+
return component;
|
|
403
|
+
}
|
|
404
|
+
default:
|
|
405
|
+
return undefined;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
package/src/ui/widget.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type TUI, type TuiMouseEvent, type TuiMouseEventResult, truncateToWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
import { clip, shortModelLabel } from "../text";
|
|
4
|
+
import type { Worker } from "../worker";
|
|
5
|
+
|
|
6
|
+
const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
7
|
+
const MAX_WIDGET_LINES = 12;
|
|
8
|
+
const WIDGET_KEY = "subagents";
|
|
9
|
+
|
|
10
|
+
export class SubagentWidget {
|
|
11
|
+
private ctx: ExtensionContext | undefined;
|
|
12
|
+
private tui: TUI | undefined;
|
|
13
|
+
private registered = false;
|
|
14
|
+
private frame = 0;
|
|
15
|
+
private interval: ReturnType<typeof setInterval> | undefined;
|
|
16
|
+
private rowWorkers: (string | undefined)[] = [];
|
|
17
|
+
|
|
18
|
+
constructor(
|
|
19
|
+
private readonly getWorkers: () => Worker[],
|
|
20
|
+
private readonly onSelect: (name: string) => void,
|
|
21
|
+
) {}
|
|
22
|
+
|
|
23
|
+
attach(ctx: ExtensionContext): void {
|
|
24
|
+
this.dispose();
|
|
25
|
+
this.ctx = ctx;
|
|
26
|
+
this.refresh();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
refresh(): void {
|
|
30
|
+
const ctx = this.ctx;
|
|
31
|
+
if (ctx?.mode !== "tui") return;
|
|
32
|
+
const workers = this.getWorkers();
|
|
33
|
+
if (workers.some((worker) => worker.status === "running")) {
|
|
34
|
+
this.interval ??= setInterval(() => {
|
|
35
|
+
this.frame++;
|
|
36
|
+
this.tui?.requestRender();
|
|
37
|
+
}, 90);
|
|
38
|
+
} else {
|
|
39
|
+
this.stopTimer();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (workers.length === 0) {
|
|
43
|
+
if (this.registered) ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
44
|
+
this.registered = false;
|
|
45
|
+
} else if (!this.registered) {
|
|
46
|
+
ctx.ui.setWidget(WIDGET_KEY, (tui, theme) => {
|
|
47
|
+
this.tui = tui;
|
|
48
|
+
return {
|
|
49
|
+
render: (width: number) => this.render(width, theme),
|
|
50
|
+
handleMouse: (event: TuiMouseEvent) => this.handleMouse(event),
|
|
51
|
+
invalidate: () => {},
|
|
52
|
+
};
|
|
53
|
+
});
|
|
54
|
+
this.registered = true;
|
|
55
|
+
} else {
|
|
56
|
+
this.tui?.requestRender();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
dispose(): void {
|
|
61
|
+
this.stopTimer();
|
|
62
|
+
if (this.registered && this.ctx?.mode === "tui") this.ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
63
|
+
this.registered = false;
|
|
64
|
+
this.tui = undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private stopTimer(): void {
|
|
68
|
+
clearInterval(this.interval);
|
|
69
|
+
this.interval = undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
73
|
+
if (event.button !== "left" || (event.type !== "press" && event.type !== "click")) return undefined;
|
|
74
|
+
const name = this.rowWorkers[event.y];
|
|
75
|
+
if (!name) return undefined;
|
|
76
|
+
if (event.type === "click") this.onSelect(name);
|
|
77
|
+
// Claiming the press is what makes Pi send the matching click.
|
|
78
|
+
return { handled: true };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private render(width: number, theme: Theme): string[] {
|
|
82
|
+
const workers = this.getWorkers();
|
|
83
|
+
const truncate = (text: string) => truncateToWidth(text, width);
|
|
84
|
+
const running = workers.some((worker) => worker.status === "running");
|
|
85
|
+
const hint = this.tui?.mode === "fullscreen" ? theme.fg("dim", " · click to inspect") : "";
|
|
86
|
+
const rows: { line: string; name: string }[] = [];
|
|
87
|
+
for (const worker of workers) {
|
|
88
|
+
const label = `${theme.bold(worker.name)} ${theme.fg("muted", `· ${shortModelLabel(worker.info.modelLabel)}`)}`;
|
|
89
|
+
if (worker.status === "running") {
|
|
90
|
+
rows.push({
|
|
91
|
+
line: `${theme.fg("dim", "├─")} ${theme.fg("accent", SPINNER[this.frame % SPINNER.length])} ${label}`,
|
|
92
|
+
name: worker.name,
|
|
93
|
+
});
|
|
94
|
+
rows.push({
|
|
95
|
+
line: `${theme.fg("dim", "│ ")} ${theme.fg("dim", "⎿")} ${theme.fg("muted", worker.activity())}`,
|
|
96
|
+
name: worker.name,
|
|
97
|
+
});
|
|
98
|
+
} else {
|
|
99
|
+
const icon =
|
|
100
|
+
worker.status === "done"
|
|
101
|
+
? theme.fg("success", "✓")
|
|
102
|
+
: worker.status === "error"
|
|
103
|
+
? theme.fg("error", "✗")
|
|
104
|
+
: theme.fg("dim", "○");
|
|
105
|
+
const error = worker.status === "error" ? theme.fg("error", ` · ${clip(worker.error, 50)}`) : "";
|
|
106
|
+
rows.push({ line: `${theme.fg("dim", "├─")} ${icon} ${label}${error}`, name: worker.name });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const shown = rows.length > MAX_WIDGET_LINES - 1 ? rows.slice(0, MAX_WIDGET_LINES - 2) : rows;
|
|
110
|
+
this.rowWorkers = [undefined, ...shown.map((row) => row.name)];
|
|
111
|
+
return [
|
|
112
|
+
truncate(`${theme.fg(running ? "accent" : "dim", "●")} ${theme.fg("accent", theme.bold("Subagents"))}${hint}`),
|
|
113
|
+
...shown.map((row) => truncate(row.line)),
|
|
114
|
+
...(shown.length < rows.length
|
|
115
|
+
? [truncate(theme.fg("dim", `└─ ... +${rows.length - shown.length} more`))]
|
|
116
|
+
: []),
|
|
117
|
+
];
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
4
|
+
import {
|
|
5
|
+
type AgentSession,
|
|
6
|
+
createAgentSessionFromServices,
|
|
7
|
+
createAgentSessionServices,
|
|
8
|
+
createCodemodeExtension,
|
|
9
|
+
createMcpExtension,
|
|
10
|
+
createToolSearchExtension,
|
|
11
|
+
type ExtensionContext,
|
|
12
|
+
getAgentDir,
|
|
13
|
+
hasTrustRequiringProjectResources,
|
|
14
|
+
type LoadExtensionsResult,
|
|
15
|
+
type ModelRuntime,
|
|
16
|
+
ProjectTrustStore,
|
|
17
|
+
SessionManager,
|
|
18
|
+
SettingsManager,
|
|
19
|
+
} from "@earendil-works/pi-coding-agent";
|
|
20
|
+
import { isSubagentTool, WORKER_SYSTEM_PROMPT } from "./copy";
|
|
21
|
+
import { resolveModel, type WorkerModel } from "./model-resolver";
|
|
22
|
+
|
|
23
|
+
export interface WorkerSessionOptions {
|
|
24
|
+
cwd: string;
|
|
25
|
+
model?: string;
|
|
26
|
+
thinking: ThinkingLevel;
|
|
27
|
+
tools: string[];
|
|
28
|
+
onExtensionError: (message: string) => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface WorkerSession {
|
|
32
|
+
session: AgentSession;
|
|
33
|
+
modelLabel: string;
|
|
34
|
+
warnings: string[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function resolveWorkerCwd(parentCwd: string, cwd: string | undefined): string {
|
|
38
|
+
const resolved = realpathSync(resolve(parentCwd, cwd || "."));
|
|
39
|
+
if (!statSync(resolved).isDirectory()) throw new Error(`Not a directory: ${resolved}`);
|
|
40
|
+
return resolved;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function createWorkerSession(
|
|
44
|
+
ctx: ExtensionContext,
|
|
45
|
+
options: WorkerSessionOptions,
|
|
46
|
+
): Promise<WorkerSession> {
|
|
47
|
+
const { cwd, tools } = options;
|
|
48
|
+
const agentDir = getAgentDir();
|
|
49
|
+
const projectTrusted =
|
|
50
|
+
cwd === realpathSync(ctx.cwd) ? ctx.isProjectTrusted() : new ProjectTrustStore(agentDir).get(cwd) === true;
|
|
51
|
+
const services = await createAgentSessionServices({
|
|
52
|
+
cwd,
|
|
53
|
+
agentDir,
|
|
54
|
+
settingsManager: SettingsManager.create(cwd, agentDir, { projectTrusted }),
|
|
55
|
+
resourceLoaderOptions: {
|
|
56
|
+
noPromptTemplates: true,
|
|
57
|
+
noThemes: true,
|
|
58
|
+
extensionFactories: cliBuiltinExtensionsNeededBy(tools),
|
|
59
|
+
extensionsOverride: withoutSubagentExtensions,
|
|
60
|
+
appendSystemPrompt: [WORKER_SYSTEM_PROMPT],
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
let created: Awaited<ReturnType<typeof createAgentSessionFromServices>>;
|
|
65
|
+
let model: WorkerModel;
|
|
66
|
+
try {
|
|
67
|
+
model = await pickModel(services.modelRuntime, options.model, ctx);
|
|
68
|
+
created = await createAgentSessionFromServices({
|
|
69
|
+
services,
|
|
70
|
+
sessionManager: SessionManager.create(cwd, join(agentDir, "subagent-sessions"), {
|
|
71
|
+
parentSession: ctx.sessionManager.getSessionFile(),
|
|
72
|
+
}),
|
|
73
|
+
model,
|
|
74
|
+
thinkingLevel: options.thinking,
|
|
75
|
+
tools,
|
|
76
|
+
});
|
|
77
|
+
} catch (error) {
|
|
78
|
+
await services.modelRuntime.settleCredentialWrites();
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const { session, extensionsResult } = created;
|
|
83
|
+
const warnings = [
|
|
84
|
+
...(!projectTrusted && hasTrustRequiringProjectResources(cwd)
|
|
85
|
+
? [`Project resources in ${cwd} were not loaded because the folder is not trusted.`]
|
|
86
|
+
: []),
|
|
87
|
+
...services.diagnostics.map((diagnostic) => diagnostic.message),
|
|
88
|
+
...extensionsResult.errors.map((error) => `Extension ${error.path}: ${error.error}`),
|
|
89
|
+
...(extensionsResult.warnings ?? []).map((warning) => `Extension ${warning.path}: ${warning.warning}`),
|
|
90
|
+
];
|
|
91
|
+
try {
|
|
92
|
+
await session.bindExtensions({
|
|
93
|
+
onError: (error) => {
|
|
94
|
+
const warning = `Extension ${error.extensionPath} (${error.event}): ${error.error}`;
|
|
95
|
+
warnings.push(warning);
|
|
96
|
+
options.onExtensionError(warning);
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
session.setActiveToolsByName(tools);
|
|
100
|
+
return { session, modelLabel: `${model.provider}/${model.id}`, warnings };
|
|
101
|
+
} catch (error) {
|
|
102
|
+
await closeWorkerSession(session);
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function closeWorkerSession(session: AgentSession): Promise<void> {
|
|
108
|
+
try {
|
|
109
|
+
await session.abort();
|
|
110
|
+
// dispose() does not emit session_shutdown, which worker extensions such as MCP need to clean up.
|
|
111
|
+
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
|
|
112
|
+
} finally {
|
|
113
|
+
session.dispose();
|
|
114
|
+
await session.modelRuntime.settleCredentialWrites();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function pickModel(
|
|
119
|
+
modelRuntime: ModelRuntime,
|
|
120
|
+
query: string | undefined,
|
|
121
|
+
ctx: ExtensionContext,
|
|
122
|
+
): Promise<WorkerModel> {
|
|
123
|
+
const parent = ctx.model && modelRuntime.getModel(ctx.model.provider, ctx.model.id);
|
|
124
|
+
if (!query?.trim() && ctx.model && !parent) {
|
|
125
|
+
throw new Error(
|
|
126
|
+
`Model ${ctx.model.provider}/${ctx.model.id} is not registered in the worker's independent runtime. Parent-only provider/model overrides are not inherited.`,
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
return resolveModel(query, await modelRuntime.getAvailable(), parent);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function cliBuiltinExtensionsNeededBy(tools: string[]) {
|
|
133
|
+
const usesMcp = tools.some((name) => name === "codemode" || name === "tool_search" || name.startsWith("mcp__"));
|
|
134
|
+
return [
|
|
135
|
+
...(tools.includes("codemode") ? [createCodemodeExtension()] : []),
|
|
136
|
+
...(tools.includes("tool_search") ? [createToolSearchExtension()] : []),
|
|
137
|
+
...(usesMcp ? [createMcpExtension()] : []),
|
|
138
|
+
];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function withoutSubagentExtensions(base: LoadExtensionsResult): LoadExtensionsResult {
|
|
142
|
+
return {
|
|
143
|
+
...base,
|
|
144
|
+
extensions: base.extensions.filter((extension) => ![...extension.tools.keys()].some(isSubagentTool)),
|
|
145
|
+
};
|
|
146
|
+
}
|