-
-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathinject.ts
More file actions
370 lines (318 loc) · 12.2 KB
/
inject.ts
File metadata and controls
370 lines (318 loc) · 12.2 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import type { SessionState, WithParts } from "../state"
import type { Logger } from "../logger"
import type { PluginConfig } from "../config"
import type { UserMessage } from "@opencode-ai/sdk/v2"
import { formatMessageIdTag } from "../message-ids"
import { renderNudge, renderCompressNudge } from "../prompts"
import {
extractParameterKey,
createSyntheticTextPart,
createSyntheticToolPart,
isIgnoredUserMessage,
appendMessageIdTagToToolOutput,
findLastToolPart,
} from "./utils"
import { getFilePathsFromParameters, isProtected } from "../protected-file-patterns"
import { getLastUserMessage, isMessageCompacted } from "../shared-utils"
import { getCurrentTokenUsage } from "../strategies/utils"
function parsePercentageString(value: string, total: number): number | undefined {
if (!value.endsWith("%")) return undefined
const percent = parseFloat(value.slice(0, -1))
if (isNaN(percent)) {
return undefined
}
const roundedPercent = Math.round(percent)
const clampedPercent = Math.max(0, Math.min(100, roundedPercent))
return Math.round((clampedPercent / 100) * total)
}
// XML wrappers
export const wrapPrunableTools = (content: string): string => {
return `<prunable-tools>
The following tools have been invoked and are available for pruning. This list does not mandate immediate action. Consider your current goals and the resources you need before pruning valuable tool inputs or outputs. Consolidate your prunes for efficiency; it is rarely worth pruning a single tiny tool output. Keep the context free of noise.
${content}
</prunable-tools>`
}
export const wrapCompressContext = (messageCount: number): string => `<compress-context>
Compress available. Conversation: ${messageCount} messages.
Compress collapses completed task sequences or exploration phases into summaries.
Uses ID boundaries [startId, endId, topic, summary].
</compress-context>`
export const wrapCooldownMessage = (flags: {
prune: boolean
distill: boolean
compress: boolean
}): string => {
const enabledTools: string[] = []
if (flags.distill) enabledTools.push("distill")
if (flags.compress) enabledTools.push("compress")
if (flags.prune) enabledTools.push("prune")
let toolName: string
if (enabledTools.length === 0) {
toolName = "pruning tools"
} else if (enabledTools.length === 1) {
toolName = `${enabledTools[0]} tool`
} else {
const last = enabledTools.pop()
toolName = `${enabledTools.join(", ")} or ${last} tools`
}
return `<context-info>
Context management was just performed. Do NOT use the ${toolName} again. A fresh list will be available after your next tool use.
</context-info>`
}
const resolveContextLimit = (
config: PluginConfig,
state: SessionState,
providerId: string | undefined,
modelId: string | undefined,
): number | undefined => {
const modelLimits = config.tools.settings.modelLimits
const contextLimit = config.tools.settings.contextLimit
if (modelLimits) {
const providerModelId =
providerId !== undefined && modelId !== undefined
? `${providerId}/${modelId}`
: undefined
const limit = providerModelId !== undefined ? modelLimits[providerModelId] : undefined
if (limit !== undefined) {
if (typeof limit === "string" && limit.endsWith("%")) {
if (state.modelContextLimit === undefined) {
return undefined
}
return parsePercentageString(limit, state.modelContextLimit)
}
return typeof limit === "number" ? limit : undefined
}
}
if (typeof contextLimit === "string") {
if (contextLimit.endsWith("%")) {
if (state.modelContextLimit === undefined) {
return undefined
}
return parsePercentageString(contextLimit, state.modelContextLimit)
}
return undefined
}
return contextLimit
}
const shouldInjectCompressNudge = (
config: PluginConfig,
state: SessionState,
messages: WithParts[],
providerId: string | undefined,
modelId: string | undefined,
): boolean => {
if (config.tools.compress.permission === "deny") {
return false
}
const lastAssistant = messages.findLast((msg) => msg.info.role === "assistant")
if (lastAssistant) {
const parts = Array.isArray(lastAssistant.parts) ? lastAssistant.parts : []
const hasDcpTool = parts.some(
(part) =>
part.type === "tool" &&
part.state.status === "completed" &&
(part.tool === "compress" || part.tool === "prune" || part.tool === "distill"),
)
if (hasDcpTool) {
return false
}
}
const contextLimit = resolveContextLimit(config, state, providerId, modelId)
if (contextLimit === undefined) {
return false
}
const currentTokens = getCurrentTokenUsage(messages)
return currentTokens > contextLimit
}
const getNudgeString = (config: PluginConfig): string => {
const flags = {
prune: config.tools.prune.permission !== "deny",
distill: config.tools.distill.permission !== "deny",
compress: config.tools.compress.permission !== "deny",
manual: false,
}
if (!flags.prune && !flags.distill && !flags.compress) {
return ""
}
return renderNudge(flags)
}
const getCooldownMessage = (config: PluginConfig): string => {
return wrapCooldownMessage({
prune: config.tools.prune.permission !== "deny",
distill: config.tools.distill.permission !== "deny",
compress: config.tools.compress.permission !== "deny",
})
}
const buildCompressContext = (state: SessionState, messages: WithParts[]): string => {
const messageCount = messages.filter((msg) => !isMessageCompacted(state, msg)).length
return wrapCompressContext(messageCount)
}
export const buildPrunableToolsList = (
state: SessionState,
config: PluginConfig,
logger: Logger,
): string => {
const lines: string[] = []
const toolIdList = state.toolIdList
state.toolParameters.forEach((toolParameterEntry, toolCallId) => {
if (state.prune.tools.has(toolCallId)) {
return
}
const allProtectedTools = config.tools.settings.protectedTools
if (allProtectedTools.includes(toolParameterEntry.tool)) {
return
}
const filePaths = getFilePathsFromParameters(
toolParameterEntry.tool,
toolParameterEntry.parameters,
)
if (isProtected(filePaths, config.protectedFilePatterns)) {
return
}
const numericId = toolIdList.indexOf(toolCallId)
if (numericId === -1) {
logger.warn(`Tool in cache but not in toolIdList - possible stale entry`, {
toolCallId,
tool: toolParameterEntry.tool,
})
return
}
const paramKey = extractParameterKey(toolParameterEntry.tool, toolParameterEntry.parameters)
const description = paramKey
? `${toolParameterEntry.tool}, ${paramKey}`
: toolParameterEntry.tool
const tokenSuffix =
toolParameterEntry.tokenCount !== undefined
? ` (~${toolParameterEntry.tokenCount} tokens)`
: ""
lines.push(`${numericId}: ${description}${tokenSuffix}`)
logger.debug(
`Prunable tool found - ID: ${numericId}, Tool: ${toolParameterEntry.tool}, Call ID: ${toolCallId}`,
)
})
if (lines.length === 0) {
return ""
}
return wrapPrunableTools(lines.join("\n"))
}
export const insertPruneToolContext = (
state: SessionState,
config: PluginConfig,
logger: Logger,
messages: WithParts[],
): void => {
if (state.manualMode || state.pendingManualTrigger) {
return
}
const pruneEnabled = config.tools.prune.permission !== "deny"
const distillEnabled = config.tools.distill.permission !== "deny"
const compressEnabled = config.tools.compress.permission !== "deny"
if (!pruneEnabled && !distillEnabled && !compressEnabled) {
return
}
const pruneOrDistillEnabled = pruneEnabled || distillEnabled
const contentParts: string[] = []
const lastUserMessage = getLastUserMessage(messages)
const providerId = lastUserMessage
? (lastUserMessage.info as UserMessage).model.providerID
: undefined
const modelId = lastUserMessage
? (lastUserMessage.info as UserMessage).model.modelID
: undefined
if (state.lastToolPrune) {
logger.debug("Last tool was prune - injecting cooldown message")
contentParts.push(getCooldownMessage(config))
} else {
if (pruneOrDistillEnabled) {
const prunableToolsList = buildPrunableToolsList(state, config, logger)
if (prunableToolsList) {
// logger.debug("prunable-tools: \n" + prunableToolsList)
contentParts.push(prunableToolsList)
}
}
if (compressEnabled) {
const compressContext = buildCompressContext(state, messages)
// logger.debug("compress-context: \n" + compressContext)
contentParts.push(compressContext)
}
if (shouldInjectCompressNudge(config, state, messages, providerId, modelId)) {
logger.info("Inserting compress nudge - token usage exceeds contextLimit")
contentParts.push(renderCompressNudge())
} else if (
config.tools.settings.nudgeEnabled &&
state.nudgeCounter >= Math.max(1, config.tools.settings.nudgeFrequency)
) {
logger.info("Inserting prune nudge message")
contentParts.push(getNudgeString(config))
}
}
if (contentParts.length === 0) {
return
}
const combinedContent = `\n${contentParts.join("\n")}`
if (!lastUserMessage) {
return
}
const lastNonIgnoredMessage = messages.findLast(
(msg) => !(msg.info.role === "user" && isIgnoredUserMessage(msg)),
)
if (!lastNonIgnoredMessage) {
return
}
// When following a user message, append a synthetic text part since models like Claude
// expect assistant turns to start with reasoning parts which cannot be easily faked.
// For all other cases, append a synthetic tool part to the last message which works
// across all models without disrupting their behavior.
if (lastNonIgnoredMessage.info.role === "user") {
const textPart = createSyntheticTextPart(
lastNonIgnoredMessage,
combinedContent,
`${lastNonIgnoredMessage.info.id}:context`,
)
lastNonIgnoredMessage.parts.push(textPart)
} else {
const toolPart = createSyntheticToolPart(
lastNonIgnoredMessage,
combinedContent,
modelId ?? "",
`${lastNonIgnoredMessage.info.id}:context`,
)
lastNonIgnoredMessage.parts.push(toolPart)
}
}
export const insertMessageIdContext = (
state: SessionState,
config: PluginConfig,
messages: WithParts[],
): void => {
if (config.tools.compress.permission === "deny") {
return
}
const lastUserMessage = getLastUserMessage(messages)
const toolModelId = lastUserMessage
? ((lastUserMessage.info as UserMessage).model.modelID ?? "")
: ""
for (const message of messages) {
if (message.info.role === "user" && isIgnoredUserMessage(message)) {
continue
}
const messageRef = state.messageIds.byRawId.get(message.info.id)
if (!messageRef) {
continue
}
const tag = formatMessageIdTag(messageRef)
const messageIdSeed = `${message.info.id}:message-id:${messageRef}`
if (message.info.role === "user") {
message.parts.push(createSyntheticTextPart(message, tag, messageIdSeed))
continue
}
if (message.info.role !== "assistant") {
continue
}
const lastToolPart = findLastToolPart(message)
if (lastToolPart && appendMessageIdTagToToolOutput(lastToolPart, tag)) {
continue
}
message.parts.push(createSyntheticToolPart(message, tag, toolModelId, messageIdSeed))
}
}