@yefengr/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/CHANGELOG.md +2411 -0
- package/LICENSE +21 -0
- package/README.md +374 -2
- package/UPSTREAM.md +48 -0
- package/dist/public.d.ts +201 -0
- package/dist/settings.d.ts +82 -0
- package/docs/architecture/architecture.md +833 -0
- package/docs/architecture/client-server-opportunities.md +127 -0
- package/docs/architecture/history/phase-1-api-boundary.md +8 -0
- package/docs/architecture/history/phase-10-structural-decomposition.md +141 -0
- package/docs/architecture/history/phase-11-closure-to-class.md +100 -0
- package/docs/architecture/history/phase-12-complexity-test-fixtures.md +55 -0
- package/docs/architecture/history/phase-13-remaining-smells.md +88 -0
- package/docs/architecture/history/phase-14-strip-policy.md +49 -0
- package/docs/architecture/history/phase-15-domain-model-evolution.md +73 -0
- package/docs/architecture/history/phase-16-invert-dependencies.md +144 -0
- package/docs/architecture/history/phase-17-core-consolidation.md +214 -0
- package/docs/architecture/history/phase-18-reconsider-ui.md +166 -0
- package/docs/architecture/history/phase-19-implement-ui-decisions.md +282 -0
- package/docs/architecture/history/phase-2-remove-scheduling.md +9 -0
- package/docs/architecture/history/phase-20-result-delivery.md +245 -0
- package/docs/architecture/history/phase-21-classification-model-boundary.md +107 -0
- package/docs/architecture/history/phase-3-remove-rpc-groupjoin.md +11 -0
- package/docs/architecture/history/phase-4-implement-service.md +8 -0
- package/docs/architecture/history/phase-5-decompose-index.md +42 -0
- package/docs/architecture/history/phase-7-encapsulation.md +173 -0
- package/docs/architecture/history/phase-8-testability.md +103 -0
- package/docs/architecture/history/phase-9-observation-ctx.md +122 -0
- package/docs/comparison-with-upstream.md +79 -0
- package/docs/configuration.md +215 -0
- package/docs/decisions/0001-deferred-patches.md +80 -0
- package/docs/decisions/0002-extensions-on-a-minimal-core.md +114 -0
- package/docs/decisions/0003-publish-bundled-type-declarations.md +71 -0
- package/docs/decisions/0004-reconsider-ui-direction.md +279 -0
- package/index.ts +1 -0
- package/package.json +91 -4
- package/src/config/agent-enablement.ts +132 -0
- package/src/config/agent-types.ts +144 -0
- package/src/config/custom-agents.ts +114 -0
- package/src/config/default-agents.ts +120 -0
- package/src/config/invocation-config.ts +39 -0
- package/src/config/resource-limits.ts +26 -0
- package/src/config/settings-file.ts +174 -0
- package/src/debug.ts +14 -0
- package/src/handlers/index.ts +3 -0
- package/src/handlers/interrupt.ts +58 -0
- package/src/handlers/lifecycle.ts +65 -0
- package/src/handlers/tool-start.ts +32 -0
- package/src/index.ts +257 -0
- package/src/layered-settings.ts +105 -0
- package/src/lifecycle/child-lifecycle.ts +89 -0
- package/src/lifecycle/child-shutdown.ts +105 -0
- package/src/lifecycle/concurrency-limiter.ts +123 -0
- package/src/lifecycle/create-subagent-session.ts +265 -0
- package/src/lifecycle/invocation-control.ts +109 -0
- package/src/lifecycle/lifecycle-record.ts +159 -0
- package/src/lifecycle/parent-snapshot.ts +46 -0
- package/src/lifecycle/run-listeners.ts +41 -0
- package/src/lifecycle/subagent-manager.ts +392 -0
- package/src/lifecycle/subagent-session.ts +287 -0
- package/src/lifecycle/subagent-state.ts +307 -0
- package/src/lifecycle/subagent.ts +854 -0
- package/src/lifecycle/usage.ts +60 -0
- package/src/lifecycle/workspace-bracket.ts +59 -0
- package/src/lifecycle/workspace.ts +47 -0
- package/src/observation/composite-subagent-observer.ts +53 -0
- package/src/observation/notification.ts +233 -0
- package/src/observation/record-observer.ts +78 -0
- package/src/observation/renderer.ts +106 -0
- package/src/observation/subagent-events-observer.ts +75 -0
- package/src/runtime.ts +78 -0
- package/src/service/service-adapter.ts +159 -0
- package/src/service/service.ts +147 -0
- package/src/session/content-items.ts +53 -0
- package/src/session/context.ts +80 -0
- package/src/session/conversation.ts +49 -0
- package/src/session/env.ts +40 -0
- package/src/session/model-resolver.ts +135 -0
- package/src/session/package-exclusions.ts +75 -0
- package/src/session/prompts.ts +145 -0
- package/src/session/provider-inheritance.ts +38 -0
- package/src/session/session-config.ts +177 -0
- package/src/session/session-dir.ts +38 -0
- package/src/settings.ts +436 -0
- package/src/tools/agent-tool.ts +289 -0
- package/src/tools/background-spawner.ts +73 -0
- package/src/tools/foreground-runner.ts +135 -0
- package/src/tools/get-result-report.ts +73 -0
- package/src/tools/get-result-tool.ts +109 -0
- package/src/tools/helpers.ts +134 -0
- package/src/tools/result-renderer.ts +121 -0
- package/src/tools/spawn-config.ts +182 -0
- package/src/tools/steer-tool.ts +120 -0
- package/src/types.ts +145 -0
- package/src/ui/agent-widget.ts +313 -0
- package/src/ui/display.ts +214 -0
- package/src/ui/glyphs.ts +62 -0
- package/src/ui/session-navigation.ts +152 -0
- package/src/ui/session-navigator.ts +257 -0
- package/src/ui/subagents-agents.ts +116 -0
- package/src/ui/subagents-settings.ts +207 -0
- package/src/ui/transcript-content.ts +374 -0
- package/src/ui/widget-renderer.ts +289 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-widget.ts — Persistent widget showing running/completed agents above 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
|
+
|
|
8
|
+
import { AgentTypeRegistry } from "#src/config/agent-types";
|
|
9
|
+
import type { Subagent } from "#src/lifecycle/subagent";
|
|
10
|
+
import type { SubagentManager, SubagentManagerObserver } from "#src/lifecycle/subagent-manager";
|
|
11
|
+
import type { SubagentOutcome, SubagentPhase } from "#src/lifecycle/subagent-state";
|
|
12
|
+
import type { CompactionInfo } from "#src/types";
|
|
13
|
+
import { isErrorOutcome, type Theme } from "#src/ui/display";
|
|
14
|
+
import { renderWidgetLines, type WidgetAgent } from "#src/ui/widget-renderer";
|
|
15
|
+
|
|
16
|
+
// ---- Types ----
|
|
17
|
+
|
|
18
|
+
/** Minimal agent shape needed for widget lifecycle decisions. */
|
|
19
|
+
interface AgentSummary {
|
|
20
|
+
readonly id: string;
|
|
21
|
+
readonly phase: SubagentPhase;
|
|
22
|
+
readonly outcome?: SubagentOutcome;
|
|
23
|
+
readonly completedAt?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Lightweight state snapshot used by AgentWidget.update() to decide what to show. */
|
|
27
|
+
export interface WidgetState {
|
|
28
|
+
readonly runningCount: number;
|
|
29
|
+
readonly queuedCount: number;
|
|
30
|
+
readonly hasFinished: boolean;
|
|
31
|
+
/** True when runningCount > 0 || queuedCount > 0. Included for call-site readability. */
|
|
32
|
+
readonly hasActive: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Count agents by phase and return a lightweight state snapshot.
|
|
37
|
+
* Pure function — no IO, no side effects. Exported for direct unit testing.
|
|
38
|
+
*/
|
|
39
|
+
export function assembleWidgetState(
|
|
40
|
+
agents: readonly AgentSummary[],
|
|
41
|
+
shouldShowFinished: (agentId: string, outcome: SubagentOutcome | undefined) => boolean,
|
|
42
|
+
): WidgetState {
|
|
43
|
+
let runningCount = 0;
|
|
44
|
+
let queuedCount = 0;
|
|
45
|
+
let hasFinished = false;
|
|
46
|
+
for (const a of agents) {
|
|
47
|
+
if (a.phase === "running") { runningCount++; }
|
|
48
|
+
else if (a.phase === "queued") { queuedCount++; }
|
|
49
|
+
else if (a.completedAt && shouldShowFinished(a.id, a.outcome)) { hasFinished = true; }
|
|
50
|
+
}
|
|
51
|
+
const hasActive = runningCount > 0 || queuedCount > 0;
|
|
52
|
+
return { runningCount, queuedCount, hasFinished, hasActive };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The slice of the TUI the widget factory callback touches. */
|
|
56
|
+
export interface TuiSurface {
|
|
57
|
+
readonly terminal: { readonly columns: number };
|
|
58
|
+
requestRender(): void;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type UICtx = {
|
|
62
|
+
setStatus(key: string, text: string | undefined): void;
|
|
63
|
+
setWidget(
|
|
64
|
+
key: string,
|
|
65
|
+
content: undefined | ((tui: TuiSurface, theme: Theme) => { render(): string[]; invalidate(): void }),
|
|
66
|
+
options?: { placement?: "aboveEditor" | "belowEditor" },
|
|
67
|
+
): void;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
// ---- Widget manager ----
|
|
71
|
+
|
|
72
|
+
export class AgentWidget implements SubagentManagerObserver {
|
|
73
|
+
private uiCtx: UICtx | undefined;
|
|
74
|
+
private widgetFrame = 0;
|
|
75
|
+
private widgetInterval: ReturnType<typeof setInterval> | undefined;
|
|
76
|
+
/** Tracks how many turns each finished agent has survived. Key: agent ID, Value: turns since finished. */
|
|
77
|
+
private finishedTurnAge = new Map<string, number>();
|
|
78
|
+
/** How many extra turns errors/aborted agents linger (completed agents clear after 1 turn). */
|
|
79
|
+
private static readonly ERROR_LINGER_TURNS = 2;
|
|
80
|
+
|
|
81
|
+
/** Whether the widget callback is currently registered with the TUI. */
|
|
82
|
+
private widgetRegistered = false;
|
|
83
|
+
/** Cached TUI reference from widget factory callback, used for requestRender(). */
|
|
84
|
+
private tui: TuiSurface | undefined;
|
|
85
|
+
/** Last status bar text, used to avoid redundant setStatus calls. */
|
|
86
|
+
private lastStatusText: string | undefined;
|
|
87
|
+
|
|
88
|
+
constructor(
|
|
89
|
+
private manager: SubagentManager,
|
|
90
|
+
private registry: AgentTypeRegistry,
|
|
91
|
+
) {}
|
|
92
|
+
|
|
93
|
+
/** Set the UI context (grabbed from first tool execution). */
|
|
94
|
+
setUICtx(ctx: UICtx) {
|
|
95
|
+
if (ctx !== this.uiCtx) {
|
|
96
|
+
// UICtx changed — the widget registered on the old context is gone.
|
|
97
|
+
// Force re-registration on next update().
|
|
98
|
+
this.uiCtx = ctx;
|
|
99
|
+
this.widgetRegistered = false;
|
|
100
|
+
this.tui = undefined;
|
|
101
|
+
this.lastStatusText = undefined;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Called on each new turn (tool_execution_start).
|
|
107
|
+
* Ages finished agents and clears those that have lingered long enough.
|
|
108
|
+
*/
|
|
109
|
+
onTurnStart() {
|
|
110
|
+
// Age all finished agents
|
|
111
|
+
for (const [id, age] of this.finishedTurnAge) {
|
|
112
|
+
this.finishedTurnAge.set(id, age + 1);
|
|
113
|
+
}
|
|
114
|
+
// Trigger a widget refresh (will filter out expired agents)
|
|
115
|
+
this.update();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// ---- SubagentManagerObserver: react to lifecycle, self-drive the timer ----
|
|
119
|
+
|
|
120
|
+
/** A subagent started running — ensure the update loop is live and render. */
|
|
121
|
+
onSubagentStarted(_record: Subagent) {
|
|
122
|
+
this.startLoop();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A background subagent was created (queued) — ensure the loop is live and render. */
|
|
126
|
+
onSubagentCreated(_record: Subagent) {
|
|
127
|
+
this.startLoop();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** A subagent completed — render so the finished state is seeded and shown. */
|
|
131
|
+
onSubagentCompleted(_record: Subagent) {
|
|
132
|
+
this.update();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A subagent finished a resume — render so the refreshed result is shown. */
|
|
136
|
+
onSubagentResumed(_record: Subagent) {
|
|
137
|
+
this.update();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** A subagent's session compacted — render to refresh the compaction count. */
|
|
141
|
+
onSubagentCompacted(_record: Subagent, _info: CompactionInfo) {
|
|
142
|
+
this.update();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Start the update timer (if not already running) and render immediately. */
|
|
146
|
+
private startLoop() {
|
|
147
|
+
this.ensureTimer();
|
|
148
|
+
this.update();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Ensure the widget update timer is running. */
|
|
152
|
+
private ensureTimer() {
|
|
153
|
+
this.widgetInterval ??= setInterval(() => this.update(), 80);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Check if a finished agent should still be shown in the widget. */
|
|
157
|
+
private shouldShowFinished(agentId: string, outcome: SubagentOutcome | undefined): boolean {
|
|
158
|
+
const age = this.finishedTurnAge.get(agentId) ?? 0;
|
|
159
|
+
const maxAge = isErrorOutcome(outcome) ? AgentWidget.ERROR_LINGER_TURNS : 1;
|
|
160
|
+
return age < maxAge;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Background agents only — the widget's sole audience (ADR-0004 Decision A).
|
|
165
|
+
* Foreground runs are rendered by the `subagent` tool's inline `onUpdate` stream,
|
|
166
|
+
* so funneling both `listAgents()` call sites through this accessor applies the
|
|
167
|
+
* background predicate exactly once at the source.
|
|
168
|
+
*/
|
|
169
|
+
private listBackgroundAgents(): Subagent[] {
|
|
170
|
+
return this.manager.listAgents().filter(record => record.invocation?.runInBackground === true);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Project a live Subagent record onto a pure-data WidgetAgent snapshot. */
|
|
174
|
+
private toWidgetAgent(record: Subagent): WidgetAgent {
|
|
175
|
+
return {
|
|
176
|
+
id: record.id,
|
|
177
|
+
type: record.type,
|
|
178
|
+
phase: record.phase,
|
|
179
|
+
...(record.outcome ? { outcome: record.outcome } : {}),
|
|
180
|
+
description: record.description,
|
|
181
|
+
toolUses: record.toolUses,
|
|
182
|
+
startedAt: record.startedAt,
|
|
183
|
+
completedAt: record.completedAt,
|
|
184
|
+
error: record.error,
|
|
185
|
+
lifetimeUsage: record.lifetimeUsage,
|
|
186
|
+
compactionCount: record.compactionCount,
|
|
187
|
+
invocationTurnCount: record.invocationTurnCount,
|
|
188
|
+
maxTurns: record.maxTurns,
|
|
189
|
+
activeTools: record.activeTools,
|
|
190
|
+
responseText: record.responseText,
|
|
191
|
+
contextPercent: record.getContextPercent(),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Delegate rendering to the pure widget-renderer module. */
|
|
196
|
+
private renderWidget(tui: TuiSurface, theme: Theme): string[] {
|
|
197
|
+
return renderWidgetLines({
|
|
198
|
+
agents: this.listBackgroundAgents().map(r => this.toWidgetAgent(r)),
|
|
199
|
+
registry: this.registry,
|
|
200
|
+
spinnerFrame: this.widgetFrame,
|
|
201
|
+
terminalWidth: tui.terminal.columns,
|
|
202
|
+
theme,
|
|
203
|
+
shouldShowFinished: (id, outcome) => this.shouldShowFinished(id, outcome),
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Unregister the widget, clear the status bar, stop the interval timer, and
|
|
209
|
+
* purge stale `finishedTurnAge` entries for agents no longer in `backgroundAgents`.
|
|
210
|
+
* Called only from `update`'s idle path — not from `dispose`.
|
|
211
|
+
*/
|
|
212
|
+
private clearWidget(backgroundAgents: readonly AgentSummary[]): void {
|
|
213
|
+
if (this.widgetRegistered) {
|
|
214
|
+
this.uiCtx!.setWidget("agents", undefined);
|
|
215
|
+
this.widgetRegistered = false;
|
|
216
|
+
this.tui = undefined;
|
|
217
|
+
}
|
|
218
|
+
if (this.lastStatusText !== undefined) {
|
|
219
|
+
this.uiCtx!.setStatus("subagents", undefined);
|
|
220
|
+
this.lastStatusText = undefined;
|
|
221
|
+
}
|
|
222
|
+
if (this.widgetInterval) { clearInterval(this.widgetInterval); this.widgetInterval = undefined; }
|
|
223
|
+
for (const [id] of this.finishedTurnAge) {
|
|
224
|
+
if (!backgroundAgents.some(a => a.id === id)) this.finishedTurnAge.delete(id);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Compute the status bar text from the current widget state and call
|
|
230
|
+
* `setStatus` only when it differs from the last cached value.
|
|
231
|
+
*/
|
|
232
|
+
private updateStatusBar(state: WidgetState): void {
|
|
233
|
+
let newStatusText: string | undefined;
|
|
234
|
+
if (state.hasActive) {
|
|
235
|
+
const statusParts: string[] = [];
|
|
236
|
+
if (state.runningCount > 0) statusParts.push(`${state.runningCount} running`);
|
|
237
|
+
if (state.queuedCount > 0) statusParts.push(`${state.queuedCount} queued`);
|
|
238
|
+
const total = state.runningCount + state.queuedCount;
|
|
239
|
+
newStatusText = `${statusParts.join(", ")} agent${total === 1 ? "" : "s"}`;
|
|
240
|
+
}
|
|
241
|
+
if (newStatusText !== this.lastStatusText) {
|
|
242
|
+
this.uiCtx!.setStatus("subagents", newStatusText);
|
|
243
|
+
this.lastStatusText = newStatusText;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Seed linger tracking for any newly-observed finished agent.
|
|
249
|
+
* The widget owns detection of completions it observes via `listAgents()`,
|
|
250
|
+
* so no external bookkeeping call is needed.
|
|
251
|
+
* Idempotent — only seeds when an entry is absent, so repeated updates within
|
|
252
|
+
* a turn neither reset nor advance the age.
|
|
253
|
+
*/
|
|
254
|
+
private seedFinishedAgents(agents: readonly AgentSummary[]): void {
|
|
255
|
+
for (const a of agents) {
|
|
256
|
+
if (a.completedAt && !this.finishedTurnAge.has(a.id)) {
|
|
257
|
+
this.finishedTurnAge.set(a.id, 0);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Force an immediate widget update. */
|
|
263
|
+
update() {
|
|
264
|
+
if (!this.uiCtx) return;
|
|
265
|
+
|
|
266
|
+
const backgroundAgents = this.listBackgroundAgents();
|
|
267
|
+
this.seedFinishedAgents(backgroundAgents);
|
|
268
|
+
const state = assembleWidgetState(backgroundAgents, (id, outcome) => this.shouldShowFinished(id, outcome));
|
|
269
|
+
|
|
270
|
+
if (!state.hasActive && !state.hasFinished) {
|
|
271
|
+
this.clearWidget(backgroundAgents);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
this.updateStatusBar(state);
|
|
276
|
+
this.widgetFrame++;
|
|
277
|
+
|
|
278
|
+
// Register widget callback once; subsequent updates use requestRender()
|
|
279
|
+
// which re-invokes render() without replacing the component (avoids layout thrashing).
|
|
280
|
+
if (!this.widgetRegistered) {
|
|
281
|
+
this.uiCtx.setWidget("agents", (tui, theme) => {
|
|
282
|
+
this.tui = tui;
|
|
283
|
+
return {
|
|
284
|
+
render: () => this.renderWidget(tui, theme),
|
|
285
|
+
invalidate: () => {
|
|
286
|
+
// Theme changed — force re-registration so factory captures fresh theme.
|
|
287
|
+
this.widgetRegistered = false;
|
|
288
|
+
this.tui = undefined;
|
|
289
|
+
},
|
|
290
|
+
};
|
|
291
|
+
}, { placement: "aboveEditor" });
|
|
292
|
+
this.widgetRegistered = true;
|
|
293
|
+
} else {
|
|
294
|
+
// Widget already registered — just request a re-render of existing components.
|
|
295
|
+
this.tui?.requestRender();
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// fallow-ignore-next-line unused-class-member
|
|
300
|
+
dispose() {
|
|
301
|
+
if (this.widgetInterval) {
|
|
302
|
+
clearInterval(this.widgetInterval);
|
|
303
|
+
this.widgetInterval = undefined;
|
|
304
|
+
}
|
|
305
|
+
if (this.uiCtx) {
|
|
306
|
+
this.uiCtx.setWidget("agents", undefined);
|
|
307
|
+
this.uiCtx.setStatus("subagents", undefined);
|
|
308
|
+
}
|
|
309
|
+
this.widgetRegistered = false;
|
|
310
|
+
this.tui = undefined;
|
|
311
|
+
this.lastStatusText = undefined;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* display.ts — Pure formatting helpers and display utilities for agent UI.
|
|
3
|
+
*
|
|
4
|
+
* All functions are stateless and dependency-free (no SDK, no widget lifecycle).
|
|
5
|
+
* Consumed by the widget, the menu, tool modules, and the notification renderer.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { AgentConfigLookup } from "#src/config/agent-types";
|
|
9
|
+
import type { SubagentOutcome, SubagentPhase } from "#src/lifecycle/subagent-state";
|
|
10
|
+
import type { AgentInvocation, SubagentType } from "#src/types";
|
|
11
|
+
import { GLYPHS } from "#src/ui/glyphs";
|
|
12
|
+
|
|
13
|
+
// ---- Types ----
|
|
14
|
+
|
|
15
|
+
export type Theme = {
|
|
16
|
+
fg(color: string, text: string): string;
|
|
17
|
+
bold(text: string): string;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** Metadata attached to Agent tool results for custom rendering. */
|
|
21
|
+
export interface AgentDetails {
|
|
22
|
+
displayName: string;
|
|
23
|
+
description: string;
|
|
24
|
+
subagentType: string;
|
|
25
|
+
toolUses: number;
|
|
26
|
+
tokens: string;
|
|
27
|
+
durationMs: number;
|
|
28
|
+
/** Execution phase; "background" marks a detached launch acknowledgement. */
|
|
29
|
+
phase: SubagentPhase | "background";
|
|
30
|
+
/** Terminal outcome; present once phase is "terminal". */
|
|
31
|
+
outcome?: SubagentOutcome;
|
|
32
|
+
/** Human-readable description of what the agent is currently doing. */
|
|
33
|
+
activity?: string;
|
|
34
|
+
/** Current spinner frame index (for animated running indicator). */
|
|
35
|
+
spinnerFrame?: number;
|
|
36
|
+
/** Short model name if different from parent (e.g. "haiku", "sonnet"). */
|
|
37
|
+
modelName?: string;
|
|
38
|
+
/** Notable config tags (e.g. ["thinking: high", "inherit context"]). */
|
|
39
|
+
tags?: string[];
|
|
40
|
+
/** Current invocation turn count — compared against maxTurns (never lifetime). */
|
|
41
|
+
invocationTurnCount?: number;
|
|
42
|
+
/** Total turns across all invocations of this agent, informational only. */
|
|
43
|
+
lifetimeTurnCount?: number;
|
|
44
|
+
/** Effective max turns for one invocation; omitted only when no invocation exists yet. */
|
|
45
|
+
maxTurns?: number;
|
|
46
|
+
agentId?: string;
|
|
47
|
+
error?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ---- Constants ----
|
|
51
|
+
|
|
52
|
+
/** Terminal outcomes rendered with failure styling — everything but completed. */
|
|
53
|
+
export const ERROR_OUTCOMES = new Set<SubagentOutcome>([
|
|
54
|
+
"turn_limit",
|
|
55
|
+
"timeout",
|
|
56
|
+
"queue_timeout",
|
|
57
|
+
"cancelled",
|
|
58
|
+
"error",
|
|
59
|
+
]);
|
|
60
|
+
|
|
61
|
+
/** True when a terminal outcome did not complete normally. */
|
|
62
|
+
export function isErrorOutcome(outcome: SubagentOutcome | undefined): boolean {
|
|
63
|
+
return outcome != null && outcome !== "completed";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Frozen user-facing label for a terminal outcome. */
|
|
67
|
+
export function getOutcomeLabel(outcome: SubagentOutcome | undefined): string {
|
|
68
|
+
switch (outcome) {
|
|
69
|
+
case "completed":
|
|
70
|
+
return "Done";
|
|
71
|
+
case "turn_limit":
|
|
72
|
+
return "Turn limit reached";
|
|
73
|
+
case "timeout":
|
|
74
|
+
return "Timed out";
|
|
75
|
+
case "queue_timeout":
|
|
76
|
+
return "Queue timed out";
|
|
77
|
+
case "cancelled":
|
|
78
|
+
return "Cancelled";
|
|
79
|
+
case "error":
|
|
80
|
+
return "Error";
|
|
81
|
+
default:
|
|
82
|
+
return "Unknown";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Tool name → human-readable action for activity descriptions. */
|
|
87
|
+
const TOOL_DISPLAY: Record<string, string> = {
|
|
88
|
+
read: "reading",
|
|
89
|
+
bash: "running command",
|
|
90
|
+
edit: "editing",
|
|
91
|
+
write: "writing",
|
|
92
|
+
grep: "searching",
|
|
93
|
+
find: "finding files",
|
|
94
|
+
ls: "listing",
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
// ---- Pure formatters ----
|
|
98
|
+
|
|
99
|
+
/** Format a token count compactly: "33.8k token", "1.2M token". */
|
|
100
|
+
export function formatTokens(count: number): string {
|
|
101
|
+
if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M token`;
|
|
102
|
+
if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k token`;
|
|
103
|
+
return `${count} token`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Token count with optional context-fill % and compaction-count annotations.
|
|
108
|
+
* Thresholds for percent: <70% dim, 70–85% warning, ≥85% error.
|
|
109
|
+
* Compaction count rendered as `⇊N` in dim (see `glyphs.ts`).
|
|
110
|
+
*
|
|
111
|
+
* "12.3k token" — no annotations
|
|
112
|
+
* "12.3k token (45%)" — percent only
|
|
113
|
+
* "12.3k token (⇊2)" — compactions only (e.g. right after compact)
|
|
114
|
+
* "12.3k token (45% · ⇊2)" — both
|
|
115
|
+
*/
|
|
116
|
+
export function formatSessionTokens(
|
|
117
|
+
tokens: number,
|
|
118
|
+
percent: number | null,
|
|
119
|
+
theme: Theme,
|
|
120
|
+
compactions = 0,
|
|
121
|
+
): string {
|
|
122
|
+
const tokenStr = formatTokens(tokens);
|
|
123
|
+
const annot: string[] = [];
|
|
124
|
+
if (percent !== null) {
|
|
125
|
+
const color = percent >= 85 ? "error" : percent >= 70 ? "warning" : "dim";
|
|
126
|
+
annot.push(theme.fg(color, `${Math.round(percent)}%`));
|
|
127
|
+
}
|
|
128
|
+
if (compactions > 0) {
|
|
129
|
+
annot.push(theme.fg("dim", `${GLYPHS.compactions}${compactions}`));
|
|
130
|
+
}
|
|
131
|
+
if (annot.length === 0) return tokenStr;
|
|
132
|
+
const sep = theme.fg("dim", " · ");
|
|
133
|
+
return `${tokenStr} ${theme.fg("dim", "(")}${annot.join(sep)}${theme.fg("dim", ")")}`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Format turn count with optional max limit: "↻5≤30" or "↻5". */
|
|
137
|
+
export function formatTurns(turnCount: number, maxTurns?: number | null): string {
|
|
138
|
+
return maxTurns != null
|
|
139
|
+
? `${GLYPHS.turns}${turnCount}≤${maxTurns}`
|
|
140
|
+
: `${GLYPHS.turns}${turnCount}`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Format milliseconds as human-readable duration. */
|
|
144
|
+
export function formatMs(ms: number): string {
|
|
145
|
+
return `${(ms / 1000).toFixed(1)}s`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Format duration from start/completed timestamps. */
|
|
149
|
+
export function formatDuration(startedAt: number, completedAt?: number): string {
|
|
150
|
+
if (completedAt) return formatMs(completedAt - startedAt);
|
|
151
|
+
return `${formatMs(Date.now() - startedAt)} (running)`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ---- Display helpers ----
|
|
155
|
+
|
|
156
|
+
/** Get display name for any agent type (built-in or custom). */
|
|
157
|
+
export function getDisplayName(type: SubagentType, registry: AgentConfigLookup): string {
|
|
158
|
+
const config = registry.resolveAgentConfig(type);
|
|
159
|
+
return config.displayName ?? config.name;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Short label for prompt mode: "twin" for append, nothing for replace (the default). */
|
|
163
|
+
export function getPromptModeLabel(type: SubagentType, registry: AgentConfigLookup): string | undefined {
|
|
164
|
+
const config = registry.resolveAgentConfig(type);
|
|
165
|
+
return config.promptMode === "append" ? "twin" : undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Mode label is not included — callers add it where they want it. */
|
|
169
|
+
export function buildInvocationTags(
|
|
170
|
+
invocation: AgentInvocation | undefined,
|
|
171
|
+
): { modelName?: string; tags: string[] } {
|
|
172
|
+
const tags: string[] = [];
|
|
173
|
+
if (!invocation) return { tags };
|
|
174
|
+
if (invocation.thinking) tags.push(`thinking: ${invocation.thinking}`);
|
|
175
|
+
if (invocation.inheritContext) tags.push("inherit context");
|
|
176
|
+
if (invocation.runInBackground) tags.push("background");
|
|
177
|
+
if (invocation.maxTurns != null) tags.push(`max turns: ${invocation.maxTurns}`);
|
|
178
|
+
return { modelName: invocation.modelName, tags };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Truncate text to a single line, max `len` chars. */
|
|
182
|
+
function truncateLine(text: string, len = 60): string {
|
|
183
|
+
const line = text.split("\n").find(l => l.trim())?.trim() ?? "";
|
|
184
|
+
if (line.length <= len) return line;
|
|
185
|
+
return line.slice(0, len) + "…";
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Build a human-readable activity string from currently-running tools or response text. */
|
|
189
|
+
export function describeActivity(activeTools: ReadonlyMap<string, string>, responseText?: string): string {
|
|
190
|
+
if (activeTools.size > 0) {
|
|
191
|
+
const groups = new Map<string, number>();
|
|
192
|
+
for (const toolName of activeTools.values()) {
|
|
193
|
+
const action = TOOL_DISPLAY[toolName] ?? toolName;
|
|
194
|
+
groups.set(action, (groups.get(action) ?? 0) + 1);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const parts: string[] = [];
|
|
198
|
+
for (const [action, count] of groups) {
|
|
199
|
+
if (count > 1) {
|
|
200
|
+
parts.push(`${action} ${count} ${action === "searching" ? "patterns" : "files"}`);
|
|
201
|
+
} else {
|
|
202
|
+
parts.push(action);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return parts.join(", ") + "…";
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// No tools active — show truncated response text if available
|
|
209
|
+
if (responseText && responseText.trim().length > 0) {
|
|
210
|
+
return truncateLine(responseText);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return "thinking…";
|
|
214
|
+
}
|
package/src/ui/glyphs.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* glyphs.ts — the semantic display-glyph vocabulary for the agent UI.
|
|
3
|
+
*
|
|
4
|
+
* Pi's TUI sizes each terminal cell with `get-east-asian-width`, which reports
|
|
5
|
+
* one cell for every glyph below. A glyph that no monospace font covers is
|
|
6
|
+
* therefore drawn by a proportional fallback font whose advance overruns that
|
|
7
|
+
* cell and collides with the next column — the defect in #669. East Asian Width
|
|
8
|
+
* does not detect this: the offending glyph and its replacement are both width 1.
|
|
9
|
+
*
|
|
10
|
+
* Before adding or changing a glyph, measure its monospace coverage:
|
|
11
|
+
*
|
|
12
|
+
* fc-list ":charset=<codepoint>:spacing=100" family | cut -d, -f1 | sort -u | grep -v LastResort
|
|
13
|
+
*
|
|
14
|
+
* Coverage on macOS 15, counted in families:
|
|
15
|
+
*
|
|
16
|
+
* ↻ U+21BB turns 1 (Menlo)
|
|
17
|
+
* ⇊ U+21CA compactions 1 (Menlo)
|
|
18
|
+
* ✓ U+2713 success 6
|
|
19
|
+
* ✗ U+2717 failure 6
|
|
20
|
+
* ▸ U+25B8 tool call 6
|
|
21
|
+
* ■ U+25A0 stopped 9
|
|
22
|
+
* ● U+25CF agents active 9
|
|
23
|
+
* ○ U+25CB agents idle 9
|
|
24
|
+
* ◦ U+25E6 queued 9
|
|
25
|
+
* ⎿ U+23BF sub-line 0 — pi house style, tracked in #683
|
|
26
|
+
* ◍ U+25CD streaming 1 (Menlo), tracked in #683
|
|
27
|
+
* ⠋…⠏ spinner frames 0 — pi house style, tracked in #683
|
|
28
|
+
*
|
|
29
|
+
* Glyphs are written here as literal characters rather than `\uXXXX` escapes, so
|
|
30
|
+
* a non-ASCII scan of `src/` (`rg -n '[^\x00-\x7f]' src --glob '*.ts'`) surfaces
|
|
31
|
+
* this file plus only layout and punctuation. Box-drawing characters stay at
|
|
32
|
+
* their render sites: they are layout, not vocabulary.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** Semantic indicator glyphs rendered in the widget, inline results, and notifications. */
|
|
36
|
+
export const GLYPHS = {
|
|
37
|
+
/** Turn count, as `↻5≤30`. */
|
|
38
|
+
turns: "↻",
|
|
39
|
+
/** Session compaction count, annotating the token field. */
|
|
40
|
+
compactions: "⇊",
|
|
41
|
+
/** Completed outcome, also used dim/warning for a wrapped-up agent. */
|
|
42
|
+
success: "✓",
|
|
43
|
+
/** Error or aborted outcome. */
|
|
44
|
+
failure: "✗",
|
|
45
|
+
/** Stopped outcome. */
|
|
46
|
+
stopped: "■",
|
|
47
|
+
/** Continuation line beneath a result or activity line. */
|
|
48
|
+
subLine: "⎿",
|
|
49
|
+
/** Inline tool-call heading marker. */
|
|
50
|
+
toolCall: "▸",
|
|
51
|
+
/** Live streaming activity in the session transcript. */
|
|
52
|
+
streaming: "◍",
|
|
53
|
+
/** Queued-agents marker in the widget. */
|
|
54
|
+
queued: "◦",
|
|
55
|
+
/** Widget heading while agents are active. */
|
|
56
|
+
agentsActive: "●",
|
|
57
|
+
/** Widget heading while no agents are active. */
|
|
58
|
+
agentsIdle: "○",
|
|
59
|
+
} as const;
|
|
60
|
+
|
|
61
|
+
/** Braille spinner frames for the animated running indicator. */
|
|
62
|
+
export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|