@jeffreycao/copilot-api 1.13.7 → 1.13.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,9 +33,7 @@ On the GitHub Copilot path, the gateway prefers Copilot's native Anthropic-style
33
33
  - **Agent-friendly Claude handling on Copilot**: Prefer native `/v1/messages` when available, preserve Claude-style tool flows, support Anthropic beta features, Claude WebSearch through Responses-capable models, and keep subagent/session markers intact.
34
34
  - **Claude Code and OpenCode integration**: Works with Claude Code and OpenCode, including direct Anthropic-compatible usage through `@ai-sdk/anthropic`.
35
35
  - **Flexible auth and deployment options**: Supports interactive login or direct tokens, individual/business/enterprise plans, GitHub Enterprise, opencode OAuth, and custom data directories.
36
- - **Local control and visibility**: Includes a usage dashboard, rate limiting, manual approval, and optional token visibility for debugging.
37
36
  - **Multi-provider routing**: Expose provider-specific `/:provider/...` routes or use `model: "provider/model"` on the top-level API.
38
- - **Better token and context management**: Supports exact Claude token counting and configurable GPT context compaction for long-running conversations.
39
37
 
40
38
  ## Prerequisites
41
39
 
@@ -276,7 +274,6 @@ Why these fields matter:
276
274
 
277
275
  - `npm: "@ai-sdk/anthropic"` is the important part. OpenCode will speak Anthropic Messages semantics to this AI gateway instead of flattening everything into OpenAI Chat Completions.
278
276
  - `options.baseURL` should be `http://localhost:4141/v1`; the Anthropic SDK will append `/messages`, `/models`, and `/messages/count_tokens` automatically.
279
- - `model`, `small_model`, and `agent.*.model` let you keep `gpt-5.4` for build/plan work while routing exploration and background work to `gpt-5-mini`.
280
277
  - If you enable `auth.apiKeys` in this AI gateway, replace `dummy` with a real key. Otherwise any placeholder value is fine.
281
278
 
282
279
  ## Using with Codex
@@ -488,13 +485,13 @@ The following command line options are available for the `start` command:
488
485
 
489
486
  | Option | Description | Default | Alias |
490
487
  | ------------ | ------------------------- | ------- | ----- |
491
- | --provider | Provider to log in with or configure (`copilot`, `codex`, `deepseek`, `dashscope`, `openrouter`, or `custom`) | prompt | none |
488
+ | --provider | Provider to log in with or configure (`copilot`, `codex`, `opencode-go`, `deepseek`, `dashscope`, `openrouter`, or `custom`) | prompt | none |
492
489
  | --verbose | Enable verbose logging | false | -v |
493
490
  | --show-token | Show GitHub token on auth | false | none |
494
491
 
495
492
  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.
496
493
 
497
- Use `copilot-api auth login --provider deepseek`, `--provider dashscope`, or `--provider openrouter` 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"`. After a provider is configured and enabled, `copilot-api start` can run without any GitHub token.
494
+ 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`). After a provider is configured and enabled, `copilot-api start` can run without any GitHub token.
498
495
 
499
496
  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`.
500
497
 
@@ -556,11 +553,12 @@ Use `copilot-api auth login --provider custom` to add or update another third-pa
556
553
  - `temperature` (optional): Default temperature value used when the request does not specify one.
557
554
  - `topP` (optional): Default top_p value used when the request does not specify one.
558
555
  - `topK` (optional): Default top_k value used when the request does not specify one.
559
- - `extraBody` (optional): Dynamic fields merged into the upstream request body for that model. Request body fields with the same name take precedence. OpenAI-compatible providers can use this for fields such as `enable_thinking`, `preserve_thinking`, `reasoning_effort`. `thinking_budget` is a special OpenAI-compatible provider override: when configured in `extraBody`, it is forced after Anthropic `thinking.budget_tokens` translation and overrides the request-derived budget.
556
+ - `extraBody` (optional): Dynamic fields merged into the upstream request body for that model. Request body fields with the same name take precedence. OpenAI-compatible providers can use this for fields such as `enable_thinking`, `preserve_thinking`, `reasoning_effort`. `thinking_budget` is a special OpenAI-compatible provider override: when configured in `extraBody`, it is forced after Anthropic `thinking.budget_tokens` translation and overrides the request-derived budget. For providers whose name is `dashscope` or whose `baseUrl` contains `aliyuncs.com`, the request-derived `thinking_budget` (from Anthropic `thinking.budget_tokens`) is forwarded upstream; for other OpenAI-compatible providers the request-derived `thinking_budget` is stripped, while an `extraBody` `thinking_budget` is still honored.
560
557
  - `pricing` (optional): Per-model token prices, in the provider `pricingCurrency`, per 1M tokens. Supported fields are `input`, `output`, `cachedInput` (implicit cache read), `explicitCachedInput` (explicit cache read), and `cacheCreationInput`. Use `tiers` with `maxInputTokens` for input-size tiered pricing.
561
- - `contextCache` (optional): Defaults to `true` for OpenAI-compatible providers. This enables Alibaba Cloud Model Studio/DashScope explicit context cache by injecting `cache_control: { "type": "ephemeral" }` on up to 4 content blocks using the Context Cache format. The cache breakpoint strategy matches opencode's main provider flow: the first 2 system messages plus the last 2 non-system messages. Marked string content is converted to text content part arrays for `system` / `user` / `assistant` / `tool` messages; existing array content is marked on the last part. Set this to `false` when the model already supports implicit caching, or when the upstream does not accept this explicit-cache extension field.
558
+ - `contextCache` (optional): Defaults to `true` for providers whose name is `dashscope` or whose `baseUrl` contains `aliyuncs.com`; defaults to `false` for other OpenAI-compatible providers. This enables Alibaba Cloud Model Studio/DashScope explicit context cache by injecting `cache_control: { "type": "ephemeral" }` on up to 4 content blocks using the Context Cache format. The cache breakpoint strategy matches opencode's main provider flow: the first 2 system messages plus the last 2 non-system messages. Marked string content is converted to text content part arrays for `system` / `user` / `assistant` / `tool` messages; existing array content is marked on the last part. Set this to `false` when the model already supports implicit caching, or when the upstream does not accept this explicit-cache extension field. Set this to `true` for non-DashScope providers that support the same explicit-cache extension.
562
559
  - `supportPdf` (optional): Controls whether the model supports PDF/document content. Defaults to `false`; unsupported PDFs are converted to a text notice. Set it to `true` to send PDF/document blocks as OpenAI Chat Completions file parts.
563
560
  - `toolContentSupportType` (optional): Tool result content capabilities for that model, as an array of `array`, `image`, and `pdf`. Provider routes default to string-only tool content when omitted. If `supportPdf` is `true` but this list does not include `pdf`, file parts in tool results are moved to user role messages. This provider default does not change the Copilot main flow, which continues to support array + image and not PDF.
561
+ - `type` (optional): Per-model override of the provider protocol type. Supports `anthropic`, `openai-compatible`, and `openai-responses`. When set, the provider's `/v1/messages` route uses this model's type instead of the provider-level type for request routing, auth header resolution, and upstream endpoint selection. This is useful for providers like OpenCode Go whose upstream supports both OpenAI-compatible and Anthropic Messages APIs for different models. When the type is overridden, the auth header is resolved from the overridden type's default (Anthropic defaults to `x-api-key`; OpenAI-compatible/Responses default to `authorization`).
564
562
 
565
563
  Example DashScope model settings:
566
564
  ```json
@@ -614,7 +612,7 @@ Use `copilot-api auth login --provider custom` to add or update another third-pa
614
612
  }
615
613
  }
616
614
  ```
617
- 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, and DeepSeek `deepseek-v4-flash`, `deepseek-v4-pro`, `deepseek-chat`, `deepseek-reasoner` in CNY. 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.
615
+ 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 (`glm-5.2`, `deepseek-v4-flash`, `deepseek-v4-pro`, `kimi-k2.7-code`, `mimo-v2.5`, `mimo-v2.5-pro`, `qwen3.7-plus`, `qwen3.7-max`, `minimax-m2.5`, `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.
618
616
  - **smallModel:** Fallback model used for tool-less warmup messages (e.g., Claude Code probe requests); defaults to gpt-5-mini.
619
617
  - **useResponsesApiContextManagement:** When `true`, the proxy adds Responses API `context_management` compaction instructions. Defaults to `true`. Set it to `false` to disable this globally. When enabled, the request includes `context_management` in the body and keeps only the latest compaction carrier on follow-up turns. This is especially useful for long-running tasks.
620
618
  - **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
@@ -33,9 +33,7 @@ AI gateway 会从同一个本地端点暴露 OpenAI / Anthropic 兼容 API,让
33
33
  - **面向 Claude 的更原生 Copilot 路由**:优先使用原生 `/v1/messages`,保留 Claude 风格工具流,支持 Anthropic beta 能力、通过 Responses-capable 模型支持 Claude WebSearch,并保留 subagent / session 标记。
34
34
  - **Claude Code 与 OpenCode 集成**:兼容 Claude Code 与 OpenCode,也支持通过 `@ai-sdk/anthropic` 直接作为 Anthropic provider 使用。
35
35
  - **灵活的认证与部署选项**:支持交互式登录、直接 token、个人 / Business / Enterprise、GitHub Enterprise、opencode OAuth 和自定义数据目录。
36
- - **本地控制与可观测性**:提供使用量看板、速率限制、手动审批,以及调试时显示 token 的能力。
37
36
  - **多 provider 路由**:可暴露 `/:provider/...` 路由,也可在顶层 API 上使用 `model: "provider/model"`。
38
- - **更好的 token 与上下文管理**:支持精确 Claude token 计数,以及面向长对话的 GPT 上下文压缩。
39
37
 
40
38
  ## 前置要求
41
39
 
@@ -278,7 +276,6 @@ npx @jeffreycao/copilot-api@latest start
278
276
 
279
277
  - `npm: "@ai-sdk/anthropic"` 是关键。OpenCode 会以 Anthropic Messages 语义与这个 AI gateway 通信,而不是把一切扁平化为 OpenAI Chat Completions。
280
278
  - `options.baseURL` 应设为 `http://localhost:4141/v1`;Anthropic SDK 会自动补上 `/messages`、`/models` 和 `/messages/count_tokens`。
281
- - `model`、`small_model` 与 `agent.*.model` 让你可以把 `gpt-5.4` 用于 build/plan,同时把探索和后台工作路由到 `gpt-5-mini`。
282
279
  - 如果你在此代理中启用了 `auth.apiKeys`,请把 `dummy` 替换为真实 key;否则任意占位值都可以。
283
280
 
284
281
  ## 与 Codex 一起使用
@@ -492,13 +489,13 @@ Copilot API 现在使用子命令结构,主要命令包括:
492
489
 
493
490
  | 选项 | 说明 | 默认值 | 别名 |
494
491
  | --- | --- | --- | --- |
495
- | --provider | 要登录或配置的 provider(`copilot`、`codex`、`deepseek`、`dashscope`、`openrouter` 或 `custom`) | 交互选择 | 无 |
492
+ | --provider | 要登录或配置的 provider(`copilot`、`codex`、`opencode-go`、`deepseek`、`dashscope`、`openrouter` 或 `custom`) | 交互选择 | 无 |
496
493
  | --verbose | 启用详细日志 | false | -v |
497
494
  | --show-token | 认证时显示 GitHub token | false | 无 |
498
495
 
499
496
  只有在需要启用 GitHub Copilot provider 时,才需要执行 `copilot-api auth login --provider copilot`。使用 `codex` 或第三方 provider-only 模式不要求配置 Copilot。
500
497
 
501
- 使用 `copilot-api auth login --provider deepseek`、`--provider dashscope` 或 `--provider openrouter` 可以通过 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"`。配置并启用 provider 后,`copilot-api start` 可在没有 GitHub token 的情况下启动。
498
+ 使用 `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`)。配置并启用 provider 后,`copilot-api start` 可在没有 GitHub token 的情况下启动。
502
499
 
503
500
  使用 `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`。
504
501
 
@@ -562,11 +559,12 @@ Copilot API 现在使用子命令结构,主要命令包括:
562
559
  - `temperature`:可选,当请求未指定时使用的默认温度。
563
560
  - `topP`:可选,当请求未指定时使用的默认 `top_p`。
564
561
  - `topK`:可选,当请求未指定时使用的默认 `top_k`。
565
- - `extraBody`:可选,按模型合入上游请求体的动态字段;请求体显式同名字段优先。OpenAI 兼容 provider 可用它配置 `enable_thinking`、`preserve_thinking`、`reasoning_effort` 等字段。`thinking_budget` 是 OpenAI 兼容 provider 的特殊覆盖项:配置在 `extraBody` 后,会在 Anthropic `thinking.budget_tokens` 翻译之后强制写入,并覆盖请求派生出的预算值。
562
+ - `extraBody`:可选,按模型合入上游请求体的动态字段;请求体显式同名字段优先。OpenAI 兼容 provider 可用它配置 `enable_thinking`、`preserve_thinking`、`reasoning_effort` 等字段。`thinking_budget` 是 OpenAI 兼容 provider 的特殊覆盖项:配置在 `extraBody` 后,会在 Anthropic `thinking.budget_tokens` 翻译之后强制写入,并覆盖请求派生出的预算值。对于 provider name 为 `dashscope` 或 `baseUrl` 包含 `aliyuncs.com` 的 provider,请求派生的 `thinking_budget`(来自 Anthropic `thinking.budget_tokens`)会转发给上游;其他 OpenAI 兼容 provider 会移除请求派生的 `thinking_budget`,但 `extraBody` 中的 `thinking_budget` 仍然生效。
566
563
  - `pricing`:可选,按模型配置 token 单价,币种使用 provider 的 `pricingCurrency`,单位为每 100 万 tokens。支持 `input`、`output`、`cachedInput`(隐式缓存读)、`explicitCachedInput`(显式缓存读)和 `cacheCreationInput`。如需按输入 token 总量分档,可用带 `maxInputTokens` 的 `tiers`。
567
- - `contextCache`:可选,OpenAI 兼容 provider 默认 `true`,用于启用阿里云百炼/DashScope 的显式缓存(explicit context cache),会按其 Context Cache 格式在最多 4 个 content block 上注入 `cache_control: { "type": "ephemeral" }`。缓存断点策略与 opencode 主链路保持一致:前 2 条 system 消息 + 最后 2 条非 system 消息。标记字符串 content 时会把 `system` / `user` / `assistant` / `tool` 消息转换为 text content part 数组;已有数组 content 则标记最后一个 part。如果模型本身已经支持隐式缓存,或上游不支持该显式缓存扩展字段,可在模型配置中设为 `false`。
564
+ - `contextCache`:可选,provider name 为 `dashscope` 或 `baseUrl` 包含 `aliyuncs.com` 时默认 `true`,其他 OpenAI 兼容 provider 默认 `false`。用于启用阿里云百炼/DashScope 的显式缓存(explicit context cache),会按其 Context Cache 格式在最多 4 个 content block 上注入 `cache_control: { "type": "ephemeral" }`。缓存断点策略与 opencode 主链路保持一致:前 2 条 system 消息 + 最后 2 条非 system 消息。标记字符串 content 时会把 `system` / `user` / `assistant` / `tool` 消息转换为 text content part 数组;已有数组 content 则标记最后一个 part。如果模型本身已经支持隐式缓存,或上游不支持该显式缓存扩展字段,可在模型配置中设为 `false`。支持相同显式缓存扩展的非 DashScope provider 可设为 `true`。
568
565
  - `supportPdf`:可选,控制该模型是否支持 PDF/document content。默认 `false`,不支持时会把 PDF 转成提示文本;设为 `true` 时会把 PDF/document 转成 OpenAI Chat Completions 的 file part。
569
566
  - `toolContentSupportType`:可选,配置该模型的 tool result content 支持能力,值为 `array`、`image`、`pdf` 的数组。provider 侧未配置时默认只发送 string tool content。若 `supportPdf` 为 `true` 但这里不包含 `pdf`,tool result 里的 file part 会被转成 user role 消息。Copilot 主链路不使用这个 provider 默认,仍按 array + image 且不支持 PDF 的能力处理。
567
+ - `type`:可选,按模型覆盖 provider 的协议类型。支持 `anthropic`、`openai-compatible` 和 `openai-responses`。设置后,provider 的 `/v1/messages` 路由会使用该模型的 type 替代 provider 级别的 type 进行请求路由、认证头解析和上游端点选择。适用于 OpenCode Go 等上游对不同模型同时支持 OpenAI 兼容和 Anthropic Messages API 的 provider。覆盖 type 时,认证头按覆盖后 type 的默认值解析(Anthropic 默认 `x-api-key`;OpenAI 兼容/Responses 默认 `authorization`)。
570
568
 
571
569
  DashScope 模型配置示例:
572
570
  ```json
@@ -620,7 +618,7 @@ Copilot API 现在使用子命令结构,主要命令包括:
620
618
  }
621
619
  }
622
620
  ```
623
- 内置 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)。用户配置的 `pricing` 优先于内置价格。DashScope 若上游 usage 中出现 `cache_creation_input_tokens` 字段,cached tokens 按显式缓存读价计费;否则 `cachedInput` 作为隐式缓存读价。DeepSeek 的 `prompt_cache_hit_tokens` 会归入 cached input,`prompt_cache_miss_tokens` 会归入普通 input。
621
+ 内置 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 模型(`glm-5.2`、`deepseek-v4-flash`、`deepseek-v4-pro`、`kimi-k2.7-code`、`mimo-v2.5`、`mimo-v2.5-pro`、`qwen3.7-plus`、`qwen3.7-max`、`minimax-m2.5`、`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。
624
622
  - **smallModel:** 无工具预热消息的回退模型(例如 Claude Code 的探测请求);默认是 `gpt-5-mini`。
625
623
  - **useResponsesApiContextManagement:** 当为 `true` 时,代理会为 Responses API 附加 `context_management` 压缩指令。默认值为 `true`。如需全局关闭,可设为 `false`。启用后,请求体会带上 `context_management`,并在后续轮次中仅保留最新的压缩承载内容,因此特别适合长任务场景。
626
624
  - **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-D0Oc4jsb.js";
2
+ export { auth };
@@ -1,9 +1,15 @@
1
- import { C as setProviderConfig, T as ensurePaths, _ as isSupportedProviderType, b as normalizeProviderBaseUrl, t as SUPPORTED_PROVIDER_TYPES, u as getRawProviderConfig, w as PATHS } from "./config-DODTXsGz.js";
2
- import { A as loginCodex, L as state, a as setupGitHubToken, n as persistCodexCredentials } from "./token-BOovYuN5.js";
1
+ import { D as ensurePaths, E as PATHS, T as setProviderConfig, _ as isSupportedProviderType, b as normalizeProviderBaseUrl, t as SUPPORTED_PROVIDER_TYPES, u as getRawProviderConfig } from "./config-Dm9cU9KP.js";
2
+ import { A as loginCodex, L as state, a as setupGitHubToken, n as persistCodexCredentials } from "./token-CejO9iGT.js";
3
3
  import { defineCommand } from "citty";
4
4
  import consola from "consola";
5
5
  //#region src/lib/quick-providers.ts
6
6
  const QUICK_PROVIDER_CONFIGS = {
7
+ "opencode-go": {
8
+ type: "openai-compatible",
9
+ baseUrl: "https://opencode.ai/zen/go",
10
+ pricingCurrency: "USD",
11
+ editableType: false
12
+ },
7
13
  deepseek: {
8
14
  type: "anthropic",
9
15
  baseUrl: "https://api.deepseek.com/anthropic",
@@ -28,7 +34,7 @@ const QUICK_PROVIDER_CONFIGS = {
28
34
  const authArgs = {
29
35
  provider: {
30
36
  type: "string",
31
- description: "Provider to log in with or configure (copilot, codex, deepseek, dashscope, openrouter, custom)"
37
+ description: "Provider to log in with or configure (copilot, codex, opencode-go, deepseek, dashscope, openrouter, custom)"
32
38
  },
33
39
  verbose: {
34
40
  alias: "v",
@@ -55,6 +61,7 @@ const CUSTOM_PROVIDER_AUTH_TYPES = ["x-api-key", "authorization"];
55
61
  const AUTH_PROVIDER_LABELS = {
56
62
  copilot: "GitHub Copilot",
57
63
  codex: "OpenAI Codex",
64
+ "opencode-go": "OpenCode Go",
58
65
  deepseek: "DeepSeek",
59
66
  dashscope: "DashScope",
60
67
  openrouter: "OpenRouter",
@@ -340,4 +347,4 @@ const auth = defineCommand({
340
347
  //#endregion
341
348
  export { runAuthLogin as n, runProviderSetup as r, auth as t };
342
349
 
343
- //# sourceMappingURL=auth-DDTGPBsT.js.map
350
+ //# sourceMappingURL=auth-D0Oc4jsb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-D0Oc4jsb.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 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, 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 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 },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AI,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"}
@@ -360,6 +360,11 @@ function getProviderConfig(name) {
360
360
  models: provider.models
361
361
  };
362
362
  }
363
+ function resolveEffectiveProviderType(providerConfig, model) {
364
+ const modelConfig = providerConfig.models?.[model];
365
+ if (modelConfig?.type && isSupportedProviderType(modelConfig.type)) return modelConfig.type;
366
+ return providerConfig.type;
367
+ }
363
368
  function normalizePricingCurrency(value) {
364
369
  return value?.trim().toUpperCase() || void 0;
365
370
  }
@@ -390,6 +395,6 @@ function getClaudeTokenMultiplier() {
390
395
  return getConfig().claudeTokenMultiplier ?? 1.15;
391
396
  }
392
397
  //#endregion
393
- export { setProviderConfig as C, setModelMappings as S, ensurePaths as T, isSupportedProviderType as _, getExtraPromptForModel as a, normalizeProviderBaseUrl as b, getModelResponsesApiCompactThreshold as c, getReasoningEffortForModel as d, getSmallModel as f, isResponsesApiWebSocketEnabled as g, isResponsesApiWebSearchEnabled as h, getConfig as i, getProviderConfig as l, isResponsesApiContextManagementEnabled as m, getAnthropicApiKey as n, getMessageApiWebSearchModel as o, isMessagesApiEnabled as p, getClaudeTokenMultiplier as r, getModelMappings as s, SUPPORTED_PROVIDER_TYPES as t, getRawProviderConfig as u, listEnabledProviders as v, PATHS as w, resolveMappedModel as x, mergeConfigWithDefaults as y };
398
+ export { resolveProviderAuthType as C, ensurePaths as D, PATHS as E, resolveMappedModel as S, setProviderConfig as T, isSupportedProviderType as _, getExtraPromptForModel as a, normalizeProviderBaseUrl as b, getModelResponsesApiCompactThreshold as c, getReasoningEffortForModel as d, getSmallModel as f, isResponsesApiWebSocketEnabled as g, isResponsesApiWebSearchEnabled as h, getConfig as i, getProviderConfig as l, isResponsesApiContextManagementEnabled as m, getAnthropicApiKey as n, getMessageApiWebSearchModel as o, isMessagesApiEnabled as p, getClaudeTokenMultiplier as r, getModelMappings as s, SUPPORTED_PROVIDER_TYPES as t, getRawProviderConfig as u, listEnabledProviders as v, setModelMappings as w, resolveEffectiveProviderType as x, mergeConfigWithDefaults as y };
394
399
 
395
- //# sourceMappingURL=config-DODTXsGz.js.map
400
+ //# sourceMappingURL=config-Dm9cU9KP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-Dm9cU9KP.js","names":["fs"],"sources":["../src/lib/paths.ts","../src/lib/config.ts"],"sourcesContent":["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 { 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 useResponsesApiContextManagement?: boolean\n modelResponsesApiCompactThresholds?: Record<string, number>\n modelReasoningEfforts?: Record<\n string,\n \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\"\n >\n useMessagesApi?: boolean\n useResponsesApiWebSocket?: boolean\n anthropicApiKey?: string\n useResponsesApiWebSearch?: boolean\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 claudeTokenMultiplier?: number\n}\n\nexport interface ModelConfig {\n temperature?: number\n topP?: number\n topK?: number\n extraBody?: Record<string, unknown>\n contextCache?: boolean\n pricing?: TokenUsagePricingConfig\n supportPdf?: boolean\n toolContentSupportType?: Array<ToolContentSupportType>\n type?: ProviderType\n}\n\nexport interface TokenUsagePricingTier {\n cachedInput?: number\n cacheCreationInput?: number\n explicitCachedInput?: number\n input?: number\n maxInputTokens?: number\n output?: number\n}\n\nexport interface TokenUsagePricingConfig extends TokenUsagePricingTier {\n tiers?: Array<TokenUsagePricingTier>\n}\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\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 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 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\nconst modelResponsesApiCompactThresholds = {\n \"gpt-5.4\": 272_000 * 0.8,\n \"gpt-5.5\": 272_000 * 0.8,\n}\n\nconst defaultConfig: AppConfig = {\n auth: {\n apiKeys: [],\n },\n providers: {},\n modelMappings: {},\n extraPrompts: {\n \"gpt-5-mini\": gpt5ExplorationPrompt,\n \"gpt-5.3-codex\": gpt5CommentaryPrompt,\n \"gpt-5.4-mini\": gpt5CommentaryPrompt,\n \"gpt-5.4\": gpt5CommentaryPrompt,\n \"gpt-5.5\": gpt5CommentaryPrompt,\n },\n smallModel: \"gpt-5-mini\",\n useResponsesApiContextManagement: true,\n modelResponsesApiCompactThresholds,\n modelReasoningEfforts: {\n \"gpt-5-mini\": \"low\",\n \"gpt-5.3-codex\": \"xhigh\",\n \"gpt-5.4-mini\": \"xhigh\",\n \"gpt-5.4\": \"xhigh\",\n \"gpt-5.5\": \"xhigh\",\n },\n useMessagesApi: true,\n useResponsesApiWebSocket: true,\n useResponsesApiWebSearch: true,\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 fs.mkdirSync(PATHS.APP_DIR, { recursive: true })\n fs.writeFileSync(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\n \"utf8\",\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 fs.writeFileSync(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\n \"utf8\",\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\nfunction 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\nfunction writeConfigToDisk(config: AppConfig): void {\n fs.mkdirSync(PATHS.APP_DIR, { recursive: true })\n fs.writeFileSync(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(config, null, 2)}\\n`,\n \"utf8\",\n )\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\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\n const hasExtraPromptChanges = missingExtraPromptModels.length > 0\n const hasReasoningEffortChanges = missingReasoningEffortModels.length > 0\n const hasResponsesApiCompactThresholdChanges =\n missingResponsesApiCompactThresholdModels.length > 0\n\n if (\n !hasExtraPromptChanges\n && !hasReasoningEffortChanges\n && !hasResponsesApiCompactThresholdChanges\n ) {\n return { mergedConfig: config, changed: false }\n }\n\n return {\n mergedConfig: {\n ...config,\n extraPrompts: {\n ...defaultExtraPrompts,\n ...extraPrompts,\n },\n modelResponsesApiCompactThresholds: {\n ...defaultResponsesApiCompactThresholds,\n ...responsesApiCompactThresholds,\n },\n modelReasoningEfforts: {\n ...defaultModelReasoningEfforts,\n ...modelReasoningEfforts,\n },\n },\n changed: true,\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 getExtraPromptForModel(model: string): string {\n const config = getConfig()\n return config.extraPrompts?.[model] ?? \"\"\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 cachedConfig = 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 isResponsesApiContextManagementEnabled(): boolean {\n const config = getConfig()\n return config.useResponsesApiContextManagement ?? true\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\" {\n const config = getConfig()\n return config.modelReasoningEfforts?.[model] ?? \"high\"\n}\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 cachedConfig = 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 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\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 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 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 getClaudeTokenMultiplier(): number {\n const config = getConfig()\n return config.claudeTokenMultiplier ?? 1.15\n}\n"],"mappings":";;;;;;;AAIA,MAAM,WAAW,QAAQ,IAAI,uBAAuB,MAAM,IAAI;AAC9D,MAAM,oBAAoB,QAAQ,IAAI,6BAA6B,SAAS;AAE5E,MAAM,cAAc,KAAK,KAAK,GAAG,SAAS,EAAE,UAAU,SAAS,cAAc;AAC7E,MAAM,UAAU,QAAQ,IAAI,oBAAoB;AAUhD,MAAa,QAAQ;CACnB;CACA,mBAVwB,KAAK,KAC7B,SACA,UACA,oBAAoB,eAOpB;CACA,uBAN4B,KAAK,KAAK,SAAS,yBAM/C;CACA,aANkB,KAAK,KAAK,SAAS,cAMrC;CACD;AAED,eAAsB,cAA6B;CACjD,MAAMA,KAAG,MAAM,KAAK,KAAK,MAAM,SAAS,SAAS,EAAE,EAAE,WAAW,MAAM,CAAC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OAAO,aAAa,EAAE,CACpC,CAAC,QAAQ,SAAS,kBAAkB,KAAK,KAAK,KAAK;;AAGzE,SAAgB,uBAAuB,MAAuB;CAC5D,OAAO,KAAK,MAAM,KAAK;;AAGzB,SAAgB,uBAAgC;CAE9C,OADe,WACF,CAAC,kBAAkB;;AAGlC,SAAgB,iCAA0C;CAExD,OADe,WACF,CAAC,4BAA4B;;AAG5C,SAAgB,qBAAyC;CAEvD,OADe,WACF,CAAC,mBAAmB,QAAQ,IAAI,qBAAqB,KAAA;;AAGpE,SAAgB,iCAA0C;CAExD,OADe,WACF,CAAC,4BAA4B;;AAG5C,SAAgB,8BAAkD;CAEhE,MAAM,QADS,WACK,CAAC,4BAA4B;CACjD,OAAO,SAAS,MAAM,MAAM,CAAC,SAAS,IAAI,QAAQ,KAAA;;AAGpD,SAAgB,2BAAmC;CAEjD,OADe,WACF,CAAC,yBAAyB"}
@@ -1,4 +1,4 @@
1
- import { u as getRawProviderConfig, v as listEnabledProviders, w as PATHS } from "./config-DODTXsGz.js";
1
+ import { E as PATHS, u as getRawProviderConfig, v as listEnabledProviders } from "./config-Dm9cU9KP.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-CjJqlHl_.js.map
92
+ //# sourceMappingURL=debug-JJUz1hBb.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"debug-CjJqlHl_.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"}
1
+ {"version":3,"file":"debug-JJUz1hBb.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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,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-BlEMGJZf.js");
26
- const { debug } = await import("./debug-CjJqlHl_.js");
25
+ const { auth } = await import("./auth-CfRmN-aH.js");
26
+ const { debug } = await import("./debug-JJUz1hBb.js");
27
27
  const { mcp } = await import("./mcp-BseuqgHR.js");
28
- const { start } = await import("./start-JmZKtMkn.js");
28
+ const { start } = await import("./start-CDw9cq41.js");
29
29
  await runMain(defineCommand({
30
30
  meta: {
31
31
  name: "copilot-api",
@@ -1,5 +1,5 @@
1
- import { S as setModelMappings, a as getExtraPromptForModel, c as getModelResponsesApiCompactThreshold$1, d as getReasoningEffortForModel, f as getSmallModel, g as isResponsesApiWebSocketEnabled, h as isResponsesApiWebSearchEnabled, i as getConfig, l as getProviderConfig, m as isResponsesApiContextManagementEnabled, n as getAnthropicApiKey, o as getMessageApiWebSearchModel, p as isMessagesApiEnabled, r as getClaudeTokenMultiplier, s as getModelMappings, u as getRawProviderConfig, v as listEnabledProviders, w as PATHS, x as resolveMappedModel } from "./config-DODTXsGz.js";
2
- import { C as prepareMessageProxyHeaders, E as compactMessageSections, F as createPooledWebSocketStream, I as createWebSocketUrl, L as state, M as generateTraceId, N as requestContext, O as compactSystemPromptStarts, P as resolveTraceId$1, R as HTTPError, S as prepareInteractionHeaders, T as compactAutoContinuePromptStarts, b as copilotWebSocketHeaders, d as generateRequestIdFromPayload, f as getRootSessionId, g as getCopilotUsage, h as parseUserIdMetadata, j as forwardCodexResponses, m as isNullish, p as getUUID, r as setupCodexToken, v as copilotBaseUrl, x as prepareForCompact, y as copilotHeaders, z as forwardError } from "./token-BOovYuN5.js";
1
+ import { C as resolveProviderAuthType, E as PATHS, S as resolveMappedModel, a as getExtraPromptForModel, c as getModelResponsesApiCompactThreshold$1, d as getReasoningEffortForModel, f as getSmallModel, g as isResponsesApiWebSocketEnabled, h as isResponsesApiWebSearchEnabled, i as getConfig, l as getProviderConfig, m as isResponsesApiContextManagementEnabled, n as getAnthropicApiKey, o as getMessageApiWebSearchModel, p as isMessagesApiEnabled, r as getClaudeTokenMultiplier, s as getModelMappings, u as getRawProviderConfig, v as listEnabledProviders, w as setModelMappings, x as resolveEffectiveProviderType } from "./config-Dm9cU9KP.js";
2
+ import { C as prepareMessageProxyHeaders, E as compactMessageSections, F as createPooledWebSocketStream, I as createWebSocketUrl, L as state, M as generateTraceId, N as requestContext, O as compactSystemPromptStarts, P as resolveTraceId$1, R as HTTPError, S as prepareInteractionHeaders, T as compactAutoContinuePromptStarts, b as copilotWebSocketHeaders, d as generateRequestIdFromPayload, f as getRootSessionId, g as getCopilotUsage, h as parseUserIdMetadata, j as forwardCodexResponses, m as isNullish, p as getUUID, r as setupCodexToken, v as copilotBaseUrl, x as prepareForCompact, y as copilotHeaders, z as forwardError } from "./token-CejO9iGT.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-OX6iPJ9D.js";
4
4
  import consola from "consola";
5
5
  import { createHash } from "node:crypto";
@@ -999,7 +999,8 @@ const COPILOT_NANO_AIU_TO_COST_NANOS = COST_NANOS_PER_UNIT / 1e11;
999
999
  const BUILTIN_PROVIDER_CURRENCIES = {
1000
1000
  codex: "USD",
1001
1001
  dashscope: "CNY",
1002
- deepseek: "CNY"
1002
+ deepseek: "CNY",
1003
+ "opencode-go": "USD"
1003
1004
  };
1004
1005
  const BUILTIN_PROVIDER_PRICING = {
1005
1006
  codex: {
@@ -1081,6 +1082,73 @@ const BUILTIN_PROVIDER_PRICING = {
1081
1082
  input: 3,
1082
1083
  output: 6
1083
1084
  }
1085
+ },
1086
+ "opencode-go": {
1087
+ "glm-5.2": {
1088
+ cachedInput: .26,
1089
+ input: 1.4,
1090
+ output: 4.4
1091
+ },
1092
+ "deepseek-v4-flash": {
1093
+ cachedInput: .0028,
1094
+ input: .14,
1095
+ output: .28
1096
+ },
1097
+ "deepseek-v4-pro": {
1098
+ cachedInput: .0145,
1099
+ input: 1.74,
1100
+ output: 3.48
1101
+ },
1102
+ "kimi-k2.7-code": {
1103
+ cachedInput: .19,
1104
+ input: .95,
1105
+ output: 4
1106
+ },
1107
+ "mimo-v2.5": {
1108
+ cachedInput: .0028,
1109
+ input: .14,
1110
+ output: .28
1111
+ },
1112
+ "mimo-v2.5-pro": {
1113
+ cachedInput: .0145,
1114
+ input: 1.74,
1115
+ output: 3.48
1116
+ },
1117
+ "qwen3.7-plus": { tiers: [{
1118
+ cacheCreationInput: .5,
1119
+ cachedInput: .04,
1120
+ input: .4,
1121
+ maxInputTokens: 2e5,
1122
+ output: 1.6
1123
+ }, {
1124
+ cacheCreationInput: 1.5,
1125
+ cachedInput: .12,
1126
+ input: 1.2,
1127
+ maxInputTokens: 256e3,
1128
+ output: 4.8
1129
+ }] },
1130
+ "qwen3.7-max": {
1131
+ cacheCreationInput: 3.125,
1132
+ cachedInput: .5,
1133
+ input: 2.5,
1134
+ output: 7.5
1135
+ },
1136
+ "minimax-m2.5": {
1137
+ cachedInput: .03,
1138
+ input: .3,
1139
+ output: 1.2
1140
+ },
1141
+ "minimax-m3": { tiers: [{
1142
+ cachedInput: .02,
1143
+ input: .1,
1144
+ maxInputTokens: 2e5,
1145
+ output: .4
1146
+ }, {
1147
+ cachedInput: .04,
1148
+ input: .2,
1149
+ maxInputTokens: 512e3,
1150
+ output: .8
1151
+ }] }
1084
1152
  }
1085
1153
  };
1086
1154
  function resolveTokenUsageCost(input) {
@@ -1379,7 +1447,7 @@ const logger$9 = createHandlerLogger("provider-chat-completions-handler");
1379
1447
  async function handleProviderChatCompletionsForProvider(c, options) {
1380
1448
  const { payload, provider } = options;
1381
1449
  const providerConfig = await resolveProviderConfig(provider);
1382
- if (providerConfig?.type !== "openai-compatible") return c.json({ error: {
1450
+ if (!providerConfig || resolveEffectiveProviderType(providerConfig, payload.model) !== "openai-compatible") return c.json({ error: {
1383
1451
  message: `Provider '${provider}' does not support the /v1/chat/completions endpoint`,
1384
1452
  type: "invalid_request_error"
1385
1453
  } }, 400);
@@ -5034,6 +5102,7 @@ const OPENAI_COMPATIBLE_CONTEXT_CACHE_ROLES = new Set([
5034
5102
  "assistant",
5035
5103
  "tool"
5036
5104
  ]);
5105
+ const isDashScopeAliyunProvider = (providerConfig) => providerConfig.name === "dashscope" || providerConfig.baseUrl.includes("aliyuncs.com");
5037
5106
  async function handleProviderMessages(c) {
5038
5107
  const provider = c.req.param("provider");
5039
5108
  return await handleProviderMessagesForProvider(c, {
@@ -5050,13 +5119,14 @@ async function handleProviderMessagesForProvider(c, options) {
5050
5119
  } }, 404);
5051
5120
  try {
5052
5121
  const modelConfig = providerConfig.models?.[payload.model];
5122
+ const effectiveType = resolveEffectiveProviderType(providerConfig, payload.model);
5053
5123
  debugJson(logger$6, "provider.messages.request", {
5054
5124
  payload,
5055
5125
  provider
5056
5126
  });
5057
5127
  normalizeSystemMessages(payload);
5058
5128
  applyModelDefaults(payload, modelConfig);
5059
- if (providerConfig.type === "openai-responses") {
5129
+ if (effectiveType === "openai-responses") {
5060
5130
  if (hasWebSearchServerTool(payload)) {
5061
5131
  if (isWebSearchOnlyRequest(payload)) return await handleOpenAIResponsesProviderWebSearchMessages(c, {
5062
5132
  modelConfig,
@@ -5073,7 +5143,7 @@ async function handleProviderMessagesForProvider(c, options) {
5073
5143
  providerConfig
5074
5144
  });
5075
5145
  }
5076
- if (providerConfig.type === "openai-compatible") {
5146
+ if (effectiveType === "openai-compatible") {
5077
5147
  stripWebSearchServerTool(payload);
5078
5148
  return await handleOpenAICompatibleProviderMessages(c, {
5079
5149
  modelConfig,
@@ -5087,7 +5157,11 @@ async function handleProviderMessagesForProvider(c, options) {
5087
5157
  payload,
5088
5158
  provider
5089
5159
  });
5090
- const upstreamResponse = await forwardProviderMessages(providerConfig, payload, c.req.raw.headers);
5160
+ const upstreamResponse = await forwardProviderMessages(effectiveType === providerConfig.type ? providerConfig : {
5161
+ ...providerConfig,
5162
+ type: effectiveType,
5163
+ authType: resolveProviderAuthType(providerConfig.name, void 0, effectiveType)
5164
+ }, payload, c.req.raw.headers);
5091
5165
  if (!upstreamResponse.ok) {
5092
5166
  logger$6.error("Failed to create responses", upstreamResponse);
5093
5167
  throw new HTTPError("Failed to create responses", upstreamResponse);
@@ -5255,7 +5329,7 @@ const applyOpenAICompatibleExtraBodyThinkingBudget = (payload, options) => {
5255
5329
  };
5256
5330
  const handleOpenAICompatibleProviderMessages = async (c, options) => {
5257
5331
  const { modelConfig, payload, provider, providerConfig } = options;
5258
- const openAIPayload = createOpenAICompatiblePayload(payload, modelConfig);
5332
+ const openAIPayload = createOpenAICompatiblePayload(payload, modelConfig, providerConfig);
5259
5333
  debugJson(logger$6, "provider.messages.openai_compatible.request", {
5260
5334
  payload: openAIPayload,
5261
5335
  provider
@@ -5282,12 +5356,14 @@ const handleOpenAICompatibleProviderMessages = async (c, options) => {
5282
5356
  provider
5283
5357
  });
5284
5358
  };
5285
- const createOpenAICompatiblePayload = (payload, modelConfig) => {
5359
+ const createOpenAICompatiblePayload = (payload, modelConfig, providerConfig) => {
5286
5360
  const openAIPayload = translateToOpenAI(payload, {
5287
5361
  supportPdf: modelConfig?.supportPdf,
5288
5362
  toolContentSupportType: modelConfig?.toolContentSupportType ?? []
5289
5363
  });
5290
- applyOpenAICompatibleThinkingBudget(openAIPayload, payload);
5364
+ const isDashScopeProvider = isDashScopeAliyunProvider(providerConfig);
5365
+ if (isDashScopeProvider) applyOpenAICompatibleThinkingBudget(openAIPayload, payload);
5366
+ else delete openAIPayload.thinking_budget;
5291
5367
  if (payload.top_k !== void 0) openAIPayload.top_k = payload.top_k;
5292
5368
  if (openAIPayload.stream) openAIPayload.stream_options = { include_usage: true };
5293
5369
  normalizeOpenAICompatibleReasoningContent(openAIPayload);
@@ -5298,7 +5374,7 @@ const createOpenAICompatiblePayload = (payload, modelConfig) => {
5298
5374
  applyMissingExtraBody(openAIPayload, { extraBody: modelConfig?.extraBody });
5299
5375
  applyOpenAICompatibleExtraBodyThinkingBudget(openAIPayload, { extraBody: modelConfig?.extraBody });
5300
5376
  if (!Object.hasOwn(openAIPayload, "parallel_tool_calls")) openAIPayload.parallel_tool_calls = true;
5301
- if (modelConfig?.contextCache !== false) applyOpenAICompatibleContextCache(openAIPayload);
5377
+ if (modelConfig?.contextCache ?? isDashScopeProvider) applyOpenAICompatibleContextCache(openAIPayload);
5302
5378
  return openAIPayload;
5303
5379
  };
5304
5380
  const normalizeOpenAICompatibleReasoningContent = (payload) => {
@@ -6169,7 +6245,7 @@ async function handleProviderResponsesForProvider(c, options) {
6169
6245
  provider
6170
6246
  });
6171
6247
  const providerConfig = await resolveProviderConfig(provider);
6172
- if (providerConfig?.type !== "openai-responses") return c.json({ error: {
6248
+ if (!providerConfig || resolveEffectiveProviderType(providerConfig, payload.model) !== "openai-responses") return c.json({ error: {
6173
6249
  message: `Provider '${provider}' does not support the /v1/responses endpoint`,
6174
6250
  type: "invalid_request_error"
6175
6251
  } }, 400);
@@ -6585,4 +6661,4 @@ server.route("/:provider/v1/models", providerModelRoutes);
6585
6661
  //#endregion
6586
6662
  export { server };
6587
6663
 
6588
- //# sourceMappingURL=server-Bh5h_1pZ.js.map
6664
+ //# sourceMappingURL=server-JtVsUm_H.js.map