release: 0.2.0 — custom models, gateway context caps, free daily keys

- Custom models: add a model by id (protocol, reasoning, images, context
  window, max output) next to the built-in catalog.
- Gateway context caps: read per-model context_window from each key's
  /v1/models and narrow the catalog model to the tightest window (free
  DeepSeek group: 200K, 32K output) so DSH compacts before the cap.
- Free daily keys: show each key's expiry, flag the renewal window and
  link to https://www.geek2api.com/free-ds; the no-usable-key error points
  there too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
大阔andClaude Opus 5.5 committed 2026-11-16 21:44:12 +08:00
1 parent 93a5fe93b4
commit a8f689e39c
21 files changed
+2138 -404

No files matched your search

+6
View File
@@ -1,5 +1,11 @@
# Changelog # Changelog
## 0.2.0
- **Gateway context caps (free DeepSeek group).** When a key's group limits the input per request, Geek2API now reports `context_window` in that key's `/v1/models` (the free DeepSeek group allows 200K although DeepSeek V4.1 Flash itself takes 1M). The catalog model is narrowed to the tightest window reported by the keys that reach it — DeepSeek V4.1 Flash becomes 200K with 32K max output — so DSH compacts the session at about 100K instead of being refused at 200K. Keys whose groups report no cap leave the model unchanged. If a request still overflows, the gateway's error now uses the standard `context_length_exceeded` / `maximum context length` wording, which DSH recognizes and answers by compacting and retrying.
- **Free daily keys.** The free DeepSeek group only accepts the daily key claimed at https://www.geek2api.com/free-ds; each lasts 24 hours and the next one can be claimed 2 hours before expiry (both stay valid). Settings → Geek2API shows each key's expiry, flags a daily key whose renewal window is open or that has expired, and links to the page that issues the next one. The "no usable key" error points there too. A per-request context cap is shown under the key.
- **Custom models.** Settings → Geek2API → Visible models → Custom models adds a model by id next to the built-in catalog: its protocol (Chat Completions, Responses, or Messages), whether it reasons (off / low / medium / high), whether it takes images, and optionally its context window and max output (default 128000 / 32000). It is served by the same route — same keys, endpoints, failover, and key rotation — and appears in the picker at once without restarting. Each key's `/v1/models` coverage includes the custom models (a "Custom" column under the key), so a request for one runs on a key that reaches it. Ids must not repeat a built-in id; at most 32. The list is the volatile `customModels` preference; a hand-edited entry that cannot be served is dropped instead of failing the route. Removing a custom model leaves sessions that used it with an unknown model, never another model. The built-in catalog is unchanged.
## 0.1.4 ## 0.1.4
- Releases are now published to npm automatically from the release workflow through npm trusted publishing (OIDC): the same tarball as the GitHub Release and the Geek2API mirror, with no stored npm token. No plugin behavior changes. - Releases are now published to npm automatically from the release workflow through npm trusted publishing (OIDC): the same tarball as the GitHub Release and the Geek2API mirror, with no stored npm token. No plugin behavior changes.
+2
View File
@@ -54,6 +54,8 @@ Keys rotate on `余额不足,请充值`, a lapsed subscription, `Invalid API k
Whether a key can use a model depends on its group; trust the ✓ / ✕ in settings. Whether a key can use a model depends on its group; trust the ✓ / ✕ in settings.
**Custom models.** A model Geek2API serves but the table lacks can be added by id under **Settings → Geek2API → Visible models → Custom models**: the model id (as the key's `/v1/models` lists it; not a built-in id), an optional display name, the protocol (Chat Completions by default; Messages for Claude, Responses for GPT and Grok), whether it reasons (then off / low / medium / high are offered), whether it takes images, and optionally its context window and max output (default 128000 / 32000). It appears in the picker at once, with the same key rotation and endpoint failover, and a "Custom" column under each key shows whether that key reaches it. Up to 32. A session using a removed custom model fails with an unknown model instead of switching to another one.
## Update and uninstall ## Update and uninstall
The version card in **Settings → Geek2API** checks the Geek2API mirror first and GitHub when no mirror answers; 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. The version card in **Settings → Geek2API** checks the Geek2API mirror first and GitHub when no mirror answers; 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.
+15
View File
@@ -126,6 +126,21 @@ https://hk.geek2api.com/dsh/dsh-geek2api.tgz
列表里看得到模型,不代表你的 Key 一定能用:能不能用取决于 Key 所在的分组,以设置页的 ✓ / ✕ 为准。设置页「显示的模型」可以隐藏用不到的模型。 列表里看得到模型,不代表你的 Key 一定能用:能不能用取决于 Key 所在的分组,以设置页的 ✓ / ✕ 为准。设置页「显示的模型」可以隐藏用不到的模型。
### 自定义模型
Geek2API 上有、但上表没有的模型,可以在 **设置 → Geek2API → 显示的模型 → 自定义模型** 里按模型 ID 添加:
| 字段 | 说明 |
| --- | --- |
| 模型 ID | Geek2API 上的模型名(Key 的 `/v1/models` 里列出的那个),不能和内置模型重名 |
| 显示名称 | 可选,留空显示 ID |
| 协议 | Chat Completions(默认)、Responses 或 Messages:Claude 系选 Messages,GPT / Grok 选 Responses,其他大多选 Chat Completions |
| 推理 | 勾选后提供 `off` / `low` / `medium` / `high`;不勾选则不发推理参数 |
| 可带图 | 勾选后可以在对话里发图片 |
| 上下文 / 输出 | 可选,默认 128000 / 32000 token |
添加后立即出现在模型选择器里,使用同样的多 Key 轮换和多入口切换;「账户与 Key」里会多出一栏「自定义」,显示每个 Key 能不能用。最多 32 个。删除自定义模型后,正在用它的会话会提示找不到模型,不会悄悄换成别的模型。
## 更新与卸载 ## 更新与卸载
**更新:** 打开 **设置 → Geek2API**,「插件版本」卡片会先从 Geek2API 镜像检查最新版本(国内直连可用),镜像不可用时再查 GitHub;有新版本时点「更新插件」,完成后完全退出并重新打开桌面应用。「更新说明」链接到这个版本的发布页。 **更新:** 打开 **设置 → Geek2API**,「插件版本」卡片会先从 Geek2API 镜像检查最新版本(国内直连可用),镜像不可用时再查 GitHub;有新版本时点「更新插件」,完成后完全退出并重新打开桌面应用。「更新说明」链接到这个版本的发布页。
+365 -8
View File
@@ -96,6 +96,13 @@ window.__ModuleLoader__.load({
groupsMiss: "不可用", groupsMiss: "不可用",
groupsPartial: "部分", groupsPartial: "部分",
groupsStale: "分组为上次读取的结果", groupsStale: "分组为上次读取的结果",
contextCap: "该分组单次上下文上限 {tokens},会提前自动压缩",
keyExpiresAt: "{when} 到期",
keyExpired: "已到期",
dailyKeyExpiresIn: "免费日卡 · {when} 到期(还剩 {hours} 小时 {minutes} 分)",
dailyKeyRenewOpen: "免费日卡 · {when} 到期,现在就能领下一把,两把同时有效不中断",
dailyKeyExpired: "免费日卡已到期,领一把新的粘贴到这里",
dailyKeyClaim: "去领取 →",
modelsTitle: "显示的模型", modelsTitle: "显示的模型",
modelsIntro: "切换模型时只显示已勾选的 Geek2API 模型,默认全选。修改后立即生效;已有会话仍可继续使用原模型。", modelsIntro: "切换模型时只显示已勾选的 Geek2API 模型,默认全选。修改后立即生效;已有会话仍可继续使用原模型。",
modelsChecking: "正在读取模型设置…", modelsChecking: "正在读取模型设置…",
@@ -104,6 +111,29 @@ window.__ModuleLoader__.load({
modelsNone: "全不选", modelsNone: "全不选",
modelsCount: "已选 {count} / {total}", modelsCount: "已选 {count} / {total}",
modelsEmpty: "未勾选任何模型,切换列表将隐藏 Geek2API 的模型。", modelsEmpty: "未勾选任何模型,切换列表将隐藏 Geek2API 的模型。",
customTitle: "自定义模型({count})",
customIntro: "内置列表里没有的模型,可以按模型 ID 自己添加:填 Geek2API 上的模型名,选它走的协议。添加后立即出现在模型选择器里,和内置模型一样使用多 Key 轮换和多入口切换。能不能用取决于 Key 所在分组,以「账户与 Key」里「自定义」一栏的 ✓ / ✕ 为准。",
customChip: "自定义",
customFamily: "自定义",
customAddTitle: "添加模型",
customIdPlaceholder: "模型 ID,例如 qwen3-max",
customNamePlaceholder: "显示名称(可选)",
customProtocol: "协议",
customProtocolHint: "Claude 系选 Messages;GPT、Grok 选 Responses;其他大多数模型选 Chat Completions。",
protocolCompletions: "Chat Completions",
protocolResponses: "Responses",
protocolMessages: "Messages",
customCapabilities: "能力",
customReasoning: "推理",
customImage: "可带图",
customLimits: "上下文 / 输出",
customContextPlaceholder: "上下文窗口,默认 128000",
customOutputPlaceholder: "最大输出,默认 32000",
customWindow: "上下文 {context} · 输出 {output}",
customReasoningHint: "勾选「推理」后提供 off / low / medium / high 档位;不勾选则不发送推理参数。",
customAdd: "添加",
customRemove: "删除",
customFull: "最多添加 {count} 个自定义模型。",
hostsTitle: "接口地址", hostsTitle: "接口地址",
hostsIntro: "所有请求按测速结果选用最快的地址;某个地址连不上会暂时跳过,自动改用下一个。", hostsIntro: "所有请求按测速结果选用最快的地址;某个地址连不上会暂时跳过,自动改用下一个。",
hostsProbe: "重新测速", hostsProbe: "重新测速",
@@ -205,6 +235,29 @@ window.__ModuleLoader__.load({
modelsNone: "Select none", modelsNone: "Select none",
modelsCount: "{count} / {total} selected", modelsCount: "{count} / {total} selected",
modelsEmpty: "No models selected. Geek2API models are hidden from the picker.", modelsEmpty: "No models selected. Geek2API models are hidden from the picker.",
customTitle: "Custom models ({count})",
customIntro: "Add a model the built-in list lacks by its id: the model name on Geek2API, and the protocol it is served over. It appears in the model picker at once and uses the same key rotation and endpoint failover as the built-in models. Whether a key can use it depends on the key’s groups; see the ✓ / ✕ under “Custom” in Accounts and keys.",
customChip: "Custom",
customFamily: "Custom",
customAddTitle: "Add a model",
customIdPlaceholder: "Model id, e.g. qwen3-max",
customNamePlaceholder: "Display name (optional)",
customProtocol: "Protocol",
customProtocolHint: "Claude models: Messages. GPT and Grok: Responses. Most other models: Chat Completions.",
protocolCompletions: "Chat Completions",
protocolResponses: "Responses",
protocolMessages: "Messages",
customCapabilities: "Capabilities",
customReasoning: "Reasoning",
customImage: "Images",
customLimits: "Context / output",
customContextPlaceholder: "Context window, default 128000",
customOutputPlaceholder: "Max output, default 32000",
customWindow: "context {context} · output {output}",
customReasoningHint: "With Reasoning, the off / low / medium / high efforts are offered; without it, no reasoning parameter is sent.",
customAdd: "Add",
customRemove: "Remove",
customFull: "At most {count} custom models.",
intro: "Paste a Geek2API API key to use the built-in model route. Keys are used in order: an exhausted or rejected key hands over to the next one, and a key that cannot reach the selected model is passed over for one that can. Several endpoints are measured and fail over automatically.", intro: "Paste a Geek2API API key to use the built-in model route. Keys are used in order: an exhausted or rejected key hands over to the next one, and a key that cannot reach the selected model is passed over for one that can. Several endpoints are measured and fail over automatically.",
accountsTitle: "Accounts and keys", accountsTitle: "Accounts and keys",
refresh: "Refresh", refresh: "Refresh",
@@ -264,6 +317,13 @@ window.__ModuleLoader__.load({
groupsMiss: "Not", groupsMiss: "Not",
groupsPartial: "partly", groupsPartial: "partly",
groupsStale: "groups from the last read", groupsStale: "groups from the last read",
contextCap: "This group caps the context at {tokens} per request; sessions compact early",
keyExpiresAt: "Expires {when}",
keyExpired: "Expired",
dailyKeyExpiresIn: "Free daily key · expires {when} ({hours}h {minutes}m left)",
dailyKeyRenewOpen: "Free daily key · expires {when}; claim the next one now, both stay valid",
dailyKeyExpired: "Free daily key expired; claim a new one and paste it here",
dailyKeyClaim: "Claim →",
hostsTitle: "Endpoints", hostsTitle: "Endpoints",
hostsIntro: "Every request uses the fastest endpoint by the last measurement; an endpoint that cannot be reached is skipped for a while and the next one serves.", hostsIntro: "Every request uses the fastest endpoint by the last measurement; an endpoint that cannot be reached is skipped for a while and the next one serves.",
hostsProbe: "Measure again", hostsProbe: "Measure again",
@@ -443,6 +503,9 @@ window.__ModuleLoader__.load({
.pkc-model>span{display:flex;flex-direction:column;min-width:0;gap:2px} .pkc-model>span{display:flex;flex-direction:column;min-width:0;gap:2px}
.pkc-model b{font-size:13px;font-weight:500} .pkc-model b{font-size:13px;font-weight:500}
.pkc-models:disabled .pkc-model{opacity:.5;cursor:not-allowed} .pkc-models:disabled .pkc-model{opacity:.5;cursor:not-allowed}
.pkc-model b>.pkc-chip{margin-left:6px;vertical-align:1px}
.pkc-check{display:inline-flex;align-items:center;gap:6px;font-size:13px;cursor:pointer}
.pkc-check>input{flex:none;width:16px;height:16px;margin:0;accent-color:var(--dsw-alias-state-business-primary)}
.pkc-setting{display:grid;grid-template-columns:112px minmax(0,1fr);gap:6px 16px;align-items:start} .pkc-setting{display:grid;grid-template-columns:112px minmax(0,1fr);gap:6px 16px;align-items:start}
.pkc-setting>.pkc-label{padding-top:5px} .pkc-setting>.pkc-label{padding-top:5px}
@@ -658,9 +721,14 @@ window.__ModuleLoader__.load({
if (typeof usage.availableUsd !== "number") return void 0; if (typeof usage.availableUsd !== "number") return void 0;
return Math.max(0, Math.min(1, usage.availableUsd / usage.limitUsd)); return Math.max(0, Math.min(1, usage.availableUsd / usage.limitUsd));
} }
/** Which catalog families a key reaches, from its per-model coverage. */ const BUILT_IN_IDS = new Set(MODEL_FAMILIES.flatMap(([, models]) => models));
function reachOf(coverage) { /**
return MODEL_FAMILIES.flatMap(([name, models]) => { * Which catalog families a key reaches, from its per-model coverage. Models
* the user added by id form one more family of their own.
*/
function reachOf(coverage, customName) {
const custom = Object.keys(coverage ?? {}).filter((id) => !BUILT_IN_IDS.has(id));
return (custom.length === 0 ? MODEL_FAMILIES : [...MODEL_FAMILIES, [customName, custom]]).flatMap(([name, models]) => {
const known = models.filter((id) => typeof coverage?.[id] === "boolean"); const known = models.filter((id) => typeof coverage?.[id] === "boolean");
if (known.length === 0) return []; if (known.length === 0) return [];
const reached = known.filter((id) => coverage[id] === true); const reached = known.filter((id) => coverage[id] === true);
@@ -719,7 +787,7 @@ window.__ModuleLoader__.load({
className: "pkc-error", className: "pkc-error",
children: t("groupsRejected") children: t("groupsRejected")
}); });
const reach = reachOf(group.coverage); const reach = reachOf(group.coverage, t("customFamily"));
const names = Array.isArray(group.groups) ? group.groups : []; const names = Array.isArray(group.groups) ? group.groups : [];
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
@@ -753,12 +821,66 @@ window.__ModuleLoader__.load({
className: "pkc-meta", className: "pkc-meta",
children: fill(t("groupsExtra"), { count: group.extraModels }) children: fill(t("groupsExtra"), { count: group.extraModels })
}), }),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyContextCap, {
windows: group.contextWindows,
t
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyLifetime, {
lifetime: group.lifetime,
t
}),
group.stale !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { group.stale !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta", className: "pkc-meta",
children: t("groupsStale") children: t("groupsStale")
}) })
] }); ] });
} }
/** Where the free daily key is claimed again. */
const FREE_DAILY_SITE = "https://www.geek2api.com";
const compactTokens = (value) => value >= 1e3 ? `${Math.round(value / 1e3)}K` : String(value);
/** The per-request context cap the key's group enforces (the free DeepSeek group: 200K). */
function KeyContextCap({ windows, t }) {
if (windows === void 0 || windows === null) return null;
const values = [...new Set(Object.values(windows).filter((value) => Number.isInteger(value)))];
if (values.length === 0) return null;
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: fill(t("contextCap"), { tokens: values.map(compactTokens).join(" / ") })
});
}
/** When the key expires; a daily free key also links to the page that issues the next one. */
function KeyLifetime({ lifetime, t }) {
if (lifetime === void 0 || lifetime === null || !Number.isFinite(lifetime.expiresAt)) return null;
const left = lifetime.expiresAt - Date.now();
const at = new Date(lifetime.expiresAt);
const pad = (value) => String(value).padStart(2, "0");
const when = `${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(at.getHours())}:${pad(at.getMinutes())}`;
const hours = Math.max(0, Math.floor(left / 36e5));
const minutes = Math.max(0, Math.floor(left % 36e5 / 6e4));
if (lifetime.daily !== true) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: left > 0 ? fill(t("keyExpiresAt"), { when }) : t("keyExpired")
});
const renewOpen = left <= (lifetime.renewWindowHours ?? 2) * 36e5;
const href = `${FREE_DAILY_SITE}${lifetime.renewPath ?? "/free-ds"}`;
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: left <= 0 || renewOpen ? "pkc-error" : "pkc-meta",
children: [
left <= 0 ? t("dailyKeyExpired") : fill(renewOpen ? t("dailyKeyRenewOpen") : t("dailyKeyExpiresIn"), {
when,
hours,
minutes
}),
" ",
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
href,
target: "_blank",
rel: "noreferrer noopener",
children: t("dailyKeyClaim")
})
]
});
}
function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, skippedUntil, t }) { function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, skippedUntil, t }) {
const usage = row?.usage; const usage = row?.usage;
const share = remainingShare(usage); const share = remainingShare(usage);
@@ -1230,6 +1352,198 @@ window.__ModuleLoader__.load({
] ]
}); });
} }
const PROTOCOL_KEYS = {
"openai-completions": "protocolCompletions",
"openai-responses": "protocolResponses",
"anthropic-messages": "protocolMessages"
};
const EMPTY_CUSTOM = {
id: "",
name: "",
api: "openai-completions",
reasoning: false,
image: false,
contextWindow: "",
maxTokens: ""
};
/** One user-added model: its protocol and capabilities, and a remove button. */
function CustomModelRow({ model, disabled, onRemove, t }) {
const facts = [
t(PROTOCOL_KEYS[model.api] ?? "protocolCompletions"),
model.reasoning ? t("customReasoning") : void 0,
model.image ? t("customImage") : void 0,
fill(t("customWindow"), {
context: model.contextWindow.toLocaleString(),
output: model.maxTokens.toLocaleString()
})
].filter(Boolean).join(" · ");
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-row",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-row-top",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
className: "pkc-row-name",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-name",
children: model.name === "" ? model.id : model.name
}), model.name !== "" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta pkc-mono",
children: model.id
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-actions",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
variant: "danger",
disabled,
onClick: onRemove,
children: t("customRemove")
})
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta",
children: facts
})]
});
}
/** The form that adds a model by id. */
function CustomModelForm({ disabled, onAdd, t }) {
const [draft, setDraft] = react.useState(EMPTY_CUSTOM);
const set = (patch) => setDraft((current) => ({
...current,
...patch
}));
const submit = (event) => {
event.preventDefault();
if (disabled || draft.id.trim() === "") return;
onAdd({
id: draft.id.trim(),
name: draft.name.trim(),
api: draft.api,
reasoning: draft.reasoning,
image: draft.image,
...draft.contextWindow.trim() === "" ? {} : { contextWindow: Number(draft.contextWindow) },
...draft.maxTokens.trim() === "" ? {} : { maxTokens: Number(draft.maxTokens) }
}).then((saved) => {
if (saved) setDraft(EMPTY_CUSTOM);
});
};
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
className: "pkc-add",
onSubmit: submit,
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("customAddTitle")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-form",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input pkc-mono",
type: "text",
maxLength: 128,
spellCheck: false,
autoComplete: "off",
placeholder: t("customIdPlaceholder"),
disabled,
value: draft.id,
onChange: (event) => set({ id: event.target.value })
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input",
type: "text",
maxLength: 64,
placeholder: t("customNamePlaceholder"),
disabled,
value: draft.name,
onChange: (event) => set({ name: event.target.value })
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-setting",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("customProtocol")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Segmented, {
label: t("customProtocol"),
options: Object.keys(PROTOCOL_KEYS).map((value) => ({
value,
label: t(PROTOCOL_KEYS[value])
})),
value: draft.api,
disabled,
onChange: (api) => set({ api })
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("customProtocolHint")
})] }),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("customCapabilities")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-form",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
className: "pkc-check",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
type: "checkbox",
disabled,
checked: draft.reasoning,
onChange: (event) => set({ reasoning: event.target.checked })
}), t("customReasoning")]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
className: "pkc-check",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
type: "checkbox",
disabled,
checked: draft.image,
onChange: (event) => set({ image: event.target.checked })
}), t("customImage")]
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-label",
children: t("customLimits")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-form",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input",
type: "number",
min: 1e3,
step: 1e3,
placeholder: t("customContextPlaceholder"),
disabled,
value: draft.contextWindow,
onChange: (event) => set({ contextWindow: event.target.value })
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
className: "pkc-input",
type: "number",
min: 1,
step: 1e3,
placeholder: t("customOutputPlaceholder"),
disabled,
value: draft.maxTokens,
onChange: (event) => set({ maxTokens: event.target.value })
})]
})
]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "pkc-split",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("customReasoningHint")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
type: "submit",
variant: "primary",
disabled: disabled || draft.id.trim() === "",
children: t("customAdd")
})]
})
]
});
}
function ModelsCard({ call, t }) { function ModelsCard({ call, t }) {
const [state, setState] = react.useState(); const [state, setState] = react.useState();
const [busy, setBusy] = react.useState(false); const [busy, setBusy] = react.useState(false);
@@ -1246,14 +1560,25 @@ window.__ModuleLoader__.load({
}; };
}, [call]); }, [call]);
const models = state?.models ?? []; const models = state?.models ?? [];
const custom = Array.isArray(state?.customModels) ? state.customModels : [];
const selectedIds = models.filter((model) => model.selected).map((model) => model.id); const selectedIds = models.filter((model) => model.selected).map((model) => model.id);
const disabled = busy || state?.writable !== true; const disabled = busy || state?.writable !== true;
const update = (ids) => { /** Run one write; resolves true when it was saved. */
if (disabled) return; const write = (endpoint, payload) => {
if (disabled) return Promise.resolve(false);
setBusy(true); setBusy(true);
setError(void 0); setError(void 0);
call("models/update", { selectedIds: ids }).then(setState).catch((failure) => setError(clearMessage(failure))).finally(() => setBusy(false)); return call(endpoint, payload).then((next) => {
setState(next);
return true;
}).catch((failure) => {
setError(clearMessage(failure));
return false;
}).finally(() => setBusy(false));
}; };
const update = (ids) => void write("models/update", { selectedIds: ids });
const saveCustom = (list) => write("models/custom/update", { customModels: list });
const full = custom.length >= (state?.maxCustomModels ?? Infinity);
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, { return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Card, {
title: t("modelsTitle"), title: t("modelsTitle"),
aside: state !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { aside: state !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
@@ -1296,7 +1621,11 @@ window.__ModuleLoader__.load({
type: "checkbox", type: "checkbox",
checked: model.selected, checked: model.selected,
onChange: (event) => update(event.target.checked ? [...selectedIds, model.id] : selectedIds.filter((id) => id !== model.id)) onChange: (event) => update(event.target.checked ? [...selectedIds, model.id] : selectedIds.filter((id) => id !== model.id))
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: model.name }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("b", { children: [model.name, model.custom === true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-chip",
"data-tone": "info",
children: t("customChip")
})] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "pkc-meta pkc-mono", className: "pkc-meta pkc-mono",
children: model.id children: model.id
})] })] })] })]
@@ -1306,6 +1635,34 @@ window.__ModuleLoader__.load({
className: "pkc-note", className: "pkc-note",
children: t("modelsEmpty") children: t("modelsEmpty")
}), }),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", {
className: "pkc-advanced",
open: custom.length > 0 ? true : void 0,
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", { children: fill(t("customTitle"), { count: custom.length }) }),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: t("customIntro")
}),
custom.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "pkc-list",
children: custom.map((model) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CustomModelRow, {
model,
disabled,
onRemove: () => void saveCustom(custom.filter((entry) => entry.id !== model.id)),
t
}, model.id))
}),
full ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note",
children: fill(t("customFull"), { count: state.maxCustomModels })
}) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CustomModelForm, {
disabled,
onAdd: (entry) => saveCustom([...custom, entry]),
t
})
]
}),
state.writable !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { state.writable !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "pkc-note", className: "pkc-note",
children: t("searchNotWritable") children: t("searchNotWritable")
+691 -327
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "dsh-geek2api", "name": "dsh-geek2api",
"version": "0.1.4", "version": "0.2.0",
"packageManager": "pnpm@10.32.1", "packageManager": "pnpm@10.32.1",
"description": "Use Geek2API API keys in DeepSeek Harness: a built-in multi-protocol model route with key rotation, multi-endpoint failover, and balance display", "description": "Use Geek2API API keys in DeepSeek Harness: a built-in multi-protocol model route with key rotation, multi-endpoint failover, and balance display",
"type": "module", "type": "module",
+54
View File
@@ -227,6 +227,60 @@ export const GEEK2API_MODELS = Object.freeze([
/** Every model id this catalog advertises, in picker order. */ /** Every model id this catalog advertises, in picker order. */
export const GEEK2API_MODEL_IDS = Object.freeze(GEEK2API_MODELS.map(item => item.id)) export const GEEK2API_MODEL_IDS = Object.freeze(GEEK2API_MODELS.map(item => item.id))
/** The protocols a user-added model can be served over, and each one's base URL. */
export const CUSTOM_MODEL_BASES = Object.freeze({
'openai-completions': OPENAI_BASE,
'openai-responses': OPENAI_BASE,
'anthropic-messages': MESSAGES_BASE,
})
/**
* A user-added model with reasoning: off | low | medium | high. Nothing is
* known about its vendor's levels, so only pi-ai's defaults are offered, less
* `minimal`, which most upstreams refuse; xhigh and max stay unsupported.
*/
const CUSTOM_REASONING_LEVELS = Object.freeze({ minimal: null })
/**
* The catalog entry for a user-added model. The user picks the protocol; the
* gateway compat is the conservative one each protocol's built-in models use.
* @param descriptor - a validated custom-model descriptor (see custom-models.js).
* @returns the pi-ai model.
*/
export function customCatalogModel({ id, name, api, reasoning, image, contextWindow, maxTokens }) {
return model({
id,
name: name === '' ? id : name,
api,
baseUrl: CUSTOM_MODEL_BASES[api],
reasoning: reasoning === true,
input: Object.freeze(image === true ? ['text', 'image'] : ['text']),
contextWindow,
maxTokens,
...(reasoning === true ? { thinkingLevelMap: CUSTOM_REASONING_LEVELS } : {}),
...(api === 'openai-completions' ? { compat: PLAIN_COMPAT } : {}),
})
}
/** Share of a capped context window kept for the response; DSH compaction also reserves 64K headroom. */
const CAPPED_OUTPUT_RATIO = 0.16
const MIN_CAPPED_OUTPUT = 4_096
/**
* A catalog model narrowed to the context window the gateway enforces for the
* keys that serve it (the free DeepSeek group takes 200K per request). The
* max output shrinks with it so DSH's compaction budget — window minus output
* minus headroom — stays positive and compaction starts well before the cap.
* @param catalogModel - a catalog entry.
* @param limit - the gateway's context window for this model, or undefined.
* @returns the entry unchanged when the limit is absent or not tighter; otherwise a narrowed copy.
*/
export function cappedCatalogModel(catalogModel, limit) {
if (!Number.isInteger(limit) || limit <= 0 || !(limit < catalogModel.contextWindow)) return catalogModel
const maxTokens = Math.min(catalogModel.maxTokens, Math.max(MIN_CAPPED_OUTPUT, Math.floor(limit * CAPPED_OUTPUT_RATIO)))
return Object.freeze({ ...catalogModel, contextWindow: limit, maxTokens })
}
/** /**
* Point a catalog model at another entry point, keeping its path: `/v1` for * Point a catalog model at another entry point, keeping its path: `/v1` for
* OpenAI-style models, the bare origin for Messages models. * OpenAI-style models, the bare origin for Messages models.
+60
View File
@@ -67,6 +67,13 @@ export const zh = {
groupsMiss: '不可用', groupsMiss: '不可用',
groupsPartial: '部分', groupsPartial: '部分',
groupsStale: '分组为上次读取的结果', groupsStale: '分组为上次读取的结果',
contextCap: '该分组单次上下文上限 {tokens},会提前自动压缩',
keyExpiresAt: '{when} 到期',
keyExpired: '已到期',
dailyKeyExpiresIn: '免费日卡 · {when} 到期(还剩 {hours} 小时 {minutes} 分)',
dailyKeyRenewOpen: '免费日卡 · {when} 到期,现在就能领下一把,两把同时有效不中断',
dailyKeyExpired: '免费日卡已到期,领一把新的粘贴到这里',
dailyKeyClaim: '去领取 →',
modelsTitle: '显示的模型', modelsTitle: '显示的模型',
modelsIntro: '切换模型时只显示已勾选的 Geek2API 模型,默认全选。修改后立即生效;已有会话仍可继续使用原模型。', modelsIntro: '切换模型时只显示已勾选的 Geek2API 模型,默认全选。修改后立即生效;已有会话仍可继续使用原模型。',
@@ -76,6 +83,29 @@ export const zh = {
modelsNone: '全不选', modelsNone: '全不选',
modelsCount: '已选 {count} / {total}', modelsCount: '已选 {count} / {total}',
modelsEmpty: '未勾选任何模型,切换列表将隐藏 Geek2API 的模型。', modelsEmpty: '未勾选任何模型,切换列表将隐藏 Geek2API 的模型。',
customTitle: '自定义模型({count})',
customIntro: '内置列表里没有的模型,可以按模型 ID 自己添加:填 Geek2API 上的模型名,选它走的协议。添加后立即出现在模型选择器里,和内置模型一样使用多 Key 轮换和多入口切换。能不能用取决于 Key 所在分组,以「账户与 Key」里「自定义」一栏的 ✓ / ✕ 为准。',
customChip: '自定义',
customFamily: '自定义',
customAddTitle: '添加模型',
customIdPlaceholder: '模型 ID,例如 qwen3-max',
customNamePlaceholder: '显示名称(可选)',
customProtocol: '协议',
customProtocolHint: 'Claude 系选 Messages;GPT、Grok 选 Responses;其他大多数模型选 Chat Completions。',
protocolCompletions: 'Chat Completions',
protocolResponses: 'Responses',
protocolMessages: 'Messages',
customCapabilities: '能力',
customReasoning: '推理',
customImage: '可带图',
customLimits: '上下文 / 输出',
customContextPlaceholder: '上下文窗口,默认 128000',
customOutputPlaceholder: '最大输出,默认 32000',
customWindow: '上下文 {context} · 输出 {output}',
customReasoningHint: '勾选「推理」后提供 off / low / medium / high 档位;不勾选则不发送推理参数。',
customAdd: '添加',
customRemove: '删除',
customFull: '最多添加 {count} 个自定义模型。',
hostsTitle: '接口地址', hostsTitle: '接口地址',
hostsIntro: '所有请求按测速结果选用最快的地址;某个地址连不上会暂时跳过,自动改用下一个。', hostsIntro: '所有请求按测速结果选用最快的地址;某个地址连不上会暂时跳过,自动改用下一个。',
@@ -183,6 +213,29 @@ export const en = {
modelsNone: 'Select none', modelsNone: 'Select none',
modelsCount: '{count} / {total} selected', modelsCount: '{count} / {total} selected',
modelsEmpty: 'No models selected. Geek2API models are hidden from the picker.', modelsEmpty: 'No models selected. Geek2API models are hidden from the picker.',
customTitle: 'Custom models ({count})',
customIntro: 'Add a model the built-in list lacks by its id: the model name on Geek2API, and the protocol it is served over. It appears in the model picker at once and uses the same key rotation and endpoint failover as the built-in models. Whether a key can use it depends on the key’s groups; see the ✓ / ✕ under “Custom” in Accounts and keys.',
customChip: 'Custom',
customFamily: 'Custom',
customAddTitle: 'Add a model',
customIdPlaceholder: 'Model id, e.g. qwen3-max',
customNamePlaceholder: 'Display name (optional)',
customProtocol: 'Protocol',
customProtocolHint: 'Claude models: Messages. GPT and Grok: Responses. Most other models: Chat Completions.',
protocolCompletions: 'Chat Completions',
protocolResponses: 'Responses',
protocolMessages: 'Messages',
customCapabilities: 'Capabilities',
customReasoning: 'Reasoning',
customImage: 'Images',
customLimits: 'Context / output',
customContextPlaceholder: 'Context window, default 128000',
customOutputPlaceholder: 'Max output, default 32000',
customWindow: 'context {context} · output {output}',
customReasoningHint: 'With Reasoning, the off / low / medium / high efforts are offered; without it, no reasoning parameter is sent.',
customAdd: 'Add',
customRemove: 'Remove',
customFull: 'At most {count} custom models.',
intro: 'Paste a Geek2API API key to use the built-in model route. Keys are used in order: an exhausted or rejected key hands over to the next one, and a key that cannot reach the selected model is passed over for one that can. Several endpoints are measured and fail over automatically.', intro: 'Paste a Geek2API API key to use the built-in model route. Keys are used in order: an exhausted or rejected key hands over to the next one, and a key that cannot reach the selected model is passed over for one that can. Several endpoints are measured and fail over automatically.',
accountsTitle: 'Accounts and keys', accountsTitle: 'Accounts and keys',
@@ -244,6 +297,13 @@ export const en = {
groupsMiss: 'Not', groupsMiss: 'Not',
groupsPartial: 'partly', groupsPartial: 'partly',
groupsStale: 'groups from the last read', groupsStale: 'groups from the last read',
contextCap: 'This group caps the context at {tokens} per request; sessions compact early',
keyExpiresAt: 'Expires {when}',
keyExpired: 'Expired',
dailyKeyExpiresIn: 'Free daily key · expires {when} ({hours}h {minutes}m left)',
dailyKeyRenewOpen: 'Free daily key · expires {when}; claim the next one now, both stay valid',
dailyKeyExpired: 'Free daily key expired; claim a new one and paste it here',
dailyKeyClaim: 'Claim →',
hostsTitle: 'Endpoints', hostsTitle: 'Endpoints',
hostsIntro: 'Every request uses the fastest endpoint by the last measurement; an endpoint that cannot be reached is skipped for a while and the next one serves.', hostsIntro: 'Every request uses the fastest endpoint by the last measurement; an endpoint that cannot be reached is skipped for a while and the next one serves.',
+3
View File
@@ -85,6 +85,9 @@ export const STYLE = `
.pkc-model>span{display:flex;flex-direction:column;min-width:0;gap:2px} .pkc-model>span{display:flex;flex-direction:column;min-width:0;gap:2px}
.pkc-model b{font-size:13px;font-weight:500} .pkc-model b{font-size:13px;font-weight:500}
.pkc-models:disabled .pkc-model{opacity:.5;cursor:not-allowed} .pkc-models:disabled .pkc-model{opacity:.5;cursor:not-allowed}
.pkc-model b>.pkc-chip{margin-left:6px;vertical-align:1px}
.pkc-check{display:inline-flex;align-items:center;gap:6px;font-size:13px;cursor:pointer}
.pkc-check>input{flex:none;width:16px;height:16px;margin:0;accent-color:var(--dsw-alias-state-business-primary)}
.pkc-setting{display:grid;grid-template-columns:112px minmax(0,1fr);gap:6px 16px;align-items:start} .pkc-setting{display:grid;grid-template-columns:112px minmax(0,1fr);gap:6px 16px;align-items:start}
.pkc-setting>.pkc-label{padding-top:5px} .pkc-setting>.pkc-label{padding-top:5px}
+223 -11
View File
@@ -102,9 +102,16 @@ function remainingShare(usage) {
return Math.max(0, Math.min(1, usage.availableUsd / usage.limitUsd)) return Math.max(0, Math.min(1, usage.availableUsd / usage.limitUsd))
} }
/** Which catalog families a key reaches, from its per-model coverage. */ const BUILT_IN_IDS = new Set(MODEL_FAMILIES.flatMap(([, models]) => models))
function reachOf(coverage) {
return MODEL_FAMILIES.flatMap(([name, models]) => { /**
* Which catalog families a key reaches, from its per-model coverage. Models
* the user added by id form one more family of their own.
*/
function reachOf(coverage, customName) {
const custom = Object.keys(coverage ?? {}).filter(id => !BUILT_IN_IDS.has(id))
const families = custom.length === 0 ? MODEL_FAMILIES : [...MODEL_FAMILIES, [customName, custom]]
return families.flatMap(([name, models]) => {
const known = models.filter(id => typeof coverage?.[id] === 'boolean') const known = models.filter(id => typeof coverage?.[id] === 'boolean')
if (known.length === 0) return [] if (known.length === 0) return []
const reached = known.filter(id => coverage[id] === true) const reached = known.filter(id => coverage[id] === true)
@@ -158,7 +165,7 @@ function KeyGroups({ group, descriptions, loading, t }) {
return loading ? <span className="pkc-meta">{t('groupsChecking')}</span> : null return loading ? <span className="pkc-meta">{t('groupsChecking')}</span> : null
} }
if (group.rejected === true) return <span className="pkc-error">{t('groupsRejected')}</span> if (group.rejected === true) return <span className="pkc-error">{t('groupsRejected')}</span>
const reach = reachOf(group.coverage) const reach = reachOf(group.coverage, t('customFamily'))
const names = Array.isArray(group.groups) ? group.groups : [] const names = Array.isArray(group.groups) ? group.groups : []
return ( return (
<> <>
@@ -183,11 +190,51 @@ function KeyGroups({ group, descriptions, loading, t }) {
</div> </div>
)} )}
{group.extraModels > 0 && <span className="pkc-meta">{fill(t('groupsExtra'), { count: group.extraModels })}</span>} {group.extraModels > 0 && <span className="pkc-meta">{fill(t('groupsExtra'), { count: group.extraModels })}</span>}
<KeyContextCap windows={group.contextWindows} t={t} />
<KeyLifetime lifetime={group.lifetime} t={t} />
{group.stale !== undefined && <span className="pkc-meta">{t('groupsStale')}</span>} {group.stale !== undefined && <span className="pkc-meta">{t('groupsStale')}</span>}
</> </>
) )
} }
/** Where the free daily key is claimed again. */
const FREE_DAILY_SITE = 'https://www.geek2api.com'
const compactTokens = value => (value >= 1000 ? `${Math.round(value / 1000)}K` : String(value))
/** The per-request context cap the key's group enforces (the free DeepSeek group: 200K). */
function KeyContextCap({ windows, t }) {
if (windows === undefined || windows === null) return null
const values = [...new Set(Object.values(windows).filter(value => Number.isInteger(value)))]
if (values.length === 0) return null
return <span className="pkc-meta">{fill(t('contextCap'), { tokens: values.map(compactTokens).join(' / ') })}</span>
}
/** When the key expires; a daily free key also links to the page that issues the next one. */
function KeyLifetime({ lifetime, t }) {
if (lifetime === undefined || lifetime === null || !Number.isFinite(lifetime.expiresAt)) return null
const left = lifetime.expiresAt - Date.now()
const at = new Date(lifetime.expiresAt)
const pad = value => String(value).padStart(2, '0')
const when = `${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(at.getHours())}:${pad(at.getMinutes())}`
const hours = Math.max(0, Math.floor(left / 3_600_000))
const minutes = Math.max(0, Math.floor((left % 3_600_000) / 60_000))
if (lifetime.daily !== true) {
return <span className="pkc-meta">{left > 0 ? fill(t('keyExpiresAt'), { when }) : t('keyExpired')}</span>
}
const renewOpen = left <= (lifetime.renewWindowHours ?? 2) * 3_600_000
const href = `${FREE_DAILY_SITE}${lifetime.renewPath ?? '/free-ds'}`
return (
<span className={left <= 0 || renewOpen ? 'pkc-error' : 'pkc-meta'}>
{left <= 0
? t('dailyKeyExpired')
: fill(renewOpen ? t('dailyKeyRenewOpen') : t('dailyKeyExpiresIn'), { when, hours, minutes })}
{' '}
<a href={href} target="_blank" rel="noreferrer noopener">{t('dailyKeyClaim')}</a>
</span>
)
}
function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, skippedUntil, t }) { function KeyRow({ entry, row, group, descriptions, groupsLoading, busy, renaming, onRename, onAction, skippedUntil, t }) {
const usage = row?.usage const usage = row?.usage
const share = remainingShare(usage) const share = remainingShare(usage)
@@ -527,7 +574,138 @@ function HostsCard({ call, t }) {
) )
} }
// ── model visibility ──────────────────────────────────────────────────────── // ── model visibility and custom models ─────────────────────────────────────
const PROTOCOL_KEYS = {
'openai-completions': 'protocolCompletions',
'openai-responses': 'protocolResponses',
'anthropic-messages': 'protocolMessages',
}
const EMPTY_CUSTOM = { id: '', name: '', api: 'openai-completions', reasoning: false, image: false, contextWindow: '', maxTokens: '' }
/** One user-added model: its protocol and capabilities, and a remove button. */
function CustomModelRow({ model, disabled, onRemove, t }) {
const facts = [
t(PROTOCOL_KEYS[model.api] ?? 'protocolCompletions'),
model.reasoning ? t('customReasoning') : undefined,
model.image ? t('customImage') : undefined,
fill(t('customWindow'), { context: model.contextWindow.toLocaleString(), output: model.maxTokens.toLocaleString() }),
].filter(Boolean).join(' · ')
return (
<div className="pkc-row">
<div className="pkc-row-top">
<span className="pkc-row-name">
<span className="pkc-name">{model.name === '' ? model.id : model.name}</span>
{model.name !== '' && <span className="pkc-meta pkc-mono">{model.id}</span>}
</span>
<span className="pkc-actions">
<Button variant="danger" disabled={disabled} onClick={onRemove}>{t('customRemove')}</Button>
</span>
</div>
<span className="pkc-meta">{facts}</span>
</div>
)
}
/** The form that adds a model by id. */
function CustomModelForm({ disabled, onAdd, t }) {
const [draft, setDraft] = react.useState(EMPTY_CUSTOM)
const set = patch => setDraft(current => ({ ...current, ...patch }))
const submit = event => {
event.preventDefault()
if (disabled || draft.id.trim() === '') return
const entry = {
id: draft.id.trim(),
name: draft.name.trim(),
api: draft.api,
reasoning: draft.reasoning,
image: draft.image,
...(draft.contextWindow.trim() === '' ? {} : { contextWindow: Number(draft.contextWindow) }),
...(draft.maxTokens.trim() === '' ? {} : { maxTokens: Number(draft.maxTokens) }),
}
void onAdd(entry).then(saved => {
if (saved) setDraft(EMPTY_CUSTOM)
})
}
return (
<form className="pkc-add" onSubmit={submit}>
<span className="pkc-label">{t('customAddTitle')}</span>
<div className="pkc-form">
<input
className="pkc-input pkc-mono"
type="text"
maxLength={128}
spellCheck={false}
autoComplete="off"
placeholder={t('customIdPlaceholder')}
disabled={disabled}
value={draft.id}
onChange={event => set({ id: event.target.value })}
/>
<input
className="pkc-input"
type="text"
maxLength={64}
placeholder={t('customNamePlaceholder')}
disabled={disabled}
value={draft.name}
onChange={event => set({ name: event.target.value })}
/>
</div>
<div className="pkc-setting">
<span className="pkc-label">{t('customProtocol')}</span>
<div>
<Segmented
label={t('customProtocol')}
options={Object.keys(PROTOCOL_KEYS).map(value => ({ value, label: t(PROTOCOL_KEYS[value]) }))}
value={draft.api}
disabled={disabled}
onChange={api => set({ api })}
/>
<p className="pkc-note">{t('customProtocolHint')}</p>
</div>
<span className="pkc-label">{t('customCapabilities')}</span>
<div className="pkc-form">
<label className="pkc-check">
<input type="checkbox" disabled={disabled} checked={draft.reasoning} onChange={event => set({ reasoning: event.target.checked })} />
{t('customReasoning')}
</label>
<label className="pkc-check">
<input type="checkbox" disabled={disabled} checked={draft.image} onChange={event => set({ image: event.target.checked })} />
{t('customImage')}
</label>
</div>
<span className="pkc-label">{t('customLimits')}</span>
<div className="pkc-form">
<input
className="pkc-input"
type="number"
min={1000}
step={1000}
placeholder={t('customContextPlaceholder')}
disabled={disabled}
value={draft.contextWindow}
onChange={event => set({ contextWindow: event.target.value })}
/>
<input
className="pkc-input"
type="number"
min={1}
step={1000}
placeholder={t('customOutputPlaceholder')}
disabled={disabled}
value={draft.maxTokens}
onChange={event => set({ maxTokens: event.target.value })}
/>
</div>
</div>
<div className="pkc-split">
<p className="pkc-note">{t('customReasoningHint')}</p>
<Button type="submit" variant="primary" disabled={disabled || draft.id.trim() === ''}>{t('customAdd')}</Button>
</div>
</form>
)
}
function ModelsCard({ call, t }) { function ModelsCard({ call, t }) {
const [state, setState] = react.useState() const [state, setState] = react.useState()
@@ -545,17 +723,28 @@ function ModelsCard({ call, t }) {
}, [call]) }, [call])
const models = state?.models ?? [] const models = state?.models ?? []
const custom = Array.isArray(state?.customModels) ? state.customModels : []
const selectedIds = models.filter(model => model.selected).map(model => model.id) const selectedIds = models.filter(model => model.selected).map(model => model.id)
const disabled = busy || state?.writable !== true const disabled = busy || state?.writable !== true
const update = ids => { /** Run one write; resolves true when it was saved. */
if (disabled) return const write = (endpoint, payload) => {
if (disabled) return Promise.resolve(false)
setBusy(true) setBusy(true)
setError(undefined) setError(undefined)
call('models/update', { selectedIds: ids }) return call(endpoint, payload)
.then(setState) .then(next => {
.catch(failure => setError(clearMessage(failure))) setState(next)
return true
})
.catch(failure => {
setError(clearMessage(failure))
return false
})
.finally(() => setBusy(false)) .finally(() => setBusy(false))
} }
const update = ids => void write('models/update', { selectedIds: ids })
const saveCustom = list => write('models/custom/update', { customModels: list })
const full = custom.length >= (state?.maxCustomModels ?? Infinity)
return ( return (
<Card title={t('modelsTitle')} aside={state !== undefined && <span className="pkc-meta">{fill(t('modelsCount'), { count: selectedIds.length, total: models.length })}</span>}> <Card title={t('modelsTitle')} aside={state !== undefined && <span className="pkc-meta">{fill(t('modelsCount'), { count: selectedIds.length, total: models.length })}</span>}>
@@ -575,11 +764,34 @@ function ModelsCard({ call, t }) {
checked={model.selected} checked={model.selected}
onChange={event => update(event.target.checked ? [...selectedIds, model.id] : selectedIds.filter(id => id !== model.id))} onChange={event => update(event.target.checked ? [...selectedIds, model.id] : selectedIds.filter(id => id !== model.id))}
/> />
<span><b>{model.name}</b><span className="pkc-meta pkc-mono">{model.id}</span></span> <span>
<b>{model.name}{model.custom === true && <span className="pkc-chip" data-tone="info">{t('customChip')}</span>}</b>
<span className="pkc-meta pkc-mono">{model.id}</span>
</span>
</label> </label>
))} ))}
</fieldset> </fieldset>
{selectedIds.length === 0 && <p className="pkc-note">{t('modelsEmpty')}</p>} {selectedIds.length === 0 && <p className="pkc-note">{t('modelsEmpty')}</p>}
<details className="pkc-advanced" open={custom.length > 0 ? true : undefined}>
<summary>{fill(t('customTitle'), { count: custom.length })}</summary>
<p className="pkc-note">{t('customIntro')}</p>
{custom.length > 0 && (
<div className="pkc-list">
{custom.map(model => (
<CustomModelRow
key={model.id}
model={model}
disabled={disabled}
onRemove={() => void saveCustom(custom.filter(entry => entry.id !== model.id))}
t={t}
/>
))}
</div>
)}
{full
? <p className="pkc-note">{fill(t('customFull'), { count: state.maxCustomModels })}</p>
: <CustomModelForm disabled={disabled} onAdd={entry => saveCustom([...custom, entry])} t={t} />}
</details>
{state.writable !== true && <p className="pkc-note">{t('searchNotWritable')}</p>} {state.writable !== true && <p className="pkc-note">{t('searchNotWritable')}</p>}
</> </>
)} )}
+126
View File
@@ -0,0 +1,126 @@
/**
* Models the user adds by id, next to the built-in catalog.
*
* Geek2API serves more models than the catalog declares (a key's
* `/v1/models` lists them). A user-added model names its id, the protocol the
* gateway serves it over, and whether it takes a reasoning effort or images;
* the route then serves it exactly like a built-in one, with the same keys,
* endpoints, failover, and key rotation.
*
* The list is a volatile preference (`customModels`). Writes from the panel
* are validated strictly and refused with a reason; a hand-edited profile is
* read leniently, dropping only the entries that cannot be served.
*
* @module dsh-geek2api/custom-models
*/
import z from '@deepseek-ai/schemastery'
import { CUSTOM_MODEL_BASES, GEEK2API_MODEL_IDS } from './catalog.js'
/** The protocols a custom model can use, in the order the panel offers them. */
export const CUSTOM_MODEL_PROTOCOLS = Object.freeze(Object.keys(CUSTOM_MODEL_BASES))
/** How many custom models one profile may declare. */
export const MAX_CUSTOM_MODELS = 32
export const DEFAULT_CUSTOM_CONTEXT_WINDOW = 128_000
export const DEFAULT_CUSTOM_MAX_TOKENS = 32_000
const MIN_CONTEXT_WINDOW = 1_000
const MAX_CONTEXT_WINDOW = 10_000_000
const MAX_NAME = 64
/** Gateway model ids: letters, digits and `. _ - : / @ +`, starting with a letter or digit. */
const ID_PATTERN = /^[A-Za-z0-9][\w.:/@+-]{0,127}$/u
/** The stored shape; every field but the id has a default. */
export const CustomModelSchema = z.object({
id: z.string(),
name: z.string().default(''),
api: z.union([...CUSTOM_MODEL_PROTOCOLS]).default('openai-completions'),
reasoning: z.boolean().default(false),
image: z.boolean().default(false),
contextWindow: z.natural().default(DEFAULT_CUSTOM_CONTEXT_WINDOW),
maxTokens: z.natural().default(DEFAULT_CUSTOM_MAX_TOKENS),
})
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value)
/** A positive integer field, its default when absent, or undefined when invalid. */
function integerField(value, fallback, min, max) {
if (value === undefined || value === null || value === '') return fallback
const number = typeof value === 'string' ? Number(value.trim()) : value
return Number.isInteger(number) && number >= min && number <= max ? number : undefined
}
/**
* Validate one entry.
* @param entry - a stored or submitted entry.
* @returns the normalized descriptor.
* @throws an Error naming what is wrong; the message is safe for the panel.
*/
export function parseCustomModel(entry) {
if (!record(entry)) throw new Error('Geek2API custom model entries must be objects')
const id = typeof entry.id === 'string' ? entry.id.trim() : ''
if (id === '') throw new Error('Geek2API custom model needs a model id')
if (!ID_PATTERN.test(id)) throw new Error(`Geek2API custom model id "${id.slice(0, 128)}" may only use letters, digits and . _ - : / @ +`)
if (GEEK2API_MODEL_IDS.includes(id)) throw new Error(`Geek2API custom model "${id}" is already a built-in model`)
const api = entry.api ?? 'openai-completions'
if (!CUSTOM_MODEL_PROTOCOLS.includes(api)) throw new Error(`Geek2API custom model "${id}" names an unsupported protocol`)
const contextWindow = integerField(entry.contextWindow, DEFAULT_CUSTOM_CONTEXT_WINDOW, MIN_CONTEXT_WINDOW, MAX_CONTEXT_WINDOW)
if (contextWindow === undefined) {
throw new Error(`Geek2API custom model "${id}" needs a context window between ${MIN_CONTEXT_WINDOW} and ${MAX_CONTEXT_WINDOW} tokens`)
}
const maxTokens = integerField(entry.maxTokens, Math.min(DEFAULT_CUSTOM_MAX_TOKENS, contextWindow), 1, contextWindow)
if (maxTokens === undefined) throw new Error(`Geek2API custom model "${id}" needs max output tokens between 1 and its context window`)
const name = typeof entry.name === 'string' ? entry.name.replace(/\s+/gu, ' ').trim().slice(0, MAX_NAME) : ''
return Object.freeze({
id,
name,
api,
reasoning: entry.reasoning === true,
image: entry.image === true,
contextWindow,
maxTokens,
})
}
/**
* Validate a list the panel submitted: every entry must be servable.
* @param list - the submitted entries.
* @returns the normalized descriptors, in order.
* @throws on the first invalid entry, a duplicate, or too many entries.
*/
export function validateCustomModels(list) {
if (!Array.isArray(list)) throw new Error('Geek2API custom models must be a list')
if (list.length > MAX_CUSTOM_MODELS) throw new Error(`Geek2API allows at most ${MAX_CUSTOM_MODELS} custom models`)
const seen = new Set()
return list.map(entry => {
const parsed = parseCustomModel(entry)
if (seen.has(parsed.id)) throw new Error(`Geek2API custom model "${parsed.id}" is listed twice`)
seen.add(parsed.id)
return parsed
})
}
/**
* Read the stored list leniently: an entry that cannot be served, or repeats
* an id, is dropped instead of taking the whole route down.
* @param value - the `customModels` preference.
* @returns the servable descriptors, in order.
*/
export function readCustomModels(value) {
if (!Array.isArray(value)) return []
const seen = new Set()
const models = []
for (const entry of value) {
if (models.length >= MAX_CUSTOM_MODELS) break
let parsed
try {
parsed = parseCustomModel(entry)
} catch {
continue
}
if (seen.has(parsed.id)) continue
seen.add(parsed.id)
models.push(parsed)
}
return models
}
+77 -10
View File
@@ -92,25 +92,66 @@ export function parseKeyGroups(payload) {
return names.length === 0 ? undefined : [...new Set(names)].slice(0, MAX_GROUPS) return names.length === 0 ? undefined : [...new Set(names)].slice(0, MAX_GROUPS)
} }
/** Smallest context window the gateway may report for a model; anything smaller is ignored as noise. */
const MIN_REPORTED_CONTEXT_WINDOW = 8_192
/**
* Per-model context windows from a `/v1/models` body. sub2api reports
* `context_window` when the key's group caps the input per request (the free
* DeepSeek group allows 200K although the model itself takes 1M).
* @param data - the `data` array of the model list.
* @returns model id → context window, only for models that report one.
*/
export function parseContextWindows(data) {
const windows = new Map()
if (!Array.isArray(data)) return windows
for (const item of data) {
const id = item?.id
const value = item?.context_window
if (typeof id === 'string' && Number.isInteger(value) && value >= MIN_REPORTED_CONTEXT_WINDOW) windows.set(id, value)
}
return windows
}
/**
* The key's lifetime from `/v1/usage`: when it expires and whether it is a
* daily free key that is re-claimed on the website.
* @param payload - the usage body.
* @returns `{ expiresAt, daily, renewWindowHours, renewPath }`, or undefined when the key never expires.
*/
export function parseKeyLifetime(payload) {
const key = record(payload?.key) ? payload.key : undefined
if (key === undefined || typeof key.expires_at !== 'string') return undefined
const expiresAt = Date.parse(key.expires_at)
if (!Number.isFinite(expiresAt)) return undefined
const daily = key.purpose === 'free_daily'
const renewWindowHours = Number.isInteger(key.renew_window_hours) && key.renew_window_hours > 0 ? key.renew_window_hours : 2
const renewPath = typeof key.renew_path === 'string' && /^\/[a-z0-9/_-]{1,64}$/iu.test(key.renew_path) ? key.renew_path : '/free-ds'
return Object.freeze({ expiresAt, daily, ...(daily ? { renewWindowHours, renewPath } : {}) })
}
/** /**
* Which catalog models a key can reach, from its model list. A model is * Which catalog models a key can reach, from its model list. A model is
* only marked unreachable on evidence; with no list it is left unknown. * only marked unreachable on evidence; with no list it is left unknown.
* @param models - the key's model ids, or undefined. * @param models - the key's model ids, or undefined.
* @param ids - the catalog's ids, built-in and custom.
* @returns catalog model id → reachable. * @returns catalog model id → reachable.
*/ */
export function catalogCoverage(models) { export function catalogCoverage(models, ids = GEEK2API_MODEL_IDS) {
if (models === undefined) return {} if (models === undefined) return {}
return Object.fromEntries(GEEK2API_MODEL_IDS.map(id => [id, models.has(id)])) return Object.fromEntries(ids.map(id => [id, models.has(id)]))
} }
/** /**
* Cached, single-flight group reader. * Cached, single-flight group reader.
* @param options - key listing, the host pool, and transport knobs. * @param options - key listing, the host pool, the catalog's ids (built-in and
* @returns `{ read, snapshot, hasReading, covers, requiredGroups, groupsOf, invalidate }`. * custom; drop the reading when they change), and transport knobs.
* @returns `{ read, snapshot, hasReading, covers, contextLimitFor, lifetimeOf, requiredGroups, groupsOf, invalidate }`.
*/ */
export function createGroupReader({ export function createGroupReader({
listKeys, listKeys,
hosts, hosts,
modelIds = () => GEEK2API_MODEL_IDS,
fetchImpl = ambientFetch, fetchImpl = ambientFetch,
now = Date.now, now = Date.now,
ttlMs = DEFAULT_GROUP_TTL_MS, ttlMs = DEFAULT_GROUP_TTL_MS,
@@ -137,7 +178,10 @@ export function createGroupReader({
} }
const payload = await response.json() const payload = await response.json()
if (!Array.isArray(payload?.data)) throw new Error('the gateway returned an unrecognized model list') if (!Array.isArray(payload?.data)) throw new Error('the gateway returned an unrecognized model list')
return new Set(payload.data.map(item => item?.id).filter(id => typeof id === 'string')) return {
ids: new Set(payload.data.map(item => item?.id).filter(id => typeof id === 'string')),
windows: parseContextWindows(payload.data),
}
} }
/** The key's groups, when the gateway names them. */ /** The key's groups, when the gateway names them. */
@@ -145,7 +189,8 @@ export function createGroupReader({
const response = await get('/v1/usage?lite=1', entry, signal) const response = await get('/v1/usage?lite=1', entry, signal)
if (response.status === 401) throw new RejectedKeyError() if (response.status === 401) throw new RejectedKeyError()
if (!response.ok) return undefined if (!response.ok) return undefined
return parseKeyGroups(await response.json()) const payload = await response.json()
return { groups: parseKeyGroups(payload), lifetime: parseKeyLifetime(payload) }
} }
/** /**
@@ -157,7 +202,8 @@ export function createGroupReader({
const [models, groups] = await Promise.allSettled([loadModels(entry, signal), loadGroups(entry, signal)]) const [models, groups] = await Promise.allSettled([loadModels(entry, signal), loadGroups(entry, signal)])
if ([models, groups].some(result => result.status === 'rejected' && result.reason instanceof RejectedKeyError)) return { rejected: true } if ([models, groups].some(result => result.status === 'rejected' && result.reason instanceof RejectedKeyError)) return { rejected: true }
if (models.status === 'rejected') throw models.reason if (models.status === 'rejected') throw models.reason
return { models: models.value, groups: groups.status === 'fulfilled' ? groups.value : undefined } const usage = groups.status === 'fulfilled' ? groups.value : undefined
return { models: models.value.ids, windows: models.value.windows, groups: usage?.groups, lifetime: usage?.lifetime }
} }
const load = async signal => { const load = async signal => {
@@ -168,19 +214,22 @@ export function createGroupReader({
} }
const readings = await mapLimited(keys, KEY_CONCURRENCY, entry => readKey(entry, signal).then(value => ({ value }), error => ({ error }))) const readings = await mapLimited(keys, KEY_CONCURRENCY, entry => readKey(entry, signal).then(value => ({ value }), error => ({ error })))
signal?.throwIfAborted() signal?.throwIfAborted()
const ids = modelIds()
const entries = keys.map((entry, index) => { const entries = keys.map((entry, index) => {
const { value, error } = readings[index] const { value, error } = readings[index]
if (value?.rejected === true) { if (value?.rejected === true) {
// Evidence, not a failed read: a rejected key reaches nothing. // Evidence, not a failed read: a rejected key reaches nothing.
lastGood.delete(entry.id) lastGood.delete(entry.id)
return { id: entry.id, rejected: true, coverage: Object.fromEntries(GEEK2API_MODEL_IDS.map(id => [id, false])), error: new RejectedKeyError().message } return { id: entry.id, rejected: true, coverage: Object.fromEntries(ids.map(id => [id, false])), error: new RejectedKeyError().message }
} }
if (value !== undefined) { if (value !== undefined) {
const reading = { const reading = {
id: entry.id, id: entry.id,
...(value.groups === undefined ? {} : { groups: value.groups }), ...(value.groups === undefined ? {} : { groups: value.groups }),
coverage: catalogCoverage(value.models), ...(value.lifetime === undefined ? {} : { lifetime: value.lifetime }),
extraModels: [...value.models].filter(id => !GEEK2API_MODEL_IDS.includes(id)).length, ...(value.windows.size === 0 ? {} : { contextWindows: Object.fromEntries(value.windows) }),
coverage: catalogCoverage(value.models, ids),
extraModels: [...value.models].filter(id => !ids.includes(id)).length,
} }
lastGood.set(entry.id, { value: reading, fetchedAt: now() }) lastGood.set(entry.id, { value: reading, fetchedAt: now() })
return reading return reading
@@ -214,6 +263,24 @@ export function createGroupReader({
}, },
/** Geek2API publishes no per-model group table; always undefined. */ /** Geek2API publishes no per-model group table; always undefined. */
requiredGroups: () => undefined, requiredGroups: () => undefined,
/**
* The tightest context window any key that reaches `modelId` reports, from
* the last reading. A key that reports none is not limited by its group.
* @returns the window in tokens, or undefined when no covering key reports one.
*/
contextLimitFor(modelId) {
let limit
for (const entry of cache.peek()?.keys ?? []) {
if (entry.rejected === true || entry.coverage?.[modelId] !== true) continue
const value = entry.contextWindows?.[modelId]
if (Number.isInteger(value) && (limit === undefined || value < limit)) limit = value
}
return limit
},
/** When a key expires and whether it is a daily free key, from the last reading. */
lifetimeOf(keyId) {
return keyEntry(keyId)?.lifetime
},
/** The groups the last reading found for a key. */ /** The groups the last reading found for a key. */
groupsOf(keyId) { groupsOf(keyId) {
const groups = keyEntry(keyId)?.groups const groups = keyEntry(keyId)?.groups
+35 -13
View File
@@ -19,12 +19,12 @@ import { join } from 'node:path'
import z from '@deepseek-ai/schemastery' import z from '@deepseek-ai/schemastery'
import { createBalanceReader } from './balance.js' import { createBalanceReader } from './balance.js'
import { GEEK2API_MODEL_IDS } from './catalog.js'
import { CLI_BACKED_MODEL_IDS, createClaudeCliAdapter } from './claude-adapter.js' import { CLI_BACKED_MODEL_IDS, createClaudeCliAdapter } from './claude-adapter.js'
import { DEFAULT_CLAUDE_MODE, createClaudeRunner } from './claude-cli.js' import { DEFAULT_CLAUDE_MODE, createClaudeRunner } from './claude-cli.js'
import { createClaudeCliManager } from './claude-install.js' import { createClaudeCliManager } from './claude-install.js'
import { createClaudeSearchBridge } from './claude-search-mcp.js' import { createClaudeSearchBridge } from './claude-search-mcp.js'
import { createClaudeCodeTool } from './claude-tool.js' import { createClaudeCodeTool } from './claude-tool.js'
import { CustomModelSchema } from './custom-models.js'
import { import {
CHANNEL, CHANNEL,
DEFAULT_API_HOSTS, DEFAULT_API_HOSTS,
@@ -92,6 +92,11 @@ export const Config = z.object({
searchBackend: live(z.union([...SEARCH_BACKENDS]).default(DEFAULT_SEARCH_BACKEND)), searchBackend: live(z.union([...SEARCH_BACKENDS]).default(DEFAULT_SEARCH_BACKEND)),
/** Only the picker is filtered; an existing session can keep its model. */ /** Only the picker is filtered; an existing session can keep its model. */
hiddenModels: live(z.array(z.string()).default([])), hiddenModels: live(z.array(z.string()).default([])),
/**
* Models added by id, served next to the built-in catalog over the protocol
* each one names. Entries that cannot be served are dropped when read.
*/
customModels: live(z.array(CustomModelSchema).default([])),
}) })
export function apply(ctx, config) { export function apply(ctx, config) {
@@ -106,12 +111,28 @@ export function apply(ctx, config) {
searchProvider: fieldValue(config?.searchProvider), searchProvider: fieldValue(config?.searchProvider),
searchBackend: fieldValue(config?.searchBackend), searchBackend: fieldValue(config?.searchBackend),
hiddenModels: fieldValue(config?.hiddenModels), hiddenModels: fieldValue(config?.hiddenModels),
customModels: fieldValue(config?.customModels),
}) })
/** Every request picks its entry point from this pool. */ /** Every request picks its entry point from this pool. */
const hosts = createHostPool({ listHosts: () => normalizeHostList(fieldValue((source() ?? {}).apiHosts)), logger: ctx.logger }) const hosts = createHostPool({ listHosts: () => normalizeHostList(fieldValue((source() ?? {}).apiHosts)), logger: ctx.logger })
/** Whether the Claude models run through the local CLI this turn. */ /** Whether the Claude models run through the local CLI this turn. */
const claudeRuntime = () => (fieldValue((source() ?? {}).claudeRuntime) === 'cli' ? 'cli' : 'http') const claudeRuntime = () => (fieldValue((source() ?? {}).claudeRuntime) === 'cli' ? 'cli' : 'http')
const modelPreference = { writable: false, set: undefined }
let refreshModels = () => {}
let groups
/** The live catalog (built-in plus custom models) and which of it the picker shows. */
const modelSelection = createModelSelectionController({
readPreference: () => source() ?? {},
writePreference: patch => modelPreference.set(patch),
isWritable: () => modelPreference.writable === true && typeof modelPreference.set === 'function',
onChange: () => refreshModels(),
// Coverage is measured per catalog id: re-read it for a changed catalog.
onCatalogChange: () => groups?.invalidate(),
// The free DeepSeek group caps the input at 200K: narrow the model for the keys that report it.
contextLimitFor: modelId => groups?.contextLimitFor(modelId),
})
// A read showing money brings back a key skipped for running out of it. // A read showing money brings back a key skipped for running out of it.
const balance = createBalanceReader({ listKeys: () => ring.secrets(), hosts, onRead: rows => keys.noteBalances(rows) }) const balance = createBalanceReader({ listKeys: () => ring.secrets(), hosts, onRead: rows => keys.noteBalances(rows) })
/** /**
@@ -119,7 +140,7 @@ export function apply(ctx, config) {
* Nothing reads it at boot: the settings panel asks for it, and a request * Nothing reads it at boot: the settings panel asks for it, and a request
* with a choice of keys waits briefly for the first reading. * with a choice of keys waits briefly for the first reading.
*/ */
const groups = createGroupReader({ listKeys: () => ring.secrets(), hosts }) groups = createGroupReader({ listKeys: () => ring.secrets(), hosts, modelIds: () => modelSelection.ids() })
const keys = createKeyChooser({ ring, groups, logger: ctx.logger, onRotated: () => balance.invalidate() }) const keys = createKeyChooser({ ring, groups, logger: ctx.logger, onRotated: () => balance.invalidate() })
/** The session of the agent this turn runs for, when one is in scope. */ /** The session of the agent this turn runs for, when one is in scope. */
@@ -140,14 +161,6 @@ export function apply(ctx, config) {
} }
const fallbackSessionId = `${PLUGIN_ID}-${randomUUID()}` const fallbackSessionId = `${PLUGIN_ID}-${randomUUID()}`
const attachments = () => ctx.get?.('attachments') ?? ctx.attachments const attachments = () => ctx.get?.('attachments') ?? ctx.attachments
const modelPreference = { writable: false, set: undefined }
let refreshModels = () => {}
const modelSelection = createModelSelectionController({
readPreference: () => source() ?? {},
writePreference: patch => modelPreference.set(patch),
isWritable: () => modelPreference.writable === true && typeof modelPreference.set === 'function',
onChange: () => refreshModels(),
})
// ── the model route ─────────────────────────────────────────────────────── // ── the model route ───────────────────────────────────────────────────────
@@ -163,7 +176,7 @@ export function apply(ctx, config) {
binary: () => claudeCli.binary(), binary: () => claudeCli.binary(),
resolveCredential: async ({ model } = {}) => { resolveCredential: async ({ model } = {}) => {
// A delegated run without a model runs the CLI's default, a Claude model. // A delegated run without a model runs the CLI's default, a Claude model.
const choice = await keys.forRun(GEEK2API_MODEL_IDS.includes(model) ? model : CLI_GROUP_MODEL) const choice = await keys.forRun(modelSelection.ids().includes(model) ? model : CLI_GROUP_MODEL)
if (choice === undefined) { if (choice === undefined) {
throw new Error('Claude Code CLI needs a usable Geek2API API key; add one under Settings → Geek2API') throw new Error('Claude Code CLI needs a usable Geek2API API key; add one under Settings → Geek2API')
} }
@@ -214,7 +227,15 @@ export function apply(ctx, config) {
// CLI-backed ids run the Claude Code CLI; everything else keeps the pi-ai path. // CLI-backed ids run the Claude Code CLI; everything else keeps the pi-ai path.
const registration = ctx.llm.registerAdapter([PROVIDER], createClaudeCliAdapter({ const registration = ctx.llm.registerAdapter([PROVIDER], createClaudeCliAdapter({
inner: createRouteAdapter({ ring, keys, hosts, fallbackSessionId, resolveAttachments: attachments, isModelVisible: modelSelection.isVisible }), inner: createRouteAdapter({
ring,
keys,
hosts,
fallbackSessionId,
resolveAttachments: attachments,
isModelVisible: modelSelection.isVisible,
listModels: modelSelection.models,
}),
runner: claudeRunner, runner: claudeRunner,
isCliModel: id => claudeRuntime() === 'cli' && CLI_BACKED_MODEL_IDS.includes(id), isCliModel: id => claudeRuntime() === 'cli' && CLI_BACKED_MODEL_IDS.includes(id),
// Plan mode is "do not implement yet" for this turn, so it wins over the // Plan mode is "do not implement yet" for this turn, so it wins over the
@@ -402,7 +423,8 @@ export { createClaudeSearchBridge, cliSearchInstructions } from './claude-search
export { AUTO_CLAUDE_MODE, capClaudeMode, claudeModeFor, claudeModeForSession, planModeForSession, planModeForToolExecution } from './permission.js' export { AUTO_CLAUDE_MODE, capClaudeMode, claudeModeFor, claudeModeForSession, planModeForSession, planModeForToolExecution } from './permission.js'
export { createBalanceReader, parseKeyUsage } from './balance.js' export { createBalanceReader, parseKeyUsage } from './balance.js'
export { createHostPool, isTransportFailure, normalizeHost, normalizeHostList } from './hosts.js' export { createHostPool, isTransportFailure, normalizeHost, normalizeHostList } from './hosts.js'
export { GEEK2API_MODELS, GEEK2API_MODEL_IDS, modelForHost } from './catalog.js' export { CUSTOM_MODEL_BASES, customCatalogModel, GEEK2API_MODELS, GEEK2API_MODEL_IDS, modelForHost } from './catalog.js'
export { CUSTOM_MODEL_PROTOCOLS, MAX_CUSTOM_MODELS, parseCustomModel, readCustomModels, validateCustomModels } from './custom-models.js'
export { export {
CHANNEL, CHANNEL,
DEFAULT_API_HOST, DEFAULT_API_HOST,
+93 -15
View File
@@ -1,51 +1,129 @@
/** Profile preferences for the models advertised in Geek2API's picker. */ /**
import { GEEK2API_MODELS, GEEK2API_MODEL_IDS } from './catalog.js' * The models advertised in Geek2API's picker: the built-in catalog plus the
* models the user added by id, less the ones the user hid.
*
* This controller owns the live catalog. The route serves it, the group
* reader measures each key's coverage of it, and the panel edits both
* preferences through it.
*
* @module dsh-geek2api/model-selection
*/
import { cappedCatalogModel, customCatalogModel, GEEK2API_MODELS, GEEK2API_MODEL_IDS } from './catalog.js'
import { CUSTOM_MODEL_PROTOCOLS, MAX_CUSTOM_MODELS, readCustomModels, validateCustomModels } from './custom-models.js'
import { fieldValue } from './preferences.js' import { fieldValue } from './preferences.js'
/** Store exclusions so new catalog models are selected by default as well. */ /**
export function readHiddenModels(preference) { * Store exclusions so new catalog models are selected by default as well.
* @param preference - the preference source.
* @param ids - the ids the catalog currently advertises.
* @returns the hidden ids, in catalog order.
*/
export function readHiddenModels(preference, ids = GEEK2API_MODEL_IDS) {
const value = fieldValue(preference?.hiddenModels) const value = fieldValue(preference?.hiddenModels)
if (!Array.isArray(value)) return [] if (!Array.isArray(value)) return []
const hidden = new Set(value) const hidden = new Set(value)
return GEEK2API_MODEL_IDS.filter(id => hidden.has(id)) return ids.filter(id => hidden.has(id))
} }
export function createModelSelectionController({ readPreference, writePreference, isWritable, onChange }) { export function createModelSelectionController({ readPreference, writePreference, isWritable, onChange, onCatalogChange, contextLimitFor = () => undefined }) {
const hidden = () => readHiddenModels(readPreference()) /**
let advertised = hidden().join(',') * The catalog for the current preference, rebuilt only when the custom list
* or a gateway context cap changes: the route recognizes an unchanged
* catalog by identity. Caps come from the keys' model lists (a group that
* limits the input per request, like the free DeepSeek group's 200K), so a
* session compacts before the gateway refuses it.
*/
let memo = { key: '[]', limits: '{}', base: GEEK2API_MODELS, custom: [], models: GEEK2API_MODELS, ids: GEEK2API_MODEL_IDS }
const catalog = () => {
const custom = readCustomModels(fieldValue((readPreference() ?? {}).customModels))
const key = JSON.stringify(custom)
const base = key === memo.key ? memo.base : [...GEEK2API_MODELS, ...custom.map(customCatalogModel)]
const caps = {}
for (const model of base ?? []) {
const limit = contextLimitFor(model.id)
if (Number.isInteger(limit) && limit < model.contextWindow) caps[model.id] = limit
}
const limits = JSON.stringify(caps)
if (key !== memo.key || limits !== memo.limits) {
const models = Object.freeze(base.map(model => cappedCatalogModel(model, caps[model.id])))
memo = { key, limits, base, custom, models, ids: Object.freeze(models.map(model => model.id)) }
}
return memo
}
const hidden = () => readHiddenModels(readPreference(), catalog().ids)
const signature = () => ({ hidden: hidden().join(','), catalog: catalog().key })
let advertised = signature()
const reconcile = () => { const reconcile = () => {
const next = hidden().join(',') const next = signature()
if (next === advertised) return if (next.hidden === advertised.hidden && next.catalog === advertised.catalog) return
onChange?.() const catalogChanged = next.catalog !== advertised.catalog
advertised = next advertised = next
if (catalogChanged) onCatalogChange?.()
onChange?.()
} }
const status = () => { const status = () => {
const excluded = new Set(hidden()) const excluded = new Set(hidden())
const { custom } = catalog()
const customIds = new Set(custom.map(entry => entry.id))
return { return {
writable: isWritable() === true, writable: isWritable() === true,
models: GEEK2API_MODELS.map(({ id, name }) => ({ id, name, selected: !excluded.has(id) })), models: catalog().models.map(({ id, name }) => ({
id,
name,
selected: !excluded.has(id),
...(customIds.has(id) ? { custom: true } : {}),
})),
customModels: custom.map(entry => ({ ...entry })),
protocols: [...CUSTOM_MODEL_PROTOCOLS],
maxCustomModels: MAX_CUSTOM_MODELS,
} }
} }
const requireWritable = () => {
if (isWritable() !== true) throw new Error('Geek2API settings are not writable in this profile')
}
return Object.freeze({ return Object.freeze({
status, status,
reconcile, reconcile,
/** The pi-ai models the route serves, built-in first. */
models: () => catalog().models,
/** Every id the route serves, built-in first. */
ids: () => catalog().ids,
isVisible: id => !hidden().includes(id), isVisible: id => !hidden().includes(id),
async update({ selectedIds } = {}) { async update({ selectedIds } = {}) {
if (!Array.isArray(selectedIds) || selectedIds.some(id => !GEEK2API_MODEL_IDS.includes(id))) { const ids = catalog().ids
if (!Array.isArray(selectedIds) || selectedIds.some(id => !ids.includes(id))) {
throw new Error('That Geek2API model selection is not supported') throw new Error('That Geek2API model selection is not supported')
} }
if (isWritable() !== true) throw new Error('Geek2API settings are not writable in this profile') requireWritable()
const selected = new Set(selectedIds) const selected = new Set(selectedIds)
try { try {
await writePreference({ hiddenModels: GEEK2API_MODEL_IDS.filter(id => !selected.has(id)) }) await writePreference({ hiddenModels: ids.filter(id => !selected.has(id)) })
} catch { } catch {
throw new Error('Geek2API could not save the model selection') throw new Error('Geek2API could not save the model selection')
} }
reconcile() reconcile()
return status() return status()
}, },
/**
* Replace the custom model list. A new model is visible at once; a removed
* one leaves the picker, and sessions that used it fail with an unknown
* model instead of silently switching to another.
*/
async updateCustom({ customModels } = {}) {
const next = validateCustomModels(customModels)
requireWritable()
try {
await writePreference({ customModels: next.map(entry => ({ ...entry })) })
} catch {
throw new Error('Geek2API could not save the custom models')
}
reconcile()
return status()
},
}) })
} }
+7 -3
View File
@@ -36,14 +36,18 @@ function keyRingAuth() {
} }
} }
/** Build the route's pi-ai provider (unguarded; the plugin wraps its streams). */ /**
export function createGeek2APIProvider() { * Build the route's pi-ai provider (unguarded; the plugin wraps its streams).
* @param options - the models it serves: the built-in catalog unless the
* caller passes the catalog with the user's custom models.
*/
export function createGeek2APIProvider({ models = GEEK2API_MODELS } = {}) {
const provider = createProvider({ const provider = createProvider({
id: PROVIDER, id: PROVIDER,
name: DISPLAY_NAME, name: DISPLAY_NAME,
baseUrl: DEFAULT_API_HOST, baseUrl: DEFAULT_API_HOST,
auth: keyRingAuth(), auth: keyRingAuth(),
models: GEEK2API_MODELS, models,
api: { api: {
'openai-completions': openAICompletionsApi(), 'openai-completions': openAICompletionsApi(),
'openai-responses': openAIResponsesApi(), 'openai-responses': openAIResponsesApi(),
+34 -14
View File
@@ -1,6 +1,6 @@
/** /**
* The HTTP model route: the pi-ai provider profile and the adapter that * The HTTP model route: the pi-ai provider profile and the adapter that
* serves the catalog's HTTP models (DeepSeek, GPT and Grok) with the ring's keys. * serves the catalog's models, built-in and user-added, with the ring's keys.
* *
* @module dsh-geek2api/route * @module dsh-geek2api/route
*/ */
@@ -17,9 +17,6 @@ import { createGeek2APIProvider, guardKeyRotation } from './provider.js'
* keeps a long session completing requests instead of being refused by a * keeps a long session completing requests instead of being refused by a
* gateway size cap. * gateway size cap.
*/ */
/** Catalog models that take no reasoning control. */
const NON_REASONING_MODEL_IDS = new Set(GEEK2API_MODELS.filter(model => model.reasoning !== true).map(model => model.id))
const REQUEST_LIMITS = Object.freeze({ const REQUEST_LIMITS = Object.freeze({
streamIdleTimeoutMs: 10 * 60 * 1000, streamIdleTimeoutMs: 10 * 60 * 1000,
maxRequestImageBytes: 20 * 1024 * 1024, maxRequestImageBytes: 20 * 1024 * 1024,
@@ -58,8 +55,8 @@ function ringCredentialStore(ring) {
* The provider profile this route runs on. * The provider profile this route runs on.
* *
* `modelErrors` and `configuredMaxTokens` are required by the host adapter; * `modelErrors` and `configuredMaxTokens` are required by the host adapter;
* they stay empty because the catalog is fixed and no model carries a * they stay empty because every catalog entry is validated before it gets
* per-request output cap of its own. * here and no model carries a per-request output cap of its own.
* @param provider - the route's pi-ai provider. * @param provider - the route's pi-ai provider.
* @returns the frozen profile handed to `PiAiAdapter`. * @returns the frozen profile handed to `PiAiAdapter`.
*/ */
@@ -104,12 +101,17 @@ export function createGeek2APIProfile(provider) {
* *
* Each request resolves the active key, then runs on the key the chooser picks * Each request resolves the active key, then runs on the key the chooser picks
* for its model; a key-level failure in the stream moves that key aside. * for its model; a key-level failure in the stream moves that key aside.
*
* The catalog is read on every resolution. A changed one (the user added or
* removed a custom model) builds a new provider and profile map, which the
* host adapter recognizes by identity; an operation that already captured the
* old snapshot keeps it.
* @param options - the key ring and chooser, the session id used when a caller * @param options - the key ring and chooser, the session id used when a caller
* supplies none, and the attachment store image input is read from. * supplies none, the attachment store image input is read from, which
* models are listed in the picker, and the live catalog.
* @returns a `PiAiAdapter` serving the `geek2api` route. * @returns a `PiAiAdapter` serving the `geek2api` route.
*/ */
export function createRouteAdapter({ ring, keys, hosts, fallbackSessionId, resolveAttachments, isModelVisible = () => true }) { export function createRouteAdapter({ ring, keys, hosts, fallbackSessionId, resolveAttachments, isModelVisible = () => true, listModels = () => GEEK2API_MODELS }) {
const raw = createGeek2APIProvider()
/** /**
* GPT on Responses carries a `prompt_cache_key`, which pi-ai derives from * 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 session id; it keeps one conversation on the same upstream cache.
@@ -129,6 +131,8 @@ export function createRouteAdapter({ ring, keys, hosts, fallbackSessionId, resol
* never reached it sets that host aside, so the harness's retry of the step * never reached it sets that host aside, so the harness's retry of the step
* lands on the next one. * lands on the next one.
*/ */
const guardedProvider = models => {
const raw = createGeek2APIProvider({ models })
const guarded = method => (model, context, options) => { const guarded = method => (model, context, options) => {
const routed = requestOptions(model, options) const routed = requestOptions(model, options)
const host = hosts?.current() const host = hosts?.current()
@@ -140,8 +144,22 @@ export function createRouteAdapter({ ring, keys, hosts, fallbackSessionId, resol
onHostFailure: reason => hosts?.fail(host, reason), onHostFailure: reason => hosts?.fail(host, reason),
}) })
} }
const provider = Object.freeze({ ...raw, stream: guarded('stream'), streamSimple: guarded('streamSimple') }) return Object.freeze({ ...raw, stream: guarded('stream'), streamSimple: guarded('streamSimple') })
const profiles = new Map([[PROVIDER, createGeek2APIProfile(provider)]]) }
/** The profile map and non-reasoning ids for the catalog last seen. */
let built
const current = () => {
const models = listModels()
if (built?.models !== models) {
built = {
models,
profiles: new Map([[PROVIDER, createGeek2APIProfile(guardedProvider(models))]]),
// Catalog models that take no reasoning control.
nonReasoning: new Set(models.filter(model => model.reasoning !== true).map(model => model.id)),
}
}
return built
}
// Visibility affects discovery only. Resolution and prepared/in-flight // Visibility affects discovery only. Resolution and prepared/in-flight
// turns still use the complete catalog, including a now-hidden model. // turns still use the complete catalog, including a now-hidden model.
@@ -156,16 +174,18 @@ export function createRouteAdapter({ ring, keys, hosts, fallbackSessionId, resol
* so a session that names no effort does not fail before the request. * so a session that names no effort does not fail before the request.
*/ */
streamWithSnapshot(options, snapshot) { streamWithSnapshot(options, snapshot) {
const model = NON_REASONING_MODEL_IDS.has(options?.model) ? { ...options, reasoningEffort: 'off' } : options const model = current().nonReasoning.has(options?.model) ? { ...options, reasoningEffort: 'off' } : options
return super.streamWithSnapshot(model, snapshot) return super.streamWithSnapshot(model, snapshot)
} }
})({ })({
profiles: () => profiles, profiles: () => current().profiles,
resolveApiKey: async () => { resolveApiKey: async () => {
const active = await keys.active() const active = await keys.active()
if (active === undefined) { if (active === undefined) {
throw new LlmError( throw new LlmError(
'No usable Geek2API API key: add one under Settings → Geek2API, or re-enable the keys this plugin moved past.', 'No usable Geek2API API key: add one under Settings → Geek2API, or re-enable the keys this plugin moved past. '
+ 'A free DeepSeek daily key expires after 24 hours; claim the next one at https://www.geek2api.com/free-ds. '
+ '没有可用的 Geek2API key:免费 DeepSeek 日卡 24 小时到期,请到 https://www.geek2api.com/free-ds 领取新的并粘贴到 设置 → Geek2API。',
'MISSING_CREDENTIAL', 'MISSING_CREDENTIAL',
) )
} }
+1
View File
@@ -107,6 +107,7 @@ export function createGeek2APIRpc({ ring, balance, groups, hosts, keys, preferen
}), }),
'models/status': () => models().status(), 'models/status': () => models().status(),
'models/update': payload => models().update({ selectedIds: payload?.selectedIds }), 'models/update': payload => models().update({ selectedIds: payload?.selectedIds }),
'models/custom/update': payload => models().updateCustom({ customModels: payload?.customModels }),
} }
return async (endpoint, payload, signal) => { return async (endpoint, payload, signal) => {
+94
View File
@@ -0,0 +1,94 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { cappedCatalogModel, GEEK2API_MODELS } from '../src/catalog.js'
import { createGroupReader, parseContextWindows, parseKeyLifetime } from '../src/groups.js'
import { createModelSelectionController } from '../src/model-selection.js'
import { fixedHostPool } from './helpers.mjs'
const DS = 'deepseek-v4.1-flash'
function jsonResponse(payload, status = 200) {
const body = JSON.stringify(payload)
return { ok: status >= 200 && status < 300, status, json: async () => JSON.parse(body), text: async () => body }
}
test('per-model context windows are read from the model list, ignoring noise', () => {
const windows = parseContextWindows([
{ id: DS, context_window: 200000 },
{ id: 'gpt-6.1-sol' },
{ id: 'tiny', context_window: 100 },
{ id: 'bad', context_window: '200000' },
])
assert.deepEqual([...windows], [[DS, 200000]])
assert.equal(parseContextWindows(undefined).size, 0)
})
test('the key lifetime marks a daily free key and where to renew it', () => {
const daily = parseKeyLifetime({ key: { expires_at: '2026-11-17T12:00:00Z', purpose: 'free_daily', renew_window_hours: 2, renew_path: '/free-ds' } })
assert.equal(daily.daily, true)
assert.equal(daily.expiresAt, Date.parse('2026-11-17T12:00:00Z'))
assert.equal(daily.renewWindowHours, 2)
assert.equal(daily.renewPath, '/free-ds')
const plain = parseKeyLifetime({ key: { expires_at: '2027-01-01T00:00:00Z' } })
assert.equal(plain.daily, false)
assert.equal(plain.renewPath, undefined)
assert.equal(parseKeyLifetime({ key: {} }), undefined)
assert.equal(parseKeyLifetime({ key: { expires_at: 'soon' } }), undefined)
assert.equal(parseKeyLifetime({ key: { expires_at: '2026-11-17T12:00:00Z', purpose: 'free_daily', renew_path: 'javascript:alert(1)' } }).renewPath, '/free-ds')
})
test('a capped model keeps a positive compaction budget', () => {
const ds = GEEK2API_MODELS.find(model => model.id === DS)
assert.equal(ds.contextWindow, 1_000_000)
const capped = cappedCatalogModel(ds, 200000)
assert.equal(capped.contextWindow, 200000)
assert.equal(capped.maxTokens, 32000)
// DSH compaction: window - max output - 64K headroom must stay positive.
assert.ok(capped.contextWindow - capped.maxTokens - 65536 > 90000)
assert.equal(cappedCatalogModel(ds, undefined), ds)
assert.equal(cappedCatalogModel(ds, 2_000_000), ds, 'a looser limit never widens the model')
})
test('the free key narrows the catalog model; a paid key alone leaves it at 1M', async () => {
const lists = {
'sk-free': [{ id: DS, context_window: 200000 }],
'sk-paid': [{ id: DS }, { id: 'claude-opus-5-5' }],
}
const fetchImpl = async (url, options) => {
const key = String(options.headers.Authorization).replace('Bearer ', '')
if (url.endsWith('/v1/models')) return jsonResponse({ object: 'list', data: lists[key] ?? [] })
if (url.endsWith('/v1/usage?lite=1')) {
return jsonResponse(key === 'sk-free'
? { mode: 'unrestricted', key: { name: 'd', expires_at: '2026-11-17T12:00:00Z', purpose: 'free_daily', renew_window_hours: 2, renew_path: '/free-ds' } }
: { mode: 'unrestricted', key: { name: 'p' } })
}
throw new Error(`unrouted ${url}`)
}
let keys = [{ id: 'p', label: 'paid', key: 'sk-paid', disabled: false }]
const reader = createGroupReader({ listKeys: async () => keys, hosts: await fixedHostPool(), fetchImpl })
const selection = createModelSelectionController({
readPreference: () => ({}),
writePreference: () => {},
isWritable: () => false,
contextLimitFor: id => reader.contextLimitFor(id),
})
const dsOf = () => selection.models().find(model => model.id === DS)
await reader.read()
assert.equal(reader.contextLimitFor(DS), undefined)
assert.equal(dsOf().contextWindow, 1_000_000)
const before = selection.models()
keys = [...keys, { id: 'f', label: 'free', key: 'sk-free', disabled: false }]
await reader.read({ force: true })
assert.equal(reader.contextLimitFor(DS), 200000)
assert.equal(dsOf().contextWindow, 200000)
assert.equal(dsOf().maxTokens, 32000)
assert.notEqual(selection.models(), before, 'a new cap is a new catalog, so the route rebuilds')
assert.equal(selection.models(), selection.models(), 'an unchanged cap keeps the catalog identity')
assert.equal(reader.lifetimeOf('f').daily, true)
assert.equal(reader.lifetimeOf('p'), undefined)
const claude = selection.models().find(model => model.id === 'claude-opus-5-5')
assert.equal(claude.contextWindow, 1_000_000, 'models without a cap are untouched')
})
+223
View File
@@ -0,0 +1,223 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai'
import { customCatalogModel, GEEK2API_MODEL_IDS } from '../src/catalog.js'
import { PROVIDER } from '../src/constants.js'
import {
DEFAULT_CUSTOM_CONTEXT_WINDOW,
DEFAULT_CUSTOM_MAX_TOKENS,
MAX_CUSTOM_MODELS,
parseCustomModel,
readCustomModels,
validateCustomModels,
} from '../src/custom-models.js'
import { createGroupReader } from '../src/groups.js'
import { createHostPool } from '../src/hosts.js'
import { Geek2APIKeyRing } from '../src/key-ring.js'
import { createModelSelectionController } from '../src/model-selection.js'
import { createRouteAdapter } from '../src/route.js'
import { fakeCredentials, fixedHostPool, stubHostPool } from './helpers.mjs'
test('a custom model needs only an id; everything else has a default', () => {
assert.deepEqual({ ...parseCustomModel({ id: ' qwen3-max ' }) }, {
id: 'qwen3-max',
name: '',
api: 'openai-completions',
reasoning: false,
image: false,
contextWindow: DEFAULT_CUSTOM_CONTEXT_WINDOW,
maxTokens: DEFAULT_CUSTOM_MAX_TOKENS,
})
// A small window caps the default output.
assert.equal(parseCustomModel({ id: 'tiny', contextWindow: 8000 }).maxTokens, 8000)
// The panel's number inputs may arrive as strings.
assert.equal(parseCustomModel({ id: 'm', contextWindow: '200000', maxTokens: '64000' }).maxTokens, 64_000)
assert.equal(parseCustomModel({ id: 'org/model:free@v2+x', name: ' My model ' }).name, 'My model')
})
test('a custom model that cannot be served is refused with a reason the panel may show', () => {
const refuses = (entry, pattern) => assert.throws(() => parseCustomModel(entry), error => {
assert.match(error.message, /^Geek2API /u, 'the RPC only lets messages it authored through')
assert.match(error.message, pattern)
return true
})
refuses({ id: '' }, /needs a model id/u)
refuses({ id: 'has space' }, /may only use/u)
refuses({ id: '-leading' }, /may only use/u)
refuses({ id: 'x'.repeat(129) }, /may only use/u)
refuses({ id: 'claude-opus-5-5' }, /already a built-in/u)
refuses({ id: 'm', api: 'google-generative-ai' }, /unsupported protocol/u)
refuses({ id: 'm', contextWindow: 10 }, /context window/u)
refuses({ id: 'm', contextWindow: 1.5e4 + 0.5 }, /context window/u)
refuses({ id: 'm', contextWindow: 16_000, maxTokens: 32_000 }, /max output/u)
refuses({ id: 'm', maxTokens: 0 }, /max output/u)
refuses('m', /must be objects/u)
assert.throws(() => validateCustomModels([{ id: 'a' }, { id: 'a' }]), /listed twice/u)
assert.throws(() => validateCustomModels(Array.from({ length: MAX_CUSTOM_MODELS + 1 }, (_, i) => ({ id: `m${i}` }))), /at most/u)
assert.throws(() => validateCustomModels('a'), /must be a list/u)
})
test('a hand-edited list is read leniently: only unservable entries are dropped', () => {
const read = readCustomModels([{ id: 'ok-1' }, { id: 'gpt-6.1-sol' }, { id: 'bad id' }, null, { id: 'ok-1', name: 'dup' }, { id: 'ok-2', api: 'anthropic-messages' }])
assert.deepEqual(read.map(entry => entry.id), ['ok-1', 'ok-2'])
assert.equal(read[0].name, '')
assert.deepEqual(readCustomModels(undefined), [])
assert.deepEqual(readCustomModels({ id: 'x' }), [])
})
test('each protocol gets the base URL and compat its built-in models use', () => {
const completions = customCatalogModel(parseCustomModel({ id: 'qwen3-max' }))
assert.equal(completions.provider, PROVIDER)
assert.equal(completions.name, 'qwen3-max', 'an empty name shows the id')
assert.equal(completions.baseUrl, 'https://hk.geek2api.com/v1')
assert.equal(completions.compat.maxTokensField, 'max_tokens')
assert.equal(completions.reasoning, false)
assert.deepEqual([...completions.input], ['text'])
const responses = customCatalogModel(parseCustomModel({ id: 'gpt-x', api: 'openai-responses', reasoning: true, image: true }))
assert.equal(responses.baseUrl, 'https://hk.geek2api.com/v1')
assert.equal(responses.compat, undefined)
assert.deepEqual([...responses.input], ['text', 'image'])
assert.equal(responses.thinkingLevelMap.minimal, null)
const messages = customCatalogModel(parseCustomModel({ id: 'claude-x', api: 'anthropic-messages', name: 'Claude X' }))
assert.equal(messages.baseUrl, 'https://hk.geek2api.com', 'the Anthropic client appends /v1/messages itself')
assert.equal(messages.name, 'Claude X')
})
/** The controller over an in-memory preference, as `apply()` composes it. */
function selection(initial = {}) {
let values = { ...initial }
const seen = { changes: 0, catalogChanges: 0, writes: [] }
const controller = createModelSelectionController({
readPreference: () => values,
writePreference: async patch => {
seen.writes.push(patch)
values = { ...values, ...patch }
},
isWritable: () => true,
onChange: () => { seen.changes += 1 },
onCatalogChange: () => { seen.catalogChanges += 1 },
})
return { controller, seen, set: patch => { values = { ...values, ...patch } } }
}
test('custom models join the catalog after the built-in ones, selected by default', async () => {
const { controller, seen } = selection()
const before = controller.models()
assert.equal(controller.models(), before, 'an unchanged catalog keeps its identity')
const status = await controller.updateCustom({ customModels: [{ id: 'qwen3-max', name: 'Qwen3 Max' }, { id: 'claude-x', api: 'anthropic-messages' }] })
assert.deepEqual(seen.writes.at(-1).customModels.map(entry => entry.id), ['qwen3-max', 'claude-x'])
assert.deepEqual(controller.ids(), [...GEEK2API_MODEL_IDS, 'qwen3-max', 'claude-x'])
assert.notEqual(controller.models(), before)
assert.equal(seen.changes, 1)
assert.equal(seen.catalogChanges, 1)
const qwen = status.models.find(model => model.id === 'qwen3-max')
assert.deepEqual(qwen, { id: 'qwen3-max', name: 'Qwen3 Max', selected: true, custom: true })
assert.equal(status.models[0].custom, undefined)
assert.deepEqual(status.customModels.map(entry => entry.api), ['openai-completions', 'anthropic-messages'])
assert.deepEqual(status.protocols, ['openai-completions', 'openai-responses', 'anthropic-messages'])
// A custom model can be hidden like any other.
await controller.update({ selectedIds: GEEK2API_MODEL_IDS })
assert.equal(controller.isVisible('qwen3-max'), false)
assert.equal(seen.catalogChanges, 1, 'hiding a model does not re-read coverage')
// An invalid list is refused without writing anything.
const writes = seen.writes.length
await assert.rejects(controller.updateCustom({ customModels: [{ id: 'gpt-6-luna' }] }), /already a built-in/u)
assert.equal(seen.writes.length, writes)
await controller.updateCustom({ customModels: [] })
assert.deepEqual(controller.ids(), [...GEEK2API_MODEL_IDS])
assert.equal(seen.catalogChanges, 2)
})
test('a hand edit of the custom list is followed on reconcile', () => {
const { controller, seen, set } = selection()
set({ customModels: [{ id: 'kimi-k4' }] })
controller.reconcile()
assert.equal(seen.changes, 1)
assert.equal(seen.catalogChanges, 1)
assert.ok(controller.ids().includes('kimi-k4'))
controller.reconcile()
assert.equal(seen.changes, 1, 'the same list is no change')
})
test('the route serves a custom model on its protocol and refreshes with the catalog', async t => {
const { controller } = selection()
const ring = new Geek2APIKeyRing(fakeCredentials())
await ring.add('sk-fixture-only-not-a-real-key', 'fixture')
const adapter = createRouteAdapter({
ring,
hosts: stubHostPool(createHostPool),
keys: { active: () => ring.activeKey(), forRequest: (_model, key) => key, onKeyFailure: () => {} },
fallbackSessionId: 'custom-fixture',
listModels: controller.models,
})
assert.ok(adapter instanceof PiAiAdapter)
await assert.rejects(adapter.resolveModel(PROVIDER, 'qwen3-max'), /no configured model/u)
await controller.updateCustom({ customModels: [{ id: 'qwen3-max', contextWindow: 256_000 }, { id: 'think-x', api: 'openai-responses', reasoning: true }] })
assert.deepEqual((await adapter.listModels(PROVIDER)).slice(-2).map(model => model.id), ['qwen3-max', 'think-x'])
const qwen = await adapter.resolveModel(PROVIDER, 'qwen3-max')
assert.equal(qwen.context.contextWindow, 256_000)
assert.equal(qwen.reasoning?.defaultEffort, undefined)
const think = await adapter.resolveModel(PROVIDER, 'think-x')
assert.deepEqual(think.reasoning.efforts.map(effort => effort.id), ['off', 'low', 'medium', 'high'])
const requests = []
t.mock.method(globalThis, 'fetch', async (input, init) => {
const request = new Request(input, init)
requests.push({ url: request.url, body: await request.json() })
const chunks = [
{ id: 'c1', object: 'chat.completion.chunk', created: 1, model: 'qwen3-max', choices: [{ index: 0, delta: { role: 'assistant', content: 'ok' }, finish_reason: null }] },
{ id: 'c1', object: 'chat.completion.chunk', created: 1, model: 'qwen3-max', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
]
return new Response(chunks.map(event => `data: ${JSON.stringify(event)}\n\n`).join('') + 'data: [DONE]\n\n', { headers: { 'Content-Type': 'text/event-stream' } })
})
const { createUserMessage } = await import('@deepseek-ai/dsh-llm')
const prepared = await adapter.prepareCall(PROVIDER, 'qwen3-max')
let last
for await (const chunk of prepared.stream({
provider: PROVIDER,
model: 'qwen3-max',
sessionId: 'custom-fixture',
maxTokens: 64,
// A non-reasoning custom model is asked for `off` like a built-in one.
reasoningEffort: 'high',
messages: [createUserMessage({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } })],
})) last = chunk
assert.equal(last.reason.kind, 'stop')
assert.equal(requests.length, 1)
assert.equal(requests[0].url, 'https://h1.example/v1/chat/completions')
assert.equal(requests[0].body.model, 'qwen3-max')
assert.equal(requests[0].body.reasoning_effort, undefined)
await controller.updateCustom({ customModels: [] })
await assert.rejects(adapter.resolveModel(PROVIDER, 'qwen3-max'), /no configured model/u, 'a removed model never falls back to another')
})
test('key coverage is measured for custom models too', async () => {
const { controller } = selection({ customModels: [{ id: 'qwen3-max' }] })
const fetchImpl = async url => {
const body = url.endsWith('/v1/models')
? { object: 'list', data: ['qwen3-max', 'claude-opus-5-5', 'other'].map(id => ({ id })) }
: { mode: 'unrestricted', balance: 1 }
return { ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) }
}
const reader = createGroupReader({
listKeys: async () => [{ id: 'k', label: 'k', key: 'sk-fixture', disabled: false }],
hosts: await fixedHostPool(),
modelIds: () => controller.ids(),
fetchImpl,
})
const value = await reader.read()
assert.equal(value.keys[0].coverage['qwen3-max'], true)
assert.equal(value.keys[0].coverage['gpt-6.1-sol'], false)
assert.equal(value.keys[0].extraModels, 1, 'a custom model is no longer "outside the list"')
assert.equal(reader.covers('k', 'qwen3-max'), true)
})
+27 -1
View File
@@ -59,7 +59,9 @@ function host({ generation = '0.2', writable = true, failWrite = false, initial
}, },
effect(callback) { return callback() }, effect(callback) { return callback() },
} }
const config = generation === '0.2' ? { hiddenModels: { get: () => values.hiddenModels } } : {} const config = generation === '0.2'
? { hiddenModels: { get: () => values.hiddenModels }, customModels: { get: () => values.customModels } }
: {}
apply(ctx, config) apply(ctx, config)
return { return {
seen, seen,
@@ -182,3 +184,27 @@ test('the actual DSH LLM registry refreshes discovery atomically and keeps a pre
assert.deepEqual((await llm.listModels('geek2api')).map(model => model.id), ['grok-4.7']) assert.deepEqual((await llm.listModels('geek2api')).map(model => model.id), ['grok-4.7'])
registration() registration()
}) })
for (const generation of ['0.1', '0.2']) {
test(`DSH ${generation}: a custom model added in the panel reaches the picker and survives reconstruction`, async () => {
const env = host({ generation })
const { seen } = env
const added = await seen.handler('models/custom/update', { customModels: [{ id: 'qwen3-max', name: 'Qwen3 Max', api: 'openai-completions' }] })
assert.equal(added.ok, true)
assert.deepEqual(seen.updates.at(-1).customModels.map(entry => entry.id), ['qwen3-max'])
assert.equal(seen.notifications, 1, 'one registry refresh for the changed catalog')
assert.equal(added.value.models.at(-1).id, 'qwen3-max')
assert.equal(added.value.models.at(-1).custom, true)
assert.equal((await seen.adapter.listModels('geek2api')).at(-1).id, 'qwen3-max')
assert.equal((await seen.adapter.resolveModel('geek2api', 'qwen3-max')).id, 'qwen3-max')
assert.equal((await env.reapply().seen.adapter.listModels('geek2api')).at(-1).id, 'qwen3-max')
const refused = await seen.handler('models/custom/update', { customModels: [{ id: 'claude-opus-5-5' }] })
assert.equal(refused.ok, false)
assert.match(refused.error.message, /already a built-in model/u, 'the reason reaches the panel')
await seen.handler('models/custom/update', { customModels: [] })
assert.equal(seen.notifications, 2)
assert.ok(!(await seen.adapter.listModels('geek2api')).some(model => model.id === 'qwen3-max'))
})
}
+1 -1
View File
@@ -9,7 +9,7 @@ import { fakeCredentials, stubHostPool } from './helpers.mjs'
import { Config } from '../src/index.js' import { Config } from '../src/index.js'
test('search settings declare volatile fields accepted by DSH 0.2', () => { test('search settings declare volatile fields accepted by DSH 0.2', () => {
for (const field of ['searchProvider', 'searchBackend', 'hiddenModels', 'apiHosts', 'claudeRuntime']) { for (const field of ['searchProvider', 'searchBackend', 'hiddenModels', 'customModels', 'apiHosts', 'claudeRuntime']) {
assert.equal(Config.dict[field].meta.volatile, true, `${field}: DSH 0.2 otherwise rejects settings.update with no volatile fields`) assert.equal(Config.dict[field].meta.volatile, true, `${field}: DSH 0.2 otherwise rejects settings.update with no volatile fields`)
} }
}) })