@luxass/pi-subagents 0.0.0-stage → 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.
package/src/tools.ts ADDED
@@ -0,0 +1,210 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { Text } from "@earendil-works/pi-tui";
4
+ import { Type } from "typebox";
5
+
6
+ import type { SubagentDefinition } from "./agents.ts";
7
+ import { isSubagentFinished, type SubagentManager } from "./manager.ts";
8
+ import type { SubagentThinking } from "./session.ts";
9
+ import {
10
+ agentToolDescription,
11
+ subagentFinishedText,
12
+ subagentStatusLine,
13
+ subagentToolResult,
14
+ type AgentToolDetails,
15
+ } from "./tool-text.ts";
16
+ import { AgentCardBody, subagentTitle } from "./ui/agent-card.ts";
17
+
18
+ const thinkingLevels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
19
+
20
+ const agentParameters = Type.Object({
21
+ subagent_type: Type.Optional(
22
+ Type.String({ description: "Agent type for a new agent. Required unless resume is set." }),
23
+ ),
24
+ name: Type.Optional(
25
+ Type.String({
26
+ description:
27
+ "Unique task name for a new agent: lowercase words joined by hyphens, such as auth-review. Required unless resume is set. Names are never reused in a session.",
28
+ }),
29
+ ),
30
+ prompt: Type.String({ description: "The task, or for resume the follow-up instruction." }),
31
+ resume: Type.Optional(
32
+ Type.String({
33
+ description: "Task name of a finished agent to continue in its saved conversation.",
34
+ }),
35
+ ),
36
+ run_in_background: Type.Optional(
37
+ Type.Boolean({
38
+ description: "false waits for the answer. Otherwise the result arrives later by itself.",
39
+ }),
40
+ ),
41
+ model: Type.Optional(
42
+ Type.String({
43
+ description:
44
+ "Model for this agent: provider/id, or a name such as \"opus 5.5\". Set it only when the user asks for a model. It replaces the agent type's own model. Leave it out to use the type's model, or yours when the type has none.",
45
+ }),
46
+ ),
47
+ thinking: Type.Optional(StringEnum(thinkingLevels, { description: "Thinking level." })),
48
+ max_turns: Type.Optional(
49
+ Type.Integer({ minimum: 0, description: "Turn limit. 0 means unlimited." }),
50
+ ),
51
+ inherit_context: Type.Optional(
52
+ Type.Boolean({ description: "Give the agent a copy of the conversation you currently see." }),
53
+ ),
54
+ });
55
+
56
+ const nameParameter = Type.Object({
57
+ name: Type.String({ description: "Task name returned by Agent." }),
58
+ });
59
+
60
+ /**
61
+ * Gives the session's manager, or nothing before a session has started. The tools are registered
62
+ * in the extension's default function, where no session exists yet.
63
+ */
64
+ type SubagentManagerSource = () => SubagentManager | undefined;
65
+
66
+ function requireManager(getManager: SubagentManagerSource): SubagentManager {
67
+ const manager = getManager();
68
+ if (!manager) throw new Error("Agents are not available until the session has started.");
69
+ return manager;
70
+ }
71
+
72
+ /**
73
+ * Registers the `Agent` tool. Its description lists the agent types, which are known only after
74
+ * the session starts, so it is registered again then. The later registration replaces this one.
75
+ */
76
+ export function registerAgentTool(
77
+ pi: ExtensionAPI,
78
+ getManager: SubagentManagerSource,
79
+ types: readonly SubagentDefinition[] | undefined,
80
+ ): void {
81
+ pi.registerTool({
82
+ name: "Agent",
83
+ label: "Agent",
84
+ description: agentToolDescription(types),
85
+ promptSnippet: "Delegate a task to a named agent that works in its own conversation",
86
+ parameters: agentParameters,
87
+ renderCall(args, theme) {
88
+ const title = args.resume
89
+ ? subagentTitle(theme, "resume", args.resume)
90
+ : subagentTitle(theme, args.subagent_type, args.name);
91
+ return new Text(title, 0, 0);
92
+ },
93
+ renderResult(result, options, theme, context) {
94
+ const { id, run } = (result.details as AgentToolDetails | undefined) ?? {};
95
+ const text = result.content
96
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
97
+ .join("\n");
98
+ if (context.isError || !id) {
99
+ return new Text(theme.fg(context.isError ? "error" : "text", text), 0, 0);
100
+ }
101
+ const hint = context.keyHint("app.tools.expand", "to expand");
102
+ // The agent is looked up on every draw. On /reload Pi redraws the chat before the session
103
+ // has restored its agents, so the card shows the result text until they are back.
104
+ return new AgentCardBody(
105
+ () => getManager()?.runOutcome(id, run),
106
+ theme,
107
+ options.expanded,
108
+ hint,
109
+ text,
110
+ );
111
+ },
112
+ async execute(_toolCallId, params, signal, onUpdate) {
113
+ const manager = requireManager(getManager);
114
+ // Checked before the launch changes the record.
115
+ const continued = params.resume ? manager.find(params.resume) : undefined;
116
+ const startedOver =
117
+ continued && manager.continuesWithoutConversation(continued)
118
+ ? `${continued.name} was interrupted before it started, so it has no earlier conversation. It began now with only this prompt.\n\n`
119
+ : "";
120
+ // StringEnum keeps the schema provider-friendly but types its value as unknown.
121
+ const record = manager.launch({
122
+ ...params,
123
+ thinking: params.thinking as SubagentThinking | undefined,
124
+ });
125
+ const details = { id: record.id, run: record.run };
126
+ if (record.background) {
127
+ const where =
128
+ record.status === "queued" ? "queued for the background" : "running in the background";
129
+ return subagentToolResult(
130
+ `${startedOver}Started ${record.name} (${record.agentType}) on ${record.model}, ${where}. Its result arrives by itself. Do not poll it or repeat its work. Continue with other work, or tell the user what you started and end your turn.`,
131
+ details,
132
+ );
133
+ }
134
+ const update = () =>
135
+ onUpdate?.(subagentToolResult(`${record.name}: ${record.activity}`, details));
136
+ const unsubscribe = manager.subscribe(update);
137
+ try {
138
+ const outcome = await manager.waitForeground(record, signal);
139
+ if (outcome === "background") {
140
+ return subagentToolResult(
141
+ `${record.name} moved to the background. Its result arrives by itself. Do not poll it or repeat its work.`,
142
+ details,
143
+ );
144
+ }
145
+ if (outcome === "aborted")
146
+ return subagentToolResult(
147
+ `Stopped ${record.name} because you were interrupted.`,
148
+ details,
149
+ );
150
+ return subagentToolResult(startedOver + subagentFinishedText(record), details);
151
+ } finally {
152
+ unsubscribe();
153
+ }
154
+ },
155
+ });
156
+ }
157
+
158
+ /** Registers the main session's tools: Agent, get_subagent_result, steer_subagent, stop_subagent. */
159
+ export function registerSubagentTools(pi: ExtensionAPI, getManager: SubagentManagerSource): void {
160
+ registerAgentTool(pi, getManager, undefined);
161
+
162
+ pi.registerTool({
163
+ name: "get_subagent_result",
164
+ label: "Agent result",
165
+ description:
166
+ "Read the full result of a finished agent by task name. For a running or queued agent, report its status without waiting.",
167
+ parameters: nameParameter,
168
+ async execute(_toolCallId, params) {
169
+ const manager = requireManager(getManager);
170
+ const record = manager.find(params.name);
171
+ if (!record) throw new Error(`No agent named "${params.name}" exists in this session.`);
172
+ if (!isSubagentFinished(record.status)) {
173
+ return subagentToolResult(
174
+ `${subagentStatusLine(record)} Current activity: ${record.activity}.`,
175
+ {
176
+ id: record.id,
177
+ },
178
+ );
179
+ }
180
+ manager.markReceipt(record, "consumed");
181
+ return subagentToolResult(subagentFinishedText(record), { id: record.id });
182
+ },
183
+ });
184
+
185
+ pi.registerTool({
186
+ name: "steer_subagent",
187
+ label: "Steer agent",
188
+ description: "Send a correction to a running or queued agent by task name.",
189
+ parameters: Type.Object({
190
+ name: Type.String({ description: "Task name returned by Agent." }),
191
+ message: Type.String({ description: "The correction for the agent." }),
192
+ }),
193
+ async execute(_toolCallId, params) {
194
+ const record = await requireManager(getManager).steer(params.name, params.message);
195
+ return subagentToolResult(`Sent the correction to ${record.name}.`, { id: record.id });
196
+ },
197
+ });
198
+
199
+ pi.registerTool({
200
+ name: "stop_subagent",
201
+ label: "Stop agent",
202
+ description:
203
+ "Stop a running or queued agent by task name. Other agents keep running. No result is sent afterwards.",
204
+ parameters: nameParameter,
205
+ async execute(_toolCallId, params) {
206
+ const record = await requireManager(getManager).stop(params.name, "model");
207
+ return subagentToolResult(subagentStatusLine(record), { id: record.id });
208
+ },
209
+ });
210
+ }
@@ -0,0 +1,123 @@
1
+ import {
2
+ getMarkdownTheme,
3
+ type MessageRenderer,
4
+ type Theme,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ Box,
8
+ Container,
9
+ Markdown,
10
+ Spacer,
11
+ Text,
12
+ truncateToWidth,
13
+ visibleWidth,
14
+ type Component,
15
+ } from "@earendil-works/pi-tui";
16
+
17
+ import { isSubagentFinished, type SubagentRecord } from "../manager.ts";
18
+ import type { SubagentResultDetails } from "../results.ts";
19
+ import {
20
+ cleanSubagentText,
21
+ firstSubagentLine,
22
+ showsBackgroundHint,
23
+ subagentActivity,
24
+ subagentCounters,
25
+ subagentStatusLabel,
26
+ subagentStatusMark,
27
+ } from "./agent-status.ts";
28
+
29
+ /** One line naming the agent: `Agent explorer · auth-review`. */
30
+ export function subagentTitle(
31
+ theme: Theme,
32
+ agentType: string | undefined,
33
+ name: string | undefined,
34
+ ): string {
35
+ const parts = [agentType, name].filter(Boolean).join(theme.fg("muted", " · "));
36
+ return `${theme.fg("toolTitle", theme.bold("Agent"))}${parts ? ` ${parts}` : ""}`;
37
+ }
38
+
39
+ /**
40
+ * Live progress, then the outcome and one answer line, expandable to the full answer.
41
+ * It reads the record on every render, so it stays current while the agent works.
42
+ */
43
+ export class AgentCardBody implements Component {
44
+ private markdown: { text: string; component: Markdown } | undefined;
45
+
46
+ constructor(
47
+ private readonly record: () => SubagentRecord | undefined,
48
+ private readonly theme: Theme,
49
+ private readonly expanded: boolean,
50
+ private readonly expandHint: string,
51
+ /** Shown while the agent is unknown, for example before a reloaded session restores it. */
52
+ private readonly fallbackText = "",
53
+ ) {}
54
+
55
+ render(width: number): ReturnType<Component["render"]> {
56
+ const record = this.record();
57
+ if (!record) {
58
+ if (!this.fallbackText) return [];
59
+ return new Text(this.theme.fg("text", this.fallbackText), 0, 0).render(width);
60
+ }
61
+ const { theme } = this;
62
+ const fit = (line: string) => truncateToWidth(line, width, "…");
63
+ const mark = subagentStatusMark(record, theme);
64
+ if (!isSubagentFinished(record.status)) {
65
+ const counters = `· ${subagentCounters(record)}`;
66
+ // Mark, space, activity, space, counters. The activity gets what the counters leave.
67
+ const activity = subagentActivity(record, width - 3 - visibleWidth(counters));
68
+ const lines = [fit(`${mark} ${activity} ${theme.fg("dim", counters)}`)];
69
+ if (showsBackgroundHint(record))
70
+ lines.push(fit(theme.fg("dim", " (ctrl+b to run in background)")));
71
+ return lines;
72
+ }
73
+ const lines = [
74
+ fit(
75
+ `${mark} ${subagentStatusLabel(record)} ${theme.fg("dim", `· ${subagentCounters(record)}`)}`,
76
+ ),
77
+ ];
78
+ const answer = cleanSubagentText(record.result || record.error || "");
79
+ if (!answer.trim()) return lines;
80
+ if (!this.expanded) {
81
+ const more = answer.trim().includes("\n")
82
+ ? ` ${theme.fg("dim", `(${this.expandHint})`)}`
83
+ : "";
84
+ lines.push(
85
+ fit(
86
+ ` ${theme.fg(record.error && !record.result ? "error" : "text", firstSubagentLine(answer))}${more}`,
87
+ ),
88
+ );
89
+ return lines;
90
+ }
91
+ if (this.markdown?.text !== answer) {
92
+ this.markdown = { text: answer, component: new Markdown(answer, 2, 0, getMarkdownTheme()) };
93
+ }
94
+ return [...lines, ...this.markdown.component.render(width)];
95
+ }
96
+
97
+ invalidate(): void {
98
+ this.markdown = undefined;
99
+ }
100
+ }
101
+
102
+ /** Renders delivered background results as the same card, inside a message block. */
103
+ export const renderSubagentResultMessage: MessageRenderer<SubagentResultDetails> = (
104
+ message,
105
+ options,
106
+ theme,
107
+ ) => {
108
+ const records = message.details?.records ?? [];
109
+ if (!records.length) return undefined;
110
+ const box = new Box(options.outputPad, 1, (text) => theme.bg("customMessageBg", text));
111
+ const hint = options.keyHint("app.tools.expand", "to expand");
112
+ records.forEach((record, index) => {
113
+ if (index > 0) box.addChild(new Spacer(1));
114
+ box.addChild(new Text(subagentTitle(theme, record.agentType, record.name), 0, 0));
115
+ box.addChild(new AgentCardBody(() => record, theme, options.expanded, hint));
116
+ });
117
+ return box;
118
+ };
119
+
120
+ /** Empty component for a slot that has nothing to show. */
121
+ export function emptyComponent(): Component {
122
+ return new Container();
123
+ }
@@ -0,0 +1,162 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { visibleWidth } from "@earendil-works/pi-tui";
3
+
4
+ import { isSubagentFinished, type SubagentManager, type SubagentRecord } from "../manager.ts";
5
+ import {
6
+ SUBAGENT_BADGE_WIDTH,
7
+ subagentBadge,
8
+ subagentElapsed,
9
+ subagentTaskTitle,
10
+ } from "./agent-status.ts";
11
+ import { cutPlainText, fitLine } from "./text-layout.ts";
12
+
13
+ /** Which agents the list shows. An agent is active until it has finished. */
14
+ export type SubagentListFilter = "all" | "active" | "finished";
15
+
16
+ /**
17
+ * The agent list of `/agents`: which agents the filter shows, their order, and the selection.
18
+ * Each agent takes two lines: its task name and type, then its task, status, and elapsed time.
19
+ */
20
+ export class SubagentList {
21
+ filter: SubagentListFilter = "all";
22
+ private selectedId: string | undefined;
23
+ /** Index of the first agent drawn, so a long list scrolls with the selection. */
24
+ start = 0;
25
+ /** Lines the agents took in the last render. Zero when the list was not drawn. */
26
+ drawnHeight = 0;
27
+ private stopTargetId: string | undefined;
28
+
29
+ constructor(
30
+ private readonly theme: Theme,
31
+ private readonly manager: SubagentManager,
32
+ ) {}
33
+
34
+ /** The agents the filter shows: unfinished agents first, and the newest first in each group. */
35
+ rows(): SubagentRecord[] {
36
+ const newestFirst = this.manager.list().toReversed();
37
+ const shown =
38
+ this.filter === "all"
39
+ ? newestFirst
40
+ : newestFirst.filter(
41
+ (record) => isSubagentFinished(record.status) === (this.filter === "finished"),
42
+ );
43
+ // The sort is stable, so each group keeps its newest-first order.
44
+ return shown.toSorted(
45
+ (first, second) =>
46
+ Number(isSubagentFinished(first.status)) - Number(isSubagentFinished(second.status)),
47
+ );
48
+ }
49
+
50
+ /** How many agents each filter tab holds. */
51
+ counts(): Record<SubagentListFilter, number> {
52
+ const all = this.manager.list();
53
+ const finished = all.filter((record) => isSubagentFinished(record.status)).length;
54
+ return { all: all.length, active: all.length - finished, finished };
55
+ }
56
+
57
+ /** The selected agent. Falls back to the first shown agent when the selection is not shown. */
58
+ selected(): SubagentRecord | undefined {
59
+ const rows = this.rows();
60
+ const selected = rows.find((record) => record.id === this.selectedId) ?? rows[0];
61
+ this.selectedId = selected?.id;
62
+ return selected;
63
+ }
64
+
65
+ select(id: string | undefined): void {
66
+ this.selectedId = id;
67
+ }
68
+
69
+ move(delta: number): void {
70
+ const rows = this.rows();
71
+ if (!rows.length) return;
72
+ const index = rows.findIndex((record) => record.id === this.selected()?.id);
73
+ const next = Math.max(0, Math.min(rows.length - 1, index + delta));
74
+ this.select(rows[next]?.id);
75
+ }
76
+
77
+ setFilter(filter: SubagentListFilter): void {
78
+ this.filter = filter;
79
+ }
80
+
81
+ /** Whether the agent can be stopped: it is queued or running. */
82
+ canStop(record: SubagentRecord): boolean {
83
+ return !isSubagentFinished(record.status) && record.status !== "stopping";
84
+ }
85
+
86
+ /** Asks to stop the selected agent. The stop waits for `confirmStop`. */
87
+ askStop(): void {
88
+ const record = this.selected();
89
+ if (record && this.canStop(record)) this.stopTargetId = record.id;
90
+ }
91
+
92
+ /** The agent whose stop waits for an answer. The wait ends when the agent finishes by itself. */
93
+ stopTarget(): SubagentRecord | undefined {
94
+ const record = this.stopTargetId ? this.manager.records.get(this.stopTargetId) : undefined;
95
+ if (record && this.canStop(record)) return record;
96
+ this.stopTargetId = undefined;
97
+ return undefined;
98
+ }
99
+
100
+ /** Answers the stop question. Yes stops the agent as the user. */
101
+ async confirmStop(yes: boolean): Promise<void> {
102
+ const record = this.stopTarget();
103
+ this.stopTargetId = undefined;
104
+ if (yes && record) await this.manager.stop(record.name, "user");
105
+ }
106
+
107
+ /**
108
+ * Draws the agents in `width` columns and at most `height` lines. `compact` rows have no blank
109
+ * line between agents. The selection mark dims while the preview has the focus.
110
+ */
111
+ render(width: number, height: number, compact: boolean, previewFocused: boolean): string[] {
112
+ const { theme } = this;
113
+ const rows = this.rows();
114
+ // Two lines for an agent, and a blank line between agents when there is room for it.
115
+ const rowHeight = compact ? 2 : 3;
116
+ const slots = Math.max(1, Math.floor(height / rowHeight));
117
+ this.drawnHeight = Math.min(height, slots * rowHeight, rows.length * rowHeight);
118
+ const index = Math.max(
119
+ 0,
120
+ rows.findIndex((record) => record.id === this.selected()?.id),
121
+ );
122
+ this.start = Math.max(0, Math.min(this.start, index, Math.max(0, rows.length - slots)));
123
+ if (index >= this.start + slots) this.start = index - slots + 1;
124
+
125
+ const durationWidth = rows.reduce(
126
+ (widest, record) => Math.max(widest, visibleWidth(subagentElapsed(record))),
127
+ 6,
128
+ );
129
+ const identityWidth = Math.max(0, width - SUBAGENT_BADGE_WIDTH - durationWidth - 4);
130
+ const lines: string[] = [];
131
+ for (const record of rows.slice(this.start, this.start + slots)) {
132
+ const selected = record.id === this.selectedId;
133
+ const marker = selected ? theme.fg(previewFocused ? "muted" : "accent", "▌ ") : " ";
134
+ // The short task name is the title. The prompt is long, so it goes on the second line.
135
+ // Text is cut before it is colored, so the selection background reaches the row's end.
136
+ const name = cutPlainText(record.name, width - 2);
137
+ const type = cutPlainText(` · ${record.agentType}`, width - 2 - visibleWidth(name));
138
+ const title = fitLine(
139
+ `${marker}${selected ? theme.bold(name) : name}${theme.fg("dim", type)}`,
140
+ width,
141
+ );
142
+ const badge = subagentBadge(record, theme);
143
+ const task = cutPlainText(subagentTaskTitle(record), identityWidth - 2);
144
+ const caption = fitLine(`${marker}${theme.fg("muted", task)}`, identityWidth);
145
+ const duration = subagentElapsed(record);
146
+ const timing = theme.fg(
147
+ "dim",
148
+ " ".repeat(Math.max(0, durationWidth - visibleWidth(duration))) + duration,
149
+ );
150
+ const alignedBadge =
151
+ " ".repeat(Math.max(0, SUBAGENT_BADGE_WIDTH - visibleWidth(badge))) + badge;
152
+ const details = `${caption} · ${alignedBadge} ${timing}`;
153
+ lines.push(
154
+ selected ? theme.bg("selectedBg", title) : title,
155
+ selected ? theme.bg("selectedBg", details) : details,
156
+ );
157
+ if (!compact) lines.push("");
158
+ }
159
+ if (!lines.length) lines.push(theme.fg("dim", "No matching agents"));
160
+ return lines;
161
+ }
162
+ }