Skip to content

fix(auth): cooldown inline api key billing failures - #88709

Merged
Patrick-Erichsen merged 23 commits into
openclaw:mainfrom
MertBasar0:fix/inline-api-key-billing-cooldown
Aug 4, 2026
Merged

Patrick-Erichsen merged 23 commits into
openclaw:mainfrom
MertBasar0:fix/inline-api-key-billing-cooldown

Conversation

@MertBasar0

@MertBasar0 MertBasar0 commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • record provider-level cooldown state for inline models.providers.<id>.apiKey credentials
  • block literal, env-marker, and env SecretRef inline API keys while provider-level auth/billing cooldown is active
  • keep healthy stored auth profiles available as fallback when an inline provider key is cooling down
  • preserve inline provider cooldown usage state across auth-store load/merge pruning

Closes #39807.

Real behavior proof

  • Behavior addressed: Inline provider API keys without auth profiles record billing/auth failures under a provider-level usage id (inline-api-key:<provider>), fail closed while that cooldown is active, stay hidden from model browsing and model-backed tool auth during it, keep healthy stored profiles usable as fallback, and become usable again once the window expires.
  • Real environment tested: Local Linux (WSL) checkout, branch merged with current upstream/main, branch head 80595c9ae7a.
  • Exact steps or command run after this patch:
    • Live driver against the real production modules (no vitest, no mocks), run with an isolated home so the real state DB is untouched:
      HOME=$(mktemp -d) OPENCLAW_HOME=$HOME/.openclaw node --import tsx proof.ts — the driver builds a throwaway agent dir plus a config carrying an inline models.providers.proofprov.apiKey, then calls resolveApiKeyForProvider, markInlineProviderApiKeyFailure, hasRuntimeAvailableProviderAuth and hasAvailableAuthForProvider directly.
    • node node_modules/.bin/vitest run over the auth, browse, tool, command and failover suites (844 tests).
    • pnpm check:test-types
    • node scripts/run-tsgo.mjs -p tsconfig.core.json
    • ./node_modules/.bin/oxfmt --check on the touched files.
  • Evidence after fix: Terminal output at head 80595c9ae7a (keys are placeholders by construction):
    provider: proofprov (inline models.providers.proofprov.apiKey)
    
    STEP 1 — baseline: inline key resolves, provider is available
      resolve      : RESOLVED apiKey=sk-inline-REDACTED source=models.json mode=api-key
      availability : hasRuntimeAvailableProviderAuth=true  hasAvailableAuthForProvider=true
      cooldown row : <none>
    
    STEP 2 — provider returns a billing failure (402): runner marks the inline key
    [agent/embedded] auth profile failure state updated: runId=run:proof profile=sha256:e79e0f18561f provider=proofprov reason=billing window=disabled reused=false
      cooldown row : disabledReason=billing window=active, 300min left errorCount=1
    
    STEP 3 — active cooldown: resolution fails closed, browse/tool auth hide the key
      resolve      : BLOCKED  Inline API key for provider "proofprov" is temporarily disabled after a provider auth/billing failure. Retry after about 300 minutes, or switch to a different auth profile/API key.
      availability : hasRuntimeAvailableProviderAuth=false  hasAvailableAuthForProvider=false
    
    STEP 4 — stored-profile fallback while the inline key is still cooling
      resolve      : RESOLVED apiKey=sk-profile-REDACTED source=profile:proofprov:backup mode=api-key
      availability : hasRuntimeAvailableProviderAuth=false  hasAvailableAuthForProvider=true
      cooldown row : disabledReason=billing window=active, 300min left errorCount=1
    
    STEP 5 — recovery scope: cooldown expiry restores the inline key
      cooldown row : disabledReason=billing window=expired 1min ago errorCount=1
      resolve      : RESOLVED apiKey=sk-inline-REDACTED source=models.json mode=api-key
      availability : hasRuntimeAvailableProviderAuth=true  hasAvailableAuthForProvider=true
    
  • Observed result after fix: The production auth store persisted the inline cooldown under inline-api-key:proofprov with disabledReason=billing and a 5h window; model auth then failed closed on reuse with the temporary-disabled message, and both browse (hasRuntimeAvailableProviderAuth) and model auth (hasAvailableAuthForProvider) reported the provider unavailable. Adding a healthy stored profile restored resolution through profile:proofprov:backup while the inline key stayed cooled and stayed hidden from browse. After the window lapsed, the inline key resolved again and availability returned.
  • Recovery scope (open policy question): Recovery is expiry-only today. Stored profiles clear their cooldown on success (markAuthProfileSuccess → resetSuccessfulUsageStats resets disabledUntil/errorCount), but inline keys have no success counterpart, and because they fail closed while cooling no request is attempted, so nothing clears the state early — a user who restores credit still waits out the window, and errorCount never resets so repeat failures escalate toward the 24h cap. This is left as a maintainer policy call; candidate directions are success-clear parity, a half-open probe after expiry, an explicit clear command, or a shorter initial billing backoff for inline keys.
  • What was not tested: A live paid-provider 402 against a real exhausted account; the driver exercises the production auth-store and model-auth paths without triggering real billing failures. The *.e2e.test.ts regression file is excluded from the local vitest projects, so its behavioral run is covered by CI rather than locally.

Background

This replaces the closed polluted PR #80482 with the same intended auth-runtime fix rebuilt as a clean branch from current upstream/main.

@MertBasar0
MertBasar0 requested a review from a team as a code owner May 31, 2026 16:35
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: L triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. labels May 31, 2026
@clawsweeper

clawsweeper Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 3, 2026, 10:18 AM ET / 14:18 UTC.

ClawSweeper review

What this changes

The PR records billing and auth failures for inline models.providers.&lt;id>.apiKey credentials, blocks cooled keys from resolution and availability checks, and retains stored-profile fallback until cooldown expiry.

Merge readiness

⚠️ Needs maintainer review before merge - 4 items remain

Keep this PR open: it fixes the reported retry spiral, but its provider-scoped fail-closed cooldown has no supported recovery when an inline key is restored or replaced. The prior P1 remains on the identical head and needs an auth-policy decision before merge.

Priority: P1
Reviewed head: 80595c9ae7a261658dd3782e24e58cabcfe933cc
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong direct terminal proof supports the intended cooldown behavior, but the unresolved P1 recovery contract blocks merge readiness.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body provides a current-head redacted terminal run against production auth modules that shows marking, fail-closed resolution, browse/tool hiding, stored-profile fallback, and expiry recovery; CI supplies supplemental validation.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body provides a current-head redacted terminal run against production auth modules that shows marking, fail-closed resolution, browse/tool hiding, stored-profile fallback, and expiry recovery; CI supplies supplemental validation.
Evidence reviewed 5 items Current-main recovery path is profile-only: Current main describes models auth login as clearing stale billing/auth lockouts, but it enumerates only stored profile IDs and calls clearAuthProfileCooldown for each; an inline-api-key:&lt;provider> usage row is not a profile and is not included.
PR blocks every inline key by provider during cooldown: The changed helper reads only inline-api-key:&lt;normalized provider> and throws until expiry; it has no credential-change, explicit-clear, or half-open recovery branch.
PR records provider-scoped state without a paired recovery producer: The failure marker persists usage statistics under inline-api-key:&lt;provider> using the existing stepped cooldown calculation; the branch adds the producer that enforcement consumes.
Findings 1 actionable finding [P1] Add a supported recovery for cooled inline keys
Security None None.

How this fits together

Embedded agent failures update provider authentication state; model resolution, browsing, and tool-auth checks consume that state before offering an inline provider key. Stored auth profiles already have a deliberate re-authentication recovery flow, while this PR introduces a provider-scoped state row for inline keys.

flowchart LR
  A[Provider billing or auth failure] --> B[Embedded agent failover]
  B --> C[Provider-scoped cooldown state]
  C --> D[Model credential resolver]
  C --> E[Browse and tool availability]
  D --> F[Stored profile fallback]
  D --> G[Inline key blocked]
  H[Explicit re-authentication] --> F
Loading

Decision needed

Question Recommendation
Which supported recovery contract should let an operator intentionally resume a cooled inline provider key before its provider-scoped cooldown expires? Add an explicit inline-key recovery action: Provide a generic auth or Doctor action that clears the provider-scoped inline cooldown only after an intentional operator recovery step, then add rotated-key and restored-credit proof.

Why: The branch correctly prevents repeated billing retries, but choosing whether deliberate key replacement, an explicit clear action, or expiry-only behavior is the durable operator contract cannot be resolved mechanically.

Before merge

  • Add a supported recovery for cooled inline keys (P1) - inline-api-key:&lt;provider> is written without a credential identity, and this guard rejects every inline key for that provider until expiry. Current models auth login clears only stored profile IDs, so an inline-only operator who restores credit or rotates the key has no supported way to resume service; this was the prior P1 and the relevant branch code is unchanged.
  • Resolve merge risk (P1) - A user who restores provider credit or replaces an inline API key remains blocked because the new state is keyed only by provider and the PR's resolver rejects it until expiry.
  • Resolve merge risk (P2) - The PR changes authentication fallback behavior across inline literals, environment markers, SecretRefs, model browsing, and tool selection; landing expiry-only lockout without an intentional recovery contract risks breaking an existing operator recovery workflow.

Findings

  • [P1] Add a supported recovery for cooled inline keys — src/agents/model-auth-provider-config.ts:574-587
Agent review details

Security

None.

PR surface

Source +347, Tests +719. Total +1066 across 25 files.

View PR surface stats
Area Files Added Removed Net
Source 16 384 37 +347
Tests 9 722 3 +719
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 25 1106 40 +1066

Review metrics

Metric Value Why it matters
Production vs test delta production +384/-37, tests +722/-3 The production growth is justified by carrying one new cooldown invariant through failure marking, credential resolution, browsing, warm state, and tool-auth callers; it still warrants a single recovery contract before merge.

Stored data model

Persistent data-model change detected: serialized state: src/agents/embedded-agent-runner.run-embedded-agent.auth-profile-rotation.e2e.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #39807
Summary: This PR is a credible candidate fix for the canonical inline-key billing retry problem, but it has a remaining recovery-policy blocker.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Add a supported recovery before merge (recommended)
    Keep the cooldown enforcement but add and prove a deliberate inline-key recovery path that cannot be mistaken for an automatic retry loop.
  2. Accept expiry-only provider lockout
    Merge the branch unchanged only if maintainers explicitly accept that restoring credit or rotating an inline key does not take effect until cooldown expiry.
  3. Pause enforcement pending policy
    Split or pause the enforcement portion if the intended recovery contract cannot be agreed now.

Technical review

Best possible solution:

Preserve the provider-level backoff, but add one supported, documented recovery contract for intentional inline-key remediation—preferably a generic explicit clear/reconfigure action that does not require editing state files—and cover both rotated-key and restored-credit flows.

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

Yes, by source: an inline billing failure writes inline-api-key:<provider>, and every inline credential for that provider then hits the branch's fail-closed resolver guard. The PR also supplies a current-head terminal run of this path, although this review did not execute a live paid-provider 402.

Is this the best way to solve the issue?

No. Provider-level cooldown enforcement is a sound repair for repeated failures, but expiry-only recovery is not the best complete solution because the established re-authentication path clears only stored profiles and cannot clear the new inline state.

Full review comments:

  • [P1] Add a supported recovery for cooled inline keys — src/agents/model-auth-provider-config.ts:574-587
    inline-api-key:<provider> is written without a credential identity, and this guard rejects every inline key for that provider until expiry. Current models auth login clears only stored profile IDs, so an inline-only operator who restores credit or rotates the key has no supported way to resume service; this was the prior P1 and the relevant branch code is unchanged.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: The patch addresses repeated billing failures that can leave configured agent providers unusable, and its remaining recovery gap can lock out affected operators.
  • merge-risk: 🚨 compatibility: Existing inline-key users who restore credit or rotate a configured key can remain blocked by newly persisted provider-scoped state until expiry.
  • merge-risk: 🚨 auth-provider: The branch changes provider credential resolution, fallback selection, and the visibility of credentials to model and tool auth.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body provides a current-head redacted terminal run against production auth modules that shows marking, fail-closed resolution, browse/tool hiding, stored-profile fallback, and expiry recovery; CI supplies supplemental validation.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides a current-head redacted terminal run against production auth modules that shows marking, fail-closed resolution, browse/tool hiding, stored-profile fallback, and expiry recovery; CI supplies supplemental validation.

Evidence

What I checked:

  • Current-main recovery path is profile-only: Current main describes models auth login as clearing stale billing/auth lockouts, but it enumerates only stored profile IDs and calls clearAuthProfileCooldown for each; an inline-api-key:<provider> usage row is not a profile and is not included. (src/commands/models/auth.ts:934, ffcca757eb3a)
  • PR blocks every inline key by provider during cooldown: The changed helper reads only inline-api-key:<normalized provider> and throws until expiry; it has no credential-change, explicit-clear, or half-open recovery branch. (src/agents/model-auth-provider-config.ts:574, 80595c9ae7a2)
  • PR records provider-scoped state without a paired recovery producer: The failure marker persists usage statistics under inline-api-key:<provider> using the existing stepped cooldown calculation; the branch adds the producer that enforcement consumes. (src/agents/auth-profiles/usage.ts:1143, 80595c9ae7a2)
  • Current auth recovery ownership: Blame ties the current main re-authentication recovery flow to the recent auth command and usage-state work in commit 188957a18af8e075c4ea5e971d09dad34be0bbf6. (src/commands/models/auth.ts:928, 188957a18af8)
  • Not already implemented or shipped: Current main has no inline-cooldown symbols, and the PR head is not an ancestor of either current main or the latest release commit; this remains a live candidate fix rather than an obsolete branch. (src/agents/model-auth-provider-config.ts:574, ffcca757eb3a)

Likely related people:

  • steipete: Current main's profile cooldown recovery and the related auth usage state were introduced in the recent commit identified by blame, making this the closest current ownership boundary for deciding equivalent inline-key recovery. (role: recent auth recovery author; confidence: high; commits: 188957a18af8; files: src/commands/models/auth.ts, src/agents/auth-profiles/usage.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Obtain an owner decision on the inline-key recovery contract.
  • Implement and prove the selected recovery path for both restored credit and a replaced inline key.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-26T22:40:42.907Z sha 8bfc33a :: needs maintainer review before merge. :: none
  • reviewed 2026-07-27T14:25:11.465Z sha 4973f75 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-28T09:06:26.354Z sha 4359102 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-28T15:06:32.593Z sha 4359102 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-29T13:42:51.914Z sha b1f77d9 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-30T13:04:25.050Z sha b1f77d9 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-31T13:25:59.296Z sha b1f77d9 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-03T14:09:47.801Z sha 80595c9 :: found issues before merge. :: [P1] Add a supported recovery for cooled inline keys

@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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels May 31, 2026
@MertBasar0
MertBasar0 force-pushed the fix/inline-api-key-billing-cooldown branch from 2c33109 to 160ac62 Compare May 31, 2026 16:44
@MertBasar0

Copy link
Copy Markdown
Contributor Author

Follow-up after CI guard failure on the replacement PR.

Fix:

  • Added the missing isInlineProviderApiKeyAuth import in src/agents/embedded-agent-runner/run.ts.
  • New head: 160ac624eb

Additional validation:

  • node scripts/run-tsgo.mjs -p tsconfig.plugin-sdk.dts.json --declaration true: passed
  • node scripts/run-vitest.mjs src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts src/agents/embedded-agent-runner/run/assistant-failover.test.ts src/agents/embedded-agent-runner.run-embedded-agent.auth-profile-rotation.e2e.test.ts --reporter=dot
    • agents shard: 3 files / 106 tests passed
    • e2e shard: 1 file / 28 tests passed
  • ./node_modules/.bin/oxfmt --check --threads=1 src/agents/embedded-agent-runner/run.ts
  • git diff --check

@MertBasar0
MertBasar0 force-pushed the fix/inline-api-key-billing-cooldown branch from 160ac62 to 6db1364 Compare May 31, 2026 16:46
@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. labels May 31, 2026
@MertBasar0

Copy link
Copy Markdown
Contributor Author

Updated the Real behavior proof section with the local terminal probe output for the exact current head 6db13645ab9706ada6222806fa6cd79128fbf3bb.

Latest proof status:

  • Real behavior proof passed on run 26718568519, job 78741415772.
  • Full rollup is mergeable/clean; the remaining failed/cancelled proof entries shown by GitHub are stale runs from before the body update.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 May 31, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 31, 2026
@MertBasar0

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed the remaining P1 prompt-stage no-profile marker gap.

Change:

  • Prompt-error auth/billing failure marking now calls the shared marker path whenever a failure reason exists, even when there is no failed auth profile id.
  • Added an e2e regression proving models.providers.openai.apiKey prompt billing failures write the inline-api-key:openai usage state without creating or touching an auth profile.

Current head: d1c43c4

Validation after this patch:

  • node scripts/run-vitest.mjs src/agents/embedded-agent-runner.run-embedded-agent.auth-profile-rotation.e2e.test.ts --reporter=dot
    • 1 file / 29 tests passed
  • node scripts/run-vitest.mjs src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts src/agents/embedded-agent-runner/run/assistant-failover.test.ts src/agents/embedded-agent-runner.run-embedded-agent.auth-profile-rotation.e2e.test.ts --reporter=dot
    • agents shard: 3 files / 106 tests passed
    • e2e shard: 1 file / 29 tests passed
  • node scripts/run-tsgo.mjs -p tsconfig.plugin-sdk.dts.json --declaration true
  • ./node_modules/.bin/oxfmt --check --threads=1 on the touched auth/runner files
  • git diff --check

@clawsweeper

clawsweeper Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels May 31, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 2, 2026
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 2, 2026
MertBasar0 and others added 3 commits July 9, 2026 10:03
The runner failure-marker now gates on isConfigBackedInlineProviderApiKey, so
isInlineProviderApiKeyAuth has no remaining callers. Removing the dead export
also trims one public callable export back under the plugin-SDK surface budget.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The inline-api-key cooldown was recorded for managed (file/exec) SecretRef
provider keys but never enforced: these keys resolve through the synthetic
runtime path (resolveSyntheticLocalProviderAuth) and the explicit api-key
override path, neither of which consulted the inline-key cooldown gate. So an
exhausted file/exec SecretRef provider kept resolving and reporting available
during an active inline-api-key:<provider> cooldown.

Gate both resolution exits (and the provider-availability check) on
isConfigBackedInlineProviderApiKey + assertInlineProviderApiKeyUsable, matching
the literal/env paths. Local no-auth markers are not config-backed inline keys,
so they stay untouched. Adds regression coverage for both resolution paths.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

Copy link
Copy Markdown
Contributor Author

Rebased this PR onto current upstream/main and pushed 8935c5e180.

Changes made:

  • Resolved the rebase conflicts against main.
  • Fixed the managed SecretRef runtime-auth fast path so config-backed inline provider keys honor inline-api-key:<provider> cooldowns before reporting runtime auth as available.
  • Applied the same cooldown gate to the direct managed runtime SecretRef resolution path.
  • Added focused coverage for hasRuntimeAvailableProviderAuth(..., store) returning false while the provider inline-key cooldown is active.
  • Refreshed plugin SDK surface budgets after the rebase.

Local verification:

  • git diff --check
  • oxfmt --check --threads=1 src/agents/model-auth.ts src/agents/model-auth.test.ts src/agents/model-auth.profiles.test.ts src/agents/auth-profiles/usage.ts scripts/plugin-sdk-surface-report.mjs
  • node --no-maglev ./node_modules/vitest/vitest.mjs run --config test/vitest/vitest.agents.config.ts --configLoader runner src/agents/model-auth.test.ts src/agents/model-auth.profiles.test.ts src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-provider-auth.test.ts src/agents/model-provider-auth.worker.test.ts src/agents/embedded-agent-runner/run/assistant-failover.test.ts --reporter=dot (6 files, 215 tests passed)
  • node --no-maglev ./node_modules/vitest/vitest.mjs run --config test/vitest/vitest.tooling.config.ts --configLoader runner test/scripts/plugin-sdk-surface-report.test.ts --reporter=dot (9 tests passed)
  • node scripts/plugin-sdk-surface-report.mjs --check

Note: local run-tsgo still fails in this checkout on existing environment/workspace issues such as missing markdown-it-cjk-friendly, @openclaw/uirouter, @openclaw/libterminal/browser, and unrelated StatsFs.frsize test typings.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

MertBasar0 and others added 2 commits July 9, 2026 10:48
Direct hasRuntimeAvailableProviderAuth callers omitted the auth store, so
inline provider keys in billing cooldown were still advertised as available
in model browsing (models.list) and model-backed tool auth checks. Pass the
scoped auth store at each call site and cover the cooled-key paths with
regression tests, including profile fallback and cooldown expiry.

Co-Authored-By: Claude Fable 5 <[email protected]>
@MertBasar0

MertBasar0 commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Closed the remaining P1: direct hasRuntimeAvailableProviderAuth callers now thread the scoped auth store, so inline provider keys in billing cooldown are hidden from model browsing (models.list) and from model-backed tool auth checks (hasProviderAuthForTool, hasDirectProviderApiKeyAuthForTool, Codex synthetic-media route). Added regression coverage for the cooled-key paths — model-list rows go available: false during cooldown and back to available: true on expiry, tool auth hides the cooled inline key while keeping stored-profile fallback, and existing inline cooldown tests still pass. Rebased onto current branch tip.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

Resolve conflicts and re-port the inline-api-key billing cooldown onto
main's refactored auth/runner/browse modules (~5570 commits of drift).

- model-auth.ts: interleave inline-key cooldown enforcement with main's new
  resolveDirectProviderCredentialMode / isAuthModeAllowedForModel mode gating.
- Write side (run.ts was gutted into run/* modules): port the inline-key
  failure marker into failover-retry-controller.maybeMarkAuthProfileFailure
  (thread getApiKeyInfo) and relax the two prompt-failure.ts profile-id gates
  so inline keys record cooldowns on prompt failover.
- Browse side (models-list-result.ts availability moved to
  model-auth-availability.ts): hide config-backed inline keys from browse
  availability while their inline cooldown is active.
- tool auth (model-config.helpers.ts): keep store threading through the
  runtime availability checks.
- usage.ts: align markInlineProviderApiKeyFailure with main's no-arg
  resolveAuthCooldownConfig (main dropped configurable per-provider cooldowns);
  drop the now-obsolete per-provider-override regression test.
- plugin-sdk surface budgets: keep main's values (our exports are not SDK
  surface; report confirms 4721/2879).

Validated: 618 targeted tests pass, tsgo core typecheck clean, plugin-sdk
surface check passes.

Co-Authored-By: Claude Fable 5 <[email protected]>
@MertBasar0

Copy link
Copy Markdown
Contributor Author

Merged current upstream/main and resolved the conflicts. Main had re-modularized this whole subsystem since this PR was opened, so the inline-key cooldown had to be re-ported onto the new structure rather than mechanically merged:

  • Read side (model-auth.ts): inline-key cooldown enforcement is now interleaved with main's new resolveDirectProviderCredentialMode / isAuthModeAllowedForModel mode gating.
  • Write side (run.ts was split into run/* modules): the inline-key failure marker moved into failover-retry-controller.maybeMarkAuthProfileFailure (threading getApiKeyInfo), and the two prompt-failover profile-id gates in prompt-failure.ts were relaxed so inline keys record cooldowns on failover.
  • Browse side (availability moved to model-auth-availability.ts): config-backed inline keys are now hidden from browse availability while their cooldown is active — this is the P1 from the last review, re-applied on the new architecture.
  • Aligned markInlineProviderApiKeyFailure with main's now-argumentless resolveAuthCooldownConfig (main dropped configurable per-provider cooldowns) and removed the obsolete per-provider-override test.

The branch is now current with upstream/main (no conflicts). Validated locally: 618 targeted tests pass across the read/write/browse/tool/failover paths, tsgo core typecheck is clean, and the plugin-SDK surface check passes (no new SDK surface).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

MertBasar0 and others added 2 commits July 21, 2026 16:56
…ndependence)

- failover-retry-controller.ts: apply oxfmt formatting missed after the port.
- model-auth-availability.ts: the browse-side inline cooldown check imported
  resolveInlineProviderApiKeyUnusableUntil from the auth-profiles usage module,
  which several command/directive tests partially mock — the new export was
  absent from those mocks, so every mocking test threw at the browse path.
  Read the inline cooldown via usage-state primitives (resolveProfileUnusableUntil
  + isAuthCooldownBypassedForProvider) and build the usage id with the same
  normalizeProviderId the write side uses, so the hot browse path no longer
  depends on the mocked usage module while keeping key resolution identical.

Co-Authored-By: Claude Fable 5 <[email protected]>
resolveApiKeyForProvider/assertInlineProviderApiKeyUsable read the inline
provider API-key cooldown, which this PR routes through the auth-profiles
usage module. Many existing suites partially mock that barrel (e.g.
run.overflow-compaction.test.ts) without the new export, so those tests
threw once merged code reached the inline path.

Read the cooldown via usage-state primitives (resolveProfileUnusableUntil +
isAuthCooldownBypassedForProvider) and build the `inline-api-key:<provider>`
usage id with the same normalizeProviderId the write side uses, so model-auth
no longer depends on the mocked usage module while key resolution stays
identical. Verified across all 30 suites that mock the auth-profiles module.

Co-Authored-By: Claude Fable 5 <[email protected]>
@MertBasar0

Copy link
Copy Markdown
Contributor Author

CI is now fully green on the merged branch (ci-gate passing, all checks-node-compact shards green).

Since the last re-review I merged current upstream/main and re-ported the inline-key cooldown onto main's refactored modules, then fixed two follow-ups the merge surfaced:

  • The browse-side cooldown check (model-auth-availability.ts) and the read-side check (model-auth.ts) read the inline inline-api-key:<provider> cooldown via auth-profiles/usage-state.js primitives instead of the auth-profiles usage barrel, so the many suites that partially mock that module (e.g. run.overflow-compaction.test.ts, list.status.test.ts) no longer throw when they reach the inline path. The usage id is built with the same normalizeProviderId the write side uses, so key resolution is identical.
  • Applied the oxfmt formatting the port had missed on run/failover-retry-controller.ts.

Verified locally: the full set of suites that mock the auth-profiles module (1557 tests) pass, tsgo core typecheck is clean, and oxfmt is clean.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@MertBasar0

Copy link
Copy Markdown
Contributor Author

The previous re-review looks like it stalled: ClawSweeper posted "review started" ~20h ago (2026-07-22 12:26 UTC) but never followed up with a verdict, and the PR has had no activity since — so that run didn't complete and the status: ⏳ waiting on author label is stuck on the incomplete review rather than reflecting the current state.

Nothing has changed on the branch in the meantime: it's still merged with current upstream/main (no conflicts), CI is green, and the earlier P1 (inline keys hidden from models.list / tool auth while cooling) is closed with regression coverage. Kicking off a fresh review.

@clawsweeper re-review

Main split the model-auth monolith into a facade plus responsibility-focused
modules, so the inline-api-key cooldown had to be re-ported onto that layout
rather than merged mechanically.

- model-auth.ts: take main's facade; re-export isConfigBackedInlineProviderApiKey
  so the runner's failure marker keeps its import path.
- model-auth-provider-config.ts: home for the shared inline-key helpers
  (isConfigBackedInlineProviderApiKey, resolveInlineProviderApiKeyCooldownUntil,
  assertInlineProviderApiKeyUsable). Both the provider and runtime modules
  already import this module, and the cooldown read still goes through
  usage-state primitives so partially-mocked suites keep working.
- model-auth-provider.ts: fail closed on a cooling inline key at each site that
  returns one (env-first and profile-first env paths, managed SecretRef runtime
  auth, and both custom-key returns), reusing the module's getScopedStore().
- model-auth-runtime.ts: restore the optional auth store on
  hasRuntimeAvailableProviderAuth and gate the env/custom/managed branches on
  the inline cooldown, so browse and tool selection hide a cooled key.
- model-auth-model.ts: resolve the store before the env/custom/synthetic checks
  in hasAvailableAuthForProvider and apply the same gate.

Validated: 844 targeted tests pass across the auth, browse, tool, command and
failover suites; tsgo core typecheck clean for these modules; oxfmt clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
@MertBasar0

Copy link
Copy Markdown
Contributor Author

Merged current upstream/main again — conflicts resolved, branch is clean.

Main split the model-auth monolith into a facade plus responsibility-focused modules since the last merge, so the cooldown was re-ported onto that layout rather than merged mechanically:

  • model-auth-provider-config.ts now hosts the shared inline-key helpers (isConfigBackedInlineProviderApiKey, resolveInlineProviderApiKeyCooldownUntil, assertInlineProviderApiKeyUsable) — both the provider and runtime modules already import it, and the cooldown read still goes through usage-state primitives so partially-mocked suites keep working.
  • model-auth-provider.ts fails closed at each site that returns an inline key (env-first / profile-first env paths, managed SecretRef runtime auth, both custom-key returns).
  • model-auth-runtime.ts and model-auth-model.ts gate browse/tool availability on the same cooldown, so a cooled key is not advertised as usable.

Verified locally: 844 targeted tests pass across the auth, browse, tool, command and failover suites; tsgo core typecheck is clean for these modules; oxfmt is clean.


On the open question about recovery after credit restoration — that concern is real, and I'd rather flag it precisely than paper over it. There is an asymmetry in the current design:

  • Stored auth profiles recover on success: markAuthProfileSuccess → resetSuccessfulUsageStats clears disabledUntil/disabledReason/errorCount.
  • Inline provider keys have no success counterpart. markInlineProviderApiKeyFailure writes the cooldown, but nothing clears it, and because the key is fail-closed while cooling, no request is attempted, so no success can ever clear it.

Net effect: a user who tops up credit immediately after a 402 still waits out the window (5h default, escalating toward the 24h cap on repeat failures), and errorCount never resets, so subsequent failures keep escalating. There is no manual clear path either — isAuthCooldownBypassedForProvider is hardcoded to openrouter/kilocode.

That is a product/policy decision rather than a mechanical fix, which is why I have not changed it unilaterally. The options I see, smallest first:

  1. Success-clear parity — add an inline counterpart to markAuthProfileSuccess so a successful run resets the inline cooldown state. Stops the exponential escalation across days, but does not shorten an active window.
  2. Half-open probe — after the window expires (or periodically), allow one trial request before re-blocking. Standard circuit-breaker behavior and the closest match to "user restored credit".
  3. Explicit clear — a CLI/config escape hatch.
  4. Shorter initial billing backoff for inline keys specifically.

Happy to implement whichever direction maintainers prefer — or to reduce the PR to the detection/marking half and leave enforcement policy for a follow-up, if that lands more easily.

…ng case

Main reworked EmbeddedRunAttemptResult so attempt failures are reported via
`terminal: { kind: "failed", source, error }` instead of the old
`promptError`/`promptErrorSource` fields. The inline-key billing regression
test still used the removed fields, which merged cleanly but broke
check-test-types.

Switch it to the same shape the sibling helper in this file already uses.
Verified with `pnpm check:test-types` (exit 0).

Co-Authored-By: Claude Fable 5 <[email protected]>
@MertBasar0

Copy link
Copy Markdown
Contributor Author

Refreshed the Real behavior proof section in the PR body at the current head (43591020f95), since the previous evidence predated the re-port across the split auth modules.

It now shows a live run against the real production modules (no vitest, no mocks, isolated home/agent dir) covering each requested item: failure marking (inline-api-key:proofprov written with disabledReason=billing), the active cooldown failing closed, browse and model auth both hiding the cooled key, stored-profile fallback still resolving while it cools, and the key resolving again after expiry.

The body also now states the recovery scope explicitly: it is expiry-only today. Stored profiles clear their cooldown on success (markAuthProfileSuccess → resetSuccessfulUsageStats), but inline keys have no success counterpart and fail closed while cooling, so nothing clears the state early — a user who restores credit still waits out the window. I have deliberately not changed that unilaterally since it is a policy call; the candidate directions (success-clear parity, half-open probe, explicit clear, shorter initial backoff) are listed in the body, and I am happy to implement whichever maintainers prefer.

Also fixed the check-test-types failure from the merge: the regression test still used the removed promptError/promptErrorSource fields and now uses main's terminal: { kind: "failed", source, error } shape. CI is green on this head.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@MertBasar0

Copy link
Copy Markdown
Contributor Author

Offer: split this into a small mechanical PR + a separate policy PR

This PR is size: XL, spans auth resolution / runner / browse / tool selection, and its remaining blocker is a product decision (fail-closed semantics and the recovery scope). That combination makes it awkward to land as one unit, so if it helps, I'm happy to cut it in two:

PR A — record only (no behavior change). Adds the provider-scoped failure marker so an inline models.providers.<id>.apiKey billing/auth failure is recorded under inline-api-key:<provider>, plus the runner wiring that calls it (failover-retry-controller threading getApiKeyInfo, and the two prompt-failover gates so a keyless inline credential can be marked at all) and focused regression tests. Nothing reads the new state, so user-visible behavior is unchanged — it is purely the missing bookkeeping that #39807 identified.

PR B — enforcement policy. Everything that acts on that state: failing closed during the window in resolveApiKeyForProvider, hiding cooled keys from models.list and model-backed tool auth, and whichever recovery direction maintainers pick (success-clear parity, half-open probe after expiry, explicit clear, or a shorter initial billing backoff).

Being explicit about the tradeoff: PR A on its own does not fix the reported symptom — the retry spiral in #39807 stops only once enforcement lands in B. A is the narrow, reviewable foundation; B is where the policy call belongs.

Happy to do this split, keep it as one PR, or reshape it some other way — whichever is easiest to review. Just say which and I'll turn it around.

For reference, current state of this PR: merged with current main, CI green, proof: sufficient with a current-head live run in the body covering failure marking, active cooldown, stored-profile fallback, and expiry.

MertBasar0 and others added 2 commits July 29, 2026 16:35
Single conflict in model-config.helpers.ts: main added `runtimeLookup` to the
`hasRuntimeAvailableProviderAuth` call in hasProviderAuthForTool while this
branch added the scoped auth `store` to the same call. Both are needed, so keep
them together rather than picking a side.

Validated: 746 targeted tests pass across the auth, browse, tool, command and
directive suites; `pnpm check:test-types` is clean; oxfmt is clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
Three conflicts, all where this branch's inline-key cooldown meets main's
ongoing auth refactor:

- model-auth-availability.ts: keep both sides of the import block — main's new
  listProviderEnvAuthLookupKeys and this branch's usage-state primitives.
- model-auth-provider-config.ts: adopt main's restructured imports (order.js /
  types.js, resolveApiKeyForProfile now imported dynamically) and its
  un-exported isCustomLocalProviderConfig, keeping the inline-key helpers.
- auth-profile-rotation.e2e.test.ts: keep this branch's inline-key billing
  regression test and honor main's removal of its deferred-mark test, whose
  authProfileUsageTesting hook no longer exists.

Validated: 563 targeted tests pass; `pnpm check:test-types` clean; oxfmt clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

Maintainer decision: we accept the provider-scoped, expiry-only recovery policy for inline API-key auth/billing cooldowns in this PR.

The intended scope is to stop the retry spiral while preserving the existing inline-key path; we are not requiring credential migration, synthetic auth profiles, or an early clear after key replacement/credit restoration in this change. Healthy stored profiles remain available independently during the window.

One wording correction for the record: current computeNextProfileUsageStats resets stale counters after the previous unusable window expires, so errorCount does not grow forever across expired windows. The accepted limitation is specifically that an active window has no early-clear path.

Proceeding through the guarded landing workflow on head 80595c9ae7a261658dd3782e24e58cabcfe933cc.

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling 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. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Billing error (402) causes infinite retry death spiral for inline-apiKey providers (no backoff)

2 participants