@leing2021/super-pi 0.20.0 → 0.22.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.
Files changed (79) hide show
  1. package/README.md +40 -19
  2. package/extensions/ce-core/index.ts +7 -136
  3. package/extensions/subagent/agent-management.ts +595 -0
  4. package/extensions/subagent/agent-manager-chain-detail.ts +162 -0
  5. package/extensions/subagent/agent-manager-detail.ts +231 -0
  6. package/extensions/subagent/agent-manager-edit.ts +390 -0
  7. package/extensions/subagent/agent-manager-list.ts +278 -0
  8. package/extensions/subagent/agent-manager-parallel.ts +304 -0
  9. package/extensions/subagent/agent-manager.ts +705 -0
  10. package/extensions/subagent/agent-scope.ts +8 -0
  11. package/extensions/subagent/agent-selection.ts +25 -0
  12. package/extensions/subagent/agent-serializer.ts +123 -0
  13. package/extensions/subagent/agent-templates.ts +62 -0
  14. package/extensions/subagent/agents/context-builder.md +37 -0
  15. package/extensions/subagent/agents/delegate.md +9 -0
  16. package/extensions/subagent/agents/oracle.md +73 -0
  17. package/extensions/subagent/agents/planner.md +52 -0
  18. package/extensions/subagent/agents/researcher.md +50 -0
  19. package/extensions/subagent/agents/reviewer.md +38 -0
  20. package/extensions/subagent/agents/scout.md +48 -0
  21. package/extensions/subagent/agents/worker.md +52 -0
  22. package/extensions/subagent/agents.ts +761 -0
  23. package/extensions/subagent/artifacts.ts +100 -0
  24. package/extensions/subagent/async-execution.ts +520 -0
  25. package/extensions/subagent/async-job-tracker.ts +216 -0
  26. package/extensions/subagent/async-status.ts +241 -0
  27. package/extensions/subagent/chain-clarify.ts +1364 -0
  28. package/extensions/subagent/chain-execution.ts +853 -0
  29. package/extensions/subagent/chain-serializer.ts +126 -0
  30. package/extensions/subagent/completion-dedupe.ts +65 -0
  31. package/extensions/subagent/doctor.ts +200 -0
  32. package/extensions/subagent/execution.ts +738 -0
  33. package/extensions/subagent/file-coalescer.ts +42 -0
  34. package/extensions/subagent/fork-context.ts +63 -0
  35. package/extensions/subagent/formatters.ts +122 -0
  36. package/extensions/subagent/frontmatter.ts +31 -0
  37. package/extensions/subagent/index.ts +585 -0
  38. package/extensions/subagent/intercom-bridge.ts +240 -0
  39. package/extensions/subagent/jsonl-writer.ts +83 -0
  40. package/extensions/subagent/model-fallback.ts +108 -0
  41. package/extensions/subagent/notify.ts +110 -0
  42. package/extensions/subagent/parallel-utils.ts +108 -0
  43. package/extensions/subagent/pi-args.ts +138 -0
  44. package/extensions/subagent/pi-spawn.ts +100 -0
  45. package/extensions/subagent/post-exit-stdio-guard.ts +87 -0
  46. package/extensions/subagent/prompt-template-bridge.ts +399 -0
  47. package/extensions/subagent/prompts/gather-context-and-clarify.md +13 -0
  48. package/extensions/subagent/prompts/parallel-cleanup.md +42 -0
  49. package/extensions/subagent/prompts/parallel-research.md +50 -0
  50. package/extensions/subagent/prompts/parallel-review.md +40 -0
  51. package/extensions/subagent/render-helpers.ts +82 -0
  52. package/extensions/subagent/render.ts +836 -0
  53. package/extensions/subagent/result-intercom.ts +237 -0
  54. package/extensions/subagent/result-watcher.ts +171 -0
  55. package/extensions/subagent/run-history.ts +57 -0
  56. package/extensions/subagent/run-status.ts +136 -0
  57. package/extensions/subagent/schemas.ts +164 -0
  58. package/extensions/subagent/session-tokens.ts +50 -0
  59. package/extensions/subagent/settings.ts +367 -0
  60. package/extensions/subagent/single-output.ts +97 -0
  61. package/extensions/subagent/skills.ts +626 -0
  62. package/extensions/subagent/slash-bridge.ts +176 -0
  63. package/extensions/subagent/slash-commands.ts +303 -0
  64. package/extensions/subagent/slash-live-state.ts +294 -0
  65. package/extensions/subagent/subagent-control.ts +150 -0
  66. package/extensions/subagent/subagent-executor.ts +1899 -0
  67. package/extensions/subagent/subagent-prompt-runtime.ts +75 -0
  68. package/extensions/subagent/subagent-runner.ts +1470 -0
  69. package/extensions/subagent/subagents-status.ts +472 -0
  70. package/extensions/subagent/text-editor.ts +272 -0
  71. package/extensions/subagent/top-level-async.ts +15 -0
  72. package/extensions/subagent/types.ts +623 -0
  73. package/extensions/subagent/utils.ts +456 -0
  74. package/extensions/subagent/worktree.ts +579 -0
  75. package/extensions/super-pi-extension/agents/ce-worker.md +1 -1
  76. package/extensions/super-pi-extension/index.ts +2 -55
  77. package/package.json +12 -5
  78. package/skills/03-work/SKILL.md +3 -3
  79. package/skills/pi-subagents/SKILL.md +566 -0
@@ -0,0 +1,1364 @@
1
+ // Based on pi-subagents by Nico Bailon (https://github.com/nicobailon/pi-subagents)
2
+ // MIT License
3
+ /**
4
+ * Chain Clarification TUI Component
5
+ *
6
+ * Shows templates and resolved behaviors for each step in a chain.
7
+ * Supports editing templates, output paths, reads lists, and progress toggle.
8
+ */
9
+
10
+ import type { Theme } from "@mariozechner/pi-coding-agent";
11
+ import type { Component, TUI } from "@mariozechner/pi-tui";
12
+ import { matchesKey, visibleWidth, truncateToWidth } from "@mariozechner/pi-tui";
13
+ import * as fs from "node:fs";
14
+ import * as os from "node:os";
15
+ import * as path from "node:path";
16
+ import type { AgentConfig, ChainConfig, ChainStepConfig } from "./agents.ts";
17
+ import type { ResolvedStepBehavior } from "./settings.ts";
18
+ import type { TextEditorState } from "./text-editor.ts";
19
+ import { createEditorState, ensureCursorVisible, getCursorDisplayPos, handleEditorInput, renderEditor, wrapText } from "./text-editor.ts";
20
+ import { updateFrontmatterField } from "./agent-serializer.ts";
21
+ import { serializeChain } from "./chain-serializer.ts";
22
+ import { resolveModelCandidate, splitThinkingSuffix } from "./model-fallback.ts";
23
+
24
+ export type ClarifyMode = 'single' | 'parallel' | 'chain';
25
+
26
+ export interface ModelInfo {
27
+ provider: string;
28
+ id: string;
29
+ fullId: string;
30
+ }
31
+
32
+ export interface BehaviorOverride {
33
+ output?: string | false;
34
+ reads?: string[] | false;
35
+ progress?: boolean;
36
+ model?: string;
37
+ skills?: string[] | false;
38
+ }
39
+
40
+ export interface ChainClarifyResult {
41
+ confirmed: boolean;
42
+ templates: string[];
43
+ behaviorOverrides: (BehaviorOverride | undefined)[];
44
+ runInBackground?: boolean;
45
+ }
46
+
47
+ type EditMode = "template" | "output" | "reads" | "model" | "thinking" | "skills";
48
+
49
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"] as const;
50
+ type ThinkingLevel = typeof THINKING_LEVELS[number];
51
+
52
+ /**
53
+ * TUI component for chain clarification.
54
+ * Factory signature matches ctx.ui.custom: (tui, theme, kb, done) => Component
55
+ */
56
+ export class ChainClarifyComponent implements Component {
57
+ readonly width = 84;
58
+
59
+ private selectedStep = 0;
60
+ private editingStep: number | null = null;
61
+ private editMode: EditMode = "template";
62
+ private editState: TextEditorState = createEditorState();
63
+
64
+ private readonly EDIT_VIEWPORT_HEIGHT = 12;
65
+ private behaviorOverrides: Map<number, BehaviorOverride> = new Map();
66
+ private modelSearchQuery: string = "";
67
+ private modelSelectedIndex: number = 0;
68
+ private filteredModels: ModelInfo[] = [];
69
+ private readonly MODEL_SELECTOR_HEIGHT = 10;
70
+ private thinkingSelectedIndex: number = 0;
71
+ private skillSearchQuery: string = "";
72
+ private skillSelectedNames: Set<string> = new Set();
73
+ private skillCursorIndex: number = 0;
74
+ private filteredSkills: Array<{ name: string; source: string; description?: string }> = [];
75
+ private saveMessage: { text: string; type: "info" | "error" } | null = null;
76
+ private saveMessageTimer: ReturnType<typeof setTimeout> | null = null;
77
+ private saveChainNameState: TextEditorState = createEditorState();
78
+ private savingChain = false;
79
+ /** Run in background (async) mode */
80
+ private runInBackground = false;
81
+ private tui: TUI;
82
+ private theme: Theme;
83
+ private agentConfigs: AgentConfig[];
84
+ private templates: string[];
85
+ private originalTask: string;
86
+ private chainDir: string | undefined;
87
+ private resolvedBehaviors: ResolvedStepBehavior[];
88
+ private availableModels: ModelInfo[];
89
+ private preferredProvider: string | undefined;
90
+ private availableSkills: Array<{ name: string; source: string; description?: string }>;
91
+ private done: (result: ChainClarifyResult) => void;
92
+ private mode: ClarifyMode;
93
+
94
+ constructor(
95
+ tui: TUI,
96
+ theme: Theme,
97
+ agentConfigs: AgentConfig[],
98
+ templates: string[],
99
+ originalTask: string,
100
+ chainDir: string | undefined,
101
+ resolvedBehaviors: ResolvedStepBehavior[],
102
+ availableModels: ModelInfo[],
103
+ preferredProvider: string | undefined,
104
+ availableSkills: Array<{ name: string; source: string; description?: string }>,
105
+ done: (result: ChainClarifyResult) => void,
106
+ mode: ClarifyMode = 'chain',
107
+ ) {
108
+ this.tui = tui;
109
+ this.theme = theme;
110
+ this.agentConfigs = agentConfigs;
111
+ this.templates = templates;
112
+ this.originalTask = originalTask;
113
+ this.chainDir = chainDir;
114
+ this.resolvedBehaviors = resolvedBehaviors;
115
+ this.availableModels = availableModels;
116
+ this.preferredProvider = preferredProvider;
117
+ this.availableSkills = availableSkills;
118
+ this.done = done;
119
+ this.mode = mode;
120
+ this.filteredModels = [...availableModels];
121
+ this.filteredSkills = [...availableSkills];
122
+ }
123
+
124
+ // ─────────────────────────────────────────────────────────────────────────────
125
+ // Helper methods for rendering
126
+ // ─────────────────────────────────────────────────────────────────────────────
127
+
128
+ /** Pad string to specified visible width */
129
+ private pad(s: string, len: number): string {
130
+ const vis = visibleWidth(s);
131
+ return s + " ".repeat(Math.max(0, len - vis));
132
+ }
133
+
134
+ /** Create a row with border characters */
135
+ private row(content: string): string {
136
+ const innerW = this.width - 2;
137
+ return this.theme.fg("border", "│") + this.pad(content, innerW) + this.theme.fg("border", "│");
138
+ }
139
+
140
+ /** Render centered header line with border */
141
+ private renderHeader(text: string): string {
142
+ const innerW = this.width - 2;
143
+ const padLen = Math.max(0, innerW - visibleWidth(text));
144
+ const padLeft = Math.floor(padLen / 2);
145
+ const padRight = padLen - padLeft;
146
+ return (
147
+ this.theme.fg("border", "╭" + "─".repeat(padLeft)) +
148
+ this.theme.fg("accent", text) +
149
+ this.theme.fg("border", "─".repeat(padRight) + "╮")
150
+ );
151
+ }
152
+
153
+ /** Render centered footer line with border */
154
+ private renderFooter(text: string): string {
155
+ const innerW = this.width - 2;
156
+ const padLen = Math.max(0, innerW - visibleWidth(text));
157
+ const padLeft = Math.floor(padLen / 2);
158
+ const padRight = padLen - padLeft;
159
+ return (
160
+ this.theme.fg("border", "╰" + "─".repeat(padLeft)) +
161
+ this.theme.fg("dim", text) +
162
+ this.theme.fg("border", "─".repeat(padRight) + "╯")
163
+ );
164
+ }
165
+
166
+ /** Exit edit mode and reset state */
167
+ private exitEditMode(): void {
168
+ this.editingStep = null;
169
+ this.editState = createEditorState();
170
+ this.tui.requestRender();
171
+ }
172
+
173
+ // ─────────────────────────────────────────────────────────────────────────────
174
+ // Full edit mode methods
175
+ // ─────────────────────────────────────────────────────────────────────────────
176
+
177
+ /** Render the full-edit takeover view */
178
+ private renderFullEditMode(): string[] {
179
+ const innerW = this.width - 2;
180
+ const textWidth = innerW - 2; // 1 char padding on each side
181
+ const lines: string[] = [];
182
+
183
+ const { lines: wrapped, starts } = wrapText(this.editState.buffer, textWidth);
184
+ const cursorPos = getCursorDisplayPos(this.editState.cursor, starts);
185
+ this.editState = {
186
+ ...this.editState,
187
+ viewportOffset: ensureCursorVisible(
188
+ cursorPos.line,
189
+ this.EDIT_VIEWPORT_HEIGHT,
190
+ this.editState.viewportOffset,
191
+ ),
192
+ };
193
+
194
+ // Header (truncate agent name to prevent overflow)
195
+ const fieldName = this.editMode === "template" ? "task" : this.editMode;
196
+ const rawAgentName = this.agentConfigs[this.editingStep!]?.name ?? "unknown";
197
+ const maxAgentLen = innerW - 30; // Reserve space for " Editing X (Step/Task N: ) "
198
+ const agentName = rawAgentName.length > maxAgentLen
199
+ ? rawAgentName.slice(0, maxAgentLen - 1) + "…"
200
+ : rawAgentName;
201
+ // Use mode-appropriate terminology
202
+ const stepLabel = this.mode === 'single'
203
+ ? agentName
204
+ : this.mode === 'parallel'
205
+ ? `Task ${this.editingStep! + 1}: ${agentName}`
206
+ : `Step ${this.editingStep! + 1}: ${agentName}`;
207
+ const headerText = ` Editing ${fieldName} (${stepLabel}) `;
208
+ lines.push(this.renderHeader(headerText));
209
+ lines.push(this.row(""));
210
+
211
+ const editorLines = renderEditor(this.editState, textWidth, this.EDIT_VIEWPORT_HEIGHT);
212
+ for (const line of editorLines) {
213
+ lines.push(this.row(` ${line}`));
214
+ }
215
+
216
+ const linesBelow = wrapped.length - this.editState.viewportOffset - this.EDIT_VIEWPORT_HEIGHT;
217
+ const hasMore = linesBelow > 0;
218
+ const hasLess = this.editState.viewportOffset > 0;
219
+ let scrollInfo = "";
220
+ if (hasLess) scrollInfo += "↑";
221
+ if (hasMore) scrollInfo += `↓ ${linesBelow}+`;
222
+
223
+ lines.push(this.row(""));
224
+
225
+ const footerText = scrollInfo
226
+ ? ` [Esc] Done • [Ctrl+C] Discard • ${scrollInfo} `
227
+ : " [Esc] Done • [Ctrl+C] Discard ";
228
+ lines.push(this.renderFooter(footerText));
229
+
230
+ return lines;
231
+ }
232
+
233
+ // ─────────────────────────────────────────────────────────────────────────────
234
+ // Behavior helpers
235
+ // ─────────────────────────────────────────────────────────────────────────────
236
+
237
+ /** Get effective behavior for a step (with user overrides applied) */
238
+ private getEffectiveBehavior(stepIndex: number): ResolvedStepBehavior {
239
+ const base = this.resolvedBehaviors[stepIndex]!;
240
+ const override = this.behaviorOverrides.get(stepIndex);
241
+ if (!override) return base;
242
+
243
+ return {
244
+ output: override.output !== undefined ? override.output : base.output,
245
+ reads: override.reads !== undefined ? override.reads : base.reads,
246
+ progress: override.progress !== undefined ? override.progress : base.progress,
247
+ skills: override.skills !== undefined ? override.skills : base.skills,
248
+ model: override.model !== undefined ? override.model : base.model,
249
+ };
250
+ }
251
+
252
+ /** Get the effective model for a step (override or agent default) */
253
+ private getEffectiveModel(stepIndex: number): string {
254
+ const override = this.behaviorOverrides.get(stepIndex);
255
+ if (override?.model) return this.resolveModelFullId(override.model);
256
+
257
+ const baseModel = this.resolvedBehaviors[stepIndex]?.model;
258
+ if (baseModel) return this.resolveModelFullId(baseModel);
259
+ return "default";
260
+ }
261
+
262
+ /** Resolve a model name to its full provider/model format */
263
+ private resolveModelFullId(modelName: string): string {
264
+ return resolveModelCandidate(modelName, this.availableModels, this.preferredProvider) ?? modelName;
265
+ }
266
+
267
+ /** Update a behavior override for a step */
268
+ private updateBehavior(stepIndex: number, field: keyof BehaviorOverride, value: string | boolean | string[] | false): void {
269
+ const existing = this.behaviorOverrides.get(stepIndex) ?? {};
270
+ this.behaviorOverrides.set(stepIndex, { ...existing, [field]: value });
271
+ }
272
+
273
+ private buildChainConfig(name: string): ChainConfig {
274
+ const steps: ChainStepConfig[] = [];
275
+ for (let i = 0; i < this.agentConfigs.length; i++) {
276
+ const agent = this.agentConfigs[i]!;
277
+ const behavior = this.getEffectiveBehavior(i);
278
+ const override = this.behaviorOverrides.get(i);
279
+ const template = this.templates[i] ?? "";
280
+ const step: ChainStepConfig = { agent: agent.name, task: template };
281
+ if (override?.output !== undefined) step.output = behavior.output;
282
+ if (override?.reads !== undefined) step.reads = behavior.reads;
283
+ if (override?.model !== undefined) step.model = behavior.model;
284
+ if (override?.skills !== undefined) step.skills = behavior.skills;
285
+ if (override?.progress !== undefined) step.progress = behavior.progress;
286
+ steps.push(step);
287
+ }
288
+ return {
289
+ name,
290
+ description: `Chain: ${steps.map((s) => s.agent).join(" → ")}`,
291
+ source: "user",
292
+ filePath: "",
293
+ steps,
294
+ };
295
+ }
296
+
297
+ private enterSaveChainName(): void {
298
+ this.savingChain = true;
299
+ this.saveChainNameState = createEditorState();
300
+ this.tui.requestRender();
301
+ }
302
+
303
+ private handleSaveChainNameInput(data: string): void {
304
+ if (matchesKey(data, "tab")) return;
305
+ const innerW = this.width - 2;
306
+ const boxInnerWidth = Math.max(10, innerW - 4);
307
+ const nextState = handleEditorInput(this.saveChainNameState, data, boxInnerWidth);
308
+ if (nextState) {
309
+ this.saveChainNameState = nextState;
310
+ this.tui.requestRender();
311
+ return;
312
+ }
313
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
314
+ this.savingChain = false;
315
+ this.saveChainNameState = createEditorState();
316
+ this.tui.requestRender();
317
+ return;
318
+ }
319
+ if (matchesKey(data, "return")) {
320
+ const name = this.saveChainNameState.buffer.trim();
321
+ if (!name) {
322
+ this.showSaveMessage("Name is required", "error");
323
+ this.savingChain = false;
324
+ this.saveChainNameState = createEditorState();
325
+ return;
326
+ }
327
+ try {
328
+ const dir = path.join(os.homedir(), ".pi", "agent", "agents");
329
+ fs.mkdirSync(dir, { recursive: true });
330
+ const filePath = path.join(dir, `${name}.chain.md`);
331
+ const config = this.buildChainConfig(name);
332
+ config.filePath = filePath;
333
+ fs.writeFileSync(filePath, serializeChain(config), "utf-8");
334
+ this.showSaveMessage(`Saved ${name}.chain.md`, "info");
335
+ } catch (err) {
336
+ this.showSaveMessage(err instanceof Error ? err.message : String(err), "error");
337
+ }
338
+ this.savingChain = false;
339
+ this.saveChainNameState = createEditorState();
340
+ }
341
+ }
342
+
343
+ private showSaveMessage(text: string, type: "info" | "error"): void {
344
+ this.saveMessage = { text, type };
345
+ if (this.saveMessageTimer) clearTimeout(this.saveMessageTimer);
346
+ this.saveMessageTimer = setTimeout(() => {
347
+ this.saveMessage = null;
348
+ this.saveMessageTimer = null;
349
+ this.tui.requestRender();
350
+ }, 2000);
351
+ this.tui.requestRender();
352
+ }
353
+
354
+ private arraysEqual(a: string[] | false, b: string[] | false): boolean {
355
+ if (a === b) return true;
356
+ if (a === false || b === false) return false;
357
+ if (a.length !== b.length) return false;
358
+ for (let i = 0; i < a.length; i++) {
359
+ if (a[i] !== b[i]) return false;
360
+ }
361
+ return true;
362
+ }
363
+
364
+ private saveOverridesToAgent(): void {
365
+ const stepIndex = this.selectedStep;
366
+ const agent = this.agentConfigs[stepIndex];
367
+ if (!agent?.filePath) {
368
+ this.showSaveMessage("Agent file not found", "error");
369
+ return;
370
+ }
371
+
372
+ const override = this.behaviorOverrides.get(stepIndex);
373
+ if (!override) {
374
+ this.showSaveMessage("No changes to save", "info");
375
+ return;
376
+ }
377
+
378
+ const base = this.resolvedBehaviors[stepIndex]!;
379
+ const updates: Array<{ field: string; value: string | undefined }> = [];
380
+
381
+ if (override.output !== undefined && override.output !== base.output) {
382
+ updates.push({
383
+ field: "output",
384
+ value: override.output === false ? undefined : override.output,
385
+ });
386
+ }
387
+
388
+ if (override.reads !== undefined && !this.arraysEqual(override.reads, base.reads)) {
389
+ updates.push({
390
+ field: "defaultReads",
391
+ value: override.reads === false ? undefined : override.reads.join(", "),
392
+ });
393
+ }
394
+
395
+ if (override.progress !== undefined && override.progress !== base.progress) {
396
+ updates.push({
397
+ field: "defaultProgress",
398
+ value: override.progress ? "true" : undefined,
399
+ });
400
+ }
401
+
402
+ if (override.skills !== undefined && !this.arraysEqual(override.skills, base.skills)) {
403
+ updates.push({
404
+ field: "skills",
405
+ value: override.skills === false || override.skills.length === 0 ? undefined : override.skills.join(", "),
406
+ });
407
+ }
408
+
409
+ if (override.model !== undefined) {
410
+ const baseModel = agent.model ? this.resolveModelFullId(agent.model) : undefined;
411
+ if (override.model !== baseModel) {
412
+ updates.push({ field: "model", value: override.model });
413
+ }
414
+ }
415
+
416
+ if (updates.length === 0) {
417
+ this.showSaveMessage("No changes to save", "info");
418
+ return;
419
+ }
420
+
421
+ try {
422
+ for (const update of updates) {
423
+ updateFrontmatterField(agent.filePath, update.field, update.value);
424
+ }
425
+ this.showSaveMessage("Saved agent settings", "info");
426
+ } catch (err) {
427
+ this.showSaveMessage(err instanceof Error ? err.message : String(err), "error");
428
+ }
429
+ }
430
+
431
+ handleInput(data: string): void {
432
+ if (this.savingChain) {
433
+ this.handleSaveChainNameInput(data);
434
+ return;
435
+ }
436
+
437
+ if (this.editingStep !== null) {
438
+ if (this.editMode === "model") {
439
+ this.handleModelSelectorInput(data);
440
+ } else if (this.editMode === "thinking") {
441
+ this.handleThinkingSelectorInput(data);
442
+ } else if (this.editMode === "skills") {
443
+ this.handleSkillSelectorInput(data);
444
+ } else {
445
+ this.handleEditInput(data);
446
+ }
447
+ return;
448
+ }
449
+
450
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
451
+ this.done({ confirmed: false, templates: [], behaviorOverrides: [] });
452
+ return;
453
+ }
454
+
455
+ if (matchesKey(data, "return")) {
456
+ const overrides: (BehaviorOverride | undefined)[] = [];
457
+ for (let i = 0; i < this.agentConfigs.length; i++) {
458
+ overrides.push(this.behaviorOverrides.get(i));
459
+ }
460
+ this.done({ confirmed: true, templates: this.templates, behaviorOverrides: overrides, runInBackground: this.runInBackground });
461
+ return;
462
+ }
463
+
464
+ if (matchesKey(data, "up")) {
465
+ this.selectedStep = Math.max(0, this.selectedStep - 1);
466
+ this.tui.requestRender();
467
+ return;
468
+ }
469
+
470
+ if (matchesKey(data, "down")) {
471
+ const maxStep = Math.max(0, this.agentConfigs.length - 1);
472
+ this.selectedStep = Math.min(maxStep, this.selectedStep + 1);
473
+ this.tui.requestRender();
474
+ return;
475
+ }
476
+
477
+ if (data === "e") {
478
+ this.enterEditMode("template");
479
+ return;
480
+ }
481
+
482
+ if (data === "m") {
483
+ this.enterModelSelector();
484
+ return;
485
+ }
486
+
487
+ if (data === "t") {
488
+ this.enterThinkingSelector();
489
+ return;
490
+ }
491
+
492
+ if (data === "s") {
493
+ this.editingStep = this.selectedStep;
494
+ this.editMode = "skills";
495
+ this.skillSearchQuery = "";
496
+ this.skillCursorIndex = 0;
497
+ this.filteredSkills = [...this.availableSkills];
498
+ const current = this.getEffectiveBehavior(this.selectedStep).skills;
499
+ this.skillSelectedNames.clear();
500
+ if (current !== false && current.length > 0) {
501
+ current.forEach((skillName) => this.skillSelectedNames.add(skillName));
502
+ }
503
+ this.tui.requestRender();
504
+ return;
505
+ }
506
+
507
+ if (data === "w" && this.mode !== 'parallel') {
508
+ this.enterEditMode("output");
509
+ return;
510
+ }
511
+
512
+ if (data === "r" && this.mode === 'chain') {
513
+ this.enterEditMode("reads");
514
+ return;
515
+ }
516
+
517
+ if (data === "p" && this.mode === 'chain') {
518
+ const anyEnabled = this.agentConfigs.some((_, i) => this.getEffectiveBehavior(i).progress);
519
+ const newState = !anyEnabled;
520
+ for (let i = 0; i < this.agentConfigs.length; i++) {
521
+ this.updateBehavior(i, "progress", newState);
522
+ }
523
+ this.tui.requestRender();
524
+ return;
525
+ }
526
+
527
+ if (data === "b") {
528
+ this.runInBackground = !this.runInBackground;
529
+ this.tui.requestRender();
530
+ return;
531
+ }
532
+
533
+ if (data === "S") {
534
+ this.saveOverridesToAgent();
535
+ return;
536
+ }
537
+
538
+ if (data === "W" && this.mode === "chain") {
539
+ this.enterSaveChainName();
540
+ return;
541
+ }
542
+ }
543
+
544
+ private enterEditMode(mode: EditMode): void {
545
+ this.editingStep = this.selectedStep;
546
+ this.editMode = mode;
547
+ let buffer = "";
548
+
549
+ if (mode === "template") {
550
+ const template = this.templates[this.selectedStep] ?? "";
551
+ buffer = template.split("\n")[0] ?? "";
552
+ } else if (mode === "output") {
553
+ const behavior = this.getEffectiveBehavior(this.selectedStep);
554
+ buffer = behavior.output === false ? "" : (behavior.output || "");
555
+ } else if (mode === "reads") {
556
+ const behavior = this.getEffectiveBehavior(this.selectedStep);
557
+ buffer = behavior.reads === false ? "" : (behavior.reads?.join(", ") || "");
558
+ }
559
+
560
+ this.editState = createEditorState(buffer);
561
+ this.tui.requestRender();
562
+ }
563
+
564
+ /** Enter model selector mode */
565
+ private enterModelSelector(): void {
566
+ this.editingStep = this.selectedStep;
567
+ this.editMode = "model";
568
+ this.modelSearchQuery = "";
569
+ this.modelSelectedIndex = 0;
570
+ this.filteredModels = [...this.availableModels];
571
+ const currentModel = splitThinkingSuffix(this.getEffectiveModel(this.selectedStep)).baseModel;
572
+ const currentIndex = this.filteredModels.findIndex((m) => m.fullId === currentModel || m.id === currentModel);
573
+ if (currentIndex >= 0) {
574
+ this.modelSelectedIndex = currentIndex;
575
+ }
576
+
577
+ this.tui.requestRender();
578
+ }
579
+
580
+ /** Filter models based on search query */
581
+ private filterModels(): void {
582
+ const query = this.modelSearchQuery.toLowerCase();
583
+ if (!query) {
584
+ this.filteredModels = [...this.availableModels];
585
+ } else {
586
+ this.filteredModels = this.availableModels.filter((m) =>
587
+ m.fullId.toLowerCase().includes(query) ||
588
+ m.id.toLowerCase().includes(query) ||
589
+ m.provider.toLowerCase().includes(query)
590
+ );
591
+ }
592
+ this.modelSelectedIndex = Math.min(this.modelSelectedIndex, Math.max(0, this.filteredModels.length - 1));
593
+ }
594
+
595
+ private handleModelSelectorInput(data: string): void {
596
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
597
+ this.exitEditMode();
598
+ return;
599
+ }
600
+
601
+ if (matchesKey(data, "return")) {
602
+ const selected = this.filteredModels[this.modelSelectedIndex];
603
+ if (selected) {
604
+ const { thinkingSuffix } = splitThinkingSuffix(this.getEffectiveModel(this.editingStep!));
605
+ this.updateBehavior(this.editingStep!, "model", `${selected.fullId}${thinkingSuffix}`);
606
+ }
607
+ this.exitEditMode();
608
+ return;
609
+ }
610
+
611
+ if (matchesKey(data, "up")) {
612
+ if (this.filteredModels.length > 0) {
613
+ this.modelSelectedIndex = this.modelSelectedIndex === 0
614
+ ? this.filteredModels.length - 1
615
+ : this.modelSelectedIndex - 1;
616
+ }
617
+ this.tui.requestRender();
618
+ return;
619
+ }
620
+
621
+ if (matchesKey(data, "down")) {
622
+ if (this.filteredModels.length > 0) {
623
+ this.modelSelectedIndex = this.modelSelectedIndex === this.filteredModels.length - 1
624
+ ? 0
625
+ : this.modelSelectedIndex + 1;
626
+ }
627
+ this.tui.requestRender();
628
+ return;
629
+ }
630
+
631
+ if (matchesKey(data, "backspace")) {
632
+ if (this.modelSearchQuery.length > 0) {
633
+ this.modelSearchQuery = this.modelSearchQuery.slice(0, -1);
634
+ this.filterModels();
635
+ }
636
+ this.tui.requestRender();
637
+ return;
638
+ }
639
+
640
+ if (data.length === 1 && data.charCodeAt(0) >= 32) {
641
+ this.modelSearchQuery += data;
642
+ this.filterModels();
643
+ this.tui.requestRender();
644
+ return;
645
+ }
646
+ }
647
+
648
+ /** Enter thinking level selector mode */
649
+ private enterThinkingSelector(): void {
650
+ if (!this.getEffectiveBehavior(this.selectedStep).model) {
651
+ this.showSaveMessage("Select a model first", "error");
652
+ return;
653
+ }
654
+ this.editingStep = this.selectedStep;
655
+ this.editMode = "thinking";
656
+
657
+ const currentModel = this.getEffectiveModel(this.selectedStep);
658
+ const colonIdx = currentModel.lastIndexOf(":");
659
+ if (colonIdx !== -1) {
660
+ const suffix = currentModel.substring(colonIdx + 1);
661
+ const levelIdx = THINKING_LEVELS.indexOf(suffix as ThinkingLevel);
662
+ this.thinkingSelectedIndex = levelIdx >= 0 ? levelIdx : 0;
663
+ } else {
664
+ this.thinkingSelectedIndex = 0;
665
+ }
666
+
667
+ this.tui.requestRender();
668
+ }
669
+
670
+ private handleThinkingSelectorInput(data: string): void {
671
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
672
+ this.exitEditMode();
673
+ return;
674
+ }
675
+
676
+ if (matchesKey(data, "return")) {
677
+ const selectedLevel = THINKING_LEVELS[this.thinkingSelectedIndex];
678
+ this.applyThinkingLevel(selectedLevel);
679
+ this.exitEditMode();
680
+ return;
681
+ }
682
+
683
+ if (matchesKey(data, "up")) {
684
+ this.thinkingSelectedIndex = this.thinkingSelectedIndex === 0
685
+ ? THINKING_LEVELS.length - 1
686
+ : this.thinkingSelectedIndex - 1;
687
+ this.tui.requestRender();
688
+ return;
689
+ }
690
+
691
+ if (matchesKey(data, "down")) {
692
+ this.thinkingSelectedIndex = this.thinkingSelectedIndex === THINKING_LEVELS.length - 1
693
+ ? 0
694
+ : this.thinkingSelectedIndex + 1;
695
+ this.tui.requestRender();
696
+ return;
697
+ }
698
+ }
699
+
700
+ /** Apply thinking level to the current step's model */
701
+ private applyThinkingLevel(level: ThinkingLevel): void {
702
+ const stepIndex = this.editingStep!;
703
+ const currentModel = this.getEffectiveBehavior(stepIndex).model;
704
+ if (!currentModel) return;
705
+
706
+ const { baseModel } = splitThinkingSuffix(currentModel);
707
+ const newModel = level === "off" ? baseModel : `${baseModel}:${level}`;
708
+ this.updateBehavior(stepIndex, "model", newModel);
709
+ }
710
+
711
+ private filterSkills(): void {
712
+ const query = this.skillSearchQuery.toLowerCase();
713
+ if (!query) {
714
+ this.filteredSkills = [...this.availableSkills];
715
+ } else {
716
+ this.filteredSkills = this.availableSkills.filter((s) =>
717
+ s.name.toLowerCase().includes(query) ||
718
+ (s.description?.toLowerCase().includes(query) ?? false),
719
+ );
720
+ }
721
+ this.skillCursorIndex = Math.min(this.skillCursorIndex, Math.max(0, this.filteredSkills.length - 1));
722
+ }
723
+
724
+ private handleSkillSelectorInput(data: string): void {
725
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
726
+ this.exitEditMode();
727
+ return;
728
+ }
729
+
730
+ if (matchesKey(data, "return")) {
731
+ const selected = [...this.skillSelectedNames];
732
+ this.updateBehavior(this.editingStep!, "skills", selected);
733
+ this.exitEditMode();
734
+ return;
735
+ }
736
+
737
+ if (data === " ") {
738
+ if (this.filteredSkills.length > 0) {
739
+ const skill = this.filteredSkills[this.skillCursorIndex];
740
+ if (skill) {
741
+ if (this.skillSelectedNames.has(skill.name)) {
742
+ this.skillSelectedNames.delete(skill.name);
743
+ } else {
744
+ this.skillSelectedNames.add(skill.name);
745
+ }
746
+ }
747
+ }
748
+ this.tui.requestRender();
749
+ return;
750
+ }
751
+
752
+ if (matchesKey(data, "up")) {
753
+ if (this.filteredSkills.length > 0) {
754
+ this.skillCursorIndex = this.skillCursorIndex === 0
755
+ ? this.filteredSkills.length - 1
756
+ : this.skillCursorIndex - 1;
757
+ }
758
+ this.tui.requestRender();
759
+ return;
760
+ }
761
+
762
+ if (matchesKey(data, "down")) {
763
+ if (this.filteredSkills.length > 0) {
764
+ this.skillCursorIndex = this.skillCursorIndex === this.filteredSkills.length - 1
765
+ ? 0
766
+ : this.skillCursorIndex + 1;
767
+ }
768
+ this.tui.requestRender();
769
+ return;
770
+ }
771
+
772
+ if (matchesKey(data, "backspace")) {
773
+ if (this.skillSearchQuery.length > 0) {
774
+ this.skillSearchQuery = this.skillSearchQuery.slice(0, -1);
775
+ this.filterSkills();
776
+ }
777
+ this.tui.requestRender();
778
+ return;
779
+ }
780
+
781
+ if (data.length === 1 && data.charCodeAt(0) >= 32) {
782
+ this.skillSearchQuery += data;
783
+ this.filterSkills();
784
+ this.tui.requestRender();
785
+ return;
786
+ }
787
+ }
788
+
789
+ private handleEditInput(data: string): void {
790
+ const textWidth = this.width - 4; // Must match render: innerW - 2 = (width - 2) - 2
791
+ if (matchesKey(data, "shift+up") || matchesKey(data, "pageup")) {
792
+ const { lines: wrapped, starts } = wrapText(this.editState.buffer, textWidth);
793
+ const cursorPos = getCursorDisplayPos(this.editState.cursor, starts);
794
+ const targetLine = Math.max(0, cursorPos.line - this.EDIT_VIEWPORT_HEIGHT);
795
+ const targetCol = Math.min(cursorPos.col, wrapped[targetLine]?.length ?? 0);
796
+ this.editState = { ...this.editState, cursor: starts[targetLine] + targetCol };
797
+ this.tui.requestRender();
798
+ return;
799
+ }
800
+
801
+ if (matchesKey(data, "shift+down") || matchesKey(data, "pagedown")) {
802
+ const { lines: wrapped, starts } = wrapText(this.editState.buffer, textWidth);
803
+ const cursorPos = getCursorDisplayPos(this.editState.cursor, starts);
804
+ const targetLine = Math.min(wrapped.length - 1, cursorPos.line + this.EDIT_VIEWPORT_HEIGHT);
805
+ const targetCol = Math.min(cursorPos.col, wrapped[targetLine]?.length ?? 0);
806
+ this.editState = { ...this.editState, cursor: starts[targetLine] + targetCol };
807
+ this.tui.requestRender();
808
+ return;
809
+ }
810
+
811
+ if (matchesKey(data, "tab")) return;
812
+
813
+ const nextState = handleEditorInput(this.editState, data, textWidth);
814
+ if (nextState) {
815
+ this.editState = nextState;
816
+ this.tui.requestRender();
817
+ return;
818
+ }
819
+
820
+ if (matchesKey(data, "escape")) {
821
+ this.saveEdit();
822
+ this.exitEditMode();
823
+ return;
824
+ }
825
+
826
+ if (matchesKey(data, "ctrl+c")) {
827
+ this.exitEditMode();
828
+ return;
829
+ }
830
+ }
831
+
832
+ private saveEdit(): void {
833
+ const stepIndex = this.editingStep!;
834
+
835
+ if (this.editMode === "template") {
836
+ // For template, preserve other lines if they existed
837
+ const original = this.templates[stepIndex] ?? "";
838
+ const originalLines = original.split("\n");
839
+ originalLines[0] = this.editState.buffer;
840
+ this.templates[stepIndex] = originalLines.join("\n");
841
+ } else if (this.editMode === "output") {
842
+ // Capture OLD output before updating (for downstream propagation)
843
+ const oldBehavior = this.getEffectiveBehavior(stepIndex);
844
+ const oldOutput = typeof oldBehavior.output === "string" ? oldBehavior.output : null;
845
+
846
+ // Empty string or whitespace means disable output
847
+ const trimmed = this.editState.buffer.trim();
848
+ const newOutput = trimmed === "" ? false : trimmed;
849
+ this.updateBehavior(stepIndex, "output", newOutput);
850
+
851
+ // Propagate output filename change to downstream steps' reads
852
+ if (oldOutput && typeof newOutput === "string" && oldOutput !== newOutput) {
853
+ this.propagateOutputChange(stepIndex, oldOutput, newOutput);
854
+ }
855
+ } else if (this.editMode === "reads") {
856
+ // Parse comma-separated list, empty means disable reads
857
+ const trimmed = this.editState.buffer.trim();
858
+ if (trimmed === "") {
859
+ this.updateBehavior(stepIndex, "reads", false);
860
+ } else {
861
+ const files = trimmed.split(",").map(f => f.trim()).filter(f => f !== "");
862
+ this.updateBehavior(stepIndex, "reads", files.length > 0 ? files : false);
863
+ }
864
+ }
865
+ }
866
+
867
+ /**
868
+ * When a step's output filename changes, update downstream steps that read from it.
869
+ * This maintains the chain dependency automatically.
870
+ */
871
+ private propagateOutputChange(changedStepIndex: number, oldOutput: string, newOutput: string): void {
872
+ // Check all downstream steps (steps that come after the changed step)
873
+ for (let i = changedStepIndex + 1; i < this.agentConfigs.length; i++) {
874
+ const behavior = this.getEffectiveBehavior(i);
875
+
876
+ // Skip if reads is disabled or empty
877
+ if (behavior.reads === false || !behavior.reads || behavior.reads.length === 0) {
878
+ continue;
879
+ }
880
+
881
+ // Check if this step reads the old output file
882
+ const readsArray = behavior.reads;
883
+ const oldIndex = readsArray.indexOf(oldOutput);
884
+
885
+ if (oldIndex !== -1) {
886
+ // Replace old filename with new filename in reads
887
+ const newReads = [...readsArray];
888
+ newReads[oldIndex] = newOutput;
889
+ this.updateBehavior(i, "reads", newReads);
890
+ }
891
+ }
892
+ }
893
+
894
+ private renderSaveChainName(): string[] {
895
+ const lines: string[] = [];
896
+ const innerW = this.width - 2;
897
+ const boxInnerWidth = Math.max(10, innerW - 4);
898
+ lines.push(this.renderHeader(" Save Chain "));
899
+ lines.push(this.row(""));
900
+ lines.push(this.row(` ${this.theme.fg("dim", "Name:")}`));
901
+ const top = `┌${"─".repeat(boxInnerWidth)}┐`;
902
+ const bottom = `└${"─".repeat(boxInnerWidth)}┘`;
903
+ lines.push(this.row(` ${top}`));
904
+ const editorState = { ...this.saveChainNameState };
905
+ const wrapped = wrapText(editorState.buffer, boxInnerWidth);
906
+ const cursorPos = getCursorDisplayPos(editorState.cursor, wrapped.starts);
907
+ editorState.viewportOffset = ensureCursorVisible(cursorPos.line, 1, editorState.viewportOffset);
908
+ const editorLine = renderEditor(editorState, boxInnerWidth, 1)[0] ?? "";
909
+ lines.push(this.row(` │${this.pad(editorLine, boxInnerWidth)}│`));
910
+ lines.push(this.row(` ${bottom}`));
911
+ lines.push(this.row(""));
912
+ lines.push(this.renderFooter(" [Enter] Save • [Esc] Cancel "));
913
+ return lines;
914
+ }
915
+
916
+ render(_width: number): string[] {
917
+ if (this.savingChain) {
918
+ return this.renderSaveChainName();
919
+ }
920
+ if (this.editingStep !== null) {
921
+ if (this.editMode === "model") {
922
+ return this.renderModelSelector();
923
+ }
924
+ if (this.editMode === "thinking") {
925
+ return this.renderThinkingSelector();
926
+ }
927
+ if (this.editMode === "skills") {
928
+ return this.renderSkillSelector();
929
+ }
930
+ return this.renderFullEditMode();
931
+ }
932
+ // Mode-based navigation rendering
933
+ switch (this.mode) {
934
+ case 'single': return this.renderSingleMode();
935
+ case 'parallel': return this.renderParallelMode();
936
+ case 'chain': return this.renderChainMode();
937
+ }
938
+ }
939
+
940
+ /** Render the model selector view */
941
+ private renderModelSelector(): string[] {
942
+ const th = this.theme;
943
+ const lines: string[] = [];
944
+
945
+ // Header (mode-aware terminology)
946
+ const agentName = this.agentConfigs[this.editingStep!]?.name ?? "unknown";
947
+ const stepLabel = this.mode === 'single'
948
+ ? agentName
949
+ : this.mode === 'parallel'
950
+ ? `Task ${this.editingStep! + 1}: ${agentName}`
951
+ : `Step ${this.editingStep! + 1}: ${agentName}`;
952
+ const headerText = ` Select Model (${stepLabel}) `;
953
+ lines.push(this.renderHeader(headerText));
954
+ lines.push(this.row(""));
955
+
956
+ const searchPrefix = th.fg("dim", "Search: ");
957
+ const cursor = "\x1b[7m \x1b[27m"; // Reverse video space for cursor
958
+ const searchDisplay = this.modelSearchQuery + cursor;
959
+ lines.push(this.row(` ${searchPrefix}${searchDisplay}`));
960
+ lines.push(this.row(""));
961
+
962
+ const currentModel = this.getEffectiveModel(this.editingStep!);
963
+ const currentModelBase = splitThinkingSuffix(currentModel).baseModel;
964
+ const currentLabel = th.fg("dim", "Current: ");
965
+ lines.push(this.row(` ${currentLabel}${th.fg("warning", currentModel)}`));
966
+ lines.push(this.row(""));
967
+
968
+ if (this.filteredModels.length === 0) {
969
+ lines.push(this.row(` ${th.fg("dim", "No matching models")}`));
970
+ } else {
971
+ const maxVisible = this.MODEL_SELECTOR_HEIGHT;
972
+ let startIdx = 0;
973
+
974
+ if (this.filteredModels.length > maxVisible) {
975
+ startIdx = Math.max(0, this.modelSelectedIndex - Math.floor(maxVisible / 2));
976
+ startIdx = Math.min(startIdx, this.filteredModels.length - maxVisible);
977
+ }
978
+
979
+ const endIdx = Math.min(startIdx + maxVisible, this.filteredModels.length);
980
+
981
+ if (startIdx > 0) {
982
+ lines.push(this.row(` ${th.fg("dim", ` ↑ ${startIdx} more`)}`));
983
+ }
984
+
985
+ for (let i = startIdx; i < endIdx; i++) {
986
+ const model = this.filteredModels[i]!;
987
+ const isSelected = i === this.modelSelectedIndex;
988
+ const isCurrent = model.fullId === currentModelBase || model.id === currentModelBase;
989
+ const prefix = isSelected ? th.fg("accent", "→ ") : " ";
990
+ const modelText = isSelected ? th.fg("accent", model.id) : model.id;
991
+ const providerBadge = th.fg("dim", ` [${model.provider}]`);
992
+ const currentBadge = isCurrent ? th.fg("success", " current") : "";
993
+
994
+ lines.push(this.row(` ${prefix}${modelText}${providerBadge}${currentBadge}`));
995
+ }
996
+
997
+ const remaining = this.filteredModels.length - endIdx;
998
+ if (remaining > 0) {
999
+ lines.push(this.row(` ${th.fg("dim", ` ↓ ${remaining} more`)}`));
1000
+ }
1001
+ }
1002
+
1003
+ const contentLines = lines.length;
1004
+ const targetHeight = 18;
1005
+ for (let i = contentLines; i < targetHeight; i++) {
1006
+ lines.push(this.row(""));
1007
+ }
1008
+
1009
+ const footerText = " [Enter] Select • [Esc] Cancel • Type to search ";
1010
+ lines.push(this.renderFooter(footerText));
1011
+
1012
+ return lines;
1013
+ }
1014
+
1015
+ /** Render the thinking level selector view */
1016
+ private renderThinkingSelector(): string[] {
1017
+ const th = this.theme;
1018
+ const lines: string[] = [];
1019
+
1020
+ const agentName = this.agentConfigs[this.editingStep!]?.name ?? "unknown";
1021
+ const stepLabel = this.mode === 'single'
1022
+ ? agentName
1023
+ : this.mode === 'parallel'
1024
+ ? `Task ${this.editingStep! + 1}: ${agentName}`
1025
+ : `Step ${this.editingStep! + 1}: ${agentName}`;
1026
+ const headerText = ` Thinking Level (${stepLabel}) `;
1027
+ lines.push(this.renderHeader(headerText));
1028
+ lines.push(this.row(""));
1029
+
1030
+ const currentModel = this.getEffectiveModel(this.editingStep!);
1031
+ const currentLabel = th.fg("dim", "Model: ");
1032
+ lines.push(this.row(` ${currentLabel}${th.fg("accent", currentModel)}`));
1033
+ lines.push(this.row(""));
1034
+
1035
+ lines.push(this.row(` ${th.fg("dim", "Select thinking level (extended thinking budget):")}`));
1036
+ lines.push(this.row(""));
1037
+
1038
+ const levelDescriptions: Record<ThinkingLevel, string> = {
1039
+ "off": "No extended thinking",
1040
+ "minimal": "Brief reasoning",
1041
+ "low": "Light reasoning",
1042
+ "medium": "Moderate reasoning",
1043
+ "high": "Deep reasoning",
1044
+ "xhigh": "Maximum reasoning (ultrathink)",
1045
+ };
1046
+
1047
+ for (let i = 0; i < THINKING_LEVELS.length; i++) {
1048
+ const level = THINKING_LEVELS[i];
1049
+ const isSelected = i === this.thinkingSelectedIndex;
1050
+ const prefix = isSelected ? th.fg("accent", "→ ") : " ";
1051
+ const levelText = isSelected ? th.fg("accent", level) : level;
1052
+ const desc = th.fg("dim", ` - ${levelDescriptions[level]}`);
1053
+ lines.push(this.row(` ${prefix}${levelText}${desc}`));
1054
+ }
1055
+
1056
+ const contentLines = lines.length;
1057
+ const targetHeight = 16;
1058
+ for (let i = contentLines; i < targetHeight; i++) {
1059
+ lines.push(this.row(""));
1060
+ }
1061
+
1062
+ const footerText = " [Enter] Select • [Esc] Cancel • ↑↓ Navigate ";
1063
+ lines.push(this.renderFooter(footerText));
1064
+
1065
+ return lines;
1066
+ }
1067
+
1068
+ private renderSkillSelector(): string[] {
1069
+ const innerW = this.width - 2;
1070
+ const th = this.theme;
1071
+ const lines: string[] = [];
1072
+
1073
+ const agentName = this.agentConfigs[this.editingStep!]?.name ?? "unknown";
1074
+ const stepLabel = this.mode === 'single'
1075
+ ? agentName
1076
+ : this.mode === 'parallel'
1077
+ ? `Task ${this.editingStep! + 1}: ${agentName}`
1078
+ : `Step ${this.editingStep! + 1}: ${agentName}`;
1079
+ lines.push(this.renderHeader(` Select Skills (${stepLabel}) `));
1080
+ lines.push(this.row(""));
1081
+
1082
+ const cursor = "\x1b[7m \x1b[27m";
1083
+ lines.push(this.row(` ${th.fg("dim", "Search: ")}${this.skillSearchQuery}${cursor}`));
1084
+ lines.push(this.row(""));
1085
+
1086
+ const selected = [...this.skillSelectedNames].join(", ") || th.fg("dim", "(none)");
1087
+ lines.push(this.row(` ${th.fg("dim", "Selected: ")}${truncateToWidth(selected, innerW - 12)}`));
1088
+ lines.push(this.row(""));
1089
+
1090
+ const selectorHeight = 10;
1091
+ if (this.filteredSkills.length === 0) {
1092
+ lines.push(this.row(` ${th.fg("dim", "No matching skills")}`));
1093
+ } else {
1094
+ let startIdx = 0;
1095
+ if (this.filteredSkills.length > selectorHeight) {
1096
+ startIdx = Math.max(0, this.skillCursorIndex - Math.floor(selectorHeight / 2));
1097
+ startIdx = Math.min(startIdx, this.filteredSkills.length - selectorHeight);
1098
+ }
1099
+ const endIdx = Math.min(startIdx + selectorHeight, this.filteredSkills.length);
1100
+
1101
+ if (startIdx > 0) {
1102
+ lines.push(this.row(` ${th.fg("dim", ` ↑ ${startIdx} more`)}`));
1103
+ }
1104
+
1105
+ for (let i = startIdx; i < endIdx; i++) {
1106
+ const skill = this.filteredSkills[i]!;
1107
+ const isCursor = i === this.skillCursorIndex;
1108
+ const isSelected = this.skillSelectedNames.has(skill.name);
1109
+
1110
+ const prefix = isCursor ? th.fg("accent", "→ ") : " ";
1111
+ const checkbox = isSelected ? th.fg("success", "[x]") : "[ ]";
1112
+ const nameText = isCursor ? th.fg("accent", skill.name) : skill.name;
1113
+ const sourceBadge = th.fg("dim", ` [${skill.source}]`);
1114
+ const desc = skill.description
1115
+ ? th.fg("dim", ` - ${truncateToWidth(skill.description, 25)}`)
1116
+ : "";
1117
+
1118
+ lines.push(this.row(` ${prefix}${checkbox} ${nameText}${sourceBadge}${desc}`));
1119
+ }
1120
+
1121
+ const remaining = this.filteredSkills.length - endIdx;
1122
+ if (remaining > 0) {
1123
+ lines.push(this.row(` ${th.fg("dim", ` ↓ ${remaining} more`)}`));
1124
+ }
1125
+ }
1126
+
1127
+ const targetHeight = 18;
1128
+ for (let i = lines.length; i < targetHeight; i++) {
1129
+ lines.push(this.row(""));
1130
+ }
1131
+
1132
+ lines.push(this.renderFooter(" [Enter] Confirm • [Space] Toggle • [Esc] Cancel "));
1133
+ return lines;
1134
+ }
1135
+
1136
+ private getFooterText(): string {
1137
+ const bgLabel = this.runInBackground ? '[b]g:ON' : '[b]g';
1138
+ switch (this.mode) {
1139
+ case 'single':
1140
+ return ` [Enter] Run • [Esc] Cancel • e m t w s ${bgLabel} S `;
1141
+ case 'parallel':
1142
+ return ` [Enter] Run • [Esc] Cancel • e m t s ${bgLabel} S • ↑↓ Nav `;
1143
+ case 'chain':
1144
+ return ` [Enter] Run • [Esc] Cancel • e m t w r p s ${bgLabel} S W • ↑↓ Nav `;
1145
+ }
1146
+ }
1147
+
1148
+ private appendSaveMessage(lines: string[]): void {
1149
+ if (!this.saveMessage) return;
1150
+ const color = this.saveMessage.type === "error" ? "error" : "success";
1151
+ lines.push(this.row(` ${this.theme.fg(color, this.saveMessage.text)}`));
1152
+ }
1153
+
1154
+ private renderSingleMode(): string[] {
1155
+ const innerW = this.width - 2;
1156
+ const th = this.theme;
1157
+ const lines: string[] = [];
1158
+
1159
+ const agentName = this.agentConfigs[0]?.name ?? "unknown";
1160
+ const maxHeaderLen = innerW - 4;
1161
+ const headerText = ` Agent: ${truncateToWidth(agentName, maxHeaderLen - 9)} `;
1162
+ lines.push(this.renderHeader(headerText));
1163
+ lines.push(this.row(""));
1164
+
1165
+ const config = this.agentConfigs[0]!;
1166
+ const behavior = this.getEffectiveBehavior(0);
1167
+
1168
+ const stepLabel = config.name;
1169
+ lines.push(this.row(` ${th.fg("accent", "▶ " + stepLabel)}`));
1170
+
1171
+ const template = (this.templates[0] ?? "").split("\n")[0] ?? "";
1172
+ const taskLabel = th.fg("dim", "task: ");
1173
+ lines.push(this.row(` ${taskLabel}${truncateToWidth(template, innerW - 12)}`));
1174
+
1175
+ const effectiveModel = this.getEffectiveModel(0);
1176
+ const override = this.behaviorOverrides.get(0);
1177
+ const isOverridden = override?.model !== undefined;
1178
+ const modelValue = isOverridden
1179
+ ? th.fg("warning", effectiveModel) + th.fg("dim", " ✎")
1180
+ : effectiveModel;
1181
+ const modelLabel = th.fg("dim", "model: ");
1182
+ lines.push(this.row(` ${modelLabel}${truncateToWidth(modelValue, innerW - 13)}`));
1183
+
1184
+ const writesValue = behavior.output === false
1185
+ ? th.fg("dim", "(disabled)")
1186
+ : (behavior.output || th.fg("dim", "(none)"));
1187
+ const writesLabel = th.fg("dim", "writes: ");
1188
+ lines.push(this.row(` ${writesLabel}${truncateToWidth(writesValue, innerW - 14)}`));
1189
+
1190
+ const skillsValue = behavior.skills === false
1191
+ ? th.fg("dim", "(disabled)")
1192
+ : (behavior.skills?.length ? behavior.skills.join(", ") : th.fg("dim", "(none)"));
1193
+ const skillsLabel = th.fg("dim", "skills: ");
1194
+ lines.push(this.row(` ${skillsLabel}${truncateToWidth(skillsValue, innerW - 14)}`));
1195
+
1196
+ lines.push(this.row(""));
1197
+
1198
+ this.appendSaveMessage(lines);
1199
+ lines.push(this.renderFooter(this.getFooterText()));
1200
+
1201
+ return lines;
1202
+ }
1203
+
1204
+ private renderParallelMode(): string[] {
1205
+ const innerW = this.width - 2;
1206
+ const th = this.theme;
1207
+ const lines: string[] = [];
1208
+
1209
+ const headerText = ` Parallel Tasks (${this.agentConfigs.length}) `;
1210
+ lines.push(this.renderHeader(headerText));
1211
+ lines.push(this.row(""));
1212
+
1213
+ for (let i = 0; i < this.agentConfigs.length; i++) {
1214
+ const config = this.agentConfigs[i]!;
1215
+ const isSelected = i === this.selectedStep;
1216
+
1217
+ const color = isSelected ? "accent" : "dim";
1218
+ const prefix = isSelected ? "▶ " : " ";
1219
+ const taskPrefix = `Task ${i + 1}: `;
1220
+ const maxNameLen = innerW - 4 - prefix.length - taskPrefix.length;
1221
+ const agentName = config.name.length > maxNameLen
1222
+ ? config.name.slice(0, maxNameLen - 1) + "…"
1223
+ : config.name;
1224
+ const taskLabel = `${taskPrefix}${agentName}`;
1225
+ lines.push(this.row(` ${th.fg(color, prefix + taskLabel)}`));
1226
+
1227
+ const template = (this.templates[i] ?? "").split("\n")[0] ?? "";
1228
+ const taskTextLabel = th.fg("dim", "task: ");
1229
+ lines.push(this.row(` ${taskTextLabel}${truncateToWidth(template, innerW - 12)}`));
1230
+
1231
+ const effectiveModel = this.getEffectiveModel(i);
1232
+ const override = this.behaviorOverrides.get(i);
1233
+ const isOverridden = override?.model !== undefined;
1234
+ const modelValue = isOverridden
1235
+ ? th.fg("warning", effectiveModel) + th.fg("dim", " ✎")
1236
+ : effectiveModel;
1237
+ const modelLabel = th.fg("dim", "model: ");
1238
+ lines.push(this.row(` ${modelLabel}${truncateToWidth(modelValue, innerW - 13)}`));
1239
+
1240
+ const behavior = this.getEffectiveBehavior(i);
1241
+ const skillsValue = behavior.skills === false
1242
+ ? th.fg("dim", "(disabled)")
1243
+ : (behavior.skills?.length ? behavior.skills.join(", ") : th.fg("dim", "(none)"));
1244
+ const skillsLabel = th.fg("dim", "skills: ");
1245
+ lines.push(this.row(` ${skillsLabel}${truncateToWidth(skillsValue, innerW - 14)}`));
1246
+
1247
+ lines.push(this.row(""));
1248
+ }
1249
+
1250
+ this.appendSaveMessage(lines);
1251
+ lines.push(this.renderFooter(this.getFooterText()));
1252
+
1253
+ return lines;
1254
+ }
1255
+
1256
+ private renderChainMode(): string[] {
1257
+ const innerW = this.width - 2;
1258
+ const th = this.theme;
1259
+ const lines: string[] = [];
1260
+
1261
+ const chainLabel = this.agentConfigs.map((c) => c.name).join(" → ");
1262
+ const maxHeaderLen = innerW - 4;
1263
+ const headerText = ` Chain: ${truncateToWidth(chainLabel, maxHeaderLen - 9)} `;
1264
+ lines.push(this.renderHeader(headerText));
1265
+
1266
+ lines.push(this.row(""));
1267
+
1268
+ const taskPreview = truncateToWidth(this.originalTask, innerW - 16);
1269
+ lines.push(this.row(` Original Task: ${taskPreview}`));
1270
+ const chainDirPreview = truncateToWidth(this.chainDir ?? "", innerW - 12);
1271
+ lines.push(this.row(` Chain Dir: ${th.fg("dim", chainDirPreview)}`));
1272
+
1273
+ const progressEnabled = this.agentConfigs.some((_, i) => this.getEffectiveBehavior(i).progress);
1274
+ const progressValue = progressEnabled ? th.fg("success", "enabled") : th.fg("dim", "disabled");
1275
+ lines.push(this.row(` Progress: ${progressValue} ${th.fg("dim", "(press [p] to toggle)")}`));
1276
+ lines.push(this.row(""));
1277
+
1278
+ for (let i = 0; i < this.agentConfigs.length; i++) {
1279
+ const config = this.agentConfigs[i]!;
1280
+ const isSelected = i === this.selectedStep;
1281
+ const behavior = this.getEffectiveBehavior(i);
1282
+
1283
+ const color = isSelected ? "accent" : "dim";
1284
+ const prefix = isSelected ? "▶ " : " ";
1285
+ const stepPrefix = `Step ${i + 1}: `;
1286
+ const maxNameLen = innerW - 4 - prefix.length - stepPrefix.length;
1287
+ const agentName = config.name.length > maxNameLen
1288
+ ? config.name.slice(0, maxNameLen - 1) + "…"
1289
+ : config.name;
1290
+ const stepLabel = `${stepPrefix}${agentName}`;
1291
+ lines.push(
1292
+ this.row(` ${th.fg(color, prefix + stepLabel)}`),
1293
+ );
1294
+
1295
+ const template = (this.templates[i] ?? "").split("\n")[0] ?? "";
1296
+ const highlighted = template
1297
+ .replace(/\{task\}/g, th.fg("success", "{task}"))
1298
+ .replace(/\{previous\}/g, th.fg("warning", "{previous}"))
1299
+ .replace(/\{chain_dir\}/g, th.fg("accent", "{chain_dir}"));
1300
+
1301
+ const templateLabel = th.fg("dim", "task: ");
1302
+ lines.push(this.row(` ${templateLabel}${truncateToWidth(highlighted, innerW - 12)}`));
1303
+
1304
+ const effectiveModel = this.getEffectiveModel(i);
1305
+ const override = this.behaviorOverrides.get(i);
1306
+ const isOverridden = override?.model !== undefined;
1307
+ const modelValue = isOverridden
1308
+ ? th.fg("warning", effectiveModel) + th.fg("dim", " ✎")
1309
+ : effectiveModel;
1310
+ const modelLabel = th.fg("dim", "model: ");
1311
+ lines.push(this.row(` ${modelLabel}${truncateToWidth(modelValue, innerW - 13)}`));
1312
+
1313
+ const writesValue = behavior.output === false
1314
+ ? th.fg("dim", "(disabled)")
1315
+ : (behavior.output || th.fg("dim", "(none)"));
1316
+ const writesLabel = th.fg("dim", "writes: ");
1317
+ lines.push(this.row(` ${writesLabel}${truncateToWidth(writesValue, innerW - 14)}`));
1318
+
1319
+ const readsValue = behavior.reads === false
1320
+ ? th.fg("dim", "(disabled)")
1321
+ : (behavior.reads && behavior.reads.length > 0
1322
+ ? behavior.reads.join(", ")
1323
+ : th.fg("dim", "(none)"));
1324
+ const readsLabel = th.fg("dim", "reads: ");
1325
+ lines.push(this.row(` ${readsLabel}${truncateToWidth(readsValue, innerW - 13)}`));
1326
+
1327
+ const skillsValue = behavior.skills === false
1328
+ ? th.fg("dim", "(disabled)")
1329
+ : (behavior.skills?.length ? behavior.skills.join(", ") : th.fg("dim", "(none)"));
1330
+ const skillsLabel = th.fg("dim", "skills: ");
1331
+ lines.push(this.row(` ${skillsLabel}${truncateToWidth(skillsValue, innerW - 14)}`));
1332
+
1333
+ if (progressEnabled) {
1334
+ const isFirstStep = i === 0;
1335
+ const progressAction = isFirstStep
1336
+ ? th.fg("success", "writes progress.md")
1337
+ : th.fg("accent", "reads progress.md");
1338
+ const progressLabel = th.fg("dim", "progress: ");
1339
+ lines.push(this.row(` ${progressLabel}${progressAction}`));
1340
+ }
1341
+
1342
+ if (i < this.agentConfigs.length - 1) {
1343
+ const nextStepUsePrevious = (this.templates[i + 1] ?? "").includes("{previous}");
1344
+ if (nextStepUsePrevious) {
1345
+ const indicator = th.fg("dim", " ↳ response → ") + th.fg("warning", "{previous}");
1346
+ lines.push(this.row(indicator));
1347
+ }
1348
+ }
1349
+
1350
+ lines.push(this.row(""));
1351
+ }
1352
+
1353
+ this.appendSaveMessage(lines);
1354
+ lines.push(this.renderFooter(this.getFooterText()));
1355
+
1356
+ return lines;
1357
+ }
1358
+
1359
+ invalidate(): void {}
1360
+ dispose(): void {
1361
+ if (this.saveMessageTimer) clearTimeout(this.saveMessageTimer);
1362
+ this.saveMessageTimer = null;
1363
+ }
1364
+ }