Skip to content

Commit 9f27169

Browse files
committed
feat: add tiered tool-repetition detection (soft warning + hard stop)
Replace the single-threshold ToolRepetitionDetector with a two-tier system: - Soft block (default 2nd identical call): the tool is not executed and the model receives an error asking it to justify the repeat. The user is not involved and the counter keeps incrementing toward the hard limit. - Hard stop: execution stops and the user is asked for guidance (previous behavior).
1 parent 80fb159 commit 9f27169

52 files changed

Lines changed: 508 additions & 419 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/vscode-e2e/src/types/global.d.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import type { RooCodeAPI } from "@roo-code/types"
22

33
declare global {
4+
// `var` is required here: only a `var` declaration inside `declare global`
5+
// attaches the property to `globalThis` so that `global.api` is typed.
6+
// `let`/`const` and interface augmentation do not achieve this, so the
7+
// `no-var` rule is a false positive in this specific declaration context.
8+
// eslint-disable-next-line no-var
49
var api: RooCodeAPI
510
}
611

‎packages/types/src/provider-settings.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@ import {
3030

3131
export const DEFAULT_CONSECUTIVE_MISTAKE_LIMIT = 3
3232

33+
/**
34+
* Number of identical consecutive tool calls allowed before the tool is
35+
* soft-blocked. When reached, the tool is not executed and the model is
36+
* asked to justify why it needs to repeat the call. Set to 0 to disable.
37+
*/
38+
export const DEFAULT_TOOL_REPETITION_SOFT_LIMIT = 2
39+
3340
/**
3441
* DynamicProvider
3542
*
@@ -191,6 +198,7 @@ const baseProviderSettingsSchema = z.object({
191198
modelTemperature: z.number().nullish(),
192199
rateLimitSeconds: z.number().optional(),
193200
consecutiveMistakeLimit: z.number().min(0).optional(),
201+
toolRepetitionSoftLimit: z.number().min(0).optional(),
194202

195203
// Model reasoning.
196204
enableReasoningEffort: z.boolean().optional(),

‎packages/types/src/task.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ export interface CreateTaskOptions {
8787
taskId?: string
8888
enableCheckpoints?: boolean
8989
consecutiveMistakeLimit?: number
90+
toolRepetitionSoftLimit?: number
9091
experiments?: Record<string, boolean>
9192
initialTodos?: TodoItem[]
9293
/** Initial status for the task's history item (e.g., "active" for child tasks) */

‎src/core/assistant-message/__tests__/presentAssistantMessage-custom-tool.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ describe("presentAssistantMessage - Custom Tool Recording", () => {
6363
recordToolUsage: vi.fn(),
6464
recordToolError: vi.fn(),
6565
toolRepetitionDetector: {
66-
check: vi.fn().mockReturnValue({ allowExecution: true }),
66+
check: vi.fn().mockReturnValue({ action: "allow" }),
6767
},
6868
providerRef: {
6969
deref: () => ({

‎src/core/assistant-message/__tests__/presentAssistantMessage-images.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ describe("presentAssistantMessage - Image Handling in Native Tool Calling", () =
4747
},
4848
recordToolUsage: vi.fn(),
4949
toolRepetitionDetector: {
50-
check: vi.fn().mockReturnValue({ allowExecution: true }),
50+
check: vi.fn().mockReturnValue({ action: "allow" }),
5151
},
5252
providerRef: {
5353
deref: () => ({

‎src/core/assistant-message/__tests__/presentAssistantMessage-unknown-tool.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ describe("presentAssistantMessage - Unknown Tool Handling", () => {
4343
recordToolUsage: vi.fn(),
4444
recordToolError: vi.fn(),
4545
toolRepetitionDetector: {
46-
check: vi.fn().mockReturnValue({ allowExecution: true }),
46+
check: vi.fn().mockReturnValue({ action: "allow" }),
4747
},
4848
providerRef: {
4949
deref: () => ({

‎src/core/assistant-message/presentAssistantMessage.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -629,8 +629,17 @@ export async function presentAssistantMessage(cline: Task) {
629629
// block directly.
630630
const repetitionCheck = cline.toolRepetitionDetector.check(block)
631631

632-
// If execution is not allowed, notify user and break.
633-
if (!repetitionCheck.allowExecution && repetitionCheck.askUser) {
632+
// Soft block: do NOT involve the user. Return an error to the
633+
// model asking it to justify repeating the call (or try a
634+
// different approach). The detector keeps counting so continued
635+
// repetition will eventually escalate to a hard block.
636+
if (repetitionCheck.action === "soft_block") {
637+
pushToolResult(formatResponse.toolError(repetitionCheck.message))
638+
break
639+
}
640+
641+
// Hard block: stop and ask the user for guidance.
642+
if (repetitionCheck.action === "hard_block") {
634643
// Handle repetition similar to mistake_limit_reached pattern.
635644
const { response, text, images } = await cline.ask(
636645
repetitionCheck.askUser.messageKey as ClineAsk,

‎src/core/config/ProviderSettingsManager.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
isSecretStateKey,
1010
ProviderSettingsEntry,
1111
DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
12+
DEFAULT_TOOL_REPETITION_SOFT_LIMIT,
1213
getModelId,
1314
type ProviderName,
1415
isProviderName,
@@ -43,6 +44,7 @@ export const providerProfilesSchema = z.object({
4344
rateLimitSecondsMigrated: z.boolean().optional(),
4445
openAiHeadersMigrated: z.boolean().optional(),
4546
consecutiveMistakeLimitMigrated: z.boolean().optional(),
47+
toolRepetitionLimitsMigrated: z.boolean().optional(),
4648
todoListEnabledMigrated: z.boolean().optional(),
4749
claudeCodeLegacySettingsMigrated: z.boolean().optional(),
4850
routerProviderMigrated: z.boolean().optional(),
@@ -68,6 +70,7 @@ export class ProviderSettingsManager {
6870
rateLimitSecondsMigrated: true, // Mark as migrated on fresh installs
6971
openAiHeadersMigrated: true, // Mark as migrated on fresh installs
7072
consecutiveMistakeLimitMigrated: true, // Mark as migrated on fresh installs
73+
toolRepetitionLimitsMigrated: true, // Mark as migrated on fresh installs
7174
todoListEnabledMigrated: true, // Mark as migrated on fresh installs
7275
claudeCodeLegacySettingsMigrated: true, // Mark as migrated on fresh installs
7376
routerProviderMigrated: true, // Mark as migrated on fresh installs
@@ -174,6 +177,12 @@ export class ProviderSettingsManager {
174177
isDirty = true
175178
}
176179

180+
if (!providerProfiles.migrations.toolRepetitionLimitsMigrated) {
181+
await this.migrateToolRepetitionLimits(providerProfiles)
182+
providerProfiles.migrations.toolRepetitionLimitsMigrated = true
183+
isDirty = true
184+
}
185+
177186
if (!providerProfiles.migrations.todoListEnabledMigrated) {
178187
await this.migrateTodoListEnabled(providerProfiles)
179188
providerProfiles.migrations.todoListEnabledMigrated = true
@@ -271,6 +280,19 @@ export class ProviderSettingsManager {
271280
}
272281
}
273282

283+
private async migrateToolRepetitionLimits(providerProfiles: ProviderProfiles) {
284+
try {
285+
for (const [_name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
286+
// Default the soft warning threshold.
287+
if (apiConfig.toolRepetitionSoftLimit == null) {
288+
apiConfig.toolRepetitionSoftLimit = DEFAULT_TOOL_REPETITION_SOFT_LIMIT
289+
}
290+
}
291+
} catch (error) {
292+
console.error(`[MigrateToolRepetitionLimits] Failed to migrate tool repetition limits:`, error)
293+
}
294+
}
295+
274296
private async migrateTodoListEnabled(providerProfiles: ProviderProfiles) {
275297
try {
276298
for (const [_name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {

‎src/core/config/__tests__/ProviderSettingsManager.spec.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ describe("ProviderSettingsManager", () => {
9191
rateLimitSecondsMigrated: true,
9292
openAiHeadersMigrated: true,
9393
consecutiveMistakeLimitMigrated: true,
94+
toolRepetitionLimitsMigrated: true,
9495
todoListEnabledMigrated: true,
9596
claudeCodeLegacySettingsMigrated: true,
9697
routerProviderMigrated: true,
@@ -211,6 +212,49 @@ describe("ProviderSettingsManager", () => {
211212
expect(storedConfig.migrations.consecutiveMistakeLimitMigrated).toEqual(true)
212213
})
213214

215+
it("should call migrateToolRepetitionLimits if it has not done so already", async () => {
216+
mockSecrets.get.mockResolvedValue(
217+
JSON.stringify({
218+
currentApiConfigName: "default",
219+
apiConfigs: {
220+
default: {
221+
config: {},
222+
id: "default",
223+
},
224+
existing: {
225+
apiProvider: "anthropic",
226+
consecutiveMistakeLimit: 7,
227+
},
228+
preset: {
229+
apiProvider: "anthropic",
230+
// Pre-existing repetition limits should not be overwritten
231+
toolRepetitionSoftLimit: 1,
232+
},
233+
},
234+
migrations: {
235+
rateLimitSecondsMigrated: true,
236+
openAiHeadersMigrated: true,
237+
consecutiveMistakeLimitMigrated: true,
238+
toolRepetitionLimitsMigrated: false,
239+
},
240+
}),
241+
)
242+
243+
await providerSettingsManager.initialize()
244+
245+
const calls = mockSecrets.store.mock.calls
246+
const storedConfig = JSON.parse(calls[calls.length - 1][1])
247+
248+
// Default soft limit applied everywhere it was missing
249+
expect(storedConfig.apiConfigs.default.toolRepetitionSoftLimit).toEqual(2)
250+
expect(storedConfig.apiConfigs.existing.toolRepetitionSoftLimit).toEqual(2)
251+
252+
// Pre-existing soft limit is not overwritten
253+
expect(storedConfig.apiConfigs.preset.toolRepetitionSoftLimit).toEqual(1)
254+
255+
expect(storedConfig.migrations.toolRepetitionLimitsMigrated).toEqual(true)
256+
})
257+
214258
it("should call migrateTodoListEnabled if it has not done so already", async () => {
215259
mockSecrets.get.mockResolvedValue(
216260
JSON.stringify({

‎src/core/task/Task.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import {
4848
isResumableAsk,
4949
QueuedMessage,
5050
DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
51+
DEFAULT_TOOL_REPETITION_SOFT_LIMIT,
5152
DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
5253
MAX_CHECKPOINT_TIMEOUT_SECONDS,
5354
MIN_CHECKPOINT_TIMEOUT_SECONDS,
@@ -315,6 +316,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
315316
// Tool Use
316317
consecutiveMistakeCount: number = 0
317318
consecutiveMistakeLimit: number
319+
toolRepetitionSoftLimit: number
318320
consecutiveMistakeCountForApplyDiff: Map<string, number> = new Map()
319321
consecutiveMistakeCountForEditFile: Map<string, number> = new Map()
320322
consecutiveNoToolUseCount: number = 0
@@ -442,6 +444,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
442444
enableCheckpoints = true,
443445
checkpointTimeout = DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
444446
consecutiveMistakeLimit = DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
447+
toolRepetitionSoftLimit = DEFAULT_TOOL_REPETITION_SOFT_LIMIT,
445448
taskId,
446449
task,
447450
images,
@@ -510,6 +513,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
510513
this.autoApprovalHandler = new AutoApprovalHandler()
511514

512515
this.consecutiveMistakeLimit = consecutiveMistakeLimit ?? DEFAULT_CONSECUTIVE_MISTAKE_LIMIT
516+
this.toolRepetitionSoftLimit = toolRepetitionSoftLimit ?? DEFAULT_TOOL_REPETITION_SOFT_LIMIT
513517
this.providerRef = new WeakRef(provider)
514518
this.globalStoragePath = provider.context.globalStorageUri.fsPath
515519
this.diffViewProvider = new DiffViewProvider(this.cwd, this)
@@ -564,7 +568,10 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
564568
// Set up diff strategy
565569
this.diffStrategy = new MultiSearchReplaceDiffStrategy(diffFuzzyThreshold)
566570

567-
this.toolRepetitionDetector = new ToolRepetitionDetector(this.consecutiveMistakeLimit)
571+
this.toolRepetitionDetector = new ToolRepetitionDetector(
572+
this.toolRepetitionSoftLimit,
573+
this.consecutiveMistakeLimit,
574+
)
568575

569576
// Initialize todo list if provided
570577
if (initialTodos && initialTodos.length > 0) {

0 commit comments

Comments
 (0)