@jeffreycao/copilot-api 2.3.10 → 2.3.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/README.zh-CN.md +3 -0
- package/dist/config-ByEK-9s6.js.map +1 -1
- package/dist/main.js +1 -1
- package/dist/{server-BZe1LSIn.js → server-fiF0jU-7.js} +47 -20
- package/dist/server-fiF0jU-7.js.map +1 -0
- package/dist/{start-Ccs4AOzy.js → start-BaYrtsEL.js} +2 -2
- package/dist/{start-Ccs4AOzy.js.map → start-BaYrtsEL.js.map} +1 -1
- package/package.json +1 -1
- package/dist/server-BZe1LSIn.js.map +0 -1
package/README.md
CHANGED
|
@@ -310,6 +310,8 @@ Without this configuration, Codex cannot fetch `/v1/models` while not signed in
|
|
|
310
310
|
|
|
311
311
|
When a Codex client (`User-Agent` starts with `codex`) requests the top-level `GET /v1/models`, the gateway merges native Codex models with models available through the Messages adapter. The latter advertise `use_responses_lite: true`, except DeepSeek models, which use `use_responses_lite: false` and `tool_mode: null`. For other models, `/v1/responses` uses **Responses → Messages** for Anthropic providers, while OpenAI-compatible providers and Chat-only Copilot models reuse the existing Messages route for **Responses → Messages → Chat Completions**, then translate streaming or JSON results back to Responses.
|
|
312
312
|
|
|
313
|
+
> **Note:** DeepSeek models do not use Responses Lite (`use_responses_lite: false`, `tool_mode: null`), so the tool set they advertise to Codex differs from other models, which use `tool_mode: "code_mode_only"`. Switching between a DeepSeek model and a Responses Lite model mid-session is not compatible, because tool calls and conversation history produced under one tool set do not translate to the other. Start a new Codex session when switching between them.
|
|
314
|
+
|
|
313
315
|
The merged catalog is what Codex shows in its model picker, including the models exposed by your configured providers:
|
|
314
316
|
|
|
315
317
|
<img src="./docs/screenshots/codex-models.png" alt="Codex model picker showing models provided by the gateway" width="900" />
|
|
@@ -723,6 +725,7 @@ Gateway API keys live under `auth.apiKeys` in `config.json`. Manage them with `c
|
|
|
723
725
|
- `inputModalities` (optional): Supported Codex input types. Use `["text", "image"]` for a model that accepts both text and images. Missing configured values use upstream metadata before the built-in non-GPT model catalog. GPT models do not receive these built-in capability defaults and continue to use the native Codex catalog or upstream metadata.
|
|
724
726
|
- `reasoningEfforts` (optional): Reasoning levels advertised for Codex. Missing configured and upstream values use the built-in non-GPT model catalog before falling back to `["high", "xhigh", "max", "ultra"]`. Provider Responses requests with an unsupported effort are normalized to a supported level when these capabilities are known.
|
|
725
727
|
- `defaultReasoningEffort` (optional): Default Codex reasoning level. Built-in model metadata may provide a known default; otherwise it defaults to `max` when available, then the first configured level. Synthetic Codex models always enable parallel tool calls.
|
|
728
|
+
- `reasoningField` (optional): Assistant thinking field sent upstream on OpenAI-compatible `/v1/messages` requests. Supports `reasoning` and `reasoning_content`; defaults to `reasoning_content`. Use `reasoning` for OpenRouter-style models; the built-in catalog already does this for OpenCode Go `hy3` and `hy4-preview`.
|
|
726
729
|
- **smallModel:** Fallback model used for tool-less warmup messages (e.g., Claude Code probe requests); defaults to gpt-5-mini. The gateway forces this small model on no-tool warmup or probe requests to avoid consuming premium requests. This behavior only applies to non-token-based-billing GitHub Copilot accounts (`token_based_billing` is false); for token-based-billing accounts the warmup small-model fallback is skipped since there is no premium-request quota to preserve.
|
|
727
730
|
- **contextManagement:** Controls whether the proxy adds Responses API `context_management` compaction instructions. `messages` applies when Anthropic-style `/v1/messages` requests are translated to Responses API, including `openai-responses` provider message routes, and defaults to `true`. `responses` applies to native `/v1/responses` traffic, including `provider/model` aliases and the built-in `codex` provider, and defaults to `false`. Enable `responses` only after checking that your client supports context management compaction. When enabled, the request includes `context_management` in the body and keeps only the latest compaction carrier on follow-up turns. The proxy only adds context management and compacts history for `gpt-*` models; both configuration switches have no effect on non-GPT models such as Grok. **Note:** Context management is also forcibly disabled for GPT-5.6 and above models (e.g. `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`) because enabling it breaks prompt cache hits on those models. These overrides take precedence over the `contextManagement` and `modelResponsesApiCompactThresholds` settings.
|
|
728
731
|
- **modelResponsesApiCompactThresholds:** Per-model Responses API `compact_threshold` overrides used when the proxy adds `context_management`. These values take precedence over the fallback threshold from `resolveResponsesCompactThreshold` (`max_prompt_tokens * ratio`, or the default fallback). Defaults set `gpt-5.4` and `gpt-5.5` to `217600` (`272000 * 0.8`). Models not listed continue to use the normal fallback logic.
|
package/README.zh-CN.md
CHANGED
|
@@ -326,6 +326,8 @@ args = [
|
|
|
326
326
|
|
|
327
327
|
Codex 客户端(`User-Agent` 以 `codex` 开头)请求顶层 `GET /v1/models` 时,网关会把原生 Codex 模型与可通过 Messages 适配的模型合并返回。除 DeepSeek 模型外,后者会声明 `use_responses_lite: true`;DeepSeek 模型使用 `use_responses_lite: false` 和 `tool_mode: null`。调用 `/v1/responses` 后,Anthropic provider 走 **Responses → Messages**,OpenAI 兼容 provider 以及只支持 Chat 的 Copilot 模型则复用现有 Messages 路由继续走 **Responses → Messages → Chat Completions**,最终统一翻译回 Responses(包括流式事件)。
|
|
328
328
|
|
|
329
|
+
> **注意:** DeepSeek 模型不使用 Responses Lite(`use_responses_lite: false`、`tool_mode: null`),因此向 Codex 暴露的工具集合与其他模型(`tool_mode: "code_mode_only"`)不一致。在会话中途切换 DeepSeek 模型与 Responses Lite 模型并不兼容——一套工具集合下产生的工具调用和会话历史无法直接沿用到另一套。切换模型时请新建 Codex 会话。
|
|
330
|
+
|
|
329
331
|
合并后的模型列表会直接展示在 Codex 的模型选择界面中,包含各 provider 暴露的模型:
|
|
330
332
|
|
|
331
333
|
<img src="./docs/screenshots/codex-models.png" alt="Codex 模型选择界面展示网关提供的模型列表" width="900" />
|
|
@@ -767,6 +769,7 @@ Copilot API 现在使用子命令结构,主要命令包括:
|
|
|
767
769
|
- `inputModalities`:可选,Codex 支持的输入类型;模型同时支持文本和图片时配置为 `["text", "image"]`。用户未配置时优先使用上游元数据,再使用非 GPT 模型的内置目录。GPT 模型不注入这些内置能力默认值,继续使用原生 Codex catalog 或上游元数据。
|
|
768
770
|
- `reasoningEfforts`:可选,Codex 支持的推理档位。配置和上游元数据均未提供时,会先使用非 GPT 模型的内置目录,再回退到 `["high", "xhigh", "max", "ultra"]`。已知模型能力时,Provider Responses 请求中的不支持档位会被归一化为支持的档位。
|
|
769
771
|
- `defaultReasoningEffort`:可选,Codex 默认推理档位;内置模型元数据可以提供已知默认值,否则可用档位包含 `max` 时默认取 `max`,再回退到配置的第一个档位。合成 Codex 模型始终启用并行工具调用。
|
|
772
|
+
- `reasoningField`:可选,OpenAI-compatible `/v1/messages` 转发 assistant 思考文本时使用的字段,支持 `reasoning` 与 `reasoning_content`,默认 `reasoning_content`;OpenRouter 风格模型设为 `reasoning`,内置目录已为 OpenCode Go `hy3`、`hy4-preview` 配置该值。
|
|
770
773
|
- **smallModel:** 无工具预热消息的回退模型(例如 Claude Code 的探测请求);默认是 `gpt-5-mini`。网关会对无工具的预热或探测请求强制使用该小模型,以避免消耗 premium 请求。该行为仅在 GitHub Copilot 账户为非 token-based 计费时生效(`token_based_billing` 为 false);对于 token-based 计费账户,预热小模型回退会被跳过,因为不存在需要节省的 premium 请求配额。
|
|
771
774
|
- **contextManagement:** 控制代理是否为 Responses API 附加 `context_management` 压缩指令。`messages` 作用于被翻译成 Responses API 的 Anthropic 风格 `/v1/messages` 请求,包括 `openai-responses` provider 的 Messages 路由,默认值为 `true`。`responses` 作用于 native `/v1/responses` 流量,包括 `provider/model` 别名和内置 `codex` provider,默认值为 `false`。只有在确认客户端支持 context management compaction 后,才建议在 Responses API 下启用 `responses`。启用后,请求体会带上 `context_management`,并在后续轮次中仅保留最新的压缩承载内容。代理仅为 `gpt-*` 模型添加 context management 并压缩历史;这两个配置开关对 Grok 等非 GPT 模型不生效。**注意:** 对于 GPT-5.6 及以上模型(如 `gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-5.6-luna`),context management 功能同样会被强制禁用,因为开启后会破坏这些模型的 prompt 缓存命中。这些强制覆盖优先于 `contextManagement` 和 `modelResponsesApiCompactThresholds` 配置。
|
|
772
775
|
- **modelResponsesApiCompactThresholds:** 按模型覆盖 Responses API 的 `compact_threshold`,仅在代理自动附加 `context_management` 时使用。它的优先级高于 `resolveResponsesCompactThreshold` 基于 `max_prompt_tokens * ratio` 的兜底阈值。默认将 `gpt-5.4` 和 `gpt-5.5` 设为 `217600`(`272000 * 0.8`)。未列出的模型继续使用原有兜底逻辑。
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-ByEK-9s6.js","names":["fs"],"sources":["../src/lib/atomic-file.ts","../src/lib/paths.ts","../src/lib/config-store.ts","../src/lib/model-policy.ts","../src/lib/provider-config.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs\"\nimport path from \"node:path\"\n\nconst TEMP_FILE_RANDOM_BYTES = 8\n\n// The file-level fsync persists the contents, but the rename only updates the\n// parent directory entry, which needs its own fsync to survive a crash or\n// power loss. Best-effort: the rename has already taken effect, so a failure\n// here only weakens crash durability and must not fail the write. Directory\n// fsync is not supported on Windows (opening a directory handle fails there).\nconst fsyncDirectory = (directory: string): void => {\n if (process.platform === \"win32\") {\n return\n }\n\n let directoryFd: number | undefined\n try {\n directoryFd = fs.openSync(directory, \"r\")\n fs.fsyncSync(directoryFd)\n } catch (error) {\n console.warn(`Failed to fsync directory: ${directory}`, error)\n } finally {\n if (directoryFd !== undefined) {\n try {\n fs.closeSync(directoryFd)\n } catch {\n // Preserve the fsync warning.\n }\n }\n }\n}\n\nexport function writeFileAtomically(filePath: string, content: string): void {\n const directory = path.dirname(filePath)\n const tempPath = path.join(\n directory,\n `.${path.basename(filePath)}.${process.pid}.${randomBytes(TEMP_FILE_RANDOM_BYTES).toString(\"hex\")}.tmp`,\n )\n\n fs.mkdirSync(directory, { recursive: true })\n\n let fileDescriptor: number | undefined\n let tempFileCreated = false\n try {\n fileDescriptor = fs.openSync(tempPath, \"wx\", 0o600)\n tempFileCreated = true\n fs.writeFileSync(fileDescriptor, content, \"utf8\")\n fs.fsyncSync(fileDescriptor)\n fs.closeSync(fileDescriptor)\n fileDescriptor = undefined\n fs.renameSync(tempPath, filePath)\n tempFileCreated = false\n fsyncDirectory(directory)\n } catch (error) {\n if (fileDescriptor !== undefined) {\n try {\n fs.closeSync(fileDescriptor)\n } catch {\n // Preserve the original write error.\n }\n }\n\n if (tempFileCreated) {\n try {\n fs.rmSync(tempPath, { force: true })\n } catch {\n // Preserve the original write error.\n }\n }\n\n throw error\n }\n}\n","import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nconst AUTH_APP = process.env.COPILOT_API_OAUTH_APP?.trim() || \"\"\nconst ENTERPRISE_PREFIX = process.env.COPILOT_API_ENTERPRISE_URL ? \"ent_\" : \"\"\n\nconst DEFAULT_DIR = path.join(os.homedir(), \".local\", \"share\", \"copilot-api\")\nconst APP_DIR = process.env.COPILOT_API_HOME || DEFAULT_DIR\n\nconst GITHUB_TOKEN_PATH = path.join(\n APP_DIR,\n AUTH_APP,\n ENTERPRISE_PREFIX + \"github_token\",\n)\nconst CODEX_CREDENTIAL_PATH = path.join(APP_DIR, \"codex_credentials.json\")\nconst CONFIG_PATH = path.join(APP_DIR, \"config.json\")\n\nexport const PATHS = {\n APP_DIR,\n GITHUB_TOKEN_PATH,\n CODEX_CREDENTIAL_PATH,\n CONFIG_PATH,\n}\n\nexport async function ensurePaths(): Promise<void> {\n await fs.mkdir(path.join(PATHS.APP_DIR, AUTH_APP), { recursive: true })\n await ensureFile(PATHS.GITHUB_TOKEN_PATH)\n await ensureFile(PATHS.CONFIG_PATH)\n}\n\nasync function ensureFile(filePath: string): Promise<void> {\n try {\n await fs.access(filePath, fs.constants.W_OK)\n } catch {\n await fs.writeFile(filePath, \"\")\n await fs.chmod(filePath, 0o600)\n }\n}\n","import consola from \"consola\"\nimport { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs\"\n\nimport type { TokenUsagePricingConfig } from \"~/lib/token-usage/pricing\"\n\nimport { writeFileAtomically } from \"./atomic-file\"\nimport { PATHS } from \"./paths\"\n\nexport interface AppConfig {\n auth?: {\n apiKeys?: Array<string>\n adminApiKey?: string\n }\n providers?: Record<string, ProviderConfig>\n modelMappings?: Record<string, string>\n extraPrompts?: Record<string, string>\n smallModel?: string\n contextManagement?: ContextManagementConfig\n modelResponsesApiCompactThresholds?: Record<string, number>\n modelReasoningEfforts?: Record<\n string,\n \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\"\n >\n useMessagesApi?: boolean\n useResponsesApiWebSocket?: boolean\n responsesTransport?: ResponsesTransportConfig\n anthropicApiKey?: string\n useResponsesApiWebSearch?: boolean\n alphaSearchCodexPriority?: boolean\n alphaSearchModel?: string\n // Copilot rejects Anthropic's web_search server tool on /v1/messages, so a\n // Claude request that only asks for web search is switched to this model.\n // A `provider/model` alias is passed straight through to that provider's\n // (websearch-capable) message API, while a plain GPT model runs the search\n // via /responses. Leave unset to disable (the tool is then stripped).\n // Mixing web_search with other tools is not supported.\n messageApiWebSearchModel?: string\n // Model used for Claude Code background security-monitor requests on\n // /v1/messages and provider message APIs: requests without tools, with\n // `stop_sequences: [\"</block>\"]` and a system block starting with\n // \"You are a security monitor for autonomous AI coding agents.\".\n // A `provider/model` alias is forwarded to that provider's message API on\n // the top-level route. Provider message routes use the configured value on\n // their current provider. Leave empty to disable (default).\n claudeAutoModel?: string\n claudeTokenMultiplier?: number\n}\n\nexport interface ContextManagementConfig {\n messages?: boolean\n responses?: boolean\n}\n\nexport interface ResponsesTransportConfig {\n headersTimeoutMsV2?: number\n streamInactivityTimeoutMs?: number\n websocketMaxBufferedBytes?: number\n websocketMaxBufferedMessages?: number\n websocketOpenTimeoutMs?: number\n websocketPoolIdleTimeoutMs?: number\n}\n\nexport const defaultResponsesTransportConfig = {\n headersTimeoutMsV2: 5 * 60 * 1000,\n streamInactivityTimeoutMs: 5 * 60 * 1000,\n websocketMaxBufferedBytes: 8 * 1024 * 1024,\n websocketMaxBufferedMessages: 1024,\n websocketOpenTimeoutMs: 30_000,\n websocketPoolIdleTimeoutMs: 60_000,\n} satisfies Required<ResponsesTransportConfig>\n\nexport interface ModelConfig {\n temperature?: number\n topP?: number\n topK?: number\n extraBody?: Record<string, unknown>\n contextCache?: boolean\n contextWindow?: number\n maxOutputTokens?: number\n inputModalities?: Array<\"text\" | \"image\">\n reasoningEfforts?: Array<CodexReasoningEffort>\n defaultReasoningEffort?: CodexReasoningEffort\n pricing?: TokenUsagePricingConfig\n supportPdf?: boolean\n toolContentSupportType?: Array<ToolContentSupportType>\n type?: ProviderType\n}\n\nexport type CodexReasoningEffort =\n | \"none\"\n | \"minimal\"\n | \"low\"\n | \"medium\"\n | \"high\"\n | \"xhigh\"\n | \"max\"\n | \"ultra\"\n\nexport type ProviderAuthType = \"authorization\" | \"oauth2\" | \"x-api-key\"\nexport const SUPPORTED_PROVIDER_TYPES = [\n \"anthropic\",\n \"openai-compatible\",\n \"openai-responses\",\n] as const\nexport type ProviderType = (typeof SUPPORTED_PROVIDER_TYPES)[number]\nexport type ToolContentSupportType = \"array\" | \"image\" | \"pdf\"\n\nexport interface ProviderConfig {\n type?: string\n enabled?: boolean\n baseUrl?: string\n apiKey?: string\n authType?: ProviderAuthType\n pricingCurrency?: string\n models?: Record<string, ModelConfig>\n}\n\nconst gpt5ExplorationPrompt = `## Exploration and reading files\n- **Think first.** Before any tool call, decide ALL files/resources you will need.\n- **Batch everything.** If you need multiple files (even from different places), read them together.\n- **multi_tool_use.parallel** Use multi_tool_use.parallel to parallelize tool calls and only this.\n- **Only make sequential calls if you truly cannot know the next file without seeing a result first.**\n- **Workflow:** (a) plan all needed reads → (b) issue one parallel batch → (c) analyze results → (d) repeat if new, unpredictable reads arise.`\n\nconst modelResponsesApiCompactThresholds = {\n \"gpt-5.4\": 272_000 * 0.8,\n \"gpt-5.5\": 272_000 * 0.8,\n}\n\nexport const defaultContextManagement = {\n messages: true,\n responses: false,\n} satisfies Required<ContextManagementConfig>\n\nexport const defaultConfig: AppConfig = {\n auth: {\n apiKeys: [],\n },\n providers: {},\n modelMappings: {},\n extraPrompts: {\n \"gpt-5-mini\": gpt5ExplorationPrompt,\n },\n smallModel: \"gpt-5-mini\",\n contextManagement: defaultContextManagement,\n modelResponsesApiCompactThresholds,\n modelReasoningEfforts: {\n \"gpt-5-mini\": \"low\",\n },\n useMessagesApi: true,\n useResponsesApiWebSocket: true,\n responsesTransport: defaultResponsesTransportConfig,\n useResponsesApiWebSearch: true,\n alphaSearchCodexPriority: true,\n alphaSearchModel: \"gpt-5-mini\",\n messageApiWebSearchModel: \"gpt-5-mini\",\n}\n\nlet cachedConfig: AppConfig | null = null\n\nfunction normalizeAdminApiKey(adminApiKey: unknown): string | null {\n if (typeof adminApiKey !== \"string\") {\n if (adminApiKey !== undefined) {\n consola.warn(\n \"Invalid auth.adminApiKey config. Expected a non-empty string.\",\n )\n }\n return null\n }\n\n const normalizedAdminApiKey = adminApiKey.trim()\n if (!normalizedAdminApiKey) {\n consola.warn(\n \"Invalid auth.adminApiKey config. Expected a non-empty string.\",\n )\n return null\n }\n\n return normalizedAdminApiKey\n}\n\nfunction generateAdminApiKey(): string {\n return randomBytes(32).toString(\"hex\")\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error\n}\n\nfunction ensureConfigFile(): void {\n try {\n fs.accessSync(PATHS.CONFIG_PATH, fs.constants.R_OK | fs.constants.W_OK)\n } catch {\n writeFileAtomically(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\n )\n try {\n fs.chmodSync(PATHS.CONFIG_PATH, 0o600)\n } catch {\n return\n }\n }\n}\n\nfunction readConfigFromDisk(): AppConfig {\n ensureConfigFile()\n const raw = fs.readFileSync(PATHS.CONFIG_PATH, \"utf8\")\n if (!raw.trim()) {\n writeFileAtomically(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\n )\n return defaultConfig\n }\n\n try {\n return JSON.parse(raw) as AppConfig\n } catch (error) {\n // Fail closed: falling back to the default config here would let the\n // startup merge overwrite the corrupt file (discarding providers, API\n // keys, and model mappings) and, because the default has no apiKeys,\n // silently disable API key authentication on normal routes.\n const message = `Config file is not valid JSON: ${PATHS.CONFIG_PATH}. Refusing to start with the default config. Fix the JSON syntax or delete the file to regenerate a fresh config.`\n consola.error(message, error)\n throw new Error(message, { cause: error })\n }\n}\n\nexport function readEditableConfigFromDisk(): AppConfig {\n try {\n const raw = fs.readFileSync(PATHS.CONFIG_PATH, \"utf8\")\n if (!raw.trim()) {\n return {}\n }\n return JSON.parse(raw) as AppConfig\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return {}\n }\n if (error instanceof SyntaxError) {\n throw new Error(`Config file is not valid JSON: ${PATHS.CONFIG_PATH}`)\n }\n throw error\n }\n}\n\nexport function writeConfigToDisk(config: AppConfig): void {\n writeFileAtomically(PATHS.CONFIG_PATH, `${JSON.stringify(config, null, 2)}\\n`)\n}\n\nexport function setConfiguredApiKeys(apiKeys: Array<string>): Array<string> {\n const normalizedKeys = apiKeys\n .map((key) => key.trim())\n .filter((key) => key.length > 0)\n const uniqueKeys = [...new Set(normalizedKeys)]\n\n const editableConfig = readEditableConfigFromDisk()\n writeConfigToDisk({\n ...editableConfig,\n auth: {\n ...editableConfig.auth,\n apiKeys: uniqueKeys,\n },\n })\n reloadConfig()\n return [...uniqueKeys]\n}\n\nfunction mergeDefaultConfig(config: AppConfig): {\n mergedConfig: AppConfig\n changed: boolean\n} {\n const extraPrompts = config.extraPrompts ?? {}\n const defaultExtraPrompts = defaultConfig.extraPrompts ?? {}\n const responsesApiCompactThresholds =\n config.modelResponsesApiCompactThresholds ?? {}\n const defaultResponsesApiCompactThresholds =\n defaultConfig.modelResponsesApiCompactThresholds ?? {}\n const modelReasoningEfforts = config.modelReasoningEfforts ?? {}\n const defaultModelReasoningEfforts = defaultConfig.modelReasoningEfforts ?? {}\n const contextManagement = normalizeContextManagementConfig(\n config.contextManagement,\n )\n const responsesTransport = normalizeResponsesTransportConfig(\n config.responsesTransport,\n )\n const defaultContextManagementConfig = defaultConfig.contextManagement ?? {}\n\n const missingExtraPromptModels = Object.keys(defaultExtraPrompts).filter(\n (model) => !Object.hasOwn(extraPrompts, model),\n )\n\n const missingReasoningEffortModels = Object.keys(\n defaultModelReasoningEfforts,\n ).filter((model) => !Object.hasOwn(modelReasoningEfforts, model))\n const missingResponsesApiCompactThresholdModels = Object.keys(\n defaultResponsesApiCompactThresholds,\n ).filter((model) => !Object.hasOwn(responsesApiCompactThresholds, model))\n const missingContextManagementKeys = Object.keys(\n defaultContextManagementConfig,\n ).filter((key) => !Object.hasOwn(contextManagement, key))\n\n const hasExtraPromptChanges = missingExtraPromptModels.length > 0\n const hasReasoningEffortChanges = missingReasoningEffortModels.length > 0\n const hasResponsesApiCompactThresholdChanges =\n missingResponsesApiCompactThresholdModels.length > 0\n const hasContextManagementChanges = missingContextManagementKeys.length > 0\n const hasResponsesTransportChanges = Object.entries(responsesTransport).some(\n ([key, value]) =>\n config.responsesTransport?.[key as keyof ResponsesTransportConfig]\n !== value,\n )\n\n if (\n !hasExtraPromptChanges\n && !hasReasoningEffortChanges\n && !hasResponsesApiCompactThresholdChanges\n && !hasContextManagementChanges\n && !hasResponsesTransportChanges\n ) {\n return { mergedConfig: config, changed: false }\n }\n\n return {\n mergedConfig: {\n ...config,\n contextManagement: {\n ...defaultContextManagementConfig,\n ...contextManagement,\n },\n extraPrompts: {\n ...defaultExtraPrompts,\n ...extraPrompts,\n },\n modelResponsesApiCompactThresholds: {\n ...defaultResponsesApiCompactThresholds,\n ...responsesApiCompactThresholds,\n },\n modelReasoningEfforts: {\n ...defaultModelReasoningEfforts,\n ...modelReasoningEfforts,\n },\n responsesTransport,\n },\n changed: true,\n }\n}\n\nfunction normalizeContextManagementConfig(\n value: ContextManagementConfig | undefined,\n): ContextManagementConfig {\n if (!value || typeof value !== \"object\") {\n return {}\n }\n\n return {\n ...(typeof value.messages === \"boolean\" ?\n { messages: value.messages }\n : {}),\n ...(typeof value.responses === \"boolean\" ?\n { responses: value.responses }\n : {}),\n }\n}\n\nfunction ensureAdminApiKey(config: AppConfig): {\n mergedConfig: AppConfig\n changed: boolean\n} {\n const normalizedAdminApiKey = normalizeAdminApiKey(config.auth?.adminApiKey)\n if (normalizedAdminApiKey) {\n if (config.auth?.adminApiKey === normalizedAdminApiKey) {\n return { mergedConfig: config, changed: false }\n }\n\n return {\n mergedConfig: {\n ...config,\n auth: {\n ...config.auth,\n adminApiKey: normalizedAdminApiKey,\n },\n },\n changed: true,\n }\n }\n\n const editableConfig = readEditableConfigFromDisk()\n const { mergedConfig } = mergeDefaultConfig({\n ...editableConfig,\n auth: {\n ...editableConfig.auth,\n adminApiKey: generateAdminApiKey(),\n },\n })\n\n return { mergedConfig, changed: true }\n}\n\nexport function mergeConfigWithDefaults(): AppConfig {\n const config = readConfigFromDisk()\n const { mergedConfig, changed } = mergeDefaultConfig(config)\n const {\n mergedConfig: mergedConfigWithAdminApiKey,\n changed: adminApiKeyChanged,\n } = ensureAdminApiKey(mergedConfig)\n const shouldPersistConfig = changed || adminApiKeyChanged\n\n if (shouldPersistConfig) {\n try {\n writeConfigToDisk(mergedConfigWithAdminApiKey)\n } catch (writeError) {\n if (adminApiKeyChanged) {\n throw writeError\n }\n\n consola.warn(\n \"Failed to write merged default config to config file\",\n writeError,\n )\n }\n }\n\n cachedConfig = mergedConfigWithAdminApiKey\n return mergedConfigWithAdminApiKey\n}\n\nexport function getConfig(): AppConfig {\n cachedConfig ??= mergeDefaultConfig(readConfigFromDisk()).mergedConfig\n return cachedConfig\n}\n\nexport function reloadConfig(): AppConfig {\n return mergeConfigWithDefaults()\n}\n\nexport function isMessagesApiEnabled(): boolean {\n const config = getConfig()\n return config.useMessagesApi ?? true\n}\n\nexport function isResponsesApiWebSocketEnabled(): boolean {\n const config = getConfig()\n return config.useResponsesApiWebSocket ?? true\n}\n\nexport function getResponsesTransportConfig() {\n const { headersTimeoutMsV2, ...config } = normalizeResponsesTransportConfig(\n getConfig().responsesTransport,\n )\n return { headersTimeoutMs: headersTimeoutMsV2, ...config }\n}\n\nexport const normalizeResponsesTransportConfig = (\n configured: ResponsesTransportConfig | undefined,\n): Required<ResponsesTransportConfig> => ({\n headersTimeoutMsV2: positiveIntegerOrDefault(\n configured?.headersTimeoutMsV2,\n defaultResponsesTransportConfig.headersTimeoutMsV2,\n ),\n streamInactivityTimeoutMs: positiveIntegerOrDefault(\n configured?.streamInactivityTimeoutMs,\n defaultResponsesTransportConfig.streamInactivityTimeoutMs,\n ),\n websocketMaxBufferedBytes: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedBytes,\n defaultResponsesTransportConfig.websocketMaxBufferedBytes,\n ),\n websocketMaxBufferedMessages: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedMessages,\n defaultResponsesTransportConfig.websocketMaxBufferedMessages,\n ),\n websocketOpenTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketOpenTimeoutMs,\n defaultResponsesTransportConfig.websocketOpenTimeoutMs,\n ),\n websocketPoolIdleTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketPoolIdleTimeoutMs,\n defaultResponsesTransportConfig.websocketPoolIdleTimeoutMs,\n ),\n})\n\nconst positiveIntegerOrDefault = (value: unknown, fallback: number): number => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback\n\n const normalized = Math.floor(value)\n return normalized > 0 ? normalized : fallback\n}\n\nexport function getAnthropicApiKey(): string | undefined {\n const config = getConfig()\n return config.anthropicApiKey ?? process.env.ANTHROPIC_API_KEY ?? undefined\n}\n\nexport function isResponsesApiWebSearchEnabled(): boolean {\n const config = getConfig()\n return config.useResponsesApiWebSearch ?? true\n}\n\nexport function isAlphaSearchCodexPriorityEnabled(): boolean {\n const config = getConfig()\n return config.alphaSearchCodexPriority ?? true\n}\n\nexport function getAlphaSearchModel(): string | undefined {\n const model = getConfig().alphaSearchModel ?? \"gpt-5-mini\"\n return model.trim() || undefined\n}\n\nexport function getMessageApiWebSearchModel(): string | undefined {\n const config = getConfig()\n const model = config.messageApiWebSearchModel ?? \"gpt-5-mini\"\n return model && model.trim().length > 0 ? model : undefined\n}\n\nexport function getClaudeAutoModel(): string | undefined {\n const config = getConfig()\n const model = config.claudeAutoModel\n return model && model.trim().length > 0 ? model.trim() : undefined\n}\n\nexport function getClaudeTokenMultiplier(): number {\n const config = getConfig()\n return config.claudeTokenMultiplier ?? 1.15\n}\n","import {\n defaultConfig,\n defaultContextManagement,\n getConfig,\n readEditableConfigFromDisk,\n reloadConfig,\n writeConfigToDisk,\n} from \"./config-store\"\n\nconst GPT_MODEL_PATTERN = /^gpt-(\\d+)(?:\\.(\\d+))?/\n\nfunction isGpt53OrAbove(model: string): boolean {\n const match = GPT_MODEL_PATTERN.exec(model)\n if (!match) {\n return false\n }\n const majorVersion = Number.parseInt(match[1], 10)\n if (majorVersion > 5) {\n return true\n }\n if (majorVersion !== 5) {\n return false\n }\n const minorVersion = match[2] ? Number.parseInt(match[2], 10) : 0\n return minorVersion >= 3\n}\n\nexport function isGpt56OrAbove(model: string): boolean {\n const match = GPT_MODEL_PATTERN.exec(model)\n if (!match) {\n return false\n }\n const majorVersion = Number.parseInt(match[1], 10)\n if (majorVersion > 5) {\n return true\n }\n if (majorVersion !== 5) {\n return false\n }\n const minorVersion = match[2] ? Number.parseInt(match[2], 10) : 0\n return minorVersion >= 6\n}\n\nconst gpt5CommentaryPrompt = `# Working with the user\n\nYou interact with the user through a terminal. You have 2 ways of communicating with the users: \n- Share intermediary updates in \\`commentary\\` channel. \n- After you have completed all your work, send a message to the \\`final\\` channel. \n\n## Intermediary updates\n\n- Intermediary updates go to the \\`commentary\\` channel.\n- User updates are short updates while you are working, they are NOT final answers.\n- You use 1-2 sentence user updates to communicate progress and new information to the user as you are doing work.\n- Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements (“Done —”, “Got it”, “Great question, ”) or framing phrases.\n- You provide user updates frequently, every 20s.\n- Before exploring or doing substantial work, you start with a user update acknowledging the request and explaining your first step. You should include your understanding of the user request and explain what you will do. Avoid commenting on the request or using starters such as \"Got it -\" or \"Understood -\" etc.\n- When exploring, e.g. searching, reading files, you provide user updates as you go, every 20s, explaining what context you are gathering and what you've learned. Vary your sentence structure when providing these updates to avoid sounding repetitive - in particular, don't start each sentence the same way.\n- After you have sufficient context, and the work is substantial, you provide a longer plan (this is the only user update that may be longer than 2 sentences and can contain formatting).\n- Before performing file edits of any kind, you provide updates explaining what edits you are making.\n- As you are thinking, you very frequently provide updates even if not taking any actions, informing the user of your progress. You interrupt your thinking and send multiple updates in a row if thinking for more than 100 words.\n- Tone of your updates MUST match your personality.`\n\nexport function getExtraPromptForModel(model: string): string {\n const config = getConfig()\n const userPrompt = config.extraPrompts?.[model]\n if (userPrompt !== undefined) {\n return userPrompt\n }\n return isGpt53OrAbove(model) ? gpt5CommentaryPrompt : \"\"\n}\n\nexport function getModelMappings(): Record<string, string> {\n const config = getConfig()\n const modelMappings = config.modelMappings\n if (!modelMappings) {\n return { ...defaultConfig.modelMappings }\n }\n\n const validMappings: Record<string, string> = {}\n for (const [sourceModel, targetModel] of Object.entries(modelMappings)) {\n if (\n !sourceModel\n || typeof targetModel !== \"string\"\n || targetModel.length === 0\n ) {\n continue\n }\n validMappings[sourceModel] = targetModel\n }\n\n return validMappings\n}\n\nfunction validateModelMappings(\n modelMappings: Record<string, string>,\n): Record<string, string> {\n const validatedMappings: Record<string, string> = {}\n for (const [sourceModel, targetModel] of Object.entries(modelMappings)) {\n if (!sourceModel || !targetModel) {\n throw new Error(\n \"Each model mapping must use non-empty source and target values.\",\n )\n }\n validatedMappings[sourceModel] = targetModel\n }\n\n return validatedMappings\n}\n\nexport function setModelMappings(\n modelMappings: Record<string, string>,\n): Record<string, string> {\n const nextConfig = {\n ...readEditableConfigFromDisk(),\n modelMappings: validateModelMappings(modelMappings),\n }\n\n writeConfigToDisk(nextConfig)\n reloadConfig()\n return getModelMappings()\n}\n\nexport function resolveMappedModel(model: string): string {\n return getModelMappings()[model] ?? model\n}\n\nexport function getSmallModel(): string {\n const config = getConfig()\n return config.smallModel ?? \"gpt-5-mini\"\n}\n\nexport function isContextManagementEnabledForMessages(): boolean {\n const config = getConfig()\n return config.contextManagement?.messages ?? defaultContextManagement.messages\n}\n\nexport function isContextManagementEnabledForResponses(): boolean {\n const config = getConfig()\n return (\n config.contextManagement?.responses ?? defaultContextManagement.responses\n )\n}\n\nexport function getModelResponsesApiCompactThreshold(\n model: string,\n): number | undefined {\n const config = getConfig()\n const threshold = config.modelResponsesApiCompactThresholds?.[model]\n\n if (\n typeof threshold !== \"number\"\n || !Number.isFinite(threshold)\n || threshold <= 0\n ) {\n return undefined\n }\n\n return threshold\n}\n\nexport function getReasoningEffortForModel(\n model: string,\n): \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" {\n const config = getConfig()\n const userEffort = config.modelReasoningEfforts?.[model]\n if (userEffort !== undefined) {\n return userEffort\n }\n return isGpt53OrAbove(model) ? \"xhigh\" : \"high\"\n}\n","import consola from \"consola\"\n\nimport {\n SUPPORTED_PROVIDER_TYPES,\n getConfig,\n readEditableConfigFromDisk,\n reloadConfig,\n writeConfigToDisk,\n type ModelConfig,\n type ProviderAuthType,\n type ProviderConfig,\n type ProviderType,\n} from \"./config-store\"\n\nexport interface ResolvedProviderConfig {\n name: string\n type: ProviderType\n baseUrl: string\n apiKey: string\n authType: ProviderAuthType\n pricingCurrency?: string\n models?: Record<string, ModelConfig>\n}\n\nconst OPENCODE_ANTHROPIC_MODEL_PATTERN = /^(?:qwen|minimax)/iu\nconst OPENCODE_RESPONSES_MODEL_PATTERN = /^(?:gpt|grok|muse-spark)(?:[-_.]|$)/iu\n\nexport function normalizeProviderBaseUrl(url: string): string {\n return url.trim().replace(/\\/+$/u, \"\")\n}\n\nexport function isSupportedProviderType(value: string): value is ProviderType {\n return SUPPORTED_PROVIDER_TYPES.includes(value as ProviderType)\n}\n\nfunction getDefaultProviderAuthType(\n providerType: ProviderType,\n): ProviderAuthType {\n return providerType === \"anthropic\" ? \"x-api-key\" : \"authorization\"\n}\n\nexport function resolveProviderAuthType(\n providerName: string,\n authType: string | undefined,\n providerType: ProviderType,\n): ProviderAuthType {\n const defaultAuthType = getDefaultProviderAuthType(providerType)\n if (authType === undefined) {\n return defaultAuthType\n }\n\n if (authType === \"x-api-key\") {\n return \"x-api-key\"\n }\n\n if (authType === \"oauth2\") {\n if (providerName === \"codex\") {\n return authType\n }\n\n consola.warn(\n `Provider ${providerName} has authType 'oauth2', which is only supported by the builtin codex provider, falling back to ${defaultAuthType}`,\n )\n return defaultAuthType\n }\n\n if (authType === \"authorization\") {\n return authType\n }\n\n consola.warn(\n `Provider ${providerName} has invalid authType '${authType}', falling back to ${defaultAuthType}`,\n )\n return defaultAuthType\n}\n\nfunction isProviderApiKeyRequired(\n providerName: string,\n authType: ProviderAuthType,\n): boolean {\n return !(providerName === \"codex\" && authType === \"oauth2\")\n}\n\nexport function getRawProviderConfig(name: string): ProviderConfig | null {\n const providerName = name.trim()\n if (!providerName) {\n return null\n }\n\n const config = getConfig()\n return config.providers?.[providerName] ?? null\n}\n\nexport function setProviderConfig(\n name: string,\n provider: ProviderConfig,\n): ProviderConfig {\n const providerName = name.trim()\n if (!providerName) {\n throw new Error(\"Provider name must be a non-empty string\")\n }\n\n if (isReservedProviderName(providerName)) {\n throw new Error(\n `Provider ${providerName} is reserved and cannot be configured in config.providers`,\n )\n }\n\n const editableConfig = readEditableConfigFromDisk()\n const nextConfig = {\n ...editableConfig,\n providers: {\n ...editableConfig.providers,\n [providerName]: provider,\n },\n }\n\n writeConfigToDisk(nextConfig)\n reloadConfig()\n return getRawProviderConfig(providerName) ?? provider\n}\n\nexport function getProviderConfig(name: string): ResolvedProviderConfig | null {\n const providerName = name.trim()\n if (!providerName) {\n return null\n }\n\n if (isReservedProviderName(providerName)) {\n consola.warn(\n `Provider ${providerName} is reserved and cannot be configured in config.providers`,\n )\n return null\n }\n\n const provider = getRawProviderConfig(providerName)\n if (!provider) {\n return null\n }\n\n if (provider.enabled === false) {\n return null\n }\n\n const type = provider.type ?? \"anthropic\"\n if (!isSupportedProviderType(type)) {\n consola.warn(\n `Provider ${providerName} is ignored because type '${type}' is not supported`,\n )\n return null\n }\n\n const baseUrl = normalizeProviderBaseUrl(provider.baseUrl ?? \"\")\n const authType = resolveProviderAuthType(\n providerName,\n provider.authType,\n type,\n )\n const apiKey = (provider.apiKey ?? \"\").trim()\n const missingFields = [\n ...(baseUrl ? [] : [\"baseUrl\"]),\n ...(isProviderApiKeyRequired(providerName, authType) && !apiKey ?\n [\"apiKey\"]\n : []),\n ]\n\n if (missingFields.length > 0) {\n consola.warn(\n `Provider ${providerName} is enabled but missing ${missingFields.join(\" or \")}`,\n )\n return null\n }\n\n return {\n name: providerName,\n type,\n baseUrl,\n apiKey,\n authType,\n pricingCurrency: normalizePricingCurrency(provider.pricingCurrency),\n models: provider.models,\n }\n}\n\nexport function resolveEffectiveProviderType(\n providerConfig: ResolvedProviderConfig,\n model: string,\n): ProviderType {\n const modelConfig = providerConfig.models?.[model]\n if (modelConfig?.type && isSupportedProviderType(modelConfig.type)) {\n return modelConfig.type\n }\n\n if (providerConfig.name === \"opencode-go\") {\n if (OPENCODE_ANTHROPIC_MODEL_PATTERN.test(model)) {\n return \"anthropic\"\n }\n if (OPENCODE_RESPONSES_MODEL_PATTERN.test(model)) {\n return \"openai-responses\"\n }\n }\n\n return providerConfig.type\n}\n\nfunction normalizePricingCurrency(\n value: string | undefined,\n): string | undefined {\n const currency = value?.trim().toUpperCase()\n return currency || undefined\n}\n\nexport function listEnabledProviders(): Array<string> {\n const config = getConfig()\n const providerNames = Object.keys(config.providers ?? {})\n return providerNames.filter((name) => getProviderConfig(name) !== null)\n}\n\nexport function isReservedProviderName(name: string): boolean {\n return name.trim() === \"copilot\"\n}\n"],"mappings":";;;;;;;AAIA,MAAM,yBAAyB;AAO/B,MAAM,kBAAk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
|
1
|
+
{"version":3,"file":"config-ByEK-9s6.js","names":["fs"],"sources":["../src/lib/atomic-file.ts","../src/lib/paths.ts","../src/lib/config-store.ts","../src/lib/model-policy.ts","../src/lib/provider-config.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs\"\nimport path from \"node:path\"\n\nconst TEMP_FILE_RANDOM_BYTES = 8\n\n// The file-level fsync persists the contents, but the rename only updates the\n// parent directory entry, which needs its own fsync to survive a crash or\n// power loss. Best-effort: the rename has already taken effect, so a failure\n// here only weakens crash durability and must not fail the write. Directory\n// fsync is not supported on Windows (opening a directory handle fails there).\nconst fsyncDirectory = (directory: string): void => {\n if (process.platform === \"win32\") {\n return\n }\n\n let directoryFd: number | undefined\n try {\n directoryFd = fs.openSync(directory, \"r\")\n fs.fsyncSync(directoryFd)\n } catch (error) {\n console.warn(`Failed to fsync directory: ${directory}`, error)\n } finally {\n if (directoryFd !== undefined) {\n try {\n fs.closeSync(directoryFd)\n } catch {\n // Preserve the fsync warning.\n }\n }\n }\n}\n\nexport function writeFileAtomically(filePath: string, content: string): void {\n const directory = path.dirname(filePath)\n const tempPath = path.join(\n directory,\n `.${path.basename(filePath)}.${process.pid}.${randomBytes(TEMP_FILE_RANDOM_BYTES).toString(\"hex\")}.tmp`,\n )\n\n fs.mkdirSync(directory, { recursive: true })\n\n let fileDescriptor: number | undefined\n let tempFileCreated = false\n try {\n fileDescriptor = fs.openSync(tempPath, \"wx\", 0o600)\n tempFileCreated = true\n fs.writeFileSync(fileDescriptor, content, \"utf8\")\n fs.fsyncSync(fileDescriptor)\n fs.closeSync(fileDescriptor)\n fileDescriptor = undefined\n fs.renameSync(tempPath, filePath)\n tempFileCreated = false\n fsyncDirectory(directory)\n } catch (error) {\n if (fileDescriptor !== undefined) {\n try {\n fs.closeSync(fileDescriptor)\n } catch {\n // Preserve the original write error.\n }\n }\n\n if (tempFileCreated) {\n try {\n fs.rmSync(tempPath, { force: true })\n } catch {\n // Preserve the original write error.\n }\n }\n\n throw error\n }\n}\n","import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nconst AUTH_APP = process.env.COPILOT_API_OAUTH_APP?.trim() || \"\"\nconst ENTERPRISE_PREFIX = process.env.COPILOT_API_ENTERPRISE_URL ? \"ent_\" : \"\"\n\nconst DEFAULT_DIR = path.join(os.homedir(), \".local\", \"share\", \"copilot-api\")\nconst APP_DIR = process.env.COPILOT_API_HOME || DEFAULT_DIR\n\nconst GITHUB_TOKEN_PATH = path.join(\n APP_DIR,\n AUTH_APP,\n ENTERPRISE_PREFIX + \"github_token\",\n)\nconst CODEX_CREDENTIAL_PATH = path.join(APP_DIR, \"codex_credentials.json\")\nconst CONFIG_PATH = path.join(APP_DIR, \"config.json\")\n\nexport const PATHS = {\n APP_DIR,\n GITHUB_TOKEN_PATH,\n CODEX_CREDENTIAL_PATH,\n CONFIG_PATH,\n}\n\nexport async function ensurePaths(): Promise<void> {\n await fs.mkdir(path.join(PATHS.APP_DIR, AUTH_APP), { recursive: true })\n await ensureFile(PATHS.GITHUB_TOKEN_PATH)\n await ensureFile(PATHS.CONFIG_PATH)\n}\n\nasync function ensureFile(filePath: string): Promise<void> {\n try {\n await fs.access(filePath, fs.constants.W_OK)\n } catch {\n await fs.writeFile(filePath, \"\")\n await fs.chmod(filePath, 0o600)\n }\n}\n","import consola from \"consola\"\nimport { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs\"\n\nimport type { TokenUsagePricingConfig } from \"~/lib/token-usage/pricing\"\n\nimport { writeFileAtomically } from \"./atomic-file\"\nimport { PATHS } from \"./paths\"\n\nexport interface AppConfig {\n auth?: {\n apiKeys?: Array<string>\n adminApiKey?: string\n }\n providers?: Record<string, ProviderConfig>\n modelMappings?: Record<string, string>\n extraPrompts?: Record<string, string>\n smallModel?: string\n contextManagement?: ContextManagementConfig\n modelResponsesApiCompactThresholds?: Record<string, number>\n modelReasoningEfforts?: Record<\n string,\n \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\"\n >\n useMessagesApi?: boolean\n useResponsesApiWebSocket?: boolean\n responsesTransport?: ResponsesTransportConfig\n anthropicApiKey?: string\n useResponsesApiWebSearch?: boolean\n alphaSearchCodexPriority?: boolean\n alphaSearchModel?: string\n // Copilot rejects Anthropic's web_search server tool on /v1/messages, so a\n // Claude request that only asks for web search is switched to this model.\n // A `provider/model` alias is passed straight through to that provider's\n // (websearch-capable) message API, while a plain GPT model runs the search\n // via /responses. Leave unset to disable (the tool is then stripped).\n // Mixing web_search with other tools is not supported.\n messageApiWebSearchModel?: string\n // Model used for Claude Code background security-monitor requests on\n // /v1/messages and provider message APIs: requests without tools, with\n // `stop_sequences: [\"</block>\"]` and a system block starting with\n // \"You are a security monitor for autonomous AI coding agents.\".\n // A `provider/model` alias is forwarded to that provider's message API on\n // the top-level route. Provider message routes use the configured value on\n // their current provider. Leave empty to disable (default).\n claudeAutoModel?: string\n claudeTokenMultiplier?: number\n}\n\nexport interface ContextManagementConfig {\n messages?: boolean\n responses?: boolean\n}\n\nexport interface ResponsesTransportConfig {\n headersTimeoutMsV2?: number\n streamInactivityTimeoutMs?: number\n websocketMaxBufferedBytes?: number\n websocketMaxBufferedMessages?: number\n websocketOpenTimeoutMs?: number\n websocketPoolIdleTimeoutMs?: number\n}\n\nexport const defaultResponsesTransportConfig = {\n headersTimeoutMsV2: 5 * 60 * 1000,\n streamInactivityTimeoutMs: 5 * 60 * 1000,\n websocketMaxBufferedBytes: 8 * 1024 * 1024,\n websocketMaxBufferedMessages: 1024,\n websocketOpenTimeoutMs: 30_000,\n websocketPoolIdleTimeoutMs: 60_000,\n} satisfies Required<ResponsesTransportConfig>\n\nexport interface ModelConfig {\n temperature?: number\n topP?: number\n topK?: number\n extraBody?: Record<string, unknown>\n contextCache?: boolean\n contextWindow?: number\n maxOutputTokens?: number\n inputModalities?: Array<\"text\" | \"image\">\n reasoningEfforts?: Array<CodexReasoningEffort>\n defaultReasoningEffort?: CodexReasoningEffort\n pricing?: TokenUsagePricingConfig\n supportPdf?: boolean\n toolContentSupportType?: Array<ToolContentSupportType>\n type?: ProviderType\n // Message field used to carry assistant thinking text when forwarding\n // requests upstream; defaults to \"reasoning_content\"\n reasoningField?: ModelReasoningField\n}\n\nexport type ModelReasoningField = \"reasoning\" | \"reasoning_content\"\n\nexport type CodexReasoningEffort =\n | \"none\"\n | \"minimal\"\n | \"low\"\n | \"medium\"\n | \"high\"\n | \"xhigh\"\n | \"max\"\n | \"ultra\"\n\nexport type ProviderAuthType = \"authorization\" | \"oauth2\" | \"x-api-key\"\nexport const SUPPORTED_PROVIDER_TYPES = [\n \"anthropic\",\n \"openai-compatible\",\n \"openai-responses\",\n] as const\nexport type ProviderType = (typeof SUPPORTED_PROVIDER_TYPES)[number]\nexport type ToolContentSupportType = \"array\" | \"image\" | \"pdf\"\n\nexport interface ProviderConfig {\n type?: string\n enabled?: boolean\n baseUrl?: string\n apiKey?: string\n authType?: ProviderAuthType\n pricingCurrency?: string\n models?: Record<string, ModelConfig>\n}\n\nconst gpt5ExplorationPrompt = `## Exploration and reading files\n- **Think first.** Before any tool call, decide ALL files/resources you will need.\n- **Batch everything.** If you need multiple files (even from different places), read them together.\n- **multi_tool_use.parallel** Use multi_tool_use.parallel to parallelize tool calls and only this.\n- **Only make sequential calls if you truly cannot know the next file without seeing a result first.**\n- **Workflow:** (a) plan all needed reads → (b) issue one parallel batch → (c) analyze results → (d) repeat if new, unpredictable reads arise.`\n\nconst modelResponsesApiCompactThresholds = {\n \"gpt-5.4\": 272_000 * 0.8,\n \"gpt-5.5\": 272_000 * 0.8,\n}\n\nexport const defaultContextManagement = {\n messages: true,\n responses: false,\n} satisfies Required<ContextManagementConfig>\n\nexport const defaultConfig: AppConfig = {\n auth: {\n apiKeys: [],\n },\n providers: {},\n modelMappings: {},\n extraPrompts: {\n \"gpt-5-mini\": gpt5ExplorationPrompt,\n },\n smallModel: \"gpt-5-mini\",\n contextManagement: defaultContextManagement,\n modelResponsesApiCompactThresholds,\n modelReasoningEfforts: {\n \"gpt-5-mini\": \"low\",\n },\n useMessagesApi: true,\n useResponsesApiWebSocket: true,\n responsesTransport: defaultResponsesTransportConfig,\n useResponsesApiWebSearch: true,\n alphaSearchCodexPriority: true,\n alphaSearchModel: \"gpt-5-mini\",\n messageApiWebSearchModel: \"gpt-5-mini\",\n}\n\nlet cachedConfig: AppConfig | null = null\n\nfunction normalizeAdminApiKey(adminApiKey: unknown): string | null {\n if (typeof adminApiKey !== \"string\") {\n if (adminApiKey !== undefined) {\n consola.warn(\n \"Invalid auth.adminApiKey config. Expected a non-empty string.\",\n )\n }\n return null\n }\n\n const normalizedAdminApiKey = adminApiKey.trim()\n if (!normalizedAdminApiKey) {\n consola.warn(\n \"Invalid auth.adminApiKey config. Expected a non-empty string.\",\n )\n return null\n }\n\n return normalizedAdminApiKey\n}\n\nfunction generateAdminApiKey(): string {\n return randomBytes(32).toString(\"hex\")\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error\n}\n\nfunction ensureConfigFile(): void {\n try {\n fs.accessSync(PATHS.CONFIG_PATH, fs.constants.R_OK | fs.constants.W_OK)\n } catch {\n writeFileAtomically(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\n )\n try {\n fs.chmodSync(PATHS.CONFIG_PATH, 0o600)\n } catch {\n return\n }\n }\n}\n\nfunction readConfigFromDisk(): AppConfig {\n ensureConfigFile()\n const raw = fs.readFileSync(PATHS.CONFIG_PATH, \"utf8\")\n if (!raw.trim()) {\n writeFileAtomically(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\n )\n return defaultConfig\n }\n\n try {\n return JSON.parse(raw) as AppConfig\n } catch (error) {\n // Fail closed: falling back to the default config here would let the\n // startup merge overwrite the corrupt file (discarding providers, API\n // keys, and model mappings) and, because the default has no apiKeys,\n // silently disable API key authentication on normal routes.\n const message = `Config file is not valid JSON: ${PATHS.CONFIG_PATH}. Refusing to start with the default config. Fix the JSON syntax or delete the file to regenerate a fresh config.`\n consola.error(message, error)\n throw new Error(message, { cause: error })\n }\n}\n\nexport function readEditableConfigFromDisk(): AppConfig {\n try {\n const raw = fs.readFileSync(PATHS.CONFIG_PATH, \"utf8\")\n if (!raw.trim()) {\n return {}\n }\n return JSON.parse(raw) as AppConfig\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return {}\n }\n if (error instanceof SyntaxError) {\n throw new Error(`Config file is not valid JSON: ${PATHS.CONFIG_PATH}`)\n }\n throw error\n }\n}\n\nexport function writeConfigToDisk(config: AppConfig): void {\n writeFileAtomically(PATHS.CONFIG_PATH, `${JSON.stringify(config, null, 2)}\\n`)\n}\n\nexport function setConfiguredApiKeys(apiKeys: Array<string>): Array<string> {\n const normalizedKeys = apiKeys\n .map((key) => key.trim())\n .filter((key) => key.length > 0)\n const uniqueKeys = [...new Set(normalizedKeys)]\n\n const editableConfig = readEditableConfigFromDisk()\n writeConfigToDisk({\n ...editableConfig,\n auth: {\n ...editableConfig.auth,\n apiKeys: uniqueKeys,\n },\n })\n reloadConfig()\n return [...uniqueKeys]\n}\n\nfunction mergeDefaultConfig(config: AppConfig): {\n mergedConfig: AppConfig\n changed: boolean\n} {\n const extraPrompts = config.extraPrompts ?? {}\n const defaultExtraPrompts = defaultConfig.extraPrompts ?? {}\n const responsesApiCompactThresholds =\n config.modelResponsesApiCompactThresholds ?? {}\n const defaultResponsesApiCompactThresholds =\n defaultConfig.modelResponsesApiCompactThresholds ?? {}\n const modelReasoningEfforts = config.modelReasoningEfforts ?? {}\n const defaultModelReasoningEfforts = defaultConfig.modelReasoningEfforts ?? {}\n const contextManagement = normalizeContextManagementConfig(\n config.contextManagement,\n )\n const responsesTransport = normalizeResponsesTransportConfig(\n config.responsesTransport,\n )\n const defaultContextManagementConfig = defaultConfig.contextManagement ?? {}\n\n const missingExtraPromptModels = Object.keys(defaultExtraPrompts).filter(\n (model) => !Object.hasOwn(extraPrompts, model),\n )\n\n const missingReasoningEffortModels = Object.keys(\n defaultModelReasoningEfforts,\n ).filter((model) => !Object.hasOwn(modelReasoningEfforts, model))\n const missingResponsesApiCompactThresholdModels = Object.keys(\n defaultResponsesApiCompactThresholds,\n ).filter((model) => !Object.hasOwn(responsesApiCompactThresholds, model))\n const missingContextManagementKeys = Object.keys(\n defaultContextManagementConfig,\n ).filter((key) => !Object.hasOwn(contextManagement, key))\n\n const hasExtraPromptChanges = missingExtraPromptModels.length > 0\n const hasReasoningEffortChanges = missingReasoningEffortModels.length > 0\n const hasResponsesApiCompactThresholdChanges =\n missingResponsesApiCompactThresholdModels.length > 0\n const hasContextManagementChanges = missingContextManagementKeys.length > 0\n const hasResponsesTransportChanges = Object.entries(responsesTransport).some(\n ([key, value]) =>\n config.responsesTransport?.[key as keyof ResponsesTransportConfig]\n !== value,\n )\n\n if (\n !hasExtraPromptChanges\n && !hasReasoningEffortChanges\n && !hasResponsesApiCompactThresholdChanges\n && !hasContextManagementChanges\n && !hasResponsesTransportChanges\n ) {\n return { mergedConfig: config, changed: false }\n }\n\n return {\n mergedConfig: {\n ...config,\n contextManagement: {\n ...defaultContextManagementConfig,\n ...contextManagement,\n },\n extraPrompts: {\n ...defaultExtraPrompts,\n ...extraPrompts,\n },\n modelResponsesApiCompactThresholds: {\n ...defaultResponsesApiCompactThresholds,\n ...responsesApiCompactThresholds,\n },\n modelReasoningEfforts: {\n ...defaultModelReasoningEfforts,\n ...modelReasoningEfforts,\n },\n responsesTransport,\n },\n changed: true,\n }\n}\n\nfunction normalizeContextManagementConfig(\n value: ContextManagementConfig | undefined,\n): ContextManagementConfig {\n if (!value || typeof value !== \"object\") {\n return {}\n }\n\n return {\n ...(typeof value.messages === \"boolean\" ?\n { messages: value.messages }\n : {}),\n ...(typeof value.responses === \"boolean\" ?\n { responses: value.responses }\n : {}),\n }\n}\n\nfunction ensureAdminApiKey(config: AppConfig): {\n mergedConfig: AppConfig\n changed: boolean\n} {\n const normalizedAdminApiKey = normalizeAdminApiKey(config.auth?.adminApiKey)\n if (normalizedAdminApiKey) {\n if (config.auth?.adminApiKey === normalizedAdminApiKey) {\n return { mergedConfig: config, changed: false }\n }\n\n return {\n mergedConfig: {\n ...config,\n auth: {\n ...config.auth,\n adminApiKey: normalizedAdminApiKey,\n },\n },\n changed: true,\n }\n }\n\n const editableConfig = readEditableConfigFromDisk()\n const { mergedConfig } = mergeDefaultConfig({\n ...editableConfig,\n auth: {\n ...editableConfig.auth,\n adminApiKey: generateAdminApiKey(),\n },\n })\n\n return { mergedConfig, changed: true }\n}\n\nexport function mergeConfigWithDefaults(): AppConfig {\n const config = readConfigFromDisk()\n const { mergedConfig, changed } = mergeDefaultConfig(config)\n const {\n mergedConfig: mergedConfigWithAdminApiKey,\n changed: adminApiKeyChanged,\n } = ensureAdminApiKey(mergedConfig)\n const shouldPersistConfig = changed || adminApiKeyChanged\n\n if (shouldPersistConfig) {\n try {\n writeConfigToDisk(mergedConfigWithAdminApiKey)\n } catch (writeError) {\n if (adminApiKeyChanged) {\n throw writeError\n }\n\n consola.warn(\n \"Failed to write merged default config to config file\",\n writeError,\n )\n }\n }\n\n cachedConfig = mergedConfigWithAdminApiKey\n return mergedConfigWithAdminApiKey\n}\n\nexport function getConfig(): AppConfig {\n cachedConfig ??= mergeDefaultConfig(readConfigFromDisk()).mergedConfig\n return cachedConfig\n}\n\nexport function reloadConfig(): AppConfig {\n return mergeConfigWithDefaults()\n}\n\nexport function isMessagesApiEnabled(): boolean {\n const config = getConfig()\n return config.useMessagesApi ?? true\n}\n\nexport function isResponsesApiWebSocketEnabled(): boolean {\n const config = getConfig()\n return config.useResponsesApiWebSocket ?? true\n}\n\nexport function getResponsesTransportConfig() {\n const { headersTimeoutMsV2, ...config } = normalizeResponsesTransportConfig(\n getConfig().responsesTransport,\n )\n return { headersTimeoutMs: headersTimeoutMsV2, ...config }\n}\n\nexport const normalizeResponsesTransportConfig = (\n configured: ResponsesTransportConfig | undefined,\n): Required<ResponsesTransportConfig> => ({\n headersTimeoutMsV2: positiveIntegerOrDefault(\n configured?.headersTimeoutMsV2,\n defaultResponsesTransportConfig.headersTimeoutMsV2,\n ),\n streamInactivityTimeoutMs: positiveIntegerOrDefault(\n configured?.streamInactivityTimeoutMs,\n defaultResponsesTransportConfig.streamInactivityTimeoutMs,\n ),\n websocketMaxBufferedBytes: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedBytes,\n defaultResponsesTransportConfig.websocketMaxBufferedBytes,\n ),\n websocketMaxBufferedMessages: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedMessages,\n defaultResponsesTransportConfig.websocketMaxBufferedMessages,\n ),\n websocketOpenTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketOpenTimeoutMs,\n defaultResponsesTransportConfig.websocketOpenTimeoutMs,\n ),\n websocketPoolIdleTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketPoolIdleTimeoutMs,\n defaultResponsesTransportConfig.websocketPoolIdleTimeoutMs,\n ),\n})\n\nconst positiveIntegerOrDefault = (value: unknown, fallback: number): number => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback\n\n const normalized = Math.floor(value)\n return normalized > 0 ? normalized : fallback\n}\n\nexport function getAnthropicApiKey(): string | undefined {\n const config = getConfig()\n return config.anthropicApiKey ?? process.env.ANTHROPIC_API_KEY ?? undefined\n}\n\nexport function isResponsesApiWebSearchEnabled(): boolean {\n const config = getConfig()\n return config.useResponsesApiWebSearch ?? true\n}\n\nexport function isAlphaSearchCodexPriorityEnabled(): boolean {\n const config = getConfig()\n return config.alphaSearchCodexPriority ?? true\n}\n\nexport function getAlphaSearchModel(): string | undefined {\n const model = getConfig().alphaSearchModel ?? \"gpt-5-mini\"\n return model.trim() || undefined\n}\n\nexport function getMessageApiWebSearchModel(): string | undefined {\n const config = getConfig()\n const model = config.messageApiWebSearchModel ?? \"gpt-5-mini\"\n return model && model.trim().length > 0 ? model : undefined\n}\n\nexport function getClaudeAutoModel(): string | undefined {\n const config = getConfig()\n const model = config.claudeAutoModel\n return model && model.trim().length > 0 ? model.trim() : undefined\n}\n\nexport function getClaudeTokenMultiplier(): number {\n const config = getConfig()\n return config.claudeTokenMultiplier ?? 1.15\n}\n","import {\n defaultConfig,\n defaultContextManagement,\n getConfig,\n readEditableConfigFromDisk,\n reloadConfig,\n writeConfigToDisk,\n} from \"./config-store\"\n\nconst GPT_MODEL_PATTERN = /^gpt-(\\d+)(?:\\.(\\d+))?/\n\nfunction isGpt53OrAbove(model: string): boolean {\n const match = GPT_MODEL_PATTERN.exec(model)\n if (!match) {\n return false\n }\n const majorVersion = Number.parseInt(match[1], 10)\n if (majorVersion > 5) {\n return true\n }\n if (majorVersion !== 5) {\n return false\n }\n const minorVersion = match[2] ? Number.parseInt(match[2], 10) : 0\n return minorVersion >= 3\n}\n\nexport function isGpt56OrAbove(model: string): boolean {\n const match = GPT_MODEL_PATTERN.exec(model)\n if (!match) {\n return false\n }\n const majorVersion = Number.parseInt(match[1], 10)\n if (majorVersion > 5) {\n return true\n }\n if (majorVersion !== 5) {\n return false\n }\n const minorVersion = match[2] ? Number.parseInt(match[2], 10) : 0\n return minorVersion >= 6\n}\n\nconst gpt5CommentaryPrompt = `# Working with the user\n\nYou interact with the user through a terminal. You have 2 ways of communicating with the users: \n- Share intermediary updates in \\`commentary\\` channel. \n- After you have completed all your work, send a message to the \\`final\\` channel. \n\n## Intermediary updates\n\n- Intermediary updates go to the \\`commentary\\` channel.\n- User updates are short updates while you are working, they are NOT final answers.\n- You use 1-2 sentence user updates to communicate progress and new information to the user as you are doing work.\n- Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements (“Done —”, “Got it”, “Great question, ”) or framing phrases.\n- You provide user updates frequently, every 20s.\n- Before exploring or doing substantial work, you start with a user update acknowledging the request and explaining your first step. You should include your understanding of the user request and explain what you will do. Avoid commenting on the request or using starters such as \"Got it -\" or \"Understood -\" etc.\n- When exploring, e.g. searching, reading files, you provide user updates as you go, every 20s, explaining what context you are gathering and what you've learned. Vary your sentence structure when providing these updates to avoid sounding repetitive - in particular, don't start each sentence the same way.\n- After you have sufficient context, and the work is substantial, you provide a longer plan (this is the only user update that may be longer than 2 sentences and can contain formatting).\n- Before performing file edits of any kind, you provide updates explaining what edits you are making.\n- As you are thinking, you very frequently provide updates even if not taking any actions, informing the user of your progress. You interrupt your thinking and send multiple updates in a row if thinking for more than 100 words.\n- Tone of your updates MUST match your personality.`\n\nexport function getExtraPromptForModel(model: string): string {\n const config = getConfig()\n const userPrompt = config.extraPrompts?.[model]\n if (userPrompt !== undefined) {\n return userPrompt\n }\n return isGpt53OrAbove(model) ? gpt5CommentaryPrompt : \"\"\n}\n\nexport function getModelMappings(): Record<string, string> {\n const config = getConfig()\n const modelMappings = config.modelMappings\n if (!modelMappings) {\n return { ...defaultConfig.modelMappings }\n }\n\n const validMappings: Record<string, string> = {}\n for (const [sourceModel, targetModel] of Object.entries(modelMappings)) {\n if (\n !sourceModel\n || typeof targetModel !== \"string\"\n || targetModel.length === 0\n ) {\n continue\n }\n validMappings[sourceModel] = targetModel\n }\n\n return validMappings\n}\n\nfunction validateModelMappings(\n modelMappings: Record<string, string>,\n): Record<string, string> {\n const validatedMappings: Record<string, string> = {}\n for (const [sourceModel, targetModel] of Object.entries(modelMappings)) {\n if (!sourceModel || !targetModel) {\n throw new Error(\n \"Each model mapping must use non-empty source and target values.\",\n )\n }\n validatedMappings[sourceModel] = targetModel\n }\n\n return validatedMappings\n}\n\nexport function setModelMappings(\n modelMappings: Record<string, string>,\n): Record<string, string> {\n const nextConfig = {\n ...readEditableConfigFromDisk(),\n modelMappings: validateModelMappings(modelMappings),\n }\n\n writeConfigToDisk(nextConfig)\n reloadConfig()\n return getModelMappings()\n}\n\nexport function resolveMappedModel(model: string): string {\n return getModelMappings()[model] ?? model\n}\n\nexport function getSmallModel(): string {\n const config = getConfig()\n return config.smallModel ?? \"gpt-5-mini\"\n}\n\nexport function isContextManagementEnabledForMessages(): boolean {\n const config = getConfig()\n return config.contextManagement?.messages ?? defaultContextManagement.messages\n}\n\nexport function isContextManagementEnabledForResponses(): boolean {\n const config = getConfig()\n return (\n config.contextManagement?.responses ?? defaultContextManagement.responses\n )\n}\n\nexport function getModelResponsesApiCompactThreshold(\n model: string,\n): number | undefined {\n const config = getConfig()\n const threshold = config.modelResponsesApiCompactThresholds?.[model]\n\n if (\n typeof threshold !== \"number\"\n || !Number.isFinite(threshold)\n || threshold <= 0\n ) {\n return undefined\n }\n\n return threshold\n}\n\nexport function getReasoningEffortForModel(\n model: string,\n): \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" {\n const config = getConfig()\n const userEffort = config.modelReasoningEfforts?.[model]\n if (userEffort !== undefined) {\n return userEffort\n }\n return isGpt53OrAbove(model) ? \"xhigh\" : \"high\"\n}\n","import consola from \"consola\"\n\nimport {\n SUPPORTED_PROVIDER_TYPES,\n getConfig,\n readEditableConfigFromDisk,\n reloadConfig,\n writeConfigToDisk,\n type ModelConfig,\n type ProviderAuthType,\n type ProviderConfig,\n type ProviderType,\n} from \"./config-store\"\n\nexport interface ResolvedProviderConfig {\n name: string\n type: ProviderType\n baseUrl: string\n apiKey: string\n authType: ProviderAuthType\n pricingCurrency?: string\n models?: Record<string, ModelConfig>\n}\n\nconst OPENCODE_ANTHROPIC_MODEL_PATTERN = /^(?:qwen|minimax)/iu\nconst OPENCODE_RESPONSES_MODEL_PATTERN = /^(?:gpt|grok|muse-spark)(?:[-_.]|$)/iu\n\nexport function normalizeProviderBaseUrl(url: string): string {\n return url.trim().replace(/\\/+$/u, \"\")\n}\n\nexport function isSupportedProviderType(value: string): value is ProviderType {\n return SUPPORTED_PROVIDER_TYPES.includes(value as ProviderType)\n}\n\nfunction getDefaultProviderAuthType(\n providerType: ProviderType,\n): ProviderAuthType {\n return providerType === \"anthropic\" ? \"x-api-key\" : \"authorization\"\n}\n\nexport function resolveProviderAuthType(\n providerName: string,\n authType: string | undefined,\n providerType: ProviderType,\n): ProviderAuthType {\n const defaultAuthType = getDefaultProviderAuthType(providerType)\n if (authType === undefined) {\n return defaultAuthType\n }\n\n if (authType === \"x-api-key\") {\n return \"x-api-key\"\n }\n\n if (authType === \"oauth2\") {\n if (providerName === \"codex\") {\n return authType\n }\n\n consola.warn(\n `Provider ${providerName} has authType 'oauth2', which is only supported by the builtin codex provider, falling back to ${defaultAuthType}`,\n )\n return defaultAuthType\n }\n\n if (authType === \"authorization\") {\n return authType\n }\n\n consola.warn(\n `Provider ${providerName} has invalid authType '${authType}', falling back to ${defaultAuthType}`,\n )\n return defaultAuthType\n}\n\nfunction isProviderApiKeyRequired(\n providerName: string,\n authType: ProviderAuthType,\n): boolean {\n return !(providerName === \"codex\" && authType === \"oauth2\")\n}\n\nexport function getRawProviderConfig(name: string): ProviderConfig | null {\n const providerName = name.trim()\n if (!providerName) {\n return null\n }\n\n const config = getConfig()\n return config.providers?.[providerName] ?? null\n}\n\nexport function setProviderConfig(\n name: string,\n provider: ProviderConfig,\n): ProviderConfig {\n const providerName = name.trim()\n if (!providerName) {\n throw new Error(\"Provider name must be a non-empty string\")\n }\n\n if (isReservedProviderName(providerName)) {\n throw new Error(\n `Provider ${providerName} is reserved and cannot be configured in config.providers`,\n )\n }\n\n const editableConfig = readEditableConfigFromDisk()\n const nextConfig = {\n ...editableConfig,\n providers: {\n ...editableConfig.providers,\n [providerName]: provider,\n },\n }\n\n writeConfigToDisk(nextConfig)\n reloadConfig()\n return getRawProviderConfig(providerName) ?? provider\n}\n\nexport function getProviderConfig(name: string): ResolvedProviderConfig | null {\n const providerName = name.trim()\n if (!providerName) {\n return null\n }\n\n if (isReservedProviderName(providerName)) {\n consola.warn(\n `Provider ${providerName} is reserved and cannot be configured in config.providers`,\n )\n return null\n }\n\n const provider = getRawProviderConfig(providerName)\n if (!provider) {\n return null\n }\n\n if (provider.enabled === false) {\n return null\n }\n\n const type = provider.type ?? \"anthropic\"\n if (!isSupportedProviderType(type)) {\n consola.warn(\n `Provider ${providerName} is ignored because type '${type}' is not supported`,\n )\n return null\n }\n\n const baseUrl = normalizeProviderBaseUrl(provider.baseUrl ?? \"\")\n const authType = resolveProviderAuthType(\n providerName,\n provider.authType,\n type,\n )\n const apiKey = (provider.apiKey ?? \"\").trim()\n const missingFields = [\n ...(baseUrl ? [] : [\"baseUrl\"]),\n ...(isProviderApiKeyRequired(providerName, authType) && !apiKey ?\n [\"apiKey\"]\n : []),\n ]\n\n if (missingFields.length > 0) {\n consola.warn(\n `Provider ${providerName} is enabled but missing ${missingFields.join(\" or \")}`,\n )\n return null\n }\n\n return {\n name: providerName,\n type,\n baseUrl,\n apiKey,\n authType,\n pricingCurrency: normalizePricingCurrency(provider.pricingCurrency),\n models: provider.models,\n }\n}\n\nexport function resolveEffectiveProviderType(\n providerConfig: ResolvedProviderConfig,\n model: string,\n): ProviderType {\n const modelConfig = providerConfig.models?.[model]\n if (modelConfig?.type && isSupportedProviderType(modelConfig.type)) {\n return modelConfig.type\n }\n\n if (providerConfig.name === \"opencode-go\") {\n if (OPENCODE_ANTHROPIC_MODEL_PATTERN.test(model)) {\n return \"anthropic\"\n }\n if (OPENCODE_RESPONSES_MODEL_PATTERN.test(model)) {\n return \"openai-responses\"\n }\n }\n\n return providerConfig.type\n}\n\nfunction normalizePricingCurrency(\n value: string | undefined,\n): string | undefined {\n const currency = value?.trim().toUpperCase()\n return currency || undefined\n}\n\nexport function listEnabledProviders(): Array<string> {\n const config = getConfig()\n const providerNames = Object.keys(config.providers ?? {})\n return providerNames.filter((name) => getProviderConfig(name) !== null)\n}\n\nexport function isReservedProviderName(name: string): boolean {\n return name.trim() === \"copilot\"\n}\n"],"mappings":";;;;;;;AAIA,MAAM,yBAAyB;AAO/B,MAAM,kBAAkB,cAA4B;CAClD,IAAI,QAAQ,aAAa,SACvB;CAGF,IAAI;CACJ,IAAI;EACF,cAAc,GAAG,SAAS,WAAW,IAAI;EACzC,GAAG,UAAU,YAAY;UAClB,OAAO;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ClC,QAAQ,KACN,YAAY,aAAa,4BAA4B,KAAK,oBAC3D;EACD,OAAO;;CAGT,MAAM,UAAU,yBAAyB,SAAS,WAAW,GAAG;CAChE,MAAM,WAAW,wBACf,cACA,SAAS,UACT,KACD;CACD,MAAM,UAAU,SAAS,UAAU,IAAI,MAAM;CAC7C,MAAM,gBAAgB,CACpB,GAAI,UAAU,EAAE,GAAG,CAAC,UAAU,EAC9B,GAAI,yBAAyB,cAAc,SAAS,IAAI,CAAC,SACvD,CAAC,SAAS,GACV,EAAE,CACL;CAED,IAAI,cAAc,SAAS,GAAG;EAC5B,QAAQ,KACN,YAAY,aAAa,0BAA0B,cAAc,KAAK,OAAO,GAC9E;EACD,OAAO;;CAGT,OAAO;EACL,MAAM;EACN;EACA;EACA;EACA;EACA,iBAAiB,yBAAyB,SAAS,gBAAgB;EACnE,QAAQ,SAAS;EAClB;;AAGH,SAAgB,6BACd,gBACA,OACc;CACd,MAAM,cAAc,eAAe,SAAS;CAC5C,IAAI,aAAa,QAAQ,wBAAwB,YAAY,KAAK,EAChE,OAAO,YAAY;CAGrB,IAAI,eAAe,SAAS,eAAe;EACzC,IAAI,iCAAiC,KAAK,MAAM,EAC9C,OAAO;EAET,IAAI,iCAAiC,KAAK,MAAM,EAC9C,OAAO;;CAIX,OAAO,eAAe;;AAGxB,SAAS,yBACP,OACoB;CAEpB,OADiB,OAAO,MAAM,CAAC,aAAa,IACzB,KAAA;;AAGrB,SAAgB,uBAAsC;CACpD,MAAM,SAAS,WAAW;CAE1B,OADsB,OAAO,KAAK,OAAO,aAAa,EAAE,CACpC,CAAC,QAAQ,SAAS,kBAAkB,KAAK,KAAK,KAAK;;AAGzE,SAAgB,uBAAuB,MAAuB;CAC5D,OAAO,KAAK,MAAM,KAAK"}
|
package/dist/main.js
CHANGED
|
@@ -30,7 +30,7 @@ if (isMcpFastPath(process.argv)) {
|
|
|
30
30
|
const { auth } = await import("./auth-DgKX2oyO.js");
|
|
31
31
|
const { debug } = await import("./debug-BHOitPm3.js");
|
|
32
32
|
const { mcp } = await import("./mcp-fpSlKZxK.js");
|
|
33
|
-
const { start } = await import("./start-
|
|
33
|
+
const { start } = await import("./start-BaYrtsEL.js");
|
|
34
34
|
await runMain(defineCommand({
|
|
35
35
|
meta: {
|
|
36
36
|
name: "copilot-api",
|
|
@@ -626,7 +626,8 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
|
|
|
626
626
|
cachedInput: .035,
|
|
627
627
|
input: .14,
|
|
628
628
|
output: .58
|
|
629
|
-
}
|
|
629
|
+
},
|
|
630
|
+
reasoningField: "reasoning"
|
|
630
631
|
},
|
|
631
632
|
"hy4-preview": {
|
|
632
633
|
contextWindow: 1024e3,
|
|
@@ -637,7 +638,8 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
|
|
|
637
638
|
input: .834,
|
|
638
639
|
output: 2.501
|
|
639
640
|
},
|
|
640
|
-
reasoningEfforts: ["high"]
|
|
641
|
+
reasoningEfforts: ["high"],
|
|
642
|
+
reasoningField: "reasoning"
|
|
641
643
|
},
|
|
642
644
|
"gpt-5.6-luna": { pricing: { tiers: [{
|
|
643
645
|
cacheCreationInput: .125,
|
|
@@ -3937,7 +3939,7 @@ function mapOpenAIChatCompletionUsage(response) {
|
|
|
3937
3939
|
return usage;
|
|
3938
3940
|
}
|
|
3939
3941
|
function getOpenAIReasoningText(message) {
|
|
3940
|
-
return message.reasoning_text ?? message.reasoning_content;
|
|
3942
|
+
return message.reasoning_text ?? message.reasoning_content ?? message.reasoning;
|
|
3941
3943
|
}
|
|
3942
3944
|
function getAnthropicTextBlocks(messageContent) {
|
|
3943
3945
|
if (typeof messageContent === "string" && messageContent.length > 0) return [{
|
|
@@ -4834,12 +4836,13 @@ function handleReasoningOpaque(delta, events, state) {
|
|
|
4834
4836
|
}
|
|
4835
4837
|
}
|
|
4836
4838
|
function handleThinkingText(delta, state, events) {
|
|
4837
|
-
const reasoningText = delta.reasoning_text ?? delta.reasoning_content;
|
|
4839
|
+
const reasoningText = delta.reasoning_text ?? delta.reasoning_content ?? delta.reasoning;
|
|
4838
4840
|
if (reasoningText && reasoningText.length > 0) {
|
|
4839
4841
|
if (state.contentBlockOpen) {
|
|
4840
4842
|
delta.content = reasoningText;
|
|
4841
4843
|
delta.reasoning_text = void 0;
|
|
4842
4844
|
delta.reasoning_content = void 0;
|
|
4845
|
+
delta.reasoning = void 0;
|
|
4843
4846
|
return;
|
|
4844
4847
|
}
|
|
4845
4848
|
if (!state.thinkingBlockOpen) {
|
|
@@ -6987,7 +6990,10 @@ const createOpenAICompatiblePayload = (payload, modelConfig, providerConfig) =>
|
|
|
6987
6990
|
else delete openAIPayload.thinking_budget;
|
|
6988
6991
|
if (payload.top_k !== void 0) openAIPayload.top_k = payload.top_k;
|
|
6989
6992
|
if (openAIPayload.stream) openAIPayload.stream_options = { include_usage: true };
|
|
6990
|
-
normalizeOpenAICompatibleReasoningContent(openAIPayload
|
|
6993
|
+
normalizeOpenAICompatibleReasoningContent(openAIPayload, {
|
|
6994
|
+
modelConfig,
|
|
6995
|
+
providerConfig
|
|
6996
|
+
});
|
|
6991
6997
|
applyOpenAICompatibleRequestOverrides(openAIPayload, {
|
|
6992
6998
|
extraBody: modelConfig?.extraBody,
|
|
6993
6999
|
source: payload
|
|
@@ -6999,10 +7005,15 @@ const createOpenAICompatiblePayload = (payload, modelConfig, providerConfig) =>
|
|
|
6999
7005
|
if (modelConfig?.contextCache ?? isDashScopeProvider) applyOpenAICompatibleContextCache(openAIPayload);
|
|
7000
7006
|
return openAIPayload;
|
|
7001
7007
|
};
|
|
7002
|
-
const normalizeOpenAICompatibleReasoningContent = (payload) => {
|
|
7008
|
+
const normalizeOpenAICompatibleReasoningContent = (payload, options) => {
|
|
7009
|
+
const reasoningField = options.modelConfig?.reasoningField ?? builtinProviderModelRegistry.getModelConfig(options.providerConfig.name, payload.model)?.reasoningField ?? "reasoning_content";
|
|
7003
7010
|
for (const message of payload.messages) {
|
|
7004
7011
|
if (message.role !== "assistant") continue;
|
|
7005
|
-
|
|
7012
|
+
const reasoningText = message.reasoning_text ?? message.reasoning_content ?? message.reasoning;
|
|
7013
|
+
if (reasoningText && reasoningText.length > 0) if (reasoningField === "reasoning") message.reasoning ??= reasoningText;
|
|
7014
|
+
else message.reasoning_content ??= reasoningText;
|
|
7015
|
+
if (reasoningField === "reasoning") delete message.reasoning_content;
|
|
7016
|
+
else delete message.reasoning;
|
|
7006
7017
|
delete message.reasoning_text;
|
|
7007
7018
|
delete message.reasoning_opaque;
|
|
7008
7019
|
}
|
|
@@ -8686,6 +8697,9 @@ providerModelRoutes.get("/", async (c) => {
|
|
|
8686
8697
|
//#endregion
|
|
8687
8698
|
//#region src/routes/responses/messages-translation.ts
|
|
8688
8699
|
const MESSAGES_COMPACTION_PREFIX = "copilot-api:messages-compaction:v1:";
|
|
8700
|
+
const MESSAGES_REASONING_ID_SUFFIX = "__a1";
|
|
8701
|
+
const markMessagesReasoningId = (id) => `${id}${MESSAGES_REASONING_ID_SUFFIX}`;
|
|
8702
|
+
const isMessagesReasoningId = (id) => typeof id === "string" && id.endsWith(MESSAGES_REASONING_ID_SUFFIX);
|
|
8689
8703
|
const MESSAGES_COMPACTION_PROMPT = [
|
|
8690
8704
|
"You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.",
|
|
8691
8705
|
"Do NOT continue the task, make changes, or call any tools. Your only output must be the handoff summary.",
|
|
@@ -9195,7 +9209,7 @@ function translateAssistantOutput(response, registry) {
|
|
|
9195
9209
|
for (const [index, block] of response.content.entries()) {
|
|
9196
9210
|
if (block.type === "thinking") {
|
|
9197
9211
|
output.push({
|
|
9198
|
-
id: `rs_${createStableHash(`${response.id}:${index}:reasoning`)}
|
|
9212
|
+
id: markMessagesReasoningId(`rs_${createStableHash(`${response.id}:${index}:reasoning`)}`),
|
|
9199
9213
|
type: "reasoning",
|
|
9200
9214
|
status: "completed",
|
|
9201
9215
|
...block.thinking && block.thinking !== "Thinking..." ? { summary: [{
|
|
@@ -9227,7 +9241,6 @@ function translateAssistantOutput(response, registry) {
|
|
|
9227
9241
|
function translateToolUseOutput(block, registry, idSeed) {
|
|
9228
9242
|
const descriptor = resolveToolDescriptor(registry, block.name);
|
|
9229
9243
|
const common = {
|
|
9230
|
-
id: `fc_${createStableHash(idSeed)}`,
|
|
9231
9244
|
call_id: block.id,
|
|
9232
9245
|
name: descriptor.name,
|
|
9233
9246
|
status: "completed",
|
|
@@ -9235,11 +9248,13 @@ function translateToolUseOutput(block, registry, idSeed) {
|
|
|
9235
9248
|
};
|
|
9236
9249
|
if (descriptor.kind === "custom") return {
|
|
9237
9250
|
...common,
|
|
9251
|
+
id: `ctc_${createStableHash(idSeed)}`,
|
|
9238
9252
|
type: "custom_tool_call",
|
|
9239
9253
|
input: decodeCustomToolInput(block.input)
|
|
9240
9254
|
};
|
|
9241
9255
|
return {
|
|
9242
9256
|
...common,
|
|
9257
|
+
id: `fc_${createStableHash(idSeed)}`,
|
|
9243
9258
|
type: "function_call",
|
|
9244
9259
|
arguments: JSON.stringify(block.input)
|
|
9245
9260
|
};
|
|
@@ -9834,7 +9849,7 @@ function* startContentBlock(state, event) {
|
|
|
9834
9849
|
}
|
|
9835
9850
|
if (block.type === "thinking") {
|
|
9836
9851
|
const item = {
|
|
9837
|
-
id: `rs_${state.responseId.slice(-18)}_${event.index}
|
|
9852
|
+
id: markMessagesReasoningId(`rs_${state.responseId.slice(-18)}_${event.index}`),
|
|
9838
9853
|
type: "reasoning",
|
|
9839
9854
|
status: "in_progress",
|
|
9840
9855
|
summary: [],
|
|
@@ -9861,7 +9876,6 @@ function* startContentBlock(state, event) {
|
|
|
9861
9876
|
if (block.type === "tool_use") {
|
|
9862
9877
|
const descriptor = resolveToolDescriptor(state.context.registry, block.name);
|
|
9863
9878
|
const common = {
|
|
9864
|
-
id: `fc_${state.responseId.slice(-18)}_${event.index}`,
|
|
9865
9879
|
call_id: block.id,
|
|
9866
9880
|
name: descriptor.name,
|
|
9867
9881
|
status: "in_progress",
|
|
@@ -9870,6 +9884,7 @@ function* startContentBlock(state, event) {
|
|
|
9870
9884
|
if (descriptor.kind === "custom") {
|
|
9871
9885
|
const item = {
|
|
9872
9886
|
...common,
|
|
9887
|
+
id: `ctc_${state.responseId.slice(-18)}_${event.index}`,
|
|
9873
9888
|
type: "custom_tool_call",
|
|
9874
9889
|
input: ""
|
|
9875
9890
|
};
|
|
@@ -9899,6 +9914,7 @@ function* startContentBlock(state, event) {
|
|
|
9899
9914
|
}
|
|
9900
9915
|
const item = {
|
|
9901
9916
|
...common,
|
|
9917
|
+
id: `fc_${state.responseId.slice(-18)}_${event.index}`,
|
|
9902
9918
|
type: "function_call",
|
|
9903
9919
|
arguments: ""
|
|
9904
9920
|
};
|
|
@@ -10512,18 +10528,22 @@ const handleResponses = async (c) => {
|
|
|
10512
10528
|
const normalizedReasoningEffort = normalizeResponsesReasoningEffort(payload, selectedModel?.capabilities?.supports?.reasoning_effort);
|
|
10513
10529
|
if (normalizedReasoningEffort) logger$1.debug(`Normalized reasoning effort from ${normalizedReasoningEffort.from} to ${normalizedReasoningEffort.to} based on the selected model capabilities`);
|
|
10514
10530
|
const responsesTransport = getResponsesTransportForModel(selectedModel);
|
|
10515
|
-
if (shouldFallbackToMessages(c, payload.model, selectedModel, responsesTransport))
|
|
10516
|
-
payload,
|
|
10517
|
-
|
|
10518
|
-
|
|
10519
|
-
|
|
10520
|
-
|
|
10521
|
-
|
|
10522
|
-
|
|
10531
|
+
if (shouldFallbackToMessages(c, payload.model, selectedModel, responsesTransport)) {
|
|
10532
|
+
filterReasoningForTransport(payload, true);
|
|
10533
|
+
return await handleResponsesViaMessages(c, {
|
|
10534
|
+
payload,
|
|
10535
|
+
publicModel: requestedModel,
|
|
10536
|
+
targetModel: payload.model,
|
|
10537
|
+
subagentMarker,
|
|
10538
|
+
requestId,
|
|
10539
|
+
sessionId: fallbackSessionId
|
|
10540
|
+
});
|
|
10541
|
+
}
|
|
10523
10542
|
if (!responsesTransport) return c.json({ error: {
|
|
10524
10543
|
message: "This model does not support the responses endpoint. Please choose a different model.",
|
|
10525
10544
|
type: "invalid_request_error"
|
|
10526
10545
|
} }, 400);
|
|
10546
|
+
filterReasoningForTransport(payload, false);
|
|
10527
10547
|
const recordUsage = createCopilotTokenUsageRecorder({
|
|
10528
10548
|
endpoint: "responses",
|
|
10529
10549
|
fallbackSessionId,
|
|
@@ -10594,6 +10614,13 @@ const handleResponses = async (c) => {
|
|
|
10594
10614
|
return c.json(result);
|
|
10595
10615
|
};
|
|
10596
10616
|
const isStreamingRequested = (payload) => Boolean(payload.stream);
|
|
10617
|
+
const filterReasoningForTransport = (payload, useMessagesFallback) => {
|
|
10618
|
+
if (!Array.isArray(payload.input)) return;
|
|
10619
|
+
payload.input = payload.input.filter((item) => {
|
|
10620
|
+
if (item.type !== "reasoning") return true;
|
|
10621
|
+
return isMessagesReasoningId(item.id) === useMessagesFallback;
|
|
10622
|
+
});
|
|
10623
|
+
};
|
|
10597
10624
|
const shouldFallbackToMessages = (c, modelId, selectedModel, responsesTransport) => {
|
|
10598
10625
|
if (isCodexUserAgent(c.req.header("user-agent"))) return !(modelId.startsWith("gpt") || modelId.startsWith("codex"));
|
|
10599
10626
|
if (responsesTransport) return false;
|
|
@@ -10781,4 +10808,4 @@ server.route("/:provider/images", providerImageRoutes);
|
|
|
10781
10808
|
//#endregion
|
|
10782
10809
|
export { server };
|
|
10783
10810
|
|
|
10784
|
-
//# sourceMappingURL=server-
|
|
10811
|
+
//# sourceMappingURL=server-fiF0jU-7.js.map
|