@jeffreycao/copilot-api 2.3.16 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/README.zh-CN.md +6 -6
- package/dist/auth-BCZdnMmK.js +2 -0
- package/dist/{auth-DmscMMR2.js → auth-DvqwYkJr.js} +58 -13
- package/dist/auth-DvqwYkJr.js.map +1 -0
- package/dist/{config-ByEK-9s6.js → config-DVWu2hKk.js} +3 -3
- package/dist/config-DVWu2hKk.js.map +1 -0
- package/dist/{debug-BHOitPm3.js → debug-DwoWAiuC.js} +2 -2
- package/dist/{debug-BHOitPm3.js.map → debug-DwoWAiuC.js.map} +1 -1
- package/dist/main.js +3 -3
- package/dist/{models-BWI-BuVr.js → models-DKNAPa_j.js} +2 -2
- package/dist/{models-BWI-BuVr.js.map → models-DKNAPa_j.js.map} +1 -1
- package/dist/server-HBeQNO83.js +12044 -0
- package/dist/server-HBeQNO83.js.map +1 -0
- package/dist/{start-CCE-hQBT.js → start-Bxq46GxM.js} +6 -6
- package/dist/{start-CCE-hQBT.js.map → start-Bxq46GxM.js.map} +1 -1
- package/dist/{token-BYTz7z9X.js → token-D0GGk3E8.js} +2 -2
- package/dist/{token-BYTz7z9X.js.map → token-D0GGk3E8.js.map} +1 -1
- package/package.json +3 -1
- package/pages/index.html +106 -32
- package/dist/auth-BsFMCDdr.js +0 -2
- package/dist/auth-DmscMMR2.js.map +0 -1
- package/dist/config-ByEK-9s6.js.map +0 -1
- package/dist/server-DZ2B4MKu.js +0 -10845
- package/dist/server-DZ2B4MKu.js.map +0 -1
package/README.md
CHANGED
|
@@ -585,16 +585,16 @@ The dashboard provides a user-friendly interface to view your Copilot usage data
|
|
|
585
585
|
|
|
586
586
|
- **API Endpoint URL**: The dashboard is pre-configured to fetch data from your local server endpoint via a URL query parameter. You can manually switch this to any other compatible API endpoint.
|
|
587
587
|
- **API Key Authentication**: If API Key authentication is enabled, enter a raw API key (sent as the `x-api-key` header) or `Authorization: Bearer <key>`. Credentials are remembered in the browser's local storage per endpoint origin, and switching to a different endpoint origin does not automatically send the previous credential.
|
|
588
|
-
- **Period Selector**: Choose from
|
|
588
|
+
- **Period Selector**: Choose from six time ranges: `today` (the current local calendar day so far), `this_week` (Monday at 00:00 through now), `last_7_days` (the rolling seven calendar days through now), `this_month` (the first day of the current month at 00:00 through now), `last_30_days` (the rolling 30 calendar days through now), and `lifetime` (the earliest recorded event through now). Today is selected by default, and the exact date range appears next to the selector. The URL query parameter updates automatically when you switch, making it easy to bookmark and share. The legacy values `day`, `week`, and `month` are still accepted and mapped to their new equivalents.
|
|
589
589
|
- **Fetch Data**: Click the "Refresh" button to load or refresh the usage data. The dashboard also fetches data automatically on page load.
|
|
590
590
|
- **Copilot Quotas**: View quota usage for services such as Chat and Completions via progress bars. Hover over a card to see used/remaining details.
|
|
591
591
|
- **Token Usage Metric Cards**: See a summary of Total, Input, Output, Cache Read, Cache Write, Requests, and estimated cost for the current period.
|
|
592
|
-
- **Trend Chart
|
|
592
|
+
- **Trend Chart**: An interactive line chart with model and metric filters for the selected period. Click a data point to inspect the usage breakdown for a day; Lifetime chart data is sampled from the daily buckets and capped at 180 points for readability.
|
|
593
593
|
- **Model Breakdown Table**: A per-model summary of requests, input/output/cache tokens, and estimated cost for the selected period.
|
|
594
594
|
- **Request Events (Paginated)**: A time-sorted list of request event records with pagination support, showing timestamps, models, request IDs, and token counts.
|
|
595
595
|
- **Detailed Information**: See the full JSON response from the API for a detailed breakdown of all available usage statistics.
|
|
596
596
|
- **URL-based Configuration**: You can also specify the API endpoint and period directly via `endpoint` and `period` query parameters. For example:
|
|
597
|
-
`http://localhost:4141/usage-viewer?endpoint=http://your-api-server/usage&period=
|
|
597
|
+
`http://localhost:4141/usage-viewer?endpoint=http://your-api-server/usage&period=this_week`
|
|
598
598
|
|
|
599
599
|
### Usage Viewer Screenshot
|
|
600
600
|
|
|
@@ -707,8 +707,8 @@ Gateway API keys live under `auth.apiKeys` in `config.json`. Manage them with `c
|
|
|
707
707
|
- **providers:** Global upstream provider map. Each provider key (for example `dashscope`) becomes a route prefix (`/dashscope/v1/messages`). Supports `type: "anthropic"`, `type: "openai-compatible"`, and `type: "openai-responses"`. Top-level clients can also use `model: "dashscope/model-id"` with `/v1/messages`, `/v1/messages/count_tokens`, `/v1/responses`, and `/v1/chat/completions`; the gateway strips the `dashscope/` prefix before forwarding upstream. The `/v1/responses` route for `anthropic` and `openai-compatible` providers uses the Responses Lite → Messages adapter; `openai-compatible` providers then reuse the Messages → Chat translation. Codex clients (`User-Agent` starting with `codex`) also use the adapter for non-`gpt-*` models on `openai-responses` providers. `GET /v1/models` aggregates enabled provider models with `provider/model-id` IDs, while the top-level Codex-UA catalog also merges these adaptable models as `use_responses_lite` entries (except DeepSeek models, which use `use_responses_lite: false` and `tool_mode: null`). Use `GET /dashscope/v1/models` for a single provider's raw model list.
|
|
708
708
|
- `enabled` defaults to `true` if omitted.
|
|
709
709
|
- `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`.
|
|
710
|
-
- `apiKey` is used as the upstream credential value and is required
|
|
711
|
-
- `authType` (optional): Controls
|
|
710
|
+
- `apiKey` is used as the upstream credential value and is required unless `authType` is `azure-entra`.
|
|
711
|
+
- `authType` (optional): Controls upstream authentication. Supports `x-api-key`, `authorization`, and `azure-entra` for regular providers. Anthropic providers default to `x-api-key`; OpenAI-compatible and OpenAI Responses providers default to `authorization`. `authorization` sends `Authorization: Bearer <apiKey>`. `azure-entra` uses Azure Identity's `DefaultAzureCredential` with the `https://cognitiveservices.azure.com/.default` scope, sends the resulting bearer token, and does not require `apiKey`. For an Azure OpenAI v1 endpoint, use a provider such as `{ "type": "openai-compatible", "baseUrl": "https://<resource-name>.openai.azure.com/openai", "authType": "azure-entra" }`. Authenticate locally with `az login`, use a managed identity in Azure, or set the standard `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET` environment variables. `oauth2` is reserved for the built-in `codex` provider and is written automatically by `auth login --provider codex`.
|
|
712
712
|
- `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.
|
|
713
713
|
- `models` (optional): Per-model configuration map. Each key is a model ID (matching the model name in requests), and the value is:
|
|
714
714
|
- `temperature` (optional): Default temperature value used when the request does not specify one.
|
|
@@ -719,7 +719,7 @@ Gateway API keys live under `auth.apiKeys` in `config.json`. Manage them with `c
|
|
|
719
719
|
- `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. Applied on both `/v1/messages` and `/v1/chat/completions` routes.
|
|
720
720
|
- `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.
|
|
721
721
|
- `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. The Copilot main flow uses the same string-only default, because some Copilot models do not support array or image tool content either.
|
|
722
|
-
- `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`).
|
|
722
|
+
- `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`). Providers configured with `azure-entra` keep their Entra bearer credential instead of falling back to the overridden type's default.
|
|
723
723
|
- `contextWindow` (optional): Context window token limit advertised when this model is merged into the Codex-UA model catalog; for example, `1000000` declares a 1M-token context window. Missing configured values use upstream metadata first, then the built-in non-GPT model catalog, then `256000`.
|
|
724
724
|
- `maxOutputTokens` (optional): Maximum output token limit advertised in the Codex-UA model catalog. Missing configured values use upstream metadata first, then the built-in non-GPT model catalog, where defaults are capped at `64000`, then `32000`.
|
|
725
725
|
- `inputModalities` (optional): Supported Codex input types. Use `["text", "image"]` for a model that accepts both text and images. Missing configured values use upstream metadata before the built-in non-GPT model catalog. GPT models do not receive these built-in capability defaults and continue to use the native Codex catalog or upstream metadata.
|
package/README.zh-CN.md
CHANGED
|
@@ -623,16 +623,16 @@ cp plugin/opencode/subagent-marker.js ~/.config/opencode/plugins/
|
|
|
623
623
|
|
|
624
624
|
- **API Endpoint URL**:通过 URL 查询参数指定 API endpoints,默认指向本地服务。支持手动切换为其他兼容 endpoints。
|
|
625
625
|
- **API Key 认证**:如果启用了 API Key 认证,可填入原始 API key(默认通过 `x-api-key` 请求头发送)或 `Authorization: Bearer <key>`。凭据会按 endpoint origin 保存在浏览器本地存储中;切换到不同 endpoint origin 时,不会自动携带其他 origin 的凭据。
|
|
626
|
-
- **Period
|
|
626
|
+
- **Period 选择器**:支持六种时间范围:`today`(当前本地日历日至今)、`this_week`(本周一 00:00 至现在)、`last_7_days`(滚动 7 个日历日至现在)、`this_month`(本月 1 日 00:00 至现在)、`last_30_days`(滚动 30 个日历日至现在)和 `lifetime`(从最早记录事件至现在)。默认选择 Today,选择器旁会显示具体日期范围;切换时 URL 参数会自动同步,方便收藏和分享。旧版取值 `day`、`week`、`month` 仍被兼容,会自动映射到对应的新值。
|
|
627
627
|
- **Fetch Data**:点击 "Refresh" 按钮加载或刷新使用数据。页面加载时也会自动拉取数据。
|
|
628
628
|
- **Copilot Quotas 额度**:通过进度条展示 Chat、Completions 等不同服务的额度使用情况,悬停可查看已用/剩余详情。
|
|
629
629
|
- **Token Usage 指标卡片**:汇总当前周期的 Total、Input、Output、Cache Read、Cache Write、Requests 和预估费用。
|
|
630
|
-
-
|
|
630
|
+
- **趋势图**:提供按所选周期、模型和指标筛选的折线趋势图,点击数据点可查看用量明细;Lifetime 图表数据从每日数据桶中采样,最多显示 180 个点,以便查看长期趋势。
|
|
631
631
|
- **Model Breakdown 表格**:按模型维度列出周期内的请求数、输入/输出/缓存 token 和预计费用。
|
|
632
632
|
- **Request Events 分页列表**:按时间排序的请求事件记录,支持分页浏览,含时间戳、模型、请求 ID 和 token 用量。
|
|
633
633
|
- **Detailed Information**:展示 API 返回的完整 JSON 响应,便于深入分析所有可用统计数据。
|
|
634
634
|
- **URL-based Configuration**:也可通过 `endpoint` 和 `period` 查询参数直接指定 API 端点与时间范围。例如:
|
|
635
|
-
`http://localhost:4141/usage-viewer?endpoint=http://your-api-server/usage&period=
|
|
635
|
+
`http://localhost:4141/usage-viewer?endpoint=http://your-api-server/usage&period=this_week`
|
|
636
636
|
|
|
637
637
|
### Usage Viewer 截图
|
|
638
638
|
|
|
@@ -751,8 +751,8 @@ Copilot API 现在使用子命令结构,主要命令包括:
|
|
|
751
751
|
- **providers:** 全局上游 provider 映射。每个 provider key(例如 `dashscope`)都会变成一个路由前缀(`/dashscope/v1/messages`)。支持 `type: "anthropic"`、`type: "openai-compatible"` 和 `type: "openai-responses"`。顶层客户端也可以在 `/v1/messages`、`/v1/messages/count_tokens`、`/v1/responses` 和 `/v1/chat/completions` 中使用 `model: "dashscope/model-id"`;AI gateway 会在转发上游前移除 `dashscope/` 前缀。`anthropic` 和 `openai-compatible` provider 的 `/v1/responses` 会通过 Responses Lite → Messages 适配;其中 `openai-compatible` provider 再复用 Messages → Chat 翻译。Codex 客户端(`User-Agent` 以 `codex` 开头)在 `openai-responses` provider 上请求非 `gpt-*` 模型时同样走该适配路径。`GET /v1/models` 会聚合已启用 provider 的模型,并以 `provider/model-id` 形式返回;Codex UA 的顶层模型列表还会把这些可适配模型合并为 `use_responses_lite` 模型(DeepSeek 模型除外,它们使用 `use_responses_lite: false` 和 `tool_mode: null`)。单个 provider 的原始模型列表仍可使用 `GET /dashscope/v1/models`。
|
|
752
752
|
- `enabled`:可选,若省略则默认为 `true`。
|
|
753
753
|
- `baseUrl`:provider API 的基础 URL,不要带结尾的 endpoint。Anthropic provider 不要带 `/v1/messages`;OpenAI 兼容 provider 不要带 `/v1/chat/completions`;OpenAI Responses provider 不要带 `/v1/responses`。
|
|
754
|
-
- `apiKey
|
|
755
|
-
- `authType
|
|
754
|
+
- `apiKey`:作为上游凭据值使用;除 `authType` 为 `azure-entra` 外,普通 provider 必须配置。
|
|
755
|
+
- `authType`:可选,控制上游认证方式。普通 provider 支持 `x-api-key`、`authorization` 和 `azure-entra`。Anthropic provider 默认 `x-api-key`;OpenAI 兼容和 OpenAI Responses provider 默认 `authorization`。`authorization` 会发送 `Authorization: Bearer <apiKey>`。`azure-entra` 使用 Azure Identity 的 `DefaultAzureCredential` 和 `https://cognitiveservices.azure.com/.default` scope 获取并发送 Bearer token,不需要配置 `apiKey`。Azure OpenAI v1 endpoint 可配置为 `{ "type": "openai-compatible", "baseUrl": "https://<resource-name>.openai.azure.com/openai", "authType": "azure-entra" }`。本地可先执行 `az login`,在 Azure 中可使用托管身份,也可设置标准的 `AZURE_TENANT_ID`、`AZURE_CLIENT_ID` 和 `AZURE_CLIENT_SECRET` 环境变量。`oauth2` 仅保留给内置 `codex` provider,并由 `auth login --provider codex` 自动写入。
|
|
756
756
|
- `pricingCurrency`:可选,provider 维度的 token 费用币种,例如 `USD` 或 `CNY`。快捷 provider 默认 DashScope、DeepSeek 为 `CNY`,Codex、Kimi、OpenCode Go、OpenRouter 为 `USD`。费用按币种分别汇总,不做汇率换算。
|
|
757
757
|
- `models`:可选,按模型 ID 配置的映射。每个键为请求中的模型名,值支持:
|
|
758
758
|
- `temperature`:可选,当请求未指定时使用的默认温度。
|
|
@@ -763,7 +763,7 @@ Copilot API 现在使用子命令结构,主要命令包括:
|
|
|
763
763
|
- `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`。同时适用于 `/v1/messages` 和 `/v1/chat/completions` 路由。
|
|
764
764
|
- `supportPdf`:可选,控制该模型是否支持 PDF/document content。默认 `false`,不支持时会把 PDF 转成提示文本;设为 `true` 时会把 PDF/document 转成 OpenAI Chat Completions 的 file part。
|
|
765
765
|
- `toolContentSupportType`:可选,配置该模型的 tool result content 支持能力,值为 `array`、`image`、`pdf` 的数组。provider 侧未配置时默认只发送 string tool content。若 `supportPdf` 为 `true` 但这里不包含 `pdf`,tool result 里的 file part 会被转成 user role 消息。Copilot 主链路同样默认只发送 string tool content,因为部分 Copilot 模型也不支持数组或图片形式的 tool content。
|
|
766
|
-
- `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
|
|
766
|
+
- `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`)。配置了 `azure-entra` 的 provider 在覆盖 type 时会保留 Entra bearer 凭证,而不会回退到覆盖后 type 的默认值。
|
|
767
767
|
- `contextWindow`:可选,模型合并到 Codex UA 模型列表时声明的上下文窗口 token 上限;例如 `1000000` 表示 1M token 上下文。用户未配置时依次使用上游元数据、非 GPT 模型的内置目录和 `256000`。
|
|
768
768
|
- `maxOutputTokens`:可选,Codex UA 模型列表中声明的最大输出 token 数。用户未配置时优先使用上游元数据,其次使用非 GPT 模型的内置目录(内置默认值最高为 `64000`),最后默认为 `32000`。
|
|
769
769
|
- `inputModalities`:可选,Codex 支持的输入类型;模型同时支持文本和图片时配置为 `["text", "image"]`。用户未配置时优先使用上游元数据,再使用非 GPT 模型的内置目录。GPT 模型不注入这些内置能力默认值,继续使用原生 Codex catalog 或上游元数据。
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { M as setConfiguredApiKeys, N as PATHS, P as ensurePaths, a as normalizeProviderBaseUrl, c as setProviderConfig, n as getRawProviderConfig, r as isSupportedProviderType, y as SUPPORTED_PROVIDER_TYPES } from "./config-
|
|
2
|
-
import { A as getConfiguredApiKeys, K as state, M as loginCodex, a as setupGitHubToken, n as persistCodexCredentials } from "./token-
|
|
1
|
+
import { M as setConfiguredApiKeys, N as PATHS, P as ensurePaths, a as normalizeProviderBaseUrl, c as setProviderConfig, n as getRawProviderConfig, r as isSupportedProviderType, y as SUPPORTED_PROVIDER_TYPES } from "./config-DVWu2hKk.js";
|
|
2
|
+
import { A as getConfiguredApiKeys, K as state, M as loginCodex, a as setupGitHubToken, n as persistCodexCredentials } from "./token-D0GGk3E8.js";
|
|
3
3
|
import { defineCommand } from "citty";
|
|
4
4
|
import consola from "consola";
|
|
5
5
|
//#region src/lib/quick-providers.ts
|
|
@@ -36,6 +36,52 @@ const QUICK_PROVIDER_CONFIGS = {
|
|
|
36
36
|
}
|
|
37
37
|
};
|
|
38
38
|
//#endregion
|
|
39
|
+
//#region src/lib/interactive-prompt.ts
|
|
40
|
+
function shouldUseClackPrompt(runtime = {
|
|
41
|
+
bunVersion: process.versions.bun,
|
|
42
|
+
platform: process.platform,
|
|
43
|
+
stdinIsTTY: process.stdin.isTTY,
|
|
44
|
+
stdoutIsTTY: process.stdout.isTTY,
|
|
45
|
+
stdoutIsTTYStream: typeof process.stdout.getColorDepth === "function"
|
|
46
|
+
}) {
|
|
47
|
+
return Boolean(runtime.platform === "win32" && runtime.bunVersion && runtime.stdinIsTTY && runtime.stdoutIsTTY && runtime.stdoutIsTTYStream);
|
|
48
|
+
}
|
|
49
|
+
function getCancelValue(options) {
|
|
50
|
+
return options.type === "select" ? options.initial : options.default ?? options.initial;
|
|
51
|
+
}
|
|
52
|
+
async function promptWithClack(message, options, backend) {
|
|
53
|
+
if (options.type === "select") {
|
|
54
|
+
const value = await backend.select({
|
|
55
|
+
message,
|
|
56
|
+
options: options.options.map((option) => typeof option === "string" ? {
|
|
57
|
+
label: option,
|
|
58
|
+
value: option
|
|
59
|
+
} : option),
|
|
60
|
+
initialValue: options.initial
|
|
61
|
+
});
|
|
62
|
+
if (backend.isCancel(value)) return getCancelValue(options);
|
|
63
|
+
return typeof value === "string" ? value : void 0;
|
|
64
|
+
}
|
|
65
|
+
const value = await backend.text({
|
|
66
|
+
message,
|
|
67
|
+
defaultValue: options.default,
|
|
68
|
+
initialValue: options.initial,
|
|
69
|
+
placeholder: options.placeholder
|
|
70
|
+
});
|
|
71
|
+
if (backend.isCancel(value)) return getCancelValue(options);
|
|
72
|
+
return typeof value === "string" ? value : void 0;
|
|
73
|
+
}
|
|
74
|
+
async function prompt(message, options) {
|
|
75
|
+
if (!shouldUseClackPrompt()) {
|
|
76
|
+
if (options.type === "select") {
|
|
77
|
+
const value = await consola.prompt(message, options);
|
|
78
|
+
return typeof value === "string" ? value : void 0;
|
|
79
|
+
}
|
|
80
|
+
return await consola.prompt(message, options);
|
|
81
|
+
}
|
|
82
|
+
return await promptWithClack(message, options, await import("@clack/prompts"));
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
39
85
|
//#region src/auth.ts
|
|
40
86
|
const authArgs = {
|
|
41
87
|
provider: {
|
|
@@ -91,7 +137,7 @@ async function resolveProviderSelection(providerArg) {
|
|
|
91
137
|
return providerName;
|
|
92
138
|
}
|
|
93
139
|
if (availableProviders.length === 1) return availableProviders[0];
|
|
94
|
-
const provider = await
|
|
140
|
+
const provider = await prompt("Select a provider to log in with", {
|
|
95
141
|
type: "select",
|
|
96
142
|
options: availableProviders.map((providerName) => ({
|
|
97
143
|
label: `${AUTH_PROVIDER_LABELS[providerName]} (${providerName})`,
|
|
@@ -107,7 +153,7 @@ function assertCustomProviderName(providerName) {
|
|
|
107
153
|
if (providerName === "copilot" || providerName === "codex") throw new Error(`Provider name '${providerName}' is reserved for a builtin provider`);
|
|
108
154
|
}
|
|
109
155
|
async function promptRequiredText(message, fieldName) {
|
|
110
|
-
const value = await
|
|
156
|
+
const value = await prompt(message, { type: "text" });
|
|
111
157
|
const normalizedValue = typeof value === "string" ? value.trim() : "";
|
|
112
158
|
if (!normalizedValue) throw new Error(`${fieldName} must be a non-empty string`);
|
|
113
159
|
return normalizedValue;
|
|
@@ -117,7 +163,7 @@ function canUseMaskedPrompt() {
|
|
|
117
163
|
}
|
|
118
164
|
async function promptMaskedText(message) {
|
|
119
165
|
if (!canUseMaskedPrompt()) {
|
|
120
|
-
const value = await
|
|
166
|
+
const value = await prompt(message, { type: "text" });
|
|
121
167
|
return typeof value === "string" ? value : "";
|
|
122
168
|
}
|
|
123
169
|
return await new Promise((resolve, reject) => {
|
|
@@ -180,7 +226,7 @@ async function promptCustomProviderName() {
|
|
|
180
226
|
return providerName;
|
|
181
227
|
}
|
|
182
228
|
async function promptCustomProviderType() {
|
|
183
|
-
const providerType = await
|
|
229
|
+
const providerType = await prompt("Select provider type", {
|
|
184
230
|
type: "select",
|
|
185
231
|
options: SUPPORTED_PROVIDER_TYPES.map((type) => ({
|
|
186
232
|
label: type,
|
|
@@ -191,7 +237,7 @@ async function promptCustomProviderType() {
|
|
|
191
237
|
return providerType;
|
|
192
238
|
}
|
|
193
239
|
async function promptQuickProviderType(defaultType) {
|
|
194
|
-
const providerType = await
|
|
240
|
+
const providerType = await prompt(`Select provider type (default: ${defaultType})`, {
|
|
195
241
|
type: "select",
|
|
196
242
|
options: [{
|
|
197
243
|
label: `Default (${defaultType})`,
|
|
@@ -209,11 +255,10 @@ function getDefaultProviderAuthType(providerType) {
|
|
|
209
255
|
return providerType === "anthropic" ? "x-api-key" : "authorization";
|
|
210
256
|
}
|
|
211
257
|
async function promptCustomProviderAuthType(providerType) {
|
|
212
|
-
const
|
|
213
|
-
const authType = await consola.prompt("Select provider auth type", {
|
|
258
|
+
const authType = await prompt("Select provider auth type", {
|
|
214
259
|
type: "select",
|
|
215
260
|
options: [{
|
|
216
|
-
label: `Default (${
|
|
261
|
+
label: `Default (${getDefaultProviderAuthType(providerType)})`,
|
|
217
262
|
value: CUSTOM_PROVIDER_AUTH_TYPE_OPTION
|
|
218
263
|
}, ...CUSTOM_PROVIDER_AUTH_TYPES.map((value) => ({
|
|
219
264
|
label: value,
|
|
@@ -225,7 +270,7 @@ async function promptCustomProviderAuthType(providerType) {
|
|
|
225
270
|
throw new Error("No provider auth type selected");
|
|
226
271
|
}
|
|
227
272
|
async function promptQuickProviderBaseUrl(defaultBaseUrl) {
|
|
228
|
-
const value = await
|
|
273
|
+
const value = await prompt(`Enter provider baseUrl (default: ${defaultBaseUrl})`, {
|
|
229
274
|
type: "text",
|
|
230
275
|
default: defaultBaseUrl,
|
|
231
276
|
initial: defaultBaseUrl
|
|
@@ -281,7 +326,7 @@ async function loginWithCodex() {
|
|
|
281
326
|
if (info.instructions) consola.info(info.instructions);
|
|
282
327
|
},
|
|
283
328
|
onPrompt(message) {
|
|
284
|
-
return
|
|
329
|
+
return prompt(message, { type: "text" }).then((value) => value ?? "");
|
|
285
330
|
},
|
|
286
331
|
onProgress(message) {
|
|
287
332
|
consola.debug(message);
|
|
@@ -445,4 +490,4 @@ const auth = defineCommand({
|
|
|
445
490
|
//#endregion
|
|
446
491
|
export { runProviderSetup as i, runAuthKeys as n, runAuthLogin as r, auth as t };
|
|
447
492
|
|
|
448
|
-
//# sourceMappingURL=auth-
|
|
493
|
+
//# sourceMappingURL=auth-DvqwYkJr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-DvqwYkJr.js","names":[],"sources":["../src/lib/quick-providers.ts","../src/lib/interactive-prompt.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: true,\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","import consola from \"consola\"\n\ninterface PromptSelectOption {\n label: string\n value: string\n hint?: string\n}\n\ninterface TextPromptOptions {\n type?: \"text\"\n default?: string\n initial?: string\n placeholder?: string\n}\n\ninterface SelectPromptOptions {\n type: \"select\"\n initial?: string\n options: Array<string | PromptSelectOption>\n}\n\nexport type InteractivePromptOptions = SelectPromptOptions | TextPromptOptions\n\ninterface ClackSelectOptions {\n message: string\n initialValue?: string\n options: Array<PromptSelectOption>\n}\n\ninterface ClackTextOptions {\n message: string\n defaultValue?: string\n initialValue?: string\n placeholder?: string\n}\n\nexport interface ClackPromptBackend {\n isCancel(value: unknown): boolean\n select(options: ClackSelectOptions): Promise<string | symbol>\n text(options: ClackTextOptions): Promise<string | symbol>\n}\n\ninterface PromptRuntime {\n bunVersion?: string\n platform: NodeJS.Platform\n stdinIsTTY?: boolean\n stdoutIsTTY?: boolean\n stdoutIsTTYStream?: boolean\n}\n\n// Consola 3.4.2 bundles a prompt implementation that writes keyboard input to\n// tty fd 0. Bun treats that as a real stdin write on Windows and throws EPIPE.\nexport function shouldUseClackPrompt(\n runtime: PromptRuntime = {\n bunVersion: process.versions.bun,\n platform: process.platform,\n stdinIsTTY: process.stdin.isTTY,\n stdoutIsTTY: process.stdout.isTTY,\n stdoutIsTTYStream: typeof process.stdout.getColorDepth === \"function\",\n },\n): boolean {\n return Boolean(\n runtime.platform === \"win32\"\n && runtime.bunVersion\n && runtime.stdinIsTTY\n && runtime.stdoutIsTTY\n && runtime.stdoutIsTTYStream,\n )\n}\n\nfunction getCancelValue(options: InteractivePromptOptions): string | undefined {\n return options.type === \"select\" ?\n options.initial\n : (options.default ?? options.initial)\n}\n\nexport async function promptWithClack(\n message: string,\n options: InteractivePromptOptions,\n backend: ClackPromptBackend,\n): Promise<string | undefined> {\n if (options.type === \"select\") {\n const value = await backend.select({\n message,\n options: options.options.map((option) =>\n typeof option === \"string\" ? { label: option, value: option } : option,\n ),\n initialValue: options.initial,\n })\n if (backend.isCancel(value)) {\n return getCancelValue(options)\n }\n return typeof value === \"string\" ? value : undefined\n }\n\n const value = await backend.text({\n message,\n defaultValue: options.default,\n initialValue: options.initial,\n placeholder: options.placeholder,\n })\n if (backend.isCancel(value)) {\n return getCancelValue(options)\n }\n return typeof value === \"string\" ? value : undefined\n}\n\nexport async function prompt(\n message: string,\n options: InteractivePromptOptions,\n): Promise<string | undefined> {\n if (!shouldUseClackPrompt()) {\n if (options.type === \"select\") {\n const value = await consola.prompt(message, options)\n return typeof value === \"string\" ? value : undefined\n }\n return await consola.prompt(message, options)\n }\n\n const clack = await import(\"@clack/prompts\")\n return await promptWithClack(message, options, clack)\n}\n","#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport {\n getRawProviderConfig,\n isSupportedProviderType,\n normalizeProviderBaseUrl,\n setProviderConfig,\n setConfiguredApiKeys,\n SUPPORTED_PROVIDER_TYPES,\n type ProviderAuthType,\n type ProviderConfig,\n type ProviderType,\n} from \"./lib/config\"\nimport { loginCodex } from \"./lib/oauth/codex\"\nimport { PATHS, ensurePaths } from \"./lib/paths\"\nimport { getConfiguredApiKeys } from \"./lib/request-auth\"\nimport {\n QUICK_PROVIDER_CONFIGS,\n type QuickProviderName,\n} from \"./lib/quick-providers\"\nimport { prompt } from \"./lib/interactive-prompt\"\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 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 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 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 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 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 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 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 prompt(message, { type: \"text\" }).then((value) => value ?? \"\")\n },\n onProgress(message) {\n consola.debug(message)\n },\n })\n\n await persistCodexCredentials(credentials, { enableProvider: true })\n consola.success(\n `Codex provider config written to ${PATHS.CONFIG_PATH} and credentials written to ${PATHS.CODEX_CREDENTIAL_PATH}`,\n )\n}\n\nasync function loginWithProvider(provider: AuthProviderName): Promise<void> {\n if (provider === \"copilot\") {\n await setupGitHubToken({ force: true })\n consola.success(\"GitHub token written to\", PATHS.GITHUB_TOKEN_PATH)\n return\n }\n\n if (provider === \"codex\") {\n await loginWithCodex()\n return\n }\n\n if (isQuickProviderName(provider)) {\n await configureQuickProvider(provider)\n return\n }\n\n await configureCustomProvider()\n}\n\nexport async function runProviderSetup(): Promise<void> {\n const provider = await resolveProviderSelection(undefined)\n consola.info(`Logging in with ${AUTH_PROVIDER_LABELS[provider]}`)\n await loginWithProvider(provider)\n}\n\nexport async function runAuthLogin(options: RunAuthOptions): Promise<void> {\n const tlsModule = await import(\"./lib/tls\")\n tlsModule.enableSystemCACompat()\n\n if (options.verbose) {\n consola.level = 5\n consola.info(\"Verbose logging enabled\")\n }\n\n state.showToken = options.showToken\n\n await ensurePaths()\n const provider = await resolveProviderSelection(options.provider)\n\n consola.info(`Logging in with ${AUTH_PROVIDER_LABELS[provider]}`)\n await loginWithProvider(provider)\n}\n\nconst authKeysArgs = {\n add: {\n alias: \"a\",\n type: \"string\",\n description: \"Add an API key for gateway authentication\",\n },\n remove: {\n alias: \"r\",\n type: \"string\",\n description: \"Remove an API key\",\n },\n list: {\n alias: \"l\",\n type: \"boolean\",\n default: false,\n description: \"List configured API keys\",\n },\n clear: {\n type: \"boolean\",\n default: false,\n description: \"Remove all configured API keys\",\n },\n} as const\n\ninterface RunAuthKeysOptions {\n add?: string\n remove?: string\n list?: boolean\n clear?: boolean\n}\n\nfunction normalizeAuthKeyValue(value: string): string {\n const normalizedKey = value.trim()\n if (!normalizedKey) {\n throw new Error(\"API key must be a non-empty string\")\n }\n return normalizedKey\n}\n\nexport async function runAuthKeys(options: RunAuthKeysOptions): Promise<void> {\n const tlsModule = await import(\"./lib/tls\")\n tlsModule.enableSystemCACompat()\n\n await ensurePaths()\n\n const operations = [\n ...(options.add !== undefined ? [\"add\"] : []),\n ...(options.remove !== undefined ? [\"remove\"] : []),\n ...(options.list ? [\"list\"] : []),\n ...(options.clear ? [\"clear\"] : []),\n ]\n if (operations.length > 1) {\n throw new Error(\n \"Use only one of --add, --remove, --list, or --clear per invocation\",\n )\n }\n\n const operation = operations[0] ?? \"list\"\n\n if (operation === \"add\") {\n const apiKey = normalizeAuthKeyValue(options.add ?? \"\")\n const currentKeys = getConfiguredApiKeys()\n if (currentKeys.includes(apiKey)) {\n consola.info(\n `API key already configured. ${currentKeys.length} API key(s) configured.`,\n )\n return\n }\n const storedKeys = setConfiguredApiKeys([...currentKeys, apiKey])\n consola.success(\n `API key added to ${PATHS.CONFIG_PATH}. ${storedKeys.length} API key(s) configured.`,\n )\n return\n }\n\n if (operation === \"remove\") {\n const apiKey = normalizeAuthKeyValue(options.remove ?? \"\")\n const currentKeys = getConfiguredApiKeys()\n if (!currentKeys.includes(apiKey)) {\n consola.info(\n `API key not found. ${currentKeys.length} API key(s) configured.`,\n )\n return\n }\n const storedKeys = setConfiguredApiKeys(\n currentKeys.filter((key) => key !== apiKey),\n )\n consola.success(\n `API key removed from ${PATHS.CONFIG_PATH}. ${storedKeys.length} API key(s) configured.`,\n )\n return\n }\n\n if (operation === \"clear\") {\n setConfiguredApiKeys([])\n consola.success(`Removed all API keys from ${PATHS.CONFIG_PATH}.`)\n return\n }\n\n const currentKeys = getConfiguredApiKeys()\n if (currentKeys.length === 0) {\n consola.info(\n \"No API keys configured. Run `npx copilot-api auth keys --add <key>` to add one.\",\n )\n return\n }\n consola.info(\"Configured API keys:\")\n for (const key of currentKeys) {\n consola.info(`- ${key}`)\n }\n}\n\nconst authLogin = defineCommand({\n meta: {\n name: \"login\",\n description:\n \"Authenticate or configure a provider without running the server\",\n },\n args: authArgs,\n run({ args }) {\n return runAuthLogin({\n provider: args.provider,\n verbose: args.verbose,\n showToken: args[\"show-token\"],\n })\n },\n})\n\nconst authKeys = defineCommand({\n meta: {\n name: \"keys\",\n description: \"Manage gateway API keys (auth.apiKeys) in the config\",\n },\n args: authKeysArgs,\n run({ args }) {\n return runAuthKeys({\n add: args.add,\n remove: args.remove,\n list: args.list,\n clear: args.clear,\n })\n },\n})\n\nexport const auth = defineCommand({\n meta: {\n name: \"auth\",\n description: \"Run authentication flows without running the server\",\n },\n args: authArgs,\n subCommands: {\n login: authLogin,\n keys: authKeys,\n },\n run({ args }) {\n if ((args._[0] ?? \"\").trim()) {\n return\n }\n\n return runAuthLogin({\n provider: args.provider,\n verbose: args.verbose,\n showToken: args[\"show-token\"],\n })\n },\n})\n"],"mappings":";;;;;AASA,MAAa,yBAAyB;CACpC,eAAe;EACb,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACD,MAAM;EACJ,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACD,UAAU;EACR,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACD,WAAW;EACT,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACD,YAAY;EACV,MAAM;EACN,SAAS;EACT,iBAAiB;EACjB,cAAc;EACf;CACF;;;ACYD,SAAgB,qBACd,UAAyB;CACvB,YAAY,QAAQ,SAAS;CAC7B,UAAU,QAAQ;CAClB,YAAY,QAAQ,MAAM;CAC1B,aAAa,QAAQ,OAAO;CAC5B,mBAAmB,OAAO,Q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ACJ,MAAM;IACN,aAAa;IACd;GACD,MAAM;GACN,IAAI,EAAE,QAAQ;IACZ,OAAO,YAAY;KACjB,KAAK,KAAK;KACV,QAAQ,KAAK;KACb,MAAM,KAAK;KACX,OAAO,KAAK;KACb,CAAC;;GAEL,CAUS;EACP;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"}
|
|
@@ -457,12 +457,12 @@ function resolveProviderAuthType(providerName, authType, providerType) {
|
|
|
457
457
|
consola.warn(`Provider ${providerName} has authType 'oauth2', which is only supported by the builtin codex provider, falling back to ${defaultAuthType}`);
|
|
458
458
|
return defaultAuthType;
|
|
459
459
|
}
|
|
460
|
-
if (authType === "authorization") return authType;
|
|
460
|
+
if (authType === "authorization" || authType === "azure-entra") return authType;
|
|
461
461
|
consola.warn(`Provider ${providerName} has invalid authType '${authType}', falling back to ${defaultAuthType}`);
|
|
462
462
|
return defaultAuthType;
|
|
463
463
|
}
|
|
464
464
|
function isProviderApiKeyRequired(providerName, authType) {
|
|
465
|
-
return !(providerName === "codex" && authType === "oauth2");
|
|
465
|
+
return authType !== "azure-entra" && !(providerName === "codex" && authType === "oauth2");
|
|
466
466
|
}
|
|
467
467
|
function getRawProviderConfig(name) {
|
|
468
468
|
const providerName = name.trim();
|
|
@@ -539,4 +539,4 @@ function isReservedProviderName(name) {
|
|
|
539
539
|
//#endregion
|
|
540
540
|
export { isResponsesApiWebSocketEnabled as A, getClaudeTokenMultiplier as C, isAlphaSearchCodexPriorityEnabled as D, getResponsesTransportConfig as E, setConfiguredApiKeys as M, PATHS as N, isMessagesApiEnabled as O, ensurePaths as P, getClaudeAutoModel as S, getMessageApiWebSearchModel as T, resolveMappedModel as _, normalizeProviderBaseUrl as a, getAlphaSearchModel as b, setProviderConfig as c, getModelResponsesApiCompactThreshold as d, getReasoningEffortForModel as f, isGpt56OrAbove as g, isContextManagementEnabledForResponses as h, listEnabledProviders as i, mergeConfigWithDefaults as j, isResponsesApiWebSearchEnabled as k, getExtraPromptForModel as l, isContextManagementEnabledForMessages as m, getRawProviderConfig as n, resolveEffectiveProviderType as o, getSmallModel as p, isSupportedProviderType as r, resolveProviderAuthType as s, getProviderConfig as t, getModelMappings as u, setModelMappings as v, getConfig as w, getAnthropicApiKey as x, SUPPORTED_PROVIDER_TYPES as y };
|
|
541
541
|
|
|
542
|
-
//# sourceMappingURL=config-
|
|
542
|
+
//# sourceMappingURL=config-DVWu2hKk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-DVWu2hKk.js","names":["fs"],"sources":["../src/lib/atomic-file.ts","../src/lib/paths.ts","../src/lib/config-store.ts","../src/lib/model-policy.ts","../src/lib/provider-config.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs\"\nimport path from \"node:path\"\n\nconst TEMP_FILE_RANDOM_BYTES = 8\n\n// The file-level fsync persists the contents, but the rename only updates the\n// parent directory entry, which needs its own fsync to survive a crash or\n// power loss. Best-effort: the rename has already taken effect, so a failure\n// here only weakens crash durability and must not fail the write. Directory\n// fsync is not supported on Windows (opening a directory handle fails there).\nconst fsyncDirectory = (directory: string): void => {\n if (process.platform === \"win32\") {\n return\n }\n\n let directoryFd: number | undefined\n try {\n directoryFd = fs.openSync(directory, \"r\")\n fs.fsyncSync(directoryFd)\n } catch (error) {\n console.warn(`Failed to fsync directory: ${directory}`, error)\n } finally {\n if (directoryFd !== undefined) {\n try {\n fs.closeSync(directoryFd)\n } catch {\n // Preserve the fsync warning.\n }\n }\n }\n}\n\nexport function writeFileAtomically(filePath: string, content: string): void {\n const directory = path.dirname(filePath)\n const tempPath = path.join(\n directory,\n `.${path.basename(filePath)}.${process.pid}.${randomBytes(TEMP_FILE_RANDOM_BYTES).toString(\"hex\")}.tmp`,\n )\n\n fs.mkdirSync(directory, { recursive: true })\n\n let fileDescriptor: number | undefined\n let tempFileCreated = false\n try {\n fileDescriptor = fs.openSync(tempPath, \"wx\", 0o600)\n tempFileCreated = true\n fs.writeFileSync(fileDescriptor, content, \"utf8\")\n fs.fsyncSync(fileDescriptor)\n fs.closeSync(fileDescriptor)\n fileDescriptor = undefined\n fs.renameSync(tempPath, filePath)\n tempFileCreated = false\n fsyncDirectory(directory)\n } catch (error) {\n if (fileDescriptor !== undefined) {\n try {\n fs.closeSync(fileDescriptor)\n } catch {\n // Preserve the original write error.\n }\n }\n\n if (tempFileCreated) {\n try {\n fs.rmSync(tempPath, { force: true })\n } catch {\n // Preserve the original write error.\n }\n }\n\n throw error\n }\n}\n","import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nconst AUTH_APP = process.env.COPILOT_API_OAUTH_APP?.trim() || \"\"\nconst ENTERPRISE_PREFIX = process.env.COPILOT_API_ENTERPRISE_URL ? \"ent_\" : \"\"\n\nconst DEFAULT_DIR = path.join(os.homedir(), \".local\", \"share\", \"copilot-api\")\nconst APP_DIR = process.env.COPILOT_API_HOME || DEFAULT_DIR\n\nconst GITHUB_TOKEN_PATH = path.join(\n APP_DIR,\n AUTH_APP,\n ENTERPRISE_PREFIX + \"github_token\",\n)\nconst CODEX_CREDENTIAL_PATH = path.join(APP_DIR, \"codex_credentials.json\")\nconst CONFIG_PATH = path.join(APP_DIR, \"config.json\")\n\nexport const PATHS = {\n APP_DIR,\n GITHUB_TOKEN_PATH,\n CODEX_CREDENTIAL_PATH,\n CONFIG_PATH,\n}\n\nexport async function ensurePaths(): Promise<void> {\n await fs.mkdir(path.join(PATHS.APP_DIR, AUTH_APP), { recursive: true })\n await ensureFile(PATHS.GITHUB_TOKEN_PATH)\n await ensureFile(PATHS.CONFIG_PATH)\n}\n\nasync function ensureFile(filePath: string): Promise<void> {\n try {\n await fs.access(filePath, fs.constants.W_OK)\n } catch {\n await fs.writeFile(filePath, \"\")\n await fs.chmod(filePath, 0o600)\n }\n}\n","import consola from \"consola\"\nimport { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs\"\n\nimport type { TokenUsagePricingConfig } from \"~/lib/token-usage/pricing\"\n\nimport { writeFileAtomically } from \"./atomic-file\"\nimport { PATHS } from \"./paths\"\n\nexport interface AppConfig {\n auth?: {\n apiKeys?: Array<string>\n adminApiKey?: string\n }\n providers?: Record<string, ProviderConfig>\n modelMappings?: Record<string, string>\n extraPrompts?: Record<string, string>\n smallModel?: string\n contextManagement?: ContextManagementConfig\n modelResponsesApiCompactThresholds?: Record<string, number>\n modelReasoningEfforts?: Record<\n string,\n \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\"\n >\n useMessagesApi?: boolean\n useResponsesApiWebSocket?: boolean\n responsesTransport?: ResponsesTransportConfig\n anthropicApiKey?: string\n useResponsesApiWebSearch?: boolean\n alphaSearchCodexPriority?: boolean\n alphaSearchModel?: string\n // Copilot rejects Anthropic's web_search server tool on /v1/messages, so a\n // Claude request that only asks for web search is switched to this model.\n // A `provider/model` alias is passed straight through to that provider's\n // (websearch-capable) message API, while a plain GPT model runs the search\n // via /responses. Leave unset to disable (the tool is then stripped).\n // Mixing web_search with other tools is not supported.\n messageApiWebSearchModel?: string\n // Model used for Claude Code background security-monitor requests on\n // /v1/messages and provider message APIs: requests without tools, with\n // `stop_sequences: [\"</block>\"]` and a system block starting with\n // \"You are a security monitor for autonomous AI coding agents.\".\n // A `provider/model` alias is forwarded to that provider's message API on\n // the top-level route. Provider message routes use the configured value on\n // their current provider. Leave empty to disable (default).\n claudeAutoModel?: string\n claudeTokenMultiplier?: number\n}\n\nexport interface ContextManagementConfig {\n messages?: boolean\n responses?: boolean\n}\n\nexport interface ResponsesTransportConfig {\n headersTimeoutMsV2?: number\n streamInactivityTimeoutMs?: number\n websocketMaxBufferedBytes?: number\n websocketMaxBufferedMessages?: number\n websocketOpenTimeoutMs?: number\n websocketPoolIdleTimeoutMs?: number\n}\n\nexport const defaultResponsesTransportConfig = {\n headersTimeoutMsV2: 5 * 60 * 1000,\n streamInactivityTimeoutMs: 5 * 60 * 1000,\n websocketMaxBufferedBytes: 8 * 1024 * 1024,\n websocketMaxBufferedMessages: 1024,\n websocketOpenTimeoutMs: 30_000,\n websocketPoolIdleTimeoutMs: 60_000,\n} satisfies Required<ResponsesTransportConfig>\n\nexport interface ModelConfig {\n temperature?: number\n topP?: number\n topK?: number\n extraBody?: Record<string, unknown>\n contextCache?: boolean\n contextWindow?: number\n maxOutputTokens?: number\n inputModalities?: Array<\"text\" | \"image\">\n reasoningEfforts?: Array<CodexReasoningEffort>\n defaultReasoningEffort?: CodexReasoningEffort\n pricing?: TokenUsagePricingConfig\n supportPdf?: boolean\n toolContentSupportType?: Array<ToolContentSupportType>\n type?: ProviderType\n // Message field used to carry assistant thinking text when forwarding\n // requests upstream; defaults to \"reasoning_content\"\n reasoningField?: ModelReasoningField\n}\n\nexport type ModelReasoningField = \"reasoning\" | \"reasoning_content\"\n\nexport type CodexReasoningEffort =\n | \"none\"\n | \"minimal\"\n | \"low\"\n | \"medium\"\n | \"high\"\n | \"xhigh\"\n | \"max\"\n | \"ultra\"\n\nexport type ProviderAuthType =\n | \"authorization\"\n | \"azure-entra\"\n | \"oauth2\"\n | \"x-api-key\"\nexport const SUPPORTED_PROVIDER_TYPES = [\n \"anthropic\",\n \"openai-compatible\",\n \"openai-responses\",\n] as const\nexport type ProviderType = (typeof SUPPORTED_PROVIDER_TYPES)[number]\nexport type ToolContentSupportType = \"array\" | \"image\" | \"pdf\"\n\nexport interface ProviderConfig {\n type?: string\n enabled?: boolean\n baseUrl?: string\n apiKey?: string\n authType?: ProviderAuthType\n pricingCurrency?: string\n models?: Record<string, ModelConfig>\n}\n\nconst gpt5ExplorationPrompt = `## Exploration and reading files\n- **Think first.** Before any tool call, decide ALL files/resources you will need.\n- **Batch everything.** If you need multiple files (even from different places), read them together.\n- **multi_tool_use.parallel** Use multi_tool_use.parallel to parallelize tool calls and only this.\n- **Only make sequential calls if you truly cannot know the next file without seeing a result first.**\n- **Workflow:** (a) plan all needed reads → (b) issue one parallel batch → (c) analyze results → (d) repeat if new, unpredictable reads arise.`\n\nconst modelResponsesApiCompactThresholds = {\n \"gpt-5.4\": 272_000 * 0.8,\n \"gpt-5.5\": 272_000 * 0.8,\n}\n\nexport const defaultContextManagement = {\n messages: true,\n responses: false,\n} satisfies Required<ContextManagementConfig>\n\nexport const defaultConfig: AppConfig = {\n auth: {\n apiKeys: [],\n },\n providers: {},\n modelMappings: {},\n extraPrompts: {\n \"gpt-5-mini\": gpt5ExplorationPrompt,\n },\n smallModel: \"gpt-5-mini\",\n contextManagement: defaultContextManagement,\n modelResponsesApiCompactThresholds,\n modelReasoningEfforts: {\n \"gpt-5-mini\": \"low\",\n },\n useMessagesApi: true,\n useResponsesApiWebSocket: true,\n responsesTransport: defaultResponsesTransportConfig,\n useResponsesApiWebSearch: true,\n alphaSearchCodexPriority: true,\n alphaSearchModel: \"gpt-5-mini\",\n messageApiWebSearchModel: \"gpt-5-mini\",\n}\n\nlet cachedConfig: AppConfig | null = null\n\nfunction normalizeAdminApiKey(adminApiKey: unknown): string | null {\n if (typeof adminApiKey !== \"string\") {\n if (adminApiKey !== undefined) {\n consola.warn(\n \"Invalid auth.adminApiKey config. Expected a non-empty string.\",\n )\n }\n return null\n }\n\n const normalizedAdminApiKey = adminApiKey.trim()\n if (!normalizedAdminApiKey) {\n consola.warn(\n \"Invalid auth.adminApiKey config. Expected a non-empty string.\",\n )\n return null\n }\n\n return normalizedAdminApiKey\n}\n\nfunction generateAdminApiKey(): string {\n return randomBytes(32).toString(\"hex\")\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error\n}\n\nfunction ensureConfigFile(): void {\n try {\n fs.accessSync(PATHS.CONFIG_PATH, fs.constants.R_OK | fs.constants.W_OK)\n } catch {\n writeFileAtomically(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\n )\n try {\n fs.chmodSync(PATHS.CONFIG_PATH, 0o600)\n } catch {\n return\n }\n }\n}\n\nfunction readConfigFromDisk(): AppConfig {\n ensureConfigFile()\n const raw = fs.readFileSync(PATHS.CONFIG_PATH, \"utf8\")\n if (!raw.trim()) {\n writeFileAtomically(\n PATHS.CONFIG_PATH,\n `${JSON.stringify(defaultConfig, null, 2)}\\n`,\n )\n return defaultConfig\n }\n\n try {\n return JSON.parse(raw) as AppConfig\n } catch (error) {\n // Fail closed: falling back to the default config here would let the\n // startup merge overwrite the corrupt file (discarding providers, API\n // keys, and model mappings) and, because the default has no apiKeys,\n // silently disable API key authentication on normal routes.\n const message = `Config file is not valid JSON: ${PATHS.CONFIG_PATH}. Refusing to start with the default config. Fix the JSON syntax or delete the file to regenerate a fresh config.`\n consola.error(message, error)\n throw new Error(message, { cause: error })\n }\n}\n\nexport function readEditableConfigFromDisk(): AppConfig {\n try {\n const raw = fs.readFileSync(PATHS.CONFIG_PATH, \"utf8\")\n if (!raw.trim()) {\n return {}\n }\n return JSON.parse(raw) as AppConfig\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return {}\n }\n if (error instanceof SyntaxError) {\n throw new Error(`Config file is not valid JSON: ${PATHS.CONFIG_PATH}`)\n }\n throw error\n }\n}\n\nexport function writeConfigToDisk(config: AppConfig): void {\n writeFileAtomically(PATHS.CONFIG_PATH, `${JSON.stringify(config, null, 2)}\\n`)\n}\n\nexport function setConfiguredApiKeys(apiKeys: Array<string>): Array<string> {\n const normalizedKeys = apiKeys\n .map((key) => key.trim())\n .filter((key) => key.length > 0)\n const uniqueKeys = [...new Set(normalizedKeys)]\n\n const editableConfig = readEditableConfigFromDisk()\n writeConfigToDisk({\n ...editableConfig,\n auth: {\n ...editableConfig.auth,\n apiKeys: uniqueKeys,\n },\n })\n reloadConfig()\n return [...uniqueKeys]\n}\n\nfunction mergeDefaultConfig(config: AppConfig): {\n mergedConfig: AppConfig\n changed: boolean\n} {\n const extraPrompts = config.extraPrompts ?? {}\n const defaultExtraPrompts = defaultConfig.extraPrompts ?? {}\n const responsesApiCompactThresholds =\n config.modelResponsesApiCompactThresholds ?? {}\n const defaultResponsesApiCompactThresholds =\n defaultConfig.modelResponsesApiCompactThresholds ?? {}\n const modelReasoningEfforts = config.modelReasoningEfforts ?? {}\n const defaultModelReasoningEfforts = defaultConfig.modelReasoningEfforts ?? {}\n const contextManagement = normalizeContextManagementConfig(\n config.contextManagement,\n )\n const responsesTransport = normalizeResponsesTransportConfig(\n config.responsesTransport,\n )\n const defaultContextManagementConfig = defaultConfig.contextManagement ?? {}\n\n const missingExtraPromptModels = Object.keys(defaultExtraPrompts).filter(\n (model) => !Object.hasOwn(extraPrompts, model),\n )\n\n const missingReasoningEffortModels = Object.keys(\n defaultModelReasoningEfforts,\n ).filter((model) => !Object.hasOwn(modelReasoningEfforts, model))\n const missingResponsesApiCompactThresholdModels = Object.keys(\n defaultResponsesApiCompactThresholds,\n ).filter((model) => !Object.hasOwn(responsesApiCompactThresholds, model))\n const missingContextManagementKeys = Object.keys(\n defaultContextManagementConfig,\n ).filter((key) => !Object.hasOwn(contextManagement, key))\n\n const hasExtraPromptChanges = missingExtraPromptModels.length > 0\n const hasReasoningEffortChanges = missingReasoningEffortModels.length > 0\n const hasResponsesApiCompactThresholdChanges =\n missingResponsesApiCompactThresholdModels.length > 0\n const hasContextManagementChanges = missingContextManagementKeys.length > 0\n const hasResponsesTransportChanges = Object.entries(responsesTransport).some(\n ([key, value]) =>\n config.responsesTransport?.[key as keyof ResponsesTransportConfig]\n !== value,\n )\n\n if (\n !hasExtraPromptChanges\n && !hasReasoningEffortChanges\n && !hasResponsesApiCompactThresholdChanges\n && !hasContextManagementChanges\n && !hasResponsesTransportChanges\n ) {\n return { mergedConfig: config, changed: false }\n }\n\n return {\n mergedConfig: {\n ...config,\n contextManagement: {\n ...defaultContextManagementConfig,\n ...contextManagement,\n },\n extraPrompts: {\n ...defaultExtraPrompts,\n ...extraPrompts,\n },\n modelResponsesApiCompactThresholds: {\n ...defaultResponsesApiCompactThresholds,\n ...responsesApiCompactThresholds,\n },\n modelReasoningEfforts: {\n ...defaultModelReasoningEfforts,\n ...modelReasoningEfforts,\n },\n responsesTransport,\n },\n changed: true,\n }\n}\n\nfunction normalizeContextManagementConfig(\n value: ContextManagementConfig | undefined,\n): ContextManagementConfig {\n if (!value || typeof value !== \"object\") {\n return {}\n }\n\n return {\n ...(typeof value.messages === \"boolean\" ?\n { messages: value.messages }\n : {}),\n ...(typeof value.responses === \"boolean\" ?\n { responses: value.responses }\n : {}),\n }\n}\n\nfunction ensureAdminApiKey(config: AppConfig): {\n mergedConfig: AppConfig\n changed: boolean\n} {\n const normalizedAdminApiKey = normalizeAdminApiKey(config.auth?.adminApiKey)\n if (normalizedAdminApiKey) {\n if (config.auth?.adminApiKey === normalizedAdminApiKey) {\n return { mergedConfig: config, changed: false }\n }\n\n return {\n mergedConfig: {\n ...config,\n auth: {\n ...config.auth,\n adminApiKey: normalizedAdminApiKey,\n },\n },\n changed: true,\n }\n }\n\n const editableConfig = readEditableConfigFromDisk()\n const { mergedConfig } = mergeDefaultConfig({\n ...editableConfig,\n auth: {\n ...editableConfig.auth,\n adminApiKey: generateAdminApiKey(),\n },\n })\n\n return { mergedConfig, changed: true }\n}\n\nexport function mergeConfigWithDefaults(): AppConfig {\n const config = readConfigFromDisk()\n const { mergedConfig, changed } = mergeDefaultConfig(config)\n const {\n mergedConfig: mergedConfigWithAdminApiKey,\n changed: adminApiKeyChanged,\n } = ensureAdminApiKey(mergedConfig)\n const shouldPersistConfig = changed || adminApiKeyChanged\n\n if (shouldPersistConfig) {\n try {\n writeConfigToDisk(mergedConfigWithAdminApiKey)\n } catch (writeError) {\n if (adminApiKeyChanged) {\n throw writeError\n }\n\n consola.warn(\n \"Failed to write merged default config to config file\",\n writeError,\n )\n }\n }\n\n cachedConfig = mergedConfigWithAdminApiKey\n return mergedConfigWithAdminApiKey\n}\n\nexport function getConfig(): AppConfig {\n cachedConfig ??= mergeDefaultConfig(readConfigFromDisk()).mergedConfig\n return cachedConfig\n}\n\nexport function reloadConfig(): AppConfig {\n return mergeConfigWithDefaults()\n}\n\nexport function isMessagesApiEnabled(): boolean {\n const config = getConfig()\n return config.useMessagesApi ?? true\n}\n\nexport function isResponsesApiWebSocketEnabled(): boolean {\n const config = getConfig()\n return config.useResponsesApiWebSocket ?? true\n}\n\nexport function getResponsesTransportConfig() {\n const { headersTimeoutMsV2, ...config } = normalizeResponsesTransportConfig(\n getConfig().responsesTransport,\n )\n return { headersTimeoutMs: headersTimeoutMsV2, ...config }\n}\n\nexport const normalizeResponsesTransportConfig = (\n configured: ResponsesTransportConfig | undefined,\n): Required<ResponsesTransportConfig> => ({\n headersTimeoutMsV2: positiveIntegerOrDefault(\n configured?.headersTimeoutMsV2,\n defaultResponsesTransportConfig.headersTimeoutMsV2,\n ),\n streamInactivityTimeoutMs: positiveIntegerOrDefault(\n configured?.streamInactivityTimeoutMs,\n defaultResponsesTransportConfig.streamInactivityTimeoutMs,\n ),\n websocketMaxBufferedBytes: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedBytes,\n defaultResponsesTransportConfig.websocketMaxBufferedBytes,\n ),\n websocketMaxBufferedMessages: positiveIntegerOrDefault(\n configured?.websocketMaxBufferedMessages,\n defaultResponsesTransportConfig.websocketMaxBufferedMessages,\n ),\n websocketOpenTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketOpenTimeoutMs,\n defaultResponsesTransportConfig.websocketOpenTimeoutMs,\n ),\n websocketPoolIdleTimeoutMs: positiveIntegerOrDefault(\n configured?.websocketPoolIdleTimeoutMs,\n defaultResponsesTransportConfig.websocketPoolIdleTimeoutMs,\n ),\n})\n\nconst positiveIntegerOrDefault = (value: unknown, fallback: number): number => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback\n\n const normalized = Math.floor(value)\n return normalized > 0 ? normalized : fallback\n}\n\nexport function getAnthropicApiKey(): string | undefined {\n const config = getConfig()\n return config.anthropicApiKey ?? process.env.ANTHROPIC_API_KEY ?? undefined\n}\n\nexport function isResponsesApiWebSearchEnabled(): boolean {\n const config = getConfig()\n return config.useResponsesApiWebSearch ?? true\n}\n\nexport function isAlphaSearchCodexPriorityEnabled(): boolean {\n const config = getConfig()\n return config.alphaSearchCodexPriority ?? true\n}\n\nexport function getAlphaSearchModel(): string | undefined {\n const model = getConfig().alphaSearchModel ?? \"gpt-5-mini\"\n return model.trim() || undefined\n}\n\nexport function getMessageApiWebSearchModel(): string | undefined {\n const config = getConfig()\n const model = config.messageApiWebSearchModel ?? \"gpt-5-mini\"\n return model && model.trim().length > 0 ? model : undefined\n}\n\nexport function getClaudeAutoModel(): string | undefined {\n const config = getConfig()\n const model = config.claudeAutoModel\n return model && model.trim().length > 0 ? model.trim() : undefined\n}\n\nexport function getClaudeTokenMultiplier(): number {\n const config = getConfig()\n return config.claudeTokenMultiplier ?? 1.15\n}\n","import {\n defaultConfig,\n defaultContextManagement,\n getConfig,\n readEditableConfigFromDisk,\n reloadConfig,\n writeConfigToDisk,\n} from \"./config-store\"\n\nconst GPT_MODEL_PATTERN = /^gpt-(\\d+)(?:\\.(\\d+))?/\n\nfunction isGpt53OrAbove(model: string): boolean {\n const match = GPT_MODEL_PATTERN.exec(model)\n if (!match) {\n return false\n }\n const majorVersion = Number.parseInt(match[1], 10)\n if (majorVersion > 5) {\n return true\n }\n if (majorVersion !== 5) {\n return false\n }\n const minorVersion = match[2] ? Number.parseInt(match[2], 10) : 0\n return minorVersion >= 3\n}\n\nexport function isGpt56OrAbove(model: string): boolean {\n const match = GPT_MODEL_PATTERN.exec(model)\n if (!match) {\n return false\n }\n const majorVersion = Number.parseInt(match[1], 10)\n if (majorVersion > 5) {\n return true\n }\n if (majorVersion !== 5) {\n return false\n }\n const minorVersion = match[2] ? Number.parseInt(match[2], 10) : 0\n return minorVersion >= 6\n}\n\nconst gpt5CommentaryPrompt = `# Working with the user\n\nYou interact with the user through a terminal. You have 2 ways of communicating with the users: \n- Share intermediary updates in \\`commentary\\` channel. \n- After you have completed all your work, send a message to the \\`final\\` channel. \n\n## Intermediary updates\n\n- Intermediary updates go to the \\`commentary\\` channel.\n- User updates are short updates while you are working, they are NOT final answers.\n- You use 1-2 sentence user updates to communicate progress and new information to the user as you are doing work.\n- Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements (“Done —”, “Got it”, “Great question, ”) or framing phrases.\n- You provide user updates frequently, every 20s.\n- Before exploring or doing substantial work, you start with a user update acknowledging the request and explaining your first step. You should include your understanding of the user request and explain what you will do. Avoid commenting on the request or using starters such as \"Got it -\" or \"Understood -\" etc.\n- When exploring, e.g. searching, reading files, you provide user updates as you go, every 20s, explaining what context you are gathering and what you've learned. Vary your sentence structure when providing these updates to avoid sounding repetitive - in particular, don't start each sentence the same way.\n- After you have sufficient context, and the work is substantial, you provide a longer plan (this is the only user update that may be longer than 2 sentences and can contain formatting).\n- Before performing file edits of any kind, you provide updates explaining what edits you are making.\n- As you are thinking, you very frequently provide updates even if not taking any actions, informing the user of your progress. You interrupt your thinking and send multiple updates in a row if thinking for more than 100 words.\n- Tone of your updates MUST match your personality.`\n\nexport function getExtraPromptForModel(model: string): string {\n const config = getConfig()\n const userPrompt = config.extraPrompts?.[model]\n if (userPrompt !== undefined) {\n return userPrompt\n }\n return isGpt53OrAbove(model) ? gpt5CommentaryPrompt : \"\"\n}\n\nexport function getModelMappings(): Record<string, string> {\n const config = getConfig()\n const modelMappings = config.modelMappings\n if (!modelMappings) {\n return { ...defaultConfig.modelMappings }\n }\n\n const validMappings: Record<string, string> = {}\n for (const [sourceModel, targetModel] of Object.entries(modelMappings)) {\n if (\n !sourceModel\n || typeof targetModel !== \"string\"\n || targetModel.length === 0\n ) {\n continue\n }\n validMappings[sourceModel] = targetModel\n }\n\n return validMappings\n}\n\nfunction validateModelMappings(\n modelMappings: Record<string, string>,\n): Record<string, string> {\n const validatedMappings: Record<string, string> = {}\n for (const [sourceModel, targetModel] of Object.entries(modelMappings)) {\n if (!sourceModel || !targetModel) {\n throw new Error(\n \"Each model mapping must use non-empty source and target values.\",\n )\n }\n validatedMappings[sourceModel] = targetModel\n }\n\n return validatedMappings\n}\n\nexport function setModelMappings(\n modelMappings: Record<string, string>,\n): Record<string, string> {\n const nextConfig = {\n ...readEditableConfigFromDisk(),\n modelMappings: validateModelMappings(modelMappings),\n }\n\n writeConfigToDisk(nextConfig)\n reloadConfig()\n return getModelMappings()\n}\n\nexport function resolveMappedModel(model: string): string {\n return getModelMappings()[model] ?? model\n}\n\nexport function getSmallModel(): string {\n const config = getConfig()\n return config.smallModel ?? \"gpt-5-mini\"\n}\n\nexport function isContextManagementEnabledForMessages(): boolean {\n const config = getConfig()\n return config.contextManagement?.messages ?? defaultContextManagement.messages\n}\n\nexport function isContextManagementEnabledForResponses(): boolean {\n const config = getConfig()\n return (\n config.contextManagement?.responses ?? defaultContextManagement.responses\n )\n}\n\nexport function getModelResponsesApiCompactThreshold(\n model: string,\n): number | undefined {\n const config = getConfig()\n const threshold = config.modelResponsesApiCompactThresholds?.[model]\n\n if (\n typeof threshold !== \"number\"\n || !Number.isFinite(threshold)\n || threshold <= 0\n ) {\n return undefined\n }\n\n return threshold\n}\n\nexport function getReasoningEffortForModel(\n model: string,\n): \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" {\n const config = getConfig()\n const userEffort = config.modelReasoningEfforts?.[model]\n if (userEffort !== undefined) {\n return userEffort\n }\n return isGpt53OrAbove(model) ? \"xhigh\" : \"high\"\n}\n","import consola from \"consola\"\n\nimport {\n SUPPORTED_PROVIDER_TYPES,\n getConfig,\n readEditableConfigFromDisk,\n reloadConfig,\n writeConfigToDisk,\n type ModelConfig,\n type ProviderAuthType,\n type ProviderConfig,\n type ProviderType,\n} from \"./config-store\"\n\nexport interface ResolvedProviderConfig {\n name: string\n type: ProviderType\n baseUrl: string\n apiKey: string\n authType: ProviderAuthType\n pricingCurrency?: string\n models?: Record<string, ModelConfig>\n}\n\nconst OPENCODE_ANTHROPIC_MODEL_PATTERN = /^(?:qwen|minimax)/iu\nconst OPENCODE_RESPONSES_MODEL_PATTERN = /^(?:gpt|grok|muse-spark)(?:[-_.]|$)/iu\n\nexport function normalizeProviderBaseUrl(url: string): string {\n return url.trim().replace(/\\/+$/u, \"\")\n}\n\nexport function isSupportedProviderType(value: string): value is ProviderType {\n return SUPPORTED_PROVIDER_TYPES.includes(value as ProviderType)\n}\n\nfunction getDefaultProviderAuthType(\n providerType: ProviderType,\n): ProviderAuthType {\n return providerType === \"anthropic\" ? \"x-api-key\" : \"authorization\"\n}\n\nexport function resolveProviderAuthType(\n providerName: string,\n authType: string | undefined,\n providerType: ProviderType,\n): ProviderAuthType {\n const defaultAuthType = getDefaultProviderAuthType(providerType)\n if (authType === undefined) {\n return defaultAuthType\n }\n\n if (authType === \"x-api-key\") {\n return \"x-api-key\"\n }\n\n if (authType === \"oauth2\") {\n if (providerName === \"codex\") {\n return authType\n }\n\n consola.warn(\n `Provider ${providerName} has authType 'oauth2', which is only supported by the builtin codex provider, falling back to ${defaultAuthType}`,\n )\n return defaultAuthType\n }\n\n if (authType === \"authorization\" || authType === \"azure-entra\") {\n return authType\n }\n\n consola.warn(\n `Provider ${providerName} has invalid authType '${authType}', falling back to ${defaultAuthType}`,\n )\n return defaultAuthType\n}\n\nfunction isProviderApiKeyRequired(\n providerName: string,\n authType: ProviderAuthType,\n): boolean {\n return (\n authType !== \"azure-entra\"\n && !(providerName === \"codex\" && authType === \"oauth2\")\n )\n}\n\nexport function getRawProviderConfig(name: string): ProviderConfig | null {\n const providerName = name.trim()\n if (!providerName) {\n return null\n }\n\n const config = getConfig()\n return config.providers?.[providerName] ?? null\n}\n\nexport function setProviderConfig(\n name: string,\n provider: ProviderConfig,\n): ProviderConfig {\n const providerName = name.trim()\n if (!providerName) {\n throw new Error(\"Provider name must be a non-empty string\")\n }\n\n if (isReservedProviderName(providerName)) {\n throw new Error(\n `Provider ${providerName} is reserved and cannot be configured in config.providers`,\n )\n }\n\n const editableConfig = readEditableConfigFromDisk()\n const nextConfig = {\n ...editableConfig,\n providers: {\n ...editableConfig.providers,\n [providerName]: provider,\n },\n }\n\n writeConfigToDisk(nextConfig)\n reloadConfig()\n return getRawProviderConfig(providerName) ?? provider\n}\n\nexport function getProviderConfig(name: string): ResolvedProviderConfig | null {\n const providerName = name.trim()\n if (!providerName) {\n return null\n }\n\n if (isReservedProviderName(providerName)) {\n consola.warn(\n `Provider ${providerName} is reserved and cannot be configured in config.providers`,\n )\n return null\n }\n\n const provider = getRawProviderConfig(providerName)\n if (!provider) {\n return null\n }\n\n if (provider.enabled === false) {\n return null\n }\n\n const type = provider.type ?? \"anthropic\"\n if (!isSupportedProviderType(type)) {\n consola.warn(\n `Provider ${providerName} is ignored because type '${type}' is not supported`,\n )\n return null\n }\n\n const baseUrl = normalizeProviderBaseUrl(provider.baseUrl ?? \"\")\n const authType = resolveProviderAuthType(\n providerName,\n provider.authType,\n type,\n )\n const apiKey = (provider.apiKey ?? \"\").trim()\n const missingFields = [\n ...(baseUrl ? [] : [\"baseUrl\"]),\n ...(isProviderApiKeyRequired(providerName, authType) && !apiKey ?\n [\"apiKey\"]\n : []),\n ]\n\n if (missingFields.length > 0) {\n consola.warn(\n `Provider ${providerName} is enabled but missing ${missingFields.join(\" or \")}`,\n )\n return null\n }\n\n return {\n name: providerName,\n type,\n baseUrl,\n apiKey,\n authType,\n pricingCurrency: normalizePricingCurrency(provider.pricingCurrency),\n models: provider.models,\n }\n}\n\nexport function resolveEffectiveProviderType(\n providerConfig: ResolvedProviderConfig,\n model: string,\n): ProviderType {\n const modelConfig = providerConfig.models?.[model]\n if (modelConfig?.type && isSupportedProviderType(modelConfig.type)) {\n return modelConfig.type\n }\n\n if (providerConfig.name === \"opencode-go\") {\n if (OPENCODE_ANTHROPIC_MODEL_PATTERN.test(model)) {\n return \"anthropic\"\n }\n if (OPENCODE_RESPONSES_MODEL_PATTERN.test(model)) {\n return \"openai-responses\"\n }\n }\n\n return providerConfig.type\n}\n\nfunction normalizePricingCurrency(\n value: string | undefined,\n): string | undefined {\n const currency = value?.trim().toUpperCase()\n return currency || undefined\n}\n\nexport function listEnabledProviders(): Array<string> {\n const config = getConfig()\n const providerNames = Object.keys(config.providers ?? {})\n return providerNames.filter((name) => getProviderConfig(name) !== null)\n}\n\nexport function isReservedProviderName(name: string): boolean {\n return name.trim() === \"copilot\"\n}\n"],"mappings":";;;;;;;AAIA,MAAM,yBAAyB;AAO/B,MAAM,kBAAkB,cAA4B;CAClD,IAAI,QAAQ,aAAa,SACvB;CAGF,IAAI;CACJ,IAAI;EACF,cAAc,GAAG,SAAS,WAAW,IAAI;EACzC,GAAG,UAAU,YAAY;UAClB,OAAO;EACd,QAAQ,KAAK,8BAA8B,aAAa,MAAM;WACtD;EACR,IAAI,gBAAgB,KAAA,GAClB,IAAI;GACF,GAAG,UAAU,YAAY;UACnB;;;AAOd,SAAgB,oBAAoB,UAAkB,SAAuB;CAC3E,MAAM,YAAY,KAAK,QAAQ,SAAS;CACxC,MAAM,WAAW,KAAK,KACpB,WACA,IAAI,KAAK,SAAS,SAAS,CAAC,GAAG,QAAQ,IAAI,GAAG,YAAY,uBAAuB,CAAC,SAAS,MAAM,CAAC,MACnG;CAED,GAAG,UAAU,WAAW,EAAE,WAAW,MAAM,CAAC;CAE5C,IAAI;CACJ,IAAI,kBAAkB;CACtB,IAAI;EACF,iBAAiB,GAAG,SAAS,UAAU,MAAM,IAAM;EACnD,kBAAkB;EAClB,GAAG,cAAc,gBAAgB,SAAS,OAAO;EACjD,GAAG,UAAU,eAAe;EAC5B,GAAG,UAAU,eAAe;EAC5B,iBAAiB,KAAA;EACjB,GAAG,WAAW,UAAU,SAAS;EACjC,kBAAkB;EAClB,eAAe,UAAU;UAClB,OAAO;EACd,IAAI,mBAAmB,KAAA,GACrB,IAAI;GACF,GAAG,UAAU,eAAe;UACtB;EAKV,IAAI,iBACF,IAAI;GAC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AAK,MAAM,EAC9C,OAAO;EAET,IAAI,iCAAiC,KAAK,MAAM,EAC9C,OAAO;;CAIX,OAAO,eAAe;;AAGxB,SAAS,yBACP,OACoB;CAEpB,OADiB,OAAO,MAAM,CAAC,aAAa,IACzB,KAAA;;AAGrB,SAAgB,uBAAsC;CACpD,MAAM,SAAS,WAAW;CAE1B,OADsB,OAAO,KAAK,OAAO,aAAa,EAAE,CACpC,CAAC,QAAQ,SAAS,kBAAkB,KAAK,KAAK,KAAK;;AAGzE,SAAgB,uBAAuB,MAAuB;CAC5D,OAAO,KAAK,MAAM,KAAK"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { N as PATHS, i as listEnabledProviders, n as getRawProviderConfig } from "./config-
|
|
1
|
+
import { N as PATHS, i as listEnabledProviders, n as getRawProviderConfig } from "./config-DVWu2hKk.js";
|
|
2
2
|
import { defineCommand } from "citty";
|
|
3
3
|
import consola from "consola";
|
|
4
4
|
import fs from "node:fs/promises";
|
|
@@ -89,4 +89,4 @@ const debug = defineCommand({
|
|
|
89
89
|
//#endregion
|
|
90
90
|
export { debug };
|
|
91
91
|
|
|
92
|
-
//# sourceMappingURL=debug-
|
|
92
|
+
//# sourceMappingURL=debug-DwoWAiuC.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debug-
|
|
1
|
+
{"version":3,"file":"debug-DwoWAiuC.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport { fileURLToPath } from \"node:url\"\n\nimport { getRawProviderConfig, listEnabledProviders } from \"./lib/config\"\nimport { PATHS } from \"./lib/paths\"\n\ninterface DebugInfo {\n providers: {\n codexConfigured: boolean\n enabled: Array<string>\n }\n version: string\n runtime: {\n name: string\n version: string\n platform: string\n arch: string\n }\n paths: {\n APP_DIR: string\n CONFIG_PATH: string\n GITHUB_TOKEN_PATH: string\n }\n tokenExists: boolean\n}\n\ninterface RunDebugOptions {\n json: boolean\n}\n\nasync function getPackageVersion(): Promise<string> {\n try {\n const packageJsonPath = fileURLToPath(\n new URL(\"../package.json\", import.meta.url),\n )\n // @ts-expect-error https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v59.0.1/docs/rules/prefer-json-parse-buffer.md\n // JSON.parse() can actually parse buffers\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath)) as {\n version: string\n }\n return packageJson.version\n } catch {\n return \"unknown\"\n }\n}\n\nfunction getRuntimeInfo() {\n const isBun = typeof Bun !== \"undefined\"\n\n return {\n name: isBun ? \"bun\" : \"node\",\n version: isBun ? Bun.version : process.version.slice(1),\n platform: os.platform(),\n arch: os.arch(),\n }\n}\n\nasync function checkFileExists(filePath: string): Promise<boolean> {\n try {\n const stats = await fs.stat(filePath)\n if (!stats.isFile()) return false\n\n const content = await fs.readFile(filePath, \"utf8\")\n return content.trim().length > 0\n } catch {\n return false\n }\n}\n\nasync function getDebugInfo(): Promise<DebugInfo> {\n const [version, tokenExists] = await Promise.all([\n getPackageVersion(),\n checkFileExists(PATHS.GITHUB_TOKEN_PATH),\n ])\n\n return {\n providers: {\n codexConfigured: getRawProviderConfig(\"codex\") !== null,\n enabled: listEnabledProviders(),\n },\n version,\n runtime: getRuntimeInfo(),\n paths: {\n APP_DIR: PATHS.APP_DIR,\n CONFIG_PATH: PATHS.CONFIG_PATH,\n GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH,\n },\n tokenExists,\n }\n}\n\nfunction printDebugInfoPlain(info: DebugInfo): void {\n consola.info(`copilot-api debug\n\nVersion: ${info.version}\nRuntime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})\n\nProviders:\n- enabled: ${info.providers.enabled.join(\", \") || \"none\"}\n- codex configured: ${info.providers.codexConfigured ? \"Yes\" : \"No\"}\n\nPaths:\n- APP_DIR: ${info.paths.APP_DIR}\n- CONFIG_PATH: ${info.paths.CONFIG_PATH}\n- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}\n\nGitHub token exists: ${info.tokenExists ? \"Yes\" : \"No\"}`)\n}\n\nfunction printDebugInfoJson(info: DebugInfo): void {\n console.log(JSON.stringify(info, null, 2))\n}\n\nexport async function runDebug(options: RunDebugOptions): Promise<void> {\n const debugInfo = await getDebugInfo()\n\n if (options.json) {\n printDebugInfoJson(debugInfo)\n } else {\n printDebugInfoPlain(debugInfo)\n }\n}\n\nexport const debug = defineCommand({\n meta: {\n name: \"debug\",\n description: \"Print debug information about the application\",\n },\n args: {\n json: {\n type: \"boolean\",\n default: false,\n description: \"Output debug information as JSON\",\n },\n },\n run({ args }) {\n return runDebug({\n json: args.json,\n })\n },\n})\n"],"mappings":";;;;;;;AAmCA,eAAe,oBAAqC;CAClD,IAAI;EACF,MAAM,kBAAkB,cACtB,IAAI,IAAI,mBAAmB,OAAO,KAAK,IAAI,CAC5C;EAMD,OAHoB,KAAK,MAAM,MAAM,GAAG,SAAS,gBAAgB,CAG/C,CAAC;SACb;EACN,OAAO;;;AAIX,SAAS,iBAAiB;CACxB,MAAM,QAAQ,OAAO,QAAQ;CAE7B,OAAO;EACL,MAAM,QAAQ,QAAQ;EACtB,SAAS,QAAQ,IAAI,UAAU,QAAQ,QAAQ,MAAM,EAAE;EACvD,UAAU,GAAG,UAAU;EACvB,MAAM,GAAG,MAAM;EAChB;;AAGH,eAAe,gBAAgB,UAAoC;CACjE,IAAI;EAEF,IAAI,EAAC,MADe,GAAG,KAAK,SAAS,EAC1B,QAAQ,EAAE,OAAO;EAG5B,QAAO,MADe,GAAG,SAAS,UAAU,OAAO,EACpC,MAAM,CAAC,SAAS;SACzB;EACN,OAAO;;;AAIX,eAAe,eAAmC;CAChD,MAAM,CAAC,SAAS,eAAe,MAAM,QAAQ,IAAI,CAC/C,mBAAmB,EACnB,gBAAgB,MAAM,kBAAkB,CACzC,CAAC;CAEF,OAAO;EACL,WAAW;GACT,iBAAiB,qBAAqB,QAAQ,KAAK;GACnD,SAAS,sBAAsB;GAChC;EACD;EACA,SAAS,gBAAgB;EACzB,OAAO;GACL,SAAS,MAAM;GACf,aAAa,MAAM;GACnB,mBAAmB,MAAM;GAC1B;EACD;EACD;;AAGH,SAAS,oBAAoB,MAAuB;CAClD,QAAQ,KAAK;;WAEJ,KAAK,QAAQ;WACb,KAAK,QAAQ,KAAK,GAAG,KAAK,QAAQ,QAAQ,IAAI,KAAK,QAAQ,SAAS,GAAG,KAAK,QAAQ,KAAK;;;aAGvF,KAAK,UAAU,QAAQ,KAAK,KAAK,IAAI,OAAO;sBACnC,KAAK,UAAU,kBAAkB,QAAQ,KAAK;;;aAGvD,KAAK,MAAM,QAAQ;iBACf,KAAK,MAAM,YAAY;uBACjB,KAAK,MAAM,kBAAkB;;uBAE7B,KAAK,cAAc,QAAQ,OAAO;;AAGzD,SAAS,mBAAmB,MAAuB;CACjD,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,EAAE,CAAC;;AAG5C,eAAsB,SAAS,SAAyC;CACtE,MAAM,YAAY,MAAM,cAAc;CAEtC,IAAI,QAAQ,MACV,mBAAmB,UAAU;MAE7B,oBAAoB,UAAU;;AAIlC,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;EACd;CACD,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;EACd,EACF;CACD,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,MACZ,CAAC;;CAEL,CAAC"}
|
package/dist/main.js
CHANGED
|
@@ -27,10 +27,10 @@ if (isMcpFastPath(process.argv)) {
|
|
|
27
27
|
if (process.platform === "win32" && process.stdout.isTTY && !process.env.WT_SESSION) process.env.WT_SESSION = "copilot-api";
|
|
28
28
|
const { bindElectronFetch } = await import("./electron-fetch-BRX-ug5E.js");
|
|
29
29
|
bindElectronFetch();
|
|
30
|
-
const { auth } = await import("./auth-
|
|
31
|
-
const { debug } = await import("./debug-
|
|
30
|
+
const { auth } = await import("./auth-BCZdnMmK.js");
|
|
31
|
+
const { debug } = await import("./debug-DwoWAiuC.js");
|
|
32
32
|
const { mcp } = await import("./mcp-fpSlKZxK.js");
|
|
33
|
-
const { start } = await import("./start-
|
|
33
|
+
const { start } = await import("./start-Bxq46GxM.js");
|
|
34
34
|
await runMain(defineCommand({
|
|
35
35
|
meta: {
|
|
36
36
|
name: "copilot-api",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { K as state } from "./token-
|
|
1
|
+
import { K as state } from "./token-D0GGk3E8.js";
|
|
2
2
|
//#region src/lib/models.ts
|
|
3
3
|
/**
|
|
4
4
|
* Converts a Copilot upstream model ID to a client-friendly ID that Claude Code
|
|
@@ -87,4 +87,4 @@ const normalizeSdkModelId = (sdkModelId) => {
|
|
|
87
87
|
//#endregion
|
|
88
88
|
export { toClientModelId as i, getLatestModelForFamily as n, normalizeSdkModelId as r, findEndpointModel as t };
|
|
89
89
|
|
|
90
|
-
//# sourceMappingURL=models-
|
|
90
|
+
//# sourceMappingURL=models-DKNAPa_j.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models-
|
|
1
|
+
{"version":3,"file":"models-DKNAPa_j.js","names":[],"sources":["../src/lib/models.ts"],"sourcesContent":["import type { Model } from \"~/lib/types/models\"\n\nimport { state } from \"~/lib/state\"\n\n/**\n * Converts a Copilot upstream model ID to a client-friendly ID that Claude Code\n * and Claude Desktop recognize (dots in version replaced with hyphens).\n * e.g. \"claude-sonnet-4.6\" -> \"claude-sonnet-4-6\"\n * Non-Claude models are returned unchanged.\n */\nexport const toClientModelId = (modelId: string): string => {\n const normalized = normalizeSdkModelId(modelId)\n if (!normalized) return modelId\n const versionHyphenated = normalized.version.replaceAll(\".\", \"-\")\n return `claude-${normalized.family}-${versionHyphenated}`\n}\n\nexport interface NormalizedSdkModelId {\n family: string\n version: string\n}\n\nexport const findEndpointModel = (sdkModelId: string): Model | undefined => {\n const models = state.models?.data ?? []\n const exactMatch = models.find((m) => m.id === sdkModelId)\n if (exactMatch) {\n return exactMatch\n }\n\n const normalized = normalizeSdkModelId(sdkModelId)\n if (!normalized) {\n return undefined\n }\n\n const modelName = `claude-${normalized.family}-${normalized.version}`\n const model = models.find((m) => m.id === modelName)\n if (model) {\n return model\n }\n\n return undefined\n}\n\n/**\n * Finds the latest available model for a given Claude family (e.g. \"opus\",\n * \"sonnet\", \"haiku\") among the models currently cached in `state.models`.\n * \"Latest\" is determined by the highest semantic version parsed from the model\n * ID. Returns `undefined` when no model of that family is available.\n */\nexport const getLatestModelForFamily = (family: string): Model | undefined => {\n const models = state.models?.data ?? []\n\n let best: { model: Model; major: number; minor: number } | undefined\n\n for (const model of models) {\n const normalized = normalizeSdkModelId(model.id)\n if (!normalized || normalized.family !== family) {\n continue\n }\n\n const [majorPart, minorPart = \"0\"] = normalized.version.split(\".\")\n const major = Number.parseInt(majorPart, 10)\n const minor = Number.parseInt(minorPart, 10)\n if (Number.isNaN(major) || Number.isNaN(minor)) {\n continue\n }\n\n if (\n !best\n || major > best.major\n || (major === best.major && minor > best.minor)\n ) {\n best = { model, major, minor }\n }\n }\n\n return best?.model\n}\n\n/**\n * Normalizes an SDK model ID to extract the model family and version.\n * this method from github copilot extension\n * Examples:\n * - \"claude-opus-4-5-20251101\" -> { family: \"opus\", version: \"4.5\" }\n * - \"claude-3-5-sonnet-20241022\" -> { family: \"sonnet\", version: \"3.5\" }\n * - \"claude-sonnet-4-20250514\" -> { family: \"sonnet\", version: \"4\" }\n * - \"claude-haiku-3-5-20250514\" -> { family: \"haiku\", version: \"3.5\" }\n * - \"claude-haiku-4.5\" -> { family: \"haiku\", version: \"4.5\" }\n */\nexport const normalizeSdkModelId = (\n sdkModelId: string,\n): NormalizedSdkModelId | undefined => {\n const lower = sdkModelId.toLowerCase()\n\n // Strip date suffix (8 digits at the end)\n const withoutDate = lower.replace(/-\\d{8}$/, \"\")\n\n // Pattern 1: claude-{family}-{major}.{minor} (e.g., claude-haiku-4.5)\n const pattern1 = withoutDate.match(/^claude-(\\w+)-(\\d+)\\.(\\d+)$/)\n if (pattern1) {\n return { family: pattern1[1], version: `${pattern1[2]}.${pattern1[3]}` }\n }\n\n // Pattern 2: claude-{family}-{major}-{minor} (e.g., claude-opus-4-5, claude-haiku-3-5)\n const pattern2 = withoutDate.match(/^claude-(\\w+)-(\\d+)-(\\d+)$/)\n if (pattern2) {\n return { family: pattern2[1], version: `${pattern2[2]}.${pattern2[3]}` }\n }\n\n // Pattern 3: claude-{major}-{minor}-{family} (e.g., claude-3-5-sonnet)\n const pattern3 = withoutDate.match(/^claude-(\\d+)-(\\d+)-(\\w+)$/)\n if (pattern3) {\n return { family: pattern3[3], version: `${pattern3[1]}.${pattern3[2]}` }\n }\n\n // Pattern 4: claude-{family}-{major} (e.g., claude-sonnet-4)\n const pattern4 = withoutDate.match(/^claude-(\\w+)-(\\d+)$/)\n if (pattern4) {\n return { family: pattern4[1], version: pattern4[2] }\n }\n\n // Pattern 5: claude-{major}-{family} (e.g., claude-3-opus)\n const pattern5 = withoutDate.match(/^claude-(\\d+)-(\\w+)$/)\n if (pattern5) {\n return { family: pattern5[2], version: pattern5[1] }\n }\n\n return undefined\n}\n"],"mappings":";;;;;;;;AAUA,MAAa,mBAAmB,YAA4B;CAC1D,MAAM,aAAa,oBAAoB,QAAQ;CAC/C,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,oBAAoB,WAAW,QAAQ,WAAW,KAAK,IAAI;CACjE,OAAO,UAAU,WAAW,OAAO,GAAG;;AAQxC,MAAa,qBAAqB,eAA0C;CAC1E,MAAM,SAAS,MAAM,QAAQ,QAAQ,EAAE;CACvC,MAAM,aAAa,OAAO,MAAM,MAAM,EAAE,OAAO,WAAW;CAC1D,IAAI,YACF,OAAO;CAGT,MAAM,aAAa,oBAAoB,WAAW;CAClD,IAAI,CAAC,YACH;CAGF,MAAM,YAAY,UAAU,WAAW,OAAO,GAAG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