@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.
@@ -0,0 +1,250 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth, type TUI } from "@earendil-works/pi-tui";
3
+
4
+ import { isSubagentFinished, type SubagentRecord } from "../manager.ts";
5
+ import type { SubagentList, SubagentListFilter } from "./agent-list.ts";
6
+ import type { SubagentPreview } from "./agent-preview.ts";
7
+ import {
8
+ subagentActivity,
9
+ subagentBadge,
10
+ subagentCounters,
11
+ subagentElapsed,
12
+ subagentModelLabel,
13
+ subagentTaskTitle,
14
+ } from "./agent-status.ts";
15
+ import { fitLine, lineEnds } from "./text-layout.ts";
16
+
17
+ /** What the panel draws from. */
18
+ export interface AgentPanelState {
19
+ theme: Theme;
20
+ tui: TUI;
21
+ list: SubagentList;
22
+ preview: SubagentPreview;
23
+ fullscreen: boolean;
24
+ /** True when Up and Down scroll the answer, false when they select an agent. */
25
+ previewFocused: boolean;
26
+ redraw: () => void;
27
+ }
28
+
29
+ const FILTER_TABS: { filter: SubagentListFilter; label: string }[] = [
30
+ { filter: "all", label: "All" },
31
+ { filter: "active", label: "Active" },
32
+ { filter: "finished", label: "Finished" },
33
+ ];
34
+
35
+ /** The filter tabs with their counts, such as "All 3 Active 1 Finished 2". */
36
+ function filterTabs(state: AgentPanelState, width: number): string {
37
+ const { theme, list } = state;
38
+ const counts = list.counts();
39
+ let line = "";
40
+ for (const [index, tab] of FILTER_TABS.entries()) {
41
+ const label = `${tab.label} ${counts[tab.filter]}`;
42
+ line +=
43
+ list.filter === tab.filter ? theme.fg("accent", theme.bold(label)) : theme.fg("muted", label);
44
+ if (index < FILTER_TABS.length - 1) line += " ";
45
+ }
46
+ return fitLine(line, width);
47
+ }
48
+
49
+ /** The one quiet footer: the keys that apply now on the left, Esc on the right. */
50
+ function actionHints(
51
+ state: AgentPanelState,
52
+ record: SubagentRecord | undefined,
53
+ width: number,
54
+ ): string {
55
+ const { theme, list, preview, previewFocused } = state;
56
+ const confirming = list.stopTarget() !== undefined;
57
+ const hints = confirming
58
+ ? ["y Stop", "n Keep running"]
59
+ : [
60
+ ...(preview.scroll.isFollowingEnd ? [] : ["End Follow"]),
61
+ previewFocused ? "Tab Agents" : "Tab Output",
62
+ "Enter Open",
63
+ ...(record && list.canStop(record) ? ["x Stop"] : []),
64
+ ];
65
+ const ending = confirming ? "Esc Cancel" : "Esc Close";
66
+ const right = width < 28 ? "Esc" : ending;
67
+ const budget = Math.max(0, width - visibleWidth(right) - 2);
68
+ let left = "";
69
+ for (const hint of hints) {
70
+ const gap = left ? " " : "";
71
+ if (visibleWidth(left + gap + hint) > budget) break;
72
+ left += gap + hint;
73
+ }
74
+ return theme.fg("muted", lineEnds(left, right, width));
75
+ }
76
+
77
+ /**
78
+ * What the selected agent is doing and has used, such as "bash sleep 100 · ↻1 · 1 tool use ·
79
+ * 3.5k tokens". A finished agent has only the counters. The activity gets the room they leave.
80
+ */
81
+ function progressText(record: SubagentRecord, width: number): string {
82
+ const counters = subagentCounters(record, { elapsed: false });
83
+ if (isSubagentFinished(record.status)) return counters;
84
+ return `${subagentActivity(record, width - visibleWidth(counters) - 3)} · ${counters}`;
85
+ }
86
+
87
+ /**
88
+ * The lines under the list in the stacked layout: the selected agent's progress and its model.
89
+ * They share one line when both fit, with the model at the right. Otherwise each has its own.
90
+ */
91
+ function progressLines(state: AgentPanelState, record: SubagentRecord, width: number): string[] {
92
+ const { theme } = state;
93
+ const model = subagentModelLabel(record);
94
+ const room = width - visibleWidth(model) - 2;
95
+ // A working agent needs room for its counters and at least a short activity.
96
+ const needed =
97
+ visibleWidth(subagentCounters(record, { elapsed: false })) +
98
+ (isSubagentFinished(record.status) ? 0 : 19);
99
+ if (room >= needed) {
100
+ return [lineEnds(theme.fg("muted", progressText(record, room)), theme.fg("dim", model), width)];
101
+ }
102
+ return [
103
+ fitLine(theme.fg("muted", progressText(record, width)), width),
104
+ fitLine(theme.fg("dim", model), width),
105
+ ];
106
+ }
107
+
108
+ /** The selected agent's task, status line, and answer, for the wide and the small layout. */
109
+ function selectedOutput(
110
+ state: AgentPanelState,
111
+ record: SubagentRecord | undefined,
112
+ width: number,
113
+ height: number,
114
+ ): string[] {
115
+ const { theme, preview } = state;
116
+ if (!record) {
117
+ return [
118
+ theme.bold("No agents yet"),
119
+ "",
120
+ theme.fg("muted", "Start a task from the conversation."),
121
+ ];
122
+ }
123
+ const paused = !preview.scroll.isFollowingEnd;
124
+ const header = [
125
+ fitLine(`${theme.bold(record.name)}${theme.fg("dim", ` · ${record.agentType}`)}`, width),
126
+ lineEnds(
127
+ `${subagentBadge(record, theme)} · ${theme.fg("muted", subagentModelLabel(record))}`,
128
+ theme.fg("dim", `${subagentElapsed(record)}${paused ? " · Paused" : ""}`),
129
+ width,
130
+ ),
131
+ fitLine(theme.fg("muted", progressText(record, width)), width),
132
+ fitLine(theme.fg("muted", subagentTaskTitle(record)), width),
133
+ "",
134
+ ];
135
+ const remaining = Math.max(1, height - header.length);
136
+ return [...header, ...preview.render(record, width, remaining, state.redraw)];
137
+ }
138
+
139
+ /** A terminal too small for the frame gets the title, the selected answer, and the footer. */
140
+ function renderSmallPanel(state: AgentPanelState, width: number, height: number): string[] {
141
+ const { theme, list } = state;
142
+ const bodyHeight = Math.max(1, height - 2);
143
+ const record = list.selected();
144
+ let lines = height <= 3 ? [] : [theme.fg("accent", theme.bold("Agents"))];
145
+ if (list.stopTarget()) lines.push("Stop this agent? y / n");
146
+ else lines.push(...selectedOutput(state, record, width, bodyHeight).slice(0, bodyHeight));
147
+ lines = lines.slice(0, Math.max(1, height - 1));
148
+ if (height > 1) lines.push(actionHints(state, record, width));
149
+ return lines.map((line) => truncateToWidth(line, width));
150
+ }
151
+
152
+ /**
153
+ * Draws the first view of `/agents`: a rounded panel with the agent counts, the filter tabs, the
154
+ * agent list, the selected answer, and the footer. From 104 columns the list and the answer are
155
+ * side by side. Below that the list is on top, with a preview of at most three lines under it.
156
+ */
157
+ export function renderAgentPanel(state: AgentPanelState, width: number): string[] {
158
+ const { theme, tui, list, preview, fullscreen, previewFocused } = state;
159
+ const inner = Math.max(1, width - 6);
160
+ const terminalHeight = Math.max(1, tui.terminal.rows - (fullscreen ? 0 : 4));
161
+ const maximum = fullscreen ? terminalHeight : Math.min(36, terminalHeight);
162
+ const stopTarget = list.stopTarget();
163
+ const available = maximum - 9 - (stopTarget ? 1 : 0);
164
+ if (available < 7 || width < 36) {
165
+ return renderSmallPanel(state, width, Math.max(1, maximum));
166
+ }
167
+
168
+ // From 104 columns the list and the answer are side by side.
169
+ const wide = width >= 104;
170
+ const listWidth = wide ? Math.min(39, Math.floor(inner * 0.34)) : inner;
171
+ const rightWidth = wide ? Math.max(1, inner - listWidth - 3) : inner;
172
+ const record = list.selected();
173
+ const rows = list.rows();
174
+
175
+ const edge = (text: string): string => theme.fg("borderMuted", text);
176
+ const line = (text = ""): string => `${edge("│")} ${fitLine(text, inner)} ${edge("│")}`;
177
+ const rule = (left: string, right: string): string =>
178
+ edge(left + "─".repeat(Math.max(0, width - 2)) + right);
179
+
180
+ const counts = list.counts();
181
+ const title =
182
+ theme.fg("accent", theme.bold("Agents")) +
183
+ theme.fg(
184
+ "dim",
185
+ counts.active
186
+ ? ` ${counts.active} active${counts.finished ? ` · ${counts.finished} finished` : ""}`
187
+ : counts.all
188
+ ? ` ${counts.finished} finished`
189
+ : "",
190
+ );
191
+ const expand = theme.fg("dim", fullscreen ? "f Restore" : "f Fullscreen");
192
+
193
+ let body: string[] = [];
194
+ let bodyHeight: number;
195
+ if (wide) {
196
+ const measured = selectedOutput(state, record, rightWidth, available);
197
+ const natural = Math.max(10, Math.min(12, rows.length * 3), measured.length);
198
+ bodyHeight = fullscreen ? available : Math.min(available, natural);
199
+ const left = list.render(listWidth, bodyHeight, false, previewFocused);
200
+ const right = selectedOutput(state, record, rightWidth, bodyHeight);
201
+ const divider = theme.fg(previewFocused ? "borderAccent" : "borderMuted", "│");
202
+ for (let index = 0; index < bodyHeight; index++) {
203
+ body.push(`${fitLine(left[index] ?? "", listWidth)} ${divider} ${right[index] ?? ""}`);
204
+ }
205
+ } else {
206
+ // Under the list: a rule, the selected agent's progress and model, and its answer. The answer gets
207
+ // at least three lines. The list takes what it needs from the rest.
208
+ const minimumPreview = 3;
209
+ const status = record ? progressLines(state, record, inner) : [];
210
+ const listRoom = Math.max(2, available - 1 - status.length - minimumPreview);
211
+ const overflow = rows.length * 2 > listRoom;
212
+ const listBudget = overflow ? Math.max(2, listRoom - 1) : Math.max(2, rows.length * 2);
213
+ body = list.render(inner, listBudget, true, previewFocused);
214
+ if (overflow) {
215
+ const last = Math.min(rows.length, list.start + list.drawnHeight / 2);
216
+ body.push(theme.fg("dim", `${list.start + 1}–${last} of ${rows.length} agents · ↑↓ More`));
217
+ }
218
+ body.push(edge("─".repeat(inner)));
219
+ body.push(...status);
220
+ // The answer is as tall as its text, up to the rows that are left. Fullscreen uses them all.
221
+ const previewRoom = Math.max(minimumPreview, available - body.length);
222
+ const previewHeight =
223
+ fullscreen || !record
224
+ ? record
225
+ ? previewRoom
226
+ : minimumPreview
227
+ : Math.max(minimumPreview, Math.min(previewRoom, preview.lineCount(record, inner)));
228
+ const answer = record
229
+ ? preview.render(record, inner, previewHeight, state.redraw, true)
230
+ : [theme.fg("muted", "Start a task from the main conversation.")];
231
+ body.push(...answer.slice(0, previewHeight));
232
+ bodyHeight = fullscreen ? available : Math.min(available, Math.max(7, body.length));
233
+ }
234
+ while (body.length < bodyHeight) body.push("");
235
+
236
+ const lines = [
237
+ rule("╭", "╮"),
238
+ line(lineEnds(title, expand, inner)),
239
+ line(),
240
+ line(filterTabs(state, inner)),
241
+ line(),
242
+ ...body.slice(0, bodyHeight).map((text) => line(text)),
243
+ line(),
244
+ ];
245
+ if (stopTarget) {
246
+ lines.push(line(theme.fg("warning", `Stop ${stopTarget.name}? y / n`)));
247
+ }
248
+ lines.push(rule("├", "┤"), line(actionHints(state, record, inner)), rule("╰", "╯"));
249
+ return lines.map((text) => truncateToWidth(text, width));
250
+ }
@@ -0,0 +1,124 @@
1
+ import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
2
+ import { Markdown, ScrollView, Text, type Component } from "@earendil-works/pi-tui";
3
+
4
+ import { isSubagentFinished, type SubagentManager, type SubagentRecord } from "../manager.ts";
5
+ import { subagentMessageText } from "../message-text.ts";
6
+ import { cleanSubagentText } from "./agent-status.ts";
7
+
8
+ /** What the preview shows for an agent: its answer, its latest tool output, or a waiting note. */
9
+ interface SubagentOutput {
10
+ kind: "answer" | "tool" | "empty";
11
+ text: string;
12
+ /** Heading of a tool output, such as "Output · bash". */
13
+ label?: string;
14
+ }
15
+
16
+ /**
17
+ * The newest thing worth showing. A finished agent shows its answer. A working agent shows its
18
+ * latest tool output or reply, not an earlier one.
19
+ */
20
+ function subagentOutput(record: SubagentRecord, manager: SubagentManager): SubagentOutput {
21
+ if (isSubagentFinished(record.status)) {
22
+ if (record.result) return { kind: "answer", text: record.result };
23
+ // The saved conversation can hold earlier runs, so it is not searched for a finished agent.
24
+ return { kind: "empty", text: record.error || "No answer." };
25
+ }
26
+ const messages = manager.transcript(record);
27
+ for (let index = messages.length - 1; index >= 0; index--) {
28
+ const message = messages[index];
29
+ if (message?.role === "toolResult") {
30
+ const text = subagentMessageText(message.content);
31
+ if (text.trim()) return { kind: "tool", label: `Output · ${message.toolName}`, text };
32
+ } else if (message?.role === "assistant") {
33
+ const call = message.content.find((part) => part.type === "toolCall");
34
+ // A tool call in the newest message has no result yet.
35
+ if (call?.type === "toolCall" && index === messages.length - 1) {
36
+ return { kind: "tool", label: `Live output · ${call.name}`, text: "Waiting for output…" };
37
+ }
38
+ const text = subagentMessageText(message.content);
39
+ if (text.trim()) return { kind: "answer", text };
40
+ }
41
+ }
42
+ return { kind: "empty", text: "Waiting for the agent's first output…" };
43
+ }
44
+
45
+ /**
46
+ * The answer preview of `/agents`. It follows new output of a working agent, and starts at the
47
+ * top of a finished answer when it has only a few lines to show it in.
48
+ */
49
+ export class SubagentPreview {
50
+ private lines: ReturnType<Component["render"]> = [];
51
+ private shownText: string | undefined;
52
+ private width = 0;
53
+ private markdown: Markdown | undefined;
54
+ private runKey: string | undefined;
55
+ private wasCompact = false;
56
+ private wasFinished = false;
57
+ readonly scroll = new ScrollView(
58
+ { render: () => this.lines, invalidate() {} },
59
+ { follow: "end", scrollbar: "hidden" },
60
+ );
61
+
62
+ constructor(private readonly manager: SubagentManager) {}
63
+
64
+ invalidate(): void {
65
+ this.width = 0;
66
+ this.markdown?.invalidate();
67
+ }
68
+
69
+ /** Lays the agent's newest output out in `width` columns. Returns what kind of output it is. */
70
+ private layOut(record: SubagentRecord, width: number): "answer" | "tool" | "empty" {
71
+ const output = subagentOutput(record, this.manager);
72
+ const text = `${output.kind}\n${output.label ?? ""}\n${output.text}`;
73
+ if (text !== this.shownText || width !== this.width) {
74
+ this.shownText = text;
75
+ this.width = width;
76
+ if (output.kind === "answer") {
77
+ this.markdown = new Markdown(cleanSubagentText(output.text), 0, 0, getMarkdownTheme());
78
+ this.lines = this.markdown.render(width);
79
+ } else {
80
+ this.markdown = undefined;
81
+ const plain = output.label ? `${output.label}\n\n${output.text}` : output.text;
82
+ this.lines = new Text(cleanSubagentText(plain), 0, 0).render(width);
83
+ }
84
+ }
85
+ return output.kind;
86
+ }
87
+
88
+ /** How many lines the agent's newest output takes in `width` columns, to size the preview. */
89
+ lineCount(record: SubagentRecord, width: number): number {
90
+ this.layOut(record, width);
91
+ return this.lines.length;
92
+ }
93
+
94
+ /**
95
+ * Returns at most `height` lines of `width` columns. `compact` is the preview under the list,
96
+ * which starts at the top of a finished answer.
97
+ */
98
+ render(
99
+ record: SubagentRecord,
100
+ width: number,
101
+ height: number,
102
+ redraw: () => void,
103
+ compact = false,
104
+ ): string[] {
105
+ const runKey = `${record.id}:${record.run}`;
106
+ const selectionChanged = runKey !== this.runKey;
107
+ const finished = isSubagentFinished(record.status);
108
+ const startAtAnswer =
109
+ compact &&
110
+ finished &&
111
+ (selectionChanged || (this.scroll.isFollowingEnd && (!this.wasCompact || !this.wasFinished)));
112
+ this.wasCompact = compact;
113
+ this.wasFinished = finished;
114
+ if (selectionChanged) {
115
+ this.runKey = runKey;
116
+ this.scroll.scrollToEnd();
117
+ }
118
+
119
+ const kind = this.layOut(record, width);
120
+ this.scroll.updateLayout(this.lines.length, height, redraw);
121
+ if (startAtAnswer && kind === "answer") this.scroll.scrollToStart();
122
+ return this.lines.slice(this.scroll.scrollTop, this.scroll.scrollTop + height);
123
+ }
124
+ }
@@ -0,0 +1,159 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+
3
+ import type { SubagentRecord } from "../manager.ts";
4
+ import { cutPlainText } from "./text-layout.ts";
5
+
6
+ const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
7
+
8
+ /** How long a foreground agent runs before its row suggests Ctrl+B. */
9
+ export const BACKGROUND_HINT_DELAY_MS = 3000;
10
+
11
+ // CSI and OSC sequences, then any other escape or control character except newline and tab.
12
+ const CONTROL_SEQUENCES =
13
+ // oxlint-disable-next-line no-control-regex -- matching terminal control sequences is the point.
14
+ /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b.|[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
15
+
16
+ /** Removes terminal control sequences from agent output before it is displayed. */
17
+ export function cleanSubagentText(text: string): string {
18
+ return text.replace(CONTROL_SEQUENCES, "");
19
+ }
20
+
21
+ /**
22
+ * Cleans every string inside a value from an agent, such as tool-call arguments or result details.
23
+ * Pi's tool renderers print these as they are, so they are cleaned before a renderer sees them.
24
+ */
25
+ export function cleanSubagentValue<Value>(value: Value): Value {
26
+ // The shape stays the same. Only the strings inside it change.
27
+ return cleanStrings(value) as Value;
28
+ }
29
+
30
+ function cleanStrings(value: unknown): unknown {
31
+ if (typeof value === "string") return cleanSubagentText(value);
32
+ if (Array.isArray(value)) return value.map((item: unknown) => cleanStrings(item));
33
+ if (value && typeof value === "object") {
34
+ return Object.fromEntries(
35
+ Object.entries(value).map(([key, item]: [string, unknown]) => [
36
+ cleanSubagentText(key),
37
+ cleanStrings(item),
38
+ ]),
39
+ );
40
+ }
41
+ return value;
42
+ }
43
+
44
+ /** First line of agent text with words in it, cleaned for one-line display. Code fences are skipped. */
45
+ export function firstSubagentLine(text: string): string {
46
+ const lines = cleanSubagentText(text).split("\n");
47
+ return lines.find((line) => line.trim() && !line.trim().startsWith("```"))?.trim() ?? "";
48
+ }
49
+
50
+ const STATUS_MARKS = {
51
+ queued: ["dim", "◌"],
52
+ stopping: ["warning", "■"],
53
+ completed: ["success", "✓"],
54
+ stopped: ["warning", "■"],
55
+ failed: ["error", "✗"],
56
+ interrupted: ["warning", "!"],
57
+ } as const;
58
+
59
+ /** The color of an agent's status mark and status word. */
60
+ function subagentStatusColor(record: SubagentRecord) {
61
+ if (record.status === "running") return "accent" as const;
62
+ // A partial answer is still an answer, but it stopped at the turn limit.
63
+ return record.partial ? ("warning" as const) : STATUS_MARKS[record.status][0];
64
+ }
65
+
66
+ /** The one status mark the widget, cards, and `/agents` share. */
67
+ export function subagentStatusMark(record: SubagentRecord, theme: Theme): string {
68
+ if (record.status === "running") {
69
+ return theme.fg("accent", SPINNER[Math.floor(Date.now() / 80) % SPINNER.length] ?? "⠋");
70
+ }
71
+ return theme.fg(subagentStatusColor(record), STATUS_MARKS[record.status][1]);
72
+ }
73
+
74
+ const STATUS_WORDS = {
75
+ queued: "Queued",
76
+ running: "Running",
77
+ stopping: "Stopping",
78
+ completed: "Done",
79
+ stopped: "Stopped",
80
+ failed: "Failed",
81
+ interrupted: "Interrupted",
82
+ } as const;
83
+
84
+ /** Width of the longest status badge, "! Interrupted", so badges line up in a column. */
85
+ export const SUBAGENT_BADGE_WIDTH = 13;
86
+
87
+ /** Status mark and status word in the status color, such as "✓ Done", for the `/agents` list. */
88
+ export function subagentBadge(record: SubagentRecord, theme: Theme): string {
89
+ const word =
90
+ record.partial && record.status === "completed" ? "Partial" : STATUS_WORDS[record.status];
91
+ return `${subagentStatusMark(record, theme)} ${theme.fg(subagentStatusColor(record), word)}`;
92
+ }
93
+
94
+ /** The model and thinking level an agent runs on, such as "openai/gpt-6.1-sol · thinking medium". */
95
+ export function subagentModelLabel(record: SubagentRecord): string {
96
+ return `${record.model || "model pending"} · thinking ${record.thinking}`;
97
+ }
98
+
99
+ /** The agent's task on one line: the first line of its prompt, cleaned for display. */
100
+ export function subagentTaskTitle(record: SubagentRecord): string {
101
+ const title = cleanSubagentText(record.task).replace(/\s+/g, " ").trim().slice(0, 160);
102
+ return title || record.name;
103
+ }
104
+
105
+ function formatTokens(tokens: number): string {
106
+ if (tokens < 1000) return String(tokens);
107
+ if (tokens < 1_000_000) return `${(tokens / 1000).toFixed(1)}k`;
108
+ return `${(tokens / 1_000_000).toFixed(1)}M`;
109
+ }
110
+
111
+ /** Elapsed time of the latest run, such as 42s or 3m 05s. */
112
+ export function subagentElapsed(record: SubagentRecord): string {
113
+ if (!record.startedAt) return "";
114
+ const seconds = Math.max(
115
+ 0,
116
+ Math.round(((record.endedAt ?? Date.now()) - record.startedAt) / 1000),
117
+ );
118
+ if (seconds < 60) return `${seconds}s`;
119
+ return `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, "0")}s`;
120
+ }
121
+
122
+ /**
123
+ * What a working agent is doing, such as "bash sleep 100", cut to `room` columns. Callers give it
124
+ * the room that is left after the counters, so a long command cannot push the counters off the
125
+ * line. It keeps at least 16 columns, enough to name the tool and the start of its input.
126
+ */
127
+ export function subagentActivity(record: SubagentRecord, room: number): string {
128
+ return cutPlainText(cleanSubagentText(record.activity), Math.max(16, room));
129
+ }
130
+
131
+ /**
132
+ * Turns, tool uses, tokens with context percentage, and elapsed time, joined with dots. Pass
133
+ * `elapsed: false` where the elapsed time is already shown next to it.
134
+ */
135
+ export function subagentCounters(record: SubagentRecord, options = { elapsed: true }): string {
136
+ const context = record.contextPercent === null ? "" : ` (${Math.round(record.contextPercent)}%)`;
137
+ const parts = [
138
+ `↻${record.turns}${record.maxTurns ? `/${record.maxTurns}` : ""}`,
139
+ `${record.toolUses} tool use${record.toolUses === 1 ? "" : "s"}`,
140
+ `${formatTokens(record.tokens.total)} tokens${context}`,
141
+ ];
142
+ const elapsed = options.elapsed ? subagentElapsed(record) : "";
143
+ if (elapsed) parts.push(elapsed);
144
+ return parts.join(" · ");
145
+ }
146
+
147
+ /** Whether a foreground row should show the Ctrl+B hint now. */
148
+ export function showsBackgroundHint(record: SubagentRecord): boolean {
149
+ return (
150
+ !record.background &&
151
+ record.status === "running" &&
152
+ Date.now() - (record.startedAt ?? Date.now()) >= BACKGROUND_HINT_DELAY_MS
153
+ );
154
+ }
155
+
156
+ /** Status word for the latest run, with partial results marked. */
157
+ export function subagentStatusLabel(record: SubagentRecord): string {
158
+ return record.partial && record.status === "completed" ? "partial" : record.status;
159
+ }
@@ -0,0 +1,33 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { isKeyRelease, matchesKey } from "@earendil-works/pi-tui";
3
+
4
+ import type { SubagentManager } from "../manager.ts";
5
+
6
+ /**
7
+ * Ctrl+B moves all running foreground agents to the background. It acts only while one runs
8
+ * and no dialog is open. Otherwise the key keeps its editor meaning. Returns the cleanup function.
9
+ */
10
+ export function installBackgroundShortcut(
11
+ pi: ExtensionAPI,
12
+ ctx: ExtensionContext,
13
+ manager: SubagentManager,
14
+ ): () => void {
15
+ let openPrompts = 0;
16
+ const offStart = pi.on("ui_prompt_start", () => {
17
+ openPrompts++;
18
+ });
19
+ const offEnd = pi.on("ui_prompt_end", () => {
20
+ openPrompts = Math.max(0, openPrompts - 1);
21
+ });
22
+ const offInput = ctx.ui.onTerminalInput((data) => {
23
+ if (isKeyRelease(data) || !matchesKey(data, "ctrl+b")) return undefined;
24
+ if (openPrompts > 0 || !manager.hasForeground()) return undefined;
25
+ manager.moveForegroundToBackground();
26
+ return { consume: true };
27
+ });
28
+ return () => {
29
+ offStart();
30
+ offEnd();
31
+ offInput();
32
+ };
33
+ }