pi-subagent-manager 0.2.0 → 0.3.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/src/ui.ts CHANGED
@@ -5,7 +5,6 @@ import { tmpdir } from "node:os";
5
5
  import { join, resolve } from "node:path";
6
6
  import { parse as parseShell } from "shell-quote";
7
7
  import {
8
- DynamicBorder,
9
8
  type ExtensionCommandContext,
10
9
  type ExtensionContext,
11
10
  getSelectListTheme,
@@ -20,11 +19,32 @@ import {
20
19
  rgbColor,
21
20
  stripTerminalSequences,
22
21
  truncateToWidth,
22
+ visibleWidth,
23
23
  } from "@earendil-works/pi-tui";
24
- import { AGENT_COLORS, ConfigStore, parseAgentType, serializeAgentType } from "./config.ts";
24
+ import {
25
+ AGENT_COLORS,
26
+ ConfigStore,
27
+ parseAgentType,
28
+ serializeAgentType,
29
+ } from "./config.ts";
25
30
  import { editModelPreferences, MODEL_EDITOR_CANCEL } from "./model-picker.ts";
31
+ import {
32
+ canOpenDialog,
33
+ dialogEditor,
34
+ dialogMenu,
35
+ dialogHeight,
36
+ frameDialog,
37
+ DIALOG_OPTIONS,
38
+ withDialogSession,
39
+ } from "./dialog.ts";
26
40
  import { getModelPreferences } from "./models.ts";
27
- import { THINKING_LEVELS, type AgentType, type ThreadService, type ThreadView } from "./types.ts";
41
+ import { buildStatusTree, type StatusRow } from "./thread-tree.ts";
42
+ import {
43
+ THINKING_LEVELS,
44
+ type AgentType,
45
+ type ThreadService,
46
+ type ThreadView,
47
+ } from "./types.ts";
28
48
 
29
49
  export type ThreadController = Pick<
30
50
  ThreadService,
@@ -38,27 +58,113 @@ export function sanitizeText(text: string): string {
38
58
 
39
59
  type AgentBadgeTheme = Pick<Theme, "fg" | "colors" | "style">;
40
60
 
41
- /** Use the theme's concrete token color as a background, with readable text. */
42
- function agentNameBadge(name: string, color: string | undefined, theme: AgentBadgeTheme): string {
43
- const token: ThemeColor = AGENT_COLORS.includes(color as (typeof AGENT_COLORS)[number])
61
+ /** Selected type token, or accent when unset or unknown. Shared by the pill and path. */
62
+ function agentColorToken(color: string | undefined): ThemeColor {
63
+ return AGENT_COLORS.includes(color as (typeof AGENT_COLORS)[number])
44
64
  ? (color as ThemeColor)
45
65
  : "accent";
46
- const background = theme.colors[token];
66
+ }
67
+
68
+ /** Background pill with bold contrasting text. Label is sanitized; caller supplies brackets. */
69
+ function contrastPill(
70
+ label: string,
71
+ color: string | undefined,
72
+ theme: AgentBadgeTheme,
73
+ ): string {
74
+ const background = theme.colors[agentColorToken(color)];
47
75
  const { r, g, b } = colorToRgb(background);
48
76
  const linear = (channel: number) => {
49
77
  const value = channel / 255;
50
78
  return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
51
79
  };
52
- const luminance = 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
80
+ const luminance =
81
+ 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
53
82
  // Pick whichever of black/white has the higher WCAG contrast ratio.
54
83
  const foreground = luminance > Math.sqrt(0.0525) - 0.05 ? 0 : 255;
55
- return theme.style(` ${sanitizeText(name)} `, {
84
+ return theme.style(` ${sanitizeText(label)} `, {
56
85
  bg: background,
57
86
  fg: rgbColor(foreground, foreground, foreground),
58
87
  bold: true,
59
88
  });
60
89
  }
61
90
 
91
+ function agentTypeBadge(
92
+ type: string,
93
+ color: string | undefined,
94
+ theme: AgentBadgeTheme,
95
+ ): string {
96
+ return contrastPill(`[${type}]`, color, theme);
97
+ }
98
+
99
+ function agentPath(
100
+ path: string,
101
+ color: string | undefined,
102
+ theme: AgentBadgeTheme,
103
+ ): string {
104
+ return theme.fg(agentColorToken(color), sanitizeText(path));
105
+ }
106
+
107
+ function metricCount(value: number | undefined): number {
108
+ return typeof value === "number" && Number.isFinite(value)
109
+ ? Math.max(0, Math.floor(value))
110
+ : 0;
111
+ }
112
+
113
+ /** Settled active time plus the current live run, only while starting or running. */
114
+ function elapsedTotal(thread: ThreadView, now = Date.now()): number {
115
+ const live =
116
+ typeof thread.startedAt === "number" &&
117
+ Number.isFinite(thread.startedAt) &&
118
+ (thread.state === "starting" || thread.state === "running")
119
+ ? now - thread.startedAt
120
+ : 0;
121
+ const total = metricCount(thread.elapsedMs) + live;
122
+ return Number.isFinite(total) ? total : 0;
123
+ }
124
+
125
+ function formatDuration(ms: number): string {
126
+ const total = Math.max(0, Math.floor(ms / 1000));
127
+ const seconds = total % 60;
128
+ const minutes = Math.floor(total / 60) % 60;
129
+ const hours = Math.floor(total / 3600) % 24;
130
+ const days = Math.floor(total / 86400);
131
+ if (days > 0) return `${days}d${hours}h`;
132
+ if (hours > 0) return `${hours}h${minutes}m`;
133
+ if (minutes > 0) return `${minutes}m${seconds}s`;
134
+ return `${seconds}s`;
135
+ }
136
+
137
+ const compactCount = new Intl.NumberFormat("en", {
138
+ notation: "compact",
139
+ maximumFractionDigits: 1,
140
+ });
141
+
142
+ function formatCount(value: number | undefined): string {
143
+ // Intl emits uppercase units (`1.2K`); the widget uses lowercase.
144
+ return compactCount.format(metricCount(value)).toLowerCase();
145
+ }
146
+
147
+ export function threadMetrics(thread: ThreadView, now = Date.now()): string {
148
+ return `${formatDuration(elapsedTotal(thread, now))} ↑${formatCount(thread.inputTokens)} ↓${formatCount(thread.outputTokens)}`;
149
+ }
150
+
151
+ /** Keep the right-hand counters intact; truncate the left side to the remaining columns. */
152
+ function fitLine(left: string, right: string, width: number): string {
153
+ if (width <= 0) return "";
154
+ const rightWidth = visibleWidth(right);
155
+ if (rightWidth >= width) return truncateToWidth(right, width, "");
156
+ const fitted = truncateToWidth(left, width - rightWidth - 1);
157
+ const pad = width - visibleWidth(fitted) - rightWidth;
158
+ return fitted + " ".repeat(Math.max(0, pad)) + right;
159
+ }
160
+
161
+ function isLive(thread: ThreadView): boolean {
162
+ return (
163
+ thread.path !== "/root" &&
164
+ (thread.state === "starting" || thread.state === "running")
165
+ );
166
+ }
167
+
62
168
  export function renderThreads(
63
169
  threads: ThreadView[],
64
170
  width: number,
@@ -73,23 +179,36 @@ export function renderThreads(
73
179
  const visible = threads
74
180
  .filter((thread) => thread.path !== "/root")
75
181
  .sort(
76
- (a, b) => priority(a) - priority(b) || b.updatedAt - a.updatedAt || b.createdAt - a.createdAt,
182
+ (a, b) =>
183
+ priority(a) - priority(b) ||
184
+ b.updatedAt - a.updatedAt ||
185
+ b.createdAt - a.createdAt,
77
186
  );
78
187
  const limit = visible.length > 8 ? 7 : 8;
79
188
  const lines = visible.slice(0, limit).map((thread) => {
80
189
  const stateColor =
81
- thread.state === "failed" ? "error" : thread.state === "paused" ? "warning" : "accent";
82
- const badge = agentNameBadge(thread.path, thread.color, theme);
190
+ thread.state === "failed"
191
+ ? "error"
192
+ : thread.state === "paused"
193
+ ? "warning"
194
+ : "accent";
195
+ const badge = agentTypeBadge(thread.type, thread.color, theme);
196
+ const path = agentPath(thread.path, thread.color, theme);
83
197
  const state = theme.fg(stateColor, `[${sanitizeText(thread.state)}]`);
84
- return truncateToWidth(
85
- `${badge} ${state} ${sanitizeText(thread.status || thread.task)}`,
198
+ const left = `${badge} ${path} ${state} ${sanitizeText(thread.status || thread.task)}`;
199
+ return fitLine(
200
+ left,
201
+ theme.fg("muted", threadMetrics(thread)),
86
202
  Math.max(0, width),
87
203
  );
88
204
  });
89
205
  if (visible.length > limit) {
90
206
  lines.push(
91
207
  truncateToWidth(
92
- theme.fg("muted", `+${visible.length - limit} more threads · /agents thread`),
208
+ theme.fg(
209
+ "muted",
210
+ `+${visible.length - limit} more threads · /agents tree`,
211
+ ),
93
212
  Math.max(0, width),
94
213
  ),
95
214
  );
@@ -97,19 +216,275 @@ export function renderThreads(
97
216
  return lines;
98
217
  }
99
218
 
100
- export function updateWidget(ctx: ExtensionContext, threads: ThreadView[]): void {
219
+ const WIDGET_ROOT = "/root";
220
+ const MAX_WIDGET_LINES = 10;
221
+ const AGENT_WIDGET_PLACEMENT = { placement: "aboveEditor" as const };
222
+
223
+ function statePriority(state: ThreadView["state"] | undefined): number {
224
+ if (state === "starting" || state === "running") return 0;
225
+ if (state === "paused") return 1;
226
+ return 2;
227
+ }
228
+
229
+ function explicitParent(
230
+ path: string,
231
+ threadsByPath: Map<string, ThreadView>,
232
+ ): string | null {
233
+ if (path === WIDGET_ROOT) return null;
234
+ const thread = threadsByPath.get(path);
235
+ if (thread)
236
+ return thread.parent && thread.parent !== path ? thread.parent : null;
237
+ const index = path.lastIndexOf("/");
238
+ return index > 0 ? path.slice(0, index) : null;
239
+ }
240
+
241
+ /** Lowest state in the branch. Parent links define ancestry; cycles are guarded. */
242
+ function branchPriorityComparator(
243
+ threads: ThreadView[],
244
+ ): (a: string, b: string) => number {
245
+ const threadsByPath = new Map<string, ThreadView>();
246
+ for (const thread of threads) {
247
+ if (thread?.path && !threadsByPath.has(thread.path))
248
+ threadsByPath.set(thread.path, thread);
249
+ }
250
+ const children = new Map<string, string[]>();
251
+ const link = (path: string, seen: Set<string>) => {
252
+ if (!path || seen.has(path)) return;
253
+ seen.add(path);
254
+ const parent = explicitParent(path, threadsByPath);
255
+ if (!parent || parent === path) return;
256
+ const list = children.get(parent) ?? [];
257
+ if (!list.includes(path)) list.push(path);
258
+ children.set(parent, list);
259
+ link(parent, seen);
260
+ };
261
+ link(WIDGET_ROOT, new Set());
262
+ for (const path of threadsByPath.keys()) link(path, new Set());
263
+
264
+ const subtree = new Map<string, number>();
265
+ const ancestors = new Map<string, number>();
266
+ const subtreeOf = (path: string, stack: Set<string>): number => {
267
+ const cached = subtree.get(path);
268
+ if (cached !== undefined) return cached;
269
+ const own = statePriority(threadsByPath.get(path)?.state);
270
+ if (stack.has(path)) return own;
271
+ stack.add(path);
272
+ let best = own;
273
+ for (const child of children.get(path) ?? [])
274
+ best = Math.min(best, subtreeOf(child, stack));
275
+ stack.delete(path);
276
+ subtree.set(path, best);
277
+ return best;
278
+ };
279
+ const ancestorOf = (path: string): number => {
280
+ const cached = ancestors.get(path);
281
+ if (cached !== undefined) return cached;
282
+ let best = 2;
283
+ const seen = new Set<string>();
284
+ let current: string | null = path;
285
+ while (current && !seen.has(current)) {
286
+ seen.add(current);
287
+ best = Math.min(best, statePriority(threadsByPath.get(current)?.state));
288
+ current = explicitParent(current, threadsByPath);
289
+ }
290
+ ancestors.set(path, best);
291
+ return best;
292
+ };
293
+ return (a, b) =>
294
+ subtreeOf(a, new Set()) - subtreeOf(b, new Set()) ||
295
+ ancestorOf(a) - ancestorOf(b) ||
296
+ (a < b ? -1 : a > b ? 1 : 0);
297
+ }
298
+
299
+ function activityIndent(prefix: string): string {
300
+ if (prefix.endsWith("├─ ")) return prefix.slice(0, -3) + "│ ";
301
+ if (prefix.endsWith("└─ ")) return prefix.slice(0, -3) + " ";
302
+ return " ".repeat(prefix.length + 3);
303
+ }
304
+
305
+ function agentStateColor(
306
+ state: ThreadView["state"],
307
+ ): "error" | "warning" | "accent" {
308
+ return state === "failed"
309
+ ? "error"
310
+ : state === "paused"
311
+ ? "warning"
312
+ : "accent";
313
+ }
314
+
315
+ function agentLine(
316
+ row: StatusRow,
317
+ width: number,
318
+ theme: AgentBadgeTheme,
319
+ ): string {
320
+ const thread = row.thread!;
321
+ const left = `${row.prefix}${agentTypeBadge(thread.type, thread.color, theme)} ${agentPath(thread.path, thread.color, theme)} ${theme.fg(agentStateColor(thread.state), `[${sanitizeText(thread.state)}]`)} ${sanitizeText(thread.task)}`;
322
+ return fitLine(left, theme.fg("muted", threadMetrics(thread)), width);
323
+ }
324
+
325
+ function activityLine(
326
+ row: StatusRow,
327
+ width: number,
328
+ theme: AgentBadgeTheme,
329
+ ): string {
330
+ const thread = row.thread!;
331
+ return truncateToWidth(
332
+ `${activityIndent(row.prefix)}${theme.fg("muted", sanitizeText(thread.status || thread.task))}`,
333
+ width,
334
+ "",
335
+ );
336
+ }
337
+
338
+ function placeholderLine(
339
+ row: StatusRow,
340
+ width: number,
341
+ theme: AgentBadgeTheme,
342
+ ): string {
343
+ return truncateToWidth(
344
+ `${row.prefix}${theme.fg("muted", `${sanitizeText(row.path)} missing parent`)}`,
345
+ width,
346
+ "",
347
+ );
348
+ }
349
+
350
+ function takeWidgetRows(rows: StatusRow[], budget: number): StatusRow[] {
351
+ const parents = new Map<number, number[]>();
352
+ const stack: number[] = [];
353
+ for (const [index, row] of rows.entries()) {
354
+ while (
355
+ stack.length &&
356
+ rows[stack[stack.length - 1]!]!.prefix.length >= row.prefix.length
357
+ )
358
+ stack.pop();
359
+ parents.set(index, [...stack]);
360
+ stack.push(index);
361
+ }
362
+ const rowCost = (row: StatusRow) =>
363
+ row.path === WIDGET_ROOT ? 0 : row.thread ? 2 : 1;
364
+ const candidates = rows
365
+ .map((row, index) => ({ row, index }))
366
+ .filter(({ row }) => row.thread && row.path !== WIDGET_ROOT)
367
+ .sort(
368
+ (a, b) =>
369
+ statePriority(a.row.thread!.state) -
370
+ statePriority(b.row.thread!.state) || a.index - b.index,
371
+ );
372
+ const chosen = new Set<number>();
373
+ let used = 0;
374
+ for (const { index } of candidates) {
375
+ const needed = [...parents.get(index)!, index].filter(
376
+ (ancestor) => !chosen.has(ancestor),
377
+ );
378
+ const cost = needed.reduce(
379
+ (total, ancestor) => total + rowCost(rows[ancestor]!),
380
+ 0,
381
+ );
382
+ if (used + cost > budget) continue;
383
+ for (const ancestor of needed) chosen.add(ancestor);
384
+ used += cost;
385
+ }
386
+ // If a missing-parent chain cannot fit its agent, retain a useful tree prefix.
387
+ if (!chosen.size) {
388
+ for (const [index, row] of rows.entries()) {
389
+ const cost = rowCost(row);
390
+ if (used + cost > budget) break;
391
+ chosen.add(index);
392
+ used += cost;
393
+ }
394
+ }
395
+ return rows.filter(
396
+ (row, index) => row.path !== WIDGET_ROOT && chosen.has(index),
397
+ );
398
+ }
399
+
400
+ /** Themed agent tree above the editor. Synthetic /root is the main conversation and is omitted. */
401
+ export function renderAgentTree(
402
+ threads: ThreadView[],
403
+ width: number,
404
+ theme: AgentBadgeTheme,
405
+ ): string[] {
406
+ const columns = Math.max(0, width);
407
+ const rows = buildStatusTree(
408
+ threads,
409
+ new Set(),
410
+ branchPriorityComparator(threads),
411
+ );
412
+ const agents = rows.filter((row) => row.thread && row.path !== WIDGET_ROOT);
413
+ if (!agents.length) return [];
414
+ const live = agents.filter(
415
+ (row) =>
416
+ row.thread!.state === "starting" || row.thread!.state === "running",
417
+ ).length;
418
+ const paused = agents.filter((row) => row.thread!.state === "paused").length;
419
+ const heading = fitLine(
420
+ theme.fg("accent", "Agents"),
421
+ theme.fg("muted", `${live} live · ${paused} paused`),
422
+ columns,
423
+ );
424
+ let visible = takeWidgetRows(rows, MAX_WIDGET_LINES - 1);
425
+ let omitted = agents.length - visible.filter((row) => row.thread).length;
426
+ if (omitted > 0) {
427
+ visible = takeWidgetRows(rows, MAX_WIDGET_LINES - 2);
428
+ omitted = agents.length - visible.filter((row) => row.thread).length;
429
+ }
430
+ const lines = [heading];
431
+ for (const row of visible) {
432
+ if (!row.thread) {
433
+ lines.push(placeholderLine(row, columns, theme));
434
+ continue;
435
+ }
436
+ lines.push(agentLine(row, columns, theme));
437
+ lines.push(activityLine(row, columns, theme));
438
+ }
439
+ if (omitted > 0) {
440
+ lines.push(
441
+ truncateToWidth(
442
+ theme.fg("muted", `+${omitted} more agents · /agents tree`),
443
+ columns,
444
+ "",
445
+ ),
446
+ );
447
+ }
448
+ return lines;
449
+ }
450
+
451
+ export function updateWidget(
452
+ ctx: ExtensionContext,
453
+ threads: ThreadView[],
454
+ ): void {
101
455
  if (!ctx.hasUI) return;
102
456
  if (!threads.some((thread) => thread.path !== "/root")) {
103
- ctx.ui.setWidget("pi-subagent", undefined, { placement: "belowEditor" });
457
+ ctx.ui.setWidget("pi-subagent", undefined, AGENT_WIDGET_PLACEMENT);
104
458
  return;
105
459
  }
460
+ // RPC hosts accept string widgets only; a component factory is ignored.
461
+ if (ctx.mode === "rpc") {
462
+ ctx.ui.setWidget(
463
+ "pi-subagent",
464
+ renderAgentTree(threads, 80, ctx.ui.theme),
465
+ AGENT_WIDGET_PLACEMENT,
466
+ );
467
+ return;
468
+ }
469
+ const snapshot = threads.map((thread) => ({ ...thread }));
106
470
  ctx.ui.setWidget(
107
471
  "pi-subagent",
108
- () => ({
109
- render: (width) => renderThreads(threads, width, ctx.ui.theme),
110
- invalidate: () => {},
111
- }),
112
- { placement: "belowEditor" },
472
+ (tui) => {
473
+ let timer: ReturnType<typeof setInterval> | undefined;
474
+ if (snapshot.some(isLive)) {
475
+ timer = setInterval(() => tui.requestRender(), 1000);
476
+ timer.unref();
477
+ }
478
+ return {
479
+ render: (width) => renderAgentTree(snapshot, width, ctx.ui.theme),
480
+ invalidate: () => {},
481
+ dispose: () => {
482
+ if (timer) clearInterval(timer);
483
+ timer = undefined;
484
+ },
485
+ };
486
+ },
487
+ AGENT_WIDGET_PLACEMENT,
113
488
  );
114
489
  }
115
490
 
@@ -123,7 +498,9 @@ export async function showThreads(
123
498
  while (true) {
124
499
  try {
125
500
  if (!selectedPath) {
126
- const threads = controller.list().filter((thread) => thread.path !== "/root");
501
+ const threads = controller
502
+ .list()
503
+ .filter((thread) => thread.path !== "/root");
127
504
  if (!threads.length) {
128
505
  ctx.ui.notify("No subagent threads.", "info");
129
506
  return;
@@ -140,7 +517,9 @@ export async function showThreads(
140
517
  if (selectedPath === "/root")
141
518
  throw new Error("/root is the current Pi thread, not a subagent.");
142
519
  const thread = controller.get(selectedPath);
143
- const children = controller.list().filter((child) => child.parent === selectedPath);
520
+ const children = controller
521
+ .list()
522
+ .filter((child) => child.parent === selectedPath);
144
523
  const title = `${sanitizeText(thread.path)} [${sanitizeText(thread.state)}] ${sanitizeText(thread.status)}`;
145
524
  const action = await ctx.ui.select(title, [
146
525
  "View output",
@@ -166,7 +545,10 @@ export async function showThreads(
166
545
  text.split("\n").map(sanitizeText).join("\n"),
167
546
  );
168
547
  } else if (action === "Send input / resume") {
169
- const message = await ctx.ui.editor("Send input / resume retained session", "");
548
+ const message = await ctx.ui.editor(
549
+ "Send input / resume retained session",
550
+ "",
551
+ );
170
552
  if (message?.trim()) await controller.steer(selectedPath, message);
171
553
  } else if (action === "Stop") {
172
554
  if (
@@ -183,10 +565,14 @@ export async function showThreads(
183
565
  );
184
566
  const selected = await ctx.ui.select("Children", labels);
185
567
  if (selected !== undefined)
186
- selectedPath = children[labels.indexOf(selected)]?.path ?? selectedPath;
568
+ selectedPath =
569
+ children[labels.indexOf(selected)]?.path ?? selectedPath;
187
570
  }
188
571
  } catch (error) {
189
- ctx.ui.notify(sanitizeText(error instanceof Error ? error.message : String(error)), "error");
572
+ ctx.ui.notify(
573
+ sanitizeText(error instanceof Error ? error.message : String(error)),
574
+ "error",
575
+ );
190
576
  return;
191
577
  }
192
578
  }
@@ -203,9 +589,15 @@ export function editorArguments(command: string): string[] {
203
589
  return args as string[];
204
590
  }
205
591
 
206
- async function externalEdit(ctx: ExtensionCommandContext, text: string): Promise<string> {
207
- if (ctx.mode !== "tui") throw new Error("External editing requires interactive TUI mode.");
208
- const [command, ...args] = editorArguments(process.env.VISUAL || process.env.EDITOR || "vi");
592
+ async function externalEdit(
593
+ ctx: ExtensionCommandContext,
594
+ text: string,
595
+ ): Promise<string> {
596
+ if (ctx.mode !== "tui")
597
+ throw new Error("External editing requires interactive TUI mode.");
598
+ const [command, ...args] = editorArguments(
599
+ process.env.VISUAL || process.env.EDITOR || "vi",
600
+ );
209
601
  const directory = await mkdtemp(join(tmpdir(), "pi-subagent-"));
210
602
  const file = join(directory, "agent.md");
211
603
  try {
@@ -219,7 +611,9 @@ async function externalEdit(ctx: ExtensionCommandContext, text: string): Promise
219
611
  });
220
612
  if (result.error) throw result.error;
221
613
  if (result.status !== 0)
222
- throw new Error(`Editor exited with status ${result.status ?? result.signal}.`);
614
+ throw new Error(
615
+ `Editor exited with status ${result.status ?? result.signal}.`,
616
+ );
223
617
  } finally {
224
618
  tui.start();
225
619
  tui.requestRender(true);
@@ -238,9 +632,24 @@ async function editToolList(
238
632
  type: AgentType,
239
633
  field: "allow" | "block",
240
634
  ): Promise<void> {
241
- const mode = await ctx.ui.select(
242
- `tools.${field} (${sanitizeText(toolListMenuValue(type.tools?.[field]))})`,
243
- ["Unset (use default policy)", "Empty list", "Enter exact tool names"],
635
+ const modes = [
636
+ "Unset (use default policy)",
637
+ "Empty list",
638
+ "Enter exact tool names",
639
+ ];
640
+ const current = type.tools?.[field];
641
+ const mode = await dialogMenu(
642
+ ctx,
643
+ `tools.${field} (${sanitizeText(toolListMenuValue(current))})`,
644
+ modes.map((label) => ({ id: label, label })),
645
+ {
646
+ selectedId:
647
+ current === undefined
648
+ ? modes[0]
649
+ : current.length === 0
650
+ ? modes[1]
651
+ : modes[2],
652
+ },
244
653
  );
245
654
  if (!mode) return;
246
655
  if (mode === "Unset (use default policy)") {
@@ -249,7 +658,8 @@ async function editToolList(
249
658
  const value =
250
659
  mode === "Empty list"
251
660
  ? ""
252
- : await ctx.ui.editor(
661
+ : await dialogEditor(
662
+ ctx,
253
663
  `tools.${field}: comma-separated exact names`,
254
664
  type.tools?.[field]?.join(", ") ?? "",
255
665
  );
@@ -267,13 +677,20 @@ const AGENT_COLOR_DEFAULT = "__default__";
267
677
  const AGENT_COLOR_CANCEL = Symbol("agent-color-cancel");
268
678
 
269
679
  class AgentColorPickerComponent extends Container {
270
- private readonly items: { value: string; label: string; description?: string }[];
680
+ private readonly items: {
681
+ value: string;
682
+ label: string;
683
+ description?: string;
684
+ }[];
271
685
  private readonly preview: Text;
272
686
  private readonly theme: Theme;
273
687
  readonly selectList: SelectList;
274
688
 
275
689
  constructor(
276
- tui: { requestRender(force?: boolean): void },
690
+ private readonly tui: {
691
+ requestRender(force?: boolean): void;
692
+ terminal?: { rows: number };
693
+ },
277
694
  theme: Theme,
278
695
  currentColor: AgentType["color"] | undefined,
279
696
  private readonly agentName: string,
@@ -286,12 +703,12 @@ class AgentColorPickerComponent extends Container {
286
703
  {
287
704
  value: AGENT_COLOR_DEFAULT,
288
705
  label: "Default (inherit)",
289
- description: "Use the default accent background for the agent name",
706
+ description: "Use the default accent background for the type pill",
290
707
  },
291
708
  ...AGENT_COLORS.map((color) => ({
292
709
  value: color,
293
- label: agentNameBadge(color, color, theme),
294
- description: `Agent name background: ${color}`,
710
+ label: contrastPill(color, color, theme),
711
+ description: `Type pill background: ${color}`,
295
712
  })),
296
713
  ];
297
714
  this.preview = new Text();
@@ -307,20 +724,65 @@ class AgentColorPickerComponent extends Container {
307
724
  this.updatePreview(tui, item.value);
308
725
  };
309
726
  this.selectList.onSelect = (item) => {
310
- onSelect(item.value === AGENT_COLOR_DEFAULT ? undefined : (item.value as AgentType["color"]));
727
+ onSelect(
728
+ item.value === AGENT_COLOR_DEFAULT
729
+ ? undefined
730
+ : (item.value as AgentType["color"]),
731
+ );
311
732
  };
312
733
  this.selectList.onCancel = onCancel;
313
- this.addChild(new DynamicBorder((text) => theme.fg("muted", text)));
314
- this.updatePreview(tui, this.items[selectedIndex >= 0 ? selectedIndex : 0]!.value);
315
- this.addChild(this.preview);
316
- this.addChild(this.selectList);
317
- this.addChild(new DynamicBorder((text) => theme.fg("muted", text)));
734
+ this.updatePreview(
735
+ tui,
736
+ this.items[selectedIndex >= 0 ? selectedIndex : 0]!.value,
737
+ );
318
738
  }
319
739
 
320
- getItems(): readonly { value: string; label: string; description?: string }[] {
740
+ getItems(): readonly {
741
+ value: string;
742
+ label: string;
743
+ description?: string;
744
+ }[] {
321
745
  return this.items;
322
746
  }
323
747
 
748
+ render(width: number): string[] {
749
+ const height = dialogHeight(this.tui);
750
+ const budget = Math.max(1, height - 7);
751
+ const selected = this.items.findIndex(
752
+ (item) => item.value === this.selectList.getSelectedItem()?.value,
753
+ );
754
+ const start = Math.max(
755
+ 0,
756
+ Math.min(selected - budget + 1, this.items.length - budget),
757
+ );
758
+ const body = [
759
+ ` ${truncateToWidth(
760
+ this.preview
761
+ .render(1000)
762
+ .map((line) => line.trim())
763
+ .filter(Boolean)
764
+ .join(" "),
765
+ Math.max(1, width - 4),
766
+ "",
767
+ )}`,
768
+ "",
769
+ ...this.items
770
+ .slice(start, start + budget)
771
+ .map(
772
+ (item, i) =>
773
+ `${start + i === selected ? "›" : " "} ${item.label} ${this.theme.fg("muted", item.description ?? "")}`,
774
+ ),
775
+ ];
776
+ return frameDialog(
777
+ this.theme,
778
+ width,
779
+ height,
780
+ "Agent color",
781
+ body,
782
+ "↑↓ preview · Enter apply · Esc cancel",
783
+ );
784
+ }
785
+
324
786
  getPreview(): Text {
325
787
  return this.preview;
326
788
  }
@@ -333,13 +795,16 @@ class AgentColorPickerComponent extends Container {
333
795
  this.selectList.handleInput(keyData);
334
796
  }
335
797
 
336
- private updatePreview(tui: { requestRender(force?: boolean): void }, value: string): void {
337
- const badge = agentNameBadge(
338
- `/${this.agentName}`,
339
- value === AGENT_COLOR_DEFAULT ? undefined : value,
340
- this.theme,
798
+ private updatePreview(
799
+ tui: { requestRender(force?: boolean): void },
800
+ value: string,
801
+ ): void {
802
+ const color = value === AGENT_COLOR_DEFAULT ? undefined : value;
803
+ const badge = agentTypeBadge(this.agentName, color, this.theme);
804
+ const path = agentPath("/root/example-task", color, this.theme);
805
+ this.preview.setText(
806
+ `Preview: ${badge} ${path} ${this.theme.fg("accent", "[running]")} Working`,
341
807
  );
342
- this.preview.setText(`Preview: ${badge} ${this.theme.fg("accent", "[running]")} Working`);
343
808
  tui.requestRender();
344
809
  }
345
810
  }
@@ -349,19 +814,16 @@ async function selectAgentColor(
349
814
  currentColor: AgentType["color"] | undefined,
350
815
  agentName: string,
351
816
  ): Promise<AgentType["color"] | undefined | typeof AGENT_COLOR_CANCEL> {
352
- return ctx.ui.custom(
353
- (tui, theme, _keys, done) => {
354
- return new AgentColorPickerComponent(
355
- tui,
356
- theme,
357
- currentColor,
358
- agentName,
359
- (value) => done(value),
360
- () => done(AGENT_COLOR_CANCEL),
361
- );
362
- },
363
- { overlay: true },
364
- );
817
+ return ctx.ui.custom((tui, theme, _keys, done) => {
818
+ return new AgentColorPickerComponent(
819
+ tui,
820
+ theme,
821
+ currentColor,
822
+ agentName,
823
+ (value) => done(value),
824
+ () => done(AGENT_COLOR_CANCEL),
825
+ );
826
+ }, DIALOG_OPTIONS);
365
827
  }
366
828
 
367
829
  async function editDocument(
@@ -377,7 +839,8 @@ async function editDocument(
377
839
  text = await externalEdit(ctx, text);
378
840
  } else {
379
841
  const end = text.indexOf("\n---", 4);
380
- const yaml = await ctx.ui.editor(
842
+ const yaml = await dialogEditor(
843
+ ctx,
381
844
  "Agent frontmatter YAML (Markdown body preserved)",
382
845
  text.slice(4, end),
383
846
  );
@@ -390,15 +853,28 @@ async function editDocument(
390
853
  source: type.source,
391
854
  };
392
855
  } catch (error) {
393
- const diagnostic = sanitizeText(error instanceof Error ? error.message : String(error));
394
- ctx.ui.notify(`Edit not accepted: ${diagnostic}. Original definition is unchanged.`, "error");
395
- if (
396
- !(await ctx.ui.confirm(
397
- "Invalid edit — retry?",
398
- `${diagnostic}\nRetry editing, or cancel to restore the previous definition.`,
399
- ))
400
- )
401
- return;
856
+ const diagnostic = sanitizeText(
857
+ error instanceof Error ? error.message : String(error),
858
+ );
859
+ ctx.ui.notify(
860
+ `Edit not accepted: ${diagnostic}. Original definition is unchanged.`,
861
+ "error",
862
+ );
863
+ const action = await dialogMenu(ctx, "Invalid edit — retry?", [
864
+ {
865
+ id: "Retry",
866
+ label: "Retry",
867
+ value: "Continue editing",
868
+ help: diagnostic,
869
+ },
870
+ {
871
+ id: "Cancel",
872
+ label: "Cancel",
873
+ value: "Restore previous definition",
874
+ help: diagnostic,
875
+ },
876
+ ]);
877
+ if (action !== "Retry") return;
402
878
  }
403
879
  }
404
880
  }
@@ -413,7 +889,9 @@ function assertSaveDestination(
413
889
  const entries = store.list();
414
890
  const sameName = entries.find((entry) => entry.name === type.name);
415
891
  if (sameName && (!original || type.name !== original.name)) {
416
- throw new Error(`Agent type ${type.name} already exists; choose a different name.`);
892
+ throw new Error(
893
+ `Agent type ${type.name} already exists; choose a different name.`,
894
+ );
417
895
  }
418
896
  const destination = store.destination(type.name, scope, original);
419
897
  if (
@@ -430,10 +908,14 @@ const EDIT_MENU_ACTIONS = [
430
908
  "name",
431
909
  "description",
432
910
  "models",
911
+ "modelSuggestions",
433
912
  "thinkingLevel",
434
913
  "tools.allow",
435
914
  "tools.block",
436
915
  "color",
916
+ "systemPrompt",
917
+ "Save scope",
918
+ "Source",
437
919
  "Edit frontmatter YAML",
438
920
  "External editor (entire Markdown)",
439
921
  "Save",
@@ -442,6 +924,66 @@ const EDIT_MENU_ACTIONS = [
442
924
 
443
925
  type EditMenuAction = (typeof EDIT_MENU_ACTIONS)[number];
444
926
 
927
+ const EDIT_FIELD_LABELS: Record<EditMenuAction, string> = {
928
+ name: "Name",
929
+ description: "Description",
930
+ models: "Models",
931
+ modelSuggestions: "Model suggestions",
932
+ thinkingLevel: "Thinking level",
933
+ "tools.allow": "Allowed tools",
934
+ "tools.block": "Blocked tools",
935
+ color: "Color",
936
+ systemPrompt: "System prompt",
937
+ "Save scope": "Save scope",
938
+ Source: "Source (read-only)",
939
+ "Edit frontmatter YAML": "Frontmatter YAML",
940
+ "External editor (entire Markdown)": "External editor",
941
+ Save: "Save",
942
+ Cancel: "Cancel",
943
+ };
944
+
945
+ const EDIT_FIELD_HELP: Record<EditMenuAction, string> = {
946
+ name: "Unique type identifier. Renaming retains the original file.",
947
+ description: "Description shown when browsing and spawning agents.",
948
+ models:
949
+ "Ordered model preferences. Unavailable models are skipped at runtime. Advisory names in model suggestions never pin a model.",
950
+ modelSuggestions:
951
+ "Advisory display names to help pick a model. Not provider/model pins; never selected or required. One name per line; empty clears.",
952
+ thinkingLevel: "Reasoning effort. Default follows the parent session.",
953
+ "tools.allow":
954
+ "Unset uses default policy; an empty list explicitly allows no tools.",
955
+ "tools.block": "Exact tool names to remove from the allowed set.",
956
+ color: "Thread widget color with live preview.",
957
+ systemPrompt: "Edit the Markdown prompt body in a multiline dialog.",
958
+ "Save scope":
959
+ "Project definitions override global definitions with the same name.",
960
+ Source:
961
+ "Read-only source. Bundled definitions are copied, never overwritten.",
962
+ "Edit frontmatter YAML": "Edit metadata as YAML, preserving the prompt body.",
963
+ "External editor (entire Markdown)":
964
+ "Edit the complete definition using $VISUAL / $EDITOR.",
965
+ Save: "Validate and save. Existing sessions keep their original configuration.",
966
+ Cancel: "Close without saving any edits.",
967
+ };
968
+
969
+ async function chooseSaveScope(
970
+ ctx: ExtensionCommandContext,
971
+ store: ConfigStore,
972
+ current: "user" | "project",
973
+ ): Promise<"user" | "project" | undefined> {
974
+ const choices = [
975
+ "Global",
976
+ ...(store.canSaveProject() ? ["Trusted project"] : []),
977
+ ];
978
+ const value = await dialogMenu(
979
+ ctx,
980
+ "Save scope",
981
+ choices.map((label) => ({ id: label, label })),
982
+ { selectedId: current === "user" ? "Global" : "Trusted project" },
983
+ );
984
+ return value ? (value === "Global" ? "user" : "project") : undefined;
985
+ }
986
+
445
987
  /** Omitted tool lists use the default policy; [] is an explicit empty list, not inheritance. */
446
988
  function toolListMenuValue(names: string[] | undefined): string {
447
989
  if (names === undefined) return "Unset (use default policy)";
@@ -449,6 +991,15 @@ function toolListMenuValue(names: string[] | undefined): string {
449
991
  return names.join(", ");
450
992
  }
451
993
 
994
+ function modelSuggestionLabel(suggestions: string[] | undefined): string {
995
+ if (suggestions === undefined || suggestions.length === 0) return "None";
996
+ return suggestions.join(", ");
997
+ }
998
+
999
+ function modelSuggestionPrefill(suggestions: string[] | undefined): string {
1000
+ return (suggestions ?? []).map((name) => sanitizeText(name)).join("\n");
1001
+ }
1002
+
452
1003
  function editMenuLabel(action: EditMenuAction, draft: AgentType): string {
453
1004
  switch (action) {
454
1005
  case "name":
@@ -459,6 +1010,8 @@ function editMenuLabel(action: EditMenuAction, draft: AgentType): string {
459
1010
  const models = getModelPreferences(draft);
460
1011
  return `models: ${sanitizeText(models?.join(", ") ?? "Default (inherit)")}`;
461
1012
  }
1013
+ case "modelSuggestions":
1014
+ return `modelSuggestions: ${sanitizeText(modelSuggestionLabel(draft.modelSuggestions))}`;
462
1015
  case "thinkingLevel":
463
1016
  return `thinkingLevel: ${sanitizeText(draft.thinkingLevel ?? "Default (inherit)")}`;
464
1017
  case "tools.allow":
@@ -467,6 +1020,8 @@ function editMenuLabel(action: EditMenuAction, draft: AgentType): string {
467
1020
  return `tools.block: ${sanitizeText(toolListMenuValue(draft.tools?.block))}`;
468
1021
  case "color":
469
1022
  return `color: ${sanitizeText(draft.color ?? "Default (inherit)")}`;
1023
+ case "systemPrompt":
1024
+ return `systemPrompt: ${draft.systemPrompt.split("\n").length} lines · ${draft.systemPrompt.length} characters`;
470
1025
  default:
471
1026
  return action;
472
1027
  }
@@ -476,32 +1031,82 @@ export async function editAgentTypes(
476
1031
  ctx: ExtensionCommandContext,
477
1032
  store: ConfigStore,
478
1033
  ): Promise<void> {
479
- if (!ctx.hasUI) return;
1034
+ if (!canOpenDialog(ctx)) return;
1035
+ await withDialogSession(ctx, (scoped) => editAgentTypesDialog(scoped, store));
1036
+ }
1037
+
1038
+ async function editAgentTypesDialog(
1039
+ ctx: ExtensionCommandContext,
1040
+ store: ConfigStore,
1041
+ ): Promise<void> {
480
1042
  while (true) {
481
1043
  const types = store.list();
482
- const names = types.map((type) => type.name);
483
- const selection = await ctx.ui.select("Agent types", ["Create new type", ...names]);
1044
+ const selection = await dialogMenu(ctx, "Agent types", [
1045
+ {
1046
+ id: "Create new type",
1047
+ label: "Create new type",
1048
+ value: "New definition",
1049
+ help: "Nothing is written until you save.",
1050
+ },
1051
+ ...types.map((type) => ({
1052
+ id: type.name,
1053
+ label: type.name,
1054
+ value: type.description,
1055
+ help: `${type.source ?? "user"} · ${type.filePath ?? ""}`,
1056
+ })),
1057
+ ]);
484
1058
  if (selection === undefined) return;
485
- const original = selection === "Create new type" ? undefined : store.get(selection);
1059
+ const original =
1060
+ selection === "Create new type" ? undefined : store.get(selection);
486
1061
  let draft: AgentType = original
487
1062
  ? structuredClone(original)
488
1063
  : { name: "new-agent", description: "New agent", systemPrompt: "" };
1064
+ let selectedId: string | undefined;
1065
+ let saveScope: "user" | "project" =
1066
+ original?.source === "project" && store.canSaveProject()
1067
+ ? "project"
1068
+ : "user";
489
1069
  while (true) {
490
- const labels = EDIT_MENU_ACTIONS.map((action) => editMenuLabel(action, draft));
491
- const selected = await ctx.ui.select(`Edit ${sanitizeText(draft.name)} (unsaved)`, labels);
492
- if (selected === undefined) break;
493
- const field = EDIT_MENU_ACTIONS[labels.indexOf(selected)];
1070
+ const field = await dialogMenu(
1071
+ ctx,
1072
+ `Edit ${sanitizeText(draft.name)} (unsaved)`,
1073
+ EDIT_MENU_ACTIONS.map((action) => {
1074
+ const decorated = editMenuLabel(action, draft);
1075
+ const separator = decorated.indexOf(": ");
1076
+ return {
1077
+ id: action,
1078
+ label: EDIT_FIELD_LABELS[action],
1079
+ value:
1080
+ action === "Source"
1081
+ ? (original?.source ?? "New draft")
1082
+ : action === "Save scope"
1083
+ ? saveScope === "user"
1084
+ ? "Global"
1085
+ : "Trusted project"
1086
+ : separator >= 0
1087
+ ? decorated.slice(separator + 2)
1088
+ : "",
1089
+ help:
1090
+ action === "Source"
1091
+ ? (original?.filePath ??
1092
+ "Not saved yet. Bundled definitions are copied, never overwritten.")
1093
+ : EDIT_FIELD_HELP[action],
1094
+ };
1095
+ }),
1096
+ {
1097
+ selectedId,
1098
+ saveId: "Save",
1099
+ footer: "↑↓/Tab fields · Enter edit · Ctrl+S save · Esc cancel",
1100
+ },
1101
+ );
1102
+ selectedId = field;
494
1103
  if (!field || field === "Cancel") break;
495
1104
  try {
496
1105
  if (field === "Save") {
497
1106
  // Round-trip before saving: no partial or invalid configuration is accepted.
498
1107
  const validated = parseAgentType(serializeAgentType(draft));
499
- const scopeChoice = await ctx.ui.select(
500
- "Save scope",
501
- store.canSaveProject() ? ["Global", "Trusted project"] : ["Global"],
502
- );
503
- if (!scopeChoice) continue;
504
- const scope = scopeChoice === "Global" ? "user" : "project";
1108
+ const scope = await chooseSaveScope(ctx, store, saveScope);
1109
+ if (!scope) continue;
505
1110
  assertSaveDestination(store, validated, original, scope);
506
1111
  const saved = store.save(validated, scope, original);
507
1112
  ctx.ui.notify(
@@ -510,7 +1115,22 @@ export async function editAgentTypes(
510
1115
  );
511
1116
  break;
512
1117
  }
513
- if (field === "External editor (entire Markdown)" || field === "Edit frontmatter YAML") {
1118
+ if (field === "Save scope") {
1119
+ const scope = await chooseSaveScope(ctx, store, saveScope);
1120
+ if (scope) saveScope = scope;
1121
+ continue;
1122
+ }
1123
+ if (field === "Source") {
1124
+ ctx.ui.notify(
1125
+ original?.filePath ?? "This definition has not been saved yet.",
1126
+ "info",
1127
+ );
1128
+ continue;
1129
+ }
1130
+ if (
1131
+ field === "External editor (entire Markdown)" ||
1132
+ field === "Edit frontmatter YAML"
1133
+ ) {
514
1134
  const edited = await editDocument(
515
1135
  ctx,
516
1136
  draft,
@@ -520,7 +1140,11 @@ export async function editAgentTypes(
520
1140
  continue;
521
1141
  }
522
1142
  const candidate = structuredClone(draft);
523
- if (field === "name" || field === "description") {
1143
+ if (
1144
+ field === "name" ||
1145
+ field === "description" ||
1146
+ field === "systemPrompt"
1147
+ ) {
524
1148
  const originalValue = candidate[field] ?? "";
525
1149
  // Editor prefill must not carry terminal controls. An unmodified or
526
1150
  // SDK-trimmed submit keeps the original, including whitespace and CRLF.
@@ -530,11 +1154,17 @@ export async function editAgentTypes(
530
1154
  .split("\n")
531
1155
  .map(sanitizeText)
532
1156
  .join("\n");
533
- const value = await ctx.ui.editor(`Agent ${field}`, prefill);
1157
+ const value = await dialogEditor(ctx, `Agent ${field}`, prefill);
534
1158
  if (value === undefined) continue;
535
- candidate[field] = value === prefill || value === prefill.trim() ? originalValue : value;
1159
+ candidate[field] =
1160
+ value === prefill || value === prefill.trim()
1161
+ ? originalValue
1162
+ : value;
536
1163
  } else if (field === "models") {
537
- const value = await editModelPreferences(ctx, getModelPreferences(candidate));
1164
+ const value = await editModelPreferences(
1165
+ ctx,
1166
+ getModelPreferences(candidate),
1167
+ );
538
1168
  if (value === MODEL_EDITOR_CANCEL) continue;
539
1169
  if (value.length === 0) {
540
1170
  delete candidate.models;
@@ -543,21 +1173,49 @@ export async function editAgentTypes(
543
1173
  candidate.models = [...value];
544
1174
  delete candidate.model;
545
1175
  }
1176
+ } else if (field === "modelSuggestions") {
1177
+ const prefill = modelSuggestionPrefill(candidate.modelSuggestions);
1178
+ const value = await dialogEditor(
1179
+ ctx,
1180
+ "Agent modelSuggestions (one display name per line)",
1181
+ prefill,
1182
+ );
1183
+ if (value === undefined) continue;
1184
+ if (value === prefill || value === prefill.trim()) continue;
1185
+ const names = value
1186
+ .split("\n")
1187
+ .map((line) => line.trim())
1188
+ .filter((line) => line.length > 0);
1189
+ if (names.length === 0) delete candidate.modelSuggestions;
1190
+ else candidate.modelSuggestions = [...names];
546
1191
  } else if (field === "thinkingLevel") {
547
- const value = await ctx.ui.select("Thinking level", [
548
- "Default (inherit)",
549
- ...THINKING_LEVELS,
550
- ]);
1192
+ const value = await dialogMenu(
1193
+ ctx,
1194
+ "Thinking level",
1195
+ ["Default (inherit)", ...THINKING_LEVELS].map((label) => ({
1196
+ id: label,
1197
+ label,
1198
+ })),
1199
+ { selectedId: candidate.thinkingLevel ?? "Default (inherit)" },
1200
+ );
551
1201
  if (!value) continue;
552
1202
  if (value === "Default (inherit)") delete candidate.thinkingLevel;
553
1203
  else candidate.thinkingLevel = value as AgentType["thinkingLevel"];
554
1204
  } else if (field === "color") {
555
- const value = await selectAgentColor(ctx, candidate.color, candidate.name);
1205
+ const value = await selectAgentColor(
1206
+ ctx,
1207
+ candidate.color,
1208
+ candidate.name,
1209
+ );
556
1210
  if (value === AGENT_COLOR_CANCEL) continue;
557
1211
  if (value === undefined) delete candidate.color;
558
1212
  else candidate.color = value;
559
1213
  } else if (field === "tools.allow" || field === "tools.block") {
560
- await editToolList(ctx, candidate, field === "tools.allow" ? "allow" : "block");
1214
+ await editToolList(
1215
+ ctx,
1216
+ candidate,
1217
+ field === "tools.allow" ? "allow" : "block",
1218
+ );
561
1219
  }
562
1220
  parseAgentType(serializeAgentType(candidate));
563
1221
  draft = candidate;