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.
- package/README.md +23 -15
- package/dist/main.js +549 -552
- package/package.json +4 -2
- package/src/agent/Agent.ts +903 -0
- package/src/agent/SimpleAgent.ts +48 -0
- package/src/agent/index.ts +54 -0
- package/src/agent/orchestrator/AppBuilder.ts +443 -0
- package/src/agent/orchestrator/CouncilAgent.ts +310 -0
- package/src/agent/orchestrator/DiscussionRoom.ts +462 -0
- package/src/agent/orchestrator/OrchestratorAgent.ts +637 -0
- package/src/agent/orchestrator/index.ts +38 -0
- package/src/agent/orchestrator/utils.ts +397 -0
- package/src/agent/pricing.ts +115 -0
- package/src/agent/router.ts +74 -0
- package/src/agent/routerStats.ts +121 -0
- package/src/agent/types.ts +318 -0
- package/src/auth/login.ts +383 -0
- package/src/cli/config.ts +189 -0
- package/src/cli/index.ts +17 -0
- package/src/cli/middleware.ts +119 -0
- package/src/cli/types.ts +75 -0
- package/src/config/ConfigManager.ts +587 -0
- package/src/config/index.ts +7 -0
- package/src/config/types.ts +584 -0
- package/src/context/CompactionService.ts +300 -0
- package/src/context/ContextManager.ts +450 -0
- package/src/context/FileAnalyzer.ts +267 -0
- package/src/context/TokenCounter.ts +265 -0
- package/src/context/index.ts +27 -0
- package/src/context/storage/CacheStore.ts +176 -0
- package/src/context/storage/JSONLStore.ts +201 -0
- package/src/context/storage/MemoryStore.ts +205 -0
- package/src/context/storage/PersistentStore.ts +327 -0
- package/src/context/storage/index.ts +9 -0
- package/src/context/storage/pathUtils.ts +114 -0
- package/src/context/test.ts +309 -0
- package/src/context/types.ts +268 -0
- package/src/hooks/HookExecutor.ts +434 -0
- package/src/hooks/HookManager.ts +596 -0
- package/src/hooks/HookService.ts +269 -0
- package/src/hooks/Matcher.ts +157 -0
- package/src/hooks/index.ts +63 -0
- package/src/hooks/types.ts +424 -0
- package/src/main.tsx +596 -0
- package/src/mcp/HealthMonitor.ts +150 -0
- package/src/mcp/McpClient.ts +491 -0
- package/src/mcp/McpRegistry.ts +321 -0
- package/src/mcp/createMcpTool.ts +251 -0
- package/src/mcp/index.ts +15 -0
- package/src/mcp/server.ts +334 -0
- package/src/mcp/test-server.ts +88 -0
- package/src/mcp/test.ts +372 -0
- package/src/mcp/types.ts +247 -0
- package/src/memory/AgentMemoryBus.ts +432 -0
- package/src/memory/CloudSync.ts +99 -0
- package/src/memory/DriveSync.ts +106 -0
- package/src/memory/SharedMemory.ts +951 -0
- package/src/memory/index.ts +14 -0
- package/src/memory/machineFingerprint.ts +40 -0
- package/src/orchestrator/SubAgentMetadata.ts +136 -0
- package/src/prompts/builder.ts +213 -0
- package/src/prompts/default.ts +144 -0
- package/src/prompts/index.ts +16 -0
- package/src/prompts/plan.ts +64 -0
- package/src/prompts/test.ts +78 -0
- package/src/services/AnthropicChatService.ts +341 -0
- package/src/services/ChatService.ts +347 -0
- package/src/services/ClaudeCliChatService.ts +256 -0
- package/src/services/CloudSync.ts +168 -0
- package/src/services/CostLedger.ts +211 -0
- package/src/services/Heartbeat.ts +135 -0
- package/src/services/LearningCollector.ts +291 -0
- package/src/services/OllamaInstaller.ts +342 -0
- package/src/services/VersionChecker.ts +445 -0
- package/src/services/index.ts +57 -0
- package/src/services/streaming/OpenAIEventAdapter.ts +126 -0
- package/src/services/streaming/RenderingProfile.ts +90 -0
- package/src/services/streaming/StreamEventParser.ts +181 -0
- package/src/services/streaming/ThrottledRenderer.ts +139 -0
- package/src/services/streaming/TranscriptBuffer.ts +574 -0
- package/src/services/streaming/eventStatusMap.ts +52 -0
- package/src/services/streaming/index.ts +46 -0
- package/src/services/streaming/renderFormatting.ts +79 -0
- package/src/services/streaming/types.ts +234 -0
- package/src/skills/SkillLoader.ts +126 -0
- package/src/skills/SkillRegistry.ts +366 -0
- package/src/skills/index.ts +48 -0
- package/src/skills/types.ts +146 -0
- package/src/slash-commands/billing.ts +70 -0
- package/src/slash-commands/build.ts +413 -0
- package/src/slash-commands/builtinCommands.ts +2733 -0
- package/src/slash-commands/clone.ts +242 -0
- package/src/slash-commands/council.ts +125 -0
- package/src/slash-commands/custom/CustomCommandExecutor.ts +143 -0
- package/src/slash-commands/custom/CustomCommandLoader.ts +251 -0
- package/src/slash-commands/custom/CustomCommandRegistry.ts +144 -0
- package/src/slash-commands/custom/index.ts +7 -0
- package/src/slash-commands/debate.ts +254 -0
- package/src/slash-commands/gmail.ts +105 -0
- package/src/slash-commands/index.ts +388 -0
- package/src/slash-commands/mcpCommand.ts +205 -0
- package/src/slash-commands/types.ts +201 -0
- package/src/store/index.ts +76 -0
- package/src/store/selectors.ts +246 -0
- package/src/store/slices/appSlice.ts +205 -0
- package/src/store/slices/commandSlice.ts +115 -0
- package/src/store/slices/configSlice.ts +46 -0
- package/src/store/slices/focusSlice.ts +64 -0
- package/src/store/slices/index.ts +9 -0
- package/src/store/slices/sessionSlice.ts +424 -0
- package/src/store/streaming-buffer.ts +425 -0
- package/src/store/test.ts +296 -0
- package/src/store/types.ts +274 -0
- package/src/store/vanilla.ts +186 -0
- package/src/tools/builtin/bash.ts +236 -0
- package/src/tools/builtin/council.ts +105 -0
- package/src/tools/builtin/edit.ts +213 -0
- package/src/tools/builtin/glob.ts +136 -0
- package/src/tools/builtin/grep.ts +263 -0
- package/src/tools/builtin/index.ts +61 -0
- package/src/tools/builtin/memory.ts +66 -0
- package/src/tools/builtin/read.ts +168 -0
- package/src/tools/builtin/skill.ts +97 -0
- package/src/tools/builtin/snapshot.ts +40 -0
- package/src/tools/builtin/task.ts +106 -0
- package/src/tools/builtin/write.ts +134 -0
- package/src/tools/createTool.ts +221 -0
- package/src/tools/execution/ExecutionPipeline.ts +263 -0
- package/src/tools/execution/index.ts +40 -0
- package/src/tools/execution/stages/CacheStage.ts +131 -0
- package/src/tools/execution/stages/ConfirmationStage.ts +203 -0
- package/src/tools/execution/stages/DiscoveryStage.ts +46 -0
- package/src/tools/execution/stages/ExecutionStage.ts +48 -0
- package/src/tools/execution/stages/FormattingStage.ts +44 -0
- package/src/tools/execution/stages/HookStage.ts +72 -0
- package/src/tools/execution/stages/PermissionStage.ts +287 -0
- package/src/tools/execution/stages/PostHookStage.ts +71 -0
- package/src/tools/execution/stages/index.ts +12 -0
- package/src/tools/execution/test.ts +266 -0
- package/src/tools/execution/types.ts +273 -0
- package/src/tools/index.ts +81 -0
- package/src/tools/registry.ts +304 -0
- package/src/tools/schemas.ts +109 -0
- package/src/tools/test.ts +220 -0
- package/src/tools/types.ts +175 -0
- package/src/tools/validation/PermissionChecker.ts +242 -0
- package/src/tools/validation/SensitiveFileDetector.ts +210 -0
- package/src/tools/validation/index.ts +11 -0
- package/src/ui/App.tsx +166 -0
- package/src/ui/components/AegisInterface.tsx +484 -0
- package/src/ui/components/common/ChatSearch.tsx +150 -0
- package/src/ui/components/common/ErrorBoundary.tsx +82 -0
- package/src/ui/components/common/ExitMessage.tsx +120 -0
- package/src/ui/components/common/LoadingIndicator.tsx +49 -0
- package/src/ui/components/common/index.ts +6 -0
- package/src/ui/components/dialog/ConfirmationPrompt.tsx +208 -0
- package/src/ui/components/dialog/InteractiveSelector.tsx +149 -0
- package/src/ui/components/dialog/SetupWizard.tsx +297 -0
- package/src/ui/components/dialog/UpdatePrompt.tsx +155 -0
- package/src/ui/components/dialog/index.ts +8 -0
- package/src/ui/components/index.ts +28 -0
- package/src/ui/components/input/CommandSuggestions.tsx +139 -0
- package/src/ui/components/input/CustomTextInput.tsx +220 -0
- package/src/ui/components/input/InputArea.tsx +361 -0
- package/src/ui/components/input/PromptSuggestions.tsx +66 -0
- package/src/ui/components/input/index.ts +6 -0
- package/src/ui/components/layout/ChatStatusBar.tsx +90 -0
- package/src/ui/components/layout/ContextBar.tsx +79 -0
- package/src/ui/components/layout/MessageArea.tsx +96 -0
- package/src/ui/components/layout/MessageList.tsx +647 -0
- package/src/ui/components/layout/MessageSeparator.tsx +26 -0
- package/src/ui/components/layout/WelcomeMessage.tsx +93 -0
- package/src/ui/components/layout/index.ts +7 -0
- package/src/ui/components/markdown/CodeHighlighter.tsx +292 -0
- package/src/ui/components/markdown/MessageRenderer.tsx +1211 -0
- package/src/ui/components/markdown/index.ts +8 -0
- package/src/ui/components/markdown/parser.ts +336 -0
- package/src/ui/components/markdown/types.ts +66 -0
- package/src/ui/focus/FocusManager.ts +137 -0
- package/src/ui/focus/index.ts +13 -0
- package/src/ui/focus/types.ts +54 -0
- package/src/ui/focus/useFocus.ts +75 -0
- package/src/ui/hooks/index.ts +11 -0
- package/src/ui/hooks/useAgent.ts +284 -0
- package/src/ui/hooks/useCommandHistory.ts +87 -0
- package/src/ui/hooks/useCommandProcessor.ts +443 -0
- package/src/ui/hooks/useConfirmation.ts +99 -0
- package/src/ui/hooks/useCtrlCHandler.ts +100 -0
- package/src/ui/hooks/useInputBuffer.ts +122 -0
- package/src/ui/hooks/useTerminalSize.ts +68 -0
- package/src/ui/hooks/useTerminalWidth.ts +5 -0
- package/src/ui/hooks/useWindowedList.ts +118 -0
- package/src/ui/render-debugger.ts +621 -0
- package/src/ui/test.ts +189 -0
- package/src/ui/themes/ThemeManager.ts +332 -0
- package/src/ui/themes/aegisTheme.ts +87 -0
- package/src/ui/themes/darkTheme.ts +87 -0
- package/src/ui/themes/defaultTheme.ts +85 -0
- package/src/ui/themes/index.ts +10 -0
- package/src/ui/themes/lightTheme.ts +89 -0
- package/src/ui/themes/popularThemes.ts +187 -0
- package/src/ui/themes/types.ts +130 -0
- package/src/utils/clipboard.ts +48 -0
- package/src/utils/debug.ts +43 -0
- package/src/utils/environment.ts +68 -0
- package/src/utils/index.ts +10 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
*
|
|
3
|
+
*
|
|
4
|
+
*
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { nanoid } from 'nanoid';
|
|
8
|
+
import type { Message } from '../agent/types.js';
|
|
9
|
+
import type { CompactionOptions, CompactionResult, FileContent } from './types.js';
|
|
10
|
+
import { TokenCounter } from './TokenCounter.js';
|
|
11
|
+
import { FileAnalyzer } from './FileAnalyzer.js';
|
|
12
|
+
import { onCompaction } from '../hooks/index.js';
|
|
13
|
+
|
|
14
|
+
export class CompactionService {
|
|
15
|
+
/** 压缩阈值百分比(80%) */
|
|
16
|
+
private static readonly THRESHOLD_PERCENT = 0.8;
|
|
17
|
+
/** 保留比例(20%) */
|
|
18
|
+
private static readonly RETAIN_PERCENT = 0.2;
|
|
19
|
+
/** 降级时保留比例(30%) */
|
|
20
|
+
private static readonly FALLBACK_RETAIN_PERCENT = 0.3;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
*
|
|
24
|
+
*/
|
|
25
|
+
static shouldCompact(
|
|
26
|
+
messages: Message[],
|
|
27
|
+
modelName: string,
|
|
28
|
+
maxContextTokens: number
|
|
29
|
+
): boolean {
|
|
30
|
+
return TokenCounter.shouldCompact(
|
|
31
|
+
messages,
|
|
32
|
+
modelName,
|
|
33
|
+
maxContextTokens,
|
|
34
|
+
this.THRESHOLD_PERCENT
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
*
|
|
40
|
+
*/
|
|
41
|
+
static async compact(
|
|
42
|
+
messages: Message[],
|
|
43
|
+
options: CompactionOptions
|
|
44
|
+
): Promise<CompactionResult> {
|
|
45
|
+
const preTokens = options.actualPreTokens
|
|
46
|
+
?? TokenCounter.countTokens(messages, options.modelName);
|
|
47
|
+
|
|
48
|
+
// 执行 Compaction Hook - 检查是否应该阻止压
|
|
49
|
+
const shouldPrevent = await onCompaction(
|
|
50
|
+
preTokens,
|
|
51
|
+
messages.length,
|
|
52
|
+
options.sessionId || 'unknown',
|
|
53
|
+
options.projectDir || process.cwd()
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
if (shouldPrevent) {
|
|
57
|
+
console.log('[CompactionService] 压缩被 Hook 阻止');
|
|
58
|
+
return {
|
|
59
|
+
success: false,
|
|
60
|
+
summary: '',
|
|
61
|
+
preTokens,
|
|
62
|
+
postTokens: preTokens,
|
|
63
|
+
filesIncluded: [],
|
|
64
|
+
compactedMessages: messages,
|
|
65
|
+
error: 'Compaction prevented by hook',
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
console.log('[CompactionService] 开始压缩,消息数:', messages.length);
|
|
71
|
+
|
|
72
|
+
// 1. 分析并读取重点文
|
|
73
|
+
const fileRefs = FileAnalyzer.analyzeFiles(messages);
|
|
74
|
+
const filePaths = fileRefs.map(f => f.path);
|
|
75
|
+
const fileContents = await FileAnalyzer.readFilesContent(filePaths);
|
|
76
|
+
|
|
77
|
+
// 2. 调用 LLM 生成总
|
|
78
|
+
const summary = await this.generateSummary(messages, fileContents, options);
|
|
79
|
+
|
|
80
|
+
// 3. 计算保留范围并过滤孤儿 tool 消
|
|
81
|
+
const retainCount = Math.ceil(messages.length * this.RETAIN_PERCENT);
|
|
82
|
+
const candidateMessages = messages.slice(-retainCount);
|
|
83
|
+
const retainedMessages = this.filterOrphanToolMessages(candidateMessages);
|
|
84
|
+
|
|
85
|
+
// 4. 创建压缩消
|
|
86
|
+
const summaryMessage = this.createSummaryMessage(nanoid(), summary);
|
|
87
|
+
const compactedMessages = [summaryMessage, ...retainedMessages];
|
|
88
|
+
|
|
89
|
+
const postTokens = TokenCounter.countTokens(compactedMessages, options.modelName);
|
|
90
|
+
|
|
91
|
+
console.log(`[CompactionService] Token 变化: ${preTokens} → ${postTokens}`);
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
success: true,
|
|
95
|
+
summary,
|
|
96
|
+
preTokens,
|
|
97
|
+
postTokens,
|
|
98
|
+
filesIncluded: filePaths,
|
|
99
|
+
compactedMessages,
|
|
100
|
+
};
|
|
101
|
+
} catch (error) {
|
|
102
|
+
// 降级策略:简单截
|
|
103
|
+
return this.fallbackCompact(messages, options, preTokens, error);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
*
|
|
109
|
+
*/
|
|
110
|
+
private static async generateSummary(
|
|
111
|
+
messages: Message[],
|
|
112
|
+
fileContents: FileContent[],
|
|
113
|
+
options: CompactionOptions
|
|
114
|
+
): Promise<string> {
|
|
115
|
+
const prompt = this.buildCompactionPrompt(messages, fileContents);
|
|
116
|
+
|
|
117
|
+
// 如果提供了 chatService,使用它来生成总
|
|
118
|
+
if (options.chatService && typeof (options.chatService as any).chat === 'function') {
|
|
119
|
+
try {
|
|
120
|
+
const response = await (options.chatService as any).chat([
|
|
121
|
+
{ role: 'system', content: 'You are a helpful assistant that creates concise summaries.' },
|
|
122
|
+
{ role: 'user', content: prompt },
|
|
123
|
+
]);
|
|
124
|
+
return response.content || this.createFallbackSummary(messages);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
console.warn('[CompactionService] LLM 调用失败,使用回退总结', error);
|
|
127
|
+
return this.createFallbackSummary(messages);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 没有 chatService,使用简单的摘
|
|
132
|
+
return this.createFallbackSummary(messages);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
*
|
|
137
|
+
*/
|
|
138
|
+
private static buildCompactionPrompt(
|
|
139
|
+
messages: Message[],
|
|
140
|
+
fileContents: FileContent[]
|
|
141
|
+
): string {
|
|
142
|
+
// 格式化消息历
|
|
143
|
+
const messagesText = messages.map((msg, i) => {
|
|
144
|
+
const role = msg.role || 'unknown';
|
|
145
|
+
const content = typeof msg.content === 'string'
|
|
146
|
+
? msg.content
|
|
147
|
+
: JSON.stringify(msg.content);
|
|
148
|
+
|
|
149
|
+
// 截断过长消
|
|
150
|
+
const maxLength = 5000;
|
|
151
|
+
const truncated = content.length > maxLength
|
|
152
|
+
? content.substring(0, maxLength) + '...'
|
|
153
|
+
: content;
|
|
154
|
+
|
|
155
|
+
return `[${i + 1}] ${role}: ${truncated}`;
|
|
156
|
+
}).join('\n\n');
|
|
157
|
+
|
|
158
|
+
// 格式化文件内
|
|
159
|
+
const filesText = fileContents.map(file =>
|
|
160
|
+
`### ${file.path}\n\`\`\`\n${file.content}\n\`\`\``
|
|
161
|
+
).join('\n\n');
|
|
162
|
+
|
|
163
|
+
return `Your task is to create a detailed summary of the conversation so far. This summary will be used as context for continuing the conversation, so it's important to preserve key information.
|
|
164
|
+
|
|
165
|
+
## Conversation History
|
|
166
|
+
${messagesText}
|
|
167
|
+
|
|
168
|
+
${fileContents.length > 0 ? `## Important Files\n\n${filesText}` : ''}
|
|
169
|
+
|
|
170
|
+
Please provide your summary following this structure:
|
|
171
|
+
|
|
172
|
+
1. **Primary Request and Intent** - What is the user trying to accomplish?
|
|
173
|
+
2. **Key Technical Concepts** - Important technical details, patterns, or decisions
|
|
174
|
+
3. **Files and Code Sections** - Key files mentioned or modified
|
|
175
|
+
4. **Errors and Fixes** - Any issues encountered and how they were resolved
|
|
176
|
+
5. **Problem Solving** - Approach taken to solve problems
|
|
177
|
+
6. **All User Messages** - Brief summary of what the user asked
|
|
178
|
+
7. **Pending Tasks** - Any incomplete work or next steps
|
|
179
|
+
8. **Current Work** - What was being worked on most recently
|
|
180
|
+
9. **Optional Next Step** - Suggested next action
|
|
181
|
+
|
|
182
|
+
Keep the summary concise but comprehensive. Focus on information that would be needed to continue the work.`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
*
|
|
187
|
+
*/
|
|
188
|
+
private static createFallbackSummary(messages: Message[]): string {
|
|
189
|
+
const userMessages = messages.filter(m => m.role === 'user');
|
|
190
|
+
const assistantMessages = messages.filter(m => m.role === 'assistant');
|
|
191
|
+
const toolCalls = messages.filter(m => m.role === 'tool' || (m.tool_calls && m.tool_calls.length > 0));
|
|
192
|
+
|
|
193
|
+
const userSummary = userMessages.slice(-5).map(m => {
|
|
194
|
+
const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content);
|
|
195
|
+
return `- ${content.substring(0, 200)}${content.length > 200 ? '...' : ''}`;
|
|
196
|
+
}).join('\n');
|
|
197
|
+
|
|
198
|
+
return `## Conversation Summary (Auto-generated)
|
|
199
|
+
|
|
200
|
+
### Statistics
|
|
201
|
+
- Total messages: ${messages.length}
|
|
202
|
+
- User messages: ${userMessages.length}
|
|
203
|
+
- Assistant messages: ${assistantMessages.length}
|
|
204
|
+
- Tool interactions: ${toolCalls.length}
|
|
205
|
+
|
|
206
|
+
### Recent User Requests
|
|
207
|
+
${userSummary || '(No user messages)'}
|
|
208
|
+
|
|
209
|
+
### Note
|
|
210
|
+
This is an automatically generated summary. Some context may have been lost.
|
|
211
|
+
The conversation can continue normally.`;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
*
|
|
216
|
+
*/
|
|
217
|
+
private static filterOrphanToolMessages(messages: Message[]): Message[] {
|
|
218
|
+
// 收集保留消息中所有 tool_call
|
|
219
|
+
const availableToolCallIds = new Set<string>();
|
|
220
|
+
for (const msg of messages) {
|
|
221
|
+
if (msg.role === 'assistant' && msg.tool_calls) {
|
|
222
|
+
for (const tc of msg.tool_calls) {
|
|
223
|
+
if (tc.id) {
|
|
224
|
+
availableToolCallIds.add(tc.id);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// 过滤孤儿 tool 消
|
|
231
|
+
return messages.filter(msg => {
|
|
232
|
+
if (msg.role === 'tool' && msg.tool_call_id) {
|
|
233
|
+
return availableToolCallIds.has(msg.tool_call_id);
|
|
234
|
+
}
|
|
235
|
+
return true;
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
*
|
|
241
|
+
*/
|
|
242
|
+
private static createSummaryMessage(id: string, summary: string): Message {
|
|
243
|
+
return {
|
|
244
|
+
role: 'user',
|
|
245
|
+
content: `[Previous conversation summary]\n\n${summary}\n\n[End of summary - conversation continues below]`,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
*
|
|
251
|
+
*/
|
|
252
|
+
private static fallbackCompact(
|
|
253
|
+
messages: Message[],
|
|
254
|
+
options: CompactionOptions,
|
|
255
|
+
preTokens: number,
|
|
256
|
+
error: unknown
|
|
257
|
+
): CompactionResult {
|
|
258
|
+
console.warn('[CompactionService] 使用降级策略', error);
|
|
259
|
+
|
|
260
|
+
// 保留 30% 的最近消
|
|
261
|
+
const retainCount = Math.ceil(messages.length * this.FALLBACK_RETAIN_PERCENT);
|
|
262
|
+
const candidateMessages = messages.slice(-retainCount);
|
|
263
|
+
const retainedMessages = this.filterOrphanToolMessages(candidateMessages);
|
|
264
|
+
|
|
265
|
+
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
266
|
+
const summaryMessage = this.createSummaryMessage(
|
|
267
|
+
nanoid(),
|
|
268
|
+
`[Automatic compaction failed; using fallback]
|
|
269
|
+
|
|
270
|
+
An error occurred during compaction. Retained the latest ${retainCount} messages (~30%).
|
|
271
|
+
|
|
272
|
+
Error: ${errorMsg}
|
|
273
|
+
|
|
274
|
+
The conversation can continue, but consider retrying compaction later with /compact.`
|
|
275
|
+
);
|
|
276
|
+
|
|
277
|
+
const compactedMessages = [summaryMessage, ...retainedMessages];
|
|
278
|
+
const postTokens = TokenCounter.countTokens(compactedMessages, options.modelName);
|
|
279
|
+
|
|
280
|
+
return {
|
|
281
|
+
success: false,
|
|
282
|
+
summary: typeof summaryMessage.content === 'string' ? summaryMessage.content : '',
|
|
283
|
+
preTokens,
|
|
284
|
+
postTokens,
|
|
285
|
+
filesIncluded: [],
|
|
286
|
+
compactedMessages,
|
|
287
|
+
error: errorMsg,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
*
|
|
293
|
+
*/
|
|
294
|
+
static async forceCompact(
|
|
295
|
+
messages: Message[],
|
|
296
|
+
options: Omit<CompactionOptions, 'trigger'>
|
|
297
|
+
): Promise<CompactionResult> {
|
|
298
|
+
return this.compact(messages, { ...options, trigger: 'auto' });
|
|
299
|
+
}
|
|
300
|
+
}
|