@jeffreycao/copilot-api 2.5.6 → 2.5.8
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 +6 -3
- package/README.zh-CN.md +6 -3
- package/dist/{auth-LJ5y6v6e.js → auth-CMufJUfF.js} +43 -38
- package/dist/{auth-LJ5y6v6e.js.map → auth-CMufJUfF.js.map} +1 -1
- package/dist/auth-CX6c7jlD.js +2 -0
- package/dist/{config-DYtohLpX.js → config-2Dli6AI8.js} +6 -6
- package/dist/{config-DYtohLpX.js.map → config-2Dli6AI8.js.map} +1 -1
- package/dist/{debug-CcgIYPL-.js → debug-DV0aYj65.js} +2 -2
- package/dist/{debug-CcgIYPL-.js.map → debug-DV0aYj65.js.map} +1 -1
- package/dist/{electron-fetch-BRX-ug5E.js → electron-fetch-DsMaRX6v.js} +1 -1
- package/dist/{electron-fetch-BRX-ug5E.js.map → electron-fetch-DsMaRX6v.js.map} +1 -1
- package/dist/{fast-path-BoMnZCVC.js → fast-path-BwgQKZBk.js} +1 -1
- package/dist/{fast-path-BoMnZCVC.js.map → fast-path-BwgQKZBk.js.map} +1 -1
- package/dist/main.js +7 -7
- package/dist/main.js.map +1 -1
- package/dist/{mcp-fpSlKZxK.js → mcp-Byz9h_xz.js} +2 -2
- package/dist/{mcp-fpSlKZxK.js.map → mcp-Byz9h_xz.js.map} +1 -1
- package/dist/{mcp-server-BeNu_Edl.js → mcp-server-D6uKVzo6.js} +2 -2
- package/dist/{mcp-server-BeNu_Edl.js.map → mcp-server-D6uKVzo6.js.map} +1 -1
- package/dist/mcp-server-ouCaZXlw.js +2 -0
- package/dist/{models-uKftaEt_.js → models-mp3HRQcW.js} +2 -2
- package/dist/{models-uKftaEt_.js.map → models-mp3HRQcW.js.map} +1 -1
- package/dist/{server-DJl6uDKl.js → server-CcnH-kO1.js} +105 -91
- package/dist/server-CcnH-kO1.js.map +1 -0
- package/dist/{start-r3xnAtBs.js → start-CBnChdoU.js} +19 -16
- package/dist/{start-r3xnAtBs.js.map → start-CBnChdoU.js.map} +1 -1
- package/dist/{tls-Aq1Dd8E2.js → tls-uiriilgk.js} +1 -1
- package/dist/{tls-Aq1Dd8E2.js.map → tls-uiriilgk.js.map} +1 -1
- package/dist/{token-DZDtQb7h.js → token-O2WH6ipn.js} +81 -25
- package/dist/token-O2WH6ipn.js.map +1 -0
- package/dist/{tool-search-Ds1vbmGG.js → tool-search-BgFcDbNQ.js} +2 -2
- package/dist/{tool-search-Ds1vbmGG.js.map → tool-search-BgFcDbNQ.js.map} +1 -1
- package/package.json +4 -5
- package/dist/auth-BKEWjsYR.js +0 -2
- package/dist/mcp-server-DQ4r-fAy.js +0 -2
- package/dist/server-DJl6uDKl.js.map +0 -1
- package/dist/token-DZDtQb7h.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-DYtohLpX.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,IAAI;EACzC,GAAG,UAAU,YAAY;UAClB,OAAO;EACd,QAAQ,KAAK,8BAA8B,aAAa,MAAM;WACtD;EACR,IAAI,gBAAgB,KAAA,GAClB,IAAI;GACF,GAAG,UAAU,YAAY;UACnB;;;AAOd,SAAgB,oBAAoB,UAAkB,SAAuB;CAC3E,MAAM,YAAY,KAAK,QAAQ,SAAS;CACxC,MAAM,WAAW,KAAK,KACpB,WACA,IAAI,KAAK,SAAS,SAAS,CAAC,GAAG,QAAQ,IAAI,GAAG,YAAY,uBAAuB,CAAC,SAAS,MAAM,CAAC,MACnG;CAED,GAAG,UAAU,WAAW,EAAE,WAAW,MAAM,CAAC;CAE5C,IAAI;CACJ,IAAI,kBAAkB;CACtB,IAAI;EACF,iBAAiB,GAAG,SAAS,UAAU,MAAM,IAAM;EACnD,kBAAkB;EAClB,GAAG,cAAc,gBAAgB,SAAS,OAAO;EACjD,GAAG,UAAU,eAAe;EAC5B,GAAG,UAAU,eAAe;EAC5B,iBAAiB,KAAA;EACjB,GAAG,WAAW,UAAU,SAAS;EACjC,kBAAkB;EAClB,eAAe,UAAU;UAClB,OAAO;EACd,IAAI,mBAAmB,KAAA,GACrB,IAAI;GACF,GAAG,UAAU,eAAe;UACtB;EAKV,IAAI,iBACF,IAAI;GACF,GAAG,OAAO,UAAU,EAAE,OAAO,MAAM,CAAC;UAC9B;EAKV,MAAM;;;;;ACnEV,MAAM,WAAW,QAAQ,IAAI,uBAAuB,MAAM,IAAI;AAC9D,MAAM,oBAA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;;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"}
|
|
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/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,GAAG,UAAU,cAAc;EAC3B,GAAG,UAAU,cAAc;EAC3B,iBAAiB,KAAA;EACjB,GAAG,WAAW,UAAU,QAAQ;EAChC,kBAAkB;EAClB,eAAe,SAAS;CAC1B,SAAS,OAAO;EACd,IAAI,mBAAmB,KAAA,GACrB,IAAI;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AAC,CACpC,CAAC,CAAC,QAAQ,SAAS,kBAAkB,IAAI,MAAM,IAAI;AACxE;AAEA,SAAgB,uBAAuB,MAAuB;CAC5D,OAAO,KAAK,KAAK,MAAM;AACzB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { N as PATHS, i as listEnabledProviders, n as getRawProviderConfig } from "./config-
|
|
1
|
+
import { N as PATHS, i as listEnabledProviders, n as getRawProviderConfig } from "./config-2Dli6AI8.js";
|
|
2
2
|
import { defineCommand } from "citty";
|
|
3
3
|
import consola from "consola";
|
|
4
4
|
import fs from "node:fs/promises";
|
|
@@ -89,4 +89,4 @@ const debug = defineCommand({
|
|
|
89
89
|
//#endregion
|
|
90
90
|
export { debug };
|
|
91
91
|
|
|
92
|
-
//# sourceMappingURL=debug-
|
|
92
|
+
//# sourceMappingURL=debug-DV0aYj65.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debug-
|
|
1
|
+
{"version":3,"file":"debug-DV0aYj65.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport { fileURLToPath } from \"node:url\"\n\nimport { getRawProviderConfig, listEnabledProviders } from \"./lib/config\"\nimport { PATHS } from \"./lib/paths\"\n\ninterface DebugInfo {\n providers: {\n codexConfigured: boolean\n enabled: Array<string>\n }\n version: string\n runtime: {\n name: string\n version: string\n platform: string\n arch: string\n }\n paths: {\n APP_DIR: string\n CONFIG_PATH: string\n GITHUB_TOKEN_PATH: string\n }\n tokenExists: boolean\n}\n\ninterface RunDebugOptions {\n json: boolean\n}\n\nasync function getPackageVersion(): Promise<string> {\n try {\n const packageJsonPath = fileURLToPath(\n new URL(\"../package.json\", import.meta.url),\n )\n // @ts-expect-error https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v59.0.1/docs/rules/prefer-json-parse-buffer.md\n // JSON.parse() can actually parse buffers\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath)) as {\n version: string\n }\n return packageJson.version\n } catch {\n return \"unknown\"\n }\n}\n\nfunction getRuntimeInfo() {\n const isBun = typeof Bun !== \"undefined\"\n\n return {\n name: isBun ? \"bun\" : \"node\",\n version: isBun ? Bun.version : process.version.slice(1),\n platform: os.platform(),\n arch: os.arch(),\n }\n}\n\nasync function checkFileExists(filePath: string): Promise<boolean> {\n try {\n const stats = await fs.stat(filePath)\n if (!stats.isFile()) return false\n\n const content = await fs.readFile(filePath, \"utf8\")\n return content.trim().length > 0\n } catch {\n return false\n }\n}\n\nasync function getDebugInfo(): Promise<DebugInfo> {\n const [version, tokenExists] = await Promise.all([\n getPackageVersion(),\n checkFileExists(PATHS.GITHUB_TOKEN_PATH),\n ])\n\n return {\n providers: {\n codexConfigured: getRawProviderConfig(\"codex\") !== null,\n enabled: listEnabledProviders(),\n },\n version,\n runtime: getRuntimeInfo(),\n paths: {\n APP_DIR: PATHS.APP_DIR,\n CONFIG_PATH: PATHS.CONFIG_PATH,\n GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH,\n },\n tokenExists,\n }\n}\n\nfunction printDebugInfoPlain(info: DebugInfo): void {\n consola.info(`copilot-api debug\n\nVersion: ${info.version}\nRuntime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})\n\nProviders:\n- enabled: ${info.providers.enabled.join(\", \") || \"none\"}\n- codex configured: ${info.providers.codexConfigured ? \"Yes\" : \"No\"}\n\nPaths:\n- APP_DIR: ${info.paths.APP_DIR}\n- CONFIG_PATH: ${info.paths.CONFIG_PATH}\n- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}\n\nGitHub token exists: ${info.tokenExists ? \"Yes\" : \"No\"}`)\n}\n\nfunction printDebugInfoJson(info: DebugInfo): void {\n console.log(JSON.stringify(info, null, 2))\n}\n\nexport async function runDebug(options: RunDebugOptions): Promise<void> {\n const debugInfo = await getDebugInfo()\n\n if (options.json) {\n printDebugInfoJson(debugInfo)\n } else {\n printDebugInfoPlain(debugInfo)\n }\n}\n\nexport const debug = defineCommand({\n meta: {\n name: \"debug\",\n description: \"Print debug information about the application\",\n },\n args: {\n json: {\n type: \"boolean\",\n default: false,\n description: \"Output debug information as JSON\",\n },\n },\n run({ args }) {\n return runDebug({\n json: args.json,\n })\n },\n})\n"],"mappings":";;;;;;;AAmCA,eAAe,oBAAqC;CAClD,IAAI;EACF,MAAM,kBAAkB,cACtB,IAAI,IAAI,mBAAmB,YAAY,GAAG,CAC5C;EAMA,OAHoB,KAAK,MAAM,MAAM,GAAG,SAAS,eAAe,CAG/C,CAAC,CAAC;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,iBAAiB;CACxB,MAAM,QAAQ,OAAO,QAAQ;CAE7B,OAAO;EACL,MAAM,QAAQ,QAAQ;EACtB,SAAS,QAAQ,IAAI,UAAU,QAAQ,QAAQ,MAAM,CAAC;EACtD,UAAU,GAAG,SAAS;EACtB,MAAM,GAAG,KAAK;CAChB;AACF;AAEA,eAAe,gBAAgB,UAAoC;CACjE,IAAI;EAEF,IAAI,EAAC,MADe,GAAG,KAAK,QAAQ,EAAA,CACzB,OAAO,GAAG,OAAO;EAG5B,QAAO,MADe,GAAG,SAAS,UAAU,MAAM,EAAA,CACnC,KAAK,CAAC,CAAC,SAAS;CACjC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,eAAmC;CAChD,MAAM,CAAC,SAAS,eAAe,MAAM,QAAQ,IAAI,CAC/C,kBAAkB,GAClB,gBAAgB,MAAM,iBAAiB,CACzC,CAAC;CAED,OAAO;EACL,WAAW;GACT,iBAAiB,qBAAqB,OAAO,MAAM;GACnD,SAAS,qBAAqB;EAChC;EACA;EACA,SAAS,eAAe;EACxB,OAAO;GACL,SAAS,MAAM;GACf,aAAa,MAAM;GACnB,mBAAmB,MAAM;EAC3B;EACA;CACF;AACF;AAEA,SAAS,oBAAoB,MAAuB;CAClD,QAAQ,KAAK;;WAEJ,KAAK,QAAQ;WACb,KAAK,QAAQ,KAAK,GAAG,KAAK,QAAQ,QAAQ,IAAI,KAAK,QAAQ,SAAS,GAAG,KAAK,QAAQ,KAAK;;;aAGvF,KAAK,UAAU,QAAQ,KAAK,IAAI,KAAK,OAAO;sBACnC,KAAK,UAAU,kBAAkB,QAAQ,KAAK;;;aAGvD,KAAK,MAAM,QAAQ;iBACf,KAAK,MAAM,YAAY;uBACjB,KAAK,MAAM,kBAAkB;;uBAE7B,KAAK,cAAc,QAAQ,MAAM;AACxD;AAEA,SAAS,mBAAmB,MAAuB;CACjD,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAC3C;AAEA,eAAsB,SAAS,SAAyC;CACtE,MAAM,YAAY,MAAM,aAAa;CAErC,IAAI,QAAQ,MACV,mBAAmB,SAAS;MAE5B,oBAAoB,SAAS;AAEjC;AAEA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;CACf,EACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,KACb,CAAC;CACH;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"electron-fetch-
|
|
1
|
+
{"version":3,"file":"electron-fetch-DsMaRX6v.js","names":[],"sources":["../src/lib/electron-fetch.ts"],"sourcesContent":["import consola from \"consola\"\nimport { createRequire } from \"node:module\"\n\ntype ElectronModule = {\n net?: {\n fetch?: typeof fetch\n }\n}\n\nconst require = createRequire(import.meta.url)\n\nexport function bindElectronFetch(): boolean {\n if (!process.versions.electron) return false\n\n try {\n const electronModule = require(\"electron\") as ElectronModule\n const netFetch = electronModule.net?.fetch\n\n if (typeof netFetch !== \"function\") return false\n\n globalThis.fetch = netFetch.bind(electronModule.net)\n consola.log(\"Successfully bound Electron's net.fetch to global fetch.\")\n return true\n } catch {\n consola.log(\n \"Failed to bind Electron's net.fetch. Falling back to global fetch.\",\n )\n return false\n }\n}\n"],"mappings":";;;AASA,MAAM,UAAU,cAAc,YAAY,GAAG;AAE7C,SAAgB,oBAA6B;CAC3C,IAAI,CAAC,QAAQ,SAAS,UAAU,OAAO;CAEvC,IAAI;EACF,MAAM,iBAAiB,QAAQ,UAAU;EACzC,MAAM,WAAW,eAAe,KAAK;EAErC,IAAI,OAAO,aAAa,YAAY,OAAO;EAE3C,WAAW,QAAQ,SAAS,KAAK,eAAe,GAAG;EACnD,QAAQ,IAAI,0DAA0D;EACtE,OAAO;CACT,QAAQ;EACN,QAAQ,IACN,oEACF;EACA,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fast-path-
|
|
1
|
+
{"version":3,"file":"fast-path-BwgQKZBk.js","names":[],"sources":["../src/lib/fast-path.ts"],"sourcesContent":["export const MCP_SUBCOMMAND = \"mcp\"\n\n/**\n * Only a direct `copilot-api mcp` invocation takes the fast path. Global flags\n * before the subcommand (e.g. `--api-home`) or help flags after it route to\n * citty through the regular startup path. Any other trailing args after `mcp`\n * are ignored because the MCP server consumes no CLI options.\n */\nexport const isMcpFastPath = (argv: ReadonlyArray<string>): boolean =>\n argv[2] === MCP_SUBCOMMAND\n && !argv\n .slice(3)\n .some((argument) => argument === \"-h\" || argument === \"--help\")\n"],"mappings":";;;;;;AAQA,MAAa,iBAAiB,SAC5B,KAAK,OAAA,SACF,CAAC,KACD,MAAM,CAAC,CAAC,CACR,MAAM,aAAa,aAAa,QAAQ,aAAa,QAAQ"}
|
package/dist/main.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { t as isMcpFastPath } from "./fast-path-
|
|
2
|
+
import { t as isMcpFastPath } from "./fast-path-BwgQKZBk.js";
|
|
3
3
|
//#region src/main.ts
|
|
4
4
|
if (isMcpFastPath(process.argv)) {
|
|
5
|
-
const { runMcpServer } = await import("./mcp-server-
|
|
5
|
+
const { runMcpServer } = await import("./mcp-server-ouCaZXlw.js");
|
|
6
6
|
await runMcpServer();
|
|
7
7
|
} else {
|
|
8
8
|
const { defineCommand, runMain, parseArgs } = await import("citty");
|
|
@@ -25,12 +25,12 @@ if (isMcpFastPath(process.argv)) {
|
|
|
25
25
|
if (typeof args["oauth-app"] === "string") process.env.COPILOT_API_OAUTH_APP = args["oauth-app"];
|
|
26
26
|
if (typeof args["enterprise-url"] === "string") process.env.COPILOT_API_ENTERPRISE_URL = args["enterprise-url"];
|
|
27
27
|
if (process.platform === "win32" && process.stdout.isTTY && !process.env.WT_SESSION) process.env.WT_SESSION = "copilot-api";
|
|
28
|
-
const { bindElectronFetch } = await import("./electron-fetch-
|
|
28
|
+
const { bindElectronFetch } = await import("./electron-fetch-DsMaRX6v.js");
|
|
29
29
|
bindElectronFetch();
|
|
30
|
-
const { auth } = await import("./auth-
|
|
31
|
-
const { debug } = await import("./debug-
|
|
32
|
-
const { mcp } = await import("./mcp-
|
|
33
|
-
const { start } = await import("./start-
|
|
30
|
+
const { auth } = await import("./auth-CX6c7jlD.js");
|
|
31
|
+
const { debug } = await import("./debug-DV0aYj65.js");
|
|
32
|
+
const { mcp } = await import("./mcp-Byz9h_xz.js");
|
|
33
|
+
const { start } = await import("./start-CBnChdoU.js");
|
|
34
34
|
await runMain(defineCommand({
|
|
35
35
|
meta: {
|
|
36
36
|
name: "copilot-api",
|
package/dist/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.js","names":[],"sources":["../src/main.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { isMcpFastPath } from \"./lib/fast-path\"\n\n// Fast path: `copilot-api mcp` starts the MCP bridge without loading citty\n// or the gateway modules, keeping MCP client startup fast.\nif (isMcpFastPath(process.argv)) {\n const { runMcpServer } = await import(\"./lib/mcp-server\")\n await runMcpServer()\n} else {\n const { defineCommand, runMain, parseArgs } = await import(\"citty\")\n\n const cliArgs = {\n \"api-home\": {\n type: \"string\",\n description: \"Path to the API home directory.\",\n },\n \"oauth-app\": {\n type: \"string\",\n description: \"OAuth app identifier.\",\n },\n \"enterprise-url\": {\n type: \"string\",\n description: \"Enterprise URL for GitHub.\",\n },\n } as const\n\n const args = parseArgs(process.argv, cliArgs)\n\n // Set environment variables before loading other modules\n if (typeof args[\"api-home\"] === \"string\") {\n process.env.COPILOT_API_HOME = args[\"api-home\"]\n }\n if (typeof args[\"oauth-app\"] === \"string\") {\n process.env.COPILOT_API_OAUTH_APP = args[\"oauth-app\"]\n }\n if (typeof args[\"enterprise-url\"] === \"string\") {\n process.env.COPILOT_API_ENTERPRISE_URL = args[\"enterprise-url\"]\n }\n\n // Work around unjs/consola#392 until consola ships the upstream fix.\n if (\n process.platform === \"win32\"\n && process.stdout.isTTY\n && !process.env.WT_SESSION\n ) {\n process.env.WT_SESSION = \"copilot-api\"\n }\n\n const { bindElectronFetch } = await import(\"./lib/electron-fetch\")\n bindElectronFetch()\n\n // Dynamically import other modules to ensure environment variables are set\n const { auth } = await import(\"./auth\")\n const { debug } = await import(\"./debug\")\n const { mcp } = await import(\"./mcp\")\n const { start } = await import(\"./start\")\n\n const main = defineCommand({\n meta: {\n name: \"copilot-api\",\n description:\n \"A wrapper around GitHub Copilot API to make it OpenAI compatible, making it usable for other tools.\",\n },\n subCommands: { auth, start, debug, mcp },\n args: cliArgs,\n })\n\n await runMain(main)\n}\n"],"mappings":";;;AAMA,IAAI,cAAc,QAAQ,
|
|
1
|
+
{"version":3,"file":"main.js","names":[],"sources":["../src/main.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { isMcpFastPath } from \"./lib/fast-path\"\n\n// Fast path: `copilot-api mcp` starts the MCP bridge without loading citty\n// or the gateway modules, keeping MCP client startup fast.\nif (isMcpFastPath(process.argv)) {\n const { runMcpServer } = await import(\"./lib/mcp-server\")\n await runMcpServer()\n} else {\n const { defineCommand, runMain, parseArgs } = await import(\"citty\")\n\n const cliArgs = {\n \"api-home\": {\n type: \"string\",\n description: \"Path to the API home directory.\",\n },\n \"oauth-app\": {\n type: \"string\",\n description: \"OAuth app identifier.\",\n },\n \"enterprise-url\": {\n type: \"string\",\n description: \"Enterprise URL for GitHub.\",\n },\n } as const\n\n const args = parseArgs(process.argv, cliArgs)\n\n // Set environment variables before loading other modules\n if (typeof args[\"api-home\"] === \"string\") {\n process.env.COPILOT_API_HOME = args[\"api-home\"]\n }\n if (typeof args[\"oauth-app\"] === \"string\") {\n process.env.COPILOT_API_OAUTH_APP = args[\"oauth-app\"]\n }\n if (typeof args[\"enterprise-url\"] === \"string\") {\n process.env.COPILOT_API_ENTERPRISE_URL = args[\"enterprise-url\"]\n }\n\n // Work around unjs/consola#392 until consola ships the upstream fix.\n if (\n process.platform === \"win32\"\n && process.stdout.isTTY\n && !process.env.WT_SESSION\n ) {\n process.env.WT_SESSION = \"copilot-api\"\n }\n\n const { bindElectronFetch } = await import(\"./lib/electron-fetch\")\n bindElectronFetch()\n\n // Dynamically import other modules to ensure environment variables are set\n const { auth } = await import(\"./auth\")\n const { debug } = await import(\"./debug\")\n const { mcp } = await import(\"./mcp\")\n const { start } = await import(\"./start\")\n\n const main = defineCommand({\n meta: {\n name: \"copilot-api\",\n description:\n \"A wrapper around GitHub Copilot API to make it OpenAI compatible, making it usable for other tools.\",\n },\n subCommands: { auth, start, debug, mcp },\n args: cliArgs,\n })\n\n await runMain(main)\n}\n"],"mappings":";;;AAMA,IAAI,cAAc,QAAQ,IAAI,GAAG;CAC/B,MAAM,EAAE,iBAAiB,MAAM,OAAO;CACtC,MAAM,aAAa;AACrB,OAAO;CACL,MAAM,EAAE,eAAe,SAAS,cAAc,MAAM,OAAO;CAE3D,MAAM,UAAU;EACd,YAAY;GACV,MAAM;GACN,aAAa;EACf;EACA,aAAa;GACX,MAAM;GACN,aAAa;EACf;EACA,kBAAkB;GAChB,MAAM;GACN,aAAa;EACf;CACF;CAEA,MAAM,OAAO,UAAU,QAAQ,MAAM,OAAO;CAG5C,IAAI,OAAO,KAAK,gBAAgB,UAC9B,QAAQ,IAAI,mBAAmB,KAAK;CAEtC,IAAI,OAAO,KAAK,iBAAiB,UAC/B,QAAQ,IAAI,wBAAwB,KAAK;CAE3C,IAAI,OAAO,KAAK,sBAAsB,UACpC,QAAQ,IAAI,6BAA6B,KAAK;CAIhD,IACE,QAAQ,aAAa,WAClB,QAAQ,OAAO,SACf,CAAC,QAAQ,IAAI,YAEhB,QAAQ,IAAI,aAAa;CAG3B,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,kBAAkB;CAGlB,MAAM,EAAE,SAAS,MAAM,OAAO;CAC9B,MAAM,EAAE,UAAU,MAAM,OAAO;CAC/B,MAAM,EAAE,QAAQ,MAAM,OAAO;CAC7B,MAAM,EAAE,UAAU,MAAM,OAAO;CAY/B,MAAM,QAVO,cAAc;EACzB,MAAM;GACJ,MAAM;GACN,aACE;EACJ;EACA,aAAa;GAAE;GAAM;GAAO;GAAO;EAAI;EACvC,MAAM;CACR,CAEiB,CAAC;AACpB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as runMcpServer } from "./mcp-server-
|
|
1
|
+
import { t as runMcpServer } from "./mcp-server-D6uKVzo6.js";
|
|
2
2
|
import { defineCommand } from "citty";
|
|
3
3
|
//#region src/mcp.ts
|
|
4
4
|
const mcp = defineCommand({
|
|
@@ -13,4 +13,4 @@ const mcp = defineCommand({
|
|
|
13
13
|
//#endregion
|
|
14
14
|
export { mcp };
|
|
15
15
|
|
|
16
|
-
//# sourceMappingURL=mcp-
|
|
16
|
+
//# sourceMappingURL=mcp-Byz9h_xz.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-
|
|
1
|
+
{"version":3,"file":"mcp-Byz9h_xz.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\n\nimport { MCP_SUBCOMMAND } from \"./lib/fast-path\"\nimport { runMcpServer } from \"./lib/mcp-server\"\n\nexport const mcp = defineCommand({\n meta: {\n name: MCP_SUBCOMMAND,\n description: \"Start the Copilot API MCP tool_search bridge over stdio\",\n },\n run() {\n return runMcpServer()\n },\n})\n"],"mappings":";;;AAOA,MAAa,MAAM,cAAc;CAC/B,MAAM;EACJ,MAAA;EACA,aAAa;CACf;CACA,MAAM;EACJ,OAAO,aAAa;CACtB;AACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as createMcpToolSearchSentinel } from "./tool-search-
|
|
1
|
+
import { n as createMcpToolSearchSentinel } from "./tool-search-BgFcDbNQ.js";
|
|
2
2
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
3
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
4
|
import { z } from "zod";
|
|
@@ -24,4 +24,4 @@ const runMcpServer = async () => {
|
|
|
24
24
|
//#endregion
|
|
25
25
|
export { runMcpServer as t };
|
|
26
26
|
|
|
27
|
-
//# sourceMappingURL=mcp-server-
|
|
27
|
+
//# sourceMappingURL=mcp-server-D6uKVzo6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-server-
|
|
1
|
+
{"version":3,"file":"mcp-server-D6uKVzo6.js","names":[],"sources":["../src/lib/mcp-server.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\"\nimport { z } from \"zod\"\n\nimport { createMcpToolSearchSentinel } from \"./tool-search\"\n\nconst SERVER_NAME = \"tool_search\"\nconst SERVER_VERSION = \"1.0.0\"\n\nexport const runMcpServer = async (): Promise<void> => {\n const server = new McpServer({\n name: SERVER_NAME,\n version: SERVER_VERSION,\n })\n\n server.registerTool(\n \"search\",\n {\n title: \"Tool Search Bridge\",\n description:\n \"Load deferred tools by exact name through the Copilot API tool_search bridge.\",\n inputSchema: {\n names: z\n .string()\n .describe(\n 'Comma-separated exact deferred tool names to load, for example \"TaskList,TaskGet,mcp__fetch__fetch\".',\n ),\n },\n _meta: {\n \"anthropic/alwaysLoad\": true,\n },\n },\n ({ names }) => ({\n content: [\n {\n type: \"text\",\n text: createMcpToolSearchSentinel(names),\n },\n ],\n }),\n )\n\n await server.connect(new StdioServerTransport())\n}\n"],"mappings":";;;;;AAMA,MAAM,cAAc;AACpB,MAAM,iBAAiB;AAEvB,MAAa,eAAe,YAA2B;CACrD,MAAM,SAAS,IAAI,UAAU;EAC3B,MAAM;EACN,SAAS;CACX,CAAC;CAED,OAAO,aACL,UACA;EACE,OAAO;EACP,aACE;EACF,aAAa,EACX,OAAO,EACJ,OAAO,CAAC,CACR,SACC,wGACF,EACJ;EACA,OAAO,EACL,wBAAwB,KAC1B;CACF,IACC,EAAE,aAAa,EACd,SAAS,CACP;EACE,MAAM;EACN,MAAM,4BAA4B,KAAK;CACzC,CACF,EACF,EACF;CAEA,MAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AACjD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { J as state } from "./token-
|
|
1
|
+
import { J as state } from "./token-O2WH6ipn.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-
|
|
90
|
+
//# sourceMappingURL=models-mp3HRQcW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models-
|
|
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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