@aoshizuku/pi-subagent 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/LICENSE +21 -0
- package/README.md +173 -2
- package/agents/explore.md +20 -0
- package/agents/general.md +17 -0
- package/package.json +55 -5
- package/src/batcher.ts +77 -0
- package/src/child.ts +212 -0
- package/src/cleanup.ts +40 -0
- package/src/config.ts +181 -0
- package/src/detail.ts +408 -0
- package/src/focus.ts +240 -0
- package/src/hud-state.ts +183 -0
- package/src/index.ts +1013 -0
- package/src/list.ts +223 -0
- package/src/manager.ts +588 -0
- package/src/models.ts +80 -0
- package/src/observer.ts +275 -0
- package/src/prompts.ts +103 -0
- package/src/render.ts +592 -0
- package/src/result.ts +226 -0
- package/src/run.ts +204 -0
- package/src/settings.ts +140 -0
- package/src/shizuku-settings.ts +92 -0
- package/src/stop-confirm.ts +47 -0
- package/src/test-helpers.ts +194 -0
- package/src/tool-line.ts +85 -0
- package/src/types.ts +257 -0
package/src/config.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Plugin configuration: ~/.pi/agent/pi-subagent.json (global only; docs/04 §5).
|
|
2
|
+
|
|
3
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname } from "node:path";
|
|
5
|
+
|
|
6
|
+
export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
7
|
+
export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
|
|
8
|
+
|
|
9
|
+
export function isThinkingLevel(value: unknown): value is ThinkingLevel {
|
|
10
|
+
return typeof value === "string" && (THINKING_LEVELS as readonly string[]).includes(value);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Per-type overrides; priority is call parameter > this > type file > parent session (docs/02 §3). */
|
|
14
|
+
export interface TypeOverride {
|
|
15
|
+
model?: string;
|
|
16
|
+
thinking?: ThinkingLevel;
|
|
17
|
+
maxTurns?: number;
|
|
18
|
+
contextLimit?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface SubagentConfig {
|
|
22
|
+
/** Keyed by lower-case type name. */
|
|
23
|
+
types: Record<string, TypeOverride>;
|
|
24
|
+
maxConcurrent: number;
|
|
25
|
+
resultMaxChars: number;
|
|
26
|
+
/** Per agent in a background notification (docs/05 §3.2). */
|
|
27
|
+
notifyMaxChars: number;
|
|
28
|
+
/** Whole notification batch (docs/05 §3.2). */
|
|
29
|
+
notifyBatchMaxChars: number;
|
|
30
|
+
/** Child session directories of other parent sessions older than this are deleted (docs/06 §8). */
|
|
31
|
+
retentionDays: number;
|
|
32
|
+
/** Extensions a child session may load: package names or paths (docs/02 §5.2). */
|
|
33
|
+
childExtensions: string[];
|
|
34
|
+
/** x stops an agent only when pressed twice on it: the /agents list, the detail overlay, HUD focus mode (docs/07 §4.4). */
|
|
35
|
+
confirmStop: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const DEFAULT_CONFIG: SubagentConfig = {
|
|
39
|
+
types: {},
|
|
40
|
+
maxConcurrent: 4,
|
|
41
|
+
resultMaxChars: 20_000,
|
|
42
|
+
notifyMaxChars: 8000,
|
|
43
|
+
notifyBatchMaxChars: 24_000,
|
|
44
|
+
retentionDays: 14,
|
|
45
|
+
// pi-dsweb gives the built-in types web_search / web_fetch (agents/*.md); harmless when it is not installed.
|
|
46
|
+
childExtensions: ["pi-dsweb"],
|
|
47
|
+
confirmStop: true,
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export const CONFIG_FILE_NAME = "pi-subagent.json";
|
|
51
|
+
|
|
52
|
+
export interface LoadedConfig {
|
|
53
|
+
config: SubagentConfig;
|
|
54
|
+
/** Set when the file exists but could not be read or parsed; defaults are used then. */
|
|
55
|
+
error?: string;
|
|
56
|
+
/** Fields that were present but invalid and therefore ignored. */
|
|
57
|
+
warnings: string[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function defaultConfig(): SubagentConfig {
|
|
61
|
+
return { ...DEFAULT_CONFIG, types: {}, childExtensions: [...DEFAULT_CONFIG.childExtensions] };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function loadConfig(path: string): LoadedConfig {
|
|
65
|
+
let raw: string;
|
|
66
|
+
try {
|
|
67
|
+
raw = readFileSync(path, "utf8");
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { config: defaultConfig(), warnings: [] };
|
|
70
|
+
return { config: defaultConfig(), error: `cannot read ${path}: ${(error as Error).message}`, warnings: [] };
|
|
71
|
+
}
|
|
72
|
+
let parsed: unknown;
|
|
73
|
+
try {
|
|
74
|
+
parsed = JSON.parse(raw);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
return { config: defaultConfig(), error: `invalid JSON in ${path}: ${(error as Error).message}`, warnings: [] };
|
|
77
|
+
}
|
|
78
|
+
if (!isObject(parsed)) return { config: defaultConfig(), error: `${path} must contain a JSON object`, warnings: [] };
|
|
79
|
+
return parseConfig(parsed);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function parseConfig(input: Record<string, unknown>): LoadedConfig {
|
|
83
|
+
const config = defaultConfig();
|
|
84
|
+
const warnings: string[] = [];
|
|
85
|
+
|
|
86
|
+
const positiveInt = (key: "maxConcurrent" | "resultMaxChars" | "notifyMaxChars" | "notifyBatchMaxChars" | "retentionDays", min: number): void => {
|
|
87
|
+
const value = input[key];
|
|
88
|
+
if (value === undefined) return;
|
|
89
|
+
if (typeof value === "number" && Number.isInteger(value) && value >= min) config[key] = value;
|
|
90
|
+
else warnings.push(`${key} must be an integer >= ${min}; using ${config[key]}`);
|
|
91
|
+
};
|
|
92
|
+
positiveInt("maxConcurrent", 1);
|
|
93
|
+
positiveInt("resultMaxChars", 1000);
|
|
94
|
+
positiveInt("notifyMaxChars", 1000);
|
|
95
|
+
positiveInt("notifyBatchMaxChars", 1000);
|
|
96
|
+
positiveInt("retentionDays", 1);
|
|
97
|
+
|
|
98
|
+
if (input.childExtensions !== undefined) {
|
|
99
|
+
const value = input.childExtensions;
|
|
100
|
+
if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
|
|
101
|
+
config.childExtensions = (value as string[]).map((entry) => entry.trim()).filter(Boolean);
|
|
102
|
+
} else {
|
|
103
|
+
warnings.push("childExtensions must be a list of package names or paths");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (input.confirmStop !== undefined) {
|
|
108
|
+
if (typeof input.confirmStop === "boolean") config.confirmStop = input.confirmStop;
|
|
109
|
+
else warnings.push(`confirmStop must be true or false; using ${config.confirmStop}`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (input.types !== undefined) {
|
|
113
|
+
if (!isObject(input.types)) {
|
|
114
|
+
warnings.push("types must be an object");
|
|
115
|
+
} else {
|
|
116
|
+
for (const [name, value] of Object.entries(input.types)) {
|
|
117
|
+
if (!isObject(value)) {
|
|
118
|
+
warnings.push(`types.${name} must be an object`);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const override: TypeOverride = {};
|
|
122
|
+
if (value.model !== undefined) {
|
|
123
|
+
if (typeof value.model === "string" && value.model.trim()) override.model = value.model.trim();
|
|
124
|
+
else warnings.push(`types.${name}.model must be a non-empty string`);
|
|
125
|
+
}
|
|
126
|
+
if (value.thinking !== undefined) {
|
|
127
|
+
if (isThinkingLevel(value.thinking)) override.thinking = value.thinking;
|
|
128
|
+
else warnings.push(`types.${name}.thinking must be one of ${THINKING_LEVELS.join(", ")}`);
|
|
129
|
+
}
|
|
130
|
+
if (value.max_turns !== undefined) {
|
|
131
|
+
if (isMaxTurns(value.max_turns)) override.maxTurns = value.max_turns;
|
|
132
|
+
else warnings.push(`types.${name}.max_turns must be an integer >= 2`);
|
|
133
|
+
}
|
|
134
|
+
if (value.context_limit !== undefined) {
|
|
135
|
+
if (isContextLimit(value.context_limit)) override.contextLimit = value.context_limit;
|
|
136
|
+
else warnings.push(`types.${name}.context_limit must be an integer from ${CONTEXT_LIMIT_MIN} to ${CONTEXT_LIMIT_MAX}`);
|
|
137
|
+
}
|
|
138
|
+
config.types[name.toLowerCase()] = override;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return { config, warnings };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function isMaxTurns(value: unknown): value is number {
|
|
146
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 2;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Bounds of context_limit: below 10% a run could not do anything; above 95% the report may not fit. */
|
|
150
|
+
export const CONTEXT_LIMIT_MIN = 10;
|
|
151
|
+
export const CONTEXT_LIMIT_MAX = 95;
|
|
152
|
+
|
|
153
|
+
export function isContextLimit(value: unknown): value is number {
|
|
154
|
+
return typeof value === "number" && Number.isInteger(value) && value >= CONTEXT_LIMIT_MIN && value <= CONTEXT_LIMIT_MAX;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
158
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Write `patch` (raw JSON fields) into the file and keep every other field (types, unknown keys) as it is. A
|
|
163
|
+
* missing file is created. Throws when the file exists but is not a JSON object (it is left alone) or cannot be written.
|
|
164
|
+
*/
|
|
165
|
+
export function saveConfigPatch(path: string, patch: Record<string, unknown>): void {
|
|
166
|
+
let current: Record<string, unknown> = {};
|
|
167
|
+
let raw: string | undefined;
|
|
168
|
+
try {
|
|
169
|
+
raw = readFileSync(path, "utf8");
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
172
|
+
}
|
|
173
|
+
if (raw !== undefined) {
|
|
174
|
+
const parsed: unknown = JSON.parse(raw);
|
|
175
|
+
if (!isObject(parsed)) throw new Error("the file must contain a JSON object");
|
|
176
|
+
current = parsed;
|
|
177
|
+
}
|
|
178
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
179
|
+
writeFileSync(path, `${JSON.stringify({ ...current, ...patch }, null, 2)}
|
|
180
|
+
`, "utf8");
|
|
181
|
+
}
|
package/src/detail.ts
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
// Detail overlay for one agent: stats, prompt, live activity, report, transcript (docs/07 §6).
|
|
2
|
+
//
|
|
3
|
+
// Scrolling is done here, not with pi-tui's ScrollView: a ScrollView only scrolls as a node of the fullscreen
|
|
4
|
+
// layout tree (its offset comes from updateLayout, scroll-view.ts:183-200, while render() returns every line),
|
|
5
|
+
// and overlays are rendered by calling component.render() and cutting to maxHeight (tui.ts:1395-1410).
|
|
6
|
+
// Wheel events over an overlay go to its handleMouse (tui-alt-screen.ts:726), which scrolls this view.
|
|
7
|
+
|
|
8
|
+
import { copyToClipboard, getMarkdownTheme, type KeybindingsManager, type Theme } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import { type Component, Markdown, matchesKey, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
10
|
+
|
|
11
|
+
import type { AgentRecord } from "./manager.js";
|
|
12
|
+
import { contextPercent, displayTokens, type ProgressSnapshot, type ToolCallEntry } from "./observer.js";
|
|
13
|
+
import { formatCost, formatTokens } from "./render.js";
|
|
14
|
+
import { durationOf, formatDuration } from "./result.js";
|
|
15
|
+
import type { AgentStatus } from "./run.js";
|
|
16
|
+
import { ARMED_HINT, StopConfirm } from "./stop-confirm.js";
|
|
17
|
+
|
|
18
|
+
export interface DetailSource {
|
|
19
|
+
get(agentId: string): AgentRecord | undefined;
|
|
20
|
+
progress(agentId: string): ProgressSnapshot | undefined;
|
|
21
|
+
subscribe(listener: (record: AgentRecord) => void): () => void;
|
|
22
|
+
stop(agentId: string): void;
|
|
23
|
+
/** The final report of a finished agent: the result file, else the in-memory text. */
|
|
24
|
+
report(record: AgentRecord): string;
|
|
25
|
+
/** The transcript path when the file exists. */
|
|
26
|
+
transcript(record: AgentRecord): string | undefined;
|
|
27
|
+
/** x must be pressed twice (docs/07 §4.4); default true. */
|
|
28
|
+
confirmStop?(): boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface DetailHost {
|
|
32
|
+
requestRender(): void;
|
|
33
|
+
readonly terminal: { readonly rows: number };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const PROMPT_PREVIEW_LINES = 8;
|
|
37
|
+
const RENDER_THROTTLE_MS = 100;
|
|
38
|
+
const TICK_MS = 1000;
|
|
39
|
+
const FLASH_MS = 2000;
|
|
40
|
+
export const OVERLAY_OPTIONS = { width: "90%", maxHeight: "80%", anchor: "center" } as const;
|
|
41
|
+
|
|
42
|
+
const ICONS: Record<AgentStatus, string> = {
|
|
43
|
+
queued: "◌",
|
|
44
|
+
running: "●",
|
|
45
|
+
completed: "✓",
|
|
46
|
+
failed: "✗",
|
|
47
|
+
aborted: "■",
|
|
48
|
+
max_turns: "↻",
|
|
49
|
+
context_limit: "◔",
|
|
50
|
+
};
|
|
51
|
+
const COLORS: Record<AgentStatus, "accent" | "warning" | "success" | "error" | "dim"> = {
|
|
52
|
+
queued: "dim",
|
|
53
|
+
running: "accent",
|
|
54
|
+
completed: "success",
|
|
55
|
+
failed: "error",
|
|
56
|
+
aborted: "warning",
|
|
57
|
+
max_turns: "warning",
|
|
58
|
+
context_limit: "warning",
|
|
59
|
+
};
|
|
60
|
+
const STATUS_TEXT: Partial<Record<AgentStatus, string>> = { max_turns: "out of turns", context_limit: "context full" };
|
|
61
|
+
|
|
62
|
+
export function isRunningStatus(status: AgentStatus): boolean {
|
|
63
|
+
return status === "queued" || status === "running";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* x can stop it: queued or running, and no stop requested yet. A stopped run keeps its status until the run
|
|
68
|
+
* returns (up to a few seconds), and an x in that window must not arm a second stop.
|
|
69
|
+
*/
|
|
70
|
+
export function isStoppable(record: Pick<AgentRecord, "status" | "stoppedBy">): boolean {
|
|
71
|
+
return isRunningStatus(record.status) && record.stoppedBy === undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Between the stop request and the run's end: the list and the overlay title say "stopping". */
|
|
75
|
+
export function isStopping(record: Pick<AgentRecord, "status" | "stoppedBy">): boolean {
|
|
76
|
+
return isRunningStatus(record.status) && record.stoppedBy !== undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Keys that move (a selection or a scroll position): they cancel an armed stop and still move. */
|
|
80
|
+
export function isMoveKey(data: string, keybindings: KeybindingsManager): boolean {
|
|
81
|
+
return (
|
|
82
|
+
keybindings.matches(data, "tui.select.up") ||
|
|
83
|
+
keybindings.matches(data, "tui.select.down") ||
|
|
84
|
+
matchesKey(data, "pageUp") ||
|
|
85
|
+
matchesKey(data, "pageDown") ||
|
|
86
|
+
matchesKey(data, "home") ||
|
|
87
|
+
matchesKey(data, "end")
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function openCommand(transcript: string): string {
|
|
92
|
+
return `pi --session "${transcript}"`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* `ctx 42%` for the title row, left of the duration; undefined until the child reports a fill. Thresholds
|
|
97
|
+
* match pi-hud's context bar: warning from 70%, error from 85%, dim below.
|
|
98
|
+
*/
|
|
99
|
+
export function contextLabel(record: Pick<AgentRecord, "context">, theme: Theme): string | undefined {
|
|
100
|
+
if (!record.context) return undefined;
|
|
101
|
+
const percent = contextPercent(record.context);
|
|
102
|
+
const color = percent >= 85 ? "error" : percent >= 70 ? "warning" : "dim";
|
|
103
|
+
return theme.fg(color, `ctx ${percent}%`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface DetailContentOptions {
|
|
107
|
+
width: number;
|
|
108
|
+
now: number;
|
|
109
|
+
fullPrompt: boolean;
|
|
110
|
+
progress?: ProgressSnapshot;
|
|
111
|
+
report?: string;
|
|
112
|
+
transcript?: string;
|
|
113
|
+
renderMarkdown?: (text: string, width: number) => string[];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The scrollable body of the overlay. Pure, for tests. */
|
|
117
|
+
export function detailContent(record: AgentRecord, theme: Theme, options: DetailContentOptions): string[] {
|
|
118
|
+
const dim = (text: string) => theme.fg("dim", text);
|
|
119
|
+
const lines: string[] = [];
|
|
120
|
+
const progress = options.progress;
|
|
121
|
+
const turns = progress?.turns ?? record.stats.turns;
|
|
122
|
+
const tools = progress?.toolCalls ?? record.stats.toolCalls;
|
|
123
|
+
const usage = record.totalUsage;
|
|
124
|
+
const turnText = record.status === "running" ? `turn ${turns + 1}${record.maxTurns ? `/${record.maxTurns}` : ""}` : `${turns} turn${turns === 1 ? "" : "s"}`;
|
|
125
|
+
const stats = [record.model, turnText, `${tools} tool${tools === 1 ? "" : "s"}`, formatTokens(displayTokens(usage))];
|
|
126
|
+
if (usage.cost > 0) stats.push(formatCost(usage.cost));
|
|
127
|
+
if (record.runs > 1) stats.push(`run ${record.runs}`);
|
|
128
|
+
lines.push(dim(stats.join(" · ")));
|
|
129
|
+
if (record.reason && record.status !== "completed") lines.push(theme.fg(COLORS[record.status], `reason: ${record.reason}`));
|
|
130
|
+
for (const note of record.notes) lines.push(dim(`note: ${note}`));
|
|
131
|
+
|
|
132
|
+
lines.push("", theme.bold("Prompt"));
|
|
133
|
+
const promptLines = record.prompt.replace(/\r\n?/g, "\n").trim().split("\n");
|
|
134
|
+
const shown = options.fullPrompt ? promptLines : promptLines.slice(0, PROMPT_PREVIEW_LINES);
|
|
135
|
+
for (const line of shown) lines.push(` ${line}`);
|
|
136
|
+
if (!options.fullPrompt && promptLines.length > PROMPT_PREVIEW_LINES) {
|
|
137
|
+
lines.push(dim(` … ${promptLines.length - PROMPT_PREVIEW_LINES} more lines (e to expand)`));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
lines.push("", theme.bold("Activity"));
|
|
141
|
+
const activity = record.activity;
|
|
142
|
+
if (!activity) lines.push(dim(record.status === "queued" ? " (queued)" : " (not recorded in this pi process; open the transcript)"));
|
|
143
|
+
else if (activity.length === 0) lines.push(dim(" (no tool calls yet)"));
|
|
144
|
+
else for (const entry of activity) lines.push(` ${activityLine(entry, theme, options.now)}`);
|
|
145
|
+
|
|
146
|
+
if (isRunningStatus(record.status)) {
|
|
147
|
+
const recent = progress?.recentText.trim().split(/\r?\n/).filter(Boolean).at(-1);
|
|
148
|
+
if (recent) lines.push("", `${dim("Writing: ")}${recent}`);
|
|
149
|
+
} else {
|
|
150
|
+
lines.push("", theme.bold("Report"));
|
|
151
|
+
const report = options.report?.trim() ?? "";
|
|
152
|
+
if (!report) lines.push(dim(" (no final report)"));
|
|
153
|
+
else {
|
|
154
|
+
const rendered = options.renderMarkdown?.(report, Math.max(20, options.width - 2)) ?? report.split("\n");
|
|
155
|
+
for (const line of rendered) lines.push(` ${line}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (options.transcript) {
|
|
160
|
+
lines.push("", `${dim("Transcript: ")}${options.transcript}`);
|
|
161
|
+
if (!isRunningStatus(record.status)) lines.push(`${dim("Open it in pi: ")}${openCommand(options.transcript)}`);
|
|
162
|
+
}
|
|
163
|
+
return lines;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function activityLine(entry: ToolCallEntry, theme: Theme, now: number): string {
|
|
167
|
+
if (entry.endedAt === undefined) {
|
|
168
|
+
return `${theme.fg("accent", "●")} ${entry.line}${theme.fg("dim", ` · ${formatDuration(now - entry.startedAt)}`)}`;
|
|
169
|
+
}
|
|
170
|
+
const icon = entry.isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
|
171
|
+
return `${icon} ${entry.line}${theme.fg("dim", ` · ${formatDuration(entry.endedAt - entry.startedAt)}`)}`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Scroll state with follow-the-end behaviour: following until the user scrolls up, again at the bottom. */
|
|
175
|
+
export class ScrollState {
|
|
176
|
+
top = 0;
|
|
177
|
+
following: boolean;
|
|
178
|
+
private maxTop = 0;
|
|
179
|
+
private viewport = 1;
|
|
180
|
+
|
|
181
|
+
constructor(follow: boolean) {
|
|
182
|
+
this.following = follow;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Fit to the latest content; returns the first visible line. */
|
|
186
|
+
layout(contentLines: number, viewport: number): number {
|
|
187
|
+
this.viewport = Math.max(1, viewport);
|
|
188
|
+
this.maxTop = Math.max(0, contentLines - this.viewport);
|
|
189
|
+
this.top = this.following ? this.maxTop : Math.min(this.top, this.maxTop);
|
|
190
|
+
return this.top;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
scrollBy(lines: number): void {
|
|
194
|
+
if (lines === 0) return;
|
|
195
|
+
const start = this.following ? this.maxTop : this.top;
|
|
196
|
+
this.top = Math.max(0, Math.min(this.maxTop, start + lines));
|
|
197
|
+
// Scrolling up stops following; scrolling down to the bottom resumes it.
|
|
198
|
+
this.following = lines > 0 && this.top >= this.maxTop;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
page(direction: 1 | -1): void {
|
|
202
|
+
this.scrollBy(direction * Math.max(1, this.viewport - 1));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
toStart(): void {
|
|
206
|
+
this.top = 0;
|
|
207
|
+
this.following = false;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
toEnd(): void {
|
|
211
|
+
this.following = true;
|
|
212
|
+
this.top = this.maxTop;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export class AgentDetailView implements Component {
|
|
217
|
+
private readonly scroll: ScrollState;
|
|
218
|
+
private fullPrompt = false;
|
|
219
|
+
private flash: { text: string; until: number } | undefined;
|
|
220
|
+
private readonly unsubscribe: () => void;
|
|
221
|
+
private pending: ReturnType<typeof setTimeout> | undefined;
|
|
222
|
+
private lastRender = 0;
|
|
223
|
+
private readonly tick: ReturnType<typeof setInterval>;
|
|
224
|
+
private markdownCache: { key: string; lines: string[] } | undefined;
|
|
225
|
+
private closed = false;
|
|
226
|
+
private readonly confirm: StopConfirm;
|
|
227
|
+
|
|
228
|
+
constructor(
|
|
229
|
+
private readonly host: DetailHost,
|
|
230
|
+
private readonly theme: Theme,
|
|
231
|
+
private readonly keybindings: KeybindingsManager,
|
|
232
|
+
private readonly source: DetailSource,
|
|
233
|
+
private readonly agentId: string,
|
|
234
|
+
private readonly done: () => void,
|
|
235
|
+
) {
|
|
236
|
+
this.confirm = new StopConfirm(() => source.confirmStop?.() ?? true);
|
|
237
|
+
const record = source.get(agentId);
|
|
238
|
+
// A running agent opens at the bottom and follows new activity; a finished one opens at the top.
|
|
239
|
+
this.scroll = new ScrollState(record ? isRunningStatus(record.status) : false);
|
|
240
|
+
this.unsubscribe = source.subscribe((changed) => {
|
|
241
|
+
if (changed.agentId === agentId) this.scheduleRender();
|
|
242
|
+
});
|
|
243
|
+
this.tick = setInterval(() => {
|
|
244
|
+
const current = this.source.get(this.agentId);
|
|
245
|
+
if ((current && isRunningStatus(current.status)) || this.flash) this.host.requestRender();
|
|
246
|
+
}, TICK_MS);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
render(width: number): string[] {
|
|
250
|
+
const theme = this.theme;
|
|
251
|
+
const record = this.source.get(this.agentId);
|
|
252
|
+
if (!record || width < 10) return [];
|
|
253
|
+
const now = Date.now();
|
|
254
|
+
const inner = width - 4;
|
|
255
|
+
const height = Math.max(8, Math.floor(this.host.terminal.rows * 0.8));
|
|
256
|
+
const viewport = height - 3;
|
|
257
|
+
|
|
258
|
+
const transcript = this.source.transcript(record);
|
|
259
|
+
const report = isRunningStatus(record.status) ? undefined : this.source.report(record);
|
|
260
|
+
const content = detailContent(record, theme, {
|
|
261
|
+
width: inner,
|
|
262
|
+
now,
|
|
263
|
+
fullPrompt: this.fullPrompt,
|
|
264
|
+
progress: this.source.progress(this.agentId),
|
|
265
|
+
report,
|
|
266
|
+
transcript,
|
|
267
|
+
renderMarkdown: (text, w) => this.markdown(text, w, record),
|
|
268
|
+
});
|
|
269
|
+
const top = this.scroll.layout(content.length, viewport);
|
|
270
|
+
const body = content.slice(top, top + viewport);
|
|
271
|
+
// A fixed-height box, as /background's detail: a centred overlay that grew with each activity line
|
|
272
|
+
// would breathe up and down until it filled the 80%.
|
|
273
|
+
while (body.length < viewport) body.push("");
|
|
274
|
+
|
|
275
|
+
const border = (text: string) => theme.fg("dim", text);
|
|
276
|
+
const title = ` ${record.agentId} · ${record.type} · ${record.description} `;
|
|
277
|
+
const statusText = isStopping(record) ? "stopping" : (STATUS_TEXT[record.status] ?? record.status);
|
|
278
|
+
const context = contextLabel(record, theme);
|
|
279
|
+
const status = ` ${theme.fg(COLORS[record.status], `${ICONS[record.status]} ${statusText}`)}${context ? `${theme.fg("dim", " · ")}${context}` : ""}${theme.fg("dim", ` · ${formatDuration(durationOf(record, now))}`)} `;
|
|
280
|
+
// `╭─` title, at least one `─`, status, `─╮`: the right label keeps a dash before the corner, as the
|
|
281
|
+
// boxes in /provider and /sessions do.
|
|
282
|
+
const titleText = truncateToWidth(theme.bold(title), Math.max(4, width - 5 - visibleWidth(status)), "…");
|
|
283
|
+
const fill = Math.max(1, width - 4 - visibleWidth(titleText) - visibleWidth(status));
|
|
284
|
+
const topBorder = `${border("╭─")}${titleText}${border("─".repeat(fill))}${status}${border("─╮")}`;
|
|
285
|
+
const lines = [truncateToWidth(topBorder, width, "")];
|
|
286
|
+
const row = (text: string) => {
|
|
287
|
+
const cut = truncateToWidth(text, inner, "…");
|
|
288
|
+
return `${border("│")} ${cut}${" ".repeat(Math.max(0, inner - visibleWidth(cut)))} ${border("│")}`;
|
|
289
|
+
};
|
|
290
|
+
for (const line of body) lines.push(row(line));
|
|
291
|
+
lines.push(row(this.hint(record, transcript, content.length > viewport)));
|
|
292
|
+
lines.push(border(`╰${"─".repeat(Math.max(0, width - 2))}╯`));
|
|
293
|
+
return lines;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
handleInput(data: string): void {
|
|
297
|
+
const record = this.source.get(this.agentId);
|
|
298
|
+
const kb = this.keybindings;
|
|
299
|
+
// Armed (docs/07 §4.4): only x goes on to stop. Scroll keys cancel and still scroll; every other key,
|
|
300
|
+
// Esc included, only cancels, so backing out of the stop does not also close the overlay.
|
|
301
|
+
this.confirm.keep(this.agentId, record !== undefined && isStoppable(record));
|
|
302
|
+
if (this.confirm.isArmed(this.agentId) && data !== "x") {
|
|
303
|
+
this.confirm.cancel();
|
|
304
|
+
if (!isMoveKey(data, kb)) {
|
|
305
|
+
this.host.requestRender();
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (kb.matches(data, "tui.select.cancel") || data === "q") {
|
|
310
|
+
this.close();
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
if (kb.matches(data, "tui.select.up")) this.scroll.scrollBy(-1);
|
|
314
|
+
else if (kb.matches(data, "tui.select.down")) this.scroll.scrollBy(1);
|
|
315
|
+
else if (matchesKey(data, "pageUp")) this.scroll.page(-1);
|
|
316
|
+
else if (matchesKey(data, "pageDown")) this.scroll.page(1);
|
|
317
|
+
else if (matchesKey(data, "home")) this.scroll.toStart();
|
|
318
|
+
else if (matchesKey(data, "end")) this.scroll.toEnd();
|
|
319
|
+
else if (data === "e") this.fullPrompt = !this.fullPrompt;
|
|
320
|
+
else if (data === "x" && record && isStoppable(record)) {
|
|
321
|
+
if (this.confirm.press(this.agentId)) {
|
|
322
|
+
this.source.stop(this.agentId);
|
|
323
|
+
this.setFlash(`stopping ${this.agentId}…`);
|
|
324
|
+
}
|
|
325
|
+
} else if (data === "c" && record) {
|
|
326
|
+
const transcript = this.source.transcript(record);
|
|
327
|
+
if (transcript) {
|
|
328
|
+
const command = openCommand(transcript);
|
|
329
|
+
copyToClipboard(command).then(
|
|
330
|
+
() => this.setFlash("copied: " + command),
|
|
331
|
+
() => this.setFlash("could not copy to the clipboard"),
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
} else return;
|
|
335
|
+
this.host.requestRender();
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
handleMouse(event: TuiMouseEvent): { handled: true } | undefined {
|
|
339
|
+
if (event.type !== "wheel" || !event.wheelDelta) return undefined;
|
|
340
|
+
// Scrolling moves, like the scroll keys: it cancels an armed stop.
|
|
341
|
+
this.confirm.cancel();
|
|
342
|
+
this.scroll.scrollBy(event.wheelDelta);
|
|
343
|
+
return { handled: true };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
invalidate(): void {
|
|
347
|
+
this.markdownCache = undefined;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
dispose(): void {
|
|
351
|
+
this.cleanup();
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
private close(): void {
|
|
355
|
+
if (this.closed) return;
|
|
356
|
+
this.cleanup();
|
|
357
|
+
this.done();
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
private cleanup(): void {
|
|
361
|
+
this.closed = true;
|
|
362
|
+
this.unsubscribe();
|
|
363
|
+
clearInterval(this.tick);
|
|
364
|
+
if (this.pending) clearTimeout(this.pending);
|
|
365
|
+
this.pending = undefined;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
private hint(record: AgentRecord, transcript: string | undefined, scrollable: boolean): string {
|
|
369
|
+
// The agent may have ended on its own since the first x: the arm goes with it.
|
|
370
|
+
this.confirm.keep(this.agentId, isStoppable(record));
|
|
371
|
+
if (this.confirm.isArmed(this.agentId)) return this.theme.fg("error", ARMED_HINT);
|
|
372
|
+
if (this.flash && this.flash.until > Date.now()) return this.theme.fg("warning", this.flash.text);
|
|
373
|
+
this.flash = undefined;
|
|
374
|
+
const parts = [scrollable ? "↑↓/wheel scroll" : undefined, "e prompt", isStoppable(record) ? "x stop" : undefined];
|
|
375
|
+
if (transcript && !isRunningStatus(record.status)) parts.push("c copy open command");
|
|
376
|
+
parts.push("esc close");
|
|
377
|
+
return this.theme.fg("dim", parts.filter(Boolean).join(" · "));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private setFlash(text: string): void {
|
|
381
|
+
this.flash = { text, until: Date.now() + FLASH_MS };
|
|
382
|
+
this.host.requestRender();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** Observer updates arrive per streamed token; redraw at most every 100 ms (docs/07 §6). */
|
|
386
|
+
private scheduleRender(): void {
|
|
387
|
+
if (this.closed || this.pending) return;
|
|
388
|
+
const wait = Math.max(0, RENDER_THROTTLE_MS - (Date.now() - this.lastRender));
|
|
389
|
+
this.pending = setTimeout(() => {
|
|
390
|
+
this.pending = undefined;
|
|
391
|
+
this.lastRender = Date.now();
|
|
392
|
+
this.host.requestRender();
|
|
393
|
+
}, wait);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private markdown(text: string, width: number, record: AgentRecord): string[] {
|
|
397
|
+
const key = `${record.runs}:${record.endedAt ?? ""}:${width}:${text.length}`;
|
|
398
|
+
if (this.markdownCache?.key === key) return this.markdownCache.lines;
|
|
399
|
+
let lines: string[];
|
|
400
|
+
try {
|
|
401
|
+
lines = new Markdown(text, 0, 0, getMarkdownTheme()).render(width).map((line) => line.trimEnd());
|
|
402
|
+
} catch {
|
|
403
|
+
lines = text.split("\n");
|
|
404
|
+
}
|
|
405
|
+
this.markdownCache = { key, lines };
|
|
406
|
+
return lines;
|
|
407
|
+
}
|
|
408
|
+
}
|