Skip to content

Commit 6417797

Browse files
committed
fix: bound denied tool call retries with cross-message doom loop detection
Reworks the previous attempt (b6c640b) after reproducing the actual bug from anomalyco#31108: with experimental.continue_loop_on_deny: true and a plugin that auto-rejects permission asks via the v1 SDK (e.g. kimaki subagent auto-reject), the model can retry the same denied tool call forever. Root cause: a denied tool call ends the provider step, so the model's retry always lands in a NEW assistant message. The doom loop guard only scanned parts of the current assistant message, so identical denied retries never accumulated and the guard never fired. Fix: - processor.ts: add a cross-message doom loop check. When the same-message scan does not match, look at the trailing tool parts across the session (MessageV2.lastParts, bounded window). If the last DOOM_LOOP_THRESHOLD tool parts are identical errored calls matching the incoming call, trigger the doom_loop permission ask. Only errored runs count, so routine successful repeats (e.g. periodic status checks) do not trip the guard. The part of the call being evaluated is excluded by messageID + callID since provider tool call IDs are only unique within a single response. - message-v2.ts: add lastParts(sessionID, limit) querying the most recent parts of a session via the part_session_idx index. Reverted from the previous attempt, with reasons: - tools.ts catchDefect converting permission defects to typed failures: a no-op. Effect v4 runPromise rejects with the squashed cause, which is the original error object for both Fail and Die, so error identity already survives Effect.orDie all the way to failToolCall. Verified by instrumentation. - processor.ts blocking on DeniedError/CorrectedError: behavior change that contradicts the original design (7368342). CorrectedError carries user feedback the model should act on; DeniedError is a static ruleset deny the model should adapt to. Both now documented in a comment. Tests (the previous test was vacuous: a blanket pattern "*" deny removes the tool from the tool list entirely via Permission.disabled, so no permission ask ever fired and it passed on unpatched upstream): - rejected permission continues loop when continue_loop_on_deny is true - rejected permission blocks loop by default - repeated identical rejected calls trigger doom loop guard across messages (fails without this fix: 7 LLM calls instead of 4) Fixes anomalyco#31108 Session: ses_15eee3980ffe5eK2RPweao3nyU
1 parent a6e5538 commit 6417797

4 files changed

Lines changed: 191 additions & 40 deletions

File tree

‎packages/opencode/src/session/message-v2.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -514,6 +514,28 @@ export function parts(messageID: MessageID) {
514514
})
515515
}
516516

517+
/**
518+
* Most recent parts of a session across all messages, oldest first. Part IDs
519+
* ascend globally within a session, so ordering by id is chronological.
520+
* Used by doom-loop detection, which must look across assistant messages:
521+
* a denied tool call ends the provider step, so the model's retry always
522+
* lands in a new assistant message and a per-message scan never sees it.
523+
*/
524+
export function lastParts(input: { sessionID: SessionID; limit: number }) {
525+
return Effect.gen(function* () {
526+
const { db } = yield* Database.Service
527+
const rows = yield* db
528+
.select()
529+
.from(PartTable)
530+
.where(eq(PartTable.session_id, input.sessionID))
531+
.orderBy(desc(PartTable.id))
532+
.limit(input.limit)
533+
.all()
534+
.pipe(Effect.orDie)
535+
return rows.map(part).reverse()
536+
})
537+
}
538+
517539
export const get = Effect.fn("MessageV2.get")(function* (input: { sessionID: SessionID; messageID: MessageID }) {
518540
const { db } = yield* Database.Service
519541
const row = yield* db

‎packages/opencode/src/session/processor.ts‎

Lines changed: 53 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -238,12 +238,14 @@ export const layer = Layer.effect(
238238
time: { start: match.part.state.time.start, end: Date.now() },
239239
},
240240
})
241-
if (
242-
error instanceof PermissionV1.RejectedError ||
243-
error instanceof PermissionV1.CorrectedError ||
244-
error instanceof PermissionV1.DeniedError ||
245-
error instanceof Question.RejectedError
246-
) {
241+
// Only explicit user rejections block the loop (subject to
242+
// experimental.continue_loop_on_deny). Static ruleset denies
243+
// (PermissionV1.DeniedError) and rejections with feedback
244+
// (PermissionV1.CorrectedError) intentionally do NOT block: the model
245+
// should see the error output and adapt or act on the feedback.
246+
// Note: error identity survives Effect.orDie here because runPromise
247+
// rejects with the squashed cause, which is the original error object.
248+
if (error instanceof PermissionV1.RejectedError || error instanceof Question.RejectedError) {
247249
ctx.blocked = ctx.shouldBreak
248250
}
249251
yield* settleToolCall(toolCallID)
@@ -525,19 +527,57 @@ export const layer = Layer.effect(
525527
Effect.provideService(Database.Service, database),
526528
)
527529
const recentParts = parts.slice(-DOOM_LOOP_THRESHOLD)
528-
529-
if (
530-
recentParts.length !== DOOM_LOOP_THRESHOLD ||
531-
!recentParts.every(
530+
const sameMessageLoop =
531+
recentParts.length === DOOM_LOOP_THRESHOLD &&
532+
recentParts.every(
532533
(part) =>
533534
part.type === "tool" &&
534535
part.tool === value.name &&
535536
part.state.status !== "pending" &&
536537
JSON.stringify(part.state.input) === JSON.stringify(input),
537538
)
538-
) {
539-
return
540-
}
539+
540+
// A denied or failed tool call ends the provider step, so the
541+
// model's retry lands in a NEW assistant message and the
542+
// per-message scan above never accumulates. Without this
543+
// cross-message check, continue_loop_on_deny: true plus an
544+
// auto-rejecting permission handler retries the same denied call
545+
// forever. Only errored runs count here so routine successful
546+
// repeats (e.g. periodic status checks) don't trip the guard.
547+
const failedRetryLoop = sameMessageLoop
548+
? false
549+
: yield* MessageV2.lastParts({
550+
sessionID: ctx.sessionID,
551+
// Bounded window: each retry message holds a handful of
552+
// parts (step-start, text, tool), so the trailing run of
553+
// identical denied calls sits well within this limit.
554+
limit: DOOM_LOOP_THRESHOLD * 8,
555+
}).pipe(
556+
Effect.provideService(Database.Service, database),
557+
Effect.map((all) => {
558+
// Exclude the part of the tool call being evaluated; it
559+
// was just written as "running" by updateToolCall above.
560+
// Match on messageID + callID because provider tool call
561+
// IDs are only unique within a single response.
562+
const tools = all.filter(
563+
(part): part is SessionV1.ToolPart =>
564+
part.type === "tool" &&
565+
!(part.messageID === ctx.assistantMessage.id && part.callID === value.id),
566+
)
567+
const recent = tools.slice(-DOOM_LOOP_THRESHOLD)
568+
return (
569+
recent.length === DOOM_LOOP_THRESHOLD &&
570+
recent.every(
571+
(part) =>
572+
part.tool === value.name &&
573+
part.state.status === "error" &&
574+
JSON.stringify(part.state.input) === JSON.stringify(input),
575+
)
576+
)
577+
}),
578+
)
579+
580+
if (!sameMessageLoop && !failedRetryLoop) return
541581

542582
const agent = yield* agents.get(ctx.assistantMessage.agent)
543583
yield* permission.ask({

‎packages/opencode/src/session/tools.ts‎

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import { Plugin } from "@/plugin"
1313
import type { TaskPromptOps } from "@/tool/task"
1414
import { type Tool as AITool, tool, jsonSchema, type ToolExecutionOptions, asSchema } from "ai"
1515
import { Effect } from "effect"
16-
import { PermissionV1 } from "@opencode-ai/core/v1/permission"
1716
import { MessageV2 } from "./message-v2"
1817
import { Session } from "./session"
1918
import { SessionProcessor } from "./processor"
@@ -90,11 +89,7 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: {
9089
{ tool: item.id, sessionID: ctx.sessionID, callID: ctx.callID },
9190
{ args },
9291
)
93-
const result = yield* item.execute(args, ctx).pipe(
94-
Effect.catchDefect((defect) =>
95-
isPermissionError(defect) ? Effect.fail(defect as Error) : Effect.die(defect),
96-
),
97-
)
92+
const result = yield* item.execute(args, ctx)
9893
const output = {
9994
...result,
10095
attachments: result.attachments?.map((attachment) => ({
@@ -209,12 +204,4 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: {
209204
return tools
210205
})
211206

212-
function isPermissionError(defect: unknown): defect is PermissionV1.RejectedError | PermissionV1.CorrectedError | PermissionV1.DeniedError {
213-
return (
214-
defect instanceof PermissionV1.RejectedError ||
215-
defect instanceof PermissionV1.CorrectedError ||
216-
defect instanceof PermissionV1.DeniedError
217-
)
218-
}
219-
220207
export * as SessionTools from "./tools"

‎packages/opencode/test/session/prompt.test.ts‎

Lines changed: 115 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { NodeFileSystem } from "@effect/platform-node"
22
import { ConfigV1 } from "@opencode-ai/core/v1/config/config"
3+
import { PermissionV1 } from "@opencode-ai/core/v1/permission"
34
import { SessionV1 } from "@opencode-ai/core/v1/session"
45
import { Database } from "@opencode-ai/core/database/database"
56
import { eq } from "drizzle-orm"
@@ -2279,44 +2280,145 @@ noLLMServer.instance(
22792280
30_000,
22802281
)
22812282

2283+
// Permission deny / reject loop semantics
2284+
//
2285+
// A permission ask inside a tool's execute fails the tool call; the error
2286+
// reaches SessionProcessor.failToolCall with its identity intact (Effect.orDie
2287+
// does not destroy it: runPromise rejects with the squashed cause, the original
2288+
// error object). Only explicit user rejections (PermissionV1.RejectedError)
2289+
// block the loop, subject to experimental.continue_loop_on_deny.
2290+
//
2291+
// autoRejectAsks mimics a plugin using the v1 SDK that rejects every
2292+
// permission ask as soon as it is published (e.g. subagent auto-reject).
2293+
const autoRejectAsks = Effect.fn("test.autoRejectAsks")(function* () {
2294+
const events = yield* EventV2Bridge.Service
2295+
const permission = yield* Permission.Service
2296+
const off = yield* events.listen((event) =>
2297+
Effect.gen(function* () {
2298+
if (event.type !== Permission.Event.Asked.type) return
2299+
const req = event.data as { id: PermissionV1.ID }
2300+
yield* permission.reply({ requestID: req.id, reply: "reject" })
2301+
}).pipe(Effect.ignore),
2302+
)
2303+
yield* Effect.addFinalizer(() => off)
2304+
})
2305+
22822306
unix(
2283-
"denied tool permission does not crash and loop continues with continue_loop_on_deny",
2307+
"rejected permission continues loop when continue_loop_on_deny is true",
22842308
() =>
22852309
withSh(() =>
22862310
Effect.gen(function* () {
22872311
const { llm, dir } = yield* useServerConfig((url) => ({
22882312
...providerCfg(url),
22892313
experimental: { continue_loop_on_deny: true },
22902314
}))
2315+
yield* autoRejectAsks()
22912316
const prompt = yield* SessionPrompt.Service
22922317
const sessions = yield* Session.Service
22932318
const session = yield* sessions.create({
2294-
title: "PermDenyContinue",
2295-
permission: [{ permission: "bash", pattern: "*", action: "deny" }],
2319+
title: "RejectContinue",
2320+
permission: [{ permission: "bash", pattern: "*", action: "ask" }],
22962321
})
2297-
22982322
yield* prompt.prompt({
22992323
sessionID: session.id,
23002324
agent: "build",
23012325
noReply: true,
23022326
parts: [{ type: "text", text: "run a command" }],
23032327
})
2304-
2305-
yield* llm.tool("bash", { command: "echo denied", workdir: dir, description: "Echo denied" })
2328+
yield* llm.tool("bash", { command: "rm -rf /tmp/reject-continue", workdir: dir, description: "Remove dir" })
23062329
yield* llm.text("understood, command is restricted")
23072330

23082331
const result = yield* prompt.loop({ sessionID: session.id })
23092332
expect(result.info.role).toBe("assistant")
23102333
expect(yield* llm.calls).toBe(2)
23112334

23122335
const msgs = yield* MessageV2.filterCompactedEffect(session.id)
2313-
const assistantParts = msgs.flatMap((m) => m.parts)
2314-
expect(
2315-
assistantParts.some(
2316-
(p) => p.type === "text" && p.text === "understood, command is restricted",
2317-
),
2318-
).toBe(true)
2336+
const parts = msgs.flatMap((m) => m.parts)
2337+
const tool = parts.find((p): p is SessionV1.ToolPart => p.type === "tool")
2338+
expect(tool?.state.status).toBe("error")
2339+
if (tool?.state.status === "error") expect(tool.state.error).toContain("rejected permission")
2340+
expect(parts.some((p) => p.type === "text" && p.text === "understood, command is restricted")).toBe(true)
23192341
}),
23202342
),
2321-
10_000,
2343+
15_000,
2344+
)
2345+
2346+
unix(
2347+
"rejected permission blocks loop by default",
2348+
() =>
2349+
withSh(() =>
2350+
Effect.gen(function* () {
2351+
const { llm, dir } = yield* useServerConfig((url) => ({
2352+
...providerCfg(url),
2353+
experimental: { continue_loop_on_deny: false },
2354+
}))
2355+
yield* autoRejectAsks()
2356+
const prompt = yield* SessionPrompt.Service
2357+
const sessions = yield* Session.Service
2358+
const session = yield* sessions.create({
2359+
title: "RejectStop",
2360+
permission: [{ permission: "bash", pattern: "*", action: "ask" }],
2361+
})
2362+
yield* prompt.prompt({
2363+
sessionID: session.id,
2364+
agent: "build",
2365+
noReply: true,
2366+
parts: [{ type: "text", text: "run a command" }],
2367+
})
2368+
yield* llm.tool("bash", { command: "rm -rf /tmp/reject-stop", workdir: dir, description: "Remove dir" })
2369+
yield* llm.text("should never be requested")
2370+
2371+
const result = yield* prompt.loop({ sessionID: session.id })
2372+
expect(result.info.role).toBe("assistant")
2373+
if (result.info.role === "assistant") expect(result.info.finish).toBe("tool-calls")
2374+
expect(yield* llm.calls).toBe(1)
2375+
}),
2376+
),
2377+
15_000,
2378+
)
2379+
2380+
unix(
2381+
"repeated identical rejected calls trigger doom loop guard across messages",
2382+
() =>
2383+
withSh(() =>
2384+
Effect.gen(function* () {
2385+
// With continue_loop_on_deny: true and an auto-rejecting permission
2386+
// handler, every rejection lands the retry in a NEW assistant message,
2387+
// so the per-message doom loop scan never accumulated and the model
2388+
// could ping-pong against the same denied call forever. The
2389+
// cross-message guard asks doom_loop permission on the fourth
2390+
// identical attempt; the auto-rejecting handler rejects that too,
2391+
// which ends the loop instead of letting it run unbounded.
2392+
const { llm, dir } = yield* useServerConfig((url) => ({
2393+
...providerCfg(url),
2394+
experimental: { continue_loop_on_deny: true },
2395+
}))
2396+
yield* autoRejectAsks()
2397+
const prompt = yield* SessionPrompt.Service
2398+
const sessions = yield* Session.Service
2399+
const session = yield* sessions.create({
2400+
title: "DoomLoop",
2401+
permission: [{ permission: "bash", pattern: "*", action: "ask" }],
2402+
})
2403+
yield* prompt.prompt({
2404+
sessionID: session.id,
2405+
agent: "build",
2406+
noReply: true,
2407+
parts: [{ type: "text", text: "run a command" }],
2408+
})
2409+
const call = { command: "rm -rf /tmp/doom-loop", workdir: dir, description: "Remove dir" }
2410+
for (let i = 0; i < 6; i++) yield* llm.tool("bash", call)
2411+
yield* llm.text("gave up")
2412+
2413+
const result = yield* prompt.loop({ sessionID: session.id })
2414+
expect(result.info.role).toBe("assistant")
2415+
// 3 rejected attempts; the 4th triggers the doom_loop ask, whose
2416+
// rejection errors the turn instead of looping through all 6 pushes.
2417+
expect(yield* llm.calls).toBe(4)
2418+
if (result.info.role === "assistant") {
2419+
expect(JSON.stringify(result.info.error)).toContain("rejected permission")
2420+
}
2421+
}),
2422+
),
2423+
20_000,
23222424
)

0 commit comments

Comments
 (0)