Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,21 @@ 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/"
# 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
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
Expand Down
7 changes: 5 additions & 2 deletions deploy/payload.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -47,6 +48,8 @@
{
"path": "share/wrap-cli/cli-node",
"asset": "cli-node",
"repo": "zhang2580384/vm2api",
"release": "v2.4.4",
"size": 27784880,
"sha256": "cb2f8fb99bf2c191e5a32bd39e6489c2d02e72f3591ba7c3ba7a4e07229ba9fc"
},
Expand Down
2 changes: 1 addition & 1 deletion docs/PANEL_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,不是推理成功的前提 |
Expand Down
2 changes: 2 additions & 0 deletions docs/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 入站不注入。
Expand Down
15 changes: 8 additions & 7 deletions scripts/fetch-payload.mjs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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`)
Expand Down Expand Up @@ -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}`)
Expand Down
2 changes: 1 addition & 1 deletion src/config/routing.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down
3 changes: 2 additions & 1 deletion src/lib/admin/quality-config-store.mjs
Original file line number Diff line number Diff line change
@@ -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()
Expand Down
6 changes: 3 additions & 3 deletions src/lib/admin/vm-test-schedule.mjs
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
30 changes: 18 additions & 12 deletions src/lib/protocol/codex-convert.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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`
}
Expand Down Expand Up @@ -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])
Expand All @@ -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 = []
Expand All @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/protocol/codex-models.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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+$/

Expand Down
4 changes: 2 additions & 2 deletions src/lib/protocol/codex-route.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ 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 })

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',
Expand Down
33 changes: 20 additions & 13 deletions src/lib/protocol/gpt-model-policy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 || [],
}
}
Expand All @@ -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 }],
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
}

Expand Down Expand Up @@ -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()
Expand All @@ -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.
Expand Down
Loading