@timmyjl12/pi-subagents 0.0.0-stage → 0.21.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/CHANGELOG.md +862 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/README.md +1125 -3
- package/SECURITY.md +97 -0
- package/dist/abortable.d.ts +12 -0
- package/dist/abortable.js +42 -0
- package/dist/active-agents-prompt.d.ts +40 -0
- package/dist/active-agents-prompt.js +98 -0
- package/dist/advisor-status.d.ts +16 -0
- package/dist/advisor-status.js +74 -0
- package/dist/agent-color.d.ts +35 -0
- package/dist/agent-color.js +131 -0
- package/dist/agent-file-toggle.d.ts +125 -0
- package/dist/agent-file-toggle.js +264 -0
- package/dist/agent-manager.d.ts +872 -0
- package/dist/agent-manager.js +2910 -0
- package/dist/agent-runner.d.ts +358 -0
- package/dist/agent-runner.js +1219 -0
- package/dist/agent-types.d.ts +142 -0
- package/dist/agent-types.js +315 -0
- package/dist/awaited-result.d.ts +37 -0
- package/dist/awaited-result.js +150 -0
- package/dist/child-context.d.ts +15 -0
- package/dist/child-context.js +181 -0
- package/dist/child-session-shutdown.d.ts +21 -0
- package/dist/child-session-shutdown.js +97 -0
- package/dist/cleanup-plans.d.ts +10 -0
- package/dist/cleanup-plans.js +112 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +73 -0
- package/dist/cross-extension-rpc.js +192 -0
- package/dist/custom-agents.d.ts +79 -0
- package/dist/custom-agents.js +583 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +125 -0
- package/dist/enabled-models.d.ts +49 -0
- package/dist/enabled-models.js +145 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/error-log.d.ts +64 -0
- package/dist/error-log.js +176 -0
- package/dist/force-main-model.d.ts +21 -0
- package/dist/force-main-model.js +28 -0
- package/dist/goal-bridge.d.ts +155 -0
- package/dist/goal-bridge.js +305 -0
- package/dist/group-join.d.ts +36 -0
- package/dist/group-join.js +161 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +6390 -0
- package/dist/invocation-config.d.ts +164 -0
- package/dist/invocation-config.js +158 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/mention-clone.d.ts +87 -0
- package/dist/mention-clone.js +178 -0
- package/dist/mention.d.ts +81 -0
- package/dist/mention.js +131 -0
- package/dist/model-resolver.d.ts +36 -0
- package/dist/model-resolver.js +95 -0
- package/dist/model-scope.d.ts +49 -0
- package/dist/model-scope.js +48 -0
- package/dist/nested-tools.d.ts +76 -0
- package/dist/nested-tools.js +393 -0
- package/dist/output-diagnostics.d.ts +11 -0
- package/dist/output-diagnostics.js +64 -0
- package/dist/output-file.d.ts +64 -0
- package/dist/output-file.js +351 -0
- package/dist/prompts.d.ts +61 -0
- package/dist/prompts.js +94 -0
- package/dist/recovery.d.ts +56 -0
- package/dist/recovery.js +341 -0
- package/dist/report-cleanup.d.ts +204 -0
- package/dist/report-cleanup.js +1632 -0
- package/dist/report-store.d.ts +738 -0
- package/dist/report-store.js +3612 -0
- package/dist/schedule-store.d.ts +52 -0
- package/dist/schedule-store.js +240 -0
- package/dist/schedule.d.ts +121 -0
- package/dist/schedule.js +420 -0
- package/dist/settings.d.ts +388 -0
- package/dist/settings.js +268 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/standalone-fallback.d.ts +30 -0
- package/dist/standalone-fallback.js +239 -0
- package/dist/status-note.d.ts +61 -0
- package/dist/status-note.js +85 -0
- package/dist/structured-output.d.ts +61 -0
- package/dist/structured-output.js +112 -0
- package/dist/terminal-progress.d.ts +115 -0
- package/dist/terminal-progress.js +206 -0
- package/dist/types.d.ts +411 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-mention.d.ts +82 -0
- package/dist/ui/agent-mention.js +187 -0
- package/dist/ui/agent-widget.d.ts +304 -0
- package/dist/ui/agent-widget.js +770 -0
- package/dist/ui/cleanup-preview.d.ts +59 -0
- package/dist/ui/cleanup-preview.js +466 -0
- package/dist/ui/conversation-viewer.d.ts +105 -0
- package/dist/ui/conversation-viewer.js +544 -0
- package/dist/ui/fleet-list.d.ts +183 -0
- package/dist/ui/fleet-list.js +494 -0
- package/dist/ui/fleet-overlay.d.ts +203 -0
- package/dist/ui/fleet-overlay.js +887 -0
- package/dist/ui/hub-feed.d.ts +52 -0
- package/dist/ui/hub-feed.js +148 -0
- package/dist/ui/native-transcript.d.ts +33 -0
- package/dist/ui/native-transcript.js +234 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +94 -0
- package/dist/ui/select-item.d.ts +27 -0
- package/dist/ui/select-item.js +34 -0
- package/dist/ui/tool-progress.d.ts +22 -0
- package/dist/ui/tool-progress.js +56 -0
- package/dist/ui/viewer-keys.d.ts +20 -0
- package/dist/ui/viewer-keys.js +17 -0
- package/dist/ui/workflow-card.d.ts +175 -0
- package/dist/ui/workflow-card.js +332 -0
- package/dist/ui/workflow-dialog.d.ts +305 -0
- package/dist/ui/workflow-dialog.js +848 -0
- package/dist/ui/workflow-menu.d.ts +60 -0
- package/dist/ui/workflow-menu.js +147 -0
- package/dist/usage.d.ts +147 -0
- package/dist/usage.js +147 -0
- package/dist/workflow/collisions.d.ts +95 -0
- package/dist/workflow/collisions.js +88 -0
- package/dist/workflow/entry.d.ts +32 -0
- package/dist/workflow/entry.js +29 -0
- package/dist/workflow/host.d.ts +65 -0
- package/dist/workflow/host.js +477 -0
- package/dist/workflow/journal.d.ts +113 -0
- package/dist/workflow/journal.js +177 -0
- package/dist/workflow/json-schema.d.ts +51 -0
- package/dist/workflow/json-schema.js +111 -0
- package/dist/workflow/meta.d.ts +67 -0
- package/dist/workflow/meta.js +317 -0
- package/dist/workflow/progress.d.ts +224 -0
- package/dist/workflow/progress.js +361 -0
- package/dist/workflow/runtime.d.ts +373 -0
- package/dist/workflow/runtime.js +919 -0
- package/dist/workflow/saved.d.ts +90 -0
- package/dist/workflow/saved.js +203 -0
- package/dist/workflow/task.d.ts +145 -0
- package/dist/workflow/task.js +213 -0
- package/dist/workflow/tool-description.d.ts +43 -0
- package/dist/workflow/tool-description.js +204 -0
- package/dist/workflow/worker-source.d.ts +47 -0
- package/dist/workflow/worker-source.js +778 -0
- package/dist/worktree.d.ts +52 -0
- package/dist/worktree.js +164 -0
- package/dist/xml.d.ts +10 -0
- package/dist/xml.js +12 -0
- package/docs/DEVELOPMENT.md +40 -0
- package/docs/artifacts.md +93 -0
- package/docs/recovery.md +62 -0
- package/docs/rpc.md +252 -0
- package/docs/runtime-performance.md +53 -0
- package/docs/workflows.md +467 -0
- package/examples/agent-tool-description.md +43 -0
- package/examples/workflows/compose.js +51 -0
- package/examples/workflows/fan-out-audit.js +47 -0
- package/examples/workflows/gated-fix.js +60 -0
- package/examples/workflows/lib/count-child.js +27 -0
- package/examples/workflows/review-panel.js +66 -0
- package/examples/workflows/structured-findings.js +78 -0
- package/package.json +75 -6
- package/src/abortable.ts +43 -0
- package/src/active-agents-prompt.ts +115 -0
- package/src/advisor-status.ts +74 -0
- package/src/agent-color.ts +169 -0
- package/src/agent-file-toggle.ts +273 -0
- package/src/agent-manager.ts +3312 -0
- package/src/agent-runner.ts +1500 -0
- package/src/agent-types.ts +390 -0
- package/src/awaited-result.ts +187 -0
- package/src/child-context.ts +173 -0
- package/src/child-session-shutdown.ts +114 -0
- package/src/cleanup-plans.ts +112 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +257 -0
- package/src/custom-agents.ts +689 -0
- package/src/default-agents.ts +129 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/error-log.ts +202 -0
- package/src/force-main-model.ts +29 -0
- package/src/goal-bridge.ts +468 -0
- package/src/group-join.ts +188 -0
- package/src/index.ts +6856 -0
- package/src/invocation-config.ts +276 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +221 -0
- package/src/mention.ts +141 -0
- package/src/model-resolver.ts +118 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +553 -0
- package/src/output-diagnostics.ts +68 -0
- package/src/output-file.ts +380 -0
- package/src/prompts.ts +151 -0
- package/src/recovery.ts +320 -0
- package/src/report-cleanup.ts +2044 -0
- package/src/report-store.ts +4130 -0
- package/src/schedule-store.ts +244 -0
- package/src/schedule.ts +450 -0
- package/src/settings.ts +632 -0
- package/src/skill-loader.ts +102 -0
- package/src/standalone-fallback.ts +195 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/terminal-progress.ts +215 -0
- package/src/types.ts +424 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-widget.ts +866 -0
- package/src/ui/cleanup-preview.ts +518 -0
- package/src/ui/conversation-viewer.ts +527 -0
- package/src/ui/fleet-list.ts +563 -0
- package/src/ui/fleet-overlay.ts +1048 -0
- package/src/ui/hub-feed.ts +179 -0
- package/src/ui/native-transcript.ts +224 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/tool-progress.ts +67 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +470 -0
- package/src/ui/workflow-dialog.ts +1119 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +217 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +524 -0
- package/src/workflow/journal.ts +221 -0
- package/src/workflow/json-schema.ts +128 -0
- package/src/workflow/meta.ts +325 -0
- package/src/workflow/progress.ts +550 -0
- package/src/workflow/runtime.ts +1342 -0
- package/src/workflow/saved.ts +217 -0
- package/src/workflow/task.ts +313 -0
- package/src/workflow/tool-description.ts +205 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +205 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,770 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-widget.ts — Compact running/completed agent list above or below the editor.
|
|
3
|
+
*
|
|
4
|
+
* Displays a tree of agents with animated spinners, live stats, and activity descriptions.
|
|
5
|
+
* Uses the callback form of setWidget for themed rendering.
|
|
6
|
+
*/
|
|
7
|
+
import { Editor, isKeyRelease, isKeyRepeat, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
|
|
8
|
+
import { formatAdvisorStatus } from "../advisor-status.js";
|
|
9
|
+
import { renderAgentName } from "../agent-color.js";
|
|
10
|
+
import { isTopLevelAgent } from "../agent-manager.js";
|
|
11
|
+
import { getConfig } from "../agent-types.js";
|
|
12
|
+
import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent } from "../usage.js";
|
|
13
|
+
// ---- Constants ----
|
|
14
|
+
/** Maximum number of rendered lines before overflow collapse kicks in. */
|
|
15
|
+
const MAX_WIDGET_LINES = 12;
|
|
16
|
+
/** Header, activity and advisor status form one indivisible running card. */
|
|
17
|
+
const RUNNING_CARD_LINES = 3;
|
|
18
|
+
/** Braille spinner frames for animated running indicator. */
|
|
19
|
+
export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
20
|
+
/** Statuses that indicate an error/non-success outcome (used for linger behavior and icon rendering). */
|
|
21
|
+
export const ERROR_STATUSES = new Set(["error", "aborted", "steered", "stopped"]);
|
|
22
|
+
/** Tool name → human-readable action for activity descriptions. */
|
|
23
|
+
const TOOL_DISPLAY = {
|
|
24
|
+
read: "reading",
|
|
25
|
+
bash: "running command",
|
|
26
|
+
edit: "editing",
|
|
27
|
+
write: "writing",
|
|
28
|
+
grep: "searching",
|
|
29
|
+
find: "finding files",
|
|
30
|
+
ls: "listing",
|
|
31
|
+
};
|
|
32
|
+
// ---- Formatting helpers ----
|
|
33
|
+
/** Apply foreground styling while restoring it after nested foreground/full ANSI resets. */
|
|
34
|
+
export function fgPreservingNestedStyles(theme, color, text) {
|
|
35
|
+
const styledEmpty = theme.fg(color, "");
|
|
36
|
+
const styleStart = styledEmpty.replace(/\u001b\[(?:0|39)m/g, "");
|
|
37
|
+
return theme.fg(color, text.replace(/\u001b\[(?:0|39)m/g, reset => `${reset}${styleStart}`));
|
|
38
|
+
}
|
|
39
|
+
/** Format a token count compactly: "33.8k token", "1.2M token". */
|
|
40
|
+
export function formatTokens(count) {
|
|
41
|
+
if (count >= 1_000_000)
|
|
42
|
+
return `${(count / 1_000_000).toFixed(1)}M token`;
|
|
43
|
+
if (count >= 1_000)
|
|
44
|
+
return `${(count / 1_000).toFixed(1)}k token`;
|
|
45
|
+
return `${count} token`;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Format a cost as `~$0.0042`, or "" when there is nothing to show.
|
|
49
|
+
*
|
|
50
|
+
* The tilde is load-bearing: this is pi's own estimate from the model's listed
|
|
51
|
+
* rates, not a billed figure, and the surfaces that print it sit next to token
|
|
52
|
+
* counts that ARE exact.
|
|
53
|
+
*
|
|
54
|
+
* Nothing is printed for zero, which is also what a model with no pricing data
|
|
55
|
+
* reports: `$0.00` beside a local model's tokens would claim its cost was
|
|
56
|
+
* measured and found to be nothing, rather than never measured at all. For the
|
|
57
|
+
* same reason a real cost too small for four decimals reads `<$0.0001` — it was
|
|
58
|
+
* measured, and rounding it to `~$0.0000` would say the opposite.
|
|
59
|
+
*/
|
|
60
|
+
export function formatCost(cost) {
|
|
61
|
+
if (!(cost > 0))
|
|
62
|
+
return ""; // also catches NaN
|
|
63
|
+
if (cost < 0.0001)
|
|
64
|
+
return "<$0.0001";
|
|
65
|
+
if (cost >= 1)
|
|
66
|
+
return `~$${cost.toFixed(2)}`;
|
|
67
|
+
// Under a dollar: cents at minimum, four decimals at most, nothing trailing.
|
|
68
|
+
// Most single runs land between a tenth of a cent and a dime, where rounding
|
|
69
|
+
// to cents would collapse a 4x difference in spend into the same figure.
|
|
70
|
+
const rounded = Number(cost.toFixed(4));
|
|
71
|
+
const decimals = (String(rounded).split(".")[1] ?? "").length;
|
|
72
|
+
return `~$${rounded.toFixed(Math.max(2, decimals))}`;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Token count with optional context-fill % and compaction-count annotations.
|
|
76
|
+
* Thresholds for percent: <70% dim, 70–85% warning, ≥85% error.
|
|
77
|
+
* Compaction count rendered as `⇊N` in dim.
|
|
78
|
+
*
|
|
79
|
+
* "12.3k token" — no annotations
|
|
80
|
+
* "12.3k token (45%)" — percent only
|
|
81
|
+
* "12.3k token (⇊2)" — compactions only (e.g. right after compact)
|
|
82
|
+
* "12.3k token (45% · ⇊2)" — both
|
|
83
|
+
*/
|
|
84
|
+
export function formatSessionTokens(tokens, percent, theme, compactions = 0) {
|
|
85
|
+
const tokenStr = formatTokens(tokens);
|
|
86
|
+
const annot = [];
|
|
87
|
+
if (percent !== null) {
|
|
88
|
+
const color = percent >= 85 ? "error" : percent >= 70 ? "warning" : "dim";
|
|
89
|
+
annot.push(theme.fg(color, `${Math.round(percent)}%`));
|
|
90
|
+
}
|
|
91
|
+
if (compactions > 0) {
|
|
92
|
+
annot.push(theme.fg("dim", `⇊${compactions}`));
|
|
93
|
+
}
|
|
94
|
+
if (annot.length === 0)
|
|
95
|
+
return tokenStr;
|
|
96
|
+
return `${tokenStr} (${annot.join(" · ")})`;
|
|
97
|
+
}
|
|
98
|
+
/** Format turn count with optional max limit: "↻5≤30" or "↻5". */
|
|
99
|
+
export function formatTurns(turnCount, maxTurns) {
|
|
100
|
+
return maxTurns != null ? `↻${turnCount}≤${maxTurns}` : `↻${turnCount}`;
|
|
101
|
+
}
|
|
102
|
+
/** Format milliseconds as human-readable duration. */
|
|
103
|
+
export function formatMs(ms) {
|
|
104
|
+
return `${(ms / 1000).toFixed(1)}s`;
|
|
105
|
+
}
|
|
106
|
+
/** Format duration from start/completed timestamps. */
|
|
107
|
+
export function formatDuration(startedAt, completedAt) {
|
|
108
|
+
if (completedAt)
|
|
109
|
+
return formatMs(completedAt - startedAt);
|
|
110
|
+
return `${formatMs(Date.now() - startedAt)} (running)`;
|
|
111
|
+
}
|
|
112
|
+
/** Get display name for any agent type (built-in or custom). */
|
|
113
|
+
export function getDisplayName(type) {
|
|
114
|
+
return getConfig(type).displayName;
|
|
115
|
+
}
|
|
116
|
+
/** Short label for prompt mode: "twin" for append, nothing for replace (the default). */
|
|
117
|
+
export function getPromptModeLabel(type) {
|
|
118
|
+
const config = getConfig(type);
|
|
119
|
+
return config.promptMode === "append" ? "twin" : undefined;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Mode label is not included — callers add it where they want it.
|
|
123
|
+
*
|
|
124
|
+
* Both model forms come back so each surface can pick by width; the
|
|
125
|
+
* "(asked X)" annotation is applied here rather than by callers, so a value the
|
|
126
|
+
* spawn did not honor cannot be rendered as though it had been (#182).
|
|
127
|
+
*/
|
|
128
|
+
export function buildInvocationTags(invocation) {
|
|
129
|
+
const tags = [];
|
|
130
|
+
if (!invocation)
|
|
131
|
+
return { tags };
|
|
132
|
+
const asked = (value, requested) => value && requested && requested !== value ? `${value} (asked ${requested})` : value;
|
|
133
|
+
const thinking = asked(invocation.thinking, invocation.requestedThinking);
|
|
134
|
+
if (thinking)
|
|
135
|
+
tags.push(`thinking: ${thinking}`);
|
|
136
|
+
if (invocation.isolated)
|
|
137
|
+
tags.push("isolated");
|
|
138
|
+
if (invocation.isolation === "worktree")
|
|
139
|
+
tags.push("worktree");
|
|
140
|
+
if (invocation.inheritContext)
|
|
141
|
+
tags.push("inherit context");
|
|
142
|
+
if (invocation.runInBackground)
|
|
143
|
+
tags.push("background");
|
|
144
|
+
if (invocation.maxTurns != null)
|
|
145
|
+
tags.push(`max turns: ${invocation.maxTurns}`);
|
|
146
|
+
return {
|
|
147
|
+
modelName: asked(invocation.modelName, invocation.requestedModel),
|
|
148
|
+
modelId: asked(invocation.modelId, invocation.requestedModel),
|
|
149
|
+
tags,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Make externally supplied text safe to place in ONE terminal row.
|
|
154
|
+
*
|
|
155
|
+
* Every entry an extension returns from `render()` is ONE terminal row: pi's
|
|
156
|
+
* TUI pushes each array element verbatim (`tui.js` `lines.push(line)`) and
|
|
157
|
+
* measures the block's height as `childLines.length`. A literal `\n` — or `\t`,
|
|
158
|
+
* or any other control byte — inside an entry makes the terminal advance a row
|
|
159
|
+
* the renderer never counted, permanently desynchronising its line diff. The
|
|
160
|
+
* visible symptom is a frozen duplicate row left on screen above and rows
|
|
161
|
+
* clipped below (the footer/statusline among them). Truncation cannot rescue
|
|
162
|
+
* it either: pi-tui's `visibleWidth` counts control characters as zero-width,
|
|
163
|
+
* so such a line passes the width check and still wraps in the terminal.
|
|
164
|
+
*
|
|
165
|
+
* Agent descriptions and error messages are the realistic carriers — both are
|
|
166
|
+
* free text (a model-supplied tool argument; a raw `Error.message`, which is
|
|
167
|
+
* frequently multi-line). ANSI styling is applied AFTER this runs, so stripping
|
|
168
|
+
* ESC here doubles as a terminal-injection guard for the plain fragments.
|
|
169
|
+
*
|
|
170
|
+
* Internal whitespace is preserved; see {@link sanitizeRowText} to collapse it.
|
|
171
|
+
*/
|
|
172
|
+
export function flattenRow(text) {
|
|
173
|
+
return text
|
|
174
|
+
// Whole escape sequences go, not just the ESC byte: a stripped-but-not-
|
|
175
|
+
// consumed CSI would leave its `[31m` payload as visible garbage.
|
|
176
|
+
.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, " ") // OSC (hyperlinks, titles)
|
|
177
|
+
.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, " ") // CSI (cursor, erase, SGR)
|
|
178
|
+
.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ");
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* {@link flattenRow} plus whitespace collapsing, for short single-line labels
|
|
182
|
+
* (descriptions, names, error heads) where runs of spaces carry nothing.
|
|
183
|
+
* Use {@link flattenRow} instead where indentation is meaningful.
|
|
184
|
+
*/
|
|
185
|
+
export function sanitizeRowText(text) {
|
|
186
|
+
return flattenRow(text).replace(/\s+/g, " ").trim();
|
|
187
|
+
}
|
|
188
|
+
/** Truncate text to a single line, max `len` chars. */
|
|
189
|
+
function truncateLine(text, len = 60) {
|
|
190
|
+
const line = sanitizeRowText(text.split("\n").find(l => l.trim()) ?? "");
|
|
191
|
+
if (line.length <= len)
|
|
192
|
+
return line;
|
|
193
|
+
return line.slice(0, len) + "…";
|
|
194
|
+
}
|
|
195
|
+
/** Build a human-readable activity string from currently-running tools or response text. */
|
|
196
|
+
export function describeActivity(activeTools, responseText) {
|
|
197
|
+
if (activeTools.size > 0) {
|
|
198
|
+
const groups = new Map();
|
|
199
|
+
for (const toolName of activeTools.values()) {
|
|
200
|
+
const action = TOOL_DISPLAY[toolName] ?? toolName;
|
|
201
|
+
groups.set(action, (groups.get(action) ?? 0) + 1);
|
|
202
|
+
}
|
|
203
|
+
const parts = [];
|
|
204
|
+
for (const [action, count] of groups) {
|
|
205
|
+
if (count > 1) {
|
|
206
|
+
parts.push(`${action} ${count} ${action === "searching" ? "patterns" : "files"}`);
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
parts.push(action);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return parts.join(", ") + "…";
|
|
213
|
+
}
|
|
214
|
+
// No tools active — show truncated response text if available
|
|
215
|
+
if (responseText && responseText.trim().length > 0) {
|
|
216
|
+
return truncateLine(responseText);
|
|
217
|
+
}
|
|
218
|
+
return "thinking…";
|
|
219
|
+
}
|
|
220
|
+
// ---- Widget manager ----
|
|
221
|
+
export class AgentWidget {
|
|
222
|
+
manager;
|
|
223
|
+
agentActivity;
|
|
224
|
+
mode;
|
|
225
|
+
showCost;
|
|
226
|
+
showModel;
|
|
227
|
+
placement;
|
|
228
|
+
uiCtx;
|
|
229
|
+
widgetFrame = 0;
|
|
230
|
+
widgetInterval;
|
|
231
|
+
/** One-shot timer that re-runs update() when the earliest finished row expires. */
|
|
232
|
+
expiryTimer;
|
|
233
|
+
/** Wall-clock time each finished agent was first seen finished. */
|
|
234
|
+
finishedAt = new Map();
|
|
235
|
+
/** How long a completed row lingers without any turn activity. */
|
|
236
|
+
static FINISHED_LINGER_MS = 5000;
|
|
237
|
+
/** Errors/aborts linger longer so they are not missed. */
|
|
238
|
+
static ERROR_LINGER_MS = 10000;
|
|
239
|
+
/** Tracks how many turns each finished agent has survived. Key: agent ID, Value: turns since finished. */
|
|
240
|
+
finishedTurnAge = new Map();
|
|
241
|
+
/** How many extra turns errors/aborted agents linger (completed agents clear after 1 turn). */
|
|
242
|
+
static ERROR_LINGER_TURNS = 2;
|
|
243
|
+
/** Whether the widget callback is currently registered with the TUI. */
|
|
244
|
+
widgetRegistered = false;
|
|
245
|
+
registeredPlacement;
|
|
246
|
+
inputUnsub;
|
|
247
|
+
hub;
|
|
248
|
+
/** Cached TUI reference from widget factory callback, used for repaint and focus checks. */
|
|
249
|
+
tui;
|
|
250
|
+
/** Last status bar text, used to avoid redundant setStatus calls. */
|
|
251
|
+
lastStatusText;
|
|
252
|
+
constructor(manager, agentActivity,
|
|
253
|
+
/**
|
|
254
|
+
* Read live at render time. Selects which agents the widget shows — see
|
|
255
|
+
* `WidgetMode`. Defaults to `"all"`, matching the extension's own default.
|
|
256
|
+
*/
|
|
257
|
+
mode = () => "all",
|
|
258
|
+
/**
|
|
259
|
+
* Read live at render time, like `mode`. Whether running agents show an
|
|
260
|
+
* estimated cost beside their token count. Defaults to off — the extension
|
|
261
|
+
* supplies the user's `showCost` setting.
|
|
262
|
+
*/
|
|
263
|
+
showCost = () => false,
|
|
264
|
+
/**
|
|
265
|
+
* Read live at render time, like `mode`. Whether running agents name the
|
|
266
|
+
* model driving them and the thinking level it is running at. Defaults to
|
|
267
|
+
* off — the extension supplies the user's `showModel` setting — because the
|
|
268
|
+
* row is already dense and the same pair is on the tool result and in the
|
|
269
|
+
* conversation viewer unconditionally.
|
|
270
|
+
*/
|
|
271
|
+
showModel = () => false,
|
|
272
|
+
/** Read live; changing placement remounts the same widget key once. */
|
|
273
|
+
placement = () => "above") {
|
|
274
|
+
this.manager = manager;
|
|
275
|
+
this.agentActivity = agentActivity;
|
|
276
|
+
this.mode = mode;
|
|
277
|
+
this.showCost = showCost;
|
|
278
|
+
this.showModel = showModel;
|
|
279
|
+
this.placement = placement;
|
|
280
|
+
}
|
|
281
|
+
/** Reuse the extension's canonical Agent Hub, without an inline navigation mode. */
|
|
282
|
+
setHubOpener(hub) {
|
|
283
|
+
this.hub = hub;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Agents eligible for the widget, per the current `WidgetMode`:
|
|
287
|
+
* - `off`: none (the widget's existing empty-state path hides it entirely).
|
|
288
|
+
* - `background`: drop only agents *known* to be foreground
|
|
289
|
+
* (`isBackground === false`); keep everything else — background, queued,
|
|
290
|
+
* scheduled, or RPC-spawned (`undefined`). Keying off the `isBackground`
|
|
291
|
+
* record flag rather than the UI-only `invocation` snapshot (which only the
|
|
292
|
+
* Agent-tool path sets), and excluding rather than allow-listing, means
|
|
293
|
+
* only proven-foreground runs drop out — nothing else silently vanishes.
|
|
294
|
+
* - `all`: every agent.
|
|
295
|
+
*/
|
|
296
|
+
widgetAgents() {
|
|
297
|
+
const all = this.manager.listAgents().filter(isTopLevelAgent);
|
|
298
|
+
switch (this.mode()) {
|
|
299
|
+
case "off": return [];
|
|
300
|
+
case "background": return all.filter(a => a.isBackground !== false);
|
|
301
|
+
default: return all;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/** Set the UI context (grabbed from first tool execution). */
|
|
305
|
+
setUICtx(ctx) {
|
|
306
|
+
if (ctx !== this.uiCtx) {
|
|
307
|
+
// UICtx changed — force re-registration and detach the old input listener.
|
|
308
|
+
this.inputUnsub?.();
|
|
309
|
+
this.uiCtx = ctx;
|
|
310
|
+
this.widgetRegistered = false;
|
|
311
|
+
this.registeredPlacement = undefined;
|
|
312
|
+
this.tui = undefined;
|
|
313
|
+
this.lastStatusText = undefined;
|
|
314
|
+
this.inputUnsub = ctx.onTerminalInput?.(data => {
|
|
315
|
+
if (ctx !== this.uiCtx || !this.hub)
|
|
316
|
+
return undefined;
|
|
317
|
+
if (isKeyRelease(data) || isKeyRepeat(data) || !matchesKey(data, "left") || ctx.getEditorText?.() !== "")
|
|
318
|
+
return undefined;
|
|
319
|
+
// The Hub owns every key while it holds the keyboard — re-entering it
|
|
320
|
+
// here would stack a second overlay and swallow the first one's input.
|
|
321
|
+
if (this.hub.isOpen?.())
|
|
322
|
+
return undefined;
|
|
323
|
+
// "off" retires the key with the list, like the retired fleetView: false.
|
|
324
|
+
if (this.mode() === "off")
|
|
325
|
+
return undefined;
|
|
326
|
+
// Focus distinguishes the real prompt from a detached empty editor
|
|
327
|
+
// underneath a dialog — but only with a TUI to read it from. The list
|
|
328
|
+
// may never have mounted (a foreground-only roster under "background"),
|
|
329
|
+
// so the reference is acquired on demand rather than awaited.
|
|
330
|
+
if (this.tui === undefined)
|
|
331
|
+
this.probeTui();
|
|
332
|
+
if (this.tui === undefined)
|
|
333
|
+
return undefined;
|
|
334
|
+
const focused = this.tui.getFocusedComponent?.() ?? this.tui.focusedComponent;
|
|
335
|
+
if (focused != null && !(focused instanceof Editor))
|
|
336
|
+
return undefined;
|
|
337
|
+
const hasContent = this.hub.hasContent?.() ?? this.manager.listAgents().some(isTopLevelAgent);
|
|
338
|
+
if (!hasContent)
|
|
339
|
+
return undefined;
|
|
340
|
+
this.hub.open();
|
|
341
|
+
return { consume: true };
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Called on each new turn (tool_execution_start).
|
|
347
|
+
* Ages finished agents and clears those that have lingered long enough.
|
|
348
|
+
*/
|
|
349
|
+
onTurnStart() {
|
|
350
|
+
// Age all finished agents
|
|
351
|
+
for (const [id, age] of this.finishedTurnAge) {
|
|
352
|
+
this.finishedTurnAge.set(id, age + 1);
|
|
353
|
+
}
|
|
354
|
+
// Trigger a widget refresh (will filter out expired agents)
|
|
355
|
+
this.update();
|
|
356
|
+
}
|
|
357
|
+
/** Ensure the widget update timer is running. */
|
|
358
|
+
ensureTimer() {
|
|
359
|
+
if (!this.widgetInterval) {
|
|
360
|
+
// The spinner only animates while something is running/queued; update()
|
|
361
|
+
// stops this interval as soon as nothing active remains.
|
|
362
|
+
this.widgetInterval = setInterval(() => this.update(), 80);
|
|
363
|
+
this.widgetInterval.unref?.();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/** Check if a finished agent should still be shown in the widget. */
|
|
367
|
+
shouldShowFinished(agentId, status) {
|
|
368
|
+
const age = this.finishedTurnAge.get(agentId) ?? 0;
|
|
369
|
+
const maxAge = ERROR_STATUSES.has(status) ? AgentWidget.ERROR_LINGER_TURNS : 1;
|
|
370
|
+
if (age >= maxAge)
|
|
371
|
+
return false;
|
|
372
|
+
return Date.now() < this.finishedExpiry(agentId, status);
|
|
373
|
+
}
|
|
374
|
+
/** Wall-clock expiry of a finished row (seeds the finish time on first sight). */
|
|
375
|
+
finishedExpiry(agentId, status) {
|
|
376
|
+
let at = this.finishedAt.get(agentId);
|
|
377
|
+
if (at === undefined) {
|
|
378
|
+
at = Date.now();
|
|
379
|
+
this.finishedAt.set(agentId, at);
|
|
380
|
+
}
|
|
381
|
+
return at + (ERROR_STATUSES.has(status) ? AgentWidget.ERROR_LINGER_MS : AgentWidget.FINISHED_LINGER_MS);
|
|
382
|
+
}
|
|
383
|
+
/** Record an agent as finished (call when agent completes). */
|
|
384
|
+
markFinished(agentId) {
|
|
385
|
+
if (!this.finishedTurnAge.has(agentId)) {
|
|
386
|
+
this.finishedTurnAge.set(agentId, 0);
|
|
387
|
+
}
|
|
388
|
+
if (!this.finishedAt.has(agentId))
|
|
389
|
+
this.finishedAt.set(agentId, Date.now());
|
|
390
|
+
}
|
|
391
|
+
stopInterval() {
|
|
392
|
+
if (this.widgetInterval) {
|
|
393
|
+
clearInterval(this.widgetInterval);
|
|
394
|
+
this.widgetInterval = undefined;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
clearExpiryTimer() {
|
|
398
|
+
if (this.expiryTimer) {
|
|
399
|
+
clearTimeout(this.expiryTimer);
|
|
400
|
+
this.expiryTimer = undefined;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/** Schedule one unref'd update() at the given wall-clock time. */
|
|
404
|
+
scheduleExpiry(at) {
|
|
405
|
+
this.clearExpiryTimer();
|
|
406
|
+
this.expiryTimer = setTimeout(() => {
|
|
407
|
+
this.expiryTimer = undefined;
|
|
408
|
+
this.update();
|
|
409
|
+
}, Math.max(0, at - Date.now()) + 20);
|
|
410
|
+
this.expiryTimer.unref?.();
|
|
411
|
+
}
|
|
412
|
+
/** True while the widget holds a repaint timer (interval or expiry). */
|
|
413
|
+
hasPendingTimers() {
|
|
414
|
+
return this.widgetInterval !== undefined || this.expiryTimer !== undefined;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Drop an agent's finished-age (call when a settled agent starts running
|
|
418
|
+
* again, i.e. a background resume). markFinished only seeds an age it has not
|
|
419
|
+
* seen before, so a resumed agent would otherwise keep the age from its
|
|
420
|
+
* previous run — already past the linger limit, hiding the new run's
|
|
421
|
+
* completion line entirely.
|
|
422
|
+
*/
|
|
423
|
+
markRunning(agentId) {
|
|
424
|
+
this.finishedTurnAge.delete(agentId);
|
|
425
|
+
this.finishedAt.delete(agentId);
|
|
426
|
+
}
|
|
427
|
+
/** Render a finished agent line. */
|
|
428
|
+
renderFinishedLine(a, theme) {
|
|
429
|
+
const modeLabel = getPromptModeLabel(a.type);
|
|
430
|
+
const duration = formatMs((a.completedAt ?? Date.now()) - a.startedAt);
|
|
431
|
+
let icon;
|
|
432
|
+
let statusText;
|
|
433
|
+
if (a.status === "completed") {
|
|
434
|
+
icon = theme.fg("success", "✓");
|
|
435
|
+
statusText = "";
|
|
436
|
+
}
|
|
437
|
+
else if (a.status === "steered") {
|
|
438
|
+
icon = theme.fg("warning", "✓");
|
|
439
|
+
statusText = theme.fg("warning", " (turn limit)");
|
|
440
|
+
}
|
|
441
|
+
else if (a.status === "stopped") {
|
|
442
|
+
icon = theme.fg("dim", "■");
|
|
443
|
+
statusText = theme.fg("dim", " stopped");
|
|
444
|
+
}
|
|
445
|
+
else if (a.status === "error") {
|
|
446
|
+
icon = theme.fg("error", "✗");
|
|
447
|
+
// Error messages are routinely multi-line; they must be flattened before
|
|
448
|
+
// the slice, or a truncated tail keeps the newline that breaks the row.
|
|
449
|
+
const errMsg = a.error ? `: ${sanitizeRowText(a.error).slice(0, 60)}` : "";
|
|
450
|
+
statusText = theme.fg("error", ` error${errMsg}`);
|
|
451
|
+
}
|
|
452
|
+
else {
|
|
453
|
+
// aborted
|
|
454
|
+
icon = theme.fg("error", "✗");
|
|
455
|
+
statusText = theme.fg("warning", " aborted");
|
|
456
|
+
}
|
|
457
|
+
const parts = [];
|
|
458
|
+
const activity = this.agentActivity.get(a.id);
|
|
459
|
+
if (activity)
|
|
460
|
+
parts.push(formatTurns(activity.turnCount, activity.maxTurns));
|
|
461
|
+
if (a.toolUses > 0)
|
|
462
|
+
parts.push(`${a.toolUses} tool use${a.toolUses === 1 ? "" : "s"}`);
|
|
463
|
+
// From the record, not the activity tracker: that entry is deleted the
|
|
464
|
+
// moment an agent finishes, and "what did it cost" is a question asked
|
|
465
|
+
// about finished agents.
|
|
466
|
+
const costText = this.showCost() ? formatCost(getLifetimeCost(a.lifetimeUsage)) : "";
|
|
467
|
+
if (costText)
|
|
468
|
+
parts.push(costText);
|
|
469
|
+
parts.push(duration);
|
|
470
|
+
const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
|
|
471
|
+
return `${icon} ${renderAgentName(a.type, theme, { fallbackColor: "dim" })}${modeTag} ${theme.fg("dim", sanitizeRowText(a.description))} ${theme.fg("dim", "·")} ${theme.fg("dim", parts.join(" · "))}${statusText}`;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Render the widget content. Called from the registered widget's render() callback,
|
|
475
|
+
* reading live state each time instead of capturing it in a closure.
|
|
476
|
+
*/
|
|
477
|
+
renderWidget(tui, theme, width) {
|
|
478
|
+
const allAgents = this.widgetAgents();
|
|
479
|
+
const running = allAgents.filter(a => a.status === "running");
|
|
480
|
+
const queued = allAgents.filter(a => a.status === "queued");
|
|
481
|
+
const finished = allAgents.filter(a => a.status !== "running" && a.status !== "queued" && a.completedAt
|
|
482
|
+
&& this.shouldShowFinished(a.id, a.status));
|
|
483
|
+
const hasActive = running.length > 0 || queued.length > 0;
|
|
484
|
+
const hasFinished = finished.length > 0;
|
|
485
|
+
// Nothing to show — return empty (widget will be unregistered by update())
|
|
486
|
+
if (!hasActive && !hasFinished)
|
|
487
|
+
return [];
|
|
488
|
+
// Render to the width the HOST allocated, not the terminal's: the dock can
|
|
489
|
+
// be narrower than `terminal.columns`, and a line wider than its slot wraps
|
|
490
|
+
// in the terminal while the renderer still counts one row — the same
|
|
491
|
+
// desync an embedded newline causes. Older hosts call render() with no
|
|
492
|
+
// argument; fall back to the terminal width for them.
|
|
493
|
+
const w = typeof width === "number" && Number.isFinite(width) && width >= 0 ? width : tui.terminal.columns;
|
|
494
|
+
const truncate = (line) => truncateToWidth(line, w);
|
|
495
|
+
const headingColor = hasActive ? "accent" : "dim";
|
|
496
|
+
const headingIcon = hasActive ? "●" : "○";
|
|
497
|
+
const frame = SPINNER[this.widgetFrame % SPINNER.length];
|
|
498
|
+
// Apply the existing overflow priority before formatting. Hidden cards must
|
|
499
|
+
// not project session history or format text just to be discarded below.
|
|
500
|
+
const maxBody = MAX_WIDGET_LINES - 1;
|
|
501
|
+
const queueRows = queued.length > 0 ? 1 : 0;
|
|
502
|
+
const totalBody = finished.length + running.length * RUNNING_CARD_LINES + queueRows;
|
|
503
|
+
const overflow = totalBody > maxBody;
|
|
504
|
+
const cardBudget = overflow ? maxBody - 1 - queueRows : maxBody;
|
|
505
|
+
const runningLimit = overflow ? Math.min(running.length, Math.floor(cardBudget / RUNNING_CARD_LINES)) : running.length;
|
|
506
|
+
const finishedLimit = overflow ? Math.max(0, cardBudget - runningLimit * RUNNING_CARD_LINES) : finished.length;
|
|
507
|
+
const finishedLines = [];
|
|
508
|
+
for (const a of finished.slice(0, finishedLimit)) {
|
|
509
|
+
finishedLines.push(truncate(theme.fg("dim", "├─") + " " + this.renderFinishedLine(a, theme)));
|
|
510
|
+
}
|
|
511
|
+
const runningLines = []; // each entry is [header, activity, advisor]
|
|
512
|
+
for (const a of running.slice(0, runningLimit)) {
|
|
513
|
+
const modeLabel = getPromptModeLabel(a.type);
|
|
514
|
+
const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
|
|
515
|
+
const elapsed = formatMs(Date.now() - a.startedAt);
|
|
516
|
+
const bg = this.agentActivity.get(a.id);
|
|
517
|
+
const toolUses = bg?.toolUses ?? a.toolUses;
|
|
518
|
+
// Spend comes from the record, never from the activity tracker: the record
|
|
519
|
+
// is the one that survives the agent finishing, and the one nested-tools
|
|
520
|
+
// folds a hidden child's spend into. Reading the tracker while an agent
|
|
521
|
+
// runs and the record once it stops made the figure jump at completion.
|
|
522
|
+
const tokens = getLifetimeTotal(a.lifetimeUsage);
|
|
523
|
+
const contextPercent = getSessionContextPercent(bg?.session);
|
|
524
|
+
const tokenText = tokens > 0 ? formatSessionTokens(tokens, contextPercent, theme, a.compactionCount) : "";
|
|
525
|
+
const costText = this.showCost() ? formatCost(getLifetimeCost(a.lifetimeUsage)) : "";
|
|
526
|
+
const parts = [];
|
|
527
|
+
if (this.showModel()) {
|
|
528
|
+
// Leading, and paired: a thinking level means nothing without the model
|
|
529
|
+
// it applies to. The tag is taken from buildInvocationTags rather than
|
|
530
|
+
// rebuilt so the "(asked X)" annotation survives. Both are plain text
|
|
531
|
+
// that ends up inside a styled run, so they are flattened first — a
|
|
532
|
+
// control byte here would still break the row.
|
|
533
|
+
const { modelName, tags } = buildInvocationTags(a.invocation);
|
|
534
|
+
if (modelName)
|
|
535
|
+
parts.push(sanitizeRowText(modelName));
|
|
536
|
+
const thinkingTag = tags.find(tag => tag.startsWith("thinking: "));
|
|
537
|
+
if (thinkingTag)
|
|
538
|
+
parts.push(sanitizeRowText(thinkingTag));
|
|
539
|
+
}
|
|
540
|
+
if (bg)
|
|
541
|
+
parts.push(formatTurns(bg.turnCount, bg.maxTurns));
|
|
542
|
+
if (toolUses > 0)
|
|
543
|
+
parts.push(`${toolUses} tool use${toolUses === 1 ? "" : "s"}`);
|
|
544
|
+
if (tokenText)
|
|
545
|
+
parts.push(tokenText);
|
|
546
|
+
if (costText)
|
|
547
|
+
parts.push(costText);
|
|
548
|
+
parts.push(elapsed);
|
|
549
|
+
const statsText = parts.join(" · ");
|
|
550
|
+
const activity = sanitizeRowText(bg ? describeActivity(bg.activeTools, bg.responseText) : "thinking…");
|
|
551
|
+
runningLines.push([
|
|
552
|
+
truncate(theme.fg("dim", "├─") + ` ${theme.fg("accent", frame)} ${renderAgentName(a.type, theme, { bold: true })}${modeTag} ${theme.fg("muted", sanitizeRowText(a.description))} ${theme.fg("dim", "·")} ${fgPreservingNestedStyles(theme, "dim", statsText)}`),
|
|
553
|
+
truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${activity}`)),
|
|
554
|
+
truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${sanitizeRowText(formatAdvisorStatus(a.advisorStatus))}`)),
|
|
555
|
+
]);
|
|
556
|
+
}
|
|
557
|
+
const queuedLine = queued.length > 0
|
|
558
|
+
? truncate(theme.fg("dim", "├─") + ` ${theme.fg("muted", "◦")} ${theme.fg("dim", `${queued.length} queued`)}`)
|
|
559
|
+
: undefined;
|
|
560
|
+
const hubHint = this.hub ? theme.fg("dim", " · ← Agent Hub") : "";
|
|
561
|
+
const lines = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, "Agents") + hubHint)];
|
|
562
|
+
if (totalBody <= maxBody) {
|
|
563
|
+
// Everything fits — add all lines and fix up connectors for the last item.
|
|
564
|
+
lines.push(...finishedLines);
|
|
565
|
+
for (const pair of runningLines)
|
|
566
|
+
lines.push(...pair);
|
|
567
|
+
if (queuedLine)
|
|
568
|
+
lines.push(queuedLine);
|
|
569
|
+
// Fix last connector: swap ├─ → └─ and │ → space for activity lines.
|
|
570
|
+
if (lines.length > 1) {
|
|
571
|
+
const last = lines.length - 1;
|
|
572
|
+
lines[last] = lines[last].replace("├─", "└─");
|
|
573
|
+
// If last item is a running agent activity line, fix indent of that line
|
|
574
|
+
// and fix the header line above it.
|
|
575
|
+
if (runningLines.length > 0 && !queuedLine) {
|
|
576
|
+
const lastRows = runningLines[runningLines.length - 1];
|
|
577
|
+
const header = lines.length - lastRows.length;
|
|
578
|
+
lines[header] = lines[header].replace("├─", "└─");
|
|
579
|
+
for (let row = header + 1; row < lines.length; row++) {
|
|
580
|
+
lines[row] = lines[row].replace("│ ", " ");
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
else {
|
|
586
|
+
// Overflow — prioritize: running > queued > finished.
|
|
587
|
+
// Reserve 1 line for overflow indicator.
|
|
588
|
+
let budget = maxBody - 1;
|
|
589
|
+
let hiddenRunning = running.length - runningLines.length;
|
|
590
|
+
let hiddenFinished = finished.length - finishedLines.length;
|
|
591
|
+
// Reserve the queued line's row up front. It is a single summary of N
|
|
592
|
+
// waiting agents, so it cannot be folded into the "+N more" count (which
|
|
593
|
+
// is denominated in agents) without either under-reporting it as 1 or
|
|
594
|
+
// inflating the total with agents that were never getting their own rows.
|
|
595
|
+
// Reserving costs at most one running agent — which IS counted below —
|
|
596
|
+
// and makes the drop unreachable. It matters most exactly when it used to
|
|
597
|
+
// vanish: the pool is saturated and the queue is what the user needs to see.
|
|
598
|
+
const queuedReserve = queuedLine ? 1 : 0;
|
|
599
|
+
budget -= queuedReserve;
|
|
600
|
+
// 1. Running agents (whole cards only)
|
|
601
|
+
for (const pair of runningLines) {
|
|
602
|
+
if (budget >= pair.length) {
|
|
603
|
+
lines.push(...pair);
|
|
604
|
+
budget -= pair.length;
|
|
605
|
+
}
|
|
606
|
+
else {
|
|
607
|
+
hiddenRunning++;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
// 2. Queued line (always fits — its row was reserved above)
|
|
611
|
+
if (queuedLine) {
|
|
612
|
+
budget += queuedReserve;
|
|
613
|
+
lines.push(queuedLine);
|
|
614
|
+
budget--;
|
|
615
|
+
}
|
|
616
|
+
// 3. Finished agents
|
|
617
|
+
for (const fl of finishedLines) {
|
|
618
|
+
if (budget >= 1) {
|
|
619
|
+
lines.push(fl);
|
|
620
|
+
budget--;
|
|
621
|
+
}
|
|
622
|
+
else {
|
|
623
|
+
hiddenFinished++;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
// Overflow summary
|
|
627
|
+
const overflowParts = [];
|
|
628
|
+
if (hiddenRunning > 0)
|
|
629
|
+
overflowParts.push(`${hiddenRunning} running`);
|
|
630
|
+
if (hiddenFinished > 0)
|
|
631
|
+
overflowParts.push(`${hiddenFinished} finished`);
|
|
632
|
+
const overflowText = overflowParts.join(", ");
|
|
633
|
+
lines.push(truncate(theme.fg("dim", "└─") + ` ${theme.fg("dim", `+${hiddenRunning + hiddenFinished} more (${overflowText})`)}`));
|
|
634
|
+
}
|
|
635
|
+
return lines;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Acquire the TUI reference without a visible list. Pi invokes the factory
|
|
639
|
+
* synchronously inside setWidget but paints on the next render tick, so a
|
|
640
|
+
* register immediately followed by an unregister captures the reference and
|
|
641
|
+
* never draws a frame. A separate key from the real widget, so the
|
|
642
|
+
* registration state machine never notices.
|
|
643
|
+
*/
|
|
644
|
+
probeTui() {
|
|
645
|
+
if (!this.uiCtx)
|
|
646
|
+
return;
|
|
647
|
+
this.uiCtx.setWidget("agents-probe", tui => {
|
|
648
|
+
this.tui = tui;
|
|
649
|
+
return { render: () => [], invalidate: () => { } };
|
|
650
|
+
});
|
|
651
|
+
this.uiCtx.setWidget("agents-probe", undefined);
|
|
652
|
+
}
|
|
653
|
+
/** Force an immediate widget update. */
|
|
654
|
+
update() {
|
|
655
|
+
if (!this.uiCtx)
|
|
656
|
+
return;
|
|
657
|
+
const allAgents = this.widgetAgents();
|
|
658
|
+
// Lightweight existence checks — full categorization happens in renderWidget()
|
|
659
|
+
let runningCount = 0;
|
|
660
|
+
let queuedCount = 0;
|
|
661
|
+
let hasFinished = false;
|
|
662
|
+
let earliestExpiry = Number.POSITIVE_INFINITY;
|
|
663
|
+
for (const a of allAgents) {
|
|
664
|
+
if (a.status === "running") {
|
|
665
|
+
runningCount++;
|
|
666
|
+
}
|
|
667
|
+
else if (a.status === "queued") {
|
|
668
|
+
queuedCount++;
|
|
669
|
+
}
|
|
670
|
+
else if (a.completedAt && this.shouldShowFinished(a.id, a.status)) {
|
|
671
|
+
hasFinished = true;
|
|
672
|
+
earliestExpiry = Math.min(earliestExpiry, this.finishedExpiry(a.id, a.status));
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
const hasActive = runningCount > 0 || queuedCount > 0;
|
|
676
|
+
// Repaint scheduling: animate only while something is active. With only
|
|
677
|
+
// finished rows left, render once and wake a single time when the
|
|
678
|
+
// earliest row expires — an idle session must not redraw at 12.5 Hz.
|
|
679
|
+
if (hasActive) {
|
|
680
|
+
this.clearExpiryTimer();
|
|
681
|
+
this.ensureTimer();
|
|
682
|
+
}
|
|
683
|
+
else {
|
|
684
|
+
this.stopInterval();
|
|
685
|
+
if (hasFinished)
|
|
686
|
+
this.scheduleExpiry(earliestExpiry);
|
|
687
|
+
else
|
|
688
|
+
this.clearExpiryTimer();
|
|
689
|
+
}
|
|
690
|
+
// Nothing to show — clear widget
|
|
691
|
+
if (!hasActive && !hasFinished) {
|
|
692
|
+
if (this.widgetRegistered) {
|
|
693
|
+
this.uiCtx.setWidget("agents", undefined);
|
|
694
|
+
this.widgetRegistered = false;
|
|
695
|
+
this.registeredPlacement = undefined;
|
|
696
|
+
// `this.tui` deliberately survives the hide: the ← handler reads focus
|
|
697
|
+
// from it, and a reference from any past mount stays valid for the
|
|
698
|
+
// whole interactive session.
|
|
699
|
+
}
|
|
700
|
+
if (this.lastStatusText !== undefined) {
|
|
701
|
+
this.uiCtx.setStatus("subagents", undefined);
|
|
702
|
+
this.lastStatusText = undefined;
|
|
703
|
+
}
|
|
704
|
+
// Clean up stale entries
|
|
705
|
+
for (const [id] of this.finishedTurnAge) {
|
|
706
|
+
if (!allAgents.some(a => a.id === id))
|
|
707
|
+
this.finishedTurnAge.delete(id);
|
|
708
|
+
}
|
|
709
|
+
for (const [id] of this.finishedAt) {
|
|
710
|
+
if (!allAgents.some(a => a.id === id))
|
|
711
|
+
this.finishedAt.delete(id);
|
|
712
|
+
}
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
// Status bar — only call setStatus when the text actually changes
|
|
716
|
+
let newStatusText;
|
|
717
|
+
if (hasActive) {
|
|
718
|
+
const statusParts = [];
|
|
719
|
+
if (runningCount > 0)
|
|
720
|
+
statusParts.push(`${runningCount} running`);
|
|
721
|
+
if (queuedCount > 0)
|
|
722
|
+
statusParts.push(`${queuedCount} queued`);
|
|
723
|
+
const total = runningCount + queuedCount;
|
|
724
|
+
newStatusText = `${statusParts.join(", ")} agent${total === 1 ? "" : "s"}`;
|
|
725
|
+
}
|
|
726
|
+
if (newStatusText !== this.lastStatusText) {
|
|
727
|
+
this.uiCtx.setStatus("subagents", newStatusText);
|
|
728
|
+
this.lastStatusText = newStatusText;
|
|
729
|
+
}
|
|
730
|
+
this.widgetFrame++;
|
|
731
|
+
// Same-key registration moves between Pi's placement Maps. Otherwise keep
|
|
732
|
+
// the component and its insertion order stable across spinner updates.
|
|
733
|
+
const placement = this.placement();
|
|
734
|
+
if (!this.widgetRegistered || this.registeredPlacement !== placement) {
|
|
735
|
+
this.uiCtx.setWidget("agents", (tui, theme) => {
|
|
736
|
+
this.tui = tui;
|
|
737
|
+
return {
|
|
738
|
+
render: (width) => this.renderWidget(tui, theme, width),
|
|
739
|
+
invalidate: () => {
|
|
740
|
+
// Theme changed — force re-registration so the factory captures the
|
|
741
|
+
// fresh theme. The TUI reference stays: it does not change themes.
|
|
742
|
+
this.widgetRegistered = false;
|
|
743
|
+
this.registeredPlacement = undefined;
|
|
744
|
+
},
|
|
745
|
+
};
|
|
746
|
+
}, { placement: placement === "above" ? "aboveEditor" : "belowEditor" });
|
|
747
|
+
this.widgetRegistered = true;
|
|
748
|
+
this.registeredPlacement = placement;
|
|
749
|
+
}
|
|
750
|
+
else {
|
|
751
|
+
// Widget already registered — just request a re-render of existing components.
|
|
752
|
+
this.tui?.requestRender();
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
dispose() {
|
|
756
|
+
this.stopInterval();
|
|
757
|
+
this.clearExpiryTimer();
|
|
758
|
+
this.inputUnsub?.();
|
|
759
|
+
this.inputUnsub = undefined;
|
|
760
|
+
if (this.uiCtx) {
|
|
761
|
+
this.uiCtx.setWidget("agents", undefined);
|
|
762
|
+
this.uiCtx.setStatus("subagents", undefined);
|
|
763
|
+
}
|
|
764
|
+
this.widgetRegistered = false;
|
|
765
|
+
this.registeredPlacement = undefined;
|
|
766
|
+
this.tui = undefined;
|
|
767
|
+
this.uiCtx = undefined;
|
|
768
|
+
this.lastStatusText = undefined;
|
|
769
|
+
}
|
|
770
|
+
}
|