From 322552d7ffa031f4b8276731745bf63d7ac321e8 Mon Sep 17 00:00:00 2001 From: zhang2580384 <859112211@qq.com> Date: Thu, 19 Nov 2026 22:45:27 +0800 Subject: [PATCH 1/2] Support Codex 6.2 models and ultra reasoning --- .github/workflows/test.yml | 13 + deploy/payload.json | 7 +- docs/PANEL_API.md | 2 +- docs/PROTOCOL.md | 2 + scripts/fetch-payload.mjs | 15 +- src/config/routing.json | 2 +- src/lib/admin/quality-config-store.mjs | 3 +- src/lib/admin/vm-test-schedule.mjs | 6 +- src/lib/protocol/codex-convert.mjs | 30 +- src/lib/protocol/codex-models.mjs | 4 +- src/lib/protocol/codex-route.mjs | 4 +- src/lib/protocol/gpt-model-policy.mjs | 33 ++- src/lib/protocol/handle-codex.mjs | 20 +- src/lib/protocol/handle-protocol.mjs | 14 + src/lib/protocol/log-fields.mjs | 2 +- test/e2e/codex-62.e2e.test.mjs | 260 ++++++++++++++++++ test/unit/fetch-payload.test.mjs | 57 ++++ test/unit/gpt-model-policy.test.mjs | 24 ++ web/src/features/logs/log-display.ts | 2 + .../features/operations/quality-preview.ts | 3 +- .../features/operations/quality-workspace.tsx | 3 +- web/src/features/settings/openai-pane.tsx | 4 +- web/src/features/vm/detail-test-tab.tsx | 1 + web/src/types/panel-usage-logs.ts | 10 +- 24 files changed, 465 insertions(+), 56 deletions(-) create mode 100644 test/e2e/codex-62.e2e.test.mjs create mode 100644 test/unit/fetch-payload.test.mjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 306aa32c6..c2032aab1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -61,6 +61,19 @@ jobs: run: | node scripts/fetch-payload.mjs node scripts/fetch-payload.mjs --check + - name: Codex 6.2 kernel over loopback HTTP and WebSocket + run: | + fixture=$(mktemp -d) + mkdir -p "$fixture/bin" "$fixture/deploy" + cp -R src scripts test node_modules VERSION package.json "$fixture/" + cp deploy/payload.json "$fixture/deploy/" + cp bin/kin-codex-kernel "$fixture/bin/" + CGO_ENABLED=0 go -C api-kernel build -o "$fixture/bin/kin-api-kernel" ./cmd/kin-api-kernel + docker run --rm --network none --read-only --cap-drop ALL --security-opt no-new-privileges \ + --user "$(id -u):$(id -g)" --tmpfs /tmp:rw,mode=1777 -e HOME=/tmp \ + -v "$fixture:/project:ro" -w /project -e KIN_CODEX_TEST_BIN=/project/bin/kin-codex-kernel \ + -e KIN_API_KERNEL_BIN=/project/bin/kin-api-kernel node:22-bookworm-slim \ + node --test test/e2e/codex-62.e2e.test.mjs - run: npm run test:unit - name: offline backup and cloud restore end-to-end run: node --test test/e2e/backup.e2e.test.mjs test/e2e/panel-proxy-domain-forward.e2e.test.mjs diff --git a/deploy/payload.json b/deploy/payload.json index 75f2887be..02b6fc5a2 100644 --- a/deploy/payload.json +++ b/deploy/payload.json @@ -11,8 +11,9 @@ { "path": "bin/kin-codex-kernel", "asset": "kin-codex-kernel", - "size": 7892048, - "sha256": "0ffec538a57afbe66f13832513ee4c2a27ecc970faa9367c7cb8a13551196dd3" + "release": "payload-2026.11.17-kernel-1091-968", + "size": 5981528, + "sha256": "95727081222f4096e9e63d29e6c9c2e009ff00365a70add30a885063fe7f9993" }, { "path": "bin/kin-oauth-auth", @@ -47,6 +48,8 @@ { "path": "share/wrap-cli/cli-node", "asset": "cli-node", + "repo": "zhang2580384/vm2api", + "release": "v2.4.4", "size": 27784880, "sha256": "cb2f8fb99bf2c191e5a32bd39e6489c2d02e72f3591ba7c3ba7a4e07229ba9fc" }, diff --git a/docs/PANEL_API.md b/docs/PANEL_API.md index 7978742b2..c23749f84 100644 --- a/docs/PANEL_API.md +++ b/docs/PANEL_API.md @@ -241,7 +241,7 @@ Claude PATCH `max_sessions` 返回 400 `claude_max_sessions_forbidden`;OpenAI | `websocket.enabled` | `true` | 全局推理 WS 总闸,不影响面板终端或集群连接 | | `codex.websocket.enabled` | `true` | GPT 推理 WS 子闸;必须与总闸同时开启 | | `codex.upstream_transport` | `prefer_websocket` | `prefer_websocket` 或 `http`;入站与上游传输不是同一段连接 | -| `codex.user_agent` | `codex_cli_rs/0.160.0 (linux x86_64)` | 上游客户端画像,不读取下游用户的系统信息 | +| `codex.user_agent` | `codex_cli_rs/0.167.1 (linux x86_64)` | 上游客户端画像,不读取下游用户的系统信息 | | `codex.catalog_client_version` | `auto` | 模型目录同步的客户端版本,与推理 UA 分开 | | `codex.client_features.enabled` | `false` | 显式开启后上送槽位独立安装 UUID 与官方 `client_metadata`;不使用 VM/硬件指纹 | | `codex.analytics.enabled` | `false` | 显式开启后独立上报运行环境 Analytics,不是推理成功的前提 | diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 723b872d3..3ea39754e 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -91,6 +91,8 @@ Go worker JSON 透传,不必因人设重建 worker。 模型目录权威是面板 `model_policy`(`GET/PUT /api/panel/model-policy`)。`GET /v1/models` 与 `validateOfficialModel` 读这份集合,**禁止** hop 槽位 `/internal/v1/models`。`GET /v1/models` 只列出该 key 的 `group_type` 能调度的模型:`openai` 只列 GPT,`anthropic` 只列 Claude,`all` 与 master 两者都列。 +Codex 的回退目录默认启用 `gpt-6.2-astra` 和 `gpt-6.2-sol`。已同步账号目录的实例沿用账号返回的型号,新同步到的这两款默认启用,已有的禁用设置继续生效。Responses 可传 `reasoning.effort`,Chat 和 Completions 可传 `reasoning_effort`,包括 `ultra`。模型名按原值转发,显式配置的模型映射仍然生效。 + ## web_search 五种人设方案只在末轮 user 提示词出现「搜索」/`search`/`web search` 时注入 `{type: web_search_20250305, name: web_search}`。调用方已声明则原样转发。`web_search=false` / `x-kin-web-search: false` / `tool_choice=none` 不补。官方 Claude Code 入站不注入。 diff --git a/scripts/fetch-payload.mjs b/scripts/fetch-payload.mjs index e179a5ca1..3ab44f6f3 100644 --- a/scripts/fetch-payload.mjs +++ b/scripts/fetch-payload.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node /** - * Slot payloads (closed-source kernels, wrap CLIs, glibc shim) live in a GitHub - * release, not in git. deploy/payload.json pins every file by size and sha256. + * Slot payloads (closed-source kernels, wrap CLIs, glibc shim) live in GitHub + * releases, not in git. Files inherit the manifest repo and release unless they pin their own source. * * node scripts/fetch-payload.mjs [--dest DIR] download missing / stale files * node scripts/fetch-payload.mjs --check verify local files, no network @@ -50,6 +50,9 @@ if (opts.pin) { if (buf === null) throw new Error(`${file.path} is missing; cannot pin`) file.size = buf.length file.sha256 = sha256(buf) + // All staged assets will be published to the same repository and tag. + delete file.release + delete file.repo } manifest.release = opts.pin fs.writeFileSync(opts.manifest, `${JSON.stringify(manifest, null, 2)}\n`) @@ -77,15 +80,13 @@ if (opts.pin) { } console.log(`payload ok (${manifest.release}, ${manifest.files.length} files)`) } else { - const base = (process.env.VM2API_PAYLOAD_BASE_URL || `https://github.com/${manifest.repo}/releases/download`).replace( - /\/+$/, - '', - ) + const mirror = process.env.VM2API_PAYLOAD_BASE_URL?.replace(/\/+$/, '') const downloads = new Map() for (const file of manifest.files) { const target = path.join(opts.dest, file.path) if (matches(readLocal(file), file)) continue - const url = `${base}/${manifest.release}/${file.asset}` + const base = mirror || `https://github.com/${file.repo || manifest.repo}/releases/download` + const url = `${base}/${file.release || manifest.release}/${file.asset}` if (!downloads.has(url)) { const res = await fetch(url) if (!res.ok) throw new Error(`GET ${url} -> HTTP ${res.status}`) diff --git a/src/config/routing.json b/src/config/routing.json index a63a9e39e..aea74b0dd 100644 --- a/src/config/routing.json +++ b/src/config/routing.json @@ -97,7 +97,7 @@ "codex": { "enabled": true, "catalog_client_version": "auto", - "user_agent": "codex_cli_rs/0.160.0 (linux x86_64)", + "user_agent": "codex_cli_rs/0.167.1 (linux x86_64)", "upstream_transport": "prefer_websocket", "websocket": { "enabled": true }, "client_features": { "enabled": false }, diff --git a/src/lib/admin/quality-config-store.mjs b/src/lib/admin/quality-config-store.mjs index 205ad5c6e..f71e4b90b 100644 --- a/src/lib/admin/quality-config-store.mjs +++ b/src/lib/admin/quality-config-store.mjs @@ -1,11 +1,12 @@ import fs from 'node:fs' import path from 'node:path' import crypto from 'node:crypto' +import { CODEX_REASONING_EFFORTS } from '../protocol/codex-convert.mjs' const fail = (message, status = 400) => { throw Object.assign(new Error(message), { status }) } -export const QUALITY_EFFORTS = ['none', 'low', 'medium', 'high', 'xhigh', 'max'] +export const QUALITY_EFFORTS = CODEX_REASONING_EFFORTS export function validateQualityTasks(tasks) { if (!Array.isArray(tasks) || tasks.length > 200) fail('任务数量不得超过 200') const ids = new Set() diff --git a/src/lib/admin/vm-test-schedule.mjs b/src/lib/admin/vm-test-schedule.mjs index 99f622c6c..917b50871 100644 --- a/src/lib/admin/vm-test-schedule.mjs +++ b/src/lib/admin/vm-test-schedule.mjs @@ -1,5 +1,6 @@ import { randomUUID } from 'node:crypto' import { Cron } from 'croner' +import { CODEX_REASONING_EFFORTS } from '../protocol/codex-convert.mjs' import { validTimezone } from '../core/timezone.mjs' import { isValidVmId } from '../vm/vm-file.mjs' import { isCodexVm } from '../vm/vm-kind.mjs' @@ -13,7 +14,6 @@ const MAX_CRON_LENGTH = 120 const MAX_MODEL_LENGTH = 200 const MAX_PROMPT_LENGTH = 16_000 const MAX_ERROR_LENGTH = 300 -const REASONING_EFFORTS = new Set(['none', 'low', 'medium', 'high', 'xhigh', 'max']) const FREQUENCIES = new Set(['hourly', 'daily', 'weekly']) const DEFAULT_PROMPT = 'hello' const DEFAULT_MAX_TOKENS = 64 @@ -222,8 +222,8 @@ export function normalizeVmTestSchedule(input, vm) { let reasoningEffort = input.reasoning_effort == null ? null : String(input.reasoning_effort).trim() if (reasoningEffort === '') reasoningEffort = null - if (reasoningEffort != null && !REASONING_EFFORTS.has(reasoningEffort)) { - throw new VmTestScheduleError('reasoning_effort must be none, low, medium, high, xhigh, or max') + if (reasoningEffort != null && !CODEX_REASONING_EFFORTS.includes(reasoningEffort)) { + throw new VmTestScheduleError(`reasoning_effort must be one of ${CODEX_REASONING_EFFORTS.join(', ')}`) } if (isCodexVm(vm)) { if (maxTokens != null || reasoningEffort == null) { diff --git a/src/lib/protocol/codex-convert.mjs b/src/lib/protocol/codex-convert.mjs index f98c45349..b71037af7 100644 --- a/src/lib/protocol/codex-convert.mjs +++ b/src/lib/protocol/codex-convert.mjs @@ -222,6 +222,8 @@ export function completionsToCodexResponses(body = {}) { stream: body.stream !== false, store: false, } + if (body.reasoning) out.reasoning = body.reasoning + if (body.reasoning_effort) out.reasoning_effort = body.reasoning_effort if (body.prompt_cache_key) out.prompt_cache_key = body.prompt_cache_key return out } @@ -237,7 +239,7 @@ export function codexTextInput(text) { ] } -export const CODEX_REASONING_EFFORTS = Object.freeze(['none', 'low', 'medium', 'high', 'xhigh', 'max']) +export const CODEX_REASONING_EFFORTS = Object.freeze(['none', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']) export const DEFAULT_CODEX_REASONING_EFFORT = 'medium' export function normalizeCodexReasoningEffort(raw) { @@ -332,11 +334,15 @@ export function createChatSseState(id = 'codex') { return { id, seq: 0, tools: new Map(), sawTool: false, finished: false } } -function chatChunk(id, delta, finish, extra = {}) { +function chatChunk(session, delta, finish, extra = {}) { + const legacy = session.protocol === 'openai.completions' + if (legacy && delta.content == null && !finish) return '' return `data: ${JSON.stringify({ - id, - object: 'chat.completion.chunk', - choices: [{ index: 0, delta, finish_reason: finish ?? null }], + id: session.id, + object: legacy ? 'text_completion' : 'chat.completion.chunk', + model: session.model, + created: (session.created ??= Math.floor(Date.now() / 1000)), + choices: [{ index: 0, ...(legacy ? { text: delta.content || '' } : { delta }), finish_reason: finish ?? null }], ...extra, })}\n\n` } @@ -400,7 +406,7 @@ export function responsesSseToChatChunk(line, id = 'codex', state = null) { name: item.name, }) const calls = toolDoneDeltas(slot, item.arguments ?? item.input) - return calls.length ? chatChunk(session.id, { tool_calls: calls }) : null + return calls.length ? chatChunk(session, { tool_calls: calls }) : null } if (type === 'response.function_call_arguments.delta' || type === 'response.custom_tool_call_input.delta') { const slot = bindTool(session, [event.output_index, event.item_id]) @@ -411,21 +417,21 @@ export function responsesSseToChatChunk(line, id = 'codex', state = null) { slot.args += event.delta calls.push({ index: slot.index, function: { arguments: event.delta } }) } - return calls.length ? chatChunk(session.id, { tool_calls: calls }) : null + return calls.length ? chatChunk(session, { tool_calls: calls }) : null } if (type === 'response.function_call_arguments.done' || type === 'response.custom_tool_call_input.done') { const slot = bindTool(session, [event.output_index, event.item_id], { name: event.name }) const calls = toolDoneDeltas(slot, event.arguments ?? event.input) - return calls.length ? chatChunk(session.id, { tool_calls: calls }) : null + return calls.length ? chatChunk(session, { tool_calls: calls }) : null } if (type.startsWith('response.reasoning_') && typeof event.delta === 'string' && event.delta) { - return chatChunk(session.id, { reasoning_content: event.delta }) + return chatChunk(session, { reasoning_content: event.delta }) } if ( type === 'response.output_text.delta' || (typeof event.delta === 'string' && event.delta && type !== 'response.completed' && type !== 'response.done') ) { - return chatChunk(session.id, { content: event.delta || event.text || '' }) + return chatChunk(session, { content: event.delta || event.text || '' }) } if (type === 'response.completed' || type === 'response.done') { const calls = [] @@ -435,9 +441,9 @@ export function responsesSseToChatChunk(line, id = 'codex', state = null) { calls.push(...toolDoneDeltas(slot, item.arguments ?? item.input)) } const usage = openaiChatUsageFromExtract(extractOpenaiUsage(event.response?.usage || event.usage)) - const repaired = calls.length ? chatChunk(session.id, { tool_calls: calls }) : '' + const repaired = calls.length ? chatChunk(session, { tool_calls: calls }) : '' session.finished = true - return `${repaired}${chatChunk(session.id, {}, session.sawTool ? 'tool_calls' : 'stop', usage ? { usage } : {})}data: [DONE]\n\n` + return `${repaired}${chatChunk(session, {}, session.sawTool ? 'tool_calls' : 'stop', usage ? { usage } : {})}data: [DONE]\n\n` } return null } diff --git a/src/lib/protocol/codex-models.mjs b/src/lib/protocol/codex-models.mjs index c045ed1af..8d6bb7c09 100644 --- a/src/lib/protocol/codex-models.mjs +++ b/src/lib/protocol/codex-models.mjs @@ -30,7 +30,7 @@ export const CODEX_OAUTH_SCOPE = 'openid profile email offline_access api.connec export const CODEX_OAUTH_ORIGINATOR = 'Codex Desktop' // This is the version embedded in the shipped kernel. Catalog discovery uses // the separately resolved official Codex client version below. -export const CODEX_APP_VERSION = '0.160.0' +export const CODEX_APP_VERSION = '0.167.1' // The model endpoint validates that Originator matches the User-Agent prefix. // OAuth still uses CODEX_OAUTH_ORIGINATOR (the desktop login surface), while // catalog requests use the resolved catalog client identity below. @@ -39,7 +39,7 @@ export const CODEX_USER_AGENT = `${CODEX_CATALOG_ORIGINATOR}/${CODEX_APP_VERSION export const CODEX_CATALOG_VERSION_URL = 'https://registry.npmjs.org/@openai%2fcodex/latest' export const CODEX_CATALOG_VERSION_TTL_MS = 6 * 60 * 60 * 1000 export const CODEX_CATALOG_VERSION_CACHE_FILE = 'codex-catalog-client.json' -export const CODEX_CATALOG_DEFAULT_VERSION = '0.160.0' +export const CODEX_CATALOG_DEFAULT_VERSION = '0.169.0' const SEMVER_RE = /^\d+\.\d+\.\d+$/ diff --git a/src/lib/protocol/codex-route.mjs b/src/lib/protocol/codex-route.mjs index d0d0c69b0..cae30f12e 100644 --- a/src/lib/protocol/codex-route.mjs +++ b/src/lib/protocol/codex-route.mjs @@ -7,7 +7,7 @@ import { normalizeCodexModelMappings, validateCodexModelMappingsPatch } from './ export { isCodexVm, normalizeVmKind } from '../vm/vm-kind.mjs' -export const DEFAULT_CODEX_USER_AGENT = 'codex_cli_rs/0.160.0 (linux x86_64)' +export const DEFAULT_CODEX_USER_AGENT = 'codex_cli_rs/0.167.1 (linux x86_64)' export const CODEX_UPSTREAM_TRANSPORTS = Object.freeze(['prefer_websocket', 'http']) export const DEFAULT_INFERENCE_WEBSOCKET = Object.freeze({ enabled: true }) @@ -15,7 +15,7 @@ export const DEFAULT_INFERENCE_WEBSOCKET = Object.freeze({ enabled: true }) export const DEFAULT_CODEX_ROUTING = Object.freeze({ enabled: true, // `auto` resolves the official Codex catalog client version at sync time, - // falling back to 0.160.0 when the registry is unavailable. + // falling back to 0.169.0 when the registry is unavailable. catalog_client_version: 'auto', user_agent: DEFAULT_CODEX_USER_AGENT, upstream_transport: 'prefer_websocket', diff --git a/src/lib/protocol/gpt-model-policy.mjs b/src/lib/protocol/gpt-model-policy.mjs index e8eab732f..85d8a1f79 100644 --- a/src/lib/protocol/gpt-model-policy.mjs +++ b/src/lib/protocol/gpt-model-policy.mjs @@ -8,6 +8,11 @@ import { IMAGE_TOOL_MODELS, canonicalImageToolModel } from './image-tool-models. const SETTINGS_KEY = 'gpt_model_policy' +const CODEX_62_MODELS = new Map([ + ['gpt-6.2-astra', { display_name: 'GPT-6.2 Astra', sort: 62, capabilities: {}, params: {} }], + ['gpt-6.2-sol', { display_name: 'GPT-6.2 Sol', sort: 63, capabilities: {}, params: {} }], +]) + const CAP_GPT = { context_window: 272000, supports_1m: false, @@ -26,8 +31,8 @@ function entry(id, extra = {}) { family: 'codex', enabled: extra.enabled !== false, sort: extra.sort || 80, - capabilities: extra.capabilities || { ...CAP_GPT }, - params: extra.params || { max_tokens_default: 16384, max_tokens_cap: 128000 }, + capabilities: { ...(extra.capabilities || CAP_GPT) }, + params: { ...(extra.params || { max_tokens_default: 16384, max_tokens_cap: 128000 }) }, aliases: extra.aliases || [], } } @@ -49,6 +54,7 @@ function normalizeImageTools(raw, base = null) { export function seedGptPolicy() { const models = {} for (const [id, extra] of [ + ...CODEX_62_MODELS, ['gpt-6-sol', { display_name: 'GPT-6 Sol', sort: 70 }], ['gpt-6-luna', { display_name: 'GPT-6 Luna', sort: 71 }], ['gpt-5.6', { display_name: 'GPT-5.6', sort: 76 }], @@ -109,8 +115,8 @@ export function getGptModelPolicy() { } export function saveGptModelPolicy(next) { - const seed = seedGptPolicy() - const models = { ...(seed.models || {}) } + const current = getGptModelPolicy() + const models = { ...current.models } if (next?.models && typeof next.models === 'object') { for (const [id, row] of Object.entries(next.models)) { if (!isGptSeriesId(id) || !row || typeof row !== 'object') continue @@ -123,13 +129,13 @@ export function saveGptModelPolicy(next) { } const currentImageTools = policy.image_tools policy = { - ...seed, + ...current, ...next, models, image_tools: normalizeImageTools(next?.image_tools, currentImageTools), platform: 'openai', updated_at: new Date().toISOString(), - source: 'panel', + source: current.source === 'codex' ? 'codex' : 'panel', } persist() return policy @@ -149,12 +155,12 @@ export function getGptPolicyCatalogIds({ enabledOnly = false } = {}) { .map(([id]) => id) } -export function isGptModelEnabled(id) { +export function isGptModelEnabled(id, { allowUnlisted = false } = {}) { if (!isGptSeriesId(id)) return false if (!loaded) loadGptModelPolicy() - const row = policy.models?.[id] + const row = policy.models?.[id] || policy.models?.[String(id).toLowerCase()] if (row) return row.enabled !== false - if (policy.source === 'codex' && Object.keys(policy.models || {}).length) return false + if (!allowUnlisted && policy.source === 'codex' && Object.keys(policy.models || {}).length) return false return true } @@ -187,8 +193,7 @@ export function resetGptModelPolicy() { /** * Replace the GPT catalog with the live Codex list. Existing rows keep their edits; - * a GPT id the policy has never seen starts disabled until the admin enables it - * (GPT has no worker_only mode). + * a newly confirmed 6.2 model starts enabled. Other new ids wait for the admin. */ export function syncGptIdsIntoPolicy(ids = [], { displayNameOf = null } = {}) { if (!loaded) loadGptModelPolicy() @@ -211,11 +216,13 @@ export function syncGptIdsIntoPolicy(ids = [], { displayNameOf = null } = {}) { const added = [] for (const row of live) { const prev = policy.models[row.id] + const known = CODEX_62_MODELS.get(row.id) if (!prev) added.push(row.id) next[row.id] = entry(row.id, { + ...known, ...prev, - display_name: row.display_name || prev?.display_name || displayNameOf?.(row.id) || row.id, - enabled: prev ? prev.enabled !== false : false, + display_name: row.display_name || prev?.display_name || known?.display_name || displayNameOf?.(row.id) || row.id, + enabled: prev ? prev.enabled !== false : !!known, source: 'codex', }) // Upstream catalog facts replace the previous snapshot; a sync without them keeps it. diff --git a/src/lib/protocol/handle-codex.mjs b/src/lib/protocol/handle-codex.mjs index c29ae44ae..1ebe03a25 100644 --- a/src/lib/protocol/handle-codex.mjs +++ b/src/lib/protocol/handle-codex.mjs @@ -3,6 +3,7 @@ import { recordMailboxAuthFailure } from '../oauth/codex-mailbox-events.mjs' * Codex hop from handle-protocol. Claude convert/pool/CRS never runs here. */ import path from 'node:path' +import { fromClaudeToOpenAIChat, fromClaudeToOpenAICompletions, isClientStream } from './convert.mjs' import { getVm, listVms, persistCodexUsage, syncCodexQuotaSchedule } from '../vm/vm-registry.mjs' import { isValidVmId, listVmRecordFiles, readJsonCached } from '../vm/vm-file.mjs' import { isCodexProtocolAllowed, isCodexVm, normalizeCodexRouting } from './codex-route.mjs' @@ -627,7 +628,10 @@ export async function handleCodexProtocol({ }, }) } - const stream = inbound?.stream !== false && ctx.body?.stream !== false + const stream = + protocol === 'anthropic.messages' + ? inbound?.stream !== false && ctx.body?.stream !== false + : isClientStream(ctx.body, req.headers) const inboundSession = sessionFrom(req, converted.body) const sessionMode = outboundSessionMode(routing) const callerSession = extractCallerSession({ @@ -644,7 +648,7 @@ export async function handleCodexProtocol({ const anthropicSse = protocol === 'anthropic.messages' ? createAnthropicSseState() : null const chatSse = protocol === 'openai.chat' || protocol === 'openai.completions' - ? { id: 'codex', seq: 0, tools: new Map(), sawTool: false } + ? { id: 'codex', model: converted.body.model, protocol, seq: 0, tools: new Map(), sawTool: false } : null const pickOpts = { stickyRouter, @@ -937,10 +941,14 @@ export async function handleCodexProtocol({ let body try { const assembled = assembleCodexBodyFromSse(chunks, result.body || {}) - body = - protocol === 'anthropic.messages' - ? codexBodyToAnthropicMessage(assembled, converted.body.model) - : assembled + body = assembled + if (protocol !== 'openai.responses') { + const message = codexBodyToAnthropicMessage(assembled, converted.body.model) + if (protocol === 'openai.chat') body = fromClaudeToOpenAIChat(message, converted.body.model) + else if (protocol === 'openai.completions') + body = fromClaudeToOpenAICompletions(message, converted.body.model) + else body = message + } } catch (error) { if (!isToolArgumentsError(error)) throw error stats.errors++ diff --git a/src/lib/protocol/handle-protocol.mjs b/src/lib/protocol/handle-protocol.mjs index 37f28613d..02916e2aa 100644 --- a/src/lib/protocol/handle-protocol.mjs +++ b/src/lib/protocol/handle-protocol.mjs @@ -44,6 +44,7 @@ import { readRawBody } from '../http/respond.mjs' import { disjointOpenaiUsage } from './openai-usage.mjs' import { costColumnsFromUsage } from '../admin/pricing.mjs' import { detectInboundPlatform } from './platform-detect.mjs' +import { isGptModelEnabled } from './gpt-model-policy.mjs' import { normalizeCodexRouting } from './codex-route.mjs' import { applyCodexInboundModelRewrite } from './codex-model-mapping.mjs' import { hasClaudeCode1mSuffix } from './context-1m.mjs' @@ -744,6 +745,19 @@ export function createHandleProtocol(deps) { return } if (platform.platform === 'openai') { + // A saved off switch also applies to direct ids. Unlisted ids retain the existing pass-through route. + if (!isGptModelEnabled(platform.model, { allowUnlisted: true })) { + stats.errors++ + logBag.error_code = 'model_disabled' + return json(res, 400, { + error: { + type: 'invalid_request_error', + code: 'model_disabled', + param: 'model', + message: `model '${platform.model}' is not enabled by gateway GPT model policy`, + }, + }) + } const routing = getRouting() || {} const codexSticky = { requestStartedAt: logCtx.t0, diff --git a/src/lib/protocol/log-fields.mjs b/src/lib/protocol/log-fields.mjs index bac1eee25..1a6d7314c 100644 --- a/src/lib/protocol/log-fields.mjs +++ b/src/lib/protocol/log-fields.mjs @@ -3,7 +3,7 @@ * Kept dependency-free so protocol handlers can import them without the DB. */ -export const REASONING_EFFORTS = new Set(['none', 'minimal', 'auto', 'low', 'medium', 'high', 'xhigh', 'max']) +export const REASONING_EFFORTS = new Set(['none', 'minimal', 'auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']) /** * Requested thinking effort across inbound dialects: Anthropic diff --git a/test/e2e/codex-62.e2e.test.mjs b/test/e2e/codex-62.e2e.test.mjs new file mode 100644 index 000000000..55bcaf0eb --- /dev/null +++ b/test/e2e/codex-62.e2e.test.mjs @@ -0,0 +1,260 @@ +import assert from 'node:assert/strict' +import { spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import { once } from 'node:events' +import fs from 'node:fs' +import http from 'node:http' +import os from 'node:os' +import path from 'node:path' +import test from 'node:test' +import { setTimeout as delay } from 'node:timers/promises' +import * as zlib from 'node:zlib' +import WebSocket, { WebSocketServer } from 'ws' +import { api, REPO_ROOT, startGateway } from '../harness.mjs' +import { codexKernelHealth } from '../../src/lib/transport/codex-kernel-client.mjs' +import { writeCodexKernelConfig } from '../../src/lib/transport/codex-kernel-supervisor.mjs' + +const kernelBin = process.env.KIN_CODEX_TEST_BIN +const models = ['gpt-6.2-astra', 'gpt-6.2-sol'] + +async function startCodexFixture(t, transport) { + const pin = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'deploy/payload.json'))).files.find( + (file) => file.path === 'bin/kin-codex-kernel', + ) + const bytes = fs.readFileSync(kernelBin) + assert.equal(bytes.length, pin.size) + assert.equal(createHash('sha256').update(bytes).digest('hex'), pin.sha256) + const project = fs.mkdtempSync(path.join(os.tmpdir(), 'codex62-')) + const vm = { + id: 'vm-test62', + family: 'codex', + platform: 'openai', + status: 'running', + schedulable: true, + has_token: true, + } + const slot = path.join(project, 'vms', vm.id) + fs.mkdirSync(slot, { recursive: true }) + fs.writeFileSync(path.join(project, 'vms/active.json'), JSON.stringify({ active_vm: vm.id })) + fs.writeFileSync( + path.join(slot, 'codex-credentials.json'), + JSON.stringify({ + accounts: [ + { + id: 'fixture', + access_token: 'fixture-access', + chatgpt_account_id: 'fixture-account', + expires_at: Date.now() + 3_600_000, + }, + ], + }), + ) + const routing = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'src/config/routing.json'))) + routing.codex.upstream_transport = transport + routing.codex.model_mappings = { 'fixture-alias': 'gpt-6.2-sol' } + fs.mkdirSync(path.join(project, 'config')) + fs.writeFileSync(path.join(project, 'config/routing.json'), JSON.stringify(routing)) + const received = [] + const receiver = http.createServer(async (req, res) => { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + const raw = Buffer.concat(chunks) + const input = JSON.parse(req.headers['content-encoding'] === 'zstd' ? zlib.zstdDecompressSync(raw) : raw) + const events = respond(input, req.url, 'http') + res.writeHead(200, { 'content-type': 'text/event-stream' }) + for (const event of events) res.write(`data: ${JSON.stringify(event)}\n\n`) + res.end() + }) + function respond(input, url, wire) { + received.push({ path: url, model: input.model, effort: input.reasoning?.effort, wire }) + const text = `fixture reply for ${input.model}` + const response = { + id: 'resp_fixture', + object: 'response', + model: input.model, + status: 'completed', + output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text }] }], + usage: { input_tokens: 3, output_tokens: 2 }, + } + return [ + { type: 'response.created', response: { id: response.id, model: input.model } }, + { type: 'response.output_text.delta', output_index: 0, content_index: 0, delta: text }, + { type: 'response.completed', response }, + ] + } + const sockets = new WebSocketServer({ server: receiver }) + sockets.on('connection', (ws, req) => + ws.on('message', (data) => { + const frame = JSON.parse(data) + for (const event of respond(frame, req.url, 'ws')) ws.send(JSON.stringify(event)) + }), + ) + let kernel, gateway + t.after(async () => { + if (gateway) await gateway.stop() + if (kernel && kernel.exitCode == null && kernel.signalCode == null) { + const exited = once(kernel, 'exit') + kernel.kill('SIGTERM') + await exited + } + for (const client of sockets.clients) client.terminate() + sockets.close() + receiver.closeAllConnections() + if (receiver.listening) await new Promise((resolve) => receiver.close(resolve)) + fs.rmSync(project, { recursive: true, force: true }) + }) + receiver.listen(0, '127.0.0.1') + await once(receiver, 'listening') + // Keep endpoint overrides in this fixture only. The gateway attaches to the already listening kernel. + const { configPath, runDir } = writeCodexKernelConfig(project, vm, { routing, proxyRequired: false }) + const config = JSON.parse(fs.readFileSync(configPath)) + const testConfig = path.join(slot, 'loopback.json') + fs.writeFileSync( + testConfig, + JSON.stringify({ + ...config, + proxy_url: '', + proxy_required: false, + test_endpoints: true, + custom_base_url: `http://127.0.0.1:${receiver.address().port}`, + }), + ) + kernel = spawn(kernelBin, [testConfig], { stdio: 'ignore', env: { PATH: process.env.PATH, HOME: project } }) + const exec = { vmId: vm.id, vm: { ...vm, runtime: { worker_run_dir: runDir } } } + let ready = false + for (let i = 0; i < 60 && kernel.exitCode == null; i++) { + if ((await codexKernelHealth(exec, { timeoutMs: 250 })).ok) { + ready = true + break + } + await delay(50) + } + assert.ok(ready, `pinned Codex kernel failed startup (exit ${kernel.exitCode})`) + gateway = await startGateway({ + project, + env: { KIN_CRS_MOCK: '0', KIN_DOCKER_BIN: '/bin/false', KIN_CODEX_KERNEL_BIN: kernelBin }, + }) + // Register the synthetic slot after boot. The fixture does not manage any guest containers. + fs.writeFileSync(path.join(project, 'vms', `${vm.id}.json`), JSON.stringify(vm)) + return { gateway, received, pin } +} + +test('Codex 6.2 catalog and HTTP responses through the pinned Linux kernel', { skip: !kernelBin }, async (t) => { + const { gateway, received, pin } = await startCodexFixture(t, 'http') + const catalog = await api(gateway, 'GET', '/v1/models') + assert.equal(catalog.status, 200, catalog.text) + for (const model of models) { + assert.equal(catalog.json.data.find((row) => row.id === model)?.family, 'codex') + for (const [endpoint, fields] of [ + ['/v1/responses', { input: 'hello', reasoning: { effort: 'ultra' } }], + ['/v1/chat/completions', { messages: [{ role: 'user', content: 'hello' }], reasoning_effort: 'ultra' }], + ['/v1/completions', { prompt: 'hello', reasoning_effort: 'ultra' }], + ]) { + for (const stream of [false, true]) + await t.test(`${model} ${endpoint} ${stream ? 'SSE' : 'JSON'}`, async () => { + const before = received.length + const reply = await api(gateway, 'POST', endpoint, { body: { model, ...fields, ...(stream && { stream }) } }) + assert.equal(reply.status, 200, reply.text) + assert.equal(received.length, before + 1) + const capture = received[before] + assert.equal(capture.wire, 'http') + assert.equal(capture.model, model) + assert.equal(capture.effort, 'ultra') + assert.match(capture.path, /\/responses$/) + const text = `fixture reply for ${model}` + if (!stream) { + assert.match(reply.headers.get('content-type'), /application\/json/) + assert.equal(reply.json.model, model) + if (endpoint === '/v1/responses') assert.equal(reply.json.output[0].content[0].text, text) + else if (endpoint === '/v1/chat/completions') assert.equal(reply.json.choices[0].message.content, text) + else assert.equal(reply.json.choices[0].text, text) + } else { + assert.match(reply.headers.get('content-type'), /text\/event-stream/) + const data = reply.text + .split(/\r?\n/) + .filter((line) => line.startsWith('data:')) + .map((line) => line.slice(5).trim()) + const events = data.filter((s) => s !== '[DONE]').map((s) => JSON.parse(s)) + if (endpoint === '/v1/responses') { + assert.equal(events.find((ev) => ev.type === 'response.completed')?.response.model, model) + assert.equal(events.find((ev) => ev.type === 'response.output_text.delta')?.delta, text) + } else { + assert.equal(data.at(-1), '[DONE]') + assert.ok(events.length > 0 && events.every((ev) => ev.model === model)) + const chat = endpoint === '/v1/chat/completions' + assert.equal(events[0].object, chat ? 'chat.completion.chunk' : 'text_completion') + assert.equal(events.map((ev) => (chat ? ev.choices[0].delta.content : ev.choices[0].text)).join(''), text) + } + } + }) + } + } + await t.test('explicit alias reaches Sol and a saved disable stops direct and mapped requests', async () => { + const target = 'gpt-6.2-sol' + const send = (model) => api(gateway, 'POST', '/v1/responses', { body: { model, input: 'hello' } }) + const before = received.length + const mapped = await send('fixture-alias') + assert.equal(mapped.status, 200, mapped.text) + assert.equal(received[before]?.model, target) + const saved = await api(gateway, 'PUT', '/api/panel/model-policy?platform=openai', { + body: { models: { [target]: { enabled: false } } }, + }) + assert.equal(saved.status, 200, saved.text) + const listed = await api(gateway, 'GET', '/v1/models') + assert.ok(listed.json.data.some((model) => model.id === 'gpt-6.2-astra')) + assert.ok(!listed.json.data.some((model) => model.id === target)) + for (const model of [target, 'fixture-alias']) { + const denied = await send(model) + assert.equal(denied.status, 400, denied.text) + assert.equal(denied.json.error.code, 'model_disabled') + } + assert.equal(received.length, before + 1) + }) + t.diagnostic(`kernel sha256 ${pin.sha256}; received ${received.length} loopback requests`) +}) + +test('Codex 6.2 Responses WebSocket through the pinned Linux kernel', { skip: !kernelBin }, async (t) => { + const { gateway, received } = await startCodexFixture(t, 'prefer_websocket') + for (const model of models) + await t.test(model, async () => { + const ws = new WebSocket(gateway.baseUrl.replace('http:', 'ws:') + '/v1/responses', { + headers: { authorization: `Bearer ${gateway.apiKey}` }, + handshakeTimeout: 5000, + }) + try { + await once(ws, 'open') + const before = received.length + const events = [] + const terminal = new Promise((resolve, reject) => { + ws.on('error', reject) + ws.on('close', () => reject(new Error('websocket closed before completion'))) + ws.on('message', (data) => { + const event = JSON.parse(data) + events.push(event) + if (event.type === 'response.completed') resolve(event.response) + if (event.type === 'error' || event.type === 'response.failed') reject(new Error(JSON.stringify(event))) + }) + }) + ws.send(JSON.stringify({ type: 'response.create', model, input: 'hello', reasoning: { effort: 'ultra' } })) + const timer = setTimeout(() => ws.terminate(), 8000) + let response + try { + response = await terminal + } finally { + clearTimeout(timer) + } + assert.equal(received.length, before + 1) + const capture = received[before] + assert.equal(capture.wire, 'ws') + assert.equal(capture.model, model) + assert.equal(capture.effort, 'ultra') + assert.equal(response.model, model) + assert.equal( + events.find((event) => event.type === 'response.output_text.delta')?.delta, + `fixture reply for ${model}`, + ) + } finally { + ws.terminate() + } + }) +}) diff --git a/test/unit/fetch-payload.test.mjs b/test/unit/fetch-payload.test.mjs new file mode 100644 index 000000000..6f6b8abe9 --- /dev/null +++ b/test/unit/fetch-payload.test.mjs @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict' +import { execFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import fs from 'node:fs/promises' +import http from 'node:http' +import os from 'node:os' +import path from 'node:path' +import test from 'node:test' +import { promisify } from 'node:util' + +const run = promisify(execFile) + +test('fetch and repin a kernel from its own component release', async (t) => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'payload-tags-')) + t.after(() => fs.rm(dir, { recursive: true, force: true })) + const manifest = path.join(dir, 'manifest.json') + const files = [ + { path: 'bin/old', asset: 'old' }, + { path: 'bin/codex', asset: 'codex', repo: 'other/fixture', release: 'component' }, + ].map((row) => ({ ...row, size: row.asset.length, sha256: createHash('sha256').update(row.asset).digest('hex') })) + await fs.writeFile(manifest, JSON.stringify({ repo: 'example/fixture', release: 'base', files })) + const requests = [] + const server = http.createServer((req, res) => { + requests.push(req.url) + const row = files.find((row) => req.url === `/${row.release || 'base'}/${row.asset}`) + if (!row) res.writeHead(404) + res.end(row?.asset) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise((resolve) => server.close(resolve))) + const fetchPayload = (...args) => + run( + process.execPath, + [ + path.resolve(import.meta.dirname, '../../scripts/fetch-payload.mjs'), + '--manifest', + manifest, + '--dest', + dir, + ...args, + ], + { + env: { ...process.env, VM2API_PAYLOAD_BASE_URL: `http://127.0.0.1:${server.address().port}` }, + }, + ) + await fetchPayload() + await fetchPayload('--check') + assert.deepEqual(requests, ['/base/old', '/component/codex']) + await fetchPayload('--pin', 'repacked') + const pinned = JSON.parse(await fs.readFile(manifest, 'utf8')) + assert.equal(pinned.release, 'repacked') + assert.ok(pinned.files.every((file) => !Object.hasOwn(file, 'release') && !Object.hasOwn(file, 'repo'))) + assert.deepEqual( + pinned.files.map((file) => file.sha256), + files.map((file) => file.sha256), + ) +}) diff --git a/test/unit/gpt-model-policy.test.mjs b/test/unit/gpt-model-policy.test.mjs index 881c6ada7..6d068d6c7 100644 --- a/test/unit/gpt-model-policy.test.mjs +++ b/test/unit/gpt-model-policy.test.mjs @@ -135,3 +135,27 @@ test('panel save keeps the synced catalog; only a sync writes it', (t) => { saveGptModelPolicy({ models: { 'gpt-7': { enabled: true, catalog: { context_window: 9 } } } }) assert.equal(getGptModelPolicy().models['gpt-7'].catalog, undefined) }) + +test('6.2 defaults apply on first discovery without overriding catalog removals or saved switches', (t) => { + withDb(t) + const astra = 'gpt-6.2-astra' + const sol = 'gpt-6.2-sol' + const enabled = () => listGptPolicyModels().map((row) => row.id) + assert.ok(enabled().includes(astra) && enabled().includes(sol)) + + // A pre-upgrade, synchronized policy has no fallback rows. Its account still owns the catalog. + new SettingsRepo().set('gpt_model_policy', { source: 'codex', models: { 'gpt-6-sol': { enabled: false } } }) + loadGptModelPolicy({ force: true }) + assert.ok(!enabled().includes(astra)) + syncGptIdsIntoPolicy([{ id: astra, catalog: { context_window: 12345 } }, sol, 'gpt-future', 'gpt-6-sol']) + assert.deepEqual(enabled(), [astra, sol]) + assert.equal(getGptModelPolicy().models[astra].catalog.context_window, 12345) + saveGptModelPolicy({ models: { [astra]: { enabled: false } } }) + saveGptModelPolicy({ image_tools: { 'gpt-image-2.5-flare': { enabled: false } } }) + loadGptModelPolicy({ force: true }) + assert.deepEqual(enabled(), [sol]) + syncGptIdsIntoPolicy([astra, 'gpt-6-sol']) + loadGptModelPolicy({ force: true }) + assert.equal(getGptModelPolicy().models[astra].enabled, false) + assert.equal(getGptModelPolicy().models[sol], undefined) +}) diff --git a/web/src/features/logs/log-display.ts b/web/src/features/logs/log-display.ts index c03edd1c6..d37cbb63b 100644 --- a/web/src/features/logs/log-display.ts +++ b/web/src/features/logs/log-display.ts @@ -219,6 +219,8 @@ const THINKING_EFFORT_BADGE_STYLES: Record = { // xhigh 介于 high 与 max 之间,独立样式维持强度等级的视觉顺序。 xhigh: 'border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-950/30 dark:text-red-300', + ultra: + 'border-violet-300 bg-violet-100 text-violet-800 dark:border-violet-700 dark:bg-violet-950/40 dark:text-violet-200', max: 'border-red-300 bg-red-100 text-red-800 dark:border-red-700 dark:bg-red-950/40 dark:text-red-200', } diff --git a/web/src/features/operations/quality-preview.ts b/web/src/features/operations/quality-preview.ts index 4149c5e29..bc0098ef8 100644 --- a/web/src/features/operations/quality-preview.ts +++ b/web/src/features/operations/quality-preview.ts @@ -18,7 +18,8 @@ export type QualityTask = { enabled: boolean action: 'record' | 'pause' autoRestore: boolean - reasoningEffort: 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' + reasoningEffort: + 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra' } export type QualityRecord = { id: string diff --git a/web/src/features/operations/quality-workspace.tsx b/web/src/features/operations/quality-workspace.tsx index 93f56dced..743292b5e 100644 --- a/web/src/features/operations/quality-workspace.tsx +++ b/web/src/features/operations/quality-workspace.tsx @@ -1140,7 +1140,8 @@ function TaskEditor({ - + + GPT 按所选强度发送;模型不支持时记录真实错误。Claude diff --git a/web/src/features/settings/openai-pane.tsx b/web/src/features/settings/openai-pane.tsx index af51a305b..b3c1f3c74 100644 --- a/web/src/features/settings/openai-pane.tsx +++ b/web/src/features/settings/openai-pane.tsx @@ -12,7 +12,7 @@ import { ChipGroup, PaneSection } from './scheduler-controls' type Block = Record type Transport = 'prefer_websocket' | 'http' -const DEFAULT_USER_AGENT = 'codex_cli_rs/0.160.0 (linux x86_64)' +const DEFAULT_USER_AGENT = 'codex_cli_rs/0.167.1 (linux x86_64)' const TRANSPORT_OPTIONS: [Transport, string][] = [ ['prefer_websocket', '优先 WebSocket'], ['http', '仅 HTTP'], @@ -290,7 +290,7 @@ export function OpenaiPane({ Date: Thu, 19 Nov 2026 22:48:58 +0800 Subject: [PATCH 2/2] Write the gateway CI snapshot to the container temp directory --- .github/workflows/test.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c2032aab1..bbc7298d9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -66,6 +66,8 @@ jobs: fixture=$(mktemp -d) mkdir -p "$fixture/bin" "$fixture/deploy" cp -R src scripts test node_modules VERSION package.json "$fixture/" + # The gateway writes its public startup snapshot; keep that output in the container tmpfs. + ln -sf /tmp/gateway-v2.public.json "$fixture/src/config/gateway-v2.public.json" cp deploy/payload.json "$fixture/deploy/" cp bin/kin-codex-kernel "$fixture/bin/" CGO_ENABLED=0 go -C api-kernel build -o "$fixture/bin/kin-api-kernel" ./cmd/kin-api-kernel