Skip to content

fix(models): saving provider credentials shows that provider's models - #190019

Merged
obviyus merged 8 commits into
mainfrom
fix/provider-dialog-allow-models
Nov 1, 2026
Merged

obviyus merged 8 commits into
mainfrom
fix/provider-dialog-allow-models

Conversation

@obviyus

@obviyus obviyus commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Adding a provider did not make it usable when a model allowlist (modelPolicy.allow) existed. On the Team server, saving a Particle API key in Settings → Models → Connect provider succeeded, but no Particle model appeared in the model picker: the allowlist hid them all. Sign-in flows (CLI, chat /login, Telegram, Control UI wizard) asked Show all <Provider> models / Keep current restrictions with Keep as the default. The API-key save path skipped even that, and #189917 only added a text warning that told the user to edit config by hand.

Fix

Saving credentials for a provider is now the request to use its models. When the allowlist that governs the agent hides every model of that provider, the save adds <provider>/* to that allowlist, through the existing model-policy owner (src/commands/models/auth-model-policy.ts):

  • per-agent agents.entries.<id>.modelPolicy.allow when the agent sets its own policy, otherwise agents.defaults.modelPolicy.allow;
  • an unmigrated legacy agents.defaults.models allowlist gets the wildcard key, so none of its models is dropped.

Nothing changes when there is no allowlist, or when the allowlist already names some of the provider's models (an exact ref such as openai/gpt-x, or a narrower wildcard such as clawrouter/anthropic/*). The policy owner decides that: the check reads providers from createModelVisibilityPolicy(...).allowedKeys, which resolves exact refs, aliases and bare legacy refs (inferring their provider from configured provider rows) the same way the picker does. A deliberate exact list is never widened.

Paths:

  • API key / token save (models.authSetApiKey, openclaw models auth paste-api-key, paste-token): the wildcard is added in the same config write as the credential's auth profile.
  • Sign-in (openclaw models auth login, Control UI wizard, chat /login, Telegram /login): after the credential is saved, one write adds the wildcard. The login result carries modelAccess: { message, applied }; chat and Telegram append "Added <provider>/* to allowed models." to the completion message; the Control UI wizard reports an unconfirmed apply as before.

Removed: the post-save select prompt, the deferred onModelAccessRequested request, offerProviderLoginModelAccess / answerProviderLoginModelAccess, the /login access and /login choice model-access commands, createLoginChoicePrompt, ProviderModelPolicyChangedError, and the #189917 Control UI warning. provider-auth-login-flow-runtime is a private-local SDK subpath (docs/plugins/sdk-subpaths.md), so its only consumers are bundled (core chat /login, Telegram), migrated here.

Authority: every models.authSetApiKey save now checks live requester authority (readGatewayRequestMutationAuthority, the guard config.patch uses) before its credential and config writes. Before, browser saves without expectedOwnerId passed no guard; the save now also widens the allowlist, so a requester whose connection or scopes end mid-save cannot commit it. Owner-bound CLI saves keep their owner check and add the same requester check.

Plugin setup defaults still cannot change restrictions (withoutProviderModelPolicy is unchanged); only the credential save does.

This reverses the ask-first default from #144468 by maintainer decision.

No undo button: the models.authSetApiKey result has no field for the change, and adding one is a protocol change; the change is a single visible provider/* allowlist entry.

User Impact

Add a provider key or sign in → its models show in the model picker, even under an existing allowlist that did not mention the provider. Operators who listed specific models of that provider keep exactly their list.

Evidence

Real Gateway, real config write (src/gateway/server-methods/models-auth-api-key.integration.test.ts): config agents.defaults.modelPolicy.allow: ["other/*"], models.authSetApiKey for fixture → saved config ["other/*", "fixture/*"]. Negative control: with the new line disabled, the test fails expected [ 'other/*' ] to deeply equal [ 'other/*', 'fixture/*' ].

Policy owner (src/commands/models/auth-model-policy.test.ts, real config file):

  • per-agent policy widened, defaults untouched;
  • no allowlist / provider already allowed → config bytes unchanged;
  • allowlist with exact sample/one, sample/two → unchanged; with sample/family/* → unchanged (both fail when the check is reverted to "literal sample/* missing");
  • deferred legacy map keeps existing-model and gains sample/*;
  • migrated model map is not treated as an allowlist;
  • authority revoked during the writer's preflight → no write.

Sign-in end to end against a real plugin and config (src/commands/models.auth.provider-resolution.test.ts): access, access-legacy, access-legacy-set-default cases save the credential, add authstore-proof/* with no prompt, and log the notice.

Real key writer under revocation (src/commands/models/auth-api-key.test.ts, real auth store and config file): with an allowlist present, authority revoked inside the config write leaves the config bytes unchanged (no auth binding, no sample/*); unrevoked, the same write saves the binding and ["other/*", "sample/*"].

Gateway-to-writer revocation chain (src/commands/models/auth-api-key.test.ts): the real models.authSetApiKey handler, its readGatewayRequestMutationAuthority guard and the real key/config writer, with the requester's authority ending inside the config write. The RPC fails with "Gateway requester authority changed"; the config file bytes are unchanged (no auth binding, allowlist still ["other/*"]). The key itself committed earlier, while the requester was still authorized, and stays saved. Negative control: with the handler guard replaced by a no-op, the test fails. Run output (synthetic keys only):

✓ |commands| src/commands/models/auth-api-key.test.ts > checks requester authority after credential commit (revoked=false) 1511ms
✓ |commands| src/commands/models/auth-api-key.test.ts > checks requester authority after credential commit (revoked=true) 914ms
✓ |commands| src/commands/models/auth-api-key.test.ts > checks requester authority after config transform (revoked=false) 1392ms
✓ |commands| src/commands/models/auth-api-key.test.ts > checks requester authority after config transform (revoked=true) 1067ms
✓ |commands| src/commands/models/auth-api-key.test.ts > models.authSetApiKey writes no binding or allowlist once the requester is revoked 977ms
Tests  5 passed | 42 skipped (47)

Upgrade compatibility: no stored schema or config shape changes. Existing configs load as before and keep working: explicit modelPolicy.allow (defaults and per-agent), unmigrated legacy agents.defaults.models allowlists (wildcard added as a map key, every existing model kept), migrated maps with the modelPolicyAllowlist marker (not treated as an allowlist), and configs without an allowlist (never written). Each case runs against a real config file in auth-model-policy.test.ts and models.auth.provider-resolution.test.ts. The removed chat model-access questions were in-memory only, so no stored state refers to them.

Existing data, real CLI entry point: a temporary state directory seeded with the Team server's pre-change allowlist shape (exact openai/... refs plus clawrouter/anthropic/... refs, and a legacy agents.defaults.models map), then openclaw models auth paste-api-key from this branch for three providers (synthetic keys, the first run's output trimmed to the resulting list):

Team pre-change allowlist (exact openai refs + clawrouter/anthropic refs), no Gateway running
== openclaw models auth paste-api-key --provider openai
allow = ['openai/gpt-6-luna', 'openai/gpt-6-astra', 'openai/gpt-daybreak-blue-latest', 'openai/gpt-daybreak-red-latest', 'openai/gpt-6.1-sol', 'clawrouter/anthropic/claude-fable-5-1', 'clawrouter/anthropic/claude-opus-5-5']
== openclaw models auth paste-api-key --provider particle
Auth profile: particle:manual (particle/api_key)
Added particle/* to allowed models.
allow = ['openai/gpt-6-luna', 'openai/gpt-6-astra', 'openai/gpt-daybreak-blue-latest', 'openai/gpt-daybreak-red-latest', 'openai/gpt-6.1-sol', 'clawrouter/anthropic/claude-fable-5-1', 'clawrouter/anthropic/claude-opus-5-5', 'particle/*']
== openclaw models auth paste-api-key --provider clawrouter
Auth profile: clawrouter:manual (clawrouter/api_key)
allow = ['openai/gpt-6-luna', 'openai/gpt-6-astra', 'openai/gpt-daybreak-blue-latest', 'openai/gpt-daybreak-red-latest', 'openai/gpt-6.1-sol', 'clawrouter/anthropic/claude-fable-5-1', 'clawrouter/anthropic/claude-opus-5-5', 'particle/*']

OpenAI and ClawRouter keep the operator's exact lists; only Particle, which the list did not mention, gains particle/*.

Bare legacy ref (auth-model-policy.test.ts): legacy map { tiny: {} } with a configured sample provider that has tiny → saving a sample credential leaves config unchanged (fails against the earlier DEFAULT_PROVIDER parse).

Requester authority (src/gateway/server-methods/models-auth-status.set-api-key.test-support.ts): authority ends during the save → the RPC fails with "Gateway requester authority changed" and the writer's assertCurrent throws before commit. Negative control: with the handler's default guard replaced by a no-op, the test fails.

Surface tests: chat /login and Telegram completion messages include the notice; Control UI wizard reports unconfirmed apply; mocked-Gateway Control UI E2E (model-provider-login.e2e.test.ts) passes.

Control UI, mocked Gateway, policy allow: ["openai/*"], save a Particle key:

Before (main, #189917): the dialog stays open with a config-editing instruction.

Before: dialog tells the user to edit modelPolicy.allow

After: the Gateway widens the policy during the save; the dialog closes like any successful save.

After: dialog closes after save

Commands:

  • pnpm test src/commands/models/auth-model-policy.test.ts --maxWorkers=1: 7 passed.
  • pnpm test src/gateway/server-methods/models-auth-api-key.integration.test.ts --maxWorkers=1: 1 passed (~12.5 s, real Gateway, existing test extended; no new boot).
  • pnpm test src/commands/models/auth.test.ts src/commands/models.auth.provider-resolution.test.ts --maxWorkers=1: 80 passed.
  • Chat/Gateway/Telegram/UI suites: passed.
  • pnpm tsgo:core, pnpm tsgo:extensions, OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 pnpm check:changed.

No overlap with Pash/Sarah changes.

Merge danger: one-way for configs: a credential save can now write <provider>/* into a model allowlist. A revert stops new writes but does not remove entries already added. Blast radius: operators who rely on an allowlist that does not mention a provider to keep that provider hidden after someone adds its credentials. Only admins can save credentials.

🤖 Generated with Claude Code

obviyus and others added 3 commits November 1, 2026 08:10
Saving an API key, token or sign-in for a provider now adds <provider>/* to the
model allowlist that governs the agent when that allowlist hides every model of
the provider. Allowlists that already name some of its models, and configs
without an allowlist, stay unchanged. This replaces the post-save
"Show all / Keep current restrictions" prompt and its chat buttons, and the
Control UI warning from #189917.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 1, 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 channel: telegram Channel integration: telegram app: web-ui App: web-ui gateway Gateway runtime commands Command implementations size: XL labels Nov 1, 2026
@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: cc64743232bae6009197e23dced0e078373df2fa
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/server-methods/models-auth-login.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods/models-auth-status.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 1, 2026
@clawsweeper

clawsweeper Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Saving provider credentials adds the provider to the effective model allowlist when that list names none of its models.

Example: Save a Particle API key with allowlist ["openai/*"].

  • Before: The credential saves, but Particle models remain hidden.
  • After: The allowlist becomes ["openai/", "particle/"], making Particle models selectable.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful and supported by production-entry-point output plus final-write authority proof; one weaker duplicate test remains.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The supplied real Gateway RPC saves the wildcard through the production writer; the handler-to-writer harness proves revocation prevents the later config effect, and real CLI output shows existing provider lists remain intact. Inspected screenshots support the mocked-Gateway dialog change.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Connecting a provider can save its credentials while leaving every model hidden, requiring manual configuration to proceed.
Reason: The maintainer-authored direction resolves the reported setup failure while retaining exact and narrower provider lists; it explicitly accepts reversing the earlier consent default.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR implements an approved change to provider model visibility, and the earlier correctness findings are resolved. No blocking production defect was found; CI remains pending.

Priority: P2
Reviewed head: cc64743232bae6009197e23dced0e078373df2fa

Before merge

None.

Findings

None.

Tests

  • Low-value test src/gateway/server-methods/models-auth-status.set-api-key.test-support.ts: Remove the mocked-writer revocation case: the added real handler-to-writer regression now covers the same authority propagation and additionally verifies persisted config remains unchanged.
Agent review details

How this fits together

CLI, chat, Telegram, and Control UI credential flows use shared auth writers and the model-policy owner to persist credentials and update the configuration consumed by model pickers.

flowchart TD
  A[Credential save request] --> B[Current caller authority]
  B --> C[Credential writer]
  C --> D[Model policy owner]
  D --> E[Existing configuration writer]
  E --> F[Gateway model picker]
Loading

Technical review

Best possible solution:

Retain the shared policy-owner change and complete the existing CI gate before landing.

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

Current main confirms that API-key saves do not widen the model allowlist; the supplied real Gateway integration demonstrates the corresponding after-fix write and a failing negative control.

Is this the best way to solve the issue?

The change uses the existing policy and persistence owners, preserves provider-specific selections, and removes the replaced consent machinery rather than maintaining competing paths.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Post-save provider model access changes intended behavior with a stated reason (047c925: Ask before expanding restrictions and preserve saved credentials independently of the user's model-access choice.)
  • Saved-state versus active-state reporting keeps the original intent (3b7b4be: Distinguish credential persistence, policy persistence, and confirmed Gateway application.)
  • Control UI hidden-provider warning changes intended behavior with a stated reason (afe8191: Explain successful credential saves whose models remain hidden by the effective policy.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned change and clean checkout: Reviewed the introduced merge-base-to-head hunks; the checkout remained clean. (cc64743232ba)
  • Maintainer-approved behavioral tradeoff: The maintainer-authored body explicitly reverses the ask-first default from feat(auth): ask before showing restricted provider models #144468 and accepts that added wildcard entries survive a revert. (cc64743232ba)
  • Shared policy and preserved preferences: The existing policy owner resolves provider identity, preserves lists already naming that provider, updates the effective agent/default owner, and retains deferred legacy-map entries. (src/commands/models/auth-model-policy.ts:60, cc64743232ba)
  • Authority reaches the final write: Every Gateway API-key save now passes current requester authority to the real credential/config writer; supplied execution output covers allowed writes and revocation after the config transform, with unchanged config bytes on rejection. (src/commands/models/auth-api-key.test.ts:899, cc64743232ba)
  • Existing-state compatibility: The supplied real CLI trace preserves exact provider lists and appends only the absent provider wildcard. Stable v2026.10.9 already supports the same wildcard grammar, explicit policy ownership, legacy-map handling, and migration marker; no new stored format is introduced. (src/config/model-policy-allowlist-migration.ts:1, 8b18b5578f66)
  • Internal SDK cutover: The removed login-choice helpers belong to a documented private-local subpath, and their bundled consumers are migrated together; searches found no remaining references to the retired helpers. Public docs: docs/plugins/sdk-subpaths.md. (docs/plugins/sdk-subpaths.md:350, cc64743232ba)

Likely related people:

  • Ayaan Zaidi: Raw commit 047c925 adds src/commands/models/auth-model-policy.ts:25 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 047c925cff7e; files: src/commands/models/auth-model-policy.ts)

PR surface

Source -302, Tests -760, Docs -39, Other -1. Total -1102 across 37 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 11 226 528 -302
Tests 20 379 1139 -760
Docs 5 23 62 -39
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 37 628 1730 -1102

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Improves provider connection under existing operator-managed model restrictions with a bounded policy change.
  • merge-risk: 🚨 compatibility: Credential saves can now persist provider wildcards instead of preserving complete provider exclusion; the maintainer explicitly accepts this behavior and its persistence after revert.
  • merge-risk: 🚨 security-boundary: Credential saves now also widen model visibility; current requester authority is propagated to final writes and exercised under revocation.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • 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.

History

Review history (4 earlier review cycles)
  • reviewed 2026-11-01T03:27:03.963Z sha 5e10e7c :: needs real behavior proof before merge. :: [P1] Bind ordinary browser saves to live requester authority | [P2] Update the save-handler test for the new agent argument
  • reviewed 2026-11-01T04:25:27.461Z sha 5b9ad2c :: needs real behavior proof before merge. :: [P1] Resolve legacy bare refs with the policy owner's provider inference
  • reviewed 2026-11-01T05:19:40.210Z sha 096e23c :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-01T05:30:27.246Z sha cc64743 :: blocked before merge. :: none

Reviewed November 1, 2026, 1:38 AM ET / 05:38 UTC (Revision 5).

obviyus and others added 2 commits November 1, 2026 09:09
The save writes credentials and can widen the model allowlist, so browser saves
without an owner binding now use the request mutation authority too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@obviyus

obviyus commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Nov 1, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 1, 2026
@obviyus
obviyus merged commit 8f606d9 into main Nov 1, 2026
165 checks passed
@obviyus
obviyus deleted the fix/provider-dialog-allow-models branch November 1, 2026 05:49
@obviyus

obviyus commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 8f606d9. Saving provider credentials now adds <provider>/* to the governing model allowlist only when that list names none of the provider's models; exact and narrower lists stay as they are. Every API-key save now also checks live requester authority. Proof: real Gateway key save, real writer revocation chain, and the Team allowlist shape through openclaw models auth paste-api-key (OpenAI and ClawRouter unchanged, particle/* added).

steipete added a commit that referenced this pull request Nov 1, 2026
Remove dead exports left by #190019, #189350, and #190165. Preserve existing auth and repository restoration coverage through the production entry points. Production LOC is unchanged; no runtime behavior or Knip exemptions change.
obviyus added a commit that referenced this pull request Nov 1, 2026
…allowlists (#190112)

## Summary

- **Problem:** `openclaw configure` wrote the model multi-select as exact `provider/model` refs into `agents.defaults.modelPolicy.allow`, and it also copied every pick into the `agents.defaults.models` keys. Three bad outcomes:
  - A fresh install with no allowlist got one just by pressing Enter. Any provider added later was then hidden (the Particle case).
  - Re-running configure for a provider replaced an existing `particle/*` entry (for example, one added by #190019 when a key is saved) with exact refs. New Particle models then disappeared again.
  - The wizard read the legacy model map itself and parsed wildcards with `slice(0, -2)`, so `clawrouter/anthropic/*` never matched its scope.
- **Fix:**
  - **No new allowlists.** Configure never creates an allowlist. It decides this from the saved config, because wizard steps add model metadata that an unmarked in-memory config would read as a legacy allowlist.
  - **Without an allowlist,** the prompt is **Fallback models**. It starts from the primary and its fallbacks, and every pick is saved as a fallback, including picks outside the primary's provider. Model metadata is not preselected.
  - **With an allowlist,** the prompt starts from the models the saved list already allows, wildcards included, through the visibility owner. The selection replaces only that provider's entries, as exact refs.
    - An existing `<provider>/*` stays while every shown model of that provider stays selected.
    - Configure never adds a wildcard on its own, because a picker can show only offered or configured models.
    - Credential saves still add `<provider>/*` through the #190019 owner.
  - **No-catalog text prompt.** When the provider catalog is unavailable, configure falls back to a text prompt. That prompt now starts from the saved allowlist, wildcards included. Before, it started from the model-map keys, so pressing Enter replaced `["openai/*", "anthropic/…"]` with exact OpenAI refs. In fallback-only mode it is labeled **Fallback models** and starts from the fallbacks.
  - **Policy edits leave fallbacks alone.** An unscoped selection with an allowlist edits the saved policy as a whole. It no longer goes through fallback reconciliation, which would have turned `anthropic/*` into a fallback and dropped the working one.
  - **No metadata mirroring.** Picks are no longer copied into `agents.defaults.models`.
  - **One reader and one parser.** The existing-policy read goes through `resolveConfiguredModelPolicyAllow`, the runtime owner, and wildcard parsing goes through `parseModelPolicyWildcardRef`.
  - `applyModelAllowlist` and the seed helper live in `src/flows/model-picker-allowlist.ts`, for the line-cap ratchet.
- **User impact:**
  - Running configure no longer hides providers you add later or drops an existing provider wildcard.
  - Earlier picks are preselected again.
  - Fallback-only picks are saved.

## Evidence

- `pnpm test src/commands/configure.gateway-auth.prompt-auth-config.test.ts src/commands/model-picker.test.ts --maxWorkers=1`: 29 passed, about 25 s wall time (most of it is the shared transform; the tests themselves take about 3 s).
- The new cases fail without the fix:
  - kept wildcard;
  - saved-policy seeding, exact and `nvidia/*` (fails with seeding disabled);
  - no allowlist → unchanged;
  - fallback-only pick outside the primary's provider is saved;
  - fallback-only prompt does not preselect metadata.
- Contract cases:
  - An exact list with every scoped pick stays exact (no widening).
  - A plugin-offered partial scope stays exact.
  - No prior allowlist → none created (`promptAuthConfig`).
- **Upgrade run from v2026.10.9, real CLI.**
  - The published `[email protected]` (8b18b55, run on Node 26.12.1) wrote four stored configs with `openclaw config set --strict-json` and validated them with `openclaw config validate`.
  - The fifth, a legacy unmarked model map, is a pre-marker shape that a release can no longer write. v2026.10.9 validated it.
  - I then drove the candidate `pnpm openclaw configure --section model` (built at 12c7b24) on each file through a pseudo-terminal, with isolated `OPENCLAW_CONFIG_PATH`/`OPENCLAW_STATE_DIR`. Each run: OpenAI → API key (a synthetic test key) → accept the defaults.
  - This machine has no live catalog, so each run took the no-catalog text prompt.

  | Stored shape (written by v2026.10.9) | Prompt | `modelPolicy` after | `model` (primary/fallbacks) | Saved `models` entries |
  |---|---|---|---|---|
  | unrestricted | Fallback models | none (no allowlist created) | unchanged | intact |
  | exact `["openai/gpt-5.5", "anthropic/claude-sonnet-4-6"]` | Allowlist models | unchanged | unchanged | intact |
  | wildcard `["openai/*", "anthropic/claude-sonnet-4-6"]` | Allowlist models | unchanged | unchanged | intact |
  | `["openai/gpt-5.5", "anthropic/*"]` + fallback `anthropic/claude-sonnet-4-6` | Allowlist models | unchanged | unchanged (no `anthropic/*` fallback) | intact |
  | legacy unmarked map (2 keys, no policy; validated by v2026.10.9) | Allowlist models | materialized as the same 2 refs | unchanged | intact |

  Every saved `agents.defaults.models` entry kept its value. The only additions are model metadata that the OpenAI auth setup and model setup write, for example `openai/gpt-6-astra`; configure no longer mirrors picks there.

- Unit coverage of the same shapes: the default policy (none/agent/shared `promptAuthConfig` cases), the selected agent's projected policy, and the legacy map refs carried into the explicit policy with the map byte-equal.
- `OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 pnpm check:changed`: green.
- No overlap with Pash/Sarah changes.

## Merge danger

A two-way door. No migration and no schema change; a revert restores the old wizard behavior. Blast radius: interactive `openclaw configure` and the model step of onboarding. A user who relied on configure to create a first allowlist must now set `modelPolicy.allow` explicitly. Existing allowlists are still edited, never widened to a wildcard.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 1, 2026
…olicies (#190036)

## Summary

- **Problem:** `modelPolicy.allow` had two grammars under one name. Operator roles accepted a model-name prefix such as `openai/gpt-*`; agent policies rejected it. Role matching used a separate glob matcher, and five other callers detected wildcards by hand (`endsWith("/*")`, `slice(0, -2)`, `startsWith`). The copies agreed today but could drift, for example on padded refs like `"openai / *"`.
- **Fix:** `src/config/model-policy-ref.ts` now owns one parser (`parseModelPolicyWildcardRef`: `provider/*`, `provider/namespace/*`, `provider/family-*`) and one matcher (`modelPolicyWildcardMatches`). Role policy matching, config validation, `isModelKeyAllowedBySet`, configured model entries, alias candidates, `models status` and the legacy Codex wildcard migration use them. The role-only parser, the role glob matcher and the role-only validation branch are deleted.
- **User impact:** agent policies now also accept model-name prefixes such as `openai/gpt-*`. Existing agent and role configs keep their meaning; no config is invalidated.

## Evidence

**Live Gateway, real operator-role identity.** Setup:
- Candidate Gateway (`openclaw.mjs gateway run` from this branch) on an isolated HOME, state and loopback port.
- `gateway.auth.mode: "trusted-proxy"` with a loopback proxy that sets `x-forwarded-user: [email protected]`.
- `gateway.roles.default: "limited"`, with `modelPolicy: { allow: ["fixture/echo-*"], deny: ["fixture/echo-restricted*"] }`.
- A loopback fake OpenAI-completions provider that logs every request.
- The client is the real `GatewayClient` (webchat mode, device identity, no token), so the proxy-verified user is its only credential.

```text
(1)+(2) sessions.patch fixture/echo-restricted       -> FORBIDDEN "Your operator role cannot use this model…"
        sessions.patch fixture/echo-restricted-mini  -> FORBIDDEN
        sessions.patch fixture/other-x               -> FORBIDDEN (outside allow)
        sessions.patch fixture/echo-main             -> ok
        agent run on that session                    -> status ok
        provider log: POST /v1/chat/completions model=echo-main   (only request; no echo-restricted* or other-x call)
(3)     live reload narrows the role: deny += "fixture/echo-main*"
        [reload] config change detected; evaluating reload (gateway.roles.definitions.limited.modelPolicy.deny)
        next agent run on the pinned echo-main session -> status error "Your operator role cannot use this model…"
        provider requests before=2 after=2 (no new provider call)
(4)     upgrade cell, same state directory:
        published [email protected] Gateway writes and serves the role config:
          echo-restricted / echo-restricted-mini / other-x -> FORBIDDEN, echo-main -> ok, provider called with echo-main
        stop; candidate `doctor --fix` (agent DB schema 25 -> 39, role config untouched); candidate Gateway on that state:
          identical sessions.patch decisions (diff: IDENTICAL), provider called only with echo-main
```

**Role policy compatibility (main vs this PR, real owner code).** One script prepared role policies through `prepareOperatorModelPolicy` on an `origin/main` checkout and on this branch. It evaluated `allows()` for 12 models under 5 policies (family deny `vendor/restricted-v1*`, family allow `vendor/gpt-*`, nested `router/anthropic/*`, padded ` VENDOR / gpt-* ` with deny `vendor/gpt-5.5*`, inherited-source deny `vendor/restricted-*`). It also captured the `main` snapshots with `captureOperatorModelPolicySnapshot` and restored them on this branch with `restoreOperatorModelPolicySnapshot`.

```text
prepared decisions, main vs PR:           0 differences / 60
main snapshots restored on PR vs main:    0 differences / 60
familyDeny on PR: vendor/restricted-v1 false, vendor/restricted-v1-mini false, vendor/restricted-v2 true, vendor/primary true
```

**Admission proof.** New case in `src/gateway/sessions-patch.operator-model-policy.test.ts` drives `projectSessionsPatchEntry` (the `sessions.patch` owner that admits a model before any run or provider request) with role policy `allow: ["fixture/*"]`, `deny: ["fixture/restricted-v1*"]`, once with the freshly prepared policy and once with a policy restored from its captured snapshot:

```text
fixture/restricted-v1       -> FORBIDDEN "operator role cannot use this model"
fixture/restricted-v1-mini  -> FORBIDDEN
fixture/allowed             -> ok; after the operator source is revoked, its commit guard -> FORBIDDEN
```

It fails with this PR's first matcher (strict length check) and passes now. Rebased onto #190019; `pnpm check:changed` and the auth-model-policy suites pass on the rebased head.

Role admission suites that consume this predicate before provider calls also pass on this branch: model fallback, CLI runner, isolated completion and image fallback operator-policy suites, plus `operator-model-policy.test.ts` (65 tests).

- New regression in `model-visibility-policy.test.ts` (agent policy `openai/gpt-5.6-*` allows `gpt-5.6-sol`, not `gpt-5.5`) fails on `origin/main` and passes here.
- Validation table adds `openai/gpt-*` (valid for agents) and rejects `openai/gpt *` and `*`.
- Focused suites pass: model visibility, config model-ref validation, operator model policy, role mutation authority, `models status`, legacy Codex model migration, configured model entries, model selection.
- Role compatibility: `modelPolicyWildcardMatches` is a plain prefix test, the same set the old role glob (`^prefix.*$`) accepted, because the parser forbids any other `*`. A new operator-policy regression (`allow: ["vendor/*"]`, `deny: ["vendor/restricted-v1*"]` must deny `vendor/restricted-v1` itself) fails on the first head of this PR and passes now. Stored role snapshots keep the same canonical wildcard keys, so restored policies match as before.
- `pnpm check:changed` (dead-code step skipped) passes; config docs baseline regenerated.

## Merge danger

Two-way door: no stored state or migration; a revert restores the narrower agent grammar. Blast radius: model policy matching for agents and operator roles. Role semantics are unchanged (same prefix rule, same normalized `provider/model` key).

Pash/Sarah check: Sarah's commits on these files (#161609, #162335, #161048, #161004, #159363, #158307, #158703, #151176, #123875) touch Agents API, Codex and Slack config help/validation entries. This PR edits only model-policy wildcard parsing, matching and help text, so their behavior is unchanged.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

## What Problem This Solves

Adding a provider did not make it usable when a model allowlist (`modelPolicy.allow`) existed. On the Team server, saving a Particle API key in **Settings → Models → Connect provider** succeeded, but no Particle model appeared in the model picker: the allowlist hid them all. Sign-in flows (CLI, chat `/login`, Telegram, Control UI wizard) asked **Show all &lt;Provider&gt; models / Keep current restrictions** with Keep as the default. The API-key save path skipped even that, and openclaw#189917 only added a text warning that told the user to edit config by hand.

## Fix

Saving credentials for a provider is now the request to use its models. When the allowlist that governs the agent hides **every** model of that provider, the save adds `<provider>/*` to that allowlist, through the existing model-policy owner (`src/commands/models/auth-model-policy.ts`):

- per-agent `agents.entries.<id>.modelPolicy.allow` when the agent sets its own policy, otherwise `agents.defaults.modelPolicy.allow`;
- an unmigrated legacy `agents.defaults.models` allowlist gets the wildcard key, so none of its models is dropped.

Nothing changes when there is no allowlist, or when the allowlist already names some of the provider's models (an exact ref such as `openai/gpt-x`, or a narrower wildcard such as `clawrouter/anthropic/*`). The policy owner decides that: the check reads providers from `createModelVisibilityPolicy(...).allowedKeys`, which resolves exact refs, aliases and bare legacy refs (inferring their provider from configured provider rows) the same way the picker does. A deliberate exact list is never widened.

Paths:

- API key / token save (`models.authSetApiKey`, `openclaw models auth paste-api-key`, `paste-token`): the wildcard is added in the same config write as the credential's auth profile.
- Sign-in (`openclaw models auth login`, Control UI wizard, chat `/login`, Telegram `/login`): after the credential is saved, one write adds the wildcard. The login result carries `modelAccess: { message, applied }`; chat and Telegram append "Added `<provider>/*` to allowed models." to the completion message; the Control UI wizard reports an unconfirmed apply as before.

Removed: the post-save select prompt, the deferred `onModelAccessRequested` request, `offerProviderLoginModelAccess` / `answerProviderLoginModelAccess`, the `/login access` and `/login choice` model-access commands, `createLoginChoicePrompt`, `ProviderModelPolicyChangedError`, and the openclaw#189917 Control UI warning. `provider-auth-login-flow-runtime` is a private-local SDK subpath (docs/plugins/sdk-subpaths.md), so its only consumers are bundled (core chat `/login`, Telegram), migrated here.

Authority: every `models.authSetApiKey` save now checks live requester authority (`readGatewayRequestMutationAuthority`, the guard `config.patch` uses) before its credential and config writes. Before, browser saves without `expectedOwnerId` passed no guard; the save now also widens the allowlist, so a requester whose connection or scopes end mid-save cannot commit it. Owner-bound CLI saves keep their owner check and add the same requester check.

Plugin setup defaults still cannot change restrictions (`withoutProviderModelPolicy` is unchanged); only the credential save does.

This reverses the ask-first default from openclaw#144468 by maintainer decision.

No undo button: the `models.authSetApiKey` result has no field for the change, and adding one is a protocol change; the change is a single visible `provider/*` allowlist entry.

## User Impact

Add a provider key or sign in → its models show in the model picker, even under an existing allowlist that did not mention the provider. Operators who listed specific models of that provider keep exactly their list.

## Evidence

Real Gateway, real config write (`src/gateway/server-methods/models-auth-api-key.integration.test.ts`): config `agents.defaults.modelPolicy.allow: ["other/*"]`, `models.authSetApiKey` for `fixture` → saved config `["other/*", "fixture/*"]`. Negative control: with the new line disabled, the test fails `expected [ 'other/*' ] to deeply equal [ 'other/*', 'fixture/*' ]`.

Policy owner (`src/commands/models/auth-model-policy.test.ts`, real config file):

- per-agent policy widened, defaults untouched;
- no allowlist / provider already allowed → config bytes unchanged;
- allowlist with exact `sample/one`, `sample/two` → unchanged; with `sample/family/*` → unchanged (both fail when the check is reverted to "literal `sample/*` missing");
- deferred legacy map keeps `existing-model` and gains `sample/*`;
- migrated model map is not treated as an allowlist;
- authority revoked during the writer's preflight → no write.

Sign-in end to end against a real plugin and config (`src/commands/models.auth.provider-resolution.test.ts`): `access`, `access-legacy`, `access-legacy-set-default` cases save the credential, add `authstore-proof/*` with no prompt, and log the notice.

Real key writer under revocation (`src/commands/models/auth-api-key.test.ts`, real auth store and config file): with an allowlist present, authority revoked inside the config write leaves the config bytes unchanged (no auth binding, no `sample/*`); unrevoked, the same write saves the binding and `["other/*", "sample/*"]`.

Gateway-to-writer revocation chain (`src/commands/models/auth-api-key.test.ts`): the real `models.authSetApiKey` handler, its `readGatewayRequestMutationAuthority` guard and the real key/config writer, with the requester's authority ending inside the config write. The RPC fails with "Gateway requester authority changed"; the config file bytes are unchanged (no auth binding, allowlist still `["other/*"]`). The key itself committed earlier, while the requester was still authorized, and stays saved. Negative control: with the handler guard replaced by a no-op, the test fails. Run output (synthetic keys only):

```
✓ |commands| src/commands/models/auth-api-key.test.ts > checks requester authority after credential commit (revoked=false) 1511ms
✓ |commands| src/commands/models/auth-api-key.test.ts > checks requester authority after credential commit (revoked=true) 914ms
✓ |commands| src/commands/models/auth-api-key.test.ts > checks requester authority after config transform (revoked=false) 1392ms
✓ |commands| src/commands/models/auth-api-key.test.ts > checks requester authority after config transform (revoked=true) 1067ms
✓ |commands| src/commands/models/auth-api-key.test.ts > models.authSetApiKey writes no binding or allowlist once the requester is revoked 977ms
Tests  5 passed | 42 skipped (47)
```

Upgrade compatibility: no stored schema or config shape changes. Existing configs load as before and keep working: explicit `modelPolicy.allow` (defaults and per-agent), unmigrated legacy `agents.defaults.models` allowlists (wildcard added as a map key, every existing model kept), migrated maps with the `modelPolicyAllowlist` marker (not treated as an allowlist), and configs without an allowlist (never written). Each case runs against a real config file in `auth-model-policy.test.ts` and `models.auth.provider-resolution.test.ts`. The removed chat model-access questions were in-memory only, so no stored state refers to them.

Existing data, real CLI entry point: a temporary state directory seeded with the Team server's pre-change allowlist shape (exact `openai/...` refs plus `clawrouter/anthropic/...` refs, and a legacy `agents.defaults.models` map), then `openclaw models auth paste-api-key` from this branch for three providers (synthetic keys, the first run's output trimmed to the resulting list):

```
Team pre-change allowlist (exact openai refs + clawrouter/anthropic refs), no Gateway running
== openclaw models auth paste-api-key --provider openai
allow = ['openai/gpt-6-luna', 'openai/gpt-6-astra', 'openai/gpt-daybreak-blue-latest', 'openai/gpt-daybreak-red-latest', 'openai/gpt-6.1-sol', 'clawrouter/anthropic/claude-fable-5-1', 'clawrouter/anthropic/claude-opus-5-5']
== openclaw models auth paste-api-key --provider particle
Auth profile: particle:manual (particle/api_key)
Added particle/* to allowed models.
allow = ['openai/gpt-6-luna', 'openai/gpt-6-astra', 'openai/gpt-daybreak-blue-latest', 'openai/gpt-daybreak-red-latest', 'openai/gpt-6.1-sol', 'clawrouter/anthropic/claude-fable-5-1', 'clawrouter/anthropic/claude-opus-5-5', 'particle/*']
== openclaw models auth paste-api-key --provider clawrouter
Auth profile: clawrouter:manual (clawrouter/api_key)
allow = ['openai/gpt-6-luna', 'openai/gpt-6-astra', 'openai/gpt-daybreak-blue-latest', 'openai/gpt-daybreak-red-latest', 'openai/gpt-6.1-sol', 'clawrouter/anthropic/claude-fable-5-1', 'clawrouter/anthropic/claude-opus-5-5', 'particle/*']
```

OpenAI and ClawRouter keep the operator's exact lists; only Particle, which the list did not mention, gains `particle/*`.

Bare legacy ref (`auth-model-policy.test.ts`): legacy map `{ tiny: {} }` with a configured `sample` provider that has `tiny` → saving a `sample` credential leaves config unchanged (fails against the earlier `DEFAULT_PROVIDER` parse).

Requester authority (`src/gateway/server-methods/models-auth-status.set-api-key.test-support.ts`): authority ends during the save → the RPC fails with "Gateway requester authority changed" and the writer's `assertCurrent` throws before commit. Negative control: with the handler's default guard replaced by a no-op, the test fails.

Surface tests: chat `/login` and Telegram completion messages include the notice; Control UI wizard reports unconfirmed apply; mocked-Gateway Control UI E2E (`model-provider-login.e2e.test.ts`) passes.

Control UI, mocked Gateway, policy `allow: ["openai/*"]`, save a Particle key:

Before (main, openclaw#189917): the dialog stays open with a config-editing instruction.

![Before: dialog tells the user to edit modelPolicy.allow](https://github.com/user-attachments/assets/793cafbe-5e2d-4be0-b111-a95265d6db8a)

After: the Gateway widens the policy during the save; the dialog closes like any successful save.

![After: dialog closes after save](https://github.com/user-attachments/assets/480dced1-3ec3-4fed-b092-c2b6842ba31b)

Commands:

- `pnpm test src/commands/models/auth-model-policy.test.ts --maxWorkers=1`: 7 passed.
- `pnpm test src/gateway/server-methods/models-auth-api-key.integration.test.ts --maxWorkers=1`: 1 passed (~12.5 s, real Gateway, existing test extended; no new boot).
- `pnpm test src/commands/models/auth.test.ts src/commands/models.auth.provider-resolution.test.ts --maxWorkers=1`: 80 passed.
- Chat/Gateway/Telegram/UI suites: passed.
- `pnpm tsgo:core`, `pnpm tsgo:extensions`, `OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 pnpm check:changed`.

No overlap with Pash/Sarah changes.

Merge danger: one-way for configs: a credential save can now write `<provider>/*` into a model allowlist. A revert stops new writes but does not remove entries already added. Blast radius: operators who rely on an allowlist that does not mention a provider to keep that provider hidden after someone adds its credentials. Only admins can save credentials.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 2, 2026
Remove dead exports left by openclaw#190019, openclaw#189350, and openclaw#190165. Preserve existing auth and repository restoration coverage through the production entry points. Production LOC is unchanged; no runtime behavior or Knip exemptions change.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 2, 2026
…allowlists (openclaw#190112)

## Summary

- **Problem:** `openclaw configure` wrote the model multi-select as exact `provider/model` refs into `agents.defaults.modelPolicy.allow`, and it also copied every pick into the `agents.defaults.models` keys. Three bad outcomes:
  - A fresh install with no allowlist got one just by pressing Enter. Any provider added later was then hidden (the Particle case).
  - Re-running configure for a provider replaced an existing `particle/*` entry (for example, one added by openclaw#190019 when a key is saved) with exact refs. New Particle models then disappeared again.
  - The wizard read the legacy model map itself and parsed wildcards with `slice(0, -2)`, so `clawrouter/anthropic/*` never matched its scope.
- **Fix:**
  - **No new allowlists.** Configure never creates an allowlist. It decides this from the saved config, because wizard steps add model metadata that an unmarked in-memory config would read as a legacy allowlist.
  - **Without an allowlist,** the prompt is **Fallback models**. It starts from the primary and its fallbacks, and every pick is saved as a fallback, including picks outside the primary's provider. Model metadata is not preselected.
  - **With an allowlist,** the prompt starts from the models the saved list already allows, wildcards included, through the visibility owner. The selection replaces only that provider's entries, as exact refs.
    - An existing `<provider>/*` stays while every shown model of that provider stays selected.
    - Configure never adds a wildcard on its own, because a picker can show only offered or configured models.
    - Credential saves still add `<provider>/*` through the openclaw#190019 owner.
  - **No-catalog text prompt.** When the provider catalog is unavailable, configure falls back to a text prompt. That prompt now starts from the saved allowlist, wildcards included. Before, it started from the model-map keys, so pressing Enter replaced `["openai/*", "anthropic/…"]` with exact OpenAI refs. In fallback-only mode it is labeled **Fallback models** and starts from the fallbacks.
  - **Policy edits leave fallbacks alone.** An unscoped selection with an allowlist edits the saved policy as a whole. It no longer goes through fallback reconciliation, which would have turned `anthropic/*` into a fallback and dropped the working one.
  - **No metadata mirroring.** Picks are no longer copied into `agents.defaults.models`.
  - **One reader and one parser.** The existing-policy read goes through `resolveConfiguredModelPolicyAllow`, the runtime owner, and wildcard parsing goes through `parseModelPolicyWildcardRef`.
  - `applyModelAllowlist` and the seed helper live in `src/flows/model-picker-allowlist.ts`, for the line-cap ratchet.
- **User impact:**
  - Running configure no longer hides providers you add later or drops an existing provider wildcard.
  - Earlier picks are preselected again.
  - Fallback-only picks are saved.

## Evidence

- `pnpm test src/commands/configure.gateway-auth.prompt-auth-config.test.ts src/commands/model-picker.test.ts --maxWorkers=1`: 29 passed, about 25 s wall time (most of it is the shared transform; the tests themselves take about 3 s).
- The new cases fail without the fix:
  - kept wildcard;
  - saved-policy seeding, exact and `nvidia/*` (fails with seeding disabled);
  - no allowlist → unchanged;
  - fallback-only pick outside the primary's provider is saved;
  - fallback-only prompt does not preselect metadata.
- Contract cases:
  - An exact list with every scoped pick stays exact (no widening).
  - A plugin-offered partial scope stays exact.
  - No prior allowlist → none created (`promptAuthConfig`).
- **Upgrade run from v2026.10.9, real CLI.**
  - The published `[email protected]` (8b18b55, run on Node 26.12.1) wrote four stored configs with `openclaw config set --strict-json` and validated them with `openclaw config validate`.
  - The fifth, a legacy unmarked model map, is a pre-marker shape that a release can no longer write. v2026.10.9 validated it.
  - I then drove the candidate `pnpm openclaw configure --section model` (built at 12c7b24) on each file through a pseudo-terminal, with isolated `OPENCLAW_CONFIG_PATH`/`OPENCLAW_STATE_DIR`. Each run: OpenAI → API key (a synthetic test key) → accept the defaults.
  - This machine has no live catalog, so each run took the no-catalog text prompt.

  | Stored shape (written by v2026.10.9) | Prompt | `modelPolicy` after | `model` (primary/fallbacks) | Saved `models` entries |
  |---|---|---|---|---|
  | unrestricted | Fallback models | none (no allowlist created) | unchanged | intact |
  | exact `["openai/gpt-5.5", "anthropic/claude-sonnet-4-6"]` | Allowlist models | unchanged | unchanged | intact |
  | wildcard `["openai/*", "anthropic/claude-sonnet-4-6"]` | Allowlist models | unchanged | unchanged | intact |
  | `["openai/gpt-5.5", "anthropic/*"]` + fallback `anthropic/claude-sonnet-4-6` | Allowlist models | unchanged | unchanged (no `anthropic/*` fallback) | intact |
  | legacy unmarked map (2 keys, no policy; validated by v2026.10.9) | Allowlist models | materialized as the same 2 refs | unchanged | intact |

  Every saved `agents.defaults.models` entry kept its value. The only additions are model metadata that the OpenAI auth setup and model setup write, for example `openai/gpt-6-astra`; configure no longer mirrors picks there.

- Unit coverage of the same shapes: the default policy (none/agent/shared `promptAuthConfig` cases), the selected agent's projected policy, and the legacy map refs carried into the explicit policy with the map byte-equal.
- `OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 pnpm check:changed`: green.
- No overlap with Pash/Sarah changes.

## Merge danger

A two-way door. No migration and no schema change; a revert restores the old wizard behavior. Blast radius: interactive `openclaw configure` and the model step of onboarding. A user who relied on configure to create a first allowlist must now set `modelPolicy.allow` explicitly. Existing allowlists are still edited, never widened to a wildcard.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 2, 2026
…olicies (openclaw#190036)

## Summary

- **Problem:** `modelPolicy.allow` had two grammars under one name. Operator roles accepted a model-name prefix such as `openai/gpt-*`; agent policies rejected it. Role matching used a separate glob matcher, and five other callers detected wildcards by hand (`endsWith("/*")`, `slice(0, -2)`, `startsWith`). The copies agreed today but could drift, for example on padded refs like `"openai / *"`.
- **Fix:** `src/config/model-policy-ref.ts` now owns one parser (`parseModelPolicyWildcardRef`: `provider/*`, `provider/namespace/*`, `provider/family-*`) and one matcher (`modelPolicyWildcardMatches`). Role policy matching, config validation, `isModelKeyAllowedBySet`, configured model entries, alias candidates, `models status` and the legacy Codex wildcard migration use them. The role-only parser, the role glob matcher and the role-only validation branch are deleted.
- **User impact:** agent policies now also accept model-name prefixes such as `openai/gpt-*`. Existing agent and role configs keep their meaning; no config is invalidated.

## Evidence

**Live Gateway, real operator-role identity.** Setup:
- Candidate Gateway (`openclaw.mjs gateway run` from this branch) on an isolated HOME, state and loopback port.
- `gateway.auth.mode: "trusted-proxy"` with a loopback proxy that sets `x-forwarded-user: [email protected]`.
- `gateway.roles.default: "limited"`, with `modelPolicy: { allow: ["fixture/echo-*"], deny: ["fixture/echo-restricted*"] }`.
- A loopback fake OpenAI-completions provider that logs every request.
- The client is the real `GatewayClient` (webchat mode, device identity, no token), so the proxy-verified user is its only credential.

```text
(1)+(2) sessions.patch fixture/echo-restricted       -> FORBIDDEN "Your operator role cannot use this model…"
        sessions.patch fixture/echo-restricted-mini  -> FORBIDDEN
        sessions.patch fixture/other-x               -> FORBIDDEN (outside allow)
        sessions.patch fixture/echo-main             -> ok
        agent run on that session                    -> status ok
        provider log: POST /v1/chat/completions model=echo-main   (only request; no echo-restricted* or other-x call)
(3)     live reload narrows the role: deny += "fixture/echo-main*"
        [reload] config change detected; evaluating reload (gateway.roles.definitions.limited.modelPolicy.deny)
        next agent run on the pinned echo-main session -> status error "Your operator role cannot use this model…"
        provider requests before=2 after=2 (no new provider call)
(4)     upgrade cell, same state directory:
        published [email protected] Gateway writes and serves the role config:
          echo-restricted / echo-restricted-mini / other-x -> FORBIDDEN, echo-main -> ok, provider called with echo-main
        stop; candidate `doctor --fix` (agent DB schema 25 -> 39, role config untouched); candidate Gateway on that state:
          identical sessions.patch decisions (diff: IDENTICAL), provider called only with echo-main
```

**Role policy compatibility (main vs this PR, real owner code).** One script prepared role policies through `prepareOperatorModelPolicy` on an `origin/main` checkout and on this branch. It evaluated `allows()` for 12 models under 5 policies (family deny `vendor/restricted-v1*`, family allow `vendor/gpt-*`, nested `router/anthropic/*`, padded ` VENDOR / gpt-* ` with deny `vendor/gpt-5.5*`, inherited-source deny `vendor/restricted-*`). It also captured the `main` snapshots with `captureOperatorModelPolicySnapshot` and restored them on this branch with `restoreOperatorModelPolicySnapshot`.

```text
prepared decisions, main vs PR:           0 differences / 60
main snapshots restored on PR vs main:    0 differences / 60
familyDeny on PR: vendor/restricted-v1 false, vendor/restricted-v1-mini false, vendor/restricted-v2 true, vendor/primary true
```

**Admission proof.** New case in `src/gateway/sessions-patch.operator-model-policy.test.ts` drives `projectSessionsPatchEntry` (the `sessions.patch` owner that admits a model before any run or provider request) with role policy `allow: ["fixture/*"]`, `deny: ["fixture/restricted-v1*"]`, once with the freshly prepared policy and once with a policy restored from its captured snapshot:

```text
fixture/restricted-v1       -> FORBIDDEN "operator role cannot use this model"
fixture/restricted-v1-mini  -> FORBIDDEN
fixture/allowed             -> ok; after the operator source is revoked, its commit guard -> FORBIDDEN
```

It fails with this PR's first matcher (strict length check) and passes now. Rebased onto openclaw#190019; `pnpm check:changed` and the auth-model-policy suites pass on the rebased head.

Role admission suites that consume this predicate before provider calls also pass on this branch: model fallback, CLI runner, isolated completion and image fallback operator-policy suites, plus `operator-model-policy.test.ts` (65 tests).

- New regression in `model-visibility-policy.test.ts` (agent policy `openai/gpt-5.6-*` allows `gpt-5.6-sol`, not `gpt-5.5`) fails on `origin/main` and passes here.
- Validation table adds `openai/gpt-*` (valid for agents) and rejects `openai/gpt *` and `*`.
- Focused suites pass: model visibility, config model-ref validation, operator model policy, role mutation authority, `models status`, legacy Codex model migration, configured model entries, model selection.
- Role compatibility: `modelPolicyWildcardMatches` is a plain prefix test, the same set the old role glob (`^prefix.*$`) accepted, because the parser forbids any other `*`. A new operator-policy regression (`allow: ["vendor/*"]`, `deny: ["vendor/restricted-v1*"]` must deny `vendor/restricted-v1` itself) fails on the first head of this PR and passes now. Stored role snapshots keep the same canonical wildcard keys, so restored policies match as before.
- `pnpm check:changed` (dead-code step skipped) passes; config docs baseline regenerated.

## Merge danger

Two-way door: no stored state or migration; a revert restores the narrower agent grammar. Blast radius: model policy matching for agents and operator roles. Role semantics are unchanged (same prefix rule, same normalized `provider/model` key).

Pash/Sarah check: Sarah's commits on these files (openclaw#161609, openclaw#162335, openclaw#161048, openclaw#161004, openclaw#159363, openclaw#158307, openclaw#158703, openclaw#151176, openclaw#123875) touch Agents API, Codex and Slack config help/validation entries. This PR edits only model-policy wildcard parsing, matching and help text, so their behavior is unchanged.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
ivankuznetsov added a commit to ivankuznetsov/openclaw that referenced this pull request Nov 20, 2026
Conflicts: src/commands/models/auth.ts, auth.test.ts and
src/plugin-sdk/provider-auth-login-flow-runtime.ts. Upstream openclaw#190019
replaced the post-login model-access consent with allowLoginProviderModels;
a harness sign-in that stages its runtime policy now takes that path too, and
the login result carries both modelAccess and stagedRuntimePolicy. The
consent regression is ported to assert the provider wildcard instead.
Upstream folded auth-authority.test-support into auth.test.ts, so that
import is dropped; auth.test.ts gets a max-lines override for the staging
tests that share its fixture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui channel: telegram Channel integration: telegram commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant