aegiscode 3.1.7 → 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 +555 -556
  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,309 @@
1
+ /**
2
+ *
3
+ */
4
+
5
+ import { TokenCounter } from './TokenCounter.js';
6
+ import { MemoryStore } from './storage/MemoryStore.js';
7
+ import { CacheStore } from './storage/CacheStore.js';
8
+ import { JSONLStore } from './storage/JSONLStore.js';
9
+ import { FileAnalyzer } from './FileAnalyzer.js';
10
+ import { CompactionService } from './CompactionService.js';
11
+ import { escapeProjectPath, getProjectStoragePath } from './storage/pathUtils.js';
12
+ import * as path from 'node:path';
13
+ import * as os from 'node:os';
14
+ import * as fs from 'node:fs/promises';
15
+ import type { ContextData, ContextMessage, JSONLEntry } from './types.js';
16
+ import type { Message } from '../agent/types.js';
17
+
18
+ let passed = 0;
19
+ let failed = 0;
20
+
21
+ function test(name: string, fn: () => void | Promise<void>) {
22
+ return (async () => {
23
+ try {
24
+ await fn();
25
+ console.log(`✅ ${name}`);
26
+ passed++;
27
+ } catch (error) {
28
+ console.log(`❌ ${name}`);
29
+ console.error(' ', error instanceof Error ? error.message : error);
30
+ failed++;
31
+ }
32
+ })();
33
+ }
34
+
35
+ function assert(condition: boolean, message: string) {
36
+ if (!condition) {
37
+ throw new Error(message);
38
+ }
39
+ }
40
+
41
+ async function runTests() {
42
+ console.log('\n=== 上下文管理测试 ===\n');
43
+
44
+ // TokenCounter 测
45
+ await test('TokenCounter: 计算文本 Token 数量', () => {
46
+ const tokens = TokenCounter.estimateTokens('Hello, world!');
47
+ assert(tokens > 0, 'Token 数量应该大于 0');
48
+ });
49
+
50
+ await test('TokenCounter: 中英文混合估算', () => {
51
+ const text = 'Hello 你好 World 世界';
52
+ const tokens = TokenCounter.estimateTokens(text);
53
+ assert(tokens > 0, 'Token 数量应该大于 0');
54
+ });
55
+
56
+ await test('TokenCounter: 计算消息 Token', () => {
57
+ const messages: Message[] = [
58
+ { role: 'user', content: 'Hello' },
59
+ { role: 'assistant', content: 'Hi there!' },
60
+ ];
61
+ const tokens = TokenCounter.countTokens(messages, 'claude-sonnet-4-20250514');
62
+ assert(tokens > 0, 'Token 数量应该大于 0');
63
+ });
64
+
65
+ await test('TokenCounter: shouldCompact 检测', () => {
66
+ const messages: Message[] = [
67
+ { role: 'user', content: 'Hello' },
68
+ ];
69
+ const shouldCompact = TokenCounter.shouldCompact(messages, 'claude-sonnet-4-20250514', 100, 0.8);
70
+ // 消息很短,不应该触发压
71
+ assert(!shouldCompact, '短消息不应该触发压缩');
72
+ });
73
+
74
+ // MemoryStore 测
75
+ await test('MemoryStore: 初始化和设置上下文', () => {
76
+ const store = new MemoryStore(100);
77
+ const contextData: ContextData = {
78
+ layers: {
79
+ system: { osType: 'test', osVersion: '1.0', shell: 'bash', nodeVersion: 'v18', cwd: '/' },
80
+ session: { sessionId: 'test-123', preferences: {}, startTime: Date.now() },
81
+ conversation: { messages: [], topics: [], lastActivity: Date.now() },
82
+ tool: { recentCalls: [], toolStates: {}, dependencies: {} },
83
+ workspace: { projectPath: '/' },
84
+ },
85
+ metadata: { totalTokens: 0, priority: 1, lastUpdated: Date.now() },
86
+ };
87
+ store.setContext(contextData);
88
+ assert(store.hasData(), '应该有数据');
89
+ assert(store.getSessionId() === 'test-123', '会话 ID 应该匹配');
90
+ });
91
+
92
+ await test('MemoryStore: 添加消息', () => {
93
+ const store = new MemoryStore(100);
94
+ const contextData: ContextData = {
95
+ layers: {
96
+ system: { osType: 'test', osVersion: '1.0', shell: 'bash', nodeVersion: 'v18', cwd: '/' },
97
+ session: { sessionId: 'test', preferences: {}, startTime: Date.now() },
98
+ conversation: { messages: [], topics: [], lastActivity: Date.now() },
99
+ tool: { recentCalls: [], toolStates: {}, dependencies: {} },
100
+ workspace: { projectPath: '/' },
101
+ },
102
+ metadata: { totalTokens: 0, priority: 1, lastUpdated: Date.now() },
103
+ };
104
+ store.setContext(contextData);
105
+
106
+ const message: ContextMessage = {
107
+ id: 'msg-1',
108
+ role: 'user',
109
+ content: 'Hello',
110
+ timestamp: Date.now(),
111
+ };
112
+ store.addMessage(message);
113
+
114
+ const messages = store.getMessages();
115
+ assert(messages.length === 1, '应该有 1 条消息');
116
+ assert(messages[0].content === 'Hello', '消息内容应该匹配');
117
+ });
118
+
119
+ await test('MemoryStore: 内存限制', () => {
120
+ const store = new MemoryStore(5); // 最多 5 条消
121
+ const contextData: ContextData = {
122
+ layers: {
123
+ system: { osType: 'test', osVersion: '1.0', shell: 'bash', nodeVersion: 'v18', cwd: '/' },
124
+ session: { sessionId: 'test', preferences: {}, startTime: Date.now() },
125
+ conversation: { messages: [], topics: [], lastActivity: Date.now() },
126
+ tool: { recentCalls: [], toolStates: {}, dependencies: {} },
127
+ workspace: { projectPath: '/' },
128
+ },
129
+ metadata: { totalTokens: 0, priority: 1, lastUpdated: Date.now() },
130
+ };
131
+ store.setContext(contextData);
132
+
133
+ // 添加 10 条消
134
+ for (let i = 0; i < 10; i++) {
135
+ store.addMessage({
136
+ id: `msg-${i}`,
137
+ role: 'user',
138
+ content: `Message ${i}`,
139
+ timestamp: Date.now(),
140
+ });
141
+ }
142
+
143
+ const messages = store.getMessages();
144
+ assert(messages.length <= 5, '消息数量应该被限制');
145
+ });
146
+
147
+ // CacheStore 测
148
+ await test('CacheStore: 设置和获取', () => {
149
+ const cache = new CacheStore(10, 1000);
150
+ cache.set('key1', 'value1');
151
+ const value = cache.get<string>('key1');
152
+ assert(value === 'value1', '值应该匹配');
153
+ });
154
+
155
+ await test('CacheStore: TTL 过期', async () => {
156
+ const cache = new CacheStore(10, 50); // 50ms TTL
157
+ cache.set('key1', 'value1');
158
+ await new Promise(r => setTimeout(r, 100)); // 等
159
+ const value = cache.get<string>('key1');
160
+ assert(value === undefined, '过期后应该返回 undefined');
161
+ });
162
+
163
+ await test('CacheStore: LRU 淘汰', () => {
164
+ const cache = new CacheStore(3, 10000);
165
+ cache.set('key1', 'value1');
166
+ cache.set('key2', 'value2');
167
+ cache.set('key3', 'value3');
168
+
169
+ // 访问 key2 和 key3 使它们成为最近使用(key1 最久未使
170
+ cache.get('key2');
171
+ cache.get('key3');
172
+
173
+ // 添加新项,应该淘汰 key1(最久未使
174
+ cache.set('key4', 'value4');
175
+
176
+ assert(cache.has('key2'), 'key2 应该存在');
177
+ assert(cache.has('key3'), 'key3 应该存在');
178
+ assert(cache.has('key4'), 'key4 应该存在');
179
+ });
180
+
181
+ // 路径工具函数测
182
+ await test('pathUtils: escapeProjectPath', () => {
183
+ const escaped = escapeProjectPath('/Users/foo/project');
184
+ assert(!escaped.includes('/'), '不应该包含斜杠');
185
+ assert(escaped.includes('Users'), '应该包含 Users');
186
+ });
187
+
188
+ await test('pathUtils: getProjectStoragePath', () => {
189
+ const storagePath = getProjectStoragePath('/Users/foo/project');
190
+ assert(storagePath.includes('.aegis'), '应该包含 .aegis');
191
+ assert(storagePath.includes('projects'), '应该包含 projects');
192
+ });
193
+
194
+ // JSONLStore 测
195
+ const testDir = path.join(os.tmpdir(), 'aegis-test-' + Date.now());
196
+ const testFile = path.join(testDir, 'test.jsonl');
197
+
198
+ await test('JSONLStore: 追加和读取', async () => {
199
+ const store = new JSONLStore(testFile);
200
+
201
+ const entry: JSONLEntry = {
202
+ uuid: 'test-uuid',
203
+ parentUuid: null,
204
+ sessionId: 'test-session',
205
+ timestamp: new Date().toISOString(),
206
+ type: 'user',
207
+ cwd: '/test',
208
+ version: '0.1.0',
209
+ message: { role: 'user', content: 'Hello' },
210
+ };
211
+
212
+ await store.append(entry);
213
+ const entries = await store.readAll();
214
+
215
+ assert(entries.length === 1, '应该有 1 条记录');
216
+ assert(entries[0].uuid === 'test-uuid', 'UUID 应该匹配');
217
+ });
218
+
219
+ await test('JSONLStore: 批量追加', async () => {
220
+ const store = new JSONLStore(testFile);
221
+
222
+ const entries: JSONLEntry[] = [
223
+ {
224
+ uuid: 'batch-1',
225
+ parentUuid: null,
226
+ sessionId: 'test-session',
227
+ timestamp: new Date().toISOString(),
228
+ type: 'user',
229
+ cwd: '/test',
230
+ version: '0.1.0',
231
+ message: { role: 'user', content: 'Message 1' },
232
+ },
233
+ {
234
+ uuid: 'batch-2',
235
+ parentUuid: 'batch-1',
236
+ sessionId: 'test-session',
237
+ timestamp: new Date().toISOString(),
238
+ type: 'assistant',
239
+ cwd: '/test',
240
+ version: '0.1.0',
241
+ message: { role: 'assistant', content: 'Message 2' },
242
+ },
243
+ ];
244
+
245
+ await store.appendBatch(entries);
246
+ const all = await store.readAll();
247
+
248
+ // 之前有 1 条,现在加 2
249
+ assert(all.length === 3, '应该有 3 条记录');
250
+ });
251
+
252
+ // FileAnalyzer 测
253
+ await test('FileAnalyzer: 分析消息中的文件', () => {
254
+ const messages: Message[] = [
255
+ { role: 'user', content: '请帮我看看 src/index.ts 文件' },
256
+ { role: 'assistant', content: '好的,让我读取这个文件', tool_calls: [
257
+ { id: 'tc1', type: 'function', function: { name: 'Read', arguments: JSON.stringify({ file_path: 'src/index.ts' }) } }
258
+ ]},
259
+ ];
260
+
261
+ const fileRefs = FileAnalyzer.analyzeFiles(messages);
262
+ // 文件可能不存在,所以这里只检查逻辑是否正确执
263
+ assert(Array.isArray(fileRefs), '应该返回数组');
264
+ });
265
+
266
+ // CompactionService 测
267
+ await test('CompactionService: shouldCompact', () => {
268
+ const messages: Message[] = [
269
+ { role: 'user', content: 'Hello' },
270
+ ];
271
+ const should = CompactionService.shouldCompact(messages, 'claude-sonnet-4-20250514', 100000);
272
+ assert(!should, '短消息不应该触发压缩');
273
+ });
274
+
275
+ await test('CompactionService: 压缩降级', async () => {
276
+ const messages: Message[] = [
277
+ { role: 'user', content: 'Hello' },
278
+ { role: 'assistant', content: 'Hi there!' },
279
+ { role: 'user', content: 'How are you?' },
280
+ ];
281
+
282
+ const result = await CompactionService.compact(messages, {
283
+ trigger: 'manual',
284
+ modelName: 'claude-sonnet-4-20250514',
285
+ maxContextTokens: 100000,
286
+ // 不提供 chatService,会使用降级策
287
+ });
288
+
289
+ assert(result.compactedMessages.length > 0, '应该有压缩后的消息');
290
+ assert(result.preTokens > 0, '应该有压缩前的 Token 数');
291
+ });
292
+
293
+ // 清理测试文
294
+ try {
295
+ await fs.rm(testDir, { recursive: true });
296
+ } catch {
297
+ // 忽略清理错
298
+ }
299
+
300
+ // 输出结
301
+ console.log('\n---');
302
+ console.log(`测试完成: ${passed} 通过, ${failed} 失败`);
303
+
304
+ if (failed > 0) {
305
+ process.exit(1);
306
+ }
307
+ }
308
+
309
+ runTests().catch(console.error);
@@ -0,0 +1,268 @@
1
+ /**
2
+ *
3
+ */
4
+
5
+ import type { Message } from '../agent/types.js';
6
+
7
+ // ============================================================================
8
+ // 基础消息类
9
+ // ============================================================================
10
+
11
+ /**
12
+ *
13
+ */
14
+ export interface ContextMessage {
15
+ id: string;
16
+ role: 'user' | 'assistant' | 'system' | 'tool';
17
+ content: string;
18
+ timestamp: number;
19
+ metadata?: Record<string, unknown>;
20
+ }
21
+
22
+ /**
23
+ *
24
+ */
25
+ export interface ToolCallRecord {
26
+ id: string;
27
+ name: string;
28
+ input: unknown;
29
+ output?: unknown;
30
+ timestamp: number;
31
+ status: 'pending' | 'success' | 'error';
32
+ error?: string;
33
+ }
34
+
35
+ // ============================================================================
36
+ // 上下文分
37
+ // ============================================================================
38
+
39
+ /**
40
+ *
41
+ */
42
+ export interface SystemContext {
43
+ osType: string;
44
+ osVersion: string;
45
+ shell: string;
46
+ nodeVersion: string;
47
+ cwd: string;
48
+ }
49
+
50
+ /**
51
+ *
52
+ */
53
+ export interface SessionContext {
54
+ sessionId: string;
55
+ userId?: string;
56
+ preferences: Record<string, unknown>;
57
+ configuration?: Record<string, unknown>;
58
+ startTime: number;
59
+ }
60
+
61
+ /**
62
+ *
63
+ */
64
+ export interface ConversationContext {
65
+ messages: ContextMessage[];
66
+ topics: string[];
67
+ lastActivity: number;
68
+ }
69
+
70
+ /**
71
+ *
72
+ */
73
+ export interface ToolContext {
74
+ recentCalls: ToolCallRecord[];
75
+ toolStates: Record<string, unknown>;
76
+ dependencies: Record<string, string[]>;
77
+ }
78
+
79
+ /**
80
+ *
81
+ */
82
+ export interface WorkspaceContext {
83
+ projectPath: string;
84
+ gitBranch?: string;
85
+ gitRemote?: string;
86
+ packageJson?: {
87
+ name?: string;
88
+ version?: string;
89
+ dependencies?: Record<string, string>;
90
+ };
91
+ }
92
+
93
+ /**
94
+ *
95
+ */
96
+ export interface ContextLayer {
97
+ system: SystemContext;
98
+ session: SessionContext;
99
+ conversation: ConversationContext;
100
+ tool: ToolContext;
101
+ workspace: WorkspaceContext;
102
+ }
103
+
104
+ /**
105
+ *
106
+ */
107
+ export interface ContextData {
108
+ layers: ContextLayer;
109
+ metadata: {
110
+ totalTokens: number;
111
+ priority: number;
112
+ relevanceScore?: number;
113
+ lastUpdated: number;
114
+ };
115
+ }
116
+
117
+ // ============================================================================
118
+ // JSONL 存储格
119
+ // ============================================================================
120
+
121
+ /**
122
+ * JSONL 条目类型
123
+ */
124
+ export type JSONLEntryType = 'user' | 'assistant' | 'tool_use' | 'tool_result' | 'system';
125
+
126
+ /**
127
+ * JSONL 条目
128
+ */
129
+ export interface JSONLEntry {
130
+ /** 消息唯一 ID (nanoid) */
131
+ uuid: string;
132
+ /** 父消息 ID (用于对话线程追踪) */
133
+ parentUuid: string | null;
134
+ /** 会话 ID */
135
+ sessionId: string;
136
+ /** ISO 8601 时间戳 */
137
+ timestamp: string;
138
+ /** 消息类型 */
139
+ type: JSONLEntryType;
140
+ /** 子类型 */
141
+ subtype?: 'compact_boundary';
142
+ /** 工作目录 */
143
+ cwd: string;
144
+ /** Git 分支 */
145
+ gitBranch?: string;
146
+ /** 版本号 */
147
+ version: string;
148
+ /** 消息内容 */
149
+ message: {
150
+ role: 'user' | 'assistant' | 'system';
151
+ content: string | unknown;
152
+ model?: string;
153
+ usage?: { input_tokens: number; output_tokens: number };
154
+ };
155
+ /** 工具调用信息 */
156
+ tool?: { id: string; name: string; input: unknown };
157
+ /** 工具结果 */
158
+ toolResult?: { id: string; output: unknown; error?: string };
159
+ /** 压缩标记 */
160
+ isCompactSummary?: boolean;
161
+ compactMetadata?: CompactMetadata;
162
+ }
163
+
164
+ /**
165
+ *
166
+ */
167
+ export interface CompactMetadata {
168
+ trigger: 'auto' | 'manual';
169
+ preTokens: number;
170
+ postTokens?: number;
171
+ filesIncluded?: string[];
172
+ }
173
+
174
+ // ============================================================================
175
+ // 存储选
176
+ // ============================================================================
177
+
178
+ /**
179
+ *
180
+ */
181
+ export interface StorageOptions {
182
+ maxMemorySize: number;
183
+ persistentPath: string;
184
+ cacheSize: number;
185
+ compressionEnabled: boolean;
186
+ }
187
+
188
+ /**
189
+ *
190
+ */
191
+ export interface FilterOptions {
192
+ maxTokens: number;
193
+ maxMessages: number;
194
+ timeWindow: number;
195
+ }
196
+
197
+ /**
198
+ * ContextManager 配置
199
+ */
200
+ export interface ContextManagerOptions {
201
+ storage: StorageOptions;
202
+ defaultFilter: FilterOptions;
203
+ compressionThreshold: number;
204
+ }
205
+
206
+ // ============================================================================
207
+ // 压缩服
208
+ // ============================================================================
209
+
210
+ /**
211
+ *
212
+ */
213
+ export interface CompactionOptions {
214
+ trigger: 'auto' | 'manual';
215
+ modelName: string;
216
+ maxContextTokens: number;
217
+ actualPreTokens?: number;
218
+ chatService?: unknown; // ChatService 类
219
+ sessionId?: string; // 用于 Hook 上下
220
+ projectDir?: string; // 用于 Hook 上下
221
+ }
222
+
223
+ /**
224
+ *
225
+ */
226
+ export interface CompactionResult {
227
+ success: boolean;
228
+ summary: string;
229
+ preTokens: number;
230
+ postTokens: number;
231
+ filesIncluded: string[];
232
+ compactedMessages: Message[];
233
+ error?: string;
234
+ }
235
+
236
+ /**
237
+ *
238
+ */
239
+ export interface FileReference {
240
+ path: string;
241
+ mentions: number;
242
+ lastMentioned: number;
243
+ wasModified: boolean;
244
+ }
245
+
246
+ /**
247
+ *
248
+ */
249
+ export interface FileContent {
250
+ path: string;
251
+ content: string;
252
+ lines: number;
253
+ truncated: boolean;
254
+ }
255
+
256
+ // ============================================================================
257
+ // 内存信
258
+ // ============================================================================
259
+
260
+ /**
261
+ *
262
+ */
263
+ export interface MemoryInfo {
264
+ hasData: boolean;
265
+ messageCount: number;
266
+ toolCallCount: number;
267
+ lastUpdated: number | null;
268
+ }