forked from nicobailon/pi-subagents
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchain-clarify.ts
More file actions
1451 lines (1254 loc) · 50.2 KB
/
chain-clarify.ts
File metadata and controls
1451 lines (1254 loc) · 50.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Chain Clarification TUI Component
*
* Shows templates and resolved behaviors for each step in a chain.
* Supports editing templates, output paths, reads lists, and progress toggle.
*/
import type { Theme } from "@mariozechner/pi-coding-agent";
import type { Component, TUI } from "@mariozechner/pi-tui";
import { matchesKey, visibleWidth, truncateToWidth } from "@mariozechner/pi-tui";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import type { AgentConfig, ChainConfig, ChainStepConfig } from "./agents.js";
import type { ResolvedStepBehavior } from "./settings.js";
import type { TextEditorState } from "./text-editor.js";
import { createEditorState, ensureCursorVisible, getCursorDisplayPos, handleEditorInput, renderEditor, wrapText } from "./text-editor.js";
import { updateFrontmatterField } from "./agent-serializer.js";
import { serializeChain } from "./chain-serializer.js";
/** Clarify TUI mode */
export type ClarifyMode = 'single' | 'parallel' | 'chain';
/** Model info for display */
export interface ModelInfo {
provider: string;
id: string;
fullId: string; // "provider/id"
}
/** Modified behavior overrides from TUI editing */
export interface BehaviorOverride {
output?: string | false;
reads?: string[] | false;
progress?: boolean;
model?: string; // Override agent's default model (format: "provider/id")
skills?: string[] | false;
}
export interface ChainClarifyResult {
confirmed: boolean;
templates: string[];
/** User-modified behavior overrides per step (undefined = no changes) */
behaviorOverrides: (BehaviorOverride | undefined)[];
/** User requested background/async execution */
runInBackground?: boolean;
}
type EditMode = "template" | "output" | "reads" | "model" | "thinking" | "skills";
/** Valid thinking levels */
const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"] as const;
type ThinkingLevel = typeof THINKING_LEVELS[number];
/**
* TUI component for chain clarification.
* Factory signature matches ctx.ui.custom: (tui, theme, kb, done) => Component
*/
export class ChainClarifyComponent implements Component {
readonly width = 84;
private selectedStep = 0;
private editingStep: number | null = null;
private editMode: EditMode = "template";
private editState: TextEditorState = createEditorState();
/** Lines visible in full edit mode */
private readonly EDIT_VIEWPORT_HEIGHT = 12;
/** Track user modifications to behaviors (sparse - only stores changes) */
private behaviorOverrides: Map<number, BehaviorOverride> = new Map();
/** Model selector state */
private modelSearchQuery: string = "";
private modelSelectedIndex: number = 0;
private filteredModels: ModelInfo[] = [];
/** Max models visible in selector */
private readonly MODEL_SELECTOR_HEIGHT = 10;
/** Thinking level selector state */
private thinkingSelectedIndex: number = 0;
/** Skill selector state */
private skillSearchQuery: string = "";
private skillSelectedNames: Set<string> = new Set();
private skillCursorIndex: number = 0;
private filteredSkills: Array<{ name: string; source: string; description?: string }> = [];
private saveMessage: { text: string; type: "info" | "error" } | null = null;
private saveMessageTimer: ReturnType<typeof setTimeout> | null = null;
private saveChainNameState: TextEditorState = createEditorState();
private savingChain = false;
/** Run in background (async) mode */
private runInBackground = false;
constructor(
private tui: TUI,
private theme: Theme,
private agentConfigs: AgentConfig[],
private templates: string[],
private originalTask: string,
private chainDir: string | undefined, // undefined for single/parallel modes
private resolvedBehaviors: ResolvedStepBehavior[],
private availableModels: ModelInfo[],
private availableSkills: Array<{ name: string; source: string; description?: string }>,
private done: (result: ChainClarifyResult) => void,
private mode: ClarifyMode = 'chain', // Mode: 'single', 'parallel', or 'chain'
) {
// Initialize filtered models
this.filteredModels = [...availableModels];
this.filteredSkills = [...availableSkills];
}
// ─────────────────────────────────────────────────────────────────────────────
// Helper methods for rendering
// ─────────────────────────────────────────────────────────────────────────────
/** Pad string to specified visible width */
private pad(s: string, len: number): string {
const vis = visibleWidth(s);
return s + " ".repeat(Math.max(0, len - vis));
}
/** Create a row with border characters */
private row(content: string): string {
const innerW = this.width - 2;
return this.theme.fg("border", "│") + this.pad(content, innerW) + this.theme.fg("border", "│");
}
/** Render centered header line with border */
private renderHeader(text: string): string {
const innerW = this.width - 2;
const padLen = Math.max(0, innerW - visibleWidth(text));
const padLeft = Math.floor(padLen / 2);
const padRight = padLen - padLeft;
return (
this.theme.fg("border", "╭" + "─".repeat(padLeft)) +
this.theme.fg("accent", text) +
this.theme.fg("border", "─".repeat(padRight) + "╮")
);
}
/** Render centered footer line with border */
private renderFooter(text: string): string {
const innerW = this.width - 2;
const padLen = Math.max(0, innerW - visibleWidth(text));
const padLeft = Math.floor(padLen / 2);
const padRight = padLen - padLeft;
return (
this.theme.fg("border", "╰" + "─".repeat(padLeft)) +
this.theme.fg("dim", text) +
this.theme.fg("border", "─".repeat(padRight) + "╯")
);
}
/** Exit edit mode and reset state */
private exitEditMode(): void {
this.editingStep = null;
this.editState = createEditorState();
this.tui.requestRender();
}
// ─────────────────────────────────────────────────────────────────────────────
// Full edit mode methods
// ─────────────────────────────────────────────────────────────────────────────
/** Render the full-edit takeover view */
private renderFullEditMode(): string[] {
const innerW = this.width - 2;
const textWidth = innerW - 2; // 1 char padding on each side
const lines: string[] = [];
const { lines: wrapped, starts } = wrapText(this.editState.buffer, textWidth);
const cursorPos = getCursorDisplayPos(this.editState.cursor, starts);
this.editState = {
...this.editState,
viewportOffset: ensureCursorVisible(
cursorPos.line,
this.EDIT_VIEWPORT_HEIGHT,
this.editState.viewportOffset,
),
};
// Header (truncate agent name to prevent overflow)
const fieldName = this.editMode === "template" ? "task" : this.editMode;
const rawAgentName = this.agentConfigs[this.editingStep!]?.name ?? "unknown";
const maxAgentLen = innerW - 30; // Reserve space for " Editing X (Step/Task N: ) "
const agentName = rawAgentName.length > maxAgentLen
? rawAgentName.slice(0, maxAgentLen - 1) + "…"
: rawAgentName;
// Use mode-appropriate terminology
const stepLabel = this.mode === 'single'
? agentName
: this.mode === 'parallel'
? `Task ${this.editingStep! + 1}: ${agentName}`
: `Step ${this.editingStep! + 1}: ${agentName}`;
const headerText = ` Editing ${fieldName} (${stepLabel}) `;
lines.push(this.renderHeader(headerText));
lines.push(this.row(""));
const editorLines = renderEditor(this.editState, textWidth, this.EDIT_VIEWPORT_HEIGHT);
for (const line of editorLines) {
lines.push(this.row(` ${line}`));
}
// Scroll indicators
const linesBelow = wrapped.length - this.editState.viewportOffset - this.EDIT_VIEWPORT_HEIGHT;
const hasMore = linesBelow > 0;
const hasLess = this.editState.viewportOffset > 0;
let scrollInfo = "";
if (hasLess) scrollInfo += "↑";
if (hasMore) scrollInfo += `↓ ${linesBelow}+`;
lines.push(this.row(""));
// Footer with scroll indicators if applicable
const footerText = scrollInfo
? ` [Esc] Done • [Ctrl+C] Discard • ${scrollInfo} `
: " [Esc] Done • [Ctrl+C] Discard ";
lines.push(this.renderFooter(footerText));
return lines;
}
// ─────────────────────────────────────────────────────────────────────────────
// Behavior helpers
// ─────────────────────────────────────────────────────────────────────────────
/** Get effective behavior for a step (with user overrides applied) */
private getEffectiveBehavior(stepIndex: number): ResolvedStepBehavior {
const base = this.resolvedBehaviors[stepIndex]!;
const override = this.behaviorOverrides.get(stepIndex);
if (!override) return base;
return {
output: override.output !== undefined ? override.output : base.output,
reads: override.reads !== undefined ? override.reads : base.reads,
progress: override.progress !== undefined ? override.progress : base.progress,
skills: override.skills !== undefined ? override.skills : base.skills,
model: override.model !== undefined ? override.model : base.model,
};
}
/** Get the effective model for a step (override or agent default) */
private getEffectiveModel(stepIndex: number): string {
const override = this.behaviorOverrides.get(stepIndex);
if (override?.model) return override.model; // Override is already in provider/model format
const baseModel = this.resolvedBehaviors[stepIndex]?.model;
if (baseModel) return this.resolveModelFullId(baseModel);
return "default";
}
/** Resolve a model name to its full provider/model format */
private resolveModelFullId(modelName: string): string {
// If already in provider/model format, return as-is
if (modelName.includes("/")) return modelName;
// Handle thinking level suffixes (e.g., "claude-sonnet-4-5:high")
// Strip the suffix for lookup, then add it back
const colonIdx = modelName.lastIndexOf(":");
const baseModel = colonIdx !== -1 ? modelName.substring(0, colonIdx) : modelName;
const thinkingSuffix = colonIdx !== -1 ? modelName.substring(colonIdx) : "";
// Look up base model in available models to find provider
const match = this.availableModels.find(m => m.id === baseModel);
if (match) {
return thinkingSuffix ? `${match.fullId}${thinkingSuffix}` : match.fullId;
}
// Fallback to just the model name if not found
return modelName;
}
/** Update a behavior override for a step */
private updateBehavior(stepIndex: number, field: keyof BehaviorOverride, value: string | boolean | string[] | false): void {
const existing = this.behaviorOverrides.get(stepIndex) ?? {};
this.behaviorOverrides.set(stepIndex, { ...existing, [field]: value });
}
private buildChainConfig(name: string): ChainConfig {
const steps: ChainStepConfig[] = [];
for (let i = 0; i < this.agentConfigs.length; i++) {
const agent = this.agentConfigs[i]!;
const behavior = this.getEffectiveBehavior(i);
const override = this.behaviorOverrides.get(i);
const template = this.templates[i] ?? "";
const step: ChainStepConfig = { agent: agent.name, task: template };
if (override?.output !== undefined) step.output = behavior.output;
if (override?.reads !== undefined) step.reads = behavior.reads;
if (override?.model !== undefined) step.model = behavior.model;
if (override?.skills !== undefined) step.skills = behavior.skills;
if (override?.progress !== undefined) step.progress = behavior.progress;
steps.push(step);
}
return {
name,
description: `Chain: ${steps.map((s) => s.agent).join(" → ")}`,
source: "user",
filePath: "",
steps,
};
}
private enterSaveChainName(): void {
this.savingChain = true;
this.saveChainNameState = createEditorState();
this.tui.requestRender();
}
private handleSaveChainNameInput(data: string): void {
if (matchesKey(data, "tab")) return;
const innerW = this.width - 2;
const boxInnerWidth = Math.max(10, innerW - 4);
const nextState = handleEditorInput(this.saveChainNameState, data, boxInnerWidth);
if (nextState) {
this.saveChainNameState = nextState;
this.tui.requestRender();
return;
}
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
this.savingChain = false;
this.saveChainNameState = createEditorState();
this.tui.requestRender();
return;
}
if (matchesKey(data, "return")) {
const name = this.saveChainNameState.buffer.trim();
if (!name) {
this.showSaveMessage("Name is required", "error");
this.savingChain = false;
this.saveChainNameState = createEditorState();
return;
}
try {
const dir = path.join(os.homedir(), ".pi", "agent", "agents");
fs.mkdirSync(dir, { recursive: true });
const filePath = path.join(dir, `${name}.chain.md`);
const config = this.buildChainConfig(name);
config.filePath = filePath;
fs.writeFileSync(filePath, serializeChain(config), "utf-8");
this.showSaveMessage(`Saved ${name}.chain.md`, "info");
} catch (err) {
this.showSaveMessage(err instanceof Error ? err.message : "Failed to save chain", "error");
}
this.savingChain = false;
this.saveChainNameState = createEditorState();
}
}
private showSaveMessage(text: string, type: "info" | "error"): void {
this.saveMessage = { text, type };
if (this.saveMessageTimer) clearTimeout(this.saveMessageTimer);
this.saveMessageTimer = setTimeout(() => {
this.saveMessage = null;
this.saveMessageTimer = null;
this.tui.requestRender();
}, 2000);
this.tui.requestRender();
}
private arraysEqual(a: string[] | false, b: string[] | false): boolean {
if (a === b) return true;
if (a === false || b === false) return false;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
private saveOverridesToAgent(): void {
const stepIndex = this.selectedStep;
const agent = this.agentConfigs[stepIndex];
if (!agent?.filePath) {
this.showSaveMessage("Agent file not found", "error");
return;
}
const override = this.behaviorOverrides.get(stepIndex);
if (!override) {
this.showSaveMessage("No changes to save", "info");
return;
}
const base = this.resolvedBehaviors[stepIndex]!;
const updates: Array<{ field: string; value: string | undefined }> = [];
if (override.output !== undefined && override.output !== base.output) {
updates.push({
field: "output",
value: override.output === false ? undefined : override.output,
});
}
if (override.reads !== undefined && !this.arraysEqual(override.reads, base.reads)) {
updates.push({
field: "defaultReads",
value: override.reads === false ? undefined : override.reads.join(", "),
});
}
if (override.progress !== undefined && override.progress !== base.progress) {
updates.push({
field: "defaultProgress",
value: override.progress ? "true" : undefined,
});
}
if (override.skills !== undefined && !this.arraysEqual(override.skills, base.skills)) {
updates.push({
field: "skills",
value: override.skills === false || override.skills.length === 0 ? undefined : override.skills.join(", "),
});
}
if (override.model !== undefined) {
const baseModel = agent.model ? this.resolveModelFullId(agent.model) : undefined;
if (override.model !== baseModel) {
updates.push({ field: "model", value: override.model });
}
}
if (updates.length === 0) {
this.showSaveMessage("No changes to save", "info");
return;
}
try {
for (const update of updates) {
updateFrontmatterField(agent.filePath, update.field, update.value);
}
this.showSaveMessage("Saved agent settings", "info");
} catch (err) {
this.showSaveMessage(err instanceof Error ? err.message : "Failed to save agent settings", "error");
}
}
handleInput(data: string): void {
if (this.savingChain) {
this.handleSaveChainNameInput(data);
return;
}
if (this.editingStep !== null) {
if (this.editMode === "model") {
this.handleModelSelectorInput(data);
} else if (this.editMode === "thinking") {
this.handleThinkingSelectorInput(data);
} else if (this.editMode === "skills") {
this.handleSkillSelectorInput(data);
} else {
this.handleEditInput(data);
}
return;
}
// Navigation mode
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
this.done({ confirmed: false, templates: [], behaviorOverrides: [] });
return;
}
if (matchesKey(data, "return")) {
// Build behavior overrides array
const overrides: (BehaviorOverride | undefined)[] = [];
for (let i = 0; i < this.agentConfigs.length; i++) {
overrides.push(this.behaviorOverrides.get(i));
}
this.done({ confirmed: true, templates: this.templates, behaviorOverrides: overrides, runInBackground: this.runInBackground });
return;
}
if (matchesKey(data, "up")) {
this.selectedStep = Math.max(0, this.selectedStep - 1);
this.tui.requestRender();
return;
}
if (matchesKey(data, "down")) {
const maxStep = Math.max(0, this.agentConfigs.length - 1);
this.selectedStep = Math.min(maxStep, this.selectedStep + 1);
this.tui.requestRender();
return;
}
// 'e' to edit template (all modes)
if (data === "e") {
this.enterEditMode("template");
return;
}
// 'm' to select model (all modes)
if (data === "m") {
this.enterModelSelector();
return;
}
// 't' to select thinking level (all modes)
if (data === "t") {
this.enterThinkingSelector();
return;
}
// 's' to select skills (all modes)
if (data === "s") {
this.editingStep = this.selectedStep;
this.editMode = "skills";
this.skillSearchQuery = "";
this.skillCursorIndex = 0;
this.filteredSkills = [...this.availableSkills];
const current = this.getEffectiveBehavior(this.selectedStep).skills;
this.skillSelectedNames.clear();
if (current !== false && current.length > 0) {
current.forEach((skillName) => this.skillSelectedNames.add(skillName));
}
this.tui.requestRender();
return;
}
// 'w' to edit writes (single and chain only - not parallel)
if (data === "w" && this.mode !== 'parallel') {
this.enterEditMode("output");
return;
}
// 'r' to edit reads (chain only)
if (data === "r" && this.mode === 'chain') {
this.enterEditMode("reads");
return;
}
// 'p' to toggle progress for ALL steps (chain only - chains share a single progress.md)
if (data === "p" && this.mode === 'chain') {
// Check if any step has progress enabled
const anyEnabled = this.agentConfigs.some((_, i) => this.getEffectiveBehavior(i).progress);
// Toggle all steps to the opposite state
const newState = !anyEnabled;
for (let i = 0; i < this.agentConfigs.length; i++) {
this.updateBehavior(i, "progress", newState);
}
this.tui.requestRender();
return;
}
// 'b' to toggle background/async execution (all modes)
if (data === "b") {
this.runInBackground = !this.runInBackground;
this.tui.requestRender();
return;
}
if (data === "S") {
this.saveOverridesToAgent();
return;
}
if (data === "W" && this.mode === "chain") {
this.enterSaveChainName();
return;
}
}
private enterEditMode(mode: EditMode): void {
this.editingStep = this.selectedStep;
this.editMode = mode;
let buffer = "";
if (mode === "template") {
const template = this.templates[this.selectedStep] ?? "";
buffer = template.split("\n")[0] ?? "";
} else if (mode === "output") {
const behavior = this.getEffectiveBehavior(this.selectedStep);
buffer = behavior.output === false ? "" : (behavior.output || "");
} else if (mode === "reads") {
const behavior = this.getEffectiveBehavior(this.selectedStep);
buffer = behavior.reads === false ? "" : (behavior.reads?.join(", ") || "");
}
this.editState = createEditorState(buffer);
this.tui.requestRender();
}
/** Enter model selector mode */
private enterModelSelector(): void {
this.editingStep = this.selectedStep;
this.editMode = "model";
this.modelSearchQuery = "";
this.modelSelectedIndex = 0;
this.filteredModels = [...this.availableModels];
// Pre-select current model if it exists in the list
const currentModel = this.getEffectiveModel(this.selectedStep);
const currentIndex = this.filteredModels.findIndex(m => m.fullId === currentModel || m.id === currentModel);
if (currentIndex >= 0) {
this.modelSelectedIndex = currentIndex;
}
this.tui.requestRender();
}
/** Filter models based on search query (fuzzy match) */
private filterModels(): void {
const query = this.modelSearchQuery.toLowerCase();
if (!query) {
this.filteredModels = [...this.availableModels];
} else {
this.filteredModels = this.availableModels.filter(m =>
m.fullId.toLowerCase().includes(query) ||
m.id.toLowerCase().includes(query) ||
m.provider.toLowerCase().includes(query)
);
}
// Clamp selected index
this.modelSelectedIndex = Math.min(this.modelSelectedIndex, Math.max(0, this.filteredModels.length - 1));
}
/** Handle input in model selector mode */
private handleModelSelectorInput(data: string): void {
// Escape or Ctrl+C - cancel and exit
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
this.exitEditMode();
return;
}
// Enter - select current model
if (matchesKey(data, "return")) {
const selected = this.filteredModels[this.modelSelectedIndex];
if (selected) {
this.updateBehavior(this.editingStep!, "model", selected.fullId);
}
this.exitEditMode();
return;
}
// Up arrow - move selection up
if (matchesKey(data, "up")) {
if (this.filteredModels.length > 0) {
this.modelSelectedIndex = this.modelSelectedIndex === 0
? this.filteredModels.length - 1
: this.modelSelectedIndex - 1;
}
this.tui.requestRender();
return;
}
// Down arrow - move selection down
if (matchesKey(data, "down")) {
if (this.filteredModels.length > 0) {
this.modelSelectedIndex = this.modelSelectedIndex === this.filteredModels.length - 1
? 0
: this.modelSelectedIndex + 1;
}
this.tui.requestRender();
return;
}
// Backspace - delete last character from search
if (matchesKey(data, "backspace")) {
if (this.modelSearchQuery.length > 0) {
this.modelSearchQuery = this.modelSearchQuery.slice(0, -1);
this.filterModels();
}
this.tui.requestRender();
return;
}
// Printable character - add to search query
if (data.length === 1 && data.charCodeAt(0) >= 32) {
this.modelSearchQuery += data;
this.filterModels();
this.tui.requestRender();
return;
}
}
/** Enter thinking level selector mode */
private enterThinkingSelector(): void {
this.editingStep = this.selectedStep;
this.editMode = "thinking";
// Pre-select current thinking level if set
const currentModel = this.getEffectiveModel(this.selectedStep);
const colonIdx = currentModel.lastIndexOf(":");
if (colonIdx !== -1) {
const suffix = currentModel.substring(colonIdx + 1);
const levelIdx = THINKING_LEVELS.indexOf(suffix as ThinkingLevel);
this.thinkingSelectedIndex = levelIdx >= 0 ? levelIdx : 0;
} else {
this.thinkingSelectedIndex = 0; // Default to "off"
}
this.tui.requestRender();
}
/** Handle input in thinking level selector mode */
private handleThinkingSelectorInput(data: string): void {
// Escape or Ctrl+C - cancel and exit
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
this.exitEditMode();
return;
}
// Enter - select current thinking level
if (matchesKey(data, "return")) {
const selectedLevel = THINKING_LEVELS[this.thinkingSelectedIndex];
this.applyThinkingLevel(selectedLevel);
this.exitEditMode();
return;
}
// Up arrow - move selection up
if (matchesKey(data, "up")) {
this.thinkingSelectedIndex = this.thinkingSelectedIndex === 0
? THINKING_LEVELS.length - 1
: this.thinkingSelectedIndex - 1;
this.tui.requestRender();
return;
}
// Down arrow - move selection down
if (matchesKey(data, "down")) {
this.thinkingSelectedIndex = this.thinkingSelectedIndex === THINKING_LEVELS.length - 1
? 0
: this.thinkingSelectedIndex + 1;
this.tui.requestRender();
return;
}
}
/** Apply thinking level to the current step's model */
private applyThinkingLevel(level: ThinkingLevel): void {
const stepIndex = this.editingStep!;
const currentModel = this.getEffectiveModel(stepIndex);
// Strip any existing thinking level suffix
const colonIdx = currentModel.lastIndexOf(":");
let baseModel = currentModel;
if (colonIdx !== -1) {
const suffix = currentModel.substring(colonIdx + 1);
if (THINKING_LEVELS.includes(suffix as ThinkingLevel)) {
baseModel = currentModel.substring(0, colonIdx);
}
}
// Apply new thinking level (don't add suffix for "off")
const newModel = level === "off" ? baseModel : `${baseModel}:${level}`;
this.updateBehavior(stepIndex, "model", newModel);
}
private filterSkills(): void {
const query = this.skillSearchQuery.toLowerCase();
if (!query) {
this.filteredSkills = [...this.availableSkills];
} else {
this.filteredSkills = this.availableSkills.filter((s) =>
s.name.toLowerCase().includes(query) ||
(s.description?.toLowerCase().includes(query) ?? false),
);
}
this.skillCursorIndex = Math.min(this.skillCursorIndex, Math.max(0, this.filteredSkills.length - 1));
}
private handleSkillSelectorInput(data: string): void {
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
this.exitEditMode();
return;
}
if (matchesKey(data, "return")) {
const selected = [...this.skillSelectedNames];
this.updateBehavior(this.editingStep!, "skills", selected);
this.exitEditMode();
return;
}
if (data === " ") {
if (this.filteredSkills.length > 0) {
const skill = this.filteredSkills[this.skillCursorIndex];
if (skill) {
if (this.skillSelectedNames.has(skill.name)) {
this.skillSelectedNames.delete(skill.name);
} else {
this.skillSelectedNames.add(skill.name);
}
}
}
this.tui.requestRender();
return;
}
if (matchesKey(data, "up")) {
if (this.filteredSkills.length > 0) {
this.skillCursorIndex = this.skillCursorIndex === 0
? this.filteredSkills.length - 1
: this.skillCursorIndex - 1;
}
this.tui.requestRender();
return;
}
if (matchesKey(data, "down")) {
if (this.filteredSkills.length > 0) {
this.skillCursorIndex = this.skillCursorIndex === this.filteredSkills.length - 1
? 0
: this.skillCursorIndex + 1;
}
this.tui.requestRender();
return;
}
if (matchesKey(data, "backspace")) {
if (this.skillSearchQuery.length > 0) {
this.skillSearchQuery = this.skillSearchQuery.slice(0, -1);
this.filterSkills();
}
this.tui.requestRender();
return;
}
if (data.length === 1 && data.charCodeAt(0) >= 32) {
this.skillSearchQuery += data;
this.filterSkills();
this.tui.requestRender();
return;
}
}
private handleEditInput(data: string): void {
const textWidth = this.width - 4; // Must match render: innerW - 2 = (width - 2) - 2
if (matchesKey(data, "shift+up") || matchesKey(data, "pageup")) {
const { lines: wrapped, starts } = wrapText(this.editState.buffer, textWidth);
const cursorPos = getCursorDisplayPos(this.editState.cursor, starts);
const targetLine = Math.max(0, cursorPos.line - this.EDIT_VIEWPORT_HEIGHT);
const targetCol = Math.min(cursorPos.col, wrapped[targetLine]?.length ?? 0);
this.editState = { ...this.editState, cursor: starts[targetLine] + targetCol };
this.tui.requestRender();
return;
}
if (matchesKey(data, "shift+down") || matchesKey(data, "pagedown")) {
const { lines: wrapped, starts } = wrapText(this.editState.buffer, textWidth);
const cursorPos = getCursorDisplayPos(this.editState.cursor, starts);
const targetLine = Math.min(wrapped.length - 1, cursorPos.line + this.EDIT_VIEWPORT_HEIGHT);
const targetCol = Math.min(cursorPos.col, wrapped[targetLine]?.length ?? 0);
this.editState = { ...this.editState, cursor: starts[targetLine] + targetCol };
this.tui.requestRender();
return;
}
if (matchesKey(data, "tab")) return;
const nextState = handleEditorInput(this.editState, data, textWidth);
if (nextState) {
this.editState = nextState;
this.tui.requestRender();
return;
}
if (matchesKey(data, "escape")) {
this.saveEdit();
this.exitEditMode();
return;
}
if (matchesKey(data, "ctrl+c")) {
this.exitEditMode();
return;
}
}
private saveEdit(): void {
const stepIndex = this.editingStep!;
if (this.editMode === "template") {
// For template, preserve other lines if they existed
const original = this.templates[stepIndex] ?? "";
const originalLines = original.split("\n");
originalLines[0] = this.editState.buffer;
this.templates[stepIndex] = originalLines.join("\n");
} else if (this.editMode === "output") {
// Capture OLD output before updating (for downstream propagation)
const oldBehavior = this.getEffectiveBehavior(stepIndex);
const oldOutput = typeof oldBehavior.output === "string" ? oldBehavior.output : null;
// Empty string or whitespace means disable output
const trimmed = this.editState.buffer.trim();
const newOutput = trimmed === "" ? false : trimmed;
this.updateBehavior(stepIndex, "output", newOutput);
// Propagate output filename change to downstream steps' reads
if (oldOutput && typeof newOutput === "string" && oldOutput !== newOutput) {
this.propagateOutputChange(stepIndex, oldOutput, newOutput);
}
} else if (this.editMode === "reads") {
// Parse comma-separated list, empty means disable reads
const trimmed = this.editState.buffer.trim();
if (trimmed === "") {
this.updateBehavior(stepIndex, "reads", false);
} else {
const files = trimmed.split(",").map(f => f.trim()).filter(f => f !== "");
this.updateBehavior(stepIndex, "reads", files.length > 0 ? files : false);
}
}
}
/**
* When a step's output filename changes, update downstream steps that read from it.
* This maintains the chain dependency automatically.
*/
private propagateOutputChange(changedStepIndex: number, oldOutput: string, newOutput: string): void {
// Check all downstream steps (steps that come after the changed step)
for (let i = changedStepIndex + 1; i < this.agentConfigs.length; i++) {
const behavior = this.getEffectiveBehavior(i);
// Skip if reads is disabled or empty
if (behavior.reads === false || !behavior.reads || behavior.reads.length === 0) {
continue;
}
// Check if this step reads the old output file
const readsArray = behavior.reads;
const oldIndex = readsArray.indexOf(oldOutput);
if (oldIndex !== -1) {
// Replace old filename with new filename in reads
const newReads = [...readsArray];
newReads[oldIndex] = newOutput;
this.updateBehavior(i, "reads", newReads);
}
}
}
private renderSaveChainName(): string[] {
const lines: string[] = [];
const innerW = this.width - 2;
const boxInnerWidth = Math.max(10, innerW - 4);
lines.push(this.renderHeader(" Save Chain "));
lines.push(this.row(""));
lines.push(this.row(` ${this.theme.fg("dim", "Name:")}`));
const top = `┌${"─".repeat(boxInnerWidth)}┐`;
const bottom = `└${"─".repeat(boxInnerWidth)}┘`;
lines.push(this.row(` ${top}`));
const editorState = { ...this.saveChainNameState };
const wrapped = wrapText(editorState.buffer, boxInnerWidth);
const cursorPos = getCursorDisplayPos(editorState.cursor, wrapped.starts);
editorState.viewportOffset = ensureCursorVisible(cursorPos.line, 1, editorState.viewportOffset);
const editorLine = renderEditor(editorState, boxInnerWidth, 1)[0] ?? "";
lines.push(this.row(` │${this.pad(editorLine, boxInnerWidth)}│`));
lines.push(this.row(` ${bottom}`));
lines.push(this.row(""));
lines.push(this.renderFooter(" [Enter] Save • [Esc] Cancel "));
return lines;
}
render(_width: number): string[] {
if (this.savingChain) {
return this.renderSaveChainName();
}
if (this.editingStep !== null) {
if (this.editMode === "model") {
return this.renderModelSelector();
}
if (this.editMode === "thinking") {
return this.renderThinkingSelector();
}
if (this.editMode === "skills") {
return this.renderSkillSelector();
}
return this.renderFullEditMode();
}
// Mode-based navigation rendering
switch (this.mode) {
case 'single': return this.renderSingleMode();
case 'parallel': return this.renderParallelMode();
case 'chain': return this.renderChainMode();
}
}
/** Render the model selector view */
private renderModelSelector(): string[] {
const th = this.theme;
const lines: string[] = [];
// Header (mode-aware terminology)
const agentName = this.agentConfigs[this.editingStep!]?.name ?? "unknown";
const stepLabel = this.mode === 'single'
? agentName
: this.mode === 'parallel'
? `Task ${this.editingStep! + 1}: ${agentName}`
: `Step ${this.editingStep! + 1}: ${agentName}`;
const headerText = ` Select Model (${stepLabel}) `;
lines.push(this.renderHeader(headerText));
lines.push(this.row(""));
// Search input
const searchPrefix = th.fg("dim", "Search: ");
const cursor = "\x1b[7m \x1b[27m"; // Reverse video space for cursor
const searchDisplay = this.modelSearchQuery + cursor;
lines.push(this.row(` ${searchPrefix}${searchDisplay}`));