pi-subagent-manager 1.10.0 → 1.12.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/README.md +9 -9
- package/dist/index.d.ts +2 -0
- package/dist/index.js +790 -0
- package/dist/orch/checklist-integration.js +176 -0
- package/dist/orch/context-entries.js +6 -0
- package/dist/orch/cost-ledger.js +38 -0
- package/dist/orch/diagnostics.js +86 -0
- package/dist/orch/extensions.js +66 -0
- package/dist/orch/housekeeping-usage.js +22 -0
- package/dist/orch/housekeeping.js +248 -0
- package/dist/orch/inherited-tools.js +57 -0
- package/dist/orch/mailbox.js +195 -0
- package/dist/orch/manager.js +970 -0
- package/dist/orch/paths.js +69 -0
- package/dist/orch/prompt.js +30 -0
- package/dist/orch/registry.js +115 -0
- package/dist/orch/runtime.js +835 -0
- package/dist/orch/tools.js +112 -0
- package/dist/orch/transcript.js +165 -0
- package/dist/prefs/agent-import.js +188 -0
- package/dist/prefs/config.js +878 -0
- package/dist/prefs/import-discovery.js +547 -0
- package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +0 -1
- package/dist/prefs/models.js +56 -0
- package/dist/prefs/settings.js +491 -0
- package/dist/types.js +1 -0
- package/dist/ui/agent-loader.js +63 -0
- package/dist/ui/agent-navigation-editor.js +168 -0
- package/dist/ui/cost-footer.js +209 -0
- package/dist/ui/dialog.js +505 -0
- package/dist/ui/import-picker.js +191 -0
- package/dist/ui/live-agent-view.js +527 -0
- package/dist/ui/model-picker.js +529 -0
- package/dist/ui/settings-ui.js +671 -0
- package/dist/ui/status-ui.js +470 -0
- package/dist/ui/thread-tree.js +142 -0
- package/dist/ui/tool-picker.js +331 -0
- package/dist/ui/transcript-tool.js +91 -0
- package/dist/ui/ui.js +1019 -0
- package/package.json +17 -5
- package/docs/assets/subagent-manager-demo.gif +0 -0
- package/docs/async-lifecycle.md +0 -153
- package/docs/custom-agents.md +0 -154
- package/docs/default-agents.md +0 -95
- package/docs/demo.md +0 -63
- package/docs/development.md +0 -74
- package/docs/importing-agents.md +0 -41
- package/docs/pi-footer.md +0 -128
- package/docs/research-claude.md +0 -258
- package/docs/research-codex.md +0 -143
- package/docs/research-default-agent-models.md +0 -121
- package/docs/research-model-audit-2026-10.md +0 -154
- package/docs/research-model-roles-coding.md +0 -99
- package/docs/research-model-roles-writing.md +0 -78
- package/docs/research-researcher-workflow.md +0 -97
- package/docs/settings.md +0 -293
- package/docs/subagent-extension-limitations.md +0 -98
- package/docs/threads.md +0 -73
- package/docs/tools-and-ui.md +0 -129
- package/src/index.ts +0 -920
- package/src/orch/checklist-integration.ts +0 -230
- package/src/orch/context-entries.ts +0 -15
- package/src/orch/cost-ledger.ts +0 -56
- package/src/orch/diagnostics.ts +0 -95
- package/src/orch/extensions.ts +0 -83
- package/src/orch/housekeeping-usage.ts +0 -47
- package/src/orch/housekeeping.ts +0 -348
- package/src/orch/inherited-tools.ts +0 -84
- package/src/orch/mailbox.ts +0 -261
- package/src/orch/manager.ts +0 -1084
- package/src/orch/paths.ts +0 -73
- package/src/orch/prompt.ts +0 -39
- package/src/orch/registry.ts +0 -168
- package/src/orch/runtime.ts +0 -1041
- package/src/orch/tools.ts +0 -190
- package/src/orch/transcript.ts +0 -186
- package/src/prefs/agent-import.ts +0 -245
- package/src/prefs/config.ts +0 -1017
- package/src/prefs/import-discovery.ts +0 -643
- package/src/prefs/models.ts +0 -74
- package/src/prefs/settings.ts +0 -614
- package/src/types.ts +0 -271
- package/src/ui/agent-loader.ts +0 -98
- package/src/ui/agent-navigation-editor.ts +0 -233
- package/src/ui/cost-footer.ts +0 -230
- package/src/ui/dialog.ts +0 -678
- package/src/ui/import-picker.ts +0 -231
- package/src/ui/live-agent-view.ts +0 -600
- package/src/ui/model-picker.ts +0 -701
- package/src/ui/settings-ui.ts +0 -830
- package/src/ui/status-ui.ts +0 -628
- package/src/ui/thread-tree.ts +0 -173
- package/src/ui/tool-picker.ts +0 -398
- package/src/ui/transcript-tool.ts +0 -142
- package/src/ui/ui.ts +0 -1407
package/dist/ui/ui.js
ADDED
|
@@ -0,0 +1,1019 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { parse as parseShell } from "shell-quote";
|
|
7
|
+
import { getSelectListTheme, } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { Container, SelectList, Text, colorToRgb, rgbColor, stripTerminalSequences, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui";
|
|
9
|
+
import { AGENT_COLORS, parseAgentType, serializeAgentType } from "../prefs/config.js";
|
|
10
|
+
import { editModelPreferences, MODEL_EDITOR_CANCEL } from "./model-picker.js";
|
|
11
|
+
import { editToolSelection, TOOL_EDITOR_CANCEL } from "./tool-picker.js";
|
|
12
|
+
import { canOpenDialog, dialogEditor, dialogMenu, dialogHeight, frameDialog, DIALOG_OPTIONS, withDialogSession, } from "./dialog.js";
|
|
13
|
+
import { getModelPreferences } from "../prefs/models.js";
|
|
14
|
+
import { AGENT_PROGRESS_INTERVAL, agentProgressIcon, isAgentLoaderGlyph } from "./agent-loader.js";
|
|
15
|
+
export { AGENT_PROGRESS_INTERVAL, agentProgressIcon } from "./agent-loader.js";
|
|
16
|
+
import { buildStatusTree, lastStarted, threadActivity } from "./thread-tree.js";
|
|
17
|
+
import { THINKING_LEVELS, } from "../types.js";
|
|
18
|
+
export function sanitizeText(text) {
|
|
19
|
+
return stripTerminalSequences(text).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
20
|
+
}
|
|
21
|
+
function agentColorToken(color) {
|
|
22
|
+
return AGENT_COLORS.includes(color)
|
|
23
|
+
? color
|
|
24
|
+
: "accent";
|
|
25
|
+
}
|
|
26
|
+
function contrastPill(label, color, theme) {
|
|
27
|
+
const background = theme.colors[agentColorToken(color)];
|
|
28
|
+
const { r, g, b } = colorToRgb(background);
|
|
29
|
+
const linear = (channel) => {
|
|
30
|
+
const value = channel / 255;
|
|
31
|
+
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
|
|
32
|
+
};
|
|
33
|
+
const luminance = 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
|
|
34
|
+
const foreground = luminance > Math.sqrt(0.0525) - 0.05 ? 0 : 255;
|
|
35
|
+
return theme.style(` ${sanitizeText(label)} `, {
|
|
36
|
+
bg: background,
|
|
37
|
+
fg: rgbColor(foreground, foreground, foreground),
|
|
38
|
+
bold: true,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
export function agentTypeLabel(type, icon, nerdFontIcons = false, loaderIcon) {
|
|
42
|
+
const role = nerdFontIcons && typeof icon === "string" && /^\p{Co}$/u.test(icon) ? `${icon} ` : "";
|
|
43
|
+
const progress = loaderIcon && isAgentLoaderGlyph(loaderIcon, nerdFontIcons) ? `${loaderIcon} ` : "";
|
|
44
|
+
return `${progress}${role}${sanitizeText(type)}`;
|
|
45
|
+
}
|
|
46
|
+
export function agentTypeBadge(type, color, theme, icon, nerdFontIcons = false, loaderIcon) {
|
|
47
|
+
return contrastPill(agentTypeLabel(type, icon, nerdFontIcons, loaderIcon), color, theme);
|
|
48
|
+
}
|
|
49
|
+
function agentPath(path, color, theme) {
|
|
50
|
+
return theme.fg(agentColorToken(color), sanitizeText(path));
|
|
51
|
+
}
|
|
52
|
+
function metricCount(value) {
|
|
53
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
|
|
54
|
+
}
|
|
55
|
+
function elapsedTotal(thread, now = Date.now()) {
|
|
56
|
+
const live = typeof thread.startedAt === "number" &&
|
|
57
|
+
Number.isFinite(thread.startedAt) &&
|
|
58
|
+
(thread.state === "starting" || thread.state === "running")
|
|
59
|
+
? now - thread.startedAt
|
|
60
|
+
: 0;
|
|
61
|
+
const total = metricCount(thread.elapsedMs) + live;
|
|
62
|
+
return Number.isFinite(total) ? total : 0;
|
|
63
|
+
}
|
|
64
|
+
function formatDuration(ms) {
|
|
65
|
+
const total = Math.max(0, Math.floor(ms / 1000));
|
|
66
|
+
const seconds = total % 60;
|
|
67
|
+
const minutes = Math.floor(total / 60) % 60;
|
|
68
|
+
const hours = Math.floor(total / 3600) % 24;
|
|
69
|
+
const days = Math.floor(total / 86400);
|
|
70
|
+
if (days > 0)
|
|
71
|
+
return `${days}d${hours}h`;
|
|
72
|
+
if (hours > 0)
|
|
73
|
+
return `${hours}h${minutes}m`;
|
|
74
|
+
if (minutes > 0)
|
|
75
|
+
return `${minutes}m${seconds}s`;
|
|
76
|
+
return `${seconds}s`;
|
|
77
|
+
}
|
|
78
|
+
const compactCount = new Intl.NumberFormat("en", {
|
|
79
|
+
notation: "compact",
|
|
80
|
+
maximumFractionDigits: 1,
|
|
81
|
+
});
|
|
82
|
+
function formatCount(value) {
|
|
83
|
+
return compactCount.format(metricCount(value)).toLowerCase();
|
|
84
|
+
}
|
|
85
|
+
export function threadMetrics(thread, now = Date.now()) {
|
|
86
|
+
const cost = thread.costUsd === undefined ? "" : ` $${thread.costUsd.toFixed(4)}`;
|
|
87
|
+
return `${formatDuration(elapsedTotal(thread, now))} ↑${formatCount(thread.inputTokens)} ↓${formatCount(thread.outputTokens)}${cost}`;
|
|
88
|
+
}
|
|
89
|
+
function fitLine(left, right, width) {
|
|
90
|
+
if (width <= 0)
|
|
91
|
+
return "";
|
|
92
|
+
const rightWidth = visibleWidth(right);
|
|
93
|
+
if (rightWidth >= width)
|
|
94
|
+
return truncateToWidth(right, width, "");
|
|
95
|
+
const fitted = truncateToWidth(left, width - rightWidth - 1);
|
|
96
|
+
const pad = width - visibleWidth(fitted) - rightWidth;
|
|
97
|
+
return fitted + " ".repeat(Math.max(0, pad)) + right;
|
|
98
|
+
}
|
|
99
|
+
function isLive(thread) {
|
|
100
|
+
return thread.path !== "/root" && (thread.state === "starting" || thread.state === "running");
|
|
101
|
+
}
|
|
102
|
+
export function renderThreads(threads, width, theme, nerdFontIcons = false, loaderStyle = "circle") {
|
|
103
|
+
const priority = (thread) => thread.state === "starting" || thread.state === "running"
|
|
104
|
+
? 0
|
|
105
|
+
: thread.state === "paused"
|
|
106
|
+
? 1
|
|
107
|
+
: 2;
|
|
108
|
+
const visible = threads
|
|
109
|
+
.filter((thread) => thread.path !== "/root")
|
|
110
|
+
.sort((a, b) => priority(a) - priority(b) || b.updatedAt - a.updatedAt || b.createdAt - a.createdAt);
|
|
111
|
+
const limit = visible.length > 8 ? 7 : 8;
|
|
112
|
+
const lines = visible.slice(0, limit).map((thread) => {
|
|
113
|
+
const stateColor = thread.state === "failed" ? "error" : thread.state === "paused" ? "warning" : "accent";
|
|
114
|
+
const badge = agentTypeBadge(thread.type, thread.color, theme, thread.icon, nerdFontIcons, agentProgressIcon(thread, nerdFontIcons, Date.now(), true, loaderStyle));
|
|
115
|
+
const path = agentPath(thread.path, thread.color, theme);
|
|
116
|
+
const state = theme.fg(stateColor, `[${sanitizeText(thread.state)}]`);
|
|
117
|
+
const left = `${badge} ${path} ${state} ${sanitizeText(threadActivity(thread))}`;
|
|
118
|
+
return fitLine(left, theme.fg("muted", threadMetrics(thread)), Math.max(0, width));
|
|
119
|
+
});
|
|
120
|
+
if (visible.length > limit) {
|
|
121
|
+
lines.push(truncateToWidth(theme.fg("muted", `+${visible.length - limit} more threads · /agents tree`), Math.max(0, width)));
|
|
122
|
+
}
|
|
123
|
+
return lines;
|
|
124
|
+
}
|
|
125
|
+
const WIDGET_ROOT = "/root";
|
|
126
|
+
const MAX_WIDGET_LINES = 12;
|
|
127
|
+
const AGENT_WIDGET_PLACEMENT = { placement: "aboveEditor" };
|
|
128
|
+
const AGENT_BROWSER_HINT = "Press ← to open subagent browser";
|
|
129
|
+
function agentWidgetStatus(running, omitted, width, theme, showBrowserHint) {
|
|
130
|
+
const details = [
|
|
131
|
+
omitted > 0 ? `+${omitted} more agents` : "",
|
|
132
|
+
showBrowserHint && running > 0 ? AGENT_BROWSER_HINT : "",
|
|
133
|
+
showBrowserHint ? "→ collapse" : "",
|
|
134
|
+
].filter(Boolean);
|
|
135
|
+
return truncateToWidth(theme.fg("accent", `${running} running`) +
|
|
136
|
+
(details.length ? theme.fg("muted", ` · ${details.join(" · ")}`) : ""), width, "");
|
|
137
|
+
}
|
|
138
|
+
function statePriority(state) {
|
|
139
|
+
if (state === "starting" || state === "running")
|
|
140
|
+
return 0;
|
|
141
|
+
if (state === "paused")
|
|
142
|
+
return 1;
|
|
143
|
+
return 2;
|
|
144
|
+
}
|
|
145
|
+
function agentStateColor(state) {
|
|
146
|
+
return state === "failed" ? "error" : state === "paused" ? "warning" : "accent";
|
|
147
|
+
}
|
|
148
|
+
function agentLine(row, width, theme, nerdFontIcons, animate, loaderStyle) {
|
|
149
|
+
const thread = row.thread;
|
|
150
|
+
const badge = agentTypeBadge(thread.type, thread.color, theme, thread.icon, nerdFontIcons, agentProgressIcon(thread, nerdFontIcons, Date.now(), animate, loaderStyle));
|
|
151
|
+
const left = `${row.prefix}${badge} ${agentPath(thread.path, thread.color, theme)} ${theme.fg(agentStateColor(thread.state), `[${sanitizeText(thread.state)}]`)} ${sanitizeText(threadActivity(thread, thread.task))}`;
|
|
152
|
+
return fitLine(left, theme.fg("muted", threadMetrics(thread)), width);
|
|
153
|
+
}
|
|
154
|
+
function placeholderLine(row, width, theme) {
|
|
155
|
+
return truncateToWidth(`${row.prefix}${theme.fg("muted", `${sanitizeText(row.path)} missing parent`)}`, width, "");
|
|
156
|
+
}
|
|
157
|
+
function takeWidgetRows(rows, budget) {
|
|
158
|
+
const parents = new Map();
|
|
159
|
+
const stack = [];
|
|
160
|
+
for (const [index, row] of rows.entries()) {
|
|
161
|
+
while (stack.length && rows[stack[stack.length - 1]].prefix.length >= row.prefix.length)
|
|
162
|
+
stack.pop();
|
|
163
|
+
parents.set(index, [...stack]);
|
|
164
|
+
stack.push(index);
|
|
165
|
+
}
|
|
166
|
+
const rowCost = (row) => (row.path === WIDGET_ROOT ? 0 : 1);
|
|
167
|
+
const candidates = rows
|
|
168
|
+
.map((row, index) => ({ row, index }))
|
|
169
|
+
.filter(({ row }) => row.thread && row.path !== WIDGET_ROOT)
|
|
170
|
+
.sort((a, b) => statePriority(a.row.thread.state) - statePriority(b.row.thread.state) ||
|
|
171
|
+
lastStarted(b.row.thread) - lastStarted(a.row.thread) ||
|
|
172
|
+
a.index - b.index);
|
|
173
|
+
const chosen = new Set();
|
|
174
|
+
let used = 0;
|
|
175
|
+
for (const { index } of candidates) {
|
|
176
|
+
const needed = [...parents.get(index), index].filter((ancestor) => !chosen.has(ancestor));
|
|
177
|
+
const cost = needed.reduce((total, ancestor) => total + rowCost(rows[ancestor]), 0);
|
|
178
|
+
if (used + cost > budget)
|
|
179
|
+
continue;
|
|
180
|
+
for (const ancestor of needed)
|
|
181
|
+
chosen.add(ancestor);
|
|
182
|
+
used += cost;
|
|
183
|
+
}
|
|
184
|
+
if (!chosen.size) {
|
|
185
|
+
for (const [index, row] of rows.entries()) {
|
|
186
|
+
const cost = rowCost(row);
|
|
187
|
+
if (used + cost > budget)
|
|
188
|
+
break;
|
|
189
|
+
chosen.add(index);
|
|
190
|
+
used += cost;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return rows.filter((row, index) => row.path !== WIDGET_ROOT && chosen.has(index));
|
|
194
|
+
}
|
|
195
|
+
export function renderAgentTree(threads, width, theme, { showBrowserHint = true, nerdFontIcons = false, animate = true, loaderStyle = "circle", } = {}) {
|
|
196
|
+
const columns = Math.max(0, width);
|
|
197
|
+
const rows = buildStatusTree(threads, new Set());
|
|
198
|
+
const agents = rows.filter((row) => row.thread && row.path !== WIDGET_ROOT);
|
|
199
|
+
if (!agents.length)
|
|
200
|
+
return [];
|
|
201
|
+
const live = agents.filter((row) => row.thread.state === "starting" || row.thread.state === "running").length;
|
|
202
|
+
const paused = agents.filter((row) => row.thread.state === "paused").length;
|
|
203
|
+
const heading = fitLine(theme.fg("accent", "Agents"), theme.fg("muted", `${live} live · ${paused} paused`), columns);
|
|
204
|
+
const visible = takeWidgetRows(rows, MAX_WIDGET_LINES - 2);
|
|
205
|
+
const omitted = agents.length - visible.filter((row) => row.thread).length;
|
|
206
|
+
const lines = [heading];
|
|
207
|
+
for (const row of visible) {
|
|
208
|
+
if (!row.thread) {
|
|
209
|
+
lines.push(placeholderLine(row, columns, theme));
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
lines.push(agentLine(row, columns, theme, nerdFontIcons, animate, loaderStyle));
|
|
213
|
+
}
|
|
214
|
+
lines.push(agentWidgetStatus(live, omitted, columns, theme, showBrowserHint));
|
|
215
|
+
return lines;
|
|
216
|
+
}
|
|
217
|
+
export function renderAgentSummary(threads, width, theme, { showBrowserHint = true, nerdFontIcons = false, animate = true, loaderStyle = "circle", expandHint = false, } = {}) {
|
|
218
|
+
const agents = new Map();
|
|
219
|
+
for (const thread of threads) {
|
|
220
|
+
if (thread?.path && thread.path !== WIDGET_ROOT && !agents.has(thread.path))
|
|
221
|
+
agents.set(thread.path, thread);
|
|
222
|
+
}
|
|
223
|
+
if (!agents.size)
|
|
224
|
+
return [];
|
|
225
|
+
const counts = {
|
|
226
|
+
running: 0,
|
|
227
|
+
stopped: 0,
|
|
228
|
+
failed: 0,
|
|
229
|
+
paused: 0,
|
|
230
|
+
completed: 0,
|
|
231
|
+
};
|
|
232
|
+
let input = 0;
|
|
233
|
+
let output = 0;
|
|
234
|
+
for (const thread of agents.values()) {
|
|
235
|
+
counts[thread.state === "starting" ? "running" : thread.state] += 1;
|
|
236
|
+
if (isLive(thread)) {
|
|
237
|
+
input += metricCount(thread.inputTokens);
|
|
238
|
+
output += metricCount(thread.outputTokens);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const statuses = [
|
|
242
|
+
["running", "accent"],
|
|
243
|
+
["stopped", "muted"],
|
|
244
|
+
["failed", "error"],
|
|
245
|
+
["paused", "warning"],
|
|
246
|
+
["completed", "success"],
|
|
247
|
+
];
|
|
248
|
+
const left = statuses
|
|
249
|
+
.filter(([state]) => state === "running" || counts[state] > 0)
|
|
250
|
+
.map(([state, color]) => {
|
|
251
|
+
const progress = counts[state] > 0
|
|
252
|
+
? agentProgressIcon({ state }, nerdFontIcons, Date.now(), animate, loaderStyle)
|
|
253
|
+
: undefined;
|
|
254
|
+
return theme.fg(color, `${progress ? `${progress} ` : ""}${counts[state]} ${state}`);
|
|
255
|
+
})
|
|
256
|
+
.join(theme.fg("muted", ", ")) +
|
|
257
|
+
(showBrowserHint && counts.running > 0
|
|
258
|
+
? theme.fg("muted", expandHint ? " · ← expand" : " · ← browser")
|
|
259
|
+
: "");
|
|
260
|
+
const right = theme.fg("muted", `↑${formatCount(input)} ↓${formatCount(output)}`);
|
|
261
|
+
return [fitLine(left, right, Math.max(0, width))];
|
|
262
|
+
}
|
|
263
|
+
export function updateWidget(ctx, threads, mode = "full", nerdFontIcons = false, rootTurnEnded = false, loaderStyle = "circle", sessionCollapsed = false) {
|
|
264
|
+
if (!ctx.hasUI)
|
|
265
|
+
return;
|
|
266
|
+
if (!threads.some((thread) => thread.path !== "/root")) {
|
|
267
|
+
ctx.ui.setWidget("pi-subagent", undefined, AGENT_WIDGET_PLACEMENT);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const settled = rootTurnEnded && !threads.some(isLive);
|
|
271
|
+
const render = mode === "minimal" || settled ? renderAgentSummary : renderAgentTree;
|
|
272
|
+
if (ctx.mode === "rpc") {
|
|
273
|
+
ctx.ui.setWidget("pi-subagent", render(threads, 80, ctx.ui.theme, {
|
|
274
|
+
showBrowserHint: false,
|
|
275
|
+
nerdFontIcons,
|
|
276
|
+
loaderStyle,
|
|
277
|
+
animate: false,
|
|
278
|
+
}), AGENT_WIDGET_PLACEMENT);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
const snapshot = threads.map((thread) => ({ ...thread }));
|
|
282
|
+
ctx.ui.setWidget("pi-subagent", (tui) => {
|
|
283
|
+
let timer;
|
|
284
|
+
if (snapshot.some(isLive)) {
|
|
285
|
+
timer = setInterval(() => tui.requestRender(), AGENT_PROGRESS_INTERVAL);
|
|
286
|
+
timer.unref();
|
|
287
|
+
}
|
|
288
|
+
return {
|
|
289
|
+
render: (width) => render(snapshot, width, ctx.ui.theme, {
|
|
290
|
+
showBrowserHint: !settled,
|
|
291
|
+
nerdFontIcons,
|
|
292
|
+
loaderStyle,
|
|
293
|
+
expandHint: sessionCollapsed,
|
|
294
|
+
}),
|
|
295
|
+
invalidate: () => { },
|
|
296
|
+
dispose: () => {
|
|
297
|
+
if (timer)
|
|
298
|
+
clearInterval(timer);
|
|
299
|
+
timer = undefined;
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
}, AGENT_WIDGET_PLACEMENT);
|
|
303
|
+
}
|
|
304
|
+
export async function showThreads(ctx, controller, path) {
|
|
305
|
+
if (!ctx.hasUI)
|
|
306
|
+
return;
|
|
307
|
+
let selectedPath = path;
|
|
308
|
+
while (true) {
|
|
309
|
+
try {
|
|
310
|
+
if (!selectedPath) {
|
|
311
|
+
const threads = controller.list().filter((thread) => thread.path !== "/root");
|
|
312
|
+
if (!threads.length) {
|
|
313
|
+
ctx.ui.notify("No subagent threads.", "info");
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
const labels = threads.map((thread) => `${sanitizeText(thread.path)} [${sanitizeText(thread.state)}] ${sanitizeText(thread.status)}`);
|
|
317
|
+
const selected = await ctx.ui.select("Subagent threads", labels);
|
|
318
|
+
if (selected === undefined)
|
|
319
|
+
return;
|
|
320
|
+
selectedPath = threads[labels.indexOf(selected)]?.path;
|
|
321
|
+
if (!selectedPath)
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (selectedPath === "/root")
|
|
325
|
+
throw new Error("/root is the current Pi thread, not a subagent.");
|
|
326
|
+
const thread = controller.get(selectedPath);
|
|
327
|
+
const children = controller.list().filter((child) => child.parent === selectedPath);
|
|
328
|
+
const title = `${sanitizeText(thread.path)} [${sanitizeText(thread.state)}] ${sanitizeText(thread.status)}`;
|
|
329
|
+
const action = await ctx.ui.select(title, [
|
|
330
|
+
"View output",
|
|
331
|
+
"View transcript",
|
|
332
|
+
"Send input / resume",
|
|
333
|
+
"Stop",
|
|
334
|
+
...(children.length ? ["Children"] : []),
|
|
335
|
+
"Back",
|
|
336
|
+
]);
|
|
337
|
+
if (!action || action === "Back") {
|
|
338
|
+
if (path)
|
|
339
|
+
return;
|
|
340
|
+
selectedPath = undefined;
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (action === "View output" || action === "View transcript") {
|
|
344
|
+
const text = action === "View output"
|
|
345
|
+
? controller.output(selectedPath)
|
|
346
|
+
: await controller.transcript(selectedPath);
|
|
347
|
+
await ctx.ui.editor(`${sanitizeText(selectedPath)} — READ ONLY (changes discarded)`, text.split("\n").map(sanitizeText).join("\n"));
|
|
348
|
+
}
|
|
349
|
+
else if (action === "Send input / resume") {
|
|
350
|
+
const message = await ctx.ui.editor("Send input / resume retained session", "");
|
|
351
|
+
if (message?.trim())
|
|
352
|
+
await controller.steer(selectedPath, message);
|
|
353
|
+
}
|
|
354
|
+
else if (action === "Stop") {
|
|
355
|
+
if (await ctx.ui.confirm("Stop thread", `Stop ${sanitizeText(selectedPath)} and its descendants?`))
|
|
356
|
+
await controller.stop(selectedPath);
|
|
357
|
+
}
|
|
358
|
+
else if (action === "Children") {
|
|
359
|
+
const labels = children.map((child) => `${sanitizeText(child.path)} [${sanitizeText(child.state)}] ${sanitizeText(child.status)}`);
|
|
360
|
+
const selected = await ctx.ui.select("Children", labels);
|
|
361
|
+
if (selected !== undefined)
|
|
362
|
+
selectedPath = children[labels.indexOf(selected)]?.path ?? selectedPath;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
ctx.ui.notify(sanitizeText(error instanceof Error ? error.message : String(error)), "error");
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
export function editorArguments(command) {
|
|
372
|
+
const args = parseShell(command, process.env);
|
|
373
|
+
if (!args.length || args.some((arg) => typeof arg !== "string") || !args[0]) {
|
|
374
|
+
throw new Error("VISUAL/EDITOR must be an executable and arguments, without shell operators or globs.");
|
|
375
|
+
}
|
|
376
|
+
return args;
|
|
377
|
+
}
|
|
378
|
+
async function externalEdit(ctx, text) {
|
|
379
|
+
if (ctx.mode !== "tui")
|
|
380
|
+
throw new Error("External editing requires interactive TUI mode.");
|
|
381
|
+
const [command, ...args] = editorArguments(process.env.VISUAL || process.env.EDITOR || "vi");
|
|
382
|
+
const directory = await mkdtemp(join(tmpdir(), "pi-subagent-"));
|
|
383
|
+
const file = join(directory, "agent.md");
|
|
384
|
+
try {
|
|
385
|
+
await writeFile(file, text, "utf8");
|
|
386
|
+
await ctx.ui.custom((tui, _theme, _keys, done) => {
|
|
387
|
+
tui.stop();
|
|
388
|
+
try {
|
|
389
|
+
const result = spawnSync(command, [...args, file], {
|
|
390
|
+
stdio: "inherit",
|
|
391
|
+
env: process.env,
|
|
392
|
+
});
|
|
393
|
+
if (result.error)
|
|
394
|
+
throw result.error;
|
|
395
|
+
if (result.status !== 0)
|
|
396
|
+
throw new Error(`Editor exited with status ${result.status ?? result.signal}.`);
|
|
397
|
+
}
|
|
398
|
+
finally {
|
|
399
|
+
tui.start();
|
|
400
|
+
tui.requestRender(true);
|
|
401
|
+
}
|
|
402
|
+
done();
|
|
403
|
+
return { render: () => [], invalidate: () => { } };
|
|
404
|
+
});
|
|
405
|
+
return await readFile(file, "utf8");
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
await rm(directory, { recursive: true, force: true });
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
async function editToolList(ctx, type, field, options) {
|
|
412
|
+
const value = await editToolSelection(ctx, field, type.tools?.[field], options);
|
|
413
|
+
if (value === TOOL_EDITOR_CANCEL)
|
|
414
|
+
return;
|
|
415
|
+
if (value === undefined) {
|
|
416
|
+
if (type.tools)
|
|
417
|
+
delete type.tools[field];
|
|
418
|
+
}
|
|
419
|
+
else {
|
|
420
|
+
type.tools ??= {};
|
|
421
|
+
type.tools[field] = [...value];
|
|
422
|
+
}
|
|
423
|
+
if (type.tools && !Object.keys(type.tools).length)
|
|
424
|
+
delete type.tools;
|
|
425
|
+
}
|
|
426
|
+
const AGENT_COLOR_DEFAULT = "__default__";
|
|
427
|
+
const AGENT_COLOR_CANCEL = Symbol("agent-color-cancel");
|
|
428
|
+
class AgentColorPickerComponent extends Container {
|
|
429
|
+
tui;
|
|
430
|
+
agentName;
|
|
431
|
+
items;
|
|
432
|
+
preview;
|
|
433
|
+
theme;
|
|
434
|
+
selectList;
|
|
435
|
+
constructor(tui, theme, currentColor, agentName, onSelect, onCancel) {
|
|
436
|
+
super();
|
|
437
|
+
this.tui = tui;
|
|
438
|
+
this.agentName = agentName;
|
|
439
|
+
this.theme = theme;
|
|
440
|
+
this.items = [
|
|
441
|
+
{
|
|
442
|
+
value: AGENT_COLOR_DEFAULT,
|
|
443
|
+
label: "Default (inherit)",
|
|
444
|
+
description: "Use the default accent background for the type pill",
|
|
445
|
+
},
|
|
446
|
+
...AGENT_COLORS.map((color) => ({
|
|
447
|
+
value: color,
|
|
448
|
+
label: contrastPill(color, color, theme),
|
|
449
|
+
description: `Type pill background: ${color}`,
|
|
450
|
+
})),
|
|
451
|
+
];
|
|
452
|
+
this.preview = new Text();
|
|
453
|
+
this.selectList = new SelectList(this.items, 10, getSelectListTheme(), {
|
|
454
|
+
minPrimaryColumnWidth: 18,
|
|
455
|
+
maxPrimaryColumnWidth: 28,
|
|
456
|
+
});
|
|
457
|
+
const selectedIndex = this.items.findIndex((item) => item.value === (currentColor ?? AGENT_COLOR_DEFAULT));
|
|
458
|
+
this.selectList.setSelectedIndex(selectedIndex >= 0 ? selectedIndex : 0);
|
|
459
|
+
this.selectList.onSelectionChange = (item) => {
|
|
460
|
+
this.updatePreview(tui, item.value);
|
|
461
|
+
};
|
|
462
|
+
this.selectList.onSelect = (item) => {
|
|
463
|
+
onSelect(item.value === AGENT_COLOR_DEFAULT ? undefined : item.value);
|
|
464
|
+
};
|
|
465
|
+
this.selectList.onCancel = onCancel;
|
|
466
|
+
this.updatePreview(tui, this.items[selectedIndex >= 0 ? selectedIndex : 0].value);
|
|
467
|
+
}
|
|
468
|
+
getItems() {
|
|
469
|
+
return this.items;
|
|
470
|
+
}
|
|
471
|
+
render(width) {
|
|
472
|
+
const height = dialogHeight(this.tui);
|
|
473
|
+
const budget = Math.max(1, height - 7);
|
|
474
|
+
const selected = this.items.findIndex((item) => item.value === this.selectList.getSelectedItem()?.value);
|
|
475
|
+
const start = Math.max(0, Math.min(selected - budget + 1, this.items.length - budget));
|
|
476
|
+
const body = [
|
|
477
|
+
` ${truncateToWidth(this.preview
|
|
478
|
+
.render(1000)
|
|
479
|
+
.map((line) => line.trim())
|
|
480
|
+
.filter(Boolean)
|
|
481
|
+
.join(" "), Math.max(1, width - 4), "")}`,
|
|
482
|
+
"",
|
|
483
|
+
...this.items
|
|
484
|
+
.slice(start, start + budget)
|
|
485
|
+
.map((item, i) => `${start + i === selected ? "›" : " "} ${item.label} ${this.theme.fg("muted", item.description ?? "")}`),
|
|
486
|
+
];
|
|
487
|
+
return frameDialog(this.theme, width, height, "Agent color", body, "↑↓ preview · Enter apply · Esc cancel");
|
|
488
|
+
}
|
|
489
|
+
getPreview() {
|
|
490
|
+
return this.preview;
|
|
491
|
+
}
|
|
492
|
+
getSelectList() {
|
|
493
|
+
return this.selectList;
|
|
494
|
+
}
|
|
495
|
+
handleInput(keyData) {
|
|
496
|
+
this.selectList.handleInput(keyData);
|
|
497
|
+
}
|
|
498
|
+
updatePreview(tui, value) {
|
|
499
|
+
const color = value === AGENT_COLOR_DEFAULT ? undefined : value;
|
|
500
|
+
const badge = agentTypeBadge(this.agentName, color, this.theme);
|
|
501
|
+
const path = agentPath("/root/example-task", color, this.theme);
|
|
502
|
+
this.preview.setText(`Preview: ${badge} ${path} ${this.theme.fg("accent", "[running]")} Working`);
|
|
503
|
+
tui.requestRender();
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
async function selectAgentColor(ctx, currentColor, agentName) {
|
|
507
|
+
return ctx.ui.custom((tui, theme, _keys, done) => {
|
|
508
|
+
return new AgentColorPickerComponent(tui, theme, currentColor, agentName, (value) => done(value), () => done(AGENT_COLOR_CANCEL));
|
|
509
|
+
}, DIALOG_OPTIONS);
|
|
510
|
+
}
|
|
511
|
+
async function editDocument(ctx, type, external) {
|
|
512
|
+
const original = serializeAgentType(type);
|
|
513
|
+
let text = original;
|
|
514
|
+
while (true) {
|
|
515
|
+
try {
|
|
516
|
+
if (external) {
|
|
517
|
+
text = await externalEdit(ctx, text);
|
|
518
|
+
}
|
|
519
|
+
else {
|
|
520
|
+
const end = text.indexOf("\n---", 4);
|
|
521
|
+
const yaml = await dialogEditor(ctx, "Agent frontmatter YAML (Markdown body preserved)", text.slice(4, end));
|
|
522
|
+
if (yaml === undefined)
|
|
523
|
+
return;
|
|
524
|
+
text = `---\n${yaml.replace(/\n?$/, "\n")}---\n${type.systemPrompt}`;
|
|
525
|
+
}
|
|
526
|
+
return {
|
|
527
|
+
...parseAgentType(text),
|
|
528
|
+
filePath: type.filePath,
|
|
529
|
+
source: type.source,
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
catch (error) {
|
|
533
|
+
const diagnostic = sanitizeText(error instanceof Error ? error.message : String(error));
|
|
534
|
+
ctx.ui.notify(`Edit not accepted: ${diagnostic}. Original definition is unchanged.`, "error");
|
|
535
|
+
const action = await dialogMenu(ctx, "Invalid edit — retry?", [
|
|
536
|
+
{
|
|
537
|
+
id: "Retry",
|
|
538
|
+
label: "Retry",
|
|
539
|
+
value: "Continue editing",
|
|
540
|
+
help: diagnostic,
|
|
541
|
+
},
|
|
542
|
+
{
|
|
543
|
+
id: "Cancel",
|
|
544
|
+
label: "Cancel",
|
|
545
|
+
value: "Restore previous definition",
|
|
546
|
+
help: diagnostic,
|
|
547
|
+
},
|
|
548
|
+
]);
|
|
549
|
+
if (action !== "Retry")
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function assertSaveDestination(store, type, original, scope, kind = "fork") {
|
|
555
|
+
if (kind === "override" && original && type.name !== original.name) {
|
|
556
|
+
throw new Error("Settings overrides cannot rename the agent; fork it instead.");
|
|
557
|
+
}
|
|
558
|
+
const entries = store.list();
|
|
559
|
+
const sameName = entries.find((entry) => entry.name === type.name);
|
|
560
|
+
if (sameName && (!original || type.name !== original.name)) {
|
|
561
|
+
throw new Error(`Agent type ${type.name} already exists; choose a different name.`);
|
|
562
|
+
}
|
|
563
|
+
const destination = store.destination(type.name, scope, original, kind);
|
|
564
|
+
if (existsSync(destination) &&
|
|
565
|
+
(!original?.filePath || resolve(original.filePath) !== destination)) {
|
|
566
|
+
throw new Error(`Refusing to overwrite existing definition ${destination}. Edit that definition instead.`);
|
|
567
|
+
}
|
|
568
|
+
const otherKind = kind === "fork" ? "override" : "fork";
|
|
569
|
+
const otherDestination = store.destination(type.name, scope, undefined, otherKind);
|
|
570
|
+
if (otherDestination !== destination &&
|
|
571
|
+
existsSync(otherDestination) &&
|
|
572
|
+
(!original?.filePath || resolve(original.filePath) !== otherDestination)) {
|
|
573
|
+
const kept = kind === "fork" ? ".md (full fork)" : ".yml (settings override)";
|
|
574
|
+
throw new Error(`Agent type ${type.name} already has a ${otherKind === "fork" ? ".md fork" : ".yml override"} in this scope (${otherDestination}). Remove it before saving a ${kept}.`);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
const EDIT_MENU_ACTIONS = [
|
|
578
|
+
"Customization",
|
|
579
|
+
"name",
|
|
580
|
+
"description",
|
|
581
|
+
"models",
|
|
582
|
+
"modelSuggestions",
|
|
583
|
+
"thinkingLevel",
|
|
584
|
+
"tools.allow",
|
|
585
|
+
"tools.block",
|
|
586
|
+
"color",
|
|
587
|
+
"icon",
|
|
588
|
+
"systemPrompt",
|
|
589
|
+
"Save scope",
|
|
590
|
+
"Source",
|
|
591
|
+
"Edit frontmatter YAML",
|
|
592
|
+
"External editor (entire Markdown)",
|
|
593
|
+
"Save",
|
|
594
|
+
"Reset to bundled",
|
|
595
|
+
"Cancel",
|
|
596
|
+
];
|
|
597
|
+
const EDIT_FIELD_LABELS = {
|
|
598
|
+
Customization: "Customization",
|
|
599
|
+
name: "Name",
|
|
600
|
+
description: "Description",
|
|
601
|
+
models: "Models",
|
|
602
|
+
modelSuggestions: "Model suggestions",
|
|
603
|
+
thinkingLevel: "Thinking level",
|
|
604
|
+
"tools.allow": "Allowed tools",
|
|
605
|
+
"tools.block": "Blocked tools",
|
|
606
|
+
color: "Color",
|
|
607
|
+
icon: "[lab] Icon",
|
|
608
|
+
systemPrompt: "System prompt",
|
|
609
|
+
"Save scope": "Save scope",
|
|
610
|
+
Source: "Source (read-only)",
|
|
611
|
+
"Edit frontmatter YAML": "Frontmatter YAML",
|
|
612
|
+
"External editor (entire Markdown)": "External editor",
|
|
613
|
+
Save: "Save",
|
|
614
|
+
"Reset to bundled": "Reset to bundled",
|
|
615
|
+
Cancel: "Cancel",
|
|
616
|
+
};
|
|
617
|
+
const EDIT_FIELD_HELP = {
|
|
618
|
+
Customization: "Settings override tweaks bundled settings via <name>.yml and keeps receiving prompt updates. Fork copies everything into <name>.md and you own the prompt.",
|
|
619
|
+
name: "Unique type identifier. Renaming retains the original file.",
|
|
620
|
+
description: "Description shown when browsing and spawning agents.",
|
|
621
|
+
models: "Ordered model preferences. Unavailable models are skipped at runtime. Advisory names in model suggestions never pin a model.",
|
|
622
|
+
modelSuggestions: "Advisory display names to help pick a model. Not provider/model pins; never selected or required. One name per line; empty clears.",
|
|
623
|
+
thinkingLevel: "Reasoning effort. Default follows the parent session.",
|
|
624
|
+
"tools.allow": "Pick session tools with checkboxes. Under Allowed (except blocked), an unset or empty allow list allows no tools.",
|
|
625
|
+
"tools.block": "Pick session tools to block. Blocked tools take precedence when the policy uses this list.",
|
|
626
|
+
color: "Thread widget color with live preview.",
|
|
627
|
+
icon: "Paste a single Nerd Font glyph from nerdfonts.com/cheat-sheet (not its name or codepoint).\nLeave blank to remove. Display requires [lab] Nerd Font icons in settings and a Nerd Font in your terminal.",
|
|
628
|
+
systemPrompt: "Edit the Markdown prompt body in a multiline dialog.",
|
|
629
|
+
"Save scope": "Project definitions override global definitions with the same name.",
|
|
630
|
+
Source: "Read-only source. Bundled definitions are copied, never overwritten.",
|
|
631
|
+
"Edit frontmatter YAML": "Edit metadata as YAML, preserving the prompt body.",
|
|
632
|
+
"External editor (entire Markdown)": "Edit the complete definition using $VISUAL / $EDITOR.",
|
|
633
|
+
Save: "Validate and save. Existing sessions keep their original configuration.",
|
|
634
|
+
"Reset to bundled": "Delete this fork/override file and go back to the definition shipped with the extension. Unsaved edits are discarded.",
|
|
635
|
+
Cancel: "Close without saving any edits.",
|
|
636
|
+
};
|
|
637
|
+
async function chooseSaveScope(ctx, store, current) {
|
|
638
|
+
const choices = ["Global", ...(store.canSaveProject() ? ["Trusted project"] : [])];
|
|
639
|
+
const value = await dialogMenu(ctx, "Save scope", choices.map((label) => ({ id: label, label })), { selectedId: current === "user" ? "Global" : "Trusted project" });
|
|
640
|
+
return value ? (value === "Global" ? "user" : "project") : undefined;
|
|
641
|
+
}
|
|
642
|
+
function toolListMenuValue(names) {
|
|
643
|
+
if (names === undefined)
|
|
644
|
+
return "Unset (use default policy)";
|
|
645
|
+
if (names.length === 0)
|
|
646
|
+
return "Empty list";
|
|
647
|
+
return names.join(", ");
|
|
648
|
+
}
|
|
649
|
+
function modelSuggestionLabel(suggestions) {
|
|
650
|
+
if (suggestions === undefined || suggestions.length === 0)
|
|
651
|
+
return "None";
|
|
652
|
+
return suggestions.join(", ");
|
|
653
|
+
}
|
|
654
|
+
function modelSuggestionPrefill(suggestions) {
|
|
655
|
+
return (suggestions ?? []).map((name) => sanitizeText(name)).join("\n");
|
|
656
|
+
}
|
|
657
|
+
function customizationMenuValue(editMode, isNew) {
|
|
658
|
+
if (isNew)
|
|
659
|
+
return "New full definition (.md)";
|
|
660
|
+
if (editMode === "override")
|
|
661
|
+
return "Settings override (.yml)";
|
|
662
|
+
if (editMode === "fork")
|
|
663
|
+
return "Full copy (.md)";
|
|
664
|
+
return "Choose to unlock editing";
|
|
665
|
+
}
|
|
666
|
+
function isPureBundled(original) {
|
|
667
|
+
return !!original && !original.customization && original.source === "bundled";
|
|
668
|
+
}
|
|
669
|
+
async function chooseCustomizationMode(ctx, agentName, current) {
|
|
670
|
+
const value = await dialogMenu(ctx, `Customize ${sanitizeText(agentName)}`, [
|
|
671
|
+
{
|
|
672
|
+
id: "override",
|
|
673
|
+
label: "Tweak settings",
|
|
674
|
+
value: `${agentName}.yml`,
|
|
675
|
+
help: "Start with an empty settings overlay; only changed fields are saved. The prompt stays bundled and keeps receiving updates. System prompt and name stay locked.",
|
|
676
|
+
},
|
|
677
|
+
{
|
|
678
|
+
id: "fork",
|
|
679
|
+
label: "Fork agent",
|
|
680
|
+
value: `${agentName}.md`,
|
|
681
|
+
help: "Copy the full definition including the system prompt. You own the prompt; bundled updates no longer apply. Everything is editable.",
|
|
682
|
+
},
|
|
683
|
+
], { selectedId: current });
|
|
684
|
+
return value === "override" || value === "fork" ? value : undefined;
|
|
685
|
+
}
|
|
686
|
+
function editMenuLabel(action, draft) {
|
|
687
|
+
switch (action) {
|
|
688
|
+
case "name":
|
|
689
|
+
return `name: ${sanitizeText(draft.name)}`;
|
|
690
|
+
case "description":
|
|
691
|
+
return `description: ${sanitizeText(draft.description)}`;
|
|
692
|
+
case "models": {
|
|
693
|
+
const models = getModelPreferences(draft);
|
|
694
|
+
return `models: ${sanitizeText(models?.join(", ") ?? "Default (inherit)")}`;
|
|
695
|
+
}
|
|
696
|
+
case "modelSuggestions":
|
|
697
|
+
return `modelSuggestions: ${sanitizeText(modelSuggestionLabel(draft.modelSuggestions))}`;
|
|
698
|
+
case "thinkingLevel":
|
|
699
|
+
return `thinkingLevel: ${sanitizeText(draft.thinkingLevel ?? "Default (inherit)")}`;
|
|
700
|
+
case "tools.allow":
|
|
701
|
+
return `tools.allow: ${sanitizeText(toolListMenuValue(draft.tools?.allow))}`;
|
|
702
|
+
case "tools.block":
|
|
703
|
+
return `tools.block: ${sanitizeText(toolListMenuValue(draft.tools?.block))}`;
|
|
704
|
+
case "color":
|
|
705
|
+
return `color: ${sanitizeText(draft.color ?? "Default (inherit)")}`;
|
|
706
|
+
case "icon":
|
|
707
|
+
return `icon: ${draft.icon ? "Configured" : "None"}`;
|
|
708
|
+
case "systemPrompt":
|
|
709
|
+
return `systemPrompt: ${draft.systemPrompt.split("\n").length} lines · ${draft.systemPrompt.length} characters`;
|
|
710
|
+
default:
|
|
711
|
+
return action;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
function effectiveModelLine(type, options) {
|
|
715
|
+
try {
|
|
716
|
+
const settings = options.resolveAgentSettings?.(type);
|
|
717
|
+
return settings
|
|
718
|
+
? `Model: ${settings.model} · thinking: ${settings.thinkingLevel}`
|
|
719
|
+
: "Model: unavailable";
|
|
720
|
+
}
|
|
721
|
+
catch {
|
|
722
|
+
return "Model: unavailable";
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
export async function editAgentTypes(ctx, store, nerdFontIcons = false, toolEditor = { getAllTools: () => [], toolFiltering: "allowed" }) {
|
|
726
|
+
if (!canOpenDialog(ctx))
|
|
727
|
+
return;
|
|
728
|
+
await withDialogSession(ctx, (scoped) => editAgentTypesDialog(scoped, store, nerdFontIcons, toolEditor));
|
|
729
|
+
}
|
|
730
|
+
function agentSourceHelp(store, name) {
|
|
731
|
+
const layers = store.getLayers(name);
|
|
732
|
+
const paths = layers
|
|
733
|
+
.map((layer) => `${layer.source ?? "user"} · ${layer.filePath ?? ""}`)
|
|
734
|
+
.join("\n");
|
|
735
|
+
return layers.length > 1 ? `${layers.map((layer) => layer.source).join(" → ")}\n${paths}` : paths;
|
|
736
|
+
}
|
|
737
|
+
function agentSettingsIndicators(store, name, action) {
|
|
738
|
+
const hasKey = (scope) => {
|
|
739
|
+
const settings = store.getSettingsOverride(name, scope);
|
|
740
|
+
if (!settings)
|
|
741
|
+
return false;
|
|
742
|
+
if (action === "tools.allow" || action === "tools.block") {
|
|
743
|
+
return (Object.hasOwn(settings, "tools") &&
|
|
744
|
+
(settings.tools === null || Object.hasOwn(settings.tools ?? {}, action.split(".")[1])));
|
|
745
|
+
}
|
|
746
|
+
return Object.hasOwn(settings, action);
|
|
747
|
+
};
|
|
748
|
+
const global = hasKey("user");
|
|
749
|
+
const project = hasKey("project");
|
|
750
|
+
return (theme) => (global ? theme.fg("accent", "●") : " ") + " " + (project ? theme.fg("warning", "●") : " ");
|
|
751
|
+
}
|
|
752
|
+
function agentSettingsLegend(theme) {
|
|
753
|
+
const global = theme.fg("accent", "●");
|
|
754
|
+
const project = theme.fg("warning", "●");
|
|
755
|
+
return (theme.fg("muted", "Saved: ") +
|
|
756
|
+
`${global} Global · ${project} Current Project · ${global} ${project} Both`);
|
|
757
|
+
}
|
|
758
|
+
async function editAgentTypesDialog(ctx, store, nerdFontIcons, toolEditor) {
|
|
759
|
+
while (true) {
|
|
760
|
+
const types = store.list();
|
|
761
|
+
const selection = await dialogMenu(ctx, "Agent types", [
|
|
762
|
+
{
|
|
763
|
+
id: "Create new type",
|
|
764
|
+
label: "Create new type",
|
|
765
|
+
value: "New definition",
|
|
766
|
+
help: "Nothing is written until you save.",
|
|
767
|
+
},
|
|
768
|
+
...types.map((type) => ({
|
|
769
|
+
id: type.name,
|
|
770
|
+
label: type.name,
|
|
771
|
+
renderLabel: (label, theme) => agentTypeBadge(label, type.color, theme, type.icon, nerdFontIcons),
|
|
772
|
+
value: type.description,
|
|
773
|
+
valueDetail: effectiveModelLine(type, toolEditor),
|
|
774
|
+
help: agentSourceHelp(store, type.name),
|
|
775
|
+
})),
|
|
776
|
+
]);
|
|
777
|
+
if (selection === undefined)
|
|
778
|
+
return;
|
|
779
|
+
const original = selection === "Create new type" ? undefined : store.get(selection);
|
|
780
|
+
const isNew = !original;
|
|
781
|
+
let draft = original
|
|
782
|
+
? structuredClone(original)
|
|
783
|
+
: { name: "new-agent", description: "New agent", systemPrompt: "" };
|
|
784
|
+
const originalContent = serializeAgentType(draft);
|
|
785
|
+
let selectedId;
|
|
786
|
+
let saveScope = original?.source === "project" && store.canSaveProject() ? "project" : "user";
|
|
787
|
+
let editMode = isNew
|
|
788
|
+
? "fork"
|
|
789
|
+
: (original?.customization?.kind ?? undefined);
|
|
790
|
+
if (!isNew && isPureBundled(original)) {
|
|
791
|
+
const mode = await chooseCustomizationMode(ctx, original.name);
|
|
792
|
+
if (!mode)
|
|
793
|
+
continue;
|
|
794
|
+
editMode = mode;
|
|
795
|
+
}
|
|
796
|
+
while (true) {
|
|
797
|
+
const dirty = !original || serializeAgentType(draft) !== originalContent;
|
|
798
|
+
const field = await dialogMenu(ctx, `Edit ${sanitizeText(draft.name)} (unsaved)`, EDIT_MENU_ACTIONS.filter((action) => action !== "Reset to bundled" ||
|
|
799
|
+
(!isNew && !!original?.customization && !!original.baseSource)).map((action) => {
|
|
800
|
+
const decorated = editMenuLabel(action, draft);
|
|
801
|
+
const separator = decorated.indexOf(": ");
|
|
802
|
+
return {
|
|
803
|
+
id: action,
|
|
804
|
+
label: EDIT_FIELD_LABELS[action],
|
|
805
|
+
renderIndicators: editMode === "override" && original
|
|
806
|
+
? agentSettingsIndicators(store, original.name, action)
|
|
807
|
+
: undefined,
|
|
808
|
+
valueColor: action === "Save" && dirty ? "warning" : undefined,
|
|
809
|
+
value: action === "Customization"
|
|
810
|
+
? customizationMenuValue(editMode, isNew)
|
|
811
|
+
: action === "Save" && dirty
|
|
812
|
+
? "(changes)"
|
|
813
|
+
: action === "Source"
|
|
814
|
+
? original
|
|
815
|
+
? store
|
|
816
|
+
.getLayers(original.name)
|
|
817
|
+
.map((layer) => layer.source)
|
|
818
|
+
.join(" → ")
|
|
819
|
+
: "New draft"
|
|
820
|
+
: action === "Save scope"
|
|
821
|
+
? saveScope === "user"
|
|
822
|
+
? "Global"
|
|
823
|
+
: "Trusted project"
|
|
824
|
+
: action === "icon" && nerdFontIcons && draft.icon
|
|
825
|
+
? draft.icon
|
|
826
|
+
: separator >= 0
|
|
827
|
+
? decorated.slice(separator + 2)
|
|
828
|
+
: "",
|
|
829
|
+
help: action === "Source"
|
|
830
|
+
? original
|
|
831
|
+
? agentSourceHelp(store, original.name)
|
|
832
|
+
: "Not saved yet. Bundled definitions are copied, never overwritten."
|
|
833
|
+
: EDIT_FIELD_HELP[action],
|
|
834
|
+
};
|
|
835
|
+
}), {
|
|
836
|
+
selectedId,
|
|
837
|
+
saveId: "Save",
|
|
838
|
+
footer: "↑↓/Tab fields · Enter edit · Ctrl+S save · Esc cancel",
|
|
839
|
+
renderLegend: editMode === "override" ? agentSettingsLegend : undefined,
|
|
840
|
+
});
|
|
841
|
+
selectedId = field;
|
|
842
|
+
if (!field || field === "Cancel")
|
|
843
|
+
break;
|
|
844
|
+
try {
|
|
845
|
+
if (field === "Customization") {
|
|
846
|
+
if (isNew) {
|
|
847
|
+
ctx.ui.notify("New types are always full definitions (.md).", "info");
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
const mode = await chooseCustomizationMode(ctx, draft.name, editMode);
|
|
851
|
+
if (!mode)
|
|
852
|
+
continue;
|
|
853
|
+
if (mode !== editMode && mode === "override" && original) {
|
|
854
|
+
const base = store.getBase(original.name) ?? original;
|
|
855
|
+
draft.systemPrompt = base.systemPrompt;
|
|
856
|
+
ctx.ui.notify("Switched to settings override: prompt edits were dropped (the bundled prompt applies).", "info");
|
|
857
|
+
}
|
|
858
|
+
editMode = mode;
|
|
859
|
+
continue;
|
|
860
|
+
}
|
|
861
|
+
if (!isNew && !editMode) {
|
|
862
|
+
ctx.ui.notify("Pick Customization first: tweak settings (.yml) or fork the agent (.md).", "error");
|
|
863
|
+
continue;
|
|
864
|
+
}
|
|
865
|
+
if (editMode === "override" &&
|
|
866
|
+
(field === "name" ||
|
|
867
|
+
field === "systemPrompt" ||
|
|
868
|
+
field === "Edit frontmatter YAML" ||
|
|
869
|
+
field === "External editor (entire Markdown)")) {
|
|
870
|
+
ctx.ui.notify(field === "name"
|
|
871
|
+
? "Settings overrides cannot rename the agent; fork it instead."
|
|
872
|
+
: "The system prompt lives with the bundled definition; fork the agent to edit it.", "error");
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
if (field === "Save") {
|
|
876
|
+
if (!editMode)
|
|
877
|
+
continue;
|
|
878
|
+
const validated = parseAgentType(serializeAgentType(draft));
|
|
879
|
+
const scope = await chooseSaveScope(ctx, store, saveScope);
|
|
880
|
+
if (!scope)
|
|
881
|
+
continue;
|
|
882
|
+
assertSaveDestination(store, validated, original, scope, editMode);
|
|
883
|
+
if (editMode === "override") {
|
|
884
|
+
if (original?.customization?.kind === "fork" &&
|
|
885
|
+
original.customization.scope === scope) {
|
|
886
|
+
store.removeCustomization(original.name, scope);
|
|
887
|
+
}
|
|
888
|
+
const saved = store.saveOverride(draft.name, validated, scope, original);
|
|
889
|
+
ctx.ui.notify(`Saved settings override ${sanitizeText(saved.filePath ?? saved.name)}. Prompt and unset fields follow the base definition.`, "info");
|
|
890
|
+
break;
|
|
891
|
+
}
|
|
892
|
+
if (original?.customization?.kind === "override" &&
|
|
893
|
+
original.customization.scope === scope) {
|
|
894
|
+
store.removeCustomization(original.name, scope);
|
|
895
|
+
}
|
|
896
|
+
const saved = store.save(validated, scope, original);
|
|
897
|
+
ctx.ui.notify(`Saved ${sanitizeText(saved.filePath ?? saved.name)}${original && original.name !== saved.name ? " (original file retained)" : ""}.`, "info");
|
|
898
|
+
break;
|
|
899
|
+
}
|
|
900
|
+
if (field === "Reset to bundled") {
|
|
901
|
+
if (!original?.customization || !original.baseSource)
|
|
902
|
+
continue;
|
|
903
|
+
const { scope, filePath } = original.customization;
|
|
904
|
+
const confirmed = await dialogMenu(ctx, `Reset ${sanitizeText(original.name)}?`, [
|
|
905
|
+
{
|
|
906
|
+
id: "reset",
|
|
907
|
+
label: "Reset",
|
|
908
|
+
help: `Deletes ${filePath} and restores the ${original.baseSource ?? "bundled"} definition.`,
|
|
909
|
+
},
|
|
910
|
+
{ id: "keep", label: "Keep" },
|
|
911
|
+
], { selectedId: "keep" });
|
|
912
|
+
if (confirmed !== "reset")
|
|
913
|
+
continue;
|
|
914
|
+
store.removeCustomization(original.name, scope);
|
|
915
|
+
ctx.ui.notify(`Reset ${sanitizeText(original.name)}: deleted ${sanitizeText(filePath)}; using the ${original.baseSource ?? "bundled"} definition.`, "info");
|
|
916
|
+
break;
|
|
917
|
+
}
|
|
918
|
+
if (field === "Save scope") {
|
|
919
|
+
const scope = await chooseSaveScope(ctx, store, saveScope);
|
|
920
|
+
if (scope)
|
|
921
|
+
saveScope = scope;
|
|
922
|
+
continue;
|
|
923
|
+
}
|
|
924
|
+
if (field === "Source") {
|
|
925
|
+
ctx.ui.notify(original?.filePath ?? "This definition has not been saved yet.", "info");
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
if (field === "External editor (entire Markdown)" || field === "Edit frontmatter YAML") {
|
|
929
|
+
const edited = await editDocument(ctx, draft, field === "External editor (entire Markdown)");
|
|
930
|
+
if (edited)
|
|
931
|
+
draft = edited;
|
|
932
|
+
continue;
|
|
933
|
+
}
|
|
934
|
+
const candidate = structuredClone(draft);
|
|
935
|
+
if (field === "name" || field === "description" || field === "systemPrompt") {
|
|
936
|
+
const originalValue = candidate[field] ?? "";
|
|
937
|
+
const prefill = originalValue
|
|
938
|
+
.replace(/\r\n/g, "\n")
|
|
939
|
+
.replace(/\r/g, "\n")
|
|
940
|
+
.split("\n")
|
|
941
|
+
.map(sanitizeText)
|
|
942
|
+
.join("\n");
|
|
943
|
+
const value = await dialogEditor(ctx, `Agent ${field}`, prefill);
|
|
944
|
+
if (value === undefined)
|
|
945
|
+
continue;
|
|
946
|
+
candidate[field] = value === prefill || value === prefill.trim() ? originalValue : value;
|
|
947
|
+
}
|
|
948
|
+
else if (field === "icon") {
|
|
949
|
+
const value = await dialogEditor(ctx, "Agent icon (Nerd Font glyph; blank to remove)", candidate.icon ?? "");
|
|
950
|
+
if (value === undefined)
|
|
951
|
+
continue;
|
|
952
|
+
const icon = value.trim();
|
|
953
|
+
if (!icon)
|
|
954
|
+
delete candidate.icon;
|
|
955
|
+
else
|
|
956
|
+
candidate.icon = icon;
|
|
957
|
+
}
|
|
958
|
+
else if (field === "models") {
|
|
959
|
+
const value = await editModelPreferences(ctx, getModelPreferences(candidate), candidate.modelSuggestions);
|
|
960
|
+
if (value === MODEL_EDITOR_CANCEL)
|
|
961
|
+
continue;
|
|
962
|
+
if (value.length === 0) {
|
|
963
|
+
delete candidate.models;
|
|
964
|
+
delete candidate.model;
|
|
965
|
+
}
|
|
966
|
+
else {
|
|
967
|
+
candidate.models = [...value];
|
|
968
|
+
delete candidate.model;
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
else if (field === "modelSuggestions") {
|
|
972
|
+
const prefill = modelSuggestionPrefill(candidate.modelSuggestions);
|
|
973
|
+
const value = await dialogEditor(ctx, "Agent modelSuggestions (one display name per line)", prefill);
|
|
974
|
+
if (value === undefined)
|
|
975
|
+
continue;
|
|
976
|
+
if (value === prefill || value === prefill.trim())
|
|
977
|
+
continue;
|
|
978
|
+
const names = value
|
|
979
|
+
.split("\n")
|
|
980
|
+
.map((line) => line.trim())
|
|
981
|
+
.filter((line) => line.length > 0);
|
|
982
|
+
if (names.length === 0)
|
|
983
|
+
delete candidate.modelSuggestions;
|
|
984
|
+
else
|
|
985
|
+
candidate.modelSuggestions = [...names];
|
|
986
|
+
}
|
|
987
|
+
else if (field === "thinkingLevel") {
|
|
988
|
+
const value = await dialogMenu(ctx, "Thinking level", ["Default (inherit)", ...THINKING_LEVELS].map((label) => ({
|
|
989
|
+
id: label,
|
|
990
|
+
label,
|
|
991
|
+
})), { selectedId: candidate.thinkingLevel ?? "Default (inherit)" });
|
|
992
|
+
if (!value)
|
|
993
|
+
continue;
|
|
994
|
+
if (value === "Default (inherit)")
|
|
995
|
+
delete candidate.thinkingLevel;
|
|
996
|
+
else
|
|
997
|
+
candidate.thinkingLevel = value;
|
|
998
|
+
}
|
|
999
|
+
else if (field === "color") {
|
|
1000
|
+
const value = await selectAgentColor(ctx, candidate.color, candidate.name);
|
|
1001
|
+
if (value === AGENT_COLOR_CANCEL)
|
|
1002
|
+
continue;
|
|
1003
|
+
if (value === undefined)
|
|
1004
|
+
delete candidate.color;
|
|
1005
|
+
else
|
|
1006
|
+
candidate.color = value;
|
|
1007
|
+
}
|
|
1008
|
+
else if (field === "tools.allow" || field === "tools.block") {
|
|
1009
|
+
await editToolList(ctx, candidate, field === "tools.allow" ? "allow" : "block", toolEditor);
|
|
1010
|
+
}
|
|
1011
|
+
parseAgentType(serializeAgentType(candidate));
|
|
1012
|
+
draft = candidate;
|
|
1013
|
+
}
|
|
1014
|
+
catch (error) {
|
|
1015
|
+
ctx.ui.notify(sanitizeText(error instanceof Error ? error.message : String(error)), "error");
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}
|