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:
大阔andClaude Opus 5.5 committed 2026-10-15 01:15:24 +08:00
1 parent 86b8e4d24f
commit f4f4ce55b3
34 files changed
+953 -521

No files matched your search

+236 -106
View File
@@ -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,