diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml deleted file mode 100644 index 280b2ca..0000000 --- a/.github/workflows/publish.yml +++ /dev/null @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..47a101a --- /dev/null +++ b/.github/workflows/release.yml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 845f9d3..4fb4de6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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-.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 # must fail ``` - Fast-forward clean remote changes before editing. Never discard remote changes. +2. Update `package.json` version and add a `## ` 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 --json - git ls-remote --exit-code --tags origin refs/tags/v - ``` - - 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-.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 `/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 -m "dsh-geek2api v" git push origin v ``` - `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-.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. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3280016..ba706a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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-.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. diff --git a/README.en.md b/README.en.md index d4d0429..9dbe96a 100644 --- a/README.en.md +++ b/README.en.md @@ -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 diff --git a/README.md b/README.md index f984e24..037df83 100644 --- a/README.md +++ b/README.md @@ -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` 标记的那一段即可。 diff --git a/lib/client.js b/lib/client.js index b98cc16..30ebde4 100644 --- a/lib/client.js +++ b/lib/client.js @@ -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") }), diff --git a/lib/index.js b/lib/index.js index 1060646..1058f39 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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, diff --git a/package.json b/package.json index 64cd811..079d7ed 100644 --- a/package.json +++ b/package.json @@ -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" }, diff --git a/src/balance.js b/src/balance.js index 149eb6d..5d609d6 100644 --- a/src/balance.js +++ b/src/balance.js @@ -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() } } diff --git a/src/claude-adapter.js b/src/claude-adapter.js index ad368da..ee9f420 100644 --- a/src/claude-adapter.js +++ b/src/claude-adapter.js @@ -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' }) diff --git a/src/claude-cli.js b/src/claude-cli.js index f7a63db..7092453 100644 --- a/src/claude-cli.js +++ b/src/claude-cli.js @@ -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 diff --git a/src/client-copy.js b/src/client-copy.js index b6c3226..15bb0ae 100644 --- a/src/client-copy.js +++ b/src/client-copy.js @@ -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.', diff --git a/src/client-style.js b/src/client-style.js index 699eeff..1a71fef 100644 --- a/src/client-style.js +++ b/src/client-style.js @@ -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} diff --git a/src/client.jsx b/src/client.jsx index 052d58a..eeb526e 100644 --- a/src/client.jsx +++ b/src/client.jsx @@ -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 ) : {entry.label}} {entry.active && {t('keyActive')}} + {!entry.disabled && skippedUntil !== undefined && {t('keySkipped')}} {entry.disabled && {entry.disabledReason ? `${t('keyDisabled')} · ${entry.disabledReason}` : t('keyDisabled')}} {!editing && ( @@ -377,10 +385,11 @@ function AccountsCard({ call, t }) { - {(totals.unread > 0 || staleCount > 0 || totals.shared > 0) && ( + {(totals.unread > 0 || staleCount > 0 || totals.shared > 0 || totals.capped > 0) && (

{[ 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 ( {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')} ))} -

event.currentTarget.open && draft === undefined && setDraft(hosts.map(entry => entry.host).join('\n'))}> +
setEditing(event.currentTarget.open)}> {t('hostsEdit')}

{t('hostsEditHint')}