@mariozechner/pi-coding-agent 0.7.26 → 0.7.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +33 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -0
- package/dist/main.js.map +1 -1
- package/dist/settings-manager.d.ts +3 -0
- package/dist/settings-manager.d.ts.map +1 -1
- package/dist/settings-manager.js +7 -0
- package/dist/settings-manager.js.map +1 -1
- package/dist/tui/queue-mode-selector.d.ts +10 -0
- package/dist/tui/queue-mode-selector.d.ts.map +1 -0
- package/dist/tui/queue-mode-selector.js +49 -0
- package/dist/tui/queue-mode-selector.js.map +1 -0
- package/dist/tui/tui-renderer.d.ts +6 -0
- package/dist/tui/tui-renderer.d.ts.map +1 -1
- package/dist/tui/tui-renderer.js +105 -3
- package/dist/tui/tui-renderer.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Container, SelectList } from "@mariozechner/pi-tui";
|
|
2
|
+
/**
|
|
3
|
+
* Component that renders a queue mode selector with borders
|
|
4
|
+
*/
|
|
5
|
+
export declare class QueueModeSelectorComponent extends Container {
|
|
6
|
+
private selectList;
|
|
7
|
+
constructor(currentMode: "all" | "one-at-a-time", onSelect: (mode: "all" | "one-at-a-time") => void, onCancel: () => void);
|
|
8
|
+
getSelectList(): SelectList;
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=queue-mode-selector.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queue-mode-selector.d.ts","sourceRoot":"","sources":["../../src/tui/queue-mode-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,SAAS,EAAmB,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAY9F;;GAEG;AACH,qBAAa,0BAA2B,SAAQ,SAAS;IACxD,OAAO,CAAC,UAAU,CAAa;IAE/B,YACC,WAAW,EAAE,KAAK,GAAG,eAAe,EACpC,QAAQ,EAAE,CAAC,IAAI,EAAE,KAAK,GAAG,eAAe,KAAK,IAAI,EACjD,QAAQ,EAAE,MAAM,IAAI,EAqCpB;IAED,aAAa,IAAI,UAAU,CAE1B;CACD","sourcesContent":["import { type Component, Container, type SelectItem, SelectList } from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\n\n/**\n * Dynamic border component that adjusts to viewport width\n */\nclass DynamicBorder implements Component {\n\trender(width: number): string[] {\n\t\treturn [chalk.blue(\"─\".repeat(Math.max(1, width)))];\n\t}\n}\n\n/**\n * Component that renders a queue mode selector with borders\n */\nexport class QueueModeSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(\n\t\tcurrentMode: \"all\" | \"one-at-a-time\",\n\t\tonSelect: (mode: \"all\" | \"one-at-a-time\") => void,\n\t\tonCancel: () => void,\n\t) {\n\t\tsuper();\n\n\t\tconst queueModes: SelectItem[] = [\n\t\t\t{\n\t\t\t\tvalue: \"one-at-a-time\",\n\t\t\t\tlabel: \"one-at-a-time\",\n\t\t\t\tdescription: \"Process queued messages one by one (recommended)\",\n\t\t\t},\n\t\t\t{ value: \"all\", label: \"all\", description: \"Process all queued messages at once\" },\n\t\t];\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Create selector\n\t\tthis.selectList = new SelectList(queueModes, 2);\n\n\t\t// Preselect current mode\n\t\tconst currentIndex = queueModes.findIndex((item) => item.value === currentMode);\n\t\tif (currentIndex !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(currentIndex);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value as \"all\" | \"one-at-a-time\");\n\t\t};\n\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSelectList(): SelectList {\n\t\treturn this.selectList;\n\t}\n}\n"]}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Container, SelectList } from "@mariozechner/pi-tui";
|
|
2
|
+
import chalk from "chalk";
|
|
3
|
+
/**
|
|
4
|
+
* Dynamic border component that adjusts to viewport width
|
|
5
|
+
*/
|
|
6
|
+
class DynamicBorder {
|
|
7
|
+
render(width) {
|
|
8
|
+
return [chalk.blue("─".repeat(Math.max(1, width)))];
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Component that renders a queue mode selector with borders
|
|
13
|
+
*/
|
|
14
|
+
export class QueueModeSelectorComponent extends Container {
|
|
15
|
+
selectList;
|
|
16
|
+
constructor(currentMode, onSelect, onCancel) {
|
|
17
|
+
super();
|
|
18
|
+
const queueModes = [
|
|
19
|
+
{
|
|
20
|
+
value: "one-at-a-time",
|
|
21
|
+
label: "one-at-a-time",
|
|
22
|
+
description: "Process queued messages one by one (recommended)",
|
|
23
|
+
},
|
|
24
|
+
{ value: "all", label: "all", description: "Process all queued messages at once" },
|
|
25
|
+
];
|
|
26
|
+
// Add top border
|
|
27
|
+
this.addChild(new DynamicBorder());
|
|
28
|
+
// Create selector
|
|
29
|
+
this.selectList = new SelectList(queueModes, 2);
|
|
30
|
+
// Preselect current mode
|
|
31
|
+
const currentIndex = queueModes.findIndex((item) => item.value === currentMode);
|
|
32
|
+
if (currentIndex !== -1) {
|
|
33
|
+
this.selectList.setSelectedIndex(currentIndex);
|
|
34
|
+
}
|
|
35
|
+
this.selectList.onSelect = (item) => {
|
|
36
|
+
onSelect(item.value);
|
|
37
|
+
};
|
|
38
|
+
this.selectList.onCancel = () => {
|
|
39
|
+
onCancel();
|
|
40
|
+
};
|
|
41
|
+
this.addChild(this.selectList);
|
|
42
|
+
// Add bottom border
|
|
43
|
+
this.addChild(new DynamicBorder());
|
|
44
|
+
}
|
|
45
|
+
getSelectList() {
|
|
46
|
+
return this.selectList;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=queue-mode-selector.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queue-mode-selector.js","sourceRoot":"","sources":["../../src/tui/queue-mode-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,SAAS,EAAmB,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B;;GAEG;AACH,MAAM,aAAa;IAClB,MAAM,CAAC,KAAa,EAAY;QAC/B,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAAA,CACpD;CACD;AAED;;GAEG;AACH,MAAM,OAAO,0BAA2B,SAAQ,SAAS;IAChD,UAAU,CAAa;IAE/B,YACC,WAAoC,EACpC,QAAiD,EACjD,QAAoB,EACnB;QACD,KAAK,EAAE,CAAC;QAER,MAAM,UAAU,GAAiB;YAChC;gBACC,KAAK,EAAE,eAAe;gBACtB,KAAK,EAAE,eAAe;gBACtB,WAAW,EAAE,kDAAkD;aAC/D;YACD,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,qCAAqC,EAAE;SAClF,CAAC;QAEF,iBAAiB;QACjB,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;QAEnC,kBAAkB;QAClB,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;QAEhD,yBAAyB;QACzB,MAAM,YAAY,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,WAAW,CAAC,CAAC;QAChF,IAAI,YAAY,KAAK,CAAC,CAAC,EAAE,CAAC;YACzB,IAAI,CAAC,UAAU,CAAC,gBAAgB,CAAC,YAAY,CAAC,CAAC;QAChD,CAAC;QAED,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC;YACpC,QAAQ,CAAC,IAAI,CAAC,KAAgC,CAAC,CAAC;QAAA,CAChD,CAAC;QAEF,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,GAAG,EAAE,CAAC;YAChC,QAAQ,EAAE,CAAC;QAAA,CACX,CAAC;QAEF,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAE/B,oBAAoB;QACpB,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;IAAA,CACnC;IAED,aAAa,GAAe;QAC3B,OAAO,IAAI,CAAC,UAAU,CAAC;IAAA,CACvB;CACD","sourcesContent":["import { type Component, Container, type SelectItem, SelectList } from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\n\n/**\n * Dynamic border component that adjusts to viewport width\n */\nclass DynamicBorder implements Component {\n\trender(width: number): string[] {\n\t\treturn [chalk.blue(\"─\".repeat(Math.max(1, width)))];\n\t}\n}\n\n/**\n * Component that renders a queue mode selector with borders\n */\nexport class QueueModeSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(\n\t\tcurrentMode: \"all\" | \"one-at-a-time\",\n\t\tonSelect: (mode: \"all\" | \"one-at-a-time\") => void,\n\t\tonCancel: () => void,\n\t) {\n\t\tsuper();\n\n\t\tconst queueModes: SelectItem[] = [\n\t\t\t{\n\t\t\t\tvalue: \"one-at-a-time\",\n\t\t\t\tlabel: \"one-at-a-time\",\n\t\t\t\tdescription: \"Process queued messages one by one (recommended)\",\n\t\t\t},\n\t\t\t{ value: \"all\", label: \"all\", description: \"Process all queued messages at once\" },\n\t\t];\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Create selector\n\t\tthis.selectList = new SelectList(queueModes, 2);\n\n\t\t// Preselect current mode\n\t\tconst currentIndex = queueModes.findIndex((item) => item.value === currentMode);\n\t\tif (currentIndex !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(currentIndex);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value as \"all\" | \"one-at-a-time\");\n\t\t};\n\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSelectList(): SelectList {\n\t\treturn this.selectList;\n\t}\n}\n"]}
|
|
@@ -8,6 +8,7 @@ import type { SettingsManager } from "../settings-manager.js";
|
|
|
8
8
|
export declare class TuiRenderer {
|
|
9
9
|
private ui;
|
|
10
10
|
private chatContainer;
|
|
11
|
+
private pendingMessagesContainer;
|
|
11
12
|
private statusContainer;
|
|
12
13
|
private editor;
|
|
13
14
|
private editorContainer;
|
|
@@ -23,9 +24,11 @@ export declare class TuiRenderer {
|
|
|
23
24
|
private lastSigintTime;
|
|
24
25
|
private changelogMarkdown;
|
|
25
26
|
private newVersion;
|
|
27
|
+
private queuedMessages;
|
|
26
28
|
private streamingComponent;
|
|
27
29
|
private pendingTools;
|
|
28
30
|
private thinkingSelector;
|
|
31
|
+
private queueModeSelector;
|
|
29
32
|
private modelSelector;
|
|
30
33
|
private userMessageSelector;
|
|
31
34
|
private oauthSelector;
|
|
@@ -50,6 +53,8 @@ export declare class TuiRenderer {
|
|
|
50
53
|
showWarning(warningMessage: string): void;
|
|
51
54
|
private showThinkingSelector;
|
|
52
55
|
private hideThinkingSelector;
|
|
56
|
+
private showQueueModeSelector;
|
|
57
|
+
private hideQueueModeSelector;
|
|
53
58
|
private showModelSelector;
|
|
54
59
|
private hideModelSelector;
|
|
55
60
|
private showUserMessageSelector;
|
|
@@ -59,6 +64,7 @@ export declare class TuiRenderer {
|
|
|
59
64
|
private handleExportCommand;
|
|
60
65
|
private handleSessionCommand;
|
|
61
66
|
private handleChangelogCommand;
|
|
67
|
+
private updatePendingMessagesDisplay;
|
|
62
68
|
stop(): void;
|
|
63
69
|
}
|
|
64
70
|
//# sourceMappingURL=tui-renderer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tui-renderer.d.ts","sourceRoot":"","sources":["../../src/tui/tui-renderer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,EAAiB,MAAM,wBAAwB,CAAC;AAC3F,OAAO,KAAK,EAA6B,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAmB5E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAY9D;;GAEG;AACH,qBAAa,WAAW;IACvB,OAAO,CAAC,EAAE,CAAM;IAChB,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,KAAK,CAAQ;IACrB,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,eAAe,CAAC,CAAyB;IACjD,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,mBAAmB,CAAC,CAAa;IACzC,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,iBAAiB,CAAuB;IAChD,OAAO,CAAC,UAAU,CAAuB;IAGzC,OAAO,CAAC,kBAAkB,CAA0C;IAGpE,OAAO,CAAC,YAAY,CAA6C;IAGjE,OAAO,CAAC,gBAAgB,CAA0C;IAGlE,OAAO,CAAC,aAAa,CAAuC;IAG5D,OAAO,CAAC,mBAAmB,CAA6C;IAGxE,OAAO,CAAC,aAAa,CAAoB;IAGzC,OAAO,CAAC,kBAAkB,CAAQ;IAGlC,OAAO,CAAC,YAAY,CAAoB;IAGxC,OAAO,CAAC,kBAAkB,CAAS;IAEnC,YACC,KAAK,EAAE,KAAK,EACZ,cAAc,EAAE,cAAc,EAC9B,eAAe,EAAE,eAAe,EAChC,OAAO,EAAE,MAAM,EACf,iBAAiB,GAAE,MAAM,GAAG,IAAW,EACvC,UAAU,GAAE,MAAM,GAAG,IAAW,EAChC,YAAY,GAAE,KAAK,CAAC,GAAG,CAAC,EAAO,EAyE/B;IAEK,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CA8L1B;IAEK,WAAW,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAmJrE;IAED,OAAO,CAAC,gBAAgB;IAqBxB,qBAAqB,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAoE7C;IAEK,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC,CAOpC;IAED,oBAAoB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAE/C;IAED,OAAO,CAAC,WAAW;IAgBnB,OAAO,CAAC,sBAAsB;IAkB9B,OAAO,CAAC,uBAAuB;IAO/B,OAAO,CAAC,kBAAkB;YA8BZ,UAAU;IAuDxB,OAAO,CAAC,yBAAyB;IAajC,WAAW,IAAI,IAAI,CAGlB;IAED,SAAS,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAKpC;IAED,WAAW,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAKxC;IAED,OAAO,CAAC,oBAAoB;IAqC5B,OAAO,CAAC,oBAAoB;IAQ5B,OAAO,CAAC,iBAAiB;IAoCzB,OAAO,CAAC,iBAAiB;IAQzB,OAAO,CAAC,uBAAuB;IA4E/B,OAAO,CAAC,uBAAuB;YAQjB,iBAAiB;IA2G/B,OAAO,CAAC,iBAAiB;IAQzB,OAAO,CAAC,mBAAmB;IAuB3B,OAAO,CAAC,oBAAoB;IAwE5B,OAAO,CAAC,sBAAsB;IAuB9B,IAAI,IAAI,IAAI,CASX;CACD","sourcesContent":["import type { Agent, AgentEvent, AgentState, ThinkingLevel } from \"@mariozechner/pi-agent\";\nimport type { AssistantMessage, Message, Model } from \"@mariozechner/pi-ai\";\nimport type { SlashCommand } from \"@mariozechner/pi-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\tContainer,\n\tInput,\n\tLoader,\n\tMarkdown,\n\tProcessTerminal,\n\tSpacer,\n\tText,\n\tTUI,\n} from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\nimport { exec } from \"child_process\";\nimport { getChangelogPath, parseChangelog } from \"../changelog.js\";\nimport { exportSessionToHtml } from \"../export-html.js\";\nimport { getApiKeyForModel, getAvailableModels } from \"../model-config.js\";\nimport { listOAuthProviders, login, logout } from \"../oauth/index.js\";\nimport type { SessionManager } from \"../session-manager.js\";\nimport type { SettingsManager } from \"../settings-manager.js\";\nimport { AssistantMessageComponent } from \"./assistant-message.js\";\nimport { CustomEditor } from \"./custom-editor.js\";\nimport { DynamicBorder } from \"./dynamic-border.js\";\nimport { FooterComponent } from \"./footer.js\";\nimport { ModelSelectorComponent } from \"./model-selector.js\";\nimport { OAuthSelectorComponent } from \"./oauth-selector.js\";\nimport { ThinkingSelectorComponent } from \"./thinking-selector.js\";\nimport { ToolExecutionComponent } from \"./tool-execution.js\";\nimport { UserMessageComponent } from \"./user-message.js\";\nimport { UserMessageSelectorComponent } from \"./user-message-selector.js\";\n\n/**\n * TUI renderer for the coding agent\n */\nexport class TuiRenderer {\n\tprivate ui: TUI;\n\tprivate chatContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate editor: CustomEditor;\n\tprivate editorContainer: Container; // Container to swap between editor and selector\n\tprivate footer: FooterComponent;\n\tprivate agent: Agent;\n\tprivate sessionManager: SessionManager;\n\tprivate settingsManager: SettingsManager;\n\tprivate version: string;\n\tprivate isInitialized = false;\n\tprivate onInputCallback?: (text: string) => void;\n\tprivate loadingAnimation: Loader | null = null;\n\tprivate onInterruptCallback?: () => void;\n\tprivate lastSigintTime = 0;\n\tprivate changelogMarkdown: string | null = null;\n\tprivate newVersion: string | null = null;\n\n\t// Streaming message tracking\n\tprivate streamingComponent: AssistantMessageComponent | null = null;\n\n\t// Tool execution tracking: toolCallId -> component\n\tprivate pendingTools = new Map<string, ToolExecutionComponent>();\n\n\t// Thinking level selector\n\tprivate thinkingSelector: ThinkingSelectorComponent | null = null;\n\n\t// Model selector\n\tprivate modelSelector: ModelSelectorComponent | null = null;\n\n\t// User message selector (for branching)\n\tprivate userMessageSelector: UserMessageSelectorComponent | null = null;\n\n\t// OAuth selector\n\tprivate oauthSelector: any | null = null;\n\n\t// Track if this is the first user message (to skip spacer)\n\tprivate isFirstUserMessage = true;\n\n\t// Model scope for quick cycling\n\tprivate scopedModels: Model<any>[] = [];\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\n\tconstructor(\n\t\tagent: Agent,\n\t\tsessionManager: SessionManager,\n\t\tsettingsManager: SettingsManager,\n\t\tversion: string,\n\t\tchangelogMarkdown: string | null = null,\n\t\tnewVersion: string | null = null,\n\t\tscopedModels: Model<any>[] = [],\n\t) {\n\t\tthis.agent = agent;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.settingsManager = settingsManager;\n\t\tthis.version = version;\n\t\tthis.newVersion = newVersion;\n\t\tthis.changelogMarkdown = changelogMarkdown;\n\t\tthis.scopedModels = scopedModels;\n\t\tthis.ui = new TUI(new ProcessTerminal());\n\t\tthis.chatContainer = new Container();\n\t\tthis.statusContainer = new Container();\n\t\tthis.editor = new CustomEditor();\n\t\tthis.editorContainer = new Container(); // Container to hold editor or selector\n\t\tthis.editorContainer.addChild(this.editor); // Start with editor\n\t\tthis.footer = new FooterComponent(agent.state);\n\n\t\t// Define slash commands\n\t\tconst thinkingCommand: SlashCommand = {\n\t\t\tname: \"thinking\",\n\t\t\tdescription: \"Select reasoning level (opens selector UI)\",\n\t\t};\n\n\t\tconst modelCommand: SlashCommand = {\n\t\t\tname: \"model\",\n\t\t\tdescription: \"Select model (opens selector UI)\",\n\t\t};\n\n\t\tconst exportCommand: SlashCommand = {\n\t\t\tname: \"export\",\n\t\t\tdescription: \"Export session to HTML file\",\n\t\t};\n\n\t\tconst sessionCommand: SlashCommand = {\n\t\t\tname: \"session\",\n\t\t\tdescription: \"Show session info and stats\",\n\t\t};\n\n\t\tconst changelogCommand: SlashCommand = {\n\t\t\tname: \"changelog\",\n\t\t\tdescription: \"Show changelog entries\",\n\t\t};\n\n\t\tconst branchCommand: SlashCommand = {\n\t\t\tname: \"branch\",\n\t\t\tdescription: \"Create a new branch from a previous message\",\n\t\t};\n\n\t\tconst loginCommand: SlashCommand = {\n\t\t\tname: \"login\",\n\t\t\tdescription: \"Login with OAuth provider\",\n\t\t};\n\n\t\tconst logoutCommand: SlashCommand = {\n\t\t\tname: \"logout\",\n\t\t\tdescription: \"Logout from OAuth provider\",\n\t\t};\n\n\t\t// Setup autocomplete for file paths and slash commands\n\t\tconst autocompleteProvider = new CombinedAutocompleteProvider(\n\t\t\t[\n\t\t\t\tthinkingCommand,\n\t\t\t\tmodelCommand,\n\t\t\t\texportCommand,\n\t\t\t\tsessionCommand,\n\t\t\t\tchangelogCommand,\n\t\t\t\tbranchCommand,\n\t\t\t\tloginCommand,\n\t\t\t\tlogoutCommand,\n\t\t\t],\n\t\t\tprocess.cwd(),\n\t\t);\n\t\tthis.editor.setAutocompleteProvider(autocompleteProvider);\n\t}\n\n\tasync init(): Promise<void> {\n\t\tif (this.isInitialized) return;\n\n\t\t// Add header with logo and instructions\n\t\tconst logo = chalk.bold.cyan(\"pi\") + chalk.dim(` v${this.version}`);\n\t\tconst instructions =\n\t\t\tchalk.dim(\"esc\") +\n\t\t\tchalk.gray(\" to interrupt\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+c\") +\n\t\t\tchalk.gray(\" to clear\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+c twice\") +\n\t\t\tchalk.gray(\" to exit\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+k\") +\n\t\t\tchalk.gray(\" to delete line\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"shift+tab\") +\n\t\t\tchalk.gray(\" to cycle thinking\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+p\") +\n\t\t\tchalk.gray(\" to cycle models\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+o\") +\n\t\t\tchalk.gray(\" to expand tools\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"/\") +\n\t\t\tchalk.gray(\" for commands\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"drop files\") +\n\t\t\tchalk.gray(\" to attach\");\n\t\tconst header = new Text(logo + \"\\n\" + instructions, 1, 0);\n\n\t\t// Setup UI layout\n\t\tthis.ui.addChild(new Spacer(1));\n\t\tthis.ui.addChild(header);\n\t\tthis.ui.addChild(new Spacer(1));\n\n\t\t// Add new version notification if available\n\t\tif (this.newVersion) {\n\t\t\tthis.ui.addChild(new DynamicBorder(chalk.yellow));\n\t\t\tthis.ui.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\tchalk.bold.yellow(\"Update Available\") +\n\t\t\t\t\t\t\"\\n\" +\n\t\t\t\t\t\tchalk.gray(`New version ${this.newVersion} is available. Run: `) +\n\t\t\t\t\t\tchalk.cyan(\"npm install -g @mariozechner/pi-coding-agent\"),\n\t\t\t\t\t1,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t\tthis.ui.addChild(new DynamicBorder(chalk.yellow));\n\t\t}\n\n\t\t// Add changelog if provided\n\t\tif (this.changelogMarkdown) {\n\t\t\tthis.ui.addChild(new DynamicBorder(chalk.cyan));\n\t\t\tthis.ui.addChild(new Text(chalk.bold.cyan(\"What's New\"), 1, 0));\n\t\t\tthis.ui.addChild(new Spacer(1));\n\t\t\tthis.ui.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0));\n\t\t\tthis.ui.addChild(new Spacer(1));\n\t\t\tthis.ui.addChild(new DynamicBorder(chalk.cyan));\n\t\t}\n\n\t\tthis.ui.addChild(this.chatContainer);\n\t\tthis.ui.addChild(this.statusContainer);\n\t\tthis.ui.addChild(new Spacer(1));\n\t\tthis.ui.addChild(this.editorContainer); // Use container that can hold editor or selector\n\t\tthis.ui.addChild(this.footer);\n\t\tthis.ui.setFocus(this.editor);\n\n\t\t// Set up custom key handlers on the editor\n\t\tthis.editor.onEscape = () => {\n\t\t\t// Intercept Escape key when processing\n\t\t\tif (this.loadingAnimation && this.onInterruptCallback) {\n\t\t\t\tthis.onInterruptCallback();\n\t\t\t}\n\t\t};\n\n\t\tthis.editor.onCtrlC = () => {\n\t\t\tthis.handleCtrlC();\n\t\t};\n\n\t\tthis.editor.onShiftTab = () => {\n\t\t\tthis.cycleThinkingLevel();\n\t\t};\n\n\t\tthis.editor.onCtrlP = () => {\n\t\t\tthis.cycleModel();\n\t\t};\n\n\t\tthis.editor.onCtrlO = () => {\n\t\t\tthis.toggleToolOutputExpansion();\n\t\t};\n\n\t\t// Handle editor submission\n\t\tthis.editor.onSubmit = async (text: string) => {\n\t\t\ttext = text.trim();\n\t\t\tif (!text) return;\n\n\t\t\t// Check for /thinking command\n\t\t\tif (text === \"/thinking\") {\n\t\t\t\t// Show thinking level selector\n\t\t\t\tthis.showThinkingSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /model command\n\t\t\tif (text === \"/model\") {\n\t\t\t\t// Show model selector\n\t\t\t\tthis.showModelSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /export command\n\t\t\tif (text.startsWith(\"/export\")) {\n\t\t\t\tthis.handleExportCommand(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /session command\n\t\t\tif (text === \"/session\") {\n\t\t\t\tthis.handleSessionCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /changelog command\n\t\t\tif (text === \"/changelog\") {\n\t\t\t\tthis.handleChangelogCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /branch command\n\t\t\tif (text === \"/branch\") {\n\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /login command\n\t\t\tif (text === \"/login\") {\n\t\t\t\tthis.showOAuthSelector(\"login\");\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /logout command\n\t\t\tif (text === \"/logout\") {\n\t\t\t\tthis.showOAuthSelector(\"logout\");\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Normal message submission - validate model and API key first\n\t\t\tconst currentModel = this.agent.state.model;\n\t\t\tif (!currentModel) {\n\t\t\t\tthis.showError(\n\t\t\t\t\t\"No model selected.\\n\\n\" +\n\t\t\t\t\t\t\"Set an API key (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.)\\n\" +\n\t\t\t\t\t\t\"or create ~/.pi/agent/models.json\\n\\n\" +\n\t\t\t\t\t\t\"Then use /model to select a model.\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Validate API key (async)\n\t\t\tconst apiKey = await getApiKeyForModel(currentModel);\n\t\t\tif (!apiKey) {\n\t\t\t\tthis.showError(\n\t\t\t\t\t`No API key found for ${currentModel.provider}.\\n\\n` +\n\t\t\t\t\t\t`Set the appropriate environment variable or update ~/.pi/agent/models.json`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// All good, proceed with submission\n\t\t\tif (this.onInputCallback) {\n\t\t\t\tthis.onInputCallback(text);\n\t\t\t}\n\t\t};\n\n\t\t// Start the UI\n\t\tthis.ui.start();\n\t\tthis.isInitialized = true;\n\t}\n\n\tasync handleEvent(event: AgentEvent, state: AgentState): Promise<void> {\n\t\tif (!this.isInitialized) {\n\t\t\tawait this.init();\n\t\t}\n\n\t\t// Update footer with current stats\n\t\tthis.footer.updateState(state);\n\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\t\t// Show loading animation\n\t\t\t\tthis.editor.disableSubmit = true;\n\t\t\t\t// Stop old loader before clearing\n\t\t\t\tif (this.loadingAnimation) {\n\t\t\t\t\tthis.loadingAnimation.stop();\n\t\t\t\t}\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t\tthis.loadingAnimation = new Loader(this.ui, \"Working... (esc to interrupt)\");\n\t\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_start\":\n\t\t\t\tif (event.message.role === \"user\") {\n\t\t\t\t\t// Show user message immediately and clear editor\n\t\t\t\t\tthis.addMessageToChat(event.message);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t} else if (event.message.role === \"assistant\") {\n\t\t\t\t\t// Create assistant component for streaming\n\t\t\t\t\tthis.streamingComponent = new AssistantMessageComponent();\n\t\t\t\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\t\t\t\tthis.streamingComponent.updateContent(event.message as AssistantMessage);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\t// Update streaming component\n\t\t\t\tif (this.streamingComponent && event.message.role === \"assistant\") {\n\t\t\t\t\tconst assistantMsg = event.message as AssistantMessage;\n\t\t\t\t\tthis.streamingComponent.updateContent(assistantMsg);\n\n\t\t\t\t\t// Create tool execution components as soon as we see tool calls\n\t\t\t\t\tfor (const content of assistantMsg.content) {\n\t\t\t\t\t\tif (content.type === \"toolCall\") {\n\t\t\t\t\t\t\t// Only create if we haven't created it yet\n\t\t\t\t\t\t\tif (!this.pendingTools.has(content.id)) {\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(\"\", 0, 0));\n\t\t\t\t\t\t\t\tconst component = new ToolExecutionComponent(content.name, content.arguments);\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\t\t\t\tthis.pendingTools.set(content.id, component);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Update existing component with latest arguments as they stream\n\t\t\t\t\t\t\t\tconst component = this.pendingTools.get(content.id);\n\t\t\t\t\t\t\t\tif (component) {\n\t\t\t\t\t\t\t\t\tcomponent.updateArgs(content.arguments);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\t// Skip user messages (already shown in message_start)\n\t\t\t\tif (event.message.role === \"user\") {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (this.streamingComponent && event.message.role === \"assistant\") {\n\t\t\t\t\tconst assistantMsg = event.message as AssistantMessage;\n\n\t\t\t\t\t// Update streaming component with final message (includes stopReason)\n\t\t\t\t\tthis.streamingComponent.updateContent(assistantMsg);\n\n\t\t\t\t\t// If message was aborted or errored, mark all pending tool components as failed\n\t\t\t\t\tif (assistantMsg.stopReason === \"aborted\" || assistantMsg.stopReason === \"error\") {\n\t\t\t\t\t\tconst errorMessage =\n\t\t\t\t\t\t\tassistantMsg.stopReason === \"aborted\" ? \"Operation aborted\" : assistantMsg.errorMessage || \"Error\";\n\t\t\t\t\t\tfor (const [toolCallId, component] of this.pendingTools.entries()) {\n\t\t\t\t\t\t\tcomponent.updateResult({\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: errorMessage }],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.pendingTools.clear();\n\t\t\t\t\t}\n\n\t\t\t\t\t// Keep the streaming component - it's now the final assistant message\n\t\t\t\t\tthis.streamingComponent = null;\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\t// Component should already exist from message_update, but create if missing\n\t\t\t\tif (!this.pendingTools.has(event.toolCallId)) {\n\t\t\t\t\tconst component = new ToolExecutionComponent(event.toolName, event.args);\n\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\tthis.pendingTools.set(event.toolCallId, component);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\t// Update the existing tool component with the result\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\t// Convert result to the format expected by updateResult\n\t\t\t\t\tconst resultData =\n\t\t\t\t\t\ttypeof event.result === \"string\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: event.result }],\n\t\t\t\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t\t\t\t\tisError: event.isError,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tcontent: event.result.content,\n\t\t\t\t\t\t\t\t\tdetails: event.result.details,\n\t\t\t\t\t\t\t\t\tisError: event.isError,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\tcomponent.updateResult(resultData);\n\t\t\t\t\tthis.pendingTools.delete(event.toolCallId);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"agent_end\":\n\t\t\t\t// Stop loading animation\n\t\t\t\tif (this.loadingAnimation) {\n\t\t\t\t\tthis.loadingAnimation.stop();\n\t\t\t\t\tthis.loadingAnimation = null;\n\t\t\t\t\tthis.statusContainer.clear();\n\t\t\t\t}\n\t\t\t\tif (this.streamingComponent) {\n\t\t\t\t\tthis.chatContainer.removeChild(this.streamingComponent);\n\t\t\t\t\tthis.streamingComponent = null;\n\t\t\t\t}\n\t\t\t\tthis.pendingTools.clear();\n\t\t\t\tthis.editor.disableSubmit = false;\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate addMessageToChat(message: Message): void {\n\t\tif (message.role === \"user\") {\n\t\t\tconst userMsg = message as any;\n\t\t\t// Extract text content from content blocks\n\t\t\tconst textBlocks = userMsg.content.filter((c: any) => c.type === \"text\");\n\t\t\tconst textContent = textBlocks.map((c: any) => c.text).join(\"\");\n\t\t\tif (textContent) {\n\t\t\t\tconst userComponent = new UserMessageComponent(textContent, this.isFirstUserMessage);\n\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\tthis.isFirstUserMessage = false;\n\t\t\t}\n\t\t} else if (message.role === \"assistant\") {\n\t\t\tconst assistantMsg = message as AssistantMessage;\n\n\t\t\t// Add assistant message component\n\t\t\tconst assistantComponent = new AssistantMessageComponent(assistantMsg);\n\t\t\tthis.chatContainer.addChild(assistantComponent);\n\t\t}\n\t\t// Note: tool calls and results are now handled via tool_execution_start/end events\n\t}\n\n\trenderInitialMessages(state: AgentState): void {\n\t\t// Render all existing messages (for --continue mode)\n\t\t// Reset first user message flag for initial render\n\t\tthis.isFirstUserMessage = true;\n\n\t\t// Update footer with loaded state\n\t\tthis.footer.updateState(state);\n\n\t\t// Update editor border color based on current thinking level\n\t\tthis.updateEditorBorderColor();\n\n\t\t// Render messages\n\t\tfor (let i = 0; i < state.messages.length; i++) {\n\t\t\tconst message = state.messages[i];\n\n\t\t\tif (message.role === \"user\") {\n\t\t\t\tconst userMsg = message as any;\n\t\t\t\tconst textBlocks = userMsg.content.filter((c: any) => c.type === \"text\");\n\t\t\t\tconst textContent = textBlocks.map((c: any) => c.text).join(\"\");\n\t\t\t\tif (textContent) {\n\t\t\t\t\tconst userComponent = new UserMessageComponent(textContent, this.isFirstUserMessage);\n\t\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\t\tthis.isFirstUserMessage = false;\n\t\t\t\t}\n\t\t\t} else if (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\tconst assistantComponent = new AssistantMessageComponent(assistantMsg);\n\t\t\t\tthis.chatContainer.addChild(assistantComponent);\n\n\t\t\t\t// Create tool execution components for any tool calls\n\t\t\t\tfor (const content of assistantMsg.content) {\n\t\t\t\t\tif (content.type === \"toolCall\") {\n\t\t\t\t\t\tconst component = new ToolExecutionComponent(content.name, content.arguments);\n\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\n\t\t\t\t\t\t// If message was aborted/errored, immediately mark tool as failed\n\t\t\t\t\t\tif (assistantMsg.stopReason === \"aborted\" || assistantMsg.stopReason === \"error\") {\n\t\t\t\t\t\t\tconst errorMessage =\n\t\t\t\t\t\t\t\tassistantMsg.stopReason === \"aborted\"\n\t\t\t\t\t\t\t\t\t? \"Operation aborted\"\n\t\t\t\t\t\t\t\t\t: assistantMsg.errorMessage || \"Error\";\n\t\t\t\t\t\t\tcomponent.updateResult({\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: errorMessage }],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Store in map so we can update with results later\n\t\t\t\t\t\t\tthis.pendingTools.set(content.id, component);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (message.role === \"toolResult\") {\n\t\t\t\t// Update existing tool execution component with results\t\t\t\t;\n\t\t\t\tconst component = this.pendingTools.get(message.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({\n\t\t\t\t\t\tcontent: message.content,\n\t\t\t\t\t\tdetails: message.details,\n\t\t\t\t\t\tisError: message.isError,\n\t\t\t\t\t});\n\t\t\t\t\t// Remove from pending map since it's complete\n\t\t\t\t\tthis.pendingTools.delete(message.toolCallId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Clear pending tools after rendering initial messages\n\t\tthis.pendingTools.clear();\n\t\tthis.ui.requestRender();\n\t}\n\n\tasync getUserInput(): Promise<string> {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.onInputCallback = (text: string) => {\n\t\t\t\tthis.onInputCallback = undefined;\n\t\t\t\tresolve(text);\n\t\t\t};\n\t\t});\n\t}\n\n\tsetInterruptCallback(callback: () => void): void {\n\t\tthis.onInterruptCallback = callback;\n\t}\n\n\tprivate handleCtrlC(): void {\n\t\t// Handle Ctrl+C double-press logic\n\t\tconst now = Date.now();\n\t\tconst timeSinceLastCtrlC = now - this.lastSigintTime;\n\n\t\tif (timeSinceLastCtrlC < 500) {\n\t\t\t// Second Ctrl+C within 500ms - exit\n\t\t\tthis.stop();\n\t\t\tprocess.exit(0);\n\t\t} else {\n\t\t\t// First Ctrl+C - clear the editor\n\t\t\tthis.clearEditor();\n\t\t\tthis.lastSigintTime = now;\n\t\t}\n\t}\n\n\tprivate getThinkingBorderColor(level: ThinkingLevel): (str: string) => string {\n\t\t// More thinking = more color (gray → dim colors → bright colors)\n\t\tswitch (level) {\n\t\t\tcase \"off\":\n\t\t\t\treturn chalk.gray;\n\t\t\tcase \"minimal\":\n\t\t\t\treturn chalk.dim.blue;\n\t\t\tcase \"low\":\n\t\t\t\treturn chalk.blue;\n\t\t\tcase \"medium\":\n\t\t\t\treturn chalk.cyan;\n\t\t\tcase \"high\":\n\t\t\t\treturn chalk.magenta;\n\t\t\tdefault:\n\t\t\t\treturn chalk.gray;\n\t\t}\n\t}\n\n\tprivate updateEditorBorderColor(): void {\n\t\tconst level = this.agent.state.thinkingLevel || \"off\";\n\t\tconst color = this.getThinkingBorderColor(level);\n\t\tthis.editor.borderColor = color;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate cycleThinkingLevel(): void {\n\t\t// Only cycle if model supports thinking\n\t\tif (!this.agent.state.model?.reasoning) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(\"Current model does not support thinking\"), 1, 0));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tconst levels: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\t\tconst currentLevel = this.agent.state.thinkingLevel || \"off\";\n\t\tconst currentIndex = levels.indexOf(currentLevel);\n\t\tconst nextIndex = (currentIndex + 1) % levels.length;\n\t\tconst nextLevel = levels[nextIndex];\n\n\t\t// Apply the new thinking level\n\t\tthis.agent.setThinkingLevel(nextLevel);\n\n\t\t// Save thinking level change to session\n\t\tthis.sessionManager.saveThinkingLevelChange(nextLevel);\n\n\t\t// Update border color\n\t\tthis.updateEditorBorderColor();\n\n\t\t// Show brief notification\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Thinking level: ${nextLevel}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async cycleModel(): Promise<void> {\n\t\t// Use scoped models if available, otherwise all available models\n\t\tlet modelsToUse: Model<any>[];\n\t\tif (this.scopedModels.length > 0) {\n\t\t\tmodelsToUse = this.scopedModels;\n\t\t} else {\n\t\t\tconst { models: availableModels, error } = await getAvailableModels();\n\t\t\tif (error) {\n\t\t\t\tthis.showError(`Failed to load models: ${error}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tmodelsToUse = availableModels;\n\t\t}\n\n\t\tif (modelsToUse.length === 0) {\n\t\t\tthis.showError(\"No models available to cycle\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (modelsToUse.length === 1) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(\"Only one model in scope\"), 1, 0));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentModel = this.agent.state.model;\n\t\tlet currentIndex = modelsToUse.findIndex(\n\t\t\t(m) => m.id === currentModel?.id && m.provider === currentModel?.provider,\n\t\t);\n\n\t\t// If current model not in scope, start from first\n\t\tif (currentIndex === -1) {\n\t\t\tcurrentIndex = 0;\n\t\t}\n\n\t\tconst nextIndex = (currentIndex + 1) % modelsToUse.length;\n\t\tconst nextModel = modelsToUse[nextIndex];\n\n\t\t// Validate API key\n\t\tconst apiKey = await getApiKeyForModel(nextModel);\n\t\tif (!apiKey) {\n\t\t\tthis.showError(`No API key for ${nextModel.provider}/${nextModel.id}`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Switch model\n\t\tthis.agent.setModel(nextModel);\n\n\t\t// Show notification\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Switched to ${nextModel.name || nextModel.id}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate toggleToolOutputExpansion(): void {\n\t\tthis.toolOutputExpanded = !this.toolOutputExpanded;\n\n\t\t// Update all tool execution components\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\tchild.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\tclearEditor(): void {\n\t\tthis.editor.setText(\"\");\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowError(errorMessage: string): void {\n\t\t// Show error message in the chat\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(chalk.red(`Error: ${errorMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowWarning(warningMessage: string): void {\n\t\t// Show warning message in the chat\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(chalk.yellow(`Warning: ${warningMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showThinkingSelector(): void {\n\t\t// Create thinking selector with current level\n\t\tthis.thinkingSelector = new ThinkingSelectorComponent(\n\t\t\tthis.agent.state.thinkingLevel,\n\t\t\t(level) => {\n\t\t\t\t// Apply the selected thinking level\n\t\t\t\tthis.agent.setThinkingLevel(level);\n\n\t\t\t\t// Save thinking level change to session\n\t\t\t\tthis.sessionManager.saveThinkingLevelChange(level);\n\n\t\t\t\t// Update border color\n\t\t\t\tthis.updateEditorBorderColor();\n\n\t\t\t\t// Show confirmation message with proper spacing\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tconst confirmText = new Text(chalk.dim(`Thinking level: ${level}`), 1, 0);\n\t\t\t\tthis.chatContainer.addChild(confirmText);\n\n\t\t\t\t// Hide selector and show editor again\n\t\t\t\tthis.hideThinkingSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Just hide the selector\n\t\t\t\tthis.hideThinkingSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t);\n\n\t\t// Replace editor with selector\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.thinkingSelector);\n\t\tthis.ui.setFocus(this.thinkingSelector.getSelectList());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate hideThinkingSelector(): void {\n\t\t// Replace selector with editor in the container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.thinkingSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate showModelSelector(): void {\n\t\t// Create model selector with current model\n\t\tthis.modelSelector = new ModelSelectorComponent(\n\t\t\tthis.ui,\n\t\t\tthis.agent.state.model,\n\t\t\tthis.settingsManager,\n\t\t\t(model) => {\n\t\t\t\t// Apply the selected model\n\t\t\t\tthis.agent.setModel(model);\n\n\t\t\t\t// Save model change to session\n\t\t\t\tthis.sessionManager.saveModelChange(model.provider, model.id);\n\n\t\t\t\t// Show confirmation message with proper spacing\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tconst confirmText = new Text(chalk.dim(`Model: ${model.id}`), 1, 0);\n\t\t\t\tthis.chatContainer.addChild(confirmText);\n\n\t\t\t\t// Hide selector and show editor again\n\t\t\t\tthis.hideModelSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Just hide the selector\n\t\t\t\tthis.hideModelSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t);\n\n\t\t// Replace editor with selector\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.modelSelector);\n\t\tthis.ui.setFocus(this.modelSelector);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate hideModelSelector(): void {\n\t\t// Replace selector with editor in the container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.modelSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate showUserMessageSelector(): void {\n\t\t// Extract all user messages from the current state\n\t\tconst userMessages: Array<{ index: number; text: string }> = [];\n\n\t\tfor (let i = 0; i < this.agent.state.messages.length; i++) {\n\t\t\tconst message = this.agent.state.messages[i];\n\t\t\tif (message.role === \"user\") {\n\t\t\t\tconst userMsg = message as any;\n\t\t\t\tconst textBlocks = userMsg.content.filter((c: any) => c.type === \"text\");\n\t\t\t\tconst textContent = textBlocks.map((c: any) => c.text).join(\"\");\n\t\t\t\tif (textContent) {\n\t\t\t\t\tuserMessages.push({ index: i, text: textContent });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Don't show selector if there are no messages or only one message\n\t\tif (userMessages.length <= 1) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(\"No messages to branch from\"), 1, 0));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\t// Create user message selector\n\t\tthis.userMessageSelector = new UserMessageSelectorComponent(\n\t\t\tuserMessages,\n\t\t\t(messageIndex) => {\n\t\t\t\t// Get the selected user message text to put in the editor\n\t\t\t\tconst selectedMessage = this.agent.state.messages[messageIndex];\n\t\t\t\tconst selectedUserMsg = selectedMessage as any;\n\t\t\t\tconst textBlocks = selectedUserMsg.content.filter((c: any) => c.type === \"text\");\n\t\t\t\tconst selectedText = textBlocks.map((c: any) => c.text).join(\"\");\n\n\t\t\t\t// Create a branched session with messages UP TO (but not including) the selected message\n\t\t\t\tconst newSessionFile = this.sessionManager.createBranchedSession(this.agent.state, messageIndex - 1);\n\n\t\t\t\t// Set the new session file as active\n\t\t\t\tthis.sessionManager.setSessionFile(newSessionFile);\n\n\t\t\t\t// Truncate messages in agent state to before the selected message\n\t\t\t\tconst truncatedMessages = this.agent.state.messages.slice(0, messageIndex);\n\t\t\t\tthis.agent.replaceMessages(truncatedMessages);\n\n\t\t\t\t// Clear and re-render the chat\n\t\t\t\tthis.chatContainer.clear();\n\t\t\t\tthis.isFirstUserMessage = true;\n\t\t\t\tthis.renderInitialMessages(this.agent.state);\n\n\t\t\t\t// Show confirmation message\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\tnew Text(chalk.dim(`Branched to new session from message ${messageIndex}`), 1, 0),\n\t\t\t\t);\n\n\t\t\t\t// Put the selected message in the editor\n\t\t\t\tthis.editor.setText(selectedText);\n\n\t\t\t\t// Hide selector and show editor again\n\t\t\t\tthis.hideUserMessageSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Just hide the selector\n\t\t\t\tthis.hideUserMessageSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t);\n\n\t\t// Replace editor with selector\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.userMessageSelector);\n\t\tthis.ui.setFocus(this.userMessageSelector.getMessageList());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate hideUserMessageSelector(): void {\n\t\t// Replace selector with editor in the container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.userMessageSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate async showOAuthSelector(mode: \"login\" | \"logout\"): Promise<void> {\n\t\t// For logout mode, filter to only show logged-in providers\n\t\tlet providersToShow: string[] = [];\n\t\tif (mode === \"logout\") {\n\t\t\tconst loggedInProviders = listOAuthProviders();\n\t\t\tif (loggedInProviders.length === 0) {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(\"No OAuth providers logged in. Use /login first.\"), 1, 0));\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprovidersToShow = loggedInProviders;\n\t\t}\n\n\t\t// Create OAuth selector\n\t\tthis.oauthSelector = new OAuthSelectorComponent(\n\t\t\tmode,\n\t\t\tasync (providerId: any) => {\n\t\t\t\t// Hide selector first\n\t\t\t\tthis.hideOAuthSelector();\n\n\t\t\t\tif (mode === \"login\") {\n\t\t\t\t\t// Handle login\n\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Logging in to ${providerId}...`), 1, 0));\n\t\t\t\t\tthis.ui.requestRender();\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait login(\n\t\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\t\t(url: string) => {\n\t\t\t\t\t\t\t\t// Show auth URL to user\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.cyan(\"Opening browser to:\"), 1, 0));\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.cyan(url), 1, 0));\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\t\tnew Text(chalk.yellow(\"Paste the authorization code below:\"), 1, 0),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tthis.ui.requestRender();\n\n\t\t\t\t\t\t\t\t// Open URL in browser\n\t\t\t\t\t\t\t\tconst openCmd =\n\t\t\t\t\t\t\t\t\tprocess.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n\t\t\t\t\t\t\t\texec(`${openCmd} \"${url}\"`);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\t// Prompt for code with a simple Input\n\t\t\t\t\t\t\t\treturn new Promise<string>((resolve) => {\n\t\t\t\t\t\t\t\t\tconst codeInput = new Input();\n\t\t\t\t\t\t\t\t\tcodeInput.onSubmit = () => {\n\t\t\t\t\t\t\t\t\t\tconst code = codeInput.getValue();\n\t\t\t\t\t\t\t\t\t\t// Restore editor\n\t\t\t\t\t\t\t\t\t\tthis.editorContainer.clear();\n\t\t\t\t\t\t\t\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\t\t\t\t\t\t\t\tthis.ui.setFocus(this.editor);\n\t\t\t\t\t\t\t\t\t\tresolve(code);\n\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\tthis.editorContainer.clear();\n\t\t\t\t\t\t\t\t\tthis.editorContainer.addChild(codeInput);\n\t\t\t\t\t\t\t\t\tthis.ui.setFocus(codeInput);\n\t\t\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\t// Success\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.green(`✓ Successfully logged in to ${providerId}`), 1, 0));\n\t\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Tokens saved to ~/.pi/agent/oauth.json`), 1, 0));\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\tthis.showError(`Login failed: ${error.message}`);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Handle logout\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait logout(providerId);\n\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\tnew Text(chalk.green(`✓ Successfully logged out of ${providerId}`), 1, 0),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\tnew Text(chalk.dim(`Credentials removed from ~/.pi/agent/oauth.json`), 1, 0),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\tthis.showError(`Logout failed: ${error.message}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Cancel - just hide the selector\n\t\t\t\tthis.hideOAuthSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t);\n\n\t\t// Replace editor with selector\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.oauthSelector);\n\t\tthis.ui.setFocus(this.oauthSelector);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate hideOAuthSelector(): void {\n\t\t// Replace selector with editor in the container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.oauthSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate handleExportCommand(text: string): void {\n\t\t// Parse optional filename from command: /export [filename]\n\t\tconst parts = text.split(/\\s+/);\n\t\tconst outputPath = parts.length > 1 ? parts[1] : undefined;\n\n\t\ttry {\n\t\t\t// Export session to HTML\n\t\t\tconst filePath = exportSessionToHtml(this.sessionManager, this.agent.state, outputPath);\n\n\t\t\t// Show success message in chat - matching thinking level style\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Session exported to: ${filePath}`), 1, 0));\n\t\t\tthis.ui.requestRender();\n\t\t} catch (error: any) {\n\t\t\t// Show error message in chat\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Text(chalk.red(`Failed to export session: ${error.message || \"Unknown error\"}`), 1, 0),\n\t\t\t);\n\t\t\tthis.ui.requestRender();\n\t\t}\n\t}\n\n\tprivate handleSessionCommand(): void {\n\t\t// Get session info\n\t\tconst sessionFile = this.sessionManager.getSessionFile();\n\t\tconst state = this.agent.state;\n\n\t\t// Count messages\n\t\tconst userMessages = state.messages.filter((m) => m.role === \"user\").length;\n\t\tconst assistantMessages = state.messages.filter((m) => m.role === \"assistant\").length;\n\t\tconst toolResults = state.messages.filter((m) => m.role === \"toolResult\").length;\n\t\tconst totalMessages = state.messages.length;\n\n\t\t// Count tool calls from assistant messages\n\t\tlet toolCalls = 0;\n\t\tfor (const message of state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttoolCalls += assistantMsg.content.filter((c) => c.type === \"toolCall\").length;\n\t\t\t}\n\t\t}\n\n\t\t// Calculate cumulative usage from all assistant messages (same as footer)\n\t\tlet totalInput = 0;\n\t\tlet totalOutput = 0;\n\t\tlet totalCacheRead = 0;\n\t\tlet totalCacheWrite = 0;\n\t\tlet totalCost = 0;\n\n\t\tfor (const message of state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttotalInput += assistantMsg.usage.input;\n\t\t\t\ttotalOutput += assistantMsg.usage.output;\n\t\t\t\ttotalCacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\ttotalCacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\ttotalCost += assistantMsg.usage.cost.total;\n\t\t\t}\n\t\t}\n\n\t\tconst totalTokens = totalInput + totalOutput + totalCacheRead + totalCacheWrite;\n\n\t\t// Build info text\n\t\tlet info = `${chalk.bold(\"Session Info\")}\\n\\n`;\n\t\tinfo += `${chalk.dim(\"File:\")} ${sessionFile}\\n`;\n\t\tinfo += `${chalk.dim(\"ID:\")} ${this.sessionManager.getSessionId()}\\n\\n`;\n\t\tinfo += `${chalk.bold(\"Messages\")}\\n`;\n\t\tinfo += `${chalk.dim(\"User:\")} ${userMessages}\\n`;\n\t\tinfo += `${chalk.dim(\"Assistant:\")} ${assistantMessages}\\n`;\n\t\tinfo += `${chalk.dim(\"Tool Calls:\")} ${toolCalls}\\n`;\n\t\tinfo += `${chalk.dim(\"Tool Results:\")} ${toolResults}\\n`;\n\t\tinfo += `${chalk.dim(\"Total:\")} ${totalMessages}\\n\\n`;\n\t\tinfo += `${chalk.bold(\"Tokens\")}\\n`;\n\t\tinfo += `${chalk.dim(\"Input:\")} ${totalInput.toLocaleString()}\\n`;\n\t\tinfo += `${chalk.dim(\"Output:\")} ${totalOutput.toLocaleString()}\\n`;\n\t\tif (totalCacheRead > 0) {\n\t\t\tinfo += `${chalk.dim(\"Cache Read:\")} ${totalCacheRead.toLocaleString()}\\n`;\n\t\t}\n\t\tif (totalCacheWrite > 0) {\n\t\t\tinfo += `${chalk.dim(\"Cache Write:\")} ${totalCacheWrite.toLocaleString()}\\n`;\n\t\t}\n\t\tinfo += `${chalk.dim(\"Total:\")} ${totalTokens.toLocaleString()}\\n`;\n\n\t\tif (totalCost > 0) {\n\t\t\tinfo += `\\n${chalk.bold(\"Cost\")}\\n`;\n\t\t\tinfo += `${chalk.dim(\"Total:\")} ${totalCost.toFixed(4)}`;\n\t\t}\n\n\t\t// Show info in chat\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(info, 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleChangelogCommand(): void {\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst allEntries = parseChangelog(changelogPath);\n\n\t\t// Show all entries in reverse order (oldest first, newest last)\n\t\tconst changelogMarkdown =\n\t\t\tallEntries.length > 0\n\t\t\t\t? allEntries\n\t\t\t\t\t\t.reverse()\n\t\t\t\t\t\t.map((e) => e.content)\n\t\t\t\t\t\t.join(\"\\n\\n\")\n\t\t\t\t: \"No changelog entries found.\";\n\n\t\t// Display in chat\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder(chalk.cyan));\n\t\tthis.ui.addChild(new Text(chalk.bold.cyan(\"What's New\"), 1, 0));\n\t\tthis.ui.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1));\n\t\tthis.chatContainer.addChild(new DynamicBorder(chalk.cyan));\n\t\tthis.ui.requestRender();\n\t}\n\n\tstop(): void {\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = null;\n\t\t}\n\t\tif (this.isInitialized) {\n\t\t\tthis.ui.stop();\n\t\t\tthis.isInitialized = false;\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tui-renderer.d.ts","sourceRoot":"","sources":["../../src/tui/tui-renderer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,EAAiB,MAAM,wBAAwB,CAAC;AAC3F,OAAO,KAAK,EAA6B,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAoB5E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAa9D;;GAEG;AACH,qBAAa,WAAW;IACvB,OAAO,CAAC,EAAE,CAAM;IAChB,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,wBAAwB,CAAY;IAC5C,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,KAAK,CAAQ;IACrB,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,eAAe,CAAC,CAAyB;IACjD,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,mBAAmB,CAAC,CAAa;IACzC,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,iBAAiB,CAAuB;IAChD,OAAO,CAAC,UAAU,CAAuB;IAGzC,OAAO,CAAC,cAAc,CAAgB;IAGtC,OAAO,CAAC,kBAAkB,CAA0C;IAGpE,OAAO,CAAC,YAAY,CAA6C;IAGjE,OAAO,CAAC,gBAAgB,CAA0C;IAGlE,OAAO,CAAC,iBAAiB,CAA2C;IAGpE,OAAO,CAAC,aAAa,CAAuC;IAG5D,OAAO,CAAC,mBAAmB,CAA6C;IAGxE,OAAO,CAAC,aAAa,CAAoB;IAGzC,OAAO,CAAC,kBAAkB,CAAQ;IAGlC,OAAO,CAAC,YAAY,CAAoB;IAGxC,OAAO,CAAC,kBAAkB,CAAS;IAEnC,YACC,KAAK,EAAE,KAAK,EACZ,cAAc,EAAE,cAAc,EAC9B,eAAe,EAAE,eAAe,EAChC,OAAO,EAAE,MAAM,EACf,iBAAiB,GAAE,MAAM,GAAG,IAAW,EACvC,UAAU,GAAE,MAAM,GAAG,IAAW,EAChC,YAAY,GAAE,KAAK,CAAC,GAAG,CAAC,EAAO,EAgF/B;IAEK,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CA+O1B;IAEK,WAAW,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CA+JrE;IAED,OAAO,CAAC,gBAAgB;IAqBxB,qBAAqB,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAoE7C;IAEK,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC,CAOpC;IAED,oBAAoB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAE/C;IAED,OAAO,CAAC,WAAW;IAgBnB,OAAO,CAAC,sBAAsB;IAkB9B,OAAO,CAAC,uBAAuB;IAO/B,OAAO,CAAC,kBAAkB;YA8BZ,UAAU;IAuDxB,OAAO,CAAC,yBAAyB;IAajC,WAAW,IAAI,IAAI,CAGlB;IAED,SAAS,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAKpC;IAED,WAAW,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAKxC;IAED,OAAO,CAAC,oBAAoB;IAqC5B,OAAO,CAAC,oBAAoB;IAQ5B,OAAO,CAAC,qBAAqB;IAkC7B,OAAO,CAAC,qBAAqB;IAQ7B,OAAO,CAAC,iBAAiB;IAoCzB,OAAO,CAAC,iBAAiB;IAQzB,OAAO,CAAC,uBAAuB;IA4E/B,OAAO,CAAC,uBAAuB;YAQjB,iBAAiB;IA2G/B,OAAO,CAAC,iBAAiB;IAQzB,OAAO,CAAC,mBAAmB;IAuB3B,OAAO,CAAC,oBAAoB;IAwE5B,OAAO,CAAC,sBAAsB;IAuB9B,OAAO,CAAC,4BAA4B;IAapC,IAAI,IAAI,IAAI,CASX;CACD","sourcesContent":["import type { Agent, AgentEvent, AgentState, ThinkingLevel } from \"@mariozechner/pi-agent\";\nimport type { AssistantMessage, Message, Model } from \"@mariozechner/pi-ai\";\nimport type { SlashCommand } from \"@mariozechner/pi-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\tContainer,\n\tInput,\n\tLoader,\n\tMarkdown,\n\tProcessTerminal,\n\tSpacer,\n\tText,\n\tTruncatedText,\n\tTUI,\n} from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\nimport { exec } from \"child_process\";\nimport { getChangelogPath, parseChangelog } from \"../changelog.js\";\nimport { exportSessionToHtml } from \"../export-html.js\";\nimport { getApiKeyForModel, getAvailableModels } from \"../model-config.js\";\nimport { listOAuthProviders, login, logout } from \"../oauth/index.js\";\nimport type { SessionManager } from \"../session-manager.js\";\nimport type { SettingsManager } from \"../settings-manager.js\";\nimport { AssistantMessageComponent } from \"./assistant-message.js\";\nimport { CustomEditor } from \"./custom-editor.js\";\nimport { DynamicBorder } from \"./dynamic-border.js\";\nimport { FooterComponent } from \"./footer.js\";\nimport { ModelSelectorComponent } from \"./model-selector.js\";\nimport { OAuthSelectorComponent } from \"./oauth-selector.js\";\nimport { QueueModeSelectorComponent } from \"./queue-mode-selector.js\";\nimport { ThinkingSelectorComponent } from \"./thinking-selector.js\";\nimport { ToolExecutionComponent } from \"./tool-execution.js\";\nimport { UserMessageComponent } from \"./user-message.js\";\nimport { UserMessageSelectorComponent } from \"./user-message-selector.js\";\n\n/**\n * TUI renderer for the coding agent\n */\nexport class TuiRenderer {\n\tprivate ui: TUI;\n\tprivate chatContainer: Container;\n\tprivate pendingMessagesContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate editor: CustomEditor;\n\tprivate editorContainer: Container; // Container to swap between editor and selector\n\tprivate footer: FooterComponent;\n\tprivate agent: Agent;\n\tprivate sessionManager: SessionManager;\n\tprivate settingsManager: SettingsManager;\n\tprivate version: string;\n\tprivate isInitialized = false;\n\tprivate onInputCallback?: (text: string) => void;\n\tprivate loadingAnimation: Loader | null = null;\n\tprivate onInterruptCallback?: () => void;\n\tprivate lastSigintTime = 0;\n\tprivate changelogMarkdown: string | null = null;\n\tprivate newVersion: string | null = null;\n\n\t// Message queueing\n\tprivate queuedMessages: string[] = [];\n\n\t// Streaming message tracking\n\tprivate streamingComponent: AssistantMessageComponent | null = null;\n\n\t// Tool execution tracking: toolCallId -> component\n\tprivate pendingTools = new Map<string, ToolExecutionComponent>();\n\n\t// Thinking level selector\n\tprivate thinkingSelector: ThinkingSelectorComponent | null = null;\n\n\t// Queue mode selector\n\tprivate queueModeSelector: QueueModeSelectorComponent | null = null;\n\n\t// Model selector\n\tprivate modelSelector: ModelSelectorComponent | null = null;\n\n\t// User message selector (for branching)\n\tprivate userMessageSelector: UserMessageSelectorComponent | null = null;\n\n\t// OAuth selector\n\tprivate oauthSelector: any | null = null;\n\n\t// Track if this is the first user message (to skip spacer)\n\tprivate isFirstUserMessage = true;\n\n\t// Model scope for quick cycling\n\tprivate scopedModels: Model<any>[] = [];\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\n\tconstructor(\n\t\tagent: Agent,\n\t\tsessionManager: SessionManager,\n\t\tsettingsManager: SettingsManager,\n\t\tversion: string,\n\t\tchangelogMarkdown: string | null = null,\n\t\tnewVersion: string | null = null,\n\t\tscopedModels: Model<any>[] = [],\n\t) {\n\t\tthis.agent = agent;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.settingsManager = settingsManager;\n\t\tthis.version = version;\n\t\tthis.newVersion = newVersion;\n\t\tthis.changelogMarkdown = changelogMarkdown;\n\t\tthis.scopedModels = scopedModels;\n\t\tthis.ui = new TUI(new ProcessTerminal());\n\t\tthis.chatContainer = new Container();\n\t\tthis.pendingMessagesContainer = new Container();\n\t\tthis.statusContainer = new Container();\n\t\tthis.editor = new CustomEditor();\n\t\tthis.editorContainer = new Container(); // Container to hold editor or selector\n\t\tthis.editorContainer.addChild(this.editor); // Start with editor\n\t\tthis.footer = new FooterComponent(agent.state);\n\n\t\t// Define slash commands\n\t\tconst thinkingCommand: SlashCommand = {\n\t\t\tname: \"thinking\",\n\t\t\tdescription: \"Select reasoning level (opens selector UI)\",\n\t\t};\n\n\t\tconst modelCommand: SlashCommand = {\n\t\t\tname: \"model\",\n\t\t\tdescription: \"Select model (opens selector UI)\",\n\t\t};\n\n\t\tconst exportCommand: SlashCommand = {\n\t\t\tname: \"export\",\n\t\t\tdescription: \"Export session to HTML file\",\n\t\t};\n\n\t\tconst sessionCommand: SlashCommand = {\n\t\t\tname: \"session\",\n\t\t\tdescription: \"Show session info and stats\",\n\t\t};\n\n\t\tconst changelogCommand: SlashCommand = {\n\t\t\tname: \"changelog\",\n\t\t\tdescription: \"Show changelog entries\",\n\t\t};\n\n\t\tconst branchCommand: SlashCommand = {\n\t\t\tname: \"branch\",\n\t\t\tdescription: \"Create a new branch from a previous message\",\n\t\t};\n\n\t\tconst loginCommand: SlashCommand = {\n\t\t\tname: \"login\",\n\t\t\tdescription: \"Login with OAuth provider\",\n\t\t};\n\n\t\tconst logoutCommand: SlashCommand = {\n\t\t\tname: \"logout\",\n\t\t\tdescription: \"Logout from OAuth provider\",\n\t\t};\n\n\t\tconst queueCommand: SlashCommand = {\n\t\t\tname: \"queue\",\n\t\t\tdescription: \"Select message queue mode (opens selector UI)\",\n\t\t};\n\n\t\t// Setup autocomplete for file paths and slash commands\n\t\tconst autocompleteProvider = new CombinedAutocompleteProvider(\n\t\t\t[\n\t\t\t\tthinkingCommand,\n\t\t\t\tmodelCommand,\n\t\t\t\texportCommand,\n\t\t\t\tsessionCommand,\n\t\t\t\tchangelogCommand,\n\t\t\t\tbranchCommand,\n\t\t\t\tloginCommand,\n\t\t\t\tlogoutCommand,\n\t\t\t\tqueueCommand,\n\t\t\t],\n\t\t\tprocess.cwd(),\n\t\t);\n\t\tthis.editor.setAutocompleteProvider(autocompleteProvider);\n\t}\n\n\tasync init(): Promise<void> {\n\t\tif (this.isInitialized) return;\n\n\t\t// Add header with logo and instructions\n\t\tconst logo = chalk.bold.cyan(\"pi\") + chalk.dim(` v${this.version}`);\n\t\tconst instructions =\n\t\t\tchalk.dim(\"esc\") +\n\t\t\tchalk.gray(\" to interrupt\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+c\") +\n\t\t\tchalk.gray(\" to clear\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+c twice\") +\n\t\t\tchalk.gray(\" to exit\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+k\") +\n\t\t\tchalk.gray(\" to delete line\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"shift+tab\") +\n\t\t\tchalk.gray(\" to cycle thinking\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+p\") +\n\t\t\tchalk.gray(\" to cycle models\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"ctrl+o\") +\n\t\t\tchalk.gray(\" to expand tools\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"/\") +\n\t\t\tchalk.gray(\" for commands\") +\n\t\t\t\"\\n\" +\n\t\t\tchalk.dim(\"drop files\") +\n\t\t\tchalk.gray(\" to attach\");\n\t\tconst header = new Text(logo + \"\\n\" + instructions, 1, 0);\n\n\t\t// Setup UI layout\n\t\tthis.ui.addChild(new Spacer(1));\n\t\tthis.ui.addChild(header);\n\t\tthis.ui.addChild(new Spacer(1));\n\n\t\t// Add new version notification if available\n\t\tif (this.newVersion) {\n\t\t\tthis.ui.addChild(new DynamicBorder(chalk.yellow));\n\t\t\tthis.ui.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\tchalk.bold.yellow(\"Update Available\") +\n\t\t\t\t\t\t\"\\n\" +\n\t\t\t\t\t\tchalk.gray(`New version ${this.newVersion} is available. Run: `) +\n\t\t\t\t\t\tchalk.cyan(\"npm install -g @mariozechner/pi-coding-agent\"),\n\t\t\t\t\t1,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t\tthis.ui.addChild(new DynamicBorder(chalk.yellow));\n\t\t}\n\n\t\t// Add changelog if provided\n\t\tif (this.changelogMarkdown) {\n\t\t\tthis.ui.addChild(new DynamicBorder(chalk.cyan));\n\t\t\tthis.ui.addChild(new Text(chalk.bold.cyan(\"What's New\"), 1, 0));\n\t\t\tthis.ui.addChild(new Spacer(1));\n\t\t\tthis.ui.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0));\n\t\t\tthis.ui.addChild(new Spacer(1));\n\t\t\tthis.ui.addChild(new DynamicBorder(chalk.cyan));\n\t\t}\n\n\t\tthis.ui.addChild(this.chatContainer);\n\t\tthis.ui.addChild(this.pendingMessagesContainer);\n\t\tthis.ui.addChild(this.statusContainer);\n\t\tthis.ui.addChild(new Spacer(1));\n\t\tthis.ui.addChild(this.editorContainer); // Use container that can hold editor or selector\n\t\tthis.ui.addChild(this.footer);\n\t\tthis.ui.setFocus(this.editor);\n\n\t\t// Set up custom key handlers on the editor\n\t\tthis.editor.onEscape = () => {\n\t\t\t// Intercept Escape key when processing\n\t\t\tif (this.loadingAnimation && this.onInterruptCallback) {\n\t\t\t\t// Get all queued messages\n\t\t\t\tconst queuedText = this.queuedMessages.join(\"\\n\\n\");\n\n\t\t\t\t// Get current editor text\n\t\t\t\tconst currentText = this.editor.getText();\n\n\t\t\t\t// Combine: queued messages + current editor text\n\t\t\t\tconst combinedText = [queuedText, currentText].filter((t) => t.trim()).join(\"\\n\\n\");\n\n\t\t\t\t// Put back in editor\n\t\t\t\tthis.editor.setText(combinedText);\n\n\t\t\t\t// Clear queued messages\n\t\t\t\tthis.queuedMessages = [];\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\n\t\t\t\t// Clear agent's queue too\n\t\t\t\tthis.agent.clearMessageQueue();\n\n\t\t\t\t// Abort\n\t\t\t\tthis.onInterruptCallback();\n\t\t\t}\n\t\t};\n\n\t\tthis.editor.onCtrlC = () => {\n\t\t\tthis.handleCtrlC();\n\t\t};\n\n\t\tthis.editor.onShiftTab = () => {\n\t\t\tthis.cycleThinkingLevel();\n\t\t};\n\n\t\tthis.editor.onCtrlP = () => {\n\t\t\tthis.cycleModel();\n\t\t};\n\n\t\tthis.editor.onCtrlO = () => {\n\t\t\tthis.toggleToolOutputExpansion();\n\t\t};\n\n\t\t// Handle editor submission\n\t\tthis.editor.onSubmit = async (text: string) => {\n\t\t\ttext = text.trim();\n\t\t\tif (!text) return;\n\n\t\t\t// Check for /thinking command\n\t\t\tif (text === \"/thinking\") {\n\t\t\t\t// Show thinking level selector\n\t\t\t\tthis.showThinkingSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /model command\n\t\t\tif (text === \"/model\") {\n\t\t\t\t// Show model selector\n\t\t\t\tthis.showModelSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /export command\n\t\t\tif (text.startsWith(\"/export\")) {\n\t\t\t\tthis.handleExportCommand(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /session command\n\t\t\tif (text === \"/session\") {\n\t\t\t\tthis.handleSessionCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /changelog command\n\t\t\tif (text === \"/changelog\") {\n\t\t\t\tthis.handleChangelogCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /branch command\n\t\t\tif (text === \"/branch\") {\n\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /login command\n\t\t\tif (text === \"/login\") {\n\t\t\t\tthis.showOAuthSelector(\"login\");\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /logout command\n\t\t\tif (text === \"/logout\") {\n\t\t\t\tthis.showOAuthSelector(\"logout\");\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for /queue command\n\t\t\tif (text === \"/queue\") {\n\t\t\t\tthis.showQueueModeSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Normal message submission - validate model and API key first\n\t\t\tconst currentModel = this.agent.state.model;\n\t\t\tif (!currentModel) {\n\t\t\t\tthis.showError(\n\t\t\t\t\t\"No model selected.\\n\\n\" +\n\t\t\t\t\t\t\"Set an API key (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.)\\n\" +\n\t\t\t\t\t\t\"or create ~/.pi/agent/models.json\\n\\n\" +\n\t\t\t\t\t\t\"Then use /model to select a model.\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Validate API key (async)\n\t\t\tconst apiKey = await getApiKeyForModel(currentModel);\n\t\t\tif (!apiKey) {\n\t\t\t\tthis.showError(\n\t\t\t\t\t`No API key found for ${currentModel.provider}.\\n\\n` +\n\t\t\t\t\t\t`Set the appropriate environment variable or update ~/.pi/agent/models.json`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check if agent is currently streaming\n\t\t\tif (this.agent.state.isStreaming) {\n\t\t\t\t// Queue the message instead of submitting\n\t\t\t\tthis.queuedMessages.push(text);\n\n\t\t\t\t// Queue in agent\n\t\t\t\tawait this.agent.queueMessage({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\n\t\t\t\t// Update pending messages display\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\n\t\t\t\t// Clear editor\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// All good, proceed with submission\n\t\t\tif (this.onInputCallback) {\n\t\t\t\tthis.onInputCallback(text);\n\t\t\t}\n\t\t};\n\n\t\t// Start the UI\n\t\tthis.ui.start();\n\t\tthis.isInitialized = true;\n\t}\n\n\tasync handleEvent(event: AgentEvent, state: AgentState): Promise<void> {\n\t\tif (!this.isInitialized) {\n\t\t\tawait this.init();\n\t\t}\n\n\t\t// Update footer with current stats\n\t\tthis.footer.updateState(state);\n\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\t\t// Show loading animation\n\t\t\t\t// Note: Don't disable submit - we handle queuing in onSubmit callback\n\t\t\t\t// Stop old loader before clearing\n\t\t\t\tif (this.loadingAnimation) {\n\t\t\t\t\tthis.loadingAnimation.stop();\n\t\t\t\t}\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t\tthis.loadingAnimation = new Loader(this.ui, \"Working... (esc to interrupt)\");\n\t\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_start\":\n\t\t\t\tif (event.message.role === \"user\") {\n\t\t\t\t\t// Check if this is a queued message\n\t\t\t\t\tconst userMsg = event.message as any;\n\t\t\t\t\tconst textBlocks = userMsg.content.filter((c: any) => c.type === \"text\");\n\t\t\t\t\tconst messageText = textBlocks.map((c: any) => c.text).join(\"\");\n\n\t\t\t\t\tconst queuedIndex = this.queuedMessages.indexOf(messageText);\n\t\t\t\t\tif (queuedIndex !== -1) {\n\t\t\t\t\t\t// Remove from queued messages\n\t\t\t\t\t\tthis.queuedMessages.splice(queuedIndex, 1);\n\t\t\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\t\t}\n\n\t\t\t\t\t// Show user message immediately and clear editor\n\t\t\t\t\tthis.addMessageToChat(event.message);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t} else if (event.message.role === \"assistant\") {\n\t\t\t\t\t// Create assistant component for streaming\n\t\t\t\t\tthis.streamingComponent = new AssistantMessageComponent();\n\t\t\t\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\t\t\t\tthis.streamingComponent.updateContent(event.message as AssistantMessage);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\t// Update streaming component\n\t\t\t\tif (this.streamingComponent && event.message.role === \"assistant\") {\n\t\t\t\t\tconst assistantMsg = event.message as AssistantMessage;\n\t\t\t\t\tthis.streamingComponent.updateContent(assistantMsg);\n\n\t\t\t\t\t// Create tool execution components as soon as we see tool calls\n\t\t\t\t\tfor (const content of assistantMsg.content) {\n\t\t\t\t\t\tif (content.type === \"toolCall\") {\n\t\t\t\t\t\t\t// Only create if we haven't created it yet\n\t\t\t\t\t\t\tif (!this.pendingTools.has(content.id)) {\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(\"\", 0, 0));\n\t\t\t\t\t\t\t\tconst component = new ToolExecutionComponent(content.name, content.arguments);\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\t\t\t\tthis.pendingTools.set(content.id, component);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Update existing component with latest arguments as they stream\n\t\t\t\t\t\t\t\tconst component = this.pendingTools.get(content.id);\n\t\t\t\t\t\t\t\tif (component) {\n\t\t\t\t\t\t\t\t\tcomponent.updateArgs(content.arguments);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\t// Skip user messages (already shown in message_start)\n\t\t\t\tif (event.message.role === \"user\") {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (this.streamingComponent && event.message.role === \"assistant\") {\n\t\t\t\t\tconst assistantMsg = event.message as AssistantMessage;\n\n\t\t\t\t\t// Update streaming component with final message (includes stopReason)\n\t\t\t\t\tthis.streamingComponent.updateContent(assistantMsg);\n\n\t\t\t\t\t// If message was aborted or errored, mark all pending tool components as failed\n\t\t\t\t\tif (assistantMsg.stopReason === \"aborted\" || assistantMsg.stopReason === \"error\") {\n\t\t\t\t\t\tconst errorMessage =\n\t\t\t\t\t\t\tassistantMsg.stopReason === \"aborted\" ? \"Operation aborted\" : assistantMsg.errorMessage || \"Error\";\n\t\t\t\t\t\tfor (const [toolCallId, component] of this.pendingTools.entries()) {\n\t\t\t\t\t\t\tcomponent.updateResult({\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: errorMessage }],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.pendingTools.clear();\n\t\t\t\t\t}\n\n\t\t\t\t\t// Keep the streaming component - it's now the final assistant message\n\t\t\t\t\tthis.streamingComponent = null;\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\t// Component should already exist from message_update, but create if missing\n\t\t\t\tif (!this.pendingTools.has(event.toolCallId)) {\n\t\t\t\t\tconst component = new ToolExecutionComponent(event.toolName, event.args);\n\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\tthis.pendingTools.set(event.toolCallId, component);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\t// Update the existing tool component with the result\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\t// Convert result to the format expected by updateResult\n\t\t\t\t\tconst resultData =\n\t\t\t\t\t\ttypeof event.result === \"string\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: event.result }],\n\t\t\t\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t\t\t\t\tisError: event.isError,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tcontent: event.result.content,\n\t\t\t\t\t\t\t\t\tdetails: event.result.details,\n\t\t\t\t\t\t\t\t\tisError: event.isError,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\tcomponent.updateResult(resultData);\n\t\t\t\t\tthis.pendingTools.delete(event.toolCallId);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"agent_end\":\n\t\t\t\t// Stop loading animation\n\t\t\t\tif (this.loadingAnimation) {\n\t\t\t\t\tthis.loadingAnimation.stop();\n\t\t\t\t\tthis.loadingAnimation = null;\n\t\t\t\t\tthis.statusContainer.clear();\n\t\t\t\t}\n\t\t\t\tif (this.streamingComponent) {\n\t\t\t\t\tthis.chatContainer.removeChild(this.streamingComponent);\n\t\t\t\t\tthis.streamingComponent = null;\n\t\t\t\t}\n\t\t\t\tthis.pendingTools.clear();\n\t\t\t\t// Note: Don't need to re-enable submit - we never disable it\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate addMessageToChat(message: Message): void {\n\t\tif (message.role === \"user\") {\n\t\t\tconst userMsg = message as any;\n\t\t\t// Extract text content from content blocks\n\t\t\tconst textBlocks = userMsg.content.filter((c: any) => c.type === \"text\");\n\t\t\tconst textContent = textBlocks.map((c: any) => c.text).join(\"\");\n\t\t\tif (textContent) {\n\t\t\t\tconst userComponent = new UserMessageComponent(textContent, this.isFirstUserMessage);\n\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\tthis.isFirstUserMessage = false;\n\t\t\t}\n\t\t} else if (message.role === \"assistant\") {\n\t\t\tconst assistantMsg = message as AssistantMessage;\n\n\t\t\t// Add assistant message component\n\t\t\tconst assistantComponent = new AssistantMessageComponent(assistantMsg);\n\t\t\tthis.chatContainer.addChild(assistantComponent);\n\t\t}\n\t\t// Note: tool calls and results are now handled via tool_execution_start/end events\n\t}\n\n\trenderInitialMessages(state: AgentState): void {\n\t\t// Render all existing messages (for --continue mode)\n\t\t// Reset first user message flag for initial render\n\t\tthis.isFirstUserMessage = true;\n\n\t\t// Update footer with loaded state\n\t\tthis.footer.updateState(state);\n\n\t\t// Update editor border color based on current thinking level\n\t\tthis.updateEditorBorderColor();\n\n\t\t// Render messages\n\t\tfor (let i = 0; i < state.messages.length; i++) {\n\t\t\tconst message = state.messages[i];\n\n\t\t\tif (message.role === \"user\") {\n\t\t\t\tconst userMsg = message as any;\n\t\t\t\tconst textBlocks = userMsg.content.filter((c: any) => c.type === \"text\");\n\t\t\t\tconst textContent = textBlocks.map((c: any) => c.text).join(\"\");\n\t\t\t\tif (textContent) {\n\t\t\t\t\tconst userComponent = new UserMessageComponent(textContent, this.isFirstUserMessage);\n\t\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\t\tthis.isFirstUserMessage = false;\n\t\t\t\t}\n\t\t\t} else if (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\tconst assistantComponent = new AssistantMessageComponent(assistantMsg);\n\t\t\t\tthis.chatContainer.addChild(assistantComponent);\n\n\t\t\t\t// Create tool execution components for any tool calls\n\t\t\t\tfor (const content of assistantMsg.content) {\n\t\t\t\t\tif (content.type === \"toolCall\") {\n\t\t\t\t\t\tconst component = new ToolExecutionComponent(content.name, content.arguments);\n\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\n\t\t\t\t\t\t// If message was aborted/errored, immediately mark tool as failed\n\t\t\t\t\t\tif (assistantMsg.stopReason === \"aborted\" || assistantMsg.stopReason === \"error\") {\n\t\t\t\t\t\t\tconst errorMessage =\n\t\t\t\t\t\t\t\tassistantMsg.stopReason === \"aborted\"\n\t\t\t\t\t\t\t\t\t? \"Operation aborted\"\n\t\t\t\t\t\t\t\t\t: assistantMsg.errorMessage || \"Error\";\n\t\t\t\t\t\t\tcomponent.updateResult({\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: errorMessage }],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Store in map so we can update with results later\n\t\t\t\t\t\t\tthis.pendingTools.set(content.id, component);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (message.role === \"toolResult\") {\n\t\t\t\t// Update existing tool execution component with results\t\t\t\t;\n\t\t\t\tconst component = this.pendingTools.get(message.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({\n\t\t\t\t\t\tcontent: message.content,\n\t\t\t\t\t\tdetails: message.details,\n\t\t\t\t\t\tisError: message.isError,\n\t\t\t\t\t});\n\t\t\t\t\t// Remove from pending map since it's complete\n\t\t\t\t\tthis.pendingTools.delete(message.toolCallId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Clear pending tools after rendering initial messages\n\t\tthis.pendingTools.clear();\n\t\tthis.ui.requestRender();\n\t}\n\n\tasync getUserInput(): Promise<string> {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.onInputCallback = (text: string) => {\n\t\t\t\tthis.onInputCallback = undefined;\n\t\t\t\tresolve(text);\n\t\t\t};\n\t\t});\n\t}\n\n\tsetInterruptCallback(callback: () => void): void {\n\t\tthis.onInterruptCallback = callback;\n\t}\n\n\tprivate handleCtrlC(): void {\n\t\t// Handle Ctrl+C double-press logic\n\t\tconst now = Date.now();\n\t\tconst timeSinceLastCtrlC = now - this.lastSigintTime;\n\n\t\tif (timeSinceLastCtrlC < 500) {\n\t\t\t// Second Ctrl+C within 500ms - exit\n\t\t\tthis.stop();\n\t\t\tprocess.exit(0);\n\t\t} else {\n\t\t\t// First Ctrl+C - clear the editor\n\t\t\tthis.clearEditor();\n\t\t\tthis.lastSigintTime = now;\n\t\t}\n\t}\n\n\tprivate getThinkingBorderColor(level: ThinkingLevel): (str: string) => string {\n\t\t// More thinking = more color (gray → dim colors → bright colors)\n\t\tswitch (level) {\n\t\t\tcase \"off\":\n\t\t\t\treturn chalk.gray;\n\t\t\tcase \"minimal\":\n\t\t\t\treturn chalk.dim.blue;\n\t\t\tcase \"low\":\n\t\t\t\treturn chalk.blue;\n\t\t\tcase \"medium\":\n\t\t\t\treturn chalk.cyan;\n\t\t\tcase \"high\":\n\t\t\t\treturn chalk.magenta;\n\t\t\tdefault:\n\t\t\t\treturn chalk.gray;\n\t\t}\n\t}\n\n\tprivate updateEditorBorderColor(): void {\n\t\tconst level = this.agent.state.thinkingLevel || \"off\";\n\t\tconst color = this.getThinkingBorderColor(level);\n\t\tthis.editor.borderColor = color;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate cycleThinkingLevel(): void {\n\t\t// Only cycle if model supports thinking\n\t\tif (!this.agent.state.model?.reasoning) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(\"Current model does not support thinking\"), 1, 0));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tconst levels: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\t\tconst currentLevel = this.agent.state.thinkingLevel || \"off\";\n\t\tconst currentIndex = levels.indexOf(currentLevel);\n\t\tconst nextIndex = (currentIndex + 1) % levels.length;\n\t\tconst nextLevel = levels[nextIndex];\n\n\t\t// Apply the new thinking level\n\t\tthis.agent.setThinkingLevel(nextLevel);\n\n\t\t// Save thinking level change to session\n\t\tthis.sessionManager.saveThinkingLevelChange(nextLevel);\n\n\t\t// Update border color\n\t\tthis.updateEditorBorderColor();\n\n\t\t// Show brief notification\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Thinking level: ${nextLevel}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async cycleModel(): Promise<void> {\n\t\t// Use scoped models if available, otherwise all available models\n\t\tlet modelsToUse: Model<any>[];\n\t\tif (this.scopedModels.length > 0) {\n\t\t\tmodelsToUse = this.scopedModels;\n\t\t} else {\n\t\t\tconst { models: availableModels, error } = await getAvailableModels();\n\t\t\tif (error) {\n\t\t\t\tthis.showError(`Failed to load models: ${error}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tmodelsToUse = availableModels;\n\t\t}\n\n\t\tif (modelsToUse.length === 0) {\n\t\t\tthis.showError(\"No models available to cycle\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (modelsToUse.length === 1) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(\"Only one model in scope\"), 1, 0));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentModel = this.agent.state.model;\n\t\tlet currentIndex = modelsToUse.findIndex(\n\t\t\t(m) => m.id === currentModel?.id && m.provider === currentModel?.provider,\n\t\t);\n\n\t\t// If current model not in scope, start from first\n\t\tif (currentIndex === -1) {\n\t\t\tcurrentIndex = 0;\n\t\t}\n\n\t\tconst nextIndex = (currentIndex + 1) % modelsToUse.length;\n\t\tconst nextModel = modelsToUse[nextIndex];\n\n\t\t// Validate API key\n\t\tconst apiKey = await getApiKeyForModel(nextModel);\n\t\tif (!apiKey) {\n\t\t\tthis.showError(`No API key for ${nextModel.provider}/${nextModel.id}`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Switch model\n\t\tthis.agent.setModel(nextModel);\n\n\t\t// Show notification\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Switched to ${nextModel.name || nextModel.id}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate toggleToolOutputExpansion(): void {\n\t\tthis.toolOutputExpanded = !this.toolOutputExpanded;\n\n\t\t// Update all tool execution components\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\tchild.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\tclearEditor(): void {\n\t\tthis.editor.setText(\"\");\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowError(errorMessage: string): void {\n\t\t// Show error message in the chat\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(chalk.red(`Error: ${errorMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowWarning(warningMessage: string): void {\n\t\t// Show warning message in the chat\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(chalk.yellow(`Warning: ${warningMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showThinkingSelector(): void {\n\t\t// Create thinking selector with current level\n\t\tthis.thinkingSelector = new ThinkingSelectorComponent(\n\t\t\tthis.agent.state.thinkingLevel,\n\t\t\t(level) => {\n\t\t\t\t// Apply the selected thinking level\n\t\t\t\tthis.agent.setThinkingLevel(level);\n\n\t\t\t\t// Save thinking level change to session\n\t\t\t\tthis.sessionManager.saveThinkingLevelChange(level);\n\n\t\t\t\t// Update border color\n\t\t\t\tthis.updateEditorBorderColor();\n\n\t\t\t\t// Show confirmation message with proper spacing\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tconst confirmText = new Text(chalk.dim(`Thinking level: ${level}`), 1, 0);\n\t\t\t\tthis.chatContainer.addChild(confirmText);\n\n\t\t\t\t// Hide selector and show editor again\n\t\t\t\tthis.hideThinkingSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Just hide the selector\n\t\t\t\tthis.hideThinkingSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t);\n\n\t\t// Replace editor with selector\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.thinkingSelector);\n\t\tthis.ui.setFocus(this.thinkingSelector.getSelectList());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate hideThinkingSelector(): void {\n\t\t// Replace selector with editor in the container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.thinkingSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate showQueueModeSelector(): void {\n\t\t// Create queue mode selector with current mode\n\t\tthis.queueModeSelector = new QueueModeSelectorComponent(\n\t\t\tthis.agent.getQueueMode(),\n\t\t\t(mode) => {\n\t\t\t\t// Apply the selected queue mode\n\t\t\t\tthis.agent.setQueueMode(mode);\n\n\t\t\t\t// Save queue mode to settings\n\t\t\t\tthis.settingsManager.setQueueMode(mode);\n\n\t\t\t\t// Show confirmation message with proper spacing\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tconst confirmText = new Text(chalk.dim(`Queue mode: ${mode}`), 1, 0);\n\t\t\t\tthis.chatContainer.addChild(confirmText);\n\n\t\t\t\t// Hide selector and show editor again\n\t\t\t\tthis.hideQueueModeSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Just hide the selector\n\t\t\t\tthis.hideQueueModeSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t);\n\n\t\t// Replace editor with selector\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.queueModeSelector);\n\t\tthis.ui.setFocus(this.queueModeSelector.getSelectList());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate hideQueueModeSelector(): void {\n\t\t// Replace selector with editor in the container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.queueModeSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate showModelSelector(): void {\n\t\t// Create model selector with current model\n\t\tthis.modelSelector = new ModelSelectorComponent(\n\t\t\tthis.ui,\n\t\t\tthis.agent.state.model,\n\t\t\tthis.settingsManager,\n\t\t\t(model) => {\n\t\t\t\t// Apply the selected model\n\t\t\t\tthis.agent.setModel(model);\n\n\t\t\t\t// Save model change to session\n\t\t\t\tthis.sessionManager.saveModelChange(model.provider, model.id);\n\n\t\t\t\t// Show confirmation message with proper spacing\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tconst confirmText = new Text(chalk.dim(`Model: ${model.id}`), 1, 0);\n\t\t\t\tthis.chatContainer.addChild(confirmText);\n\n\t\t\t\t// Hide selector and show editor again\n\t\t\t\tthis.hideModelSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Just hide the selector\n\t\t\t\tthis.hideModelSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t);\n\n\t\t// Replace editor with selector\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.modelSelector);\n\t\tthis.ui.setFocus(this.modelSelector);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate hideModelSelector(): void {\n\t\t// Replace selector with editor in the container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.modelSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate showUserMessageSelector(): void {\n\t\t// Extract all user messages from the current state\n\t\tconst userMessages: Array<{ index: number; text: string }> = [];\n\n\t\tfor (let i = 0; i < this.agent.state.messages.length; i++) {\n\t\t\tconst message = this.agent.state.messages[i];\n\t\t\tif (message.role === \"user\") {\n\t\t\t\tconst userMsg = message as any;\n\t\t\t\tconst textBlocks = userMsg.content.filter((c: any) => c.type === \"text\");\n\t\t\t\tconst textContent = textBlocks.map((c: any) => c.text).join(\"\");\n\t\t\t\tif (textContent) {\n\t\t\t\t\tuserMessages.push({ index: i, text: textContent });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Don't show selector if there are no messages or only one message\n\t\tif (userMessages.length <= 1) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(\"No messages to branch from\"), 1, 0));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\t// Create user message selector\n\t\tthis.userMessageSelector = new UserMessageSelectorComponent(\n\t\t\tuserMessages,\n\t\t\t(messageIndex) => {\n\t\t\t\t// Get the selected user message text to put in the editor\n\t\t\t\tconst selectedMessage = this.agent.state.messages[messageIndex];\n\t\t\t\tconst selectedUserMsg = selectedMessage as any;\n\t\t\t\tconst textBlocks = selectedUserMsg.content.filter((c: any) => c.type === \"text\");\n\t\t\t\tconst selectedText = textBlocks.map((c: any) => c.text).join(\"\");\n\n\t\t\t\t// Create a branched session with messages UP TO (but not including) the selected message\n\t\t\t\tconst newSessionFile = this.sessionManager.createBranchedSession(this.agent.state, messageIndex - 1);\n\n\t\t\t\t// Set the new session file as active\n\t\t\t\tthis.sessionManager.setSessionFile(newSessionFile);\n\n\t\t\t\t// Truncate messages in agent state to before the selected message\n\t\t\t\tconst truncatedMessages = this.agent.state.messages.slice(0, messageIndex);\n\t\t\t\tthis.agent.replaceMessages(truncatedMessages);\n\n\t\t\t\t// Clear and re-render the chat\n\t\t\t\tthis.chatContainer.clear();\n\t\t\t\tthis.isFirstUserMessage = true;\n\t\t\t\tthis.renderInitialMessages(this.agent.state);\n\n\t\t\t\t// Show confirmation message\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\tnew Text(chalk.dim(`Branched to new session from message ${messageIndex}`), 1, 0),\n\t\t\t\t);\n\n\t\t\t\t// Put the selected message in the editor\n\t\t\t\tthis.editor.setText(selectedText);\n\n\t\t\t\t// Hide selector and show editor again\n\t\t\t\tthis.hideUserMessageSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Just hide the selector\n\t\t\t\tthis.hideUserMessageSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t);\n\n\t\t// Replace editor with selector\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.userMessageSelector);\n\t\tthis.ui.setFocus(this.userMessageSelector.getMessageList());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate hideUserMessageSelector(): void {\n\t\t// Replace selector with editor in the container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.userMessageSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate async showOAuthSelector(mode: \"login\" | \"logout\"): Promise<void> {\n\t\t// For logout mode, filter to only show logged-in providers\n\t\tlet providersToShow: string[] = [];\n\t\tif (mode === \"logout\") {\n\t\t\tconst loggedInProviders = listOAuthProviders();\n\t\t\tif (loggedInProviders.length === 0) {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(\"No OAuth providers logged in. Use /login first.\"), 1, 0));\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprovidersToShow = loggedInProviders;\n\t\t}\n\n\t\t// Create OAuth selector\n\t\tthis.oauthSelector = new OAuthSelectorComponent(\n\t\t\tmode,\n\t\t\tasync (providerId: any) => {\n\t\t\t\t// Hide selector first\n\t\t\t\tthis.hideOAuthSelector();\n\n\t\t\t\tif (mode === \"login\") {\n\t\t\t\t\t// Handle login\n\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Logging in to ${providerId}...`), 1, 0));\n\t\t\t\t\tthis.ui.requestRender();\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait login(\n\t\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\t\t(url: string) => {\n\t\t\t\t\t\t\t\t// Show auth URL to user\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.cyan(\"Opening browser to:\"), 1, 0));\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.cyan(url), 1, 0));\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\t\tnew Text(chalk.yellow(\"Paste the authorization code below:\"), 1, 0),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tthis.ui.requestRender();\n\n\t\t\t\t\t\t\t\t// Open URL in browser\n\t\t\t\t\t\t\t\tconst openCmd =\n\t\t\t\t\t\t\t\t\tprocess.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n\t\t\t\t\t\t\t\texec(`${openCmd} \"${url}\"`);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\t// Prompt for code with a simple Input\n\t\t\t\t\t\t\t\treturn new Promise<string>((resolve) => {\n\t\t\t\t\t\t\t\t\tconst codeInput = new Input();\n\t\t\t\t\t\t\t\t\tcodeInput.onSubmit = () => {\n\t\t\t\t\t\t\t\t\t\tconst code = codeInput.getValue();\n\t\t\t\t\t\t\t\t\t\t// Restore editor\n\t\t\t\t\t\t\t\t\t\tthis.editorContainer.clear();\n\t\t\t\t\t\t\t\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\t\t\t\t\t\t\t\tthis.ui.setFocus(this.editor);\n\t\t\t\t\t\t\t\t\t\tresolve(code);\n\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\tthis.editorContainer.clear();\n\t\t\t\t\t\t\t\t\tthis.editorContainer.addChild(codeInput);\n\t\t\t\t\t\t\t\t\tthis.ui.setFocus(codeInput);\n\t\t\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\t// Success\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.green(`✓ Successfully logged in to ${providerId}`), 1, 0));\n\t\t\t\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Tokens saved to ~/.pi/agent/oauth.json`), 1, 0));\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\tthis.showError(`Login failed: ${error.message}`);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Handle logout\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait logout(providerId);\n\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\tnew Text(chalk.green(`✓ Successfully logged out of ${providerId}`), 1, 0),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\tnew Text(chalk.dim(`Credentials removed from ~/.pi/agent/oauth.json`), 1, 0),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\tthis.showError(`Logout failed: ${error.message}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Cancel - just hide the selector\n\t\t\t\tthis.hideOAuthSelector();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t);\n\n\t\t// Replace editor with selector\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.oauthSelector);\n\t\tthis.ui.setFocus(this.oauthSelector);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate hideOAuthSelector(): void {\n\t\t// Replace selector with editor in the container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.oauthSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate handleExportCommand(text: string): void {\n\t\t// Parse optional filename from command: /export [filename]\n\t\tconst parts = text.split(/\\s+/);\n\t\tconst outputPath = parts.length > 1 ? parts[1] : undefined;\n\n\t\ttry {\n\t\t\t// Export session to HTML\n\t\t\tconst filePath = exportSessionToHtml(this.sessionManager, this.agent.state, outputPath);\n\n\t\t\t// Show success message in chat - matching thinking level style\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(chalk.dim(`Session exported to: ${filePath}`), 1, 0));\n\t\t\tthis.ui.requestRender();\n\t\t} catch (error: any) {\n\t\t\t// Show error message in chat\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Text(chalk.red(`Failed to export session: ${error.message || \"Unknown error\"}`), 1, 0),\n\t\t\t);\n\t\t\tthis.ui.requestRender();\n\t\t}\n\t}\n\n\tprivate handleSessionCommand(): void {\n\t\t// Get session info\n\t\tconst sessionFile = this.sessionManager.getSessionFile();\n\t\tconst state = this.agent.state;\n\n\t\t// Count messages\n\t\tconst userMessages = state.messages.filter((m) => m.role === \"user\").length;\n\t\tconst assistantMessages = state.messages.filter((m) => m.role === \"assistant\").length;\n\t\tconst toolResults = state.messages.filter((m) => m.role === \"toolResult\").length;\n\t\tconst totalMessages = state.messages.length;\n\n\t\t// Count tool calls from assistant messages\n\t\tlet toolCalls = 0;\n\t\tfor (const message of state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttoolCalls += assistantMsg.content.filter((c) => c.type === \"toolCall\").length;\n\t\t\t}\n\t\t}\n\n\t\t// Calculate cumulative usage from all assistant messages (same as footer)\n\t\tlet totalInput = 0;\n\t\tlet totalOutput = 0;\n\t\tlet totalCacheRead = 0;\n\t\tlet totalCacheWrite = 0;\n\t\tlet totalCost = 0;\n\n\t\tfor (const message of state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttotalInput += assistantMsg.usage.input;\n\t\t\t\ttotalOutput += assistantMsg.usage.output;\n\t\t\t\ttotalCacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\ttotalCacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\ttotalCost += assistantMsg.usage.cost.total;\n\t\t\t}\n\t\t}\n\n\t\tconst totalTokens = totalInput + totalOutput + totalCacheRead + totalCacheWrite;\n\n\t\t// Build info text\n\t\tlet info = `${chalk.bold(\"Session Info\")}\\n\\n`;\n\t\tinfo += `${chalk.dim(\"File:\")} ${sessionFile}\\n`;\n\t\tinfo += `${chalk.dim(\"ID:\")} ${this.sessionManager.getSessionId()}\\n\\n`;\n\t\tinfo += `${chalk.bold(\"Messages\")}\\n`;\n\t\tinfo += `${chalk.dim(\"User:\")} ${userMessages}\\n`;\n\t\tinfo += `${chalk.dim(\"Assistant:\")} ${assistantMessages}\\n`;\n\t\tinfo += `${chalk.dim(\"Tool Calls:\")} ${toolCalls}\\n`;\n\t\tinfo += `${chalk.dim(\"Tool Results:\")} ${toolResults}\\n`;\n\t\tinfo += `${chalk.dim(\"Total:\")} ${totalMessages}\\n\\n`;\n\t\tinfo += `${chalk.bold(\"Tokens\")}\\n`;\n\t\tinfo += `${chalk.dim(\"Input:\")} ${totalInput.toLocaleString()}\\n`;\n\t\tinfo += `${chalk.dim(\"Output:\")} ${totalOutput.toLocaleString()}\\n`;\n\t\tif (totalCacheRead > 0) {\n\t\t\tinfo += `${chalk.dim(\"Cache Read:\")} ${totalCacheRead.toLocaleString()}\\n`;\n\t\t}\n\t\tif (totalCacheWrite > 0) {\n\t\t\tinfo += `${chalk.dim(\"Cache Write:\")} ${totalCacheWrite.toLocaleString()}\\n`;\n\t\t}\n\t\tinfo += `${chalk.dim(\"Total:\")} ${totalTokens.toLocaleString()}\\n`;\n\n\t\tif (totalCost > 0) {\n\t\t\tinfo += `\\n${chalk.bold(\"Cost\")}\\n`;\n\t\t\tinfo += `${chalk.dim(\"Total:\")} ${totalCost.toFixed(4)}`;\n\t\t}\n\n\t\t// Show info in chat\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(info, 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleChangelogCommand(): void {\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst allEntries = parseChangelog(changelogPath);\n\n\t\t// Show all entries in reverse order (oldest first, newest last)\n\t\tconst changelogMarkdown =\n\t\t\tallEntries.length > 0\n\t\t\t\t? allEntries\n\t\t\t\t\t\t.reverse()\n\t\t\t\t\t\t.map((e) => e.content)\n\t\t\t\t\t\t.join(\"\\n\\n\")\n\t\t\t\t: \"No changelog entries found.\";\n\n\t\t// Display in chat\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder(chalk.cyan));\n\t\tthis.ui.addChild(new Text(chalk.bold.cyan(\"What's New\"), 1, 0));\n\t\tthis.ui.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1));\n\t\tthis.chatContainer.addChild(new DynamicBorder(chalk.cyan));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate updatePendingMessagesDisplay(): void {\n\t\tthis.pendingMessagesContainer.clear();\n\n\t\tif (this.queuedMessages.length > 0) {\n\t\t\tthis.pendingMessagesContainer.addChild(new Spacer(1));\n\n\t\t\tfor (const message of this.queuedMessages) {\n\t\t\t\tconst queuedText = chalk.dim(\"Queued: \" + message);\n\t\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(queuedText, 1, 0));\n\t\t\t}\n\t\t}\n\t}\n\n\tstop(): void {\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = null;\n\t\t}\n\t\tif (this.isInitialized) {\n\t\t\tthis.ui.stop();\n\t\t\tthis.isInitialized = false;\n\t\t}\n\t}\n}\n"]}
|
package/dist/tui/tui-renderer.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CombinedAutocompleteProvider, Container, Input, Loader, Markdown, ProcessTerminal, Spacer, Text, TUI, } from "@mariozechner/pi-tui";
|
|
1
|
+
import { CombinedAutocompleteProvider, Container, Input, Loader, Markdown, ProcessTerminal, Spacer, Text, TruncatedText, TUI, } from "@mariozechner/pi-tui";
|
|
2
2
|
import chalk from "chalk";
|
|
3
3
|
import { exec } from "child_process";
|
|
4
4
|
import { getChangelogPath, parseChangelog } from "../changelog.js";
|
|
@@ -11,6 +11,7 @@ import { DynamicBorder } from "./dynamic-border.js";
|
|
|
11
11
|
import { FooterComponent } from "./footer.js";
|
|
12
12
|
import { ModelSelectorComponent } from "./model-selector.js";
|
|
13
13
|
import { OAuthSelectorComponent } from "./oauth-selector.js";
|
|
14
|
+
import { QueueModeSelectorComponent } from "./queue-mode-selector.js";
|
|
14
15
|
import { ThinkingSelectorComponent } from "./thinking-selector.js";
|
|
15
16
|
import { ToolExecutionComponent } from "./tool-execution.js";
|
|
16
17
|
import { UserMessageComponent } from "./user-message.js";
|
|
@@ -21,6 +22,7 @@ import { UserMessageSelectorComponent } from "./user-message-selector.js";
|
|
|
21
22
|
export class TuiRenderer {
|
|
22
23
|
ui;
|
|
23
24
|
chatContainer;
|
|
25
|
+
pendingMessagesContainer;
|
|
24
26
|
statusContainer;
|
|
25
27
|
editor;
|
|
26
28
|
editorContainer; // Container to swap between editor and selector
|
|
@@ -36,12 +38,16 @@ export class TuiRenderer {
|
|
|
36
38
|
lastSigintTime = 0;
|
|
37
39
|
changelogMarkdown = null;
|
|
38
40
|
newVersion = null;
|
|
41
|
+
// Message queueing
|
|
42
|
+
queuedMessages = [];
|
|
39
43
|
// Streaming message tracking
|
|
40
44
|
streamingComponent = null;
|
|
41
45
|
// Tool execution tracking: toolCallId -> component
|
|
42
46
|
pendingTools = new Map();
|
|
43
47
|
// Thinking level selector
|
|
44
48
|
thinkingSelector = null;
|
|
49
|
+
// Queue mode selector
|
|
50
|
+
queueModeSelector = null;
|
|
45
51
|
// Model selector
|
|
46
52
|
modelSelector = null;
|
|
47
53
|
// User message selector (for branching)
|
|
@@ -64,6 +70,7 @@ export class TuiRenderer {
|
|
|
64
70
|
this.scopedModels = scopedModels;
|
|
65
71
|
this.ui = new TUI(new ProcessTerminal());
|
|
66
72
|
this.chatContainer = new Container();
|
|
73
|
+
this.pendingMessagesContainer = new Container();
|
|
67
74
|
this.statusContainer = new Container();
|
|
68
75
|
this.editor = new CustomEditor();
|
|
69
76
|
this.editorContainer = new Container(); // Container to hold editor or selector
|
|
@@ -102,6 +109,10 @@ export class TuiRenderer {
|
|
|
102
109
|
name: "logout",
|
|
103
110
|
description: "Logout from OAuth provider",
|
|
104
111
|
};
|
|
112
|
+
const queueCommand = {
|
|
113
|
+
name: "queue",
|
|
114
|
+
description: "Select message queue mode (opens selector UI)",
|
|
115
|
+
};
|
|
105
116
|
// Setup autocomplete for file paths and slash commands
|
|
106
117
|
const autocompleteProvider = new CombinedAutocompleteProvider([
|
|
107
118
|
thinkingCommand,
|
|
@@ -112,6 +123,7 @@ export class TuiRenderer {
|
|
|
112
123
|
branchCommand,
|
|
113
124
|
loginCommand,
|
|
114
125
|
logoutCommand,
|
|
126
|
+
queueCommand,
|
|
115
127
|
], process.cwd());
|
|
116
128
|
this.editor.setAutocompleteProvider(autocompleteProvider);
|
|
117
129
|
}
|
|
@@ -170,6 +182,7 @@ export class TuiRenderer {
|
|
|
170
182
|
this.ui.addChild(new DynamicBorder(chalk.cyan));
|
|
171
183
|
}
|
|
172
184
|
this.ui.addChild(this.chatContainer);
|
|
185
|
+
this.ui.addChild(this.pendingMessagesContainer);
|
|
173
186
|
this.ui.addChild(this.statusContainer);
|
|
174
187
|
this.ui.addChild(new Spacer(1));
|
|
175
188
|
this.ui.addChild(this.editorContainer); // Use container that can hold editor or selector
|
|
@@ -179,6 +192,20 @@ export class TuiRenderer {
|
|
|
179
192
|
this.editor.onEscape = () => {
|
|
180
193
|
// Intercept Escape key when processing
|
|
181
194
|
if (this.loadingAnimation && this.onInterruptCallback) {
|
|
195
|
+
// Get all queued messages
|
|
196
|
+
const queuedText = this.queuedMessages.join("\n\n");
|
|
197
|
+
// Get current editor text
|
|
198
|
+
const currentText = this.editor.getText();
|
|
199
|
+
// Combine: queued messages + current editor text
|
|
200
|
+
const combinedText = [queuedText, currentText].filter((t) => t.trim()).join("\n\n");
|
|
201
|
+
// Put back in editor
|
|
202
|
+
this.editor.setText(combinedText);
|
|
203
|
+
// Clear queued messages
|
|
204
|
+
this.queuedMessages = [];
|
|
205
|
+
this.updatePendingMessagesDisplay();
|
|
206
|
+
// Clear agent's queue too
|
|
207
|
+
this.agent.clearMessageQueue();
|
|
208
|
+
// Abort
|
|
182
209
|
this.onInterruptCallback();
|
|
183
210
|
}
|
|
184
211
|
};
|
|
@@ -249,6 +276,12 @@ export class TuiRenderer {
|
|
|
249
276
|
this.editor.setText("");
|
|
250
277
|
return;
|
|
251
278
|
}
|
|
279
|
+
// Check for /queue command
|
|
280
|
+
if (text === "/queue") {
|
|
281
|
+
this.showQueueModeSelector();
|
|
282
|
+
this.editor.setText("");
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
252
285
|
// Normal message submission - validate model and API key first
|
|
253
286
|
const currentModel = this.agent.state.model;
|
|
254
287
|
if (!currentModel) {
|
|
@@ -265,6 +298,23 @@ export class TuiRenderer {
|
|
|
265
298
|
`Set the appropriate environment variable or update ~/.pi/agent/models.json`);
|
|
266
299
|
return;
|
|
267
300
|
}
|
|
301
|
+
// Check if agent is currently streaming
|
|
302
|
+
if (this.agent.state.isStreaming) {
|
|
303
|
+
// Queue the message instead of submitting
|
|
304
|
+
this.queuedMessages.push(text);
|
|
305
|
+
// Queue in agent
|
|
306
|
+
await this.agent.queueMessage({
|
|
307
|
+
role: "user",
|
|
308
|
+
content: [{ type: "text", text }],
|
|
309
|
+
timestamp: Date.now(),
|
|
310
|
+
});
|
|
311
|
+
// Update pending messages display
|
|
312
|
+
this.updatePendingMessagesDisplay();
|
|
313
|
+
// Clear editor
|
|
314
|
+
this.editor.setText("");
|
|
315
|
+
this.ui.requestRender();
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
268
318
|
// All good, proceed with submission
|
|
269
319
|
if (this.onInputCallback) {
|
|
270
320
|
this.onInputCallback(text);
|
|
@@ -283,7 +333,7 @@ export class TuiRenderer {
|
|
|
283
333
|
switch (event.type) {
|
|
284
334
|
case "agent_start":
|
|
285
335
|
// Show loading animation
|
|
286
|
-
|
|
336
|
+
// Note: Don't disable submit - we handle queuing in onSubmit callback
|
|
287
337
|
// Stop old loader before clearing
|
|
288
338
|
if (this.loadingAnimation) {
|
|
289
339
|
this.loadingAnimation.stop();
|
|
@@ -295,6 +345,16 @@ export class TuiRenderer {
|
|
|
295
345
|
break;
|
|
296
346
|
case "message_start":
|
|
297
347
|
if (event.message.role === "user") {
|
|
348
|
+
// Check if this is a queued message
|
|
349
|
+
const userMsg = event.message;
|
|
350
|
+
const textBlocks = userMsg.content.filter((c) => c.type === "text");
|
|
351
|
+
const messageText = textBlocks.map((c) => c.text).join("");
|
|
352
|
+
const queuedIndex = this.queuedMessages.indexOf(messageText);
|
|
353
|
+
if (queuedIndex !== -1) {
|
|
354
|
+
// Remove from queued messages
|
|
355
|
+
this.queuedMessages.splice(queuedIndex, 1);
|
|
356
|
+
this.updatePendingMessagesDisplay();
|
|
357
|
+
}
|
|
298
358
|
// Show user message immediately and clear editor
|
|
299
359
|
this.addMessageToChat(event.message);
|
|
300
360
|
this.editor.setText("");
|
|
@@ -404,7 +464,7 @@ export class TuiRenderer {
|
|
|
404
464
|
this.streamingComponent = null;
|
|
405
465
|
}
|
|
406
466
|
this.pendingTools.clear();
|
|
407
|
-
|
|
467
|
+
// Note: Don't need to re-enable submit - we never disable it
|
|
408
468
|
this.ui.requestRender();
|
|
409
469
|
break;
|
|
410
470
|
}
|
|
@@ -672,6 +732,38 @@ export class TuiRenderer {
|
|
|
672
732
|
this.thinkingSelector = null;
|
|
673
733
|
this.ui.setFocus(this.editor);
|
|
674
734
|
}
|
|
735
|
+
showQueueModeSelector() {
|
|
736
|
+
// Create queue mode selector with current mode
|
|
737
|
+
this.queueModeSelector = new QueueModeSelectorComponent(this.agent.getQueueMode(), (mode) => {
|
|
738
|
+
// Apply the selected queue mode
|
|
739
|
+
this.agent.setQueueMode(mode);
|
|
740
|
+
// Save queue mode to settings
|
|
741
|
+
this.settingsManager.setQueueMode(mode);
|
|
742
|
+
// Show confirmation message with proper spacing
|
|
743
|
+
this.chatContainer.addChild(new Spacer(1));
|
|
744
|
+
const confirmText = new Text(chalk.dim(`Queue mode: ${mode}`), 1, 0);
|
|
745
|
+
this.chatContainer.addChild(confirmText);
|
|
746
|
+
// Hide selector and show editor again
|
|
747
|
+
this.hideQueueModeSelector();
|
|
748
|
+
this.ui.requestRender();
|
|
749
|
+
}, () => {
|
|
750
|
+
// Just hide the selector
|
|
751
|
+
this.hideQueueModeSelector();
|
|
752
|
+
this.ui.requestRender();
|
|
753
|
+
});
|
|
754
|
+
// Replace editor with selector
|
|
755
|
+
this.editorContainer.clear();
|
|
756
|
+
this.editorContainer.addChild(this.queueModeSelector);
|
|
757
|
+
this.ui.setFocus(this.queueModeSelector.getSelectList());
|
|
758
|
+
this.ui.requestRender();
|
|
759
|
+
}
|
|
760
|
+
hideQueueModeSelector() {
|
|
761
|
+
// Replace selector with editor in the container
|
|
762
|
+
this.editorContainer.clear();
|
|
763
|
+
this.editorContainer.addChild(this.editor);
|
|
764
|
+
this.queueModeSelector = null;
|
|
765
|
+
this.ui.setFocus(this.editor);
|
|
766
|
+
}
|
|
675
767
|
showModelSelector() {
|
|
676
768
|
// Create model selector with current model
|
|
677
769
|
this.modelSelector = new ModelSelectorComponent(this.ui, this.agent.state.model, this.settingsManager, (model) => {
|
|
@@ -963,6 +1055,16 @@ export class TuiRenderer {
|
|
|
963
1055
|
this.chatContainer.addChild(new DynamicBorder(chalk.cyan));
|
|
964
1056
|
this.ui.requestRender();
|
|
965
1057
|
}
|
|
1058
|
+
updatePendingMessagesDisplay() {
|
|
1059
|
+
this.pendingMessagesContainer.clear();
|
|
1060
|
+
if (this.queuedMessages.length > 0) {
|
|
1061
|
+
this.pendingMessagesContainer.addChild(new Spacer(1));
|
|
1062
|
+
for (const message of this.queuedMessages) {
|
|
1063
|
+
const queuedText = chalk.dim("Queued: " + message);
|
|
1064
|
+
this.pendingMessagesContainer.addChild(new TruncatedText(queuedText, 1, 0));
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
966
1068
|
stop() {
|
|
967
1069
|
if (this.loadingAnimation) {
|
|
968
1070
|
this.loadingAnimation.stop();
|