@jeffreycao/copilot-api 2.2.3 → 2.2.6

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 CHANGED
@@ -603,6 +603,8 @@ Use `copilot-api auth login --provider deepseek`, `--provider dashscope`, `--pro
603
603
 
604
604
  Use `copilot-api auth login --provider custom` to add or update another third-party provider from the CLI. The command prompts for the provider name, supported type (`anthropic`, `openai-compatible`, or `openai-responses`), `baseUrl`, masked `apiKey`, and `authType`; `authType` may be left as the type default or set to `x-api-key` / `authorization`.
605
605
 
606
+ Gateway API keys live under `auth.apiKeys` in `config.json`. Manage them with `copilot-api auth keys` (one operation per invocation): add a key with `--add <key>`, remove one with `--remove <key>`, list all with `--list`, or clear them all with `--clear`. Clients authenticate with any configured key via `x-api-key` or `Authorization: Bearer`. When no keys are configured, `copilot-api start` starts with authentication bypassed and prints a startup info message.
607
+
606
608
  ### Debug Command Options
607
609
 
608
610
  | Option | Description | Default | Alias |
package/README.zh-CN.md CHANGED
@@ -645,6 +645,8 @@ Copilot API 现在使用子命令结构,主要命令包括:
645
645
 
646
646
  使用 `copilot-api auth login --provider custom` 可以通过 CLI 新增或更新其他第三方 provider。命令会依次提示输入 provider name、项目支持的 type(`anthropic`、`openai-compatible` 或 `openai-responses`)、`baseUrl`、掩码显示的 `apiKey` 和 `authType`;`authType` 可保持 type 默认值,也可选择 `x-api-key` / `authorization`。
647
647
 
648
+ 网关 API Key 存放在 `config.json` 的 `auth.apiKeys` 中,可通过 `copilot-api auth keys` 管理(每次只执行一种操作):`--add <key>` 添加、`--remove <key>` 删除、`--list` 列出全部、`--clear` 清空。客户端通过 `x-api-key` 或 `Authorization: Bearer` 使用任意已配置的 Key 认证。未配置任何 Key 时,`copilot-api start` 会以“不校验认证”的方式启动并输出一条 info 级别的启动提示。
649
+
648
650
  ### Debug 命令选项
649
651
 
650
652
  | 选项 | 说明 | 默认值 | 别名 |
@@ -0,0 +1,2 @@
1
+ import { t as auth } from "./auth-Y46nJiDg.js";
2
+ export { auth };
@@ -1,5 +1,5 @@
1
- import { M as PATHS, N as ensurePaths, a as normalizeProviderBaseUrl, c as setProviderConfig, n as getRawProviderConfig, r as isSupportedProviderType, y as SUPPORTED_PROVIDER_TYPES } from "./config-BTzeWHkr.js";
2
- import { H as state, O as loginCodex, a as setupGitHubToken, n as persistCodexCredentials } from "./token-CVbmPxHp.js";
1
+ import { M as setConfiguredApiKeys, N as PATHS, P as ensurePaths, a as normalizeProviderBaseUrl, c as setProviderConfig, n as getRawProviderConfig, r as isSupportedProviderType, y as SUPPORTED_PROVIDER_TYPES } from "./config-BK3_YOxx.js";
2
+ import { A as getConfiguredApiKeys, K as state, M as loginCodex, a as setupGitHubToken, n as persistCodexCredentials } from "./token-u7yV0_hw.js";
3
3
  import { defineCommand } from "citty";
4
4
  import consola from "consola";
5
5
  //#region src/lib/quick-providers.ts
@@ -322,26 +322,117 @@ async function runAuthLogin(options) {
322
322
  consola.info(`Logging in with ${AUTH_PROVIDER_LABELS[provider]}`);
323
323
  await loginWithProvider(provider);
324
324
  }
325
+ const authKeysArgs = {
326
+ add: {
327
+ alias: "a",
328
+ type: "string",
329
+ description: "Add an API key for gateway authentication"
330
+ },
331
+ remove: {
332
+ alias: "r",
333
+ type: "string",
334
+ description: "Remove an API key"
335
+ },
336
+ list: {
337
+ alias: "l",
338
+ type: "boolean",
339
+ default: false,
340
+ description: "List configured API keys"
341
+ },
342
+ clear: {
343
+ type: "boolean",
344
+ default: false,
345
+ description: "Remove all configured API keys"
346
+ }
347
+ };
348
+ function normalizeAuthKeyValue(value) {
349
+ const normalizedKey = value.trim();
350
+ if (!normalizedKey) throw new Error("API key must be a non-empty string");
351
+ return normalizedKey;
352
+ }
353
+ async function runAuthKeys(options) {
354
+ (await import("./tls-Aq1Dd8E2.js")).enableSystemCACompat();
355
+ await ensurePaths();
356
+ const operations = [
357
+ ...options.add !== void 0 ? ["add"] : [],
358
+ ...options.remove !== void 0 ? ["remove"] : [],
359
+ ...options.list ? ["list"] : [],
360
+ ...options.clear ? ["clear"] : []
361
+ ];
362
+ if (operations.length > 1) throw new Error("Use only one of --add, --remove, --list, or --clear per invocation");
363
+ const operation = operations[0] ?? "list";
364
+ if (operation === "add") {
365
+ const apiKey = normalizeAuthKeyValue(options.add ?? "");
366
+ const currentKeys = getConfiguredApiKeys();
367
+ if (currentKeys.includes(apiKey)) {
368
+ consola.info(`API key already configured. ${currentKeys.length} API key(s) configured.`);
369
+ return;
370
+ }
371
+ const storedKeys = setConfiguredApiKeys([...currentKeys, apiKey]);
372
+ consola.success(`API key added to ${PATHS.CONFIG_PATH}. ${storedKeys.length} API key(s) configured.`);
373
+ return;
374
+ }
375
+ if (operation === "remove") {
376
+ const apiKey = normalizeAuthKeyValue(options.remove ?? "");
377
+ const currentKeys = getConfiguredApiKeys();
378
+ if (!currentKeys.includes(apiKey)) {
379
+ consola.info(`API key not found. ${currentKeys.length} API key(s) configured.`);
380
+ return;
381
+ }
382
+ const storedKeys = setConfiguredApiKeys(currentKeys.filter((key) => key !== apiKey));
383
+ consola.success(`API key removed from ${PATHS.CONFIG_PATH}. ${storedKeys.length} API key(s) configured.`);
384
+ return;
385
+ }
386
+ if (operation === "clear") {
387
+ setConfiguredApiKeys([]);
388
+ consola.success(`Removed all API keys from ${PATHS.CONFIG_PATH}.`);
389
+ return;
390
+ }
391
+ const currentKeys = getConfiguredApiKeys();
392
+ if (currentKeys.length === 0) {
393
+ consola.info("No API keys configured. Run `npx copilot-api auth keys --add <key>` to add one.");
394
+ return;
395
+ }
396
+ consola.info("Configured API keys:");
397
+ for (const key of currentKeys) consola.info(`- ${key}`);
398
+ }
325
399
  const auth = defineCommand({
326
400
  meta: {
327
401
  name: "auth",
328
402
  description: "Run authentication flows without running the server"
329
403
  },
330
404
  args: authArgs,
331
- subCommands: { login: defineCommand({
332
- meta: {
333
- name: "login",
334
- description: "Authenticate or configure a provider without running the server"
335
- },
336
- args: authArgs,
337
- run({ args }) {
338
- return runAuthLogin({
339
- provider: args.provider,
340
- verbose: args.verbose,
341
- showToken: args["show-token"]
342
- });
343
- }
344
- }) },
405
+ subCommands: {
406
+ login: defineCommand({
407
+ meta: {
408
+ name: "login",
409
+ description: "Authenticate or configure a provider without running the server"
410
+ },
411
+ args: authArgs,
412
+ run({ args }) {
413
+ return runAuthLogin({
414
+ provider: args.provider,
415
+ verbose: args.verbose,
416
+ showToken: args["show-token"]
417
+ });
418
+ }
419
+ }),
420
+ keys: defineCommand({
421
+ meta: {
422
+ name: "keys",
423
+ description: "Manage gateway API keys (auth.apiKeys) in the config"
424
+ },
425
+ args: authKeysArgs,
426
+ run({ args }) {
427
+ return runAuthKeys({
428
+ add: args.add,
429
+ remove: args.remove,
430
+ list: args.list,
431
+ clear: args.clear
432
+ });
433
+ }
434
+ })
435
+ },
345
436
  run({ args }) {
346
437
  if ((args._[0] ?? "").trim()) return;
347
438
  return runAuthLogin({
@@ -352,6 +443,6 @@ const auth = defineCommand({
352
443
  }
353
444
  });
354
445
  //#endregion
355
- export { runAuthLogin as n, runProviderSetup as r, auth as t };
446
+ export { runProviderSetup as i, runAuthKeys as n, runAuthLogin as r, auth as t };
356
447
 
357
- //# sourceMappingURL=auth-DflW0qnE.js.map
448
+ //# sourceMappingURL=auth-Y46nJiDg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-Y46nJiDg.js","names":[],"sources":["../src/lib/quick-providers.ts","../src/auth.ts"],"sourcesContent":["import type { ProviderType } from \"./config\"\n\ninterface QuickProviderConfig {\n type: ProviderType\n baseUrl: string\n pricingCurrency: string\n editableType: boolean\n}\n\nexport const QUICK_PROVIDER_CONFIGS = {\n \"opencode-go\": {\n type: \"openai-compatible\",\n baseUrl: \"https://opencode.ai/zen/go\",\n pricingCurrency: \"USD\",\n editableType: false,\n },\n kimi: {\n type: \"openai-compatible\",\n baseUrl: \"https://api.kimi.com/coding\",\n pricingCurrency: \"USD\",\n editableType: false,\n },\n deepseek: {\n type: \"anthropic\",\n baseUrl: \"https://api.deepseek.com/anthropic\",\n pricingCurrency: \"CNY\",\n editableType: true,\n },\n dashscope: {\n type: \"openai-compatible\",\n baseUrl: \"https://dashscope.aliyuncs.com/compatible-mode\",\n pricingCurrency: \"CNY\",\n editableType: true,\n },\n openrouter: {\n type: \"anthropic\",\n baseUrl: \"https://openrouter.ai/api\",\n pricingCurrency: \"USD\",\n editableType: false,\n },\n} satisfies Record<string, QuickProviderConfig>\n\nexport type QuickProviderName = keyof typeof QUICK_PROVIDER_CONFIGS\n","#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport {\n getRawProviderConfig,\n isSupportedProviderType,\n normalizeProviderBaseUrl,\n setProviderConfig,\n setConfiguredApiKeys,\n SUPPORTED_PROVIDER_TYPES,\n type ProviderAuthType,\n type ProviderConfig,\n type ProviderType,\n} from \"./lib/config\"\nimport { loginCodex } from \"./lib/oauth/codex\"\nimport { PATHS, ensurePaths } from \"./lib/paths\"\nimport { getConfiguredApiKeys } from \"./lib/request-auth\"\nimport {\n QUICK_PROVIDER_CONFIGS,\n type QuickProviderName,\n} from \"./lib/quick-providers\"\nimport { state } from \"./lib/state\"\nimport { persistCodexCredentials, setupGitHubToken } from \"./lib/token\"\n\ninterface RunAuthOptions {\n provider?: string\n verbose: boolean\n showToken: boolean\n}\n\nconst authArgs = {\n provider: {\n type: \"string\",\n description:\n \"Provider to log in with or configure (copilot, codex, opencode-go, kimi, deepseek, dashscope, openrouter, custom)\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n \"show-token\": {\n type: \"boolean\",\n default: false,\n description: \"Show provider access token on auth\",\n },\n} as const\n\nconst BUILTIN_PROVIDER_NAMES = [\"copilot\", \"codex\"] as const\nconst QUICK_PROVIDER_NAMES = Object.keys(\n QUICK_PROVIDER_CONFIGS,\n) as Array<QuickProviderName>\nconst AUTH_PROVIDER_NAMES = [\n ...BUILTIN_PROVIDER_NAMES,\n ...QUICK_PROVIDER_NAMES,\n \"custom\",\n] as const\nconst CUSTOM_PROVIDER_AUTH_TYPE_OPTION = \"__default__\"\nconst QUICK_PROVIDER_DEFAULT_TYPE_OPTION = \"__default__\"\nconst CUSTOM_PROVIDER_AUTH_TYPES = [\"x-api-key\", \"authorization\"] as const\n\ntype BuiltinProviderName = (typeof BUILTIN_PROVIDER_NAMES)[number]\ntype AuthProviderName = (typeof AUTH_PROVIDER_NAMES)[number]\ntype CustomProviderAuthType = (typeof CUSTOM_PROVIDER_AUTH_TYPES)[number]\n\nconst BUILTIN_PROVIDER_LABELS: Record<BuiltinProviderName, string> = {\n copilot: \"GitHub Copilot\",\n codex: \"OpenAI Codex\",\n}\nconst AUTH_PROVIDER_LABELS: Record<AuthProviderName, string> = {\n ...BUILTIN_PROVIDER_LABELS,\n \"opencode-go\": \"OpenCode Go\",\n kimi: \"Kimi\",\n deepseek: \"DeepSeek\",\n dashscope: \"DashScope\",\n openrouter: \"OpenRouter\",\n custom: \"Custom provider\",\n}\n\nfunction isAuthProviderName(\n providerName: string,\n): providerName is AuthProviderName {\n return AUTH_PROVIDER_NAMES.includes(providerName as AuthProviderName)\n}\n\nfunction isCustomProviderAuthType(\n value: string,\n): value is CustomProviderAuthType {\n return CUSTOM_PROVIDER_AUTH_TYPES.includes(value as CustomProviderAuthType)\n}\n\nfunction isQuickProviderName(\n providerName: AuthProviderName,\n): providerName is QuickProviderName {\n return QUICK_PROVIDER_NAMES.includes(providerName as QuickProviderName)\n}\n\nasync function resolveProviderSelection(\n providerArg: string | undefined,\n): Promise<AuthProviderName> {\n const availableProviders = [...AUTH_PROVIDER_NAMES]\n\n if (providerArg !== undefined) {\n const providerName = providerArg.trim()\n if (!isAuthProviderName(providerName)) {\n throw new Error(\n `Unknown provider '${providerArg}'. Expected one of: ${availableProviders.join(\", \")}`,\n )\n }\n return providerName\n }\n\n if (availableProviders.length === 1) {\n return availableProviders[0]\n }\n\n const provider = await consola.prompt(\"Select a provider to log in with\", {\n type: \"select\",\n options: availableProviders.map((providerName) => ({\n label: `${AUTH_PROVIDER_LABELS[providerName]} (${providerName})`,\n value: providerName,\n })),\n })\n\n if (!provider || !isAuthProviderName(provider)) {\n throw new Error(\"No provider selected\")\n }\n\n return provider\n}\n\nfunction assertCustomProviderName(providerName: string): void {\n if (!providerName) {\n throw new Error(\"Provider name must be a non-empty string\")\n }\n\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/u.test(providerName)) {\n throw new Error(\n \"Provider name must start with a letter or number and contain only letters, numbers, underscores, or hyphens\",\n )\n }\n\n if (providerName === \"copilot\" || providerName === \"codex\") {\n throw new Error(\n `Provider name '${providerName}' is reserved for a builtin provider`,\n )\n }\n}\n\nasync function promptRequiredText(\n message: string,\n fieldName: string,\n): Promise<string> {\n const value = await consola.prompt(message, { type: \"text\" })\n const normalizedValue = typeof value === \"string\" ? value.trim() : \"\"\n if (!normalizedValue) {\n throw new Error(`${fieldName} must be a non-empty string`)\n }\n return normalizedValue\n}\n\nfunction canUseMaskedPrompt(): boolean {\n return Boolean(\n process.stdin.isTTY\n && process.stdout.isTTY\n && typeof process.stdin.setRawMode === \"function\",\n )\n}\n\nasync function promptMaskedText(message: string): Promise<string> {\n if (!canUseMaskedPrompt()) {\n const value = await consola.prompt(message, { type: \"text\" })\n return typeof value === \"string\" ? value : \"\"\n }\n\n return await new Promise<string>((resolve, reject) => {\n let value = \"\"\n const rawModeWasEnabled = process.stdin.isRaw === true\n\n function cleanup(): void {\n process.stdin.off(\"data\", onData)\n process.stdin.setRawMode(rawModeWasEnabled)\n process.stdin.pause()\n }\n\n function finish(): void {\n cleanup()\n process.stdout.write(\"\\n\")\n resolve(value)\n }\n\n function cancel(): void {\n cleanup()\n process.stdout.write(\"\\n\")\n reject(new Error(\"Prompt cancelled\"))\n }\n\n function onData(chunk: Buffer): void {\n const input = chunk.toString(\"utf8\")\n\n if (input.startsWith(\"\\u001B\")) {\n return\n }\n\n for (const char of input) {\n if (char === \"\\u0003\") {\n cancel()\n return\n }\n\n if (char === \"\\r\" || char === \"\\n\") {\n finish()\n return\n }\n\n if (char === \"\\b\" || char === \"\\u007F\") {\n if (value.length > 0) {\n value = value.slice(0, -1)\n process.stdout.write(\"\\b \\b\")\n }\n continue\n }\n\n if (char >= \" \") {\n value += char\n process.stdout.write(\"*\")\n }\n }\n }\n\n process.stdout.write(`${message}: `)\n process.stdin.setRawMode(true)\n process.stdin.resume()\n process.stdin.on(\"data\", onData)\n })\n}\n\nasync function promptRequiredSecret(\n message: string,\n fieldName: string,\n): Promise<string> {\n const value = await promptMaskedText(message)\n const normalizedValue = value.trim()\n if (!normalizedValue) {\n throw new Error(`${fieldName} must be a non-empty string`)\n }\n return normalizedValue\n}\n\nasync function promptCustomProviderName(): Promise<string> {\n const providerName = await promptRequiredText(\n \"Enter provider name\",\n \"Provider name\",\n )\n assertCustomProviderName(providerName)\n return providerName\n}\n\nasync function promptCustomProviderType(): Promise<ProviderType> {\n const providerType = await consola.prompt(\"Select provider type\", {\n type: \"select\",\n options: SUPPORTED_PROVIDER_TYPES.map((type) => ({\n label: type,\n value: type,\n })),\n })\n\n if (\n typeof providerType !== \"string\"\n || !isSupportedProviderType(providerType)\n ) {\n throw new Error(\"No provider type selected\")\n }\n\n return providerType\n}\n\nasync function promptQuickProviderType(\n defaultType: ProviderType,\n): Promise<ProviderType> {\n const providerType = await consola.prompt(\n `Select provider type (default: ${defaultType})`,\n {\n type: \"select\",\n options: [\n {\n label: `Default (${defaultType})`,\n value: QUICK_PROVIDER_DEFAULT_TYPE_OPTION,\n },\n ...SUPPORTED_PROVIDER_TYPES.map((type) => ({\n label: type,\n value: type,\n })),\n ],\n },\n )\n\n if (providerType === QUICK_PROVIDER_DEFAULT_TYPE_OPTION) {\n return defaultType\n }\n\n if (\n typeof providerType === \"string\"\n && isSupportedProviderType(providerType)\n ) {\n return providerType\n }\n\n throw new Error(\"No provider type selected\")\n}\n\nfunction getDefaultProviderAuthType(\n providerType: ProviderType,\n): ProviderAuthType {\n return providerType === \"anthropic\" ? \"x-api-key\" : \"authorization\"\n}\n\nasync function promptCustomProviderAuthType(\n providerType: ProviderType,\n): Promise<ProviderAuthType | undefined> {\n const defaultAuthType = getDefaultProviderAuthType(providerType)\n const authType = await consola.prompt(\"Select provider auth type\", {\n type: \"select\",\n options: [\n {\n label: `Default (${defaultAuthType})`,\n value: CUSTOM_PROVIDER_AUTH_TYPE_OPTION,\n },\n ...CUSTOM_PROVIDER_AUTH_TYPES.map((value) => ({\n label: value,\n value,\n })),\n ],\n })\n\n if (authType === CUSTOM_PROVIDER_AUTH_TYPE_OPTION) {\n return undefined\n }\n\n if (typeof authType === \"string\" && isCustomProviderAuthType(authType)) {\n return authType\n }\n\n throw new Error(\"No provider auth type selected\")\n}\n\nasync function promptQuickProviderBaseUrl(\n defaultBaseUrl: string,\n): Promise<string> {\n const value = await consola.prompt(\n `Enter provider baseUrl (default: ${defaultBaseUrl})`,\n {\n type: \"text\",\n default: defaultBaseUrl,\n initial: defaultBaseUrl,\n },\n )\n const baseUrl = normalizeProviderBaseUrl(\n typeof value === \"string\" && value.trim() ? value : defaultBaseUrl,\n )\n if (!baseUrl) {\n throw new Error(\"baseUrl must be a non-empty string\")\n }\n\n return baseUrl\n}\n\nfunction buildCustomProviderConfig(\n existingProviderConfig: ProviderConfig,\n options: {\n apiKey: string\n authType?: ProviderAuthType\n baseUrl: string\n pricingCurrency?: string\n type: ProviderType\n },\n): ProviderConfig {\n return {\n type: options.type,\n enabled: true,\n baseUrl: options.baseUrl,\n apiKey: options.apiKey,\n ...(options.authType ? { authType: options.authType } : {}),\n pricingCurrency:\n options.pricingCurrency ?? existingProviderConfig.pricingCurrency,\n ...(existingProviderConfig.models ?\n { models: existingProviderConfig.models }\n : {}),\n }\n}\n\nasync function configureCustomProvider(): Promise<void> {\n const providerName = await promptCustomProviderName()\n const type = await promptCustomProviderType()\n const baseUrl = normalizeProviderBaseUrl(\n await promptRequiredText(\"Enter provider baseUrl\", \"baseUrl\"),\n )\n if (!baseUrl) {\n throw new Error(\"baseUrl must be a non-empty string\")\n }\n\n const apiKey = await promptRequiredSecret(\"Enter provider apiKey\", \"apiKey\")\n const authType = await promptCustomProviderAuthType(type)\n const existingProviderConfig = getRawProviderConfig(providerName) ?? {}\n\n setProviderConfig(\n providerName,\n buildCustomProviderConfig(existingProviderConfig, {\n apiKey,\n authType,\n baseUrl,\n type,\n }),\n )\n\n consola.success(\n `Custom provider '${providerName}' written to ${PATHS.CONFIG_PATH}`,\n )\n}\n\nasync function configureQuickProvider(\n providerName: QuickProviderName,\n): Promise<void> {\n const defaultProviderConfig = QUICK_PROVIDER_CONFIGS[providerName]\n const apiKey = await promptRequiredSecret(\n `Enter ${providerName} apiKey`,\n \"apiKey\",\n )\n const type =\n defaultProviderConfig.editableType ?\n await promptQuickProviderType(defaultProviderConfig.type)\n : defaultProviderConfig.type\n const baseUrl = await promptQuickProviderBaseUrl(\n defaultProviderConfig.baseUrl,\n )\n const existingProviderConfig = getRawProviderConfig(providerName) ?? {}\n\n setProviderConfig(\n providerName,\n buildCustomProviderConfig(existingProviderConfig, {\n apiKey,\n baseUrl,\n pricingCurrency: defaultProviderConfig.pricingCurrency,\n type,\n }),\n )\n\n consola.success(\n `${AUTH_PROVIDER_LABELS[providerName]} provider '${providerName}' written to ${PATHS.CONFIG_PATH}`,\n )\n}\n\nasync function loginWithCodex(): Promise<void> {\n const credentials = await loginCodex({\n onAuth(info) {\n consola.info(\"Open the following URL to authenticate with Codex:\")\n consola.log(info.url)\n if (info.instructions) {\n consola.info(info.instructions)\n }\n },\n onPrompt(message) {\n return consola.prompt(message, {\n type: \"text\",\n })\n },\n onProgress(message) {\n consola.debug(message)\n },\n })\n\n await persistCodexCredentials(credentials, { enableProvider: true })\n consola.success(\n `Codex provider config written to ${PATHS.CONFIG_PATH} and credentials written to ${PATHS.CODEX_CREDENTIAL_PATH}`,\n )\n}\n\nasync function loginWithProvider(provider: AuthProviderName): Promise<void> {\n if (provider === \"copilot\") {\n await setupGitHubToken({ force: true })\n consola.success(\"GitHub token written to\", PATHS.GITHUB_TOKEN_PATH)\n return\n }\n\n if (provider === \"codex\") {\n await loginWithCodex()\n return\n }\n\n if (isQuickProviderName(provider)) {\n await configureQuickProvider(provider)\n return\n }\n\n await configureCustomProvider()\n}\n\nexport async function runProviderSetup(): Promise<void> {\n const provider = await resolveProviderSelection(undefined)\n consola.info(`Logging in with ${AUTH_PROVIDER_LABELS[provider]}`)\n await loginWithProvider(provider)\n}\n\nexport async function runAuthLogin(options: RunAuthOptions): Promise<void> {\n const tlsModule = await import(\"./lib/tls\")\n tlsModule.enableSystemCACompat()\n\n if (options.verbose) {\n consola.level = 5\n consola.info(\"Verbose logging enabled\")\n }\n\n state.showToken = options.showToken\n\n await ensurePaths()\n const provider = await resolveProviderSelection(options.provider)\n\n consola.info(`Logging in with ${AUTH_PROVIDER_LABELS[provider]}`)\n await loginWithProvider(provider)\n}\n\nconst authKeysArgs = {\n add: {\n alias: \"a\",\n type: \"string\",\n description: \"Add an API key for gateway authentication\",\n },\n remove: {\n alias: \"r\",\n type: \"string\",\n description: \"Remove an API key\",\n },\n list: {\n alias: \"l\",\n type: \"boolean\",\n default: false,\n description: \"List configured API keys\",\n },\n clear: {\n type: \"boolean\",\n default: false,\n description: \"Remove all configured API keys\",\n },\n} as const\n\ninterface RunAuthKeysOptions {\n add?: string\n remove?: string\n list?: boolean\n clear?: boolean\n}\n\nfunction normalizeAuthKeyValue(value: string): string {\n const normalizedKey = value.trim()\n if (!normalizedKey) {\n throw new Error(\"API key must be a non-empty string\")\n }\n return normalizedKey\n}\n\nexport async function runAuthKeys(options: RunAuthKeysOptions): Promise<void> {\n const tlsModule = await import(\"./lib/tls\")\n tlsModule.enableSystemCACompat()\n\n await ensurePaths()\n\n const operations = [\n ...(options.add !== undefined ? [\"add\"] : []),\n ...(options.remove !== undefined ? [\"remove\"] : []),\n ...(options.list ? [\"list\"] : []),\n ...(options.clear ? [\"clear\"] : []),\n ]\n if (operations.length > 1) {\n throw new Error(\n \"Use only one of --add, --remove, --list, or --clear per invocation\",\n )\n }\n\n const operation = operations[0] ?? \"list\"\n\n if (operation === \"add\") {\n const apiKey = normalizeAuthKeyValue(options.add ?? \"\")\n const currentKeys = getConfiguredApiKeys()\n if (currentKeys.includes(apiKey)) {\n consola.info(\n `API key already configured. ${currentKeys.length} API key(s) configured.`,\n )\n return\n }\n const storedKeys = setConfiguredApiKeys([...currentKeys, apiKey])\n consola.success(\n `API key added to ${PATHS.CONFIG_PATH}. ${storedKeys.length} API key(s) configured.`,\n )\n return\n }\n\n if (operation === \"remove\") {\n const apiKey = normalizeAuthKeyValue(options.remove ?? \"\")\n const currentKeys = getConfiguredApiKeys()\n if (!currentKeys.includes(apiKey)) {\n consola.info(\n `API key not found. ${currentKeys.length} API key(s) configured.`,\n )\n return\n }\n const storedKeys = setConfiguredApiKeys(\n currentKeys.filter((key) => key !== apiKey),\n )\n consola.success(\n `API key removed from ${PATHS.CONFIG_PATH}. ${storedKeys.length} API key(s) configured.`,\n )\n return\n }\n\n if (operation === \"clear\") {\n setConfiguredApiKeys([])\n consola.success(`Removed all API keys from ${PATHS.CONFIG_PATH}.`)\n return\n }\n\n const currentKeys = getConfiguredApiKeys()\n if (currentKeys.length === 0) {\n consola.info(\n \"No API keys configured. Run `npx copilot-api auth keys --add <key>` to add one.\",\n )\n return\n }\n consola.info(\"Configured API keys:\")\n for (const key of currentKeys) {\n consola.info(`- ${key}`)\n }\n}\n\nconst authLogin = defineCommand({\n meta: {\n name: \"login\",\n description:\n \"Authenticate or configure a provider without running the server\",\n },\n args: authArgs,\n run({ args }) {\n return runAuthLogin({\n provider: args.provider,\n verbose: args.verbose,\n showToken: args[\"show-token\"],\n })\n },\n})\n\nconst authKeys = defineCommand({\n meta: {\n name: \"keys\",\n description: \"Manage gateway API keys (auth.apiKeys) in the config\",\n },\n args: authKeysArgs,\n run({ args }) {\n return runAuthKeys({\n add: args.add,\n remove: args.remove,\n list: args.list,\n clear: args.clear,\n })\n },\n})\n\nexport const auth = defineCommand({\n meta: {\n name: \"auth\",\n description: \"Run authentication flows without running the server\",\n },\n args: authArgs,\n subCommands: {\n login: authLogin,\n keys: authKeys,\n },\n run({ args }) {\n if ((args._[0] ?? \"\").trim()) {\n return\n }\n\n return runAuthLogin({\n provider: args.provider,\n verbose: args.verbose,\n showToken: args[\"show-token\"],\n })\n },\n})\n"],"mappings":";;;;;AASA,MAAa,yBAAyB;CACpC,eAAe;EACb,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACD,MAAM;EACJ,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACD,UAAU;EACR,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACD,WAAW;EACT,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACD,YAAY;EACV,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACF;;;ACRD,MAAM,WAAW;CACf,UAAU;EACR,MAAM;EACN,aACE;EACH;CACD,SAAS;EACP,OAAO;EACP,MAAM;EACN,SAAS;EACT,aAAa;EACd;CACD,cAAc;EACZ,MAAM;EACN,SAAS;EACT,aAAa;EACd;CACF;AAED,MAAM,yBAAyB,CAAC,WAAW,QAAQ;AACnD,MAAM,uBAAuB,OAAO,KAClC,uBACD;AACD,MAAM,sBAAsB;CAC1B,GAAG;CACH,GAAG;CACH;CACD;AACD,MAAM,mCAAmC;AACzC,MAAM,qCAAqC;AAC3C,MAAM,6BAA6B,CAAC,aAAa,gBAAgB;AAUjE,MAAM,uBAAyD;CAH7D,SAAS;CACT,OAAO;CAIP,eAAe;CACf,MAAM;CACN,UAAU;CACV,WAAW;CACX,YAAY;CACZ,QAAQ;CACT;AAED,SAAS,mBACP,cACkC;CAClC,OAAO,oBAAoB,SAAS,aAAiC;;AAGvE,SAAS,yBACP,OACiC;CACjC,OAAO,2BAA2B,SAAS,MAAgC;;AAG7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Atomically(PATHS.CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`);
178
178
  }
179
+ function setConfiguredApiKeys(apiKeys) {
180
+ const normalizedKeys = apiKeys.map((key) => key.trim()).filter((key) => key.length > 0);
181
+ const uniqueKeys = [...new Set(normalizedKeys)];
182
+ const editableConfig = readEditableConfigFromDisk();
183
+ writeConfigToDisk({
184
+ ...editableConfig,
185
+ auth: {
186
+ ...editableConfig.auth,
187
+ apiKeys: uniqueKeys
188
+ }
189
+ });
190
+ reloadConfig();
191
+ return [...uniqueKeys];
192
+ }
179
193
  function mergeDefaultConfig(config) {
180
194
  const extraPrompts = config.extraPrompts ?? {};
181
195
  const defaultExtraPrompts = defaultConfig.extraPrompts ?? {};
@@ -522,6 +536,6 @@ function isReservedProviderName(name) {
522
536
  return name.trim() === "copilot";
523
537
  }
524
538
  //#endregion
525
- export { isResponsesApiWebSocketEnabled as A, getClaudeTokenMultiplier as C, isAlphaSearchCodexPriorityEnabled as D, getResponsesTransportConfig as E, PATHS as M, ensurePaths as N, isMessagesApiEnabled as O, getClaudeAutoModel as S, getMessageApiWebSearchModel as T, resolveMappedModel as _, normalizeProviderBaseUrl as a, getAlphaSearchModel as b, setProviderConfig as c, getModelResponsesApiCompactThreshold as d, getReasoningEffortForModel as f, isGpt56OrAbove as g, isContextManagementEnabledForResponses as h, listEnabledProviders as i, mergeConfigWithDefaults as j, isResponsesApiWebSearchEnabled as k, getExtraPromptForModel as l, isContextManagementEnabledForMessages as m, getRawProviderConfig as n, resolveEffectiveProviderType as o, getSmallModel as p, isSupportedProviderType as r, resolveProviderAuthType as s, getProviderConfig as t, getModelMappings as u, setModelMappings as v, getConfig as w, getAnthropicApiKey as x, SUPPORTED_PROVIDER_TYPES as y };
539
+ export { isResponsesApiWebSocketEnabled as A, getClaudeTokenMultiplier as C, isAlphaSearchCodexPriorityEnabled as D, getResponsesTransportConfig as E, setConfiguredApiKeys as M, PATHS as N, isMessagesApiEnabled as O, ensurePaths as P, getClaudeAutoModel as S, getMessageApiWebSearchModel as T, resolveMappedModel as _, normalizeProviderBaseUrl as a, getAlphaSearchModel as b, setProviderConfig as c, getModelResponsesApiCompactThreshold as d, getReasoningEffortForModel as f, isGpt56OrAbove as g, isContextManagementEnabledForResponses as h, listEnabledProviders as i, mergeConfigWithDefaults as j, isResponsesApiWebSearchEnabled as k, getExtraPromptForModel as l, isContextManagementEnabledForMessages as m, getRawProviderConfig as n, resolveEffectiveProviderType as o, getSmallModel as p, isSupportedProviderType as r, resolveProviderAuthType as s, getProviderConfig as t, getModelMappings as u, setModelMappings as v, getConfig as w, getAnthropicApiKey as x, SUPPORTED_PROVIDER_TYPES as y };
526
540
 
527
- //# sourceMappingURL=config-BTzeWHkr.js.map
541
+ //# sourceMappingURL=config-BK3_YOxx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-BK3_YOxx.js","names":["fs"],"sources":["../src/lib/atomic-file.ts","../src/lib/paths.ts","../src/lib/config-store.ts","../src/lib/model-policy.ts","../src/lib/provider-config.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs\"\nimport path from \"node:path\"\n\nconst TEMP_FILE_RANDOM_BYTES = 8\n\n// The file-level fsync persists the contents, but the rename only updates the\n// parent directory entry, which needs its own fsync to survive a crash or\n// power loss. Best-effort: the rename has already taken effect, so a failure\n// here only weakens crash durability and must not fail the write. Directory\n// fsync is not supported on Windows (opening a directory handle fails there).\nconst fsyncDirectory = (directory: string): void => {\n if (process.platform === \"win32\") {\n return\n }\n\n let directoryFd: number | undefined\n try {\n directoryFd = fs.openSync(directory, \"r\")\n fs.fsyncSync(directoryFd)\n } catch (error) {\n console.warn(`Failed to fsync directory: ${directory}`, error)\n } finally {\n if (directoryFd !== undefined) {\n try {\n fs.closeSync(directoryFd)\n } catch {\n // Preserve the fsync warning.\n }\n }\n }\n}\n\nexport function writeFileAtomically(filePath: string, content: string): void {\n const directory = path.dirname(filePath)\n const tempPath = path.join(\n directory,\n `.${path.basename(filePath)}.${process.pid}.${randomBytes(TEMP_FILE_RANDOM_BYTES).toString(\"hex\")}.tmp`,\n )\n\n fs.mkdirSync(directory, { recursive: true })\n\n let fileDescriptor: number | undefined\n let tempFileCreated = false\n try {\n fileDescriptor = fs.openSync(tempPath, \"wx\", 0o600)\n tempFileCreated = true\n fs.writeFileSync(fileDescriptor, content, \"utf8\")\n fs.fsyncSync(fileDescriptor)\n fs.closeSync(fileDescriptor)\n fileDescriptor = undefined\n fs.renameSync(tempPath, filePath)\n tempFileCreated = false\n fsyncDirectory(directory)\n } catch (error) {\n if (fileDescriptor !== undefined) {\n try {\n fs.closeSync(fileDescriptor)\n } catch {\n // Preserve the original write error.\n }\n }\n\n if (tempFileCreated) {\n try {\n fs.rmSync(tempPath, { force: true })\n } catch {\n // Preserve the original write error.\n }\n }\n\n throw error\n }\n}\n","import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nconst AUTH_APP = process.env.COPILOT_API_OAUTH_APP?.trim() || \"\"\nconst ENTERPRISE_PREFIX = process.env.COPILOT_API_ENTERPRISE_URL ? \"ent_\" : \"\"\n\nconst DEFAULT_DIR = path.join(os.homedir(), \".local\", \"share\", \"copilot-api\")\nconst APP_DIR = process.env.COPILOT_API_HOME || DEFAULT_DIR\n\nconst GITHUB_TOKEN_PATH = path.join(\n APP_DIR,\n AUTH_APP,\n ENTERPRISE_PREFIX + \"github_token\",\n)\nconst CODEX_CREDENTIAL_PATH = path.join(APP_DIR, \"codex_credentials.json\")\nconst CONFIG_PATH = path.join(APP_DIR, \"config.json\")\n\nexport const PATHS = {\n APP_DIR,\n GITHUB_TOKEN_PATH,\n CODEX_CREDENTIAL_PATH,\n CONFIG_PATH,\n}\n\nexport async function ensurePaths(): Promise<void> {\n await fs.mkdir(path.join(PATHS.APP_DIR, AUTH_APP), { recursive: true })\n await ensureFile(PATHS.GITHUB_TOKEN_PATH)\n await ensureFile(PATHS.CONFIG_PATH)\n}\n\nasync function ensureFile(filePath: string): Promise<void> {\n try {\n await fs.access(filePath, fs.constants.W_OK)\n } catch {\n await fs.writeFile(filePath, \"\")\n await fs.chmod(filePath, 0o600)\n }\n}\n","import consola from \"consola\"\nimport { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs\"\n\nimport type { TokenUsagePricingConfig } from \"~/lib/token-usage/pricing\"\n\nimport { writeFileAtomically } from \"./atomic-file\"\nimport { PATHS } from \"./paths\"\n\nexport interface AppConfig {\n auth?: {\n apiKeys?: Array<string>\n adminApiKey?: string\n }\n providers?: Record<string, ProviderConfig>\n modelMappings?: Record<string, string>\n extraPrompts?: Record<string, string>\n smallModel?: string\n contextManagement?: ContextManagementConfig\n modelResponsesApiCompactThresholds?: Record<string, number>\n modelReasoningEfforts?: Record<\n string,\n \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\"\n >\n useMessagesApi?: boolean\n useResponsesApiWebSocket?: boolean\n responsesTransport?: ResponsesTransportConfig\n anthropicApiKey?: string\n useResponsesApiWebSearch?: boolean\n alphaSearchCodexPriority?: boolean\n alphaSearchModel?: string\n // Copilot rejects Anthropic's web_search server tool on /v1/messages, so a\n // Claude request that only asks for web search is switched to this model.\n // A `provider/model` alias is passed straight through to that provider's\n // (websearch-capable) message API, while a plain GPT model runs the search\n // via /responses. Leave unset to disable (the tool is then stripped).\n // Mixing web_search with other tools is not supported.\n messageApiWebSearchModel?: string\n // Model used for Claude Code background security-monitor requests on\n // /v1/messages and provider message APIs: requests without tools, with\n // `stop_sequences: [\"</block>\"]` and a system block starting with\n // \"You are a security monitor for autonomous AI coding agents.\".\n // A `provider/model` alias is forwarded to that provider's message API on\n // the top-level route. Provider message routes use the configured value on\n // their current provider. Leave empty to disable (default).\n claudeAutoModel?: string\n claudeTokenMultiplier?: number\n}\n\nexport interface ContextManagementConfig {\n messages?: boolean\n responses?: boolean\n}\n\nexport interface ResponsesTransportConfig {\n headersTimeoutMsV2?: number\n streamInactivityTimeoutMs?: number\n websocketMaxBufferedBytes?: number\n websocketMaxBufferedMessages?: number\n websocketOpenTimeoutMs?: number\n websocketPoolIdleTimeoutMs?: number\n}\n\nexport const defaultResponsesTransportConfig = {\n headersTimeoutMsV2: 5 * 60 * 1000,\n streamInactivityTimeoutMs: 5 * 60 * 1000,\n websocketMaxBufferedBytes: 8 * 1024 * 1024,\n websocketMaxBufferedMessages: 1024,\n websocketOpenTimeoutMs: 30_000,\n websocketPoolIdleTimeoutMs: 60_000,\n} satisfies Required<ResponsesTransportConfig>\n\nexport interface ModelConfig {\n temperature?: number\n topP?: number\n topK?: number\n extraBody?: Record<string, unknown>\n contextCache?: boolean\n contextWindow?: number\n maxOutputTokens?: number\n inputModalities?: Array<\"text\" | \"image\">\n reasoningEfforts?: Array<CodexReasoningEffort>\n defaultReasoningEffort?: CodexReasoningEffort\n pricing?: TokenUsagePricingConfig\n supportPdf?: boolean\n toolContentSupportType?: Array<ToolContentSupportType>\n type?: ProviderType\n}\n\nexport type CodexReasoningEffort =\n | \"none\"\n | \"minimal\"\n | \"low\"\n | \"medium\"\n | \"high\"\n | \"xhigh\"\n | \"max\"\n | \"ultra\"\n\nexport type ProviderAuthType = \"authorization\" | \"oauth2\" | \"x-api-key\"\nexport const SUPPORTED_PROVIDER_TYPES = [\n \"anthropic\",\n \"openai-compatible\",\n \"openai-responses\",\n] as const\nexport type ProviderType = (typeof SUPPORTED_PROVIDER_TYPES)[number]\nexport type ToolContentSupportType = \"array\" | \"image\" | \"pdf\"\n\nexport interface ProviderConfig {\n type?: string\n enabled?: boolean\n baseUrl?: string\n apiKey?: string\n authType?: ProviderAuthType\n pricingCurrency?: string\n models?: Record<string, ModelConfig>\n}\n\nconst gpt5ExplorationPrompt = `## Exploration and reading files\n- **Think first.** Before any tool call, decide ALL files/resources you will need.\n- **Batch everything.** If you need multiple files (even from different places), read them together.\n- **multi_tool_use.parallel** Use multi_tool_use.parallel to parallelize tool calls and only this.\n- **Only make sequential calls if you truly cannot know the next file without seeing a result first.**\n- **Workflow:** (a) plan all needed reads → (b) issue one parallel batch → (c) analyze results → (d) repeat if new, unpredictable reads arise.`\n\nconst modelResponsesApiCompactThresholds = {\n \"gpt-5.4\": 272_000 * 0.8,\n \"gpt-5.5\": 272_000 * 0.8,\n}\n\nexport const defaultContextManagement = {\n messages: true,\n responses: false,\n} satisfies Required<ContextManagementConfig>\n\nexport const defaultConfig: AppConfig = {\n auth: {\n apiKeys: [],\n },\n providers: {},\n modelMappings: {},\n extraPrompts: {\n \"gpt-5-mini\": gpt5ExplorationPrompt,\n },\n smallModel: \"gpt-5-mini\",\n contextManagement: defaultContextManagement,\n modelResponsesApiCompactThresholds,\n modelReasoningEfforts: {\n \"gpt-5-mini\": \"low\",\n },\n useMessagesApi: true,\n useResponsesApiWebSocket: true,\n responsesTransport: defaultResponsesTransportConfig,\n useResponsesApiWebSearch: true,\n alphaSearchCodexPriority: true,\n alphaSearchModel: \"gpt-5-mini\",\n messageApiWebSearchModel: \"gpt-5-mini\",\n}\n\nlet cachedConfig: AppConfig | null = null\n\nfunction normalizeAdminApiKey(adminApiKey: unknown): string | null {\n if (typeof adminApiKey !== \"string\") {\n if (adminApiKey !== undefined) {\n consola.warn(\n \"Invalid auth.adminApiKey config. Expected a non-empty string.\",\n )\n }\n return null\n }\n\n const normalizedAdminApiKey = adminApiKey.trim()\n if (!normalizedAdminApiKey) {\n consola.warn(\n \"Invalid auth.adminApiKey config. Expected a non-empty string.\",\n )\n return null\n }\n\n return normalizedAdminApiKey\n}\n\nfunction generateAdminApiKey(): string {\n return randomBytes(32).toString(\"hex\")\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error\n}\n\nfunction ensureConfigFile(): void {\n try {\n fs.accessSync(PATHS.CONFIG_PATH, fs.constants.R_OK | fs.constants.W_OK)\n } catch {\n writeFileAtomically(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\n )\n try {\n fs.chmodSync(PATHS.CONFIG_PATH, 0o600)\n } catch {\n return\n }\n }\n}\n\nfunction readConfigFromDisk(): AppConfig {\n ensureConfigFile()\n try {\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 return JSON.parse(raw) as AppConfig\n } catch (error) {\n consola.error(\"Failed to read config file, using default config\", error)\n return defaultConfig\n }\n}\n\nexport function readEditableConfigFromDisk(): AppConfig {\n try {\n const raw = fs.readFileSync(PATHS.CONFIG_PATH, \"utf8\")\n if (!raw.trim()) {\n return {}\n }\n return JSON.parse(raw) as AppConfig\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return {}\n }\n if (error instanceof SyntaxError) {\n throw new Error(`Config file is not valid JSON: ${PATHS.CONFIG_PATH}`)\n }\n throw error\n }\n}\n\nexport function writeConfigToDisk(config: AppConfig): void {\n writeFileAtomically(PATHS.CONFIG_PATH, `${JSON.stringify(config, null, 2)}\\n`)\n}\n\nexport function setConfiguredApiKeys(apiKeys: Array<string>): Array<string> {\n const normalizedKeys = apiKeys\n .map((key) => key.trim())\n .filter((key) => key.length > 0)\n const uniqueKeys = [...new Set(normalizedKeys)]\n\n const editableConfig = readEditableConfigFromDisk()\n writeConfigToDisk({\n ...editableConfig,\n auth: {\n ...editableConfig.auth,\n apiKeys: uniqueKeys,\n },\n })\n reloadConfig()\n return [...uniqueKeys]\n}\n\nfunction mergeDefaultConfig(config: AppConfig): {\n mergedConfig: AppConfig\n changed: boolean\n} {\n const extraPrompts = config.extraPrompts ?? {}\n const defaultExtraPrompts = defaultConfig.extraPrompts ?? {}\n const responsesApiCompactThresholds =\n config.modelResponsesApiCompactThresholds ?? {}\n const defaultResponsesApiCompactThresholds =\n defaultConfig.modelResponsesApiCompactThresholds ?? {}\n const modelReasoningEfforts = config.modelReasoningEfforts ?? {}\n const defaultModelReasoningEfforts = defaultConfig.modelReasoningEfforts ?? {}\n const contextManagement = normalizeContextManagementConfig(\n config.contextManagement,\n )\n const responsesTransport = normalizeResponsesTransportConfig(\n config.responsesTransport,\n )\n const defaultContextManagementConfig = defaultConfig.contextManagement ?? {}\n\n const missingExtraPromptModels = Object.keys(defaultExtraPrompts).filter(\n (model) => !Object.hasOwn(extraPrompts, model),\n )\n\n const missingReasoningEffortModels = Object.keys(\n defaultModelReasoningEfforts,\n ).filter((model) => !Object.hasOwn(modelReasoningEfforts, model))\n const missingResponsesApiCompactThresholdModels = Object.keys(\n defaultResponsesApiCompactThresholds,\n ).filter((model) => !Object.hasOwn(responsesApiCompactThresholds, model))\n const missingContextManagementKeys = Object.keys(\n defaultContextManagementConfig,\n ).filter((key) => !Object.hasOwn(contextManagement, key))\n\n const hasExtraPromptChanges = missingExtraPromptModels.length > 0\n const hasReasoningEffortChanges = missingReasoningEffortModels.length > 0\n const hasResponsesApiCompactThresholdChanges =\n missingResponsesApiCompactThresholdModels.length > 0\n const hasContextManagementChanges = missingContextManagementKeys.length > 0\n const hasResponsesTransportChanges = Object.entries(responsesTransport).some(\n ([key, value]) =>\n config.responsesTransport?.[key as keyof ResponsesTransportConfig]\n !== value,\n )\n\n if (\n !hasExtraPromptChanges\n && !hasReasoningEffortChanges\n && !hasResponsesApiCompactThresholdChanges\n && !hasContextManagementChanges\n && !hasResponsesTransportChanges\n ) {\n return { mergedConfig: config, changed: false }\n }\n\n return {\n mergedConfig: {\n ...config,\n contextManagement: {\n ...defaultContextManagementConfig,\n ...contextManagement,\n },\n extraPrompts: {\n ...defaultExtraPrompts,\n ...extraPrompts,\n },\n modelResponsesApiCompactThresholds: {\n ...defaultResponsesApiCompactThresholds,\n ...responsesApiCompactThresholds,\n },\n modelReasoningEfforts: {\n ...defaultModelReasoningEfforts,\n ...modelReasoningEfforts,\n },\n responsesTransport,\n },\n changed: true,\n }\n}\n\nfunction normalizeContextManagementConfig(\n value: ContextManagementConfig | undefined,\n): ContextManagementConfig {\n if (!value || typeof value !== \"object\") {\n return {}\n }\n\n return {\n ...(typeof value.messages === \"boolean\" ?\n { messages: value.messages }\n : {}),\n ...(typeof value.responses === \"boolean\" ?\n { responses: value.responses }\n : {}),\n }\n}\n\nfunction ensureAdminApiKey(config: AppConfig): {\n mergedConfig: AppConfig\n changed: boolean\n} {\n const normalizedAdminApiKey = normalizeAdminApiKey(config.auth?.adminApiKey)\n if (normalizedAdminApiKey) {\n if (config.auth?.adminApiKey === normalizedAdminApiKey) {\n return { mergedConfig: config, changed: false }\n }\n\n return {\n mergedConfig: {\n ...config,\n auth: {\n ...config.auth,\n adminApiKey: normalizedAdminApiKey,\n },\n },\n changed: true,\n }\n }\n\n const editableConfig = readEditableConfigFromDisk()\n const { mergedConfig } = mergeDefaultConfig({\n ...editableConfig,\n auth: {\n ...editableConfig.auth,\n adminApiKey: generateAdminApiKey(),\n },\n })\n\n return { mergedConfig, changed: true }\n}\n\nexport function mergeConfigWithDefaults(): AppConfig {\n const config = readConfigFromDisk()\n const { mergedConfig, changed } = mergeDefaultConfig(config)\n const {\n mergedConfig: mergedConfigWithAdminApiKey,\n changed: adminApiKeyChanged,\n } = ensureAdminApiKey(mergedConfig)\n const shouldPersistConfig = changed || adminApiKeyChanged\n\n if (shouldPersistConfig) {\n try {\n writeConfigToDisk(mergedConfigWithAdminApiKey)\n } catch (writeError) {\n if (adminApiKeyChanged) {\n throw writeError\n }\n\n consola.warn(\n \"Failed to write merged default config to config file\",\n writeError,\n )\n }\n }\n\n cachedConfig = mergedConfigWithAdminApiKey\n return mergedConfigWithAdminApiKey\n}\n\nexport function getConfig(): AppConfig {\n cachedConfig ??= mergeDefaultConfig(readConfigFromDisk()).mergedConfig\n return cachedConfig\n}\n\nexport function reloadConfig(): AppConfig {\n return mergeConfigWithDefaults()\n}\n\nexport function isMessagesApiEnabled(): boolean {\n const config = getConfig()\n return config.useMessagesApi ?? true\n}\n\nexport function isResponsesApiWebSocketEnabled(): boolean {\n const config = getConfig()\n return config.useResponsesApiWebSocket ?? true\n}\n\nexport function getResponsesTransportConfig() {\n const { headersTimeoutMsV2, ...config } = normalizeResponsesTransportConfig(\n getConfig().responsesTransport,\n )\n return { headersTimeoutMs: headersTimeoutMsV2, ...config }\n}\n\nexport const normalizeResponsesTransportConfig = (\n configured: ResponsesTransportConfig | undefined,\n): Required<ResponsesTransportConfig> => ({\n headersTimeoutMsV2: positiveIntegerOrDefault(\n configured?.headersTimeoutMsV2,\n defaultResponsesTransportConfig.headersTimeoutMsV2,\n ),\n streamInactivityTimeoutMs: positiveIntegerOrDefault(\n configured?.streamInactivityTimeoutMs,\n defaultResponsesTransportConfig.streamInactivityTimeoutMs,\n ),\n websocketMaxBufferedBytes: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedBytes,\n defaultResponsesTransportConfig.websocketMaxBufferedBytes,\n ),\n websocketMaxBufferedMessages: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedMessages,\n defaultResponsesTransportConfig.websocketMaxBufferedMessages,\n ),\n websocketOpenTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketOpenTimeoutMs,\n defaultResponsesTransportConfig.websocketOpenTimeoutMs,\n ),\n websocketPoolIdleTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketPoolIdleTimeoutMs,\n defaultResponsesTransportConfig.websocketPoolIdleTimeoutMs,\n ),\n})\n\nconst positiveIntegerOrDefault = (value: unknown, fallback: number): number => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback\n\n const normalized = Math.floor(value)\n return normalized > 0 ? normalized : fallback\n}\n\nexport function getAnthropicApiKey(): string | undefined {\n const config = getConfig()\n return config.anthropicApiKey ?? process.env.ANTHROPIC_API_KEY ?? undefined\n}\n\nexport function isResponsesApiWebSearchEnabled(): boolean {\n const config = getConfig()\n return config.useResponsesApiWebSearch ?? true\n}\n\nexport function isAlphaSearchCodexPriorityEnabled(): boolean {\n const config = getConfig()\n return config.alphaSearchCodexPriority ?? true\n}\n\nexport function getAlphaSearchModel(): string | undefined {\n const model = getConfig().alphaSearchModel ?? \"gpt-5-mini\"\n return model.trim() || undefined\n}\n\nexport function getMessageApiWebSearchModel(): string | undefined {\n const config = getConfig()\n const model = config.messageApiWebSearchModel ?? \"gpt-5-mini\"\n return model && model.trim().length > 0 ? model : undefined\n}\n\nexport function getClaudeAutoModel(): string | undefined {\n const config = getConfig()\n const model = config.claudeAutoModel\n return model && model.trim().length > 0 ? model.trim() : undefined\n}\n\nexport function getClaudeTokenMultiplier(): number {\n const config = getConfig()\n return config.claudeTokenMultiplier ?? 1.15\n}\n","import {\n defaultConfig,\n defaultContextManagement,\n getConfig,\n readEditableConfigFromDisk,\n reloadConfig,\n writeConfigToDisk,\n} from \"./config-store\"\n\nconst GPT_MODEL_PATTERN = /^gpt-(\\d+)(?:\\.(\\d+))?/\n\nfunction isGpt53OrAbove(model: string): boolean {\n const match = GPT_MODEL_PATTERN.exec(model)\n if (!match) {\n return false\n }\n const majorVersion = Number.parseInt(match[1], 10)\n if (majorVersion > 5) {\n return true\n }\n if (majorVersion !== 5) {\n return false\n }\n const minorVersion = match[2] ? Number.parseInt(match[2], 10) : 0\n return minorVersion >= 3\n}\n\nexport function isGpt56OrAbove(model: string): boolean {\n const match = GPT_MODEL_PATTERN.exec(model)\n if (!match) {\n return false\n }\n const majorVersion = Number.parseInt(match[1], 10)\n if (majorVersion > 5) {\n return true\n }\n if (majorVersion !== 5) {\n return false\n }\n const minorVersion = match[2] ? Number.parseInt(match[2], 10) : 0\n return minorVersion >= 6\n}\n\nconst gpt5CommentaryPrompt = `# Working with the user\n\nYou interact with the user through a terminal. You have 2 ways of communicating with the users: \n- Share intermediary updates in \\`commentary\\` channel. \n- After you have completed all your work, send a message to the \\`final\\` channel. \n\n## Intermediary updates\n\n- Intermediary updates go to the \\`commentary\\` channel.\n- User updates are short updates while you are working, they are NOT final answers.\n- You use 1-2 sentence user updates to communicate progress and new information to the user as you are doing work.\n- Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements (“Done —”, “Got it”, “Great question, ”) or framing phrases.\n- You provide user updates frequently, every 20s.\n- Before exploring or doing substantial work, you start with a user update acknowledging the request and explaining your first step. You should include your understanding of the user request and explain what you will do. Avoid commenting on the request or using starters such as \"Got it -\" or \"Understood -\" etc.\n- When exploring, e.g. searching, reading files, you provide user updates as you go, every 20s, explaining what context you are gathering and what you've learned. Vary your sentence structure when providing these updates to avoid sounding repetitive - in particular, don't start each sentence the same way.\n- After you have sufficient context, and the work is substantial, you provide a longer plan (this is the only user update that may be longer than 2 sentences and can contain formatting).\n- Before performing file edits of any kind, you provide updates explaining what edits you are making.\n- As you are thinking, you very frequently provide updates even if not taking any actions, informing the user of your progress. You interrupt your thinking and send multiple updates in a row if thinking for more than 100 words.\n- Tone of your updates MUST match your personality.`\n\nexport function getExtraPromptForModel(model: string): string {\n const config = getConfig()\n const userPrompt = config.extraPrompts?.[model]\n if (userPrompt !== undefined) {\n return userPrompt\n }\n return isGpt53OrAbove(model) ? gpt5CommentaryPrompt : \"\"\n}\n\nexport function getModelMappings(): Record<string, string> {\n const config = getConfig()\n const modelMappings = config.modelMappings\n if (!modelMappings) {\n return { ...defaultConfig.modelMappings }\n }\n\n const validMappings: Record<string, string> = {}\n for (const [sourceModel, targetModel] of Object.entries(modelMappings)) {\n if (\n !sourceModel\n || typeof targetModel !== \"string\"\n || targetModel.length === 0\n ) {\n continue\n }\n validMappings[sourceModel] = targetModel\n }\n\n return validMappings\n}\n\nfunction validateModelMappings(\n modelMappings: Record<string, string>,\n): Record<string, string> {\n const validatedMappings: Record<string, string> = {}\n for (const [sourceModel, targetModel] of Object.entries(modelMappings)) {\n if (!sourceModel || !targetModel) {\n throw new Error(\n \"Each model mapping must use non-empty source and target values.\",\n )\n }\n validatedMappings[sourceModel] = targetModel\n }\n\n return validatedMappings\n}\n\nexport function setModelMappings(\n modelMappings: Record<string, string>,\n): Record<string, string> {\n const nextConfig = {\n ...readEditableConfigFromDisk(),\n modelMappings: validateModelMappings(modelMappings),\n }\n\n writeConfigToDisk(nextConfig)\n reloadConfig()\n return getModelMappings()\n}\n\nexport function resolveMappedModel(model: string): string {\n return getModelMappings()[model] ?? model\n}\n\nexport function getSmallModel(): string {\n const config = getConfig()\n return config.smallModel ?? \"gpt-5-mini\"\n}\n\nexport function isContextManagementEnabledForMessages(): boolean {\n const config = getConfig()\n return config.contextManagement?.messages ?? defaultContextManagement.messages\n}\n\nexport function isContextManagementEnabledForResponses(): boolean {\n const config = getConfig()\n return (\n config.contextManagement?.responses ?? defaultContextManagement.responses\n )\n}\n\nexport function getModelResponsesApiCompactThreshold(\n model: string,\n): number | undefined {\n const config = getConfig()\n const threshold = config.modelResponsesApiCompactThresholds?.[model]\n\n if (\n typeof threshold !== \"number\"\n || !Number.isFinite(threshold)\n || threshold <= 0\n ) {\n return undefined\n }\n\n return threshold\n}\n\nexport function getReasoningEffortForModel(\n model: string,\n): \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" {\n const config = getConfig()\n const userEffort = config.modelReasoningEfforts?.[model]\n if (userEffort !== undefined) {\n return userEffort\n }\n return isGpt53OrAbove(model) ? \"xhigh\" : \"high\"\n}\n","import consola from \"consola\"\n\nimport {\n SUPPORTED_PROVIDER_TYPES,\n getConfig,\n readEditableConfigFromDisk,\n reloadConfig,\n writeConfigToDisk,\n type ModelConfig,\n type ProviderAuthType,\n type ProviderConfig,\n type ProviderType,\n} from \"./config-store\"\n\nexport interface ResolvedProviderConfig {\n name: string\n type: ProviderType\n baseUrl: string\n apiKey: string\n authType: ProviderAuthType\n pricingCurrency?: string\n models?: Record<string, ModelConfig>\n}\n\nconst OPENCODE_ANTHROPIC_MODEL_PATTERN = /^(?:qwen|minimax)/iu\nconst OPENCODE_RESPONSES_MODEL_PATTERN = /^(?:gpt|grok)(?:[-_.]|$)/iu\n\nexport function normalizeProviderBaseUrl(url: string): string {\n return url.trim().replace(/\\/+$/u, \"\")\n}\n\nexport function isSupportedProviderType(value: string): value is ProviderType {\n return SUPPORTED_PROVIDER_TYPES.includes(value as ProviderType)\n}\n\nfunction getDefaultProviderAuthType(\n providerType: ProviderType,\n): ProviderAuthType {\n return providerType === \"anthropic\" ? \"x-api-key\" : \"authorization\"\n}\n\nexport function resolveProviderAuthType(\n providerName: string,\n authType: string | undefined,\n providerType: ProviderType,\n): ProviderAuthType {\n const defaultAuthType = getDefaultProviderAuthType(providerType)\n if (authType === undefined) {\n return defaultAuthType\n }\n\n if (authType === \"x-api-key\") {\n return \"x-api-key\"\n }\n\n if (authType === \"oauth2\") {\n if (providerName === \"codex\") {\n return authType\n }\n\n consola.warn(\n `Provider ${providerName} has authType 'oauth2', which is only supported by the builtin codex provider, falling back to ${defaultAuthType}`,\n )\n return defaultAuthType\n }\n\n if (authType === \"authorization\") {\n return authType\n }\n\n consola.warn(\n `Provider ${providerName} has invalid authType '${authType}', falling back to ${defaultAuthType}`,\n )\n return defaultAuthType\n}\n\nfunction isProviderApiKeyRequired(\n providerName: string,\n authType: ProviderAuthType,\n): boolean {\n return !(providerName === \"codex\" && authType === \"oauth2\")\n}\n\nexport function getRawProviderConfig(name: string): ProviderConfig | null {\n const providerName = name.trim()\n if (!providerName) {\n return null\n }\n\n const config = getConfig()\n return config.providers?.[providerName] ?? null\n}\n\nexport function setProviderConfig(\n name: string,\n provider: ProviderConfig,\n): ProviderConfig {\n const providerName = name.trim()\n if (!providerName) {\n throw new Error(\"Provider name must be a non-empty string\")\n }\n\n if (isReservedProviderName(providerName)) {\n throw new Error(\n `Provider ${providerName} is reserved and cannot be configured in config.providers`,\n )\n }\n\n const editableConfig = readEditableConfigFromDisk()\n const nextConfig = {\n ...editableConfig,\n providers: {\n ...editableConfig.providers,\n [providerName]: provider,\n },\n }\n\n writeConfigToDisk(nextConfig)\n reloadConfig()\n return getRawProviderConfig(providerName) ?? provider\n}\n\nexport function getProviderConfig(name: string): ResolvedProviderConfig | null {\n const providerName = name.trim()\n if (!providerName) {\n return null\n }\n\n if (isReservedProviderName(providerName)) {\n consola.warn(\n `Provider ${providerName} is reserved and cannot be configured in config.providers`,\n )\n return null\n }\n\n const provider = getRawProviderConfig(providerName)\n if (!provider) {\n return null\n }\n\n if (provider.enabled === false) {\n return null\n }\n\n const type = provider.type ?? \"anthropic\"\n if (!isSupportedProviderType(type)) {\n consola.warn(\n `Provider ${providerName} is ignored because type '${type}' is not supported`,\n )\n return null\n }\n\n const baseUrl = normalizeProviderBaseUrl(provider.baseUrl ?? \"\")\n const authType = resolveProviderAuthType(\n providerName,\n provider.authType,\n type,\n )\n const apiKey = (provider.apiKey ?? \"\").trim()\n const missingFields = [\n ...(baseUrl ? [] : [\"baseUrl\"]),\n ...(isProviderApiKeyRequired(providerName, authType) && !apiKey ?\n [\"apiKey\"]\n : []),\n ]\n\n if (missingFields.length > 0) {\n consola.warn(\n `Provider ${providerName} is enabled but missing ${missingFields.join(\" or \")}`,\n )\n return null\n }\n\n return {\n name: providerName,\n type,\n baseUrl,\n apiKey,\n authType,\n pricingCurrency: normalizePricingCurrency(provider.pricingCurrency),\n models: provider.models,\n }\n}\n\nexport function resolveEffectiveProviderType(\n providerConfig: ResolvedProviderConfig,\n model: string,\n): ProviderType {\n const modelConfig = providerConfig.models?.[model]\n if (modelConfig?.type && isSupportedProviderType(modelConfig.type)) {\n return modelConfig.type\n }\n\n if (providerConfig.name === \"opencode-go\") {\n if (OPENCODE_ANTHROPIC_MODEL_PATTERN.test(model)) {\n return \"anthropic\"\n }\n if (OPENCODE_RESPONSES_MODEL_PATTERN.test(model)) {\n return \"openai-responses\"\n }\n }\n\n return providerConfig.type\n}\n\nfunction normalizePricingCurrency(\n value: string | undefined,\n): string | undefined {\n const currency = value?.trim().toUpperCase()\n return currency || undefined\n}\n\nexport function listEnabledProviders(): Array<string> {\n const config = getConfig()\n const providerNames = Object.keys(config.providers ?? {})\n return providerNames.filter((name) => getProviderConfig(name) !== null)\n}\n\nexport function isReservedProviderName(name: string): boolean {\n return name.trim() === \"copilot\"\n}\n"],"mapp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as listEnabledProviders, n as getRawProviderConfig } from "./config-BTzeWHkr.js";
1
+ import { N as PATHS, i as listEnabledProviders, n as getRawProviderConfig } from "./config-BK3_YOxx.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-BwkElUPu.js.map
92
+ //# sourceMappingURL=debug-41w6Whae.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"debug-BwkElUPu.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,eA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AkB;;uBAE7B,KAAK,cAAc,QAAQ,OAAO;;AAGzD,SAAS,mBAAmB,MAAuB;CACjD,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,EAAE,CAAC;;AAG5C,eAAsB,SAAS,SAAyC;CACtE,MAAM,YAAY,MAAM,cAAc;CAEtC,IAAI,QAAQ,MACV,mBAAmB,UAAU;MAE7B,oBAAoB,UAAU;;AAIlC,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;EACd;CACD,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;EACd,EACF;CACD,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,MACZ,CAAC;;CAEL,CAAC"}
1
+ {"version":3,"file":"debug-41w6Whae.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,OAAO,KAAK,IAAI,CAC5C;EAMD,OAHoB,KAAK,MAAM,MAAM,GAAG,SAAS,gBAAgB,CAG/C,CAAC;SACb;EACN,OAAO;;;AAIX,SAAS,iBAAiB;CACxB,MAAM,QAAQ,OAAO,QAAQ;CAE7B,OAAO;EACL,MAAM,QAAQ,QAAQ;EACtB,SAAS,QAAQ,IAAI,UAAU,QAAQ,QAAQ,MAAM,EAAE;EACvD,UAAU,GAAG,UAAU;EACvB,MAAM,GAAG,MAAM;EAChB;;AAGH,eAAe,gBAAgB,UAAoC;CACjE,IAAI;EAEF,IAAI,EAAC,MADe,GAAG,KAAK,SAAS,EAC1B,QAAQ,EAAE,OAAO;EAG5B,QAAO,MADe,GAAG,SAAS,UAAU,OAAO,EACpC,MAAM,CAAC,SAAS;SACzB;EACN,OAAO;;;AAIX,eAAe,eAAmC;CAChD,MAAM,CAAC,SAAS,eAAe,MAAM,QAAQ,IAAI,CAC/C,mBAAmB,EACnB,gBAAgB,MAAM,kBAAkB,CACzC,CAAC;CAEF,OAAO;EACL,WAAW;GACT,iBAAiB,qBAAqB,QAAQ,KAAK;GACnD,SAAS,sBAAsB;GAChC;EACD;EACA,SAAS,gBAAgB;EACzB,OAAO;GACL,SAAS,MAAM;GACf,aAAa,MAAM;GACnB,mBAAmB,MAAM;GAC1B;EACD;EACD;;AAGH,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,KAAK,IAAI,OAAO;sBACnC,KAAK,UAAU,kBAAkB,QAAQ,KAAK;;;aAGvD,KAAK,MAAM,QAAQ;iBACf,KAAK,MAAM,YAAY;uBACjB,KAAK,MAAM,kBAAkB;;uBAE7B,KAAK,cAAc,QAAQ,OAAO;;AAGzD,SAAS,mBAAmB,MAAuB;CACjD,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,EAAE,CAAC;;AAG5C,eAAsB,SAAS,SAAyC;CACtE,MAAM,YAAY,MAAM,cAAc;CAEtC,IAAI,QAAQ,MACV,mBAAmB,UAAU;MAE7B,oBAAoB,UAAU;;AAIlC,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;EACd;CACD,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;EACd,EACF;CACD,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,MACZ,CAAC;;CAEL,CAAC"}
package/dist/main.js CHANGED
@@ -27,10 +27,10 @@ if (isMcpFastPath(process.argv)) {
27
27
  if (process.platform === "win32" && process.stdout.isTTY && !process.env.WT_SESSION) process.env.WT_SESSION = "copilot-api";
28
28
  const { bindElectronFetch } = await import("./electron-fetch-BRX-ug5E.js");
29
29
  bindElectronFetch();
30
- const { auth } = await import("./auth-YxKQGwfw.js");
31
- const { debug } = await import("./debug-BwkElUPu.js");
30
+ const { auth } = await import("./auth-C-RWNXGU.js");
31
+ const { debug } = await import("./debug-41w6Whae.js");
32
32
  const { mcp } = await import("./mcp-fpSlKZxK.js");
33
- const { start } = await import("./start-CIEyg9gn.js");
33
+ const { start } = await import("./start-HcJzBszU.js");
34
34
  await runMain(defineCommand({
35
35
  meta: {
36
36
  name: "copilot-api",
@@ -1,4 +1,4 @@
1
- import { H as state } from "./token-CVbmPxHp.js";
1
+ import { K as state } from "./token-u7yV0_hw.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-FKEDPPpH.js.map
90
+ //# sourceMappingURL=models-LIZvOolN.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"models-FKEDPPpH.js","names":[],"sources":["../src/lib/models.ts"],"sourcesContent":["import type { Model } from \"~/lib/types/models\"\n\nimport { state } from \"~/lib/state\"\n\n/**\n * Converts a Copilot upstream model ID to a client-friendly ID that Claude Code\n * and Claude Desktop recognize (dots in version replaced with hyphens).\n * e.g. \"claude-sonnet-4.6\" -> \"claude-sonnet-4-6\"\n * Non-Claude models are returned unchanged.\n */\nexport const toClientModelId = (modelId: string): string => {\n const normalized = normalizeSdkModelId(modelId)\n if (!normalized) return modelId\n const versionHyphenated = normalized.version.replaceAll(\".\", \"-\")\n return `claude-${normalized.family}-${versionHyphenated}`\n}\n\nexport interface NormalizedSdkModelId {\n family: string\n version: string\n}\n\nexport const findEndpointModel = (sdkModelId: string): Model | undefined => {\n const models = state.models?.data ?? []\n const exactMatch = models.find((m) => m.id === sdkModelId)\n if (exactMatch) {\n return exactMatch\n }\n\n const normalized = normalizeSdkModelId(sdkModelId)\n if (!normalized) {\n return undefined\n }\n\n const modelName = `claude-${normalized.family}-${normalized.version}`\n const model = models.find((m) => m.id === modelName)\n if (model) {\n return model\n }\n\n return undefined\n}\n\n/**\n * Finds the latest available model for a given Claude family (e.g. \"opus\",\n * \"sonnet\", \"haiku\") among the models currently cached in `state.models`.\n * \"Latest\" is determined by the highest semantic version parsed from the model\n * ID. Returns `undefined` when no model of that family is available.\n */\nexport const getLatestModelForFamily = (family: string): Model | undefined => {\n const models = state.models?.data ?? []\n\n let best: { model: Model; major: number; minor: number } | undefined\n\n for (const model of models) {\n const normalized = normalizeSdkModelId(model.id)\n if (!normalized || normalized.family !== family) {\n continue\n }\n\n const [majorPart, minorPart = \"0\"] = normalized.version.split(\".\")\n const major = Number.parseInt(majorPart, 10)\n const minor = Number.parseInt(minorPart, 10)\n if (Number.isNaN(major) || Number.isNaN(minor)) {\n continue\n }\n\n if (\n !best\n || major > best.major\n || (major === best.major && minor > best.minor)\n ) {\n best = { model, major, minor }\n }\n }\n\n return best?.model\n}\n\n/**\n * Normalizes an SDK model ID to extract the model family and version.\n * this method from github copilot extension\n * Examples:\n * - \"claude-opus-4-5-20251101\" -> { family: \"opus\", version: \"4.5\" }\n * - \"claude-3-5-sonnet-20241022\" -> { family: \"sonnet\", version: \"3.5\" }\n * - \"claude-sonnet-4-20250514\" -> { family: \"sonnet\", version: \"4\" }\n * - \"claude-haiku-3-5-20250514\" -> { family: \"haiku\", version: \"3.5\" }\n * - \"claude-haiku-4.5\" -> { family: \"haiku\", version: \"4.5\" }\n */\nexport const normalizeSdkModelId = (\n sdkModelId: string,\n): NormalizedSdkModelId | undefined => {\n const lower = sdkModelId.toLowerCase()\n\n // Strip date suffix (8 digits at the end)\n const withoutDate = lower.replace(/-\\d{8}$/, \"\")\n\n // Pattern 1: claude-{family}-{major}.{minor} (e.g., claude-haiku-4.5)\n const pattern1 = withoutDate.match(/^claude-(\\w+)-(\\d+)\\.(\\d+)$/)\n if (pattern1) {\n return { family: pattern1[1], version: `${pattern1[2]}.${pattern1[3]}` }\n }\n\n // Pattern 2: claude-{family}-{major}-{minor} (e.g., claude-opus-4-5, claude-haiku-3-5)\n const pattern2 = withoutDate.match(/^claude-(\\w+)-(\\d+)-(\\d+)$/)\n if (pattern2) {\n return { family: pattern2[1], version: `${pattern2[2]}.${pattern2[3]}` }\n }\n\n // Pattern 3: claude-{major}-{minor}-{family} (e.g., claude-3-5-sonnet)\n const pattern3 = withoutDate.match(/^claude-(\\d+)-(\\d+)-(\\w+)$/)\n if (pattern3) {\n return { family: pattern3[3], version: `${pattern3[1]}.${pattern3[2]}` }\n }\n\n // Pattern 4: claude-{family}-{major} (e.g., claude-sonnet-4)\n const pattern4 = withoutDate.match(/^claude-(\\w+)-(\\d+)$/)\n if (pattern4) {\n return { family: pattern4[1], version: pattern4[2] }\n }\n\n // Pattern 5: claude-{major}-{family} (e.g., claude-3-opus)\n const pattern5 = withoutDate.match(/^claude-(\\d+)-(\\w+)$/)\n if (pattern5) {\n return { family: pattern5[2], version: pattern5[1] }\n }\n\n return undefined\n}\n"],"mappings":";;;;;;;;AAUA,MAAa,mBAAmB,YAA4B;CAC1D,MAAM,aAAa,oBAAoB,QAAQ;CAC/C,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,oBAAoB,WAAW,QAAQ,WAAW,KAAK,IAAI;CACjE,OAAO,UAAU,WAAW,OAAO,GAAG;;AAQxC,MAAa,qBAAqB,eAA0C;CAC1E,MAAM,SAAS,MAAM,QAAQ,QAAQ,EAAE;CACvC,MAAM,aAAa,OAAO,MAAM,MAAM,EAAE,OAAO,WAAW;CAC1D,IAAI,YACF,OAAO;CAGT,MAAM,aAAa,oBAAoB,WAAW;CAClD,IAAI,CAAC,YACH;CAGF,MAAM,YAAY,UAAU,WAAW,OAAO,GAAG,WAAW;CAC5D,MAAM,QAAQ,OAAO,MAAM,MAAM,EAAE,OAAO,UAAU;CACpD,IAAI,OACF,OAAO;;;;;;;;AAYX,MAAa,2BAA2B,WAAsC;CAC5E,MAAM,SAAS,MAAM,QAAQ,QAAQ,EAAE;CAEvC,IAAI;CAEJ,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,aAAa,oBAAoB,MAAM,GAAG;EAChD,IAAI,CAAC,cAAc,WAAW,WAAW,QACvC;EAGF,MAAM,CAAC,WAAW,YAAY,OAAO,WAAW,QAAQ,MAAM,IAAI;EAClE,MAAM,QAAQ,OAAO,SAAS,WAAW,GAAG;EAC5C,MAAM,QAAQ,OAAO,SAAS,WAAW,GAAG;EAC5C,IAAI,OAAO,MAAM,MAAM,IAAI,OAAO,MAAM,MAAM,EAC5C;EAGF,IACE,CAAC,QACE,QAAQ,KAAK,SACZ,UAAU,KAAK,SAAS,QAAQ,KAAK,OAEzC,OAAO;GAAE;GAAO;GAAO;GAAO;;CAIlC,OAAO,MAAM;;;;;;;;;;;;AAaf,MAAa,uBACX,eACqC;CAIrC,MAAM,cAHQ,WAAW,aAGA,CAAC,QAAQ,WAAW,GAAG;CAGhD,MAAM,WAAW,YAAY,MAAM,8BAA8B;CACjE,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,GAAG,SAAS,GAAG,GAAG,SAAS;EAAM;CAI1E,MAAM,WAAW,YAAY,MAAM,6BAA6B;CAChE,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,GAAG,SAAS,GAAG,GAAG,SAAS;EAAM;CAI1E,MAAM,WAAW,YAAY,MAAM,6BAA6B;CAChE,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,GAAG,SAAS,GAAG,GAAG,SAAS;EAAM;CAI1E,MAAM,WAAW,YAAY,MAAM,uBAAuB;CAC1D,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,SAAS;EAAI;CAItD,MAAM,WAAW,YAAY,MAAM,uBAAuB;CAC1D,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,SAAS;EAAI"}
1
+ {"version":3,"file":"models-LIZvOolN.js","names":[],"sources":["../src/lib/models.ts"],"sourcesContent":["import type { Model } from \"~/lib/types/models\"\n\nimport { state } from \"~/lib/state\"\n\n/**\n * Converts a Copilot upstream model ID to a client-friendly ID that Claude Code\n * and Claude Desktop recognize (dots in version replaced with hyphens).\n * e.g. \"claude-sonnet-4.6\" -> \"claude-sonnet-4-6\"\n * Non-Claude models are returned unchanged.\n */\nexport const toClientModelId = (modelId: string): string => {\n const normalized = normalizeSdkModelId(modelId)\n if (!normalized) return modelId\n const versionHyphenated = normalized.version.replaceAll(\".\", \"-\")\n return `claude-${normalized.family}-${versionHyphenated}`\n}\n\nexport interface NormalizedSdkModelId {\n family: string\n version: string\n}\n\nexport const findEndpointModel = (sdkModelId: string): Model | undefined => {\n const models = state.models?.data ?? []\n const exactMatch = models.find((m) => m.id === sdkModelId)\n if (exactMatch) {\n return exactMatch\n }\n\n const normalized = normalizeSdkModelId(sdkModelId)\n if (!normalized) {\n return undefined\n }\n\n const modelName = `claude-${normalized.family}-${normalized.version}`\n const model = models.find((m) => m.id === modelName)\n if (model) {\n return model\n }\n\n return undefined\n}\n\n/**\n * Finds the latest available model for a given Claude family (e.g. \"opus\",\n * \"sonnet\", \"haiku\") among the models currently cached in `state.models`.\n * \"Latest\" is determined by the highest semantic version parsed from the model\n * ID. Returns `undefined` when no model of that family is available.\n */\nexport const getLatestModelForFamily = (family: string): Model | undefined => {\n const models = state.models?.data ?? []\n\n let best: { model: Model; major: number; minor: number } | undefined\n\n for (const model of models) {\n const normalized = normalizeSdkModelId(model.id)\n if (!normalized || normalized.family !== family) {\n continue\n }\n\n const [majorPart, minorPart = \"0\"] = normalized.version.split(\".\")\n const major = Number.parseInt(majorPart, 10)\n const minor = Number.parseInt(minorPart, 10)\n if (Number.isNaN(major) || Number.isNaN(minor)) {\n continue\n }\n\n if (\n !best\n || major > best.major\n || (major === best.major && minor > best.minor)\n ) {\n best = { model, major, minor }\n }\n }\n\n return best?.model\n}\n\n/**\n * Normalizes an SDK model ID to extract the model family and version.\n * this method from github copilot extension\n * Examples:\n * - \"claude-opus-4-5-20251101\" -> { family: \"opus\", version: \"4.5\" }\n * - \"claude-3-5-sonnet-20241022\" -> { family: \"sonnet\", version: \"3.5\" }\n * - \"claude-sonnet-4-20250514\" -> { family: \"sonnet\", version: \"4\" }\n * - \"claude-haiku-3-5-20250514\" -> { family: \"haiku\", version: \"3.5\" }\n * - \"claude-haiku-4.5\" -> { family: \"haiku\", version: \"4.5\" }\n */\nexport const normalizeSdkModelId = (\n sdkModelId: string,\n): NormalizedSdkModelId | undefined => {\n const lower = sdkModelId.toLowerCase()\n\n // Strip date suffix (8 digits at the end)\n const withoutDate = lower.replace(/-\\d{8}$/, \"\")\n\n // Pattern 1: claude-{family}-{major}.{minor} (e.g., claude-haiku-4.5)\n const pattern1 = withoutDate.match(/^claude-(\\w+)-(\\d+)\\.(\\d+)$/)\n if (pattern1) {\n return { family: pattern1[1], version: `${pattern1[2]}.${pattern1[3]}` }\n }\n\n // Pattern 2: claude-{family}-{major}-{minor} (e.g., claude-opus-4-5, claude-haiku-3-5)\n const pattern2 = withoutDate.match(/^claude-(\\w+)-(\\d+)-(\\d+)$/)\n if (pattern2) {\n return { family: pattern2[1], version: `${pattern2[2]}.${pattern2[3]}` }\n }\n\n // Pattern 3: claude-{major}-{minor}-{family} (e.g., claude-3-5-sonnet)\n const pattern3 = withoutDate.match(/^claude-(\\d+)-(\\d+)-(\\w+)$/)\n if (pattern3) {\n return { family: pattern3[3], version: `${pattern3[1]}.${pattern3[2]}` }\n }\n\n // Pattern 4: claude-{family}-{major} (e.g., claude-sonnet-4)\n const pattern4 = withoutDate.match(/^claude-(\\w+)-(\\d+)$/)\n if (pattern4) {\n return { family: pattern4[1], version: pattern4[2] }\n }\n\n // Pattern 5: claude-{major}-{family} (e.g., claude-3-opus)\n const pattern5 = withoutDate.match(/^claude-(\\d+)-(\\w+)$/)\n if (pattern5) {\n return { family: pattern5[2], version: pattern5[1] }\n }\n\n return undefined\n}\n"],"mappings":";;;;;;;;AAUA,MAAa,mBAAmB,YAA4B;CAC1D,MAAM,aAAa,oBAAoB,QAAQ;CAC/C,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,oBAAoB,WAAW,QAAQ,WAAW,KAAK,IAAI;CACjE,OAAO,UAAU,WAAW,OAAO,GAAG;;AAQxC,MAAa,qBAAqB,eAA0C;CAC1E,MAAM,SAAS,MAAM,QAAQ,QAAQ,EAAE;CACvC,MAAM,aAAa,OAAO,MAAM,MAAM,EAAE,OAAO,WAAW;CAC1D,IAAI,YACF,OAAO;CAGT,MAAM,aAAa,oBAAoB,WAAW;CAClD,IAAI,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OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,SAAS;EAAI;CAItD,MAAM,WAAW,YAAY,MAAM,uBAAuB;CAC1D,IAAI,UACF,OAAO;EAAE,QAAQ,SAAS;EAAI,SAAS,SAAS;EAAI"}
@@ -1,7 +1,7 @@
1
- import { A as isResponsesApiWebSocketEnabled, C as getClaudeTokenMultiplier, D as isAlphaSearchCodexPriorityEnabled, E as getResponsesTransportConfig, M as PATHS, O as isMessagesApiEnabled, S as getClaudeAutoModel, T as getMessageApiWebSearchModel, _ as resolveMappedModel, b as getAlphaSearchModel, d as getModelResponsesApiCompactThreshold$1, f as getReasoningEffortForModel, g as isGpt56OrAbove, h as isContextManagementEnabledForResponses, i as listEnabledProviders, k as isResponsesApiWebSearchEnabled, l as getExtraPromptForModel, m as isContextManagementEnabledForMessages, n as getRawProviderConfig, o as resolveEffectiveProviderType, p as getSmallModel, s as resolveProviderAuthType, t as getProviderConfig, u as getModelMappings, v as setModelMappings, w as getConfig, x as getAnthropicApiKey } from "./config-BTzeWHkr.js";
2
- import { A as buildCodexRequestHeaders, B as createPooledWebSocketStream, C as compactAutoContinuePromptStarts, D as compactTextOnlyGuard, E as compactSystemPromptStarts, F as createResponsesHttpEventStream, H as state, I as fetchResponsesWithLifecycle, L as createResponsesSafeStream, M as generateTraceId, N as requestContext, P as resolveTraceId$1, R as encodePoolKeyPart, U as HTTPError, V as createWebSocketUrl, W as forwardError, b as prepareInteractionHeaders, c as getUUID, d as isResponsesStream, f as parseUserIdMetadata, g as copilotHeaders, h as copilotBaseUrl, j as forwardCodexResponses, k as CODEX_API_BASE_URL, l as isAsyncIterable, o as generateRequestIdFromPayload, p as getCopilotUsage, r as setupCodexToken, s as getRootSessionId, u as isNullish, v as copilotWebSocketHeaders, w as compactMessageSections, x as prepareMessageProxyHeaders, y as prepareForCompact, z as isTerminalResponsesStreamChunk } from "./token-CVbmPxHp.js";
1
+ import { A as isResponsesApiWebSocketEnabled, C as getClaudeTokenMultiplier, D as isAlphaSearchCodexPriorityEnabled, E as getResponsesTransportConfig, N as PATHS, O as isMessagesApiEnabled, S as getClaudeAutoModel, T as getMessageApiWebSearchModel, _ as resolveMappedModel, b as getAlphaSearchModel, d as getModelResponsesApiCompactThreshold$1, f as getReasoningEffortForModel, g as isGpt56OrAbove, h as isContextManagementEnabledForResponses, i as listEnabledProviders, k as isResponsesApiWebSearchEnabled, l as getExtraPromptForModel, m as isContextManagementEnabledForMessages, n as getRawProviderConfig, o as resolveEffectiveProviderType, p as getSmallModel, s as resolveProviderAuthType, t as getProviderConfig, u as getModelMappings, v as setModelMappings, x as getAnthropicApiKey } from "./config-BK3_YOxx.js";
2
+ import { B as fetchResponsesWithLifecycle, C as compactAutoContinuePromptStarts, D as compactTextOnlyGuard, E as compactSystemPromptStarts, F as forwardCodexResponses, G as createWebSocketUrl, H as encodePoolKeyPart, I as generateTraceId, J as forwardError, K as state, L as requestContext, N as CODEX_API_BASE_URL, O as createAuthMiddleware, P as buildCodexRequestHeaders, R as resolveTraceId$1, U as isTerminalResponsesStreamChunk, V as createResponsesSafeStream, W as createPooledWebSocketStream, b as prepareInteractionHeaders, c as getUUID, d as isResponsesStream, f as parseUserIdMetadata, g as copilotHeaders, h as copilotBaseUrl, k as getConfiguredAdminApiKeys, l as isAsyncIterable, o as generateRequestIdFromPayload, p as getCopilotUsage, q as HTTPError, r as setupCodexToken, s as getRootSessionId, u as isNullish, v as copilotWebSocketHeaders, w as compactMessageSections, x as prepareMessageProxyHeaders, y as prepareForCompact, z as createResponsesHttpEventStream } from "./token-u7yV0_hw.js";
3
3
  import { a as isDeferredToolName, c as parseMcpToolSearchSentinel, d as shouldEnableResponsesToolSearch, i as isBridgeToolSearchName, l as resolveBridgeToolSearchName, o as listDeferredToolNames, r as formatToolSearchBridgeArguments, s as normalizeToolSearchBridgeArguments, t as BRIDGE_TOOL_SEARCH_NAME, u as selectDeferredToolsByNames } from "./tool-search-Ds1vbmGG.js";
4
- import { i as toClientModelId, r as normalizeSdkModelId, t as findEndpointModel } from "./models-FKEDPPpH.js";
4
+ import { i as toClientModelId, r as normalizeSdkModelId, t as findEndpointModel } from "./models-LIZvOolN.js";
5
5
  import consola from "consola";
6
6
  import { createHash } from "node:crypto";
7
7
  import fs, { readFileSync } from "node:fs";
@@ -16,61 +16,6 @@ import { logger } from "hono/logger";
16
16
  import { decompress } from "fzstd";
17
17
  import util from "node:util";
18
18
  import { streamSSE } from "hono/streaming";
19
- //#region src/lib/request-auth.ts
20
- function normalizeApiKeys(apiKeys) {
21
- if (!Array.isArray(apiKeys)) {
22
- if (apiKeys !== void 0) consola.warn("Invalid auth.apiKeys config. Expected an array of strings.");
23
- return [];
24
- }
25
- const normalizedKeys = apiKeys.filter((key) => typeof key === "string").map((key) => key.trim()).filter((key) => key.length > 0);
26
- if (normalizedKeys.length !== apiKeys.length) consola.warn("Invalid auth.apiKeys entries found. Only non-empty strings are allowed.");
27
- return [...new Set(normalizedKeys)];
28
- }
29
- function getConfiguredApiKeys() {
30
- return normalizeApiKeys(getConfig().auth?.apiKeys);
31
- }
32
- function normalizeApiKey(apiKey) {
33
- if (typeof apiKey !== "string") return null;
34
- return apiKey.trim() || null;
35
- }
36
- function getConfiguredAdminApiKeys() {
37
- const adminApiKey = normalizeApiKey(getConfig().auth?.adminApiKey);
38
- return adminApiKey ? [adminApiKey] : [];
39
- }
40
- function extractRequestApiKey(c) {
41
- const xApiKey = c.req.header("x-api-key")?.trim();
42
- if (xApiKey) return xApiKey;
43
- const authorization = c.req.header("authorization");
44
- if (!authorization) return null;
45
- const [scheme, ...rest] = authorization.trim().split(/\s+/);
46
- if (scheme.toLowerCase() !== "bearer") return null;
47
- return rest.join(" ").trim() || null;
48
- }
49
- function createUnauthorizedResponse(c) {
50
- c.header("WWW-Authenticate", "Bearer realm=\"copilot-api\"");
51
- return c.json({ error: {
52
- message: "Unauthorized",
53
- type: "authentication_error"
54
- } }, 401);
55
- }
56
- function createAuthMiddleware(options = {}) {
57
- const getApiKeys = options.getApiKeys ?? getConfiguredApiKeys;
58
- const allowUnauthenticatedPaths = options.allowUnauthenticatedPaths ?? ["/"];
59
- const allowOptionsBypass = options.allowOptionsBypass ?? true;
60
- const allowWhenNoApiKeys = options.allowWhenNoApiKeys ?? true;
61
- const shouldSkipPath = options.shouldSkipPath ?? (() => false);
62
- return async (c, next) => {
63
- if (allowOptionsBypass && c.req.method === "OPTIONS") return next();
64
- if (shouldSkipPath(c.req.path)) return next();
65
- if (allowUnauthenticatedPaths.includes(c.req.path)) return next();
66
- const apiKeys = getApiKeys();
67
- if (apiKeys.length === 0) return allowWhenNoApiKeys ? next() : createUnauthorizedResponse(c);
68
- const requestApiKey = extractRequestApiKey(c);
69
- if (!requestApiKey || !apiKeys.includes(requestApiKey)) return createUnauthorizedResponse(c);
70
- return next();
71
- };
72
- }
73
- //#endregion
74
19
  //#region src/lib/trace.ts
75
20
  const traceIdMiddleware = async (c, next) => {
76
21
  const traceId = resolveTraceId$1(c.req.header("x-trace-id"));
@@ -6031,6 +5976,7 @@ const collectInputItemImageDataUrls = (item, images) => {
6031
5976
  const collectContentImageDataUrls = (content, images) => {
6032
5977
  if (!Array.isArray(content)) return;
6033
5978
  for (const block of content) {
5979
+ if (isResponseInputImage(block)) block.detail = normalizeInputImageDetail(block.detail);
6034
5980
  const image = getInputImageDataUrl(block);
6035
5981
  if (image) images.push(image);
6036
5982
  }
@@ -6053,11 +5999,19 @@ const replaceInputImageWithPlaceholder = (image) => {
6053
5999
  image.record.detail = "low";
6054
6000
  delete image.record.file_id;
6055
6001
  };
6002
+ const VALID_INPUT_IMAGE_DETAILS = new Set([
6003
+ "auto",
6004
+ "high",
6005
+ "low"
6006
+ ]);
6007
+ const normalizeInputImageDetail = (detail) => {
6008
+ return VALID_INPUT_IMAGE_DETAILS.has(detail) ? detail : "auto";
6009
+ };
6056
6010
  const isResponseInputMessage = (item) => {
6057
6011
  return typeof item === "object" && item !== null && "role" in item && typeof item.role === "string";
6058
6012
  };
6059
6013
  const isResponseFunctionCallOutputItem = (item) => {
6060
- return typeof item === "object" && item !== null && "type" in item && item.type === "function_call_output";
6014
+ return typeof item === "object" && item !== null && "type" in item && (item.type === "custom_tool_call_output" || item.type === "function_call_output");
6061
6015
  };
6062
6016
  const isResponseInputImage = (content) => {
6063
6017
  return typeof content === "object" && content !== null && "type" in content && content.type === "input_image";
@@ -10563,4 +10517,4 @@ server.route("/:provider/images", providerImageRoutes);
10563
10517
  //#endregion
10564
10518
  export { server };
10565
10519
 
10566
- //# sourceMappingURL=server-kYZM25jp.js.map
10520
+ //# sourceMappingURL=server-Bx7xs1FA.js.map