Skip to content

Commit df559c3

Browse files
fix(agents): stored auth profile order is ignored when resolving CLI runtime aliases (#129165)
* fix(agents): honor the stored auth profile order when resolving CLI runtime aliases `resolveCliRuntimeFromAuthProfile` built its ordered profile list from `cfg.auth.order` alone, and `RuntimeAuthAliasParams` carried no auth store at all, so the order an operator sets through `models auth order set` never reached CLI runtime alias resolution. The canonical sibling resolver, `resolveAuthProfileOrderWithMetadata`, already reads the stored order first and falls back to config, so the two disagreed about the same question. With no config `auth.order` and two profiles sharing a provider auth key, the ordered list came out empty and the resolver fell through to its "exactly one compatible profile" branch, returning undefined. The gateway then reported model availability and picked the turn's execution backend as if the reorder had not happened, and no restart cleared it because the store was never read on this path. Rather than re-deriving the precedence at the call site, extract it: the stored-first explicit-order resolution moves out of `resolveAuthProfileOrderWithMetadata` into `resolveExplicitAuthOrderSelection`, and alias routing becomes its second consumer. Both now resolve the order through one implementation, across normalized provider keys, so they cannot drift apart again. The store is read from the lifecycle-published runtime snapshot for the requested agent and its declared inherited owner, matching how prepared model catalog and registry resolve the same pair; no new snapshot API and no SQLite reopen on request paths. An authored stored order also owns selection, so it suppresses the unique-compatible-profile fallback the way the canonical resolver does. Tests cover stored-order-only selection, stored-over-config precedence, non-normalized stored keys, inheritance from the main agent, authoritative empty orders with a control for the fallback that must survive, and the unchanged config-only path. * fix(agents): align runtime routing with stored auth selection Share stored-over-config precedence, preserve stale-profile repair, and route explicitly selected stored credentials without config metadata. Remove unreachable OpenAI order-alias merging. Co-authored-by: masatohoshino <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent d692e98 commit df559c3

5 files changed

Lines changed: 247 additions & 103 deletions

File tree

‎docs/cli/models.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ Notes:
199199
- `paste-token --expires-in <duration>` stores an absolute token expiry from a relative duration such as `365d` or `12h`.
200200
- For `openai`, OpenAI API keys and ChatGPT/OAuth token material are different auth shapes. Use `paste-api-key` for `sk-...` OpenAI API keys and `paste-token` only for token auth material.
201201
- Anthropic: `setup-token`/`paste-token` are supported OpenClaw auth paths for `anthropic`, but OpenClaw prefers reusing the Claude CLI (`claude -p`) on the host when it is available.
202-
- `auth order get/set/clear` manages a per-agent auth profile order override for one provider, stored in `auth-state.json` (separate from the `auth.order.<provider>` config key). `set` takes one or more profile ids in priority order; `clear` falls back to config/round-robin ordering.
202+
- `auth order get/set/clear` manages a per-agent auth profile order override for one provider in the SQLite auth store, separate from the `auth.order.<provider>` config key. `set` takes one or more profile ids in priority order. The stored order takes precedence over config for profile selection and CLI runtime routing; `clear` falls back to config/round-robin ordering.
203203

204204
## Related
205205

‎docs/concepts/model-failover.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,9 @@ Profiles live in the per-agent `openclaw-agent.sqlite` auth profile store.
117117
When a provider has multiple profiles, OpenClaw chooses an order like this:
118118

119119
<Steps>
120+
<Step title="Stored order override">
121+
The per-agent order set with `openclaw models auth order set --provider <id> <profileIds...>`.
122+
</Step>
120123
<Step title="Explicit config">
121124
`auth.order[provider]` (if set).
122125
</Step>

‎src/agents/auth-profiles/order.ts‎

Lines changed: 30 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,29 @@ export type AuthProfileOrderResolution = {
280280
hasExplicitOrder: boolean;
281281
};
282282

283+
/** Shares stored-over-config order precedence with CLI runtime selection. */
284+
export function resolveExplicitAuthOrderSelection(params: {
285+
storeOrder: AuthProfileStore["order"] | undefined;
286+
configuredOrder: Record<string, string[]> | undefined;
287+
providerKey: string;
288+
providerAuthKey: string;
289+
}): {
290+
order: string[] | undefined;
291+
fromStore: boolean;
292+
} {
293+
const { storeOrder, configuredOrder, providerKey, providerAuthKey } = params;
294+
const stored =
295+
findNormalizedProviderValue(storeOrder, providerAuthKey) ??
296+
findNormalizedProviderValue(storeOrder, providerKey);
297+
return {
298+
order:
299+
stored ??
300+
findNormalizedProviderValue(configuredOrder, providerAuthKey) ??
301+
findNormalizedProviderValue(configuredOrder, providerKey),
302+
fromStore: stored !== undefined,
303+
};
304+
}
305+
283306
/** Resolves ordered usable auth profiles plus whether an explicit order owns selection. */
284307
export function resolveAuthProfileOrderWithMetadata(
285308
params: ResolveAuthProfileOrderParams,
@@ -296,28 +319,13 @@ export function resolveAuthProfileOrderWithMetadata(
296319
// get a fresh error count and are not immediately re-penalized on the
297320
// next transient failure. See #3604.
298321
clearExpiredCooldowns(store, now);
299-
const openAIOrderAliasProvider =
300-
providerAuthKey === OPENAI_CODEX_PROVIDER_ID || providerKey === OPENAI_CODEX_PROVIDER_ID
301-
? OPENAI_PROVIDER_ID
302-
: undefined;
303-
const directStoredOrder =
304-
resolveAuthOrder(store.order, providerAuthKey) ?? resolveAuthOrder(store.order, providerKey);
305-
const aliasStoredOrder = openAIOrderAliasProvider
306-
? resolveAuthOrder(store.order, openAIOrderAliasProvider)
307-
: undefined;
308-
const directConfiguredOrder =
309-
resolveAuthOrder(cfg?.auth?.order, providerAuthKey) ??
310-
resolveAuthOrder(cfg?.auth?.order, providerKey);
311-
const aliasConfiguredOrder = openAIOrderAliasProvider
312-
? resolveAuthOrder(cfg?.auth?.order, openAIOrderAliasProvider)
313-
: undefined;
314-
const directExplicitOrder = directStoredOrder ?? directConfiguredOrder;
315-
const aliasExplicitOrder = aliasStoredOrder ?? aliasConfiguredOrder;
316-
// Stored order repairs are allowed to fall back to live store profiles when
317-
// old setup flows persisted profile ids that no longer exist.
318-
const explicitOrderFromStore =
319-
directStoredOrder !== undefined ||
320-
(directExplicitOrder === undefined && aliasStoredOrder !== undefined);
322+
const { order: explicitOrder, fromStore: explicitOrderFromStore } =
323+
resolveExplicitAuthOrderSelection({
324+
storeOrder: store.order,
325+
configuredOrder: cfg?.auth?.order,
326+
providerKey,
327+
providerAuthKey,
328+
});
321329
const explicitProfiles = cfg?.auth?.profiles
322330
? Object.entries(cfg.auth.profiles)
323331
.filter(([profileId, profile]) =>
@@ -339,25 +347,6 @@ export function resolveAuthProfileOrderWithMetadata(
339347
provider,
340348
providerAuthKey,
341349
});
342-
const nativeStoreProfiles =
343-
openAIOrderAliasProvider && providerAuthKey === OPENAI_CODEX_PROVIDER_ID
344-
? storeProfiles.filter((profileId) =>
345-
isNativeCredentialProviderCompatibleWithAuthProvider({
346-
cfg,
347-
authAliasLookupParams: params.authAliasLookupParams,
348-
providerAuthKey,
349-
credential: store.profiles[profileId],
350-
}),
351-
)
352-
: [];
353-
const explicitOrder =
354-
directExplicitOrder ??
355-
(aliasExplicitOrder
356-
? mergeAliasOrderWithNativeProfiles({
357-
aliasOrder: aliasExplicitOrder,
358-
nativeProfiles: nativeStoreProfiles,
359-
})
360-
: undefined);
361350
const baseOrder =
362351
explicitOrder ?? (explicitProfiles.length > 0 ? explicitProfiles : storeProfiles);
363352
if (baseOrder.length === 0) {
@@ -447,43 +436,6 @@ export function resolveAuthProfileOrder(params: ResolveAuthProfileOrderParams):
447436
return resolveAuthProfileOrderWithMetadata(params).profileIds;
448437
}
449438

450-
function resolveAuthOrder(
451-
order: Record<string, string[]> | undefined,
452-
provider: string,
453-
): string[] | undefined {
454-
return findNormalizedProviderValue(order, provider);
455-
}
456-
457-
function isNativeCredentialProviderCompatibleWithAuthProvider(params: {
458-
cfg?: OpenClawConfig;
459-
authAliasLookupParams?: ProviderAuthAliasLookupParams;
460-
providerAuthKey: string;
461-
credential: AuthProfileCredential | undefined;
462-
}): boolean {
463-
if (!params.credential) {
464-
return false;
465-
}
466-
return (
467-
resolveProviderIdForAuth(params.credential.provider, {
468-
config: params.cfg,
469-
...params.authAliasLookupParams,
470-
}) === params.providerAuthKey
471-
);
472-
}
473-
474-
function mergeAliasOrderWithNativeProfiles(params: {
475-
aliasOrder: string[];
476-
nativeProfiles: string[];
477-
}): string[] {
478-
const nativeIds = new Set(params.nativeProfiles);
479-
const aliasHasNativeProfile = params.aliasOrder.some((profileId) => nativeIds.has(profileId));
480-
return dedupeProfileIds(
481-
aliasHasNativeProfile
482-
? [...params.aliasOrder, ...params.nativeProfiles]
483-
: [...params.nativeProfiles, ...params.aliasOrder],
484-
);
485-
}
486-
487439
function orderProfilesByMode(
488440
order: string[],
489441
store: AuthProfileStore,

‎src/agents/model-runtime-aliases.test.ts‎

Lines changed: 176 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
// Verifies CLI runtime alias resolution and runtime model-ref equivalence.
22
import { afterEach, beforeEach, describe, expect, it } from "vitest";
33
import type { OpenClawConfig } from "../config/types.openclaw.js";
4+
import {
5+
clearRuntimeAuthProfileStoreSnapshots,
6+
setRuntimeAuthProfileStoreSnapshot,
7+
} from "./auth-profiles/runtime-snapshots.js";
8+
import type { AuthProfileStore } from "./auth-profiles/types.js";
49
import { testing as cliBackendsTesting } from "./cli-backends.test-support.js";
510
import {
611
createModelPickerVisibleProviderPredicate,
@@ -39,17 +44,21 @@ function resolveCliRuntimeExecutionProvider(
3944

4045
function createAnthropicAuthConfig(params: {
4146
order?: string[];
47+
orderKey?: string;
48+
onlyCliProfile?: boolean;
4249
models?: NonNullable<NonNullable<OpenClawConfig["agents"]>["defaults"]>["models"];
4350
}): OpenClawConfig {
4451
// Auth order controls whether Anthropic execution is direct API or Claude
4552
// CLI-backed when no explicit runtime policy overrides it.
4653
return {
4754
auth: {
48-
order: params.order ? { anthropic: params.order } : undefined,
49-
profiles: {
50-
"anthropic:api": { provider: "anthropic", mode: "api_key" },
51-
"anthropic:claude-cli": { provider: "claude-cli", mode: "oauth" },
52-
},
55+
order: params.order ? { [params.orderKey ?? "anthropic"]: params.order } : undefined,
56+
profiles: params.onlyCliProfile
57+
? { "anthropic:claude-cli": { provider: "claude-cli", mode: "oauth" } }
58+
: {
59+
"anthropic:api": { provider: "anthropic", mode: "api_key" },
60+
"anthropic:claude-cli": { provider: "claude-cli", mode: "oauth" },
61+
},
5362
},
5463
agents: {
5564
defaults: {
@@ -83,6 +92,168 @@ describe("resolveCliRuntimeExecutionProvider", () => {
8392

8493
afterEach(() => {
8594
cliBackendsTesting.resetDepsForTest();
95+
clearRuntimeAuthProfileStoreSnapshots();
96+
});
97+
98+
function seedStoredAuthOrder(
99+
order: string[],
100+
providerKey = "anthropic",
101+
profiles: AuthProfileStore["profiles"] = {},
102+
): void {
103+
setRuntimeAuthProfileStoreSnapshot({
104+
version: 1,
105+
profiles,
106+
order: { [providerKey]: order },
107+
});
108+
}
109+
110+
it("honors a stored auth order when config declares none", () => {
111+
// `models auth order set` writes the persisted store, not the config file.
112+
// With no config order the resolver used to build an empty ordered list and
113+
// fall through to the "exactly one compatible profile" branch, which returns
114+
// undefined whenever two profiles share the provider auth key.
115+
seedStoredAuthOrder(["anthropic:claude-cli"]);
116+
expect(
117+
resolveCliRuntimeExecutionProvider({
118+
cfg: createAnthropicAuthConfig({}),
119+
provider: "anthropic",
120+
modelId: "opus-4.7",
121+
}),
122+
).toBe("claude-cli");
123+
});
124+
125+
it.each(["order", "pin"])(
126+
"routes a stored CLI profile selected by %s without config metadata",
127+
(selection) => {
128+
seedStoredAuthOrder(selection === "order" ? ["anthropic:claude-cli"] : [], "anthropic", {
129+
"anthropic:claude-cli": {
130+
type: "oauth",
131+
provider: "claude-cli",
132+
access: "test-access",
133+
refresh: "test-refresh",
134+
expires: Date.now() + 60_000,
135+
},
136+
});
137+
expect(
138+
resolveCliRuntimeExecutionProvider({
139+
provider: "anthropic",
140+
modelId: "opus-4.7",
141+
authProfileId: selection === "pin" ? "anthropic:claude-cli" : undefined,
142+
}),
143+
).toBe("claude-cli");
144+
},
145+
);
146+
147+
it("matches a stored order key that is not already canonically normalized", () => {
148+
// Persisted state only lowercases provider keys, and the canonical resolver
149+
// looks the order up through normalized provider matching rather than an exact
150+
// key hit, so an un-normalized stored key must still beat the config order.
151+
seedStoredAuthOrder(["anthropic:claude-cli"], "Anthropic");
152+
expect(
153+
resolveCliRuntimeExecutionProvider({
154+
cfg: createAnthropicAuthConfig({ order: ["anthropic:api"] }),
155+
provider: "anthropic",
156+
modelId: "opus-4.7",
157+
}),
158+
).toBe("claude-cli");
159+
});
160+
161+
it("does not route a provider disabled by an explicitly empty configured order", () => {
162+
expect(
163+
resolveCliRuntimeExecutionProvider({
164+
cfg: createAnthropicAuthConfig({ order: [], onlyCliProfile: true }),
165+
provider: "anthropic",
166+
modelId: "opus-4.7",
167+
}),
168+
).toBeUndefined();
169+
});
170+
171+
it.each(["configured", "stored"])(
172+
"repairs a %s order containing only deleted profiles",
173+
(source) => {
174+
if (source === "stored") {
175+
seedStoredAuthOrder(["anthropic:deleted"]);
176+
}
177+
expect(
178+
resolveCliRuntimeExecutionProvider({
179+
cfg: createAnthropicAuthConfig({
180+
order: source === "configured" ? ["anthropic:deleted"] : undefined,
181+
onlyCliProfile: true,
182+
}),
183+
provider: "anthropic",
184+
modelId: "opus-4.7",
185+
}),
186+
).toBe("claude-cli");
187+
},
188+
);
189+
190+
it.each([
191+
{ name: "alone", order: ["anthropic:stored-api"] },
192+
{
193+
name: "before a configured CLI profile",
194+
order: ["anthropic:stored-api", "anthropic:claude-cli"],
195+
},
196+
])("keeps a stored profile missing from config authoritative $name", ({ order }) => {
197+
seedStoredAuthOrder(order, "anthropic", {
198+
"anthropic:stored-api": { type: "api_key", provider: "anthropic", key: "test-key" },
199+
});
200+
expect(
201+
resolveCliRuntimeExecutionProvider({
202+
cfg: createAnthropicAuthConfig({ onlyCliProfile: true }),
203+
provider: "anthropic",
204+
modelId: "opus-4.7",
205+
}),
206+
).toBeUndefined();
207+
});
208+
209+
it("still picks the sole compatible profile when no stored order was authored", () => {
210+
// Control for the case above: without a stored order the fallback must survive.
211+
expect(
212+
resolveCliRuntimeExecutionProvider({
213+
cfg: createAnthropicAuthConfig({ onlyCliProfile: true }),
214+
provider: "anthropic",
215+
modelId: "opus-4.7",
216+
}),
217+
).toBe("claude-cli");
218+
});
219+
220+
it("matches a config order key through the same normalized lookup as profile selection", () => {
221+
expect(
222+
resolveCliRuntimeExecutionProvider({
223+
cfg: createAnthropicAuthConfig({ order: ["anthropic:claude-cli"], orderKey: "Anthropic" }),
224+
provider: "anthropic",
225+
modelId: "opus-4.7",
226+
}),
227+
).toBe("claude-cli");
228+
});
229+
230+
it("inherits the main-agent stored order for an agent with no snapshot of its own", () => {
231+
// Named agents inherit auth state from the main agent, and only the main
232+
// snapshot may be published. An exact-agent lookup would miss it and fall
233+
// back to config, so the order read resolves inheritance the way
234+
// getPreparedRuntimeAuthProfileStoreSnapshotCore does.
235+
seedStoredAuthOrder(["anthropic:claude-cli"]);
236+
expect(
237+
resolveCliRuntimeExecutionProvider({
238+
agentId: "secondary",
239+
cfg: createAnthropicAuthConfig({}),
240+
provider: "anthropic",
241+
modelId: "opus-4.7",
242+
}),
243+
).toBe("claude-cli");
244+
});
245+
246+
it("prefers the stored auth order over a conflicting config order", () => {
247+
// Same precedence as resolveAuthProfileOrderWithMetadata: stored order wins,
248+
// config order is only the fallback.
249+
seedStoredAuthOrder(["anthropic:claude-cli"]);
250+
expect(
251+
resolveCliRuntimeExecutionProvider({
252+
cfg: createAnthropicAuthConfig({ order: ["anthropic:api"] }),
253+
provider: "anthropic",
254+
modelId: "opus-4.7",
255+
}),
256+
).toBe("claude-cli");
86257
});
87258

88259
it("routes Anthropic execution to Claude CLI when the selected auth profile is Claude CLI", () => {

0 commit comments

Comments
 (0)