Skip to content

feat(agents): derive fallbacks from configured model catalog - #60922

Closed
08820048 wants to merge 2 commits into
openclaw:mainfrom
08820048:codex/model-catalog-fallbacks
Closed

08820048 wants to merge 2 commits into
openclaw:mainfrom
08820048:codex/model-catalog-fallbacks

Conversation

@08820048

@08820048 08820048 commented Apr 4, 2026

Copy link
Copy Markdown

Summary

  • Problem: OpenClaw only derives failover candidates from agents.defaults.model.fallbacks, so operators who keep multiple models in agents.defaults.models still have to duplicate that ordered list manually.
  • Why it matters: if the configured primary becomes unavailable, the runtime stops at the primary unless the same catalog is copied into fallbacks, which is easy to miss and easy to drift.
  • What changed: added an explicit opt-in agents.defaults.model.fallbacksFromModels: true that derives fallback candidates from agents.defaults.models in config order when explicit fallbacks are omitted.
  • What did NOT change (scope boundary): this PR does not change existing fallback error classification, auth-profile rotation behavior, or the meaning of explicit fallbacks / fallbacks: [].

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: the fallback resolver only consulted explicit fallback arrays (fallbacksOverride or agents.defaults.model.fallbacks). agents.defaults.models remained allowlist/catalog-only, so keeping multiple configured models there did not influence failover.
  • Missing detection / guardrail: there was no opt-in config path that said “use my configured model catalog as the fallback pool when I omit explicit fallbacks.”
  • Contributing context (if known): operators often keep a single ordered model catalog in agents.defaults.models, so the duplication requirement was easy to miss.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/agents/model-fallback.test.ts
  • Scenario the test should lock in: derive failover candidates from agents.defaults.models only when fallbacksFromModels: true, keep explicit fallbacks precedence, and keep fallbacks: [] as an intentional disable.
  • Why this is the smallest reliable guardrail: the behavior is isolated to fallback candidate construction before provider execution.
  • Existing test that already covers this (if any): existing runWithModelFallback unit coverage already covers explicit fallback ordering and allowlist behavior.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

  • New opt-in config: agents.defaults.model.fallbacksFromModels: true
  • When enabled and explicit fallbacks are omitted, OpenClaw derives fallback candidates from agents.defaults.models in config order, excluding the configured primary.
  • Explicit fallbacks still win, and fallbacks: [] still disables fallback.

Diagram (if applicable)

Before:
[primary model fails] -> [check explicit fallbacks only] -> [stop if none configured]

After:
[primary model fails] -> [explicit fallbacks?]
                    -> [if none + fallbacksFromModels=true, derive from models catalog]
                    -> [try next configured model]

Security Impact (required)

  • New permissions/capabilities? (No)
  • Secrets/tokens handling changed? (No)
  • New/changed network calls? (No)
  • Command/tool execution surface changed? (No)
  • Data access scope changed? (No)
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: Node 22 / pnpm workspace
  • Model/provider: fallback candidate construction only (no provider-specific network dependency)
  • Integration/channel (if any): N/A
  • Relevant config (redacted): agents.defaults.model.primary, agents.defaults.model.fallbacksFromModels, agents.defaults.models

Steps

  1. Configure a primary model plus multiple entries in agents.defaults.models.
  2. Enable agents.defaults.model.fallbacksFromModels: true without setting explicit fallbacks.
  3. Trigger a failover-worthy primary error.

Expected

  • The next configured model from agents.defaults.models is attempted.

Actual

  • Before this PR, the run stopped at the primary unless the fallback list was duplicated manually.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

  • Verified scenarios:
    • new unit coverage for catalog-derived fallback
    • explicit fallbacks still override catalog derivation
    • explicit fallbacks: [] still disables fallback
    • config schema + baseline regeneration
  • Edge cases checked:
    • configured primary is excluded from derived catalog fallbacks
    • duplicate catalog keys are deduped before candidate construction
  • What you did not verify:
    • full repository build / check green, because latest main is already red on unrelated skills/SourceInfo and provider-transport-fetch issues
    • full src/agents/model-fallback.test.ts run without unrelated unhandled plugin-registration/import noise on current main

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (Yes)
  • Migration needed? (No)
  • If yes, exact upgrade steps:

Risks and Mitigations

  • Risk: operators may assume the models catalog now always implies fallback.
    • Mitigation: the behavior is explicit opt-in (fallbacksFromModels: true) and docs clarify that explicit fallbacks still take precedence.
  • Risk: derived catalog order may surprise users if they keep a broad manual allowlist.
    • Mitigation: opt-in only, preserves config order, and fallbacks: [] remains the escape hatch to disable fallback.

Validation notes

  • pnpm exec vitest run src/agents/model-fallback.test.ts -t 'derives fallbacks from configured models when enabled|prefers explicit fallbacks over configured model derivation|treats explicit empty fallbacks as disabling configured model derivation'
    • 3 targeted tests passed
    • current main still emits unrelated unhandled plugin registration/import errors during this file
  • pnpm exec vitest run src/config/schema.base.generated.test.ts
    • passed (2 files / 6 tests)
  • pnpm build
    • fails on existing upstream errors in src/agents/provider-transport-fetch.ts, src/agents/skills/local-loader.ts, src/agents/skills/skill-contract.ts
  • pnpm check
    • fails on the same existing upstream skills/SourceInfo errors

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: S labels Apr 4, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4203909c6c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +393 to +397
const configuredFallbacks = hasAgentModelFallbacksField(configuredModel)
? resolveAgentModelFallbackValues(configuredModel)
: resolveAgentModelFallbacksFromModelsValue(configuredModel)
? resolveCatalogFallbacks()
: [];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep fallbackConfigured in sync with catalog fallbacks

This new branch derives fallback candidates when fallbacksFromModels is enabled, but the embedded runner still decides whether model failover is enabled via hasConfiguredModelFallbacks (src/agents/agent-scope.ts:245-252), which only looks at explicit fallbacks arrays. resolveRunFailoverDecision then gates fallback_model on that stale flag (src/agents/pi-embedded-runner/run/failover-policy.ts:109-153), so assistant/retry-limit failures can be surfaced instead of escalating to the next derived catalog candidate. In practice, users who enable fallbacksFromModels can still get stuck on the primary model in common rate-limit/overload scenarios.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds an opt-in agents.defaults.model.fallbacksFromModels: true flag that derives model fallback candidates from the agents.defaults.models catalog instead of requiring a manually-maintained fallbacks list. The core implementation in resolveFallbackCandidates is sound — deduplication, cross-provider filtering, and explicit-fallback/empty-fallback precedence all behave correctly, and the three new unit tests cover the key behavioral contracts.

Key issues found:

  • applyPrimaryModel silently drops fallbacksFromModels (src/plugins/provider-model-primary.ts): This function reconstructs the model config object with only fallbacks and primary, dropping the new field on every wizard/onboarding/model-picker model update. This is a data-loss regression for users who configure fallbacksFromModels: true and later change their primary model through the UI. applyAgentDefaultPrimaryModel in the same file is unaffected (it uses object spread). The fix is to spread the existing model config in applyPrimaryModel the same way applyAgentDefaultPrimaryModel already does.

  • fallbacksFromModels in AgentModelConfig is silently ineffective on non-default model types: The field is declared on AgentModelConfig which is shared by imageModel, pdfModel, and subagents.model, but the runtime only reads it for agents.defaults.model. Setting it on other positions is accepted by the schema but has no effect, creating a misleading type surface.

Confidence Score: 2/5

Not safe to merge as-is — applyPrimaryModel will silently drop the new fallbacksFromModels flag during onboarding and model-picker flows, which is a data-loss regression against the advertised feature.

The core fallback derivation logic is correct and well-tested. However, applyPrimaryModel (called from wizard, onboarding, configure, and provider auth flows) reconstructs the model config preserving only fallbacks and primary, so any fallbacksFromModels: true setting is silently lost whenever the primary model is changed through those flows. Fixing applyPrimaryModel to spread the existing model config (as applyAgentDefaultPrimaryModel already does) would close this gap.

src/plugins/provider-model-primary.ts — the applyPrimaryModel function needs to preserve fallbacksFromModels (and any future model-config fields) by spreading the existing object config rather than selectively preserving only fallbacks.

Comments Outside Diff (2)

  1. src/plugins/provider-model-primary.ts, line 51-63 (link)

    P1 fallbacksFromModels silently dropped by applyPrimaryModel

    applyPrimaryModel reconstructs the model config from scratch, preserving only the fallbacks field. The new fallbacksFromModels: true flag is silently dropped every time this function is called — during wizard/setup.ts, commands/onboard-custom.ts, commands/configure.gateway-auth.ts, and plugins/provider-api-key-auth.ts flows.

    Concretely: a user who sets agents.defaults.model.fallbacksFromModels: true and then changes their primary model through onboarding or the model picker will lose that setting silently.

    applyAgentDefaultPrimaryModel doesn't have this problem because it spreads the existing model object (...params.cfg.agents.defaults.model). The applyPrimaryModel function needs the same treatment:

    model:
      typeof existingModel === "object" && existingModel !== null
        ? { ...existingModel, primary: model }
        : { primary: model },

    The models catalog update at the end of applyPrimaryModel would also need to stay, but the model config construction should preserve all existing fields.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/plugins/provider-model-primary.ts
    Line: 51-63
    
    Comment:
    **`fallbacksFromModels` silently dropped by `applyPrimaryModel`**
    
    `applyPrimaryModel` reconstructs the model config from scratch, preserving only the `fallbacks` field. The new `fallbacksFromModels: true` flag is silently dropped every time this function is called — during `wizard/setup.ts`, `commands/onboard-custom.ts`, `commands/configure.gateway-auth.ts`, and `plugins/provider-api-key-auth.ts` flows.
    
    Concretely: a user who sets `agents.defaults.model.fallbacksFromModels: true` and then changes their primary model through onboarding or the model picker will lose that setting silently.
    
    `applyAgentDefaultPrimaryModel` doesn't have this problem because it spreads the existing model object (`...params.cfg.agents.defaults.model`). The `applyPrimaryModel` function needs the same treatment:
    
    ```ts
    model:
      typeof existingModel === "object" && existingModel !== null
        ? { ...existingModel, primary: model }
        : { primary: model },
    ```
    
    The `models` catalog update at the end of `applyPrimaryModel` would also need to stay, but the model config construction should preserve all existing fields.
    
    How can I resolve this? If you propose a fix, please make it concise.
  2. src/config/types.agents-shared.ts, line 8-20 (link)

    P2 fallbacksFromModels declared on shared AgentModelConfig but only effective for agents.defaults.model

    AgentModelConfig is the shared type used for agents.defaults.model, agents.defaults.imageModel, agents.defaults.pdfModel, and agents.defaults.subagents.model. The fallbacksFromModels field is only consulted in resolveFallbackCandidates, which reads exclusively from params.cfg?.agents?.defaults?.model. Setting fallbacksFromModels: true on imageModel, pdfModel, or subagents.model would be silently ignored since resolveImageFallbackCandidates only calls resolveAgentModelFallbackValues (not resolveAgentModelFallbacksFromModelsValue).

    Consider either:

    • Narrowing the type so fallbacksFromModels only appears on the type used for the default text model (not all AgentModelConfig usages), or
    • Adding a clarifying doc-comment noting the field is only supported at agents.defaults.model, or
    • Extending resolveImageFallbackCandidates to support it too.

    As-is, users who set this field on other model types will get no error but also no effect.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/config/types.agents-shared.ts
    Line: 8-20
    
    Comment:
    **`fallbacksFromModels` declared on shared `AgentModelConfig` but only effective for `agents.defaults.model`**
    
    `AgentModelConfig` is the shared type used for `agents.defaults.model`, `agents.defaults.imageModel`, `agents.defaults.pdfModel`, and `agents.defaults.subagents.model`. The `fallbacksFromModels` field is only consulted in `resolveFallbackCandidates`, which reads exclusively from `params.cfg?.agents?.defaults?.model`. Setting `fallbacksFromModels: true` on `imageModel`, `pdfModel`, or `subagents.model` would be silently ignored since `resolveImageFallbackCandidates` only calls `resolveAgentModelFallbackValues` (not `resolveAgentModelFallbacksFromModelsValue`).
    
    Consider either:
    - Narrowing the type so `fallbacksFromModels` only appears on the type used for the default text model (not all `AgentModelConfig` usages), or
    - Adding a clarifying doc-comment noting the field is only supported at `agents.defaults.model`, or
    - Extending `resolveImageFallbackCandidates` to support it too.
    
    As-is, users who set this field on other model types will get no error but also no effect.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/plugins/provider-model-primary.ts
Line: 51-63

Comment:
**`fallbacksFromModels` silently dropped by `applyPrimaryModel`**

`applyPrimaryModel` reconstructs the model config from scratch, preserving only the `fallbacks` field. The new `fallbacksFromModels: true` flag is silently dropped every time this function is called — during `wizard/setup.ts`, `commands/onboard-custom.ts`, `commands/configure.gateway-auth.ts`, and `plugins/provider-api-key-auth.ts` flows.

Concretely: a user who sets `agents.defaults.model.fallbacksFromModels: true` and then changes their primary model through onboarding or the model picker will lose that setting silently.

`applyAgentDefaultPrimaryModel` doesn't have this problem because it spreads the existing model object (`...params.cfg.agents.defaults.model`). The `applyPrimaryModel` function needs the same treatment:

```ts
model:
  typeof existingModel === "object" && existingModel !== null
    ? { ...existingModel, primary: model }
    : { primary: model },
```

The `models` catalog update at the end of `applyPrimaryModel` would also need to stay, but the model config construction should preserve all existing fields.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/config/types.agents-shared.ts
Line: 8-20

Comment:
**`fallbacksFromModels` declared on shared `AgentModelConfig` but only effective for `agents.defaults.model`**

`AgentModelConfig` is the shared type used for `agents.defaults.model`, `agents.defaults.imageModel`, `agents.defaults.pdfModel`, and `agents.defaults.subagents.model`. The `fallbacksFromModels` field is only consulted in `resolveFallbackCandidates`, which reads exclusively from `params.cfg?.agents?.defaults?.model`. Setting `fallbacksFromModels: true` on `imageModel`, `pdfModel`, or `subagents.model` would be silently ignored since `resolveImageFallbackCandidates` only calls `resolveAgentModelFallbackValues` (not `resolveAgentModelFallbacksFromModelsValue`).

Consider either:
- Narrowing the type so `fallbacksFromModels` only appears on the type used for the default text model (not all `AgentModelConfig` usages), or
- Adding a clarifying doc-comment noting the field is only supported at `agents.defaults.model`, or
- Extending `resolveImageFallbackCandidates` to support it too.

As-is, users who set this field on other model types will get no error but also no effect.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "Agents: derive fallbacks from model cata..." | Re-trigger Greptile

@vincentkoc vincentkoc added the triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup. label Apr 26, 2026
@clawsweeper

clawsweeper Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the contribution. This PR still needs the requested real-behavior proof, and the branch has been idle since that ask.

Close this stalled external feature PR: it has had no head commit since April 5, 2026, has been awaiting real-behavior proof since May 19, 2026, and remains dirty while a concrete embedded-runner failover gap is unresolved.

So I’m closing this for now to keep the review queue honest. Please reopen or open a fresh PR with real-behavior proof (a live run, logs, or a reproducible validation transcript) and it will be reviewed again.

Review details

Best possible solution:

If maintainers want catalog-derived fallbacks, restart from current main with one clearly owned configuration contract, synchronize the embedded-runner failover gate with the resolver, and prove an actual failover across configured providers before reconsidering the feature.

Do we have a high-confidence way to reproduce the issue?

No high-confidence live reproduction is provided. The source and recorded review make the candidate-resolution path clear, but the PR contains only unit-test claims rather than a current runtime failover trace.

Is this the best way to solve the issue?

No. The requested opt-in can be a reasonable direction, but this branch does not synchronize the embedded-runner failover decision and lacks current-main real behavior proof for the changed provider-selection path.

Security review:

Security review cleared: The diff adds configuration parsing and fallback selection only; no new secret handling, network execution, dependency, workflow, or supply-chain surface is evident.

AGENTS.md: unclear because the file could not be read completely.

What I checked:

  • Stalled proof gate: The PR is external, opened April 4, 2026, and carries both status: 📣 needs proof and triage: needs-real-behavior-proof; the proof-request label was applied May 19, 2026, leaving well over the required 14-day response window. (2793aa2b9dc3)
  • Inactive and conflicted head: The latest head commit is April 5, 2026, while GitHub reports the current branch as dirty and not mergeable; the July 18 update is a stale/proof automation event rather than contributor branch activity. (2793aa2b9dc3)
  • Proof is mock-only: The PR body reports targeted Vitest results, but contains no inspected after-fix live run, runtime log, recording, terminal artifact, or other real behavior proof for cross-provider failover. (src/agents/model-fallback.test.ts:920, 2793aa2b9dc3)
  • Unresolved failover gate: The recorded review identifies that the new fallback-candidate resolver does not update the embedded runner's hasConfiguredModelFallbacks gate, so derived catalog candidates can remain unreachable for common retry-limit and assistant failures. (src/agents/model-fallback.ts:396, 2793aa2b9dc3)

Likely related people:

  • vincentkoc: Appears in the PR timeline applying the triage: dirty-candidate label; the available review evidence does not establish a stronger current-main code owner for this stale branch. (role: triage contributor; confidence: low; files: src/agents/model-fallback.ts, src/agents/agent-scope.ts, src/agents/pi-embedded-runner/run/failover-policy.ts)

Codex review notes: model internal, reasoning high; reviewed against faf3dbdda833.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels May 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 19, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 10, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 16, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 17, 2026
@clawsweeper clawsweeper Bot removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 2, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jul 2, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 2, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this Jul 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: derive model fallback candidates from agents.defaults.models

2 participants