fix: review fixes, GitHub Releases update check (0.1.1)
- Wallet/subscription/window exhaustion skips a key for 10 minutes instead of disabling it; a balance read showing money brings it back. Only the gateway's own key refusals and a used-up key cap still disable a key. - Classify by sub2api's exact wording; a bare 401 or upstream text no longer retires a key; 'No available accounts' is capacity, not coverage. - Hosts keep only an https origin (no doubled /v1); timeouts and HTTP answers no longer set a host aside; hand edits are re-probed. - Balance: inactive subscriptions, per-plan subscription pooling, key caps kept out of the total, rate windows shown. - Endpoint editor no longer empties itself after Save. - Update check reads GitHub Releases and installs the release tarball; release workflow replaces npm publishing. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
86b8e4d24f
commit
f4f4ce55b3
34 files changed
+953
-521
No files matched your search
+90
-29
@@ -46,12 +46,14 @@ window.__ModuleLoader__.load({
|
||||
totalLimit: "合计额度",
|
||||
totalPartial: "有 {count} 个 Key 未读到余额,未计入合计。",
|
||||
totalStale: "其中 {count} 个 Key 本次读取失败,显示的是上次读到的余额。",
|
||||
totalShared: "{count} 个 Key 与其他 Key 共用同一个钱包,只计一次。",
|
||||
totalShared: "{count} 个 Key 与其他 Key 共用同一个钱包或订阅,只计一次。",
|
||||
totalCapped: "{count} 个 Key 设有自己的限额,它们花的是账户钱包,限额不计入合计。",
|
||||
staleNote: "上次读取于 {time},本次读取失败:{error}",
|
||||
empty: "还没有 Key。添加一个即可在模型选择器里看到 Geek2API 的模型。",
|
||||
keysHint: "按顺序使用:当前 Key 不可用时自动切到下一个;「切到此 Key」指定优先使用的 Key。",
|
||||
keyActive: "使用中",
|
||||
keyDisabled: "已停用",
|
||||
keySkipped: "余额不足,暂时跳过",
|
||||
keyUse: "切到此 Key",
|
||||
keyEnable: "重新启用",
|
||||
keyRemove: "删除",
|
||||
@@ -69,7 +71,10 @@ window.__ModuleLoader__.load({
|
||||
keyToday: "今日",
|
||||
planWallet: "钱包余额(同账户的 Key 共用)",
|
||||
planSubscription: "订阅:{name}",
|
||||
planQuota: "Key 限额",
|
||||
planQuota: "Key 限额(从账户钱包扣费)",
|
||||
planSubscriptionInactive: "订阅:{name}(未开通或已过期)",
|
||||
keyCapRemaining: "Key 剩余限额",
|
||||
keyWindow: "{window} 窗口 {used}/{limit}",
|
||||
keyExpires: "{date} 到期",
|
||||
resetMonthly: "每月重置",
|
||||
resetWeekly: "每周重置",
|
||||
@@ -80,7 +85,7 @@ window.__ModuleLoader__.load({
|
||||
addKeyPlaceholder: "粘贴 API Key",
|
||||
addLabelPlaceholder: "备注(可选)",
|
||||
add: "添加",
|
||||
notWritable: "当前 profile 不允许写入设置,改动只在本次运行内生效。",
|
||||
notWritable: "当前 profile 不允许写入设置,这些选项暂时不能修改。",
|
||||
error: "读取 Geek2API 状态失败",
|
||||
groupsTitle: "分组",
|
||||
groupsExtra: "另有 {count} 个模型不在内置列表中",
|
||||
@@ -108,7 +113,7 @@ window.__ModuleLoader__.load({
|
||||
hostsCooling: "暂时跳过",
|
||||
hostsUnprobed: "未测速",
|
||||
hostsEdit: "编辑地址列表",
|
||||
hostsEditHint: "每行一个地址,按优先顺序排列。留空则恢复默认列表。",
|
||||
hostsEditHint: "每行一个地址(只取域名部分,必须是 https),按优先顺序排列。要恢复内置列表请点「恢复默认」。",
|
||||
hostsSave: "保存",
|
||||
hostsReset: "恢复默认",
|
||||
composerLabel: "Geek2API 剩余额度",
|
||||
@@ -152,7 +157,8 @@ window.__ModuleLoader__.load({
|
||||
versionUpToDate: "已是最新版本",
|
||||
versionAvailable: "发现新版本 v{version}",
|
||||
versionLinked: "当前是本地开发安装,请在插件仓库拉取代码并重新构建。",
|
||||
versionManual: "无法在这里更新。请在桌面应用的插件页重新安装 dsh-geek2api。",
|
||||
versionManual: "无法在这里自动更新。请到 GitHub Releases 下载新版本,在桌面应用的插件页重新安装。",
|
||||
versionNotes: "更新说明",
|
||||
versionUpdate: "更新插件",
|
||||
versionUpdating: "正在更新…",
|
||||
versionUpdateFailed: "更新失败,请重试,或在插件页重新安装。",
|
||||
@@ -208,12 +214,14 @@ window.__ModuleLoader__.load({
|
||||
totalLimit: "Total limit",
|
||||
totalPartial: "{count} key(s) could not be read and are not counted here.",
|
||||
totalStale: "{count} of these keys failed this read and show their last read balance.",
|
||||
totalShared: "{count} key(s) share a wallet with another key and are counted once.",
|
||||
totalShared: "{count} key(s) share a wallet or subscription with another key and are counted once.",
|
||||
totalCapped: "{count} key(s) have their own cap; they spend the account wallet, so caps are not added to the total.",
|
||||
staleNote: "Last read at {time}; this read failed: {error}",
|
||||
empty: "No keys yet. Add one and the Geek2API models appear in the model picker.",
|
||||
keysHint: "Used in order: when the active key cannot serve a request, the next one takes over. “Use this key” picks the preferred key.",
|
||||
keyActive: "Active",
|
||||
keyDisabled: "Disabled",
|
||||
keySkipped: "Out of balance, skipped for now",
|
||||
keyUse: "Use this key",
|
||||
keyEnable: "Re-enable",
|
||||
keyRemove: "Remove",
|
||||
@@ -231,7 +239,10 @@ window.__ModuleLoader__.load({
|
||||
keyToday: "Today",
|
||||
planWallet: "Wallet (shared by the account’s keys)",
|
||||
planSubscription: "Subscription: {name}",
|
||||
planQuota: "Key quota",
|
||||
planQuota: "Key quota (spends the account wallet)",
|
||||
planSubscriptionInactive: "Subscription: {name} (not active)",
|
||||
keyCapRemaining: "Cap left",
|
||||
keyWindow: "{window} window {used}/{limit}",
|
||||
keyExpires: "expires {date}",
|
||||
resetMonthly: "resets monthly",
|
||||
resetWeekly: "resets weekly",
|
||||
@@ -242,7 +253,7 @@ window.__ModuleLoader__.load({
|
||||
addKeyPlaceholder: "Paste API key",
|
||||
addLabelPlaceholder: "Label (optional)",
|
||||
add: "Add",
|
||||
notWritable: "This profile does not allow settings writes; changes apply to this run only.",
|
||||
notWritable: "This profile does not allow settings writes; these options cannot be changed here.",
|
||||
error: "Could not read Geek2API status",
|
||||
groupsTitle: "Groups",
|
||||
groupsExtra: "{count} more model(s) outside the built-in list",
|
||||
@@ -262,7 +273,7 @@ window.__ModuleLoader__.load({
|
||||
hostsCooling: "skipped for now",
|
||||
hostsUnprobed: "not measured",
|
||||
hostsEdit: "Edit endpoint list",
|
||||
hostsEditHint: "One endpoint per line, in order of preference. Leave empty to restore the defaults.",
|
||||
hostsEditHint: "One endpoint per line (origin only, https), in order of preference. Use Restore defaults to go back to the built-in list.",
|
||||
hostsSave: "Save",
|
||||
hostsReset: "Restore defaults",
|
||||
composerLabel: "Geek2API remaining balance",
|
||||
@@ -306,7 +317,8 @@ window.__ModuleLoader__.load({
|
||||
versionUpToDate: "Up to date",
|
||||
versionAvailable: "v{version} is available",
|
||||
versionLinked: "Installed from a local checkout. Pull and rebuild the plugin repository instead.",
|
||||
versionManual: "This install cannot be updated here. Reinstall dsh-geek2api from the desktop Plugins page.",
|
||||
versionManual: "This install cannot update itself. Download the new version from GitHub Releases and reinstall it from the Plugins page.",
|
||||
versionNotes: "Release notes",
|
||||
versionUpdate: "Update plugin",
|
||||
versionUpdating: "Updating…",
|
||||
versionUpdateFailed: "The update failed. Try again, or reinstall from the Plugins page.",
|
||||
@@ -381,6 +393,8 @@ window.__ModuleLoader__.load({
|
||||
.pkc-input:focus{border-color:var(--dsw-alias-state-business-primary)}
|
||||
.pkc-input::placeholder{color:var(--dsw-alias-label-caption)}
|
||||
.pkc-input:disabled{opacity:.5}
|
||||
.pkc-link{color:var(--dsw-alias-state-business-primary);font-size:12px;text-decoration:none}
|
||||
.pkc-link:hover{text-decoration:underline}
|
||||
.pkc-textarea{display:block;width:100%;height:auto;min-height:96px;padding:8px 10px;line-height:1.6;resize:vertical;white-space:pre;overflow-x:auto}
|
||||
.pkc-form{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
||||
|
||||
@@ -464,17 +478,21 @@ window.__ModuleLoader__.load({
|
||||
/**
|
||||
* Totals across the keys a balance read returned.
|
||||
*
|
||||
* Keys of one Geek2API account spend the same wallet, so a wallet is counted
|
||||
* once however many of its keys are stored. Two wallet rows are the same
|
||||
* wallet when the gateway names the same account (`accountRef`) or, when it
|
||||
* names none, when they report the same balance to the micro-dollar. Key
|
||||
* quotas and subscriptions are the key's own and add up.
|
||||
* In sub2api money belongs to the account, not the key:
|
||||
* - every wallet key of one account spends the same wallet, counted once —
|
||||
* the same wallet when the gateway names the same account (`accountRef`)
|
||||
* or, when it names none, when the balances agree to the micro-dollar;
|
||||
* - a subscription belongs to the user and its group, so keys on the same
|
||||
* plan count it once;
|
||||
* - a key quota is a cap on top of the wallet, not money of its own, so it
|
||||
* is left out of the sums and reported as `capped`.
|
||||
*
|
||||
* @module dsh-geek2api/totals
|
||||
*/
|
||||
const amount = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
||||
/** Which pool of money a row draws on; rows with the same pool count once. */
|
||||
function poolOf(row, usage) {
|
||||
if (usage.mode === "subscription") return `subscription:${usage.planName ?? row?.id}`;
|
||||
if (usage.mode !== "wallet") return `key:${row?.id}`;
|
||||
if (typeof usage.accountRef === "string") return `account:${usage.accountRef}`;
|
||||
const remaining = amount(usage.availableUsd);
|
||||
@@ -484,8 +502,8 @@ window.__ModuleLoader__.load({
|
||||
* Add up the balance rows the host returned.
|
||||
* @param rows - the `keys` array of a balance projection.
|
||||
* @returns summed amounts plus the conditions that make a sum incomplete:
|
||||
* keys whose read failed, keys with no limit at all, and how many wallet
|
||||
* rows were folded into a wallet already counted.
|
||||
* keys whose read failed, keys with no limit at all, rows folded into a
|
||||
* pool already counted, and key caps left out of the sum.
|
||||
*/
|
||||
function sumBalances(rows) {
|
||||
const total = {
|
||||
@@ -494,6 +512,7 @@ window.__ModuleLoader__.load({
|
||||
unread: 0,
|
||||
unlimited: 0,
|
||||
shared: 0,
|
||||
capped: 0,
|
||||
remainingUsd: 0,
|
||||
usedUsd: 0,
|
||||
limitUsd: 0
|
||||
@@ -507,6 +526,10 @@ window.__ModuleLoader__.load({
|
||||
continue;
|
||||
}
|
||||
total.counted += 1;
|
||||
if (usage.mode === "quota") {
|
||||
total.capped += 1;
|
||||
continue;
|
||||
}
|
||||
const pool = poolOf(row, usage);
|
||||
if (seen.has(pool)) {
|
||||
total.shared += 1;
|
||||
@@ -619,6 +642,7 @@ window.__ModuleLoader__.load({
|
||||
/** What a key draws on: the shared wallet, a subscription plan, or its own quota. */
|
||||
function planLabel(usage, t) {
|
||||
if (usage?.mode === "wallet") return t("planWallet");
|
||||
if (usage?.mode === "subscription" && usage.inactive === true) return fill(t("planSubscriptionInactive"), { name: usage.planName ?? "" });
|
||||
if (usage?.mode === "subscription") return fill(t("planSubscription"), { name: usage.planName ?? "" });
|
||||
if (usage?.mode === "quota") return t("planQuota");
|
||||
}
|
||||
@@ -735,11 +759,12 @@ window.__ModuleLoader__.load({
|
||||
})
|
||||
] });
|
||||
}
|
||||
function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, t }) {
|
||||
function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, skippedUntil, t }) {
|
||||
const usage = row?.usage;
|
||||
const share = remainingShare(usage);
|
||||
const remainingLabel = usage?.mode === "quota" ? t("keyCapRemaining") : t("keyRemaining");
|
||||
const figures = [
|
||||
usage?.unlimitedQuota === true ? [t("keyRemaining"), t("keyUnlimited")] : usage?.availableUsd === void 0 ? void 0 : [t("keyRemaining"), formatUsd(usage.availableUsd)],
|
||||
usage?.unlimitedQuota === true ? [remainingLabel, t("keyUnlimited")] : usage?.availableUsd === void 0 ? void 0 : [remainingLabel, formatUsd(usage.availableUsd)],
|
||||
usage?.usedUsd === void 0 ? void 0 : [t("keyUsed"), formatUsd(usage.usedUsd)],
|
||||
usage?.limitUsd === void 0 ? void 0 : [t("accountLimit"), formatUsd(usage.limitUsd)]
|
||||
].filter(Boolean);
|
||||
@@ -748,7 +773,12 @@ window.__ModuleLoader__.load({
|
||||
usage?.keyName === void 0 ? void 0 : `${t("keyName")} ${usage.keyName}`,
|
||||
resetLabel(usage?.resetPeriod, t),
|
||||
usage?.todayUsd === void 0 ? void 0 : `${t("keyToday")} ${formatUsd(usage.todayUsd)}`,
|
||||
usage?.expiresAt === void 0 ? void 0 : fill(t("keyExpires"), { date: new Date(usage.expiresAt).toLocaleDateString() })
|
||||
usage?.expiresAt === void 0 ? void 0 : fill(t("keyExpires"), { date: new Date(usage.expiresAt).toLocaleDateString() }),
|
||||
...Array.isArray(usage?.rateLimits) ? usage.rateLimits.map((window) => fill(t("keyWindow"), {
|
||||
window: window.window,
|
||||
used: formatUsd(window.usedUsd) ?? "?",
|
||||
limit: formatUsd(window.limitUsd) ?? "?"
|
||||
})) : []
|
||||
].filter(Boolean).join(" · ");
|
||||
const editing = renaming?.id === entry.id;
|
||||
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
||||
@@ -797,6 +827,11 @@ window.__ModuleLoader__.load({
|
||||
"data-tone": "success",
|
||||
children: t("keyActive")
|
||||
}),
|
||||
!entry.disabled && skippedUntil !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
||||
className: "pkc-chip",
|
||||
"data-tone": "warn",
|
||||
children: t("keySkipped")
|
||||
}),
|
||||
entry.disabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
||||
className: "pkc-chip",
|
||||
"data-tone": "danger",
|
||||
@@ -999,10 +1034,11 @@ window.__ModuleLoader__.load({
|
||||
})
|
||||
]
|
||||
}),
|
||||
(totals.unread > 0 || staleCount > 0 || totals.shared > 0) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
(totals.unread > 0 || staleCount > 0 || totals.shared > 0 || totals.capped > 0) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
className: "pkc-note",
|
||||
children: [
|
||||
totals.shared > 0 ? fill(t("totalShared"), { count: totals.shared }) : void 0,
|
||||
totals.capped > 0 ? fill(t("totalCapped"), { count: totals.capped }) : void 0,
|
||||
totals.unread > 0 ? fill(t("totalPartial"), { count: totals.unread }) : void 0,
|
||||
staleCount > 0 ? fill(t("totalStale"), { count: staleCount }) : void 0
|
||||
].filter(Boolean).join(" ")
|
||||
@@ -1019,6 +1055,7 @@ window.__ModuleLoader__.load({
|
||||
renaming,
|
||||
onRename: rename,
|
||||
onAction: mutate,
|
||||
skippedUntil: status?.skipped?.[entry.id],
|
||||
t
|
||||
}, entry.id))
|
||||
}),
|
||||
@@ -1085,16 +1122,33 @@ window.__ModuleLoader__.load({
|
||||
const [busy, setBusy] = react.useState(false);
|
||||
const [error, setError] = react.useState();
|
||||
const [draft, setDraft] = react.useState();
|
||||
const [editing, setEditing] = react.useState(false);
|
||||
const run = react.useCallback((endpoint, payload) => {
|
||||
setBusy(true);
|
||||
setError(void 0);
|
||||
return call(endpoint, payload).then(setStatus).catch((failure) => setError(clearMessage(failure))).finally(() => setBusy(false));
|
||||
return call(endpoint, payload).then((next) => {
|
||||
setStatus(next);
|
||||
return next;
|
||||
}).catch((failure) => {
|
||||
setError(clearMessage(failure));
|
||||
}).finally(() => setBusy(false));
|
||||
}, [call]);
|
||||
react.useEffect(() => {
|
||||
run("hosts/probe", {});
|
||||
}, [run]);
|
||||
const hosts = Array.isArray(status?.hosts) ? status.hosts : [];
|
||||
const save = (list) => run("hosts/update", { apiHosts: list }).then(() => setDraft(void 0));
|
||||
const listText = (list) => Array.isArray(list) ? list.map((entry) => entry.host).join("\n") : "";
|
||||
react.useEffect(() => {
|
||||
if (editing && draft === void 0 && hosts.length > 0) setDraft(listText(hosts));
|
||||
}, [
|
||||
editing,
|
||||
draft,
|
||||
hosts
|
||||
]);
|
||||
const save = (list) => run("hosts/update", { apiHosts: list }).then((next) => {
|
||||
if (next !== void 0) setDraft(listText(next.hosts));
|
||||
});
|
||||
const draftHosts = (draft ?? "").split(/\s+/u).filter(Boolean);
|
||||
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
|
||||
title: t("hostsTitle"),
|
||||
aside: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
|
||||
@@ -1127,14 +1181,14 @@ window.__ModuleLoader__.load({
|
||||
}),
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
||||
className: "pkc-meta",
|
||||
children: entry.coolingUntil !== void 0 ? t("hostsCooling") : entry.latencyMs !== void 0 ? `${entry.latencyMs} ms` : t("hostsDown")
|
||||
children: entry.coolingUntil !== void 0 ? t("hostsCooling") : entry.latencyMs !== void 0 ? `${entry.latencyMs} ms` : entry.probed === false ? t("hostsUnprobed") : t("hostsDown")
|
||||
})
|
||||
]
|
||||
}, entry.host))
|
||||
}),
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", {
|
||||
className: "pkc-advanced",
|
||||
onToggle: (event) => event.currentTarget.open && draft === void 0 && setDraft(hosts.map((entry) => entry.host).join("\n")),
|
||||
onToggle: (event) => setEditing(event.currentTarget.open),
|
||||
children: [
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", { children: t("hostsEdit") }),
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
@@ -1152,8 +1206,8 @@ window.__ModuleLoader__.load({
|
||||
className: "pkc-split",
|
||||
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
|
||||
variant: "primary",
|
||||
disabled: status?.writable !== true || busy,
|
||||
onClick: () => save((draft ?? "").split(/\s+/u).filter(Boolean)),
|
||||
disabled: status?.writable !== true || busy || draftHosts.length === 0,
|
||||
onClick: () => save(draftHosts),
|
||||
children: t("hostsSave")
|
||||
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
|
||||
variant: "ghost",
|
||||
@@ -1657,7 +1711,7 @@ window.__ModuleLoader__.load({
|
||||
};
|
||||
const installKind = info?.install?.kind;
|
||||
const showStatus = info !== void 0 && updated === void 0;
|
||||
const canUpdate = showStatus && info.updateAvailable && installKind === "npm";
|
||||
const canUpdate = showStatus && info.updateAvailable && (info.updatable === true || info.updatable === void 0 && installKind === "npm");
|
||||
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
|
||||
title: t("versionTitle"),
|
||||
aside: updated === void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
|
||||
@@ -1696,6 +1750,13 @@ window.__ModuleLoader__.load({
|
||||
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
|
||||
className: "pkc-meta",
|
||||
children: [info.updateAvailable ? fill(t("versionAvailable"), { version: info.latest }) : t("versionUpToDate"), info.updateAvailable && ` · ${t("versionLatest")} v${info.latest}`]
|
||||
}),
|
||||
info.releaseUrl !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
|
||||
className: "pkc-link",
|
||||
href: info.releaseUrl,
|
||||
target: "_blank",
|
||||
rel: "noreferrer noopener",
|
||||
children: t("versionNotes")
|
||||
})
|
||||
]
|
||||
}),
|
||||
@@ -1703,7 +1764,7 @@ window.__ModuleLoader__.load({
|
||||
className: "pkc-note",
|
||||
children: t("versionLinked")
|
||||
}),
|
||||
showStatus && info.updateAvailable && installKind === "unknown" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
showStatus && info.updateAvailable && !canUpdate && installKind !== "link" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||
className: "pkc-note",
|
||||
children: t("versionManual")
|
||||
}),
|
||||
|
||||
+236
-106
@@ -306,14 +306,15 @@ function parseKeyUsage(payload) {
|
||||
if (payload.mode === "quota_limited") {
|
||||
const quota = record$3(payload.quota) ? payload.quota : void 0;
|
||||
const expiresAt = timestamp(payload.expires_at);
|
||||
const rateLimits = parseRateLimits(payload.rate_limits);
|
||||
return defined({
|
||||
...common,
|
||||
mode: "quota",
|
||||
unlimitedQuota: quota === void 0,
|
||||
unlimitedQuota: quota === void 0 && rateLimits === void 0,
|
||||
limitUsd: usd(quota?.limit),
|
||||
usedUsd: usd(quota?.used),
|
||||
availableUsd: usd(quota?.remaining ?? payload.remaining),
|
||||
rateLimits: parseRateLimits(payload.rate_limits),
|
||||
rateLimits,
|
||||
expiresAt
|
||||
});
|
||||
}
|
||||
@@ -330,7 +331,14 @@ function parseKeyUsage(payload) {
|
||||
expiresAt: timestamp(payload.subscription.expires_at)
|
||||
});
|
||||
}
|
||||
if (payload.mode === "unrestricted" && record$3(payload) && (payload.balance !== void 0 || payload.remaining !== void 0)) return defined({
|
||||
if (payload.mode === "unrestricted" && payload.balance === void 0 && payload.remaining === void 0 && common.planName !== void 0) return defined({
|
||||
...common,
|
||||
mode: "subscription",
|
||||
inactive: true,
|
||||
unlimitedQuota: false,
|
||||
availableUsd: 0
|
||||
});
|
||||
if (payload.mode === "unrestricted" && (payload.balance !== void 0 || payload.remaining !== void 0)) return defined({
|
||||
...common,
|
||||
mode: "wallet",
|
||||
unlimitedQuota: false,
|
||||
@@ -354,7 +362,7 @@ function statusMessage(status) {
|
||||
* @param options - key listing, the host pool, and transport knobs.
|
||||
* @returns `{ read({force, signal}), invalidate() }`.
|
||||
*/
|
||||
function createBalanceReader({ listKeys, hosts, fetchImpl = ambientFetch, now = Date.now, ttlMs = DEFAULT_BALANCE_TTL_MS, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS } = {}) {
|
||||
function createBalanceReader({ listKeys, hosts, fetchImpl = ambientFetch, now = Date.now, ttlMs = DEFAULT_BALANCE_TTL_MS, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, onRead } = {}) {
|
||||
if (typeof listKeys !== "function") throw new Error("Geek2API balance reader requires listKeys");
|
||||
if (typeof hosts?.withFailover !== "function") throw new Error("Geek2API balance reader requires a host pool");
|
||||
/** Last successful per-key usage, by key id. */
|
||||
@@ -386,40 +394,44 @@ function createBalanceReader({ listKeys, hosts, fetchImpl = ambientFetch, now =
|
||||
signal?.throwIfAborted();
|
||||
const keys = await listKeys();
|
||||
for (const id of lastGood.keys()) if (!keys.some((entry) => entry.id === id)) lastGood.delete(id);
|
||||
return {
|
||||
keys: await Promise.all(keys.map(async (entry) => {
|
||||
const base = {
|
||||
id: entry.id,
|
||||
label: entry.label,
|
||||
disabled: entry.disabled === true
|
||||
const entries = await Promise.all(keys.map(async (entry) => {
|
||||
const base = {
|
||||
id: entry.id,
|
||||
label: entry.label,
|
||||
disabled: entry.disabled === true
|
||||
};
|
||||
try {
|
||||
const usage = await loadKey(entry, signal);
|
||||
lastGood.set(entry.id, {
|
||||
usage,
|
||||
fetchedAt: now()
|
||||
});
|
||||
return {
|
||||
...base,
|
||||
usage
|
||||
};
|
||||
try {
|
||||
const usage = await loadKey(entry, signal);
|
||||
lastGood.set(entry.id, {
|
||||
usage,
|
||||
fetchedAt: now()
|
||||
});
|
||||
return {
|
||||
...base,
|
||||
usage
|
||||
};
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const previous = lastGood.get(entry.id);
|
||||
return previous === void 0 ? {
|
||||
...base,
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const previous = lastGood.get(entry.id);
|
||||
return previous === void 0 ? {
|
||||
...base,
|
||||
error: message
|
||||
} : {
|
||||
...base,
|
||||
usage: previous.usage,
|
||||
stale: {
|
||||
fetchedAt: previous.fetchedAt,
|
||||
error: message
|
||||
} : {
|
||||
...base,
|
||||
usage: previous.usage,
|
||||
stale: {
|
||||
fetchedAt: previous.fetchedAt,
|
||||
error: message
|
||||
}
|
||||
};
|
||||
}
|
||||
})),
|
||||
}
|
||||
};
|
||||
}
|
||||
}));
|
||||
try {
|
||||
onRead?.(entries);
|
||||
} catch {}
|
||||
return {
|
||||
keys: entries,
|
||||
hosts: hosts.status(),
|
||||
fetchedAt: now()
|
||||
};
|
||||
@@ -688,7 +700,7 @@ function modelForHost(catalogModel, host) {
|
||||
//#endregion
|
||||
//#region src/failures.js
|
||||
/**
|
||||
* Failure classification for the two conditions that move the key ring along.
|
||||
* Failure classification for the conditions that move the key ring along.
|
||||
*
|
||||
* The gateway reports an exhausted key and a rejected key in Chinese, and the
|
||||
* harness classifies failures by fixed English/status wording it recognizes
|
||||
@@ -700,24 +712,39 @@ function modelForHost(catalogModel, host) {
|
||||
*
|
||||
* @module dsh-geek2api/failures
|
||||
*/
|
||||
/** Terminal quota, balance, or credit wording, in the gateway's own languages. */
|
||||
const QUOTA_WORDING = /额度|余额|配额|欠费|insufficient[\s_-]+(?:quota|balance|credits?)|quota[\s_-]+(?:exceeded|exhausted|reached)|out[\s_-]+of[\s_-]+(?:credits?|budget)|no active subscription|INSUFFICIENT_BALANCE/iu;
|
||||
/** A rejected key names itself; a bare 403 does not, and must not disable one. */
|
||||
const INVALID_KEY_WORDING = /无效的令牌|令牌无效|无效密钥|密钥无效|invalid[\s_-]+api[\s_-]*key|invalid_authentication|api key is invalid|api key is disabled|api key\s*已过期|API_KEY_(?:DISABLED|EXPIRED)|user account is not active|所属分组已删除|所属专属分组不再允许|GROUP_NOT_ALLOWED/iu;
|
||||
const INVALID_KEY_STATUS = /\b401\b/;
|
||||
/**
|
||||
* A gateway group that only serves its vendor's official client. These arrive
|
||||
* as 403, which the harness reads as an authentication failure and renders as
|
||||
* The key itself is gone for good: sub2api's own refusals of the credential
|
||||
* (`INVALID_API_KEY`, `API_KEY_DISABLED`, an expired key, an inactive user, a
|
||||
* deleted or withdrawn group). Only the gateway's own wording counts; a bare
|
||||
* 401 may be an upstream account's error passed through, and must not retire
|
||||
* the user's key.
|
||||
*/
|
||||
const INVALID_KEY_WORDING = /invalid api key|INVALID_API_KEY|api key is disabled|API_KEY_DISABLED|api key\s*已过期|API_KEY_EXPIRED|user account is not active|USER_INACTIVE|user associated with api key not found|所属分组已删除|所属专属分组不再允许|GROUP_NOT_ALLOWED/iu;
|
||||
/**
|
||||
* The key's own spending cap is used up (`API key 额度已用完`). It stays used up
|
||||
* until someone raises the cap, so the key is moved aside until re-enabled.
|
||||
*/
|
||||
const KEY_QUOTA_WORDING = /api key\s*额度已用完|api key quota exhausted|API_KEY_QUOTA_EXHAUSTED/iu;
|
||||
/**
|
||||
* Money that comes back on its own or with a top-up: the account wallet
|
||||
* (shared by every key of the account), a subscription window, a key's
|
||||
* 5h/1d/7d window, or a per-platform daily quota. The key is skipped for a
|
||||
* while, never retired: recharging must not leave keys disabled by hand.
|
||||
*/
|
||||
const EXHAUSTED_WORDING = /余额不足,?请充值|INSUFFICIENT_BALANCE|no active subscription|SUBSCRIPTION_NOT_FOUND|(?:daily|weekly|monthly) usage limit exceeded|限额已用完|usage quota exhausted for this platform/iu;
|
||||
/**
|
||||
* A group that only serves its vendor's official client. These arrive as
|
||||
* 403, which the harness reads as an authentication failure and renders as
|
||||
* an invalid-API-key problem — the opposite of what happened, and a condition
|
||||
* no retry can clear.
|
||||
*/
|
||||
const CLIENT_POLICY_WORDING = /only accessible via the official|only accepts requests from the official|official\s+claude(?:\s+code)?\s+cli|官方\s*claude(?:\s*code)?\s*cli|请使用标准\s*codex\s*客户端|客户端存在异常|二次分发|API\s*转接/iu;
|
||||
const CLIENT_POLICY_WORDING = /only accessible via the official|only accepts requests from the official|official\s+claude(?:\s+code)?\s+cli|官方\s*claude(?:\s*code)?\s*cli/iu;
|
||||
/**
|
||||
* The gateway's answer when a key's groups do not include the model's
|
||||
* supplier: `model_not_found` / 当前令牌未覆盖供应商. The key is fine for other
|
||||
* models, so it is never moved aside for this.
|
||||
* The gateway's answer when the key's group does not serve the model. The key
|
||||
* is fine for other models, so it is never moved aside for this. (`No
|
||||
* available accounts` is not here: sub2api says that when a pool is busy.)
|
||||
*/
|
||||
const COVERAGE_WORDING = /model_not_found|未覆盖供应商|无可用渠道|no available channel|model is not allowed|model is not supported|is not supported by any configured account|no available accounts|is not available\. use get \/v1\/models/iu;
|
||||
const COVERAGE_WORDING = /model is not allowed|model is not supported|is not supported by any configured account|is not available\. use get \/v1\/models/iu;
|
||||
/**
|
||||
* Whether the gateway refused the model for this key's groups.
|
||||
* @param message - the failure text.
|
||||
@@ -726,8 +753,10 @@ const COVERAGE_WORDING = /model_not_found|未覆盖供应商|无可用渠道|no
|
||||
function classifyCoverage(message) {
|
||||
return COVERAGE_WORDING.test(typeof message === "string" ? message : "");
|
||||
}
|
||||
/** The key's quota is exhausted; move to the next key. */
|
||||
/** The key's own cap is used up; move to the next key until re-enabled. */
|
||||
const QUOTA_FAILURE = "quota";
|
||||
/** Wallet, subscription, or window exhausted; skip the key for a while. */
|
||||
const EXHAUSTED_FAILURE = "exhausted";
|
||||
/** The gateway rejected the key itself; move to the next key. */
|
||||
const INVALID_KEY_FAILURE = "invalid-key";
|
||||
/**
|
||||
@@ -739,11 +768,7 @@ function classifyClientPolicy(message) {
|
||||
return CLIENT_POLICY_WORDING.test(typeof message === "string" ? message : "");
|
||||
}
|
||||
/**
|
||||
* Classify a gateway failure message.
|
||||
*
|
||||
* Quota wording wins over a status token: an exhausted balance is often
|
||||
* reported as 402/403, and only the key's own rejection may read as 401. A
|
||||
* client-policy refusal is not a key fault and is classified separately.
|
||||
* Classify a gateway failure message by sub2api's own wording.
|
||||
* @param message - provider failure text, as pi-ai carries it.
|
||||
* @returns the failure kind, or undefined when the key is not at fault.
|
||||
*/
|
||||
@@ -751,9 +776,9 @@ function classifyGatewayFailure(message) {
|
||||
const text = typeof message === "string" ? message : "";
|
||||
if (text === "") return void 0;
|
||||
if (classifyClientPolicy(text)) return void 0;
|
||||
if (QUOTA_WORDING.test(text)) return QUOTA_FAILURE;
|
||||
if (INVALID_KEY_WORDING.test(text)) return INVALID_KEY_FAILURE;
|
||||
if (INVALID_KEY_STATUS.test(text)) return INVALID_KEY_FAILURE;
|
||||
if (KEY_QUOTA_WORDING.test(text)) return QUOTA_FAILURE;
|
||||
if (EXHAUSTED_WORDING.test(text)) return EXHAUSTED_FAILURE;
|
||||
}
|
||||
/**
|
||||
* Explain that no stored key can use the requested model.
|
||||
@@ -788,7 +813,7 @@ function explainClientPolicyFailure() {
|
||||
* per-account wait queue is full, or it throttled or shed the request. The
|
||||
* CLI retries these on its own; this matches what is left when it gave up.
|
||||
*/
|
||||
const CAPACITY_WORDING = /concurrency_queue_full|并发排队已满|wait queues? (?:are|is) full|负载已饱和|overloaded|rate[_\s-]?limit|API Error:\s*(?:429|502|503|504|529)\b/iu;
|
||||
const CAPACITY_WORDING = /no available accounts|concurrency limit exceeded|concurrency_queue_full|并发排队已满|wait queues? (?:are|is) full|负载已饱和|overloaded|rate[_\s-]?limit|API Error:\s*(?:429|502|503|504|529)\b/iu;
|
||||
/**
|
||||
* Whether a CLI failure is the gateway being busy rather than a fault of the
|
||||
* key, the client, or the request.
|
||||
@@ -853,7 +878,7 @@ function explainCliGroupFailure(key, message) {
|
||||
function normalizeFailureMessage(message, kind, options = {}) {
|
||||
const text = typeof message === "string" && message.length > 0 ? message : "Geek2API request failed";
|
||||
if (kind === "client-policy") return explainClientPolicyFailure(options.keyName);
|
||||
if (kind === "quota") return `${neutralizeAuthStatus(text)} — Geek2API: insufficient quota for this API key; trying the next key`;
|
||||
if (kind === "quota" || kind === "exhausted") return `${neutralizeAuthStatus(text)} — Geek2API: insufficient quota for this API key; trying the next key`;
|
||||
if (kind === "invalid-key") return `${neutralizeAuthStatus(text)} — Geek2API: 401 invalid_authentication for this API key; trying the next key`;
|
||||
return text;
|
||||
}
|
||||
@@ -865,9 +890,10 @@ function neutralizeAuthStatus(text) {
|
||||
/**
|
||||
* Route Claude models through the local Claude Code CLI.
|
||||
*
|
||||
* Geek2API's `cc` group serves its Claude models only to the official CLI, so
|
||||
* selecting one of those models runs that CLI instead of an HTTP request. The
|
||||
* other models on the route keep using the pi-ai adapter untouched — this
|
||||
* When the Claude runtime setting is `cli`, selecting a Claude model runs the
|
||||
* local Claude Code CLI instead of an HTTP request (useful when a key's group
|
||||
* only serves the official CLI). Every other model, and every Claude model on
|
||||
* the default `http` runtime, keeps using the pi-ai adapter untouched — this
|
||||
* adapter only dispatches.
|
||||
*
|
||||
* A CLI-backed turn is a *delegation*: the CLI runs its own agent loop with
|
||||
@@ -897,7 +923,7 @@ const TITLE_MODEL_ID = "claude-haiku-4-5-20251001";
|
||||
/**
|
||||
* HTTP models whose session titles run on another model of the same route.
|
||||
* A title is a few words, so the flagship `gpt-6-astra` hands it to
|
||||
* `gpt-6.1-sol`, which the same Codex group serves; the session's own turns
|
||||
* `gpt-6.1-sol`, which the same GPT groups serve; the session's own turns
|
||||
* are untouched.
|
||||
*/
|
||||
const TITLE_MODEL_ROUTES = Object.freeze({ "gpt-6-astra": "gpt-6.1-sol" });
|
||||
@@ -1878,8 +1904,8 @@ function createDeltaRedactor(values) {
|
||||
/**
|
||||
* Bridge to the local Claude Code CLI.
|
||||
*
|
||||
* The gateway's `cc` group serves its Claude models only to the official CLI,
|
||||
* so this module runs that CLI — the real binary, not an imitation of it — as
|
||||
* On the `cli` Claude runtime (and for the `claude_code` tool) this module runs
|
||||
* the official CLI — the real binary, not an imitation of it — as
|
||||
* a subprocess and hands its final answer back to the harness. The child gets
|
||||
* the plugin's own endpoint and key through the environment, plus an isolated
|
||||
* `CLAUDE_CONFIG_DIR`: `~/.claude/settings.json` env wins over an inherited
|
||||
@@ -4456,7 +4482,16 @@ function pickKeyForModel(modelId, active, usable, covers) {
|
||||
*
|
||||
* @module dsh-geek2api/hosts
|
||||
*/
|
||||
/** Accept an absolute http(s) origin and drop a trailing slash. */
|
||||
const LOOPBACK = /* @__PURE__ */ new Set([
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
"[::1]"
|
||||
]);
|
||||
/**
|
||||
* Accept an https origin, keeping only the origin: a pasted `/v1` (the base
|
||||
* URL OpenAI clients use) would otherwise double every path. Plain http is
|
||||
* refused outside loopback, because the key travels in a header.
|
||||
*/
|
||||
function normalizeHost(value, fallback) {
|
||||
const text = typeof value === "string" ? value.trim() : "";
|
||||
if (text === "") return fallback;
|
||||
@@ -4466,8 +4501,9 @@ function normalizeHost(value, fallback) {
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") return fallback;
|
||||
return `${url.origin}${url.pathname.replace(/\/+$/u, "")}`;
|
||||
if (url.protocol === "https:") return url.origin;
|
||||
if (url.protocol === "http:" && LOOPBACK.has(url.hostname)) return url.origin;
|
||||
return fallback;
|
||||
}
|
||||
/**
|
||||
* Normalize a host list: valid origins only, no duplicates, configured order
|
||||
@@ -4480,10 +4516,16 @@ function normalizeHostList(value) {
|
||||
const hosts = [...new Set(raw.map((item) => normalizeHost(item, void 0)).filter((host) => host !== void 0))];
|
||||
return hosts.length === 0 ? [...DEFAULT_API_HOSTS] : hosts;
|
||||
}
|
||||
/** Whether a failure means the host never answered. */
|
||||
/**
|
||||
* Whether a failure means the host never answered. A timeout is not: the
|
||||
* host accepted the connection and the gateway behind it is slow, which every
|
||||
* host would be. Text that carries an HTTP status is the gateway's answer,
|
||||
* whatever words it uses.
|
||||
*/
|
||||
function isTransportFailure(error) {
|
||||
if (error instanceof TransportError) return error.aborted !== true;
|
||||
if (error instanceof TransportError) return error.aborted !== true && error.timedOut !== true;
|
||||
const text = error instanceof Error ? error.message : typeof error === "string" ? error : "";
|
||||
if (/^\s*\d{3}\b|\(\d{3}\)|status code \d{3}|HTTP \d{3}/u.test(text)) return false;
|
||||
return /fetch failed|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|UND_ERR_|socket hang up|network error|other side closed|certificate|TLS|connect timeout|Connection error|ConnectTimeout|getaddrinfo/iu.test(text);
|
||||
}
|
||||
/**
|
||||
@@ -4597,6 +4639,7 @@ function createHostPool({ listHosts = () => DEFAULT_API_HOSTS, fetchImpl = ambie
|
||||
return configured().map((host) => ({
|
||||
host,
|
||||
current: host === best,
|
||||
probed: probedAt !== 0,
|
||||
...latency.has(host) ? { latencyMs: latency.get(host) } : {},
|
||||
...isCooling(host) ? { coolingUntil: cooling.get(host) } : {}
|
||||
}));
|
||||
@@ -4630,11 +4673,26 @@ function createHostPool({ listHosts = () => DEFAULT_API_HOSTS, fetchImpl = ambie
|
||||
/** How long a request with a choice of keys waits for the first group reading. */
|
||||
const DEFAULT_GROUP_WAIT_MS = 6e3;
|
||||
/**
|
||||
* How long a key whose money ran out (wallet, subscription, or window) is
|
||||
* skipped. It is never disabled for that: a top-up or a new window brings it
|
||||
* back, and a balance read showing money brings it back at once.
|
||||
*/
|
||||
const EXHAUSTED_SKIP_MS = 10 * 6e4;
|
||||
/**
|
||||
* @param options - the key ring, the group reader, what to do after a key
|
||||
* moved aside, a logger, and how long to wait for the first group reading.
|
||||
* @returns the chooser.
|
||||
*/
|
||||
function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GROUP_WAIT_MS }) {
|
||||
function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GROUP_WAIT_MS, skipMs = EXHAUSTED_SKIP_MS, now = Date.now }) {
|
||||
/** key id → epoch ms until which the key is skipped (in memory only). */
|
||||
const skipped = /* @__PURE__ */ new Map();
|
||||
const isSkipped = (id) => {
|
||||
const until = skipped.get(id);
|
||||
if (until === void 0) return false;
|
||||
if (until > now()) return true;
|
||||
skipped.delete(id);
|
||||
return false;
|
||||
};
|
||||
/**
|
||||
* Key material to ring id. A failure is reported from inside a stream, which
|
||||
* carries the request's key but not its id; this index is refreshed on every
|
||||
@@ -4648,7 +4706,7 @@ function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GR
|
||||
snapshot = entries;
|
||||
for (const entry of entries) idByKey.set(entry.key, entry.id);
|
||||
};
|
||||
const usable = () => snapshot.filter((entry) => entry.disabled !== true);
|
||||
const usable = () => snapshot.filter((entry) => entry.disabled !== true && !isSkipped(entry.id));
|
||||
const covers = (keyId, modelId) => groups.covers(keyId, modelId);
|
||||
/**
|
||||
* Keep the group reading fresh for the choice. It only matters with two
|
||||
@@ -4665,10 +4723,24 @@ function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GR
|
||||
})]);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
/** The active key, after refreshing the ring and, when it matters, the groups. */
|
||||
/**
|
||||
* The active key, after refreshing the ring and, when it matters, the
|
||||
* groups. A skipped active key hands over to the next usable one in ring
|
||||
* order; with none left, the active key is returned so the failure speaks.
|
||||
*/
|
||||
const active = async () => {
|
||||
await remember();
|
||||
const key = await ring.activeKey();
|
||||
let key = await ring.activeKey();
|
||||
if (key !== void 0 && isSkipped(key.id)) {
|
||||
const start = snapshot.findIndex((entry) => entry.id === key.id);
|
||||
const next = (start < 0 ? snapshot : [...snapshot.slice(start + 1), ...snapshot.slice(0, start)]).find((entry) => entry.disabled !== true && !isSkipped(entry.id));
|
||||
if (next !== void 0) key = {
|
||||
...key,
|
||||
id: next.id,
|
||||
label: next.label,
|
||||
key: next.key
|
||||
};
|
||||
}
|
||||
if (key !== void 0) await warm();
|
||||
return key;
|
||||
};
|
||||
@@ -4676,6 +4748,21 @@ function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GR
|
||||
remember,
|
||||
covers,
|
||||
active,
|
||||
/** Key ids skipped for running out of money, with when the skip ends. */
|
||||
skipped() {
|
||||
return Object.fromEntries([...skipped.keys()].filter(isSkipped).map((id) => [id, skipped.get(id)]));
|
||||
},
|
||||
/**
|
||||
* A balance read is fresher evidence than a failure: a skipped key that
|
||||
* now shows money is usable again.
|
||||
* @param rows - the `keys` of a balance projection.
|
||||
*/
|
||||
noteBalances(rows) {
|
||||
for (const row of Array.isArray(rows) ? rows : []) {
|
||||
const available = row?.usage?.availableUsd;
|
||||
if (row?.stale === void 0 && typeof available === "number" && available > 0) skipped.delete(row.id);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* The key one HTTP request for `modelId` runs with, given the active key
|
||||
* pi-ai resolved. Synchronous because pi-ai opens its stream synchronously;
|
||||
@@ -4741,6 +4828,12 @@ function createKeyChooser({ ring, groups, onRotated, logger, waitMs = DEFAULT_GR
|
||||
logger?.warn?.("geek2api: %s reported for an unidentified key; not rotating", kind);
|
||||
return;
|
||||
}
|
||||
if (kind === "exhausted") {
|
||||
skipped.set(id, now() + skipMs);
|
||||
logger?.warn?.("geek2api: key %s has no money left for now; skipping it for a while", id);
|
||||
onRotated?.();
|
||||
return;
|
||||
}
|
||||
logger?.warn?.("geek2api: %s on key %s; the next key serves the retry", kind, id);
|
||||
ring.disable(id, kind).then(() => onRotated?.()).catch((error) => logger?.warn?.("geek2api: could not move past key %s: %s", id, error.message));
|
||||
}
|
||||
@@ -4997,8 +5090,8 @@ var Geek2APIKeyRing = class {
|
||||
* - DSH 0.2 has no sections: a preference is a *volatile* Config field of the
|
||||
* plugin's own row, read through a live reference, written through
|
||||
* `settings.update(rowId, patch)`, and announced by `loader/volatile-update`.
|
||||
* Only volatile fields are writable there, so the host overrides stay
|
||||
* read-only while web search and model visibility are editable.
|
||||
* Only volatile fields are writable there; the endpoint list, Claude
|
||||
* runtime, web search, and model visibility are all volatile.
|
||||
*
|
||||
* @module dsh-geek2api/preferences
|
||||
*/
|
||||
@@ -5120,15 +5213,19 @@ function createModelSelectionController({ readPreference, writePreference, isWri
|
||||
* Version self-knowledge for the settings panel.
|
||||
*
|
||||
* The running version comes from this package. The latest version comes from
|
||||
* the npm registry. An in-place update is only offered for a registry install,
|
||||
* and it installs that exact version with the host's own pnpm — never through
|
||||
* `dsh plugin --profile desktop`, which the desktop app refuses. Registry
|
||||
* bodies and package-manager output stay host-side.
|
||||
* the GitHub releases of this repository: the newest non-draft release names
|
||||
* the version in its tag and carries the packed tarball as an asset. An
|
||||
* in-place update is offered for an install from a release tarball (or the
|
||||
* npm registry), and it installs that exact tarball with the host's own pnpm
|
||||
* — never through `dsh plugin --profile desktop`, which the desktop app
|
||||
* refuses. Release bodies and package-manager output stay host-side.
|
||||
*
|
||||
* @module dsh-geek2api/plugin-version
|
||||
*/
|
||||
const PACKAGE_NAME = "dsh-geek2api";
|
||||
const NPM_REGISTRY_LATEST_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;
|
||||
const GITHUB_LATEST_RELEASE_URL = `https://api.github.com/repos/CoderKuo/dsh-geek2api/releases/latest`;
|
||||
/** The tarball asset a release must carry for an in-place update. */
|
||||
const releaseAssetName = (version) => `${PACKAGE_NAME}-${version}.tgz`;
|
||||
const DEFAULT_VERSION_TTL_MS = 5 * 6e4;
|
||||
const DEFAULT_VERSION_TIMEOUT_MS = 1e4;
|
||||
const DEFAULT_UPDATE_TIMEOUT_MS = 18e4;
|
||||
@@ -5160,15 +5257,37 @@ function compareSemver(a, b) {
|
||||
return left.pre < right.pre ? -1 : 1;
|
||||
}
|
||||
/**
|
||||
* Classify how the running package reached the profile. Only registry specs
|
||||
* may be updated in place; local checkouts belong to the owner's iteration.
|
||||
* Classify how the running package reached the profile. Registry specs and
|
||||
* packed tarballs (a release download, or a local `.tgz`) may be updated in
|
||||
* place; local checkouts belong to the owner's iteration.
|
||||
*/
|
||||
function classifySpec(spec) {
|
||||
if (typeof spec !== "string" || spec === "") return "unknown";
|
||||
if (/\.tgz(?:[?#].*)?$/iu.test(spec) && /^(?:https:\/\/|file:)/iu.test(spec)) return "release";
|
||||
if (/^(?:link|file):/u.test(spec)) return "link";
|
||||
if (/^(?:\d|[~^*])/u.test(spec)) return "npm";
|
||||
return "unknown";
|
||||
}
|
||||
/** Install kinds the panel may update in place. */
|
||||
const UPDATABLE_KINDS = Object.freeze(["npm", "release"]);
|
||||
/**
|
||||
* Normalize a GitHub "latest release" body.
|
||||
* @param payload - the API body.
|
||||
* @returns `{ version, tarballUrl, releaseUrl }`, or undefined when unusable.
|
||||
*/
|
||||
function parseLatestRelease(payload) {
|
||||
if (payload === null || typeof payload !== "object" || payload.draft === true || payload.prerelease === true) return void 0;
|
||||
const version = typeof payload.tag_name === "string" ? payload.tag_name.replace(/^v/u, "") : void 0;
|
||||
if (parseSemver(version) === void 0) return void 0;
|
||||
const asset = Array.isArray(payload.assets) ? payload.assets.find((item) => item?.name === releaseAssetName(version) && typeof item.browser_download_url === "string") : void 0;
|
||||
const tarballUrl = asset !== void 0 && /^https:\/\/github\.com\//u.test(asset.browser_download_url) ? asset.browser_download_url : void 0;
|
||||
const releaseUrl = typeof payload.html_url === "string" && /^https:\/\/github\.com\//u.test(payload.html_url) ? payload.html_url : void 0;
|
||||
return {
|
||||
version,
|
||||
...tarballUrl === void 0 ? {} : { tarballUrl },
|
||||
...releaseUrl === void 0 ? {} : { releaseUrl }
|
||||
};
|
||||
}
|
||||
const readManifest = async (path) => {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(path, "utf8"));
|
||||
@@ -5325,7 +5444,7 @@ function spawnRunCommand({ command, args, cwd }, { signal, timeoutMs }) {
|
||||
* The running version, the latest registry version, which profile installed
|
||||
* this copy, and registry-spec updates against that profile.
|
||||
*/
|
||||
function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = spawnRunCommand, execPath = process.execPath, argv = process.argv, env = process.env, ownPackageJsonUrl = new URL("../package.json", import.meta.url), registryUrl = NPM_REGISTRY_LATEST_URL, now = Date.now, ttlMs = DEFAULT_VERSION_TTL_MS, timeoutMs = DEFAULT_VERSION_TIMEOUT_MS, updateTimeoutMs = DEFAULT_UPDATE_TIMEOUT_MS, settleDelayMs = 250 } = {}) {
|
||||
function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = spawnRunCommand, execPath = process.execPath, argv = process.argv, env = process.env, ownPackageJsonUrl = new URL("../package.json", import.meta.url), releaseUrl = GITHUB_LATEST_RELEASE_URL, now = Date.now, ttlMs = DEFAULT_VERSION_TTL_MS, timeoutMs = DEFAULT_VERSION_TIMEOUT_MS, updateTimeoutMs = DEFAULT_UPDATE_TIMEOUT_MS, settleDelayMs = 250 } = {}) {
|
||||
if (typeof fetchImpl !== "function") throw new Error("Geek2API plugin manager requires fetch");
|
||||
if (typeof runCommand !== "function") throw new Error("Geek2API plugin manager requires runCommand");
|
||||
const dshHome = typeof env.DSH_HOME === "string" && env.DSH_HOME !== "" ? env.DSH_HOME : join(homedir(), ".dsh");
|
||||
@@ -5334,10 +5453,15 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
execPath
|
||||
});
|
||||
let updating = false;
|
||||
/** The newest release: its version, tarball asset, and page. */
|
||||
const fetchLatest = async (signal) => {
|
||||
let response;
|
||||
try {
|
||||
response = await boundedFetch(registryUrl, { headers: { Accept: "application/json" } }, {
|
||||
response = await boundedFetch(releaseUrl, { headers: {
|
||||
Accept: "application/vnd.github+json",
|
||||
"User-Agent": PACKAGE_NAME,
|
||||
"X-GitHub-Api-Version": "2022-11-28"
|
||||
} }, {
|
||||
fetchImpl,
|
||||
timeoutMs,
|
||||
signal
|
||||
@@ -5347,14 +5471,14 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
throw new Error("Geek2API plugin version check failed");
|
||||
}
|
||||
if (!response.ok) throw new Error("Geek2API plugin version check failed");
|
||||
let version;
|
||||
let release;
|
||||
try {
|
||||
version = (await response.json())?.version;
|
||||
release = parseLatestRelease(await response.json());
|
||||
} catch {
|
||||
version = void 0;
|
||||
release = void 0;
|
||||
}
|
||||
if (parseSemver(version) === void 0) throw new Error("Geek2API plugin version check failed");
|
||||
return version;
|
||||
if (release === void 0) throw new Error("Geek2API plugin version check failed");
|
||||
return release;
|
||||
};
|
||||
const readOwnVersion = async () => {
|
||||
const version = (await readManifest(fileURLToPath(ownPackageJsonUrl)))?.version;
|
||||
@@ -5373,8 +5497,10 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
]);
|
||||
return {
|
||||
current,
|
||||
latest,
|
||||
updateAvailable: compareSemver(latest, current) === 1,
|
||||
latest: latest.version,
|
||||
...latest.releaseUrl === void 0 ? {} : { releaseUrl: latest.releaseUrl },
|
||||
updateAvailable: compareSemver(latest.version, current) === 1,
|
||||
updatable: latest.tarballUrl !== void 0 && UPDATABLE_KINDS.includes(install.kind),
|
||||
install,
|
||||
fetchedAt: now()
|
||||
};
|
||||
@@ -5395,8 +5521,9 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
ownPackageJsonUrl
|
||||
});
|
||||
if (install.kind === "link") throw new Error("Geek2API plugin is installed from a local checkout");
|
||||
if (install.kind !== "npm" || install.profile === void 0) throw new Error("Geek2API plugin update could not find the owning profile");
|
||||
if (!UPDATABLE_KINDS.includes(install.kind) || install.profile === void 0) throw new Error("Geek2API plugin update could not find the owning profile");
|
||||
const latest = await fetchLatest(signal);
|
||||
if (latest.tarballUrl === void 0) throw new Error("Geek2API plugin release has no package to install");
|
||||
const profileDir = join(dshHome, "profiles", install.profile);
|
||||
let result;
|
||||
try {
|
||||
@@ -5405,9 +5532,8 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
args: [
|
||||
...launcher.prefix,
|
||||
"add",
|
||||
"--save-exact",
|
||||
`--config.minimumReleaseAge=0`,
|
||||
`${PACKAGE_NAME}@${latest}`
|
||||
`${PACKAGE_NAME}@${latest.tarballUrl}`
|
||||
],
|
||||
cwd: profileDir
|
||||
}, {
|
||||
@@ -5421,12 +5547,12 @@ function createGeek2APIPluginManager({ fetchImpl = ambientFetch, runCommand = sp
|
||||
if (result.code !== 0) throw new Error("Geek2API plugin update failed");
|
||||
await confirmInstalled({
|
||||
profileDir,
|
||||
expected: latest,
|
||||
expected: latest.version,
|
||||
settleDelayMs
|
||||
});
|
||||
cache.invalidate();
|
||||
return {
|
||||
version: latest,
|
||||
version: latest.version,
|
||||
profile: install.profile
|
||||
};
|
||||
} finally {
|
||||
@@ -5684,8 +5810,8 @@ function createGeek2APIProfile(provider) {
|
||||
function createRouteAdapter({ ring, keys, hosts, fallbackSessionId, resolveAttachments, isModelVisible = () => true }) {
|
||||
const raw = createGeek2APIProvider();
|
||||
/**
|
||||
* The gateway's Codex-group check refuses a Responses request that carries
|
||||
* no `prompt_cache_key` with a 403, which pi-ai derives from the session id.
|
||||
* GPT on Responses carries a `prompt_cache_key`, which pi-ai derives from
|
||||
* the session id; it keeps one conversation on the same upstream cache.
|
||||
* The harness supplies one for every agent turn; the fallback covers a
|
||||
* caller that does not, so the route never fails for a missing cache key.
|
||||
*/
|
||||
@@ -5790,7 +5916,7 @@ const keyId = (payload) => String(payload?.id ?? "");
|
||||
* web search controller (without one, its endpoints refuse).
|
||||
* @returns a handler for `connection.rpc.handle(CHANNEL, handler)`.
|
||||
*/
|
||||
function createGeek2APIRpc({ ring, balance, groups, hosts, preference, claudeRuntime, claudeCli, pluginManager, search, modelSelection }) {
|
||||
function createGeek2APIRpc({ ring, balance, groups, hosts, keys, preference, claudeRuntime, claudeCli, pluginManager, search, modelSelection }) {
|
||||
const need = (service, message) => {
|
||||
if (service === void 0) throw new Error(message);
|
||||
return service;
|
||||
@@ -5805,7 +5931,8 @@ function createGeek2APIRpc({ ring, balance, groups, hosts, preference, claudeRun
|
||||
hosts: hosts.status(),
|
||||
writable: preference.writable === true,
|
||||
defaults: { apiHosts: [...DEFAULT_API_HOSTS] },
|
||||
claudeRuntime: typeof claudeRuntime === "function" ? claudeRuntime() : "http"
|
||||
claudeRuntime: typeof claudeRuntime === "function" ? claudeRuntime() : "http",
|
||||
skipped: typeof keys?.skipped === "function" ? keys.skipped() : {}
|
||||
});
|
||||
const writable = () => {
|
||||
if (preference.writable !== true) throw new Error("Geek2API settings are not writable in this profile");
|
||||
@@ -6264,7 +6391,7 @@ function createGeek2APISearchProvider({ ring, hosts, backend = () => DEFAULT_SEA
|
||||
const failure = outcome.failure === "" ? `HTTP ${outcome.status}` : outcome.failure;
|
||||
lastFailure = failure;
|
||||
if (classifyClientPolicy(failure)) throw new WebError(explainClientPolicyFailure(), "WEB_PROVIDER_ERROR");
|
||||
const kind = classifyGatewayFailure(failure) ?? (outcome.status === 401 ? "invalid-key" : void 0);
|
||||
const kind = classifyGatewayFailure(failure);
|
||||
if (kind !== void 0) {
|
||||
onKeyFailure?.(kind, failure, key.key, key.id);
|
||||
continue;
|
||||
@@ -6836,7 +6963,7 @@ const Config = z.object({
|
||||
* request DSH's own search would have served.
|
||||
*/
|
||||
searchProvider: live(z.union([...SEARCH_MODES]).default(SEARCH_MODE_DEFAULT)),
|
||||
/** Which Geek2API model runs a search: `deepseek` or `gpt`. */
|
||||
/** Which Geek2API model runs a search: `claude` or `gpt`. */
|
||||
searchBackend: live(z.union([...SEARCH_BACKENDS]).default(DEFAULT_SEARCH_BACKEND)),
|
||||
/** Only the picker is filtered; an existing session can keep its model. */
|
||||
hiddenModels: live(z.array(z.string()).default([]))
|
||||
@@ -6859,7 +6986,8 @@ function apply(ctx, config) {
|
||||
const claudeRuntime = () => fieldValue((source() ?? {}).claudeRuntime) === "cli" ? "cli" : "http";
|
||||
const balance = createBalanceReader({
|
||||
listKeys: () => ring.secrets(),
|
||||
hosts
|
||||
hosts,
|
||||
onRead: (rows) => keys.noteBalances(rows)
|
||||
});
|
||||
/**
|
||||
* Which token groups each key is in, and so which models it can reach.
|
||||
@@ -6906,8 +7034,8 @@ function apply(ctx, config) {
|
||||
onChange: () => refreshModels()
|
||||
});
|
||||
/**
|
||||
* The Claude Code CLI runner. Geek2API serves its Claude models only to the
|
||||
* official CLI, so CLI-backed models are run by that CLI itself — with this
|
||||
* The Claude Code CLI runner, for the `cli` Claude runtime and the
|
||||
* `claude_code` tool: the official CLI itself runs the turn — with this
|
||||
* plugin's endpoint and a ring key, in an isolated config home. Each run
|
||||
* uses the active key unless its groups cannot reach the run's Claude model
|
||||
* and another stored key's can, and reports which key it used by label.
|
||||
@@ -7048,6 +7176,7 @@ function apply(ctx, config) {
|
||||
ctx.on?.("loader/volatile-update", () => {
|
||||
modelSelection.reconcile();
|
||||
search.reconcile();
|
||||
hosts.probe({ force: true }).catch(() => void 0);
|
||||
});
|
||||
/**
|
||||
* Both search providers register with the web service whenever one exists.
|
||||
@@ -7065,6 +7194,7 @@ function apply(ctx, config) {
|
||||
balance,
|
||||
groups,
|
||||
hosts,
|
||||
keys,
|
||||
preference: modelPreference,
|
||||
claudeRuntime,
|
||||
claudeCli,
|
||||
|
||||
Reference in new issue
Block a user