@piotr-oles/pi-subagents 0.1.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.
@@ -0,0 +1,362 @@
1
+ import type { AssistantMessage, ToolCall } from "@earendil-works/pi-ai";
2
+ import { DynamicBorder, getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
3
+ import { type Component, Markdown, Text, truncateToWidth } from "@earendil-works/pi-tui";
4
+ import type { DoneSubagentSessionEntry } from "../../domain/instance/done-subagent.js";
5
+ import type { RunningAgentSessionEntry } from "../../domain/instance/running-subagent.js";
6
+ import type { SubagentSessionEntry } from "../../domain/types.js";
7
+ import { formatDuration, formatFilePath, formatUsage, getFirstLine } from "../../format.js";
8
+ import { InlineContainer } from "./inline-container.js";
9
+
10
+ export class SubagentToolResultComponent implements Component {
11
+ private readonly summary: SubagentSummaryComponent;
12
+ private readonly details: SubagentDetailsComponent;
13
+ private readonly border: DynamicBorder;
14
+ private expanded: boolean;
15
+
16
+ constructor(
17
+ entry: SubagentSessionEntry,
18
+ theme: Theme,
19
+ expanded: boolean,
20
+ onInvalidate: () => void,
21
+ ) {
22
+ this.summary = new SubagentSummaryComponent(entry, theme, onInvalidate);
23
+ this.details = new SubagentDetailsComponent(entry, theme);
24
+ this.expanded = expanded;
25
+ this.border = new DynamicBorder((s) => theme.fg("muted", s));
26
+ }
27
+
28
+ update(
29
+ entry: SubagentSessionEntry,
30
+ theme: Theme,
31
+ expanded: boolean,
32
+ onInvalidate: () => void,
33
+ ): void {
34
+ this.expanded = expanded;
35
+ this.summary.update(entry, theme, onInvalidate);
36
+ this.summary.invalidate();
37
+ if (expanded) {
38
+ this.details.update(entry, theme);
39
+ this.details.invalidate();
40
+ }
41
+ }
42
+
43
+ render(width: number): string[] {
44
+ const { expanded } = this;
45
+ if (expanded) {
46
+ return [
47
+ ...this.border.render(width),
48
+ ...this.summary.render(width),
49
+ ...this.details.render(width),
50
+ ];
51
+ }
52
+ return this.summary.render(width);
53
+ }
54
+
55
+ invalidate() {
56
+ this.summary.invalidate();
57
+ this.details.invalidate();
58
+ }
59
+ }
60
+
61
+ class SubagentSummaryComponent implements Component {
62
+ private readonly container: InlineContainer;
63
+ private readonly icon: SubagentIconComponent;
64
+ private readonly text: SubagentSummaryTextComponent;
65
+
66
+ constructor(entry: SubagentSessionEntry, theme: Theme, onInvalidate: () => void) {
67
+ this.container = new InlineContainer();
68
+ this.icon = new SubagentIconComponent(entry, theme, onInvalidate);
69
+ this.text = new SubagentSummaryTextComponent(entry, theme);
70
+ this.container.addChild(this.icon);
71
+ this.container.addChild(this.text);
72
+ }
73
+
74
+ update(entry: SubagentSessionEntry, theme: Theme, onInvalidate: () => void): void {
75
+ this.icon.update(entry, theme, onInvalidate);
76
+ this.text.update(entry, theme);
77
+ this.container.invalidate();
78
+ }
79
+
80
+ render(width: number): string[] {
81
+ return this.container.render(width);
82
+ }
83
+
84
+ invalidate() {
85
+ this.container.invalidate();
86
+ }
87
+ }
88
+
89
+ class SubagentDetailsComponent implements Component {
90
+ private readonly done: DoneSubagentDetailsComponent;
91
+ private readonly footer: Text;
92
+ private entry: SubagentSessionEntry;
93
+ private theme: Theme;
94
+
95
+ constructor(entry: SubagentSessionEntry, theme: Theme) {
96
+ this.entry = entry;
97
+ this.theme = theme;
98
+ this.done = new DoneSubagentDetailsComponent(entry.status === "done" ? entry : undefined);
99
+ this.footer = new Text(this.footerText());
100
+ }
101
+
102
+ update(entry: SubagentSessionEntry, theme: Theme): void {
103
+ this.entry = entry;
104
+ this.theme = theme;
105
+ switch (entry.status) {
106
+ case "queued":
107
+ case "running":
108
+ break;
109
+ case "done":
110
+ this.done.update(entry);
111
+ this.done.invalidate();
112
+ break;
113
+ }
114
+ this.footer.setText(this.footerText());
115
+ }
116
+
117
+ render(width: number): string[] {
118
+ const { entry } = this;
119
+
120
+ switch (entry.status) {
121
+ case "queued":
122
+ case "running":
123
+ return [...this.footer.render(width)];
124
+ case "done":
125
+ return [...this.done.render(width), "", ...this.footer.render(width)];
126
+ }
127
+ }
128
+
129
+ invalidate() {
130
+ this.done.invalidate();
131
+ }
132
+
133
+ private footerText(): string {
134
+ const { entry, theme } = this;
135
+ if (entry.sessionFile) {
136
+ return `${theme.fg("muted", `To open this session:`)} pi --session ${formatFilePath(entry.sessionFile)}`;
137
+ }
138
+ return "";
139
+ }
140
+ }
141
+
142
+ class DoneSubagentDetailsComponent implements Component {
143
+ private readonly markdown: Markdown;
144
+
145
+ constructor(entry: DoneSubagentSessionEntry | undefined) {
146
+ this.markdown = new Markdown(
147
+ entry?.result.status === "completed" ? entry.result.message : "",
148
+ 0,
149
+ 1,
150
+ getMarkdownTheme(),
151
+ );
152
+ }
153
+
154
+ update(entry: DoneSubagentSessionEntry): void {
155
+ this.markdown.setText(entry.result.status === "completed" ? entry.result.message : "");
156
+ this.markdown.invalidate();
157
+ }
158
+
159
+ render(width: number): string[] {
160
+ return this.markdown.render(width);
161
+ }
162
+
163
+ invalidate() {
164
+ this.markdown.invalidate();
165
+ }
166
+ }
167
+
168
+ class SubagentSummaryTextComponent implements Component {
169
+ private entry: SubagentSessionEntry;
170
+ private theme: Theme;
171
+
172
+ constructor(entry: SubagentSessionEntry, theme: Theme) {
173
+ this.entry = entry;
174
+ this.theme = theme;
175
+ }
176
+
177
+ update(entry: SubagentSessionEntry, theme: Theme) {
178
+ this.entry = entry;
179
+ this.theme = theme;
180
+ }
181
+
182
+ render(width: number): string[] {
183
+ return [truncateToWidth(this.text(), width, "", true)];
184
+ }
185
+
186
+ invalidate() {}
187
+
188
+ private text(): string {
189
+ const { entry } = this;
190
+ switch (entry.status) {
191
+ case "queued":
192
+ return this.queuedText();
193
+ case "running":
194
+ return this.runningText(entry);
195
+ case "done":
196
+ return this.doneText(entry);
197
+ }
198
+ }
199
+
200
+ private queuedText(): string {
201
+ const { theme } = this;
202
+ return theme.fg("dim", "queued");
203
+ }
204
+
205
+ private runningText(running: RunningAgentSessionEntry): string {
206
+ const { theme } = this;
207
+ const parts: string[] = [];
208
+ parts.push(theme.fg("dim", formatUsage(running.usage)));
209
+ if (running.lastMessage) {
210
+ const activity = this.lastActivity(running.lastMessage);
211
+ if (activity) {
212
+ parts.push(activity);
213
+ }
214
+ }
215
+ return parts.join(" · ");
216
+ }
217
+
218
+ private lastActivity(message: AssistantMessage): string | undefined {
219
+ const { theme } = this;
220
+ const tail = message.content.at(-1);
221
+ if (!tail) {
222
+ return undefined;
223
+ }
224
+
225
+ switch (tail.type) {
226
+ case "text":
227
+ return theme.fg("dim", getFirstLine(tail.text).slice(0, 100));
228
+ case "thinking":
229
+ return theme.italic(theme.fg("dim", getFirstLine(tail.thinking).slice(0, 100)));
230
+ case "toolCall": {
231
+ return this.toolActivity(tail);
232
+ }
233
+ }
234
+ }
235
+
236
+ private toolActivity(call: ToolCall): string | undefined {
237
+ const { theme } = this;
238
+ switch (call.name) {
239
+ case "bash":
240
+ return theme.fg("dim", getFirstLine(call.arguments.command || "bash"));
241
+ case "read":
242
+ case "write":
243
+ case "edit":
244
+ return theme.fg(
245
+ "dim",
246
+ call.arguments.path
247
+ ? getFirstLine(`${call.name} ${call.arguments.path}`)
248
+ : getFirstLine(call.name),
249
+ );
250
+ case "subagent":
251
+ return theme.fg(
252
+ "dim",
253
+ call.arguments.name
254
+ ? getFirstLine(
255
+ `${call.name} ${call.arguments.name} ${call.arguments.description ?? ""}`,
256
+ )
257
+ : getFirstLine(call.name),
258
+ );
259
+ default:
260
+ return theme.fg("dim", getFirstLine(call.name));
261
+ }
262
+ }
263
+
264
+ private doneText(done: DoneSubagentSessionEntry): string {
265
+ const { theme } = this;
266
+ const parts: string[] = [];
267
+ if (done.result.status === "error") {
268
+ parts.push(theme.fg("error", done.result.error));
269
+ }
270
+ if (done.result.status === "aborted") {
271
+ parts.push(theme.fg("dim", "cancelled"));
272
+ } else if (done.result.status === "exceeded_limit") {
273
+ parts.push(theme.fg("dim", "exceeded limit"));
274
+ }
275
+ parts.push(theme.fg("dim", formatUsage(done.usage)));
276
+ parts.push(theme.fg("dim", formatDuration(done.duration)));
277
+ return parts.join(" · ");
278
+ }
279
+ }
280
+
281
+ const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
282
+ const SPINNER_INTERVAL_MS = 80;
283
+
284
+ class SubagentIconComponent implements Component {
285
+ private frameIndex = 0;
286
+ private interval: ReturnType<typeof setInterval> | null = null;
287
+ private entry: SubagentSessionEntry;
288
+ private theme: Theme;
289
+ private onInvalidate: () => void;
290
+
291
+ constructor(entry: SubagentSessionEntry, theme: Theme, onInvalidate: () => void) {
292
+ this.entry = entry;
293
+ this.theme = theme;
294
+ this.onInvalidate = onInvalidate;
295
+ this.syncAnimation();
296
+ }
297
+
298
+ update(entry: SubagentSessionEntry, theme: Theme, onInvalidate: () => void) {
299
+ this.entry = entry;
300
+ this.theme = theme;
301
+ this.onInvalidate = onInvalidate;
302
+ this.syncAnimation();
303
+ }
304
+
305
+ render(width: number): string[] {
306
+ return [truncateToWidth(this.icon(), width)];
307
+ }
308
+
309
+ invalidate() {}
310
+
311
+ private syncAnimation(): void {
312
+ if (this.entry.status === "running") {
313
+ this.startAnimation();
314
+ } else {
315
+ this.stopAnimation();
316
+ }
317
+ }
318
+
319
+ private startAnimation(): void {
320
+ if (this.interval) {
321
+ return;
322
+ }
323
+ this.interval = setInterval(() => {
324
+ this.frameIndex++;
325
+ this.onInvalidate();
326
+ }, SPINNER_INTERVAL_MS);
327
+ }
328
+
329
+ private stopAnimation(): void {
330
+ if (this.interval) {
331
+ clearInterval(this.interval);
332
+ this.interval = null;
333
+ }
334
+ }
335
+
336
+ private icon(): string {
337
+ const { theme, entry } = this;
338
+
339
+ switch (entry.status) {
340
+ case "queued":
341
+ return theme.fg("dim", "◌");
342
+ case "running":
343
+ return theme.fg(
344
+ entry.steered ? "warning" : "accent",
345
+ SPINNER_FRAMES[this.frameIndex % SPINNER_FRAMES.length] ?? "⠋",
346
+ );
347
+ case "done": {
348
+ switch (entry.result.status) {
349
+ case "completed":
350
+ return theme.fg(
351
+ entry.result.steered ? "warning" : "success",
352
+ entry.result.steered ? "⚠" : "✓",
353
+ );
354
+ case "aborted":
355
+ return theme.fg("error", "■");
356
+ default:
357
+ return theme.fg("error", "✗");
358
+ }
359
+ }
360
+ }
361
+ }
362
+ }
@@ -0,0 +1,152 @@
1
+ import type { TextContent } from "@earendil-works/pi-ai";
2
+ import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import type { Component } from "@earendil-works/pi-tui";
4
+ import type { DoneSubagent } from "../domain/instance/done-subagent.js";
5
+ import type { SubagentInstancesManager } from "../domain/subagent-instances-manager.js";
6
+ import type { SubagentTemplatesManager } from "../domain/subagent-templates-manager.js";
7
+ import type { SubagentSessionEntry } from "../domain/types.js";
8
+ import { throttle } from "../throttle.js";
9
+ import { SubagentToolCallComponent } from "./components/subagent-tool-call-component.js";
10
+ import { SubagentToolResultComponent } from "./components/subagent-tool-result-component.js";
11
+ import { SubagentToolParams } from "./types.js";
12
+
13
+ export interface SubagentToolDeps {
14
+ pi: ExtensionAPI;
15
+ instanceManager: SubagentInstancesManager;
16
+ templatesManager: SubagentTemplatesManager;
17
+ }
18
+
19
+ export function createSubagentTool(deps: SubagentToolDeps) {
20
+ const { pi, instanceManager, templatesManager } = deps;
21
+
22
+ return defineTool<typeof SubagentToolParams, SubagentSessionEntry>({
23
+ name: "subagent",
24
+ label: "Subagent",
25
+ description: `Spawn a specialized subagent to handle a task autonomously.`,
26
+ promptGuidelines: [
27
+ "Use subagent tool to delegate self-contained tasks that don't require back-and-forth.",
28
+ "If asked to spawn multiple subagents, spawn all of them in the same turn, as they will block next turn until done.",
29
+ "You can follow-up on subagent that finished by calling subagent tool again, but this time with returned id and follow-up prompt.",
30
+ ],
31
+ parameters: SubagentToolParams,
32
+ executionMode: "parallel",
33
+ execute: async (toolCallId, params, signal, onUpdate, ctx) => {
34
+ const availableTools = pi.getActiveTools();
35
+ const resolvedId = params.id ?? instanceManager.id(toolCallId);
36
+ const onUpdateThrottled = onUpdate ? throttle(onUpdate, 500) : undefined;
37
+
38
+ let promise: Promise<DoneSubagent>;
39
+
40
+ if (params.id) {
41
+ promise = instanceManager.followUp({
42
+ id: resolvedId,
43
+ prompt: params.prompt,
44
+ description: params.description,
45
+ signal,
46
+ onUpdate: (instance) => {
47
+ onUpdateThrottled?.({ content: [], details: instance.toEntry() });
48
+ },
49
+ });
50
+ } else {
51
+ promise = instanceManager.spawn({
52
+ id: resolvedId,
53
+ ctx,
54
+ template: templatesManager.getTemplateOrDefault(params.name),
55
+ prompt: params.prompt,
56
+ description: params.description,
57
+ availableTools,
58
+ signal,
59
+ onUpdate: (instance) => {
60
+ onUpdateThrottled?.({ content: [], details: instance.toEntry() });
61
+ },
62
+ });
63
+ }
64
+
65
+ ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("dim", "●")] });
66
+ ctx.ui.setWorkingMessage("Waiting for subagents");
67
+
68
+ const done = await promise;
69
+
70
+ if (!instanceManager.isRunning()) {
71
+ ctx.ui.setWorkingIndicator();
72
+ ctx.ui.setWorkingMessage();
73
+ }
74
+
75
+ return {
76
+ content: buildSubagentResponse(done),
77
+ details: done.toEntry(),
78
+ };
79
+ },
80
+ /** Custom rendering for tool call display */
81
+ renderCall(params, theme, context): Component {
82
+ const resolvedParams = params.id
83
+ ? params
84
+ : { ...params, id: instanceManager.id(context.toolCallId) };
85
+ if (!(context.lastComponent instanceof SubagentToolCallComponent)) {
86
+ return new SubagentToolCallComponent(resolvedParams, theme, context.expanded);
87
+ }
88
+ context.lastComponent.update(resolvedParams, theme, context.expanded);
89
+ return context.lastComponent;
90
+ },
91
+ /** Custom rendering for tool result display */
92
+ renderResult(result, _options, theme, context): Component {
93
+ if (!(context.lastComponent instanceof SubagentToolResultComponent)) {
94
+ return new SubagentToolResultComponent(
95
+ result.details,
96
+ theme,
97
+ context.expanded,
98
+ context.invalidate,
99
+ );
100
+ }
101
+ context.lastComponent.update(result.details, theme, context.expanded, context.invalidate);
102
+ return context.lastComponent;
103
+ },
104
+ });
105
+ }
106
+
107
+ function buildSubagentResponse(done: DoneSubagent): TextContent[] {
108
+ const subagent = `Subagent "${done.config.name}" with id ${done.id}`;
109
+
110
+ switch (done.result.status) {
111
+ case "completed":
112
+ return [
113
+ {
114
+ type: "text",
115
+ text: done.result.steered
116
+ ? `${subagent} completed but had to finish earlier due to imposed limits. Its results might be partial.`
117
+ : `${subagent} completed.`,
118
+ },
119
+ {
120
+ type: "text",
121
+ text: done.result.message || "No result.",
122
+ },
123
+ ];
124
+ case "aborted":
125
+ return [
126
+ {
127
+ type: "text",
128
+ text: `${subagent} cancelled by the user.`,
129
+ },
130
+ ];
131
+ case "error":
132
+ return [
133
+ {
134
+ type: "text",
135
+ text: [`${subagent} failed.`, `Error: ${done.result.error || "unknown"}`].join("\n"),
136
+ },
137
+ ];
138
+ case "exceeded_limit": {
139
+ switch (done.result.limit.type) {
140
+ case "turns":
141
+ return [
142
+ {
143
+ type: "text",
144
+ text: [
145
+ `${subagent} exceeded turns limit and didn't respond after asking to wrap up.`,
146
+ ].join("\n"),
147
+ },
148
+ ];
149
+ }
150
+ }
151
+ }
152
+ }
@@ -0,0 +1,19 @@
1
+ import { type Static, Type } from "typebox";
2
+
3
+ export const SubagentToolParams = Type.Object({
4
+ name: Type.String({
5
+ description: "Name of subagent template to spawn. Required for both spawn and follow-up.",
6
+ }),
7
+ id: Type.Optional(
8
+ Type.String({
9
+ description: "ID of a done subagent to follow-up.",
10
+ }),
11
+ ),
12
+ description: Type.String({
13
+ description: "Short description of the task (shown in UI).",
14
+ }),
15
+ prompt: Type.String({
16
+ description: "Task prompt for subagent.",
17
+ }),
18
+ });
19
+ export type SubagentToolParamsType = Static<typeof SubagentToolParams>;
package/src/xml.ts ADDED
@@ -0,0 +1,12 @@
1
+ export function escapeXmlAttr(value: string): string {
2
+ return value
3
+ .replace(/&/g, "&amp;")
4
+ .replace(/</g, "&lt;")
5
+ .replace(/>/g, "&gt;")
6
+ .replace(/"/g, "&quot;")
7
+ .replace(/'/g, "&apos;");
8
+ }
9
+
10
+ export function escapeXmlContent(value: string): string {
11
+ return value.replace(/</g, "&lt;").replace(/>/g, "&gt;");
12
+ }