aegiscode 3.1.8 → 3.1.10

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 (206) hide show
  1. package/README.md +23 -15
  2. package/dist/main.js +549 -552
  3. package/package.json +4 -2
  4. package/src/agent/Agent.ts +903 -0
  5. package/src/agent/SimpleAgent.ts +48 -0
  6. package/src/agent/index.ts +54 -0
  7. package/src/agent/orchestrator/AppBuilder.ts +443 -0
  8. package/src/agent/orchestrator/CouncilAgent.ts +310 -0
  9. package/src/agent/orchestrator/DiscussionRoom.ts +462 -0
  10. package/src/agent/orchestrator/OrchestratorAgent.ts +637 -0
  11. package/src/agent/orchestrator/index.ts +38 -0
  12. package/src/agent/orchestrator/utils.ts +397 -0
  13. package/src/agent/pricing.ts +115 -0
  14. package/src/agent/router.ts +74 -0
  15. package/src/agent/routerStats.ts +121 -0
  16. package/src/agent/types.ts +318 -0
  17. package/src/auth/login.ts +383 -0
  18. package/src/cli/config.ts +189 -0
  19. package/src/cli/index.ts +17 -0
  20. package/src/cli/middleware.ts +119 -0
  21. package/src/cli/types.ts +75 -0
  22. package/src/config/ConfigManager.ts +587 -0
  23. package/src/config/index.ts +7 -0
  24. package/src/config/types.ts +584 -0
  25. package/src/context/CompactionService.ts +300 -0
  26. package/src/context/ContextManager.ts +450 -0
  27. package/src/context/FileAnalyzer.ts +267 -0
  28. package/src/context/TokenCounter.ts +265 -0
  29. package/src/context/index.ts +27 -0
  30. package/src/context/storage/CacheStore.ts +176 -0
  31. package/src/context/storage/JSONLStore.ts +201 -0
  32. package/src/context/storage/MemoryStore.ts +205 -0
  33. package/src/context/storage/PersistentStore.ts +327 -0
  34. package/src/context/storage/index.ts +9 -0
  35. package/src/context/storage/pathUtils.ts +114 -0
  36. package/src/context/test.ts +309 -0
  37. package/src/context/types.ts +268 -0
  38. package/src/hooks/HookExecutor.ts +434 -0
  39. package/src/hooks/HookManager.ts +596 -0
  40. package/src/hooks/HookService.ts +269 -0
  41. package/src/hooks/Matcher.ts +157 -0
  42. package/src/hooks/index.ts +63 -0
  43. package/src/hooks/types.ts +424 -0
  44. package/src/main.tsx +596 -0
  45. package/src/mcp/HealthMonitor.ts +150 -0
  46. package/src/mcp/McpClient.ts +491 -0
  47. package/src/mcp/McpRegistry.ts +321 -0
  48. package/src/mcp/createMcpTool.ts +251 -0
  49. package/src/mcp/index.ts +15 -0
  50. package/src/mcp/server.ts +334 -0
  51. package/src/mcp/test-server.ts +88 -0
  52. package/src/mcp/test.ts +372 -0
  53. package/src/mcp/types.ts +247 -0
  54. package/src/memory/AgentMemoryBus.ts +432 -0
  55. package/src/memory/CloudSync.ts +99 -0
  56. package/src/memory/DriveSync.ts +106 -0
  57. package/src/memory/SharedMemory.ts +951 -0
  58. package/src/memory/index.ts +14 -0
  59. package/src/memory/machineFingerprint.ts +40 -0
  60. package/src/orchestrator/SubAgentMetadata.ts +136 -0
  61. package/src/prompts/builder.ts +213 -0
  62. package/src/prompts/default.ts +144 -0
  63. package/src/prompts/index.ts +16 -0
  64. package/src/prompts/plan.ts +64 -0
  65. package/src/prompts/test.ts +78 -0
  66. package/src/services/AnthropicChatService.ts +341 -0
  67. package/src/services/ChatService.ts +347 -0
  68. package/src/services/ClaudeCliChatService.ts +256 -0
  69. package/src/services/CloudSync.ts +168 -0
  70. package/src/services/CostLedger.ts +211 -0
  71. package/src/services/Heartbeat.ts +135 -0
  72. package/src/services/LearningCollector.ts +291 -0
  73. package/src/services/OllamaInstaller.ts +342 -0
  74. package/src/services/VersionChecker.ts +445 -0
  75. package/src/services/index.ts +57 -0
  76. package/src/services/streaming/OpenAIEventAdapter.ts +126 -0
  77. package/src/services/streaming/RenderingProfile.ts +90 -0
  78. package/src/services/streaming/StreamEventParser.ts +181 -0
  79. package/src/services/streaming/ThrottledRenderer.ts +139 -0
  80. package/src/services/streaming/TranscriptBuffer.ts +574 -0
  81. package/src/services/streaming/eventStatusMap.ts +52 -0
  82. package/src/services/streaming/index.ts +46 -0
  83. package/src/services/streaming/renderFormatting.ts +79 -0
  84. package/src/services/streaming/types.ts +234 -0
  85. package/src/skills/SkillLoader.ts +126 -0
  86. package/src/skills/SkillRegistry.ts +366 -0
  87. package/src/skills/index.ts +48 -0
  88. package/src/skills/types.ts +146 -0
  89. package/src/slash-commands/billing.ts +70 -0
  90. package/src/slash-commands/build.ts +413 -0
  91. package/src/slash-commands/builtinCommands.ts +2733 -0
  92. package/src/slash-commands/clone.ts +242 -0
  93. package/src/slash-commands/council.ts +125 -0
  94. package/src/slash-commands/custom/CustomCommandExecutor.ts +143 -0
  95. package/src/slash-commands/custom/CustomCommandLoader.ts +251 -0
  96. package/src/slash-commands/custom/CustomCommandRegistry.ts +144 -0
  97. package/src/slash-commands/custom/index.ts +7 -0
  98. package/src/slash-commands/debate.ts +254 -0
  99. package/src/slash-commands/gmail.ts +105 -0
  100. package/src/slash-commands/index.ts +388 -0
  101. package/src/slash-commands/mcpCommand.ts +205 -0
  102. package/src/slash-commands/types.ts +201 -0
  103. package/src/store/index.ts +76 -0
  104. package/src/store/selectors.ts +246 -0
  105. package/src/store/slices/appSlice.ts +205 -0
  106. package/src/store/slices/commandSlice.ts +115 -0
  107. package/src/store/slices/configSlice.ts +46 -0
  108. package/src/store/slices/focusSlice.ts +64 -0
  109. package/src/store/slices/index.ts +9 -0
  110. package/src/store/slices/sessionSlice.ts +424 -0
  111. package/src/store/streaming-buffer.ts +425 -0
  112. package/src/store/test.ts +296 -0
  113. package/src/store/types.ts +274 -0
  114. package/src/store/vanilla.ts +186 -0
  115. package/src/tools/builtin/bash.ts +236 -0
  116. package/src/tools/builtin/council.ts +105 -0
  117. package/src/tools/builtin/edit.ts +213 -0
  118. package/src/tools/builtin/glob.ts +136 -0
  119. package/src/tools/builtin/grep.ts +263 -0
  120. package/src/tools/builtin/index.ts +61 -0
  121. package/src/tools/builtin/memory.ts +66 -0
  122. package/src/tools/builtin/read.ts +168 -0
  123. package/src/tools/builtin/skill.ts +97 -0
  124. package/src/tools/builtin/snapshot.ts +40 -0
  125. package/src/tools/builtin/task.ts +106 -0
  126. package/src/tools/builtin/write.ts +134 -0
  127. package/src/tools/createTool.ts +221 -0
  128. package/src/tools/execution/ExecutionPipeline.ts +263 -0
  129. package/src/tools/execution/index.ts +40 -0
  130. package/src/tools/execution/stages/CacheStage.ts +131 -0
  131. package/src/tools/execution/stages/ConfirmationStage.ts +203 -0
  132. package/src/tools/execution/stages/DiscoveryStage.ts +46 -0
  133. package/src/tools/execution/stages/ExecutionStage.ts +48 -0
  134. package/src/tools/execution/stages/FormattingStage.ts +44 -0
  135. package/src/tools/execution/stages/HookStage.ts +72 -0
  136. package/src/tools/execution/stages/PermissionStage.ts +287 -0
  137. package/src/tools/execution/stages/PostHookStage.ts +71 -0
  138. package/src/tools/execution/stages/index.ts +12 -0
  139. package/src/tools/execution/test.ts +266 -0
  140. package/src/tools/execution/types.ts +273 -0
  141. package/src/tools/index.ts +81 -0
  142. package/src/tools/registry.ts +304 -0
  143. package/src/tools/schemas.ts +109 -0
  144. package/src/tools/test.ts +220 -0
  145. package/src/tools/types.ts +175 -0
  146. package/src/tools/validation/PermissionChecker.ts +242 -0
  147. package/src/tools/validation/SensitiveFileDetector.ts +210 -0
  148. package/src/tools/validation/index.ts +11 -0
  149. package/src/ui/App.tsx +166 -0
  150. package/src/ui/components/AegisInterface.tsx +484 -0
  151. package/src/ui/components/common/ChatSearch.tsx +150 -0
  152. package/src/ui/components/common/ErrorBoundary.tsx +82 -0
  153. package/src/ui/components/common/ExitMessage.tsx +120 -0
  154. package/src/ui/components/common/LoadingIndicator.tsx +49 -0
  155. package/src/ui/components/common/index.ts +6 -0
  156. package/src/ui/components/dialog/ConfirmationPrompt.tsx +208 -0
  157. package/src/ui/components/dialog/InteractiveSelector.tsx +149 -0
  158. package/src/ui/components/dialog/SetupWizard.tsx +297 -0
  159. package/src/ui/components/dialog/UpdatePrompt.tsx +155 -0
  160. package/src/ui/components/dialog/index.ts +8 -0
  161. package/src/ui/components/index.ts +28 -0
  162. package/src/ui/components/input/CommandSuggestions.tsx +139 -0
  163. package/src/ui/components/input/CustomTextInput.tsx +220 -0
  164. package/src/ui/components/input/InputArea.tsx +361 -0
  165. package/src/ui/components/input/PromptSuggestions.tsx +66 -0
  166. package/src/ui/components/input/index.ts +6 -0
  167. package/src/ui/components/layout/ChatStatusBar.tsx +90 -0
  168. package/src/ui/components/layout/ContextBar.tsx +79 -0
  169. package/src/ui/components/layout/MessageArea.tsx +96 -0
  170. package/src/ui/components/layout/MessageList.tsx +647 -0
  171. package/src/ui/components/layout/MessageSeparator.tsx +26 -0
  172. package/src/ui/components/layout/WelcomeMessage.tsx +93 -0
  173. package/src/ui/components/layout/index.ts +7 -0
  174. package/src/ui/components/markdown/CodeHighlighter.tsx +292 -0
  175. package/src/ui/components/markdown/MessageRenderer.tsx +1211 -0
  176. package/src/ui/components/markdown/index.ts +8 -0
  177. package/src/ui/components/markdown/parser.ts +336 -0
  178. package/src/ui/components/markdown/types.ts +66 -0
  179. package/src/ui/focus/FocusManager.ts +137 -0
  180. package/src/ui/focus/index.ts +13 -0
  181. package/src/ui/focus/types.ts +54 -0
  182. package/src/ui/focus/useFocus.ts +75 -0
  183. package/src/ui/hooks/index.ts +11 -0
  184. package/src/ui/hooks/useAgent.ts +284 -0
  185. package/src/ui/hooks/useCommandHistory.ts +87 -0
  186. package/src/ui/hooks/useCommandProcessor.ts +443 -0
  187. package/src/ui/hooks/useConfirmation.ts +99 -0
  188. package/src/ui/hooks/useCtrlCHandler.ts +100 -0
  189. package/src/ui/hooks/useInputBuffer.ts +122 -0
  190. package/src/ui/hooks/useTerminalSize.ts +68 -0
  191. package/src/ui/hooks/useTerminalWidth.ts +5 -0
  192. package/src/ui/hooks/useWindowedList.ts +118 -0
  193. package/src/ui/render-debugger.ts +621 -0
  194. package/src/ui/test.ts +189 -0
  195. package/src/ui/themes/ThemeManager.ts +332 -0
  196. package/src/ui/themes/aegisTheme.ts +87 -0
  197. package/src/ui/themes/darkTheme.ts +87 -0
  198. package/src/ui/themes/defaultTheme.ts +85 -0
  199. package/src/ui/themes/index.ts +10 -0
  200. package/src/ui/themes/lightTheme.ts +89 -0
  201. package/src/ui/themes/popularThemes.ts +187 -0
  202. package/src/ui/themes/types.ts +130 -0
  203. package/src/utils/clipboard.ts +48 -0
  204. package/src/utils/debug.ts +43 -0
  205. package/src/utils/environment.ts +68 -0
  206. package/src/utils/index.ts +10 -0
@@ -0,0 +1,82 @@
1
+ /**
2
+ * ErrorBoundary - React 错误边界组件
3
+ *
4
+ * Enhanced with region name for logging and optional fallback render prop.
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Box, Text } from 'ink';
9
+
10
+ interface Props {
11
+ children: React.ReactNode;
12
+ fallback?: React.ReactNode;
13
+ /** Region name for debug logging (e.g. 'MessageList', 'ThinkingPanel') */
14
+ name?: string;
15
+ /** Called when an error is caught, for telemetry */
16
+ onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
17
+ }
18
+
19
+ interface State {
20
+ hasError: boolean;
21
+ error: Error | null;
22
+ }
23
+
24
+ export class ErrorBoundary extends React.Component<Props, State> {
25
+ constructor(props: Props) {
26
+ super(props);
27
+ this.state = { hasError: false, error: null };
28
+ }
29
+
30
+ static getDerivedStateFromError(error: Error): State {
31
+ return { hasError: true, error };
32
+ }
33
+
34
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
35
+ const region = this.props.name || 'unknown';
36
+ console.error(`[ErrorBoundary:${region}] Caught error:`, error);
37
+ console.error(`[ErrorBoundary:${region}] Component stack:`, errorInfo.componentStack);
38
+ this.props.onError?.(error, errorInfo);
39
+ }
40
+
41
+ render(): React.ReactNode {
42
+ if (this.state.hasError) {
43
+ if (this.props.fallback) {
44
+ return this.props.fallback;
45
+ }
46
+
47
+ const region = this.props.name || 'application';
48
+
49
+ return (
50
+ <Box flexDirection="column" padding={1}>
51
+ <Text color="red" bold>
52
+ ❌ {region} Error
53
+ </Text>
54
+ <Box marginTop={1}>
55
+ <Text color="yellow">
56
+ An unexpected error occurred in {region}. Please restart the application.
57
+ </Text>
58
+ </Box>
59
+ {this.state.error && (
60
+ <Box marginTop={1} flexDirection="column">
61
+ <Text color="gray">Error: {this.state.error.message}</Text>
62
+ {this.state.error.stack && (
63
+ <Box marginTop={1}>
64
+ <Text color="gray" dimColor>
65
+ {this.state.error.stack.split('\n').slice(0, 5).join('\n')}
66
+ </Text>
67
+ </Box>
68
+ )}
69
+ </Box>
70
+ )}
71
+ <Box marginTop={1}>
72
+ <Text color="cyan">Press Ctrl+C to exit</Text>
73
+ </Box>
74
+ </Box>
75
+ );
76
+ }
77
+
78
+ return this.props.children;
79
+ }
80
+ }
81
+
82
+ export default ErrorBoundary;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * ExitMessage - visar session-info och synkar till aegiscloud.org vid exit
3
+ */
4
+
5
+ import React, { useEffect, useState } from 'react';
6
+ import { Box, Text, useApp } from 'ink';
7
+ import { themeManager } from '../../themes/index.js';
8
+ import { getState } from '../../../store/index.js';
9
+
10
+ interface ExitMessageProps {
11
+ sessionId: string;
12
+ exitDelay?: number;
13
+ }
14
+
15
+ export const ExitMessage: React.FC<ExitMessageProps> = ({
16
+ sessionId,
17
+ exitDelay = 800,
18
+ }) => {
19
+ const { exit } = useApp();
20
+ const theme = themeManager.getTheme();
21
+ const [syncStatus, setSyncStatus] = useState<'syncing' | 'done' | 'skip' | 'error'>('syncing');
22
+
23
+ useEffect(() => {
24
+ const doExit = async () => {
25
+ const { appendToLocalMemory, syncConversation } = await import('../../../services/CloudSync.js');
26
+ const { sharedMemory } = await import('../../../memory/SharedMemory.js');
27
+ const storeMessages = getState().session.messages;
28
+
29
+ if (storeMessages?.length > 0) {
30
+ const messages = storeMessages.map((m: any) => ({
31
+ role: m.role as string,
32
+ content: typeof m.content === 'string' ? m.content : JSON.stringify(m.content),
33
+ }));
34
+
35
+ // Local memory + episodic summary
36
+ await appendToLocalMemory(sessionId, messages).catch(() => {});
37
+ let model: string | undefined;
38
+ try {
39
+ const fs = await import('fs');
40
+ const path = await import('path');
41
+ const os = await import('os');
42
+ const cfg = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.aegiscode', 'config.json'), 'utf8'));
43
+ model = cfg?.default?.model || cfg?.models?.find((m: any) => m.id === cfg.currentModelId)?.model;
44
+ if (sharedMemory.isEnabled()) {
45
+ const apiKey = cfg?.default?.apiKey || cfg?.models?.find((m: any) => m.id === cfg.currentModelId)?.apiKey;
46
+ const baseURL = cfg?.default?.baseURL || cfg?.models?.find((m: any) => m.id === cfg.currentModelId)?.baseURL;
47
+ await sharedMemory.summarizeAndStoreSession(sessionId, apiKey, baseURL, model);
48
+ }
49
+ } catch {}
50
+ for (let attempt = 0; attempt < 3; attempt++) {
51
+ try {
52
+ const result = await syncConversation(sessionId, messages, model);
53
+ if (result.reason === 'uploaded') {
54
+ setSyncStatus('done');
55
+ break;
56
+ } else if (result.reason === 'error' && attempt < 2) {
57
+ await new Promise(r => setTimeout(r, 1000 * (attempt + 1)));
58
+ continue;
59
+ } else {
60
+ setSyncStatus(result.reason === 'error' ? 'error' : 'skip');
61
+ break;
62
+ }
63
+ } catch {
64
+ if (attempt < 2) {
65
+ await new Promise(r => setTimeout(r, 1000 * (attempt + 1)));
66
+ continue;
67
+ }
68
+ setSyncStatus('error');
69
+ }
70
+ }
71
+ } else {
72
+ setSyncStatus('skip');
73
+ }
74
+
75
+ setTimeout(() => { exit(); setTimeout(() => process.exit(0), 50); }, 300);
76
+ };
77
+ doExit();
78
+ }, [exit, sessionId]);
79
+
80
+ const shortId = sessionId.length > 16
81
+ ? `${sessionId.slice(0, 8)}..${sessionId.slice(-6)}`
82
+ : sessionId;
83
+
84
+ return (
85
+ <Box flexDirection="column" paddingY={1}>
86
+ <Box marginBottom={1}>
87
+ <Text color={theme.colors.text.muted}>─ </Text>
88
+ <Text color={theme.colors.warning}>session saved</Text>
89
+ <Text color={theme.colors.text.muted}> [</Text>
90
+ <Text color={theme.colors.info}>{shortId}</Text>
91
+ <Text color={theme.colors.text.muted}>]</Text>
92
+ {syncStatus === 'syncing' && (
93
+ <Text color={theme.colors.text.muted}> · syncing…</Text>
94
+ )}
95
+ {syncStatus === 'done' && (
96
+ <Text color={theme.colors.success}> · synced ↑</Text>
97
+ )}
98
+ {syncStatus === 'error' && (
99
+ <Text color={theme.colors.warning}> · sync failed</Text>
100
+ )}
101
+ {syncStatus === 'skip' && (
102
+ <Text color={theme.colors.text.muted}> · local only</Text>
103
+ )}
104
+ </Box>
105
+
106
+ <Box flexDirection="column" marginLeft={2}>
107
+ <Text color={theme.colors.text.muted}>resume: </Text>
108
+ <Box marginLeft={2}>
109
+ <Text color={theme.colors.success}>aegis --continue</Text>
110
+ </Box>
111
+ <Box marginLeft={2}>
112
+ <Text color={theme.colors.success}>aegis --resume </Text>
113
+ <Text color={theme.colors.info}>{sessionId}</Text>
114
+ </Box>
115
+ </Box>
116
+ </Box>
117
+ );
118
+ };
119
+
120
+ export default ExitMessage;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * LoadingIndicator - 加载指示器组件
3
+ */
4
+
5
+ import React from 'react';
6
+ import { Box, Text } from 'ink';
7
+
8
+ import { themeManager } from '../../themes/index.js';
9
+
10
+ interface LoadingIndicatorProps {
11
+ /** 是否显示 */
12
+ isVisible?: boolean;
13
+ /** 加载文本 */
14
+ text?: string;
15
+ /** 显示详情 */
16
+ details?: string;
17
+ }
18
+
19
+ /**
20
+ *
21
+ */
22
+ export const LoadingIndicator: React.FC<LoadingIndicatorProps> = React.memo(({
23
+ isVisible = true,
24
+ text = 'Thinking...',
25
+ details,
26
+ }) => {
27
+ const theme = themeManager.getTheme();
28
+
29
+ if (!isVisible) {
30
+ return null;
31
+ }
32
+
33
+ return (
34
+ <Box flexDirection="row" paddingX={1} marginY={1}>
35
+ <Box flexDirection="column">
36
+ <Text color={theme.colors.warning}>{text}</Text>
37
+ {details && (
38
+ <Text color={theme.colors.text.muted} dimColor>
39
+ {details}
40
+ </Text>
41
+ )}
42
+ </Box>
43
+ </Box>
44
+ );
45
+ });
46
+
47
+ LoadingIndicator.displayName = 'LoadingIndicator';
48
+
49
+ export default LoadingIndicator;
@@ -0,0 +1,6 @@
1
+ /**
2
+ *
3
+ */
4
+
5
+ export { ErrorBoundary } from './ErrorBoundary.js';
6
+ export { LoadingIndicator } from './LoadingIndicator.js';
@@ -0,0 +1,208 @@
1
+ /**
2
+ * ConfirmationPrompt - 权限确认组件
3
+ *
4
+ *
5
+ */
6
+
7
+ import React, { useState } from 'react';
8
+ import { Box, Text, useInput } from 'ink';
9
+ import { themeManager } from '../../themes/index.js';
10
+ import { FocusId, focusManager, useIsFocused } from '../../focus/index.js';
11
+ import type { ConfirmationDetails, ConfirmationResponse } from '../../../agent/types.js';
12
+
13
+ interface ConfirmationPromptProps {
14
+ details: ConfirmationDetails;
15
+ onResponse: (response: ConfirmationResponse) => void;
16
+ }
17
+
18
+ export const ConfirmationPrompt: React.FC<ConfirmationPromptProps> = ({
19
+ details,
20
+ onResponse,
21
+ }) => {
22
+ const [selectedIndex, setSelectedIndex] = useState(0);
23
+ const theme = themeManager.getTheme();
24
+ const isFocused = useIsFocused(FocusId.CONFIRMATION_PROMPT);
25
+
26
+ const options = [
27
+ { key: 'y', label: 'allow', scope: 'once' as const, approved: true },
28
+ { key: 'a', label: 'always', scope: 'session' as const, approved: true },
29
+ { key: 'n', label: 'deny', scope: 'once' as const, approved: false },
30
+ { key: 'd', label: 'never', scope: 'session' as const, approved: false },
31
+ ];
32
+
33
+ useInput((input, key) => {
34
+ if (key.upArrow) {
35
+ setSelectedIndex(prev => (prev > 0 ? prev - 1 : options.length - 1));
36
+ } else if (key.downArrow) {
37
+ setSelectedIndex(prev => (prev < options.length - 1 ? prev + 1 : 0));
38
+ } else if (key.return) {
39
+ const sel = options[selectedIndex];
40
+ onResponse({ approved: sel.approved, scope: sel.scope, reason: sel.approved ? undefined : 'denied' });
41
+ } else if (input === 'y' || input === 'Y') {
42
+ onResponse({ approved: true, scope: 'once' });
43
+ } else if (input === 'a' || input === 'A') {
44
+ onResponse({ approved: true, scope: 'session' });
45
+ } else if (input === 'n' || input === 'N') {
46
+ onResponse({ approved: false, scope: 'once', reason: 'denied' });
47
+ } else if (input === 'd' || input === 'D') {
48
+ onResponse({ approved: false, scope: 'session', reason: 'denied for this session' });
49
+ }
50
+ }, { isActive: isFocused });
51
+
52
+ // Extract tool name from title (e.g. "Permission Required: Bash" -> "Bash")
53
+ const toolName = details.title.replace(/^.*:\s*/, '');
54
+
55
+ // Skip showing the tool name header for tools where the label+highlight is self-explanatory
56
+ const hideHeader = ['Bash', 'Shell'].includes(toolName) && details.details?.includes('**Command:**');
57
+
58
+ // Extract the primary content to highlight (command, file path, etc.)
59
+ const { label, highlight, extra } = extractHighlight(details.details);
60
+
61
+ return (
62
+ <Box flexDirection="column" paddingX={1}>
63
+ {/* Header: tool name + reason (skipped for bash/shell when command is shown) */}
64
+ {!hideHeader && (
65
+ <Box>
66
+ <Text color={theme.colors.warning} bold>? </Text>
67
+ <Text bold>{toolName}</Text>
68
+ {details.message && details.message !== details.title && (
69
+ <Text color={theme.colors.text.muted} dimColor> · {details.message}</Text>
70
+ )}
71
+ </Box>
72
+ )}
73
+
74
+ {/* When header is hidden (Bash/Shell), show "? Command: <cmd>" on one line */}
75
+ {hideHeader && highlight && (
76
+ <Box>
77
+ <Text color={theme.colors.warning} bold>? </Text>
78
+ {label && <Text color={theme.colors.text.muted} dimColor>{label} </Text>}
79
+ <Text color={theme.colors.accent} wrap="wrap">{highlight}</Text>
80
+ </Box>
81
+ )}
82
+
83
+ {/* Highlighted content (command / file path) — only when header is shown */}
84
+ {!hideHeader && highlight && (
85
+ <Box marginLeft={2}>
86
+ {label && <Text color={theme.colors.text.muted} dimColor>{label} </Text>}
87
+ <Text color={theme.colors.accent} wrap="wrap">{highlight}</Text>
88
+ </Box>
89
+ )}
90
+
91
+ {/* Extra detail lines (e.g. directory, content preview) */}
92
+ {extra.length > 0 && (
93
+ <Box flexDirection="column" marginLeft={2}>
94
+ {extra.map((line, i) => (
95
+ <Text key={i} color={theme.colors.text.muted} dimColor wrap="wrap">
96
+ {line}
97
+ </Text>
98
+ ))}
99
+ </Box>
100
+ )}
101
+
102
+ {/* Affected files */}
103
+ {details.affectedFiles && details.affectedFiles.length > 0 && (
104
+ <Box marginLeft={2}>
105
+ <Text color={theme.colors.info} dimColor>
106
+ {details.affectedFiles.join(', ')}
107
+ </Text>
108
+ </Box>
109
+ )}
110
+
111
+ {/* Risks - single line */}
112
+ {details.risks && details.risks.length > 0 && (
113
+ <Box marginLeft={2}>
114
+ <Text color={theme.colors.text.muted} dimColor>
115
+ {details.risks.join(' · ')}
116
+ </Text>
117
+ </Box>
118
+ )}
119
+
120
+ {/* Options - vertical, up/down selection */}
121
+ <Box flexDirection="column" marginLeft={2} marginTop={1}>
122
+ {options.map((opt, i) => {
123
+ const active = i === selectedIndex;
124
+ return (
125
+ <Box key={opt.key}>
126
+ <Text
127
+ color={active ? theme.colors.success : theme.colors.text.muted}
128
+ bold={active}
129
+ dimColor={!active}
130
+ >
131
+ {active ? '> ' : ' '}
132
+ {opt.label}
133
+ </Text>
134
+ <Text color={theme.colors.text.muted} dimColor> ({opt.key})</Text>
135
+ </Box>
136
+ );
137
+ })}
138
+ </Box>
139
+ </Box>
140
+ );
141
+ };
142
+
143
+ /**
144
+ *
145
+ *
146
+ */
147
+ function extractHighlight(details?: string): { label: string; highlight: string; extra: string[] } {
148
+ if (!details) return { label: '', highlight: '', extra: [] };
149
+
150
+ const strip = (s: string) =>
151
+ s.replace(/\*\*(.+?)\*\*/g, '$1').replace(/`([^`]+)`/g, '$1').trim();
152
+
153
+ const lines = details.split('\n').filter(l => l.trim());
154
+ let label = '';
155
+ let highlight = '';
156
+ const highlightLines: string[] = [];
157
+ const extra: string[] = [];
158
+ let inHighlight = false;
159
+
160
+ const KNOWN_PREFIX = /^(Command|File|Directory|Content Preview|Before|After):\s*/;
161
+
162
+ for (const raw of lines) {
163
+ const line = strip(raw);
164
+ if (line === '```' || line.startsWith('```')) {
165
+ // skip code fences
166
+ continue;
167
+ }
168
+ if (/^Command:\s*/.test(line)) {
169
+ label = 'Command:';
170
+ highlightLines.push(line.replace(/^Command:\s*/, ''));
171
+ inHighlight = true;
172
+ } else if (/^File:\s*/.test(line)) {
173
+ label = 'File:';
174
+ highlightLines.push(line.replace(/^File:\s*/, ''));
175
+ inHighlight = true;
176
+ } else if (/^(Directory|Content Preview|Before|After):\s*/.test(line)) {
177
+ inHighlight = false;
178
+ extra.push(line);
179
+ } else if (inHighlight) {
180
+ // Continuation of a multi-line Command/File value — keep it part of the
181
+ // highlight instead of dropping it into the unrelated "extra" lines, or
182
+ // multi-line bash commands get silently truncated to their first line.
183
+ highlightLines.push(line);
184
+ } else if (line) {
185
+ extra.push(line);
186
+ }
187
+ }
188
+
189
+ highlight = highlightLines.join('\n');
190
+
191
+ return { label, highlight, extra };
192
+ }
193
+
194
+ /**
195
+ *
196
+ *
197
+ */
198
+ export function createAutoConfirmationHandler(
199
+ mode: 'approve' | 'deny' | 'approve_session' = 'deny'
200
+ ): (details: ConfirmationDetails) => Promise<ConfirmationResponse> {
201
+ return async () => ({
202
+ approved: mode.startsWith('approve'),
203
+ scope: mode === 'approve_session' ? 'session' : 'once',
204
+ reason: `Auto-${mode} by non-interactive mode`,
205
+ });
206
+ }
207
+
208
+ export default ConfirmationPrompt;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * InteractiveSelector - 交互式选择器组件
3
+ */
4
+
5
+ import React, { useState, useEffect, useRef } from 'react';
6
+ import { Box, Text, useInput } from 'ink';
7
+ import { themeManager } from '../../themes/index.js';
8
+ import { FocusId, focusManager } from '../../focus/index.js';
9
+
10
+ export interface SelectorOption<T = string> {
11
+ value: T;
12
+ label: string;
13
+ description?: string;
14
+ isCurrent?: boolean;
15
+ }
16
+
17
+ interface InteractiveSelectorProps<T = string> {
18
+ title: string;
19
+ options: SelectorOption<T>[];
20
+ onSelect: (value: T) => void;
21
+ onCancel: () => void;
22
+ initialIndex?: number;
23
+ focusId?: string;
24
+ maxVisible?: number;
25
+ }
26
+
27
+ export function InteractiveSelector<T = string>({
28
+ title,
29
+ options,
30
+ onSelect,
31
+ onCancel,
32
+ initialIndex = 0,
33
+ focusId = FocusId.SELECTOR,
34
+ maxVisible = 10,
35
+ }: InteractiveSelectorProps<T>): React.ReactElement {
36
+ const theme = themeManager.getTheme();
37
+ const [selectedIndex, setSelectedIndex] = useState(() => {
38
+ // Start at current item if one is marked
39
+ const currentIdx = options.findIndex(o => o.isCurrent);
40
+ return currentIdx >= 0 ? currentIdx : initialIndex;
41
+ });
42
+ const [scrollTop, setScrollTop] = useState(0);
43
+
44
+ const selectFiredRef = useRef(false);
45
+ useEffect(() => { selectFiredRef.current = false; }, [options]);
46
+
47
+ // Keep viewport window in sync with cursor
48
+ useEffect(() => {
49
+ setScrollTop(prev => {
50
+ if (selectedIndex < prev) return selectedIndex;
51
+ if (selectedIndex >= prev + maxVisible) return selectedIndex - maxVisible + 1;
52
+ return prev;
53
+ });
54
+ }, [selectedIndex, maxVisible]);
55
+
56
+ useInput((input, key) => {
57
+ if (focusManager.getCurrentFocus() !== focusId) return;
58
+
59
+ if (key.upArrow || input === 'k') {
60
+ setSelectedIndex(prev => (prev > 0 ? prev - 1 : options.length - 1));
61
+ } else if (key.downArrow || input === 'j') {
62
+ setSelectedIndex(prev => (prev < options.length - 1 ? prev + 1 : 0));
63
+ } else if (key.pageUp) {
64
+ setSelectedIndex(prev => Math.max(0, prev - maxVisible));
65
+ } else if (key.pageDown) {
66
+ setSelectedIndex(prev => Math.min(options.length - 1, prev + maxVisible));
67
+ } else if (key.return) {
68
+ if (!selectFiredRef.current) {
69
+ selectFiredRef.current = true;
70
+ onSelect(options[selectedIndex].value);
71
+ }
72
+ } else if (key.escape || input === 'q') {
73
+ onCancel();
74
+ }
75
+ });
76
+
77
+ useEffect(() => {
78
+ if (selectedIndex >= options.length) setSelectedIndex(0);
79
+ }, [options.length, selectedIndex]);
80
+
81
+ const visibleOptions = options.slice(scrollTop, scrollTop + maxVisible);
82
+ const hasAbove = scrollTop > 0;
83
+ const hasBelow = scrollTop + maxVisible < options.length;
84
+
85
+ return (
86
+ <Box
87
+ flexDirection="column"
88
+ borderStyle="round"
89
+ borderColor={theme.colors.primary}
90
+ paddingX={2}
91
+ paddingY={1}
92
+ >
93
+ <Box marginBottom={1} flexDirection="row" justifyContent="space-between">
94
+ <Text bold color={theme.colors.primary}>{title}</Text>
95
+ {options.length > maxVisible && (
96
+ <Text color={theme.colors.text.muted} dimColor>
97
+ {selectedIndex + 1}/{options.length}
98
+ </Text>
99
+ )}
100
+ </Box>
101
+
102
+ {hasAbove && (
103
+ <Box>
104
+ <Text color={theme.colors.text.muted} dimColor> ↑ {scrollTop} more</Text>
105
+ </Box>
106
+ )}
107
+
108
+ <Box flexDirection="column">
109
+ {visibleOptions.map((option, i) => {
110
+ const absIndex = scrollTop + i;
111
+ const isSelected = absIndex === selectedIndex;
112
+ return (
113
+ <Box key={String(option.value)} flexDirection="row">
114
+ <Text
115
+ color={isSelected ? theme.colors.primary : theme.colors.text.primary}
116
+ bold={isSelected}
117
+ >
118
+ {isSelected ? '▸ ' : ' '}
119
+ {option.label}
120
+ {option.isCurrent ? ' ✓' : ''}
121
+ </Text>
122
+ {option.description && (
123
+ <Text color={theme.colors.text.muted} dimColor>
124
+ {' - '}{option.description}
125
+ </Text>
126
+ )}
127
+ </Box>
128
+ );
129
+ })}
130
+ </Box>
131
+
132
+ {hasBelow && (
133
+ <Box>
134
+ <Text color={theme.colors.text.muted} dimColor>
135
+ {' ↓ '}{options.length - scrollTop - maxVisible} more
136
+ </Text>
137
+ </Box>
138
+ )}
139
+
140
+ <Box marginTop={1} borderStyle="single" borderTop borderBottom={false} borderLeft={false} borderRight={false} borderColor={theme.colors.border.light}>
141
+ <Text color={theme.colors.text.muted} dimColor>
142
+ ↑/↓ navigate PgUp/PgDn page Enter confirm Esc cancel
143
+ </Text>
144
+ </Box>
145
+ </Box>
146
+ );
147
+ }
148
+
149
+ export default InteractiveSelector;