Skip to content

Commit bccb1a9

Browse files
committed
feat(desktop): 模型池端点化改造 + 端点额度监听
- 模型池改为常规端点优先形态:每端点一张卡(名称/预设徽章/baseURL/ API Key 显隐/额度行/模型列表与卡内添加模型),底部添加端点行支持 预设与自定义(名称+baseURL 校验、id slug 去重);原扁平池表与独立 密钥区合并下线;主副模型选择区不动(endpoint/model 键兼容) - 额度追随端点(endpointQuotaKind 按 baseURL 分派,key 永不外发): StepFun 双通道实时余额(GET /v1/accounts,60s 轮询+手动刷新+主进程 TTL 缓存);OpenCode Go 订阅限额(5h $12/周 $30/月 $60 静态展示 ——官方暂无余额 API,anomalyco/opencode#10448 仍在请求) - IPC endpoint:quota 契约 + preload 透传 + main 处理器(ok:false 信封 永不抛错);i18n 六语言补齐,双语翻译遗留键随批清理
1 parent 3e6856b commit bccb1a9

12 files changed

Lines changed: 795 additions & 291 deletions

File tree

‎packages/core/src/settings.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1095,6 +1095,13 @@ export type EndpointConfig = {
10951095
/** Built-in endpoint presets offered in the settings panel. */
10961096
export const ENDPOINT_PRESETS: ReadonlyArray<Pick<EndpointConfig, "id" | "name" | "baseURL">> = [
10971097
{ id: "deepseek", name: "DeepSeek", baseURL: "https://api.deepseek.com" },
1098+
// StepFun (step-3.7-flash first-party vision/reasoning family). /v1 REQUIRED:
1099+
// the SDK appends /chat/completions verbatim and StepFun serves the
1100+
// OpenAI-compatible surface at /v1/chat/completions. Two channels, same
1101+
// models: pay-as-you-go /v1 and the Step Plan SUBSCRIPTION channel
1102+
// /step_plan/v1 (quota-billed; also serves step-router-v1).
1103+
{ id: "stepfun", name: "StepFun", baseURL: "https://api.stepfun.com/v1" },
1104+
{ id: "stepfun-plan", name: "StepFun Plan", baseURL: "https://api.stepfun.com/step_plan/v1" },
10981105
// opencode Zen/Go are OpenAI-compatible gateways that REQUIRE the /v1
10991106
// segment (the SDK appends /chat/completions verbatim; without /v1 the
11001107
// request hits the website and comes back as an HTML 404 page).
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
/**
2+
* Endpoint quota probes — the per-ENDPOINT "how much is left" surface for
3+
* subscription/prepaid providers. Quota follows the endpoint, not the model:
4+
* every probe is keyed by the endpoint's own baseURL + apiKey.
5+
*
6+
* - StepFun (both channels: pay-as-you-go /v1 and Step Plan /step_plan/v1 —
7+
* the key identifies the ACCOUNT, so one read covers both): live balance
8+
* via GET https://api.stepfun.com/v1/accounts.
9+
* - OpenCode Go (subscription): the platform exposes NO balance API (open
10+
* request anomalyco/opencode#10448; only the web dashboard shows credits),
11+
* so the probe serves the plan's documented rolling limits as static info.
12+
*
13+
* Poll, don't push: neither platform offers quota webhooks, so the settings
14+
* surface refreshes on an interval while visible (60s) plus on demand. The
15+
* per-key TTL cache below keeps repeated opens cheap and rate-limit friendly.
16+
*/
17+
18+
import type { EndpointQuotaKind } from "@deeporca/core";
19+
20+
export type StepfunAccount = {
21+
/** prepaid | postpaid. */
22+
type: "prepaid" | "postpaid";
23+
/** 可用余额(元)— cash + voucher. */
24+
balance: number;
25+
/** 累计充值(元). */
26+
totalCashBalance: number;
27+
/** 累计赠送(元). */
28+
totalVoucherBalance: number;
29+
};
30+
31+
/** OpenCode Go subscription's documented rolling usage limits (USD). */
32+
export type OpencodeGoLimits = {
33+
fiveHourUsd: number;
34+
weeklyUsd: number;
35+
monthlyUsd: number;
36+
};
37+
38+
export type EndpointQuotaResult =
39+
| { ok: true; kind: "stepfun-account"; account: StepfunAccount; fetchedAt: string }
40+
| { ok: true; kind: "opencode-subscription"; limits: OpencodeGoLimits }
41+
| { ok: false; error: string };
42+
43+
const ACCOUNTS_URL = "https://api.stepfun.com/v1/accounts";
44+
45+
/** Docker/opencode docs' published Go-plan limits (usage, not balance). */
46+
const OPENCODE_GO_LIMITS: OpencodeGoLimits = { fiveHourUsd: 12, weeklyUsd: 30, monthlyUsd: 60 };
47+
48+
/** Cache TTL — balance changes at token speed; a minute is honest enough. */
49+
const CACHE_TTL_MS = 60_000;
50+
51+
type FetchLike = (url: string, init: { headers: Record<string, string> }) => Promise<Response>;
52+
53+
const cache = new Map<string, { at: number; result: EndpointQuotaResult }>();
54+
55+
function asFiniteNumber(value: unknown): number | undefined {
56+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
57+
}
58+
59+
/** Parse the /v1/accounts payload defensively (shape per API reference). */
60+
export function parseStepfunAccount(json: unknown): StepfunAccount | null {
61+
if (typeof json !== "object" || json === null) return null;
62+
const record = json as Record<string, unknown>;
63+
const balance = asFiniteNumber(record.balance);
64+
const totalCashBalance = asFiniteNumber(record.total_cash_balance);
65+
const totalVoucherBalance = asFiniteNumber(record.total_voucher_balance);
66+
if (balance === undefined) return null;
67+
return {
68+
type: record.type === "postpaid" ? "postpaid" : "prepaid",
69+
balance,
70+
totalCashBalance: totalCashBalance ?? 0,
71+
totalVoucherBalance: totalVoucherBalance ?? 0,
72+
};
73+
}
74+
75+
/**
76+
* Probe one endpoint's quota. Never throws — callers get an ok:false
77+
* envelope (network, HTTP, auth, or shape errors) so a dead probe can never
78+
* break the settings surface. The opencode kind needs no network round-trip
79+
* (static limits) and therefore no key.
80+
*/
81+
export async function fetchEndpointQuota(
82+
kind: EndpointQuotaKind,
83+
apiKey: string,
84+
fetchImpl?: FetchLike
85+
): Promise<EndpointQuotaResult> {
86+
if (kind === "opencode-subscription") {
87+
return { ok: true, kind, limits: OPENCODE_GO_LIMITS };
88+
}
89+
const key = apiKey.trim();
90+
if (!key) return { ok: false, error: "no api key" };
91+
const cached = cache.get(key);
92+
if (cached && Date.now() - cached.at < CACHE_TTL_MS) return cached.result;
93+
const doFetch: FetchLike = fetchImpl ?? ((url, init) => fetch(url, init));
94+
let result: EndpointQuotaResult;
95+
try {
96+
const response = await doFetch(ACCOUNTS_URL, {
97+
headers: { Authorization: `Bearer ${key}` },
98+
});
99+
if (!response.ok) {
100+
result = { ok: false, error: `HTTP ${response.status}` };
101+
} else {
102+
const account = parseStepfunAccount(await response.json());
103+
result = account
104+
? { ok: true, kind: "stepfun-account", account, fetchedAt: new Date().toISOString() }
105+
: { ok: false, error: "unexpected account payload" };
106+
}
107+
} catch (err) {
108+
result = { ok: false, error: err instanceof Error ? err.message : String(err) };
109+
}
110+
cache.set(key, { at: Date.now(), result });
111+
return result;
112+
}

‎packages/desktop/src/main/index.ts‎

Lines changed: 44 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,15 @@ import {
4343
configureGitmcpConfigBuilder,
4444
buildGitmcpMcpServerConfig,
4545
TaskTreeService,
46-
detectWikiLanguage,
47-
wikiVariantPath,
4846
isWikiVariantFile,
47+
endpointQuotaKind,
4948
} from "@deeporca/core";
5049
import { extractTaskTrajectory } from "./task-trajectory";
5150
import { buildSymbolGraph } from "./symbol-graph-query";
5251
import type { ModelConfigSelection, UserPromptContent } from "@deeporca/core";
5352
import { IpcEvent, IpcRequest } from "../shared/ipc.js";
5453
import { ensureDembrandtBrowserProvider, getDembrandtCdpEndpoint } from "./tools/dembrandt-browser";
54+
import { fetchEndpointQuota } from "./endpoint-quota.js";
5555
import type {
5656
CodegraphIndexEntry,
5757
CrgIndexEntry,
@@ -60,6 +60,7 @@ import type {
6060
KnowledgeArchmapSurface,
6161
KnowledgeSourceStatus,
6262
KnowledgeStatusResponse,
63+
EndpointQuotaResponse,
6364
MemoryRoutingStatus,
6465
KnowledgeSymbol,
6566
KnowledgeSymbolGraph,
@@ -1230,6 +1231,39 @@ function resolveRegisteredRoot(rootArg?: string): string | null {
12301231
return known.has(root) ? root : null;
12311232
}
12321233

1234+
function registerEndpointQuotaIpc({ handle }: IpcHelpers): void {
1235+
// Quota follows the ENDPOINT (subscription/prepaid providers): the probe is
1236+
// selected by the endpoint's own baseURL and keyed by its apiKey. Hosts
1237+
// without a quota surface short-circuit ok:false — a key must never travel
1238+
// to a host the platform doesn't own.
1239+
handle(IpcRequest.EndpointQuota, async (endpointId?: string): Promise<EndpointQuotaResponse> => {
1240+
if (!endpointId) return { ok: false, error: "missing endpoint id" };
1241+
try {
1242+
const settings = resolveCurrentSettings(getBridge().projectRoot);
1243+
const endpoint = settings.endpoints.find((ep) => ep.id === endpointId);
1244+
if (!endpoint) return { ok: false, error: "unknown endpoint" };
1245+
const kind = endpointQuotaKind(endpoint.baseURL);
1246+
if (!kind) return { ok: false, error: "endpoint has no quota probe" };
1247+
const result = await fetchEndpointQuota(kind, endpoint.apiKey);
1248+
if (!result.ok) return { ok: false, error: result.error };
1249+
if (result.kind === "opencode-subscription") {
1250+
return { ok: true, kind: result.kind, limits: result.limits };
1251+
}
1252+
return {
1253+
ok: true,
1254+
kind: result.kind,
1255+
type: result.account.type,
1256+
balance: result.account.balance,
1257+
totalCashBalance: result.account.totalCashBalance,
1258+
totalVoucherBalance: result.account.totalVoucherBalance,
1259+
fetchedAt: result.fetchedAt,
1260+
};
1261+
} catch (err) {
1262+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
1263+
}
1264+
});
1265+
}
1266+
12331267
function registerKnowledgeIpc({ handle }: IpcHelpers): void {
12341268
handle(IpcRequest.KnowledgeStatus, async (rootArg?: string): Promise<KnowledgeStatusResponse> => {
12351269
const pinned = resolveRegisteredRoot(rootArg);
@@ -1296,17 +1330,20 @@ function registerKnowledgeIpc({ handle }: IpcHelpers): void {
12961330
}
12971331
: { state: "empty", detail: "未构建" };
12981332

1333+
// Base pages only: the removed bilingual stage's legacy `*.zh.md` /
1334+
// `*.en.md` siblings stay on disk but must not count as pages.
1335+
const isCountedWikiPage = (n: string): boolean => n.endsWith(".md") && !isWikiVariantFile(n);
1336+
12991337
// OpenWiki — page count under openwiki/ (recursive for modules/ + workflows/).
13001338
const wikiDir = join(root, "openwiki");
13011339
let wikiPages = 0;
13021340
if (existsSync(wikiDir)) {
1303-
wikiPages = countDirFiles(wikiDir, (n) => n.endsWith(".md"));
1341+
wikiPages = countDirFiles(wikiDir, isCountedWikiPage);
13041342
for (const sub of ["modules", "workflows"]) {
1305-
wikiPages += countDirFiles(join(wikiDir, sub), (n) => n.endsWith(".md"));
1343+
wikiPages += countDirFiles(join(wikiDir, sub), isCountedWikiPage);
13061344
}
13071345
}
1308-
const wikiSync =
1309-
freshness.wikiSync ?? (existsSync(wikiDir) ? newestMtime(wikiDir, (n) => n.endsWith(".md")) : undefined);
1346+
const wikiSync = freshness.wikiSync ?? (existsSync(wikiDir) ? newestMtime(wikiDir, isCountedWikiPage) : undefined);
13101347
const openwiki: KnowledgeSourceStatus = existsSync(wikiDir)
13111348
? {
13121349
state: wikiPages === 0 ? "empty" : isStale(wikiSync) ? "stale" : "indexed",
@@ -2096,28 +2133,10 @@ function registerWikiIpc({ handle, handlePrivileged }: IpcHelpers): void {
20962133
} catch {
20972134
// unreadable — leave undated
20982135
}
2099-
// Bilingual translation sibling (wiki.translate build stage):
2100-
// detect the base page's language with the SAME heuristic core
2101-
// uses, then probe the other-language variant. Cheap existence
2102-
// check on a path we derived ourselves — no renderer input.
2103-
let translation: WikiPageEntry["translation"];
2104-
try {
2105-
const head = await readFile(absPath, "utf8");
2106-
const lang = detectWikiLanguage(head);
2107-
if (lang) {
2108-
const vLang: "zh" | "en" = lang === "zh" ? "en" : "zh";
2109-
const vRel = wikiVariantPath(rel, vLang);
2110-
const vStat = await stat(join(wikiDir, vRel));
2111-
translation = { lang: vLang, path: vRel, mtime: vStat.mtime.toISOString() };
2112-
}
2113-
} catch {
2114-
// No variant (or unreadable base) — no toggle.
2115-
}
21162136
entries.push({
21172137
path: rel,
21182138
title: await wikiPageTitle(absPath, item.name),
21192139
mtime,
2120-
...(translation ? { translation } : {}),
21212140
});
21222141
}
21232142
}
@@ -2245,6 +2264,7 @@ function registerIpc(): void {
22452264
registerCrgIpc(helpers);
22462265
registerMemoryIpc(helpers);
22472266
registerKnowledgeIpc(helpers);
2267+
registerEndpointQuotaIpc(helpers);
22482268
registerTaskTreeIpc(helpers);
22492269
registerDesignIpc(helpers);
22502270
registerA2uiIpc(helpers);

‎packages/desktop/src/preload/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ const api: DesktopApi = {
139139

140140
// ── Knowledge dashboard ──────────────────────────────────────────
141141
knowledgeStatus: (root) => ipcRenderer.invoke(IpcRequest.KnowledgeStatus, root),
142+
endpointQuota: (endpointId) => ipcRenderer.invoke(IpcRequest.EndpointQuota, endpointId),
142143
memoryRoutingStatus: () => ipcRenderer.invoke(IpcRequest.MemoryRoutingStatus),
143144
knowledgeReadArchmap: (path) => ipcRenderer.invoke(IpcRequest.KnowledgeReadArchmap, path),
144145
knowledgeBuild: (root) => ipcRenderer.invoke(IpcRequest.KnowledgeBuild, root),

0 commit comments

Comments
 (0)