Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
810cb2a
feat(text-normalization): add stripAnsi and truncateTerminalOutput fu…
juniorhillory-creator Nov 17, 2026
7e7fa9d
fix(execute-command): replace stripAnsi with truncateTerminalOutput f…
juniorhillory-creator Nov 17, 2026
0bd14d4
feat(auto-approval): implement token circuit breaker and extend appro…
juniorhillory-creator Nov 17, 2026
a42dc57
feat(file-truncation): implement truncateFileOutput function for slid…
juniorhillory-creator Nov 17, 2026
46fe235
vitest error fixed.
juniorhillory-creator Nov 17, 2026
33498bd
feat(read-file-tool): implement adaptive sliding-window truncation an…
juniorhillory-creator Nov 17, 2026
6a4b008
fix(tests): update import statements for AutoApprovalHandler tests
juniorhillory-creator Nov 17, 2026
41f6a49
feat(types): add ambient type declarations for Node.js modules and up…
juniorhillory-creator Nov 17, 2026
fc21be3
style: format files with prettier
juniorhillory-creator Nov 17, 2026
d3ca38c
fix: resolve knip unused exports, unlisted dependencies, and config e…
juniorhillory-creator Nov 17, 2026
749a3bc
fix(lint): resolve ESLint violations across core tools and restore pr…
juniorhillory-creator Nov 17, 2026
149da24
fix(types): resolve TS2345 in writeToFileTool and TS2578 in text-norm…
juniorhillory-creator Nov 18, 2026
14f8ae4
test(auto-approval): verify rejection and window retention for token …
juniorhillory-creator Nov 18, 2026
3431bf4
Merge branch 'main' into main
juniorhillory-creator Nov 18, 2026
5c35943
Merge branch 'main' of https://github.com/juniorhillory-creator/Zoo-Code
juniorhillory-creator Nov 18, 2026
bd98000
test(auto-approval): verify affirmative reset and post-approval messa…
juniorhillory-creator Nov 18, 2026
9dc90d3
feat(auto-approval): wire allowedMaxTokens through settings schema, g…
juniorhillory-creator Nov 18, 2026
ed97cb6
fix(task): allow yesButtonClicked approval on token circuit breaker a…
juniorhillory-creator Nov 18, 2026
097ff09
fix(execute-command): retain full inline output up to compression lim…
juniorhillory-creator Nov 18, 2026
11fac4f
Update condition for file reading limits
juniorhillory-creator Nov 18, 2026
147bce3
fix(read-file): apply adaptive sliding-window preview only when both …
juniorhillory-creator Nov 18, 2026
c2ea96f
Merge branch 'main' of https://github.com/juniorhillory-creator/Zoo-Code
juniorhillory-creator Nov 18, 2026
42e01f3
fix(read-file): use complete numbered file content for adaptive previ…
juniorhillory-creator Nov 18, 2026
ec9e55e
fix(read-file): correct pagination metadata and retrieval instruction…
juniorhillory-creator Nov 18, 2026
c8fc59b
fix(text-normalization): accurately type unescapeHtmlEntities overloa…
juniorhillory-creator Nov 18, 2026
8265fa6
refactor(text-normalization): construct ANSI regex dynamically to eli…
juniorhillory-creator Nov 18, 2026
fbabf1e
feat(auto-approval): support tokens limit warning translation keys in…
juniorhillory-creator Nov 18, 2026
937a25b
test(AutoApprovedRequestLimitWarning): add missing test case for butt…
juniorhillory-creator Nov 18, 2026
b4ef5ab
fix(auto-approval): retain current unfinished api_req_started in toke…
juniorhillory-creator Nov 18, 2026
ca417f0
test(read-file): eliminate redundant any assertions and add offline t…
juniorhillory-creator Nov 18, 2026
ca0ed49
style: format files with prettier
juniorhillory-creator Nov 18, 2026
f70d3fe
fix(core): resolve test failures in readFileTool, executeCommand, and…
juniorhillory-creator Nov 18, 2026
f4c2b35
test(task): use providerIdentifiers.anthropic in token circuit breake…
juniorhillory-creator Nov 18, 2026
430ed14
chore(lint): prune stale suppressions in readFileTool spec
juniorhillory-creator Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions packages/types/src/__tests__/global-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,25 @@ describe("collapseCommandOutputByDefault global setting", () => {
expect(globalSettingsSchema.safeParse({ collapseCommandOutputByDefault: "true" }).success).toBe(false)
})
})

describe("allowedMaxTokens global setting", () => {
it("accepts and exposes the persisted setting", () => {
expect(globalSettingsSchema.parse({ allowedMaxTokens: 50_000 })).toEqual({
allowedMaxTokens: 50_000,
})
expect(GLOBAL_SETTINGS_KEYS).toContain("allowedMaxTokens")
})

it("accepts nullish values for unset budget", () => {
expect(globalSettingsSchema.parse({ allowedMaxTokens: null })).toEqual({
allowedMaxTokens: null,
})
expect(globalSettingsSchema.parse({ allowedMaxTokens: undefined })).toEqual({
allowedMaxTokens: undefined,
})
})

it("rejects non-number values", () => {
expect(globalSettingsSchema.safeParse({ allowedMaxTokens: "50000" }).success).toBe(false)
})
})
6 changes: 6 additions & 0 deletions packages/types/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ describe("GLOBAL_STATE_KEYS", () => {
expect(GLOBAL_STATE_KEYS).toContain("autoApprovalEnabled")
})

it("should contain auto-approval limit keys", () => {
expect(GLOBAL_STATE_KEYS).toContain("allowedMaxRequests")
expect(GLOBAL_STATE_KEYS).toContain("allowedMaxCost")
expect(GLOBAL_STATE_KEYS).toContain("allowedMaxTokens")
})

it("should contain provider settings keys", () => {
expect(GLOBAL_STATE_KEYS).toContain("anthropicBaseUrl")
})
Expand Down
1 change: 1 addition & 0 deletions packages/types/src/global-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ export const globalSettingsSchema = z.object({
preventCompletionWithOpenTodos: z.boolean().optional(),
allowedMaxRequests: z.number().nullish(),
allowedMaxCost: z.number().nullish(),
allowedMaxTokens: z.number().nullish(),
autoCondenseContext: z.boolean().optional(),
autoCondenseContextPercent: z.number().optional(),

Expand Down
1 change: 1 addition & 0 deletions packages/types/src/vscode-extension-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ export type ExtensionState = Pick<
| "deniedCommands"
| "allowedMaxRequests"
| "allowedMaxCost"
| "allowedMaxTokens"
| "ttsEnabled"
| "ttsSpeed"
| "soundEnabled"
Expand Down
65 changes: 62 additions & 3 deletions src/core/auto-approval/AutoApprovalHandler.ts
Comment thread
juniorhillory-creator marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { GlobalState, ClineMessage, ClineAsk } from "@roo-code/types"

import { getApiMetrics } from "../../shared/getApiMetrics"
import { findLastIndex } from "../../shared/array"
import { ClineAskResponse } from "../../shared/WebviewMessage"

export interface AutoApprovalResult {
shouldProceed: boolean
requiresApproval: boolean
approvalType?: "requests" | "cost"
approvalType?: "requests" | "cost" | "tokens"
approvalCount?: number | string
}

export class AutoApprovalHandler {
private lastResetMessageIndex: number = 0
private consecutiveAutoApprovedRequestsCount: number = 0
private consecutiveAutoApprovedCost: number = 0
private consecutiveAutoApprovedTokens: number = 0

/**
* Check if auto-approval limits have been reached and handle user approval if needed
Expand All @@ -34,7 +36,13 @@ export class AutoApprovalHandler {

// Check cost limit
const costResult = await this.checkCostLimit(state, messages, askForApproval)
return costResult
if (!costResult.shouldProceed || costResult.requiresApproval) {
return costResult
}

// Check token limit (token circuit breaker)
const tokenResult = await this.checkTokenLimit(state, messages, askForApproval)
return tokenResult
}

/**
Expand Down Expand Up @@ -134,22 +142,73 @@ export class AutoApprovalHandler {
return { shouldProceed: true, requiresApproval: false }
}

/**
* Calculate current tokens and check if limit is exceeded (Token Circuit Breaker)
*/
private async checkTokenLimit(
state: GlobalState | undefined,
messages: ClineMessage[],
askForApproval: (
type: ClineAsk,
data: string,
) => Promise<{ response: ClineAskResponse; text?: string; images?: string[] }>,
): Promise<AutoApprovalResult> {
const maxTokens = state?.allowedMaxTokens || Infinity

// Calculate total tokens from messages after the last reset point
const messagesAfterReset = messages.slice(this.lastResetMessageIndex)
const metrics = getApiMetrics(messagesAfterReset)
this.consecutiveAutoApprovedTokens = (metrics.totalTokensIn || 0) + (metrics.totalTokensOut || 0)

if (this.consecutiveAutoApprovedTokens > maxTokens) {
const { response } = await askForApproval(
"auto_approval_max_req_reached",
JSON.stringify({ count: maxTokens.toLocaleString(), type: "tokens" }),
Comment thread
juniorhillory-creator marked this conversation as resolved.
Resolved
)

// If we get past the promise, it means the user approved and did not start a new task
if (response === "yesButtonClicked") {
// Reset tracking: exclude completed, approved usage but leave the current
// unfinished api_req_started entry in the next token window.
const lastApiReqIndex = findLastIndex(messages, (m) => m.say === "api_req_started")
this.lastResetMessageIndex = lastApiReqIndex !== -1 ? lastApiReqIndex : messages.length
return {
shouldProceed: true,
requiresApproval: true,
approvalType: "tokens",
approvalCount: maxTokens.toLocaleString(),
}
}

return {
shouldProceed: false,
requiresApproval: true,
approvalType: "tokens",
approvalCount: maxTokens.toLocaleString(),
}
}

return { shouldProceed: true, requiresApproval: false }
}

/**
* Reset the tracking (typically called when starting a new task)
*/
resetRequestCount(): void {
this.lastResetMessageIndex = 0
this.consecutiveAutoApprovedRequestsCount = 0
this.consecutiveAutoApprovedCost = 0
this.consecutiveAutoApprovedTokens = 0
}

/**
* Get current approval state for debugging/testing
*/
getApprovalState(): { requestCount: number; currentCost: number } {
getApprovalState(): { requestCount: number; currentCost: number; currentTokens: number } {
return {
requestCount: this.consecutiveAutoApprovedRequestsCount,
currentCost: this.consecutiveAutoApprovedCost,
currentTokens: this.consecutiveAutoApprovedTokens,
}
}
}
137 changes: 137 additions & 0 deletions src/core/auto-approval/__tests__/AutoApprovalHandler.spec.ts
Comment thread
juniorhillory-creator marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,143 @@ describe("AutoApprovalHandler", () => {
expect(result.requiresApproval).toBe(true)
expect(result.approvalType).toBe("requests")
})

it("should trigger token limit when tokens exceed allowedMaxTokens", async () => {
mockState.allowedMaxTokens = 50_000
const completedMessage: ClineMessage = { type: "say", say: "api_req_started", text: "{}", ts: 1000 }
const currentMessage: ClineMessage = { type: "say", say: "api_req_started", text: "{}", ts: 1500 }
const messages: ClineMessage[] = [completedMessage, currentMessage]

// Under token limit
mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 20_000, totalTokensOut: 10_000 })
let result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval)
expect(result.shouldProceed).toBe(true)
expect(result.requiresApproval).toBe(false)
expect(mockAskForApproval).not.toHaveBeenCalled()

// Exceeds token limit (40k in + 20k out = 60k > 50k)
mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 40_000, totalTokensOut: 20_000 })
mockAskForApproval.mockResolvedValue({ response: "yesButtonClicked" })
result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

expect(mockAskForApproval).toHaveBeenCalledWith(
"auto_approval_max_req_reached",
JSON.stringify({ count: (50_000).toLocaleString(), type: "tokens" }),
)
expect(result.shouldProceed).toBe(true)
expect(result.requiresApproval).toBe(true)
expect(result.approvalType).toBe("tokens")
Comment thread
juniorhillory-creator marked this conversation as resolved.
Resolved

// Subsequent check below new limit: verifies reset boundary excludes completedMessage and leaves currentMessage
mockAskForApproval.mockClear()
mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 15_000, totalTokensOut: 5_000 })
result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval)

expect(mockGetApiMetrics).toHaveBeenLastCalledWith([currentMessage])
expect(result.shouldProceed).toBe(true)
expect(result.requiresApproval).toBe(false)
expect(mockAskForApproval).not.toHaveBeenCalled()
Comment thread
juniorhillory-creator marked this conversation as resolved.
Resolved
})

it("leaves unfinished api_req_started in next token window after approval and counts increased usage", async () => {
mockState.allowedMaxTokens = 50_000
const completedMessage: ClineMessage = {
type: "say",
say: "api_req_started",
text: JSON.stringify({ tokensIn: 30_000, tokensOut: 25_000, cost: 0.1 }),
ts: 1000,
}
const unfinishedMessage: ClineMessage = {
type: "say",
say: "api_req_started",
text: JSON.stringify({ apiProtocol: "anthropic" }),
ts: 2000,
}
const messages: ClineMessage[] = [completedMessage, unfinishedMessage]

// Initial check: completed usage exceeds token limit (55k > 50k)
mockGetApiMetrics.mockReturnValue({ totalCost: 0.1, totalTokensIn: 30_000, totalTokensOut: 25_000 })
mockAskForApproval.mockResolvedValue({ response: "yesButtonClicked" })

const result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval)
expect(result.shouldProceed).toBe(true)
expect(result.requiresApproval).toBe(true)
expect(result.approvalType).toBe("tokens")

// After approval, the unfinished message's usage increases during execution
mockAskForApproval.mockClear()
mockGetApiMetrics.mockReturnValue({ totalCost: 0.05, totalTokensIn: 10_000, totalTokensOut: 5_000 })

const nextResult = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval)

// Verifies the slice excludes completedMessage and retains unfinishedMessage in the window
expect(mockGetApiMetrics).toHaveBeenLastCalledWith([unfinishedMessage])
expect(nextResult.shouldProceed).toBe(true)
expect(nextResult.requiresApproval).toBe(false)
expect(mockAskForApproval).not.toHaveBeenCalled()
})

it("should not proceed and not reset token window when user rejects token limit approval", async () => {
mockState.allowedMaxTokens = 50_000
const messages: ClineMessage[] = [{ type: "say", say: "api_req_started", text: "{}", ts: 1000 }]

// Exceeds token limit
mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 40_000, totalTokensOut: 20_000 })
mockAskForApproval.mockResolvedValue({ response: "noButtonClicked" })
const result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval)

expect(mockAskForApproval).toHaveBeenCalledWith(
"auto_approval_max_req_reached",
JSON.stringify({ count: (50_000).toLocaleString(), type: "tokens" }),
)
expect(result.shouldProceed).toBe(false)
expect(result.requiresApproval).toBe(true)
expect(result.approvalType).toBe("tokens")

// Repeat check with same usage: token window was not reset, so it prompts again
mockAskForApproval.mockClear()
mockAskForApproval.mockResolvedValue({ response: "noButtonClicked" })
const repeatResult = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval)

expect(mockAskForApproval).toHaveBeenCalledTimes(1)
expect(repeatResult.shouldProceed).toBe(false)
expect(repeatResult.requiresApproval).toBe(true)
expect(mockGetApiMetrics).toHaveBeenLastCalledWith(messages)
})

it("should trigger token limit using state constructed from provider state values", async () => {
const providerState = {
allowedMaxTokens: 50_000,
} as GlobalState
const messages: ClineMessage[] = [{ type: "say", say: "api_req_started", text: "{}", ts: 1000 }]

// When token limit is exceeded on state returned from provider
mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 40_000, totalTokensOut: 20_000 })
mockAskForApproval.mockResolvedValue({ response: "yesButtonClicked" })
const result = await handler.checkAutoApprovalLimits(providerState, messages, mockAskForApproval)

expect(mockAskForApproval).toHaveBeenCalledWith(
"auto_approval_max_req_reached",
JSON.stringify({ count: (50_000).toLocaleString(), type: "tokens" }),
)
expect(result.shouldProceed).toBe(true)
expect(result.requiresApproval).toBe(true)
expect(result.approvalType).toBe("tokens")
})

it("should fall back to Infinity when allowedMaxTokens is unset", async () => {
const unsetState = {
allowedMaxTokens: undefined,
} as GlobalState
const messages: ClineMessage[] = [{ type: "say", say: "api_req_started", text: "{}", ts: 1000 }]

mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 1_000_000, totalTokensOut: 1_000_000 })
const result = await handler.checkAutoApprovalLimits(unsetState, messages, mockAskForApproval)

expect(result.shouldProceed).toBe(true)
expect(result.requiresApproval).toBe(false)
expect(mockAskForApproval).not.toHaveBeenCalled()
})
})

describe("resetRequestCount", () => {
Expand Down
42 changes: 42 additions & 0 deletions src/core/task/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ export interface TaskOptions extends CreateTaskOptions {
enableCheckpoints?: boolean
checkpointTimeout?: number
consecutiveMistakeLimit?: number
tokenCircuitBreakerLimit?: number
task?: string
images?: string[]
historyItem?: HistoryItem
Expand Down Expand Up @@ -439,6 +440,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
private retiredApis = new Set<ApiHandler>()
private rateLimitClock: RateLimitClock
private autoApprovalHandler: AutoApprovalHandler
tokenCircuitBreakerLimit: number = 0

toolRepetitionDetector: ToolRepetitionDetector
rooIgnoreController?: RooIgnoreController
Expand Down Expand Up @@ -709,6 +711,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
enableCheckpoints = true,
checkpointTimeout = DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
consecutiveMistakeLimit = DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
tokenCircuitBreakerLimit = 0,
toolRepetitionSoftLimit = DEFAULT_TOOL_REPETITION_SOFT_LIMIT,
taskId,
task,
Expand Down Expand Up @@ -779,6 +782,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
this.api = buildApiHandler(this.apiConfiguration)
this.rateLimitClock = rateLimitClock ?? createRateLimitClock()
this.autoApprovalHandler = new AutoApprovalHandler()
this.tokenCircuitBreakerLimit = tokenCircuitBreakerLimit ?? 0

this.consecutiveMistakeLimit = consecutiveMistakeLimit ?? DEFAULT_CONSECUTIVE_MISTAKE_LIMIT
this.toolRepetitionSoftLimit = normalizeToolRepetitionSoftLimit(
Expand Down Expand Up @@ -4012,6 +4016,34 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
this.consecutiveMistakeCount = 0
}

// Token Circuit Breaker: Halt runaway loops if cumulative tokens exceed configured limit
if (this.tokenCircuitBreakerLimit > 0) {
const metrics = this.getTokenUsage()
const totalTokens = (metrics.totalTokensIn || 0) + (metrics.totalTokensOut || 0)
if (totalTokens >= this.tokenCircuitBreakerLimit) {
const { response, text } = await this.ask(
"mistake_limit_reached",
`Token circuit breaker tripped: cumulative token limit reached (${totalTokens.toLocaleString()} / ${this.tokenCircuitBreakerLimit.toLocaleString()} tokens). Please review and decide whether to proceed.`,
)

if (response === "yesButtonClicked" || response === "messageResponse") {
currentUserContent.push({
type: "text" as const,
text:
response === "messageResponse" && text
? `User approved exceeding token budget: ${text}`
: "User approved continuing beyond token circuit breaker limit.",
})
// Bump threshold to allow subsequent turns up to the next budget checkpoint
this.tokenCircuitBreakerLimit = totalTokens + this.tokenCircuitBreakerLimit
} else {
throw new Error(
`[TokenCircuitBreaker] Cumulative token limit of ${this.tokenCircuitBreakerLimit.toLocaleString()} tokens exceeded. Task paused.`,
)
}
}
}

// Getting verbose details is an expensive operation, it uses ripgrep to
// top-down build file structure of project which for large projects can
// take a few seconds. For the best UX we show a placeholder api_req_started
Expand Down Expand Up @@ -4185,6 +4217,16 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
cancelReason,
streamingFailedMessage,
} satisfies ClineApiReqInfo)

// Token Circuit Breaker: warn if turn tokens approach or exceed limit
if (this.tokenCircuitBreakerLimit > 0) {
const turnTokens = (costResult.totalInputTokens || 0) + (costResult.totalOutputTokens || 0)
if (turnTokens >= this.tokenCircuitBreakerLimit) {
console.warn(
`[TokenCircuitBreaker] Turn token consumption (${turnTokens.toLocaleString()}) reached or exceeded configured threshold (${this.tokenCircuitBreakerLimit.toLocaleString()}).`,
)
}
}
}

const abortStream = async (cancelReason: ClineApiReqCancelReason, streamingFailedMessage?: string) => {
Expand Down
Loading
Loading