@jeffreycao/copilot-api 2.5.7 → 2.5.9

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.
@@ -1 +1 @@
1
- {"version":3,"file":"config-2Dli6AI8.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 upstreamTransport?: UpstreamTransportConfig\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 UpstreamTransportConfig {\n headersTimeoutMs?: number\n streamInactivityTimeoutMs?: number\n websocketMaxBufferedBytes?: number\n websocketMaxBufferedMessages?: number\n websocketOpenTimeoutMs?: number\n websocketPoolIdleTimeoutMs?: number\n}\n\nexport const defaultUpstreamTransportConfig = {\n headersTimeoutMs: 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<UpstreamTransportConfig>\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 =\n | \"authorization\"\n | \"azure-entra\"\n | \"oauth2\"\n | \"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 upstreamTransport: defaultUpstreamTransportConfig,\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.F_OK)\n } catch (error) {\n if (!isNodeError(error) || error.code !== \"ENOENT\") {\n throw error\n }\n\n writeFileAtomically(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\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 {\n changed: upstreamTransportMigrated,\n migrated: migratedUpstreamTransport,\n } = migrateUpstreamTransportConfig(config)\n\n const upstreamTransport = normalizeUpstreamTransportConfig(\n migratedUpstreamTransport,\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 hasUpstreamTransportChanges = Object.entries(upstreamTransport).some(\n ([key, value]) =>\n migratedUpstreamTransport[key as keyof UpstreamTransportConfig] !== value,\n )\n\n if (\n !hasExtraPromptChanges\n && !hasReasoningEffortChanges\n && !hasResponsesApiCompactThresholdChanges\n && !hasContextManagementChanges\n && !hasUpstreamTransportChanges\n && !upstreamTransportMigrated\n ) {\n return { mergedConfig: config, changed: false }\n }\n\n // The deprecated responsesTransport key is dropped once it is migrated.\n const { responsesTransport: _legacyResponsesTransport, ...persistedConfig } =\n config as LegacyAppConfig\n\n return {\n mergedConfig: {\n ...persistedConfig,\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 upstreamTransport,\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\n// responsesTransport was renamed to upstreamTransport, and headersTimeoutMsV2\n// to headersTimeoutMs, when this block started applying to every upstream HTTP\n// transport. Legacy configs are migrated once during the startup merge and the\n// old keys are dropped from disk.\ninterface LegacyAppConfig extends AppConfig {\n responsesTransport?: LegacyUpstreamTransportConfig\n}\n\ninterface LegacyUpstreamTransportConfig extends UpstreamTransportConfig {\n headersTimeoutMsV2?: number\n}\n\nconst migrateUpstreamTransportConfig = (\n config: AppConfig,\n): { changed: boolean; migrated: UpstreamTransportConfig } => {\n const legacyBlock = (config as LegacyAppConfig).responsesTransport\n const { headersTimeoutMsV2, ...migrated } = (config.upstreamTransport\n ?? legacyBlock\n ?? {}) as LegacyUpstreamTransportConfig\n\n const hasLegacyBlock = legacyBlock !== undefined\n const hasLegacyHeadersTimeout = headersTimeoutMsV2 !== undefined\n if (!hasLegacyBlock && !hasLegacyHeadersTimeout) {\n return { changed: false, migrated }\n }\n\n consola.info(\n \"Migrating deprecated transport config: responsesTransport -> upstreamTransport, headersTimeoutMsV2 -> headersTimeoutMs\",\n )\n\n return {\n changed: true,\n migrated:\n migrated.headersTimeoutMs === undefined && hasLegacyHeadersTimeout ?\n { ...migrated, headersTimeoutMs: headersTimeoutMsV2 }\n : migrated,\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\n// Applies to every upstream HTTP transport (Copilot Chat Completions and\n// Messages, Codex Responses, and provider-forwarded requests), not only the\n// Responses API.\nexport function getUpstreamTransportConfig(): Required<UpstreamTransportConfig> {\n return normalizeUpstreamTransportConfig(getConfig().upstreamTransport)\n}\n\nexport const normalizeUpstreamTransportConfig = (\n configured: UpstreamTransportConfig | undefined,\n): Required<UpstreamTransportConfig> => ({\n headersTimeoutMs: positiveIntegerOrDefault(\n configured?.headersTimeoutMs,\n defaultUpstreamTransportConfig.headersTimeoutMs,\n ),\n streamInactivityTimeoutMs: positiveIntegerOrDefault(\n configured?.streamInactivityTimeoutMs,\n defaultUpstreamTransportConfig.streamInactivityTimeoutMs,\n ),\n websocketMaxBufferedBytes: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedBytes,\n defaultUpstreamTransportConfig.websocketMaxBufferedBytes,\n ),\n websocketMaxBufferedMessages: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedMessages,\n defaultUpstreamTransportConfig.websocketMaxBufferedMessages,\n ),\n websocketOpenTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketOpenTimeoutMs,\n defaultUpstreamTransportConfig.websocketOpenTimeoutMs,\n ),\n websocketPoolIdleTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketPoolIdleTimeoutMs,\n defaultUpstreamTransportConfig.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\" || authType === \"azure-entra\") {\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 (\n authType !== \"azure-entra\"\n && !(providerName === \"codex\" && authType === \"oauth2\")\n )\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,GAAG;EACxC,GAAG,UAAU,WAAW;CAC1B,SAAS,OAAO;EACd,QAAQ,KAAK,8BAA8B,aAAa,KAAK;CAC/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,SACvD,CAAC,QAAQ,IACT,CAAC,CACL;CAEA,IAAI,cAAc,SAAS,GAAG;EAC5B,QAAQ,KACN,YAAY,aAAa,0BAA0B,cAAc,KAAK,MAAM,GAC9E;EACA,OAAO;CACT;CAEA,OAAO;EACL,MAAM;EACN;EACA;EACA;EACA;EACA,iBAAiB,yBAAyB,SAAS,eAAe;EAClE,QAAQ,SAAS;CACnB;AACF;AAEA,SAAgB,6BACd,gBACA,OACc;CACd,MAAM,cAAc,eAAe,SAAS;CAC5C,IAAI,aAAa,QAAQ,wBAAwB,YAAY,IAAI,GAC/D,OAAO,YAAY;CAGrB,IAAI,eAAe,SAAS,eAAe;EACzC,IAAI,iCAAiC,KAAK,KAAK,GAC7C,OAAO;EAET,IAAI,iCAAiC,KAAK,KAAK,GAC7C,OAAO;CAEX;CAEA,OAAO,eAAe;AACxB;AAEA,SAAS,yBACP,OACoB;CAEpB,OADiB,OAAO,KAAK,CAAC,CAAC,YAAY,KACxB,KAAA;AACrB;AAEA,SAAgB,uBAAsC;CACpD,MAAM,SAAS,UAAU;CAEzB,OADsB,OAAO,KAAK,OAAO,aAAa,CAAC,CACpC,CAAC,CAAC,QAAQ,SAAS,kBAAkB,IAAI,MAAM,IAAI;AACxE;AAEA,SAAgB,uBAAuB,MAAuB;CAC5D,OAAO,KAAK,KAAK,MAAM;AACzB"}
1
+ {"version":3,"file":"config-2Dli6AI8.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 upstreamTransport?: UpstreamTransportConfig\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 UpstreamTransportConfig {\n headersTimeoutMs?: number\n streamInactivityTimeoutMs?: number\n websocketMaxBufferedBytes?: number\n websocketMaxBufferedMessages?: number\n websocketOpenTimeoutMs?: number\n websocketPoolIdleTimeoutMs?: number\n}\n\nexport const defaultUpstreamTransportConfig = {\n headersTimeoutMs: 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<UpstreamTransportConfig>\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 =\n | \"authorization\"\n | \"azure-entra\"\n | \"oauth2\"\n | \"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 accountId?: string\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 upstreamTransport: defaultUpstreamTransportConfig,\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.F_OK)\n } catch (error) {\n if (!isNodeError(error) || error.code !== \"ENOENT\") {\n throw error\n }\n\n writeFileAtomically(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\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 {\n changed: upstreamTransportMigrated,\n migrated: migratedUpstreamTransport,\n } = migrateUpstreamTransportConfig(config)\n\n const upstreamTransport = normalizeUpstreamTransportConfig(\n migratedUpstreamTransport,\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 hasUpstreamTransportChanges = Object.entries(upstreamTransport).some(\n ([key, value]) =>\n migratedUpstreamTransport[key as keyof UpstreamTransportConfig] !== value,\n )\n\n if (\n !hasExtraPromptChanges\n && !hasReasoningEffortChanges\n && !hasResponsesApiCompactThresholdChanges\n && !hasContextManagementChanges\n && !hasUpstreamTransportChanges\n && !upstreamTransportMigrated\n ) {\n return { mergedConfig: config, changed: false }\n }\n\n // The deprecated responsesTransport key is dropped once it is migrated.\n const { responsesTransport: _legacyResponsesTransport, ...persistedConfig } =\n config as LegacyAppConfig\n\n return {\n mergedConfig: {\n ...persistedConfig,\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 upstreamTransport,\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\n// responsesTransport was renamed to upstreamTransport, and headersTimeoutMsV2\n// to headersTimeoutMs, when this block started applying to every upstream HTTP\n// transport. Legacy configs are migrated once during the startup merge and the\n// old keys are dropped from disk.\ninterface LegacyAppConfig extends AppConfig {\n responsesTransport?: LegacyUpstreamTransportConfig\n}\n\ninterface LegacyUpstreamTransportConfig extends UpstreamTransportConfig {\n headersTimeoutMsV2?: number\n}\n\nconst migrateUpstreamTransportConfig = (\n config: AppConfig,\n): { changed: boolean; migrated: UpstreamTransportConfig } => {\n const legacyBlock = (config as LegacyAppConfig).responsesTransport\n const { headersTimeoutMsV2, ...migrated } = (config.upstreamTransport\n ?? legacyBlock\n ?? {}) as LegacyUpstreamTransportConfig\n\n const hasLegacyBlock = legacyBlock !== undefined\n const hasLegacyHeadersTimeout = headersTimeoutMsV2 !== undefined\n if (!hasLegacyBlock && !hasLegacyHeadersTimeout) {\n return { changed: false, migrated }\n }\n\n consola.info(\n \"Migrating deprecated transport config: responsesTransport -> upstreamTransport, headersTimeoutMsV2 -> headersTimeoutMs\",\n )\n\n return {\n changed: true,\n migrated:\n migrated.headersTimeoutMs === undefined && hasLegacyHeadersTimeout ?\n { ...migrated, headersTimeoutMs: headersTimeoutMsV2 }\n : migrated,\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\n// Applies to every upstream HTTP transport (Copilot Chat Completions and\n// Messages, Codex Responses, and provider-forwarded requests), not only the\n// Responses API.\nexport function getUpstreamTransportConfig(): Required<UpstreamTransportConfig> {\n return normalizeUpstreamTransportConfig(getConfig().upstreamTransport)\n}\n\nexport const normalizeUpstreamTransportConfig = (\n configured: UpstreamTransportConfig | undefined,\n): Required<UpstreamTransportConfig> => ({\n headersTimeoutMs: positiveIntegerOrDefault(\n configured?.headersTimeoutMs,\n defaultUpstreamTransportConfig.headersTimeoutMs,\n ),\n streamInactivityTimeoutMs: positiveIntegerOrDefault(\n configured?.streamInactivityTimeoutMs,\n defaultUpstreamTransportConfig.streamInactivityTimeoutMs,\n ),\n websocketMaxBufferedBytes: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedBytes,\n defaultUpstreamTransportConfig.websocketMaxBufferedBytes,\n ),\n websocketMaxBufferedMessages: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedMessages,\n defaultUpstreamTransportConfig.websocketMaxBufferedMessages,\n ),\n websocketOpenTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketOpenTimeoutMs,\n defaultUpstreamTransportConfig.websocketOpenTimeoutMs,\n ),\n websocketPoolIdleTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketPoolIdleTimeoutMs,\n defaultUpstreamTransportConfig.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\" || authType === \"azure-entra\") {\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 (\n authType !== \"azure-entra\"\n && !(providerName === \"codex\" && authType === \"oauth2\")\n )\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,GAAG;EACxC,GAAG,UAAU,WAAW;CAC1B,SAAS,OAAO;EACd,QAAQ,KAAK,8BAA8B,aAAa,KAAK;CAC/D,UAAU;EACR,IAAI,gBAAgB,KAAA,GAClB,IAAI;GACF,GAAG,UAAU,WAAW;EAC1B,QAAQ,CAER;CAEJ;AACF;AAEA,SAAgB,oBAAoB,UAAkB,SAAuB;CAC3E,MAAM,YAAY,KAAK,QAAQ,QAAQ;CACvC,MAAM,WAAW,KAAK,KACpB,WACA,IAAI,KAAK,SAAS,QAAQ,EAAE,GAAG,QAAQ,IAAI,GAAG,YAAY,sBAAsB,CAAC,CAAC,SAAS,KAAK,EAAE,KACpG;CAEA,GAAG,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;CAE3C,IAAI;CACJ,IAAI,kBAAkB;CACtB,IAAI;EACF,iBAAiB,GAAG,SAAS,UAAU,MAAM,GAAK;EAClD,kBAAkB;EAClB,GAAG,cAAc,gBAAgB,SAAS,MAAM;EAChD,GA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,eAAe;AACxB;AAEA,SAAS,yBACP,OACoB;CAEpB,OADiB,OAAO,KAAK,CAAC,CAAC,YAAY,KACxB,KAAA;AACrB;AAEA,SAAgB,uBAAsC;CACpD,MAAM,SAAS,UAAU;CAEzB,OADsB,OAAO,KAAK,OAAO,aAAa,CAAC,CACpC,CAAC,CAAC,QAAQ,SAAS,kBAAkB,IAAI,MAAM,IAAI;AACxE;AAEA,SAAgB,uBAAuB,MAAuB;CAC5D,OAAO,KAAK,KAAK,MAAM;AACzB"}
package/dist/main.js CHANGED
@@ -27,10 +27,10 @@ if (isMcpFastPath(process.argv)) {
27
27
  if (process.platform === "win32" && process.stdout.isTTY && !process.env.WT_SESSION) process.env.WT_SESSION = "copilot-api";
28
28
  const { bindElectronFetch } = await import("./electron-fetch-DsMaRX6v.js");
29
29
  bindElectronFetch();
30
- const { auth } = await import("./auth-CX6c7jlD.js");
30
+ const { auth } = await import("./auth-CdETqUtu.js");
31
31
  const { debug } = await import("./debug-DV0aYj65.js");
32
32
  const { mcp } = await import("./mcp-Byz9h_xz.js");
33
- const { start } = await import("./start-CBnChdoU.js");
33
+ const { start } = await import("./start-zddonYc0.js");
34
34
  await runMain(defineCommand({
35
35
  meta: {
36
36
  name: "copilot-api",
@@ -1,4 +1,4 @@
1
- import { J as state } from "./token-O2WH6ipn.js";
1
+ import { X as state } from "./token-4p5BAEqO.js";
2
2
  //#region src/lib/models.ts
3
3
  /**
4
4
  * Converts a Copilot upstream model ID to a client-friendly ID that Claude Code
@@ -87,4 +87,4 @@ const normalizeSdkModelId = (sdkModelId) => {
87
87
  //#endregion
88
88
  export { toClientModelId as i, getLatestModelForFamily as n, normalizeSdkModelId as r, findEndpointModel as t };
89
89
 
90
- //# sourceMappingURL=models-mp3HRQcW.js.map
90
+ //# sourceMappingURL=models-B1c5UcTP.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"models-mp3HRQcW.js","names":[],"sources":["../src/lib/models.ts"],"sourcesContent":["import type { Model } from \"~/lib/types/models\"\n\nimport { state } from \"~/lib/state\"\n\n/**\n * Converts a Copilot upstream model ID to a client-friendly ID that Claude Code\n * and Claude Desktop recognize (dots in version replaced with hyphens).\n * e.g. \"claude-sonnet-4.6\" -> \"claude-sonnet-4-6\"\n * Non-Claude models are returned unchanged.\n */\nexport const toClientModelId = (modelId: string): string => {\n const normalized = normalizeSdkModelId(modelId)\n if (!normalized) return modelId\n const versionHyphenated = normalized.version.replaceAll(\".\", \"-\")\n return `claude-${normalized.family}-${versionHyphenated}`\n}\n\nexport interface NormalizedSdkModelId {\n family: string\n version: string\n}\n\nexport const findEndpointModel = (sdkModelId: string): Model | undefined => {\n const models = state.models?.data ?? []\n const exactMatch = models.find((m) => m.id === sdkModelId)\n if (exactMatch) {\n return exactMatch\n }\n\n const normalized = normalizeSdkModelId(sdkModelId)\n if (!normalized) {\n return undefined\n }\n\n const modelName = `claude-${normalized.family}-${normalized.version}`\n const model = models.find((m) => m.id === modelName)\n if (model) {\n return model\n }\n\n return undefined\n}\n\n/**\n * Finds the latest available model for a given Claude family (e.g. \"opus\",\n * \"sonnet\", \"haiku\") among the models currently cached in `state.models`.\n * \"Latest\" is determined by the highest semantic version parsed from the model\n * ID. Returns `undefined` when no model of that family is available.\n */\nexport const getLatestModelForFamily = (family: string): Model | undefined => {\n const models = state.models?.data ?? []\n\n let best: { model: Model; major: number; minor: number } | undefined\n\n for (const model of models) {\n const normalized = normalizeSdkModelId(model.id)\n if (!normalized || normalized.family !== family) {\n continue\n }\n\n const [majorPart, minorPart = \"0\"] = normalized.version.split(\".\")\n const major = Number.parseInt(majorPart, 10)\n const minor = Number.parseInt(minorPart, 10)\n if (Number.isNaN(major) || Number.isNaN(minor)) {\n continue\n }\n\n if (\n !best\n || major > best.major\n || (major === best.major && minor > best.minor)\n ) {\n best = { model, major, minor }\n }\n }\n\n return best?.model\n}\n\n/**\n * Normalizes an SDK model ID to extract the model family and version.\n * this method from github copilot extension\n * Examples:\n * - \"claude-opus-4-5-20251101\" -> { family: \"opus\", version: \"4.5\" }\n * - \"claude-3-5-sonnet-20241022\" -> { family: \"sonnet\", version: \"3.5\" }\n * - \"claude-sonnet-4-20250514\" -> { family: \"sonnet\", version: \"4\" }\n * - \"claude-haiku-3-5-20250514\" -> { family: \"haiku\", version: \"3.5\" }\n * - \"claude-haiku-4.5\" -> { family: \"haiku\", version: \"4.5\" }\n */\nexport const normalizeSdkModelId = (\n sdkModelId: string,\n): NormalizedSdkModelId | undefined => {\n const lower = sdkModelId.toLowerCase()\n\n // Strip date suffix (8 digits at the end)\n const withoutDate = lower.replace(/-\\d{8}$/, \"\")\n\n // Pattern 1: claude-{family}-{major}.{minor} (e.g., claude-haiku-4.5)\n const pattern1 = withoutDate.match(/^claude-(\\w+)-(\\d+)\\.(\\d+)$/)\n if (pattern1) {\n return { family: pattern1[1], version: `${pattern1[2]}.${pattern1[3]}` }\n }\n\n // Pattern 2: claude-{family}-{major}-{minor} (e.g., claude-opus-4-5, claude-haiku-3-5)\n const pattern2 = withoutDate.match(/^claude-(\\w+)-(\\d+)-(\\d+)$/)\n if (pattern2) {\n return { family: pattern2[1], version: `${pattern2[2]}.${pattern2[3]}` }\n }\n\n // Pattern 3: claude-{major}-{minor}-{family} (e.g., claude-3-5-sonnet)\n const pattern3 = withoutDate.match(/^claude-(\\d+)-(\\d+)-(\\w+)$/)\n if (pattern3) {\n return { family: pattern3[3], version: `${pattern3[1]}.${pattern3[2]}` }\n }\n\n // Pattern 4: claude-{family}-{major} (e.g., claude-sonnet-4)\n const pattern4 = withoutDate.match(/^claude-(\\w+)-(\\d+)$/)\n if (pattern4) {\n return { family: pattern4[1], version: pattern4[2] }\n }\n\n // Pattern 5: claude-{major}-{family} (e.g., claude-3-opus)\n const pattern5 = withoutDate.match(/^claude-(\\d+)-(\\w+)$/)\n if (pattern5) {\n return { family: pattern5[2], version: pattern5[1] }\n }\n\n return undefined\n}\n"],"mappings":";;;;;;;;AAUA,MAAa,mBAAmB,YAA4B;CAC1D,MAAM,aAAa,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,GAAG,SAAS,GAAG,GAAG,SAAS;CAAK;CAIzE,MAAM,WAAW,YAAY,MAAM,4BAA4B;CAC/D,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,GAAG,SAAS,GAAG,GAAG,SAAS;CAAK;CAIzE,MAAM,WAAW,YAAY,MAAM,4BAA4B;CAC/D,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,GAAG,SAAS,GAAG,GAAG,SAAS;CAAK;CAIzE,MAAM,WAAW,YAAY,MAAM,sBAAsB;CACzD,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,SAAS;CAAG;CAIrD,MAAM,WAAW,YAAY,MAAM,sBAAsB;CACzD,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,SAAS;CAAG;AAIvD"}
1
+ {"version":3,"file":"models-B1c5UcTP.js","names":[],"sources":["../src/lib/models.ts"],"sourcesContent":["import type { Model } from \"~/lib/types/models\"\n\nimport { state } from \"~/lib/state\"\n\n/**\n * Converts a Copilot upstream model ID to a client-friendly ID that Claude Code\n * and Claude Desktop recognize (dots in version replaced with hyphens).\n * e.g. \"claude-sonnet-4.6\" -> \"claude-sonnet-4-6\"\n * Non-Claude models are returned unchanged.\n */\nexport const toClientModelId = (modelId: string): string => {\n const normalized = normalizeSdkModelId(modelId)\n if (!normalized) return modelId\n const versionHyphenated = normalized.version.replaceAll(\".\", \"-\")\n return `claude-${normalized.family}-${versionHyphenated}`\n}\n\nexport interface NormalizedSdkModelId {\n family: string\n version: string\n}\n\nexport const findEndpointModel = (sdkModelId: string): Model | undefined => {\n const models = state.models?.data ?? []\n const exactMatch = models.find((m) => m.id === sdkModelId)\n if (exactMatch) {\n return exactMatch\n }\n\n const normalized = normalizeSdkModelId(sdkModelId)\n if (!normalized) {\n return undefined\n }\n\n const modelName = `claude-${normalized.family}-${normalized.version}`\n const model = models.find((m) => m.id === modelName)\n if (model) {\n return model\n }\n\n return undefined\n}\n\n/**\n * Finds the latest available model for a given Claude family (e.g. \"opus\",\n * \"sonnet\", \"haiku\") among the models currently cached in `state.models`.\n * \"Latest\" is determined by the highest semantic version parsed from the model\n * ID. Returns `undefined` when no model of that family is available.\n */\nexport const getLatestModelForFamily = (family: string): Model | undefined => {\n const models = state.models?.data ?? []\n\n let best: { model: Model; major: number; minor: number } | undefined\n\n for (const model of models) {\n const normalized = normalizeSdkModelId(model.id)\n if (!normalized || normalized.family !== family) {\n continue\n }\n\n const [majorPart, minorPart = \"0\"] = normalized.version.split(\".\")\n const major = Number.parseInt(majorPart, 10)\n const minor = Number.parseInt(minorPart, 10)\n if (Number.isNaN(major) || Number.isNaN(minor)) {\n continue\n }\n\n if (\n !best\n || major > best.major\n || (major === best.major && minor > best.minor)\n ) {\n best = { model, major, minor }\n }\n }\n\n return best?.model\n}\n\n/**\n * Normalizes an SDK model ID to extract the model family and version.\n * this method from github copilot extension\n * Examples:\n * - \"claude-opus-4-5-20251101\" -> { family: \"opus\", version: \"4.5\" }\n * - \"claude-3-5-sonnet-20241022\" -> { family: \"sonnet\", version: \"3.5\" }\n * - \"claude-sonnet-4-20250514\" -> { family: \"sonnet\", version: \"4\" }\n * - \"claude-haiku-3-5-20250514\" -> { family: \"haiku\", version: \"3.5\" }\n * - \"claude-haiku-4.5\" -> { family: \"haiku\", version: \"4.5\" }\n */\nexport const normalizeSdkModelId = (\n sdkModelId: string,\n): NormalizedSdkModelId | undefined => {\n const lower = sdkModelId.toLowerCase()\n\n // Strip date suffix (8 digits at the end)\n const withoutDate = lower.replace(/-\\d{8}$/, \"\")\n\n // Pattern 1: claude-{family}-{major}.{minor} (e.g., claude-haiku-4.5)\n const pattern1 = withoutDate.match(/^claude-(\\w+)-(\\d+)\\.(\\d+)$/)\n if (pattern1) {\n return { family: pattern1[1], version: `${pattern1[2]}.${pattern1[3]}` }\n }\n\n // Pattern 2: claude-{family}-{major}-{minor} (e.g., claude-opus-4-5, claude-haiku-3-5)\n const pattern2 = withoutDate.match(/^claude-(\\w+)-(\\d+)-(\\d+)$/)\n if (pattern2) {\n return { family: pattern2[1], version: `${pattern2[2]}.${pattern2[3]}` }\n }\n\n // Pattern 3: claude-{major}-{minor}-{family} (e.g., claude-3-5-sonnet)\n const pattern3 = withoutDate.match(/^claude-(\\d+)-(\\d+)-(\\w+)$/)\n if (pattern3) {\n return { family: pattern3[3], version: `${pattern3[1]}.${pattern3[2]}` }\n }\n\n // Pattern 4: claude-{family}-{major} (e.g., claude-sonnet-4)\n const pattern4 = withoutDate.match(/^claude-(\\w+)-(\\d+)$/)\n if (pattern4) {\n return { family: pattern4[1], version: pattern4[2] }\n }\n\n // Pattern 5: claude-{major}-{family} (e.g., claude-3-opus)\n const pattern5 = withoutDate.match(/^claude-(\\d+)-(\\w+)$/)\n if (pattern5) {\n return { family: pattern5[2], version: pattern5[1] }\n }\n\n return undefined\n}\n"],"mappings":";;;;;;;;AAUA,MAAa,mBAAmB,YAA4B;CAC1D,MAAM,aAAa,oBAAoB,OAAO;CAC9C,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,oBAAoB,WAAW,QAAQ,WAAW,KAAK,GAAG;CAChE,OAAO,UAAU,WAAW,OAAO,GAAG;AACxC;AAOA,MAAa,qBAAqB,eAA0C;CAC1E,MAAM,SAAS,MAAM,QAAQ,QAAQ,CAAC;CACtC,MAAM,aAAa,OAAO,MAAM,MAAM,EAAE,OAAO,UAAU;CACzD,IAAI,YACF,OAAO;CAGT,MAAM,aAAa,oBAAoB,UAAU;CACjD,IAAI,CAAC,YACH;CAGF,MAAM,YAAY,UAAU,WAAW,OAAO,GAAG,WAAW;CAC5D,MAAM,QAAQ,OAAO,MAAM,MAAM,EAAE,OAAO,SAAS;CACnD,IAAI,OACF,OAAO;AAIX;;;;;;;AAQA,MAAa,2BAA2B,WAAsC;CAC5E,MAAM,SAAS,MAAM,QAAQ,QAAQ,CAAC;CAEtC,IAAI;CAEJ,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,aAA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pstreamTransportConfig, N as PATHS, O as isMessagesApiEnabled, S as getClaudeAutoModel, T as getMessageApiWebSearchModel, _ as resolveMappedModel, b as getAlphaSearchModel, d as getModelResponsesApiCompactThreshold$1, f as getReasoningEffortForModel, g as isGpt56OrAbove, h as isContextManagementEnabledForResponses, i as listEnabledProviders, k as isResponsesApiWebSearchEnabled, l as getExtraPromptForModel, m as isContextManagementEnabledForMessages, n as getRawProviderConfig, o as resolveEffectiveProviderType, p as getSmallModel, s as resolveProviderAuthType, t as getProviderConfig, u as getModelMappings, v as setModelMappings, x as getAnthropicApiKey } from "./config-2Dli6AI8.js";
2
- import { A as createAuthMiddleware, B as resolveTraceId$1, C as prepareMessageProxyHeaders, E as compactMessageSections, F as CODEX_API_BASE_URL, G as isTerminalResponsesStreamChunk, H as createResponsesHttpEventStream, I as buildCodexRequestHeaders, J as state, K as createPooledWebSocketStream, L as forwardCodexResponses, O as compactSystemPromptStarts, R as generateTraceId, S as prepareInteractionHeaders, T as compactAutoContinuePromptStarts, U as createResponsesSafeStream, V as fetchUpstreamWithLifecycle, W as encodePoolKeyPart, X as forwardError, Y as HTTPError, _ as copilotBaseUrl, b as copilotWebSocketHeaders, c as getUUID, d as isResponsesStream, f as parseUserIdMetadata, j as getConfiguredAdminApiKeys, k as compactTextOnlyGuard, l as isAsyncIterable, o as generateRequestIdFromPayload, p as getCopilotUsage, q as createWebSocketUrl, r as setupCodexToken, s as getRootSessionId, u as isNullish, v as copilotHeaders, x as prepareForCompact, z as requestContext } from "./token-O2WH6ipn.js";
2
+ import { A as compactSystemPromptStarts, B as generateTraceId, C as prepareForCompact, D as compactAutoContinuePromptStarts, G as createResponsesSafeStream, H as resolveTraceId$1, J as createPooledWebSocketStream, K as encodePoolKeyPart, L as CODEX_API_BASE_URL, M as createAuthMiddleware, N as getConfiguredAdminApiKeys, O as compactMessageSections, Q as forwardError, R as buildCodexRequestHeaders, S as copilotWebSocketHeaders, T as prepareMessageProxyHeaders, U as fetchUpstreamWithLifecycle, V as requestContext, W as createResponsesHttpEventStream, X as state, Y as createWebSocketUrl, Z as HTTPError, a as setupCodexToken, b as copilotHeaders, c as generateRequestIdFromPayload, d as isAsyncIterable, f as isNullish, h as getCopilotUsage, j as compactTextOnlyGuard, l as getRootSessionId, m as parseUserIdMetadata, p as isResponsesStream, q as isTerminalResponsesStreamChunk, u as getUUID, w as prepareInteractionHeaders, y as copilotBaseUrl, z as forwardCodexResponses } from "./token-4p5BAEqO.js";
3
3
  import { a as isDeferredToolName, c as parseMcpToolSearchSentinel, d as shouldEnableResponsesToolSearch, i as isBridgeToolSearchName, l as resolveBridgeToolSearchName, o as listDeferredToolNames, r as formatToolSearchBridgeArguments, s as normalizeToolSearchBridgeArguments, t as BRIDGE_TOOL_SEARCH_NAME, u as selectDeferredToolsByNames } from "./tool-search-BgFcDbNQ.js";
4
- import { i as toClientModelId, r as normalizeSdkModelId, t as findEndpointModel } from "./models-mp3HRQcW.js";
4
+ import { i as toClientModelId, r as normalizeSdkModelId, t as findEndpointModel } from "./models-B1c5UcTP.js";
5
5
  import consola from "consola";
6
6
  import { createHash } from "node:crypto";
7
7
  import fs, { createWriteStream, readFileSync, rmSync } from "node:fs";
@@ -396,6 +396,33 @@ var EventBus = class {
396
396
  };
397
397
  }
398
398
  };
399
+ //#endregion
400
+ //#region src/lib/token-usage/peak-windows.ts
401
+ const deepseekPeakWindows = [{
402
+ endMinuteUtc: 240,
403
+ startMinuteUtc: 60,
404
+ weekdays: [
405
+ 1,
406
+ 2,
407
+ 3,
408
+ 4,
409
+ 5
410
+ ]
411
+ }, {
412
+ endMinuteUtc: 600,
413
+ startMinuteUtc: 360,
414
+ weekdays: [
415
+ 1,
416
+ 2,
417
+ 3,
418
+ 4,
419
+ 5
420
+ ]
421
+ }];
422
+ const dashscopePeakWindows = [{
423
+ endMinuteUtc: 840,
424
+ startMinuteUtc: 0
425
+ }];
399
426
  const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
400
427
  static catalog = {
401
428
  codex: {
@@ -598,10 +625,32 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
598
625
  contextWindow: 1e6,
599
626
  inputModalities: ["text"],
600
627
  maxOutputTokens: 64e3,
628
+ pricing: {
629
+ cachedInput: .3,
630
+ input: 3,
631
+ offPeak: {
632
+ cachedInput: .15,
633
+ input: 1.5,
634
+ output: 4.5
635
+ },
636
+ output: 9,
637
+ peakWindows: dashscopePeakWindows
638
+ }
639
+ },
640
+ "deepseek-v4.1-flash": {
641
+ contextWindow: 1e6,
642
+ inputModalities: ["text", "image"],
643
+ maxOutputTokens: 393216,
601
644
  pricing: {
602
645
  cachedInput: .2,
603
- input: 1,
604
- output: 2
646
+ input: 2,
647
+ offPeak: {
648
+ cachedInput: .1,
649
+ input: 1,
650
+ output: 4
651
+ },
652
+ output: 8,
653
+ peakWindows: dashscopePeakWindows
605
654
  }
606
655
  },
607
656
  "qwen3.7-plus": {
@@ -643,7 +692,13 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
643
692
  pricing: {
644
693
  cachedInput: .04,
645
694
  input: 2,
646
- output: 8
695
+ offPeak: {
696
+ cachedInput: .02,
697
+ input: 1,
698
+ output: 4
699
+ },
700
+ output: 8,
701
+ peakWindows: deepseekPeakWindows
647
702
  },
648
703
  reasoningEfforts: [
649
704
  "low",
@@ -658,7 +713,13 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
658
713
  pricing: {
659
714
  cachedInput: .3,
660
715
  input: 9,
661
- output: 27
716
+ offPeak: {
717
+ cachedInput: .15,
718
+ input: 4.5,
719
+ output: 13.5
720
+ },
721
+ output: 27,
722
+ peakWindows: deepseekPeakWindows
662
723
  },
663
724
  reasoningEfforts: [
664
725
  "low",
@@ -822,7 +883,13 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
822
883
  pricing: {
823
884
  cachedInput: .006,
824
885
  input: .3,
825
- output: 1.2
886
+ offPeak: {
887
+ cachedInput: .003,
888
+ input: .15,
889
+ output: .6
890
+ },
891
+ output: 1.2,
892
+ peakWindows: deepseekPeakWindows
826
893
  },
827
894
  reasoningEfforts: [
828
895
  "low",
@@ -835,9 +902,15 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
835
902
  inputModalities: ["text"],
836
903
  maxOutputTokens: 64e3,
837
904
  pricing: {
838
- cachedInput: .007,
839
- input: .22,
840
- output: .66
905
+ cachedInput: .006,
906
+ input: .3,
907
+ offPeak: {
908
+ cachedInput: .003,
909
+ input: .15,
910
+ output: .6
911
+ },
912
+ output: 1.2,
913
+ peakWindows: deepseekPeakWindows
841
914
  }
842
915
  },
843
916
  "deepseek-v4-flash-vision-exp": {
@@ -845,9 +918,15 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
845
918
  inputModalities: ["text", "image"],
846
919
  maxOutputTokens: 384e3,
847
920
  pricing: {
848
- cachedInput: .007,
849
- input: .22,
850
- output: .66
921
+ cachedInput: .006,
922
+ input: .3,
923
+ offPeak: {
924
+ cachedInput: .003,
925
+ input: .15,
926
+ output: .6
927
+ },
928
+ output: 1.2,
929
+ peakWindows: deepseekPeakWindows
851
930
  },
852
931
  reasoningEfforts: [
853
932
  "low",
@@ -860,9 +939,15 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
860
939
  inputModalities: ["text"],
861
940
  maxOutputTokens: 64e3,
862
941
  pricing: {
863
- cachedInput: .022,
864
- input: .66,
865
- output: 1.98
942
+ cachedInput: .044,
943
+ input: 1.32,
944
+ offPeak: {
945
+ cachedInput: .022,
946
+ input: .66,
947
+ output: 1.98
948
+ },
949
+ output: 3.96,
950
+ peakWindows: deepseekPeakWindows
866
951
  }
867
952
  },
868
953
  "kimi-k2.7-code": {
@@ -1731,7 +1816,7 @@ function resolveTokenUsageCost(input) {
1731
1816
  if (!providerName) return null;
1732
1817
  const resolvedPricing = resolveProviderPricing(providerName, input.model, input.pricing);
1733
1818
  if (!resolvedPricing) return null;
1734
- const pricing = resolvePricingTier(resolvedPricing.pricing, getInputTokenTotal(input));
1819
+ const pricing = resolvePricingTier(resolvedPricing.pricing, getInputTokenTotal(input), resolvePricingTime(input.at));
1735
1820
  const currency = resolveProviderCurrency(providerName, input.pricingCurrency);
1736
1821
  if (!currency) return null;
1737
1822
  const inputPrice = normalizePrice(pricing.input);
@@ -1780,13 +1865,37 @@ function resolveProviderPricing(providerName, model, configuredPricing) {
1780
1865
  source: "builtin"
1781
1866
  };
1782
1867
  }
1783
- function resolvePricingTier(pricing, inputTokenTotal) {
1868
+ function resolvePricingTier(pricing, inputTokenTotal, at) {
1784
1869
  const tiers = pricing.tiers?.filter((tier) => typeof tier === "object" && tier !== null).toSorted((a, b) => normalizeTierMax(a) - normalizeTierMax(b));
1785
1870
  const selectedTier = tiers?.find((tier) => inputTokenTotal <= normalizeTierMax(tier)) ?? tiers?.at(-1);
1786
- return {
1871
+ const resolvedTier = {
1787
1872
  ...pricing,
1788
1873
  ...selectedTier
1789
1874
  };
1875
+ const offPeak = pricing.offPeak;
1876
+ const peakWindows = pricing.peakWindows;
1877
+ if (offPeak && peakWindows?.length && !isPeakPricingTime(peakWindows, at)) return {
1878
+ ...resolvedTier,
1879
+ ...offPeak
1880
+ };
1881
+ return resolvedTier;
1882
+ }
1883
+ function resolvePricingTime(at) {
1884
+ return at instanceof Date && Number.isFinite(at.getTime()) ? at : /* @__PURE__ */ new Date();
1885
+ }
1886
+ function isPeakPricingTime(windows, at) {
1887
+ const minuteOfDay = at.getUTCHours() * 60 + at.getUTCMinutes();
1888
+ const isoWeekday = at.getUTCDay() || 7;
1889
+ return windows.some((window) => {
1890
+ const startMinute = normalizeMinuteOfDay(window.startMinuteUtc);
1891
+ const endMinute = normalizeMinuteOfDay(window.endMinuteUtc);
1892
+ if (startMinute === null || endMinute === null || endMinute <= startMinute) return false;
1893
+ if (window.weekdays?.length && !window.weekdays.includes(isoWeekday)) return false;
1894
+ return minuteOfDay >= startMinute && minuteOfDay < endMinute;
1895
+ });
1896
+ }
1897
+ function normalizeMinuteOfDay(value) {
1898
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1440 ? value : null;
1790
1899
  }
1791
1900
  function normalizeTierMax(tier) {
1792
1901
  const maxInputTokens = tier.maxInputTokens;
@@ -1831,7 +1940,10 @@ function resolveUserId(input) {
1831
1940
  function toPersistedEvent(input) {
1832
1941
  if (!hasAnyToken(input)) return null;
1833
1942
  const now = /* @__PURE__ */ new Date();
1834
- const cost = resolveTokenUsageCost(input);
1943
+ const cost = resolveTokenUsageCost({
1944
+ ...input,
1945
+ at: now
1946
+ });
1835
1947
  return {
1836
1948
  cache_creation_input_tokens: normalizeToken(input.cache_creation_input_tokens),
1837
1949
  cache_read_input_tokens: normalizeToken(input.cache_read_input_tokens),
@@ -12567,4 +12679,4 @@ createServer();
12567
12679
  //#endregion
12568
12680
  export { createServer };
12569
12681
 
12570
- //# sourceMappingURL=server-CcnH-kO1.js.map
12682
+ //# sourceMappingURL=server-D0Wx-DQF.js.map