forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompact.ts
More file actions
287 lines (263 loc) · 9.84 KB
/
Copy pathcompact.ts
File metadata and controls
287 lines (263 loc) · 9.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import { feature } from 'bun:bundle'
import chalk from 'chalk'
import { markPostCompaction } from 'src/bootstrap/state.js'
import { getSystemPrompt } from '../../constants/prompts.js'
import { getSystemContext, getUserContext } from '../../context.js'
import { getShortcutDisplay } from '../../keybindings/shortcutFormat.js'
import { notifyCompaction } from '../../services/api/promptCacheBreakDetection.js'
import {
type CompactionResult,
compactConversation,
ERROR_MESSAGE_INCOMPLETE_RESPONSE,
ERROR_MESSAGE_NOT_ENOUGH_MESSAGES,
ERROR_MESSAGE_USER_ABORT,
mergeHookInstructions,
} from '../../services/compact/compact.js'
import { suppressCompactWarning } from '../../services/compact/compactWarningState.js'
import { microcompactMessages } from '../../services/compact/microCompact.js'
import { runPostCompactCleanup } from '../../services/compact/postCompactCleanup.js'
import { trySessionMemoryCompaction } from '../../services/compact/sessionMemoryCompact.js'
import { setLastSummarizedMessageId } from '../../services/SessionMemory/sessionMemoryUtils.js'
import type { ToolUseContext } from '../../Tool.js'
import type { LocalCommandCall } from '../../types/command.js'
import type { Message } from '../../types/message.js'
import { hasExactErrorMessage } from '../../utils/errors.js'
import { executePreCompactHooks } from '../../utils/hooks.js'
import { logError } from '../../utils/log.js'
import { getMessagesAfterCompactBoundary } from '../../utils/messages.js'
import { getUpgradeMessage } from '../../utils/model/contextWindowUpgradeCheck.js'
import {
buildEffectiveSystemPrompt,
type SystemPrompt,
} from '../../utils/systemPrompt.js'
/* eslint-disable @typescript-eslint/no-require-imports */
const reactiveCompact = feature('REACTIVE_COMPACT')
? (require('../../services/compact/reactiveCompact.js') as typeof import('../../services/compact/reactiveCompact.js'))
: null
/* eslint-enable @typescript-eslint/no-require-imports */
export const call: LocalCommandCall = async (args, context) => {
const { abortController } = context
let { messages } = context
// REPL keeps snipped messages for UI scrollback — project so the compact
// model doesn't summarize content that was intentionally removed.
messages = getMessagesAfterCompactBoundary(messages)
if (messages.length === 0) {
throw new Error('No messages to compact')
}
const customInstructions = args.trim()
try {
// Try session memory compaction first if no custom instructions
// (session memory compaction doesn't support custom instructions)
if (!customInstructions) {
const sessionMemoryResult = await trySessionMemoryCompaction(
messages,
context.agentId,
)
if (sessionMemoryResult) {
getUserContext.cache.clear?.()
runPostCompactCleanup()
// Reset cache read baseline so the post-compact drop isn't flagged
// as a break. compactConversation does this internally; SM-compact doesn't.
if (feature('PROMPT_CACHE_BREAK_DETECTION')) {
notifyCompaction(
context.options.querySource ?? 'compact',
context.agentId,
)
}
markPostCompaction()
// Suppress warning immediately after successful compaction
suppressCompactWarning()
return {
type: 'compact',
compactionResult: sessionMemoryResult,
displayText: buildDisplayText(context),
}
}
}
// Reactive-only mode: route /compact through the reactive path.
// Checked after session-memory (that path is cheap and orthogonal).
if (reactiveCompact?.isReactiveOnlyMode()) {
return await compactViaReactive(
messages,
context,
customInstructions,
reactiveCompact,
)
}
// Fall back to traditional compaction
// Run microcompact first to reduce tokens before summarization
const microcompactResult = await microcompactMessages(messages, context)
const messagesForCompact = microcompactResult.messages
const result = await compactConversation(
messagesForCompact,
context,
await getCacheSharingParams(context, messagesForCompact),
false,
customInstructions,
false,
)
// Reset lastSummarizedMessageId since legacy compaction replaces all messages
// and the old message UUID will no longer exist in the new messages array
setLastSummarizedMessageId(undefined)
// Suppress the "Context left until auto-compact" warning after successful compaction
suppressCompactWarning()
getUserContext.cache.clear?.()
runPostCompactCleanup()
return {
type: 'compact',
compactionResult: result,
displayText: buildDisplayText(context, result.userDisplayMessage),
}
} catch (error) {
if (abortController.signal.aborted) {
throw new Error('Compaction canceled.')
} else if (hasExactErrorMessage(error, ERROR_MESSAGE_NOT_ENOUGH_MESSAGES)) {
throw new Error(ERROR_MESSAGE_NOT_ENOUGH_MESSAGES)
} else if (hasExactErrorMessage(error, ERROR_MESSAGE_INCOMPLETE_RESPONSE)) {
throw new Error(ERROR_MESSAGE_INCOMPLETE_RESPONSE)
} else {
logError(error)
throw new Error(`Error during compaction: ${error}`)
}
}
}
async function compactViaReactive(
messages: Message[],
context: ToolUseContext,
customInstructions: string,
reactive: NonNullable<typeof reactiveCompact>,
): Promise<{
type: 'compact'
compactionResult: CompactionResult
displayText: string
}> {
context.onCompactProgress?.({
type: 'hooks_start',
hookType: 'pre_compact',
})
context.setSDKStatus?.('compacting')
try {
// Hooks and cache-param build are independent — run concurrently.
// getCacheSharingParams walks all tools to build the system prompt;
// pre-compact hooks spawn subprocesses. Neither depends on the other.
const [hookResult, cacheSafeParams] = await Promise.all([
executePreCompactHooks(
{ trigger: 'manual', customInstructions: customInstructions || null },
context.abortController.signal,
),
getCacheSharingParams(context, messages),
])
const mergedInstructions = mergeHookInstructions(
customInstructions,
hookResult.newCustomInstructions,
)
context.setStreamMode?.('requesting')
context.setResponseLength?.(() => 0)
context.onCompactProgress?.({ type: 'compact_start' })
const outcome = await reactive.reactiveCompactOnPromptTooLong(
messages,
cacheSafeParams,
{ customInstructions: mergedInstructions, trigger: 'manual' },
)
if (!outcome.ok) {
// The outer catch in `call` translates these: aborted → "Compaction
// canceled." (via abortController.signal.aborted check), NOT_ENOUGH →
// re-thrown as-is, everything else → "Error during compaction: …".
switch (outcome.reason) {
case 'too_few_groups':
throw new Error(ERROR_MESSAGE_NOT_ENOUGH_MESSAGES)
case 'aborted':
throw new Error(ERROR_MESSAGE_USER_ABORT)
case 'exhausted':
case 'error':
case 'media_unstrippable':
throw new Error(ERROR_MESSAGE_INCOMPLETE_RESPONSE)
}
}
// Mirrors the post-success cleanup in tryReactiveCompact, minus
// resetMicrocompactState — processSlashCommand calls that for all
// type:'compact' results.
setLastSummarizedMessageId(undefined)
runPostCompactCleanup()
suppressCompactWarning()
getUserContext.cache.clear?.()
// reactiveCompactOnPromptTooLong runs PostCompact hooks but not PreCompact
// — both callers (here and tryReactiveCompact) run PreCompact outside so
// they can merge its userDisplayMessage with PostCompact's here. This
// caller additionally runs it concurrently with getCacheSharingParams.
const combinedMessage =
[hookResult.userDisplayMessage, outcome.result.userDisplayMessage]
.filter(Boolean)
.join('\n') || undefined
return {
type: 'compact',
compactionResult: {
...outcome.result,
userDisplayMessage: combinedMessage,
},
displayText: buildDisplayText(context, combinedMessage),
}
} finally {
context.setStreamMode?.('requesting')
context.setResponseLength?.(() => 0)
context.onCompactProgress?.({ type: 'compact_end' })
context.setSDKStatus?.(null)
}
}
function buildDisplayText(
context: ToolUseContext,
userDisplayMessage?: string,
): string {
const upgradeMessage = getUpgradeMessage('tip')
const expandShortcut = getShortcutDisplay(
'app:toggleTranscript',
'Global',
'ctrl+o',
)
const dimmed = [
...(context.options.verbose
? []
: [`(${expandShortcut} to see full summary)`]),
...(userDisplayMessage ? [userDisplayMessage] : []),
...(upgradeMessage ? [upgradeMessage] : []),
]
return chalk.dim('Compacted ' + dimmed.join('\n'))
}
async function getCacheSharingParams(
context: ToolUseContext,
forkContextMessages: Message[],
): Promise<{
systemPrompt: SystemPrompt
userContext: { [k: string]: string }
systemContext: { [k: string]: string }
toolUseContext: ToolUseContext
forkContextMessages: Message[]
}> {
const appState = context.getAppState()
const defaultSysPrompt = await getSystemPrompt(
context.options.tools,
context.options.mainLoopModel,
Array.from(
appState.toolPermissionContext.additionalWorkingDirectories.keys(),
),
context.options.mcpClients,
)
const systemPrompt = buildEffectiveSystemPrompt({
mainThreadAgentDefinition: undefined,
toolUseContext: context,
customSystemPrompt: context.options.customSystemPrompt,
defaultSystemPrompt: defaultSysPrompt,
appendSystemPrompt: context.options.appendSystemPrompt,
})
const [userContext, systemContext] = await Promise.all([
getUserContext(),
getSystemContext(),
])
return {
systemPrompt,
userContext,
systemContext,
toolUseContext: context,
forkContextMessages,
}
}