Skip to content

Commit 60aac74

Browse files
authored
fix(openai): harden live and packaged onboarding (#114288)
1 parent 71eb9a3 commit 60aac74

12 files changed

Lines changed: 474 additions & 135 deletions

File tree

‎extensions/openai/openai-provider.test.ts‎

Lines changed: 62 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,7 @@ describe("buildOpenAIProvider", () => {
537537
contextWindow: 1_050_000,
538538
maxTokens: 128_000,
539539
reasoning: true,
540-
input: ["text"],
540+
input: ["text", "image"],
541541
cost: { input: 30, output: 180, cacheRead: 0, cacheWrite: 0 },
542542
});
543543
expect(provider.models.find((model) => model.id === "gpt-5.4-mini")).toMatchObject({
@@ -583,6 +583,31 @@ describe("buildOpenAIProvider", () => {
583583
expect(provider.models.map((model) => model.id)).toEqual(["gpt-5.5"]);
584584
});
585585

586+
it.each([
587+
["returns an empty model list", () => Response.json({ data: [] })],
588+
[
589+
"returns only unsupported models",
590+
() => Response.json({ data: [{ id: "not-in-manifest", object: "model" }] }),
591+
],
592+
["rejects the API key", () => new Response("unauthorized", { status: 401 })],
593+
["denies account access", () => new Response("forbidden", { status: 403 })],
594+
])("does not invent available OpenAI models when discovery %s", async (_label, response) => {
595+
const release = vi.fn(async () => undefined);
596+
const fetchGuard: LiveModelCatalogFetchGuard = vi.fn(async () => ({
597+
response: response(),
598+
finalUrl: "https://api.openai.com/v1/models",
599+
release,
600+
}));
601+
602+
const provider = await buildOpenAILiveProviderConfig({
603+
apiKey: "sk-openai-unavailable",
604+
fetchGuard,
605+
});
606+
607+
expect(provider.models).toEqual([]);
608+
expect(release).toHaveBeenCalledOnce();
609+
});
610+
586611
it("keeps only manifest fallback models when OpenAI discovery is unavailable", async () => {
587612
const fetchGuard: LiveModelCatalogFetchGuard = vi.fn(async () => ({
588613
response: new Response("temporarily unavailable", { status: 503 }),
@@ -1002,23 +1027,10 @@ describe("buildOpenAIProvider", () => {
10021027
).not.toContainEqual({ id: "ultra" });
10031028
});
10041029

1005-
it.each([
1006-
["fails", () => new Response("temporarily unavailable", { status: 503 })],
1007-
["returns no models", () => Response.json({ models: [] })],
1008-
[
1009-
"returns hidden-only models",
1010-
() =>
1011-
Response.json({
1012-
models: [
1013-
{ slug: "gpt-5.6-sol", display_name: "GPT-5.6 Sol", visibility: "hide" },
1014-
{ slug: "gpt-5.5", display_name: "GPT-5.5", show_in_picker: false },
1015-
],
1016-
}),
1017-
],
1018-
])("keeps static OpenAI OAuth rows when Codex catalog discovery %s", async (_label, response) => {
1030+
it("keeps static OpenAI OAuth rows when Codex catalog discovery fails", async () => {
10191031
const release = vi.fn(async () => undefined);
10201032
const fetchGuard: LiveModelCatalogFetchGuard = vi.fn(async () => ({
1021-
response: response(),
1033+
response: new Response("temporarily unavailable", { status: 503 }),
10221034
finalUrl: "https://chatgpt.com/backend-api/codex/models?client_version=1.0.0",
10231035
release,
10241036
}));
@@ -1048,6 +1060,40 @@ describe("buildOpenAIProvider", () => {
10481060
expect(release).toHaveBeenCalledOnce();
10491061
});
10501062

1063+
it.each([
1064+
["returns no models", () => Response.json({ models: [] })],
1065+
[
1066+
"returns only hidden models",
1067+
() =>
1068+
Response.json({
1069+
models: [
1070+
{ slug: "gpt-5.6-sol", display_name: "GPT-5.6 Sol", visibility: "hide" },
1071+
{ slug: "gpt-5.5", display_name: "GPT-5.5", show_in_picker: false },
1072+
],
1073+
}),
1074+
],
1075+
["rejects the subscription token", () => new Response("unauthorized", { status: 401 })],
1076+
["denies account access", () => new Response("forbidden", { status: 403 })],
1077+
])("does not invent OAuth models when the account catalog %s", async (_label, response) => {
1078+
const release = vi.fn(async () => undefined);
1079+
const fetchGuard: LiveModelCatalogFetchGuard = vi.fn(async () => ({
1080+
response: response(),
1081+
finalUrl: "https://chatgpt.com/backend-api/codex/models?client_version=1.0.0",
1082+
release,
1083+
}));
1084+
1085+
const provider = await buildOpenAICodexLiveProviderConfig({
1086+
discoveryApiKey: "oauth-token-no-visible-models",
1087+
accountId: "acct-openai-workspace",
1088+
fetchGuard,
1089+
});
1090+
1091+
expect(provider.api).toBe("openai-chatgpt-responses");
1092+
expect(provider.auth).toBe("oauth");
1093+
expect(provider.models).toEqual([]);
1094+
expect(release).toHaveBeenCalledOnce();
1095+
});
1096+
10511097
it("keeps the deprecated Codex provider builder on the public API barrel", async () => {
10521098
const { buildOpenAICodexProviderPlugin } = await import("./api.js");
10531099
const provider = buildOpenAICodexProviderPlugin();

‎extensions/openai/openai-provider.ts‎

Lines changed: 67 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import type {
55
} from "openclaw/plugin-sdk/plugin-entry";
66
import { createProviderApiKeyAuthMethod } from "openclaw/plugin-sdk/provider-auth-api-key";
77
import {
8-
buildLiveModelProviderConfig,
98
getCachedLiveProviderModelRows,
9+
LiveModelCatalogHttpError,
1010
type LiveModelCatalogFetchGuard,
1111
} from "openclaw/plugin-sdk/provider-catalog-live-runtime";
1212
import { buildManifestModelProviderConfig } from "openclaw/plugin-sdk/provider-catalog-shared";
@@ -234,7 +234,7 @@ function buildOpenAIDiscoverablePlatformModels(baseUrl: string): ModelDefinition
234234
contextWindow,
235235
api: "openai-responses",
236236
baseUrl,
237-
input: id === OPENAI_GPT_54_PRO_MODEL_ID ? ["text"] : ["text", "image"],
237+
input: ["text", "image"],
238238
maxTokens: OPENAI_GPT_54_MAX_TOKENS,
239239
}));
240240
}
@@ -245,56 +245,61 @@ async function buildOpenAILiveProviderConfig(
245245
const baseUrl =
246246
normalizeOptionalString(params.baseUrl) ?? resolveOpenAIDefaultBaseUrl(params.env);
247247
const models = buildOpenAIManifestModelsForBaseUrl(baseUrl);
248+
const fallback: ModelProviderConfig = {
249+
baseUrl,
250+
api: "openai-responses",
251+
...(params.apiKey ? { apiKey: params.apiKey } : {}),
252+
models,
253+
};
248254
if (!shouldFetchOpenAILiveModels(baseUrl)) {
249-
return {
250-
baseUrl,
251-
api: "openai-responses",
255+
return fallback;
256+
}
257+
try {
258+
const rows = await getCachedLiveProviderModelRows({
259+
providerId: PROVIDER_ID,
260+
endpoint: OPENAI_MODELS_ENDPOINT,
252261
apiKey: params.apiKey,
253-
models,
262+
discoveryApiKey: params.discoveryApiKey,
263+
fetchGuard: params.fetchGuard,
264+
signal: params.signal,
265+
ttlMs: OPENAI_MODELS_CACHE_TTL_MS,
266+
auditContext: "openai-model-discovery",
267+
});
268+
const discoveredIds = new Set(
269+
rows.flatMap((row) => {
270+
if (!row || typeof row !== "object" || Array.isArray(row)) {
271+
return [];
272+
}
273+
const candidate = row as { id?: unknown; object?: unknown };
274+
if (candidate.object !== undefined && candidate.object !== "model") {
275+
return [];
276+
}
277+
const modelId = typeof candidate.id === "string" ? candidate.id.trim() : "";
278+
return modelId ? [modelId] : [];
279+
}),
280+
);
281+
const selectedIds = new Set<string>();
282+
// A successful account catalog is authoritative even when it has no
283+
// visible supported models; static rows cannot grant model access.
284+
return {
285+
...fallback,
286+
models: [...models, ...buildOpenAIDiscoverablePlatformModels(baseUrl)].filter((model) => {
287+
if (!discoveredIds.has(model.id) || selectedIds.has(model.id)) {
288+
return false;
289+
}
290+
selectedIds.add(model.id);
291+
return true;
292+
}),
254293
};
294+
} catch (error) {
295+
if (
296+
error instanceof LiveModelCatalogHttpError &&
297+
(error.status === 401 || error.status === 403)
298+
) {
299+
return { ...fallback, models: [] };
300+
}
301+
return fallback;
255302
}
256-
return await buildLiveModelProviderConfig({
257-
providerId: PROVIDER_ID,
258-
endpoint: OPENAI_MODELS_ENDPOINT,
259-
providerConfig: {
260-
baseUrl,
261-
api: "openai-responses",
262-
},
263-
models,
264-
projectRows: (rows, fallback) => {
265-
const discoveredIds = new Set(
266-
rows.flatMap((row) => {
267-
if (!row || typeof row !== "object" || Array.isArray(row)) {
268-
return [];
269-
}
270-
const candidate = row as { id?: unknown; object?: unknown };
271-
if (candidate.object !== undefined && candidate.object !== "model") {
272-
return [];
273-
}
274-
const modelId = typeof candidate.id === "string" ? candidate.id.trim() : "";
275-
return modelId ? [modelId] : [];
276-
}),
277-
);
278-
const selectedIds = new Set<string>();
279-
// Discovery alone confirms account access; leave the manifest as the
280-
// advisory fallback when OpenAI cannot return an authenticated catalog.
281-
return [...fallback.models, ...buildOpenAIDiscoverablePlatformModels(baseUrl)].filter(
282-
(model) => {
283-
if (!discoveredIds.has(model.id) || selectedIds.has(model.id)) {
284-
return false;
285-
}
286-
selectedIds.add(model.id);
287-
return true;
288-
},
289-
);
290-
},
291-
apiKey: params.apiKey,
292-
discoveryApiKey: params.discoveryApiKey,
293-
fetchGuard: params.fetchGuard,
294-
signal: params.signal,
295-
ttlMs: OPENAI_MODELS_CACHE_TTL_MS,
296-
auditContext: "openai-model-discovery",
297-
});
298303
}
299304

300305
function readCodexModelString(row: unknown, key: string): string | undefined {
@@ -578,18 +583,21 @@ async function buildOpenAICodexLiveProviderConfig(params: {
578583
const models = rows
579584
.map(buildOpenAICodexModelFromLiveRow)
580585
.filter((model): model is ModelDefinitionConfig => Boolean(model));
581-
if (models.length > 0) {
582-
// Successful Codex OAuth discovery is account-scoped and authoritative
583-
// for the picker/list catalog. Do not merge static OpenAI fallback rows
584-
// into a successful live catalog.
585-
return {
586-
baseUrl: OPENAI_CODEX_RESPONSES_BASE_URL,
587-
api: "openai-chatgpt-responses",
588-
auth: "oauth",
589-
models,
590-
};
586+
// A successful account-scoped response is authoritative even when all
587+
// rows are hidden; static hints must not invent subscription access.
588+
return {
589+
baseUrl: OPENAI_CODEX_RESPONSES_BASE_URL,
590+
api: "openai-chatgpt-responses",
591+
auth: "oauth",
592+
models,
593+
};
594+
} catch (error) {
595+
if (
596+
error instanceof LiveModelCatalogHttpError &&
597+
(error.status === 401 || error.status === 403)
598+
) {
599+
return { ...buildOpenAICodexStaticProviderConfig(), models: [] };
591600
}
592-
} catch {
593601
// Codex/ChatGPT discovery is advisory. Static OpenAI rows stay available
594602
// when OAuth refresh or the remote model list is unavailable.
595603
}

‎scripts/e2e/lib/fixtures/mock-openai-config.mjs‎

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,10 @@ export function applyMockOpenAiModelConfig(cfg, params) {
6161
...(params.includeImageDefaults
6262
? {
6363
imageModel: { primary: modelRef, timeoutMs: 30_000 },
64-
imageGenerationModel: { primary: "openai/gpt-image-1", timeoutMs: 30_000 },
64+
mediaModels: {
65+
...cfg.agents?.defaults?.mediaModels,
66+
image: { primary: "openai/gpt-image-1", timeoutMs: 30_000 },
67+
},
6568
}
6669
: {}),
6770
models: {
@@ -72,24 +75,32 @@ export function applyMockOpenAiModelConfig(cfg, params) {
7275
},
7376
},
7477
},
75-
...(Array.isArray(cfg.agents?.list)
78+
...(cfg.agents?.entries
7679
? {
77-
list: cfg.agents.list.map((agent) => ({
78-
...agent,
79-
model: { ...agent.model, primary: modelRef },
80-
models: {
81-
...agent.models,
82-
[modelRef]: {
83-
...agent.models?.[modelRef],
84-
agentRuntime: { id: "openclaw" },
85-
params: {
86-
...agent.models?.[modelRef]?.params,
87-
transport: "sse",
88-
openaiWsWarmup: false,
80+
entries: Object.fromEntries(
81+
Object.entries(cfg.agents.entries).map(([agentId, agent]) => [
82+
agentId,
83+
{
84+
...agent,
85+
model: {
86+
...(typeof agent.model === "object" && agent.model !== null ? agent.model : {}),
87+
primary: modelRef,
88+
},
89+
models: {
90+
...agent.models,
91+
[modelRef]: {
92+
...agent.models?.[modelRef],
93+
agentRuntime: { id: "openclaw" },
94+
params: {
95+
...agent.models?.[modelRef]?.params,
96+
transport: "sse",
97+
openaiWsWarmup: false,
98+
},
99+
},
89100
},
90101
},
91-
},
92-
})),
102+
]),
103+
),
93104
}
94105
: {}),
95106
};

‎scripts/e2e/lib/npm-onboard-channel-agent/assertions.mjs‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,7 @@ function assertMockModelConfig() {
136136
const provider = cfg.models?.providers?.openai;
137137
const defaultModel = cfg.agents?.defaults?.model?.primary;
138138
const defaultRuntime = cfg.agents?.defaults?.models?.[expectedModelRef]?.agentRuntime?.id;
139-
const agent = Array.isArray(cfg.agents?.list)
140-
? (cfg.agents.list.find((entry) => entry?.id === "main") ?? cfg.agents.list[0])
141-
: undefined;
139+
const agent = cfg.agents?.entries?.main;
142140
const agentModel = agent?.model?.primary;
143141
const agentRuntime = agent?.models?.[expectedModelRef]?.agentRuntime?.id;
144142
if (provider?.baseUrl !== expectedBaseUrl) {
@@ -160,12 +158,12 @@ function assertMockModelConfig() {
160158
if (defaultRuntime !== "openclaw") {
161159
throw new Error(`mock default runtime was not preserved; got ${defaultRuntime}`);
162160
}
163-
if (agent && agentModel !== expectedModelRef) {
161+
if (agentModel !== expectedModelRef) {
164162
throw new Error(
165163
`mock agent model was not preserved; expected ${expectedModelRef}, got ${agentModel}`,
166164
);
167165
}
168-
if (agent && agentRuntime !== "openclaw") {
166+
if (agentRuntime !== "openclaw") {
169167
throw new Error(`mock agent runtime was not preserved; got ${agentRuntime}`);
170168
}
171169
}

‎scripts/e2e/lib/onboard/scenario.sh‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ stop_gateway() {
131131
}
132132

133133
cleanup_wizard_case() {
134-
exec 3>&- 2>/dev/null || true
134+
{ exec 3>&-; } 2>/dev/null || true
135135
openclaw_e2e_stop_process "${wizard_pid:-}"
136136
stop_gateway "${gw_pid:-}"
137137
rm -rf "${input_fifo_dir:-}"

0 commit comments

Comments
 (0)