Skip to content

fix(agents): explain when a listed model rejects a chat request - #200073

Merged
obviyus merged 8 commits into
mainfrom
openclaw/chat-capability-step2
Nov 16, 2026
Merged

obviyus merged 8 commits into
mainfrom
openclaw/chat-capability-step2

Conversation

@obviyus

@obviyus obviyus commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

#199998 made models that a provider lists without capability metadata visible and runnable. A listed model that is not a chat model, or is not enabled for the account, now fails at its first request instead of being hidden.

Live probes on OpenAI and Google AI Studio show these failures return a 4xx in 0.3–1.0 s. About half of the bodies say the model "does not exist" (404), so OpenClaw reported "This model was not found". That is misleading for a model that the provider itself lists. Others ("not supported with the Responses API", "response modalities", "bidiGenerateContent", "not allowed to sample") ended as a raw request rejection or a sign-in error.

Solution

Both conditions below must hold:

  • The provider answers with a deterministic 400, 403 or 404 that contains one of these phrases: "model … does not exist", "not supported with the Responses API", "not supported for generateContent", "response modalities", "bidiGenerateContent" or "not allowed to sample".
  • The successful listing made with the same credential (same provider and auth profile) returned that model ID. The check reads the outcome's listedModelIds or modelIdCatalog.

When both hold, the turn says:

The provider lists this model but rejected a chat request. It may not be a chat model, or it isn't enabled for this account. Choose another model.

Code changes:

  • live-model-errors.ts: isListedModelChatRejection(status, message). It sits next to the model-not-found matcher, so the classifier owner stays the same.
  • failover/error.ts + user-copy.ts: code model_chat_rejected and its copy. The code is rendered through the existing renderFailoverCodeUserCopy path, which every reply surface already uses for model_chat_unsupported.
  • provider-catalog-outcome.ts: isModelInCredentialListing, which uses the same credential rule as the account-entitlement check.
  • assistant-failure.ts + failover-policy.ts: the run produces a stateless format failure. This failure skips auth refresh, profile rotation, profile cooldown and session-model revert. It also skips the deterministic-format fallback stop, so a configured fallback runs next. Like the deterministic-400 handling from fix: hide non-chat models from chat selection #198288, there is no retry and no compaction.
  • Catalog owners publish their listing: the OpenAI API-key catalog's ready outcome carries modelIdCatalog, as the shared OpenAI-compatible live catalog already does. The Google AI Studio catalog's ready outcome carries listedModelIds: every ID models.list returned, including the non-chat rows its projection hides. Before this, the Google catalog published no listing, so the Google rules could never apply.

These cases stay on their current paths: 5xx, 429, 401/402, timeouts, any 200 (including empty output), and 404s for models that are not in the current listing (the real model-not-found case).

Impact

  • Users see an honest reason and the next configured model runs. Nothing is persisted.
  • Side effect: OpenAI API-key users with configured OpenAI model IDs that their listing does not return now get the existing "unlisted configured model" advisory. Other live-listing providers already show it.
  • Accepted edge: a turn that is admitted before the first listing of the Gateway's life completes cannot prove listing membership. It keeps the current model-not-found copy. The next turn after discovery uses the new copy.
  • Not covered: failures produced inside a plugin-owned harness transport (prompt stage, for example Codex app-server requests). In the real run below, the listed model went through OpenClaw's own transport.

Evidence

Regression tests (red on the merge base 84a378cfe2df, green here). assistant-failure.listed-model.test.ts replays sanitized live bodies through projectProviderError → handleEmbeddedAssistantFailure → runWithModelFallback → reply copy. Model IDs are synthetic, and request IDs and headers are removed. The positive bodies are an OpenAI Responses 404 and 400, an OpenAI Chat 403, and Google generateContent 404, modalities 400 and bidi 400. Each case uses its owner's listing shape: OpenAI modelIdCatalog, Google listedModelIds.

  • On base, all 6 copy cases fail: they show "This model was not found", "Couldn't sign in…" or "LLM request rejected: …".
  • On base, the two Google 400 cases also stop the fallback chain.
  • Negative fixtures pass on both: 500, 429, 401, an empty 200, and a 404 for a model missing from the listing.
  • A unit test checks that only 400/403/404 qualify, and never 200, 401, 402, 408, 429, 500 or 503.
  • extensions/google/provider-registration.test.ts runs the registered Google catalog against a models.list body with a chat row and an embedContent-only row. The picker gets only the chat row; the ready outcome lists both IDs under the selected auth profile.

Real Gateway turn. I built both sides with ocx build --dist. Each Gateway ran isolated under env -i with only PATH, a temporary HOME, TMPDIR, OPENCLAW_STATE_DIR and OPENAI_API_KEY. Each used loopback only, its own port and token, and no channels. The harness refreshed the OpenAI listing through the Gateway, then ran one openclaw agent turn on a model that this key's /v1/models lists but cannot use. Public listed non-chat IDs such as text-embedding-3-small are still refused before the run. Google has no real-Gateway turn; its proof is the two tests above.

Reply Provider requests ([model-fetch] start POST /v1/responses) Decision
merge base 84a378cfe2df This model was not found. Choose another model in the OpenClaw app. | model_not_found 1 (404) surface_error reason=model_not_found
this branch The provider lists this model but rejected a chat request. It may not be a chat model, or it isn't enabled for this account. | model_chat_rejected 1 (404) surface_error reason=format, no compaction

The real run used the copy before review added the trailing "Choose another model."; the regression test asserts the final copy.

An exact-key scan of every Gateway log and state directory found 0 hits. All Gateways and ports were confirmed gone afterwards.

Checks. Focused tests pass (agents failover, OpenAI catalog, Google registration and catalog). pnpm tsgo:core, pnpm tsgo:extensions, pnpm check:test-types, oxfmt, oxlint, the line-cap ratchet, the mock-exports ratchet and the test-lines ratchet pass. I left broad suites to CI.

obviyus and others added 2 commits November 16, 2026 16:01
Since listed models without capability metadata became runnable, a listed
model that is not a chat model, or is not enabled for the account, fails at
its first request. OpenAI and Google answer with a deterministic 400, 403 or
404 that often says "model does not exist", so the turn showed "This model
was not found" or a raw request rejection.

When the successful listing made with the same credential returned the model
id, and the provider answers 400, 403 or 404 with one of the captured signals
("does not exist", "not supported with the Responses API", "not supported for
generateContent", "response modalities", "bidiGenerateContent", "not allowed
to sample"), the turn now says: "The provider lists this model but rejected a
chat request. It may not be a chat model, or it isn't enabled for this
account." It is a stateless format failure: no auth refresh, profile rotation,
cooldown or compaction; a configured fallback runs next. 5xx, 429, 401/402,
timeouts, successful replies and models missing from the listing keep their
existing paths.

The OpenAI API-key catalog outcome now carries its listing as
`modelIdCatalog`, like the shared OpenAI-compatible live catalog.

Co-authored-by: obviyus <[email protected]>
OpenClaw-Publication: 9c966dee-0b13-4b80-9170-e5564c10cf6d
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: openai size: M labels Nov 16, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 16, 2026
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR explains credential-listed model chat rejections and advances to configured fallbacks without retrying credentials.

Example: A credential lists fixture-listed-model, but its chat request returns HTTP 404 saying the model does not exist.

  • Before: The reply says the model was not found.
  • After: The reply explains that the provider listed the model but rejected chat, and a configured fallback can run.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The live Gateway evidence supports the central behavior, but the introduced ratchet failure and missing recovery guidance require focused corrections.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR supplies before/after live output from built isolated Gateways through openclaw agent, with a real credential-listed model returning Responses HTTP 404 and the fixed structured reply after one request; captured-body regressions additionally cover fallback behavior.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A model visible in the provider's own listing can produce a misleading missing-model or sign-in error when it rejects chat.
Reason: The maintainer-authored direction addresses demonstrated failures while preserving selected models and existing configured fallback behavior.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep this PR open: it addresses a demonstrated misleading model error through existing owners, but the new test mock fails the repository ratchet and the replacement reply needs a recovery action.

Priority: P2
Reviewed head: 33627ac71c19ba8fac58728afc022d6765ec6ba1

Before merge

  • Preserve real exports or explain the mock's isolation (P2) - The added vi.mock factory replaces a first-party module without importOriginal/vi.importActual pass-through or an adjacent mock-isolation explanation. This new file has no grandfathered baseline entry, so scripts/check-test-mock-exports.mts rejects it; the head's failed ratchet check also reports mock-exports failure. Preserve the real module before overriding the classifier, or document the concrete state-isolation reason using the supported annotation.
  • Include a recovery action in the terminal rejection reply (P2) - When no fallback is configured, a listed model's qualifying 400/403/404 now ends with this explanation alone. It removes the previous missing-model reply's instruction to choose another model and gives the user no next step. Root AGENTS.md requires errors to name the next action; append an instruction to choose another model in the OpenClaw app and update the existing reply expectation.

Findings

  • [P2] Preserve real exports or explain the mock's isolation — src/agents/embedded-agent-runner/run/assistant-failure.listed-model.test.ts:11-13
  • [P2] Include a recovery action in the terminal rejection reply — src/agents/failover/error.ts:18-19
Agent review details

How this fits together

Provider discovery supplies credential-scoped listing facts; the embedded runner combines them with assistant failures, chooses recovery, and passes structured errors to shared reply rendering.

flowchart TD
  A[Provider discovery] --> B[Admitted model catalog]
  B --> D[Assistant failure owner]
  C[Provider chat rejection] --> D
  D --> E[Existing failover policy]
  E --> F[Configured fallback]
  E --> G[Shared failure reply]
Loading

Technical review

Best possible solution:

Retain the existing-owner implementation, repair the closed mock, and tell users to choose another model when the rejection surfaces.

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

The supplied real Gateway comparison demonstrates the original misleading 404 reply, and source inspection confirms how matching listed-model failures reach it on main; no target code was executed during this review.

Is this the best way to solve the issue?

The change uses the existing catalog snapshot, classifier, failover policy, and reply renderer without introducing a competing owner; the two focused findings can be repaired within that design.

Full review comments:

  • [P2] Preserve real exports or explain the mock's isolation — src/agents/embedded-agent-runner/run/assistant-failure.listed-model.test.ts:11-13
    The added vi.mock factory replaces a first-party module without importOriginal/vi.importActual pass-through or an adjacent mock-isolation explanation. This new file has no grandfathered baseline entry, so scripts/check-test-mock-exports.mts rejects it; the head's failed ratchet check also reports mock-exports failure. Preserve the real module before overriding the classifier, or document the concrete state-isolation reason using the supported annotation.
    Confidence: 0.99
  • [P2] Include a recovery action in the terminal rejection reply — src/agents/failover/error.ts:18-19
    When no fallback is configured, a listed model's qualifying 400/403/404 now ends with this explanation alone. It removes the previous missing-model reply's instruction to choose another model and gives the user no next step. Root AGENTS.md requires errors to name the next action; append an instruction to choose another model in the OpenClaw app and update the existing reply expectation.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3d172a634700.

Provenance checked

  • Unknown-capability model admission keeps the original intent (84a378c: Keep provider-listed models runnable when capability metadata is absent; first-use rejection copy was explicitly deferred.)
  • Deterministic assistant failures and credential recovery changes intended behavior with a stated reason (f4c0984: Skip credential retries for affirmative model absence while preserving recovery for account-access failures.)
  • Shared terminal copy and non-chat diagnosis keeps the original intent (2110db5: Preserve saved pins and provide useful non-chat errors instead of misleading missing-model failures.)
  • Private successful model-listing evidence keeps the original intent (1bee6ae: Retain server listing facts for configured-model advisories independently of entitlement.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/agents/live-model-errors.test.ts src/agents/embedded-agent-runner/run/assistant-failure.listed-model.test.ts --maxWorkers=1
  • pnpm check:test-mock-exports
  • pnpm tsgo:core
  • pnpm check:test-types
  • Verify checks-fast-baseline-ratchets passes for the repaired head.

What I checked:

  • Introduced change verified: The pinned introduction diff adds listing membership classification, the existing failover-policy branch, shared reply copy, OpenAI listing evidence, and regression coverage; current main lacks this rejection classification. (src/agents/embedded-agent-runner/run/assistant-failure.ts:212, 33627ac71c19)
  • Real Gateway evidence: The complete PR body records isolated built Gateway runs through openclaw agent: base returns model_not_found, while the branch returns model_chat_rejected after one real Responses 404 request with no compaction. (33627ac71c19)
  • CI failure matches introduced mock: The failed checks-fast-baseline-ratchets job has a mock-exports failure annotation. The added closed factory has neither real-module pass-through nor an isolation annotation and is absent from the baseline; the checker explicitly rejects that shape. (src/agents/embedded-agent-runner/run/assistant-failure.listed-model.test.ts:11, 33627ac71c19)
  • Recovery guidance omitted: The new terminal reply explains the rejection but omits the existing actionable instruction to choose another model, contrary to root guidance that errors name the next step. (src/agents/failover/error.ts:19, 33627ac71c19)
  • Prior work and accepted boundary: fix(models): read provider model kinds at one owner; unknown is not chat:false #199998 intentionally admits unknown-capability listed models and explicitly leaves first-use error copy outside its scope; this PR supplies that distinct follow-up. (src/plugins/AGENTS.md, 84a378cfe2df)
  • Inspection limits: The Actions log download was blocked at its artifact-storage host, so additional CI causes were not inferred; some historical blobs were unavailable, while scoped history, current source, introduction hunks, comments, and check annotations were readable.

PR surface

Source +84, Tests +209, Docs +8. Total +301 across 13 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 8 98 14 +84
Tests 4 211 2 +209
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 317 16 +301

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The PR improves diagnosis and fallback for a bounded class of deterministic provider rejections.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 16, 2026, 5:51 AM ET / 10:51 UTC.

obviyus and others added 6 commits November 16, 2026 16:59
OpenClaw-Publication: 386add77-eb40-4a63-bf39-eb32bf21920e
OpenClaw-Publication: cb8fc10a-a063-4da0-8776-8be6d201a621
…pply

The Google catalog returned only providers, so its ready outcome carried no
listing and a listed Google model never reached the listed-model rejection
copy. The catalog now reports every model id models.list returned, including
hidden non-chat rows, as listedModelIds.

Co-authored-by: obviyus <[email protected]>
OpenClaw-Publication: 6672b4cd-b543-4d2f-8611-469963a4dea0
@obviyus
obviyus merged commit 30e9d3e into main Nov 16, 2026
126 checks passed
@obviyus
obviyus deleted the openclaw/chat-capability-step2 branch November 16, 2026 13:11
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 30e9d3e.

  • Bug: a listed model that is not a chat model, or is not enabled for the account, failed its first request with "This model was not found" or a raw request rejection.
  • Fix: when this credential's listing returned the model and the provider answers 400/403/404 with one of the captured chat-rejection signals, the turn says the provider lists the model but rejected a chat request and asks for another model. It is a stateless format failure: no retry, no login rotation, no cooldown, no compaction; a configured fallback runs next. The OpenAI API-key and Google AI Studio catalogs now publish their listing so the check can apply.
  • Proof: regression tests red on the merge base and green here (OpenAI and Google bodies plus 5xx/429/401/empty-200/unlisted-404 negatives), a Google catalog registration test, and a real isolated-Gateway OpenAI turn (one provider request; old copy on base, new copy on the branch). Exact-head local review clean; CI green.

obviyus added a commit that referenced this pull request Nov 16, 2026
…00126)

## Problem

#200073 made the OpenAI API-key catalog put its listing (`modelIdCatalog`) on its ready outcome. `test/openai-model-discovery-auth-order.test.ts` still expected the old outcome shape. As a result, `main` fails `checks-node-changed-compact-small-20` in "continues from failed openai OAuth to profile API-key auth without repeating refresh". Open PRs that run this shard (for example #200102) inherit the failure.

## Solution

For the OpenAI case, the test now expects `modelIdCatalog: { baseUrl, modelIds: [modelId] }`. The xAI cases are unchanged. This is a test-only change.

## Evidence

- `pnpm test test/openai-model-discovery-auth-order.test.ts`: 17/17 pass. Before this change on `origin/main`, the OpenAI case failed with exactly this diff.
- oxfmt is clean.

<!-- openclaw-publication:f58bd5b3-ae10-8019-875f-27c86918b01c -->

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…claw#200073)

## Problem

openclaw#199998 made models that a provider lists without capability metadata visible and runnable. A listed model that is not a chat model, or is not enabled for the account, now fails at its first request instead of being hidden.

Live probes on OpenAI and Google AI Studio show these failures return a 4xx in 0.3–1.0 s. About half of the bodies say the model "does not exist" (404), so OpenClaw reported "This model was not found". That is misleading for a model that the provider itself lists. Others ("not supported with the Responses API", "response modalities", "bidiGenerateContent", "not allowed to sample") ended as a raw request rejection or a sign-in error.

## Solution

Both conditions below must hold:

- The provider answers with a deterministic **400, 403 or 404** that contains one of these phrases: "model … does not exist", "not supported with the Responses API", "not supported for generateContent", "response modalities", "bidiGenerateContent" or "not allowed to sample".
- The **successful listing made with the same credential** (same provider and auth profile) returned that model ID. The check reads the outcome's `listedModelIds` or `modelIdCatalog`.

When both hold, the turn says:

> The provider lists this model but rejected a chat request. It may not be a chat model, or it isn't enabled for this account. Choose another model.

Code changes:

- `live-model-errors.ts`: `isListedModelChatRejection(status, message)`. It sits next to the model-not-found matcher, so the classifier owner stays the same.
- `failover/error.ts` + `user-copy.ts`: code `model_chat_rejected` and its copy. The code is rendered through the existing `renderFailoverCodeUserCopy` path, which every reply surface already uses for `model_chat_unsupported`.
- `provider-catalog-outcome.ts`: `isModelInCredentialListing`, which uses the same credential rule as the account-entitlement check.
- `assistant-failure.ts` + `failover-policy.ts`: the run produces a stateless `format` failure. This failure skips auth refresh, profile rotation, profile cooldown and session-model revert. It also skips the deterministic-format fallback stop, so a configured fallback runs next. Like the deterministic-400 handling from openclaw#198288, there is no retry and no compaction.
- Catalog owners publish their listing: the OpenAI API-key catalog's ready outcome carries `modelIdCatalog`, as the shared OpenAI-compatible live catalog already does. The Google AI Studio catalog's ready outcome carries `listedModelIds`: every ID `models.list` returned, including the non-chat rows its projection hides. Before this, the Google catalog published no listing, so the Google rules could never apply.

These cases stay on their current paths: 5xx, 429, 401/402, timeouts, any 200 (including empty output), and 404s for models that are not in the current listing (the real model-not-found case).

## Impact

- Users see an honest reason and the next configured model runs. Nothing is persisted.
- Side effect: OpenAI API-key users with configured OpenAI model IDs that their listing does not return now get the existing "unlisted configured model" advisory. Other live-listing providers already show it.
- Accepted edge: a turn that is admitted before the first listing of the Gateway's life completes cannot prove listing membership. It keeps the current model-not-found copy. The next turn after discovery uses the new copy.
- Not covered: failures produced inside a plugin-owned harness transport (prompt stage, for example Codex app-server requests). In the real run below, the listed model went through OpenClaw's own transport.

## Evidence

**Regression tests (red on the merge base `6851ad055e6e`, green here).** `assistant-failure.listed-model.test.ts` replays sanitized live bodies through `projectProviderError` → `handleEmbeddedAssistantFailure` → `runWithModelFallback` → reply copy. Model IDs are synthetic, and request IDs and headers are removed. The positive bodies are an OpenAI Responses 404 and 400, an OpenAI Chat 403, and Google generateContent 404, modalities 400 and bidi 400. Each case uses its owner's listing shape: OpenAI `modelIdCatalog`, Google `listedModelIds`.

- On base, all 6 copy cases fail: they show "This model was not found", "Couldn't sign in…" or "LLM request rejected: …".
- On base, the two Google 400 cases also stop the fallback chain.
- Negative fixtures pass on both: 500, 429, 401, an empty 200, and a 404 for a model missing from the listing.
- A unit test checks that only 400/403/404 qualify, and never 200, 401, 402, 408, 429, 500 or 503.
- `extensions/google/provider-registration.test.ts` runs the registered Google catalog against a `models.list` body with a chat row and an `embedContent`-only row. The picker gets only the chat row; the ready outcome lists both IDs under the selected auth profile.

**Real Gateway turn.** I built both sides with `ocx build --dist`. Each Gateway ran isolated under `env -i` with only `PATH`, a temporary `HOME`, `TMPDIR`, `OPENCLAW_STATE_DIR` and `OPENAI_API_KEY`. Each used loopback only, its own port and token, and no channels. The harness refreshed the OpenAI listing through the Gateway, then ran one `openclaw agent` turn on a model that this key's `/v1/models` lists but cannot use. Public listed non-chat IDs such as `text-embedding-3-small` are still refused before the run. Google has no real-Gateway turn; its proof is the two tests above.

| | Reply | Provider requests (`[model-fetch] start POST /v1/responses`) | Decision |
|---|---|---|---|
| merge base `6851ad055e6e` | `This model was not found. Choose another model in the OpenClaw app. \| model_not_found` | 1 (404) | `surface_error reason=model_not_found` |
| this branch | `The provider lists this model but rejected a chat request. It may not be a chat model, or it isn't enabled for this account. \| model_chat_rejected` | 1 (404) | `surface_error reason=format`, no compaction |

The real run used the copy before review added the trailing "Choose another model."; the regression test asserts the final copy.

An exact-key scan of every Gateway log and state directory found 0 hits. All Gateways and ports were confirmed gone afterwards.

**Checks.** Focused tests pass (agents failover, OpenAI catalog, Google registration and catalog). `pnpm tsgo:core`, `pnpm tsgo:extensions`, `pnpm check:test-types`, oxfmt, oxlint, the line-cap ratchet, the mock-exports ratchet and the test-lines ratchet pass. I left broad suites to CI.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…enclaw#200126)

## Problem

openclaw#200073 made the OpenAI API-key catalog put its listing (`modelIdCatalog`) on its ready outcome. `test/openai-model-discovery-auth-order.test.ts` still expected the old outcome shape. As a result, `main` fails `checks-node-changed-compact-small-20` in "continues from failed openai OAuth to profile API-key auth without repeating refresh". Open PRs that run this shard (for example openclaw#200102) inherit the failure.

## Solution

For the OpenAI case, the test now expects `modelIdCatalog: { baseUrl, modelIds: [modelId] }`. The xAI cases are unchanged. This is a test-only change.

## Evidence

- `pnpm test test/openai-model-discovery-auth-order.test.ts`: 17/17 pass. Before this change on `origin/main`, the OpenAI case failed with exactly this diff.
- oxfmt is clean.

<!-- openclaw-publication:f58bd5b3-ae10-8019-875f-27c86918b01c -->

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa pushed a commit that referenced this pull request Nov 17, 2026
…ns start at once (#192534)

## What Problem This Solves

Fixes: a Gateway using the Claude CLI runtime can push its host into memory exhaustion when several conversations start new Claude processes close together.

On an 8 GB Linux VM without swap, several Slack/Teams turns arrived within about 3 minutes. The Gateway went from 3 to 7 warm Claude CLI processes, available memory fell from ~3.8 GB to ~250 MB and stayed there, and the VM thrashed (no OOM kill, CPU ~5%) until a reboot about 2 hours later. The only limit on warm processes was a fixed count of 16; idle warm processes were kept even while the host ran out of memory.

## User Impact

User impact: when host memory is low, a new Claude CLI conversation first closes idle warm processes (least recently used first). If memory is still low and every warm process is busy, that turn fails over instead of starting another process, and a channel reply says: "⚠️ This host is low on memory, so it could not start another session. Try again after active conversations finish." (Before, any such failure would have shown the generic "AI service needs a short break" rate-limit copy.) Hosts with enough free memory behave as before; turns that reuse their own warm process are unaffected; busy turns are never closed.

## Why This Change Was Made

Before a turn starts a new warm process, the live-session registry reads host free memory through the existing `readHostFreeMemoryBytes()` helper (`os.freemem()`, which is `MemAvailable` on Linux; `process.availableMemory()` on macOS). It walks the warm processes once in least-recently-used order: while memory is below 1 GiB, it closes each idle process and waits for it to exit before the next reading. If memory is still below the floor after that pass, the turn fails over with the `rate_limit` category the 16-session cap already uses, plus a distinct `cli_live_session_host_memory` code. The existing failover-code copy (`renderFailoverCodeUserCopy`) owns its user text, and the rate-limit reply renderer now returns a host-authored code's copy before generic rate-limit text (auth-profile cooldown keeps its expiry-aware copy). The registry map is now kept in least-recently-used order, so both the memory path and the existing count cap close the conversation that has waited longest.

The 1 GiB floor comes from measurements of one warm session:

| Measurement | RSS |
| --- | --- |
| Claude Code 2.1.314, Linux arm64 container, stream-json, idle after start | ~180 MiB |
| Same, after one Haiku turn / three concurrent Sonnet turns | ~195–198 MiB each |
| Full warm session under a Gateway (macOS): Claude Code + two Node supervisor helpers | ~490 MiB (264 + 138 + 87) |

1 GiB leaves room for about two more warm sessions before the kernel has to reclaim. The 16-session cap stays as the upper bound. No config key is added.

## Evidence

- Two `executePluginOwnedProcess` tests (an entry point on both `main` and this branch), with host memory simulated at `readHostFreeMemoryBytes`:
  - Low memory, new conversation: the least recently used idle process closes; the busy one and the recently used one stay. On `main` this fails on behavior (`recent.close` not called).
  - Low memory, only a busy process: the turn rejects with `rate_limit` / `cli_live_session_host_memory` before the plugin runs, the busy process stays, and `resolveReplyFailureSummary` returns the host-memory copy. On `main` this fails on behavior (the turn runs: `reason: "exit"`).
- `src/agents/cli-runner/`, `extensions/anthropic`, and the CLI attempt-execution tests: 1479 passed on the candidate; the registry and `execute-plugin` tests pass on the exact head (108). One failure, `extensions/anthropic/session-catalog.test.ts` ("reports the discovery frontier…"), also fails alone on this host and does not touch the changed files.
- Real path on the previous head `a646b6b8` (the repair batch after it adds the failover code and copy and makes eviction one bounded pass; the tests above cover both): isolated Gateway (own state, config and Claude config dir, test API key from env only), `anthropic/claude-haiku-4-5` with `agentRuntime.id: "claude-cli"`, turns sent with `openclaw agent`. Memory pressure was simulated at the same seam the code reads (`os.freemem` / `process.availableMemory`), with each live Claude process under the Gateway counted as 700 MiB, so closing a process really raises the reading.
  - Real memory: 4 concurrent sessions start (`activeSessions=1…4`), no closures.
  - Low memory, new 5th session: `free-memory read: live claude processes=4 reported=424MiB` → `memory pressure: closing idle session activeSessions=4` → `processes=3 reported=1124MiB` → `cli live session start … activeSessions=4`; the turn replied.
  - Low memory, existing session: reused its warm process, no memory read, no closure; replied.
  - Low memory, all four warm sessions busy with long turns, new session: failed over in 54 ms (`Host memory is too low for another CLI live session.`); all four busy turns completed.

## Limits

- Admission only. A warm process that grows during a long turn after it started is not limited here.
- `readHostFreeMemoryBytes()` reads host memory on Linux, not a container cgroup limit; that helper is shared and unchanged.
- Turns that start at the same instant can each read the same free-memory value before any process exists; the floor's headroom covers a small burst, and the 16-session cap still holds.
- The failover category stays `rate_limit`, as the existing count cap uses; the distinct code carries the cause.
- The live check ran on macOS with a simulated reading; the Linux numbers come from an isolated Claude Code container run.

## Merge danger

Two-way door: a revert restores the previous behavior. No config, schema, stored state or published contract changes.

Blast radius: Gateways using a CLI runtime with warm live sessions (today Claude CLI). If the floor is wrong for a host, the effect is more closed idle sessions (a cold start on the next turn) or a failover when memory is below 1 GiB and every warm session is busy. Other runtimes and channels are not affected.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit de07e00)

Release adaptation: revalidate the existing current-run authority between awaited idle-process cleanup and before capability creation; use the abort-race lazy factory so an already-aborted request starts no close. Preserve baseline cleanup-finally repair. Add one execution-boundary regression for revoked requester authority; no unrelated follow-ups.

# #192534 companion dispositions

Signed baseline e13cf15; audit bd692e9. Working base 8b3ca5d lacks the memory floor and activation LRU refresh; 16-count limit exists. Mechanical probe: clean, six touched files. Exact merged source de07e00.

Later same-path commits, each reviewed in saved relevant-followups.patch / other-followups.patch:
- 30e9d3e #200073: not-applicable, listed model chat rejection code/copy independent of host memory.
- 3a3eed8 #199591: not-applicable, tool loop policy refactor independent of memory admission.
- 8fc58f8 #199226: not-applicable, app naming copy independent of memory.
- 8ccba17 #198426: not-applicable to this admission change, warm callback async-context repair independent; do not silently absorb. Existing requestToolPermission is bound; no callback change required by memory.
- 2110db5 #198288: not-applicable, model chat eligibility and code/copy independent.
- 4527846 #198324: not-applicable, provider rate-limit reset deadlines; host-local memory refusal has no provider deadline.
- 4f8df80 #198224: present-equivalent, baseline registry remove already uses finally and releases retired map after failed cleanup.
- 8cd7d87 #197655: not-applicable, main test allocation pruning; retain this release allocation.
- 5dc6683 #197163: present-equivalent, buildHarnessHostRequester used in baseline; separate tool hook metadata.
- 7786960 #197051: not-applicable, managed WebSearch availability, independent tool policy.
- ac7e941 #196677: not-applicable, expired API-key copy independent of host admission.
- 4d6205c #194439: not-applicable, provider failure/tool warning handling independent of pre-execution host refusal.
- 4845a0f #193508: not-applicable, native credential removal propagation; no new credentials accessed by memory policy. Existing live assertion retained/rechecked.
- 6f69195 #193250: not-applicable, exhausted upstream credit failover category independent of local resource refusal.
No later #192534 mentions.

Prerequisites: readHostFreeMemoryBytes exists unchanged in baseline; @openclaw/retry abort race accepts lazy factory; createCliFailoverError preserves explicit code; FailoverError carries code; existing rate-limit reply renderer consumes it; registry closeRecord joins process exit and owned cleanup. These are present-equivalent.

Neighbor tests: cli-live-session-registry.test.ts, execute-plugin.test.ts, execute-plugin.policy.test.ts, execute-plugin.steering.test.ts, failover/user-copy.test.ts are existing consumers, not missing implementation companions. execute-plugin.warm-context.test.ts exists only after the independent #198426 change and is not applicable to this baseline or memory fix. Run focused registry/execution/copy siblings. Selected-file references: broad generic filename inventory is mostly incidental error/execute references; traced actual owners/imports above. Docs and allocation are non-runtime references; no generated exports or workflow changes needed.

Focused proof: baseline 2 failed/36 passed (LRU eviction missing; busy-only admission incorrectly exits successfully). Green 135 passed across five existing owner/consumer files, including host-memory failure copy and revoked-requester preservation. Format and diff checks clean. Type-aware lint blocked by the established shared TypeScript declaration-confinement boundary; no bypass/install. Parent owns integration and broad release qualification.

Co-authored-by: RomneyDa <[email protected]>

Parent qualification: corrected the authority regression's required braces and matching test allocation (102 lines); no production change from worker. Combined 145/145 tests across seven files passed; post-braces changed suite 39/39 passed. Supported parent type-aware lint and formatting passed six files, executable syntax and diff checks passed. Worker dependency-layout lint limitation resolved. Parent self-review and source/companion comparison recorded in cli-resources-parent-review.md. Full stable/FRV remains pending; publication held.
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 extensions: google extensions: openai P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M 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.

1 participant