fix: review fixes, GitHub Releases update check (0.1.1)
- Wallet/subscription/window exhaustion skips a key for 10 minutes instead of disabling it; a balance read showing money brings it back. Only the gateway's own key refusals and a used-up key cap still disable a key. - Classify by sub2api's exact wording; a bare 401 or upstream text no longer retires a key; 'No available accounts' is capacity, not coverage. - Hosts keep only an https origin (no doubled /v1); timeouts and HTTP answers no longer set a host aside; hand edits are re-probed. - Balance: inactive subscriptions, per-plan subscription pooling, key caps kept out of the total, rate windows shown. - Endpoint editor no longer empties itself after Save. - Update check reads GitHub Releases and installs the release tarball; release workflow replaces npm publishing. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
86b8e4d24f
commit
f4f4ce55b3
34 files changed
+953
-521
No files matched your search
@@ -1,120 +0,0 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish to npm
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10.32.1
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22.20.0
|
||||
cache: pnpm
|
||||
- name: Require an npm CLI that can use trusted publishing
|
||||
run: |
|
||||
node <<'EOF'
|
||||
const { execSync } = require('node:child_process')
|
||||
const version = () => execSync('npm --version', { encoding: 'utf8' }).trim()
|
||||
const supports = value => {
|
||||
const [major, minor, patch] = value.split('.').map(Number)
|
||||
return major > 11 || (major === 11 && (minor > 5 || (minor === 5 && patch >= 1)))
|
||||
}
|
||||
if (!supports(version())) {
|
||||
execSync('npm install -g npm@11', { stdio: 'inherit' })
|
||||
}
|
||||
const current = version()
|
||||
if (!supports(current)) {
|
||||
console.error(`npm ${current} cannot publish with a trusted publisher`)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`npm ${current}`)
|
||||
EOF
|
||||
- name: Install locked dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Refuse a tag that does not match package.json
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
run: |
|
||||
node <<'EOF'
|
||||
const version = require('./package.json').version
|
||||
const tag = process.env.GITHUB_REF_NAME.replace(/^v/, '')
|
||||
if (version !== tag) {
|
||||
console.error(`tag v${tag} does not match package.json ${version}`)
|
||||
process.exit(1)
|
||||
}
|
||||
EOF
|
||||
- name: Test
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
run: pnpm run test
|
||||
- name: Verify committed lib/ matches a fresh build of src/
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
run: |
|
||||
pnpm run build
|
||||
git diff --exit-code -- lib
|
||||
- name: Package the verified release artifact
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
run: pnpm pack --pack-destination .artifacts
|
||||
- name: Show the OIDC identity npm will match
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
run: |
|
||||
node <<'EOF'
|
||||
async function main() {
|
||||
const audience = 'npm:registry.npmjs.org'
|
||||
const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL)
|
||||
url.searchParams.set('audience', audience)
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}` },
|
||||
})
|
||||
const body = await response.json()
|
||||
if (!response.ok || !body.value) {
|
||||
console.error('GitHub did not return an OIDC token', response.status)
|
||||
process.exit(1)
|
||||
}
|
||||
const payload = JSON.parse(Buffer.from(body.value.split('.')[1], 'base64url').toString())
|
||||
const claims = ['repository','repository_owner','workflow','workflow_ref','job_workflow_ref','ref','environment','repository_visibility','aud','iss']
|
||||
for (const key of claims) console.log(`${key}=${payload[key] ?? ''}`)
|
||||
const exchange = await fetch('https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/dsh-geek2api', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${body.value}` },
|
||||
})
|
||||
// Never print the exchange body: truncation can cut off a token's
|
||||
// closing quote before a redaction regex sees it.
|
||||
await exchange.arrayBuffer()
|
||||
console.log(`exchange_status=${exchange.status}`)
|
||||
if (!exchange.ok) {
|
||||
console.error('npm rejected the trusted publisher; verify repository, workflow filename and environment before tagging')
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
main()
|
||||
EOF
|
||||
- name: Publish
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
run: |
|
||||
if [ -z "$ACTIONS_ID_TOKEN_REQUEST_URL" ]; then
|
||||
echo "GitHub did not provide an OIDC token request URL"
|
||||
exit 1
|
||||
fi
|
||||
# Do not set NODE_AUTH_TOKEN at all, even to an empty string.
|
||||
# npm treats a present token variable as token auth and skips OIDC.
|
||||
unset NODE_AUTH_TOKEN
|
||||
version="$(node -p "require('./package.json').version")"
|
||||
artifact=".artifacts/dsh-geek2api-${version:?}.tgz"
|
||||
if [ ! -f "$artifact" ]; then
|
||||
echo "The verified release artifact is missing"
|
||||
exit 1
|
||||
fi
|
||||
npm publish "${artifact:?}" --access public
|
||||
@@ -0,0 +1,56 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Build and attach the package
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10.32.1
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22.20.0
|
||||
cache: pnpm
|
||||
- name: Install locked dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Refuse a tag that does not match package.json
|
||||
run: |
|
||||
node <<'EOF'
|
||||
const version = require('./package.json').version
|
||||
const tag = process.env.GITHUB_REF_NAME.replace(/^v/, '')
|
||||
if (version !== tag) {
|
||||
console.error(`tag v${tag} does not match package.json ${version}`)
|
||||
process.exit(1)
|
||||
}
|
||||
EOF
|
||||
- name: Test, build, and pack
|
||||
run: pnpm run check
|
||||
- name: Refuse a stale lib/ build
|
||||
run: git diff --exit-code -- lib/
|
||||
- name: Create or update the release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
VERSION="${GITHUB_REF_NAME#v}"
|
||||
ASSET=".artifacts/dsh-geek2api-${VERSION}.tgz"
|
||||
test -f "$ASSET"
|
||||
# An unversioned copy gives a stable install address:
|
||||
# https://github.com/CoderKuo/dsh-geek2api/releases/latest/download/dsh-geek2api.tgz
|
||||
cp "$ASSET" .artifacts/dsh-geek2api.tgz
|
||||
NOTES="$(awk -v v="## ${VERSION}" '$0==v{f=1;next} /^## /{f=0} f' CHANGELOG.md)"
|
||||
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
|
||||
gh release upload "$GITHUB_REF_NAME" "$ASSET" .artifacts/dsh-geek2api.tgz --clobber
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" "$ASSET" .artifacts/dsh-geek2api.tgz --title "dsh-geek2api v${VERSION}" --notes "$NOTES"
|
||||
fi
|
||||
@@ -4,8 +4,8 @@ This file governs the entire `dsh-geek2api` repository.
|
||||
|
||||
## Repository identity
|
||||
|
||||
- Canonical repository: not published yet (derived from `https://github.com/BaronCyrus/dsh-packycode-api`, MIT)
|
||||
- npm package: `dsh-geek2api`
|
||||
- Canonical repository: `https://github.com/CoderKuo/dsh-geek2api` (derived from `https://github.com/BaronCyrus/dsh-packycode-api`, MIT)
|
||||
- Package name: `dsh-geek2api`, distributed as a GitHub Release tarball (`dsh-geek2api-<version>.tgz`); not published to npm
|
||||
- DSH plugin row: `geek2api`
|
||||
- Model group display name: `Geek2API`
|
||||
- Gateway: Geek2API, a sub2api deployment. Entry points: `hk`, `hk2`, `hk3`, `hk4`, `www` `.geek2api.com`. Default endpoints are geek2api.com hosts only.
|
||||
@@ -47,52 +47,30 @@ Live gateway behavior is verified with `node scripts/live-check.mjs` after a bui
|
||||
|
||||
## Release authorization
|
||||
|
||||
`npm publish`, Git tags, GitHub Releases, and version publication are externally visible and partially irreversible. Execute them only when the user explicitly asks to publish or release and confirms the target version. A request to modify, test, or commit alone is not release authorization.
|
||||
Git tags and GitHub Releases are externally visible: installed copies offer the newest release as an update. Create them only when the user explicitly asks to release and confirms the target version. A request to modify, test, or commit alone is not release authorization.
|
||||
|
||||
Never reuse, move, delete, or overwrite a published npm version or Git tag. If a published version needs a correction, create a new patch version.
|
||||
Never reuse, move, or delete a published tag or release asset. If a released version needs a correction, release a new patch version.
|
||||
|
||||
## Release checklist
|
||||
|
||||
1. Synchronize and confirm a clean base:
|
||||
1. Confirm a clean base and an unused version:
|
||||
|
||||
```sh
|
||||
git fetch origin --tags --prune
|
||||
git status --short --branch
|
||||
git log --oneline HEAD..origin/main
|
||||
git ls-remote --exit-code --tags origin refs/tags/v<version> # must fail
|
||||
```
|
||||
|
||||
Fast-forward clean remote changes before editing. Never discard remote changes.
|
||||
2. Update `package.json` version and add a `## <version>` section to `CHANGELOG.md` (the release workflow uses that section as the release notes).
|
||||
|
||||
2. Confirm the requested SemVer is unused:
|
||||
3. Validate: `pnpm install --frozen-lockfile && pnpm run check`, and commit the rebuilt `lib/`.
|
||||
|
||||
```sh
|
||||
npm view dsh-geek2api@<version> version --json
|
||||
git ls-remote --exit-code --tags origin refs/tags/v<version>
|
||||
```
|
||||
|
||||
For an unused npm version, `npm view` normally returns `E404`. An existing npm version or Git tag requires choosing a new version.
|
||||
|
||||
3. Update all release metadata together: `package.json` version, `CHANGELOG.md`, and any version pinned in `README.md` / `README.en.md`.
|
||||
|
||||
4. Validate and inspect the exact release artifact:
|
||||
|
||||
```sh
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm run check
|
||||
npm publish .artifacts/dsh-geek2api-<version>.tgz --access public --dry-run --json
|
||||
```
|
||||
|
||||
5. Commit the release and push `main` without force. [`.github/workflows/publish.yml`](.github/workflows/publish.yml) must already be on the commit that will be tagged. Do not push the tag in this step.
|
||||
|
||||
6. Confirm the package has a GitHub Actions trusted publisher before pushing the tag: repository `<owner>/dsh-geek2api`, workflow filename `publish.yml`, environment empty. Never request that a token, password, or one-time code be pasted into chat.
|
||||
|
||||
7. Create the annotated tag and push it. That push publishes with GitHub OIDC. Do not run `npm publish` locally for a release. A local publish cannot attach provenance. Do not set `NODE_AUTH_TOKEN` or a setup-node `registry-url` in the publish workflow; npm treats either as token auth and skips OIDC.
|
||||
4. Push `main`, then tag and push the tag:
|
||||
|
||||
```sh
|
||||
git tag -a v<version> -m "dsh-geek2api v<version>"
|
||||
git push origin v<version>
|
||||
```
|
||||
|
||||
`workflow_dispatch` on the same workflow only prints the OIDC identity npm will match. It does not publish.
|
||||
[`.github/workflows/release.yml`](.github/workflows/release.yml) refuses a tag that does not match `package.json`, runs `pnpm run check`, refuses a stale `lib/`, and creates the release with `dsh-geek2api-<version>.tgz` attached. The plugin's update check reads `releases/latest` and installs that asset.
|
||||
|
||||
8. Confirm the publish workflow succeeded for that tag before declaring the release public. On an OIDC `package not found` error, fix the trusted publisher and re-run the same workflow. Do not move the tag. If the tagged tree itself must change, publish a new patch version.
|
||||
5. Confirm the workflow succeeded and the asset is attached before announcing the release.
|
||||
+7
-1
@@ -2,6 +2,12 @@
|
||||
|
||||
## 0.1.1
|
||||
|
||||
- Updates come from GitHub Releases (`CoderKuo/dsh-geek2api`) instead of npm: the version card reads the latest release, links its release notes, and installs its tarball in place for installs from a release tarball (or the npm registry). The release workflow builds, tests, and attaches `dsh-geek2api-<version>.tgz` plus an unversioned `dsh-geek2api.tgz` for a stable install address.
|
||||
- Keys whose money ran out (wallet `余额不足,请充值`, a lapsed subscription, a subscription window or a key's 5h/1d/7d window) are skipped for 10 minutes instead of being disabled, and come back as soon as a balance read shows money. Previously one empty wallet disabled every key of the account until each was re-enabled by hand. Only the key's own cap (`API key 额度已用完`) and the gateway's own key refusals still disable a key; a bare 401 or generic quota wording passed through from an upstream no longer does.
|
||||
- `No available accounts` is reported as a busy gateway, not as "no key can use this model".
|
||||
- Endpoints keep only the origin, so a pasted `https://hk.geek2api.com/v1` no longer doubles every path, and must be https (plain http only on loopback). A timeout no longer sets a host aside, and gateway error text mentioning TLS no longer does either. A hand-edited endpoint list is measured at once.
|
||||
- Balance: an inactive subscription is shown as such instead of "unrecognized payload"; keys on the same subscription plan count it once; a key quota is shown as a cap (it spends the wallet) and left out of the total; 5h/1d/7d windows are shown.
|
||||
- Fixed the endpoint list editor emptying itself after Save (a second Save then restored the defaults); an empty list can no longer be saved, use Restore defaults instead.
|
||||
- Fixed the endpoint list editor in Settings → Geek2API → Endpoints being only about 20 characters wide: it now spans the card, grows with the list, and resizes vertically.
|
||||
|
||||
## 0.1.0
|
||||
@@ -10,7 +16,7 @@ First release. Derived from [dsh-packycode-api](https://github.com/BaronCyrus/ds
|
||||
|
||||
- **Route and catalog.** A self-contained `Geek2API` model route with 13 models, each pinned to the protocol its vendor serves on this gateway: Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 4.5 on Messages; GPT-6.1 Sol, GPT-6 Astra, GPT-6 Luna, Grok 4.6, and Grok 4.7 on Responses; DeepSeek V4.1 Flash, DeepSeek V4 Pro, Gemini 3.8 Flash, GLM-5.3, and Kimi K3 on Chat Completions. Gemini, GLM, and Kimi are declared without reasoning control; the route asks them for `off` so the profile's default effort never refuses them.
|
||||
- **Multi-endpoint failover.** The built-in endpoints are `hk`, `hk2`, `hk3`, `hk4`, and `www` `.geek2api.com`. They are ranked by `/health` latency (re-measured every 10 minutes and on demand). A host that fails in transit — DNS, TLS, connect timeout, reset — is passed over for two minutes, and the harness's retry of the step lands on the next one. Balance, model-list, and search reads fail over the same way. The list is editable in Settings → Geek2API → Endpoints.
|
||||
- **Balance.** Read from `/v1/usage` per key, covering the three shapes sub2api answers: wallet, subscription (the tightest daily/weekly/monthly window), and per-key quota (with 5h/1d/7d windows). Keys of one account share a wallet, so the total counts a wallet once (by the gateway's `account_ref` when present, otherwise by identical balance). Today's spend is shown per key.
|
||||
- **Balance.** Read from `/v1/usage` per key, covering the three shapes sub2api answers: wallet, subscription (the tightest daily/weekly/monthly window), and per-key quota (with 5h/1d/7d windows). Today's spend is shown per key.
|
||||
- **Per-key models.** Each key's `/v1/models` decides which catalog models it reaches (✓/✕ per family). Group names are shown when `/v1/usage` reports them. A key whose group was deleted or withdrawn (`API Key 所属分组已删除`) is recognized as rejected.
|
||||
- **Key rotation.** sub2api's own wording moves a key aside: `Invalid API key`, `API key is disabled`, `API key 已过期`, `余额不足,请充值`, `No active subscription`. A request for a model none of the stored keys can use (`Model 'x' is not available`) is explained instead of retried; HTTP 400 is no longer retryable.
|
||||
- **Claude runtime.** Claude models call the Messages API directly by default (DSH's own tools, permissions, and plan mode). Settings → Geek2API → Claude runtime switches them to the local Claude Code CLI, which keeps the CLI adapter, MCP web search bridge, and plan-mode handoff of the original. The `claude_code` delegation tool is unchanged.
|
||||
|
||||
+2
-2
@@ -27,7 +27,7 @@ Installing it adds a `Geek2API` group to the model picker. No YAML and no provid
|
||||
|
||||
## Install
|
||||
|
||||
1. In the desktop app, open **Plugins → Add plugin**, enter `dsh-geek2api`, choose the official registry, and install. No restart is needed for a first install.
|
||||
1. In the desktop app, open **Plugins → Add plugin**, enter `https://github.com/CoderKuo/dsh-geek2api/releases/latest/download/dsh-geek2api.tgz`, and install. No restart is needed for a first install. You can also download the `.tgz` from [Releases](https://github.com/CoderKuo/dsh-geek2api/releases) and install it from a local path.
|
||||
2. Open **Settings → Geek2API** and paste an API key (create one under API Keys in the Geek2API console). Add more keys for other groups; the plugin picks the right one per model.
|
||||
3. Pick a model under the `Geek2API` group.
|
||||
|
||||
@@ -56,7 +56,7 @@ Whether a key can use a model depends on its group; trust the ✓ / ✕ in setti
|
||||
|
||||
## Update and uninstall
|
||||
|
||||
Update from **Settings → Geek2API → Update plugin**, then fully quit and reopen the desktop app. Before uninstalling, set web search back to "leave DSH alone" if you used it, then uninstall from the Plugins page and restart.
|
||||
The version card in **Settings → Geek2API** checks the latest GitHub release; update from there, then fully quit and reopen the desktop app. Before uninstalling, set web search back to "leave DSH alone" if you used it, then uninstall from the Plugins page and restart.
|
||||
|
||||
## Security
|
||||
|
||||
|
||||
@@ -36,10 +36,10 @@
|
||||
打开桌面应用的**插件**页,点击**添加插件**,在**包名或地址**中填入:
|
||||
|
||||
```text
|
||||
dsh-geek2api
|
||||
https://github.com/CoderKuo/dsh-geek2api/releases/latest/download/dsh-geek2api.tgz
|
||||
```
|
||||
|
||||
在**安装源**中选择**官方源**,然后点击**安装**。首次安装后不用重启 DSH。
|
||||
然后点击**安装**。首次安装后不用重启 DSH。也可以先从 [Releases](https://github.com/CoderKuo/dsh-geek2api/releases) 下载 `.tgz`,再填本地文件路径安装。
|
||||
|
||||
### 2. 添加 Key
|
||||
|
||||
@@ -118,7 +118,7 @@ dsh-geek2api
|
||||
|
||||
## 更新与卸载
|
||||
|
||||
**更新:** 打开 **设置 → Geek2API**,有新版本时点「更新插件」,完成后完全退出并重新打开桌面应用。
|
||||
**更新:** 打开 **设置 → Geek2API**,「插件版本」卡片会检查 GitHub 上的最新发布;有新版本时点「更新插件」,完成后完全退出并重新打开桌面应用。「更新说明」链接到这个版本的发布页。
|
||||
|
||||
**卸载:** 用过 Geek2API 网页搜索的话,先在 **设置 → Geek2API → 网页搜索** 切回「不接管」,再到**插件**页卸载,然后重启桌面应用。否则 `cordis.patch.yml` 里会留下指向已卸载后端的配置;这时手动删掉带 `dsh-geek2api: web search provider` 标记的那一段即可。
|
||||
|
||||
|
||||
+90
-29
@@ -46,12 +46,14 @@ window.__ModuleLoader__.load({
|
||||
totalLimit: "合计额度",
|
||||
totalPartial: "有 {count} 个 Key 未读到余额,未计入合计。",
|
||||
totalStale: "其中 {count} 个 Key 本次读取失败,显示的是上次读到的余额。",
|
||||
totalShared: "{count} 个 Key 与其他 Key 共用同一个钱包,只计一次。",
|
||||
totalShared: "{count} 个 Key 与其他 Key 共用同一个钱包或订阅,只计一次。",
|
||||
totalCapped: "{count} 个 Key 设有自己的限额,它们花的是账户钱包,限额不计入合计。",
|
||||
staleNote: "上次读取于 {time},本次读取失败:{error}",
|
||||
empty: "还没有 Key。添加一个即可在模型选择器里看到 Geek2API 的模型。",
|
||||
keysHint: "按顺序使用:当前 Key 不可用时自动切到下一个;「切到此 Key」指定优先使用的 Key。",
|
||||
keyActive: "使用中",
|
||||
keyDisabled: "已停用",
|
||||
keySkipped: "余额不足,暂时跳过",
|
||||
keyUse: "切到此 Key",
|
||||
keyEnable: "重新启用",
|
||||
keyRemove: "删除",
|
||||
@@ -69,7 +71,10 @@ window.__ModuleLoader__.load({
|
||||
keyToday: "今日",
|
||||
planWallet: "钱包余额(同账户的 Key 共用)",
|
||||
planSubscription: "订阅:{name}",
|
||||
planQuota: "Key 限额",
|
||||
planQuota: "Key 限额(从账户钱包扣费)",
|
||||
planSubscriptionInactive: "订阅:{name}(未开通或已过期)",
|
||||
keyCapRemaining: "Key 剩余限额",
|
||||
keyWindow: "{window} 窗口 {used}/{limit}",
|
||||
keyExpires: "{date} 到期",
|
||||
resetMonthly: "每月重置",
|
||||
resetWeekly: "每周重置",
|
||||
@@ -80,7 +85,7 @@ window.__ModuleLoader__.load({
|
||||
addKeyPlaceholder: "粘贴 API Key",
|
||||
addLabelPlaceholder: "备注(可选)",
|
||||
add: "添加",
|
||||
notWritable: "当前 profile 不允许写入设置,改动只在本次运行内生效。",
|
||||
notWritable: "当前 profile 不允许写入设置,这些选项暂时不能修改。",
|
||||
error: "读取 Geek2API 状态失败",
|
||||
groupsTitle: "分组",
|
||||
groupsExtra: "另有 {count} 个模型不在内置列表中",
|
||||
@@ -108,7 +113,7 @@ window.__ModuleLoader__.load({
|
||||
hostsCooling: "暂时跳过",
|
||||
hostsUnprobed: "未测速",
|
||||
hostsEdit: "编辑地址列表",
|
||||
hostsEditHint: "每行一个地址,按优先顺序排列。留空则恢复默认列表。",
|
||||
hostsEditHint: "每行一个地址(只取域名部分,必须是 https),按优先顺序排列。要恢复内置列表请点「恢复默认」。",
|
||||
hostsSave: "保存",
|
||||
hostsReset: "恢复默认",
|
||||
composerLabel: "Geek2API 剩余额度",
|
||||
@@ -152,7 +157,8 @@ window.__ModuleLoader__.load({
|
||||
versionUpToDate: "已是最新版本",
|
||||
versionAvailable: "发现新版本 v{version}",
|
||||
versionLinked: "当前是本地开发安装,请在插件仓库拉取代码并重新构建。",
|
||||
versionManual: "无法在这里更新。请在桌面应用的插件页重新安装 dsh-geek2api。",
|
||||
versionManual: "无法在这里自动更新。请到 GitHub Releases 下载新版本,在桌面应用的插件页重新安装。",
|
||||
versionNotes: "更新说明",
|
||||
versionUpdate: "更新插件",
|
||||
versionUpdating: "正在更新…",
|
||||
versionUpdateFailed: "更新失败,请重试,或在插件页重新安装。",
|
||||
@@ -208,12 +214,14 @@ window.__ModuleLoader__.load({
|
||||
totalLimit: "Total limit",
|
||||
totalPartial: "{count} key(s) could not be read and are not counted here.",
|
||||
totalStale: "{count} of these keys failed this read and show their last read balance.",
|
||||
totalShared: "{count} key(s) share a wallet with another key and are counted once.",
|
||||
totalShared: "{count} key(s) share a wallet or subscription with another key and are counted once.",
|
||||
totalCapped: "{count} key(s) have their own cap; they spend the account wallet, so caps are not added to the total.",
|
||||
staleNote: "Last read at {time}; this read failed: {error}",
|
||||
empty: "No keys yet. Add one and the Geek2API models appear in the model picker.",
|
||||
keysHint: "Used in order: when the active key cannot serve a request, the next one takes over. “Use this key” picks the preferred key.",
|
||||
keyActive: "Active",
|
||||
keyDisabled: "Disabled",
|
||||
keySkipped: "Out of balance, skipped for now",
|
||||
keyUse: "Use this key",
|
||||
keyEnable: "Re-enable",
|
||||
keyRemove: "Remove",
|
||||
@@ -231,7 +239,10 @@ window.__ModuleLoader__.load({
|
||||
keyToday: "Today",
|
||||
planWallet: "Wallet (shared by the account’s keys)",
|
||||
planSubscription: "Subscription: {name}",
|
||||
planQuota: "Key quota",
|
||||
planQuota: "Key quota (spends the account wallet)",
|
||||
planSubscriptionInactive: "Subscription: {name} (not active)",
|
||||
keyCapRemaining: "Cap left",
|
||||
keyWindow: "{window} window {used}/{limit}",
|
||||
keyExpires: "expires {date}",
|
||||
resetMonthly: "resets monthly",
|
||||
resetWeekly: "resets weekly",
|
||||
@@ -242,7 +253,7 @@ window.__ModuleLoader__.load({
|
||||
addKeyPlaceholder: "Paste API key",
|
||||
addLabelPlaceholder: "Label (optional)",
|
||||
add: "Add",
|
||||
notWritable: "This profile does not allow settings writes; changes apply to this run only.",
|
||||
notWritable: "This profile does not allow settings writes; these options cannot be changed here.",
|
||||
error: "Could not read Geek2API status",
|
||||
groupsTitle: "Groups",
|
||||
groupsExtra: "{count} more model(s) outside the built-in list",
|
||||
@@ -262,7 +273,7 @@ window.__ModuleLoader__.load({
|
||||
hostsCooling: "skipped for now",
|
||||
hostsUnprobed: "not measured",
|
||||
hostsEdit: "Edit endpoint list",
|
||||
hostsEditHint: "One endpoint per line, in order of preference. Leave empty to restore the defaults.",
|
||||
hostsEditHint: "One endpoint per line (origin only, https), in order of preference. Use Restore defaults to go back to the built-in list.",
|
||||
hostsSave: "Save",
|
||||
hostsReset: "Restore defaults",
|
||||
composerLabel: "Geek2API remaining balance",
|
||||
@@ -306,7 +317,8 @@ window.__ModuleLoader__.load({
|
||||
versionUpToDate: "Up to date",
|
||||
versionAvailable: "v{version} is available",
|
||||
versionLinked: "Installed from a local checkout. Pull and rebuild the plugin repository instead.",
|
||||
versionManual: "This install cannot be updated here. Reinstall dsh-geek2api from the desktop Plugins page.",
|
||||
versionManual: "This install cannot update itself. Download the new version from GitHub Releases and reinstall it from the Plugins page.",
|
||||
versionNotes: "Release notes",
|
||||
versionUpdate: "Update plugin",
|
||||
versionUpdating: "Updating…",
|
||||
versionUpdateFailed: "The update failed. Try again, or reinstall from the Plugins page.",
|
||||
@@ -381,6 +393,8 @@ window.__ModuleLoader__.load({
|
||||
.pkc-input:focus{border-color:var(--dsw-alias-state-business-primary)}
|
||||
.pkc-input::placeholder{color:var(--dsw-alias-label-caption)}
|
||||
.pkc-input:disabled{opacity:.5}
|
||||
.pkc-link{color:var(--dsw-alias-state-business-primary);font-size:12px;text-decoration:none}
|
||||
.pkc-link:hover{text-decoration:underline}
|
||||
.pkc-textarea{display:block;width:100%;height:auto;min-height:96px;padding:8px 10px;line-height:1.6;resize:vertical;white-space:pre;overflow-x:auto}
|
||||
.pkc-form{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
||||
|
||||
@@ -464,17 +478,21 @@ window.__ModuleLoader__.load({
|
||||
/**
|
||||
* Totals across the keys a balance read returned.
|
||||
*
|
||||
* Keys of one Geek2API account spend the same wallet, so a wallet is counted
|
||||
* once however many of its keys are stored. Two wallet rows are the same
|
||||
* wallet when the gateway names the same account (`accountRef`) or, when it
|
||||
* names none, when they report the same balance to the micro-dollar. Key
|
||||
* quotas and subscriptions are the key's own and add up.
|
||||
* In sub2api money belongs to the account, not the key:
|
||||
* - every wallet key of one account spends the same wallet, counted once —
|
||||
* the same wallet when the gateway names the same account (`accountRef`)
|
||||
* or, when it names none, when the balances agree to the micro-dollar;
|
||||
* - a subscription belongs to the user and its group, so keys on the same
|
||||
* plan count it once;
|
||||
* - a key quota is a cap on top of the wallet, not money of its own, so it
|
||||
* is left out of the sums and reported as `capped`.
|
||||
*
|
||||
* @module dsh-geek2api/totals
|
||||
*/
|
||||
const amount = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
||||
/** Which pool of money a row draws on; rows with the same pool count once. */
|
||||
function poolOf(row, usage) {
|
||||
if (usage.mode === "subscription") return `subscription:${usage.planName ?? row?.id}`;
|
||||
if (usage.mode !== "wallet") return `key:${row?.id}`;
|
||||
if (typeof usage.accountRef === "string") return `account:${usage.accountRef}`;
|
||||
const remaining = amount(usage.availableUsd);
|
||||
@@ -484,8 +502,8 @@ window.__ModuleLoader__.load({
|
||||
* Add up the balance rows the host returned.
|
||||
* @param rows - the `keys` array of a balance projection.
|
||||
* @returns summed amounts plus the conditions that make a sum incomplete:
|
||||
* keys whose read failed, keys with no limit at all, and how many wallet
|
||||
* rows were folded into a wallet already counted.
|
||||
* keys whose read failed, keys with no limit at all, rows folded into a
|
||||
* pool already counted, and key caps left out of the sum.
|
||||
*/
|
||||
function sumBalances(rows) {
|
||||
const total = {
|
||||
@@ -494,6 +512,7 @@ window.__ModuleLoader__.load({
|
||||
unread: 0,
|
||||
unlimited: 0,
|
||||
shared: 0,
|
||||
capped: 0,
|
||||
remainingUsd: 0,
|
||||
usedUsd: 0,
|
||||
limitUsd: 0
|
||||
@@ -507,6 +526,10 @@ window.__ModuleLoader__.load({
|
||||
continue;
|
||||
}
|
||||
total.counted += 1;
|
||||
if (usage.mode === "quota") {
|
||||
total.capped += 1;
|
||||
continue;
|
||||
}
|
||||
const pool = poolOf(row, usage);
|
||||
if (seen.has(pool)) {
|
||||
total.shared += 1;
|
||||
@@ -619,6 +642,7 @@ window.__ModuleLoader__.load({
|
||||
/** What a key draws on: the shared wallet, a subscription plan, or its own quota. */
|
||||
function planLabel(usage, t) {
|
||||
if (usage?.mode === "wallet") return t("planWallet");
|
||||
if (usage?.mode === "subscription" && usage.inactive === true) return fill(t("planSubscriptionInactive"), { name: usage.planName ?? "" });
|
||||
if (usage?.mode === "subscription") return fill(t("planSubscription"), { name: usage.planName ?? "" });
|
||||
if (usage?.mode === "quota") return t("planQuota");
|
||||
}
|
||||
@@ -735,11 +759,12 @@ window.__ModuleLoader__.load({
|
||||
})
|
||||
] });
|
||||
}
|
||||
function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, t }) {
|
||||
function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, skippedUntil, t }) {
|
||||
const usage = row?.usage;
|
||||
const share = remainingShare(usage);
|
||||
const remainingLabel = usage?.mode === "quota" ? t("keyCapRemaining") : t("keyRemaining");
|
||||
const figures = [
|
||||
usage?.unlimitedQuota === true ? [t("keyRemaining"), t("keyUnlimited")] : usage?.availableUsd === void 0 ? void 0 : [t("keyRemaining"), formatUsd(usage.availableUsd)],
|
||||
usage?.unlimitedQuota === true ? [remainingLabel, t("keyUnlimited")] : usage?.availableUsd === void 0 ? void 0 : [remainingLabel, formatUsd(usage.availableUsd)],
|
||||
usage?.usedUsd === void 0 ? void 0 : [t("keyUsed"), formatUsd(usage.usedUsd)],
|
||||
usage?.limitUsd === void 0 ? void 0 : [t("accountLimit"), formatUsd(usage.limitUsd)]
|
||||
].filter(Boolean);
|
||||
@@ -748,7 +773,12 @@ window.__ModuleLoader__.load({
|
||||
usage?.keyName === void 0 ? void 0 : `${t("keyName")} ${usage.keyName}`,
|
||||
resetLabel(usage?.resetPeriod, t),
|
||||
usage?.todayUsd === void 0 ? void 0 : `${t("keyToday")} ${formatUsd(usage.todayUsd)}`,
|
||||
usage?.expiresAt === void 0 ? void 0 : fill(t("keyExpires"), { date: new Date(usage.expiresAt).toLocaleDateString() })
|
||||
usage?.expiresAt === void 0 ? void 0 : fill(t("keyExpires"), { date: new Date(usage.expiresAt).toLocaleDateString() }),
|
||||
...Array.isArray(usage?.rateLimits) ? usage.rateLimits.map((window) => fill(t("keyWindow"), {
|
||||
window: window.window,
|
||||
used: formatUsd(window.usedUsd) ?? "?",
|
||||
limit: formatUsd(window.limitUsd) ?? "?"
|
||||
})) : []
|
||||
].filter(Boolean).join(" · ");
|
||||
const editing = renaming?.id === entry.id;
|
||||
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
||||
@@ -797,6 +827,11 @@ window.__ModuleLoader__.load({
|
||||
"data-tone": "success",
|
||||
children: t("keyActive")
|
||||
}),
|
||||
!entry.disabled && skippedUntil !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
||||
className: "pkc-chip",
|
||||
"data-tone": "warn",
|
||||
children: t("keySkipped")
|
||||
}),
|
||||
entry.disabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
||||
className: "pkc-chip",
|
||||
"data-tone": "danger",
|
||||
@@ -999,10 +1034,11 @@ window.__ModuleLoader__.load({
|
||||
})
|
||||
]
|
||||
}),
|
||||
(totals.unread > 0 || staleCount > 0 || totals.shared > 0) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
(totals.unread > 0 || staleCount > 0 || totals.shared > 0 || totals.capped > 0) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
className: "pkc-note",
|
||||
children: [
|
||||
totals.shared > 0 ? fill(t("totalShared"), { count: totals.shared }) : void 0,
|
||||
totals.capped > 0 ? fill(t("totalCapped"), { count: totals.capped }) : void 0,
|
||||
totals.unread > 0 ? fill(t("totalPartial"), { count: totals.unread }) : void 0,
|
||||
staleCount > 0 ? fill(t("totalStale"), { count: staleCount }) : void 0
|
||||
].filter(Boolean).join(" ")
|
||||
@@ -1019,6 +1055,7 @@ window.__ModuleLoader__.load({
|
||||
renaming,
|
||||
onRename: rename,
|
||||
onAction: mutate,
|
||||
skippedUntil: status?.skipped?.[entry.id],
|
||||
t
|
||||
}, entry.id))
|
||||
}),
|
||||
@@ -1085,16 +1122,33 @@ window.__ModuleLoader__.load({
|
||||
const [busy, setBusy] = react.useState(false);
|
||||
const [error, setError] = react.useState();
|
||||
const [draft, setDraft] = react.useState();
|
||||
const [editing, setEditing] = react.useState(false);
|
||||
const run = react.useCallback((endpoint, payload) => {
|
||||
setBusy(true);
|
||||
setError(void 0);
|
||||
return call(endpoint, payload).then(setStatus).catch((failure) => setError(clearMessage(failure))).finally(() => setBusy(false));
|
||||
return call(endpoint, payload).then((next) => {
|
||||
setStatus(next);
|
||||
return next;
|
||||
}).catch((failure) => {
|
||||
setError(clearMessage(failure));
|
||||
}).finally(() => setBusy(false));
|
||||
}, [call]);
|
||||
react.useEffect(() => {
|
||||
run("hosts/probe", {});
|
||||
}, [run]);
|
||||
const hosts = Array.isArray(status?.hosts) ? status.hosts : [];
|
||||
const save = (list) => run("hosts/update", { apiHosts: list }).then(() => setDraft(void 0));
|
||||
const listText = (list) => Array.isArray(list) ? list.map((entry) => entry.host).join("\n") : "";
|
||||
react.useEffect(() => {
|
||||
if (editing && draft === void 0 && hosts.length > 0) setDraft(listText(hosts));
|
||||
}, [
|
||||
editing,
|
||||
draft,
|
||||
hosts
|
||||
]);
|
||||
const save = (list) => run("hosts/update", { apiHosts: list }).then((next) => {
|
||||
if (next !== void 0) setDraft(listText(next.hosts));
|
||||
});
|
||||
const draftHosts = (draft ?? "").split(/\s+/u).filter(Boolean);
|
||||
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
|
||||
title: t("hostsTitle"),
|
||||
aside: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
|
||||
@@ -1127,14 +1181,14 @@ window.__ModuleLoader__.load({
|
||||
}),
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
||||
className: "pkc-meta",
|
||||
children: entry.coolingUntil !== void 0 ? t("hostsCooling") : entry.latencyMs !== void 0 ? `${entry.latencyMs} ms` : t("hostsDown")
|
||||
children: entry.coolingUntil !== void 0 ? t("hostsCooling") : entry.latencyMs !== void 0 ? `${entry.latencyMs} ms` : entry.probed === false ? t("hostsUnprobed") : t("hostsDown")
|
||||
})
|
||||
]
|
||||
}, entry.host))
|
||||
}),
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", {
|
||||
className: "pkc-advanced",
|
||||
onToggle: (event) => event.currentTarget.open && draft === void 0 && setDraft(hosts.map((entry) => entry.host).join("\n")),
|
||||
onToggle: (event) => setEditing(event.currentTarget.open),
|
||||
children: [
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", { children: t("hostsEdit") }),
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
@@ -1152,8 +1206,8 @@ window.__ModuleLoader__.load({
|
||||
className: "pkc-split",
|
||||
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
|
||||
variant: "primary",
|
||||
disabled: status?.writable !== true || busy,
|
||||
onClick: () => save((draft ?? "").split(/\s+/u).filter(Boolean)),
|
||||
disabled: status?.writable !== true || busy || draftHosts.length === 0,
|
||||
onClick: () => save(draftHosts),
|
||||
children: t("hostsSave")
|
||||
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
|
||||
variant: "ghost",
|
||||
@@ -1657,7 +1711,7 @@ window.__ModuleLoader__.load({
|
||||
};
|
||||
const installKind = info?.install?.kind;
|
||||
const showStatus = info !== void 0 && updated === void 0;
|
||||
const canUpdate = showStatus && info.updateAvailable && installKind === "npm";
|
||||
const canUpdate = showStatus && info.updateAvailable && (info.updatable === true || info.updatable === void 0 && installKind === "npm");
|
||||
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
|
||||
title: t("versionTitle"),
|
||||
aside: updated === void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
|
||||
@@ -1696,6 +1750,13 @@ window.__ModuleLoader__.load({
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
|
||||
className: "pkc-meta",
|
||||
children: [info.updateAvailable ? fill(t("versionAvailable"), { version: info.latest }) : t("versionUpToDate"), info.updateAvailable && ` · ${t("versionLatest")} v${info.latest}`]
|
||||
}),
|
||||
info.releaseUrl !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
|
||||
className: "pkc-link",
|
||||
href: info.releaseUrl,
|
||||
target: "_blank",
|
||||
rel: "noreferrer noopener",
|
||||
children: t("versionNotes")
|
||||
})
|
||||
]
|
||||
}),
|
||||
@@ -1703,7 +1764,7 @@ window.__ModuleLoader__.load({
|
||||
className: "pkc-note",
|
||||
children: t("versionLinked")
|
||||
}),
|
||||
showStatus && info.updateAvailable && installKind === "unknown" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
showStatus && info.updateAvailable && !canUpdate && installKind !== "link" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
className: "pkc-note",
|
||||
children: t("versionManual")
|
||||
}),
|
||||
|
||||
+236
-106
@@ -306,14 +306,15 @@ function parseKeyUsage(payload) {
|
||||
if (payload.mode === "quota_limited") {
|
||||
const quota = record$3(payload.quota) ? payload.quota : void 0;
|
||||
const expiresAt = timestamp(payload.expires_at);
|
||||
const rateLimits = parseRateLimits(payload.rate_limits);
|
||||
return defined({
|
||||
...common,
|
||||
mode: "quota",
|
||||
unlimitedQuota: quota === void 0,
|
||||
unlimitedQuota: quota === void 0 && rateLimits === void 0,
|
||||
limitUsd: usd(quota?.limit),
|
||||
usedUsd: usd(quota?.used),
|
||||
availableUsd: usd(quota?.remaining ?? payload.remaining),
|
||||
rateLimits: parseRateLimits(payload.rate_limits),
|
||||
rateLimits,
|
||||
expiresAt
|
||||
});
|
||||
}
|
||||
@@ -330,7 +331,14 @@ function parseKeyUsage(payload) {
|
||||
expiresAt: timestamp(payload.subscription.expires_at)
|
||||
});
|
||||
}
|
||||
if (payload.mode === "unrestricted" && record$3(payload) && (payload.balance !== void 0 || payload.remaining !== void 0)) return defined({
|
||||
if (payload.mode === "unrestricted" && payload.balance === void 0 && payload.remaining === void 0 && common.planName !== void 0) return defined({
|
||||
...common,
|
||||
mode: "subscription",
|
||||
inactive: true,
|
||||
unlimitedQuota: false,
|
||||
availableUsd: 0
|
||||
});
|
||||
if (payload.mode === "unrestricted" && (payload.balance !== void 0 || payload.remaining !== void 0)) return defined({
|
||||
...common,
|
||||
mode: "wallet",
|
||||
unlimitedQuota: false,
|
||||
@@ -354,7 +362,7 @@ function statusMessage(status) {
|
||||
* @param options - key listing, the host pool, and transport knobs.
|
||||
* @returns `{ read({force, signal}), invalidate() }`.
|
||||
*/
|
||||
function createBalanceReader({ listKeys, hosts, fetchImpl = ambientFetch, now = Date.now, ttlMs = DEFAULT_BALANCE_TTL_MS, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS } = {}) {
|
||||
function createBalanceReader({ listKeys, hosts, fetchImpl = ambientFetch, now = Date.now, ttlMs = DEFAULT_BALANCE_TTL_MS, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, onRead } = {}) {
|
||||
if (typeof listKeys !== "function") throw new Error("Geek2API balance reader requires listKeys");
|
||||
if (typeof hosts?.withFailover !== "function") throw new Error("Geek2API balance reader requires a host pool");
|
||||
/** Last successful per-key usage, by key id. */
|
||||
@@ -386,40 +394,44 @@ function createBalanceReader({ listKeys, hosts, fetchImpl = ambientFetch, now =
|
||||
signal?.throwIfAborted();
|
||||
const keys = await listKeys();
|
||||
for (const id of lastGood.keys()) if (!keys.some((entry) => entry.id === id)) lastGood.delete(id);
|
||||
return {
|
||||
keys: await Promise.all(keys.map(async (entry) => {
|
||||
const base = {
|
||||
id: entry.id,
|
||||
label: entry.label,
|
||||
disabled: entry.disabled === true
|
||||
const entries = await Promise.all(keys.map(async (entry) => {
|
||||
const base = {
|
||||
id: entry.id,
|
||||
label: entry.label,
|
||||
disabled: entry.disabled === true
|
||||
};
|
||||
try {
|
||||
const usage = await loadKey(entry, signal);
|
||||
lastGood.set(entry.id, {
|
||||
usage,
|
||||
fetchedAt: now()
|
||||
});
|
||||
return {
|
||||
...base,
|
||||
usage
|
||||
};
|
||||
try {
|
||||
const usage = await loadKey(entry, signal);
|
||||
lastGood.set(entry.id, {
|
||||
usage,
|
||||
fetchedAt: now()
|
||||
});
|
||||
return {
|
||||
...base,
|
||||
usage
|
||||
};
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const previous = lastGood.get(entry.id);
|
||||
return previous === void 0 ? {
|
||||
...base,
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const previous = lastGood.get(entry.id);
|
||||
return previous === void 0 ? {
|
||||
...base,
|
||||
error: message
|
||||
} : {
|
||||
...base,
|
||||
usage: previous.usage,
|
||||
stale: {
|
||||
fetchedAt: previous.fetchedAt,
|
||||
error: message
|
||||
} : {
|
||||
...base,
|
||||
usage: previous.usage,
|
||||
stale: {
|
||||
fetchedAt: previous.fetchedAt,
|
||||
error: message
|
||||
}
|
||||
};
|
||||
}
|
||||
})),
|
||||
}
|
||||
};
|
||||
}
|
||||
}));
|
||||
try {
|
||||
onRead?.(entries);
|
||||
} catch {}
|
||||
return {
|
||||
keys: entries,
|
||||
hosts: hosts.status(),
|
||||
fetchedAt: now()
|
||||
};
|
||||
@@ -688,7 +700,7 @@ function modelForHost(catalogModel, host) {
|
||||
//#endregion
|
||||
//#region src/failures.js
|
||||
/**
|
||||
* Failure classification for the two conditions that move the key ring along.
|
||||
* Failure classification for the conditions that move the key ring along.
|
||||
*
|
||||
* The gateway reports an exhausted key and a rejected key in Chinese, and the
|
||||
* harness classifies failures by fixed English/status wording it recognizes
|
||||
@@ -700,24 +712,39 @@ function modelForHost(catalogModel, host) {
|
||||
*
|
||||
* @module dsh-geek2api/failures
|
||||
*/
|
||||
/** Terminal quota, balance, or credit wording, in the gateway's own languages. */
|
||||
const QUOTA_WORDING = /额度|余额|配额|欠费|insufficient[\s_-]+(?:quota|balance|credits?)|quota[\s_-]+(?:exceeded|exhausted|reached)|out[\s_-]+of[\s_-]+(?:credits?|budget)|no active subscription|INSUFFICIENT_BALANCE/iu;
|
||||
/** A rejected key names itself; a bare 403 does not, and must not disable one. */
|
||||
const INVALID_KEY_WORDING = /无效的令牌|令牌无效|无效密钥|密钥无效|invalid[\s_-]+api[\s_-]*key|invalid_authentication|api key is invalid|api key is disabled|api key\s*已过期|API_KEY_(?:DISABLED|EXPIRED)|user account is not active|所属分组已删除|所属专属分组不再允许|GROUP_NOT_ALLOWED/iu;
|
||||
const INVALID_KEY_STATUS = /\b401\b/;
|
||||
/**
|
||||
* A gateway group that only serves its vendor's official client. These arrive
|
||||
* as 403, which the harness reads as an authentication failure and renders as
|
||||
* The key itself is gone for good: sub2api's own refusals of the credential
|
||||
* (`INVALID_API_KEY`, `API_KEY_DISABLED`, an expired key, an inactive user, a
|
||||
* deleted or withdrawn group). Only the gateway's own wording counts; a bare
|
||||
* 401 may be an upstream account's error passed through, and must not retire
|
||||
* the user's key.
|
||||
*/
|
||||
const INVALID_KEY_WORDING = /invalid api key|INVALID_API_KEY|api key is disabled|API_KEY_DISABLED|api key\s*已过期|API_KEY_EXPIRED|user account is not active|USER_INACTIVE|user associated with api key not found|所属分组已删除|所属专属分组不再允许|GROUP_NOT_ALLOWED/iu;
|
||||
/**
|
||||
* The key's own spending cap is used up (`API key 额度已用完`). It stays used up
|
||||
* until someone raises the cap, so the key is moved aside until re-enabled.
|
||||
*/
|
||||
const KEY_QUOTA_WORDING = /api key\s*额度已用完|api key quota exhausted|API_KEY_QUOTA_EXHAUSTED/iu;
|
||||
/**
|
||||
* Money that comes back on its own or with a top-up: the account wallet
|
||||
* (shared by every key of the account), a subscription window, a key's
|
||||
* 5h/1d/7d window, or a per-platform daily quota. The key is skipped for a
|
||||
* while, never retired: recharging must not leave keys disabled by hand.
|
||||
*/
|
||||
const EXHAUSTED_WORDING = /余额不足,?请充值|INSUFFICIENT_BALANCE|no active subscription|SUBSCRIPTION_NOT_FOUND|(?:daily|weekly|monthly) usage limit exceeded|限额已用完|usage quota exhausted for this platform/iu;
|
||||
/**
|
||||
* A group that only serves its vendor's official client. These arrive as
|
||||
* 403, which the harness reads as an authentication failure and renders as
|
||||
* an invalid-API-key problem — the opposite of what happened, and a condition
|
||||
* no retry can clear.
|
||||
*/
|
||||
const CLIENT_POLICY_WORDING = /only accessible via the official|only accepts requests from the official|official\s+claude(?:\s+code)?\s+cli|官方\s*claude(?:\s*code)?\s*cli|请使用标准\s*codex\s*客户端|客户端存在异常|二次分发|API\s*转接/iu;
|
||||
const CLIENT_POLICY_WORDING = /only accessible via the official|only accepts requests from the official|official\s+claude(?:\s+code)?\s+cli|官方\s*claude(?:\s*code)?\s*cli/iu;
|
||||
/**
|
||||
* The gateway's answer when a key's groups do not include the model's
|
||||
* supplier: `model_not_found` / 当前令牌未覆盖供应商. The key is fine for other
|
||||
* models, so it is never moved aside for this.
|
||||
* The gateway's answer when the key's group does not serve the model. The key
|
||||
* is fine for other models, so it is never moved aside for this. (`No
|
||||
* available accounts` is not here: sub2api says that when a pool is busy.)
|
||||
*/
|
||||
const COVERAGE_WORDING = /model_not_found|未覆盖供应商|无可用渠道|no available channel|model is not allowed|model is not supported|is not supported by any configured account|no available accounts|is not available\. use get \/v1\/models/iu;
|
||||
const COVERAGE_WORDING = /model is not allowed|model is not supported|is not supported by any configured account|is not available\. use get \/v1\/models/iu;
|
||||
/**
|
||||
* Whether the gateway refused the model for this key's groups.
|
||||
* @param message - the failure text.
|
||||
@@ -726,8 +753,10 @@ const COVERAGE_WORDING = /model_not_found|未覆盖供应商|无可用渠道|no
|
||||
function classifyCoverage(message) {
|
||||
return COVERAGE_WORDING.test(typeof message === "string" ? message : "");
|
||||
}
|
||||
/** The key's quota is exhausted; move to the next key. */
|
||||
/** The key's own cap is used up; move to the next key until re-enabled. */
|
||||
const QUOTA_FAILURE = "quota";
|
||||
/** Wallet, subscription, or window exhausted; skip the key for a while. */
|
||||
const EXHAUSTED_FAILURE = "exhausted";
|
||||
/** The gateway rejected the key itself; move to the next key. */
|
||||
const INVALID_KEY_FAILURE = "invalid-key";
|
||||
/**
|
||||
@@ -739,11 +768,7 @@ function classifyClientPolicy(message) {
|
||||
return CLIENT_POLICY_WORDING.test(typeof message === "string" ? message : "");
|
||||
}
|
||||
/**
|
||||
* Classify a gateway failure message.
|
||||
*
|
||||
* Quota wording wins over a status token: an exhausted balance is often
|
||||
* reported as 402/403, and only the key's own rejection may read as 401. A
|
||||
* client-policy refusal is not a key fault and is classified separately.
|
||||
* Classify a gateway failure message by sub2api's own wording.
|
||||
* @param message - provider failure text, as pi-ai carries it.
|
||||
* @returns the failure kind, or undefined when the key is not at fault.
|
||||
*/
|
||||
@@ -751,9 +776,9 @@ function classifyGatewayFailure(message) {
|
||||
const text = typeof message === "string" ? message : "";
|
||||
if (text === "") return void 0;
|
||||
if (classifyClientPolicy(text)) return void 0;
|
||||
if (QUOTA_WORDING.test(text)) return QUOTA_FAILURE;
|
||||
if (INVALID_KEY_WORDING.test(text)) return INVALID_KEY_FAILURE;
|
||||
if (INVALID_KEY_STATUS.test(text)) return INVALID_KEY_FAILURE;
|
||||
if (KEY_QUOTA_WORDING.test(text)) return QUOTA_FAILURE;
|
||||
if (EXHAUSTED_WORDING.test(text)) return EXHAUSTED_FAILURE;
|
||||
}
|
||||
/**
|
||||
* Explain that no stored key can use the requested model.
|
||||
@@ -788,7 +813,7 @@ function explainClientPolicyFailure() {
|
||||
* per-account wait queue is full, or it throttled or shed the request. The
|
||||
* CLI retries these on its own; this matches what is left when it gave up.
|
||||
*/
|
||||
const CAPACITY_WORDING = /concurrency_queue_full|并发排队已满|wait queues? (?:are|is) full|负载已饱和|overloaded|rate[_\s-]?limit|API Error:\s*(?:429|502|503|504|529)\b/iu;
|
||||
const CAPACITY_WORDING = /no available accounts|concurrency limit exceeded|concurrency_queue_full|并发排队已满|wait queues? (?:are|is) full|负载已饱和|overloaded|rate[_\s-]?limit|API Error:\s*(?:429|502|503|504|529)\b/iu;
|
||||
/**
|
||||
* Whether a CLI failure is the gateway being busy rather than a fault of the
|
||||
* key, the client, or the request.
|
||||
@@ -853,7 +878,7 @@ function explainCliGroupFailure(key, message) {
|
||||
function normalizeFailureMessage(message, kind, options = {}) {
|
||||
const text = typeof message === "string" && message.length > 0 ? message : "Geek2API request failed";
|
||||
if (kind === "client-policy") return explainClientPolicyFailure(options.keyName);
|
||||
if (kind === "quota") return `${neutralizeAuthStatus(text)} — Geek2API: insufficient quota for this API key; trying the next key`;
|
||||
if (kind === "quota" || kind === "exhausted") return `${neutralizeAuthStatus(text)} — Geek2API: insufficient quota for this API key; trying the next key`;
|
||||
if (kind === "invalid-key") return `${neutralizeAuthStatus(text)} — Geek2API: 401 invalid_authentication for this API key; trying the next key`;
|
||||
return text;
|
||||
}
|
||||
@@ -865,9 +890,10 @@ function neutralizeAuthStatus(text) {
|
||||
/**
|
||||
* Route Claude models through the local Claude Code CLI.
|
||||
*
|
||||
* Geek2API's `cc` group serves its Claude models only to the official CLI, so
|
||||
* selecting one of those models runs that CLI instead of an HTTP request. The
|
||||
* other models on the route keep using the pi-ai adapter untouched — this
|
||||
* When the Claude runtime setting is `cli`, selecting a Claude model runs the
|
||||
* local Claude Code CLI instead of an HTTP request (useful when a key's group
|
||||
* only serves the official CLI). Every other model, and every Claude model on
|
||||
* the default `http` runtime, keeps using the pi-ai adapter untouched — this
|
||||
* adapter only dispatches.
|
||||
*
|
||||
* A CLI-backed turn is a *delegation*: the CLI runs its own agent loop with
|
||||
@@ -897,7 +923,7 @@ const TITLE_MODEL_ID = "claude-haiku-4-5-20251001";
|
||||
/**
|
||||
* HTTP models whose session titles run on another model of the same route.
|
||||
* A title is a few words, so the flagship `gpt-6-astra` hands it to
|
||||
* `gpt-6.1-sol`, which the same Codex group serves; the session's own turns
|
||||
* `gpt-6.1-sol`, which the same GPT groups serve; the session's own turns
|
||||
* are untouched.
|
||||
*/
|
||||
const TITLE_MODEL_ROUTES = Object.freeze({ "gpt-6-astra": "gpt-6.1-sol" });
|
||||
@@ -1878,8 +1904,8 @@ function createDeltaRedactor(values) {
|
||||
/**
|
||||
* Bridge to the local Claude Code CLI.
|
||||
*
|
||||
* The gateway's `cc` group serves its Claude models only to the official CLI,
|
||||
* so this module runs that CLI — the real binary, not an imitation of it — as
|
||||
* On the `cli` Claude runtime (and for the `claude_code` tool) this module runs
|
||||
* the official CLI — the real binary, not an imitation of it — as
|
||||
* a subprocess and hands its final answer back to the harness. The child gets
|
||||
* the plugin's own endpoint and key through the environment, plus an isolated
|
||||
* `CLAUDE_CONFIG_DIR`: `~/.claude/settings.json` env wins over an inherited
|
||||
@@ -4456,7 +4482,16 @@ function pickKeyForModel(modelId, active, usable, covers) {
|
||||
*
|
||||
* @module dsh-geek2api/hosts
|
||||
*/
|
||||
/** Accept an absolute http(s) origin and drop a trailing slash. */
|
||||
const LOOPBACK = /* @__PURE__ */ new Set([
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
"[::1]"
|
||||
]);
|
||||
/**
|
||||
* Accept an https origin, keeping only the origin: a pasted `/v1` (the base
|
||||
* URL OpenAI clients use) would otherwise double every path. Plain http is
|
||||
* refused outside loopback, because the key travels in a header.
|
||||
*/
|
||||
function normalizeHost(value, fallback) {
|
||||
const text = typeof value === "string" ? value.trim() : "";
|
||||
if (text === "") return fallback;
|
||||
@@ -4466,8 +4501,9 @@ function normalizeHost(value, fallback) {
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") return fallback;
|
||||
return `${url.origin}${url.pathname.replace(/\/+$/u, "")}`;
|
||||
if (url.protocol === "https:") return url.origin;
|
||||
if (url.protocol === "http:" && LOOPBACK.has(url.hostname)) return url.origin;
|
||||
return fallback;
|
||||
}
|
||||
/**
|
||||
* Normalize a host list: valid origins only, no duplicates, configured order
|
||||
@@ -4480,10 +4516,16 @@ function normalizeHostList(value) {
|
||||
const hosts = [...new Set(raw.map((item) => normalizeHost(item, void 0)).filter((host) => host !== void 0))];
|
||||
return hosts.length === 0 ? [...DEFAULT_API_HOSTS] : hosts;
|
||||
}
|
||||
/** Whether a failure means the host never answered. */
|
||||
/**
|
||||
* Whether a failure means the host never answered. A timeout is not: the
|
||||
* host accepted the connection and the gateway behind it is slow, which every
|
||||
* host would be. Text that carries an HTTP status is the gateway's answer,
|
||||
* whatever words it uses.
|
||||
*/
|
||||
function isTransportFailure(error) {
|
||||
if (error instanceof TransportError) return error.aborted !== true;
|
||||
if (error instanceof TransportError) return error.aborted !== true && error.timedOut !== true;
|
||||
const text = error instanceof Error ? error.message : typeof error === "string" ? error : "";
|
||||
if (/^\s*\d{3}\b|\(\d{3}\)|status code \d{3}|HTTP \d{3}/u.test(text)) return false;
|
||||
return /fetch failed|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|UND_ERR_|socket hang up|network error|other side closed|certificate|TLS|connect timeout|Connection error|ConnectTimeout|getaddrinfo/iu.test(text);
|
||||
}
|
||||
/**
|
||||
@@ -4597,6 +4639,7 @@ function createHostPool({ listHosts = () => DEFAULT_API_HOSTS, fetchImpl = ambie
|
||||
return configured().map((host) => ({
|
||||
host,
|
||||
current: host === best,
|
||||
probed: probedAt !== 0,
|
||||
...latency.has(host) ? { latencyMs: latency.get(host) } : {},
|
||||
...isCooling(host) ? { coolingUntil: cooling.get(host) } : {}
|
||||
}));
|
||||
@@ -4630,11 +4673,26 @@ function createHostPool({ listHosts = () => DEFAULT_API_HOSTS, fetchImpl = ambie
|
||||
/** How long a request with a choice of keys waits for the first group reading. */
|
||||
const DEFAULT_GROUP_WAIT_MS = 6e3;
|
||||
/**
|
||||
* How long a key whose money ran out (wallet, subscription, or window) is
|
||||
* skipped. It is never disabled for that: a top-up or a new window brings it
|
||||
* back, and a balance read showing money brings it back at once.
|
||||
*/
|
||||
const EXHAUSTED_SKIP_MS = 10 * 6e4;
|
||||
/**
|
||||
* @param options - the key ring, the group reader, what to do after a key
|
||||
* moved aside, a logger, and how long to wait for the first group reading.
|
||||
* @returns the chooser.
|
||||
*/
|
||||
function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GROUP_WAIT_MS }) {
|
||||
function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GROUP_WAIT_MS, skipMs = EXHAUSTED_SKIP_MS, now = Date.now }) {
|
||||
/** key id → epoch ms until which the key is skipped (in memory only). */
|
||||
const skipped = /* @__PURE__ */ new Map();
|
||||
const isSkipped = (id) => {
|
||||
const until = skipped.get(id);
|
||||
if (until === void 0) return false;
|
||||
if (until > now()) return true;
|
||||
skipped.delete(id);
|
||||
return false;
|
||||
};
|
||||
/**
|
||||
* Key material to ring id. A failure is reported from inside a stream, which
|
||||
* carries the request's key but not its id; this index is refreshed on every
|
||||
@@ -4648,7 +4706,7 @@ function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GR
|
||||
snapshot = entries;
|
||||
for (const entry of entries) idByKey.set(entry.key, entry.id);
|
||||
};
|
||||
const usable = () => snapshot.filter((entry) => entry.disabled !== true);
|
||||
const usable = () => snapshot.filter((entry) => entry.disabled !== true && !isSkipped(entry.id));
|
||||
const covers = (keyId, modelId) => groups.covers(keyId, modelId);
|
||||
/**
|
||||
* Keep the group reading fresh for the choice. It only matters with two
|
||||
@@ -4665,10 +4723,24 @@ function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GR
|
||||
})]);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
/** The active key, after refreshing the ring and, when it matters, the groups. */
|
||||
/**
|
||||
* The active key, after refreshing the ring and, when it matters, the
|
||||
* groups. A skipped active key hands over to the next usable one in ring
|
||||
* order; with none left, the active key is returned so the failure speaks.
|
||||
*/
|
||||
const active = async () => {
|
||||
await remember();
|
||||
const key = await ring.activeKey();
|
||||
let key = await ring.activeKey();
|
||||
if (key !== void 0 && isSkipped(key.id)) {
|
||||
const start = snapshot.findIndex((entry) => entry.id === key.id);
|
||||
const next = (start < 0 ? snapshot : [...snapshot.slice(start + 1), ...snapshot.slice(0, start)]).find((entry) => entry.disabled !== true && !isSkipped(entry.id));
|
||||
if (next !== void 0) key = {
|
||||
...key,
|
||||
id: next.id,
|
||||
label: next.label,
|
||||
key: next.key
|
||||
};
|
||||
}
|
||||
if (key !== void 0) await warm();
|
||||
return key;
|
||||
};
|
||||
@@ -4676,6 +4748,21 @@ function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GR
|
||||
remember,
|
||||
covers,
|
||||
active,
|
||||
/** Key ids skipped for running out of money, with when the skip ends. */
|
||||
skipped() {
|
||||
return Object.fromEntries([...skipped.keys()].filter(isSkipped).map((id) => [id, skipped.get(id)]));
|
||||
},
|
||||
/**
|
||||
* A balance read is fresher evidence than a failure: a skipped key that
|
||||
* now shows money is usable again.
|
||||
* @param rows - the `keys` of a balance projection.
|
||||
*/
|
||||
noteBalances(rows) {
|
||||
for (const row of Array.isArray(rows) ? rows : []) {
|
||||
const available = row?.usage?.availableUsd;
|
||||
if (row?.stale === void 0 && typeof available === "number" && available > 0) skipped.delete(row.id);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* The key one HTTP request for `modelId` runs with, given the active key
|
||||
* pi-ai resolved. Synchronous because pi-ai opens its stream synchronously;
|
||||
@@ -4741,6 +4828,12 @@ function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GR
|
||||
logger?.warn?.("geek2api: %s reported for an unidentified key; not rotating", kind);
|
||||
return;
|
||||
}
|
||||
if (kind === "exhausted") {
|
||||
skipped.set(id, now() + skipMs);
|
||||
logger?.warn?.("geek2api: key %s has no money left for now; skipping it for a while", id);
|
||||
onRotated?.();
|
||||
return;
|
||||
}
|
||||
logger?.warn?.("geek2api: %s on key %s; the next key serves the retry", kind, id);
|
||||
ring.disable(id, kind).then(() => onRotated?.()).catch((error) => logger?.warn?.("geek2api: could not move past key %s: %s", id, error.message));
|
||||
}
|
||||
@@ -4997,8 +5090,8 @@ var Geek2APIKeyRing = class {
|
||||
* - DSH 0.2 has no sections: a preference is a *volatile* Config field of the
|
||||
* plugin's own row, read through a live reference, written through
|
||||
* `settings.update(rowId, patch)`, and announced by `loader/volatile-update`.
|
||||
* Only volatile fields are writable there, so the host overrides stay
|
||||
* read-only while web search and model visibility are editable.
|
||||
* Only volatile fields are writable there; the endpoint list, Claude
|
||||
* runtime, web search, and model visibility are all volatile.
|
||||
*
|
||||
* @module dsh-geek2api/preferences
|
||||
*/
|
||||
@@ -5120,15 +5213,19 @@ function createModelSelectionController({ readPreference, writePreference, isWri
|
||||
* Version self-knowledge for the settings panel.
|
||||
*
|
||||
* The running version comes from this package. The latest version comes from
|
||||
* the npm registry. An in-place update is only offered for a registry install,
|
||||
* and it installs that exact version with the host's own pnpm — never through
|
||||
* `dsh plugin --profile desktop`, which the desktop app refuses. Registry
|
||||
* bodies and package-manager output stay host-side.
|
||||
* the GitHub releases of this repository: the newest non-draft release names
|
||||
* the version in its tag and carries the packed tarball as an asset. An
|
||||
* in-place update is offered for an install from a release tarball (or the
|
||||
* npm registry), and it installs that exact tarball with the host's own pnpm
|
||||
* — never through `dsh plugin --profile desktop`, which the desktop app
|
||||
* refuses. Release bodies and package-manager output stay host-side.
|
||||
*
|
||||
* @module dsh-geek2api/plugin-version
|
||||
*/
|
||||
const PACKAGE_NAME = "dsh-geek2api";
|
||||
const NPM_REGISTRY_LATEST_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;
|
||||
const GITHUB_LATEST_RELEASE_URL = `https://api.github.com/repos/CoderKuo/dsh-geek2api/releases/latest`;
|
||||
/** The tarball asset a release must carry for an in-place update. */
|
||||
const releaseAssetName = (version) => `${PACKAGE_NAME}-${version}.tgz`;
|
||||
const DEFAULT_VERSION_TTL_MS = 5 * 6e4;
|
||||
const DEFAULT_VERSION_TIMEOUT_MS = 1e4;
|
||||
const DEFAULT_UPDATE_TIMEOUT_MS = 18e4;
|
||||
@@ -5160,15 +5257,37 @@ function compareSemver(a, b) {
|
||||
return left.pre < right.pre ? -1 : 1;
|
||||
}
|
||||
/**
|
||||
* Classify how the running package reached the profile. Only registry specs
|
||||
* may be updated in place; local checkouts belong to the owner's iteration.
|
||||
* Classify how the running package reached the profile. Registry specs and
|
||||
* packed tarballs (a release download, or a local `.tgz`) may be updated in
|
||||
* place; local checkouts belong to the owner's iteration.
|
||||
*/
|
||||
function classifySpec(spec) {
|
||||
if (typeof spec !== "string" || spec === "") return "unknown";
|
||||
if (/\.tgz(?:[?#].*)?$/iu.test(spec) && /^(?:https:\/\/|file:)/iu.test(spec)) return "release";
|
||||
if (/^(?:link|file):/u.test(spec)) return "link";
|
||||
if (/^(?:\d|[~^*])/u.test(spec)) return "npm";
|
||||
return "unknown";
|
||||
}
|
||||
/** Install kinds the panel may update in place. */
|
||||
const UPDATABLE_KINDS = Object.freeze(["npm", "release"]);
|
||||
/**
|
||||
* Normalize a GitHub "latest release" body.
|
||||
* @param payload - the API body.
|
||||
* @returns `{ version, tarballUrl, releaseUrl }`, or undefined when unusable.
|
||||
*/
|
||||
function parseLatestRelease(payload) {
|
||||
if (payload === null || typeof payload !== "object" || payload.draft === true || payload.prerelease === true) return void 0;
|
||||
const version = typeof payload.tag_name === "string" ? payload.tag_name.replace(/^v/u, "") : void 0;
|
||||
if (parseSemver(version) === void 0) return void 0;
|
||||
const asset = Array.isArray(payload.assets) ? payload.assets.find((item) => item?.name === releaseAssetName(version) && typeof item.browser_download_url === "string") : void 0;
|
||||
const tarballUrl = asset !== void 0 && /^https:\/\/github\.com\//u.test(asset.browser_download_url) ? asset.browser_download_url : void 0;
|
||||
const releaseUrl = typeof payload.html_url === "string" && /^https:\/\/github\.com\//u.test(payload.html_url) ? payload.html_url : void 0;
|
||||
return {
|
||||
version,
|
||||
...tarballUrl === void 0 ? {} : { tarballUrl },
|
||||
...releaseUrl === void 0 ? {} : { releaseUrl }
|
||||
};
|
||||
}
|
||||
const readManifest = async (path) => {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(path, "utf8"));
|
||||
@@ -5325,7 +5444,7 @@ function spawnRunCommand({ command, args, cwd }, { signal, timeoutMs }) {
|
||||
* The running version, the latest registry version, which profile installed
|
||||
* this copy, and registry-spec updates against that profile.
|
||||
*/
|
||||
function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = spawnRunCommand, execPath = process.execPath, argv = process.argv, env = process.env, ownPackageJsonUrl = new URL("../package.json", import.meta.url), registryUrl = NPM_REGISTRY_LATEST_URL, now = Date.now, ttlMs = DEFAULT_VERSION_TTL_MS, timeoutMs = DEFAULT_VERSION_TIMEOUT_MS, updateTimeoutMs = DEFAULT_UPDATE_TIMEOUT_MS, settleDelayMs = 250 } = {}) {
|
||||
function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = spawnRunCommand, execPath = process.execPath, argv = process.argv, env = process.env, ownPackageJsonUrl = new URL("../package.json", import.meta.url), releaseUrl = GITHUB_LATEST_RELEASE_URL, now = Date.now, ttlMs = DEFAULT_VERSION_TTL_MS, timeoutMs = DEFAULT_VERSION_TIMEOUT_MS, updateTimeoutMs = DEFAULT_UPDATE_TIMEOUT_MS, settleDelayMs = 250 } = {}) {
|
||||
if (typeof fetchImpl !== "function") throw new Error("Geek2API plugin manager requires fetch");
|
||||
if (typeof runCommand !== "function") throw new Error("Geek2API plugin manager requires runCommand");
|
||||
const dshHome = typeof env.DSH_HOME === "string" && env.DSH_HOME !== "" ? env.DSH_HOME : join(homedir(), ".dsh");
|
||||
@@ -5334,10 +5453,15 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
execPath
|
||||
});
|
||||
let updating = false;
|
||||
/** The newest release: its version, tarball asset, and page. */
|
||||
const fetchLatest = async (signal) => {
|
||||
let response;
|
||||
try {
|
||||
response = await boundedFetch(registryUrl, { headers: { Accept: "application/json" } }, {
|
||||
response = await boundedFetch(releaseUrl, { headers: {
|
||||
Accept: "application/vnd.github+json",
|
||||
"User-Agent": PACKAGE_NAME,
|
||||
"X-GitHub-Api-Version": "2022-11-28"
|
||||
} }, {
|
||||
fetchImpl,
|
||||
timeoutMs,
|
||||
signal
|
||||
@@ -5347,14 +5471,14 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
throw new Error("Geek2API plugin version check failed");
|
||||
}
|
||||
if (!response.ok) throw new Error("Geek2API plugin version check failed");
|
||||
let version;
|
||||
let release;
|
||||
try {
|
||||
version = (await response.json())?.version;
|
||||
release = parseLatestRelease(await response.json());
|
||||
} catch {
|
||||
version = void 0;
|
||||
release = void 0;
|
||||
}
|
||||
if (parseSemver(version) === void 0) throw new Error("Geek2API plugin version check failed");
|
||||
return version;
|
||||
if (release === void 0) throw new Error("Geek2API plugin version check failed");
|
||||
return release;
|
||||
};
|
||||
const readOwnVersion = async () => {
|
||||
const version = (await readManifest(fileURLToPath(ownPackageJsonUrl)))?.version;
|
||||
@@ -5373,8 +5497,10 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
]);
|
||||
return {
|
||||
current,
|
||||
latest,
|
||||
updateAvailable: compareSemver(latest, current) === 1,
|
||||
latest: latest.version,
|
||||
...latest.releaseUrl === void 0 ? {} : { releaseUrl: latest.releaseUrl },
|
||||
updateAvailable: compareSemver(latest.version, current) === 1,
|
||||
updatable: latest.tarballUrl !== void 0 && UPDATABLE_KINDS.includes(install.kind),
|
||||
install,
|
||||
fetchedAt: now()
|
||||
};
|
||||
@@ -5395,8 +5521,9 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
ownPackageJsonUrl
|
||||
});
|
||||
if (install.kind === "link") throw new Error("Geek2API plugin is installed from a local checkout");
|
||||
if (install.kind !== "npm" || install.profile === void 0) throw new Error("Geek2API plugin update could not find the owning profile");
|
||||
if (!UPDATABLE_KINDS.includes(install.kind) || install.profile === void 0) throw new Error("Geek2API plugin update could not find the owning profile");
|
||||
const latest = await fetchLatest(signal);
|
||||
if (latest.tarballUrl === void 0) throw new Error("Geek2API plugin release has no package to install");
|
||||
const profileDir = join(dshHome, "profiles", install.profile);
|
||||
let result;
|
||||
try {
|
||||
@@ -5405,9 +5532,8 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
args: [
|
||||
...launcher.prefix,
|
||||
"add",
|
||||
"--save-exact",
|
||||
`--config.minimumReleaseAge=0`,
|
||||
`${PACKAGE_NAME}@${latest}`
|
||||
`${PACKAGE_NAME}@${latest.tarballUrl}`
|
||||
],
|
||||
cwd: profileDir
|
||||
}, {
|
||||
@@ -5421,12 +5547,12 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
if (result.code !== 0) throw new Error("Geek2API plugin update failed");
|
||||
await confirmInstalled({
|
||||
profileDir,
|
||||
expected: latest,
|
||||
expected: latest.version,
|
||||
settleDelayMs
|
||||
});
|
||||
cache.invalidate();
|
||||
return {
|
||||
version: latest,
|
||||
version: latest.version,
|
||||
profile: install.profile
|
||||
};
|
||||
} finally {
|
||||
@@ -5684,8 +5810,8 @@ function createGeek2APIProfile(provider) {
|
||||
function createRouteAdapter({ ring, keys, hosts, fallbackSessionId, resolveAttachments, isModelVisible = () => true }) {
|
||||
const raw = createGeek2APIProvider();
|
||||
/**
|
||||
* The gateway's Codex-group check refuses a Responses request that carries
|
||||
* no `prompt_cache_key` with a 403, which pi-ai derives from the session id.
|
||||
* GPT on Responses carries a `prompt_cache_key`, which pi-ai derives from
|
||||
* the session id; it keeps one conversation on the same upstream cache.
|
||||
* The harness supplies one for every agent turn; the fallback covers a
|
||||
* caller that does not, so the route never fails for a missing cache key.
|
||||
*/
|
||||
@@ -5790,7 +5916,7 @@ const keyId = (payload) => String(payload?.id ?? "");
|
||||
* web search controller (without one, its endpoints refuse).
|
||||
* @returns a handler for `connection.rpc.handle(CHANNEL, handler)`.
|
||||
*/
|
||||
function createGeek2APIRpc({ ring, balance, groups, hosts, preference, claudeRuntime, claudeCli, pluginManager, search, modelSelection }) {
|
||||
function createGeek2APIRpc({ ring, balance, groups, hosts, keys, preference, claudeRuntime, claudeCli, pluginManager, search, modelSelection }) {
|
||||
const need = (service, message) => {
|
||||
if (service === void 0) throw new Error(message);
|
||||
return service;
|
||||
@@ -5805,7 +5931,8 @@ function createGeek2APIRpc({ ring, balance, groups, hosts, preference, claudeRun
|
||||
hosts: hosts.status(),
|
||||
writable: preference.writable === true,
|
||||
defaults: { apiHosts: [...DEFAULT_API_HOSTS] },
|
||||
claudeRuntime: typeof claudeRuntime === "function" ? claudeRuntime() : "http"
|
||||
claudeRuntime: typeof claudeRuntime === "function" ? claudeRuntime() : "http",
|
||||
skipped: typeof keys?.skipped === "function" ? keys.skipped() : {}
|
||||
});
|
||||
const writable = () => {
|
||||
if (preference.writable !== true) throw new Error("Geek2API settings are not writable in this profile");
|
||||
@@ -6264,7 +6391,7 @@ function createGeek2APISearchProvider({ ring, hosts, backend = () => DEFAULT_SEA
|
||||
const failure = outcome.failure === "" ? `HTTP ${outcome.status}` : outcome.failure;
|
||||
lastFailure = failure;
|
||||
if (classifyClientPolicy(failure)) throw new WebError(explainClientPolicyFailure(), "WEB_PROVIDER_ERROR");
|
||||
const kind = classifyGatewayFailure(failure) ?? (outcome.status === 401 ? "invalid-key" : void 0);
|
||||
const kind = classifyGatewayFailure(failure);
|
||||
if (kind !== void 0) {
|
||||
onKeyFailure?.(kind, failure, key.key, key.id);
|
||||
continue;
|
||||
@@ -6836,7 +6963,7 @@ const Config = z.object({
|
||||
* request DSH's own search would have served.
|
||||
*/
|
||||
searchProvider: live(z.union([...SEARCH_MODES]).default(SEARCH_MODE_DEFAULT)),
|
||||
/** Which Geek2API model runs a search: `deepseek` or `gpt`. */
|
||||
/** Which Geek2API model runs a search: `claude` or `gpt`. */
|
||||
searchBackend: live(z.union([...SEARCH_BACKENDS]).default(DEFAULT_SEARCH_BACKEND)),
|
||||
/** Only the picker is filtered; an existing session can keep its model. */
|
||||
hiddenModels: live(z.array(z.string()).default([]))
|
||||
@@ -6859,7 +6986,8 @@ function apply(ctx, config) {
|
||||
const claudeRuntime = () => fieldValue((source() ?? {}).claudeRuntime) === "cli" ? "cli" : "http";
|
||||
const balance = createBalanceReader({
|
||||
listKeys: () => ring.secrets(),
|
||||
hosts
|
||||
hosts,
|
||||
onRead: (rows) => keys.noteBalances(rows)
|
||||
});
|
||||
/**
|
||||
* Which token groups each key is in, and so which models it can reach.
|
||||
@@ -6906,8 +7034,8 @@ function apply(ctx, config) {
|
||||
onChange: () => refreshModels()
|
||||
});
|
||||
/**
|
||||
* The Claude Code CLI runner. Geek2API serves its Claude models only to the
|
||||
* official CLI, so CLI-backed models are run by that CLI itself — with this
|
||||
* The Claude Code CLI runner, for the `cli` Claude runtime and the
|
||||
* `claude_code` tool: the official CLI itself runs the turn — with this
|
||||
* plugin's endpoint and a ring key, in an isolated config home. Each run
|
||||
* uses the active key unless its groups cannot reach the run's Claude model
|
||||
* and another stored key's can, and reports which key it used by label.
|
||||
@@ -7048,6 +7176,7 @@ function apply(ctx, config) {
|
||||
ctx.on?.("loader/volatile-update", () => {
|
||||
modelSelection.reconcile();
|
||||
search.reconcile();
|
||||
hosts.probe({ force: true }).catch(() => void 0);
|
||||
});
|
||||
/**
|
||||
* Both search providers register with the web service whenever one exists.
|
||||
@@ -7065,6 +7194,7 @@ function apply(ctx, config) {
|
||||
balance,
|
||||
groups,
|
||||
hosts,
|
||||
keys,
|
||||
preference: modelPreference,
|
||||
claudeRuntime,
|
||||
claudeCli,
|
||||
|
||||
@@ -56,6 +56,14 @@
|
||||
],
|
||||
"author": "Geek2API",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/CoderKuo/dsh-geek2api.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/CoderKuo/dsh-geek2api/issues"
|
||||
},
|
||||
"homepage": "https://github.com/CoderKuo/dsh-geek2api#readme",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
+18
-3
@@ -91,16 +91,19 @@ export function parseKeyUsage(payload) {
|
||||
})
|
||||
|
||||
if (payload.mode === 'quota_limited') {
|
||||
// A key cap, not money: the key still spends the account wallet, which
|
||||
// this shape does not report. Only the cap and the windows are known.
|
||||
const quota = record(payload.quota) ? payload.quota : undefined
|
||||
const expiresAt = timestamp(payload.expires_at)
|
||||
const rateLimits = parseRateLimits(payload.rate_limits)
|
||||
return defined({
|
||||
...common,
|
||||
mode: 'quota',
|
||||
unlimitedQuota: quota === undefined,
|
||||
unlimitedQuota: quota === undefined && rateLimits === undefined,
|
||||
limitUsd: usd(quota?.limit),
|
||||
usedUsd: usd(quota?.used),
|
||||
availableUsd: usd(quota?.remaining ?? payload.remaining),
|
||||
rateLimits: parseRateLimits(payload.rate_limits),
|
||||
rateLimits,
|
||||
expiresAt,
|
||||
})
|
||||
}
|
||||
@@ -119,7 +122,13 @@ export function parseKeyUsage(payload) {
|
||||
})
|
||||
}
|
||||
|
||||
if (payload.mode === 'unrestricted' && record(payload) && (payload.balance !== undefined || payload.remaining !== undefined)) {
|
||||
// A subscription group with no active subscription still answers here,
|
||||
// with its plan name and nothing to spend.
|
||||
if (payload.mode === 'unrestricted' && payload.balance === undefined && payload.remaining === undefined && common.planName !== undefined) {
|
||||
return defined({ ...common, mode: 'subscription', inactive: true, unlimitedQuota: false, availableUsd: 0 })
|
||||
}
|
||||
|
||||
if (payload.mode === 'unrestricted' && (payload.balance !== undefined || payload.remaining !== undefined)) {
|
||||
// The wallet has no cap of its own: what remains is all there is.
|
||||
return defined({
|
||||
...common,
|
||||
@@ -156,6 +165,7 @@ export function createBalanceReader({
|
||||
now = Date.now,
|
||||
ttlMs = DEFAULT_BALANCE_TTL_MS,
|
||||
timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
|
||||
onRead,
|
||||
} = {}) {
|
||||
if (typeof listKeys !== 'function') throw new Error('Geek2API balance reader requires listKeys')
|
||||
if (typeof hosts?.withFailover !== 'function') throw new Error('Geek2API balance reader requires a host pool')
|
||||
@@ -206,6 +216,11 @@ export function createBalanceReader({
|
||||
: { ...base, usage: previous.usage, stale: { fetchedAt: previous.fetchedAt, error: message } }
|
||||
}
|
||||
}))
|
||||
try {
|
||||
onRead?.(entries)
|
||||
} catch {
|
||||
// An observer must not fail the read.
|
||||
}
|
||||
return { keys: entries, hosts: hosts.status(), fetchedAt: now() }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* Route Claude models through the local Claude Code CLI.
|
||||
*
|
||||
* Geek2API's `cc` group serves its Claude models only to the official CLI, so
|
||||
* selecting one of those models runs that CLI instead of an HTTP request. The
|
||||
* other models on the route keep using the pi-ai adapter untouched — this
|
||||
* When the Claude runtime setting is `cli`, selecting a Claude model runs the
|
||||
* local Claude Code CLI instead of an HTTP request (useful when a key's group
|
||||
* only serves the official CLI). Every other model, and every Claude model on
|
||||
* the default `http` runtime, keeps using the pi-ai adapter untouched — this
|
||||
* adapter only dispatches.
|
||||
*
|
||||
* A CLI-backed turn is a *delegation*: the CLI runs its own agent loop with
|
||||
@@ -39,7 +40,7 @@ export const TITLE_MODEL_ID = 'claude-haiku-4-5-20251001'
|
||||
/**
|
||||
* HTTP models whose session titles run on another model of the same route.
|
||||
* A title is a few words, so the flagship `gpt-6-astra` hands it to
|
||||
* `gpt-6.1-sol`, which the same Codex group serves; the session's own turns
|
||||
* `gpt-6.1-sol`, which the same GPT groups serve; the session's own turns
|
||||
* are untouched.
|
||||
*/
|
||||
export const TITLE_MODEL_ROUTES = Object.freeze({ 'gpt-6-astra': 'gpt-6.1-sol' })
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* Bridge to the local Claude Code CLI.
|
||||
*
|
||||
* The gateway's `cc` group serves its Claude models only to the official CLI,
|
||||
* so this module runs that CLI — the real binary, not an imitation of it — as
|
||||
* On the `cli` Claude runtime (and for the `claude_code` tool) this module runs
|
||||
* the official CLI — the real binary, not an imitation of it — as
|
||||
* a subprocess and hands its final answer back to the harness. The child gets
|
||||
* the plugin's own endpoint and key through the environment, plus an isolated
|
||||
* `CLAUDE_CONFIG_DIR`: `~/.claude/settings.json` env wins over an inherited
|
||||
|
||||
+22
-10
@@ -16,12 +16,14 @@ export const zh = {
|
||||
totalLimit: '合计额度',
|
||||
totalPartial: '有 {count} 个 Key 未读到余额,未计入合计。',
|
||||
totalStale: '其中 {count} 个 Key 本次读取失败,显示的是上次读到的余额。',
|
||||
totalShared: '{count} 个 Key 与其他 Key 共用同一个钱包,只计一次。',
|
||||
totalShared: '{count} 个 Key 与其他 Key 共用同一个钱包或订阅,只计一次。',
|
||||
totalCapped: '{count} 个 Key 设有自己的限额,它们花的是账户钱包,限额不计入合计。',
|
||||
staleNote: '上次读取于 {time},本次读取失败:{error}',
|
||||
empty: '还没有 Key。添加一个即可在模型选择器里看到 Geek2API 的模型。',
|
||||
keysHint: '按顺序使用:当前 Key 不可用时自动切到下一个;「切到此 Key」指定优先使用的 Key。',
|
||||
keyActive: '使用中',
|
||||
keyDisabled: '已停用',
|
||||
keySkipped: '余额不足,暂时跳过',
|
||||
keyUse: '切到此 Key',
|
||||
keyEnable: '重新启用',
|
||||
keyRemove: '删除',
|
||||
@@ -39,7 +41,10 @@ export const zh = {
|
||||
keyToday: '今日',
|
||||
planWallet: '钱包余额(同账户的 Key 共用)',
|
||||
planSubscription: '订阅:{name}',
|
||||
planQuota: 'Key 限额',
|
||||
planQuota: 'Key 限额(从账户钱包扣费)',
|
||||
planSubscriptionInactive: '订阅:{name}(未开通或已过期)',
|
||||
keyCapRemaining: 'Key 剩余限额',
|
||||
keyWindow: '{window} 窗口 {used}/{limit}',
|
||||
keyExpires: '{date} 到期',
|
||||
resetMonthly: '每月重置',
|
||||
resetWeekly: '每周重置',
|
||||
@@ -50,7 +55,7 @@ export const zh = {
|
||||
addKeyPlaceholder: '粘贴 API Key',
|
||||
addLabelPlaceholder: '备注(可选)',
|
||||
add: '添加',
|
||||
notWritable: '当前 profile 不允许写入设置,改动只在本次运行内生效。',
|
||||
notWritable: '当前 profile 不允许写入设置,这些选项暂时不能修改。',
|
||||
error: '读取 Geek2API 状态失败',
|
||||
|
||||
groupsTitle: '分组',
|
||||
@@ -81,7 +86,7 @@ export const zh = {
|
||||
hostsCooling: '暂时跳过',
|
||||
hostsUnprobed: '未测速',
|
||||
hostsEdit: '编辑地址列表',
|
||||
hostsEditHint: '每行一个地址,按优先顺序排列。留空则恢复默认列表。',
|
||||
hostsEditHint: '每行一个地址(只取域名部分,必须是 https),按优先顺序排列。要恢复内置列表请点「恢复默认」。',
|
||||
hostsSave: '保存',
|
||||
hostsReset: '恢复默认',
|
||||
|
||||
@@ -128,7 +133,8 @@ export const zh = {
|
||||
versionUpToDate: '已是最新版本',
|
||||
versionAvailable: '发现新版本 v{version}',
|
||||
versionLinked: '当前是本地开发安装,请在插件仓库拉取代码并重新构建。',
|
||||
versionManual: '无法在这里更新。请在桌面应用的插件页重新安装 dsh-geek2api。',
|
||||
versionManual: '无法在这里自动更新。请到 GitHub Releases 下载新版本,在桌面应用的插件页重新安装。',
|
||||
versionNotes: '更新说明',
|
||||
versionUpdate: '更新插件',
|
||||
versionUpdating: '正在更新…',
|
||||
versionUpdateFailed: '更新失败,请重试,或在插件页重新安装。',
|
||||
@@ -187,12 +193,14 @@ export const en = {
|
||||
totalLimit: 'Total limit',
|
||||
totalPartial: '{count} key(s) could not be read and are not counted here.',
|
||||
totalStale: '{count} of these keys failed this read and show their last read balance.',
|
||||
totalShared: '{count} key(s) share a wallet with another key and are counted once.',
|
||||
totalShared: '{count} key(s) share a wallet or subscription with another key and are counted once.',
|
||||
totalCapped: '{count} key(s) have their own cap; they spend the account wallet, so caps are not added to the total.',
|
||||
staleNote: 'Last read at {time}; this read failed: {error}',
|
||||
empty: 'No keys yet. Add one and the Geek2API models appear in the model picker.',
|
||||
keysHint: 'Used in order: when the active key cannot serve a request, the next one takes over. “Use this key” picks the preferred key.',
|
||||
keyActive: 'Active',
|
||||
keyDisabled: 'Disabled',
|
||||
keySkipped: 'Out of balance, skipped for now',
|
||||
keyUse: 'Use this key',
|
||||
keyEnable: 'Re-enable',
|
||||
keyRemove: 'Remove',
|
||||
@@ -210,7 +218,10 @@ export const en = {
|
||||
keyToday: 'Today',
|
||||
planWallet: 'Wallet (shared by the account’s keys)',
|
||||
planSubscription: 'Subscription: {name}',
|
||||
planQuota: 'Key quota',
|
||||
planQuota: 'Key quota (spends the account wallet)',
|
||||
planSubscriptionInactive: 'Subscription: {name} (not active)',
|
||||
keyCapRemaining: 'Cap left',
|
||||
keyWindow: '{window} window {used}/{limit}',
|
||||
keyExpires: 'expires {date}',
|
||||
resetMonthly: 'resets monthly',
|
||||
resetWeekly: 'resets weekly',
|
||||
@@ -221,7 +232,7 @@ export const en = {
|
||||
addKeyPlaceholder: 'Paste API key',
|
||||
addLabelPlaceholder: 'Label (optional)',
|
||||
add: 'Add',
|
||||
notWritable: 'This profile does not allow settings writes; changes apply to this run only.',
|
||||
notWritable: 'This profile does not allow settings writes; these options cannot be changed here.',
|
||||
error: 'Could not read Geek2API status',
|
||||
|
||||
groupsTitle: 'Groups',
|
||||
@@ -243,7 +254,7 @@ export const en = {
|
||||
hostsCooling: 'skipped for now',
|
||||
hostsUnprobed: 'not measured',
|
||||
hostsEdit: 'Edit endpoint list',
|
||||
hostsEditHint: 'One endpoint per line, in order of preference. Leave empty to restore the defaults.',
|
||||
hostsEditHint: 'One endpoint per line (origin only, https), in order of preference. Use Restore defaults to go back to the built-in list.',
|
||||
hostsSave: 'Save',
|
||||
hostsReset: 'Restore defaults',
|
||||
|
||||
@@ -290,7 +301,8 @@ export const en = {
|
||||
versionUpToDate: 'Up to date',
|
||||
versionAvailable: 'v{version} is available',
|
||||
versionLinked: 'Installed from a local checkout. Pull and rebuild the plugin repository instead.',
|
||||
versionManual: 'This install cannot be updated here. Reinstall dsh-geek2api from the desktop Plugins page.',
|
||||
versionManual: 'This install cannot update itself. Download the new version from GitHub Releases and reinstall it from the Plugins page.',
|
||||
versionNotes: 'Release notes',
|
||||
versionUpdate: 'Update plugin',
|
||||
versionUpdating: 'Updating…',
|
||||
versionUpdateFailed: 'The update failed. Try again, or reinstall from the Plugins page.',
|
||||
|
||||
@@ -35,6 +35,8 @@ export const STYLE = `
|
||||
.pkc-input:focus{border-color:var(--dsw-alias-state-business-primary)}
|
||||
.pkc-input::placeholder{color:var(--dsw-alias-label-caption)}
|
||||
.pkc-input:disabled{opacity:.5}
|
||||
.pkc-link{color:var(--dsw-alias-state-business-primary);font-size:12px;text-decoration:none}
|
||||
.pkc-link:hover{text-decoration:underline}
|
||||
.pkc-textarea{display:block;width:100%;height:auto;min-height:96px;padding:8px 10px;line-height:1.6;resize:vertical;white-space:pre;overflow-x:auto}
|
||||
.pkc-form{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
||||
|
||||
|
||||
+41
-12
@@ -82,6 +82,7 @@ const RESET_KEYS = { monthly: 'resetMonthly', weekly: 'resetWeekly', daily: 'res
|
||||
/** What a key draws on: the shared wallet, a subscription plan, or its own quota. */
|
||||
function planLabel(usage, t) {
|
||||
if (usage?.mode === 'wallet') return t('planWallet')
|
||||
if (usage?.mode === 'subscription' && usage.inactive === true) return fill(t('planSubscriptionInactive'), { name: usage.planName ?? '' })
|
||||
if (usage?.mode === 'subscription') return fill(t('planSubscription'), { name: usage.planName ?? '' })
|
||||
if (usage?.mode === 'quota') return t('planQuota')
|
||||
return undefined
|
||||
@@ -187,13 +188,14 @@ function KeyGroups({ group, descriptions, loading, t }) {
|
||||
)
|
||||
}
|
||||
|
||||
function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, t }) {
|
||||
function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, skippedUntil, t }) {
|
||||
const usage = row?.usage
|
||||
const share = remainingShare(usage)
|
||||
const remainingLabel = usage?.mode === 'quota' ? t('keyCapRemaining') : t('keyRemaining')
|
||||
const figures = [
|
||||
usage?.unlimitedQuota === true
|
||||
? [t('keyRemaining'), t('keyUnlimited')]
|
||||
: usage?.availableUsd === undefined ? undefined : [t('keyRemaining'), formatUsd(usage.availableUsd)],
|
||||
? [remainingLabel, t('keyUnlimited')]
|
||||
: usage?.availableUsd === undefined ? undefined : [remainingLabel, formatUsd(usage.availableUsd)],
|
||||
usage?.usedUsd === undefined ? undefined : [t('keyUsed'), formatUsd(usage.usedUsd)],
|
||||
usage?.limitUsd === undefined ? undefined : [t('accountLimit'), formatUsd(usage.limitUsd)],
|
||||
].filter(Boolean)
|
||||
@@ -203,6 +205,11 @@ function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming
|
||||
resetLabel(usage?.resetPeriod, t),
|
||||
usage?.todayUsd === undefined ? undefined : `${t('keyToday')} ${formatUsd(usage.todayUsd)}`,
|
||||
usage?.expiresAt === undefined ? undefined : fill(t('keyExpires'), { date: new Date(usage.expiresAt).toLocaleDateString() }),
|
||||
...(Array.isArray(usage?.rateLimits) ? usage.rateLimits.map(window => fill(t('keyWindow'), {
|
||||
window: window.window,
|
||||
used: formatUsd(window.usedUsd) ?? '?',
|
||||
limit: formatUsd(window.limitUsd) ?? '?',
|
||||
})) : []),
|
||||
].filter(Boolean).join(' · ')
|
||||
const editing = renaming?.id === entry.id
|
||||
|
||||
@@ -229,6 +236,7 @@ function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming
|
||||
)
|
||||
: <span className="pkc-name">{entry.label}</span>}
|
||||
{entry.active && <span className="pkc-chip" data-tone="success">{t('keyActive')}</span>}
|
||||
{!entry.disabled && skippedUntil !== undefined && <span className="pkc-chip" data-tone="warn">{t('keySkipped')}</span>}
|
||||
{entry.disabled && <span className="pkc-chip" data-tone="danger">{entry.disabledReason ? `${t('keyDisabled')} · ${entry.disabledReason}` : t('keyDisabled')}</span>}
|
||||
</span>
|
||||
{!editing && (
|
||||
@@ -377,10 +385,11 @@ function AccountsCard({ call, t }) {
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{(totals.unread > 0 || staleCount > 0 || totals.shared > 0) && (
|
||||
{(totals.unread > 0 || staleCount > 0 || totals.shared > 0 || totals.capped > 0) && (
|
||||
<p className="pkc-note">
|
||||
{[
|
||||
totals.shared > 0 ? fill(t('totalShared'), { count: totals.shared }) : undefined,
|
||||
totals.capped > 0 ? fill(t('totalCapped'), { count: totals.capped }) : undefined,
|
||||
totals.unread > 0 ? fill(t('totalPartial'), { count: totals.unread }) : undefined,
|
||||
staleCount > 0 ? fill(t('totalStale'), { count: staleCount }) : undefined,
|
||||
].filter(Boolean).join(' ')}
|
||||
@@ -399,6 +408,7 @@ function AccountsCard({ call, t }) {
|
||||
renaming={renaming}
|
||||
onRename={rename}
|
||||
onAction={mutate}
|
||||
skippedUntil={status?.skipped?.[entry.id]}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
@@ -441,13 +451,20 @@ function HostsCard({ call, t }) {
|
||||
const [busy, setBusy] = react.useState(false)
|
||||
const [error, setError] = react.useState()
|
||||
const [draft, setDraft] = react.useState()
|
||||
const [editing, setEditing] = react.useState(false)
|
||||
|
||||
const run = react.useCallback((endpoint, payload) => {
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
return call(endpoint, payload)
|
||||
.then(setStatus)
|
||||
.catch(failure => setError(clearMessage(failure)))
|
||||
.then(next => {
|
||||
setStatus(next)
|
||||
return next
|
||||
})
|
||||
.catch(failure => {
|
||||
setError(clearMessage(failure))
|
||||
return undefined
|
||||
})
|
||||
.finally(() => setBusy(false))
|
||||
}, [call])
|
||||
|
||||
@@ -456,7 +473,16 @@ function HostsCard({ call, t }) {
|
||||
}, [run])
|
||||
|
||||
const hosts = Array.isArray(status?.hosts) ? status.hosts : []
|
||||
const save = list => run('hosts/update', { apiHosts: list }).then(() => setDraft(undefined))
|
||||
const listText = list => (Array.isArray(list) ? list.map(entry => entry.host).join('\n') : '')
|
||||
// The editor starts from the saved list, including when it opens before the
|
||||
// first status arrives, and shows what was saved after each save.
|
||||
react.useEffect(() => {
|
||||
if (editing && draft === undefined && hosts.length > 0) setDraft(listText(hosts))
|
||||
}, [editing, draft, hosts])
|
||||
const save = list => run('hosts/update', { apiHosts: list }).then(next => {
|
||||
if (next !== undefined) setDraft(listText(next.hosts))
|
||||
})
|
||||
const draftHosts = (draft ?? '').split(/\s+/u).filter(Boolean)
|
||||
return (
|
||||
<Card
|
||||
title={t('hostsTitle')}
|
||||
@@ -475,12 +501,12 @@ function HostsCard({ call, t }) {
|
||||
<span className="pkc-meta">
|
||||
{entry.coolingUntil !== undefined
|
||||
? t('hostsCooling')
|
||||
: entry.latencyMs !== undefined ? `${entry.latencyMs} ms` : t('hostsDown')}
|
||||
: entry.latencyMs !== undefined ? `${entry.latencyMs} ms` : entry.probed === false ? t('hostsUnprobed') : t('hostsDown')}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<details className="pkc-advanced" onToggle={event => event.currentTarget.open && draft === undefined && setDraft(hosts.map(entry => entry.host).join('\n'))}>
|
||||
<details className="pkc-advanced" onToggle={event => setEditing(event.currentTarget.open)}>
|
||||
<summary>{t('hostsEdit')}</summary>
|
||||
<p className="pkc-note">{t('hostsEditHint')}</p>
|
||||
<textarea
|
||||
@@ -491,7 +517,7 @@ function HostsCard({ call, t }) {
|
||||
onChange={event => setDraft(event.target.value)}
|
||||
/>
|
||||
<div className="pkc-split">
|
||||
<Button variant="primary" disabled={status?.writable !== true || busy} onClick={() => save((draft ?? '').split(/\s+/u).filter(Boolean))}>{t('hostsSave')}</Button>
|
||||
<Button variant="primary" disabled={status?.writable !== true || busy || draftHosts.length === 0} onClick={() => save(draftHosts)}>{t('hostsSave')}</Button>
|
||||
<Button variant="ghost" disabled={status?.writable !== true || busy} onClick={() => save([])}>{t('hostsReset')}</Button>
|
||||
</div>
|
||||
</details>
|
||||
@@ -858,7 +884,7 @@ function VersionCard({ call, t }) {
|
||||
|
||||
const installKind = info?.install?.kind
|
||||
const showStatus = info !== undefined && updated === undefined
|
||||
const canUpdate = showStatus && info.updateAvailable && installKind === 'npm'
|
||||
const canUpdate = showStatus && info.updateAvailable && (info.updatable === true || (info.updatable === undefined && installKind === 'npm'))
|
||||
return (
|
||||
<Card
|
||||
title={t('versionTitle')}
|
||||
@@ -879,10 +905,13 @@ function VersionCard({ call, t }) {
|
||||
{info.updateAvailable ? fill(t('versionAvailable'), { version: info.latest }) : t('versionUpToDate')}
|
||||
{info.updateAvailable && ` · ${t('versionLatest')} v${info.latest}`}
|
||||
</span>
|
||||
{info.releaseUrl !== undefined && (
|
||||
<a className="pkc-link" href={info.releaseUrl} target="_blank" rel="noreferrer noopener">{t('versionNotes')}</a>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{showStatus && installKind === 'link' && <p className="pkc-note">{t('versionLinked')}</p>}
|
||||
{showStatus && info.updateAvailable && installKind === 'unknown' && <p className="pkc-note">{t('versionManual')}</p>}
|
||||
{showStatus && info.updateAvailable && !canUpdate && installKind !== 'link' && <p className="pkc-note">{t('versionManual')}</p>}
|
||||
{updateFailed && <p className="pkc-error" role="alert">{t('versionUpdateFailed')}</p>}
|
||||
{updated !== undefined && (
|
||||
<div className="pkc-callout" data-tone="info" role="status">
|
||||
|
||||
+38
-23
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Failure classification for the two conditions that move the key ring along.
|
||||
* Failure classification for the conditions that move the key ring along.
|
||||
*
|
||||
* The gateway reports an exhausted key and a rejected key in Chinese, and the
|
||||
* harness classifies failures by fixed English/status wording it recognizes
|
||||
@@ -12,26 +12,43 @@
|
||||
* @module dsh-geek2api/failures
|
||||
*/
|
||||
|
||||
/** Terminal quota, balance, or credit wording, in the gateway's own languages. */
|
||||
const QUOTA_WORDING = /额度|余额|配额|欠费|insufficient[\s_-]+(?:quota|balance|credits?)|quota[\s_-]+(?:exceeded|exhausted|reached)|out[\s_-]+of[\s_-]+(?:credits?|budget)|no active subscription|INSUFFICIENT_BALANCE/iu
|
||||
/** A rejected key names itself; a bare 403 does not, and must not disable one. */
|
||||
const INVALID_KEY_WORDING = /无效的令牌|令牌无效|无效密钥|密钥无效|invalid[\s_-]+api[\s_-]*key|invalid_authentication|api key is invalid|api key is disabled|api key\s*已过期|API_KEY_(?:DISABLED|EXPIRED)|user account is not active|所属分组已删除|所属专属分组不再允许|GROUP_NOT_ALLOWED/iu
|
||||
const INVALID_KEY_STATUS = /\b401\b/
|
||||
/**
|
||||
* The key itself is gone for good: sub2api's own refusals of the credential
|
||||
* (`INVALID_API_KEY`, `API_KEY_DISABLED`, an expired key, an inactive user, a
|
||||
* deleted or withdrawn group). Only the gateway's own wording counts; a bare
|
||||
* 401 may be an upstream account's error passed through, and must not retire
|
||||
* the user's key.
|
||||
*/
|
||||
const INVALID_KEY_WORDING = /invalid api key|INVALID_API_KEY|api key is disabled|API_KEY_DISABLED|api key\s*已过期|API_KEY_EXPIRED|user account is not active|USER_INACTIVE|user associated with api key not found|所属分组已删除|所属专属分组不再允许|GROUP_NOT_ALLOWED/iu
|
||||
|
||||
/**
|
||||
* A gateway group that only serves its vendor's official client. These arrive
|
||||
* as 403, which the harness reads as an authentication failure and renders as
|
||||
* The key's own spending cap is used up (`API key 额度已用完`). It stays used up
|
||||
* until someone raises the cap, so the key is moved aside until re-enabled.
|
||||
*/
|
||||
const KEY_QUOTA_WORDING = /api key\s*额度已用完|api key quota exhausted|API_KEY_QUOTA_EXHAUSTED/iu
|
||||
|
||||
/**
|
||||
* Money that comes back on its own or with a top-up: the account wallet
|
||||
* (shared by every key of the account), a subscription window, a key's
|
||||
* 5h/1d/7d window, or a per-platform daily quota. The key is skipped for a
|
||||
* while, never retired: recharging must not leave keys disabled by hand.
|
||||
*/
|
||||
const EXHAUSTED_WORDING = /余额不足,?请充值|INSUFFICIENT_BALANCE|no active subscription|SUBSCRIPTION_NOT_FOUND|(?:daily|weekly|monthly) usage limit exceeded|限额已用完|usage quota exhausted for this platform/iu
|
||||
|
||||
/**
|
||||
* A group that only serves its vendor's official client. These arrive as
|
||||
* 403, which the harness reads as an authentication failure and renders as
|
||||
* an invalid-API-key problem — the opposite of what happened, and a condition
|
||||
* no retry can clear.
|
||||
*/
|
||||
const CLIENT_POLICY_WORDING = /only accessible via the official|only accepts requests from the official|official\s+claude(?:\s+code)?\s+cli|官方\s*claude(?:\s*code)?\s*cli|请使用标准\s*codex\s*客户端|客户端存在异常|二次分发|API\s*转接/iu
|
||||
const CLIENT_POLICY_WORDING = /only accessible via the official|only accepts requests from the official|official\s+claude(?:\s+code)?\s+cli|官方\s*claude(?:\s*code)?\s*cli/iu
|
||||
|
||||
/**
|
||||
* The gateway's answer when a key's groups do not include the model's
|
||||
* supplier: `model_not_found` / 当前令牌未覆盖供应商. The key is fine for other
|
||||
* models, so it is never moved aside for this.
|
||||
* The gateway's answer when the key's group does not serve the model. The key
|
||||
* is fine for other models, so it is never moved aside for this. (`No
|
||||
* available accounts` is not here: sub2api says that when a pool is busy.)
|
||||
*/
|
||||
const COVERAGE_WORDING = /model_not_found|未覆盖供应商|无可用渠道|no available channel|model is not allowed|model is not supported|is not supported by any configured account|no available accounts|is not available\. use get \/v1\/models/iu
|
||||
const COVERAGE_WORDING = /model is not allowed|model is not supported|is not supported by any configured account|is not available\. use get \/v1\/models/iu
|
||||
|
||||
/**
|
||||
* Whether the gateway refused the model for this key's groups.
|
||||
@@ -42,8 +59,10 @@ export function classifyCoverage(message) {
|
||||
return COVERAGE_WORDING.test(typeof message === 'string' ? message : '')
|
||||
}
|
||||
|
||||
/** The key's quota is exhausted; move to the next key. */
|
||||
/** The key's own cap is used up; move to the next key until re-enabled. */
|
||||
export const QUOTA_FAILURE = 'quota'
|
||||
/** Wallet, subscription, or window exhausted; skip the key for a while. */
|
||||
export const EXHAUSTED_FAILURE = 'exhausted'
|
||||
/** The gateway rejected the key itself; move to the next key. */
|
||||
export const INVALID_KEY_FAILURE = 'invalid-key'
|
||||
/** The gateway refuses this client for the route; the key is not at fault. */
|
||||
@@ -59,11 +78,7 @@ export function classifyClientPolicy(message) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a gateway failure message.
|
||||
*
|
||||
* Quota wording wins over a status token: an exhausted balance is often
|
||||
* reported as 402/403, and only the key's own rejection may read as 401. A
|
||||
* client-policy refusal is not a key fault and is classified separately.
|
||||
* Classify a gateway failure message by sub2api's own wording.
|
||||
* @param message - provider failure text, as pi-ai carries it.
|
||||
* @returns the failure kind, or undefined when the key is not at fault.
|
||||
*/
|
||||
@@ -71,9 +86,9 @@ export function classifyGatewayFailure(message) {
|
||||
const text = typeof message === 'string' ? message : ''
|
||||
if (text === '') return undefined
|
||||
if (classifyClientPolicy(text)) return undefined
|
||||
if (QUOTA_WORDING.test(text)) return QUOTA_FAILURE
|
||||
if (INVALID_KEY_WORDING.test(text)) return INVALID_KEY_FAILURE
|
||||
if (INVALID_KEY_STATUS.test(text)) return INVALID_KEY_FAILURE
|
||||
if (KEY_QUOTA_WORDING.test(text)) return QUOTA_FAILURE
|
||||
if (EXHAUSTED_WORDING.test(text)) return EXHAUSTED_FAILURE
|
||||
return undefined
|
||||
}
|
||||
|
||||
@@ -120,7 +135,7 @@ export function explainClientPolicyFailure() {
|
||||
* per-account wait queue is full, or it throttled or shed the request. The
|
||||
* CLI retries these on its own; this matches what is left when it gave up.
|
||||
*/
|
||||
const CAPACITY_WORDING = /concurrency_queue_full|并发排队已满|wait queues? (?:are|is) full|负载已饱和|overloaded|rate[_\s-]?limit|API Error:\s*(?:429|502|503|504|529)\b/iu
|
||||
const CAPACITY_WORDING = /no available accounts|concurrency limit exceeded|concurrency_queue_full|并发排队已满|wait queues? (?:are|is) full|负载已饱和|overloaded|rate[_\s-]?limit|API Error:\s*(?:429|502|503|504|529)\b/iu
|
||||
|
||||
/**
|
||||
* Whether a CLI failure is the gateway being busy rather than a fault of the
|
||||
@@ -208,7 +223,7 @@ export function explainCliGroupFailure(key, message) {
|
||||
export function normalizeFailureMessage(message, kind, options = {}) {
|
||||
const text = typeof message === 'string' && message.length > 0 ? message : 'Geek2API request failed'
|
||||
if (kind === CLIENT_POLICY_FAILURE) return explainClientPolicyFailure(options.keyName)
|
||||
if (kind === QUOTA_FAILURE) {
|
||||
if (kind === QUOTA_FAILURE || kind === EXHAUSTED_FAILURE) {
|
||||
return `${neutralizeAuthStatus(text)} — Geek2API: insufficient quota for this API key; trying the next key`
|
||||
}
|
||||
if (kind === INVALID_KEY_FAILURE) {
|
||||
|
||||
+19
-5
@@ -23,7 +23,13 @@ import {
|
||||
} from './constants.js'
|
||||
import { ambientFetch, boundedFetch, TransportError } from './request.js'
|
||||
|
||||
/** Accept an absolute http(s) origin and drop a trailing slash. */
|
||||
const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
|
||||
|
||||
/**
|
||||
* Accept an https origin, keeping only the origin: a pasted `/v1` (the base
|
||||
* URL OpenAI clients use) would otherwise double every path. Plain http is
|
||||
* refused outside loopback, because the key travels in a header.
|
||||
*/
|
||||
export function normalizeHost(value, fallback) {
|
||||
const text = typeof value === 'string' ? value.trim() : ''
|
||||
if (text === '') return fallback
|
||||
@@ -33,8 +39,9 @@ export function normalizeHost(value, fallback) {
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
if (url.protocol !== 'https:' && url.protocol !== 'http:') return fallback
|
||||
return `${url.origin}${url.pathname.replace(/\/+$/u, '')}`
|
||||
if (url.protocol === 'https:') return url.origin
|
||||
if (url.protocol === 'http:' && LOOPBACK.has(url.hostname)) return url.origin
|
||||
return fallback
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -49,10 +56,16 @@ export function normalizeHostList(value) {
|
||||
return hosts.length === 0 ? [...DEFAULT_API_HOSTS] : hosts
|
||||
}
|
||||
|
||||
/** Whether a failure means the host never answered. */
|
||||
/**
|
||||
* Whether a failure means the host never answered. A timeout is not: the
|
||||
* host accepted the connection and the gateway behind it is slow, which every
|
||||
* host would be. Text that carries an HTTP status is the gateway's answer,
|
||||
* whatever words it uses.
|
||||
*/
|
||||
export function isTransportFailure(error) {
|
||||
if (error instanceof TransportError) return error.aborted !== true
|
||||
if (error instanceof TransportError) return error.aborted !== true && error.timedOut !== true
|
||||
const text = error instanceof Error ? error.message : typeof error === 'string' ? error : ''
|
||||
if (/^\s*\d{3}\b|\(\d{3}\)|status code \d{3}|HTTP \d{3}/u.test(text)) return false
|
||||
return /fetch failed|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|UND_ERR_|socket hang up|network error|other side closed|certificate|TLS|connect timeout|Connection error|ConnectTimeout|getaddrinfo/iu.test(text)
|
||||
}
|
||||
|
||||
@@ -186,6 +199,7 @@ export function createHostPool({
|
||||
return configured().map(host => ({
|
||||
host,
|
||||
current: host === best,
|
||||
probed: probedAt !== 0,
|
||||
...(latency.has(host) ? { latencyMs: latency.get(host) } : {}),
|
||||
...(isCooling(host) ? { coolingUntil: cooling.get(host) } : {}),
|
||||
}))
|
||||
|
||||
+8
-4
@@ -88,7 +88,7 @@ export const Config = z.object({
|
||||
* request DSH's own search would have served.
|
||||
*/
|
||||
searchProvider: live(z.union([...SEARCH_MODES]).default(SEARCH_MODE_DEFAULT)),
|
||||
/** Which Geek2API model runs a search: `deepseek` or `gpt`. */
|
||||
/** Which Geek2API model runs a search: `claude` or `gpt`. */
|
||||
searchBackend: live(z.union([...SEARCH_BACKENDS]).default(DEFAULT_SEARCH_BACKEND)),
|
||||
/** Only the picker is filtered; an existing session can keep its model. */
|
||||
hiddenModels: live(z.array(z.string()).default([])),
|
||||
@@ -112,7 +112,8 @@ export function apply(ctx, config) {
|
||||
/** Whether the Claude models run through the local CLI this turn. */
|
||||
const claudeRuntime = () => (fieldValue((source() ?? {}).claudeRuntime) === 'cli' ? 'cli' : 'http')
|
||||
|
||||
const balance = createBalanceReader({ listKeys: () => ring.secrets(), hosts })
|
||||
// A read showing money brings back a key skipped for running out of it.
|
||||
const balance = createBalanceReader({ listKeys: () => ring.secrets(), hosts, onRead: rows => keys.noteBalances(rows) })
|
||||
/**
|
||||
* Which token groups each key is in, and so which models it can reach.
|
||||
* Nothing reads it at boot: the settings panel asks for it, and a request
|
||||
@@ -151,8 +152,8 @@ export function apply(ctx, config) {
|
||||
// ── the model route ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The Claude Code CLI runner. Geek2API serves its Claude models only to the
|
||||
* official CLI, so CLI-backed models are run by that CLI itself — with this
|
||||
* The Claude Code CLI runner, for the `cli` Claude runtime and the
|
||||
* `claude_code` tool: the official CLI itself runs the turn — with this
|
||||
* plugin's endpoint and a ring key, in an isolated config home. Each run
|
||||
* uses the active key unless its groups cannot reach the run's Claude model
|
||||
* and another stored key's can, and reports which key it used by label.
|
||||
@@ -301,6 +302,8 @@ export function apply(ctx, config) {
|
||||
ctx.on?.('loader/volatile-update', () => {
|
||||
modelSelection.reconcile()
|
||||
void search.reconcile()
|
||||
// A hand-edited host list is measured now, not at the next interval.
|
||||
void hosts.probe({ force: true }).catch(() => undefined)
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -323,6 +326,7 @@ export function apply(ctx, config) {
|
||||
balance,
|
||||
groups,
|
||||
hosts,
|
||||
keys,
|
||||
preference: modelPreference,
|
||||
claudeRuntime,
|
||||
claudeCli,
|
||||
|
||||
+53
-4
@@ -12,17 +12,33 @@
|
||||
* @module dsh-geek2api/key-chooser
|
||||
*/
|
||||
|
||||
import { EXHAUSTED_FAILURE } from './failures.js'
|
||||
import { pickKeyForModel } from './groups.js'
|
||||
|
||||
/** How long a request with a choice of keys waits for the first group reading. */
|
||||
export const DEFAULT_GROUP_WAIT_MS = 6_000
|
||||
/**
|
||||
* How long a key whose money ran out (wallet, subscription, or window) is
|
||||
* skipped. It is never disabled for that: a top-up or a new window brings it
|
||||
* back, and a balance read showing money brings it back at once.
|
||||
*/
|
||||
export const EXHAUSTED_SKIP_MS = 10 * 60_000
|
||||
|
||||
/**
|
||||
* @param options - the key ring, the group reader, what to do after a key
|
||||
* moved aside, a logger, and how long to wait for the first group reading.
|
||||
* @returns the chooser.
|
||||
*/
|
||||
export function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GROUP_WAIT_MS }) {
|
||||
export function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GROUP_WAIT_MS, skipMs = EXHAUSTED_SKIP_MS, now = Date.now }) {
|
||||
/** key id → epoch ms until which the key is skipped (in memory only). */
|
||||
const skipped = new Map()
|
||||
const isSkipped = id => {
|
||||
const until = skipped.get(id)
|
||||
if (until === undefined) return false
|
||||
if (until > now()) return true
|
||||
skipped.delete(id)
|
||||
return false
|
||||
}
|
||||
/**
|
||||
* Key material to ring id. A failure is reported from inside a stream, which
|
||||
* carries the request's key but not its id; this index is refreshed on every
|
||||
@@ -37,7 +53,7 @@ export function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEF
|
||||
snapshot = entries
|
||||
for (const entry of entries) idByKey.set(entry.key, entry.id)
|
||||
}
|
||||
const usable = () => snapshot.filter(entry => entry.disabled !== true)
|
||||
const usable = () => snapshot.filter(entry => entry.disabled !== true && !isSkipped(entry.id))
|
||||
const covers = (keyId, modelId) => groups.covers(keyId, modelId)
|
||||
|
||||
/**
|
||||
@@ -54,10 +70,20 @@ export function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEF
|
||||
clearTimeout(timer)
|
||||
}
|
||||
|
||||
/** The active key, after refreshing the ring and, when it matters, the groups. */
|
||||
/**
|
||||
* The active key, after refreshing the ring and, when it matters, the
|
||||
* groups. A skipped active key hands over to the next usable one in ring
|
||||
* order; with none left, the active key is returned so the failure speaks.
|
||||
*/
|
||||
const active = async () => {
|
||||
await remember()
|
||||
const key = await ring.activeKey()
|
||||
let key = await ring.activeKey()
|
||||
if (key !== undefined && isSkipped(key.id)) {
|
||||
const start = snapshot.findIndex(entry => entry.id === key.id)
|
||||
const order = start < 0 ? snapshot : [...snapshot.slice(start + 1), ...snapshot.slice(0, start)]
|
||||
const next = order.find(entry => entry.disabled !== true && !isSkipped(entry.id))
|
||||
if (next !== undefined) key = { ...key, id: next.id, label: next.label, key: next.key }
|
||||
}
|
||||
if (key !== undefined) await warm()
|
||||
return key
|
||||
}
|
||||
@@ -67,6 +93,23 @@ export function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEF
|
||||
covers,
|
||||
active,
|
||||
|
||||
/** Key ids skipped for running out of money, with when the skip ends. */
|
||||
skipped() {
|
||||
return Object.fromEntries([...skipped.keys()].filter(isSkipped).map(id => [id, skipped.get(id)]))
|
||||
},
|
||||
|
||||
/**
|
||||
* A balance read is fresher evidence than a failure: a skipped key that
|
||||
* now shows money is usable again.
|
||||
* @param rows - the `keys` of a balance projection.
|
||||
*/
|
||||
noteBalances(rows) {
|
||||
for (const row of Array.isArray(rows) ? rows : []) {
|
||||
const available = row?.usage?.availableUsd
|
||||
if (row?.stale === undefined && typeof available === 'number' && available > 0) skipped.delete(row.id)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* The key one HTTP request for `modelId` runs with, given the active key
|
||||
* pi-ai resolved. Synchronous because pi-ai opens its stream synchronously;
|
||||
@@ -135,6 +178,12 @@ export function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEF
|
||||
logger?.warn?.('geek2api: %s reported for an unidentified key; not rotating', kind)
|
||||
return
|
||||
}
|
||||
if (kind === EXHAUSTED_FAILURE) {
|
||||
skipped.set(id, now() + skipMs)
|
||||
logger?.warn?.('geek2api: key %s has no money left for now; skipping it for a while', id)
|
||||
onRotated?.()
|
||||
return
|
||||
}
|
||||
logger?.warn?.('geek2api: %s on key %s; the next key serves the retry', kind, id)
|
||||
void ring.disable(id, kind)
|
||||
.then(() => onRotated?.())
|
||||
|
||||
+55
-22
@@ -2,10 +2,12 @@
|
||||
* Version self-knowledge for the settings panel.
|
||||
*
|
||||
* The running version comes from this package. The latest version comes from
|
||||
* the npm registry. An in-place update is only offered for a registry install,
|
||||
* and it installs that exact version with the host's own pnpm — never through
|
||||
* `dsh plugin --profile desktop`, which the desktop app refuses. Registry
|
||||
* bodies and package-manager output stay host-side.
|
||||
* the GitHub releases of this repository: the newest non-draft release names
|
||||
* the version in its tag and carries the packed tarball as an asset. An
|
||||
* in-place update is offered for an install from a release tarball (or the
|
||||
* npm registry), and it installs that exact tarball with the host's own pnpm
|
||||
* — never through `dsh plugin --profile desktop`, which the desktop app
|
||||
* refuses. Release bodies and package-manager output stay host-side.
|
||||
*
|
||||
* @module dsh-geek2api/plugin-version
|
||||
*/
|
||||
@@ -23,7 +25,10 @@ import { ambientFetch, boundedFetch } from './request.js'
|
||||
export { ambientFetch, waitForSharedRequest } from './request.js'
|
||||
|
||||
export const PACKAGE_NAME = 'dsh-geek2api'
|
||||
export const NPM_REGISTRY_LATEST_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`
|
||||
export const GITHUB_REPOSITORY = 'CoderKuo/dsh-geek2api'
|
||||
export const GITHUB_LATEST_RELEASE_URL = `https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/latest`
|
||||
/** The tarball asset a release must carry for an in-place update. */
|
||||
export const releaseAssetName = version => `${PACKAGE_NAME}-${version}.tgz`
|
||||
export const DEFAULT_VERSION_TTL_MS = 5 * 60_000
|
||||
export const DEFAULT_VERSION_TIMEOUT_MS = 10_000
|
||||
export const DEFAULT_UPDATE_TIMEOUT_MS = 180_000
|
||||
@@ -54,16 +59,38 @@ export function compareSemver(a, b) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify how the running package reached the profile. Only registry specs
|
||||
* may be updated in place; local checkouts belong to the owner's iteration.
|
||||
* Classify how the running package reached the profile. Registry specs and
|
||||
* packed tarballs (a release download, or a local `.tgz`) may be updated in
|
||||
* place; local checkouts belong to the owner's iteration.
|
||||
*/
|
||||
function classifySpec(spec) {
|
||||
export function classifySpec(spec) {
|
||||
if (typeof spec !== 'string' || spec === '') return 'unknown'
|
||||
if (/\.tgz(?:[?#].*)?$/iu.test(spec) && /^(?:https:\/\/|file:)/iu.test(spec)) return 'release'
|
||||
if (/^(?:link|file):/u.test(spec)) return 'link'
|
||||
if (/^(?:\d|[~^*])/u.test(spec)) return 'npm'
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
/** Install kinds the panel may update in place. */
|
||||
export const UPDATABLE_KINDS = Object.freeze(['npm', 'release'])
|
||||
|
||||
/**
|
||||
* Normalize a GitHub "latest release" body.
|
||||
* @param payload - the API body.
|
||||
* @returns `{ version, tarballUrl, releaseUrl }`, or undefined when unusable.
|
||||
*/
|
||||
export function parseLatestRelease(payload) {
|
||||
if (payload === null || typeof payload !== 'object' || payload.draft === true || payload.prerelease === true) return undefined
|
||||
const version = typeof payload.tag_name === 'string' ? payload.tag_name.replace(/^v/u, '') : undefined
|
||||
if (parseSemver(version) === undefined) return undefined
|
||||
const asset = Array.isArray(payload.assets)
|
||||
? payload.assets.find(item => item?.name === releaseAssetName(version) && typeof item.browser_download_url === 'string')
|
||||
: undefined
|
||||
const tarballUrl = asset !== undefined && /^https:\/\/github\.com\//u.test(asset.browser_download_url) ? asset.browser_download_url : undefined
|
||||
const releaseUrl = typeof payload.html_url === 'string' && /^https:\/\/github\.com\//u.test(payload.html_url) ? payload.html_url : undefined
|
||||
return { version, ...(tarballUrl === undefined ? {} : { tarballUrl }), ...(releaseUrl === undefined ? {} : { releaseUrl }) }
|
||||
}
|
||||
|
||||
const readManifest = async path => {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(path, 'utf8'))
|
||||
@@ -217,7 +244,7 @@ export function createGeek2APIPluginManager({
|
||||
argv = process.argv,
|
||||
env = process.env,
|
||||
ownPackageJsonUrl = new URL('../package.json', import.meta.url),
|
||||
registryUrl = NPM_REGISTRY_LATEST_URL,
|
||||
releaseUrl = GITHUB_LATEST_RELEASE_URL,
|
||||
now = Date.now,
|
||||
ttlMs = DEFAULT_VERSION_TTL_MS,
|
||||
timeoutMs = DEFAULT_VERSION_TIMEOUT_MS,
|
||||
@@ -230,23 +257,26 @@ export function createGeek2APIPluginManager({
|
||||
const launcher = resolveLauncher({ argv, execPath })
|
||||
let updating = false
|
||||
|
||||
/** The newest release: its version, tarball asset, and page. */
|
||||
const fetchLatest = async signal => {
|
||||
let response
|
||||
try {
|
||||
response = await boundedFetch(registryUrl, { headers: { Accept: 'application/json' } }, { fetchImpl, timeoutMs, signal })
|
||||
response = await boundedFetch(releaseUrl, {
|
||||
headers: { Accept: 'application/vnd.github+json', 'User-Agent': PACKAGE_NAME, 'X-GitHub-Api-Version': '2022-11-28' },
|
||||
}, { fetchImpl, timeoutMs, signal })
|
||||
} catch (error) {
|
||||
if (error.aborted) throw error.cause
|
||||
throw new Error('Geek2API plugin version check failed')
|
||||
}
|
||||
if (!response.ok) throw new Error('Geek2API plugin version check failed')
|
||||
let version
|
||||
let release
|
||||
try {
|
||||
version = (await response.json())?.version
|
||||
release = parseLatestRelease(await response.json())
|
||||
} catch {
|
||||
version = undefined
|
||||
release = undefined
|
||||
}
|
||||
if (parseSemver(version) === undefined) throw new Error('Geek2API plugin version check failed')
|
||||
return version
|
||||
if (release === undefined) throw new Error('Geek2API plugin version check failed')
|
||||
return release
|
||||
}
|
||||
|
||||
const readOwnVersion = async () => {
|
||||
@@ -264,8 +294,10 @@ export function createGeek2APIPluginManager({
|
||||
])
|
||||
return {
|
||||
current,
|
||||
latest,
|
||||
updateAvailable: compareSemver(latest, current) === 1,
|
||||
latest: latest.version,
|
||||
...(latest.releaseUrl === undefined ? {} : { releaseUrl: latest.releaseUrl }),
|
||||
updateAvailable: compareSemver(latest.version, current) === 1,
|
||||
updatable: latest.tarballUrl !== undefined && UPDATABLE_KINDS.includes(install.kind),
|
||||
install,
|
||||
fetchedAt: now(),
|
||||
}
|
||||
@@ -283,10 +315,11 @@ export function createGeek2APIPluginManager({
|
||||
try {
|
||||
const install = await findInstall({ dshHome, ownPackageJsonUrl })
|
||||
if (install.kind === 'link') throw new Error('Geek2API plugin is installed from a local checkout')
|
||||
if (install.kind !== 'npm' || install.profile === undefined) {
|
||||
if (!UPDATABLE_KINDS.includes(install.kind) || install.profile === undefined) {
|
||||
throw new Error('Geek2API plugin update could not find the owning profile')
|
||||
}
|
||||
const latest = await fetchLatest(signal)
|
||||
if (latest.tarballUrl === undefined) throw new Error('Geek2API plugin release has no package to install')
|
||||
const profileDir = join(dshHome, 'profiles', install.profile)
|
||||
let result
|
||||
try {
|
||||
@@ -294,8 +327,8 @@ export function createGeek2APIPluginManager({
|
||||
command: launcher.command,
|
||||
args: [
|
||||
...launcher.prefix,
|
||||
'add', '--save-exact', `--config.minimumReleaseAge=${UPDATE_RELEASE_AGE_MINUTES}`,
|
||||
`${PACKAGE_NAME}@${latest}`,
|
||||
'add', `--config.minimumReleaseAge=${UPDATE_RELEASE_AGE_MINUTES}`,
|
||||
`${PACKAGE_NAME}@${latest.tarballUrl}`,
|
||||
],
|
||||
cwd: profileDir,
|
||||
}, { signal, timeoutMs: updateTimeoutMs })
|
||||
@@ -304,9 +337,9 @@ export function createGeek2APIPluginManager({
|
||||
throw new Error('Geek2API plugin update failed')
|
||||
}
|
||||
if (result.code !== 0) throw new Error('Geek2API plugin update failed')
|
||||
await confirmInstalled({ profileDir, expected: latest, settleDelayMs })
|
||||
await confirmInstalled({ profileDir, expected: latest.version, settleDelayMs })
|
||||
cache.invalidate()
|
||||
return { version: latest, profile: install.profile }
|
||||
return { version: latest.version, profile: install.profile }
|
||||
} finally {
|
||||
updating = false
|
||||
}
|
||||
|
||||
+2
-2
@@ -7,8 +7,8 @@
|
||||
* - DSH 0.2 has no sections: a preference is a *volatile* Config field of the
|
||||
* plugin's own row, read through a live reference, written through
|
||||
* `settings.update(rowId, patch)`, and announced by `loader/volatile-update`.
|
||||
* Only volatile fields are writable there, so the host overrides stay
|
||||
* read-only while web search and model visibility are editable.
|
||||
* Only volatile fields are writable there; the endpoint list, Claude
|
||||
* runtime, web search, and model visibility are all volatile.
|
||||
*
|
||||
* @module dsh-geek2api/preferences
|
||||
*/
|
||||
|
||||
+2
-2
@@ -50,8 +50,8 @@ export function createGeek2APIProvider() {
|
||||
'anthropic-messages': anthropicMessagesApi(),
|
||||
},
|
||||
})
|
||||
// Only GPT's Responses route requires prompt_cache_key here. Sending it
|
||||
// to Grok makes the gateway return a misleading upstream API-key error.
|
||||
// Only GPT's Responses models get prompt_cache_key; Grok upstreams have
|
||||
// rejected the field with a misleading API-key error on other gateways.
|
||||
// pi-ai's public cacheRetention option omits this field without changing
|
||||
// the model, protocol, reasoning, session headers, or credential source.
|
||||
const requestOptions = (model, options) => model.api === 'openai-responses' && !model.id.startsWith('gpt-')
|
||||
|
||||
+2
-2
@@ -111,8 +111,8 @@ export function createGeek2APIProfile(provider) {
|
||||
export function createRouteAdapter({ ring, keys, hosts, fallbackSessionId, resolveAttachments, isModelVisible = () => true }) {
|
||||
const raw = createGeek2APIProvider()
|
||||
/**
|
||||
* The gateway's Codex-group check refuses a Responses request that carries
|
||||
* no `prompt_cache_key` with a 403, which pi-ai derives from the session id.
|
||||
* GPT on Responses carries a `prompt_cache_key`, which pi-ai derives from
|
||||
* the session id; it keeps one conversation on the same upstream cache.
|
||||
* The harness supplies one for every agent turn; the fallback covers a
|
||||
* caller that does not, so the route never fails for a missing cache key.
|
||||
*/
|
||||
|
||||
+2
-1
@@ -30,7 +30,7 @@ const keyId = payload => String(payload?.id ?? '')
|
||||
* web search controller (without one, its endpoints refuse).
|
||||
* @returns a handler for `connection.rpc.handle(CHANNEL, handler)`.
|
||||
*/
|
||||
export function createGeek2APIRpc({ ring, balance, groups, hosts, preference, claudeRuntime, claudeCli, pluginManager, search, modelSelection }) {
|
||||
export function createGeek2APIRpc({ ring, balance, groups, hosts, keys, preference, claudeRuntime, claudeCli, pluginManager, search, modelSelection }) {
|
||||
const need = (service, message) => {
|
||||
if (service === undefined) throw new Error(message)
|
||||
return service
|
||||
@@ -47,6 +47,7 @@ export function createGeek2APIRpc({ ring, balance, groups, hosts, preference, cl
|
||||
writable: preference.writable === true,
|
||||
defaults: { apiHosts: [...DEFAULT_API_HOSTS] },
|
||||
claudeRuntime: typeof claudeRuntime === 'function' ? claudeRuntime() : 'http',
|
||||
skipped: typeof keys?.skipped === 'function' ? keys.skipped() : {},
|
||||
})
|
||||
const writable = () => {
|
||||
if (preference.writable !== true) throw new Error('Geek2API settings are not writable in this profile')
|
||||
|
||||
+2
-2
@@ -233,7 +233,7 @@ export function buildSearchRequest(backend, { apiHost, query, sessionId }) {
|
||||
headers: key => ({ authorization: `Bearer ${key}` }),
|
||||
body: {
|
||||
model,
|
||||
// The Codex group refuses a bare string input on some channels.
|
||||
// Message-shaped input is accepted by every Responses upstream.
|
||||
input: [{
|
||||
role: 'user',
|
||||
content: [{
|
||||
@@ -401,7 +401,7 @@ export function createGeek2APISearchProvider({
|
||||
if (classifyClientPolicy(failure)) {
|
||||
throw new WebError(explainClientPolicyFailure(), 'WEB_PROVIDER_ERROR')
|
||||
}
|
||||
const kind = classifyGatewayFailure(failure) ?? (outcome.status === 401 ? 'invalid-key' : undefined)
|
||||
const kind = classifyGatewayFailure(failure)
|
||||
if (kind !== undefined) {
|
||||
// The same sink the model route uses: the key moves aside for both.
|
||||
onKeyFailure?.(kind, failure, key.key, key.id)
|
||||
|
||||
+16
-8
@@ -1,11 +1,14 @@
|
||||
/**
|
||||
* Totals across the keys a balance read returned.
|
||||
*
|
||||
* Keys of one Geek2API account spend the same wallet, so a wallet is counted
|
||||
* once however many of its keys are stored. Two wallet rows are the same
|
||||
* wallet when the gateway names the same account (`accountRef`) or, when it
|
||||
* names none, when they report the same balance to the micro-dollar. Key
|
||||
* quotas and subscriptions are the key's own and add up.
|
||||
* In sub2api money belongs to the account, not the key:
|
||||
* - every wallet key of one account spends the same wallet, counted once —
|
||||
* the same wallet when the gateway names the same account (`accountRef`)
|
||||
* or, when it names none, when the balances agree to the micro-dollar;
|
||||
* - a subscription belongs to the user and its group, so keys on the same
|
||||
* plan count it once;
|
||||
* - a key quota is a cap on top of the wallet, not money of its own, so it
|
||||
* is left out of the sums and reported as `capped`.
|
||||
*
|
||||
* @module dsh-geek2api/totals
|
||||
*/
|
||||
@@ -14,6 +17,7 @@ const amount = value => (typeof value === 'number' && Number.isFinite(value) ? v
|
||||
|
||||
/** Which pool of money a row draws on; rows with the same pool count once. */
|
||||
function poolOf(row, usage) {
|
||||
if (usage.mode === 'subscription') return `subscription:${usage.planName ?? row?.id}`
|
||||
if (usage.mode !== 'wallet') return `key:${row?.id}`
|
||||
if (typeof usage.accountRef === 'string') return `account:${usage.accountRef}`
|
||||
const remaining = amount(usage.availableUsd)
|
||||
@@ -24,11 +28,11 @@ function poolOf(row, usage) {
|
||||
* Add up the balance rows the host returned.
|
||||
* @param rows - the `keys` array of a balance projection.
|
||||
* @returns summed amounts plus the conditions that make a sum incomplete:
|
||||
* keys whose read failed, keys with no limit at all, and how many wallet
|
||||
* rows were folded into a wallet already counted.
|
||||
* keys whose read failed, keys with no limit at all, rows folded into a
|
||||
* pool already counted, and key caps left out of the sum.
|
||||
*/
|
||||
export function sumBalances(rows) {
|
||||
const total = { keys: 0, counted: 0, unread: 0, unlimited: 0, shared: 0, remainingUsd: 0, usedUsd: 0, limitUsd: 0 }
|
||||
const total = { keys: 0, counted: 0, unread: 0, unlimited: 0, shared: 0, capped: 0, remainingUsd: 0, usedUsd: 0, limitUsd: 0 }
|
||||
const seen = new Set()
|
||||
for (const row of Array.isArray(rows) ? rows : []) {
|
||||
total.keys += 1
|
||||
@@ -38,6 +42,10 @@ export function sumBalances(rows) {
|
||||
continue
|
||||
}
|
||||
total.counted += 1
|
||||
if (usage.mode === 'quota') {
|
||||
total.capped += 1
|
||||
continue
|
||||
}
|
||||
const pool = poolOf(row, usage)
|
||||
if (seen.has(pool)) {
|
||||
total.shared += 1
|
||||
|
||||
@@ -253,7 +253,7 @@ test('an official-CLI refusal from a key without a Claude group blames the key,
|
||||
runner: {
|
||||
async *stream() {
|
||||
yield { type: 'key', label: 'no-cc', model: 'claude-opus-5-5', groups: ['codex'], required: ['cc'], covers: false }
|
||||
throw new Error('Claude Code CLI failed: API Error: 400 当前令牌未覆盖供应商 "Anthropic"(模型=claude-opus-5-5,已选分组=[codex]) (request id: r2)')
|
||||
throw new Error("Claude Code CLI failed: API Error: 400 Model 'claude-opus-5-5' is not available. Use GET /v1/models to see supported models. (request id: r2)")
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
+27
-21
@@ -5,6 +5,7 @@ import { isQuotaExceededError } from '@deepseek-ai/dsh-llm'
|
||||
|
||||
import {
|
||||
CLIENT_POLICY_FAILURE,
|
||||
EXHAUSTED_FAILURE,
|
||||
INVALID_KEY_FAILURE,
|
||||
QUOTA_FAILURE,
|
||||
classifyCapacity,
|
||||
@@ -30,41 +31,47 @@ const OTHER_CLASSES = [
|
||||
/\b(?:network|connection|socket|fetch)\b|\bECONN[A-Z]+\b|\bterminated\b|premature close/iu,
|
||||
]
|
||||
|
||||
test('recognizes an exhausted key from the gateway wording', () => {
|
||||
assert.equal(classifyGatewayFailure('402 {"error":{"message":"当前令牌额度已用完"}}'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('insufficient quota'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('余额不足,请充值'), QUOTA_FAILURE)
|
||||
test('money that comes back is exhausted, a used-up key cap is quota', () => {
|
||||
assert.equal(classifyGatewayFailure('403 {"error":{"code":"INSUFFICIENT_BALANCE","message":"余额不足,请充值"}}'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 daily usage limit exceeded'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 api key 日限额已用完'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 api key 5小时限额已用完'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 Daily usage quota exhausted for this platform.'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"SUBSCRIPTION_NOT_FOUND","message":"No active subscription found for this group"}'), EXHAUSTED_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('429 {"code":"API_KEY_QUOTA_EXHAUSTED","message":"API key 额度已用完"}'), QUOTA_FAILURE)
|
||||
})
|
||||
|
||||
test('recognizes a rejected key from its status or wording', () => {
|
||||
assert.equal(classifyGatewayFailure('401 {"error":{"message":"无效的令牌"}}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('invalid api key'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('api key is invalid'), INVALID_KEY_FAILURE)
|
||||
test('only the gateway\'s own words reject a key; a bare 401 or upstream wording does not', () => {
|
||||
assert.equal(classifyGatewayFailure('401 {"code":"INVALID_API_KEY","message":"Invalid API key"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('401 Unauthorized'), undefined)
|
||||
assert.equal(classifyGatewayFailure('502 upstream said: 401 {"error":{"type":"authentication_error"}}'), undefined)
|
||||
assert.equal(classifyGatewayFailure('429 {"error":{"type":"insufficient_quota","message":"You exceeded your current quota"}}'), undefined)
|
||||
assert.equal(classifyGatewayFailure('当前令牌额度已用完'), undefined)
|
||||
})
|
||||
|
||||
test('leaves transient gateway faults to the key it already used', () => {
|
||||
const channelFault = '400 {"error":{"code":"model_not_found","message":"当前令牌未覆盖供应商 \\"Anthropic\\"(模型=claude-opus-5-5)"}}'
|
||||
assert.equal(classifyGatewayFailure(channelFault), undefined)
|
||||
assert.equal(classifyGatewayFailure('503 {"error":{"message":"分组 cc-sale 下模型 claude-opus-5-5 无可用渠道"}}'), undefined)
|
||||
assert.equal(classifyGatewayFailure('503 {"error":{"message":"No available accounts"}}'), undefined)
|
||||
assert.equal(classifyGatewayFailure('502 Upstream service temporarily unavailable'), undefined)
|
||||
assert.equal(classifyGatewayFailure(''), undefined)
|
||||
assert.equal(classifyGatewayFailure(undefined), undefined)
|
||||
})
|
||||
|
||||
test('a normalized quota failure lands in the harness quota category', () => {
|
||||
const raw = '403 {"error":{"message":"当前令牌额度已用完 (request id: 01M4)"}}'
|
||||
const raw = '403 {"error":{"code":"INSUFFICIENT_BALANCE","message":"余额不足,请充值"}}'
|
||||
const kind = classifyGatewayFailure(raw)
|
||||
assert.equal(kind, QUOTA_FAILURE)
|
||||
assert.equal(kind, EXHAUSTED_FAILURE)
|
||||
const normalized = normalizeFailureMessage(raw, kind)
|
||||
assert.equal(isQuotaExceededError(normalized), true)
|
||||
// The gateway's 403 must not send this into the auth category first.
|
||||
assert.equal(AUTH_STATUS.test(normalized), false)
|
||||
// The gateway's own sentence survives, so the user sees what happened.
|
||||
assert.match(normalized, /当前令牌额度已用完/u)
|
||||
assert.match(normalized, /余额不足,请充值/u)
|
||||
assert.match(normalized, /trying the next key/u)
|
||||
assert.equal(isQuotaExceededError(normalizeFailureMessage('429 API key 额度已用完', QUOTA_FAILURE)), true)
|
||||
})
|
||||
|
||||
test('a normalized key rejection lands in the harness auth category', () => {
|
||||
const raw = '{"error":{"message":"无效的令牌 (request id: 01M4)"}}'
|
||||
const raw = '{"error":{"code":"INVALID_API_KEY","message":"Invalid API key"}}'
|
||||
const kind = classifyGatewayFailure(raw)
|
||||
assert.equal(kind, INVALID_KEY_FAILURE)
|
||||
const normalized = normalizeFailureMessage(raw, kind)
|
||||
@@ -75,8 +82,7 @@ test('a normalized key rejection lands in the harness auth category', () => {
|
||||
|
||||
test('a client-policy refusal is never blamed on the key', () => {
|
||||
const claude = '403 {"error":{"type":"geek2api_api_error","message":"This API endpoint is only accessible via the official Claude CLI (request id: 01M4Q6FJ05BX8Z4SWZ01RXSNSS)"}}'
|
||||
const codex = '403 {"error":{"message":"我们检测到您的客户端存在异常,请使用标准 Codex 客户端请求,请避免任何基于我方 API 二次分发的 API 转接接入。"}}'
|
||||
for (const raw of [claude, codex]) {
|
||||
for (const raw of [claude]) {
|
||||
assert.equal(classifyClientPolicy(raw), true)
|
||||
// Not a key fault: nothing may disable or rotate a key for this.
|
||||
assert.equal(classifyGatewayFailure(raw), undefined)
|
||||
@@ -106,7 +112,8 @@ test('a busy gateway is told apart from key, quota, and client faults', () => {
|
||||
assert.equal(classifyCapacity('API Error: 503 {"error":{"type":"geek2api_concurrency_queue_full","message":"账号并发排队已满,请稍后重试。"}}'), true)
|
||||
assert.equal(classifyCapacity('API Error: 429 rate_limit_error'), true)
|
||||
assert.equal(classifyCapacity('API Error: 529 overloaded_error'), true)
|
||||
assert.equal(classifyCapacity('API Error: 401 无效的令牌'), false)
|
||||
assert.equal(classifyCapacity('API Error: 401 Invalid API key'), false)
|
||||
assert.equal(classifyCapacity('API Error: 503 No available accounts'), true)
|
||||
assert.equal(classifyCapacity('Request blocked: official Claude Code CLI only'), false)
|
||||
const text = explainCliCapacityFailure('Claude Code CLI failed: API Error: 503 queue full', 10)
|
||||
assert.match(text, /已自动重试 10 次/u)
|
||||
@@ -121,14 +128,13 @@ test('classifies the sub2api gateway wording', () => {
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"API_KEY_EXPIRED","message":"API key 已过期"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"message":"API Key 所属分组已删除"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"GROUP_NOT_ALLOWED","message":"API Key 所属专属分组不再允许当前用户使用"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"INSUFFICIENT_BALANCE","message":"余额不足,请充值"}'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"SUBSCRIPTION_NOT_FOUND","message":"No active subscription found for this group"}'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"INSUFFICIENT_BALANCE","message":"余额不足,请充值"}'), EXHAUSTED_FAILURE)
|
||||
|
||||
// A model the key's group does not serve is coverage, never a key fault.
|
||||
const missing = `400 {"error":{"message":"Model 'kimi-k3' is not available. Use GET /v1/models to see supported models.","type":"invalid_request_error"}}`
|
||||
assert.equal(classifyGatewayFailure(missing), undefined)
|
||||
assert.equal(classifyCoverage(missing), true)
|
||||
assert.equal(classifyCoverage('503 No available accounts'), true)
|
||||
assert.equal(classifyCoverage('503 No available accounts'), false, 'a busy pool is not coverage')
|
||||
assert.equal(classifyCoverage('Model is not allowed'), true)
|
||||
assert.equal(classifyCoverage('500 upstream exploded'), false)
|
||||
})
|
||||
|
||||
@@ -7,9 +7,11 @@ import test from 'node:test'
|
||||
|
||||
import {
|
||||
compareSemver,
|
||||
classifySpec,
|
||||
createGeek2APIPluginManager,
|
||||
NPM_REGISTRY_LATEST_URL,
|
||||
GITHUB_LATEST_RELEASE_URL,
|
||||
PACKAGE_NAME,
|
||||
parseLatestRelease,
|
||||
parseSemver,
|
||||
resolvePnpm,
|
||||
} from '../src/plugin-version.js'
|
||||
@@ -43,7 +45,27 @@ async function linkInstall(root, version = '1.0.3') {
|
||||
return pathToFileURL(join(checkout, 'package.json'))
|
||||
}
|
||||
|
||||
const registryOk = version => async () => ({ ok: true, status: 200, async json() { return { version } } })
|
||||
const tarballUrl = version => `https://github.com/CoderKuo/dsh-geek2api/releases/download/v${version}/${PACKAGE_NAME}-${version}.tgz`
|
||||
const releasePage = version => `https://github.com/CoderKuo/dsh-geek2api/releases/tag/v${version}`
|
||||
/** The GitHub "latest release" body for `version`, with its tarball asset. */
|
||||
const releaseBody = version => ({
|
||||
tag_name: `v${version}`,
|
||||
html_url: releasePage(version),
|
||||
draft: false,
|
||||
prerelease: false,
|
||||
assets: [{ name: `${PACKAGE_NAME}-${version}.tgz`, browser_download_url: tarballUrl(version) }],
|
||||
})
|
||||
const registryOk = version => async () => ({ ok: true, status: 200, async json() { return releaseBody(version) } })
|
||||
|
||||
/** Fake DSH home whose `web` profile installed a release tarball. */
|
||||
async function releaseInstall(root, version = '1.0.3') {
|
||||
const installedDir = join(root, 'profiles', 'web', 'node_modules', PACKAGE_NAME)
|
||||
await writeManifest(join(root, 'profiles', 'web', 'package.json'), {
|
||||
dependencies: { [PACKAGE_NAME]: tarballUrl(version) },
|
||||
})
|
||||
await writeManifest(join(installedDir, 'package.json'), { name: PACKAGE_NAME, version })
|
||||
return pathToFileURL(join(installedDir, 'package.json'))
|
||||
}
|
||||
|
||||
const rpc = pluginManager => createGeek2APIRpc({
|
||||
ring: {},
|
||||
@@ -63,7 +85,27 @@ test('semver parsing and comparison drive the update badge', () => {
|
||||
assert.equal(compareSemver('not-a-version', '1.0.3'), undefined)
|
||||
})
|
||||
|
||||
test('version check asks the registry for an uncompressed document', async () => {
|
||||
test('install specs: release tarballs and registry versions update in place, checkouts do not', () => {
|
||||
assert.equal(classifySpec(tarballUrl('1.0.3')), 'release')
|
||||
assert.equal(classifySpec('file:C:/Downloads/dsh-geek2api-1.0.3.tgz'), 'release')
|
||||
assert.equal(classifySpec('link:../../checkout'), 'link')
|
||||
assert.equal(classifySpec('file:../checkout'), 'link')
|
||||
assert.equal(classifySpec('1.0.3'), 'npm')
|
||||
assert.equal(classifySpec('github:someone/else'), 'unknown')
|
||||
})
|
||||
|
||||
test('the latest release names its version, tarball, and page; drafts and foreign links are ignored', () => {
|
||||
assert.deepEqual(parseLatestRelease(releaseBody('1.0.4')), { version: '1.0.4', tarballUrl: tarballUrl('1.0.4'), releaseUrl: releasePage('1.0.4') })
|
||||
assert.equal(parseLatestRelease({ ...releaseBody('1.0.4'), draft: true }), undefined)
|
||||
assert.equal(parseLatestRelease({ ...releaseBody('1.0.4'), prerelease: true }), undefined)
|
||||
assert.equal(parseLatestRelease({ ...releaseBody('1.0.4'), tag_name: 'latest' }), undefined)
|
||||
const foreign = parseLatestRelease({ ...releaseBody('1.0.4'), assets: [{ name: `${PACKAGE_NAME}-1.0.4.tgz`, browser_download_url: 'https://evil.example/x.tgz' }] })
|
||||
assert.deepEqual(foreign, { version: '1.0.4', releaseUrl: releasePage('1.0.4') })
|
||||
const wrongAsset = parseLatestRelease({ ...releaseBody('1.0.4'), assets: [{ name: `${PACKAGE_NAME}-1.0.3.tgz`, browser_download_url: tarballUrl('1.0.3') }] })
|
||||
assert.equal(wrongAsset.tarballUrl, undefined)
|
||||
})
|
||||
|
||||
test('version check asks GitHub for an uncompressed document', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-encoding-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root, '1.0.3')
|
||||
const original = globalThis.fetch
|
||||
@@ -73,7 +115,7 @@ test('version check asks the registry for an uncompressed document', async () =>
|
||||
if (acceptEncoding !== 'identity') {
|
||||
return { ok: true, status: 200, async json() { throw new SyntaxError('gzip body') } }
|
||||
}
|
||||
return { ok: true, status: 200, async json() { return { version: '1.0.3' } } }
|
||||
return { ok: true, status: 200, async json() { return releaseBody('1.0.3') } }
|
||||
}
|
||||
try {
|
||||
const value = await createGeek2APIPluginManager({
|
||||
@@ -88,7 +130,7 @@ test('version check asks the registry for an uncompressed document', async () =>
|
||||
}
|
||||
})
|
||||
|
||||
test('version read combines own manifest, registry latest, and the owning npm profile', async () => {
|
||||
test('version read combines own manifest, the latest release, and the owning profile', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-npm-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root)
|
||||
let requests = 0
|
||||
@@ -108,11 +150,13 @@ test('version read combines own manifest, registry latest, and the owning npm pr
|
||||
assert.deepEqual(first, {
|
||||
current: '1.0.3',
|
||||
latest: '1.0.4',
|
||||
releaseUrl: releasePage('1.0.4'),
|
||||
updateAvailable: true,
|
||||
updatable: true,
|
||||
install: { kind: 'npm', profile: 'web' },
|
||||
fetchedAt: 1000,
|
||||
})
|
||||
assert.deepEqual(observed, { url: NPM_REGISTRY_LATEST_URL, redirect: 'error' })
|
||||
assert.deepEqual(observed, { url: GITHUB_LATEST_RELEASE_URL, redirect: 'error' })
|
||||
await manager.read()
|
||||
assert.equal(requests, 1, 'fresh cached reads stay off the network')
|
||||
await manager.read({ force: true })
|
||||
@@ -131,7 +175,7 @@ test('registry failures and malformed payloads surface one sanitized error', asy
|
||||
const malformed = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
fetchImpl: async () => ({ ok: true, status: 200, async json() { return { version: 'not-a-version' } } }),
|
||||
fetchImpl: async () => ({ ok: true, status: 200, async json() { return { tag_name: 'not-a-version' } } }),
|
||||
})
|
||||
await assert.rejects(() => malformed.read(), /^Error: Geek2API plugin version check failed$/u)
|
||||
})
|
||||
@@ -184,14 +228,14 @@ async function desktopRuntime(root) {
|
||||
const installRecorder = async ({ args, cwd }) => {
|
||||
await writeManifest(join(cwd, 'node_modules', PACKAGE_NAME, 'package.json'), {
|
||||
name: PACKAGE_NAME,
|
||||
version: args.at(-1).split('@').at(-1),
|
||||
version: /-(\d+\.\d+\.\d+)\.tgz$/u.exec(args.at(-1))[1],
|
||||
})
|
||||
return { code: 0, stdout: '', stderr: '' }
|
||||
}
|
||||
|
||||
test('update installs the exact version into the owning profile, pinned and age-free', async () => {
|
||||
test('update installs the release tarball into the owning profile, age-free', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-update-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root)
|
||||
const ownPackageJsonUrl = await releaseInstall(root)
|
||||
const calls = []
|
||||
let registryRequests = 0
|
||||
const manager = createGeek2APIPluginManager({
|
||||
@@ -212,7 +256,7 @@ test('update installs the exact version into the owning profile, pinned and age-
|
||||
assert.deepEqual(updated, { version: '1.0.4', profile: 'web' })
|
||||
assert.equal(calls[0].command, 'pnpm')
|
||||
assert.deepEqual(calls[0].args, [
|
||||
'add', '--save-exact', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@1.0.4`,
|
||||
'add', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@${tarballUrl('1.0.4')}`,
|
||||
])
|
||||
assert.equal(calls[0].cwd, join(root, 'profiles', 'web'))
|
||||
await manager.read()
|
||||
@@ -240,7 +284,7 @@ test('desktop hosts install with the bundled pnpm, never by launching the deskto
|
||||
const [call] = calls
|
||||
assert.equal(call.command, '/Applications/DeepSeek Harness')
|
||||
assert.deepEqual(call.args, [
|
||||
runtime.pnpm, 'add', '--save-exact', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@1.0.4`,
|
||||
runtime.pnpm, 'add', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@${tarballUrl('1.0.4')}`,
|
||||
])
|
||||
const flattened = JSON.stringify(call)
|
||||
assert.equal(flattened.includes(runtime.hostEntry), false)
|
||||
@@ -359,3 +403,20 @@ test('loopback RPC exposes version and update endpoints with sanitized errors',
|
||||
error: { code: 'geek2api/request-failed', message: 'Geek2API plugin version is unavailable', details: {} },
|
||||
})
|
||||
})
|
||||
|
||||
test('a release without its tarball is reported but not installed', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-noasset-'))
|
||||
const ownPackageJsonUrl = await releaseInstall(root, '1.0.3')
|
||||
const manager = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
fetchImpl: async () => ({ ok: true, status: 200, async json() { return { ...releaseBody('1.0.4'), assets: [] } } }),
|
||||
runCommand: async () => {
|
||||
throw new Error('runCommand must not run without a tarball')
|
||||
},
|
||||
})
|
||||
const info = await manager.read()
|
||||
assert.equal(info.updateAvailable, true)
|
||||
assert.equal(info.updatable, false)
|
||||
await assert.rejects(() => manager.update(), /^Error: Geek2API plugin release has no package to install$/u)
|
||||
})
|
||||
@@ -35,7 +35,7 @@ test('a terminal quota event moves the ring and is rewritten for the classifier'
|
||||
const failures = []
|
||||
const event = {
|
||||
type: 'error',
|
||||
error: { errorMessage: '403 {"error":{"message":"当前令牌额度已用完"}}' },
|
||||
error: { errorMessage: '429 {"error":{"code":"API_KEY_QUOTA_EXHAUSTED","message":"API key 额度已用完"}}' },
|
||||
}
|
||||
const guarded = guardKeyRotation(fakeStream([event]), {
|
||||
key: 'sk-aaaaaaaaaaaaaaaa',
|
||||
@@ -55,7 +55,7 @@ test('a terminal quota event moves the ring and is rewritten for the classifier'
|
||||
test('a rejected key reported as a terminal event normalizes to auth', async () => {
|
||||
const failures = []
|
||||
const guarded = guardKeyRotation(fakeStream([
|
||||
{ type: 'done', message: { errorMessage: '401 {"error":{"message":"无效的令牌"}}' } },
|
||||
{ type: 'done', message: { errorMessage: '401 {"error":{"code":"INVALID_API_KEY","message":"Invalid API key"}}' } },
|
||||
]), { key: 'sk-bbbbbbbbbbbbbbbbbb', onKeyFailure: (...args) => failures.push(args) })
|
||||
const received = []
|
||||
for await (const item of guarded) received.push(item)
|
||||
@@ -216,7 +216,8 @@ test('sub2api key faults move the ring: invalid, disabled, deleted group, and em
|
||||
['401 {"error":{"message":"Invalid API key"}}', 'invalid-key'],
|
||||
['401 {"error":{"message":"API key is disabled"}}', 'invalid-key'],
|
||||
['403 {"error":{"message":"API Key 所属分组已删除"}}', 'invalid-key'],
|
||||
['403 {"error":{"message":"余额不足,请充值"}}', 'quota'],
|
||||
['403 {"error":{"message":"余额不足,请充值"}}', 'exhausted'],
|
||||
['429 {"error":{"message":"API key 额度已用完"}}', 'quota'],
|
||||
]
|
||||
for (const [message, kind] of cases) {
|
||||
const failures = []
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
|
||||
async function preflight(exchangeStatus) {
|
||||
const workflow = await readFile(new URL('../.github/workflows/publish.yml', import.meta.url), 'utf8')
|
||||
const step = workflow.split('- name: Show the OIDC identity npm will match')[1]?.split('- name: Publish')[0]
|
||||
const code = /node <<'EOF'\n([\s\S]*?)\n\s*EOF/u.exec(step ?? '')?.[1]
|
||||
assert.ok(code, 'the trusted-publisher preflight must contain its actual Node program')
|
||||
const lines = []
|
||||
const calls = []
|
||||
const token = `fixture-secret-${'x'.repeat(2_000)}`
|
||||
const claims = {
|
||||
repository: 'BaronCyrus/dsh-geek2api',
|
||||
repository_owner: 'BaronCyrus',
|
||||
workflow: 'Publish',
|
||||
workflow_ref: 'BaronCyrus/dsh-geek2api/.github/workflows/publish.yml@refs/heads/main',
|
||||
ref: 'refs/heads/main',
|
||||
aud: 'npm:registry.npmjs.org',
|
||||
iss: 'https://token.actions.githubusercontent.com',
|
||||
}
|
||||
const oidc = `header.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.signature`
|
||||
const promise = runInNewContext(code, {
|
||||
URL,
|
||||
Buffer,
|
||||
console: { log: value => lines.push(String(value)), error: value => lines.push(String(value)) },
|
||||
process: {
|
||||
env: { ACTIONS_ID_TOKEN_REQUEST_URL: 'https://actions.example/oidc?existing=true', ACTIONS_ID_TOKEN_REQUEST_TOKEN: 'fixture-request-capability' },
|
||||
exit: code => { throw new Error(`EXIT_${code}`) },
|
||||
},
|
||||
fetch: async (url, options) => {
|
||||
calls.push({ url: String(url), options })
|
||||
if (calls.length === 1) return { ok: true, json: async () => ({ value: oidc }) }
|
||||
assert.equal(String(url), 'https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/dsh-geek2api')
|
||||
assert.equal(options.method, 'POST')
|
||||
assert.equal(options.headers.Authorization, `Bearer ${oidc}`)
|
||||
return { ok: exchangeStatus >= 200 && exchangeStatus < 300, status: exchangeStatus, arrayBuffer: async () => Buffer.from(JSON.stringify({ token })) }
|
||||
},
|
||||
})
|
||||
return { promise, lines, calls, token }
|
||||
}
|
||||
|
||||
test('publisher preflight prints safe identity claims, never an exchange credential or its truncated prefix', async () => {
|
||||
const run = await preflight(200)
|
||||
await run.promise
|
||||
assert.ok(run.lines.includes('repository=BaronCyrus/dsh-geek2api'))
|
||||
assert.ok(run.lines.includes('environment='))
|
||||
assert.ok(run.lines.includes('exchange_status=200'))
|
||||
assert.equal(new URL(run.calls[0].url).searchParams.get('audience'), 'npm:registry.npmjs.org')
|
||||
assert.equal(run.lines.join('\n').includes(run.token.slice(0, 50)), false)
|
||||
assert.equal(run.lines.join('\n').includes('fixture-request-capability'), false)
|
||||
})
|
||||
|
||||
test('publisher preflight accepts the real registry exchange Created response', async () => {
|
||||
const run = await preflight(201)
|
||||
await run.promise
|
||||
assert.ok(run.lines.includes('exchange_status=201'))
|
||||
assert.equal(run.lines.join('\n').includes(run.token.slice(0, 50)), false)
|
||||
})
|
||||
|
||||
test('tag publication uses the verified versioned tarball, not a separately packed workspace', async () => {
|
||||
const workflow = await readFile(new URL('../.github/workflows/publish.yml', import.meta.url), 'utf8')
|
||||
assert.ok(workflow.includes('run: pnpm pack --pack-destination .artifacts'))
|
||||
assert.ok(workflow.includes('artifact=".artifacts/dsh-geek2api-${version:?}.tgz"'))
|
||||
assert.ok(workflow.includes('npm publish "${artifact:?}" --access public'))
|
||||
assert.ok(workflow.includes('if [ ! -f "$artifact" ]; then'))
|
||||
})
|
||||
|
||||
test('publisher preflight fails closed when npm rejects the configured publisher', async () => {
|
||||
const run = await preflight(403)
|
||||
await assert.rejects(run.promise, /EXIT_1/u)
|
||||
assert.ok(run.lines.includes('exchange_status=403'))
|
||||
assert.equal(run.lines.join('\n').includes(run.token.slice(0, 50)), false)
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { parseKeyUsage } from '../src/balance.js'
|
||||
import { isTransportFailure, normalizeHost, normalizeHostList } from '../src/hosts.js'
|
||||
import { createKeyChooser } from '../src/key-chooser.js'
|
||||
import { Geek2APIKeyRing } from '../src/key-ring.js'
|
||||
import { TransportError } from '../src/request.js'
|
||||
|
||||
function fakeCredentials() {
|
||||
let record
|
||||
let chain = Promise.resolve()
|
||||
return {
|
||||
async readRecord() {
|
||||
return record
|
||||
},
|
||||
modifyRecord(_key, mutate) {
|
||||
const run = chain.then(async () => {
|
||||
const next = await mutate(record)
|
||||
if (next !== undefined) record = next
|
||||
return record
|
||||
})
|
||||
chain = run.then(() => undefined, () => undefined)
|
||||
return run
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const NO_GROUPS = Object.freeze({
|
||||
read: async () => ({ keys: [] }),
|
||||
hasReading: () => true,
|
||||
covers: () => undefined,
|
||||
groupsOf: () => undefined,
|
||||
requiredGroups: () => undefined,
|
||||
})
|
||||
|
||||
async function chooserWith(clock) {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add('sk-first-0000000000000000', 'first')
|
||||
await ring.add('sk-second-000000000000000', 'second')
|
||||
const keys = createKeyChooser({ ring, groups: NO_GROUPS, now: () => clock.now, skipMs: 1_000 })
|
||||
return { ring, keys }
|
||||
}
|
||||
|
||||
test('an empty wallet skips the key for a while and never disables it', async () => {
|
||||
const clock = { now: 10_000 }
|
||||
const { ring, keys } = await chooserWith(clock)
|
||||
const first = await keys.active()
|
||||
assert.equal(first.label, 'first')
|
||||
|
||||
keys.onKeyFailure('exhausted', '余额不足,请充值', first.key)
|
||||
assert.equal((await keys.active()).label, 'second', 'the next key serves the retry')
|
||||
const state = await ring.list()
|
||||
assert.equal(state.keys.every(entry => entry.disabled !== true), true, 'nothing was disabled')
|
||||
assert.deepEqual(Object.keys(keys.skipped()), [first.id])
|
||||
|
||||
clock.now += 1_001
|
||||
assert.equal((await keys.active()).label, 'first', 'the skip ends by itself')
|
||||
})
|
||||
|
||||
test('with every key out of money the active key still answers, so the failure speaks', async () => {
|
||||
const clock = { now: 10_000 }
|
||||
const { keys } = await chooserWith(clock)
|
||||
const first = await keys.active()
|
||||
keys.onKeyFailure('exhausted', 'x', first.key)
|
||||
const second = await keys.active()
|
||||
keys.onKeyFailure('exhausted', 'x', second.key)
|
||||
assert.equal((await keys.active()).label, 'first')
|
||||
})
|
||||
|
||||
test('a balance read showing money brings a skipped key back at once', async () => {
|
||||
const clock = { now: 10_000 }
|
||||
const { keys } = await chooserWith(clock)
|
||||
const first = await keys.active()
|
||||
keys.onKeyFailure('exhausted', 'x', first.key)
|
||||
keys.noteBalances([{ id: first.id, usage: { availableUsd: 0 } }])
|
||||
assert.equal((await keys.active()).label, 'second', 'still empty: still skipped')
|
||||
keys.noteBalances([{ id: first.id, usage: { availableUsd: 12 }, stale: { fetchedAt: 1 } }])
|
||||
assert.equal((await keys.active()).label, 'second', 'a stale reading is no evidence')
|
||||
keys.noteBalances([{ id: first.id, usage: { availableUsd: 12 } }])
|
||||
assert.equal((await keys.active()).label, 'first')
|
||||
})
|
||||
|
||||
test('a used-up key cap or a rejected key is still disabled', async () => {
|
||||
const clock = { now: 10_000 }
|
||||
const { ring, keys } = await chooserWith(clock)
|
||||
const first = await keys.active()
|
||||
keys.onKeyFailure('quota', 'API key 额度已用完', first.key)
|
||||
await new Promise(resolve => { setTimeout(resolve, 10) })
|
||||
assert.equal((await ring.list()).keys.find(entry => entry.id === first.id).disabled, true)
|
||||
})
|
||||
|
||||
test('hosts keep only an https origin; plain http only on loopback', () => {
|
||||
assert.equal(normalizeHost('https://hk.geek2api.com/v1', undefined), 'https://hk.geek2api.com')
|
||||
assert.equal(normalizeHost('https://hk.geek2api.com/v1/', undefined), 'https://hk.geek2api.com')
|
||||
assert.equal(normalizeHost('http://hk.geek2api.com', undefined), undefined)
|
||||
assert.equal(normalizeHost('http://127.0.0.1:8080/x', undefined), 'http://127.0.0.1:8080')
|
||||
assert.equal(normalizeHost('http://localhost:3000', undefined), 'http://localhost:3000')
|
||||
assert.deepEqual(normalizeHostList(['https://a.example/v1', 'https://a.example', 'http://evil.example']), ['https://a.example'])
|
||||
})
|
||||
|
||||
test('a timeout or an HTTP answer does not set a host aside', () => {
|
||||
const timedOut = new TransportError(new Error('aborted'), { aborted: false, timedOut: true, timeoutMs: 1000 })
|
||||
assert.equal(isTransportFailure(timedOut), false)
|
||||
assert.equal(isTransportFailure('OpenAI API error (502): TLS handshake timeout'), false)
|
||||
assert.equal(isTransportFailure('502 Bad Gateway: certificate error upstream'), false)
|
||||
assert.equal(isTransportFailure('fetch failed'), true)
|
||||
assert.equal(isTransportFailure('Connection error.'), true)
|
||||
})
|
||||
|
||||
test('an inactive subscription is shown as such, not as an unrecognized payload', () => {
|
||||
const usage = parseKeyUsage({ mode: 'unrestricted', isValid: true, planName: 'Plus', unit: 'USD', key: { name: 'k' } })
|
||||
assert.equal(usage.mode, 'subscription')
|
||||
assert.equal(usage.inactive, true)
|
||||
assert.equal(usage.availableUsd, 0)
|
||||
assert.equal(usage.planName, 'Plus')
|
||||
})
|
||||
|
||||
test('a key with only rate windows is not called unlimited', () => {
|
||||
const usage = parseKeyUsage({ mode: 'quota_limited', isValid: true, status: 'active', rate_limits: [{ window: '5h', limit: 5, used: 1, remaining: 4 }] })
|
||||
assert.equal(usage.unlimitedQuota, false)
|
||||
assert.equal(usage.availableUsd, undefined)
|
||||
assert.deepEqual(usage.rateLimits, [{ window: '5h', limitUsd: 5, usedUsd: 1, remainingUsd: 4 }])
|
||||
})
|
||||
@@ -197,7 +197,7 @@ test('an exhausted key moves aside through the shared sink and the next key answ
|
||||
assert.equal(result.sources.length, 2)
|
||||
assert.deepEqual(used, ['sk-first-key-0001', 'sk-second-key-0002'])
|
||||
assert.equal(failures.length, 1)
|
||||
assert.equal(failures[0].kind, 'quota')
|
||||
assert.equal(failures[0].kind, 'exhausted')
|
||||
assert.equal(failures[0].key, 'sk-first-key-0001')
|
||||
assert.equal(typeof failures[0].id, 'string')
|
||||
})
|
||||
@@ -234,7 +234,7 @@ test('a client-policy refusal is explained and blames no key', async () => {
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
onKeyFailure: kind => failures.push(kind),
|
||||
fetchImpl: async () => json(403, { error: { message: '请使用标准 codex 客户端' } }),
|
||||
fetchImpl: async () => json(403, { error: { message: 'This API endpoint is only accessible via the official Claude CLI' } }),
|
||||
})
|
||||
await assert.rejects(provider.search({ query: 'q' }), /拒绝了这个客户端/u)
|
||||
assert.deepEqual(failures, [])
|
||||
|
||||
+20
-7
@@ -3,20 +3,32 @@ import test from 'node:test'
|
||||
|
||||
import { sumBalances } from '../src/totals.js'
|
||||
|
||||
test('adds the per-key quotas a balance read returned', () => {
|
||||
test('a key quota is a cap on the wallet, not money: it stays out of the sums', () => {
|
||||
const rows = [
|
||||
{ id: 'a', usage: { mode: 'quota', availableUsd: 499.07, usedUsd: 0.93, limitUsd: 500 } },
|
||||
{ id: 'b', usage: { mode: 'subscription', planName: 'Plus', availableUsd: 500, usedUsd: 0, limitUsd: 500, resetPeriod: 'monthly' } },
|
||||
]
|
||||
const totals = sumBalances(rows)
|
||||
assert.equal(totals.counted, 2)
|
||||
assert.equal(Math.round(totals.remainingUsd * 100) / 100, 999.07)
|
||||
assert.equal(Math.round(totals.usedUsd * 100) / 100, 0.93)
|
||||
assert.equal(totals.limitUsd, 1000)
|
||||
assert.equal(totals.capped, 1)
|
||||
assert.equal(totals.remainingUsd, 500)
|
||||
assert.equal(totals.usedUsd, 0)
|
||||
assert.equal(totals.limitUsd, 500)
|
||||
assert.equal(totals.unread, 0)
|
||||
assert.equal(totals.unlimited, 0)
|
||||
})
|
||||
|
||||
test('keys on the same subscription plan count it once', () => {
|
||||
const totals = sumBalances([
|
||||
{ id: 'a', usage: { mode: 'subscription', planName: 'Plus', availableUsd: 30, usedUsd: 20, limitUsd: 50 } },
|
||||
{ id: 'b', usage: { mode: 'subscription', planName: 'Plus', availableUsd: 30, usedUsd: 20, limitUsd: 50 } },
|
||||
{ id: 'c', usage: { mode: 'subscription', planName: 'Max', availableUsd: 100, usedUsd: 0, limitUsd: 100 } },
|
||||
])
|
||||
assert.equal(totals.shared, 1)
|
||||
assert.equal(totals.remainingUsd, 130)
|
||||
assert.equal(totals.limitUsd, 150)
|
||||
})
|
||||
|
||||
test('counts only what it can read and reports the rest', () => {
|
||||
const rows = [
|
||||
{ id: 'a', usage: { availableUsd: 10, usedUsd: 1, limitUsd: 11 } },
|
||||
@@ -46,7 +58,7 @@ test('a key without a period limit contributes only what it reports', () => {
|
||||
})
|
||||
|
||||
test('an empty or malformed row list totals to zero', () => {
|
||||
assert.deepEqual(sumBalances([]), { keys: 0, counted: 0, unread: 0, unlimited: 0, shared: 0, remainingUsd: 0, usedUsd: 0, limitUsd: 0 })
|
||||
assert.deepEqual(sumBalances([]), { keys: 0, counted: 0, unread: 0, unlimited: 0, shared: 0, capped: 0, remainingUsd: 0, usedUsd: 0, limitUsd: 0 })
|
||||
assert.equal(sumBalances(undefined).keys, 0)
|
||||
assert.equal(sumBalances([null, 7]).keys, 2)
|
||||
assert.equal(sumBalances([null, 7]).counted, 0)
|
||||
@@ -72,6 +84,7 @@ test('without an account reference, wallets with the same balance are the same w
|
||||
{ id: 'd', usage: { mode: 'quota', availableUsd: 4226.232196, limitUsd: 5000 } },
|
||||
])
|
||||
assert.equal(totals.shared, 1)
|
||||
assert.equal(Math.round((totals.remainingUsd) * 1e6) / 1e6, Math.round((4226.232196 * 2 + 12.5) * 1e6) / 1e6, 'a key quota is its own money')
|
||||
assert.equal(totals.limitUsd, 5000)
|
||||
assert.equal(Math.round((totals.remainingUsd) * 1e6) / 1e6, Math.round((4226.232196 + 12.5) * 1e6) / 1e6, 'one wallet, counted once; the key cap is not money')
|
||||
assert.equal(totals.capped, 1)
|
||||
assert.equal(totals.limitUsd, 0)
|
||||
})
|
||||
Reference in new issue
Block a user