Compare commits

..
3 Commits
Author SHA1 Message Date
KimiSwitch Dev 8221e05db1 feat(oauth): v0.7.7 — 双区域 OAuth 支持(适配 kimi-code 0.38.0 global 账号)+ 修复模型占位别名跟随 + models.dev 快照刷新
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
Release / Attach macOS install script (push) Canceled after 0s
2026-08-22 14:00:20 +08:00
KimiSwitch Dev 6b761251bc feat(usage): v0.7.6 — OpenCode Go 套餐用量查询(5h/7天/30天三窗口)+ 插件市场入口暂时隐藏(功能保留)
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
Release / Attach macOS install script (push) Canceled after 0s
2026-08-18 19:09:54 +08:00
KimiSwitch Dev 9a3875d990 feat(subagent): v0.7.5 — 适配 kimi-code 0.36.0 子代理模型池(双写兼容/池管理/force/前置校验)+ 热力图详情按需加载 + models.dev 刷新(GLM-5.3)
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
Release / Attach macOS install script (push) Canceled after 0s
2026-08-15 23:21:22 +08:00
36 changed files with 172492 additions and 140034 deletions

No files matched your search

+1 -1
View File
@@ -111,7 +111,7 @@ Rust:
## 三、悬而未决(用户已知情,待决定)
1. **OpenCode Go 账单查询**:已实测全部端点 404(`/zen/go/v1/usages`、`/api/usage`、`/api/billing` 等 12+ 路径),cc-switch 源码也不支持 → **结论:无公开 API,不可查**。文档已记录。
1. **OpenCode Go 账单查询**:~~已实测全部端点 404(`/zen/go/v1/usages`、`/api/usage`、`/api/billing` 等 12+ 路径),cc-switch 源码也不支持 → 结论:无公开 API,不可查~~。**2026-08 推翻**:`GET https://opencode.ai/zen/go/v1/usage`(Bearer + 显式浏览器 UA,否则 Cloudflare 1010 拦截 403)实测 200,已实现为 `plan:opencode_go`(滚动 5h / 周 / 月三窗口)。
2. **Kimi login 配 API key**:可以,代码已支持(api_key 优先于 OAuth)。但 managed 供应商编辑页隐藏 key 输入框(`ProviderEdit.tsx:301` `{!provider.managed && ...}`)。选项:① 用户新建 kimi-coding 预设供应商填 key;② 改 UI 让 managed 显示可选 key 输入。
3. **OAuth refresh**:**已实现**(批次 4)。过期自动用 refresh_token 换新并写回凭据文件;单 flight 锁 + 写回前重读防 CLI 竞态。已知边界:若 access token 未过期但被服务端吊销(罕见),401 不会触发重读重试——暂不处理。
4. **NewAPI 面板自动探测**:打开配置面板时探测 `{base}/api/status` 含 `quota_per_unit` → 自动预选 NewAPI 模板。已提议,未确认。
+25 -13
View File
@@ -8,11 +8,11 @@
## 1. 结论速览
- **KimiSwitch 的账单查询不是空白**:已移植 cc-switch 的「余额查询(Balance)+ 套餐查询(Coding Plan)」两大块,共 **8 种 `usageKinds`**,Rust 侧闭环 + `UsageFooter` 展示,错误通道、keep-last-good、缓存、`detect_provider` 自动识别等核心设计均与 cc-switch 对齐。
- **KimiSwitch 的账单查询不是空白**:已移植 cc-switch 的「余额查询(Balance)+ 套餐查询(Coding Plan)」两大块,共 **11 种 `usageKinds`**,Rust 侧闭环 + `UsageFooter` 展示,错误通道、keep-last-good、缓存、`detect_provider` 自动识别等核心设计均与 cc-switch 对齐。
- **OpenCode 本身不提供账单/额度查询**。它只负责"定义"供应商与订阅套餐的接入方式(provider id、base URL、认证、模型清单,数据源为 models.dev),"套餐还剩下多少"需要查各家官方 API——这正是 cc-switch(及 KimiSwitch 已移植部分)做的事。
- **本次调研发现 2 个值得补的能力缺口**:
- **本次调研发现的能力缺口**:
1. **Kimi 开放平台余额查询**(`GET https://api.moonshot.cn/v1/users/me/balance`,Kimi 官方 2026-07 新增公开 API,cc-switch 尚未实现)→ **KimiSwitch 也缺**。
2. **OpenCode Go 订阅套餐额度**(5h / 周 / 月 三窗口)→ 无公开查询 API,只有控制台,暂不可程序化。
2. **OpenCode Go 订阅套餐额度**(5h / 周 / 月 三窗口)→ 调研时结论为"无公开 API";2026-08 已实测 `GET https://opencode.ai/zen/go/v1/usage`(Bearer)可用并已实现(见 §4.4)。
- 其余缺口(ZenMux / 火山方舟 / 智谱团队版 / JS 脚本引擎 / 官方 OAuth 订阅)为 cc-switch 独有能力,与"做好现有账单查询"的目标匹配度分层,见 §6 路线。
---
@@ -26,7 +26,7 @@ ProviderList (前端)
└─ UsageFooter ── invoke("query_provider_usage", { agent, providerName, forceRefresh })
└─ Rust commands.rs:590 ── services::query_kind(kind, base_url, api_key)
├─ balance.rs (余额,5 家)
└─ coding_plan.rs (套餐,3 家)
└─ coding_plan.rs (套餐,4 家)
```
- 前端**永不持有 API key、不直连 HTTP**;所有请求在 Rust 侧用 reqwest 完成(无浏览器 CORS 问题)。
@@ -45,6 +45,7 @@ ProviderList (前端)
| `plan:kimi_coding` | **Kimi For Coding** | `GET https://api.kimi.com/coding/v1/usages` | Bearer | ✅ |
| `plan:zhipu` | **GLM Coding Plan**(bigmodel.cn / z.ai) | `GET {open.bigmodel.cn\|api.z.ai}/api/monitor/usage/quota/limit` | **Raw key(无 Bearer)** | ✅ |
| `plan:minimax` | MiniMax Token Plan (.com/.io) | `GET https://api.minimaxi.com\|.io/v1/api/openplatform/coding_plan/remains` | Bearer | ✅ |
| `plan:opencode_go` | **OpenCode Go** | `GET https://opencode.ai/zen/go/v1/usage` | Bearer(须带浏览器 UA) | ✅ |
已有预设(`providerPresets.ts`):`kimi-coding`(`plan:kimi_coding`)、`zhipu-coding` / `zai-coding`(`plan:zhipu`)、`minimax` / `minimax-token-plan`(`plan:minimax`)、`deepseek` / `stepfun` / `siliconflow` / `novita` / `openrouter`(余额)。
@@ -54,7 +55,7 @@ ProviderList (前端)
```ts
interface UsageData {
planName?: string | null; // 套餐名:five_hour / weekly_limit
planName?: string | null; // 套餐名:five_hour / weekly_limit / monthly_limit
remaining?: number | null; // 余额:金额(balance)或剩余百分比(plan)
total?: number | null; // 总量(plan 恒为 100)
used?: number | null; // 已用百分比 0-100(plan)
@@ -101,7 +102,7 @@ OpenCode(sst/opencode)通过 `~/.config/opencode/opencode.json` 的 `provide
额度按美元计费价值计算(不同模型折算请求数不同)。超出限额后可选"Use balance"回退到 Zen 余额。
**查询方式:仅控制台(console),无公开 REST API**。OpenCode 项目本身不做用量查询(无 usage/billing 命令),社区工具(如 cc-switch 的 `usage_script`)也无法覆盖 Go 套餐——这是目前的技术边界,适配时只能提示用户"网页控制台查看"或把 Go 归入"不可查询"类。
**查询方式(✅ 已实现)**:`GET https://opencode.ai/zen/go/v1/usage`,`Authorization: Bearer <api_key>`,无 query 参数。响应含 `usage.rolling / usage.weekly / usage.monthly` 三窗口,每窗口 `status / percent / resetsAt`(`percent` = 已用百分比)。2026-08 实测可用;注意该站有 Cloudflare 1010 拦截——reqwest 默认不带 User-Agent 的裸请求会被 403,请求必须显式携带浏览器 UA(见 §4.4)。
### 3.3 OpenCode 定义 → KimiSwitch 预设的对应关系
@@ -112,8 +113,8 @@ KimiSwitch 的 `providerPresets.ts` 已镜像这套体系(`baseUrl` 与 OpenCo
| `kimi-coding` | `https://api.kimi.com/coding/v1` | subscription | `plan:kimi_coding` | ✅ 可查套餐 |
| `zhipu-coding` | `https://open.bigmodel.cn/api/coding/paas/v4` | subscription | `plan:zhipu` | ✅ 可查套餐 |
| `zai-coding` | `https://api.z.ai/api/coding/paas/v4` | subscription | `plan:zhipu` | ✅ 可查套餐 |
| `opencode-go` | `https://opencode.ai/zen/go/v1` | subscription | **(空)** | ❌ 不可查,见 §4.4 |
| `opencode-zen` | `https://opencode.ai/zen/v1` | pay_as_you_go | **(空)** | ❌ 不可查 |
| `opencode-go` | `https://opencode.ai/zen/go/v1` | subscription | `plan:opencode_go` | ✅ 可查套餐,见 §4.4 |
| `opencode-zen` | `https://opencode.ai/zen/v1` | pay_as_you_go | **(空)** | ❌ 不可查(按量,无公开余额 API) |
| `moonshot` | `https://api.moonshot.ai/v1` | pay_as_you_go | **(空)** | ❌ 未挂余额查询,见 §4.3 |
---
@@ -185,12 +186,23 @@ KimiSwitch 的 `providerPresets.ts` 已镜像这套体系(`baseUrl` 与 OpenCo
- **适配点**:`moonshot` 预设 baseUrl 为 `https://api.moonshot.ai/v1`(国际站),而该端点固定 `api.moonshot.cn`(国内站)。需按 base_url 消歧:host 含 `moonshot.cn` → 查 CN 端点;`moonshot.ai` → 查 `https://api.moonshot.ai/v1/users/me/balance`(国际站对应端点,待实测确认;官方文档仅给出 CN 示例)。
- 新增 `balance:kimi` kind 即可复用现有 balance 路径,前端 `UsageFooter` 自动生效(余额形态显示 `💰 余额 ¥49.59`)。
### 4.4 OpenCode Go / Zen(❌ 未实现 —— 无公开 API,建议标注"不可查")
### 4.4 OpenCode Go / Zen(✅ Go 已实现 —— `plan:opencode_go`)
- **Go 套餐**:额度窗口见 §3.2,仅控制台可看;`opencode.ai/zen/go/v1` 只有推理端点(`/chat/completions`、`/responses`、`/models`),**无 usage/balance 端点**。
- **Zen 余额**:充值制,同样仅控制台。
- **可选替代(不推荐投入)**:通过调用推理端点时服务端返回的 402/429/额度错误头做被动感知,无法拿到数值,价值低。
- **适配结论**:`opencode-go` / `opencode-zen` 预设维持 `usageKinds` 为空;可在预设 `note`/UI 上提示"额度请在 opencode.ai 控制台查看"。
- **Go 套餐(✅ 已实现)**:端点 `GET https://opencode.ai/zen/go/v1/usage`,`Authorization: Bearer <api_key>`,无 query 参数。响应:
```json
{
"usage": {
"rolling": { "status": "ok", "percent": 9, "resetsAt": "2026-08-18T06:09:19.735Z" },
"weekly": { "status": "ok", "percent": 5, "resetsAt": "2026-08-24T00:00:00.735Z" },
"monthly": { "status": "ok", "percent": 59, "resetsAt": "2026-08-27T03:33:50.735Z" }
}
}
```
三窗口各解析为一条 `percent_tier`(`percent` = 已用百分比,映射 five_hour / weekly_limit / monthly_limit,前端 `planLabel` 已本地化);`status` 为展示字段,缺失容忍;单窗口缺失只出其余窗口。
- **坑位(实测)**:opencode.ai 有 Cloudflare 1010 拦截——reqwest 默认不带 User-Agent 的裸请求会被 403(`error code: 1010`),请求必须显式设置浏览器 UA(`coding_plan.rs::BROWSER_USER_AGENT`,经 `get_json_with_ua` 注入)。
- **Zen 余额**:充值制,仍仅控制台,未实现;`opencode-zen` 预设维持 `usageKinds` 为空。
### 4.5 其他 cc-switch 独有、KimiSwitch 未移植的能力(按目标匹配度排序)
+473 -10
View File
@@ -1,12 +1,12 @@
{
"name": "kimiswitch",
"version": "0.4.1",
"version": "0.7.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kimiswitch",
"version": "0.4.1",
"version": "0.7.6",
"dependencies": {
"@tauri-apps/api": "^2.0.0",
"@tauri-apps/plugin-opener": "^2.5.0",
@@ -24,7 +24,8 @@
"postcss": "^8.4.41",
"tailwindcss": "^3.4.10",
"typescript": "^5.5.4",
"vite": "^5.4.2"
"vite": "^5.4.2",
"vitest": "^3.2.7"
}
},
"node_modules/@alloc/quick-lru": {
@@ -1502,6 +1503,24 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/deep-eql": "*",
"assertion-error": "^2.0.1"
}
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.9.tgz",
@@ -1558,6 +1577,121 @@
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
}
},
"node_modules/@vitest/expect": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz",
"integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/spy": "3.2.7",
"@vitest/utils": "3.2.7",
"chai": "^5.2.0",
"tinyrainbow": "^2.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/mocker": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz",
"integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/spy": "3.2.7",
"estree-walker": "^3.0.3",
"magic-string": "^0.30.17"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
},
"peerDependenciesMeta": {
"msw": {
"optional": true
},
"vite": {
"optional": true
}
}
},
"node_modules/@vitest/pretty-format": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz",
"integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"tinyrainbow": "^2.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/runner": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz",
"integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/utils": "3.2.7",
"pathe": "^2.0.3",
"strip-literal": "^3.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/snapshot": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz",
"integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "3.2.7",
"magic-string": "^0.30.17",
"pathe": "^2.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/spy": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz",
"integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"tinyspy": "^4.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/utils": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz",
"integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "3.2.7",
"loupe": "^3.1.4",
"tinyrainbow": "^2.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/any-promise": {
"version": "1.3.0",
"resolved": "https://registry.npmmirror.com/any-promise/-/any-promise-1.3.0.tgz",
@@ -1586,6 +1720,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/autoprefixer": {
"version": "10.5.2",
"resolved": "https://registry.npmmirror.com/autoprefixer/-/autoprefixer-10.5.2.tgz",
@@ -1696,6 +1840,16 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/cac": {
"version": "6.7.14",
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
"integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/camelcase-css": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/camelcase-css/-/camelcase-css-2.0.1.tgz",
@@ -1727,6 +1881,33 @@
],
"license": "CC-BY-4.0"
},
"node_modules/chai": {
"version": "5.3.3",
"resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
"integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
"dev": true,
"license": "MIT",
"dependencies": {
"assertion-error": "^2.0.1",
"check-error": "^2.1.1",
"deep-eql": "^5.0.1",
"loupe": "^3.1.0",
"pathval": "^2.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/check-error": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
"integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 16"
}
},
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-3.6.0.tgz",
@@ -1820,6 +2001,16 @@
}
}
},
"node_modules/deep-eql": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
"integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/didyoumean": {
"version": "1.2.2",
"resolved": "https://registry.npmmirror.com/didyoumean/-/didyoumean-1.2.2.tgz",
@@ -1851,6 +2042,13 @@
"node": ">= 0.4"
}
},
"node_modules/es-module-lexer": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
"integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
"dev": true,
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.21.5",
"resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.21.5.tgz",
@@ -1900,6 +2098,26 @@
"node": ">=6"
}
},
"node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0"
}
},
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/fast-glob": {
"version": "3.3.3",
"resolved": "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.3.3.tgz",
@@ -2164,6 +2382,13 @@
"loose-envify": "cli.js"
}
},
"node_modules/loupe": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
"integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
"dev": true,
"license": "MIT"
},
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -2183,6 +2408,16 @@
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/merge2": {
"version": "1.4.1",
"resolved": "https://registry.npmmirror.com/merge2/-/merge2-1.4.1.tgz",
@@ -2227,9 +2462,9 @@
}
},
"node_modules/nanoid": {
"version": "3.3.15",
"resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.15.tgz",
"integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
"version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
"dev": true,
"funding": [
{
@@ -2292,6 +2527,23 @@
"dev": true,
"license": "MIT"
},
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
"dev": true,
"license": "MIT"
},
"node_modules/pathval": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
"integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 14.16"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
@@ -2333,9 +2585,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.16",
"resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.16.tgz",
"integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
"version": "8.5.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
"integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
"dev": true,
"funding": [
{
@@ -2353,7 +2605,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.12",
"nanoid": "^3.3.17",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -2695,6 +2947,13 @@
"semver": "bin/semver.js"
}
},
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
"integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
"dev": true,
"license": "ISC"
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -2705,6 +2964,40 @@
"node": ">=0.10.0"
}
},
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
"dev": true,
"license": "MIT"
},
"node_modules/std-env": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
"integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
"dev": true,
"license": "MIT"
},
"node_modules/strip-literal": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",
"integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"js-tokens": "^9.0.1"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/strip-literal/node_modules/js-tokens": {
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz",
"integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==",
"dev": true,
"license": "MIT"
},
"node_modules/sucrase": {
"version": "3.35.1",
"resolved": "https://registry.npmmirror.com/sucrase/-/sucrase-3.35.1.tgz",
@@ -2802,6 +3095,20 @@
"node": ">=0.8"
}
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
"integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
"dev": true,
"license": "MIT"
},
"node_modules/tinyexec": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",
"integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
"dev": true,
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -2850,6 +3157,36 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/tinypool": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
"integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.0.0 || >=20.0.0"
}
},
"node_modules/tinyrainbow": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz",
"integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/tinyspy": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz",
"integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -2982,6 +3319,132 @@
}
}
},
"node_modules/vite-node": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz",
"integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==",
"dev": true,
"license": "MIT",
"dependencies": {
"cac": "^6.7.14",
"debug": "^4.4.1",
"es-module-lexer": "^1.7.0",
"pathe": "^2.0.3",
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
},
"bin": {
"vite-node": "vite-node.mjs"
},
"engines": {
"node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/vitest": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz",
"integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/expect": "3.2.7",
"@vitest/mocker": "3.2.7",
"@vitest/pretty-format": "^3.2.7",
"@vitest/runner": "3.2.7",
"@vitest/snapshot": "3.2.7",
"@vitest/spy": "3.2.7",
"@vitest/utils": "3.2.7",
"chai": "^5.2.0",
"debug": "^4.4.1",
"expect-type": "^1.2.1",
"magic-string": "^0.30.17",
"pathe": "^2.0.3",
"picomatch": "^4.0.2",
"std-env": "^3.9.0",
"tinybench": "^2.9.0",
"tinyexec": "^0.3.2",
"tinyglobby": "^0.2.14",
"tinypool": "^1.1.1",
"tinyrainbow": "^2.0.0",
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0",
"vite-node": "3.2.4",
"why-is-node-running": "^2.3.0"
},
"bin": {
"vitest": "vitest.mjs"
},
"engines": {
"node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@edge-runtime/vm": "*",
"@types/debug": "^4.1.12",
"@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
"@vitest/browser": "3.2.7",
"@vitest/ui": "3.2.7",
"happy-dom": "*",
"jsdom": "*"
},
"peerDependenciesMeta": {
"@edge-runtime/vm": {
"optional": true
},
"@types/debug": {
"optional": true
},
"@types/node": {
"optional": true
},
"@vitest/browser": {
"optional": true
},
"@vitest/ui": {
"optional": true
},
"happy-dom": {
"optional": true
},
"jsdom": {
"optional": true
}
}
},
"node_modules/vitest/node_modules/picomatch": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
"integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
"dev": true,
"license": "MIT",
"dependencies": {
"siginfo": "^2.0.0",
"stackback": "0.0.2"
},
"bin": {
"why-is-node-running": "cli.js"
},
"engines": {
"node": ">=8"
}
},
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmmirror.com/yallist/-/yallist-3.1.1.tgz",
+4 -2
View File
@@ -1,7 +1,7 @@
{
"name": "kimiswitch",
"private": true,
"version": "0.7.4",
"version": "0.7.7",
"type": "module",
"scripts": {
"dev": "vite",
@@ -9,6 +9,7 @@
"build": "tsc && vite build",
"fetch-models-dev": "node scripts/fetch-models-dev.mjs",
"preview": "vite preview",
"test": "vitest run",
"tauri": "tauri",
"pretauri": "node scripts/fetch-models-dev.mjs || echo fetch-models-dev failed, using existing snapshot",
"tauri-dev": "tauri dev",
@@ -31,6 +32,7 @@
"postcss": "^8.4.41",
"tailwindcss": "^3.4.10",
"typescript": "^5.5.4",
"vite": "^5.4.2"
"vite": "^5.4.2",
"vitest": "^3.2.7"
}
}
+37
View File
@@ -0,0 +1,37 @@
## v0.7.5
### 子代理模型池适配(kimi-code 0.36.0 新引擎)
- 适配 kimi-code v2 的 `[secondary_model]` 模型池语义:`default_model` + `[secondary_model.models]` 表 + `force`
- **双写兼容**:写入配置时 `model` 与 `default_model` 同步同值,v1 legacy 引擎(`KIMI_CODE_LEGACY_FLAG=1`)与 v2 引擎均可正常识别
- 高级设置页新增**模型池管理**:升级旧配置为模型池、增删池条目、编辑每条目的路由描述(渲染进主代理 Agent/AgentSwarm 工具描述,直接影响主模型对子代理模型的调度质量)
- 支持 **force 强制默认模型**开关(开启会清空池条目,带二次确认)
- 保存前本地校验:primary 保留别名、池条目与 default_model 一致性、别名必须已注册、force 与池互斥等 6 类错误前置拦截
- 新增 32 个单元测试覆盖池读写与校验逻辑(vitest)
### 仪表盘热力图详情改为按需加载
- 双击热力图方块改为调用后端 `get_day_detail` 按需聚合当日数据,**不再受当前 7d / 30d 范围限制**,任何有数据的日期都可查看明细
- 无数据日期双击给出提示,不再静默无响应
### 模型数据更新
- models.dev 快照刷新至 2026-08-15(6583 模型 / 185 供应商),新增 **GLM-5.3** 等一批新模型(含定价与能力标记)
### Downloads by platform
- **Windows**: `.msi` installer
- **macOS**: `.dmg` + `.app`(未签名,仅 Apple Silicon / M 系列芯片)
- **Linux**: `.deb` / `.AppImage` / `.rpm`
### macOS 安装说明(无开发者账号签名,需一次手动绕过)
1. 下载 `Kimi.Switch_*.dmg`,双击挂载后把 `Kimi Switch.app` 拖入「应用程序」文件夹
2. 下载本 Release 附带的 `install-macos.sh`,在终端运行:
```bash
bash install-macos.sh
```
脚本会自动清除下载隔离属性并启动应用,只需执行一次,之后正常使用。
3. 手动替代方案:右键 `Kimi Switch.app` → 打开 → 弹窗点「打开」;或 系统设置 → 隐私与安全性 → 仍要打开
+30
View File
@@ -0,0 +1,30 @@
## v0.7.6
### OpenCode Go 套餐用量查询
- 新增 **OpenCode Go 套餐额度查询**:供应商卡片用量页脚显示 **5 小时滚动 / 7 天 / 30 天** 三个窗口的已用百分比与重置时间(数据源为 opencode.ai 官方 usage API)
- 数据源:`GET https://opencode.ai/zen/go/v1/usage`(Bearer 认证),直接解析官方 `rolling / weekly / monthly` 三窗口的 `percent` 与 `resetsAt`
- **老配置自动适配**:已配置 OpenCode Go API Key 的现有用户无需任何手动设置,程序按 `base_url` 自动识别并启用用量查询
- 兼容处理:已适配 opencode.ai 的 Cloudflare 拦截(请求携带浏览器 User-Agent),并对外部接口失败给出可读的错误提示
### 插件目录占用错误提示优化
- 插件目录被运行中进程占用时的错误提示给出明确指引(底层改进)
### Downloads by platform
- **Windows**: `.msi` installer
- **macOS**: `.dmg` + `.app`(未签名,仅 Apple Silicon / M 系列芯片)
- **Linux**: `.deb` / `.AppImage` / `.rpm`
### macOS 安装说明(无开发者账号签名,需一次手动绕过)
1. 下载 `Kimi.Switch_*.dmg`,双击挂载后把 `Kimi Switch.app` 拖入「应用程序」文件夹
2. 下载本 Release 附带的 `install-macos.sh`,在终端运行:
```bash
bash install-macos.sh
```
脚本会自动清除下载隔离属性并启动应用,只需执行一次,之后正常使用。
3. 手动替代方案:右键 `Kimi Switch.app` → 打开 → 弹窗点「打开」;或 系统设置 → 隐私与安全性 → 仍要打开
+18
View File
@@ -0,0 +1,18 @@
## v0.7.7
### 双区域 OAuth 支持(适配 kimi-code 0.38.0)
- 适配官方 CLI v0.38.0 引入的双区域登录(mainland-cn `auth.kimi.com` / global `auth.kimi.ai`,#2862)
- **凭据动态解析**:按 provider 的 oauth ref(`key` / `oauthHost`)推导凭据文件与 token 刷新端点,global 账号(`credentials/kimi-code-env-<sha256>.json`)可正常查询用量;无 oauth ref 的老配置完全走旧路径,零回归
- **用量查询区域适配**:`api.kimi.ai/coding` 识别为官方套餐,usages 查询按 provider base_url 拼接
- **内置登录区域选择**:应用内 Kimi 登录对话框新增「中国大陆 / 国际版 (kimi.ai)」选择,登录成功后同步落盘凭据 + 按官方 CLI 行为 provision `[providers."managed:kimi-code"]`(global 写 `oauthHost`,cn 不写,保持区域信号正确)
- scoped key 推导与官方 CLI 逐字节一致(`JSON.stringify({oauthHost, baseUrl})` 的 sha256 前 16 位 hex),hash 值经独立复算验证
### 修复
- 修复手动添加模型后模型用量显示为 `xxx/新模型` 而非真实模型名:填入实际模型 ID 时别名自动跟随为 `<provider>/<model-id>`(含输入中间态跟随),连续添加占位条目不再互相覆盖
- 修复 managed(OAuth)供应商自填 `api_key` 在保存配置时被清空的问题:无 key 时按官方 provisioned 形态写空行,用户自填 key 完整保留
### 模型数据更新
- models.dev 快照刷新(**7246 模型 / 193 供应商**):新增 **DeepSeek V4 Flash Vision Exp**(官方定价与 v4-flash 一致)、**Ox Alpha Free**(opencode-go,免费)等
+53 -1
View File
@@ -59,6 +59,15 @@ version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
[[package]]
name = "arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -710,6 +719,17 @@ dependencies = [
"serde_core",
]
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.118",
]
[[package]]
name = "derive_more"
version = "2.1.1"
@@ -1958,7 +1978,7 @@ dependencies = [
[[package]]
name = "kimiswitch"
version = "0.7.4"
version = "0.7.7"
dependencies = [
"anyhow",
"chrono",
@@ -1971,13 +1991,16 @@ dependencies = [
"rusqlite",
"serde",
"serde_json",
"sha2",
"tauri",
"tauri-build",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tempfile",
"tokio",
"toml 0.8.23",
"walkdir",
"zip",
]
[[package]]
@@ -5484,12 +5507,41 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "zip"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
dependencies = [
"arbitrary",
"crc32fast",
"crossbeam-utils",
"displaydoc",
"flate2",
"indexmap 2.14.0",
"memchr",
"thiserror 2.0.18",
"zopfli",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
[[package]]
name = "zopfli"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zvariant"
version = "5.12.0"
+11 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "kimiswitch"
version = "0.7.4"
version = "0.7.7"
description = "Kimi Switch - model config manager"
authors = ["codingplan.site"]
edition = "2021"
@@ -25,7 +25,16 @@ futures-util = "0.3"
dirs = "5.0"
toml = "0.8"
rusqlite = { version = "0.32", features = ["bundled", "chrono"] }
tokio = { version = "1", features = ["sync"] }
tokio = { version = "1", features = ["sync", "fs", "io-util"] }
# Plugin marketplace: zip extraction (deflate-only; no extra compression
# backends needed for plugin archives).
zip = { version = "2", default-features = false, features = ["deflate"] }
# Scoped OAuth credential keys (oauth/kimi-code-env-<sha256>) for non-mainland
# regions, mirroring the official CLI's resolveKimiCodeOAuthKey.
sha2 = "0.10"
[dev-dependencies]
tempfile = "3"
[lib]
name = "kimiswitch_lib"
+21 -9
View File
@@ -658,7 +658,12 @@ pub async fn query_provider_usage(
});
let mut oauth_err: Option<String> = None;
if api_key.is_none() && provider.managed {
match crate::oauth::get_valid_access_token().await {
// Resolve the credential slot + refresh host from the provider's oauth
// ref (region-aware); with no ref this falls back to the mainland
// default, preserving pre-region behavior.
let oauth_ref = crate::oauth::oauth_ref_from_provider(provider);
let oauth_base_url = provider.base_url.as_deref().unwrap_or("");
match crate::oauth::get_valid_access_token(oauth_ref.as_ref(), oauth_base_url).await {
Ok(token) => api_key = Some(token),
Err(e) => oauth_err = Some(e),
}
@@ -1249,22 +1254,29 @@ pub fn open_external_url(app: tauri::AppHandle, url: String) -> Result<(), Strin
// Kimi OAuth device-code sign-in (in-app replacement for `kimi login`)
// ---------------------------------------------------------------------------
/// Step 1: ask auth.kimi.com for a user_code + verification URI.
/// Step 1: ask the region's OAuth host for a user_code + verification URI.
/// `region` is `"cn"` (default) or `"global"`.
#[tauri::command]
pub async fn kimi_oauth_start() -> Result<crate::oauth::DeviceAuthorization, String> {
crate::oauth::start_device_authorization().await
pub async fn kimi_oauth_start(
region: Option<String>,
) -> Result<crate::oauth::DeviceAuthorization, String> {
let region = crate::oauth::KimiRegion::from_opt(region.as_deref());
crate::oauth::start_device_authorization(region).await
}
/// Step 2: poll the token endpoint until the user approves. On success the
/// tokens are written to the CLI credentials file (`kimi login` no longer
/// needed). Errors are transient (network); deterministic outcomes
/// (pending / success / expired / denied / timeout) come back in the enum.
/// Step 2: poll the region's token endpoint until the user approves. On
/// success the tokens are written to the region's credentials file and the
/// provider is provisioned in config.toml (`kimi login` no longer needed).
/// Errors are transient (network); deterministic outcomes (pending / success /
/// expired / denied / timeout) come back in the enum.
#[tauri::command]
pub async fn kimi_oauth_poll(
device_code: String,
interval: i64,
region: Option<String>,
) -> Result<crate::oauth::DevicePollStatus, String> {
crate::oauth::poll_device_token(&device_code, interval).await
let region = crate::oauth::KimiRegion::from_opt(region.as_deref());
crate::oauth::poll_device_token(&device_code, interval, region).await
}
// ---------------------------------------------------------------------------
+67 -3
View File
@@ -345,7 +345,10 @@ pub struct UsageRecord {
// Helpers
// ---------------------------------------------------------------------------
fn resolve_kimi_home(override_path: Option<String>) -> PathBuf {
/// Resolve the Kimi Code home directory: explicit override, then
/// `KIMI_CODE_HOME`, then the default `~/.kimi-code`. Shared with the plugin
/// marketplace module (`crate::plugins`).
pub(crate) fn resolve_kimi_home(override_path: Option<String>) -> PathBuf {
if let Some(p) = override_path {
if !p.trim().is_empty() {
return PathBuf::from(p);
@@ -1753,10 +1756,9 @@ pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh
let t2 = std::time::Instant::now();
let scan_ms = t1.duration_since(t0).as_secs_f64() * 1000.0;
let aggregate_ms = t2.duration_since(t1).as_secs_f64() * 1000.0;
let total_ms = t2.duration_since(t0).as_secs_f64() * 1000.0;
eprintln!(
"[dashboard] get_summary range={} records={} scan={:.0}ms aggregate={:.0}ms total={:.0}ms",
r, records.len(), scan_ms, aggregate_ms, total_ms
r, records.len(), scan_ms, aggregate_ms, t2.duration_since(t0).as_secs_f64() * 1000.0
);
SummaryResult {
@@ -1774,6 +1776,68 @@ pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh
}
}
/// Aggregate a single calendar day into a `DailyRow` — lazy detail for the
/// heatmap double-click modal. Returns `None` when the date has no records.
fn build_day_detail(date: &str, records: &[UsageRecord]) -> Option<DailyRow> {
let mut t = TotalsRow::default();
let mut by_model: HashMap<String, TotalsRow> = HashMap::new();
let mut by_provider_model: HashMap<String, HashMap<String, u64>> = HashMap::new();
let mut found = false;
for r in records {
if day_key(r.time) != date {
continue;
}
found = true;
t.add(r);
by_model.entry(r.model.clone()).or_default().add(r);
let p = r.provider.clone().unwrap_or_else(|| "unknown".to_string());
*by_provider_model
.entry(p)
.or_default()
.entry(r.model.clone())
.or_insert(0) += r.input_other + r.output + r.input_cache_read + r.input_cache_creation;
}
if !found {
return None;
}
let ti = t.input_other + t.input_cache_read + t.input_cache_creation;
let ch = if ti > 0 { t.input_cache_read as f64 / ti as f64 } else { 0.0 };
let by_model: HashMap<String, TotalsRow> = by_model
.into_iter()
.map(|(k, mut mt)| {
let mi = mt.input_other + mt.input_cache_read + mt.input_cache_creation;
mt.cache_hit_rate = if mi > 0 { mt.input_cache_read as f64 / mi as f64 } else { 0.0 };
(k, mt)
})
.collect();
Some(DailyRow {
date: date.to_string(),
requests: t.requests,
input_other: t.input_other,
output: t.output,
input_cache_read: t.input_cache_read,
input_cache_creation: t.input_cache_creation,
cost_usd: t.cost_usd,
total_tokens: t.total_tokens,
cache_hit_rate: ch,
by_model,
by_provider: by_provider_model
.iter()
.map(|(p, m)| (p.clone(), m.values().sum::<u64>()))
.collect(),
by_provider_model,
})
}
/// Lazy per-day detail for the heatmap double-click modal (fetched on demand,
/// so `get_summary` stays lean). Returns null when the date has no records.
#[tauri::command]
pub fn get_day_detail(home_override: Option<String>, date: String) -> Option<DailyRow> {
let home = resolve_kimi_home(home_override);
let (records, _) = scan_usage_cached(&home, false);
build_day_detail(&date, &records)
}
#[tauri::command]
pub fn list_sessions(home_override: Option<String>, status: Option<String>, workspace: Option<String>) -> SessionsResult {
let home = resolve_kimi_home(home_override);
+77 -1
View File
@@ -261,7 +261,15 @@ pub fn config_to_kimi_code(config: &Config, existing: Option<&TomlValue>) -> Tom
if let Some(base_url) = provider.base_url.clone().filter(|s| !s.is_empty()) {
pt.insert("base_url".to_string(), TomlValue::String(base_url));
}
if let Some(api_key) = provider.api_key.clone().filter(|s| !s.is_empty()) {
// Managed (OAuth) providers persist an empty api_key line so the block
// matches the official CLI's provisioned shape (apiKey: ''). A
// user-set api_key on a managed provider (api_key outranks OAuth in
// the CLI's credential priority) must survive the round-trip.
if provider.managed
&& provider.api_key.as_deref().map_or(true, |s| s.is_empty())
{
pt.insert("api_key".to_string(), TomlValue::String("".to_string()));
} else if let Some(api_key) = provider.api_key.clone().filter(|s| !s.is_empty()) {
pt.insert("api_key".to_string(), TomlValue::String(api_key));
}
pt.insert("enabled".to_string(), TomlValue::Boolean(provider.enabled));
@@ -864,4 +872,72 @@ max_context_size = 1048576
"private default_model must not leak into config.toml"
);
}
#[test]
fn kimi_code_export_managed_api_key_roundtrip() {
// Regression: a managed (OAuth) provider keeps the official provisioned
// shape (empty api_key line) when it has no key, but a user-set api_key
// on a managed provider (api_key outranks OAuth in the CLI's credential
// priority) must survive the round-trip.
let managed_provider = |api_key: Option<&str>| Provider {
name: "managed:kimi-code".to_string(),
provider_type: ProviderType::Kimi,
base_url: Some("https://api.kimi.com/coding/v1".to_string()),
api_key: api_key.map(String::from),
env: IndexMap::new(),
note: None,
official_url: None,
managed: true,
enabled: true,
active: true,
icon: None,
icon_color: None,
raw_other: serde_json::json!({
"oauth": {"storage": "file", "key": "oauth/kimi-code"}
}),
usage_kinds: None,
usage_config: None,
};
// No api_key → the empty provisioned line is written.
let config = Config {
default_model: None,
providers: IndexMap::from([(
"managed:kimi-code".to_string(),
managed_provider(None),
)]),
models: IndexMap::new(),
raw_other: Value::Null,
};
let exported = config_to_kimi_code(&config, None);
let provider = exported
.as_table().unwrap()
.get("providers").unwrap()
.as_table().unwrap()
.get("managed:kimi-code").unwrap()
.as_table().unwrap();
assert_eq!(provider.get("api_key").and_then(|v| v.as_str()), Some(""));
// User-set api_key on a managed provider survives.
let config = Config {
default_model: None,
providers: IndexMap::from([(
"managed:kimi-code".to_string(),
managed_provider(Some("sk-user-key")),
)]),
models: IndexMap::new(),
raw_other: Value::Null,
};
let exported = config_to_kimi_code(&config, None);
let provider = exported
.as_table().unwrap()
.get("providers").unwrap()
.as_table().unwrap()
.get("managed:kimi-code").unwrap()
.as_table().unwrap();
assert_eq!(
provider.get("api_key").and_then(|v| v.as_str()),
Some("sk-user-key")
);
}
}
+7
View File
@@ -6,6 +6,7 @@ pub mod kimi_code_io;
pub mod models;
pub mod oauth;
pub mod pi_io;
pub mod plugins;
pub mod services;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
@@ -117,12 +118,18 @@ pub fn run() {
dashboard::get_paths,
dashboard::get_prices,
dashboard::get_summary,
dashboard::get_day_detail,
dashboard::list_sessions,
dashboard::archive_session,
dashboard::unarchive_session,
dashboard::delete_session,
dashboard::delete_workspace,
dashboard::get_session_preview,
plugins::get_plugin_marketplace,
plugins::list_installed_plugins,
plugins::install_plugin,
plugins::set_plugin_enabled,
plugins::remove_plugin,
])
.manage(commands::KimiWebState::default())
.build(tauri::generate_context!())
+480 -41
View File
@@ -30,7 +30,16 @@
//! 2. user opens the verification URI in a browser and approves;
//! 3. `poll_device_token()` polls POST /api/oauth/token with the device_code
//! grant until the tokens arrive, then writes them to the same
//! `~/.kimi-code/credentials/kimi-code.json` file the CLI uses.
//! `~/.kimi-code/credentials/<key>.json` file the CLI uses.
//!
//! v4 mirrors the official CLI's dual-region OAuth (v0.38.0, #2862): the login
//! flow and credential lookup are scoped by region. The mainland-cn region
//! (default) uses the shared `oauth/kimi-code` slot (`credentials/kimi-code.json`)
//! and persists no `oauthHost`; the global region derives a scoped key
//! `oauth/kimi-code-env-<sha256>` from (oauthHost, baseUrl), writes
//! `credentials/<scoped>.json`, and persists `oauthHost` in config.toml. Usage
//! queries and token refresh resolve their credentials path + refresh endpoint
//! from the provider's oauth ref instead of always assuming mainland.
use serde::{Deserialize, Serialize};
@@ -40,12 +49,181 @@ use crate::kimi_code_io::kimi_code_config_dir;
/// mid-request counts as expired.
const EXPIRY_LEEWAY_SECS: i64 = 30;
/// OAuth token endpoint (confirmed in the official kimi.exe binary).
const TOKEN_ENDPOINT: &str = "https://auth.kimi.com/api/oauth/token";
/// Device authorization endpoint (RFC 8628).
const DEVICE_AUTHORIZATION_ENDPOINT: &str = "https://auth.kimi.com/api/oauth/device_authorization";
/// Region endpoints (mirror `packages/oauth/src/region.ts`).
const CN_OAUTH_HOST: &str = "https://auth.kimi.com";
const CN_BASE_URL: &str = "https://api.kimi.com/coding/v1";
const GLOBAL_OAUTH_HOST: &str = "https://auth.kimi.ai";
const GLOBAL_BASE_URL: &str = "https://api.kimi.ai/coding/v1";
/// Shared mainland credential slot (mirror `KIMI_CODE_OAUTH_KEY`).
const DEFAULT_OAUTH_KEY: &str = "oauth/kimi-code";
/// Prefix of region-scoped credential keys (mirror `KIMI_CODE_SCOPED_OAUTH_KEY_PREFIX`).
const SCOPED_OAUTH_KEY_PREFIX: &str = "oauth/kimi-code-env-";
/// OAuth token endpoint host suffix (remaining path after the oauth host).
const TOKEN_PATH: &str = "/api/oauth/token";
/// Device authorization endpoint suffix (RFC 8628).
const DEVICE_AUTHORIZATION_PATH: &str = "/api/oauth/device_authorization";
/// Public OAuth client id used by the official CLI (from kimi.exe).
const CLIENT_ID: &str = "17e5f671-d194-4dfb-9706-5516cb48c098";
/// The managed Kimi Code provider name in config.toml.
const MANAGED_PROVIDER_NAME: &str = "managed:kimi-code";
/// A Kimi Code account region (mainland `.com` vs global `.ai`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KimiRegion {
/// Mainland China — `auth.kimi.com` / `api.kimi.com`.
Cn,
/// International — `auth.kimi.ai` / `api.kimi.ai`.
Global,
}
impl KimiRegion {
/// Parse a region hint from the frontend (`"cn"` default, `"global"`).
pub fn from_opt(s: Option<&str>) -> KimiRegion {
match s.map(|s| s.trim().to_ascii_lowercase()).as_deref() {
Some("global") => KimiRegion::Global,
_ => KimiRegion::Cn,
}
}
pub fn oauth_host(self) -> &'static str {
match self {
KimiRegion::Cn => CN_OAUTH_HOST,
KimiRegion::Global => GLOBAL_OAUTH_HOST,
}
}
/// Managed API base (`/coding/v1`): usages host for this region.
pub fn base_url(self) -> &'static str {
match self {
KimiRegion::Cn => CN_BASE_URL,
KimiRegion::Global => GLOBAL_BASE_URL,
}
}
}
/// The oauth ref stored under a provider's `raw_other["oauth"]`
/// (`storage`/`key`/`oauthHost`), all optional for lenient parsing.
/// `storage` is not read (Kimi Switch only ever uses `file`).
#[derive(Debug, Clone, Default)]
pub struct OAuthRef {
pub key: Option<String>,
pub oauth_host: Option<String>,
}
/// Extract the oauth ref from a provider's `raw_other["oauth"]` block, if any.
pub fn oauth_ref_from_provider(provider: &crate::models::Provider) -> Option<OAuthRef> {
let oauth = provider.raw_other.get("oauth")?.as_object()?;
Some(OAuthRef {
key: oauth.get("key").and_then(|v| v.as_str()).map(String::from),
oauth_host: oauth
.get("oauthHost")
.and_then(|v| v.as_str())
.map(String::from),
})
}
/// Map an oauth credential `key` to the credentials-file storage name, mirroring
/// the official CLI's `resolveKimiTokenStorageName`:
/// - `"kimi-code"` / `"oauth/kimi-code"` → `"kimi-code"` (file kimi-code.json)
/// - `"oauth/<name>"` → `<name>`
/// - `<name>` (no `/`, not `.`-prefixed) → `<name>` verbatim
/// - anything else → Err
pub fn resolve_storage_name(key: &str) -> Result<String, String> {
if key == "kimi-code" || key == DEFAULT_OAUTH_KEY {
return Ok("kimi-code".to_string());
}
if let Some(rest) = key.strip_prefix("oauth/") {
if !rest.is_empty() {
return Ok(rest.to_string());
}
}
if !key.contains('/') && !key.starts_with('.') {
return Ok(key.to_string());
}
Err(format!("Invalid Kimi OAuth token key: {key}"))
}
/// `trim().replace(/\/+$/, '')`, matching the CLI's `normalizeEndpoint`.
fn normalize_endpoint(s: &str) -> String {
s.trim().trim_end_matches('/').to_string()
}
/// Derive the oauth credential key for an (oauth_host, base_url) pair, mirroring
/// the official CLI's `resolveKimiCodeOAuthKey`: the mainland defaults map to the
/// shared `oauth/kimi-code` slot; anything else gets a scoped slot
/// `oauth/kimi-code-env-<sha256>` of `JSON.stringify({oauthHost, baseUrl})`.
///
/// The payload must byte-match JS `JSON.stringify({ oauthHost, baseUrl })`
/// (oauthHost first, no spaces), so it is hand-built with `format!` rather than
/// `serde_json::json!` (which can't guarantee field order or exact whitespace).
pub fn derive_scoped_key(oauth_host: &str, base_url: &str) -> String {
let oauth_host = normalize_endpoint(oauth_host);
let base_url = normalize_endpoint(base_url);
if oauth_host == CN_OAUTH_HOST && base_url == CN_BASE_URL {
return DEFAULT_OAUTH_KEY.to_string();
}
let payload = format!(
"{{\"oauthHost\":\"{oauth_host}\",\"baseUrl\":\"{base_url}\"}}"
);
use sha2::{Digest, Sha256};
let digest = Sha256::digest(payload.as_bytes());
let hex = digest.iter().map(|b| format!("{b:02x}")).collect::<String>();
format!("{SCOPED_OAUTH_KEY_PREFIX}{}", &hex[..16])
}
/// Resolved credential context for a usage query / token refresh: which
/// credentials file to read/write and which OAuth host to refresh against.
struct OAuthContext {
storage_name: String,
oauth_host: String,
}
impl OAuthContext {
/// Resolve from an optional oauth ref + provider base_url.
///
/// - No ref → the legacy mainland default (`credentials/kimi-code.json` +
/// `auth.kimi.com`), so a provider with no oauth block behaves exactly as
/// before the region work.
/// - Ref with a `key` → use that key's storage (scoped slot for global).
/// - Ref with only `oauthHost` (no key) → derive the scoped key from
/// (oauthHost, base_url), matching the CLI's `resolveKimiCodeOAuthRef`.
fn from(oauth_ref: Option<&OAuthRef>, base_url: &str) -> OAuthContext {
let (key, oauth_host) = match oauth_ref {
Some(r) => {
let host = r
.oauth_host
.clone()
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| CN_OAUTH_HOST.to_string());
let k = r
.key
.clone()
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| derive_scoped_key(&host, base_url));
(k, host)
}
None => (DEFAULT_OAUTH_KEY.to_string(), CN_OAUTH_HOST.to_string()),
};
let storage_name =
resolve_storage_name(&key).unwrap_or_else(|_| "kimi-code".to_string());
OAuthContext {
storage_name,
oauth_host,
}
}
fn token_endpoint(&self) -> String {
format!("{}{TOKEN_PATH}", self.oauth_host.trim_end_matches('/'))
}
}
/// Credentials file path for a given storage name.
fn credentials_path_for_storage(storage_name: &str) -> std::path::PathBuf {
kimi_code_config_dir()
.join("credentials")
.join(format!("{storage_name}.json"))
}
/// Refresh request timeout; refresh is rare, a bit more headroom than the 8s
/// query default is fine.
const REFRESH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
@@ -80,17 +258,11 @@ impl OAuthCredentials {
}
}
fn credentials_path() -> std::path::PathBuf {
kimi_code_config_dir()
.join("credentials")
.join("kimi-code.json")
}
/// Load the Kimi Code OAuth session. Errors are deterministic (missing file /
/// unreadable JSON), never transient — the caller turns them into
/// `Ok(success:false)`.
pub fn load_kimi_code_credentials() -> Result<OAuthCredentials, String> {
let path = credentials_path();
/// Load OAuth session from the credentials file for a storage name. Errors are
/// deterministic (missing file / unreadable JSON), never transient — the caller
/// turns them into `Ok(success:false)`.
fn load_credentials_for_storage(storage_name: &str) -> Result<OAuthCredentials, String> {
let path = credentials_path_for_storage(storage_name);
let content = std::fs::read_to_string(&path).map_err(|e| {
format!(
"Kimi Code OAuth credentials not found at {}: {e}. Run `kimi login` first.",
@@ -101,6 +273,11 @@ pub fn load_kimi_code_credentials() -> Result<OAuthCredentials, String> {
.map_err(|e| format!("Failed to parse Kimi Code OAuth credentials: {e}"))
}
/// Load the legacy mainland Kimi Code OAuth session (`kimi-code.json`).
pub fn load_kimi_code_credentials() -> Result<OAuthCredentials, String> {
load_credentials_for_storage("kimi-code")
}
#[derive(Debug, Deserialize)]
struct TokenResponse {
access_token: String,
@@ -118,10 +295,16 @@ fn refresh_lock() -> &'static tokio::sync::Mutex<()> {
}
/// Return a usable access token, refreshing via the refresh_token grant when
/// the stored one is expired. Errors are deterministic (missing/dead session)
/// — the caller surfaces them as `Ok(success:false)`.
pub async fn get_valid_access_token() -> Result<String, String> {
let creds = load_kimi_code_credentials()?;
/// the stored one is expired. The credential file and refresh endpoint are
/// resolved from the provider's oauth ref + base_url (see [`OAuthContext`]);
/// with no ref this is the legacy mainland default. Errors are deterministic
/// (missing/dead session) — the caller surfaces them as `Ok(success:false)`.
pub async fn get_valid_access_token(
oauth_ref: Option<&OAuthRef>,
base_url: &str,
) -> Result<String, String> {
let ctx = OAuthContext::from(oauth_ref, base_url);
let creds = load_credentials_for_storage(&ctx.storage_name)?;
if !creds.is_expired() {
return Ok(creds.access_token);
}
@@ -129,11 +312,11 @@ pub async fn get_valid_access_token() -> Result<String, String> {
let _guard = refresh_lock().lock().await;
// Re-read under the lock: the CLI or a previous waiter may have refreshed
// while we were waiting.
let creds = load_kimi_code_credentials()?;
let creds = load_credentials_for_storage(&ctx.storage_name)?;
if !creds.is_expired() {
return Ok(creds.access_token);
}
refresh_credentials(&creds).await
refresh_credentials(&creds, &ctx).await
}
/// Merge a token endpoint response into the existing credentials JSON,
@@ -181,8 +364,9 @@ fn merge_token_response(current_json: &str, resp: &TokenResponse) -> String {
}
/// Call the token endpoint with the refresh_token grant and persist the
/// rotated tokens. Caller must hold [`refresh_lock`].
async fn refresh_credentials(creds: &OAuthCredentials) -> Result<String, String> {
/// rotated tokens. The refresh endpoint + file come from the resolved context.
/// Caller must hold [`refresh_lock`].
async fn refresh_credentials(creds: &OAuthCredentials, ctx: &OAuthContext) -> Result<String, String> {
let refresh_token = creds
.refresh_token
.clone()
@@ -198,7 +382,7 @@ async fn refresh_credentials(creds: &OAuthCredentials) -> Result<String, String>
// Tokens only ever go into the request body — never into logs or errors.
let resp = client
.post(TOKEN_ENDPOINT)
.post(ctx.token_endpoint())
.form(&[
("grant_type", "refresh_token"),
("client_id", CLIENT_ID),
@@ -226,7 +410,7 @@ async fn refresh_credentials(creds: &OAuthCredentials) -> Result<String, String>
// Re-read right before writing: if the CLI refreshed meanwhile, its newer
// (rotated) tokens win — overwriting them would kill its next refresh.
let path = credentials_path();
let path = credentials_path_for_storage(&ctx.storage_name);
let current = std::fs::read_to_string(&path).unwrap_or_default();
if let Ok(latest) = serde_json::from_str::<OAuthCredentials>(&current) {
if !latest.is_expired() && latest.access_token != creds.access_token {
@@ -326,17 +510,20 @@ fn identity_headers() -> Vec<(&'static str, String)> {
headers
}
/// Step 1 of the device flow: ask the server for a user_code + device_code.
/// No user interaction required here; the frontend shows the code + URL.
pub async fn start_device_authorization() -> Result<DeviceAuthorization, String> {
/// Step 1 of the device flow: ask the region's server for a user_code +
/// device_code. No user interaction required here; the frontend shows the
/// code + URL.
pub async fn start_device_authorization(region: KimiRegion) -> Result<DeviceAuthorization, String> {
let client = reqwest::Client::builder()
.timeout(REFRESH_TIMEOUT)
.build()
.map_err(|e| format!("Failed to build HTTP client: {e}"))?;
let mut req = client
.post(DEVICE_AUTHORIZATION_ENDPOINT)
.form(&[("client_id", CLIENT_ID)]);
let endpoint = format!(
"{}{DEVICE_AUTHORIZATION_PATH}",
region.oauth_host().trim_end_matches('/')
);
let mut req = client.post(&endpoint).form(&[("client_id", CLIENT_ID)]);
for (name, value) in identity_headers() {
req = req.header(name, value);
}
@@ -356,24 +543,30 @@ pub async fn start_device_authorization() -> Result<DeviceAuthorization, String>
.map_err(|e| format!("Failed to parse device authorization response: {e}"))
}
/// Step 2 of the device flow: poll the token endpoint until the user
/// Step 2 of the device flow: poll the region's token endpoint until the user
/// approves (or the flow fails). On success the tokens are merged into the
/// CLI credentials file, making `kimi login` unnecessary.
/// region's credentials file and the provider is provisioned, making
/// `kimi login` unnecessary.
pub async fn poll_device_token(
device_code: &str,
initial_interval: i64,
region: KimiRegion,
) -> Result<DevicePollStatus, String> {
let client = reqwest::Client::builder()
.timeout(REFRESH_TIMEOUT)
.build()
.map_err(|e| format!("Failed to build HTTP client: {e}"))?;
let token_endpoint = format!(
"{}{TOKEN_PATH}",
region.oauth_host().trim_end_matches('/')
);
let deadline = std::time::Instant::now() + POLL_TIMEOUT;
let mut interval = initial_interval.max(1);
loop {
let mut req = client
.post(TOKEN_ENDPOINT)
.post(&token_endpoint)
.form(&[
("grant_type", DEVICE_GRANT_TYPE),
("client_id", CLIENT_ID),
@@ -393,7 +586,7 @@ pub async fn poll_device_token(
Ok(t) => t,
Err(e) => return Err(format!("Failed to parse token response: {e}")),
};
persist_device_token(&token)?;
persist_device_token(&token, region)?;
return Ok(DevicePollStatus::Success);
}
@@ -424,17 +617,89 @@ pub async fn poll_device_token(
}
}
/// Write a freshly obtained token set into the CLI credentials file,
/// preserving unrelated fields and using the same snake_case shape.
fn persist_device_token(token: &TokenResponse) -> Result<(), String> {
let path = credentials_path();
/// Write a freshly obtained token set into the region's credentials file,
/// preserving unrelated fields and using the same snake_case shape, then
/// provision the managed provider in config.toml (mirroring the CLI).
///
/// cn writes the shared `credentials/kimi-code.json`; global resolves the
/// scoped key from (oauthHost, baseUrl) and writes `credentials/<scoped>.json`.
fn persist_device_token(token: &TokenResponse, region: KimiRegion) -> Result<(), String> {
let key = derive_scoped_key(region.oauth_host(), region.base_url());
let storage_name = resolve_storage_name(&key)?;
let path = credentials_path_for_storage(&storage_name);
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
let current = std::fs::read_to_string(&path).unwrap_or_default();
let merged = merge_token_response(&current, token);
std::fs::write(&path, merged)
.map_err(|e| format!("Failed to write Kimi credentials: {e}"))
.map_err(|e| format!("Failed to write Kimi credentials: {e}"))?;
provision_managed_provider(region, &key)
}
/// Update `[providers."managed:kimi-code"]` in config.toml so the official CLI
/// can use the freshly obtained credentials (mirror the CLI's post-login
/// provisioning / `authService.provisionProvider`): ensure the provider exists,
/// `type="kimi"`, `base_url=<region baseUrl>`, `api_key=""`, and the oauth ref
/// block `{storage="file", key=<region key>}` — `oauthHost` is persisted only
/// for global (cn writes none, so `key == "oauth/kimi-code"` stays the
/// explicit-mainland signal). Other fields (icon, ...) are left untouched; the
/// round-trip preserves every unrelated section.
fn provision_managed_provider(region: KimiRegion, oauth_key: &str) -> Result<(), String> {
use indexmap::IndexMap;
let mut config = crate::kimi_code_io::load_kimi_code_config_as_config()
.map_err(|e| format!("Failed to read Kimi Code config: {e}"))?;
let provider = config
.providers
.entry(MANAGED_PROVIDER_NAME.to_string())
.or_insert_with(|| crate::models::Provider {
name: MANAGED_PROVIDER_NAME.to_string(),
provider_type: crate::models::ProviderType::Kimi,
base_url: None,
api_key: None,
env: IndexMap::new(),
note: None,
official_url: None,
managed: true,
enabled: true,
active: false,
icon: None,
icon_color: None,
raw_other: serde_json::Value::Object(serde_json::Map::new()),
usage_kinds: None,
usage_config: None,
});
provider.provider_type = crate::models::ProviderType::Kimi;
provider.base_url = Some(region.base_url().to_string());
provider.api_key = Some(String::new());
provider.managed = true;
let mut oauth = serde_json::Map::new();
oauth.insert(
"storage".to_string(),
serde_json::Value::String("file".to_string()),
);
oauth.insert(
"key".to_string(),
serde_json::Value::String(oauth_key.to_string()),
);
if region == KimiRegion::Global {
oauth.insert(
"oauthHost".to_string(),
serde_json::Value::String(region.oauth_host().to_string()),
);
}
if let Some(obj) = provider.raw_other.as_object_mut() {
obj.insert("oauth".to_string(), serde_json::Value::Object(oauth));
} else {
provider.raw_other = serde_json::json!({ "oauth": oauth });
}
crate::kimi_code_io::save_config_as_kimi_code(&config)
.map_err(|e| format!("Failed to write Kimi Code config: {e}"))
}
#[cfg(test)]
@@ -569,4 +834,178 @@ mod tests {
let success = serde_json::to_value(DevicePollStatus::Success).unwrap();
assert_eq!(success["status"], "success");
}
// ── region / credential-key resolution ────────────────────────────────
#[test]
fn resolve_storage_name_maps_all_branches() {
// Default slot.
assert_eq!(resolve_storage_name("kimi-code").unwrap(), "kimi-code");
assert_eq!(resolve_storage_name("oauth/kimi-code").unwrap(), "kimi-code");
// oauth/<name> strips the prefix.
assert_eq!(resolve_storage_name("oauth/foo").unwrap(), "foo");
// Bare name without '/' is kept verbatim.
assert_eq!(resolve_storage_name("custom").unwrap(), "custom");
// Invalid keys → Err.
assert!(resolve_storage_name("oauth/").is_err(), "empty suffix");
assert!(resolve_storage_name(".hidden").is_err(), "dot-prefixed");
assert!(resolve_storage_name("a/b").is_err(), "contains slash");
}
#[test]
fn derive_scoped_key_returns_default_for_mainland() {
assert_eq!(
derive_scoped_key("https://auth.kimi.com", "https://api.kimi.com/coding/v1"),
"oauth/kimi-code"
);
// Trailing slashes / whitespace normalize to the defaults.
assert_eq!(
derive_scoped_key(" https://auth.kimi.com/ ", "https://api.kimi.com/coding/v1/"),
"oauth/kimi-code"
);
}
#[test]
fn derive_scoped_key_scopes_by_endpoint_pair() {
let key = derive_scoped_key("https://auth.kimi.ai", "https://api.kimi.ai/coding/v1");
assert!(key.starts_with("oauth/kimi-code-env-"), "key: {key}");
let hex = &key["oauth/kimi-code-env-".len()..];
assert_eq!(hex.len(), 16, "key: {key}");
assert!(hex.chars().all(|c| c.is_ascii_hexdigit()), "key: {key}");
// Byte-exact vs JS JSON.stringify({oauthHost, baseUrl}) — precomputed,
// guards against serde field order / whitespace drift.
assert_eq!(key, "oauth/kimi-code-env-0e4f99c69cc27850");
}
#[test]
fn oauth_context_defaults_without_ref() {
let ctx = OAuthContext::from(None, "https://api.kimi.com/coding/v1");
assert_eq!(ctx.storage_name, "kimi-code");
assert_eq!(ctx.oauth_host, "https://auth.kimi.com");
assert_eq!(ctx.token_endpoint(), "https://auth.kimi.com/api/oauth/token");
}
#[test]
fn oauth_context_defaults_without_ref_even_for_custom_base() {
// Zero-regression: a ref-less provider must keep using the legacy
// mainland slot regardless of its base_url (derive only kicks in when
// an oauth ref carries an oauthHost).
let ctx = OAuthContext::from(None, "https://proxy.example.com/coding/v1");
assert_eq!(ctx.storage_name, "kimi-code");
assert_eq!(ctx.oauth_host, "https://auth.kimi.com");
}
#[test]
fn oauth_context_derives_scoped_key_when_ref_has_only_oauth_host() {
let r = OAuthRef {
key: None,
oauth_host: Some("https://auth.kimi.ai".to_string()),
};
let ctx = OAuthContext::from(Some(&r), "https://api.kimi.ai/coding/v1");
assert_eq!(ctx.storage_name, "kimi-code-env-0e4f99c69cc27850");
assert_eq!(ctx.oauth_host, "https://auth.kimi.ai");
}
#[test]
fn oauth_context_follows_ref_key_and_host() {
let r = OAuthRef {
key: Some("oauth/kimi-code-env-0e4f99c69cc27850".to_string()),
oauth_host: Some("https://auth.kimi.ai".to_string()),
};
let ctx = OAuthContext::from(Some(&r), "https://api.kimi.ai/coding/v1");
assert_eq!(ctx.storage_name, "kimi-code-env-0e4f99c69cc27850");
assert_eq!(ctx.oauth_host, "https://auth.kimi.ai");
assert_eq!(ctx.token_endpoint(), "https://auth.kimi.ai/api/oauth/token");
}
// ── login persistence + provisioning (via KIMI_CODE_HOME temp dir) ─────
/// Run `f` with `KIMI_CODE_HOME` pointed at a fresh temp dir (the config
/// dir). A process-wide mutex serializes env mutation so parallel tests in
/// this binary can't observe a stale override.
fn with_kimi_code_home<T>(f: impl FnOnce(&std::path::Path) -> T) -> T {
static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
let _guard = LOCK.get_or_init(|| std::sync::Mutex::new(())).lock().unwrap();
let home = tempfile::tempdir().unwrap();
std::env::set_var("KIMI_CODE_HOME", home.path());
let out = f(home.path());
std::env::remove_var("KIMI_CODE_HOME");
out
}
#[test]
fn persist_cn_login_writes_default_slot_and_provisions_without_oauth_host() {
with_kimi_code_home(|dir| {
// Pre-existing config with an unrelated section must survive.
std::fs::write(dir.join("config.toml"), "[thinking]\nenabled = true\n").unwrap();
let token = TokenResponse {
access_token: "cn-access".to_string(),
refresh_token: Some("cn-refresh".to_string()),
expires_in: Some(900),
scope: Some("kimi-code".to_string()),
token_type: None,
};
persist_device_token(&token, KimiRegion::Cn).unwrap();
// Credentials land in the shared default slot.
let cred =
std::fs::read_to_string(dir.join("credentials/kimi-code.json")).unwrap();
assert!(cred.contains("cn-access"), "cred: {cred}");
// Provider provisioned with the cn base_url and NO oauthHost.
let cfg_toml = std::fs::read_to_string(dir.join("config.toml")).unwrap();
let cfg: toml::Value = cfg_toml.parse().unwrap();
let provider = &cfg["providers"]["managed:kimi-code"];
assert_eq!(provider["type"].as_str(), Some("kimi"));
assert_eq!(
provider["base_url"].as_str(),
Some("https://api.kimi.com/coding/v1")
);
assert_eq!(provider["api_key"].as_str(), Some(""));
let oauth = &provider["oauth"];
assert_eq!(oauth["storage"].as_str(), Some("file"));
assert_eq!(oauth["key"].as_str(), Some("oauth/kimi-code"));
assert!(
oauth.get("oauthHost").is_none(),
"cn must not persist oauthHost"
);
// Unrelated section preserved by the round-trip.
assert_eq!(cfg["thinking"]["enabled"].as_bool(), Some(true));
});
}
#[test]
fn persist_global_login_writes_scoped_slot_and_provisions_oauth_host() {
with_kimi_code_home(|dir| {
std::fs::write(dir.join("config.toml"), "").unwrap();
let token = TokenResponse {
access_token: "global-access".to_string(),
refresh_token: Some("global-refresh".to_string()),
expires_in: Some(900),
scope: Some("kimi-code".to_string()),
token_type: None,
};
persist_device_token(&token, KimiRegion::Global).unwrap();
let key = derive_scoped_key("https://auth.kimi.ai", "https://api.kimi.ai/coding/v1");
assert_eq!(key, "oauth/kimi-code-env-0e4f99c69cc27850");
let storage = resolve_storage_name(&key).unwrap();
let cred =
std::fs::read_to_string(dir.join(format!("credentials/{storage}.json"))).unwrap();
assert!(cred.contains("global-access"), "cred: {cred}");
let cfg_toml = std::fs::read_to_string(dir.join("config.toml")).unwrap();
let cfg: toml::Value = cfg_toml.parse().unwrap();
let provider = &cfg["providers"]["managed:kimi-code"];
assert_eq!(
provider["base_url"].as_str(),
Some("https://api.kimi.ai/coding/v1")
);
let oauth = &provider["oauth"];
assert_eq!(oauth["key"].as_str(), Some(key.as_str()));
assert_eq!(oauth["oauthHost"].as_str(), Some("https://auth.kimi.ai"));
});
}
}
File diff suppressed because it is too large. Load diff
+23 -4
View File
@@ -37,16 +37,35 @@ pub(crate) enum Fetched {
///
/// 先 `bytes()` 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
/// 后解析失败才是确定性。reqwest 的 `.json()` 把读体错误也包成 decode,无法区分。
///
/// 默认不带 User-Agent;需要自定义 UA 的供应商(如 opencode.ai 有 Cloudflare
/// 1010 拦截,必须带浏览器 UA)走 [`get_json_with_ua`]。
pub(crate) async fn get_json(
url: &str,
api_key: &str,
auth: AuthStyle,
timeout: Duration,
) -> Result<Fetched, String> {
let client = reqwest::Client::builder()
.timeout(timeout)
.build()
.map_err(|e| format!("Failed to build HTTP client: {e}"))?;
get_json_with_ua(url, api_key, auth, timeout, None).await
}
/// [`get_json`] 的 UA 变体:`user_agent` 为 `Some` 时设到 client 上。
/// 仅新增链路需要,现有调用方不受影响。
pub(crate) async fn get_json_with_ua(
url: &str,
api_key: &str,
auth: AuthStyle,
timeout: Duration,
user_agent: Option<&str>,
) -> Result<Fetched, String> {
let mut builder = reqwest::Client::builder().timeout(timeout);
if let Some(ua) = user_agent {
builder = builder.user_agent(ua);
}
let client = match builder.build() {
Ok(c) => c,
Err(e) => return Err(format!("Failed to build HTTP client: {e}")),
};
// 注意:api_key 只允许进请求头,严禁拼进 URL / 日志 / 错误信息。
let req = client.get(url).header("Accept", "application/json");
+204 -15
View File
@@ -3,23 +3,24 @@
//! Token Plan 套餐额度查询服务
//!
//! 支持 Kimi For Coding、智谱 GLM、MiniMax 的套餐额度查询。
//! 支持 Kimi For Coding、智谱 GLM、MiniMax、OpenCode Go 的套餐额度查询。
//! cc-switch 的 SubscriptionQuota/tiers 结构在此展平为 `Vec<UsageData>`:
//! 每个窗口(tier)一条 UsageData,`plan_name` = tier 名("five_hour" /
//! "weekly_limit"),`used` = 已用百分比(0-100),`total` = 100,
//! "weekly_limit" / "monthly_limit"),`used` = 已用百分比(0-100),`total` = 100,
//! `remaining` = 剩余百分比,`resets_at` 为 ISO 8601 字符串。
//!
//! 错误通道语义与 balance.rs 一致(Err = 瞬时,Ok(success:false) = 确定性)。
use super::balance::{get_json, AuthStyle, Fetched};
use super::balance::{get_json, get_json_with_ua, AuthStyle, Fetched};
use super::usage_types::{UsageData, UsageResult};
use std::time::Duration;
// 套餐类 tier id 的唯一来源:所有套餐供应商(Kimi/智谱/MiniMax 及未来新增)
// 都只用这两个 id。前端 src/lib/usage-display.ts 的 planLabel() 依赖此约定
// 做本地化映射——新增 tier id 时必须同步加映射。
// 套餐类 tier id 的唯一来源:所有套餐供应商(Kimi/智谱/MiniMax/OpenCode Go 及
// 未来新增)都只用这三个 id。前端 src/lib/usage-display.ts 的 planLabel() 依赖
// 此约定做本地化映射——新增 tier id 时必须同步加映射。
const TIER_FIVE_HOUR: &str = "five_hour";
const TIER_WEEKLY_LIMIT: &str = "weekly_limit";
const TIER_MONTHLY_LIMIT: &str = "monthly_limit";
/// 套餐条目的统一构造:按百分比表示用量。
fn percent_tier(name: &str, used_percent: f64, resets_at: Option<String>) -> UsageData {
@@ -66,18 +67,30 @@ fn parse_f64(value: &serde_json::Value) -> Option<f64> {
}
// ── Kimi For Coding ─────────────────────────────────────────
// GET https://api.kimi.com/coding/v1/usages
// GET {base_url}/usages
// 默认 https://api.kimi.com/coding/v1/usages
// global: https://api.kimi.ai/coding/v1/usages
// Response: { limits: [{ detail: { limit, remaining, resetTime } }],
// usage: { limit, remaining, resetTime } }
pub async fn query_kimi_coding(api_key: &str, timeout: Duration) -> Result<UsageResult, String> {
match get_json(
"https://api.kimi.com/coding/v1/usages",
api_key,
AuthStyle::Bearer,
timeout,
)
.await?
/// 由 base_url 拼接 usages 查询 URL;base_url 为空/空白时回退大陆默认。
/// 纯函数,便于单测。
fn kimi_coding_usages_url(base_url: &str) -> String {
let base = if base_url.trim().is_empty() {
"https://api.kimi.com/coding/v1"
} else {
base_url.trim_end_matches('/')
};
format!("{base}/usages")
}
pub async fn query_kimi_coding(
base_url: &str,
api_key: &str,
timeout: Duration,
) -> Result<UsageResult, String> {
let url = kimi_coding_usages_url(base_url);
match get_json(&url, api_key, AuthStyle::Bearer, timeout).await?
{
Fetched::Body(body) => {
let tiers = parse_kimi_coding(&body);
@@ -315,11 +328,114 @@ fn parse_minimax(body: &serde_json::Value) -> Result<Vec<UsageData>, UsageResult
Ok(tiers)
}
// ── OpenCode Go ─────────────────────────────────────────────
// GET https://opencode.ai/zen/go/v1/usage
// Response: { usage: { rolling: { status, percent, resetsAt },
// weekly: { status, percent, resetsAt },
// monthly: { status, percent, resetsAt } } }
// percent = 已用百分比(与 percent_tier 语义一致);status 仅作展示参考,缺失容忍;
// resetsAt 为 ISO 8601 字符串。
//
// 坑位:opencode.ai 有 Cloudflare 1010 拦截——reqwest 默认不带 User-Agent 的
// 裸请求会被 403(error code: 1010)。必须显式设置浏览器 UA。
const BROWSER_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36";
pub async fn query_opencode_go(
api_key: &str,
timeout: Duration,
) -> Result<UsageResult, String> {
match get_json_with_ua(
"https://opencode.ai/zen/go/v1/usage",
api_key,
AuthStyle::Bearer,
timeout,
Some(BROWSER_USER_AGENT),
)
.await?
{
Fetched::Body(body) => {
let tiers = parse_opencode_go(&body);
if tiers.is_empty() {
// 响应里没有可解析的用量窗口(usage 缺失或字段变了)。
// 把原始响应(仅用量数字,无密钥)透出,方便对照接口结构修复。
return Ok(opencode_go_empty_failure(&body));
}
Ok(UsageResult::ok(tiers))
}
Fetched::Failed(err) => Ok(err),
}
}
/// usage 全缺时的确定性失败,附 400 字原始响应预览。抽成纯函数便于离线单测。
fn opencode_go_empty_failure(body: &serde_json::Value) -> UsageResult {
let preview = serde_json::to_string(body)
.unwrap_or_else(|_| "<unserializable body>".into());
let trimmed: String = preview.chars().take(400).collect();
UsageResult::failure(format!(
"opencode go usage 响应无套餐数据,原始返回: {trimmed}"
))
}
/// 三个窗口(5 小时滚动 / 周 / 月)各解析为一条 `percent_tier`;
/// 缺失或 percent 不可解析的窗口跳过(status 字段可缺)。
fn parse_opencode_go(body: &serde_json::Value) -> Vec<UsageData> {
let mut tiers = Vec::new();
let Some(usage) = body.get("usage") else {
return tiers;
};
let windows = [
(TIER_FIVE_HOUR, "rolling"),
(TIER_WEEKLY_LIMIT, "weekly"),
(TIER_MONTHLY_LIMIT, "monthly"),
];
for (name, key) in windows {
let Some(window) = usage.get(key) else {
continue;
};
let Some(percent) = window.get("percent").and_then(parse_f64) else {
continue;
};
let resets_at = window.get("resetsAt").and_then(extract_reset_time);
tiers.push(percent_tier(name, percent, resets_at));
}
tiers
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn kimi_coding_usages_url_uses_base_and_falls_back() {
// global base → .ai usages URL
assert_eq!(
kimi_coding_usages_url("https://api.kimi.ai/coding/v1"),
"https://api.kimi.ai/coding/v1/usages"
);
// 尾斜杠去掉
assert_eq!(
kimi_coding_usages_url("https://api.kimi.ai/coding/v1/"),
"https://api.kimi.ai/coding/v1/usages"
);
// 空串/空白回退大陆默认
assert_eq!(
kimi_coding_usages_url(""),
"https://api.kimi.com/coding/v1/usages"
);
assert_eq!(
kimi_coding_usages_url(" "),
"https://api.kimi.com/coding/v1/usages"
);
// 大陆 base 原样拼接
assert_eq!(
kimi_coding_usages_url("https://api.kimi.com/coding/v1"),
"https://api.kimi.com/coding/v1/usages"
);
}
#[test]
fn kimi_coding_flattens_limits_and_usage() {
let body = json!({
@@ -429,4 +545,77 @@ mod tests {
assert!(!err.success);
assert!(err.error.unwrap().contains("invalid key"));
}
#[test]
fn opencode_go_parses_three_windows() {
// 真实 key 实测样例(2026-08):percent 为已用百分比,直接透传
let body = json!({
"usage": {
"rolling": { "status": "ok", "percent": 9, "resetsAt": "2026-08-18T06:09:19.735Z" },
"weekly": { "status": "ok", "percent": 5, "resetsAt": "2026-08-24T00:00:00.735Z" },
"monthly": { "status": "ok", "percent": 59, "resetsAt": "2026-08-27T03:33:50.735Z" }
}
});
let tiers = parse_opencode_go(&body);
assert_eq!(tiers.len(), 3);
assert_eq!(tiers[0].plan_name.as_deref(), Some("five_hour"));
assert_eq!(tiers[0].used, Some(9.0));
assert_eq!(tiers[0].total, Some(100.0));
assert_eq!(tiers[0].remaining, Some(91.0));
assert_eq!(
tiers[0].resets_at.as_deref(),
Some("2026-08-18T06:09:19.735Z")
);
assert_eq!(tiers[1].plan_name.as_deref(), Some("weekly_limit"));
assert_eq!(tiers[1].used, Some(5.0));
assert_eq!(tiers[1].remaining, Some(95.0));
assert_eq!(tiers[2].plan_name.as_deref(), Some("monthly_limit"));
assert_eq!(tiers[2].used, Some(59.0));
assert_eq!(tiers[2].remaining, Some(41.0));
}
#[test]
fn opencode_go_tolerates_missing_status_field() {
// status 属展示字段,缺失照常解析(percent/resetsAt 都只要求本身存在)
let body = json!({
"usage": {
"rolling": { "percent": 9, "resetsAt": "2026-08-18T06:09:19.735Z" },
"weekly": { "percent": 5, "resetsAt": "2026-08-24T00:00:00.735Z" },
"monthly": { "percent": 59, "resetsAt": "2026-08-27T03:33:50.735Z" }
}
});
let tiers = parse_opencode_go(&body);
assert_eq!(tiers.len(), 3);
assert_eq!(tiers[1].plan_name.as_deref(), Some("weekly_limit"));
assert_eq!(tiers[2].used, Some(59.0));
}
#[test]
fn opencode_go_partial_windows_only_emit_present_ones() {
// 单窗口缺失只出两条;percent 缺失 / 非数字的窗口整窗跳过
let body = json!({
"usage": {
"rolling": { "status": "ok", "percent": "9", "resetsAt": "2026-08-18T06:09:19.735Z" },
"monthly": { "status": "ok", "resetsAt": "2026-08-27T03:33:50.735Z" }
}
});
let tiers = parse_opencode_go(&body);
assert_eq!(tiers.len(), 1);
// percent 以字符串给出也兼容(parse_f64)
assert_eq!(tiers[0].plan_name.as_deref(), Some("five_hour"));
assert_eq!(tiers[0].used, Some(9.0));
}
#[test]
fn opencode_go_missing_usage_is_deterministic_failure_with_preview() {
// usage 全缺:确定性失败,附原始响应预览(400 字内,无密钥)
let body = json!({ "error": { "message": "boom" } });
assert!(parse_opencode_go(&body).is_empty());
let err = opencode_go_empty_failure(&body);
assert!(!err.success);
assert!(err.data.is_none());
let msg = err.error.unwrap();
assert!(msg.contains("原始返回"), "msg: {msg}");
assert!(msg.contains(r#""message":"boom""#), "msg: {msg}");
}
}
+55 -5
View File
@@ -3,7 +3,7 @@
//! 供应商账单/用量查询统一入口。
//!
//! - [`UsageKind`]:8 种查询类型,字符串形式与前端 / SQLite settings 约定一致
//! - [`UsageKind`]:11 种查询类型,字符串形式与前端 / SQLite settings 约定一致
//! (如 `"balance:deepseek"`、`"plan:kimi_coding"`)。
//! - [`detect_provider`]:按 base_url host 子串匹配,旧用户无显式配置时自动识别。
//! - [`query_kind`]:按 kind 路由到 balance / coding_plan 的具体实现。
@@ -26,6 +26,7 @@ pub enum UsageKind {
PlanKimiCoding,
PlanZhipu,
PlanMinimax,
PlanOpencodeGo,
}
impl UsageKind {
@@ -42,10 +43,11 @@ impl UsageKind {
UsageKind::PlanKimiCoding => "plan:kimi_coding",
UsageKind::PlanZhipu => "plan:zhipu",
UsageKind::PlanMinimax => "plan:minimax",
UsageKind::PlanOpencodeGo => "plan:opencode_go",
}
}
pub const ALL: [UsageKind; 10] = [
pub const ALL: [UsageKind; 11] = [
UsageKind::BalanceDeepseek,
UsageKind::BalanceSiliconflow,
UsageKind::BalanceOpenrouter,
@@ -56,6 +58,7 @@ impl UsageKind {
UsageKind::PlanKimiCoding,
UsageKind::PlanZhipu,
UsageKind::PlanMinimax,
UsageKind::PlanOpencodeGo,
];
}
@@ -74,6 +77,7 @@ impl std::str::FromStr for UsageKind {
"plan:kimi_coding" => UsageKind::PlanKimiCoding,
"plan:zhipu" => UsageKind::PlanZhipu,
"plan:minimax" => UsageKind::PlanMinimax,
"plan:opencode_go" => UsageKind::PlanOpencodeGo,
_ => return Err(()),
})
}
@@ -104,7 +108,9 @@ pub fn detect_provider(base_url: &str) -> Vec<UsageKind> {
if url.contains("api.moonshot.cn") || url.contains("api.moonshot.ai") {
kinds.push(UsageKind::BalanceKimi);
}
if url.contains("api.kimi.com") && url.contains("/coding") {
if (url.contains("api.kimi.com") || url.contains("api.kimi.ai"))
&& url.contains("/coding")
{
kinds.push(UsageKind::PlanKimiCoding);
}
if url.contains("open.bigmodel.cn") || url.contains("api.z.ai") {
@@ -113,6 +119,10 @@ pub fn detect_provider(base_url: &str) -> Vec<UsageKind> {
if url.contains("api.minimaxi.com") {
kinds.push(UsageKind::PlanMinimax);
}
// OpenCode Go 套餐:只认 /zen/go 路径;/zen/v1(OpenCode Zen 按量付费)不得命中。
if url.contains("/zen/go") {
kinds.push(UsageKind::PlanOpencodeGo);
}
kinds
}
@@ -161,11 +171,14 @@ pub async fn query_kind(
.unwrap_or(base_url);
balance::query_newapi(url, token, uid, timeout).await
}
UsageKind::PlanKimiCoding => coding_plan::query_kimi_coding(api_key, timeout).await,
UsageKind::PlanKimiCoding => {
coding_plan::query_kimi_coding(base_url, api_key, timeout).await
}
UsageKind::PlanZhipu => coding_plan::query_zhipu(base_url, api_key, timeout).await,
UsageKind::PlanMinimax => {
coding_plan::query_minimax(api_key, !lower.contains("minimax.io"), timeout).await
}
UsageKind::PlanOpencodeGo => coding_plan::query_opencode_go(api_key, timeout).await,
}
}
@@ -175,7 +188,7 @@ mod tests {
#[test]
fn detect_provider_maps_known_hosts() {
let cases: [(&str, UsageKind); 9] = [
let cases: [(&str, UsageKind); 10] = [
("https://api.deepseek.com/v1", UsageKind::BalanceDeepseek),
("https://api.siliconflow.cn/v1", UsageKind::BalanceSiliconflow),
("https://openrouter.ai/api/v1", UsageKind::BalanceOpenrouter),
@@ -188,6 +201,7 @@ mod tests {
UsageKind::PlanZhipu,
),
("https://api.minimaxi.com/v1", UsageKind::PlanMinimax),
("https://opencode.ai/zen/go/v1", UsageKind::PlanOpencodeGo),
];
for (url, expected) in cases {
assert_eq!(
@@ -212,6 +226,42 @@ mod tests {
assert!(detect_provider("https://api.kimi.com/v1").is_empty());
}
#[test]
fn detect_provider_kimi_coding_matches_global_ai_host() {
// global 站 api.kimi.ai + /coding 命中套餐
assert_eq!(
detect_provider("https://api.kimi.ai/coding/v1"),
vec![UsageKind::PlanKimiCoding]
);
assert_eq!(
detect_provider("https://api.kimi.ai/coding/v1/usages"),
vec![UsageKind::PlanKimiCoding]
);
// api.kimi.ai 但无 /coding 路径 → 不命中(也不命中 Moonshot 余额)
assert!(detect_provider("https://api.kimi.ai/v1").is_empty());
// .com 老路径不受影响
assert_eq!(
detect_provider("https://api.kimi.com/coding/v1"),
vec![UsageKind::PlanKimiCoding]
);
}
#[test]
fn detect_provider_opencode_go_excludes_payg_zen() {
// /zen/go 命中套餐查询
assert_eq!(
detect_provider("https://opencode.ai/zen/go/v1"),
vec![UsageKind::PlanOpencodeGo]
);
// /zen/v1(OpenCode Zen 按量付费)不得命中
assert!(detect_provider("https://opencode.ai/zen/v1").is_empty());
// 裸域名也命中(go 套餐 base 无 v1 后缀时)
assert_eq!(
detect_provider("https://opencode.ai/zen/go"),
vec![UsageKind::PlanOpencodeGo]
);
}
#[test]
fn usage_kind_string_roundtrip() {
use std::str::FromStr;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"productName": "Kimi Switch",
"version": "0.7.4",
"version": "0.7.7",
"identifier": "com.kimiswitch.app",
"build": {
"beforeDevCommand": "npm run dev",
+69 -21
View File
@@ -8,6 +8,7 @@ import { ProviderEdit } from "./components/ProviderEdit";
import { SubagentSettingsPage } from "./components/SubagentSettingsPage";
import { DashboardPage } from "./components/dashboard/DashboardPage";
import { SessionsPage } from "./components/sessions/SessionsPage";
import { PluginMarketplacePage } from "./components/plugins/PluginMarketplacePage";
import { SettingsModal } from "./components/SettingsModal";
import { UsageConfigModal } from "./components/UsageConfigModal";
import { PresetPickerModal } from "./components/PresetPickerModal";
@@ -71,7 +72,9 @@ export default function App() {
updateConfig,
} = useConfig(agent);
const [view, setView] = useState<"list" | "edit" | "subagent" | "dashboard" | "sessions">("list");
const [view, setView] = useState<
"list" | "edit" | "subagent" | "dashboard" | "sessions" | "plugins"
>("list");
const [editingProvider, setEditingProvider] = useState<string>("");
const [loadTimeout, setLoadTimeout] = useState(false);
const [switchMessage, setSwitchMessage] = useState<string | null>(null);
@@ -603,6 +606,14 @@ export default function App() {
>
{t("sessions")}
</button>
{/* 插件市场功能尚未成熟,导航入口暂时隐藏;页面代码保留,
恢复时把下面的按钮加回即可(view/渲染分支均未移除)。
<button
type="button"
onClick={() => setView("plugins")}
...
</button>
*/}
</div>
<div className="flex items-center gap-2">
{/* Language */}
@@ -650,6 +661,8 @@ export default function App() {
<DashboardPage />
) : view === "sessions" ? (
<SessionsPage />
) : view === "plugins" ? (
<PluginMarketplacePage />
) : view === "subagent" ? (
<SubagentSettingsPage
rawOther={config.raw_other}
@@ -693,18 +706,44 @@ export default function App() {
onModelChange={(model) => {
updateConfig((cfg) => {
const models = { ...cfg.models };
// Auto-fix the placeholder alias from onModelAdd: once the
// real model id is filled in, rename "<provider>/新模型" (and
// the mid-typing "<provider>/<prefix>" states) to
// "<provider>/<model-id>" so the CLI records usage under the
// real model name instead of the placeholder.
let effective = model;
const safeProvider = model.provider.replace(/\//g, "-");
const prefix = `${safeProvider}/`;
const modelId = model.model.trim();
const tail = model.alias.startsWith(prefix)
? model.alias.slice(prefix.length)
: "";
const targetAlias = `${prefix}${modelId}`;
if (
modelId !== "" &&
model.alias !== targetAlias &&
(tail === "新模型" ||
tail.startsWith("新模型-") ||
(tail !== "" && modelId.startsWith(tail))) &&
!(targetAlias in models)
) {
effective = { ...model, alias: targetAlias };
delete models[model.alias];
}
const existingKeys = Object.keys(models).filter(
(k) => models[k].provider === currentProvider.name
);
const oldKey = existingKeys.find((k) =>
model.alias === k ? true : models[k].alias === model.alias
effective.alias === k ? true : models[k].alias === effective.alias
);
if (oldKey && oldKey !== model.alias) {
if (oldKey && oldKey !== effective.alias) {
delete models[oldKey];
}
models[model.alias] = model;
models[effective.alias] = effective;
let default_model = cfg.default_model;
if (default_model === oldKey) default_model = model.alias;
if (default_model === oldKey) default_model = effective.alias;
else if (effective !== model && default_model === model.alias)
default_model = effective.alias;
return { ...cfg, models, default_model };
});
}}
@@ -722,22 +761,31 @@ export default function App() {
}}
onModelAdd={() => {
const safeProvider = currentProvider.name.replace(/\//g, "-");
const alias = `${safeProvider}/新模型`;
updateConfig((cfg) => ({
...cfg,
models: {
...cfg.models,
[alias]: {
alias,
provider: currentProvider.name,
model: "",
max_context_size: getDefaultMaxContextSize(alias),
display_name: null,
supports_1m: false,
capabilities: agent === "kimi_code" ? ["thinking"] : [],
updateConfig((cfg) => {
// Deduplicate the placeholder key: a second "add model" click
// while the previous placeholder is still unedited must not
// silently overwrite it.
let alias = `${safeProvider}/新模型`;
let n = 1;
while (alias in cfg.models) {
alias = `${safeProvider}/新模型-${++n}`;
}
return {
...cfg,
models: {
...cfg.models,
[alias]: {
alias,
provider: currentProvider.name,
model: "",
max_context_size: getDefaultMaxContextSize(alias),
display_name: null,
supports_1m: false,
capabilities: agent === "kimi_code" ? ["thinking"] : [],
},
},
},
}));
};
});
}}
onBulkAdd={(models) => {
updateConfig((cfg) => {
@@ -777,7 +825,7 @@ export default function App() {
)}
</main>
{view !== "dashboard" && view !== "sessions" && (
{view !== "dashboard" && view !== "sessions" && view !== "plugins" && (
<footer className="flex items-center justify-between px-4 py-2 border-t border-border bg-panel text-sm">
<div className="flex items-center gap-2 min-w-0">
{dirty && (
+74 -23
View File
@@ -25,6 +25,8 @@ interface KimiOAuthDialogProps {
onClose: () => void;
}
type OAuthRegion = "cn" | "global";
/** Kimi device-code sign-in dialog (in-app `kimi login`). */
export function KimiOAuthDialog({ open, onClose }: KimiOAuthDialogProps) {
const { t } = useTranslation();
@@ -33,10 +35,12 @@ export function KimiOAuthDialog({ open, onClose }: KimiOAuthDialogProps) {
const [done, setDone] = useState(false);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [region, setRegion] = useState<OAuthRegion>("cn");
const [started, setStarted] = useState(false);
const activeRef = useRef(false);
const intervalRef = useRef(5);
// Start a fresh device authorization when the dialog opens.
// Reset to the "pick a region" screen when the dialog (re)opens.
useEffect(() => {
if (!open) return;
activeRef.current = true;
@@ -45,8 +49,26 @@ export function KimiOAuthDialog({ open, onClose }: KimiOAuthDialogProps) {
setDone(false);
setError(null);
setCopied(false);
setRegion("cn");
setStarted(false);
intervalRef.current = 5;
invoke<DeviceAuthorization>("kimi_oauth_start")
return () => {
activeRef.current = false;
};
}, [open]);
// Begin the device flow for a region. Locks the picker; a later restart is
// the way to switch region.
const start = (r: OAuthRegion) => {
setRegion(r);
setStarted(true);
setAuth(null);
setPolling(false);
setDone(false);
setError(null);
setCopied(false);
intervalRef.current = 5;
invoke<DeviceAuthorization>("kimi_oauth_start", { region: r })
.then((a) => {
if (!activeRef.current) return;
setAuth(a);
@@ -56,11 +78,10 @@ export function KimiOAuthDialog({ open, onClose }: KimiOAuthDialogProps) {
.catch((e) => {
if (!activeRef.current) return;
setError(e instanceof Error ? e.message : String(e));
// Allow picking the region again after a failed launch.
setStarted(false);
});
return () => {
activeRef.current = false;
};
}, [open]);
};
// Poll the token endpoint while the user authorizes in the browser.
useEffect(() => {
@@ -73,6 +94,7 @@ export function KimiOAuthDialog({ open, onClose }: KimiOAuthDialogProps) {
const res = await invoke<PollStatus>("kimi_oauth_poll", {
deviceCode: auth.device_code,
interval: intervalRef.current,
region,
});
if (cancelled) return;
switch (res.status) {
@@ -119,22 +141,8 @@ export function KimiOAuthDialog({ open, onClose }: KimiOAuthDialogProps) {
}, [open, polling, auth]);
const restart = () => {
setAuth(null);
setPolling(false);
setDone(false);
setError(null);
intervalRef.current = 5;
invoke<DeviceAuthorization>("kimi_oauth_start")
.then((a) => {
if (!activeRef.current) return;
setAuth(a);
if (a.interval && a.interval > 0) intervalRef.current = a.interval;
setPolling(true);
})
.catch((e) => {
if (!activeRef.current) return;
setError(e instanceof Error ? e.message : String(e));
});
// Restart always resets to the default region (mainland China).
start("cn");
};
const copyCode = () => {
@@ -214,13 +222,56 @@ export function KimiOAuthDialog({ open, onClose }: KimiOAuthDialogProps) {
<p className="text-sm text-content-muted text-center">
{t("kimiOAuthWaiting")}
</p>
<p className="text-xs text-content-muted text-center">
{region === "global"
? t("kimiOAuthRegionGlobal")
: t("kimiOAuthRegionCn")}
</p>
</>
)}
{!auth && !done && (
{started && !auth && !done && (
<div className="h-3.5 w-2/3 rounded bg-hover-2 animate-pulse mx-auto" />
)}
{!started && !done && (
<div className="space-y-3">
<p className="text-sm text-content-muted">{t("kimiOAuthRegionLabel")}</p>
<div className="grid grid-cols-2 gap-2">
<button
type="button"
onClick={() => setRegion("cn")}
className={`px-3 py-2 text-sm rounded border transition-colors ${
region === "cn"
? "border-blue-600 bg-blue-600/10 text-blue-600 dark:text-blue-400"
: "border-border hover:bg-hover-2 text-content-muted"
}`}
>
{t("kimiOAuthRegionCn")}
</button>
<button
type="button"
onClick={() => setRegion("global")}
className={`px-3 py-2 text-sm rounded border transition-colors ${
region === "global"
? "border-blue-600 bg-blue-600/10 text-blue-600 dark:text-blue-400"
: "border-border hover:bg-hover-2 text-content-muted"
}`}
>
{t("kimiOAuthRegionGlobal")}
</button>
</div>
<button
type="button"
onClick={() => start(region)}
className="w-full px-3 py-2 text-sm rounded bg-blue-600 text-white hover:bg-blue-500 transition-colors"
>
{t("kimiOAuthStart")}
</button>
</div>
)}
<div className="flex items-center justify-end gap-2 pt-1">
{error && !done && (
<button
+331 -31
View File
@@ -8,12 +8,19 @@ import {
clearSecondaryModel,
forcedEnvValue,
getExperimentalFlags,
getSecondaryModel,
getSubagentModelPool,
isFlagLockedByEnv,
isMasterEnvOn,
removeSubagentPoolEntry,
setExperimentalFlag,
setSecondaryModelOnly,
setSubagentDefault,
setSubagentForce,
upsertSubagentPoolEntry,
validateSubagentPool,
type ExperimentalFlagDef,
type PoolValidationError,
type ValidationErrorKey,
} from "../lib/subagent-settings";
import { Card, Toggle } from "./ui/controls";
@@ -44,6 +51,97 @@ const FLAG_LABELS: Record<string, { name: TranslationKey; desc: TranslationKey }
},
};
/** Validation-error i18n key per engine rule, for the pre-write self-check. */
const POOL_ERROR_KEYS: Record<ValidationErrorKey, TranslationKey> = {
primaryReserved: "secondaryPoolErrorPrimaryReserved",
defaultRequired: "secondaryPoolErrorDefaultRequired",
defaultNotInPool: "secondaryPoolErrorDefaultNotInPool",
aliasNotInModels: "secondaryPoolErrorAliasNotInModels",
forceRequiresDefault: "secondaryPoolErrorForceRequiresDefault",
forceExcludesModels: "secondaryPoolErrorForceExcludesModels",
};
/**
* One row of the subagent model pool: default radio + alias + editable
* description (saved on blur/Enter via the parent's write chain) + remove.
* The description input keeps a local draft so typing is not persisted per
* keystroke; everything else is derived from `rawOther` on each render.
*/
function PoolEntryRow({
alias,
displayName,
description,
isDefault,
canRemove,
onSetDefault,
onSave,
onRemove,
}: {
alias: string;
displayName: string | null;
description: string;
isDefault: boolean;
canRemove: boolean;
onSetDefault: (alias: string) => void;
onSave: (alias: string, description: string) => void;
onRemove: (alias: string) => void;
}) {
const { t } = useTranslation();
const [draft, setDraft] = useState(description);
const commit = () => {
if (draft === description) return;
onSave(alias, draft);
};
return (
<div className="flex items-center gap-2 text-sm">
<input
type="radio"
checked={isDefault}
aria-label={t("setDefault")}
onChange={() => onSetDefault(alias)}
className="shrink-0 accent-blue-600 focus:ring-blue-500"
/>
<span className="shrink-0 font-medium text-content-primary">{alias}</span>
{displayName && (
<span className="shrink-0 text-xs text-content-muted">{displayName}</span>
)}
{isDefault && (
<span className="shrink-0 text-xs text-blue-600 dark:text-blue-400 border border-blue-500/30 rounded px-1">
{t("default")}
</span>
)}
<input
type="text"
value={draft}
placeholder={t("secondaryPoolDescPlaceholder")}
onChange={(e) => setDraft(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
(e.currentTarget as HTMLInputElement).blur();
} else if (e.key === "Escape") {
setDraft(description);
(e.currentTarget as HTMLInputElement).blur();
}
}}
className="flex-1 min-w-0 bg-input border border-border rounded px-2 py-1 text-xs focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
{canRemove && (
<button
type="button"
onClick={() => onRemove(alias)}
className="shrink-0 px-2 py-1 text-xs border border-border rounded hover:bg-hover-2 text-content-muted focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("secondaryPoolRemove")}
</button>
)}
</div>
);
}
export function SubagentSettingsPage({
rawOther,
models,
@@ -52,6 +150,10 @@ export function SubagentSettingsPage({
}: SubagentSettingsPageProps) {
const { t } = useTranslation();
const [env, setEnv] = useState<ExperimentalEnvStatus | null>(null);
/** Pre-write validation failures (fallback guard; normal flows stay clear). */
const [poolErrors, setPoolErrors] = useState<PoolValidationError[]>([]);
/** Local draft for the "add pool entry" select (reset after each pick). */
const [addSelection, setAddSelection] = useState("");
useEffect(() => {
invoke<ExperimentalEnvStatus>("get_experimental_env_status")
@@ -60,7 +162,17 @@ export function SubagentSettingsPage({
}, []);
const flags = getExperimentalFlags(rawOther);
const secondary = getSecondaryModel(rawOther);
const pool = getSubagentModelPool(rawOther);
const poolKeys = pool ? Object.keys(pool.models) : [];
// View selection: no/empty section or a bare legacy `model` → simple view;
// a `models` table or `default_model` → pool management view.
const isPoolView =
!!pool && (poolKeys.length > 0 || pool.defaultModel !== undefined);
// Effective default: v2 pool key first, legacy v1 recipe key as fallback.
const effectiveDefault = pool ? pool.defaultModel ?? pool.model : undefined;
// "Upgrade" only makes sense for the bare legacy form and when `force` is
// off — upgrading with force would create an invalid force+pool-table combo.
const canUpgrade = !!pool && !isPoolView && pool.model !== undefined && !pool.force;
const masterOn = isMasterEnvOn(env);
const secondaryFlag = EXPERIMENTAL_FLAGS[0]; // "secondary-model"
const otherFlags = EXPERIMENTAL_FLAGS.slice(1);
@@ -75,10 +187,25 @@ export function SubagentSettingsPage({
const aliasList = Object.keys(models).sort();
const aliasLabel = (alias: string): string =>
models[alias]?.display_name
? `${alias}(${models[alias].display_name})`
: alias;
// Rows of the pool view: every `models` table key plus the effective default
// when it is not already in the table (the implicit single-entry form).
const implicitDefault =
pool && effectiveDefault && !(effectiveDefault in pool.models)
? [effectiveDefault]
: [];
const poolEntries = [...poolKeys, ...implicitDefault];
// Aliases that can still be added to the pool (not already in the table).
const addableAliases = aliasList.filter((a) => !(a in (pool?.models ?? {})));
// Inherited settings shown for the picked model: subagents bind the pointed
// entry directly (no patch fields), so context size and effort come from the
// model entry / global [thinking], not from a `[secondary_model]` patch.
const selectedEntry = secondary.model ? models[secondary.model] : undefined;
const selectedEntry = effectiveDefault ? models[effectiveDefault] : undefined;
const inheritedContext = selectedEntry?.max_context_size;
const modelEffort =
selectedEntry &&
@@ -106,6 +233,61 @@ export function SubagentSettingsPage({
return key ? t(key) : e;
};
/**
* Fallback guard before any pool-related write: validate the *target* state
* against the engine rules (mirrored by `validateSubagentPool`) and block the
* write when it would produce an invalid config. Normal UI flows never trip
* this — it protects against stale/divergent configs.
*/
const validateWrite = (nextRaw: unknown): boolean => {
const nextPool = getSubagentModelPool(nextRaw);
const errors = nextPool ? validateSubagentPool(nextPool, aliasList) : [];
setPoolErrors(errors);
return errors.length === 0;
};
const handleUpgrade = () => {
if (!effectiveDefault) return;
const nextRaw = setSubagentDefault(rawOther, effectiveDefault);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleSetDefault = (alias: string) => {
if (alias === effectiveDefault) return;
const nextRaw = setSubagentDefault(rawOther, alias);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleSaveDescription = (alias: string, description: string) => {
const nextRaw = upsertSubagentPoolEntry(rawOther, alias, description);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleRemoveEntry = (alias: string) => {
const nextRaw = removeSubagentPoolEntry(rawOther, alias);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleAddEntry = (alias: string) => {
const nextRaw = upsertSubagentPoolEntry(rawOther, alias, "");
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleForceChange = (next: boolean) => {
if (!pool) return;
// Turning force on drops the `models` table — confirm when it is non-empty.
if (next && Object.keys(pool.models).length > 0) {
if (!confirm(t("secondaryPoolForceConfirm"))) return;
}
const nextRaw = setSubagentForce(rawOther, next);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleClear = () => {
setPoolErrors([]);
onChange(clearSecondaryModel(rawOther));
};
const renderFlagRow = (flag: ExperimentalFlagDef) => {
const labels = FLAG_LABELS[flag.id];
const locked = masterOn || isFlagLockedByEnv(env, flag);
@@ -194,36 +376,154 @@ export function SubagentSettingsPage({
</div>
</Card>
{/* Subagent: secondary model picker + inherited settings */}
{/* Subagent: secondary model picker / pool + inherited settings */}
<Card title={t("secondaryModelSection")}>
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="text-content-muted">{t("secondaryModelLabel")}</span>
<select
className="flex-1 max-w-md bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
value={secondary.model ?? ""}
onChange={(e) => {
const alias = e.target.value;
if (alias === "") {
onChange(clearSecondaryModel(rawOther));
} else {
// Only the model reference is persisted — no patch fields.
// Subagents bind the pointed entry directly and inherit its
// settings; usage records stay keyed on the real alias
// instead of Kimi Code's synthesized `__secondary__` entry.
onChange(setSecondaryModelOnly(rawOther, alias));
}
}}
{isPoolView && pool ? (
<>
{pool.force ? (
/* Force on: the `models` table was dropped — only the pinned
default is shown, entries and "add" are hidden. */
<div className="rounded-lg border border-border bg-input/40 px-3 py-2.5">
<div className="text-sm font-medium text-content-primary">
🔒{" "}
{t("secondaryPoolForceOn", {
alias: aliasLabel(effectiveDefault ?? ""),
})}
</div>
</div>
) : (
<>
<div className="space-y-2">
{poolEntries.map((alias) => (
<PoolEntryRow
key={alias}
alias={alias}
displayName={models[alias]?.display_name ?? null}
description={pool.models[alias] ?? ""}
isDefault={alias === effectiveDefault}
canRemove={alias in pool.models}
onSetDefault={handleSetDefault}
onSave={handleSaveDescription}
onRemove={handleRemoveEntry}
/>
))}
</div>
<p className="text-xs text-content-muted">
{t("secondaryPoolDescHint")}
</p>
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="shrink-0 text-content-muted">
{t("secondaryPoolAddLabel")}
</span>
<select
className="flex-1 max-w-md bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
value={addSelection}
onChange={(e) => {
const alias = e.target.value;
setAddSelection("");
if (alias) handleAddEntry(alias);
}}
>
<option value="">{t("secondaryPoolAddPlaceholder")}</option>
{addableAliases.map((alias) => (
<option key={alias} value={alias}>
{aliasLabel(alias)}
</option>
))}
</select>
</label>
</>
)}
<div className="flex items-center gap-3">
<div className="flex-1 min-w-0">
<div className="text-sm text-content-primary">
{t("secondaryPoolForce")}
</div>
<div className="text-xs text-content-muted">
{t("secondaryPoolForceDesc")}
</div>
</div>
<Toggle
checked={pool.force}
ariaLabel={t("secondaryPoolForce")}
onChange={handleForceChange}
/>
</div>
<button
type="button"
onClick={handleClear}
className="px-3 py-1.5 text-sm border border-border rounded hover:bg-hover-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("secondaryModelClear")}
</button>
</>
) : (
<>
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="shrink-0 text-content-muted">
{t("secondaryModelLabel")}
</span>
<select
className="flex-1 max-w-md bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
value={effectiveDefault ?? ""}
onChange={(e) => {
const alias = e.target.value;
if (alias === "") {
setPoolErrors([]);
onChange(clearSecondaryModel(rawOther));
} else {
// Only the model reference is persisted — no patch fields.
// Subagents bind the pointed entry directly and inherit
// its settings; usage records stay keyed on the real
// alias instead of the synthesized `__secondary__` entry.
const nextRaw = setSecondaryModelOnly(rawOther, alias);
if (validateWrite(nextRaw)) onChange(nextRaw);
}
}}
>
<option value="">{t("secondaryModelUnset")}</option>
{aliasList.map((alias) => (
<option key={alias} value={alias}>
{aliasLabel(alias)}
</option>
))}
</select>
{pool?.force && (
<span className="shrink-0 text-xs text-content-muted">
🔒 {t("secondaryModelForceBadge")}
</span>
)}
</label>
{canUpgrade && (
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleUpgrade}
className="px-3 py-1.5 text-sm border border-border rounded hover:bg-hover-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("secondaryPoolUpgrade")}
</button>
<span className="text-xs text-content-muted">
{t("secondaryPoolUpgradeDesc")}
</span>
</div>
)}
</>
)}
{poolErrors.length > 0 && (
<div
role="alert"
className="bg-red-100 dark:bg-red-900/20 border border-red-300 dark:border-red-500/30 rounded-lg px-3 py-2 text-sm text-red-700 dark:text-red-400 space-y-1"
>
<option value="">{t("secondaryModelUnset")}</option>
{aliasList.map((alias) => (
<option key={alias} value={alias}>
{models[alias]?.display_name
? `${alias}(${models[alias].display_name})`
: alias}
</option>
{poolErrors.map((err, i) => (
<div key={i}>{t(POOL_ERROR_KEYS[err.key], err.params)}</div>
))}
</select>
</label>
</div>
)}
<div className="border-t border-border" />
<div className="flex items-center gap-3">
@@ -248,7 +548,7 @@ export function SubagentSettingsPage({
/>
</div>
{secondary.model !== undefined && (
{effectiveDefault !== undefined && (
<div className="rounded-lg border border-border bg-input/40 px-3 py-2.5 space-y-2">
<div className="flex items-baseline gap-2 text-sm">
<span className="shrink-0 text-content-muted">
+20 -12
View File
@@ -1,10 +1,11 @@
import { useMemo, useState, type ReactNode } from "react";
import { useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { invoke } from "@tauri-apps/api/core";
import { useDashboard, type DashboardRange } from "../../hooks/useDashboard";
import { useCurrency } from "../../hooks/useCurrency";
import { useTranslation } from "../../i18n";
import { fmtInt, fmtPct, fmtTime, fmtTokens } from "../../lib/dashboard-format";
import { DailyBars, modelColor } from "./DailyBars";
import { DailyBars } from "./DailyBars";
import { DailyDetailModal } from "./DailyDetailModal";
import { Heatmap } from "./Heatmap";
import { TrendLineChart } from "./TrendLineChart";
@@ -62,11 +63,6 @@ export function DashboardPage() {
const [heatmapSelected, setHeatmapSelected] = useState<DailyRow | null>(null);
const daily = data?.stats.daily ?? [];
const detailDates = useMemo(() => new Set(daily.map((d) => d.date)), [daily]);
const heatmapColorMap = useMemo(() => {
const unique = [...new Set(daily.flatMap((d) => Object.keys(d.byModel || {})))];
return Object.fromEntries(unique.map((m, i) => [m, modelColor(i)]));
}, [daily]);
const RANGE_LABELS: Record<DashboardRange, string> = {
today: t("rangeToday"),
@@ -109,9 +105,21 @@ export function DashboardPage() {
const rangeTotals = data.rangeTotals;
const visibleModels = showAllModels ? models : models.slice(0, 8);
const onHeatmapCellDoubleClick = (cell: HeatmapCell) => {
const row = daily.find((d) => d.date === cell.date);
if (row) setHeatmapSelected(row);
const onHeatmapCellDoubleClick = async (cell: HeatmapCell) => {
try {
const row = await invoke<DailyRow | null>("get_day_detail", {
date: cell.date,
});
if (row) {
setHeatmapSelected(row);
} else {
setHeatmapSelected(null);
alert(t("dayDetailNoData", { date: cell.date }));
}
} catch (err) {
setHeatmapSelected(null);
alert(err instanceof Error ? err.message : String(err));
}
};
// Recent pagination
@@ -221,7 +229,7 @@ export function DashboardPage() {
{/* Heatmap — full row */}
<Card title={t("cardHeatmap")} subtitle={t("cardHeatmapSub")}>
<Heatmap heatmap={heatmap} detailDates={detailDates} onCellDoubleClick={onHeatmapCellDoubleClick} />
<Heatmap heatmap={heatmap} onCellDoubleClick={onHeatmapCellDoubleClick} />
</Card>
{/* Usage-trend tabs + Model table side by side */}
@@ -473,7 +481,7 @@ export function DashboardPage() {
<DailyDetailModal
day={heatmapSelected}
dimension="model"
colorMap={heatmapColorMap}
colorMap={{}}
unknownProviderLabel={t("providerUnknown")}
onClose={() => setHeatmapSelected(null)}
/>,
+3 -5
View File
@@ -7,9 +7,7 @@ import type { HeatmapCell, HeatmapData } from "../../types/dashboard";
interface HeatmapProps {
heatmap: HeatmapData;
/** Set of dates (YYYY-MM-DD) that have detail data in the current range. */
detailDates?: Set<string>;
/** Called when a cell with detail data is double-clicked. */
/** Called when a cell with data (level > 0) is double-clicked. */
onCellDoubleClick?: (cell: HeatmapCell) => void;
}
@@ -34,7 +32,7 @@ interface HoverState {
y: number;
}
export function Heatmap({ heatmap, detailDates, onCellDoubleClick }: HeatmapProps) {
export function Heatmap({ heatmap, onCellDoubleClick }: HeatmapProps) {
const { t, lang } = useTranslation();
const cells = heatmap?.cells || [];
const monthLabels = heatmap?.monthLabels || [];
@@ -176,7 +174,7 @@ export function Heatmap({ heatmap, detailDates, onCellDoubleClick }: HeatmapProp
);
}
const level = cell.level ?? 0;
const hasDetail = detailDates ? detailDates.has(cell.date) : level > 0;
const hasDetail = level > 0;
return (
<button
key={cell.date}
@@ -0,0 +1,578 @@
import { useMemo, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { useTranslation } from "../../i18n";
import type { TranslationKey } from "../../i18n/zh";
import { fmtTime } from "../../lib/dashboard-format";
import type { InstalledPluginInfo } from "../../types";
import { usePlugins } from "./usePlugins";
/**
* Plugin marketplace page. Sections:
* 已安装 (installed, incl. non-marketplace "自定义安装" entries),
* 官方 (tier === "official"), 社区 (any other tier).
* Catalog failures fall back to the local installed list; cached catalog
* responses surface a yellow banner (fromCache + fetchedAt).
*/
export function PluginMarketplacePage() {
const { t, lang } = useTranslation();
const locale = lang === "zh" ? "zh" : "en";
const {
catalog,
installed,
catalogLoading,
installedLoading,
catalogError,
installedError,
loadCatalog,
loadInstalled,
installPlugin,
setPluginEnabled,
removePlugin,
} = usePlugins();
const [query, setQuery] = useState("");
const [busy, setBusy] = useState<{ id: string; action: PluginAction } | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [notice, setNotice] = useState<{ kind: PluginNoticeKind; name: string } | null>(null);
const [copiedReload, setCopiedReload] = useState(false);
const [trustEntry, setTrustEntry] = useState<PluginCard | null>(null);
const [removeEntry, setRemoveEntry] = useState<PluginCard | null>(null);
const [confirmBusy, setConfirmBusy] = useState(false);
// Fresh installed state wins over the (possibly stale) catalog snapshot.
const installedById = useMemo(
() => new Map(installed.map((i) => [i.id, i])),
[installed]
);
const catalogCards = useMemo<PluginCard[]>(() => {
return (catalog?.entries ?? []).map((e) => {
const fresh = installedById.get(e.id) ?? null;
return {
id: e.id,
displayName: e.displayName,
version: (fresh ?? e.installed)?.version ?? e.version,
description: e.description,
keywords: e.keywords,
homepage: e.homepage,
tier: e.tier,
source: e.source,
capabilityId: e.capabilityId,
updateAvailable: e.updateAvailable,
installed: fresh ?? e.installed,
customInstall: false,
};
});
}, [catalog, installedById]);
// Installed plugins with no catalog entry (catalog failed, or a manual
// install) are shown in the installed section from the local list.
const fallbackCards = useMemo<PluginCard[]>(
() =>
installed
.filter((i) => !catalogCards.some((c) => c.id === i.id))
.map((i) => ({
id: i.id,
displayName: i.id,
version: i.version,
description: null,
keywords: [],
homepage: null,
tier: i.isMarketplace ? "unknown" : "custom",
source: i.source,
capabilityId: null,
updateAvailable: false,
installed: i,
customInstall: !i.isMarketplace,
})),
[installed, catalogCards]
);
const q = query.trim().toLowerCase();
const matchesQuery = (c: PluginCard) =>
q === "" ||
c.displayName.toLowerCase().includes(q) ||
c.id.toLowerCase().includes(q) ||
(c.description ?? "").toLowerCase().includes(q) ||
c.keywords.some((k) => k.toLowerCase().includes(q));
const installedCards = useMemo(
() => [...catalogCards.filter((c) => c.installed), ...fallbackCards].filter(matchesQuery),
[catalogCards, fallbackCards, q]
);
const officialCards = useMemo(
() => catalogCards.filter((c) => !c.installed && c.tier === "official" && matchesQuery(c)),
[catalogCards, q]
);
const communityCards = useMemo(
() => catalogCards.filter((c) => !c.installed && c.tier !== "official" && matchesQuery(c)),
[catalogCards, q]
);
const initialLoading =
(catalogLoading || installedLoading) && !catalog && installed.length === 0;
const copyReload = async () => {
try {
await navigator.clipboard.writeText("/reload");
setCopiedReload(true);
setTimeout(() => setCopiedReload(false), 2000);
} catch {
// Clipboard may be unavailable; ignore silently.
}
};
/** Shared post-mutation refresh: local list is cheap, catalog force-fetch
* brings fresh updateAvailable / installed flags. */
const afterMutation = async () => {
await loadInstalled();
await loadCatalog(true);
};
const doInstall = async (card: PluginCard) => {
const isUpdate = card.updateAvailable;
setBusy({ id: card.id, action: isUpdate ? "update" : "install" });
setActionError(null);
try {
await installPlugin(card.source, card.id);
setNotice({ kind: isUpdate ? "updated" : "installed", name: card.displayName });
await afterMutation();
} catch (err) {
setActionError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(null);
}
};
const handleInstall = (card: PluginCard) => {
if (card.capabilityId) return;
if (card.tier !== "official") {
// Third-party plugin: require explicit trust confirmation first.
setTrustEntry(card);
return;
}
void doInstall(card);
};
const confirmTrust = async () => {
if (!trustEntry) return;
setConfirmBusy(true);
try {
await doInstall(trustEntry);
setTrustEntry(null);
} finally {
setConfirmBusy(false);
}
};
const handleToggle = async (card: PluginCard) => {
if (!card.installed) return;
const enabled = !card.installed.enabled;
setBusy({ id: card.id, action: enabled ? "enable" : "disable" });
setActionError(null);
try {
await setPluginEnabled(card.id, enabled);
setNotice({ kind: enabled ? "enabled" : "disabled", name: card.displayName });
await afterMutation();
} catch (err) {
setActionError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(null);
}
};
const confirmRemove = async () => {
if (!removeEntry) return;
setConfirmBusy(true);
try {
await removePlugin(removeEntry.id);
setNotice({ kind: "removed", name: removeEntry.displayName });
setRemoveEntry(null);
await afterMutation();
} catch (err) {
setActionError(err instanceof Error ? err.message : String(err));
setRemoveEntry(null);
} finally {
setConfirmBusy(false);
}
};
const sectionData = [
{ key: "installed", title: t("pluginSectionInstalled"), cards: installedCards },
{ key: "official", title: t("pluginSectionOfficial"), cards: officialCards },
{ key: "community", title: t("pluginSectionCommunity"), cards: communityCards },
].filter((s) => s.cards.length > 0);
const showEmpty =
!initialLoading && !catalogError && !installedError && sectionData.length === 0;
return (
<div className="flex h-full flex-col overflow-hidden p-4 space-y-3">
<div className="flex shrink-0 flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div>
<h2 className="text-lg font-semibold text-content-primary">{t("pluginMarketplace")}</h2>
<p className="mt-1 max-w-[60ch] text-sm text-content-muted">{t("pluginMarketplaceSubtitle")}</p>
</div>
<div className="flex items-center gap-2">
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t("pluginSearchPlaceholder")}
aria-label={t("pluginSearchPlaceholder")}
className="w-56 bg-input border border-border rounded px-2.5 py-1.5 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none sm:w-64"
/>
<button
type="button"
onClick={() => void loadCatalog(true)}
disabled={catalogLoading}
className="px-3 py-1.5 text-sm rounded border border-border hover:bg-hover-2 disabled:opacity-50"
>
{catalogLoading ? t("refreshing") : t("refresh")}
</button>
</div>
</div>
{catalogError && (
<div className="shrink-0 rounded-lg border border-red-500/40 bg-red-900/20 px-4 py-3 text-sm text-red-300">
<div className="font-semibold">{t("pluginCatalogFailed")}</div>
<div className="mt-0.5 break-all opacity-90">{catalogError}</div>
</div>
)}
{installedError && (
<div className="shrink-0 rounded-lg border border-red-500/40 bg-red-900/20 px-4 py-3 text-sm text-red-300">
<div className="font-semibold">{t("pluginInstalledListFailed")}</div>
<div className="mt-0.5 break-all opacity-90">{installedError}</div>
</div>
)}
{actionError && (
<div className="shrink-0 rounded-lg border border-red-500/40 bg-red-900/20 px-4 py-3 text-sm text-red-300">
<div className="break-all">{actionError}</div>
</div>
)}
{catalog?.fromCache && (
<div className="shrink-0 rounded-lg border border-amber-500/40 bg-amber-900/20 px-4 py-2.5 text-sm text-amber-300">
{t("pluginCacheNotice", { time: fmtTime(parseTime(catalog.fetchedAt), locale) })}
</div>
)}
{notice && (
<div className="flex shrink-0 items-center justify-between gap-3 rounded-lg border border-green-300 dark:border-green-500/20 bg-green-100 dark:bg-green-900/20 px-4 py-2.5 text-sm text-green-600 dark:text-green-400">
<span>{t(NOTICE_KEYS[notice.kind], { name: notice.name })}</span>
<button
type="button"
onClick={copyReload}
className="shrink-0 px-2.5 py-1 text-xs rounded border border-green-400/50 hover:bg-green-900/20"
>
{copiedReload ? t("pluginReloadCopied") : t("pluginCopyReload")}
</button>
</div>
)}
{initialLoading ? (
<div className="flex min-h-0 flex-1 items-center justify-center">
<div className="animate-spin h-8 w-8 border-2 border-blue-500 border-t-transparent rounded-full" />
</div>
) : (
<div className="min-h-0 flex-1 space-y-5 overflow-y-auto">
{sectionData.map((section) => (
<section key={section.key}>
<h3 className="mb-2 flex items-center gap-2 text-sm font-medium text-content-primary">
{section.title}
<span className="rounded border border-border bg-input px-1.5 py-0 text-[10px] text-content-muted tabular-nums">
{section.cards.length}
</span>
</h3>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
{section.cards.map((card) => (
<PluginCardView
key={`${section.key}:${card.id}`}
card={card}
busy={busy?.id === card.id ? busy.action : null}
onInstall={handleInstall}
onUpdate={doInstall}
onToggle={(c) => void handleToggle(c)}
onRemove={setRemoveEntry}
/>
))}
</div>
</section>
))}
{showEmpty && (
<div className="py-16 text-center text-sm text-content-muted">
{q ? t("pluginEmptyResults") : t("pluginNoPlugins")}
</div>
)}
</div>
)}
{/* Third-party trust confirm */}
{trustEntry && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
<div className="w-full max-w-md rounded-xl border border-border bg-panel shadow-xl">
<div className="space-y-3 p-5">
<h3 className="text-base font-semibold text-content-primary">{t("pluginTrustTitle")}</h3>
<p className="text-sm text-content-muted">
{t("pluginTrustDesc", { source: trustEntry.source })}
</p>
<div className="rounded-md border border-border bg-input px-3 py-2.5">
<div className="truncate text-sm font-medium">{trustEntry.displayName}</div>
<div className="mt-1 break-all font-mono text-[11px] text-content-muted">
{trustEntry.source}
</div>
</div>
</div>
<div className="flex justify-end gap-2 border-t border-border bg-footer px-5 py-3">
<button
type="button"
disabled={confirmBusy}
onClick={() => setTrustEntry(null)}
className="px-3 py-1.5 text-sm rounded border border-border hover:bg-hover-2 disabled:opacity-50"
>
{t("cancel")}
</button>
<button
type="button"
disabled={confirmBusy}
onClick={() => void confirmTrust()}
className="px-3 py-1.5 text-sm rounded bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
>
{confirmBusy ? t("pluginInstalling") : t("pluginTrustInstall")}
</button>
</div>
</div>
</div>
)}
{/* Remove confirm */}
{removeEntry && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
<div className="w-full max-w-md rounded-xl border border-border bg-panel shadow-xl">
<div className="space-y-3 p-5">
<h3 className="text-base font-semibold text-content-primary">{t("pluginRemoveTitle")}</h3>
<p className="text-sm text-content-muted">
{t("pluginRemoveConfirm", { name: removeEntry.displayName })}
</p>
<div className="rounded-md border border-border bg-input px-3 py-2.5">
<div className="truncate text-sm font-medium">{removeEntry.displayName}</div>
<div className="mt-1 break-all font-mono text-[11px] text-content-muted">
{removeEntry.id}
</div>
</div>
</div>
<div className="flex justify-end gap-2 border-t border-border bg-footer px-5 py-3">
<button
type="button"
disabled={confirmBusy}
onClick={() => setRemoveEntry(null)}
className="px-3 py-1.5 text-sm rounded border border-border hover:bg-hover-2 disabled:opacity-50"
>
{t("cancel")}
</button>
<button
type="button"
disabled={confirmBusy}
onClick={() => void confirmRemove()}
className="px-3 py-1.5 text-sm rounded bg-red-600 text-white hover:bg-red-500 disabled:opacity-50"
>
{confirmBusy ? t("pluginRemoving") : t("pluginRemove")}
</button>
</div>
</div>
</div>
)}
</div>
);
}
type PluginAction = "install" | "update" | "enable" | "disable" | "remove";
type PluginNoticeKind = "installed" | "updated" | "enabled" | "disabled" | "removed";
const NOTICE_KEYS: Record<PluginNoticeKind, TranslationKey> = {
installed: "pluginInstalledMsg",
updated: "pluginUpdatedMsg",
enabled: "pluginEnabledMsg",
disabled: "pluginDisabledMsg",
removed: "pluginRemovedMsg",
};
/** Normalized card data: catalog metadata merged with fresh installed state. */
interface PluginCard {
id: string;
displayName: string;
version: string | null;
description: string | null;
keywords: string[];
homepage: string | null;
tier: string;
source: string;
capabilityId: string | null;
updateAvailable: boolean;
installed: InstalledPluginInfo | null;
/** Card synthesized from the local installed list (not in the catalog). */
customInstall: boolean;
}
function parseTime(value: string | null | undefined): number {
if (value == null || value === "") return 0;
const ms = Date.parse(value);
return Number.isFinite(ms) ? ms : 0;
}
function PluginCardView({
card,
busy,
onInstall,
onUpdate,
onToggle,
onRemove,
}: {
card: PluginCard;
busy: PluginAction | null;
onInstall: (card: PluginCard) => void;
onUpdate: (card: PluginCard) => void;
onToggle: (card: PluginCard) => void;
onRemove: (card: PluginCard) => void;
}) {
const { t } = useTranslation();
const { installed } = card;
const busyLabel =
busy === "install"
? t("pluginInstalling")
: busy === "update"
? t("pluginUpdating")
: busy === "enable" || busy === "disable"
? t("pluginToggling")
: busy === "remove"
? t("pluginRemoving")
: null;
return (
<div className="flex flex-col gap-2.5 rounded-xl border border-border bg-panel p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-1.5">
<h4 className="truncate text-sm font-semibold text-content-primary" title={card.displayName}>
{card.displayName}
</h4>
{card.updateAvailable && (
<span className="rounded-md bg-amber-100 dark:bg-amber-900/30 px-2 py-0.5 text-[10px] text-amber-700 dark:text-amber-300">
{t("pluginUpdateAvailable")}
</span>
)}
{card.customInstall && (
<span className="rounded-md bg-blue-100 dark:bg-blue-900/30 px-2 py-0.5 text-[10px] text-blue-700 dark:text-blue-300">
{t("pluginCustomInstall")}
</span>
)}
</div>
<div className="mt-0.5 flex items-center gap-2 text-[11px] text-content-muted">
<span className="truncate font-mono">{card.id}</span>
{card.version && <span className="shrink-0">v{card.version}</span>}
</div>
</div>
{installed && (
<span
className={`shrink-0 rounded-md px-2 py-0.5 text-xs ${
installed.enabled
? "bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300"
: "bg-zinc-200 dark:bg-zinc-700/40 text-zinc-600 dark:text-zinc-300"
}`}
>
{installed.enabled ? t("activated") : t("disabled")}
</span>
)}
</div>
{card.description && (
<p className="line-clamp-2 text-sm leading-relaxed text-content-muted">{card.description}</p>
)}
{card.keywords.length > 0 && (
<div className="flex flex-wrap gap-1">
{card.keywords.slice(0, 6).map((k) => (
<span
key={k}
className="rounded border border-border bg-input px-1.5 py-0.5 text-[10px] text-content-muted"
>
{k}
</span>
))}
</div>
)}
<div className="mt-auto flex items-center justify-between gap-2 border-t border-border/50 pt-2.5">
<div className="flex min-w-0 items-center gap-2">
{card.homepage && (
<button
type="button"
onClick={() => openUrl(card.homepage!)}
title={card.homepage}
className="shrink-0 text-xs text-blue-600 hover:underline dark:text-blue-400"
>
{t("pluginHomepage")}
</button>
)}
{card.source && !card.customInstall && (
<span className="truncate font-mono text-[10px] text-content-muted" title={card.source}>
{card.source}
</span>
)}
</div>
<div className="flex shrink-0 items-center gap-1.5">
{installed ? (
<>
{card.updateAvailable && (
<button
type="button"
disabled={busy != null || !!card.capabilityId}
onClick={() => onUpdate(card)}
title={card.capabilityId ? t("pluginCapabilityRequired") : undefined}
className="px-2.5 py-1 text-xs rounded bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
>
{busy === "update" ? busyLabel : t("pluginUpdate")}
</button>
)}
<button
type="button"
disabled={busy != null}
onClick={() => onToggle(card)}
className="px-2.5 py-1 text-xs rounded border border-border hover:bg-hover-2 disabled:opacity-50"
>
{busy === "enable" || busy === "disable"
? busyLabel
: installed.enabled
? t("pluginDisable")
: t("pluginEnable")}
</button>
<button
type="button"
disabled={busy != null}
onClick={() => onRemove(card)}
className="px-2.5 py-1 text-xs rounded border border-red-500/30 text-red-300 hover:bg-red-900/20 disabled:opacity-50"
>
{busy === "remove" ? busyLabel : t("pluginRemove")}
</button>
</>
) : (
<span title={card.capabilityId ? t("pluginCapabilityRequired") : undefined}>
<button
type="button"
disabled={busy != null || !!card.capabilityId}
onClick={() => onInstall(card)}
className="px-2.5 py-1 text-xs rounded bg-blue-600 text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
>
{busy === "install" ? busyLabel : t("pluginInstall")}
</button>
</span>
)}
</div>
</div>
</div>
);
}
function openUrl(url: string) {
invoke("open_external_url", { url }).catch(() => {
const w = window.open(url, "_blank");
if (!w) console.error(`failed to open ${url}`);
});
}
+106
View File
@@ -0,0 +1,106 @@
import { useCallback, useEffect, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import type {
InstalledPluginInfo,
PluginMarketplaceResult,
} from "../../types";
/**
* Plugin marketplace data + mutations. All backend IPC for the plugin
* marketplace is concentrated here so the page stays thin and the switch
* to a live backend is a drop-in change.
*
* IPC contract (Rust, camelCase args):
* get_plugin_marketplace(homeOverride?, refresh?) → PluginMarketplaceResult
* list_installed_plugins(homeOverride?) → InstalledPluginInfo[]
* install_plugin(homeOverride?, source, expectedId?) → InstalledPluginInfo
* set_plugin_enabled(homeOverride?, id, enabled) → void
* remove_plugin(homeOverride?, id) → void
* Like the existing pages, homeOverride is never passed (Rust side defaults).
*/
export function usePlugins() {
const [catalog, setCatalog] = useState<PluginMarketplaceResult | null>(null);
const [installed, setInstalled] = useState<InstalledPluginInfo[]>([]);
const [catalogLoading, setCatalogLoading] = useState(false);
const [installedLoading, setInstalledLoading] = useState(false);
const [catalogError, setCatalogError] = useState<string | null>(null);
const [installedError, setInstalledError] = useState<string | null>(null);
const loadCatalog = useCallback(async (refresh = false) => {
setCatalogLoading(true);
setCatalogError(null);
try {
const result = await invoke<PluginMarketplaceResult>(
"get_plugin_marketplace",
{ refresh }
);
setCatalog(result);
return result;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
setCatalogError(msg);
return null;
} finally {
setCatalogLoading(false);
}
}, []);
const loadInstalled = useCallback(async () => {
setInstalledLoading(true);
setInstalledError(null);
try {
const result = await invoke<InstalledPluginInfo[]>(
"list_installed_plugins",
{}
);
setInstalled(result);
return result;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
setInstalledError(msg);
return null;
} finally {
setInstalledLoading(false);
}
}, []);
useEffect(() => {
void loadCatalog(false);
void loadInstalled();
}, [loadCatalog, loadInstalled]);
const installPlugin = useCallback(
async (source: string, expectedId?: string) => {
return invoke<InstalledPluginInfo>("install_plugin", {
source,
expectedId,
});
},
[]
);
const setPluginEnabled = useCallback(
async (id: string, enabled: boolean) => {
await invoke("set_plugin_enabled", { id, enabled });
},
[]
);
const removePlugin = useCallback(async (id: string) => {
await invoke("remove_plugin", { id });
}, []);
return {
catalog,
installed,
catalogLoading,
installedLoading,
catalogError,
installedError,
loadCatalog,
loadInstalled,
installPlugin,
setPluginEnabled,
removePlugin,
};
}
+5 -1
View File
@@ -16,7 +16,8 @@ export type UsageKind =
| "balance:kimi"
| "plan:kimi_coding"
| "plan:zhipu"
| "plan:minimax";
| "plan:minimax"
| "plan:opencode_go";
/** Billing model for a preset. Drives the tab filter in PresetPickerModal. */
export type BillingMode = "subscription" | "pay_as_you_go";
@@ -32,6 +33,7 @@ export const SUPPORTED_USAGE_KINDS: ReadonlySet<string> = new Set<UsageKind>([
"plan:kimi_coding",
"plan:zhipu",
"plan:minimax",
"plan:opencode_go",
]);
export type PresetCategory =
@@ -469,6 +471,8 @@ export const providerPresets: ProviderPreset[] = [
{ model: "deepseek-v4-flash", displayName: "DeepSeek V4 Flash" },
],
billingMode: "subscription",
// Go 套餐额度查询:GET https://opencode.ai/zen/go/v1/usage(Bearer)。
usageKinds: ["plan:opencode_go"],
},
{
id: "opencode-zen",
+82 -1
View File
@@ -68,6 +68,10 @@ export const enTranslations: Record<TranslationKey, string> = {
kimiOAuthRetry: "Restart",
kimiOAuthCancel: "Cancel",
kimiOAuthNetworkError: "Network error, retrying…",
kimiOAuthRegionLabel: "Sign-in region",
kimiOAuthRegionCn: "Mainland China (auth.kimi.com)",
kimiOAuthRegionGlobal: "International (auth.kimi.ai)",
kimiOAuthStart: "Start sign-in",
apiSettings: "API Settings",
apiFormat: "API Format",
authField: "Auth Field",
@@ -227,6 +231,7 @@ export const enTranslations: Record<TranslationKey, string> = {
// Daily detail modal
dayDetail: "Daily usage detail",
dayDetailNoData: "No usage data for {date}",
close: "Close",
totalTokens: "Total tokens",
cost: "Cost",
@@ -421,6 +426,7 @@ export const enTranslations: Record<TranslationKey, string> = {
usageUnsupportedProvider: "This provider is not supported by auto query",
usageTier5h: "5-hour",
usageTierWeekly: "Weekly",
usageTierMonthly: "Monthly",
usageErrNoKey: "No API key configured",
usageErrDisabled: "Usage query is disabled in the config panel",
usageErrLoginExpired: "Kimi Code login expired and auto-refresh failed; run `kimi login` again",
@@ -477,7 +483,35 @@ export const enTranslations: Record<TranslationKey, string> = {
secondaryModelHint:
"Second model config bound to subagents by default; when unset, subagents inherit the primary model. Only the model reference is stored; subagents inherit all of that model's settings",
secondaryModelPriorityHint:
"Priority: explicit tool model param > profile model_preference > this config > inherit primary model",
"Priority (v2): tool model param (pool alias or primary) > default_model > inherit primary; (v1 legacy): tool param > model_preference > model > inherit primary",
// Subagent model pool (secondary_model v2 keys)
secondaryPoolUpgrade: "Upgrade to model pool",
secondaryPoolUpgradeDesc:
"Writes default_model in sync with model (dual-write for both engines); more pool entries can be added afterwards",
secondaryPoolAddLabel: "Add pool entry",
secondaryPoolAddPlaceholder: "Select a model to add to the pool…",
secondaryPoolRemove: "Remove",
secondaryPoolDescPlaceholder: "Subagent routing description for this model…",
secondaryPoolDescHint:
"The description is rendered into the main agent's tool description (Agent/AgentSwarm) and directly affects how well the main model routes to subagent models",
secondaryPoolForce: "Force default model",
secondaryPoolForceDesc:
"When enabled, all subagents are forced onto the default model; force excludes pool entries, which are removed",
secondaryPoolForceOn: "Force is on: subagents always use \"{alias}\"",
secondaryPoolForceConfirm:
"Enabling force removes every pool entry, keeping only the default model. Continue?",
secondaryModelClear: "Clear subagent config",
secondaryModelForceBadge: "Force on: subagents always use this model",
secondaryPoolErrorPrimaryReserved:
"\"{alias}\" is a reserved alias and cannot be a pool entry",
secondaryPoolErrorDefaultRequired: "default_model is required when pool entries exist",
secondaryPoolErrorDefaultNotInPool: "Default model \"{alias}\" is not in the pool",
secondaryPoolErrorAliasNotInModels: "Model \"{alias}\" is not registered in [models]",
secondaryPoolErrorForceRequiresDefault:
"A default model is required before enabling force",
secondaryPoolErrorForceExcludesModels:
"force is mutually exclusive with pool entries",
// Kimi Code WebUI quick open
webuiSection: "Kimi Code WebUI",
@@ -485,4 +519,51 @@ export const enTranslations: Record<TranslationKey, string> = {
"Open the new Web UI in an independent in-app window, or in your system browser (built into kimi-code 0.33+). Requires the kimi CLI on PATH.",
openWebUIEmbedded: "Open in App",
openWebUIBrowser: "Open in Browser",
// Plugin marketplace
pluginMarketplace: "Plugin Marketplace",
pluginMarketplaceSubtitle:
"Browse and install Kimi Code plugins — official and community, with install, update, and enable/disable management.",
pluginSearchPlaceholder: "Search by name, description, keyword, or ID…",
pluginSectionInstalled: "Installed",
pluginSectionOfficial: "Official",
pluginSectionCommunity: "Community",
pluginCustomInstall: "Custom",
pluginUpdateAvailable: "Update available",
pluginCapabilityRequired: "Install inside kimi-code (/plugins)",
pluginInstall: "Install",
pluginUpdate: "Update",
pluginEnable: "Enable",
pluginDisable: "Disable",
pluginRemove: "Remove",
pluginInstalling: "Installing…",
pluginUpdating: "Updating…",
pluginToggling: "Switching…",
pluginRemoving: "Removing…",
pluginTrustTitle: "Install third-party plugin?",
pluginTrustDesc:
"This plugin comes from {source}. Plugins can contribute MCP tools, hooks, and commands, and may access your sessions and files. Only install from sources you trust.",
pluginTrustInstall: "Trust & install",
pluginRemoveTitle: "Remove plugin?",
pluginRemoveConfirm:
"Remove \"{name}\"? Run /reload in kimi-code or start a new session afterwards to apply.",
pluginInstalledMsg:
"\"{name}\" installed. Run /reload in kimi-code or start a new session to apply.",
pluginUpdatedMsg:
"\"{name}\" updated. Run /reload in kimi-code or start a new session to apply.",
pluginEnabledMsg:
"\"{name}\" enabled. Run /reload in kimi-code or start a new session to apply.",
pluginDisabledMsg:
"\"{name}\" disabled. Run /reload in kimi-code or start a new session to apply.",
pluginRemovedMsg:
"\"{name}\" removed. Run /reload in kimi-code or start a new session to apply.",
pluginCopyReload: "Copy /reload",
pluginReloadCopied: "Copied",
pluginCacheNotice: "Showing cached data (fetched {time})",
pluginCatalogFailed:
"Failed to load the plugin catalog; showing locally installed plugins",
pluginInstalledListFailed: "Failed to load the installed plugin list",
pluginEmptyResults: "No matching plugins",
pluginNoPlugins: "No plugins available",
pluginHomepage: "Homepage",
};
+72 -1
View File
@@ -66,6 +66,10 @@ export const zhTranslations = {
kimiOAuthRetry: "重新开始",
kimiOAuthCancel: "取消",
kimiOAuthNetworkError: "网络错误,正在重试…",
kimiOAuthRegionLabel: "登录区域",
kimiOAuthRegionCn: "中国大陆 (auth.kimi.com)",
kimiOAuthRegionGlobal: "国际版 (auth.kimi.ai)",
kimiOAuthStart: "开始登录",
apiSettings: "API 设置",
apiFormat: "API 格式",
authField: "认证字段",
@@ -222,6 +226,7 @@ export const zhTranslations = {
// Daily detail modal
dayDetail: "每日用量详情",
dayDetailNoData: "「{date}」当日无用量数据",
close: "关闭",
totalTokens: "总 Token",
cost: "费用",
@@ -416,6 +421,7 @@ export const zhTranslations = {
usageUnsupportedProvider: "此供应商暂不支持自动查询",
usageTier5h: "5小时",
usageTierWeekly: "7天",
usageTierMonthly: "30天",
usageErrNoKey: "未配置 API Key",
usageErrDisabled: "用量查询已在配置面板中停用",
usageErrLoginExpired: "Kimi Code 登录已过期且自动续期失败,请重新运行 `kimi login`",
@@ -472,7 +478,32 @@ export const zhTranslations = {
secondaryModelHint:
"子代理默认绑定的第二份模型配置;未配置时子代理继承主模型;仅保存模型引用,子代理继承该模型的全部设置",
secondaryModelPriorityHint:
"优先级:工具显式 model 参数 > 子代理 profile 的 model_preference > 本配置 > 继承主模型",
"优先级(v2):工具 model 参数(池别名或 primary)> default_model > 继承主模型;(v1 legacy):工具参数 > model_preference > model > 继承主模型",
// Subagent model pool (secondary_model v2 keys)
secondaryPoolUpgrade: "升级为模型池",
secondaryPoolUpgradeDesc:
"为旧式配置补写 default_model,与 model 双写一致;之后可继续添加多个池条目",
secondaryPoolAddLabel: "添加池条目",
secondaryPoolAddPlaceholder: "选择要加入模型池的模型…",
secondaryPoolRemove: "移除",
secondaryPoolDescPlaceholder: "该模型的子代理路由描述…",
secondaryPoolDescHint:
"描述会渲染进主 Agent 的工具描述(Agent/AgentSwarm),直接影响主模型挑选子代理模型的路由质量",
secondaryPoolForce: "强制使用默认模型",
secondaryPoolForceDesc:
"开启后所有子代理固定使用默认模型;force 与模型池条目互斥,条目将被移除",
secondaryPoolForceOn: "force 已开启:子代理固定使用「{alias}」",
secondaryPoolForceConfirm:
"开启 force 将移除模型池中的所有条目,只保留默认模型。确定继续?",
secondaryModelClear: "不再配置",
secondaryModelForceBadge: "force 已开启:子代理固定使用该模型",
secondaryPoolErrorPrimaryReserved: "「{alias}」是保留别名,不能用作模型池条目",
secondaryPoolErrorDefaultRequired: "存在模型池条目时 default_model 必填",
secondaryPoolErrorDefaultNotInPool: "默认模型「{alias}」不在模型池中",
secondaryPoolErrorAliasNotInModels: "模型「{alias}」未在 [models] 中注册",
secondaryPoolErrorForceRequiresDefault: "开启 force 前必须设置默认模型",
secondaryPoolErrorForceExcludesModels: "force 与模型池条目互斥",
// Kimi Code WebUI quick open
webuiSection: "Kimi Code WebUI",
@@ -480,6 +511,46 @@ export const zhTranslations = {
"以独立窗口在应用内打开新版 Web 界面,也可以选择在系统浏览器打开(kimi-code 0.33+ 内置 code-app;需要 kimi 命令在 PATH 中)。",
openWebUIEmbedded: "在应用内打开",
openWebUIBrowser: "在浏览器打开",
// Plugin marketplace
pluginMarketplace: "插件市场",
pluginMarketplaceSubtitle:
"浏览并安装 Kimi Code 插件:官方、社区插件均可安装,支持更新与启用/禁用管理。",
pluginSearchPlaceholder: "搜索插件名称、描述、关键词或 ID…",
pluginSectionInstalled: "已安装",
pluginSectionOfficial: "官方",
pluginSectionCommunity: "社区",
pluginCustomInstall: "自定义安装",
pluginUpdateAvailable: "有更新",
pluginCapabilityRequired: "需在 kimi-code 内安装(/plugins)",
pluginInstall: "安装",
pluginUpdate: "更新",
pluginEnable: "启用",
pluginDisable: "禁用",
pluginRemove: "移除",
pluginInstalling: "安装中…",
pluginUpdating: "更新中…",
pluginToggling: "切换中…",
pluginRemoving: "移除中…",
pluginTrustTitle: "安装第三方插件?",
pluginTrustDesc:
"该插件来自 {source}。插件可贡献 MCP 工具、hooks 与命令,并可能访问你的会话和文件。请仅安装你信任的来源。",
pluginTrustInstall: "信任并安装",
pluginRemoveTitle: "移除插件?",
pluginRemoveConfirm: "确定移除「{name}」?移除后请在 kimi-code 中 /reload 或开新会话生效。",
pluginInstalledMsg: "「{name}」已安装。请在 kimi-code 中 /reload 或开新会话生效。",
pluginUpdatedMsg: "「{name}」已更新。请在 kimi-code 中 /reload 或开新会话生效。",
pluginEnabledMsg: "「{name}」已启用。请在 kimi-code 中 /reload 或开新会话生效。",
pluginDisabledMsg: "「{name}」已禁用。请在 kimi-code 中 /reload 或开新会话生效。",
pluginRemovedMsg: "「{name}」已移除。请在 kimi-code 中 /reload 或开新会话生效。",
pluginCopyReload: "复制 /reload",
pluginReloadCopied: "已复制",
pluginCacheNotice: "显示缓存数据(获取于 {time})",
pluginCatalogFailed: "插件目录加载失败,已改用本地已安装列表",
pluginInstalledListFailed: "已安装插件列表加载失败",
pluginEmptyResults: "没有匹配的插件",
pluginNoPlugins: "暂无插件",
pluginHomepage: "主页",
} as const;
export type TranslationKey = keyof typeof zhTranslations;
+92322 -77787
View File
File diff suppressed because it is too large. Load diff
+74364 -62019
View File
File diff suppressed because it is too large. Load diff
+426
View File
@@ -0,0 +1,426 @@
import { describe, expect, it } from "vitest";
import {
getSecondaryModel,
getSubagentModelPool,
removeSubagentPoolEntry,
setSecondaryModelOnly,
setSubagentDefault,
setSubagentForce,
setSubagentModelPool,
upsertSubagentPoolEntry,
validateSubagentPool,
type SubagentModelPool,
} from "./subagent-settings";
// ---------------------------------------------------------------------------
// Helpers — drill into the `[secondary_model]` section of the written result
// ---------------------------------------------------------------------------
function rawWith(section: Record<string, unknown>): unknown {
return { secondary_model: section };
}
function section(raw: unknown): Record<string, unknown> {
const root = raw as { secondary_model?: unknown };
const sec = root?.secondary_model;
return sec && typeof sec === "object" && !Array.isArray(sec)
? (sec as Record<string, unknown>)
: {};
}
function modelsOf(raw: unknown): Record<string, unknown> {
const m = section(raw)["models"];
return m && typeof m === "object" && !Array.isArray(m)
? (m as Record<string, unknown>)
: {};
}
// ---------------------------------------------------------------------------
// Reading — four config combinations + effective-default normalization
// ---------------------------------------------------------------------------
describe("getSecondaryModel / getSubagentModelPool", () => {
it("returns an empty config / undefined pool when the section is absent or empty", () => {
expect(getSecondaryModel({})).toEqual({});
expect(getSubagentModelPool({})).toBeUndefined();
expect(getSubagentModelPool(rawWith({}))).toBeUndefined();
});
it("legacy `model` alone forms the effective default", () => {
const raw = rawWith({ model: "kimi-k2" });
expect(getSecondaryModel(raw)).toEqual({ model: "kimi-k2" });
const pool = getSubagentModelPool(raw);
expect(pool).toEqual({ model: "kimi-k2", models: {}, force: false });
expect(pool?.defaultModel ?? pool?.model).toBe("kimi-k2");
});
it("`default_model` alone forms the effective default", () => {
const raw = rawWith({ default_model: "kimi-k2" });
expect(getSecondaryModel(raw)).toEqual({ default_model: "kimi-k2" });
const pool = getSubagentModelPool(raw);
expect(pool?.defaultModel).toBe("kimi-k2");
expect(pool?.model).toBeUndefined();
expect(pool?.defaultModel ?? pool?.model).toBe("kimi-k2");
});
it("a divergent `model` + `default_model` resolves the effective default to `default_model`", () => {
const raw = rawWith({ model: "kimi-k2", default_model: "kimi-k1" });
expect(getSecondaryModel(raw)).toEqual({
model: "kimi-k2",
default_model: "kimi-k1",
});
const pool = getSubagentModelPool(raw);
expect(pool?.model).toBe("kimi-k2");
expect(pool?.defaultModel).toBe("kimi-k1");
expect(pool?.defaultModel ?? pool?.model).toBe("kimi-k1");
});
it("reads the models table filtering non-string values, and force", () => {
const raw = rawWith({
default_model: "kimi-k2",
models: { "kimi-k2": "Kimi K2", "kimi-k2-thinking": 42, broken: true },
force: true,
});
expect(getSecondaryModel(raw).models).toEqual({ "kimi-k2": "Kimi K2" });
expect(getSecondaryModel(raw).force).toBe(true);
expect(getSubagentModelPool(raw)).toMatchObject({
models: { "kimi-k2": "Kimi K2" },
force: true,
});
});
it("reports `force` only when true and tolerates a malformed models table", () => {
expect(getSecondaryModel(rawWith({ force: false })).force).toBeUndefined();
expect(getSubagentModelPool(rawWith({ force: false }))?.force).toBe(false);
const pool = getSubagentModelPool(rawWith({ models: "nope", model: "kimi-k2" }));
expect(pool?.models).toEqual({});
expect(pool?.model).toBe("kimi-k2");
});
});
// ---------------------------------------------------------------------------
// setSecondaryModelOnly — pool-aware pick
// ---------------------------------------------------------------------------
describe("setSecondaryModelOnly", () => {
it("creates the section when absent", () => {
const next = setSecondaryModelOnly({}, "kimi-k2");
expect(section(next)).toEqual({ model: "kimi-k2" });
});
it("without a pool: writes only `model`, drops known patch fields, keeps unknown fields", () => {
const raw = rawWith({
model: "old",
default_effort: "high",
max_output_size: 64000,
max_context_size: 128000,
custom_field: "keep",
});
const next = setSecondaryModelOnly(raw, "kimi-k2");
expect(section(next)).toEqual({ model: "kimi-k2", custom_field: "keep" });
});
it("pool via default_model: syncs both keys, adds a missing alias to the table, preserves the rest", () => {
const raw = rawWith({
default_model: "kimi-k1",
models: { "kimi-k1": "K1" },
force: true,
unknown_field: "keep",
});
const next = setSecondaryModelOnly(raw, "kimi-k2");
expect(section(next)).toEqual({
default_model: "kimi-k2",
model: "kimi-k2",
models: { "kimi-k1": "K1", "kimi-k2": "" },
force: true,
unknown_field: "keep",
});
});
it("pool via models table: keeps existing descriptions", () => {
const raw = rawWith({ models: { "kimi-k1": "K1", "kimi-k2": "K2" } });
const next = setSecondaryModelOnly(raw, "kimi-k2");
expect(modelsOf(next)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
expect(section(next).default_model).toBe("kimi-k2");
expect(section(next).model).toBe("kimi-k2");
});
it("heals a divergent legacy + pool default to the picked alias", () => {
const raw = rawWith({
model: "kimi-k1",
default_model: "kimi-k2",
models: { "kimi-k1": "K1", "kimi-k2": "K2" },
});
const next = setSecondaryModelOnly(raw, "kimi-k1");
expect(section(next).model).toBe("kimi-k1");
expect(section(next).default_model).toBe("kimi-k1");
expect(modelsOf(next)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
});
it("preserves other top-level raw_other sections", () => {
const raw = {
experimental: { "secondary-model": true },
secondary_model: { model: "kimi-k1" },
};
const next = setSecondaryModelOnly(raw, "kimi-k2") as {
experimental?: unknown;
};
expect(next.experimental).toEqual({ "secondary-model": true });
});
});
// ---------------------------------------------------------------------------
// Pool mutations — rebuild / upsert / remove / default
// ---------------------------------------------------------------------------
describe("pool mutations", () => {
it("setSubagentModelPool rebuilds with dual-written default (effective wins) and force", () => {
const raw = rawWith({ model: "stale", custom: "keep" });
const next = setSubagentModelPool(raw, {
defaultModel: "kimi-k2",
model: "kimi-k1", // divergent — effective default (`defaultModel`) wins
models: { "kimi-k2": "K2" },
force: true,
});
expect(section(next)).toEqual({
default_model: "kimi-k2",
model: "kimi-k2",
models: { "kimi-k2": "K2" },
force: true,
custom: "keep",
});
});
it("setSubagentModelPool omits the models table when the pool has no entries", () => {
const next = setSubagentModelPool(rawWith({}), {
defaultModel: "kimi-k2",
models: {},
force: false,
});
expect(section(next)).toEqual({
default_model: "kimi-k2",
model: "kimi-k2",
force: false,
});
});
it("setSubagentModelPool is idempotent", () => {
const pool: SubagentModelPool = {
defaultModel: "kimi-k2",
models: { "kimi-k2": "K2" },
force: true,
};
const once = setSubagentModelPool(rawWith({ custom: "keep" }), pool);
const twice = setSubagentModelPool(once, pool);
expect(once).toEqual(twice);
});
it("upsertSubagentPoolEntry adds and updates aliases, preserving the rest", () => {
const raw = rawWith({
default_model: "kimi-k1",
models: { "kimi-k1": "K1" },
force: false,
});
const added = upsertSubagentPoolEntry(raw, "kimi-k2", "K2");
expect(modelsOf(added)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
const updated = upsertSubagentPoolEntry(added, "kimi-k2", "K2 thinking");
expect(modelsOf(updated)).toEqual({
"kimi-k1": "K1",
"kimi-k2": "K2 thinking",
});
expect(section(updated).default_model).toBe("kimi-k1");
});
it("removeSubagentPoolEntry keeps the default when removing a non-default alias", () => {
const raw = rawWith({
default_model: "kimi-k1",
model: "kimi-k1",
models: { "kimi-k1": "K1", "kimi-k2": "K2", "kimi-k3": "K3" },
});
const next = removeSubagentPoolEntry(raw, "kimi-k3");
expect(modelsOf(next)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
expect(section(next).default_model).toBe("kimi-k1");
expect(section(next).model).toBe("kimi-k1");
});
it("removeSubagentPoolEntry falls the default back to the first remaining key", () => {
const raw = rawWith({
default_model: "kimi-k1",
model: "kimi-k1",
models: { "kimi-k1": "K1", "kimi-k2": "K2" },
});
const next = removeSubagentPoolEntry(raw, "kimi-k1");
expect(modelsOf(next)).toEqual({ "kimi-k2": "K2" });
expect(section(next).default_model).toBe("kimi-k2");
expect(section(next).model).toBe("kimi-k2");
});
it("removeSubagentPoolEntry collapses an emptied pool to the implicit form", () => {
const raw = rawWith({
default_model: "kimi-k1",
model: "kimi-k1",
models: { "kimi-k1": "K1" },
});
const next = removeSubagentPoolEntry(raw, "kimi-k1");
const sec = section(next);
expect(sec).not.toHaveProperty("models");
expect(sec.default_model).toBe("kimi-k1");
expect(sec.model).toBe("kimi-k1");
});
it("setSubagentDefault syncs both keys and adds a missing alias with an empty description", () => {
const raw = rawWith({ models: { "kimi-k2": "K2" } });
const next = setSubagentDefault(raw, "kimi-k1");
expect(section(next).default_model).toBe("kimi-k1");
expect(section(next).model).toBe("kimi-k1");
expect(modelsOf(next)).toEqual({ "kimi-k2": "K2", "kimi-k1": "" });
});
});
// ---------------------------------------------------------------------------
// setSubagentForce — mutual exclusion with the models table
// ---------------------------------------------------------------------------
describe("setSubagentForce", () => {
it("turning force on drops the models table but keeps the default and unknown fields", () => {
const raw = rawWith({
default_model: "kimi-k1",
model: "kimi-k1",
models: { "kimi-k1": "K1", "kimi-k2": "K2" },
custom: "keep",
});
const next = setSubagentForce(raw, true);
const sec = section(next);
expect(sec).not.toHaveProperty("models");
expect(sec.force).toBe(true);
expect(sec.default_model).toBe("kimi-k1");
expect(sec.model).toBe("kimi-k1");
expect(sec.custom).toBe("keep");
});
it("turning force off leaves the models table untouched", () => {
const raw = rawWith({
default_model: "kimi-k1",
models: { "kimi-k1": "K1", "kimi-k2": "K2" },
force: true,
});
const next = setSubagentForce(raw, false);
expect(section(next).force).toBe(false);
expect(modelsOf(next)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
});
it("is idempotent in both directions", () => {
const raw = rawWith({ force: false, custom: "keep" });
expect(setSubagentForce(raw, true)).toEqual(
setSubagentForce(setSubagentForce(raw, true), true)
);
expect(setSubagentForce(raw, false)).toEqual(
setSubagentForce(setSubagentForce(raw, false), false)
);
});
});
// ---------------------------------------------------------------------------
// validateSubagentPool — mirror of the 6 engine rules
// ---------------------------------------------------------------------------
describe("validateSubagentPool", () => {
const aliases = ["kimi-k1", "kimi-k2", "kimi-k3"];
const pool = (p: Partial<SubagentModelPool>): SubagentModelPool => ({
models: {},
force: false,
...p,
});
it("accepts a valid pool", () => {
expect(
validateSubagentPool(
pool({
defaultModel: "kimi-k2",
models: { "kimi-k2": "K2", "kimi-k3": "K3" },
}),
aliases
)
).toEqual([]);
});
it("accepts the implicit single-entry form when the model resolves", () => {
expect(validateSubagentPool(pool({ model: "kimi-k2" }), aliases)).toEqual([]);
});
it("accepts force with a model fallback when no pool table exists", () => {
expect(
validateSubagentPool(pool({ force: true, model: "kimi-k2" }), aliases)
).toEqual([]);
});
it("flags `primary` as a reserved pool key", () => {
const byDefault = validateSubagentPool(pool({ defaultModel: "primary" }), aliases);
expect(byDefault).toContainEqual({
key: "primaryReserved",
params: { alias: "primary" },
});
const byEntry = validateSubagentPool(
pool({ defaultModel: "kimi-k1", models: { primary: "" } }),
aliases
);
expect(byEntry).toContainEqual({
key: "primaryReserved",
params: { alias: "primary" },
});
});
it("requires `default_model` when the models table exists", () => {
// Strict mirror of the engine: a `model` fallback does not satisfy the
// `default_model` requirement once a `models` table is present.
expect(
validateSubagentPool(
pool({ model: "kimi-k2", models: { "kimi-k2": "K2" } }),
aliases
)
).toEqual([{ key: "defaultRequired" }]);
});
it("flags a default that is not a key of the pool table", () => {
const errors = validateSubagentPool(
pool({ defaultModel: "kimi-k3", models: { "kimi-k2": "K2" } }),
aliases
);
expect(errors).toContainEqual({
key: "defaultNotInPool",
params: { alias: "kimi-k3" },
});
});
it("flags pool keys that do not resolve in the [models] registry", () => {
const errors = validateSubagentPool(
pool({ defaultModel: "kimi-k2", models: { "kimi-k2": "K2", ghost: "?" } }),
aliases
);
expect(errors).toContainEqual({
key: "aliasNotInModels",
params: { alias: "ghost" },
});
// the implicit single-entry default is checked against the registry too
const implicit = validateSubagentPool(pool({ model: "ghost" }), aliases);
expect(implicit).toContainEqual({
key: "aliasNotInModels",
params: { alias: "ghost" },
});
});
it("flags force without any default", () => {
expect(validateSubagentPool(pool({ force: true }), aliases)).toEqual([
{ key: "forceRequiresDefault" },
]);
});
it("flags force coexisting with the models table", () => {
const errors = validateSubagentPool(
pool({ force: true, defaultModel: "kimi-k2", models: { "kimi-k2": "K2" } }),
aliases
);
expect(errors).toContainEqual({ key: "forceExcludesModels" });
});
});
+293 -18
View File
@@ -99,15 +99,48 @@ export function setExperimentalFlag(
}
// ---------------------------------------------------------------------------
// [secondary_model] — subagent secondary model
// [secondary_model] — subagent model pool
// ---------------------------------------------------------------------------
/**
* Parsed subagent model pool (`[secondary_model]` v2 keys). The currently
* effective default is `defaultModel ?? model` (v2 pool key first, legacy v1
* recipe key as fallback).
*/
export interface SubagentModelPool {
/** v2 pool default (`default_model`). */
defaultModel?: string;
/** Legacy v1 recipe key (`model`), kept in sync with `defaultModel`. */
model?: string;
/** `[models]` table (alias → description); non-string values dropped. */
models: Record<string, string>;
/** Force subagents onto the default alias. */
force: boolean;
}
/** Known v1 patch fields, dropped when re-picking without a pool so stale
* patches are cleaned up. */
const PATCH_FIELDS: ReadonlySet<string> = new Set([
"default_effort",
"max_output_size",
"max_context_size",
]);
/** Read `[secondary_model]` from raw_other; `{}` when absent. */
export function getSecondaryModel(rawOther: unknown): SecondaryModelConfig {
const section = asRecord(rawOther)["secondary_model"];
const cfg = asRecord(section);
const out: SecondaryModelConfig = {};
if (typeof cfg.default_model === "string" && cfg.default_model !== "")
out.default_model = cfg.default_model;
if (typeof cfg.model === "string" && cfg.model !== "") out.model = cfg.model;
const models = asRecord(cfg.models);
const pool: Record<string, string> = {};
for (const [k, v] of Object.entries(models)) {
if (typeof v === "string") pool[k] = v;
}
if (Object.keys(pool).length > 0) out.models = pool;
if (cfg.force === true) out.force = true;
if (typeof cfg.default_effort === "string" && cfg.default_effort !== "")
out.default_effort = cfg.default_effort;
if (typeof cfg.max_output_size === "number" && cfg.max_output_size > 0)
@@ -117,15 +150,40 @@ export function getSecondaryModel(rawOther: unknown): SecondaryModelConfig {
return out;
}
/** Read the v2 subagent model pool from raw_other; `undefined` when there is
* no `[secondary_model]` section or it is empty. The effective default is
* `defaultModel ?? model`. */
export function getSubagentModelPool(
rawOther: unknown
): SubagentModelPool | undefined {
const section = asRecord(asRecord(rawOther)["secondary_model"]);
if (Object.keys(section).length === 0) return undefined;
const models: Record<string, string> = {};
for (const [k, v] of Object.entries(asRecord(section["models"]))) {
if (typeof v === "string") models[k] = v;
}
const out: SubagentModelPool = { models, force: section["force"] === true };
if (typeof section["default_model"] === "string" && section["default_model"] !== "")
out.defaultModel = section["default_model"];
if (typeof section["model"] === "string" && section["model"] !== "")
out.model = section["model"];
return out;
}
/**
* Write `[secondary_model]` with only the `model` field — no patch fields.
* Subagents then bind the pointed model entry directly and inherit its
* settings (context size, capabilities, effort fallback), which also keeps
* usage records keyed on the real model alias instead of the synthesized
* `__secondary__` derived entry. Unknown fields already present in the
* section are preserved; the known patch fields (`default_effort`,
* `max_output_size`, `max_context_size`) are dropped so stale patches are
* cleaned up when the model is re-picked.
* Write `[secondary_model]` picking the given alias as the subagent model.
*
* Pool-aware: when a pool exists (`models` table or `default_model` present)
* the alias becomes the v2 default (added to the `models` table with an empty
* description when missing) and the legacy `model` key is synced; the rest of
* the section — `force`, patch fields, unknown fields — is preserved. This
* keeps usage records keyed on the real model alias instead of the
* synthesized `__secondary__` derived entry.
*
* Without a pool the legacy single-model form is written: only `model`, with
* the known patch fields (`default_effort`, `max_output_size`,
* `max_context_size`) dropped so stale patches are cleaned up when the model
* is re-picked; unknown fields are preserved.
*/
export function setSecondaryModelOnly(
rawOther: unknown,
@@ -133,20 +191,237 @@ export function setSecondaryModelOnly(
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = { model: alias };
const knownFields: ReadonlySet<string> = new Set([
"model",
"default_effort",
"max_output_size",
"max_context_size",
]);
for (const [k, v] of Object.entries(section)) {
if (!knownFields.has(k)) next[k] = v;
const next: Record<string, unknown> = {};
const hasPool =
section["models"] !== undefined || section["default_model"] !== undefined;
if (hasPool) {
for (const [k, v] of Object.entries(section)) next[k] = v;
next.default_model = alias;
next.model = alias;
const models: Record<string, unknown> = {};
for (const [k, v] of Object.entries(asRecord(next.models))) models[k] = v;
if (!(alias in models)) models[alias] = "";
next.models = models;
} else {
for (const [k, v] of Object.entries(section)) {
if (!PATCH_FIELDS.has(k)) next[k] = v;
}
next.model = alias;
}
root.secondary_model = next;
return root;
}
/**
* Rebuild the subagent model pool atomically. `default_model` and `model` are
* written with the same value — the effective default, `defaultModel ?? model`
* — plus the `models` table and `force`; unknown fields in the section are
* preserved. An empty `models` table is omitted: the engine requires
* `default_model` to be a key of the table, so an empty table can never be
* valid, and omitting it keeps the implicit single-entry form.
*/
export function setSubagentModelPool(
rawOther: unknown,
pool: SubagentModelPool
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) next[k] = v;
const effective = pool.defaultModel ?? pool.model;
if (effective) {
next.default_model = effective;
next.model = effective;
} else {
delete next.default_model;
delete next.model;
}
if (Object.keys(pool.models).length > 0) {
next.models = { ...pool.models };
} else {
delete next.models;
}
next.force = pool.force === true;
root.secondary_model = next;
return root;
}
/** Add or update one alias in the pool `models` table. The rest of the
* section (default, force, unknown fields) is preserved untouched. */
export function upsertSubagentPoolEntry(
rawOther: unknown,
alias: string,
description: string
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) next[k] = v;
const models: Record<string, unknown> = {};
for (const [k, v] of Object.entries(asRecord(next.models))) models[k] = v;
models[alias] = description;
next.models = models;
root.secondary_model = next;
return root;
}
/**
* Remove one alias from the pool `models` table. If it was the default, the
* default falls back to the first remaining key (`default_model` and `model`
* are both synced). Removing the last entry drops the `models` table and
* leaves `default_model`/`model` in place — the implicit single-entry pool.
*/
export function removeSubagentPoolEntry(
rawOther: unknown,
alias: string
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) next[k] = v;
const models: Record<string, unknown> = {};
for (const [k, v] of Object.entries(asRecord(next.models))) {
if (k !== alias) models[k] = v;
}
const remaining = Object.keys(models);
if (remaining.length === 0) {
delete next.models;
} else {
next.models = models;
if (next.default_model === alias) {
next.default_model = remaining[0];
next.model = remaining[0];
}
}
root.secondary_model = next;
return root;
}
/** Set the pool default alias, syncing `default_model` and `model`; the alias
* is added to the `models` table with an empty description when missing. */
export function setSubagentDefault(
rawOther: unknown,
alias: string
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) next[k] = v;
const models: Record<string, unknown> = {};
for (const [k, v] of Object.entries(asRecord(next.models))) models[k] = v;
if (!(alias in models)) models[alias] = "";
next.models = models;
next.default_model = alias;
next.model = alias;
root.secondary_model = next;
return root;
}
/**
* Set the `force` flag. Turning force on drops the `models` table — `force`
* and the pool table are mutually exclusive per the engine (the implicit
* `default_model`/`model` form stays); turning it off leaves the table
* untouched. Everything else in the section is preserved.
*/
export function setSubagentForce(
rawOther: unknown,
force: boolean
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) {
if (force && k === "models") continue;
next[k] = v;
}
next.force = force;
root.secondary_model = next;
return root;
}
/** Keys of validation errors, mirroring the kimi-code engine checks. */
export type ValidationErrorKey =
| "primaryReserved"
| "defaultRequired"
| "defaultNotInPool"
| "aliasNotInModels"
| "forceRequiresDefault"
| "forceExcludesModels";
/** A pool validation error; `params` carries the offending alias. */
export interface PoolValidationError {
key: ValidationErrorKey;
params?: Record<string, string>;
}
/**
* Mirror the kimi-code engine validation for the subagent model pool
* (violations fail the kimi session with CONFIG_INVALID):
* 1. `"primary"` is reserved and cannot be a pool key;
* 2. a `models` table requires `default_model`;
* 3. `default_model` must be a key of the `models` table;
* 4. every pool key must resolve in the top-level `[models]` registry;
* 5. `force` requires a default (`default_model` or the `model` fallback);
* 6. `force` and a `models` table are mutually exclusive.
*
* `availableAliases` is the set of top-level `[models]` aliases. A pool
* without a `models` table is the implicit single-entry form: only the
* effective default is checked against the registry.
*/
export function validateSubagentPool(
pool: SubagentModelPool,
availableAliases: string[]
): PoolValidationError[] {
const errors: PoolValidationError[] = [];
const { defaultModel, model, models, force } = pool;
const effectiveDefault = defaultModel ?? model;
const poolKeys = Object.keys(models);
const hasPoolTable = poolKeys.length > 0;
const registry = new Set(availableAliases);
const aliasError = (alias: string) => {
if (alias !== "primary" && !registry.has(alias)) {
errors.push({ key: "aliasNotInModels", params: { alias } });
}
};
// Rule 1: "primary" is reserved as a pool key.
if (effectiveDefault === "primary") {
errors.push({ key: "primaryReserved", params: { alias: "primary" } });
}
for (const key of poolKeys) {
if (key === "primary") {
errors.push({ key: "primaryReserved", params: { alias: key } });
}
}
// Rule 2: a `models` table requires `default_model`.
if (hasPoolTable && !defaultModel) {
errors.push({ key: "defaultRequired" });
}
// Rule 3: `default_model` must be a key of the `models` table.
if (hasPoolTable && defaultModel && !(defaultModel in models)) {
errors.push({ key: "defaultNotInPool", params: { alias: defaultModel } });
}
// Rule 4: every pool key must resolve in the `[models]` registry.
for (const key of poolKeys) aliasError(key);
if (!hasPoolTable && effectiveDefault) aliasError(effectiveDefault);
// Rule 5: `force` requires a default (`default_model` or `model` fallback).
if (force && !effectiveDefault) {
errors.push({ key: "forceRequiresDefault" });
}
// Rule 6: `force` and a `models` table are mutually exclusive.
if (force && hasPoolTable) {
errors.push({ key: "forceExcludesModels" });
}
return errors;
}
/** Remove `[secondary_model]` entirely (the "not configured" option). */
export function clearSecondaryModel(rawOther: unknown): unknown {
const root = { ...asRecord(rawOther) };
+5 -3
View File
@@ -11,9 +11,9 @@ type TranslateFn = (
*
* Coverage note: ALL plan-type (套餐) queries flow through
* src-tauri/src/services/coding_plan.rs::percent_tier, whose names come only
* from TIER_FIVE_HOUR / TIER_WEEKLY_LIMIT — so this mapping covers every
* current and future plan provider automatically. If a new tier id is ever
* added there, add a case here too.
* from TIER_FIVE_HOUR / TIER_WEEKLY_LIMIT / TIER_MONTHLY_LIMIT — so this
* mapping covers every current and future plan provider automatically. If a
* new tier id is ever added there, add a case here too.
*/
export function planLabel(name: string, t: TranslateFn): string {
switch (name) {
@@ -21,6 +21,8 @@ export function planLabel(name: string, t: TranslateFn): string {
return t("usageTier5h");
case "weekly_limit":
return t("usageTierWeekly");
case "monthly_limit":
return t("usageTierMonthly");
default:
return name;
}
+60 -4
View File
@@ -134,13 +134,28 @@ export interface AgentSettings {
}
/**
* Kimi Code `[secondary_model]` section of config.toml: the secondary model
* bound to newly spawned subagents (experimental feature).
* `model` points at an alias defined in `[models]`; the remaining fields are
* a patch applied on top of the referenced entry (subagents only).
* Kimi Code `[secondary_model]` section of config.toml: the subagent model
* pool (experimental feature).
*
* v2 engine (default) reads the pool keys: `default_model` + `[models]` table
* (alias → description) + `force`. `model` is ignored by the v2 validator when
* pool keys are present, but is kept in sync with `default_model` so the v1
* engine (KIMI_CODE_LEGACY_FLAG=1) resolves the same alias.
*
* v1 engine reads only the recipe key `model` plus the patch fields; pool keys
* are ignored by it. Pool resolution order: `models` table → `default_model` →
* `model`.
*/
export interface SecondaryModelConfig {
/** v2: default subagent alias in the pool (a key of `models`). */
default_model?: string;
/** v2: alias → description table for the subagent model pool. */
models?: Record<string, string>;
/** v2: force subagents onto the default alias (excludes `models`). */
force?: boolean;
/** Legacy v1 recipe key — written in sync so KIMI_CODE_LEGACY_FLAG=1 works. */
model?: string;
/** v1 patch fields, applied on top of the referenced entry (v1 only). */
default_effort?: string;
max_output_size?: number;
max_context_size?: number;
@@ -148,3 +163,44 @@ export interface SecondaryModelConfig {
/** Values of experimental env vars that are currently set (non-empty). */
export type ExperimentalEnvStatus = Record<string, string>;
/**
* A plugin installed under the kimi-code plugin directory
* (mirrors the Rust `InstalledPluginInfo`, camelCase via serde).
*/
export interface InstalledPluginInfo {
id: string;
root: string;
source: string;
enabled: boolean;
version: string | null;
installedAt: string | null;
updatedAt: string | null;
/** Whether the plugin came from the marketplace catalog (vs. manual install). */
isMarketplace: boolean;
}
/** One entry of the plugin marketplace catalog (mirrors Rust `MarketplaceEntry`). */
export interface MarketplaceEntry {
id: string;
displayName: string;
version: string | null;
description: string | null;
keywords: string[];
homepage: string | null;
/** "official" | "curated" | anything else → community. */
tier: string;
/** Install source (URL / path) passed to `install_plugin`. */
source: string;
/** Non-null → must be installed inside kimi-code via /plugins, not here. */
capabilityId: string | null;
installed: InstalledPluginInfo | null;
updateAvailable: boolean;
}
/** Result of `get_plugin_marketplace` (mirrors Rust `PluginMarketplaceResult`). */
export interface PluginMarketplaceResult {
fetchedAt: string;
fromCache: boolean;
entries: MarketplaceEntry[];
}
+4
View File
@@ -1,3 +1,4 @@
/// <reference types="vitest" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
@@ -10,4 +11,7 @@ export default defineConfig(async () => ({
watch: { ignored: ["**/src-tauri/**"] },
},
envPrefix: ["VITE_"],
test: {
environment: "node",
},
}));