aegiscode 3.1.10 → 3.4.2

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 (209) hide show
  1. package/bin/aegis.js +165 -0
  2. package/package.json +18 -86
  3. package/LICENSE +0 -21
  4. package/README.md +0 -394
  5. package/dist/main.js +0 -2171
  6. package/gui/run-gui.cjs +0 -13
  7. package/src/agent/Agent.ts +0 -903
  8. package/src/agent/SimpleAgent.ts +0 -48
  9. package/src/agent/index.ts +0 -54
  10. package/src/agent/orchestrator/AppBuilder.ts +0 -443
  11. package/src/agent/orchestrator/CouncilAgent.ts +0 -310
  12. package/src/agent/orchestrator/DiscussionRoom.ts +0 -462
  13. package/src/agent/orchestrator/OrchestratorAgent.ts +0 -637
  14. package/src/agent/orchestrator/index.ts +0 -38
  15. package/src/agent/orchestrator/utils.ts +0 -397
  16. package/src/agent/pricing.ts +0 -115
  17. package/src/agent/router.ts +0 -74
  18. package/src/agent/routerStats.ts +0 -121
  19. package/src/agent/types.ts +0 -318
  20. package/src/auth/login.ts +0 -383
  21. package/src/cli/config.ts +0 -189
  22. package/src/cli/index.ts +0 -17
  23. package/src/cli/middleware.ts +0 -119
  24. package/src/cli/types.ts +0 -75
  25. package/src/config/ConfigManager.ts +0 -587
  26. package/src/config/index.ts +0 -7
  27. package/src/config/types.ts +0 -584
  28. package/src/context/CompactionService.ts +0 -300
  29. package/src/context/ContextManager.ts +0 -450
  30. package/src/context/FileAnalyzer.ts +0 -267
  31. package/src/context/TokenCounter.ts +0 -265
  32. package/src/context/index.ts +0 -27
  33. package/src/context/storage/CacheStore.ts +0 -176
  34. package/src/context/storage/JSONLStore.ts +0 -201
  35. package/src/context/storage/MemoryStore.ts +0 -205
  36. package/src/context/storage/PersistentStore.ts +0 -327
  37. package/src/context/storage/index.ts +0 -9
  38. package/src/context/storage/pathUtils.ts +0 -114
  39. package/src/context/test.ts +0 -309
  40. package/src/context/types.ts +0 -268
  41. package/src/hooks/HookExecutor.ts +0 -434
  42. package/src/hooks/HookManager.ts +0 -596
  43. package/src/hooks/HookService.ts +0 -269
  44. package/src/hooks/Matcher.ts +0 -157
  45. package/src/hooks/index.ts +0 -63
  46. package/src/hooks/types.ts +0 -424
  47. package/src/main.tsx +0 -596
  48. package/src/mcp/HealthMonitor.ts +0 -150
  49. package/src/mcp/McpClient.ts +0 -491
  50. package/src/mcp/McpRegistry.ts +0 -321
  51. package/src/mcp/createMcpTool.ts +0 -251
  52. package/src/mcp/index.ts +0 -15
  53. package/src/mcp/server.ts +0 -334
  54. package/src/mcp/test-server.ts +0 -88
  55. package/src/mcp/test.ts +0 -372
  56. package/src/mcp/types.ts +0 -247
  57. package/src/memory/AgentMemoryBus.ts +0 -432
  58. package/src/memory/CloudSync.ts +0 -99
  59. package/src/memory/DriveSync.ts +0 -106
  60. package/src/memory/SharedMemory.ts +0 -951
  61. package/src/memory/index.ts +0 -14
  62. package/src/memory/machineFingerprint.ts +0 -40
  63. package/src/orchestrator/SubAgentMetadata.ts +0 -136
  64. package/src/prompts/builder.ts +0 -213
  65. package/src/prompts/default.ts +0 -144
  66. package/src/prompts/index.ts +0 -16
  67. package/src/prompts/plan.ts +0 -64
  68. package/src/prompts/test.ts +0 -78
  69. package/src/services/AnthropicChatService.ts +0 -341
  70. package/src/services/ChatService.ts +0 -347
  71. package/src/services/ClaudeCliChatService.ts +0 -256
  72. package/src/services/CloudSync.ts +0 -168
  73. package/src/services/CostLedger.ts +0 -211
  74. package/src/services/Heartbeat.ts +0 -135
  75. package/src/services/LearningCollector.ts +0 -291
  76. package/src/services/OllamaInstaller.ts +0 -342
  77. package/src/services/VersionChecker.ts +0 -445
  78. package/src/services/index.ts +0 -57
  79. package/src/services/streaming/OpenAIEventAdapter.ts +0 -126
  80. package/src/services/streaming/RenderingProfile.ts +0 -90
  81. package/src/services/streaming/StreamEventParser.ts +0 -181
  82. package/src/services/streaming/ThrottledRenderer.ts +0 -139
  83. package/src/services/streaming/TranscriptBuffer.ts +0 -574
  84. package/src/services/streaming/eventStatusMap.ts +0 -52
  85. package/src/services/streaming/index.ts +0 -46
  86. package/src/services/streaming/renderFormatting.ts +0 -79
  87. package/src/services/streaming/types.ts +0 -234
  88. package/src/skills/SkillLoader.ts +0 -126
  89. package/src/skills/SkillRegistry.ts +0 -366
  90. package/src/skills/index.ts +0 -48
  91. package/src/skills/types.ts +0 -146
  92. package/src/slash-commands/billing.ts +0 -70
  93. package/src/slash-commands/build.ts +0 -413
  94. package/src/slash-commands/builtinCommands.ts +0 -2733
  95. package/src/slash-commands/clone.ts +0 -242
  96. package/src/slash-commands/council.ts +0 -125
  97. package/src/slash-commands/custom/CustomCommandExecutor.ts +0 -143
  98. package/src/slash-commands/custom/CustomCommandLoader.ts +0 -251
  99. package/src/slash-commands/custom/CustomCommandRegistry.ts +0 -144
  100. package/src/slash-commands/custom/index.ts +0 -7
  101. package/src/slash-commands/debate.ts +0 -254
  102. package/src/slash-commands/gmail.ts +0 -105
  103. package/src/slash-commands/index.ts +0 -388
  104. package/src/slash-commands/mcpCommand.ts +0 -205
  105. package/src/slash-commands/types.ts +0 -201
  106. package/src/store/index.ts +0 -76
  107. package/src/store/selectors.ts +0 -246
  108. package/src/store/slices/appSlice.ts +0 -205
  109. package/src/store/slices/commandSlice.ts +0 -115
  110. package/src/store/slices/configSlice.ts +0 -46
  111. package/src/store/slices/focusSlice.ts +0 -64
  112. package/src/store/slices/index.ts +0 -9
  113. package/src/store/slices/sessionSlice.ts +0 -424
  114. package/src/store/streaming-buffer.ts +0 -425
  115. package/src/store/test.ts +0 -296
  116. package/src/store/types.ts +0 -274
  117. package/src/store/vanilla.ts +0 -186
  118. package/src/tools/builtin/bash.ts +0 -236
  119. package/src/tools/builtin/council.ts +0 -105
  120. package/src/tools/builtin/edit.ts +0 -213
  121. package/src/tools/builtin/glob.ts +0 -136
  122. package/src/tools/builtin/grep.ts +0 -263
  123. package/src/tools/builtin/index.ts +0 -61
  124. package/src/tools/builtin/memory.ts +0 -66
  125. package/src/tools/builtin/read.ts +0 -168
  126. package/src/tools/builtin/skill.ts +0 -97
  127. package/src/tools/builtin/snapshot.ts +0 -40
  128. package/src/tools/builtin/task.ts +0 -106
  129. package/src/tools/builtin/write.ts +0 -134
  130. package/src/tools/createTool.ts +0 -221
  131. package/src/tools/execution/ExecutionPipeline.ts +0 -263
  132. package/src/tools/execution/index.ts +0 -40
  133. package/src/tools/execution/stages/CacheStage.ts +0 -131
  134. package/src/tools/execution/stages/ConfirmationStage.ts +0 -203
  135. package/src/tools/execution/stages/DiscoveryStage.ts +0 -46
  136. package/src/tools/execution/stages/ExecutionStage.ts +0 -48
  137. package/src/tools/execution/stages/FormattingStage.ts +0 -44
  138. package/src/tools/execution/stages/HookStage.ts +0 -72
  139. package/src/tools/execution/stages/PermissionStage.ts +0 -287
  140. package/src/tools/execution/stages/PostHookStage.ts +0 -71
  141. package/src/tools/execution/stages/index.ts +0 -12
  142. package/src/tools/execution/test.ts +0 -266
  143. package/src/tools/execution/types.ts +0 -273
  144. package/src/tools/index.ts +0 -81
  145. package/src/tools/registry.ts +0 -304
  146. package/src/tools/schemas.ts +0 -109
  147. package/src/tools/test.ts +0 -220
  148. package/src/tools/types.ts +0 -175
  149. package/src/tools/validation/PermissionChecker.ts +0 -242
  150. package/src/tools/validation/SensitiveFileDetector.ts +0 -210
  151. package/src/tools/validation/index.ts +0 -11
  152. package/src/ui/App.tsx +0 -166
  153. package/src/ui/components/AegisInterface.tsx +0 -484
  154. package/src/ui/components/common/ChatSearch.tsx +0 -150
  155. package/src/ui/components/common/ErrorBoundary.tsx +0 -82
  156. package/src/ui/components/common/ExitMessage.tsx +0 -120
  157. package/src/ui/components/common/LoadingIndicator.tsx +0 -49
  158. package/src/ui/components/common/index.ts +0 -6
  159. package/src/ui/components/dialog/ConfirmationPrompt.tsx +0 -208
  160. package/src/ui/components/dialog/InteractiveSelector.tsx +0 -149
  161. package/src/ui/components/dialog/SetupWizard.tsx +0 -297
  162. package/src/ui/components/dialog/UpdatePrompt.tsx +0 -155
  163. package/src/ui/components/dialog/index.ts +0 -8
  164. package/src/ui/components/index.ts +0 -28
  165. package/src/ui/components/input/CommandSuggestions.tsx +0 -139
  166. package/src/ui/components/input/CustomTextInput.tsx +0 -220
  167. package/src/ui/components/input/InputArea.tsx +0 -361
  168. package/src/ui/components/input/PromptSuggestions.tsx +0 -66
  169. package/src/ui/components/input/index.ts +0 -6
  170. package/src/ui/components/layout/ChatStatusBar.tsx +0 -90
  171. package/src/ui/components/layout/ContextBar.tsx +0 -79
  172. package/src/ui/components/layout/MessageArea.tsx +0 -96
  173. package/src/ui/components/layout/MessageList.tsx +0 -647
  174. package/src/ui/components/layout/MessageSeparator.tsx +0 -26
  175. package/src/ui/components/layout/WelcomeMessage.tsx +0 -93
  176. package/src/ui/components/layout/index.ts +0 -7
  177. package/src/ui/components/markdown/CodeHighlighter.tsx +0 -292
  178. package/src/ui/components/markdown/MessageRenderer.tsx +0 -1211
  179. package/src/ui/components/markdown/index.ts +0 -8
  180. package/src/ui/components/markdown/parser.ts +0 -336
  181. package/src/ui/components/markdown/types.ts +0 -66
  182. package/src/ui/focus/FocusManager.ts +0 -137
  183. package/src/ui/focus/index.ts +0 -13
  184. package/src/ui/focus/types.ts +0 -54
  185. package/src/ui/focus/useFocus.ts +0 -75
  186. package/src/ui/hooks/index.ts +0 -11
  187. package/src/ui/hooks/useAgent.ts +0 -284
  188. package/src/ui/hooks/useCommandHistory.ts +0 -87
  189. package/src/ui/hooks/useCommandProcessor.ts +0 -443
  190. package/src/ui/hooks/useConfirmation.ts +0 -99
  191. package/src/ui/hooks/useCtrlCHandler.ts +0 -100
  192. package/src/ui/hooks/useInputBuffer.ts +0 -122
  193. package/src/ui/hooks/useTerminalSize.ts +0 -68
  194. package/src/ui/hooks/useTerminalWidth.ts +0 -5
  195. package/src/ui/hooks/useWindowedList.ts +0 -118
  196. package/src/ui/render-debugger.ts +0 -621
  197. package/src/ui/test.ts +0 -189
  198. package/src/ui/themes/ThemeManager.ts +0 -332
  199. package/src/ui/themes/aegisTheme.ts +0 -87
  200. package/src/ui/themes/darkTheme.ts +0 -87
  201. package/src/ui/themes/defaultTheme.ts +0 -85
  202. package/src/ui/themes/index.ts +0 -10
  203. package/src/ui/themes/lightTheme.ts +0 -89
  204. package/src/ui/themes/popularThemes.ts +0 -187
  205. package/src/ui/themes/types.ts +0 -130
  206. package/src/utils/clipboard.ts +0 -48
  207. package/src/utils/debug.ts +0 -43
  208. package/src/utils/environment.ts +0 -68
  209. package/src/utils/index.ts +0 -10
package/src/ui/App.tsx DELETED
@@ -1,166 +0,0 @@
1
- /**
2
- * App.tsx - rooted UI with stable references
3
- */
4
-
5
- import React, { useState, useCallback, useEffect, useRef } from 'react';
6
- import { Box, Text } from 'ink';
7
-
8
- import { ErrorBoundary } from './components/common/ErrorBoundary.js';
9
- import pkg from '../../package.json' with { type: 'json' };
10
- import { UpdatePrompt } from './components/dialog/UpdatePrompt.js';
11
- import { AegisInterface } from './components/AegisInterface.js';
12
- import { themeManager } from './themes/index.js';
13
- import type { PermissionMode } from '../cli/types.js';
14
- import type { VersionCheckResult } from '../services/VersionChecker.js';
15
- import type { RuntimeConfig, ClawdConfig } from '../config/types.js';
16
- import { DEFAULT_CONFIG } from '../config/types.js';
17
- import {
18
- ensureStoreInitialized,
19
- appActions,
20
- configActions,
21
- getConfig,
22
- useInitializationStatus,
23
- } from '../store/index.js';
24
-
25
- export interface AppProps {
26
- apiKey: string;
27
- baseURL?: string;
28
- model?: string;
29
- initialMessage?: string;
30
- debug?: boolean;
31
- permissionMode?: PermissionMode;
32
- versionCheckPromise?: Promise<VersionCheckResult | null>;
33
- resumeSessionId?: string;
34
- routerEnabled?: boolean;
35
- }
36
-
37
- function mergeRuntimeConfig(baseConfig: ClawdConfig, props: AppProps): RuntimeConfig {
38
- const runtimeConfig: RuntimeConfig = { ...baseConfig };
39
-
40
- if (props.initialMessage) runtimeConfig.initialMessage = props.initialMessage;
41
- if (props.resumeSessionId) runtimeConfig.resumeSessionId = props.resumeSessionId;
42
- if (props.permissionMode) runtimeConfig.defaultPermissionMode = props.permissionMode;
43
- if (props.routerEnabled) {
44
- runtimeConfig.autoRouter = { ...runtimeConfig.autoRouter, enabled: true };
45
- }
46
- if (props.model) {
47
- // Try to map model name to model ID first
48
- const models = baseConfig.models || [];
49
- const matched = models.find((m: any) => m.model === props.model || m.id === props.model);
50
- runtimeConfig.currentModelId = matched ? matched.id : props.model;
51
- }
52
-
53
- return runtimeConfig;
54
- }
55
-
56
- function initializeStoreState(config: RuntimeConfig): void {
57
- configActions().setConfig(config);
58
-
59
- const isRealKey = (key?: string) => !!key && !key.startsWith('YOUR_');
60
- const hasRealDefault = isRealKey(config.default?.apiKey);
61
- const hasRealModel = config.models?.some(m => isRealKey((m as any).apiKey));
62
-
63
- if (!hasRealDefault && !hasRealModel) {
64
- appActions().setInitializationStatus('needsSetup');
65
- } else {
66
- appActions().setInitializationStatus('ready');
67
- }
68
- }
69
-
70
- const AppWrapper: React.FC<AppProps> = (props) => {
71
- const { versionCheckPromise, permissionMode, ...mainProps } = props;
72
-
73
- const initializationStatus = useInitializationStatus();
74
-
75
- const [versionInfo, setVersionInfo] = useState<VersionCheckResult | null>(null);
76
- const [showUpdatePrompt, setShowUpdatePrompt] = useState(false);
77
- const initDoneRef = useRef(false);
78
-
79
- // Stable initializeApp using ref to avoid re-creating on every render
80
- const propsRef = useRef(props);
81
- propsRef.current = props;
82
- const initializeApp = useCallback(async () => {
83
- const p = propsRef.current;
84
- if (p.debug) console.log('[DEBUG] Initializing application and Store...');
85
-
86
- try {
87
- appActions().setInitializationStatus('loading');
88
-
89
- await ensureStoreInitialized();
90
-
91
- const baseConfig = getConfig() ?? DEFAULT_CONFIG;
92
- const mergedConfig = mergeRuntimeConfig(baseConfig, p);
93
- initializeStoreState(mergedConfig);
94
-
95
- initDoneRef.current = true;
96
- if (p.debug) console.log('[DEBUG] Store initialized successfully');
97
- } catch (error) {
98
- appActions().setInitializationError(
99
- error instanceof Error ? error.message : 'Unknown initialization error'
100
- );
101
- if (propsRef.current.debug) console.log('[DEBUG] Store initialization failed:', error);
102
- }
103
- }, []);
104
-
105
- useEffect(() => {
106
- // Start initialization immediately — don't wait for version check
107
- const initPromise = initializeApp();
108
-
109
- if (versionCheckPromise) {
110
- // Run version check in parallel; only show prompt if init hasn't finished
111
- versionCheckPromise
112
- .then((versionResult) => {
113
- if (versionResult && versionResult.shouldPrompt && !initDoneRef.current) {
114
- setVersionInfo(versionResult);
115
- setShowUpdatePrompt(true);
116
- }
117
- })
118
- .catch((error) => {
119
- if (props.debug) console.log('[DEBUG] Version check failed:', error);
120
- });
121
- }
122
-
123
- // Keep the lint happy — both are used
124
- void initPromise;
125
- // eslint-disable-next-line react-hooks/exhaustive-deps
126
- }, [versionCheckPromise, props.debug]);
127
-
128
- if (showUpdatePrompt && versionInfo) {
129
- return (
130
- <UpdatePrompt
131
- versionInfo={versionInfo}
132
- onComplete={async () => {
133
- setShowUpdatePrompt(false);
134
- await initializeApp();
135
- }}
136
- />
137
- );
138
- }
139
-
140
- if (initializationStatus === 'pending' || initializationStatus === 'loading') {
141
- return (
142
- <Box padding={1}>
143
-
144
- </Box>
145
- );
146
- }
147
-
148
- if (initializationStatus === 'error') {
149
- return (
150
- <Box padding={1} flexDirection="column">
151
- <Text color="red">❌ Initialization failed</Text>
152
- <Text color="gray">Please check your configuration and try again.</Text>
153
- </Box>
154
- );
155
- }
156
-
157
- return <AegisInterface {...mainProps} />;
158
- };
159
-
160
- export const App: React.FC<AppProps> = (props) => {
161
- return (
162
- <ErrorBoundary>
163
- <AppWrapper {...props} />
164
- </ErrorBoundary>
165
- );
166
- };
@@ -1,484 +0,0 @@
1
- /**
2
- * AegisInterface.tsx - Main CLI interface component
3
- *
4
- * Refactored to use extracted hooks: useAgent, useCommandProcessor, useTerminalSize.
5
- * Previously 977 lines — now ~450 lines of orchestration, with logic in focused hooks.
6
- */
7
-
8
- import React, { useEffect, useCallback, useRef, useState, useLayoutEffect } from 'react';
9
- import { Box, Text, useInput, measureElement, type DOMElement } from 'ink';
10
-
11
- // Store
12
- import {
13
- useInitializationStatus,
14
- useActiveModal,
15
- useMessages,
16
- usePendingCommands,
17
- useAutoRouterActiveModel,
18
- useRouterEnabled,
19
- useWorkflow,
20
- sessionActions,
21
- configActions,
22
- commandActions,
23
- getState,
24
- subscribe,
25
- } from '../../store/index.js';
26
-
27
- // Hooks
28
- import { useTerminalSize } from '../hooks/useTerminalSize.js';
29
- import { useCtrlCHandler } from '../hooks/useCtrlCHandler.js';
30
- import { useConfirmation } from '../hooks/useConfirmation.js';
31
- import { useAgent } from '../hooks/useAgent.js';
32
- import { useCommandProcessor } from '../hooks/useCommandProcessor.js';
33
-
34
- // Components
35
- import { MessageRenderer } from './markdown/MessageRenderer.js';
36
- import { InputArea } from './input/InputArea.js';
37
- import { ChatStatusBar } from './layout/ChatStatusBar.js';
38
- import { WelcomeMessage } from './layout/WelcomeMessage.js';
39
- import { MessageList } from './layout/MessageList.js';
40
- import { ContextBar } from './layout/ContextBar.js';
41
- import { ConfirmationPrompt } from './dialog/ConfirmationPrompt.js';
42
- import { InteractiveSelector, type SelectorOption } from './dialog/InteractiveSelector.js';
43
- import { SetupWizard } from './dialog/SetupWizard.js';
44
- import { ExitMessage } from './common/ExitMessage.js';
45
- import { ErrorBoundary } from './common/ErrorBoundary.js';
46
-
47
- // Focus
48
- import { FocusId, focusActions } from '../focus/index.js';
49
- import { copyToClipboard } from '../../utils/clipboard.js';
50
-
51
- // Heartbeat (online status ping)
52
- import { startHeartbeat, stopHeartbeat } from '../../services/Heartbeat.js';
53
-
54
- // Theme
55
- import { themeManager } from '../themes/index.js';
56
-
57
- // ========== Types ==========
58
-
59
- export interface AegisInterfaceProps {
60
- apiKey: string;
61
- baseURL?: string;
62
- model?: string;
63
- initialMessage?: string;
64
- debug?: boolean;
65
- resumeSessionId?: string;
66
- }
67
-
68
- // ========== Memoized Sub-Components ==========
69
-
70
- const QueuedCommands: React.FC = React.memo(() => {
71
- const pendingCommands = usePendingCommands();
72
- const theme = themeManager.getTheme();
73
-
74
- if (pendingCommands.length === 0) return null;
75
-
76
- return (
77
- <Box flexDirection="column" marginTop={0} marginBottom={0}>
78
- {pendingCommands.map((cmd, i) => (
79
- <Box key={i} flexDirection="row" marginLeft={1}>
80
- <Text color={theme.colors.text.muted} dimColor>
81
- <Text color={theme.colors.primary}>#{i+1}</Text> {cmd.length > 60 ? cmd.slice(0, 60) + '...' : cmd}
82
- </Text>
83
- </Box>
84
- ))}
85
- </Box>
86
- );
87
- });
88
-
89
- QueuedCommands.displayName = 'QueuedCommands';
90
-
91
- const RecentMessagesPreview: React.FC<{ terminalWidth: number; count?: number }> = React.memo(
92
- ({ terminalWidth, count = 3 }) => {
93
- const messages = getState().session.messages;
94
- const recentMessages = messages.slice(-count);
95
-
96
- return (
97
- <Box flexDirection="column" marginBottom={1}>
98
- {recentMessages.map((msg, index) => (
99
- <MessageRenderer
100
- key={msg.id || index}
101
- content={msg.content}
102
- role={msg.role}
103
- terminalWidth={terminalWidth}
104
- showPrefix={true}
105
- />
106
- ))}
107
- </Box>
108
- );
109
- }
110
- );
111
-
112
- RecentMessagesPreview.displayName = 'RecentMessagesPreview';
113
-
114
- // ========== Main Component ==========
115
-
116
- export const AegisInterface: React.FC<AegisInterfaceProps> = ({
117
- apiKey,
118
- baseURL,
119
- model,
120
- initialMessage,
121
- debug,
122
- resumeSessionId,
123
- }) => {
124
- // ==================== Terminal Size ====================
125
- const { width: terminalWidth, height: terminalHeight } = useTerminalSize();
126
-
127
- // ==================== Store State ====================
128
- const initializationStatus = useInitializationStatus();
129
- const activeModal = useActiveModal();
130
- const messages = useMessages();
131
-
132
- const getMessages = useCallback(() => getState().session.messages, []);
133
-
134
- // ==================== Agent Hook ====================
135
- const {
136
- agentRef,
137
- contextManagerRef,
138
- isInitializing,
139
- initError,
140
- currentModel,
141
- handleSetupComplete,
142
- } = useAgent({ apiKey, baseURL, model, debug, resumeSessionId });
143
-
144
- const autoRouterActiveModel = useAutoRouterActiveModel();
145
- const routerEnabled = useRouterEnabled();
146
- const workflow = useWorkflow();
147
-
148
- // ==================== Below-MessageList overhead measurement ====================
149
- // MessageList budgets its viewport with a fixed UI_OVERHEAD constant that only
150
- // accounts for the input area/status bar. ContextBar (workflow indicator) and
151
- // QueuedCommands render below it and can take a variable number of extra rows
152
- // (e.g. ContextBar only appears at all when workflow.visible) — without telling
153
- // MessageList about that, its row budget and what's actually left on screen drift
154
- // apart, which looks like messages getting clipped/disappearing. Measuring the
155
- // actual rendered height post-layout keeps the two in sync regardless of what
156
- // gets added below the message list in the future.
157
- const belowMessageListRef = useRef<DOMElement>(null);
158
- const [belowOverheadLines, setBelowOverheadLines] = useState(0);
159
- const pendingCommandsForOverhead = usePendingCommands();
160
- useLayoutEffect(() => {
161
- if (!belowMessageListRef.current) return;
162
- const { height } = measureElement(belowMessageListRef.current);
163
- setBelowOverheadLines(height);
164
- }, [workflow, pendingCommandsForOverhead.length]);
165
-
166
- // ==================== Stable Refs ====================
167
- const debugRef = useRef(debug);
168
- debugRef.current = debug;
169
- const modelRef = useRef(model);
170
- modelRef.current = model;
171
- const getMessagesRef = useRef(getMessages);
172
- getMessagesRef.current = getMessages;
173
-
174
- // ==================== Local State ====================
175
- const [isExiting, setIsExiting] = useState(false);
176
- const [exitSessionId, setExitSessionId] = useState<string | null>(null);
177
- const [isScrolledUp, setIsScrolledUp] = useState(false);
178
- const [renderLatency, setRenderLatency] = useState(0);
179
-
180
- const renderLatencyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
181
- const handleRenderLatency = useCallback((ms: number) => {
182
- // Debounce: only update state at most every 500ms
183
- if (renderLatencyTimerRef.current) return;
184
- renderLatencyTimerRef.current = setTimeout(() => {
185
- renderLatencyTimerRef.current = null;
186
- }, 500);
187
- setRenderLatency(ms);
188
- }, []);
189
-
190
- // Clean up latency debounce timer on unmount
191
- useEffect(() => {
192
- return () => {
193
- if (renderLatencyTimerRef.current) clearTimeout(renderLatencyTimerRef.current);
194
- };
195
- }, []);
196
-
197
- // ==================== Heartbeat (online status) ====================
198
- useEffect(() => {
199
- startHeartbeat();
200
- return () => stopHeartbeat();
201
- }, []);
202
-
203
- const [selectorState, setSelectorState] = useState<{
204
- isVisible: boolean;
205
- title: string;
206
- options: SelectorOption[];
207
- handler: 'theme' | 'model' | null;
208
- }>({
209
- isVisible: false,
210
- title: '',
211
- options: [],
212
- handler: null,
213
- });
214
-
215
- // ==================== Hooks ====================
216
- const { confirmationState, confirmationHandler, handleResponse } = useConfirmation();
217
- const confirmationHandlerRef = useRef(confirmationHandler);
218
- confirmationHandlerRef.current = confirmationHandler;
219
-
220
- // Command processor — extracted hook
221
- const { processCommand, handleSubmit, processQueue } = useCommandProcessor({
222
- agentRef,
223
- contextManagerRef,
224
- modelRef,
225
- debugRef,
226
- getMessagesRef,
227
- confirmationHandlerRef,
228
- onSelectorRequest: (state) => {
229
- setSelectorState({
230
- isVisible: true,
231
- title: state.title,
232
- options: state.options,
233
- handler: state.handler,
234
- });
235
- focusActions.setFocus(FocusId.SELECTOR);
236
- },
237
- });
238
-
239
- // ESC interrupt (scrolling handled by MessageList internally)
240
- useInput((_input, key) => {
241
- if (key.escape && getState().session.isThinking) {
242
- commandActions().abort();
243
- sessionActions().setThinking(false);
244
- }
245
- });
246
-
247
- // ==================== Alt+C: Copy last assistant reply ====================
248
- useInput((_input, key) => {
249
- if (key.meta && _input === 'c') {
250
- const msgs = getState().session.messages.filter(m => m.role === 'assistant');
251
- if (msgs.length === 0) return;
252
- const last = msgs[msgs.length - 1];
253
- // Strip markdown for clean copy
254
- const plain = last.content
255
- .replace(/```[\s\S]*?```/g, m => m.replace(/```\w*\n?/, '').replace(/\n?```/, ''))
256
- .replace(/\*\*(.+?)\*\*/g, '$1')
257
- .replace(/\*(.+?)\*/g, '$1')
258
- .replace(/`([^`]+)`/g, '$1')
259
- .replace(/~~(.+?)~~/g, '$1')
260
- .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
261
- .replace(/^#{1,6}\s+/gm, '')
262
- .replace(/^>\s+/gm, '')
263
- .trim();
264
- if (!plain) return;
265
- copyToClipboard(plain)
266
- .then(async () => {
267
- const { nanoid } = await import('nanoid');
268
- sessionActions().addMessage({
269
- id: nanoid(),
270
- role: 'system',
271
- content: '✓ Copied last reply to clipboard',
272
- timestamp: Date.now(),
273
- });
274
- })
275
- .catch(async (err) => {
276
- const { nanoid } = await import('nanoid');
277
- sessionActions().addMessage({
278
- id: nanoid(),
279
- role: 'system',
280
- content: `✗ Copy failed: ${err instanceof Error ? err.message : String(err)}`,
281
- timestamp: Date.now(),
282
- });
283
- });
284
- }
285
- });
286
-
287
- // ==================== Alt+R: Toggle auto-router ====================
288
- useInput((_input, key) => {
289
- if (key.meta && _input === 'r') {
290
- const isEnabled = getState().config.config?.autoRouter?.enabled ?? false;
291
- handleSubmit(isEnabled ? '/router off' : '/router on');
292
- }
293
- });
294
-
295
- // ==================== Ctrl+C Handler ====================
296
- useCtrlCHandler({
297
- onInterrupt: () => {
298
- commandActions().abort();
299
- sessionActions().setThinking(false);
300
- },
301
- onBeforeExit: () => {
302
- const currentMessageCount = getState().session.messages.length;
303
- const currentSessionId = contextManagerRef.current?.getCurrentSessionId() || getState().session.sessionId;
304
- if (currentSessionId && currentMessageCount > 0) {
305
- // Flush pending saves before exit so the last messages are persisted
306
- contextManagerRef.current?.flush().catch(() => {});
307
- setExitSessionId(currentSessionId);
308
- setIsExiting(true);
309
- return true;
310
- }
311
- return false;
312
- },
313
- });
314
-
315
- // ==================== Focus Management ====================
316
- useEffect(() => {
317
- if (confirmationState.isVisible) return;
318
- if (selectorState.isVisible) {
319
- focusActions.setFocus(FocusId.SELECTOR);
320
- } else if (activeModal === 'themeSelector') {
321
- focusActions.setFocus(FocusId.THEME_SELECTOR);
322
- } else {
323
- focusActions.setFocus(FocusId.MAIN_INPUT);
324
- }
325
- }, [confirmationState.isVisible, selectorState.isVisible, activeModal]);
326
-
327
- // ==================== Selector Handlers ====================
328
- const handleSelectorSelect = useCallback(async (value: string) => {
329
- const { handler } = selectorState;
330
- focusActions.setFocus(FocusId.MAIN_INPUT);
331
- setSelectorState({ isVisible: false, title: '', options: [], handler: null });
332
-
333
- if (handler === 'theme') {
334
- themeManager.setTheme(value);
335
- sessionActions().addAssistantMessage('✓ ' + value);
336
- } else if (handler === 'model') {
337
- if (value.startsWith('__ollama__')) {
338
- const modelName = value.slice('__ollama__'.length);
339
- const id = modelName.replace(/[^a-z0-9_-]/gi, '-').toLowerCase();
340
- try {
341
- const fs = await import('fs');
342
- const path = await import('path');
343
- const os = await import('os');
344
- const cfgPath = path.join(os.homedir(), '.aegiscode', 'config.json');
345
- try {
346
- const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
347
- cfg.models = cfg.models || [];
348
- if (!cfg.models.find((m: any) => m.id === id)) {
349
- cfg.models.push({ id, name: modelName, model: modelName, baseURL: 'http://localhost:11434/v1', apiKey: 'ollama' });
350
- }
351
- cfg.currentModelId = id;
352
- fs.writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));
353
- } catch { /* non-fatal */ }
354
- } catch { /* non-fatal */ }
355
- configActions().updateConfig({ currentModelId: id });
356
- } else {
357
- configActions().updateConfig({ currentModelId: value });
358
- }
359
- }
360
- }, [selectorState]);
361
-
362
- const handleSelectorCancel = useCallback(() => {
363
- setSelectorState({ isVisible: false, title: '', options: [], handler: null });
364
- focusActions.setFocus(FocusId.MAIN_INPUT);
365
- }, []);
366
-
367
- // ==================== Queue Processor ====================
368
- useEffect(() => {
369
- let prevIsThinking = getState().session.isThinking;
370
- const unsubscribe = subscribe((state) => {
371
- const currentIsThinking = state.session.isThinking;
372
- const hasPending = state.command.pendingCommands.length > 0;
373
- if (prevIsThinking && !currentIsThinking && hasPending) {
374
- processQueue();
375
- }
376
- prevIsThinking = currentIsThinking;
377
- });
378
- return unsubscribe;
379
- }, [processQueue]);
380
-
381
- // ==================== Initial Message ====================
382
- const initialMessageSent = useRef(false);
383
- useEffect(() => {
384
- if (initialMessage && !initialMessageSent.current && !isInitializing && agentRef.current) {
385
- initialMessageSent.current = true;
386
- handleSubmit(initialMessage);
387
- }
388
- }, [initialMessage, handleSubmit, isInitializing]);
389
-
390
- // ==================== Scroll State Notification ====================
391
- const handleScrolledUpChange = useCallback((scrolledUp: boolean) => {
392
- setIsScrolledUp(scrolledUp);
393
- }, []);
394
-
395
- // ==================== Render ====================
396
-
397
- if (isInitializing) {
398
- return (
399
- <Box flexDirection="column" padding={1}>
400
- <Box>
401
- <Text color="yellow"> Initializing...</Text>
402
- </Box>
403
- </Box>
404
- );
405
- }
406
-
407
- if (initError) {
408
- return (
409
- <Box flexDirection="column" padding={1}>
410
- <Text color="red">Agent initialization failed:</Text>
411
- <Text color="red">{initError}</Text>
412
- </Box>
413
- );
414
- }
415
-
416
- if (initializationStatus === 'needsSetup') {
417
- return <SetupWizard onComplete={handleSetupComplete} />;
418
- }
419
-
420
- const hasPendingInitialMessage = !!(initialMessage && !initialMessageSent.current);
421
-
422
- return (
423
- <Box flexDirection="column" width="100%" paddingX={0} flexGrow={1}>
424
- {messages.length === 0 && <WelcomeMessage terminalWidth={terminalWidth - 2} />}
425
-
426
- {selectorState.isVisible ? (
427
- <>
428
- <RecentMessagesPreview terminalWidth={terminalWidth - 2} count={3} />
429
- <InteractiveSelector
430
- title={selectorState.title}
431
- options={selectorState.options}
432
- onSelect={handleSelectorSelect}
433
- onCancel={handleSelectorCancel}
434
- focusId={FocusId.SELECTOR}
435
- />
436
- </>
437
- ) : (
438
- <>
439
- {messages.length > 0 && (
440
- <ErrorBoundary name="MessageList" fallback={<Text color="red">Message list error</Text>}>
441
- <Box flexGrow={1} minHeight={0}>
442
- <MessageList
443
- terminalWidth={terminalWidth - 2}
444
- terminalHeight={terminalHeight}
445
- onScrolledUpChange={handleScrolledUpChange}
446
- onRenderLatency={handleRenderLatency}
447
- extraOverheadLines={belowOverheadLines}
448
- />
449
- </Box>
450
- </ErrorBoundary>
451
- )}
452
- <Box ref={belowMessageListRef} flexDirection="column">
453
- <ContextBar workflow={workflow} />
454
- <QueuedCommands />
455
- </Box>
456
-
457
- {confirmationState.isVisible && confirmationState.details && (
458
- <ErrorBoundary name="ConfirmationPrompt" fallback={null}>
459
- <ConfirmationPrompt
460
- details={confirmationState.details}
461
- onResponse={handleResponse}
462
- />
463
- </ErrorBoundary>
464
- )}
465
-
466
- <ErrorBoundary name="InputArea" fallback={<Text color="red">Input error — restart app</Text>}>
467
- <InputArea onSubmit={handleSubmit} />
468
- </ErrorBoundary>
469
- <ChatStatusBar
470
- model={autoRouterActiveModel || currentModel}
471
- modelIsAuto={!!autoRouterActiveModel}
472
- isScrolledUp={messages.length > 0 && isScrolledUp}
473
- renderLatency={renderLatency}
474
- routerEnabled={routerEnabled}
475
- />
476
- </>
477
- )}
478
-
479
- {isExiting && exitSessionId && (
480
- <ExitMessage sessionId={exitSessionId} />
481
- )}
482
- </Box>
483
- );
484
- };