@mariozechner/pi-coding-agent 0.18.1 → 0.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +11 -1
  3. package/dist/core/agent-session.d.ts +43 -3
  4. package/dist/core/agent-session.d.ts.map +1 -1
  5. package/dist/core/agent-session.js +175 -7
  6. package/dist/core/agent-session.js.map +1 -1
  7. package/dist/core/export-html.d.ts.map +1 -1
  8. package/dist/core/export-html.js +10 -1
  9. package/dist/core/export-html.js.map +1 -1
  10. package/dist/core/hooks/types.d.ts +4 -4
  11. package/dist/core/hooks/types.d.ts.map +1 -1
  12. package/dist/core/hooks/types.js.map +1 -1
  13. package/dist/core/session-manager.d.ts +4 -2
  14. package/dist/core/session-manager.d.ts.map +1 -1
  15. package/dist/core/session-manager.js +23 -7
  16. package/dist/core/session-manager.js.map +1 -1
  17. package/dist/core/settings-manager.d.ts +13 -0
  18. package/dist/core/settings-manager.d.ts.map +1 -1
  19. package/dist/core/settings-manager.js +17 -0
  20. package/dist/core/settings-manager.js.map +1 -1
  21. package/dist/index.d.ts +5 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +9 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  26. package/dist/modes/interactive/components/footer.js +27 -4
  27. package/dist/modes/interactive/components/footer.js.map +1 -1
  28. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  29. package/dist/modes/interactive/components/user-message-selector.js +2 -2
  30. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  31. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  32. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  33. package/dist/modes/interactive/interactive-mode.js +37 -1
  34. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  35. package/dist/modes/rpc/rpc-client.d.ts +8 -0
  36. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  37. package/dist/modes/rpc/rpc-client.js +12 -0
  38. package/dist/modes/rpc/rpc-client.js.map +1 -1
  39. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  40. package/dist/modes/rpc/rpc-mode.js +11 -0
  41. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  42. package/dist/modes/rpc/rpc-types.d.ts +18 -1
  43. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  44. package/dist/modes/rpc/rpc-types.js.map +1 -1
  45. package/docs/compaction-new.md +387 -0
  46. package/docs/compaction-strategies.ts +502 -0
  47. package/docs/hooks.md +2 -2
  48. package/docs/rpc.md +62 -0
  49. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"footer.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/footer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAkB,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAAE,UAAU,EAAkB,YAAY,EAAE,KAAK,EAAE,MAAM,IAAI,CAAC;AACrE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C;;GAEG;AACH,MAAM,OAAO,eAAe;IACnB,KAAK,CAAa;IAClB,YAAY,GAA8B,SAAS,CAAC,CAAC,4EAA4E;IACjI,UAAU,GAAqB,IAAI,CAAC;IACpC,cAAc,GAAwB,IAAI,CAAC;IAC3C,kBAAkB,GAAY,IAAI,CAAC;IAE3C,YAAY,KAAiB,EAAE;QAC9B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAAA,CACnB;IAED,qBAAqB,CAAC,OAAgB,EAAQ;QAC7C,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC;IAAA,CAClC;IAED;;;OAGG;IACH,WAAW,CAAC,cAA0B,EAAQ;QAC7C,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WAAW,GAAG,cAAc,GAAG,UAAU,GAAG,cAAc,CAAC;QAEjE,IAAI,SAAiB,CAAC;QACtB,IAAI,WAAW,IAAI,KAAK,EAAE,CAAC;YAC1B,8CAA8C;YAC9C,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,GAAG,cAAc,GAAG,cAAc,CAAC,CAAC;YACpE,SAAS,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAAC;QAC7C,CAAC;aAAM,CAAC;YACP,8BAA8B;YAC9B,MAAM,iBAAiB,GAAG,KAAK,GAAG,cAAc,GAAG,UAAU,CAAC;YAC9D,IAAI,iBAAiB,GAAG,CAAC,EAAE,CAAC;gBAC3B,sFAAsF;gBACtF,MAAM,cAAc,GAAG,SAAS,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC;gBAChE,MAAM,cAAc,GAAG,cAAc,CAAC,SAAS,CAAC,CAAC,EAAE,iBAAiB,CAAC,CAAC;gBACtE,2EAA2E;gBAC3E,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,GAAG,cAAc,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;gBAC3E,SAAS,GAAG,SAAS,GAAG,OAAO,GAAG,cAAc,CAAC;YAClD,CAAC;iBAAM,CAAC;gBACP,yCAAyC;gBACzC,SAAS,GAAG,SAAS,CAAC;YACvB,CAAC;QACF,CAAC;QAED,kCAAkC;QAClC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC;IAAA,CAC1D;CACD","sourcesContent":["import type { AgentState } from \"@mariozechner/pi-agent-core\";\nimport type { AssistantMessage } from \"@mariozechner/pi-ai\";\nimport { type Component, visibleWidth } from \"@mariozechner/pi-tui\";\nimport { existsSync, type FSWatcher, readFileSync, watch } from \"fs\";\nimport { join } from \"path\";\nimport { isModelUsingOAuth } from \"../../../core/model-config.js\";\nimport { theme } from \"../theme/theme.js\";\n\n/**\n * Footer component that shows pwd, token stats, and context usage\n */\nexport class FooterComponent implements Component {\n\tprivate state: AgentState;\n\tprivate cachedBranch: string | null | undefined = undefined; // undefined = not checked yet, null = not in git repo, string = branch name\n\tprivate gitWatcher: FSWatcher | null = null;\n\tprivate onBranchChange: (() => void) | null = null;\n\tprivate autoCompactEnabled: boolean = true;\n\n\tconstructor(state: AgentState) {\n\t\tthis.state = state;\n\t}\n\n\tsetAutoCompactEnabled(enabled: boolean): void {\n\t\tthis.autoCompactEnabled = enabled;\n\t}\n\n\t/**\n\t * Set up a file watcher on .git/HEAD to detect branch changes.\n\t * Call the provided callback when branch changes.\n\t */\n\twatchBranch(onBranchChange: () => void): void {\n\t\tthis.onBranchChange = onBranchChange;\n\t\tthis.setupGitWatcher();\n\t}\n\n\tprivate setupGitWatcher(): void {\n\t\t// Clean up existing watcher\n\t\tif (this.gitWatcher) {\n\t\t\tthis.gitWatcher.close();\n\t\t\tthis.gitWatcher = null;\n\t\t}\n\n\t\tconst gitHeadPath = join(process.cwd(), \".git\", \"HEAD\");\n\t\tif (!existsSync(gitHeadPath)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.gitWatcher = watch(gitHeadPath, () => {\n\t\t\t\tthis.cachedBranch = undefined; // Invalidate cache\n\t\t\t\tif (this.onBranchChange) {\n\t\t\t\t\tthis.onBranchChange();\n\t\t\t\t}\n\t\t\t});\n\t\t} catch {\n\t\t\t// Silently fail if we can't watch\n\t\t}\n\t}\n\n\t/**\n\t * Clean up the file watcher\n\t */\n\tdispose(): void {\n\t\tif (this.gitWatcher) {\n\t\t\tthis.gitWatcher.close();\n\t\t\tthis.gitWatcher = null;\n\t\t}\n\t}\n\n\tupdateState(state: AgentState): void {\n\t\tthis.state = state;\n\t}\n\n\tinvalidate(): void {\n\t\t// Invalidate cached branch so it gets re-read on next render\n\t\tthis.cachedBranch = undefined;\n\t}\n\n\t/**\n\t * Get current git branch by reading .git/HEAD directly.\n\t * Returns null if not in a git repo, branch name otherwise.\n\t */\n\tprivate getCurrentBranch(): string | null {\n\t\t// Return cached value if available\n\t\tif (this.cachedBranch !== undefined) {\n\t\t\treturn this.cachedBranch;\n\t\t}\n\n\t\ttry {\n\t\t\tconst gitHeadPath = join(process.cwd(), \".git\", \"HEAD\");\n\t\t\tconst content = readFileSync(gitHeadPath, \"utf8\").trim();\n\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\t// Normal branch: extract branch name\n\t\t\t\tthis.cachedBranch = content.slice(16);\n\t\t\t} else {\n\t\t\t\t// Detached HEAD state\n\t\t\t\tthis.cachedBranch = \"detached\";\n\t\t\t}\n\t\t} catch {\n\t\t\t// Not in a git repo or error reading file\n\t\t\tthis.cachedBranch = null;\n\t\t}\n\n\t\treturn this.cachedBranch;\n\t}\n\n\trender(width: number): string[] {\n\t\t// Calculate cumulative usage from all assistant messages\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 this.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\t// Get last assistant message for context percentage calculation (skip aborted messages)\n\t\tconst lastAssistantMessage = this.state.messages\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.find((m) => m.role === \"assistant\" && m.stopReason !== \"aborted\") as AssistantMessage | undefined;\n\n\t\t// Calculate context percentage from last message (input + output + cacheRead + cacheWrite)\n\t\tconst contextTokens = lastAssistantMessage\n\t\t\t? lastAssistantMessage.usage.input +\n\t\t\t\tlastAssistantMessage.usage.output +\n\t\t\t\tlastAssistantMessage.usage.cacheRead +\n\t\t\t\tlastAssistantMessage.usage.cacheWrite\n\t\t\t: 0;\n\t\tconst contextWindow = this.state.model?.contextWindow || 0;\n\t\tconst contextPercentValue = contextWindow > 0 ? (contextTokens / contextWindow) * 100 : 0;\n\t\tconst contextPercent = contextPercentValue.toFixed(1);\n\n\t\t// Format token counts (similar to web-ui)\n\t\tconst formatTokens = (count: number): string => {\n\t\t\tif (count < 1000) return count.toString();\n\t\t\tif (count < 10000) return (count / 1000).toFixed(1) + \"k\";\n\t\t\tif (count < 1000000) return Math.round(count / 1000) + \"k\";\n\t\t\tif (count < 10000000) return (count / 1000000).toFixed(1) + \"M\";\n\t\t\treturn Math.round(count / 1000000) + \"M\";\n\t\t};\n\n\t\t// Replace home directory with ~\n\t\tlet pwd = process.cwd();\n\t\tconst home = process.env.HOME || process.env.USERPROFILE;\n\t\tif (home && pwd.startsWith(home)) {\n\t\t\tpwd = \"~\" + pwd.slice(home.length);\n\t\t}\n\n\t\t// Add git branch if available\n\t\tconst branch = this.getCurrentBranch();\n\t\tif (branch) {\n\t\t\tpwd = `${pwd} (${branch})`;\n\t\t}\n\n\t\t// Truncate path if too long to fit width\n\t\tconst maxPathLength = Math.max(20, width - 10); // Leave some margin\n\t\tif (pwd.length > maxPathLength) {\n\t\t\tconst start = pwd.slice(0, Math.floor(maxPathLength / 2) - 2);\n\t\t\tconst end = pwd.slice(-(Math.floor(maxPathLength / 2) - 1));\n\t\t\tpwd = `${start}...${end}`;\n\t\t}\n\n\t\t// Build stats line\n\t\tconst statsParts = [];\n\t\tif (totalInput) statsParts.push(`↑${formatTokens(totalInput)}`);\n\t\tif (totalOutput) statsParts.push(`↓${formatTokens(totalOutput)}`);\n\t\tif (totalCacheRead) statsParts.push(`R${formatTokens(totalCacheRead)}`);\n\t\tif (totalCacheWrite) statsParts.push(`W${formatTokens(totalCacheWrite)}`);\n\n\t\t// Show cost with \"(sub)\" indicator if using OAuth subscription\n\t\tconst usingSubscription = this.state.model ? isModelUsingOAuth(this.state.model) : false;\n\t\tif (totalCost || usingSubscription) {\n\t\t\tconst costStr = `$${totalCost.toFixed(3)}${usingSubscription ? \" (sub)\" : \"\"}`;\n\t\t\tstatsParts.push(costStr);\n\t\t}\n\n\t\t// Colorize context percentage based on usage\n\t\tlet contextPercentStr: string;\n\t\tconst autoIndicator = this.autoCompactEnabled ? \" (auto)\" : \"\";\n\t\tconst contextPercentDisplay = `${contextPercent}%/${formatTokens(contextWindow)}${autoIndicator}`;\n\t\tif (contextPercentValue > 90) {\n\t\t\tcontextPercentStr = theme.fg(\"error\", contextPercentDisplay);\n\t\t} else if (contextPercentValue > 70) {\n\t\t\tcontextPercentStr = theme.fg(\"warning\", contextPercentDisplay);\n\t\t} else {\n\t\t\tcontextPercentStr = contextPercentDisplay;\n\t\t}\n\t\tstatsParts.push(contextPercentStr);\n\n\t\tlet statsLeft = statsParts.join(\" \");\n\n\t\t// Add model name on the right side, plus thinking level if model supports it\n\t\tconst modelName = this.state.model?.id || \"no-model\";\n\n\t\t// Add thinking level hint if model supports reasoning and thinking is enabled\n\t\tlet rightSide = modelName;\n\t\tif (this.state.model?.reasoning) {\n\t\t\tconst thinkingLevel = this.state.thinkingLevel || \"off\";\n\t\t\tif (thinkingLevel !== \"off\") {\n\t\t\t\trightSide = `${modelName} • ${thinkingLevel}`;\n\t\t\t}\n\t\t}\n\n\t\tlet statsLeftWidth = visibleWidth(statsLeft);\n\t\tconst rightSideWidth = visibleWidth(rightSide);\n\n\t\t// If statsLeft is too wide, truncate it\n\t\tif (statsLeftWidth > width) {\n\t\t\t// Truncate statsLeft to fit width (no room for right side)\n\t\t\tconst plainStatsLeft = statsLeft.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n\t\t\tstatsLeft = plainStatsLeft.substring(0, width - 3) + \"...\";\n\t\t\tstatsLeftWidth = visibleWidth(statsLeft);\n\t\t}\n\n\t\t// Calculate available space for padding (minimum 2 spaces between stats and model)\n\t\tconst minPadding = 2;\n\t\tconst totalNeeded = statsLeftWidth + minPadding + rightSideWidth;\n\n\t\tlet statsLine: string;\n\t\tif (totalNeeded <= width) {\n\t\t\t// Both fit - add padding to right-align model\n\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - rightSideWidth);\n\t\t\tstatsLine = statsLeft + padding + rightSide;\n\t\t} else {\n\t\t\t// Need to truncate right side\n\t\t\tconst availableForRight = width - statsLeftWidth - minPadding;\n\t\t\tif (availableForRight > 3) {\n\t\t\t\t// Truncate to fit (strip ANSI codes for length calculation, then truncate raw string)\n\t\t\t\tconst plainRightSide = rightSide.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n\t\t\t\tconst truncatedPlain = plainRightSide.substring(0, availableForRight);\n\t\t\t\t// For simplicity, just use plain truncated version (loses color, but fits)\n\t\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - truncatedPlain.length);\n\t\t\t\tstatsLine = statsLeft + padding + truncatedPlain;\n\t\t\t} else {\n\t\t\t\t// Not enough space for right side at all\n\t\t\t\tstatsLine = statsLeft;\n\t\t\t}\n\t\t}\n\n\t\t// Return two lines: pwd and stats\n\t\treturn [theme.fg(\"dim\", pwd), theme.fg(\"dim\", statsLine)];\n\t}\n}\n"]}
1
+ {"version":3,"file":"footer.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/footer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAkB,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAAE,UAAU,EAAkB,YAAY,EAAE,KAAK,EAAE,MAAM,IAAI,CAAC;AACrE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C;;;GAGG;AACH,SAAS,eAA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AU,CAAC;YAC9D,IAAI,iBAAiB,GAAG,CAAC,EAAE,CAAC;gBAC3B,sFAAsF;gBACtF,MAAM,cAAc,GAAG,SAAS,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC;gBAChE,MAAM,cAAc,GAAG,cAAc,CAAC,SAAS,CAAC,CAAC,EAAE,iBAAiB,CAAC,CAAC;gBACtE,2EAA2E;gBAC3E,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,GAAG,cAAc,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;gBAC3E,SAAS,GAAG,SAAS,GAAG,OAAO,GAAG,cAAc,CAAC;YAClD,CAAC;iBAAM,CAAC;gBACP,yCAAyC;gBACzC,SAAS,GAAG,SAAS,CAAC;YACvB,CAAC;QACF,CAAC;QAED,kCAAkC;QAClC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC;IAAA,CAC1D;CACD","sourcesContent":["import type { AgentState } from \"@mariozechner/pi-agent-core\";\nimport type { AssistantMessage } from \"@mariozechner/pi-ai\";\nimport { type Component, visibleWidth } from \"@mariozechner/pi-tui\";\nimport { existsSync, type FSWatcher, readFileSync, watch } from \"fs\";\nimport { dirname, join } from \"path\";\nimport { isModelUsingOAuth } from \"../../../core/model-config.js\";\nimport { theme } from \"../theme/theme.js\";\n\n/**\n * Find the git root directory by walking up from cwd.\n * Returns the path to .git/HEAD if found, null otherwise.\n */\nfunction findGitHeadPath(): string | null {\n\tlet dir = process.cwd();\n\twhile (true) {\n\t\tconst gitHeadPath = join(dir, \".git\", \"HEAD\");\n\t\tif (existsSync(gitHeadPath)) {\n\t\t\treturn gitHeadPath;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\t// Reached filesystem root\n\t\t\treturn null;\n\t\t}\n\t\tdir = parent;\n\t}\n}\n\n/**\n * Footer component that shows pwd, token stats, and context usage\n */\nexport class FooterComponent implements Component {\n\tprivate state: AgentState;\n\tprivate cachedBranch: string | null | undefined = undefined; // undefined = not checked yet, null = not in git repo, string = branch name\n\tprivate gitWatcher: FSWatcher | null = null;\n\tprivate onBranchChange: (() => void) | null = null;\n\tprivate autoCompactEnabled: boolean = true;\n\n\tconstructor(state: AgentState) {\n\t\tthis.state = state;\n\t}\n\n\tsetAutoCompactEnabled(enabled: boolean): void {\n\t\tthis.autoCompactEnabled = enabled;\n\t}\n\n\t/**\n\t * Set up a file watcher on .git/HEAD to detect branch changes.\n\t * Call the provided callback when branch changes.\n\t */\n\twatchBranch(onBranchChange: () => void): void {\n\t\tthis.onBranchChange = onBranchChange;\n\t\tthis.setupGitWatcher();\n\t}\n\n\tprivate setupGitWatcher(): void {\n\t\t// Clean up existing watcher\n\t\tif (this.gitWatcher) {\n\t\t\tthis.gitWatcher.close();\n\t\t\tthis.gitWatcher = null;\n\t\t}\n\n\t\tconst gitHeadPath = findGitHeadPath();\n\t\tif (!gitHeadPath) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.gitWatcher = watch(gitHeadPath, () => {\n\t\t\t\tthis.cachedBranch = undefined; // Invalidate cache\n\t\t\t\tif (this.onBranchChange) {\n\t\t\t\t\tthis.onBranchChange();\n\t\t\t\t}\n\t\t\t});\n\t\t} catch {\n\t\t\t// Silently fail if we can't watch\n\t\t}\n\t}\n\n\t/**\n\t * Clean up the file watcher\n\t */\n\tdispose(): void {\n\t\tif (this.gitWatcher) {\n\t\t\tthis.gitWatcher.close();\n\t\t\tthis.gitWatcher = null;\n\t\t}\n\t}\n\n\tupdateState(state: AgentState): void {\n\t\tthis.state = state;\n\t}\n\n\tinvalidate(): void {\n\t\t// Invalidate cached branch so it gets re-read on next render\n\t\tthis.cachedBranch = undefined;\n\t}\n\n\t/**\n\t * Get current git branch by reading .git/HEAD directly.\n\t * Returns null if not in a git repo, branch name otherwise.\n\t */\n\tprivate getCurrentBranch(): string | null {\n\t\t// Return cached value if available\n\t\tif (this.cachedBranch !== undefined) {\n\t\t\treturn this.cachedBranch;\n\t\t}\n\n\t\ttry {\n\t\t\tconst gitHeadPath = findGitHeadPath();\n\t\t\tif (!gitHeadPath) {\n\t\t\t\tthis.cachedBranch = null;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst content = readFileSync(gitHeadPath, \"utf8\").trim();\n\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\t// Normal branch: extract branch name\n\t\t\t\tthis.cachedBranch = content.slice(16);\n\t\t\t} else {\n\t\t\t\t// Detached HEAD state\n\t\t\t\tthis.cachedBranch = \"detached\";\n\t\t\t}\n\t\t} catch {\n\t\t\t// Not in a git repo or error reading file\n\t\t\tthis.cachedBranch = null;\n\t\t}\n\n\t\treturn this.cachedBranch;\n\t}\n\n\trender(width: number): string[] {\n\t\t// Calculate cumulative usage from all assistant messages\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 this.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\t// Get last assistant message for context percentage calculation (skip aborted messages)\n\t\tconst lastAssistantMessage = this.state.messages\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.find((m) => m.role === \"assistant\" && m.stopReason !== \"aborted\") as AssistantMessage | undefined;\n\n\t\t// Calculate context percentage from last message (input + output + cacheRead + cacheWrite)\n\t\tconst contextTokens = lastAssistantMessage\n\t\t\t? lastAssistantMessage.usage.input +\n\t\t\t\tlastAssistantMessage.usage.output +\n\t\t\t\tlastAssistantMessage.usage.cacheRead +\n\t\t\t\tlastAssistantMessage.usage.cacheWrite\n\t\t\t: 0;\n\t\tconst contextWindow = this.state.model?.contextWindow || 0;\n\t\tconst contextPercentValue = contextWindow > 0 ? (contextTokens / contextWindow) * 100 : 0;\n\t\tconst contextPercent = contextPercentValue.toFixed(1);\n\n\t\t// Format token counts (similar to web-ui)\n\t\tconst formatTokens = (count: number): string => {\n\t\t\tif (count < 1000) return count.toString();\n\t\t\tif (count < 10000) return (count / 1000).toFixed(1) + \"k\";\n\t\t\tif (count < 1000000) return Math.round(count / 1000) + \"k\";\n\t\t\tif (count < 10000000) return (count / 1000000).toFixed(1) + \"M\";\n\t\t\treturn Math.round(count / 1000000) + \"M\";\n\t\t};\n\n\t\t// Replace home directory with ~\n\t\tlet pwd = process.cwd();\n\t\tconst home = process.env.HOME || process.env.USERPROFILE;\n\t\tif (home && pwd.startsWith(home)) {\n\t\t\tpwd = \"~\" + pwd.slice(home.length);\n\t\t}\n\n\t\t// Add git branch if available\n\t\tconst branch = this.getCurrentBranch();\n\t\tif (branch) {\n\t\t\tpwd = `${pwd} (${branch})`;\n\t\t}\n\n\t\t// Truncate path if too long to fit width\n\t\tconst maxPathLength = Math.max(20, width - 10); // Leave some margin\n\t\tif (pwd.length > maxPathLength) {\n\t\t\tconst start = pwd.slice(0, Math.floor(maxPathLength / 2) - 2);\n\t\t\tconst end = pwd.slice(-(Math.floor(maxPathLength / 2) - 1));\n\t\t\tpwd = `${start}...${end}`;\n\t\t}\n\n\t\t// Build stats line\n\t\tconst statsParts = [];\n\t\tif (totalInput) statsParts.push(`↑${formatTokens(totalInput)}`);\n\t\tif (totalOutput) statsParts.push(`↓${formatTokens(totalOutput)}`);\n\t\tif (totalCacheRead) statsParts.push(`R${formatTokens(totalCacheRead)}`);\n\t\tif (totalCacheWrite) statsParts.push(`W${formatTokens(totalCacheWrite)}`);\n\n\t\t// Show cost with \"(sub)\" indicator if using OAuth subscription\n\t\tconst usingSubscription = this.state.model ? isModelUsingOAuth(this.state.model) : false;\n\t\tif (totalCost || usingSubscription) {\n\t\t\tconst costStr = `$${totalCost.toFixed(3)}${usingSubscription ? \" (sub)\" : \"\"}`;\n\t\t\tstatsParts.push(costStr);\n\t\t}\n\n\t\t// Colorize context percentage based on usage\n\t\tlet contextPercentStr: string;\n\t\tconst autoIndicator = this.autoCompactEnabled ? \" (auto)\" : \"\";\n\t\tconst contextPercentDisplay = `${contextPercent}%/${formatTokens(contextWindow)}${autoIndicator}`;\n\t\tif (contextPercentValue > 90) {\n\t\t\tcontextPercentStr = theme.fg(\"error\", contextPercentDisplay);\n\t\t} else if (contextPercentValue > 70) {\n\t\t\tcontextPercentStr = theme.fg(\"warning\", contextPercentDisplay);\n\t\t} else {\n\t\t\tcontextPercentStr = contextPercentDisplay;\n\t\t}\n\t\tstatsParts.push(contextPercentStr);\n\n\t\tlet statsLeft = statsParts.join(\" \");\n\n\t\t// Add model name on the right side, plus thinking level if model supports it\n\t\tconst modelName = this.state.model?.id || \"no-model\";\n\n\t\t// Add thinking level hint if model supports reasoning and thinking is enabled\n\t\tlet rightSide = modelName;\n\t\tif (this.state.model?.reasoning) {\n\t\t\tconst thinkingLevel = this.state.thinkingLevel || \"off\";\n\t\t\tif (thinkingLevel !== \"off\") {\n\t\t\t\trightSide = `${modelName} • ${thinkingLevel}`;\n\t\t\t}\n\t\t}\n\n\t\tlet statsLeftWidth = visibleWidth(statsLeft);\n\t\tconst rightSideWidth = visibleWidth(rightSide);\n\n\t\t// If statsLeft is too wide, truncate it\n\t\tif (statsLeftWidth > width) {\n\t\t\t// Truncate statsLeft to fit width (no room for right side)\n\t\t\tconst plainStatsLeft = statsLeft.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n\t\t\tstatsLeft = plainStatsLeft.substring(0, width - 3) + \"...\";\n\t\t\tstatsLeftWidth = visibleWidth(statsLeft);\n\t\t}\n\n\t\t// Calculate available space for padding (minimum 2 spaces between stats and model)\n\t\tconst minPadding = 2;\n\t\tconst totalNeeded = statsLeftWidth + minPadding + rightSideWidth;\n\n\t\tlet statsLine: string;\n\t\tif (totalNeeded <= width) {\n\t\t\t// Both fit - add padding to right-align model\n\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - rightSideWidth);\n\t\t\tstatsLine = statsLeft + padding + rightSide;\n\t\t} else {\n\t\t\t// Need to truncate right side\n\t\t\tconst availableForRight = width - statsLeftWidth - minPadding;\n\t\t\tif (availableForRight > 3) {\n\t\t\t\t// Truncate to fit (strip ANSI codes for length calculation, then truncate raw string)\n\t\t\t\tconst plainRightSide = rightSide.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n\t\t\t\tconst truncatedPlain = plainRightSide.substring(0, availableForRight);\n\t\t\t\t// For simplicity, just use plain truncated version (loses color, but fits)\n\t\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - truncatedPlain.length);\n\t\t\t\tstatsLine = statsLeft + padding + truncatedPlain;\n\t\t\t} else {\n\t\t\t\t// Not enough space for right side at all\n\t\t\t\tstatsLine = statsLeft;\n\t\t\t}\n\t\t}\n\n\t\t// Return two lines: pwd and stats\n\t\treturn [theme.fg(\"dim\", pwd), theme.fg(\"dim\", statsLine)];\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"user-message-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/user-message-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,SAAS,EAAiC,MAAM,sBAAsB,CAAC;AAIhG,UAAU,eAAe;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,cAAM,eAAgB,YAAW,SAAS;IACzC,OAAO,CAAC,QAAQ,CAAyB;IACzC,OAAO,CAAC,aAAa,CAAa;IAC3B,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,IAAI,CAAC;IAC1C,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IAC7B,OAAO,CAAC,UAAU,CAAc;IAEhC,YAAY,QAAQ,EAAE,eAAe,EAAE,EAKtC;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CA8C9B;IAED,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CA4BjC;CACD;AAED;;GAEG;AACH,qBAAa,4BAA6B,SAAQ,SAAS;IAC1D,OAAO,CAAC,WAAW,CAAkB;IAErC,YAAY,QAAQ,EAAE,eAAe,EAAE,EAAE,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,EA0BtG;IAED,cAAc,IAAI,eAAe,CAEhC;CACD","sourcesContent":["import { type Component, Container, Spacer, Text, truncateToWidth } from \"@mariozechner/pi-tui\";\nimport { theme } from \"../theme/theme.js\";\nimport { DynamicBorder } from \"./dynamic-border.js\";\n\ninterface UserMessageItem {\n\tindex: number; // Index in the full messages array\n\ttext: string; // The message text\n\ttimestamp?: string; // Optional timestamp if available\n}\n\n/**\n * Custom user message list component with selection\n */\nclass UserMessageList implements Component {\n\tprivate messages: UserMessageItem[] = [];\n\tprivate selectedIndex: number = 0;\n\tpublic onSelect?: (messageIndex: number) => void;\n\tpublic onCancel?: () => void;\n\tprivate maxVisible: number = 10; // Max messages visible\n\n\tconstructor(messages: UserMessageItem[]) {\n\t\t// Store messages in chronological order (oldest to newest)\n\t\tthis.messages = messages;\n\t\t// Start with the last (most recent) message selected\n\t\tthis.selectedIndex = Math.max(0, messages.length - 1);\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached state to invalidate currently\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\tif (this.messages.length === 0) {\n\t\t\tlines.push(theme.fg(\"muted\", \" No user messages found\"));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range with scrolling\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.messages.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.messages.length);\n\n\t\t// Render visible messages (2 lines per message + blank line)\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst message = this.messages[i];\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\t// Normalize message to single line\n\t\t\tconst normalizedMessage = message.text.replace(/\\n/g, \" \").trim();\n\n\t\t\t// First line: cursor + message\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\t\t\tconst maxMsgWidth = width - 2; // Account for cursor (2 chars)\n\t\t\tconst truncatedMsg = truncateToWidth(normalizedMessage, maxMsgWidth);\n\t\t\tconst messageLine = cursor + (isSelected ? theme.bold(truncatedMsg) : truncatedMsg);\n\n\t\t\tlines.push(messageLine);\n\n\t\t\t// Second line: metadata (position in history)\n\t\t\tconst position = i + 1;\n\t\t\tconst metadata = ` Message ${position} of ${this.messages.length}`;\n\t\t\tconst metadataLine = theme.fg(\"muted\", metadata);\n\t\t\tlines.push(metadataLine);\n\t\t\tlines.push(\"\"); // Blank line between messages\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.messages.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.messages.length})`);\n\t\t\tlines.push(scrollInfo);\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\t// Up arrow - go to previous (older) message, wrap to bottom when at top\n\t\tif (keyData === \"\\x1b[A\") {\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.messages.length - 1 : this.selectedIndex - 1;\n\t\t}\n\t\t// Down arrow - go to next (newer) message, wrap to top when at bottom\n\t\telse if (keyData === \"\\x1b[B\") {\n\t\t\tthis.selectedIndex = this.selectedIndex === this.messages.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t}\n\t\t// Enter - select message and branch\n\t\telse if (keyData === \"\\r\") {\n\t\t\tconst selected = this.messages[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.index);\n\t\t\t}\n\t\t}\n\t\t// Escape - cancel\n\t\telse if (keyData === \"\\x1b\") {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t\t// Ctrl+C - cancel\n\t\telse if (keyData === \"\\x03\") {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Component that renders a user message selector for branching\n */\nexport class UserMessageSelectorComponent extends Container {\n\tprivate messageList: UserMessageList;\n\n\tconstructor(messages: UserMessageItem[], onSelect: (messageIndex: number) => void, onCancel: () => void) {\n\t\tsuper();\n\n\t\t// Add header\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.bold(\"Branch from Message\"), 1, 0));\n\t\tthis.addChild(new Text(theme.fg(\"muted\", \"Select a message to create a new branch from that point\"), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create message list\n\t\tthis.messageList = new UserMessageList(messages);\n\t\tthis.messageList.onSelect = onSelect;\n\t\tthis.messageList.onCancel = onCancel;\n\n\t\tthis.addChild(this.messageList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Auto-cancel if no messages or only one message\n\t\tif (messages.length <= 1) {\n\t\t\tsetTimeout(() => onCancel(), 100);\n\t\t}\n\t}\n\n\tgetMessageList(): UserMessageList {\n\t\treturn this.messageList;\n\t}\n}\n"]}
1
+ {"version":3,"file":"user-message-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/user-message-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,SAAS,EAAiC,MAAM,sBAAsB,CAAC;AAIhG,UAAU,eAAe;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,cAAM,eAAgB,YAAW,SAAS;IACzC,OAAO,CAAC,QAAQ,CAAyB;IACzC,OAAO,CAAC,aAAa,CAAa;IAC3B,QAAQ,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,IAAI,CAAC;IAC1C,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IAC7B,OAAO,CAAC,UAAU,CAAc;IAEhC,YAAY,QAAQ,EAAE,eAAe,EAAE,EAKtC;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CA8C9B;IAED,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CA4BjC;CACD;AAED;;GAEG;AACH,qBAAa,4BAA6B,SAAQ,SAAS;IAC1D,OAAO,CAAC,WAAW,CAAkB;IAErC,YAAY,QAAQ,EAAE,eAAe,EAAE,EAAE,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,EA0BtG;IAED,cAAc,IAAI,eAAe,CAEhC;CACD","sourcesContent":["import { type Component, Container, Spacer, Text, truncateToWidth } from \"@mariozechner/pi-tui\";\nimport { theme } from \"../theme/theme.js\";\nimport { DynamicBorder } from \"./dynamic-border.js\";\n\ninterface UserMessageItem {\n\tindex: number; // Index in the full messages array\n\ttext: string; // The message text\n\ttimestamp?: string; // Optional timestamp if available\n}\n\n/**\n * Custom user message list component with selection\n */\nclass UserMessageList implements Component {\n\tprivate messages: UserMessageItem[] = [];\n\tprivate selectedIndex: number = 0;\n\tpublic onSelect?: (messageIndex: number) => void;\n\tpublic onCancel?: () => void;\n\tprivate maxVisible: number = 10; // Max messages visible\n\n\tconstructor(messages: UserMessageItem[]) {\n\t\t// Store messages in chronological order (oldest to newest)\n\t\tthis.messages = messages;\n\t\t// Start with the last (most recent) message selected\n\t\tthis.selectedIndex = Math.max(0, messages.length - 1);\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached state to invalidate currently\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\tif (this.messages.length === 0) {\n\t\t\tlines.push(theme.fg(\"muted\", \" No user messages found\"));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range with scrolling\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.messages.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.messages.length);\n\n\t\t// Render visible messages (2 lines per message + blank line)\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst message = this.messages[i];\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\t// Normalize message to single line\n\t\t\tconst normalizedMessage = message.text.replace(/\\n/g, \" \").trim();\n\n\t\t\t// First line: cursor + message\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\t\t\tconst maxMsgWidth = width - 2; // Account for cursor (2 chars)\n\t\t\tconst truncatedMsg = truncateToWidth(normalizedMessage, maxMsgWidth);\n\t\t\tconst messageLine = cursor + (isSelected ? theme.bold(truncatedMsg) : truncatedMsg);\n\n\t\t\tlines.push(messageLine);\n\n\t\t\t// Second line: metadata (position in history)\n\t\t\tconst position = i + 1;\n\t\t\tconst metadata = ` Message ${position} of ${this.messages.length}`;\n\t\t\tconst metadataLine = theme.fg(\"muted\", metadata);\n\t\t\tlines.push(metadataLine);\n\t\t\tlines.push(\"\"); // Blank line between messages\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.messages.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.messages.length})`);\n\t\t\tlines.push(scrollInfo);\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\t// Up arrow - go to previous (older) message, wrap to bottom when at top\n\t\tif (keyData === \"\\x1b[A\") {\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.messages.length - 1 : this.selectedIndex - 1;\n\t\t}\n\t\t// Down arrow - go to next (newer) message, wrap to top when at bottom\n\t\telse if (keyData === \"\\x1b[B\") {\n\t\t\tthis.selectedIndex = this.selectedIndex === this.messages.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t}\n\t\t// Enter - select message and branch\n\t\telse if (keyData === \"\\r\") {\n\t\t\tconst selected = this.messages[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.index);\n\t\t\t}\n\t\t}\n\t\t// Escape - cancel\n\t\telse if (keyData === \"\\x1b\") {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t\t// Ctrl+C - cancel\n\t\telse if (keyData === \"\\x03\") {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Component that renders a user message selector for branching\n */\nexport class UserMessageSelectorComponent extends Container {\n\tprivate messageList: UserMessageList;\n\n\tconstructor(messages: UserMessageItem[], onSelect: (messageIndex: number) => void, onCancel: () => void) {\n\t\tsuper();\n\n\t\t// Add header\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.bold(\"Branch from Message\"), 1, 0));\n\t\tthis.addChild(new Text(theme.fg(\"muted\", \"Select a message to create a new branch from that point\"), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create message list\n\t\tthis.messageList = new UserMessageList(messages);\n\t\tthis.messageList.onSelect = onSelect;\n\t\tthis.messageList.onCancel = onCancel;\n\n\t\tthis.addChild(this.messageList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Auto-cancel if no messages\n\t\tif (messages.length === 0) {\n\t\t\tsetTimeout(() => onCancel(), 100);\n\t\t}\n\t}\n\n\tgetMessageList(): UserMessageList {\n\t\treturn this.messageList;\n\t}\n}\n"]}
@@ -106,8 +106,8 @@ export class UserMessageSelectorComponent extends Container {
106
106
  // Add bottom border
107
107
  this.addChild(new Spacer(1));
108
108
  this.addChild(new DynamicBorder());
109
- // Auto-cancel if no messages or only one message
110
- if (messages.length <= 1) {
109
+ // Auto-cancel if no messages
110
+ if (messages.length === 0) {
111
111
  setTimeout(() => onCancel(), 100);
112
112
  }
113
113
  }
@@ -1 +1 @@
1
- {"version":3,"file":"user-message-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/user-message-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAChG,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAQpD;;GAEG;AACH,MAAM,eAAe;IACZ,QAAQ,GAAsB,EAAE,CAAC;IACjC,aAAa,GAAW,CAAC,CAAC;IAC3B,QAAQ,CAAkC;IAC1C,QAAQ,CAAc;IACrB,UAAU,GAAW,EAAE,CAAC,CAAC,uBAAuB;IAExD,YAAY,QAA2B,EAAE;QACxC,2DAA2D;QAC3D,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,qDAAqD;QACrD,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC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,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACjE,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,yDAAyD,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAC5G,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;QACnC,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAE7B,sBAAsB;QACtB,IAAI,CAAC,WAAW,GAAG,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;QACjD,IAAI,CAAC,WAAW,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACrC,IAAI,CAAC,WAAW,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAErC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAEhC,oBAAoB;QACpB,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;QAEnC,iDAAiD;QACjD,IAAI,QAAQ,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;YAC1B,UAAU,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,EAAE,GAAG,CAAC,CAAC;QACnC,CAAC;IAAA,CACD;IAED,cAAc,GAAoB;QACjC,OAAO,IAAI,CAAC,WAAW,CAAC;IAAA,CACxB;CACD","sourcesContent":["import { type Component, Container, Spacer, Text, truncateToWidth } from \"@mariozechner/pi-tui\";\nimport { theme } from \"../theme/theme.js\";\nimport { DynamicBorder } from \"./dynamic-border.js\";\n\ninterface UserMessageItem {\n\tindex: number; // Index in the full messages array\n\ttext: string; // The message text\n\ttimestamp?: string; // Optional timestamp if available\n}\n\n/**\n * Custom user message list component with selection\n */\nclass UserMessageList implements Component {\n\tprivate messages: UserMessageItem[] = [];\n\tprivate selectedIndex: number = 0;\n\tpublic onSelect?: (messageIndex: number) => void;\n\tpublic onCancel?: () => void;\n\tprivate maxVisible: number = 10; // Max messages visible\n\n\tconstructor(messages: UserMessageItem[]) {\n\t\t// Store messages in chronological order (oldest to newest)\n\t\tthis.messages = messages;\n\t\t// Start with the last (most recent) message selected\n\t\tthis.selectedIndex = Math.max(0, messages.length - 1);\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached state to invalidate currently\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\tif (this.messages.length === 0) {\n\t\t\tlines.push(theme.fg(\"muted\", \" No user messages found\"));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range with scrolling\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.messages.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.messages.length);\n\n\t\t// Render visible messages (2 lines per message + blank line)\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst message = this.messages[i];\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\t// Normalize message to single line\n\t\t\tconst normalizedMessage = message.text.replace(/\\n/g, \" \").trim();\n\n\t\t\t// First line: cursor + message\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\t\t\tconst maxMsgWidth = width - 2; // Account for cursor (2 chars)\n\t\t\tconst truncatedMsg = truncateToWidth(normalizedMessage, maxMsgWidth);\n\t\t\tconst messageLine = cursor + (isSelected ? theme.bold(truncatedMsg) : truncatedMsg);\n\n\t\t\tlines.push(messageLine);\n\n\t\t\t// Second line: metadata (position in history)\n\t\t\tconst position = i + 1;\n\t\t\tconst metadata = ` Message ${position} of ${this.messages.length}`;\n\t\t\tconst metadataLine = theme.fg(\"muted\", metadata);\n\t\t\tlines.push(metadataLine);\n\t\t\tlines.push(\"\"); // Blank line between messages\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.messages.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.messages.length})`);\n\t\t\tlines.push(scrollInfo);\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\t// Up arrow - go to previous (older) message, wrap to bottom when at top\n\t\tif (keyData === \"\\x1b[A\") {\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.messages.length - 1 : this.selectedIndex - 1;\n\t\t}\n\t\t// Down arrow - go to next (newer) message, wrap to top when at bottom\n\t\telse if (keyData === \"\\x1b[B\") {\n\t\t\tthis.selectedIndex = this.selectedIndex === this.messages.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t}\n\t\t// Enter - select message and branch\n\t\telse if (keyData === \"\\r\") {\n\t\t\tconst selected = this.messages[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.index);\n\t\t\t}\n\t\t}\n\t\t// Escape - cancel\n\t\telse if (keyData === \"\\x1b\") {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t\t// Ctrl+C - cancel\n\t\telse if (keyData === \"\\x03\") {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Component that renders a user message selector for branching\n */\nexport class UserMessageSelectorComponent extends Container {\n\tprivate messageList: UserMessageList;\n\n\tconstructor(messages: UserMessageItem[], onSelect: (messageIndex: number) => void, onCancel: () => void) {\n\t\tsuper();\n\n\t\t// Add header\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.bold(\"Branch from Message\"), 1, 0));\n\t\tthis.addChild(new Text(theme.fg(\"muted\", \"Select a message to create a new branch from that point\"), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create message list\n\t\tthis.messageList = new UserMessageList(messages);\n\t\tthis.messageList.onSelect = onSelect;\n\t\tthis.messageList.onCancel = onCancel;\n\n\t\tthis.addChild(this.messageList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Auto-cancel if no messages or only one message\n\t\tif (messages.length <= 1) {\n\t\t\tsetTimeout(() => onCancel(), 100);\n\t\t}\n\t}\n\n\tgetMessageList(): UserMessageList {\n\t\treturn this.messageList;\n\t}\n}\n"]}
1
+ {"version":3,"file":"user-message-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/user-message-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAChG,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAQpD;;GAEG;AACH,MAAM,eAAe;IACZ,QAAQ,GAAsB,EAAE,CAAC;IACjC,aAAa,GAAW,CAAC,CAAC;IAC3B,QAAQ,CAAkC;IAC1C,QAAQ,CAAc;IACrB,UAAU,GAAW,EAAE,CAAC,CAAC,uBAAuB;IAExD,YAAY,QAA2B,EAAE;QACxC,2DAA2D;QAC3D,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,qDAAqD;QACrD,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAAA,CACtD;IAED,UAAU,GAAS;QAClB,0CAA0C;IAD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AAC;QACjE,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,yDAAyD,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAC5G,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;QACnC,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAE7B,sBAAsB;QACtB,IAAI,CAAC,WAAW,GAAG,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;QACjD,IAAI,CAAC,WAAW,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACrC,IAAI,CAAC,WAAW,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAErC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAEhC,oBAAoB;QACpB,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;QAEnC,6BAA6B;QAC7B,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC3B,UAAU,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,EAAE,GAAG,CAAC,CAAC;QACnC,CAAC;IAAA,CACD;IAED,cAAc,GAAoB;QACjC,OAAO,IAAI,CAAC,WAAW,CAAC;IAAA,CACxB;CACD","sourcesContent":["import { type Component, Container, Spacer, Text, truncateToWidth } from \"@mariozechner/pi-tui\";\nimport { theme } from \"../theme/theme.js\";\nimport { DynamicBorder } from \"./dynamic-border.js\";\n\ninterface UserMessageItem {\n\tindex: number; // Index in the full messages array\n\ttext: string; // The message text\n\ttimestamp?: string; // Optional timestamp if available\n}\n\n/**\n * Custom user message list component with selection\n */\nclass UserMessageList implements Component {\n\tprivate messages: UserMessageItem[] = [];\n\tprivate selectedIndex: number = 0;\n\tpublic onSelect?: (messageIndex: number) => void;\n\tpublic onCancel?: () => void;\n\tprivate maxVisible: number = 10; // Max messages visible\n\n\tconstructor(messages: UserMessageItem[]) {\n\t\t// Store messages in chronological order (oldest to newest)\n\t\tthis.messages = messages;\n\t\t// Start with the last (most recent) message selected\n\t\tthis.selectedIndex = Math.max(0, messages.length - 1);\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached state to invalidate currently\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\tif (this.messages.length === 0) {\n\t\t\tlines.push(theme.fg(\"muted\", \" No user messages found\"));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range with scrolling\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.messages.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.messages.length);\n\n\t\t// Render visible messages (2 lines per message + blank line)\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst message = this.messages[i];\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\t// Normalize message to single line\n\t\t\tconst normalizedMessage = message.text.replace(/\\n/g, \" \").trim();\n\n\t\t\t// First line: cursor + message\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\t\t\tconst maxMsgWidth = width - 2; // Account for cursor (2 chars)\n\t\t\tconst truncatedMsg = truncateToWidth(normalizedMessage, maxMsgWidth);\n\t\t\tconst messageLine = cursor + (isSelected ? theme.bold(truncatedMsg) : truncatedMsg);\n\n\t\t\tlines.push(messageLine);\n\n\t\t\t// Second line: metadata (position in history)\n\t\t\tconst position = i + 1;\n\t\t\tconst metadata = ` Message ${position} of ${this.messages.length}`;\n\t\t\tconst metadataLine = theme.fg(\"muted\", metadata);\n\t\t\tlines.push(metadataLine);\n\t\t\tlines.push(\"\"); // Blank line between messages\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.messages.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.messages.length})`);\n\t\t\tlines.push(scrollInfo);\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\t// Up arrow - go to previous (older) message, wrap to bottom when at top\n\t\tif (keyData === \"\\x1b[A\") {\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.messages.length - 1 : this.selectedIndex - 1;\n\t\t}\n\t\t// Down arrow - go to next (newer) message, wrap to top when at bottom\n\t\telse if (keyData === \"\\x1b[B\") {\n\t\t\tthis.selectedIndex = this.selectedIndex === this.messages.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t}\n\t\t// Enter - select message and branch\n\t\telse if (keyData === \"\\r\") {\n\t\t\tconst selected = this.messages[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.index);\n\t\t\t}\n\t\t}\n\t\t// Escape - cancel\n\t\telse if (keyData === \"\\x1b\") {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t\t// Ctrl+C - cancel\n\t\telse if (keyData === \"\\x03\") {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Component that renders a user message selector for branching\n */\nexport class UserMessageSelectorComponent extends Container {\n\tprivate messageList: UserMessageList;\n\n\tconstructor(messages: UserMessageItem[], onSelect: (messageIndex: number) => void, onCancel: () => void) {\n\t\tsuper();\n\n\t\t// Add header\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.bold(\"Branch from Message\"), 1, 0));\n\t\tthis.addChild(new Text(theme.fg(\"muted\", \"Select a message to create a new branch from that point\"), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create message list\n\t\tthis.messageList = new UserMessageList(messages);\n\t\tthis.messageList.onSelect = onSelect;\n\t\tthis.messageList.onCancel = onCancel;\n\n\t\tthis.addChild(this.messageList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Auto-cancel if no messages\n\t\tif (messages.length === 0) {\n\t\t\tsetTimeout(() => onCancel(), 100);\n\t\t}\n\t}\n\n\tgetMessageList(): UserMessageList {\n\t\treturn this.messageList;\n\t}\n}\n"]}
@@ -31,6 +31,8 @@ export declare class InteractiveMode {
31
31
  private pendingBashComponents;
32
32
  private autoCompactionLoader;
33
33
  private autoCompactionEscapeHandler?;
34
+ private retryLoader;
35
+ private retryEscapeHandler?;
34
36
  private hookSelector;
35
37
  private hookInput;
36
38
  private get agent();
@@ -1 +1 @@
1
- {"version":3,"file":"interactive-mode.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-mode.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,UAAU,EAA0B,MAAM,6BAA6B,CAAC;AAmBtF,OAAO,KAAK,EAAE,YAAY,EAAqB,MAAM,6BAA6B,CAAC;AA6BnF,qBAAa,eAAe;IAC3B,OAAO,CAAC,OAAO,CAAe;IAC9B,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,OAAO,CAAS;IACxB,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,eAAe,CAAC,CAAyB;IACjD,OAAO,CAAC,gBAAgB,CAAuB;IAE/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","sourcesContent":["/**\n * Interactive mode for the coding agent.\n * Handles TUI rendering and user interaction, delegating business logic to AgentSession.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { AgentState, AppMessage, Attachment } from \"@mariozechner/pi-agent-core\";\nimport type { AssistantMessage, Message } from \"@mariozechner/pi-ai\";\nimport type { SlashCommand } from \"@mariozechner/pi-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\ttype Component,\n\tContainer,\n\tInput,\n\tLoader,\n\tMarkdown,\n\tProcessTerminal,\n\tSpacer,\n\tText,\n\tTruncatedText,\n\tTUI,\n\tvisibleWidth,\n} from \"@mariozechner/pi-tui\";\nimport { exec } from \"child_process\";\nimport { APP_NAME, getDebugLogPath, getOAuthPath } from \"../../config.js\";\nimport type { AgentSession, AgentSessionEvent } from \"../../core/agent-session.js\";\nimport type { HookUIContext } from \"../../core/hooks/index.js\";\nimport { isBashExecutionMessage } from \"../../core/messages.js\";\nimport { invalidateOAuthCache } from \"../../core/model-config.js\";\nimport { listOAuthProviders, login, logout, type SupportedOAuthProvider } from \"../../core/oauth/index.js\";\nimport { getLatestCompactionEntry, SUMMARY_PREFIX, SUMMARY_SUFFIX } from \"../../core/session-manager.js\";\nimport { loadProjectContextFiles } from \"../../core/system-prompt.js\";\nimport type { TruncationResult } from \"../../core/tools/truncate.js\";\nimport { getChangelogPath, parseChangelog } from \"../../utils/changelog.js\";\nimport { copyToClipboard } from \"../../utils/clipboard.js\";\nimport { AssistantMessageComponent } from \"./components/assistant-message.js\";\nimport { BashExecutionComponent } from \"./components/bash-execution.js\";\nimport { CompactionComponent } from \"./components/compaction.js\";\nimport { CustomEditor } from \"./components/custom-editor.js\";\nimport { DynamicBorder } from \"./components/dynamic-border.js\";\nimport { FooterComponent } from \"./components/footer.js\";\nimport { HookInputComponent } from \"./components/hook-input.js\";\nimport { HookSelectorComponent } from \"./components/hook-selector.js\";\nimport { ModelSelectorComponent } from \"./components/model-selector.js\";\nimport { OAuthSelectorComponent } from \"./components/oauth-selector.js\";\nimport { QueueModeSelectorComponent } from \"./components/queue-mode-selector.js\";\nimport { SessionSelectorComponent } from \"./components/session-selector.js\";\nimport { ThemeSelectorComponent } from \"./components/theme-selector.js\";\nimport { ThinkingSelectorComponent } from \"./components/thinking-selector.js\";\nimport { ToolExecutionComponent } from \"./components/tool-execution.js\";\nimport { UserMessageComponent } from \"./components/user-message.js\";\nimport { UserMessageSelectorComponent } from \"./components/user-message-selector.js\";\nimport { getEditorTheme, getMarkdownTheme, onThemeChange, setTheme, theme } from \"./theme/theme.js\";\n\nexport class InteractiveMode {\n\tprivate session: AgentSession;\n\tprivate ui: TUI;\n\tprivate chatContainer: Container;\n\tprivate pendingMessagesContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate editor: CustomEditor;\n\tprivate editorContainer: Container;\n\tprivate footer: FooterComponent;\n\tprivate version: string;\n\tprivate isInitialized = false;\n\tprivate onInputCallback?: (text: string) => void;\n\tprivate loadingAnimation: Loader | null = null;\n\n\tprivate lastSigintTime = 0;\n\tprivate lastEscapeTime = 0;\n\tprivate changelogMarkdown: 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// Track if this is the first user message (to skip spacer)\n\tprivate isFirstUserMessage = true;\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\n\t// Thinking block visibility state\n\tprivate hideThinkingBlock = false;\n\n\t// Agent subscription unsubscribe function\n\tprivate unsubscribe?: () => void;\n\n\t// Track if editor is in bash mode (text starts with !)\n\tprivate isBashMode = false;\n\n\t// Track current bash execution component\n\tprivate bashComponent: BashExecutionComponent | null = null;\n\n\t// Track pending bash components (shown in pending area, moved to chat on submit)\n\tprivate pendingBashComponents: BashExecutionComponent[] = [];\n\n\t// Auto-compaction state\n\tprivate autoCompactionLoader: Loader | null = null;\n\tprivate autoCompactionEscapeHandler?: () => void;\n\n\t// Hook UI state\n\tprivate hookSelector: HookSelectorComponent | null = null;\n\tprivate hookInput: HookInputComponent | null = null;\n\n\t// Convenience accessors\n\tprivate get agent() {\n\t\treturn this.session.agent;\n\t}\n\tprivate get sessionManager() {\n\t\treturn this.session.sessionManager;\n\t}\n\tprivate get settingsManager() {\n\t\treturn this.session.settingsManager;\n\t}\n\n\tconstructor(\n\t\tsession: AgentSession,\n\t\tversion: string,\n\t\tchangelogMarkdown: string | null = null,\n\t\tfdPath: string | null = null,\n\t) {\n\t\tthis.session = session;\n\t\tthis.version = version;\n\t\tthis.changelogMarkdown = changelogMarkdown;\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(getEditorTheme());\n\t\tthis.editorContainer = new Container();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.footer = new FooterComponent(session.state);\n\t\tthis.footer.setAutoCompactEnabled(session.autoCompactionEnabled);\n\n\t\t// Define slash commands for autocomplete\n\t\tconst slashCommands: SlashCommand[] = [\n\t\t\t{ name: \"thinking\", description: \"Select reasoning level (opens selector UI)\" },\n\t\t\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t\t\t{ name: \"export\", description: \"Export session to HTML file\" },\n\t\t\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t\t\t{ name: \"session\", description: \"Show session info and stats\" },\n\t\t\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t\t\t{ name: \"branch\", description: \"Create a new branch from a previous message\" },\n\t\t\t{ name: \"login\", description: \"Login with OAuth provider\" },\n\t\t\t{ name: \"logout\", description: \"Logout from OAuth provider\" },\n\t\t\t{ name: \"queue\", description: \"Select message queue mode (opens selector UI)\" },\n\t\t\t{ name: \"theme\", description: \"Select color theme (opens selector UI)\" },\n\t\t\t{ name: \"clear\", description: \"Clear context and start a fresh session\" },\n\t\t\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t\t\t{ name: \"autocompact\", description: \"Toggle automatic context compaction\" },\n\t\t\t{ name: \"resume\", description: \"Resume a different session\" },\n\t\t];\n\n\t\t// Load hide thinking block setting\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\n\t\t// Convert file commands to SlashCommand format\n\t\tconst fileSlashCommands: SlashCommand[] = this.session.fileCommands.map((cmd) => ({\n\t\t\tname: cmd.name,\n\t\t\tdescription: cmd.description,\n\t\t}));\n\n\t\t// Setup autocomplete\n\t\tconst autocompleteProvider = new CombinedAutocompleteProvider(\n\t\t\t[...slashCommands, ...fileSlashCommands],\n\t\t\tprocess.cwd(),\n\t\t\tfdPath,\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\n\t\tconst logo = theme.bold(theme.fg(\"accent\", APP_NAME)) + theme.fg(\"dim\", ` v${this.version}`);\n\t\tconst instructions =\n\t\t\ttheme.fg(\"dim\", \"esc\") +\n\t\t\ttheme.fg(\"muted\", \" to interrupt\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+c\") +\n\t\t\ttheme.fg(\"muted\", \" to clear\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+c twice\") +\n\t\t\ttheme.fg(\"muted\", \" to exit\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+k\") +\n\t\t\ttheme.fg(\"muted\", \" to delete line\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"shift+tab\") +\n\t\t\ttheme.fg(\"muted\", \" to cycle thinking\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+p\") +\n\t\t\ttheme.fg(\"muted\", \" to cycle models\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+o\") +\n\t\t\ttheme.fg(\"muted\", \" to expand tools\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+t\") +\n\t\t\ttheme.fg(\"muted\", \" to toggle thinking\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"/\") +\n\t\t\ttheme.fg(\"muted\", \" for commands\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"!\") +\n\t\t\ttheme.fg(\"muted\", \" to run bash\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"drop files\") +\n\t\t\ttheme.fg(\"muted\", \" 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 changelog if provided\n\t\tif (this.changelogMarkdown) {\n\t\t\tthis.ui.addChild(new DynamicBorder());\n\t\t\tif (this.settingsManager.getCollapseChangelog()) {\n\t\t\t\tconst versionMatch = this.changelogMarkdown.match(/##\\s+\\[?(\\d+\\.\\d+\\.\\d+)\\]?/);\n\t\t\t\tconst latestVersion = versionMatch ? versionMatch[1] : this.version;\n\t\t\t\tconst condensedText = `Updated to v${latestVersion}. Use ${theme.bold(\"/changelog\")} to view full changelog.`;\n\t\t\t\tthis.ui.addChild(new Text(condensedText, 1, 0));\n\t\t\t} else {\n\t\t\t\tthis.ui.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\t\t\tthis.ui.addChild(new Spacer(1));\n\t\t\t\tthis.ui.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0, getMarkdownTheme()));\n\t\t\t\tthis.ui.addChild(new Spacer(1));\n\t\t\t}\n\t\t\tthis.ui.addChild(new DynamicBorder());\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);\n\t\tthis.ui.addChild(this.footer);\n\t\tthis.ui.setFocus(this.editor);\n\n\t\tthis.setupKeyHandlers();\n\t\tthis.setupEditorSubmitHandler();\n\n\t\t// Start the UI\n\t\tthis.ui.start();\n\t\tthis.isInitialized = true;\n\n\t\t// Initialize hooks with TUI-based UI context\n\t\tawait this.initHooks();\n\n\t\t// Subscribe to agent events\n\t\tthis.subscribeToAgent();\n\n\t\t// Set up theme file watcher\n\t\tonThemeChange(() => {\n\t\t\tthis.ui.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Set up git branch watcher\n\t\tthis.footer.watchBranch(() => {\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t// =========================================================================\n\t// Hook System\n\t// =========================================================================\n\n\t/**\n\t * Initialize the hook system with TUI-based UI context.\n\t */\n\tprivate async initHooks(): Promise<void> {\n\t\t// Show loaded project context files\n\t\tconst contextFiles = loadProjectContextFiles();\n\t\tif (contextFiles.length > 0) {\n\t\t\tconst contextList = contextFiles.map((f) => theme.fg(\"dim\", ` ${f.path}`)).join(\"\\n\");\n\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"muted\", \"Loaded context:\\n\") + contextList, 0, 0));\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\n\t\tconst hookRunner = this.session.hookRunner;\n\t\tif (!hookRunner) {\n\t\t\treturn; // No hooks loaded\n\t\t}\n\n\t\t// Set TUI-based UI context on the hook runner\n\t\thookRunner.setUIContext(this.createHookUIContext(), true);\n\t\thookRunner.setSessionFile(this.session.sessionFile);\n\n\t\t// Subscribe to hook errors\n\t\thookRunner.onError((error) => {\n\t\t\tthis.showHookError(error.hookPath, error.error);\n\t\t});\n\n\t\t// Set up send handler for pi.send()\n\t\thookRunner.setSendHandler((text, attachments) => {\n\t\t\tthis.handleHookSend(text, attachments);\n\t\t});\n\n\t\t// Show loaded hooks\n\t\tconst hookPaths = hookRunner.getHookPaths();\n\t\tif (hookPaths.length > 0) {\n\t\t\tconst hookList = hookPaths.map((p) => theme.fg(\"dim\", ` ${p}`)).join(\"\\n\");\n\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"muted\", \"Loaded hooks:\\n\") + hookList, 0, 0));\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\n\t\t// Emit session_start event\n\t\tawait hookRunner.emit({ type: \"session_start\" });\n\t}\n\n\t/**\n\t * Create the UI context for hooks.\n\t */\n\tprivate createHookUIContext(): HookUIContext {\n\t\treturn {\n\t\t\tselect: (title, options) => this.showHookSelector(title, options),\n\t\t\tconfirm: (title, message) => this.showHookConfirm(title, message),\n\t\t\tinput: (title, placeholder) => this.showHookInput(title, placeholder),\n\t\t\tnotify: (message, type) => this.showHookNotify(message, type),\n\t\t};\n\t}\n\n\t/**\n\t * Show a selector for hooks.\n\t */\n\tprivate showHookSelector(title: string, options: string[]): Promise<string | null> {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.hookSelector = new HookSelectorComponent(\n\t\t\t\ttitle,\n\t\t\t\toptions,\n\t\t\t\t(option) => {\n\t\t\t\t\tthis.hideHookSelector();\n\t\t\t\t\tresolve(option);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tthis.hideHookSelector();\n\t\t\t\t\tresolve(null);\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.hookSelector);\n\t\t\tthis.ui.setFocus(this.hookSelector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the hook selector.\n\t */\n\tprivate hideHookSelector(): void {\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.hookSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a confirmation dialog for hooks.\n\t */\n\tprivate async showHookConfirm(title: string, message: string): Promise<boolean> {\n\t\tconst result = await this.showHookSelector(`${title}\\n${message}`, [\"Yes\", \"No\"]);\n\t\treturn result === \"Yes\";\n\t}\n\n\t/**\n\t * Show a text input for hooks.\n\t */\n\tprivate showHookInput(title: string, placeholder?: string): Promise<string | null> {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.hookInput = new HookInputComponent(\n\t\t\t\ttitle,\n\t\t\t\tplaceholder,\n\t\t\t\t(value) => {\n\t\t\t\t\tthis.hideHookInput();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tthis.hideHookInput();\n\t\t\t\t\tresolve(null);\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.hookInput);\n\t\t\tthis.ui.setFocus(this.hookInput);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the hook input.\n\t */\n\tprivate hideHookInput(): void {\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.hookInput = null;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a notification for hooks.\n\t */\n\tprivate showHookNotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void {\n\t\tif (type === \"error\") {\n\t\t\tthis.showError(message);\n\t\t} else if (type === \"warning\") {\n\t\t\tthis.showWarning(message);\n\t\t} else {\n\t\t\tthis.showStatus(message);\n\t\t}\n\t}\n\n\t/**\n\t * Show a hook error in the UI.\n\t */\n\tprivate showHookError(hookPath: string, error: string): void {\n\t\tconst errorText = new Text(theme.fg(\"error\", `Hook \"${hookPath}\" error: ${error}`), 1, 0);\n\t\tthis.chatContainer.addChild(errorText);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Handle pi.send() from hooks.\n\t * If streaming, queue the message. Otherwise, start a new agent loop.\n\t */\n\tprivate handleHookSend(text: string, attachments?: Attachment[]): void {\n\t\tif (this.session.isStreaming) {\n\t\t\t// Queue the message for later (note: attachments are lost when queuing)\n\t\t\tthis.session.queueMessage(text);\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t} else {\n\t\t\t// Start a new agent loop immediately\n\t\t\tthis.session.prompt(text, { attachments }).catch((err) => {\n\t\t\t\tthis.showError(err instanceof Error ? err.message : String(err));\n\t\t\t});\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Key Handlers\n\t// =========================================================================\n\n\tprivate setupKeyHandlers(): void {\n\t\tthis.editor.onEscape = () => {\n\t\t\tif (this.loadingAnimation) {\n\t\t\t\t// Abort and restore queued messages to editor\n\t\t\t\tconst queuedMessages = this.session.clearQueue();\n\t\t\t\tconst queuedText = queuedMessages.join(\"\\n\\n\");\n\t\t\t\tconst currentText = this.editor.getText();\n\t\t\t\tconst combinedText = [queuedText, currentText].filter((t) => t.trim()).join(\"\\n\\n\");\n\t\t\t\tthis.editor.setText(combinedText);\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.agent.abort();\n\t\t\t} else if (this.session.isBashRunning) {\n\t\t\t\tthis.session.abortBash();\n\t\t\t} else if (this.isBashMode) {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tthis.isBashMode = false;\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t} else if (!this.editor.getText().trim()) {\n\t\t\t\t// Double-escape with empty editor triggers /branch\n\t\t\t\tconst now = Date.now();\n\t\t\t\tif (now - this.lastEscapeTime < 500) {\n\t\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\t\tthis.lastEscapeTime = 0;\n\t\t\t\t} else {\n\t\t\t\t\tthis.lastEscapeTime = now;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tthis.editor.onCtrlC = () => this.handleCtrlC();\n\t\tthis.editor.onShiftTab = () => this.cycleThinkingLevel();\n\t\tthis.editor.onCtrlP = () => this.cycleModel();\n\t\tthis.editor.onCtrlO = () => this.toggleToolOutputExpansion();\n\t\tthis.editor.onCtrlT = () => this.toggleThinkingBlockVisibility();\n\n\t\tthis.editor.onChange = (text: string) => {\n\t\t\tconst wasBashMode = this.isBashMode;\n\t\t\tthis.isBashMode = text.trimStart().startsWith(\"!\");\n\t\t\tif (wasBashMode !== this.isBashMode) {\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t}\n\t\t};\n\t}\n\n\tprivate setupEditorSubmitHandler(): void {\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// Handle slash commands\n\t\t\tif (text === \"/thinking\") {\n\t\t\t\tthis.showThinkingSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/model\") {\n\t\t\t\tthis.showModelSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\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\t\t\tif (text === \"/copy\") {\n\t\t\t\tthis.handleCopyCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\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\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\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\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\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\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\t\t\tif (text === \"/theme\") {\n\t\t\t\tthis.showThemeSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/clear\") {\n\t\t\t\tawait this.handleClearCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/compact\" || text.startsWith(\"/compact \")) {\n\t\t\t\tconst customInstructions = text.startsWith(\"/compact \") ? text.slice(9).trim() : undefined;\n\t\t\t\tawait this.handleCompactCommand(customInstructions);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/autocompact\") {\n\t\t\t\tthis.handleAutocompactCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/debug\") {\n\t\t\t\tthis.handleDebugCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/resume\") {\n\t\t\t\tthis.showSessionSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Handle bash command\n\t\t\tif (text.startsWith(\"!\")) {\n\t\t\t\tconst command = text.slice(1).trim();\n\t\t\t\tif (command) {\n\t\t\t\t\tif (this.session.isBashRunning) {\n\t\t\t\t\t\tthis.showWarning(\"A bash command is already running. Press Esc to cancel it first.\");\n\t\t\t\t\t\tthis.editor.setText(text);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.editor.addToHistory(text);\n\t\t\t\t\tawait this.handleBashCommand(command);\n\t\t\t\t\tthis.isBashMode = false;\n\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Block input during compaction (will retry automatically)\n\t\t\tif (this.session.isCompacting) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Queue message if agent is streaming\n\t\t\tif (this.session.isStreaming) {\n\t\t\t\tawait this.session.queueMessage(text);\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.editor.addToHistory(text);\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// Normal message submission\n\t\t\t// First, move any pending bash components to chat\n\t\t\tthis.flushPendingBashComponents();\n\n\t\t\tif (this.onInputCallback) {\n\t\t\t\tthis.onInputCallback(text);\n\t\t\t}\n\t\t\tthis.editor.addToHistory(text);\n\t\t};\n\t}\n\n\tprivate subscribeToAgent(): void {\n\t\tthis.unsubscribe = this.session.subscribe(async (event) => {\n\t\t\tawait this.handleEvent(event, this.session.state);\n\t\t});\n\t}\n\n\tprivate async handleEvent(event: AgentSessionEvent, state: AgentState): Promise<void> {\n\t\tif (!this.isInitialized) {\n\t\t\tawait this.init();\n\t\t}\n\n\t\tthis.footer.updateState(state);\n\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\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(\n\t\t\t\t\tthis.ui,\n\t\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\t\t\"Working... (esc to interrupt)\",\n\t\t\t\t);\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\tthis.addMessageToChat(event.message);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t} else if (event.message.role === \"assistant\") {\n\t\t\t\t\tthis.streamingComponent = new AssistantMessageComponent(undefined, this.hideThinkingBlock);\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\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\tfor (const content of assistantMsg.content) {\n\t\t\t\t\t\tif (content.type === \"toolCall\") {\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\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\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\tif (event.message.role === \"user\") break;\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\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 [, 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\t\t\t\t\tthis.streamingComponent = null;\n\t\t\t\t\tthis.footer.invalidate();\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\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\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\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: { content: event.result.content, details: event.result.details, isError: event.isError };\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\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.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"auto_compaction_start\": {\n\t\t\t\t// Set up escape to abort auto-compaction\n\t\t\t\tthis.autoCompactionEscapeHandler = this.editor.onEscape;\n\t\t\t\tthis.editor.onEscape = () => {\n\t\t\t\t\tthis.session.abortCompaction();\n\t\t\t\t};\n\t\t\t\t// Show compacting indicator with reason\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t\tconst reasonText = event.reason === \"overflow\" ? \"Context overflow detected, \" : \"\";\n\t\t\t\tthis.autoCompactionLoader = new Loader(\n\t\t\t\t\tthis.ui,\n\t\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\t\t`${reasonText}Auto-compacting... (esc to cancel)`,\n\t\t\t\t);\n\t\t\t\tthis.statusContainer.addChild(this.autoCompactionLoader);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"auto_compaction_end\": {\n\t\t\t\t// Restore escape handler\n\t\t\t\tif (this.autoCompactionEscapeHandler) {\n\t\t\t\t\tthis.editor.onEscape = this.autoCompactionEscapeHandler;\n\t\t\t\t\tthis.autoCompactionEscapeHandler = undefined;\n\t\t\t\t}\n\t\t\t\t// Stop loader\n\t\t\t\tif (this.autoCompactionLoader) {\n\t\t\t\t\tthis.autoCompactionLoader.stop();\n\t\t\t\t\tthis.autoCompactionLoader = null;\n\t\t\t\t\tthis.statusContainer.clear();\n\t\t\t\t}\n\t\t\t\t// Handle result\n\t\t\t\tif (event.aborted) {\n\t\t\t\t\tthis.showStatus(\"Auto-compaction cancelled\");\n\t\t\t\t} else if (event.result) {\n\t\t\t\t\t// Rebuild chat to show compacted state\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t// Add compaction component (same as manual /compact)\n\t\t\t\t\tconst compactionComponent = new CompactionComponent(event.result.tokensBefore, event.result.summary);\n\t\t\t\t\tcompactionComponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\tthis.chatContainer.addChild(compactionComponent);\n\t\t\t\t\tthis.footer.updateState(this.session.state);\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Extract text content from a user message */\n\tprivate getUserMessageText(message: Message): string {\n\t\tif (message.role !== \"user\") return \"\";\n\t\tconst textBlocks =\n\t\t\ttypeof message.content === \"string\"\n\t\t\t\t? [{ type: \"text\", text: message.content }]\n\t\t\t\t: message.content.filter((c: { type: string }) => c.type === \"text\");\n\t\treturn textBlocks.map((c) => (c as { text: string }).text).join(\"\");\n\t}\n\n\t/** Show a status message in the chat */\n\tprivate showStatus(message: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", message), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addMessageToChat(message: Message | AppMessage): void {\n\t\tif (isBashExecutionMessage(message)) {\n\t\t\tconst component = new BashExecutionComponent(message.command, this.ui);\n\t\t\tif (message.output) {\n\t\t\t\tcomponent.appendOutput(message.output);\n\t\t\t}\n\t\t\tcomponent.setComplete(\n\t\t\t\tmessage.exitCode,\n\t\t\t\tmessage.cancelled,\n\t\t\t\tmessage.truncated ? ({ truncated: true } as TruncationResult) : undefined,\n\t\t\t\tmessage.fullOutputPath,\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(component);\n\t\t\treturn;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst textContent = this.getUserMessageText(message);\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 assistantComponent = new AssistantMessageComponent(message as AssistantMessage, this.hideThinkingBlock);\n\t\t\tthis.chatContainer.addChild(assistantComponent);\n\t\t}\n\t}\n\n\t/**\n\t * Render messages to chat. Used for initial load and rebuild after compaction.\n\t * @param messages Messages to render\n\t * @param options.updateFooter Update footer state\n\t * @param options.populateHistory Add user messages to editor history\n\t */\n\tprivate renderMessages(\n\t\tmessages: readonly (Message | AppMessage)[],\n\t\toptions: { updateFooter?: boolean; populateHistory?: boolean } = {},\n\t): void {\n\t\tthis.isFirstUserMessage = true;\n\t\tthis.pendingTools.clear();\n\n\t\tif (options.updateFooter) {\n\t\t\tthis.footer.updateState(this.session.state);\n\t\t\tthis.updateEditorBorderColor();\n\t\t}\n\n\t\tconst compactionEntry = getLatestCompactionEntry(this.sessionManager.loadEntries());\n\n\t\tfor (const message of messages) {\n\t\t\tif (isBashExecutionMessage(message)) {\n\t\t\t\tthis.addMessageToChat(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (message.role === \"user\") {\n\t\t\t\tconst textContent = this.getUserMessageText(message);\n\t\t\t\tif (textContent) {\n\t\t\t\t\tif (textContent.startsWith(SUMMARY_PREFIX) && compactionEntry) {\n\t\t\t\t\t\tconst summary = textContent.slice(SUMMARY_PREFIX.length, -SUMMARY_SUFFIX.length);\n\t\t\t\t\t\tconst component = new CompactionComponent(compactionEntry.tokensBefore, summary);\n\t\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst userComponent = new UserMessageComponent(textContent, this.isFirstUserMessage);\n\t\t\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\t\t\tthis.isFirstUserMessage = false;\n\t\t\t\t\t\tif (options.populateHistory) {\n\t\t\t\t\t\t\tthis.editor.addToHistory(textContent);\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 === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\tconst assistantComponent = new AssistantMessageComponent(assistantMsg, this.hideThinkingBlock);\n\t\t\t\tthis.chatContainer.addChild(assistantComponent);\n\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\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({ content: [{ type: \"text\", text: errorMessage }], isError: true });\n\t\t\t\t\t\t} else {\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\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\tthis.pendingTools.delete(message.toolCallId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.pendingTools.clear();\n\t\tthis.ui.requestRender();\n\t}\n\n\trenderInitialMessages(state: AgentState): void {\n\t\tthis.renderMessages(state.messages, { updateFooter: true, populateHistory: true });\n\n\t\t// Show compaction info if session was compacted\n\t\tconst entries = this.sessionManager.loadEntries();\n\t\tconst compactionCount = entries.filter((e) => e.type === \"compaction\").length;\n\t\tif (compactionCount > 0) {\n\t\t\tconst times = compactionCount === 1 ? \"1 time\" : `${compactionCount} times`;\n\t\t\tthis.showStatus(`Session compacted ${times}`);\n\t\t}\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\tprivate rebuildChatFromMessages(): void {\n\t\tthis.renderMessages(this.session.messages);\n\t}\n\n\t// =========================================================================\n\t// Key handlers\n\t// =========================================================================\n\n\tprivate handleCtrlC(): void {\n\t\tconst now = Date.now();\n\t\tif (now - this.lastSigintTime < 500) {\n\t\t\tthis.stop();\n\t\t\tprocess.exit(0);\n\t\t} else {\n\t\t\tthis.clearEditor();\n\t\t\tthis.lastSigintTime = now;\n\t\t}\n\t}\n\n\tprivate updateEditorBorderColor(): void {\n\t\tif (this.isBashMode) {\n\t\t\tthis.editor.borderColor = theme.getBashModeBorderColor();\n\t\t} else {\n\t\t\tconst level = this.session.thinkingLevel || \"off\";\n\t\t\tthis.editor.borderColor = theme.getThinkingBorderColor(level);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate cycleThinkingLevel(): void {\n\t\tconst newLevel = this.session.cycleThinkingLevel();\n\t\tif (newLevel === null) {\n\t\t\tthis.showStatus(\"Current model does not support thinking\");\n\t\t} else {\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.showStatus(`Thinking level: ${newLevel}`);\n\t\t}\n\t}\n\n\tprivate async cycleModel(): Promise<void> {\n\t\ttry {\n\t\t\tconst result = await this.session.cycleModel();\n\t\t\tif (result === null) {\n\t\t\t\tconst msg = this.session.scopedModels.length > 0 ? \"Only one model in scope\" : \"Only one model available\";\n\t\t\t\tthis.showStatus(msg);\n\t\t\t} else {\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tconst thinkingStr =\n\t\t\t\t\tresult.model.reasoning && result.thinkingLevel !== \"off\" ? ` (thinking: ${result.thinkingLevel})` : \"\";\n\t\t\t\tthis.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate toggleToolOutputExpansion(): void {\n\t\tthis.toolOutputExpanded = !this.toolOutputExpanded;\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} else if (child instanceof CompactionComponent) {\n\t\t\t\tchild.setExpanded(this.toolOutputExpanded);\n\t\t\t} else if (child instanceof BashExecutionComponent) {\n\t\t\t\tchild.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate toggleThinkingBlockVisibility(): void {\n\t\tthis.hideThinkingBlock = !this.hideThinkingBlock;\n\t\tthis.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);\n\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\tchild.setHideThinkingBlock(this.hideThinkingBlock);\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.clear();\n\t\tthis.rebuildChatFromMessages();\n\t\tthis.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? \"hidden\" : \"visible\"}`);\n\t}\n\n\t// =========================================================================\n\t// UI helpers\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\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", `Error: ${errorMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowWarning(warningMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"warning\", `Warning: ${warningMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowNewVersionNotification(newVersion: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.bold(theme.fg(\"warning\", \"Update Available\")) +\n\t\t\t\t\t\"\\n\" +\n\t\t\t\t\ttheme.fg(\"muted\", `New version ${newVersion} is available. Run: `) +\n\t\t\t\t\ttheme.fg(\"accent\", \"npm install -g @mariozechner/pi-coding-agent\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate updatePendingMessagesDisplay(): void {\n\t\tthis.pendingMessagesContainer.clear();\n\t\tconst queuedMessages = this.session.getQueuedMessages();\n\t\tif (queuedMessages.length > 0) {\n\t\t\tthis.pendingMessagesContainer.addChild(new Spacer(1));\n\t\t\tfor (const message of queuedMessages) {\n\t\t\t\tconst queuedText = theme.fg(\"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\t/** Move pending bash components from pending area to chat */\n\tprivate flushPendingBashComponents(): void {\n\t\tfor (const component of this.pendingBashComponents) {\n\t\t\tthis.pendingMessagesContainer.removeChild(component);\n\t\t\tthis.chatContainer.addChild(component);\n\t\t}\n\t\tthis.pendingBashComponents = [];\n\t}\n\n\t// =========================================================================\n\t// Selectors\n\t// =========================================================================\n\n\t/**\n\t * Shows a selector component in place of the editor.\n\t * @param create Factory that receives a `done` callback and returns the component and focus target\n\t */\n\tprivate showSelector(create: (done: () => void) => { component: Component; focus: Component }): void {\n\t\tconst done = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t};\n\t\tconst { component, focus } = create(done);\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(component);\n\t\tthis.ui.setFocus(focus);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showThinkingSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ThinkingSelectorComponent(\n\t\t\t\tthis.session.thinkingLevel,\n\t\t\t\t(level) => {\n\t\t\t\t\tthis.session.setThinkingLevel(level);\n\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(`Thinking level: ${level}`);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSelectList() };\n\t\t});\n\t}\n\n\tprivate showQueueModeSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new QueueModeSelectorComponent(\n\t\t\t\tthis.session.queueMode,\n\t\t\t\t(mode) => {\n\t\t\t\t\tthis.session.setQueueMode(mode);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(`Queue mode: ${mode}`);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSelectList() };\n\t\t});\n\t}\n\n\tprivate showThemeSelector(): void {\n\t\tconst currentTheme = this.settingsManager.getTheme() || \"dark\";\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ThemeSelectorComponent(\n\t\t\t\tcurrentTheme,\n\t\t\t\t(themeName) => {\n\t\t\t\t\tconst result = setTheme(themeName, true);\n\t\t\t\t\tthis.settingsManager.setTheme(themeName);\n\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\tdone();\n\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\tthis.showStatus(`Theme: ${themeName}`);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.showError(`Failed to load theme \"${themeName}\": ${result.error}\\nFell back to dark theme.`);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t(themeName) => {\n\t\t\t\t\tconst result = setTheme(themeName, true);\n\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSelectList() };\n\t\t});\n\t}\n\n\tprivate showModelSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ModelSelectorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.session.model,\n\t\t\t\tthis.settingsManager,\n\t\t\t\t(model) => {\n\t\t\t\t\tthis.agent.setModel(model);\n\t\t\t\t\tthis.sessionManager.saveModelChange(model.provider, model.id);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showUserMessageSelector(): void {\n\t\tconst userMessages = this.session.getUserMessagesForBranching();\n\n\t\tif (userMessages.length <= 1) {\n\t\t\tthis.showStatus(\"No messages to branch from\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new UserMessageSelectorComponent(\n\t\t\t\tuserMessages.map((m) => ({ index: m.entryIndex, text: m.text })),\n\t\t\t\tasync (entryIndex) => {\n\t\t\t\t\tconst result = await this.session.branch(entryIndex);\n\t\t\t\t\tif (result.skipped) {\n\t\t\t\t\t\t// Hook requested to skip conversation restore\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.isFirstUserMessage = true;\n\t\t\t\t\tthis.renderInitialMessages(this.session.state);\n\t\t\t\t\tthis.editor.setText(result.selectedText);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(\"Branched to new session\");\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getMessageList() };\n\t\t});\n\t}\n\n\tprivate showSessionSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new SessionSelectorComponent(\n\t\t\t\tthis.sessionManager,\n\t\t\t\tasync (sessionPath) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tawait this.handleResumeSession(sessionPath);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSessionList() };\n\t\t});\n\t}\n\n\tprivate async handleResumeSession(sessionPath: string): Promise<void> {\n\t\t// Stop loading animation\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = null;\n\t\t}\n\t\tthis.statusContainer.clear();\n\n\t\t// Clear UI state\n\t\tthis.pendingMessagesContainer.clear();\n\t\tthis.streamingComponent = null;\n\t\tthis.pendingTools.clear();\n\n\t\t// Switch session via AgentSession\n\t\tawait this.session.switchSession(sessionPath);\n\n\t\t// Clear and re-render the chat\n\t\tthis.chatContainer.clear();\n\t\tthis.isFirstUserMessage = true;\n\t\tthis.renderInitialMessages(this.session.state);\n\t\tthis.showStatus(\"Resumed session\");\n\t}\n\n\tprivate async showOAuthSelector(mode: \"login\" | \"logout\"): Promise<void> {\n\t\tif (mode === \"logout\") {\n\t\t\tconst loggedInProviders = listOAuthProviders();\n\t\t\tif (loggedInProviders.length === 0) {\n\t\t\t\tthis.showStatus(\"No OAuth providers logged in. Use /login first.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\tmode,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tif (mode === \"login\") {\n\t\t\t\t\t\tthis.showStatus(`Logging in to ${providerId}...`);\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait login(\n\t\t\t\t\t\t\t\tproviderId as SupportedOAuthProvider,\n\t\t\t\t\t\t\t\t(url: string) => {\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"accent\", \"Opening browser to:\"), 1, 0));\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"accent\", url), 1, 0));\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\t\t\tnew Text(theme.fg(\"warning\", \"Paste the authorization code below:\"), 1, 0),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tthis.ui.requestRender();\n\n\t\t\t\t\t\t\t\t\tconst openCmd =\n\t\t\t\t\t\t\t\t\t\tprocess.platform === \"darwin\"\n\t\t\t\t\t\t\t\t\t\t\t? \"open\"\n\t\t\t\t\t\t\t\t\t\t\t: process.platform === \"win32\"\n\t\t\t\t\t\t\t\t\t\t\t\t? \"start\"\n\t\t\t\t\t\t\t\t\t\t\t\t: \"xdg-open\";\n\t\t\t\t\t\t\t\t\texec(`${openCmd} \"${url}\"`);\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\t\treturn new Promise<string>((resolve) => {\n\t\t\t\t\t\t\t\t\t\tconst codeInput = new Input();\n\t\t\t\t\t\t\t\t\t\tcodeInput.onSubmit = () => {\n\t\t\t\t\t\t\t\t\t\t\tconst code = codeInput.getValue();\n\t\t\t\t\t\t\t\t\t\t\tthis.editorContainer.clear();\n\t\t\t\t\t\t\t\t\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\t\t\t\t\t\t\t\t\tthis.ui.setFocus(this.editor);\n\t\t\t\t\t\t\t\t\t\t\tresolve(code);\n\t\t\t\t\t\t\t\t\t\t};\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(codeInput);\n\t\t\t\t\t\t\t\t\t\tthis.ui.setFocus(codeInput);\n\t\t\t\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tinvalidateOAuthCache();\n\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\tnew Text(theme.fg(\"success\", `✓ Successfully logged in to ${providerId}`), 1, 0),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Tokens saved to ${getOAuthPath()}`), 1, 0));\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\t\tthis.showError(`Login failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait logout(providerId as SupportedOAuthProvider);\n\t\t\t\t\t\t\tinvalidateOAuthCache();\n\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\tnew Text(theme.fg(\"success\", `✓ Successfully logged out of ${providerId}`), 1, 0),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\tnew Text(theme.fg(\"dim\", `Credentials removed from ${getOAuthPath()}`), 1, 0),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\t\tthis.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\t// =========================================================================\n\t// Command handlers\n\t// =========================================================================\n\n\tprivate handleExportCommand(text: string): void {\n\t\tconst parts = text.split(/\\s+/);\n\t\tconst outputPath = parts.length > 1 ? parts[1] : undefined;\n\n\t\ttry {\n\t\t\tconst filePath = this.session.exportToHtml(outputPath);\n\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\t}\n\n\tprivate handleCopyCommand(): void {\n\t\tconst text = this.session.getLastAssistantText();\n\t\tif (!text) {\n\t\t\tthis.showError(\"No agent messages to copy yet.\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tcopyToClipboard(text);\n\t\t\tthis.showStatus(\"Copied last agent message to clipboard\");\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate handleSessionCommand(): void {\n\t\tconst stats = this.session.getSessionStats();\n\n\t\tlet info = `${theme.bold(\"Session Info\")}\\n\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"File:\")} ${stats.sessionFile}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"ID:\")} ${stats.sessionId}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Messages\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"User:\")} ${stats.userMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Assistant:\")} ${stats.assistantMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tool Calls:\")} ${stats.toolCalls}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tool Results:\")} ${stats.toolResults}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.totalMessages}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Tokens\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Input:\")} ${stats.tokens.input.toLocaleString()}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Output:\")} ${stats.tokens.output.toLocaleString()}\\n`;\n\t\tif (stats.tokens.cacheRead > 0) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Cache Read:\")} ${stats.tokens.cacheRead.toLocaleString()}\\n`;\n\t\t}\n\t\tif (stats.tokens.cacheWrite > 0) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Cache Write:\")} ${stats.tokens.cacheWrite.toLocaleString()}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.tokens.total.toLocaleString()}\\n`;\n\n\t\tif (stats.cost > 0) {\n\t\t\tinfo += `\\n${theme.bold(\"Cost\")}\\n`;\n\t\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.cost.toFixed(4)}`;\n\t\t}\n\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\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\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\tthis.ui.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, getMarkdownTheme()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleClearCommand(): Promise<void> {\n\t\t// Stop loading animation\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = null;\n\t\t}\n\t\tthis.statusContainer.clear();\n\n\t\t// Reset via session\n\t\tawait this.session.reset();\n\n\t\t// Clear UI state\n\t\tthis.chatContainer.clear();\n\t\tthis.pendingMessagesContainer.clear();\n\t\tthis.streamingComponent = null;\n\t\tthis.pendingTools.clear();\n\t\tthis.isFirstUserMessage = true;\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(theme.fg(\"accent\", \"✓ Context cleared\") + \"\\n\" + theme.fg(\"muted\", \"Started fresh session\"), 1, 1),\n\t\t);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleDebugCommand(): void {\n\t\tconst width = this.ui.terminal.columns;\n\t\tconst allLines = this.ui.render(width);\n\n\t\tconst debugLogPath = getDebugLogPath();\n\t\tconst debugData = [\n\t\t\t`Debug output at ${new Date().toISOString()}`,\n\t\t\t`Terminal width: ${width}`,\n\t\t\t`Total lines: ${allLines.length}`,\n\t\t\t\"\",\n\t\t\t\"=== All rendered lines with visible widths ===\",\n\t\t\t...allLines.map((line, idx) => {\n\t\t\t\tconst vw = visibleWidth(line);\n\t\t\t\tconst escaped = JSON.stringify(line);\n\t\t\t\treturn `[${idx}] (w=${vw}) ${escaped}`;\n\t\t\t}),\n\t\t\t\"\",\n\t\t\t\"=== Agent messages (JSONL) ===\",\n\t\t\t...this.session.messages.map((msg) => JSON.stringify(msg)),\n\t\t\t\"\",\n\t\t].join(\"\\n\");\n\n\t\tfs.mkdirSync(path.dirname(debugLogPath), { recursive: true });\n\t\tfs.writeFileSync(debugLogPath, debugData);\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(theme.fg(\"accent\", \"✓ Debug log written\") + \"\\n\" + theme.fg(\"muted\", debugLogPath), 1, 1),\n\t\t);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleBashCommand(command: string): Promise<void> {\n\t\tconst isDeferred = this.session.isStreaming;\n\t\tthis.bashComponent = new BashExecutionComponent(command, this.ui);\n\n\t\tif (isDeferred) {\n\t\t\t// Show in pending area when agent is streaming\n\t\t\tthis.pendingMessagesContainer.addChild(this.bashComponent);\n\t\t\tthis.pendingBashComponents.push(this.bashComponent);\n\t\t} else {\n\t\t\t// Show in chat immediately when agent is idle\n\t\t\tthis.chatContainer.addChild(this.bashComponent);\n\t\t}\n\t\tthis.ui.requestRender();\n\n\t\ttry {\n\t\t\tconst result = await this.session.executeBash(command, (chunk) => {\n\t\t\t\tif (this.bashComponent) {\n\t\t\t\t\tthis.bashComponent.appendOutput(chunk);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(\n\t\t\t\t\tresult.exitCode,\n\t\t\t\t\tresult.cancelled,\n\t\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\t\tresult.fullOutputPath,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(null, false);\n\t\t\t}\n\t\t\tthis.showError(`Bash command failed: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\n\t\tthis.bashComponent = null;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleCompactCommand(customInstructions?: string): Promise<void> {\n\t\tconst entries = this.sessionManager.loadEntries();\n\t\tconst messageCount = entries.filter((e) => e.type === \"message\").length;\n\n\t\tif (messageCount < 2) {\n\t\t\tthis.showWarning(\"Nothing to compact (no messages yet)\");\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.executeCompaction(customInstructions, false);\n\t}\n\n\tprivate handleAutocompactCommand(): void {\n\t\tconst newState = !this.session.autoCompactionEnabled;\n\t\tthis.session.setAutoCompactionEnabled(newState);\n\t\tthis.footer.setAutoCompactEnabled(newState);\n\t\tthis.showStatus(`Auto-compaction: ${newState ? \"on\" : \"off\"}`);\n\t}\n\n\tprivate async executeCompaction(customInstructions?: string, isAuto = false): Promise<void> {\n\t\t// Stop loading animation\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = null;\n\t\t}\n\t\tthis.statusContainer.clear();\n\n\t\t// Set up escape handler during compaction\n\t\tconst originalOnEscape = this.editor.onEscape;\n\t\tthis.editor.onEscape = () => {\n\t\t\tthis.session.abortCompaction();\n\t\t};\n\n\t\t// Show compacting status\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tconst label = isAuto ? \"Auto-compacting context... (esc to cancel)\" : \"Compacting context... (esc to cancel)\";\n\t\tconst compactingLoader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tlabel,\n\t\t);\n\t\tthis.statusContainer.addChild(compactingLoader);\n\t\tthis.ui.requestRender();\n\n\t\ttry {\n\t\t\tconst result = await this.session.compact(customInstructions);\n\n\t\t\t// Rebuild UI\n\t\t\tthis.chatContainer.clear();\n\t\t\tthis.rebuildChatFromMessages();\n\n\t\t\t// Add compaction component\n\t\t\tconst compactionComponent = new CompactionComponent(result.tokensBefore, result.summary);\n\t\t\tcompactionComponent.setExpanded(this.toolOutputExpanded);\n\t\t\tthis.chatContainer.addChild(compactionComponent);\n\n\t\t\tthis.footer.updateState(this.session.state);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\")) {\n\t\t\t\tthis.showError(\"Compaction cancelled\");\n\t\t\t} else {\n\t\t\t\tthis.showError(`Compaction failed: ${message}`);\n\t\t\t}\n\t\t} finally {\n\t\t\tcompactingLoader.stop();\n\t\t\tthis.statusContainer.clear();\n\t\t\tthis.editor.onEscape = originalOnEscape;\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\tthis.footer.dispose();\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\n\t\t}\n\t\tif (this.isInitialized) {\n\t\t\tthis.ui.stop();\n\t\t\t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AAS,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAIpC;IAED,WAAW,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAIxC;IAED,0BAA0B,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAenD;IAED,OAAO,CAAC,4BAA4B;IAYpC,6DAA6D;IAC7D,OAAO,CAAC,0BAA0B;IAYlC;;;OAGG;IACH,OAAO,CAAC,YAAY;IAapB,OAAO,CAAC,oBAAoB;IAmB5B,OAAO,CAAC,qBAAqB;IAkB7B,OAAO,CAAC,iBAAiB;IAgCzB,OAAO,CAAC,iBAAiB;IAqBzB,OAAO,CAAC,uBAAuB;IAmC/B,OAAO,CAAC,mBAAmB;YAiBb,mBAAmB;YAuBnB,iBAAiB;IAiG/B,OAAO,CAAC,mBAAmB;IAY3B,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,oBAAoB;IAiC5B,OAAO,CAAC,sBAAsB;YAqBhB,kBAAkB;IAyBhC,OAAO,CAAC,kBAAkB;YAgCZ,iBAAiB;YAyCjB,oBAAoB;IAYlC,OAAO,CAAC,wBAAwB;YAOlB,iBAAiB;IAqD/B,IAAI,IAAI,IAAI,CAaX;CACD","sourcesContent":["/**\n * Interactive mode for the coding agent.\n * Handles TUI rendering and user interaction, delegating business logic to AgentSession.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { AgentState, AppMessage, Attachment } from \"@mariozechner/pi-agent-core\";\nimport type { AssistantMessage, Message } from \"@mariozechner/pi-ai\";\nimport type { SlashCommand } from \"@mariozechner/pi-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\ttype Component,\n\tContainer,\n\tInput,\n\tLoader,\n\tMarkdown,\n\tProcessTerminal,\n\tSpacer,\n\tText,\n\tTruncatedText,\n\tTUI,\n\tvisibleWidth,\n} from \"@mariozechner/pi-tui\";\nimport { exec } from \"child_process\";\nimport { APP_NAME, getDebugLogPath, getOAuthPath } from \"../../config.js\";\nimport type { AgentSession, AgentSessionEvent } from \"../../core/agent-session.js\";\nimport type { HookUIContext } from \"../../core/hooks/index.js\";\nimport { isBashExecutionMessage } from \"../../core/messages.js\";\nimport { invalidateOAuthCache } from \"../../core/model-config.js\";\nimport { listOAuthProviders, login, logout, type SupportedOAuthProvider } from \"../../core/oauth/index.js\";\nimport { getLatestCompactionEntry, SUMMARY_PREFIX, SUMMARY_SUFFIX } from \"../../core/session-manager.js\";\nimport { loadProjectContextFiles } from \"../../core/system-prompt.js\";\nimport type { TruncationResult } from \"../../core/tools/truncate.js\";\nimport { getChangelogPath, parseChangelog } from \"../../utils/changelog.js\";\nimport { copyToClipboard } from \"../../utils/clipboard.js\";\nimport { AssistantMessageComponent } from \"./components/assistant-message.js\";\nimport { BashExecutionComponent } from \"./components/bash-execution.js\";\nimport { CompactionComponent } from \"./components/compaction.js\";\nimport { CustomEditor } from \"./components/custom-editor.js\";\nimport { DynamicBorder } from \"./components/dynamic-border.js\";\nimport { FooterComponent } from \"./components/footer.js\";\nimport { HookInputComponent } from \"./components/hook-input.js\";\nimport { HookSelectorComponent } from \"./components/hook-selector.js\";\nimport { ModelSelectorComponent } from \"./components/model-selector.js\";\nimport { OAuthSelectorComponent } from \"./components/oauth-selector.js\";\nimport { QueueModeSelectorComponent } from \"./components/queue-mode-selector.js\";\nimport { SessionSelectorComponent } from \"./components/session-selector.js\";\nimport { ThemeSelectorComponent } from \"./components/theme-selector.js\";\nimport { ThinkingSelectorComponent } from \"./components/thinking-selector.js\";\nimport { ToolExecutionComponent } from \"./components/tool-execution.js\";\nimport { UserMessageComponent } from \"./components/user-message.js\";\nimport { UserMessageSelectorComponent } from \"./components/user-message-selector.js\";\nimport { getEditorTheme, getMarkdownTheme, onThemeChange, setTheme, theme } from \"./theme/theme.js\";\n\nexport class InteractiveMode {\n\tprivate session: AgentSession;\n\tprivate ui: TUI;\n\tprivate chatContainer: Container;\n\tprivate pendingMessagesContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate editor: CustomEditor;\n\tprivate editorContainer: Container;\n\tprivate footer: FooterComponent;\n\tprivate version: string;\n\tprivate isInitialized = false;\n\tprivate onInputCallback?: (text: string) => void;\n\tprivate loadingAnimation: Loader | null = null;\n\n\tprivate lastSigintTime = 0;\n\tprivate lastEscapeTime = 0;\n\tprivate changelogMarkdown: 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// Track if this is the first user message (to skip spacer)\n\tprivate isFirstUserMessage = true;\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\n\t// Thinking block visibility state\n\tprivate hideThinkingBlock = false;\n\n\t// Agent subscription unsubscribe function\n\tprivate unsubscribe?: () => void;\n\n\t// Track if editor is in bash mode (text starts with !)\n\tprivate isBashMode = false;\n\n\t// Track current bash execution component\n\tprivate bashComponent: BashExecutionComponent | null = null;\n\n\t// Track pending bash components (shown in pending area, moved to chat on submit)\n\tprivate pendingBashComponents: BashExecutionComponent[] = [];\n\n\t// Auto-compaction state\n\tprivate autoCompactionLoader: Loader | null = null;\n\tprivate autoCompactionEscapeHandler?: () => void;\n\n\t// Auto-retry state\n\tprivate retryLoader: Loader | null = null;\n\tprivate retryEscapeHandler?: () => void;\n\n\t// Hook UI state\n\tprivate hookSelector: HookSelectorComponent | null = null;\n\tprivate hookInput: HookInputComponent | null = null;\n\n\t// Convenience accessors\n\tprivate get agent() {\n\t\treturn this.session.agent;\n\t}\n\tprivate get sessionManager() {\n\t\treturn this.session.sessionManager;\n\t}\n\tprivate get settingsManager() {\n\t\treturn this.session.settingsManager;\n\t}\n\n\tconstructor(\n\t\tsession: AgentSession,\n\t\tversion: string,\n\t\tchangelogMarkdown: string | null = null,\n\t\tfdPath: string | null = null,\n\t) {\n\t\tthis.session = session;\n\t\tthis.version = version;\n\t\tthis.changelogMarkdown = changelogMarkdown;\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(getEditorTheme());\n\t\tthis.editorContainer = new Container();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.footer = new FooterComponent(session.state);\n\t\tthis.footer.setAutoCompactEnabled(session.autoCompactionEnabled);\n\n\t\t// Define slash commands for autocomplete\n\t\tconst slashCommands: SlashCommand[] = [\n\t\t\t{ name: \"thinking\", description: \"Select reasoning level (opens selector UI)\" },\n\t\t\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t\t\t{ name: \"export\", description: \"Export session to HTML file\" },\n\t\t\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t\t\t{ name: \"session\", description: \"Show session info and stats\" },\n\t\t\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t\t\t{ name: \"branch\", description: \"Create a new branch from a previous message\" },\n\t\t\t{ name: \"login\", description: \"Login with OAuth provider\" },\n\t\t\t{ name: \"logout\", description: \"Logout from OAuth provider\" },\n\t\t\t{ name: \"queue\", description: \"Select message queue mode (opens selector UI)\" },\n\t\t\t{ name: \"theme\", description: \"Select color theme (opens selector UI)\" },\n\t\t\t{ name: \"clear\", description: \"Clear context and start a fresh session\" },\n\t\t\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t\t\t{ name: \"autocompact\", description: \"Toggle automatic context compaction\" },\n\t\t\t{ name: \"resume\", description: \"Resume a different session\" },\n\t\t];\n\n\t\t// Load hide thinking block setting\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\n\t\t// Convert file commands to SlashCommand format\n\t\tconst fileSlashCommands: SlashCommand[] = this.session.fileCommands.map((cmd) => ({\n\t\t\tname: cmd.name,\n\t\t\tdescription: cmd.description,\n\t\t}));\n\n\t\t// Setup autocomplete\n\t\tconst autocompleteProvider = new CombinedAutocompleteProvider(\n\t\t\t[...slashCommands, ...fileSlashCommands],\n\t\t\tprocess.cwd(),\n\t\t\tfdPath,\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\n\t\tconst logo = theme.bold(theme.fg(\"accent\", APP_NAME)) + theme.fg(\"dim\", ` v${this.version}`);\n\t\tconst instructions =\n\t\t\ttheme.fg(\"dim\", \"esc\") +\n\t\t\ttheme.fg(\"muted\", \" to interrupt\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+c\") +\n\t\t\ttheme.fg(\"muted\", \" to clear\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+c twice\") +\n\t\t\ttheme.fg(\"muted\", \" to exit\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+k\") +\n\t\t\ttheme.fg(\"muted\", \" to delete line\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"shift+tab\") +\n\t\t\ttheme.fg(\"muted\", \" to cycle thinking\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+p\") +\n\t\t\ttheme.fg(\"muted\", \" to cycle models\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+o\") +\n\t\t\ttheme.fg(\"muted\", \" to expand tools\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"ctrl+t\") +\n\t\t\ttheme.fg(\"muted\", \" to toggle thinking\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"/\") +\n\t\t\ttheme.fg(\"muted\", \" for commands\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"!\") +\n\t\t\ttheme.fg(\"muted\", \" to run bash\") +\n\t\t\t\"\\n\" +\n\t\t\ttheme.fg(\"dim\", \"drop files\") +\n\t\t\ttheme.fg(\"muted\", \" 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 changelog if provided\n\t\tif (this.changelogMarkdown) {\n\t\t\tthis.ui.addChild(new DynamicBorder());\n\t\t\tif (this.settingsManager.getCollapseChangelog()) {\n\t\t\t\tconst versionMatch = this.changelogMarkdown.match(/##\\s+\\[?(\\d+\\.\\d+\\.\\d+)\\]?/);\n\t\t\t\tconst latestVersion = versionMatch ? versionMatch[1] : this.version;\n\t\t\t\tconst condensedText = `Updated to v${latestVersion}. Use ${theme.bold(\"/changelog\")} to view full changelog.`;\n\t\t\t\tthis.ui.addChild(new Text(condensedText, 1, 0));\n\t\t\t} else {\n\t\t\t\tthis.ui.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\t\t\tthis.ui.addChild(new Spacer(1));\n\t\t\t\tthis.ui.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0, getMarkdownTheme()));\n\t\t\t\tthis.ui.addChild(new Spacer(1));\n\t\t\t}\n\t\t\tthis.ui.addChild(new DynamicBorder());\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);\n\t\tthis.ui.addChild(this.footer);\n\t\tthis.ui.setFocus(this.editor);\n\n\t\tthis.setupKeyHandlers();\n\t\tthis.setupEditorSubmitHandler();\n\n\t\t// Start the UI\n\t\tthis.ui.start();\n\t\tthis.isInitialized = true;\n\n\t\t// Initialize hooks with TUI-based UI context\n\t\tawait this.initHooks();\n\n\t\t// Subscribe to agent events\n\t\tthis.subscribeToAgent();\n\n\t\t// Set up theme file watcher\n\t\tonThemeChange(() => {\n\t\t\tthis.ui.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Set up git branch watcher\n\t\tthis.footer.watchBranch(() => {\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t// =========================================================================\n\t// Hook System\n\t// =========================================================================\n\n\t/**\n\t * Initialize the hook system with TUI-based UI context.\n\t */\n\tprivate async initHooks(): Promise<void> {\n\t\t// Show loaded project context files\n\t\tconst contextFiles = loadProjectContextFiles();\n\t\tif (contextFiles.length > 0) {\n\t\t\tconst contextList = contextFiles.map((f) => theme.fg(\"dim\", ` ${f.path}`)).join(\"\\n\");\n\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"muted\", \"Loaded context:\\n\") + contextList, 0, 0));\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\n\t\tconst hookRunner = this.session.hookRunner;\n\t\tif (!hookRunner) {\n\t\t\treturn; // No hooks loaded\n\t\t}\n\n\t\t// Set TUI-based UI context on the hook runner\n\t\thookRunner.setUIContext(this.createHookUIContext(), true);\n\t\thookRunner.setSessionFile(this.session.sessionFile);\n\n\t\t// Subscribe to hook errors\n\t\thookRunner.onError((error) => {\n\t\t\tthis.showHookError(error.hookPath, error.error);\n\t\t});\n\n\t\t// Set up send handler for pi.send()\n\t\thookRunner.setSendHandler((text, attachments) => {\n\t\t\tthis.handleHookSend(text, attachments);\n\t\t});\n\n\t\t// Show loaded hooks\n\t\tconst hookPaths = hookRunner.getHookPaths();\n\t\tif (hookPaths.length > 0) {\n\t\t\tconst hookList = hookPaths.map((p) => theme.fg(\"dim\", ` ${p}`)).join(\"\\n\");\n\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"muted\", \"Loaded hooks:\\n\") + hookList, 0, 0));\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\n\t\t// Emit session_start event\n\t\tawait hookRunner.emit({ type: \"session_start\" });\n\t}\n\n\t/**\n\t * Create the UI context for hooks.\n\t */\n\tprivate createHookUIContext(): HookUIContext {\n\t\treturn {\n\t\t\tselect: (title, options) => this.showHookSelector(title, options),\n\t\t\tconfirm: (title, message) => this.showHookConfirm(title, message),\n\t\t\tinput: (title, placeholder) => this.showHookInput(title, placeholder),\n\t\t\tnotify: (message, type) => this.showHookNotify(message, type),\n\t\t};\n\t}\n\n\t/**\n\t * Show a selector for hooks.\n\t */\n\tprivate showHookSelector(title: string, options: string[]): Promise<string | null> {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.hookSelector = new HookSelectorComponent(\n\t\t\t\ttitle,\n\t\t\t\toptions,\n\t\t\t\t(option) => {\n\t\t\t\t\tthis.hideHookSelector();\n\t\t\t\t\tresolve(option);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tthis.hideHookSelector();\n\t\t\t\t\tresolve(null);\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.hookSelector);\n\t\t\tthis.ui.setFocus(this.hookSelector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the hook selector.\n\t */\n\tprivate hideHookSelector(): void {\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.hookSelector = null;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a confirmation dialog for hooks.\n\t */\n\tprivate async showHookConfirm(title: string, message: string): Promise<boolean> {\n\t\tconst result = await this.showHookSelector(`${title}\\n${message}`, [\"Yes\", \"No\"]);\n\t\treturn result === \"Yes\";\n\t}\n\n\t/**\n\t * Show a text input for hooks.\n\t */\n\tprivate showHookInput(title: string, placeholder?: string): Promise<string | null> {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.hookInput = new HookInputComponent(\n\t\t\t\ttitle,\n\t\t\t\tplaceholder,\n\t\t\t\t(value) => {\n\t\t\t\t\tthis.hideHookInput();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tthis.hideHookInput();\n\t\t\t\t\tresolve(null);\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.hookInput);\n\t\t\tthis.ui.setFocus(this.hookInput);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the hook input.\n\t */\n\tprivate hideHookInput(): void {\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.hookInput = null;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a notification for hooks.\n\t */\n\tprivate showHookNotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void {\n\t\tif (type === \"error\") {\n\t\t\tthis.showError(message);\n\t\t} else if (type === \"warning\") {\n\t\t\tthis.showWarning(message);\n\t\t} else {\n\t\t\tthis.showStatus(message);\n\t\t}\n\t}\n\n\t/**\n\t * Show a hook error in the UI.\n\t */\n\tprivate showHookError(hookPath: string, error: string): void {\n\t\tconst errorText = new Text(theme.fg(\"error\", `Hook \"${hookPath}\" error: ${error}`), 1, 0);\n\t\tthis.chatContainer.addChild(errorText);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Handle pi.send() from hooks.\n\t * If streaming, queue the message. Otherwise, start a new agent loop.\n\t */\n\tprivate handleHookSend(text: string, attachments?: Attachment[]): void {\n\t\tif (this.session.isStreaming) {\n\t\t\t// Queue the message for later (note: attachments are lost when queuing)\n\t\t\tthis.session.queueMessage(text);\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t} else {\n\t\t\t// Start a new agent loop immediately\n\t\t\tthis.session.prompt(text, { attachments }).catch((err) => {\n\t\t\t\tthis.showError(err instanceof Error ? err.message : String(err));\n\t\t\t});\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Key Handlers\n\t// =========================================================================\n\n\tprivate setupKeyHandlers(): void {\n\t\tthis.editor.onEscape = () => {\n\t\t\tif (this.loadingAnimation) {\n\t\t\t\t// Abort and restore queued messages to editor\n\t\t\t\tconst queuedMessages = this.session.clearQueue();\n\t\t\t\tconst queuedText = queuedMessages.join(\"\\n\\n\");\n\t\t\t\tconst currentText = this.editor.getText();\n\t\t\t\tconst combinedText = [queuedText, currentText].filter((t) => t.trim()).join(\"\\n\\n\");\n\t\t\t\tthis.editor.setText(combinedText);\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.agent.abort();\n\t\t\t} else if (this.session.isBashRunning) {\n\t\t\t\tthis.session.abortBash();\n\t\t\t} else if (this.isBashMode) {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tthis.isBashMode = false;\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t} else if (!this.editor.getText().trim()) {\n\t\t\t\t// Double-escape with empty editor triggers /branch\n\t\t\t\tconst now = Date.now();\n\t\t\t\tif (now - this.lastEscapeTime < 500) {\n\t\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\t\tthis.lastEscapeTime = 0;\n\t\t\t\t} else {\n\t\t\t\t\tthis.lastEscapeTime = now;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tthis.editor.onCtrlC = () => this.handleCtrlC();\n\t\tthis.editor.onShiftTab = () => this.cycleThinkingLevel();\n\t\tthis.editor.onCtrlP = () => this.cycleModel();\n\t\tthis.editor.onCtrlO = () => this.toggleToolOutputExpansion();\n\t\tthis.editor.onCtrlT = () => this.toggleThinkingBlockVisibility();\n\n\t\tthis.editor.onChange = (text: string) => {\n\t\t\tconst wasBashMode = this.isBashMode;\n\t\t\tthis.isBashMode = text.trimStart().startsWith(\"!\");\n\t\t\tif (wasBashMode !== this.isBashMode) {\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t}\n\t\t};\n\t}\n\n\tprivate setupEditorSubmitHandler(): void {\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// Handle slash commands\n\t\t\tif (text === \"/thinking\") {\n\t\t\t\tthis.showThinkingSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/model\") {\n\t\t\t\tthis.showModelSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\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\t\t\tif (text === \"/copy\") {\n\t\t\t\tthis.handleCopyCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\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\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\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\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\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\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\t\t\tif (text === \"/theme\") {\n\t\t\t\tthis.showThemeSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/clear\") {\n\t\t\t\tawait this.handleClearCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/compact\" || text.startsWith(\"/compact \")) {\n\t\t\t\tconst customInstructions = text.startsWith(\"/compact \") ? text.slice(9).trim() : undefined;\n\t\t\t\tawait this.handleCompactCommand(customInstructions);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/autocompact\") {\n\t\t\t\tthis.handleAutocompactCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/debug\") {\n\t\t\t\tthis.handleDebugCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/resume\") {\n\t\t\t\tthis.showSessionSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Handle bash command\n\t\t\tif (text.startsWith(\"!\")) {\n\t\t\t\tconst command = text.slice(1).trim();\n\t\t\t\tif (command) {\n\t\t\t\t\tif (this.session.isBashRunning) {\n\t\t\t\t\t\tthis.showWarning(\"A bash command is already running. Press Esc to cancel it first.\");\n\t\t\t\t\t\tthis.editor.setText(text);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.editor.addToHistory(text);\n\t\t\t\t\tawait this.handleBashCommand(command);\n\t\t\t\t\tthis.isBashMode = false;\n\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Block input during compaction (will retry automatically)\n\t\t\tif (this.session.isCompacting) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Queue message if agent is streaming\n\t\t\tif (this.session.isStreaming) {\n\t\t\t\tawait this.session.queueMessage(text);\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.editor.addToHistory(text);\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// Normal message submission\n\t\t\t// First, move any pending bash components to chat\n\t\t\tthis.flushPendingBashComponents();\n\n\t\t\tif (this.onInputCallback) {\n\t\t\t\tthis.onInputCallback(text);\n\t\t\t}\n\t\t\tthis.editor.addToHistory(text);\n\t\t};\n\t}\n\n\tprivate subscribeToAgent(): void {\n\t\tthis.unsubscribe = this.session.subscribe(async (event) => {\n\t\t\tawait this.handleEvent(event, this.session.state);\n\t\t});\n\t}\n\n\tprivate async handleEvent(event: AgentSessionEvent, state: AgentState): Promise<void> {\n\t\tif (!this.isInitialized) {\n\t\t\tawait this.init();\n\t\t}\n\n\t\tthis.footer.updateState(state);\n\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\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(\n\t\t\t\t\tthis.ui,\n\t\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\t\t\"Working... (esc to interrupt)\",\n\t\t\t\t);\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\tthis.addMessageToChat(event.message);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t} else if (event.message.role === \"assistant\") {\n\t\t\t\t\tthis.streamingComponent = new AssistantMessageComponent(undefined, this.hideThinkingBlock);\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\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\tfor (const content of assistantMsg.content) {\n\t\t\t\t\t\tif (content.type === \"toolCall\") {\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\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\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\tif (event.message.role === \"user\") break;\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\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 [, 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\t\t\t\t\tthis.streamingComponent = null;\n\t\t\t\t\tthis.footer.invalidate();\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\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\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\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: { content: event.result.content, details: event.result.details, isError: event.isError };\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\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.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"auto_compaction_start\": {\n\t\t\t\t// Set up escape to abort auto-compaction\n\t\t\t\tthis.autoCompactionEscapeHandler = this.editor.onEscape;\n\t\t\t\tthis.editor.onEscape = () => {\n\t\t\t\t\tthis.session.abortCompaction();\n\t\t\t\t};\n\t\t\t\t// Show compacting indicator with reason\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t\tconst reasonText = event.reason === \"overflow\" ? \"Context overflow detected, \" : \"\";\n\t\t\t\tthis.autoCompactionLoader = new Loader(\n\t\t\t\t\tthis.ui,\n\t\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\t\t`${reasonText}Auto-compacting... (esc to cancel)`,\n\t\t\t\t);\n\t\t\t\tthis.statusContainer.addChild(this.autoCompactionLoader);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"auto_compaction_end\": {\n\t\t\t\t// Restore escape handler\n\t\t\t\tif (this.autoCompactionEscapeHandler) {\n\t\t\t\t\tthis.editor.onEscape = this.autoCompactionEscapeHandler;\n\t\t\t\t\tthis.autoCompactionEscapeHandler = undefined;\n\t\t\t\t}\n\t\t\t\t// Stop loader\n\t\t\t\tif (this.autoCompactionLoader) {\n\t\t\t\t\tthis.autoCompactionLoader.stop();\n\t\t\t\t\tthis.autoCompactionLoader = null;\n\t\t\t\t\tthis.statusContainer.clear();\n\t\t\t\t}\n\t\t\t\t// Handle result\n\t\t\t\tif (event.aborted) {\n\t\t\t\t\tthis.showStatus(\"Auto-compaction cancelled\");\n\t\t\t\t} else if (event.result) {\n\t\t\t\t\t// Rebuild chat to show compacted state\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t// Add compaction component (same as manual /compact)\n\t\t\t\t\tconst compactionComponent = new CompactionComponent(event.result.tokensBefore, event.result.summary);\n\t\t\t\t\tcompactionComponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\tthis.chatContainer.addChild(compactionComponent);\n\t\t\t\t\tthis.footer.updateState(this.session.state);\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"auto_retry_start\": {\n\t\t\t\t// Set up escape to abort retry\n\t\t\t\tthis.retryEscapeHandler = this.editor.onEscape;\n\t\t\t\tthis.editor.onEscape = () => {\n\t\t\t\t\tthis.session.abortRetry();\n\t\t\t\t};\n\t\t\t\t// Show retry indicator\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t\tconst delaySeconds = Math.round(event.delayMs / 1000);\n\t\t\t\tthis.retryLoader = new Loader(\n\t\t\t\t\tthis.ui,\n\t\t\t\t\t(spinner) => theme.fg(\"warning\", spinner),\n\t\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\t\t`Retrying (${event.attempt}/${event.maxAttempts}) in ${delaySeconds}s... (esc to cancel)`,\n\t\t\t\t);\n\t\t\t\tthis.statusContainer.addChild(this.retryLoader);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"auto_retry_end\": {\n\t\t\t\t// Restore escape handler\n\t\t\t\tif (this.retryEscapeHandler) {\n\t\t\t\t\tthis.editor.onEscape = this.retryEscapeHandler;\n\t\t\t\t\tthis.retryEscapeHandler = undefined;\n\t\t\t\t}\n\t\t\t\t// Stop loader\n\t\t\t\tif (this.retryLoader) {\n\t\t\t\t\tthis.retryLoader.stop();\n\t\t\t\t\tthis.retryLoader = null;\n\t\t\t\t\tthis.statusContainer.clear();\n\t\t\t\t}\n\t\t\t\t// Show error only on final failure (success shows normal response)\n\t\t\t\tif (!event.success) {\n\t\t\t\t\tthis.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || \"Unknown error\"}`);\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Extract text content from a user message */\n\tprivate getUserMessageText(message: Message): string {\n\t\tif (message.role !== \"user\") return \"\";\n\t\tconst textBlocks =\n\t\t\ttypeof message.content === \"string\"\n\t\t\t\t? [{ type: \"text\", text: message.content }]\n\t\t\t\t: message.content.filter((c: { type: string }) => c.type === \"text\");\n\t\treturn textBlocks.map((c) => (c as { text: string }).text).join(\"\");\n\t}\n\n\t/** Show a status message in the chat */\n\tprivate showStatus(message: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", message), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addMessageToChat(message: Message | AppMessage): void {\n\t\tif (isBashExecutionMessage(message)) {\n\t\t\tconst component = new BashExecutionComponent(message.command, this.ui);\n\t\t\tif (message.output) {\n\t\t\t\tcomponent.appendOutput(message.output);\n\t\t\t}\n\t\t\tcomponent.setComplete(\n\t\t\t\tmessage.exitCode,\n\t\t\t\tmessage.cancelled,\n\t\t\t\tmessage.truncated ? ({ truncated: true } as TruncationResult) : undefined,\n\t\t\t\tmessage.fullOutputPath,\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(component);\n\t\t\treturn;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst textContent = this.getUserMessageText(message);\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 assistantComponent = new AssistantMessageComponent(message as AssistantMessage, this.hideThinkingBlock);\n\t\t\tthis.chatContainer.addChild(assistantComponent);\n\t\t}\n\t}\n\n\t/**\n\t * Render messages to chat. Used for initial load and rebuild after compaction.\n\t * @param messages Messages to render\n\t * @param options.updateFooter Update footer state\n\t * @param options.populateHistory Add user messages to editor history\n\t */\n\tprivate renderMessages(\n\t\tmessages: readonly (Message | AppMessage)[],\n\t\toptions: { updateFooter?: boolean; populateHistory?: boolean } = {},\n\t): void {\n\t\tthis.isFirstUserMessage = true;\n\t\tthis.pendingTools.clear();\n\n\t\tif (options.updateFooter) {\n\t\t\tthis.footer.updateState(this.session.state);\n\t\t\tthis.updateEditorBorderColor();\n\t\t}\n\n\t\tconst compactionEntry = getLatestCompactionEntry(this.sessionManager.loadEntries());\n\n\t\tfor (const message of messages) {\n\t\t\tif (isBashExecutionMessage(message)) {\n\t\t\t\tthis.addMessageToChat(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (message.role === \"user\") {\n\t\t\t\tconst textContent = this.getUserMessageText(message);\n\t\t\t\tif (textContent) {\n\t\t\t\t\tif (textContent.startsWith(SUMMARY_PREFIX) && compactionEntry) {\n\t\t\t\t\t\tconst summary = textContent.slice(SUMMARY_PREFIX.length, -SUMMARY_SUFFIX.length);\n\t\t\t\t\t\tconst component = new CompactionComponent(compactionEntry.tokensBefore, summary);\n\t\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst userComponent = new UserMessageComponent(textContent, this.isFirstUserMessage);\n\t\t\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\t\t\tthis.isFirstUserMessage = false;\n\t\t\t\t\t\tif (options.populateHistory) {\n\t\t\t\t\t\t\tthis.editor.addToHistory(textContent);\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 === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\tconst assistantComponent = new AssistantMessageComponent(assistantMsg, this.hideThinkingBlock);\n\t\t\t\tthis.chatContainer.addChild(assistantComponent);\n\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\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({ content: [{ type: \"text\", text: errorMessage }], isError: true });\n\t\t\t\t\t\t} else {\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\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\tthis.pendingTools.delete(message.toolCallId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.pendingTools.clear();\n\t\tthis.ui.requestRender();\n\t}\n\n\trenderInitialMessages(state: AgentState): void {\n\t\tthis.renderMessages(state.messages, { updateFooter: true, populateHistory: true });\n\n\t\t// Show compaction info if session was compacted\n\t\tconst entries = this.sessionManager.loadEntries();\n\t\tconst compactionCount = entries.filter((e) => e.type === \"compaction\").length;\n\t\tif (compactionCount > 0) {\n\t\t\tconst times = compactionCount === 1 ? \"1 time\" : `${compactionCount} times`;\n\t\t\tthis.showStatus(`Session compacted ${times}`);\n\t\t}\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\tprivate rebuildChatFromMessages(): void {\n\t\tthis.renderMessages(this.session.messages);\n\t}\n\n\t// =========================================================================\n\t// Key handlers\n\t// =========================================================================\n\n\tprivate handleCtrlC(): void {\n\t\tconst now = Date.now();\n\t\tif (now - this.lastSigintTime < 500) {\n\t\t\tthis.stop();\n\t\t\tprocess.exit(0);\n\t\t} else {\n\t\t\tthis.clearEditor();\n\t\t\tthis.lastSigintTime = now;\n\t\t}\n\t}\n\n\tprivate updateEditorBorderColor(): void {\n\t\tif (this.isBashMode) {\n\t\t\tthis.editor.borderColor = theme.getBashModeBorderColor();\n\t\t} else {\n\t\t\tconst level = this.session.thinkingLevel || \"off\";\n\t\t\tthis.editor.borderColor = theme.getThinkingBorderColor(level);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate cycleThinkingLevel(): void {\n\t\tconst newLevel = this.session.cycleThinkingLevel();\n\t\tif (newLevel === null) {\n\t\t\tthis.showStatus(\"Current model does not support thinking\");\n\t\t} else {\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.showStatus(`Thinking level: ${newLevel}`);\n\t\t}\n\t}\n\n\tprivate async cycleModel(): Promise<void> {\n\t\ttry {\n\t\t\tconst result = await this.session.cycleModel();\n\t\t\tif (result === null) {\n\t\t\t\tconst msg = this.session.scopedModels.length > 0 ? \"Only one model in scope\" : \"Only one model available\";\n\t\t\t\tthis.showStatus(msg);\n\t\t\t} else {\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tconst thinkingStr =\n\t\t\t\t\tresult.model.reasoning && result.thinkingLevel !== \"off\" ? ` (thinking: ${result.thinkingLevel})` : \"\";\n\t\t\t\tthis.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate toggleToolOutputExpansion(): void {\n\t\tthis.toolOutputExpanded = !this.toolOutputExpanded;\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} else if (child instanceof CompactionComponent) {\n\t\t\t\tchild.setExpanded(this.toolOutputExpanded);\n\t\t\t} else if (child instanceof BashExecutionComponent) {\n\t\t\t\tchild.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate toggleThinkingBlockVisibility(): void {\n\t\tthis.hideThinkingBlock = !this.hideThinkingBlock;\n\t\tthis.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);\n\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\tchild.setHideThinkingBlock(this.hideThinkingBlock);\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.clear();\n\t\tthis.rebuildChatFromMessages();\n\t\tthis.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? \"hidden\" : \"visible\"}`);\n\t}\n\n\t// =========================================================================\n\t// UI helpers\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\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", `Error: ${errorMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowWarning(warningMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"warning\", `Warning: ${warningMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowNewVersionNotification(newVersion: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.bold(theme.fg(\"warning\", \"Update Available\")) +\n\t\t\t\t\t\"\\n\" +\n\t\t\t\t\ttheme.fg(\"muted\", `New version ${newVersion} is available. Run: `) +\n\t\t\t\t\ttheme.fg(\"accent\", \"npm install -g @mariozechner/pi-coding-agent\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate updatePendingMessagesDisplay(): void {\n\t\tthis.pendingMessagesContainer.clear();\n\t\tconst queuedMessages = this.session.getQueuedMessages();\n\t\tif (queuedMessages.length > 0) {\n\t\t\tthis.pendingMessagesContainer.addChild(new Spacer(1));\n\t\t\tfor (const message of queuedMessages) {\n\t\t\t\tconst queuedText = theme.fg(\"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\t/** Move pending bash components from pending area to chat */\n\tprivate flushPendingBashComponents(): void {\n\t\tfor (const component of this.pendingBashComponents) {\n\t\t\tthis.pendingMessagesContainer.removeChild(component);\n\t\t\tthis.chatContainer.addChild(component);\n\t\t}\n\t\tthis.pendingBashComponents = [];\n\t}\n\n\t// =========================================================================\n\t// Selectors\n\t// =========================================================================\n\n\t/**\n\t * Shows a selector component in place of the editor.\n\t * @param create Factory that receives a `done` callback and returns the component and focus target\n\t */\n\tprivate showSelector(create: (done: () => void) => { component: Component; focus: Component }): void {\n\t\tconst done = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t};\n\t\tconst { component, focus } = create(done);\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(component);\n\t\tthis.ui.setFocus(focus);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showThinkingSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ThinkingSelectorComponent(\n\t\t\t\tthis.session.thinkingLevel,\n\t\t\t\t(level) => {\n\t\t\t\t\tthis.session.setThinkingLevel(level);\n\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(`Thinking level: ${level}`);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSelectList() };\n\t\t});\n\t}\n\n\tprivate showQueueModeSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new QueueModeSelectorComponent(\n\t\t\t\tthis.session.queueMode,\n\t\t\t\t(mode) => {\n\t\t\t\t\tthis.session.setQueueMode(mode);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(`Queue mode: ${mode}`);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSelectList() };\n\t\t});\n\t}\n\n\tprivate showThemeSelector(): void {\n\t\tconst currentTheme = this.settingsManager.getTheme() || \"dark\";\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ThemeSelectorComponent(\n\t\t\t\tcurrentTheme,\n\t\t\t\t(themeName) => {\n\t\t\t\t\tconst result = setTheme(themeName, true);\n\t\t\t\t\tthis.settingsManager.setTheme(themeName);\n\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\tdone();\n\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\tthis.showStatus(`Theme: ${themeName}`);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.showError(`Failed to load theme \"${themeName}\": ${result.error}\\nFell back to dark theme.`);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t(themeName) => {\n\t\t\t\t\tconst result = setTheme(themeName, true);\n\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSelectList() };\n\t\t});\n\t}\n\n\tprivate showModelSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ModelSelectorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.session.model,\n\t\t\t\tthis.settingsManager,\n\t\t\t\t(model) => {\n\t\t\t\t\tthis.agent.setModel(model);\n\t\t\t\t\tthis.sessionManager.saveModelChange(model.provider, model.id);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showUserMessageSelector(): void {\n\t\tconst userMessages = this.session.getUserMessagesForBranching();\n\n\t\tif (userMessages.length === 0) {\n\t\t\tthis.showStatus(\"No messages to branch from\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new UserMessageSelectorComponent(\n\t\t\t\tuserMessages.map((m) => ({ index: m.entryIndex, text: m.text })),\n\t\t\t\tasync (entryIndex) => {\n\t\t\t\t\tconst result = await this.session.branch(entryIndex);\n\t\t\t\t\tif (result.skipped) {\n\t\t\t\t\t\t// Hook requested to skip conversation restore\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.isFirstUserMessage = true;\n\t\t\t\t\tthis.renderInitialMessages(this.session.state);\n\t\t\t\t\tthis.editor.setText(result.selectedText);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(\"Branched to new session\");\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getMessageList() };\n\t\t});\n\t}\n\n\tprivate showSessionSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new SessionSelectorComponent(\n\t\t\t\tthis.sessionManager,\n\t\t\t\tasync (sessionPath) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tawait this.handleResumeSession(sessionPath);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSessionList() };\n\t\t});\n\t}\n\n\tprivate async handleResumeSession(sessionPath: string): Promise<void> {\n\t\t// Stop loading animation\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = null;\n\t\t}\n\t\tthis.statusContainer.clear();\n\n\t\t// Clear UI state\n\t\tthis.pendingMessagesContainer.clear();\n\t\tthis.streamingComponent = null;\n\t\tthis.pendingTools.clear();\n\n\t\t// Switch session via AgentSession\n\t\tawait this.session.switchSession(sessionPath);\n\n\t\t// Clear and re-render the chat\n\t\tthis.chatContainer.clear();\n\t\tthis.isFirstUserMessage = true;\n\t\tthis.renderInitialMessages(this.session.state);\n\t\tthis.showStatus(\"Resumed session\");\n\t}\n\n\tprivate async showOAuthSelector(mode: \"login\" | \"logout\"): Promise<void> {\n\t\tif (mode === \"logout\") {\n\t\t\tconst loggedInProviders = listOAuthProviders();\n\t\t\tif (loggedInProviders.length === 0) {\n\t\t\t\tthis.showStatus(\"No OAuth providers logged in. Use /login first.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\tmode,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tif (mode === \"login\") {\n\t\t\t\t\t\tthis.showStatus(`Logging in to ${providerId}...`);\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait login(\n\t\t\t\t\t\t\t\tproviderId as SupportedOAuthProvider,\n\t\t\t\t\t\t\t\t(url: string) => {\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"accent\", \"Opening browser to:\"), 1, 0));\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"accent\", url), 1, 0));\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\t\t\tnew Text(theme.fg(\"warning\", \"Paste the authorization code below:\"), 1, 0),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tthis.ui.requestRender();\n\n\t\t\t\t\t\t\t\t\tconst openCmd =\n\t\t\t\t\t\t\t\t\t\tprocess.platform === \"darwin\"\n\t\t\t\t\t\t\t\t\t\t\t? \"open\"\n\t\t\t\t\t\t\t\t\t\t\t: process.platform === \"win32\"\n\t\t\t\t\t\t\t\t\t\t\t\t? \"start\"\n\t\t\t\t\t\t\t\t\t\t\t\t: \"xdg-open\";\n\t\t\t\t\t\t\t\t\texec(`${openCmd} \"${url}\"`);\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\t\treturn new Promise<string>((resolve) => {\n\t\t\t\t\t\t\t\t\t\tconst codeInput = new Input();\n\t\t\t\t\t\t\t\t\t\tcodeInput.onSubmit = () => {\n\t\t\t\t\t\t\t\t\t\t\tconst code = codeInput.getValue();\n\t\t\t\t\t\t\t\t\t\t\tthis.editorContainer.clear();\n\t\t\t\t\t\t\t\t\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\t\t\t\t\t\t\t\t\tthis.ui.setFocus(this.editor);\n\t\t\t\t\t\t\t\t\t\t\tresolve(code);\n\t\t\t\t\t\t\t\t\t\t};\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(codeInput);\n\t\t\t\t\t\t\t\t\t\tthis.ui.setFocus(codeInput);\n\t\t\t\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tinvalidateOAuthCache();\n\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\tnew Text(theme.fg(\"success\", `✓ Successfully logged in to ${providerId}`), 1, 0),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Tokens saved to ${getOAuthPath()}`), 1, 0));\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\t\tthis.showError(`Login failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait logout(providerId as SupportedOAuthProvider);\n\t\t\t\t\t\t\tinvalidateOAuthCache();\n\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\tnew Text(theme.fg(\"success\", `✓ Successfully logged out of ${providerId}`), 1, 0),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthis.chatContainer.addChild(\n\t\t\t\t\t\t\t\tnew Text(theme.fg(\"dim\", `Credentials removed from ${getOAuthPath()}`), 1, 0),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\t\tthis.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\t// =========================================================================\n\t// Command handlers\n\t// =========================================================================\n\n\tprivate handleExportCommand(text: string): void {\n\t\tconst parts = text.split(/\\s+/);\n\t\tconst outputPath = parts.length > 1 ? parts[1] : undefined;\n\n\t\ttry {\n\t\t\tconst filePath = this.session.exportToHtml(outputPath);\n\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\t}\n\n\tprivate handleCopyCommand(): void {\n\t\tconst text = this.session.getLastAssistantText();\n\t\tif (!text) {\n\t\t\tthis.showError(\"No agent messages to copy yet.\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tcopyToClipboard(text);\n\t\t\tthis.showStatus(\"Copied last agent message to clipboard\");\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate handleSessionCommand(): void {\n\t\tconst stats = this.session.getSessionStats();\n\n\t\tlet info = `${theme.bold(\"Session Info\")}\\n\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"File:\")} ${stats.sessionFile}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"ID:\")} ${stats.sessionId}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Messages\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"User:\")} ${stats.userMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Assistant:\")} ${stats.assistantMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tool Calls:\")} ${stats.toolCalls}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tool Results:\")} ${stats.toolResults}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.totalMessages}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Tokens\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Input:\")} ${stats.tokens.input.toLocaleString()}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Output:\")} ${stats.tokens.output.toLocaleString()}\\n`;\n\t\tif (stats.tokens.cacheRead > 0) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Cache Read:\")} ${stats.tokens.cacheRead.toLocaleString()}\\n`;\n\t\t}\n\t\tif (stats.tokens.cacheWrite > 0) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Cache Write:\")} ${stats.tokens.cacheWrite.toLocaleString()}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.tokens.total.toLocaleString()}\\n`;\n\n\t\tif (stats.cost > 0) {\n\t\t\tinfo += `\\n${theme.bold(\"Cost\")}\\n`;\n\t\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.cost.toFixed(4)}`;\n\t\t}\n\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\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\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\tthis.ui.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, getMarkdownTheme()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleClearCommand(): Promise<void> {\n\t\t// Stop loading animation\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = null;\n\t\t}\n\t\tthis.statusContainer.clear();\n\n\t\t// Reset via session\n\t\tawait this.session.reset();\n\n\t\t// Clear UI state\n\t\tthis.chatContainer.clear();\n\t\tthis.pendingMessagesContainer.clear();\n\t\tthis.streamingComponent = null;\n\t\tthis.pendingTools.clear();\n\t\tthis.isFirstUserMessage = true;\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(theme.fg(\"accent\", \"✓ Context cleared\") + \"\\n\" + theme.fg(\"muted\", \"Started fresh session\"), 1, 1),\n\t\t);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleDebugCommand(): void {\n\t\tconst width = this.ui.terminal.columns;\n\t\tconst allLines = this.ui.render(width);\n\n\t\tconst debugLogPath = getDebugLogPath();\n\t\tconst debugData = [\n\t\t\t`Debug output at ${new Date().toISOString()}`,\n\t\t\t`Terminal width: ${width}`,\n\t\t\t`Total lines: ${allLines.length}`,\n\t\t\t\"\",\n\t\t\t\"=== All rendered lines with visible widths ===\",\n\t\t\t...allLines.map((line, idx) => {\n\t\t\t\tconst vw = visibleWidth(line);\n\t\t\t\tconst escaped = JSON.stringify(line);\n\t\t\t\treturn `[${idx}] (w=${vw}) ${escaped}`;\n\t\t\t}),\n\t\t\t\"\",\n\t\t\t\"=== Agent messages (JSONL) ===\",\n\t\t\t...this.session.messages.map((msg) => JSON.stringify(msg)),\n\t\t\t\"\",\n\t\t].join(\"\\n\");\n\n\t\tfs.mkdirSync(path.dirname(debugLogPath), { recursive: true });\n\t\tfs.writeFileSync(debugLogPath, debugData);\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(theme.fg(\"accent\", \"✓ Debug log written\") + \"\\n\" + theme.fg(\"muted\", debugLogPath), 1, 1),\n\t\t);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleBashCommand(command: string): Promise<void> {\n\t\tconst isDeferred = this.session.isStreaming;\n\t\tthis.bashComponent = new BashExecutionComponent(command, this.ui);\n\n\t\tif (isDeferred) {\n\t\t\t// Show in pending area when agent is streaming\n\t\t\tthis.pendingMessagesContainer.addChild(this.bashComponent);\n\t\t\tthis.pendingBashComponents.push(this.bashComponent);\n\t\t} else {\n\t\t\t// Show in chat immediately when agent is idle\n\t\t\tthis.chatContainer.addChild(this.bashComponent);\n\t\t}\n\t\tthis.ui.requestRender();\n\n\t\ttry {\n\t\t\tconst result = await this.session.executeBash(command, (chunk) => {\n\t\t\t\tif (this.bashComponent) {\n\t\t\t\t\tthis.bashComponent.appendOutput(chunk);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(\n\t\t\t\t\tresult.exitCode,\n\t\t\t\t\tresult.cancelled,\n\t\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\t\tresult.fullOutputPath,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(null, false);\n\t\t\t}\n\t\t\tthis.showError(`Bash command failed: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\n\t\tthis.bashComponent = null;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleCompactCommand(customInstructions?: string): Promise<void> {\n\t\tconst entries = this.sessionManager.loadEntries();\n\t\tconst messageCount = entries.filter((e) => e.type === \"message\").length;\n\n\t\tif (messageCount < 2) {\n\t\t\tthis.showWarning(\"Nothing to compact (no messages yet)\");\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.executeCompaction(customInstructions, false);\n\t}\n\n\tprivate handleAutocompactCommand(): void {\n\t\tconst newState = !this.session.autoCompactionEnabled;\n\t\tthis.session.setAutoCompactionEnabled(newState);\n\t\tthis.footer.setAutoCompactEnabled(newState);\n\t\tthis.showStatus(`Auto-compaction: ${newState ? \"on\" : \"off\"}`);\n\t}\n\n\tprivate async executeCompaction(customInstructions?: string, isAuto = false): Promise<void> {\n\t\t// Stop loading animation\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = null;\n\t\t}\n\t\tthis.statusContainer.clear();\n\n\t\t// Set up escape handler during compaction\n\t\tconst originalOnEscape = this.editor.onEscape;\n\t\tthis.editor.onEscape = () => {\n\t\t\tthis.session.abortCompaction();\n\t\t};\n\n\t\t// Show compacting status\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tconst label = isAuto ? \"Auto-compacting context... (esc to cancel)\" : \"Compacting context... (esc to cancel)\";\n\t\tconst compactingLoader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tlabel,\n\t\t);\n\t\tthis.statusContainer.addChild(compactingLoader);\n\t\tthis.ui.requestRender();\n\n\t\ttry {\n\t\t\tconst result = await this.session.compact(customInstructions);\n\n\t\t\t// Rebuild UI\n\t\t\tthis.chatContainer.clear();\n\t\t\tthis.rebuildChatFromMessages();\n\n\t\t\t// Add compaction component\n\t\t\tconst compactionComponent = new CompactionComponent(result.tokensBefore, result.summary);\n\t\t\tcompactionComponent.setExpanded(this.toolOutputExpanded);\n\t\t\tthis.chatContainer.addChild(compactionComponent);\n\n\t\t\tthis.footer.updateState(this.session.state);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\")) {\n\t\t\t\tthis.showError(\"Compaction cancelled\");\n\t\t\t} else {\n\t\t\t\tthis.showError(`Compaction failed: ${message}`);\n\t\t\t}\n\t\t} finally {\n\t\t\tcompactingLoader.stop();\n\t\t\tthis.statusContainer.clear();\n\t\t\tthis.editor.onEscape = originalOnEscape;\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\tthis.footer.dispose();\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\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"]}
@@ -69,6 +69,9 @@ export class InteractiveMode {
69
69
  // Auto-compaction state
70
70
  autoCompactionLoader = null;
71
71
  autoCompactionEscapeHandler;
72
+ // Auto-retry state
73
+ retryLoader = null;
74
+ retryEscapeHandler;
72
75
  // Hook UI state
73
76
  hookSelector = null;
74
77
  hookInput = null;
@@ -694,6 +697,39 @@ export class InteractiveMode {
694
697
  this.ui.requestRender();
695
698
  break;
696
699
  }
700
+ case "auto_retry_start": {
701
+ // Set up escape to abort retry
702
+ this.retryEscapeHandler = this.editor.onEscape;
703
+ this.editor.onEscape = () => {
704
+ this.session.abortRetry();
705
+ };
706
+ // Show retry indicator
707
+ this.statusContainer.clear();
708
+ const delaySeconds = Math.round(event.delayMs / 1000);
709
+ this.retryLoader = new Loader(this.ui, (spinner) => theme.fg("warning", spinner), (text) => theme.fg("muted", text), `Retrying (${event.attempt}/${event.maxAttempts}) in ${delaySeconds}s... (esc to cancel)`);
710
+ this.statusContainer.addChild(this.retryLoader);
711
+ this.ui.requestRender();
712
+ break;
713
+ }
714
+ case "auto_retry_end": {
715
+ // Restore escape handler
716
+ if (this.retryEscapeHandler) {
717
+ this.editor.onEscape = this.retryEscapeHandler;
718
+ this.retryEscapeHandler = undefined;
719
+ }
720
+ // Stop loader
721
+ if (this.retryLoader) {
722
+ this.retryLoader.stop();
723
+ this.retryLoader = null;
724
+ this.statusContainer.clear();
725
+ }
726
+ // Show error only on final failure (success shows normal response)
727
+ if (!event.success) {
728
+ this.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || "Unknown error"}`);
729
+ }
730
+ this.ui.requestRender();
731
+ break;
732
+ }
697
733
  }
698
734
  }
699
735
  /** Extract text content from a user message */
@@ -1041,7 +1077,7 @@ export class InteractiveMode {
1041
1077
  }
1042
1078
  showUserMessageSelector() {
1043
1079
  const userMessages = this.session.getUserMessagesForBranching();
1044
- if (userMessages.length <= 1) {
1080
+ if (userMessages.length === 0) {
1045
1081
  this.showStatus("No messages to branch from");
1046
1082
  return;
1047
1083
  }