Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 6 additions & 1 deletion packages/opencode/src/session/fallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ const ConfigSchema = Schema.Struct({
maxFallbackAttempts: NonNegativeInt,
maxUpstreamRetryAttempts: NonNegativeInt,
cooldownSeconds: NonNegativeInt,
// Opt-in, so a release carrying this stays inert until the coordinator asks for it.
fallbackOnRefusal: Schema.optional(Schema.Boolean),
})
export type Config = Schema.Schema.Type<typeof ConfigSchema>
const decode = Schema.decodeUnknownExit(Schema.fromJsonString(ConfigSchema))
Expand Down Expand Up @@ -111,12 +113,15 @@ export function route(model: ModelRef, now = Date.now()): ModelRef {
// a 200 stream, plus retryable errors with no status at all (connection
// resets, stream drops). Non-retryable statusless errors such as an invalid
// prompt or exhausted quota stay on the requested model. Context overflow and
// aborts are the caller's problem and never switch models.
// aborts are the caller's problem and never switch models. A provider's content
// filter is per model: a history one model refuses another will answer, and it
// keeps refusing it, so the cooldown is what holds later steps on the fallback.
function qualifies(error: Err): boolean {
const cfg = config()
if (!cfg) return false
if (SessionV1.ContextOverflowError.isInstance(error)) return false
if (SessionV1.AbortedError.isInstance(error)) return false
if (SessionV1.ContentFilterError.isInstance(error)) return cfg.fallbackOnRefusal === true
if (SessionV1.APIError.isInstance(error)) {
const status = error.data.statusCode
if (status === undefined) return error.data.isRetryable === true
Expand Down
2 changes: 2 additions & 0 deletions packages/opencode/src/session/message-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,8 @@ export function fromError(
).toObject()
case OutputLengthError.isInstance(e):
return e
case SessionV1.ContentFilterError.isInstance(e):
return e
case LoadAPIKeyError.isInstance(e):
return new AuthError(
{
Expand Down
20 changes: 19 additions & 1 deletion packages/opencode/src/session/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,9 @@ const layer = Layer.effect(
if (Option.isNone(resolved)) return undefined
ctx.model = resolved.value
ctx.fallbacks += 1
// A refused attempt finished its step. Left on the row, that finish would
// be read as this attempt's if it fails before finishing one of its own.
ctx.assistantMessage.finish = undefined
// Partial output the failed attempts wrote belongs to the previous model;
// left on this message it would be replayed as the fallback's own.
yield* Effect.forEach(
Expand Down Expand Up @@ -779,6 +782,19 @@ const layer = Layer.effect(
Stream.takeUntil(() => ctx.needsCompaction),
Stream.runDrain,
)
// A refusal ends the stream cleanly, so the retry policy never sees it.
// Failing here offers it to the fallback once the step's bookkeeping is
// done. Compaction keeps its own handling of a refused summary.
if (
ctx.assistantMessage.finish === "content-filter" &&
!ctx.assistantMessage.summary &&
SessionFallback.config()?.fallbackOnRefusal
)
return yield* Effect.fail(
new SessionV1.ContentFilterError({
message: "The response was blocked by the provider's content filter",
}).toObject(),
)
}).pipe(
Effect.onInterrupt(() =>
Effect.gen(function* () {
Expand Down Expand Up @@ -809,7 +825,9 @@ const layer = Layer.effect(
},
}),
),
Effect.catch(halt),
// A refusal no route answered is not a processor error: the loop reports
// it from the row's finish, as it does when the fallback is off.
Effect.catch((e) => (SessionV1.ContentFilterError.isInstance(e) ? Effect.void : halt(e))),
Effect.ensuring(cleanup()),
)

Expand Down
10 changes: 10 additions & 0 deletions packages/opencode/test/session/fallback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ describe("session.fallback recordFailure", () => {
expect(SessionFallback.recordFailure({ model: openrouter, error: unknown, swaps: 0 })).toEqual(anthropic)
})

test("switches on a content-filter refusal only when the config opts in", () => {
const refusal = new SessionV1.ContentFilterError({ message: "blocked" }).toObject()
useConfig(cfg)
expect(SessionFallback.recordFailure({ model: openrouter, error: refusal, swaps: 0 })).toBeUndefined()
expect(SessionFallback.isDegraded(openrouter)).toBe(false)
useConfig({ ...cfg, fallbackOnRefusal: true })
expect(SessionFallback.recordFailure({ model: openrouter, error: refusal, swaps: 0 })).toEqual(anthropic)
expect(SessionFallback.route(openrouter)).toEqual(anthropic)
})

test("ignores map values without a provider", () => {
useConfig({
...cfg,
Expand Down
204 changes: 204 additions & 0 deletions packages/opencode/test/session/processor-effect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,210 @@ it.live("session.processor effect tests keep the requested model on the row when
),
)

it.live("session.processor effect tests switch to the fallback model after a content-filter refusal", () =>
provideTmpdirServer(
({ dir, llm }) =>
Effect.gen(function* () {
useFallbackConfig({
fallbackModelsByModel: { "test/test-model": "fallback/fallback-model" },
fallbackOnErrors: [503],
maxFallbackAttempts: 1,
maxUpstreamRetryAttempts: 1,
cooldownSeconds: 60,
fallbackOnRefusal: true,
})
const { processors, session, provider } = yield* boot()

yield* llm.push(reply().text("partial").contentFilter())
yield* llm.text("hello")

const chat = yield* session.create({})
const parent = yield* user(chat.id, "hi")
const msg = yield* assistant(chat.id, parent.id, path.resolve(dir))
const mdl = yield* provider.getModel(ref.providerID, ref.modelID)
const handle = yield* processors.create({ assistantMessage: msg, sessionID: chat.id, model: mdl })

const value = yield* handle.process({
user: {
id: parent.id,
sessionID: chat.id,
role: "user",
time: parent.time,
agent: parent.agent,
model: { providerID: ref.providerID, modelID: ref.modelID },
} satisfies SessionV1.User,
sessionID: chat.id,
agent: agent(),
system: [],
messages: [{ role: "user", content: "hi" }],
convert: () => Effect.succeed([{ role: "user", content: "hi" }]),
tools: {},
})
const parts = yield* MessageV2.parts(msg.id)
const stored = yield* MessageV2.get({ sessionID: chat.id, messageID: msg.id })

expect(value).toBe("continue")
// No same-route retry: a refusal repeats, so the swap is immediate.
expect(yield* llm.calls).toBe(2)
expect(parts.filter((part) => part.type === "text").map((part) => part.type === "text" && part.text)).toEqual([
"hello",
])
expect(stored.info).toMatchObject({ providerID: "fallback", modelID: "fallback-model", finish: "stop" })
expect(stored.info.role === "assistant" ? stored.info.error : undefined).toBeUndefined()
expect(SessionFallback.isDegraded({ providerID: "test", modelID: "test-model" })).toBe(true)
}),
{ config: (url) => fallbackCfg(url) },
),
)

it.live("session.processor effect tests drop the refused finish when the fallback fails before finishing", () =>
provideTmpdirServer(
({ dir, llm }) =>
Effect.gen(function* () {
useFallbackConfig({
fallbackModelsByModel: { "test/test-model": "fallback/fallback-model" },
fallbackOnErrors: [503],
maxFallbackAttempts: 1,
maxUpstreamRetryAttempts: 0,
cooldownSeconds: 60,
fallbackOnRefusal: true,
})
const { processors, session, provider } = yield* boot()
yield* llm.push(reply().text("partial").contentFilter(), httpError(503, { error: { message: "down" } }))

const chat = yield* session.create({})
const parent = yield* user(chat.id, "hi")
const msg = yield* assistant(chat.id, parent.id, path.resolve(dir))
const mdl = yield* provider.getModel(ref.providerID, ref.modelID)
const handle = yield* processors.create({ assistantMessage: msg, sessionID: chat.id, model: mdl })

const value = yield* handle.process({
user: {
id: parent.id,
sessionID: chat.id,
role: "user",
time: parent.time,
agent: parent.agent,
model: { providerID: ref.providerID, modelID: ref.modelID },
} satisfies SessionV1.User,
sessionID: chat.id,
agent: agent(),
system: [],
messages: [{ role: "user", content: "hi" }],
convert: () => Effect.succeed([{ role: "user", content: "hi" }]),
tools: {},
})
const stored = yield* MessageV2.get({ sessionID: chat.id, messageID: msg.id })

expect(value).toBe("stop")
expect(yield* llm.calls).toBe(2)
expect(stored.info.role === "assistant" ? stored.info.error?.name : undefined).toBe("APIError")
expect(stored.info.role === "assistant" ? stored.info.finish : "unset").toBeUndefined()
}),
{ config: (url) => fallbackCfg(url) },
),
)

it.live("session.processor effect tests keep a refused step that already ran a tool", () =>
provideTmpdirServer(
({ dir, llm }) =>
Effect.gen(function* () {
useFallbackConfig({
fallbackModelsByModel: { "test/test-model": "fallback/fallback-model" },
fallbackOnErrors: [503],
maxFallbackAttempts: 1,
maxUpstreamRetryAttempts: 1,
cooldownSeconds: 60,
fallbackOnRefusal: true,
})
const { processors, session, provider } = yield* boot()
yield* llm.push(reply().tool("missing", {}).contentFilter())

const chat = yield* session.create({})
const parent = yield* user(chat.id, "hi")
const msg = yield* assistant(chat.id, parent.id, path.resolve(dir))
const mdl = yield* provider.getModel(ref.providerID, ref.modelID)
const handle = yield* processors.create({ assistantMessage: msg, sessionID: chat.id, model: mdl })

const value = yield* handle.process({
user: {
id: parent.id,
sessionID: chat.id,
role: "user",
time: parent.time,
agent: parent.agent,
model: { providerID: ref.providerID, modelID: ref.modelID },
} satisfies SessionV1.User,
sessionID: chat.id,
agent: agent(),
system: [],
messages: [{ role: "user", content: "hi" }],
convert: unconverted,
tools: {},
})
const parts = yield* MessageV2.parts(msg.id)
const stored = yield* MessageV2.get({ sessionID: chat.id, messageID: msg.id })

// Another model could run the tool again, so the step stays as the first model left it.
expect(value).toBe("continue")
expect(yield* llm.calls).toBe(1)
expect(parts.some((part) => part.type === "tool")).toBe(true)
expect(stored.info).toMatchObject({ providerID: "test", modelID: "test-model", finish: "content-filter" })
expect(stored.info.role === "assistant" ? stored.info.error : undefined).toBeUndefined()
}),
{ config: (url) => fallbackCfg(url) },
),
)

it.live("session.processor effect tests leave a refusal no route answered for the loop to report", () =>
provideTmpdirServer(
({ dir, llm }) =>
Effect.gen(function* () {
useFallbackConfig({
fallbackModelsByModel: { "test/test-model": "fallback/fallback-model" },
fallbackOnErrors: [503],
maxFallbackAttempts: 1,
maxUpstreamRetryAttempts: 1,
cooldownSeconds: 60,
fallbackOnRefusal: true,
})
const { processors, session, provider } = yield* boot()
yield* llm.push(reply().contentFilter(), reply().contentFilter())

const chat = yield* session.create({})
const parent = yield* user(chat.id, "hi")
const msg = yield* assistant(chat.id, parent.id, path.resolve(dir))
const mdl = yield* provider.getModel(ref.providerID, ref.modelID)
const handle = yield* processors.create({ assistantMessage: msg, sessionID: chat.id, model: mdl })

const value = yield* handle.process({
user: {
id: parent.id,
sessionID: chat.id,
role: "user",
time: parent.time,
agent: parent.agent,
model: { providerID: ref.providerID, modelID: ref.modelID },
} satisfies SessionV1.User,
sessionID: chat.id,
agent: agent(),
system: [],
messages: [{ role: "user", content: "hi" }],
convert: () => Effect.succeed([{ role: "user", content: "hi" }]),
tools: {},
})
const stored = yield* MessageV2.get({ sessionID: chat.id, messageID: msg.id })

// Same outcome as with the fallback off: the prompt loop turns the finish into the error.
expect(value).toBe("continue")
expect(yield* llm.calls).toBe(2)
expect(stored.info).toMatchObject({ providerID: "fallback", modelID: "fallback-model", finish: "content-filter" })
expect(stored.info.role === "assistant" ? stored.info.error : undefined).toBeUndefined()
}),
{ config: (url) => fallbackCfg(url) },
),
)

it.live("session.processor effect tests preserve text start time", () =>
provideTmpdirServer(
({ dir, llm }) =>
Expand Down
Loading
Loading