@jeffreycao/copilot-api 1.15.0 → 1.15.2

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
@@ -129,7 +129,7 @@ docker run -p 4141:4141 -e GH_TOKEN=your_github_token_here copilot-api
129
129
 
130
130
  ## Electron Desktop App
131
131
 
132
- If you prefer a GUI, this repository also includes an Electron desktop app in `desktop/`. It supports GitHub Copilot sign-in, OpenAI Codex OAuth, and API-key configuration for DeepSeek, DashScope, OpenRouter, or a custom provider. After authorization or provider configuration, it can start and stop the local proxy with one click and shows the local endpoint, auth header, available models, usage, and logs in the app.
132
+ If you prefer a GUI, this repository also includes an Electron desktop app in `desktop/`. It supports GitHub Copilot sign-in, OpenAI Codex OAuth, and API-key configuration for Kimi, DeepSeek, DashScope, OpenRouter, or a custom provider. After authorization or provider configuration, it can start and stop the local proxy with one click and shows the local endpoint, auth header, available models, usage, and logs in the app.
133
133
 
134
134
  The settings screen also exposes `OAuth App`, `API Home`, `Enterprise URL`, verbose logging, and minimize-to-tray. Windows x64 (`.exe`), macOS Apple Silicon (`.dmg`), and Linux x64 (`.AppImage`) packages are published in GitHub Releases:
135
135
 
@@ -515,13 +515,13 @@ The following command line options are available for the `start` command:
515
515
 
516
516
  | Option | Description | Default | Alias |
517
517
  | ------------ | ------------------------- | ------- | ----- |
518
- | --provider | Provider to log in with or configure (`copilot`, `codex`, `opencode-go`, `deepseek`, `dashscope`, `openrouter`, or `custom`) | prompt | none |
518
+ | --provider | Provider to log in with or configure (`copilot`, `codex`, `opencode-go`, `kimi`, `deepseek`, `dashscope`, `openrouter`, or `custom`) | prompt | none |
519
519
  | --verbose | Enable verbose logging | false | -v |
520
520
  | --show-token | Show GitHub token on auth | false | none |
521
521
 
522
522
  Use `copilot-api auth login --provider copilot` only when you want to enable the GitHub Copilot provider. Copilot is not required for `codex` or third-party provider-only usage.
523
523
 
524
- Use `copilot-api auth login --provider deepseek`, `--provider dashscope`, `--provider openrouter`, or `--provider opencode-go` to add or update those common third-party providers from the CLI. DeepSeek prompts for masked `apiKey`, provider `type` (default `anthropic`), and `baseUrl` defaulting to `https://api.deepseek.com/anthropic`. DashScope prompts for masked `apiKey`, provider `type` (default `openai-compatible`), and prefilled `baseUrl`. OpenRouter prompts for masked `apiKey` and prefilled `baseUrl` only, and writes `type: "anthropic"`. OpenCode Go prompts for masked `apiKey` and prefilled `baseUrl` only, and writes `type: "openai-compatible"` (baseUrl `https://opencode.ai/zen/go`). OpenCode Go additionally routes built-in `qwen*` and `minimax*` models through Anthropic Messages and `gpt*` models through OpenAI Responses; other models keep the OpenAI-compatible default. After a provider is configured and enabled, `copilot-api start` can run without any GitHub token.
524
+ Use `copilot-api auth login --provider deepseek`, `--provider dashscope`, `--provider openrouter`, `--provider opencode-go`, or `--provider kimi` to add or update those common third-party providers from the CLI. DeepSeek prompts for masked `apiKey`, provider `type` (default `anthropic`), and `baseUrl` defaulting to `https://api.deepseek.com/anthropic`. DashScope prompts for masked `apiKey`, provider `type` (default `openai-compatible`), and prefilled `baseUrl`. OpenRouter prompts for masked `apiKey` and prefilled `baseUrl` only, and writes `type: "anthropic"`. OpenCode Go prompts for masked `apiKey` and prefilled `baseUrl` only, and writes `type: "openai-compatible"` (baseUrl `https://opencode.ai/zen/go`). Kimi prompts for masked `apiKey` and prefilled `baseUrl` only, and writes `type: "openai-compatible"` (baseUrl `https://api.kimi.com/coding`). OpenCode Go additionally routes built-in `qwen*` and `minimax*` models through Anthropic Messages and `gpt*` models through OpenAI Responses; other models keep the OpenAI-compatible default. After a provider is configured and enabled, `copilot-api start` can run without any GitHub token.
525
525
 
526
526
  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`.
527
527
 
@@ -574,7 +574,7 @@ Use `copilot-api auth login --provider custom` to add or update another third-pa
574
574
  - `baseUrl` should be provider API base URL without the final endpoint. For Anthropic providers, omit `/v1/messages`; for OpenAI-compatible providers, omit `/v1/chat/completions`; for OpenAI Responses providers, omit `/v1/responses`.
575
575
  - `apiKey` is used as the upstream credential value and is required for regular providers.
576
576
  - `authType` (optional): Controls how `apiKey` is sent upstream. Supports `x-api-key` and `authorization` for regular providers. Anthropic providers default to `x-api-key`; OpenAI-compatible and OpenAI Responses providers default to `authorization`. When set to `authorization`, the proxy sends `Authorization: Bearer <apiKey>`. `oauth2` is reserved for the built-in `codex` provider and is written automatically by `auth login --provider codex`.
577
- - `pricingCurrency` (optional): Provider-level currency used for token cost calculation, for example `USD` or `CNY`. Quick providers default to `CNY` for DashScope and DeepSeek, and `USD` for Codex/OpenRouter. Costs are grouped by currency and are not exchange-rate converted.
577
+ - `pricingCurrency` (optional): Provider-level currency used for token cost calculation, for example `USD` or `CNY`. Quick providers default to `CNY` for DashScope and DeepSeek, and `USD` for Codex, Kimi, OpenCode Go, and OpenRouter. Costs are grouped by currency and are not exchange-rate converted.
578
578
  - `models` (optional): Per-model configuration map. Each key is a model ID (matching the model name in requests), and the value is:
579
579
  - `temperature` (optional): Default temperature value used when the request does not specify one.
580
580
  - `topP` (optional): Default top_p value used when the request does not specify one.
@@ -638,7 +638,7 @@ Use `copilot-api auth login --provider custom` to add or update another third-pa
638
638
  }
639
639
  }
640
640
  ```
641
- Built-in token prices cover Codex GPT models in USD, DashScope `qwen3.7-max`, `qwen3.7-plus`, `glm-5.1`, `glm-5.2` in CNY, DeepSeek `deepseek-v4-flash`, `deepseek-v4-pro`, `deepseek-chat`, `deepseek-reasoner` in CNY, and OpenCode Go models (`hy3`, `gpt-5.6-luna`, `glm-5.2`, `grok-4.5`, `deepseek-v4-flash`, `deepseek-v4-pro`, `kimi-k2.7-code`, `kimi-k3`, `mimo-v2.5`, `mimo-v2.5-pro`, `qwen3.7-plus`, `qwen3.7-max`, `minimax-m2.7`, `minimax-m3`) in USD. User `pricing` entries override built-ins. For DashScope, cached tokens are charged as explicit cache reads when the upstream usage includes `cache_creation_input_tokens`; otherwise `cachedInput` is used as the implicit cache read price. For DeepSeek, `prompt_cache_hit_tokens` map to cached input and `prompt_cache_miss_tokens` map to regular input.
641
+ Built-in token prices cover Codex GPT models in USD, DashScope `qwen3.7-max`, `qwen3.7-plus`, `glm-5.1`, `glm-5.2`, and `kimi/kimi-k3` in CNY, DeepSeek `deepseek-v4-flash` and `deepseek-v4-pro` in CNY, OpenCode Go models (`hy3`, `gpt-5.6-luna`, `glm-5.2`, `grok-4.5`, `deepseek-v4-flash`, `deepseek-v4-pro`, `kimi-k2.7-code`, `kimi-k3`, `mimo-v2.5`, `mimo-v2.5-pro`, `qwen3.7-plus`, `qwen3.7-max`, `minimax-m2.7`, `minimax-m3`) in USD, and Kimi `k3` and `k3-256k` models in USD. User `pricing` entries override built-ins. For DashScope, cached tokens are charged as explicit cache reads when the upstream usage includes `cache_creation_input_tokens`; otherwise `cachedInput` is used as the implicit cache read price. For DeepSeek, `prompt_cache_hit_tokens` map to cached input and `prompt_cache_miss_tokens` map to regular input.
642
642
  - **smallModel:** Fallback model used for tool-less warmup messages (e.g., Claude Code probe requests); defaults to gpt-5-mini. The gateway forces this small model on no-tool warmup or probe requests to avoid consuming premium requests. This behavior only applies to non-token-based-billing GitHub Copilot accounts (`token_based_billing` is false); for token-based-billing accounts the warmup small-model fallback is skipped since there is no premium-request quota to preserve.
643
643
  - **contextManagement:** Controls whether the proxy adds Responses API `context_management` compaction instructions. `messages` applies when Anthropic-style `/v1/messages` requests are translated to Responses API, including `openai-responses` provider message routes, and defaults to `true`. `responses` applies to native `/v1/responses` traffic, including `provider/model` aliases and the built-in `codex` provider, and defaults to `false`. Enable `responses` only after checking that your client supports context management compaction. When enabled, the request includes `context_management` in the body and keeps only the latest compaction carrier on follow-up turns. **Note:** Context management is forcibly disabled for GPT-5.6 and above models (e.g. `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`) because enabling it breaks prompt cache hits on those models. This override takes precedence over the `contextManagement` and `modelResponsesApiCompactThresholds` settings.
644
644
  - **modelResponsesApiCompactThresholds:** Per-model Responses API `compact_threshold` overrides used when the proxy adds `context_management`. These values take precedence over the fallback threshold from `resolveResponsesCompactThreshold` (`max_prompt_tokens * ratio`, or the default fallback). Defaults set `gpt-5.4` and `gpt-5.5` to `217600` (`272000 * 0.8`). Models not listed continue to use the normal fallback logic.
package/README.zh-CN.md CHANGED
@@ -129,7 +129,7 @@ docker run -p 4141:4141 -e GH_TOKEN=your_github_token_here copilot-api
129
129
 
130
130
  ## Electron 桌面应用
131
131
 
132
- 如果你更喜欢图形界面,仓库里还提供了位于 `desktop/` 的 Electron 桌面应用。它支持 GitHub Copilot 登录、OpenAI Codex OAuth,以及 DeepSeek、DashScope、OpenRouter 或自定义 provider 的 API Key 配置。授权或配置 provider 后,可以一键启动或停止本地代理,并在界面里直接查看本地端点、鉴权 Header、可用模型、额度和日志。
132
+ 如果你更喜欢图形界面,仓库里还提供了位于 `desktop/` 的 Electron 桌面应用。它支持 GitHub Copilot 登录、OpenAI Codex OAuth,以及 Kimi、DeepSeek、DashScope、OpenRouter 或自定义 provider 的 API Key 配置。授权或配置 provider 后,可以一键启动或停止本地代理,并在界面里直接查看本地端点、鉴权 Header、可用模型、额度和日志。
133
133
 
134
134
  设置页还可以配置 `OAuth App`、`API Home`、`Enterprise URL`、详细日志以及最小化到托盘。Windows x64(`.exe`)、macOS Apple Silicon(`.dmg`)和 Linux x64(`.AppImage`)安装包发布在 GitHub Releases:
135
135
 
@@ -519,13 +519,13 @@ Copilot API 现在使用子命令结构,主要命令包括:
519
519
 
520
520
  | 选项 | 说明 | 默认值 | 别名 |
521
521
  | --- | --- | --- | --- |
522
- | --provider | 要登录或配置的 provider(`copilot`、`codex`、`opencode-go`、`deepseek`、`dashscope`、`openrouter` 或 `custom`) | 交互选择 | 无 |
522
+ | --provider | 要登录或配置的 provider(`copilot`、`codex`、`opencode-go`、`kimi`、`deepseek`、`dashscope`、`openrouter` 或 `custom`) | 交互选择 | 无 |
523
523
  | --verbose | 启用详细日志 | false | -v |
524
524
  | --show-token | 认证时显示 GitHub token | false | 无 |
525
525
 
526
526
  只有在需要启用 GitHub Copilot provider 时,才需要执行 `copilot-api auth login --provider copilot`。使用 `codex` 或第三方 provider-only 模式不要求配置 Copilot。
527
527
 
528
- 使用 `copilot-api auth login --provider deepseek`、`--provider dashscope`、`--provider openrouter` 或 `--provider opencode-go` 可以通过 CLI 快速新增或更新这些常用第三方 provider。DeepSeek 会提示输入掩码显示的 `apiKey`、provider `type`(默认 `anthropic`),以及默认 `https://api.deepseek.com/anthropic` 的 `baseUrl`。DashScope 会提示输入掩码显示的 `apiKey`、provider `type`(默认 `openai-compatible`)和预填默认值的 `baseUrl`。OpenRouter 只提示输入掩码显示的 `apiKey` 和预填默认值的 `baseUrl`,并固定写入 `type: "anthropic"`。OpenCode Go 只提示输入掩码显示的 `apiKey` 和预填默认值的 `baseUrl`,并固定写入 `type: "openai-compatible"`(baseUrl `https://opencode.ai/zen/go`)。此外,OpenCode Go 内置将 `qwen*` 和 `minimax*` 模型路由到 Anthropic Messages,将 `gpt*` 模型路由到 OpenAI Responses,其他模型仍默认使用 OpenAI 兼容协议。配置并启用 provider 后,`copilot-api start` 可在没有 GitHub token 的情况下启动。
528
+ 使用 `copilot-api auth login --provider deepseek`、`--provider dashscope`、`--provider openrouter`、`--provider opencode-go` 或 `--provider kimi` 可以通过 CLI 快速新增或更新这些常用第三方 provider。DeepSeek 会提示输入掩码显示的 `apiKey`、provider `type`(默认 `anthropic`),以及默认 `https://api.deepseek.com/anthropic` 的 `baseUrl`。DashScope 会提示输入掩码显示的 `apiKey`、provider `type`(默认 `openai-compatible`)和预填默认值的 `baseUrl`。OpenRouter 只提示输入掩码显示的 `apiKey` 和预填默认值的 `baseUrl`,并固定写入 `type: "anthropic"`。OpenCode Go 只提示输入掩码显示的 `apiKey` 和预填默认值的 `baseUrl`,并固定写入 `type: "openai-compatible"`(baseUrl `https://opencode.ai/zen/go`)。Kimi 只提示输入掩码显示的 `apiKey` 和预填默认值的 `baseUrl`,并固定写入 `type: "openai-compatible"`(baseUrl `https://api.kimi.com/coding`)。此外,OpenCode Go 内置将 `qwen*` 和 `minimax*` 模型路由到 Anthropic Messages,将 `gpt*` 模型路由到 OpenAI Responses,其他模型仍默认使用 OpenAI 兼容协议。配置并启用 provider 后,`copilot-api start` 可在没有 GitHub token 的情况下启动。
529
529
 
530
530
  使用 `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`。
531
531
 
@@ -580,7 +580,7 @@ Copilot API 现在使用子命令结构,主要命令包括:
580
580
  - `baseUrl`:provider API 的基础 URL,不要带结尾的 endpoint。Anthropic provider 不要带 `/v1/messages`;OpenAI 兼容 provider 不要带 `/v1/chat/completions`;OpenAI Responses provider 不要带 `/v1/responses`。
581
581
  - `apiKey`:作为上游凭据值使用;普通 provider 必须配置。
582
582
  - `authType`:可选,控制 `apiKey` 如何发送到上游。普通 provider 支持 `x-api-key` 和 `authorization`。Anthropic provider 默认 `x-api-key`;OpenAI 兼容和 OpenAI Responses provider 默认 `authorization`。当设置为 `authorization` 时,代理会发送 `Authorization: Bearer <apiKey>`。`oauth2` 仅保留给内置 `codex` provider,并由 `auth login --provider codex` 自动写入。
583
- - `pricingCurrency`:可选,provider 维度的 token 费用币种,例如 `USD` 或 `CNY`。快捷 provider 默认 DashScope、DeepSeek 为 `CNY`,Codex/OpenRouter 为 `USD`。费用按币种分别汇总,不做汇率换算。
583
+ - `pricingCurrency`:可选,provider 维度的 token 费用币种,例如 `USD` 或 `CNY`。快捷 provider 默认 DashScope、DeepSeek 为 `CNY`,Codex、Kimi、OpenCode Go、OpenRouter 为 `USD`。费用按币种分别汇总,不做汇率换算。
584
584
  - `models`:可选,按模型 ID 配置的映射。每个键为请求中的模型名,值支持:
585
585
  - `temperature`:可选,当请求未指定时使用的默认温度。
586
586
  - `topP`:可选,当请求未指定时使用的默认 `top_p`。
@@ -644,7 +644,7 @@ Copilot API 现在使用子命令结构,主要命令包括:
644
644
  }
645
645
  }
646
646
  ```
647
- 内置 token 价格覆盖 Codex GPT 模型(USD)、DashScope `qwen3.7-max`、`qwen3.7-plus`、`glm-5.1`、`glm-5.2`(CNY),DeepSeek `deepseek-v4-flash`、`deepseek-v4-pro`、`deepseek-chat`、`deepseek-reasoner`(CNY),以及 OpenCode Go 模型(`hy3`、`gpt-5.6-luna`、`glm-5.2`、`grok-4.5`、`deepseek-v4-flash`、`deepseek-v4-pro`、`kimi-k2.7-code`、`kimi-k3`、`mimo-v2.5`、`mimo-v2.5-pro`、`qwen3.7-plus`、`qwen3.7-max`、`minimax-m2.7`、`minimax-m3`,USD)。用户配置的 `pricing` 优先于内置价格。DashScope 若上游 usage 中出现 `cache_creation_input_tokens` 字段,cached tokens 按显式缓存读价计费;否则 `cachedInput` 作为隐式缓存读价。DeepSeek 的 `prompt_cache_hit_tokens` 会归入 cached input,`prompt_cache_miss_tokens` 会归入普通 input。
647
+ 内置 token 价格覆盖 Codex GPT 模型(USD)、DashScope `qwen3.7-max`、`qwen3.7-plus`、`glm-5.1`、`glm-5.2`、`kimi/kimi-k3`(CNY),DeepSeek `deepseek-v4-flash`、`deepseek-v4-pro`(CNY),OpenCode Go 模型(`hy3`、`gpt-5.6-luna`、`glm-5.2`、`grok-4.5`、`deepseek-v4-flash`、`deepseek-v4-pro`、`kimi-k2.7-code`、`kimi-k3`、`mimo-v2.5`、`mimo-v2.5-pro`、`qwen3.7-plus`、`qwen3.7-max`、`minimax-m2.7`、`minimax-m3`,USD),以及 Kimi `k3`、`k3-256k` 模型(USD)。用户配置的 `pricing` 优先于内置价格。DashScope 若上游 usage 中出现 `cache_creation_input_tokens` 字段,cached tokens 按显式缓存读价计费;否则 `cachedInput` 作为隐式缓存读价。DeepSeek 的 `prompt_cache_hit_tokens` 会归入 cached input,`prompt_cache_miss_tokens` 会归入普通 input。
648
648
  - **smallModel:** 无工具预热消息的回退模型(例如 Claude Code 的探测请求);默认是 `gpt-5-mini`。网关会对无工具的预热或探测请求强制使用该小模型,以避免消耗 premium 请求。该行为仅在 GitHub Copilot 账户为非 token-based 计费时生效(`token_based_billing` 为 false);对于 token-based 计费账户,预热小模型回退会被跳过,因为不存在需要节省的 premium 请求配额。
649
649
  - **contextManagement:** 控制代理是否为 Responses API 附加 `context_management` 压缩指令。`messages` 作用于被翻译成 Responses API 的 Anthropic 风格 `/v1/messages` 请求,包括 `openai-responses` provider 的 Messages 路由,默认值为 `true`。`responses` 作用于 native `/v1/responses` 流量,包括 `provider/model` 别名和内置 `codex` provider,默认值为 `false`。只有在确认客户端支持 context management compaction 后,才建议在 Responses API 下启用 `responses`。启用后,请求体会带上 `context_management`,并在后续轮次中仅保留最新的压缩承载内容。**注意:** 对于 GPT-5.6 及以上模型(如 `gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-5.6-luna`),context management 功能会被强制禁用,因为开启后会破坏这些模型的 prompt 缓存命中。此强制覆盖优先于 `contextManagement` 和 `modelResponsesApiCompactThresholds` 配置。
650
650
  - **modelResponsesApiCompactThresholds:** 按模型覆盖 Responses API 的 `compact_threshold`,仅在代理自动附加 `context_management` 时使用。它的优先级高于 `resolveResponsesCompactThreshold` 基于 `max_prompt_tokens * ratio` 的兜底阈值。默认将 `gpt-5.4` 和 `gpt-5.5` 设为 `217600`(`272000 * 0.8`)。未列出的模型继续使用原有兜底逻辑。
@@ -0,0 +1,2 @@
1
+ import { t as auth } from "./auth-CskgMMwz.js";
2
+ export { auth };
@@ -10,6 +10,12 @@ const QUICK_PROVIDER_CONFIGS = {
10
10
  pricingCurrency: "USD",
11
11
  editableType: false
12
12
  },
13
+ kimi: {
14
+ type: "openai-compatible",
15
+ baseUrl: "https://api.kimi.com/coding",
16
+ pricingCurrency: "USD",
17
+ editableType: false
18
+ },
13
19
  deepseek: {
14
20
  type: "anthropic",
15
21
  baseUrl: "https://api.deepseek.com/anthropic",
@@ -34,7 +40,7 @@ const QUICK_PROVIDER_CONFIGS = {
34
40
  const authArgs = {
35
41
  provider: {
36
42
  type: "string",
37
- description: "Provider to log in with or configure (copilot, codex, opencode-go, deepseek, dashscope, openrouter, custom)"
43
+ description: "Provider to log in with or configure (copilot, codex, opencode-go, kimi, deepseek, dashscope, openrouter, custom)"
38
44
  },
39
45
  verbose: {
40
46
  alias: "v",
@@ -62,6 +68,7 @@ const AUTH_PROVIDER_LABELS = {
62
68
  copilot: "GitHub Copilot",
63
69
  codex: "OpenAI Codex",
64
70
  "opencode-go": "OpenCode Go",
71
+ kimi: "Kimi",
65
72
  deepseek: "DeepSeek",
66
73
  dashscope: "DashScope",
67
74
  openrouter: "OpenRouter",
@@ -347,4 +354,4 @@ const auth = defineCommand({
347
354
  //#endregion
348
355
  export { runAuthLogin as n, runProviderSetup as r, auth as t };
349
356
 
350
- //# sourceMappingURL=auth-DqCboaUp.js.map
357
+ //# sourceMappingURL=auth-CskgMMwz.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-CskgMMwz.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 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 {\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 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\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 },\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;;;ACVD,MAAM,WAAW;CACf,UAAU;EACR,MAAM;EACN,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BAA2B,MAAM,kBAAkB;EACnE;;CAGF,IAAI,aAAa,SAAS;EACxB,MAAM,gBAAgB;EACtB;;CAGF,IAAI,oBAAoB,SAAS,EAAE;EACjC,MAAM,uBAAuB,SAAS;EACtC;;CAGF,MAAM,yBAAyB;;AAGjC,eAAsB,mBAAkC;CACtD,MAAM,WAAW,MAAM,yBAAyB,KAAA,EAAU;CAC1D,QAAQ,KAAK,mBAAmB,qBAAqB,YAAY;CACjE,MAAM,kBAAkB,SAAS;;AAGnC,eAAsB,aAAa,SAAwC;CAEzE,CAAA,MADwB,OAAO,sBACrB,sBAAsB;CAEhC,IAAI,QAAQ,SAAS;EACnB,QAAQ,QAAQ;EAChB,QAAQ,KAAK,0BAA0B;;CAGzC,MAAM,YAAY,QAAQ;CAE1B,MAAM,aAAa;CACnB,MAAM,WAAW,MAAM,yBAAyB,QAAQ,SAAS;CAEjE,QAAQ,KAAK,mBAAmB,qBAAqB,YAAY;CACjE,MAAM,kBAAkB,SAAS;;AAmBnC,MAAa,OAAO,cAAc;CAChC,MAAM;EACJ,MAAM;EACN,aAAa;EACd;CACD,MAAM;CACN,aAAa,EACX,OAvBc,cAAc;EAC9B,MAAM;GACJ,MAAM;GACN,aACE;GACH;EACD,MAAM;EACN,IAAI,EAAE,QAAQ;GACZ,OAAO,aAAa;IAClB,UAAU,KAAK;IACf,SAAS,KAAK;IACd,WAAW,KAAK;IACjB,CAAC;;EAEL,CASU,EACR;CACD,IAAI,EAAE,QAAQ;EACZ,KAAK,KAAK,EAAE,MAAM,IAAI,MAAM,EAC1B;EAGF,OAAO,aAAa;GAClB,UAAU,KAAK;GACf,SAAS,KAAK;GACd,WAAW,KAAK;GACjB,CAAC;;CAEL,CAAC"}
package/dist/main.js CHANGED
@@ -22,10 +22,10 @@ if (typeof args["enterprise-url"] === "string") process.env.COPILOT_API_ENTERPRI
22
22
  if (process.platform === "win32" && process.stdout.isTTY && !process.env.WT_SESSION) process.env.WT_SESSION = "copilot-api";
23
23
  const { bindElectronFetch } = await import("./electron-fetch-DPhDE6JE.js");
24
24
  bindElectronFetch();
25
- const { auth } = await import("./auth-BuVLgbbO.js");
25
+ const { auth } = await import("./auth-CRonPTZQ.js");
26
26
  const { debug } = await import("./debug-CVd8Dq56.js");
27
27
  const { mcp } = await import("./mcp-BG6fpi6q.js");
28
- const { start } = await import("./start-i6nxPCwq.js");
28
+ const { start } = await import("./start-YxEMb8V2.js");
29
29
  await runMain(defineCommand({
30
30
  meta: {
31
31
  name: "copilot-api",
@@ -193,22 +193,26 @@ function registerProcessCleanup(handler) {
193
193
  //#region src/lib/logger.ts
194
194
  const LOG_RETENTION_MS = 10080 * 60 * 1e3;
195
195
  const CLEANUP_INTERVAL_MS = 1440 * 60 * 1e3;
196
- const LOG_DIR = path.join(PATHS.APP_DIR, "logs");
196
+ const LOG_DIR_ENV = "COPILOT_API_LOG_DIR";
197
+ const DEFAULT_LOG_DIR = path.join(PATHS.APP_DIR, "logs");
197
198
  const FLUSH_INTERVAL_MS = 1e3;
198
199
  const MAX_BUFFER_SIZE = 100;
200
+ const getLogDir = () => process.env[LOG_DIR_ENV]?.trim() || DEFAULT_LOG_DIR;
199
201
  const logStreams = /* @__PURE__ */ new Map();
200
202
  const logBuffers = /* @__PURE__ */ new Map();
201
203
  let runtimeInitialized = false;
202
204
  let flushInterval;
203
205
  let cleanupInterval;
204
206
  const ensureLogDirectory = () => {
205
- if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
207
+ const logDir = getLogDir();
208
+ if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });
206
209
  };
207
210
  const cleanupOldLogs = () => {
208
- if (!fs.existsSync(LOG_DIR)) return;
211
+ const logDir = getLogDir();
212
+ if (!fs.existsSync(logDir)) return;
209
213
  const now = Date.now();
210
- for (const entry of fs.readdirSync(LOG_DIR)) {
211
- const filePath = path.join(LOG_DIR, entry);
214
+ for (const entry of fs.readdirSync(logDir)) {
215
+ const filePath = path.join(logDir, entry);
212
216
  let stats;
213
217
  try {
214
218
  stats = fs.statSync(filePath);
@@ -247,7 +251,13 @@ const flushBuffer = (filePath) => {
247
251
  const flushAllBuffers = () => {
248
252
  for (const filePath of logBuffers.keys()) flushBuffer(filePath);
249
253
  };
250
- const cleanup = () => {
254
+ const flushAndCloseLogStreams = () => {
255
+ flushAllBuffers();
256
+ for (const stream of logStreams.values()) stream.end();
257
+ logStreams.clear();
258
+ logBuffers.clear();
259
+ };
260
+ const shutdownLoggerRuntime = () => {
251
261
  if (flushInterval) {
252
262
  clearInterval(flushInterval);
253
263
  flushInterval = void 0;
@@ -256,10 +266,8 @@ const cleanup = () => {
256
266
  clearInterval(cleanupInterval);
257
267
  cleanupInterval = void 0;
258
268
  }
259
- flushAllBuffers();
260
- for (const stream of logStreams.values()) stream.end();
261
- logStreams.clear();
262
- logBuffers.clear();
269
+ flushAndCloseLogStreams();
270
+ runtimeInitialized = false;
263
271
  };
264
272
  const initializeLoggerRuntime = () => {
265
273
  if (runtimeInitialized) return;
@@ -270,7 +278,7 @@ const initializeLoggerRuntime = () => {
270
278
  maybeUnref(flushInterval);
271
279
  cleanupInterval = setInterval(cleanupOldLogs, CLEANUP_INTERVAL_MS);
272
280
  maybeUnref(cleanupInterval);
273
- registerProcessCleanup(cleanup);
281
+ registerProcessCleanup(shutdownLoggerRuntime);
274
282
  };
275
283
  const getLogStream = (filePath) => {
276
284
  initializeLoggerRuntime();
@@ -319,7 +327,7 @@ const createHandlerLogger = (name) => {
319
327
  const date = logObj.date;
320
328
  const dateKey = date.toLocaleDateString("sv-SE");
321
329
  const timestamp = date.toLocaleString("sv-SE", { hour12: false });
322
- const filePath = path.join(LOG_DIR, `${sanitizedName}-${dateKey}.log`);
330
+ const filePath = path.join(getLogDir(), `${sanitizedName}-${dateKey}.log`);
323
331
  const message = formatArgs(logObj.args);
324
332
  const traceIdStr = traceId ? ` [${traceId}]` : "";
325
333
  appendLine(filePath, `[${timestamp}] [${logObj.type}] [${logObj.tag || name}]${traceIdStr}${message ? ` ${message}` : ""}`);
@@ -1031,6 +1039,7 @@ const BUILTIN_PROVIDER_CURRENCIES = {
1031
1039
  codex: "USD",
1032
1040
  dashscope: "CNY",
1033
1041
  deepseek: "CNY",
1042
+ kimi: "USD",
1034
1043
  "opencode-go": "USD"
1035
1044
  };
1036
1045
  const BUILTIN_PROVIDER_PRICING = {
@@ -1163,7 +1172,12 @@ const BUILTIN_PROVIDER_PRICING = {
1163
1172
  input: 6,
1164
1173
  maxInputTokens: 1e6,
1165
1174
  output: 24
1166
- }] }
1175
+ }] },
1176
+ "kimi/kimi-k3": {
1177
+ cachedInput: 2,
1178
+ input: 20,
1179
+ output: 100
1180
+ }
1167
1181
  },
1168
1182
  deepseek: {
1169
1183
  "deepseek-v4-flash": {
@@ -1281,6 +1295,18 @@ const BUILTIN_PROVIDER_PRICING = {
1281
1295
  maxInputTokens: 512e3,
1282
1296
  output: 2.4
1283
1297
  }] }
1298
+ },
1299
+ kimi: {
1300
+ k3: {
1301
+ cachedInput: .3,
1302
+ input: 3,
1303
+ output: 15
1304
+ },
1305
+ "k3-256k": {
1306
+ cachedInput: .3,
1307
+ input: 3,
1308
+ output: 15
1309
+ }
1284
1310
  }
1285
1311
  };
1286
1312
  function resolveTokenUsageCost(input) {
@@ -7938,4 +7964,4 @@ server.route("/:provider/images", providerImageRoutes);
7938
7964
  //#endregion
7939
7965
  export { server };
7940
7966
 
7941
- //# sourceMappingURL=server-DZtBoW6V.js.map
7967
+ //# sourceMappingURL=server-DWY7PmxG.js.map