pi-tsgw 3.4.1 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,181 @@
1
+ import type { GatewayCatalogService } from "#tsgw/models/gateway-catalog-service";
2
+ import { parseCards, parseStatusline, type MagpieCard, type MagpieStatusline } from "./data.ts";
3
+
4
+ export interface MagpieRequest {
5
+ root: string;
6
+ headers: Headers;
7
+ }
8
+ export interface MagpieSnapshot<T> {
9
+ data?: T;
10
+ fetchedAt?: number;
11
+ error?: string;
12
+ status?: number;
13
+ }
14
+ export interface RefreshTarget { provider: string; user?: string }
15
+ interface Task<T> {
16
+ controller: AbortController;
17
+ waiters: number;
18
+ promise: Promise<MagpieSnapshot<T>>;
19
+ }
20
+ interface Resource<T> {
21
+ snapshot: MagpieSnapshot<T>;
22
+ attemptedAt?: number;
23
+ blocked?: boolean;
24
+ task?: Task<T>;
25
+ }
26
+ interface MagpieState {
27
+ cards: Resource<MagpieCard[]>;
28
+ listeners: Set<() => void>;
29
+ sessions: Map<string, Resource<MagpieStatusline>>;
30
+ statusBlocked: boolean;
31
+ refresh?: { target?: RefreshTarget; task: Task<MagpieCard[]> };
32
+ cardsRevision: number;
33
+ }
34
+ const TTL = 60_000;
35
+ const resource = <T>(): Resource<T> => ({ snapshot: {} });
36
+ const createState = (): MagpieState => ({
37
+ cards: resource(), listeners: new Set(), sessions: new Map(), statusBlocked: false, cardsRevision: 0,
38
+ });
39
+
40
+ /** 只共享同一目录作用域的内存读数,不保存宿主上下文或常驻明文凭据。 */
41
+ export function createMagpieService(catalog: Pick<GatewayCatalogService, "valid" | "isMagpie">,
42
+ fetcher: typeof fetch = (...args) => globalThis.fetch(...args), now = Date.now, state = createState()) {
43
+ const { cards, listeners, sessions } = state;
44
+ const valid = () => catalog.valid() && catalog.isMagpie();
45
+ const session = (id: string) => {
46
+ let state = sessions.get(id);
47
+ if (!state) sessions.set(id, state = resource());
48
+ return state;
49
+ };
50
+
51
+ function start<T>(state: Resource<T>, request: MagpieRequest, path: string,
52
+ parse: (value: unknown) => T, method: "GET" | "POST", canCommit = () => true): Task<T> {
53
+ const controller = new AbortController();
54
+ const task: Task<T> = { controller, waiters: 0, promise: Promise.resolve(state.snapshot) };
55
+ state.attemptedAt = now();
56
+ task.promise = (async () => {
57
+ let timedOut = false;
58
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, method === "POST" ? 35_000 : 5_000);
59
+ let status: number | undefined;
60
+ let result: MagpieSnapshot<T>;
61
+ try {
62
+ const response = await fetcher(`${request.root}/v1/magpie/${path}`, {
63
+ method, headers: request.headers, signal: controller.signal, redirect: "error",
64
+ });
65
+ status = response.status;
66
+ if (!response.ok) throw new Error();
67
+ const data = parse(await response.json());
68
+ result = { data, fetchedAt: now() };
69
+ } catch {
70
+ const hidden = status === 401 || status === 403;
71
+ result = { ...(hidden ? {} : state.snapshot), status,
72
+ error: status && status >= 200 && status < 300 ? "Magpie 返回的数据无法解析,保留已有读数。"
73
+ : status ? `Magpie 查询失败(HTTP ${status})。` : "Magpie 查询失败或超时,保留已有读数。" };
74
+ } finally { clearTimeout(timer); }
75
+ if (!valid()) return {};
76
+ if ((controller.signal.aborted && !timedOut) || !canCommit()) return state.snapshot;
77
+ state.snapshot = result;
78
+ state.blocked = status === 401 || status === 403 || status === 404 || status === 405;
79
+ if (state === cards) for (const listener of listeners) listener();
80
+ return result;
81
+ })().finally(() => { if (state.task === task) state.task = undefined; });
82
+ state.task = task;
83
+ return task;
84
+ }
85
+
86
+ return {
87
+ valid,
88
+ subscribe(listener: () => void): () => void {
89
+ listeners.add(listener);
90
+ return () => { listeners.delete(listener); };
91
+ },
92
+ status: (id: string): MagpieSnapshot<MagpieStatusline> => valid() ? session(id).snapshot : {},
93
+ cards: (): MagpieSnapshot<MagpieCard[]> => valid() ? cards.snapshot : {},
94
+ async readStatus(id: string, request: MagpieRequest,
95
+ options: { force?: boolean; automatic?: boolean; signal?: AbortSignal } = {}): Promise<MagpieSnapshot<MagpieStatusline>> {
96
+ if (!valid() || options.signal?.aborted) return {};
97
+ const statusState = session(id);
98
+ if (statusState.task?.controller.signal.aborted) statusState.task = undefined;
99
+ if (statusState.task) return wait(statusState.task, options.signal);
100
+ if (options.automatic && (state.statusBlocked ||
101
+ (statusState.attemptedAt !== undefined && now() - statusState.attemptedAt < TTL))) return statusState.snapshot;
102
+ if (!options.force && statusState.snapshot.fetchedAt !== undefined && now() - statusState.snapshot.fetchedAt < TTL)
103
+ return statusState.snapshot;
104
+ const task = start(statusState, request, `statusline?format=json&session=${encodeURIComponent(id)}`, parseStatusline, "GET");
105
+ const result = await wait(task, options.signal);
106
+ state.statusBlocked = statusState.blocked === true;
107
+ if (result.status === 401 || result.status === 403)
108
+ for (const other of sessions.values()) other.snapshot = { error: result.error, status: result.status };
109
+ return result;
110
+ },
111
+ readCards(request: MagpieRequest, options: { force?: boolean; automatic?: boolean; signal?: AbortSignal } = {}): Promise<MagpieSnapshot<MagpieCard[]>> {
112
+ if (!valid() || options.signal?.aborted) return Promise.resolve({});
113
+ if (state.refresh?.task.controller.signal.aborted) state.refresh = undefined;
114
+ if (cards.task?.controller.signal.aborted) cards.task = undefined;
115
+ if (state.refresh) return wait(state.refresh.task, options.signal);
116
+ if (cards.task) return wait(cards.task, options.signal);
117
+ if (options.automatic && (cards.blocked ||
118
+ (cards.attemptedAt !== undefined && now() - cards.attemptedAt < TTL))) return Promise.resolve(cards.snapshot);
119
+ if (!options.force && cards.snapshot.fetchedAt !== undefined && now() - cards.snapshot.fetchedAt < TTL)
120
+ return Promise.resolve(cards.snapshot);
121
+ const revision = state.cardsRevision;
122
+ return wait(start(cards, request, "quotas/cards", parseCards, "GET", () => revision === state.cardsRevision), options.signal);
123
+ },
124
+ refreshCards(request: MagpieRequest, target?: RefreshTarget, signal?: AbortSignal): Promise<MagpieSnapshot<MagpieCard[]>> {
125
+ if (!valid() || signal?.aborted) return Promise.resolve({});
126
+ if (state.refresh?.task.controller.signal.aborted) state.refresh = undefined;
127
+ if (state.refresh) {
128
+ const current = state.refresh.target;
129
+ if (!current || (target && current.provider === target.provider &&
130
+ (!current.user || current.user.toLowerCase() === target.user?.toLowerCase()))) return wait(state.refresh.task, signal);
131
+ return Promise.resolve({ ...cards.snapshot, error: "另一范围的额度刷新正在进行,请完成后再操作。" });
132
+ }
133
+ state.cardsRevision++;
134
+ const query = new URLSearchParams();
135
+ if (target) {
136
+ query.set("provider", target.provider);
137
+ if (target.user) query.set("user", target.user);
138
+ }
139
+ const task = start(cards, request, `quotas/refresh${query.size ? `?${query}` : ""}`, parseCards, "POST");
140
+ state.refresh = { target, task };
141
+ void task.promise.finally(() => { if (state.refresh?.task === task) state.refresh = undefined; });
142
+ return wait(task, signal);
143
+ },
144
+ };
145
+ }
146
+
147
+ function wait<T>(task: Task<T>, signal?: AbortSignal): Promise<MagpieSnapshot<T>> {
148
+ task.waiters++;
149
+ return new Promise((resolve) => {
150
+ let done = false;
151
+ const finish = (result: MagpieSnapshot<T>) => {
152
+ if (done) return;
153
+ done = true;
154
+ signal?.removeEventListener("abort", abort);
155
+ task.waiters--;
156
+ resolve(result);
157
+ };
158
+ const abort = () => {
159
+ finish({});
160
+ if (task.waiters === 0) task.controller.abort();
161
+ };
162
+ task.promise.then(finish, () => finish({ error: "Magpie 查询失败。" }));
163
+ if (signal?.aborted) abort();
164
+ else signal?.addEventListener("abort", abort, { once: true });
165
+ });
166
+ }
167
+
168
+ export type MagpieService = ReturnType<typeof createMagpieService>;
169
+ const SHARED = Symbol.for("pi-tsgw:magpie-state");
170
+ const instances = new WeakMap<object, MagpieService>();
171
+ /** 稳定目录状态关联额度数据;服务包装与解析方法使用当前模块的代码。 */
172
+ export function getMagpieService(catalog: GatewayCatalogService): MagpieService {
173
+ const globals = globalThis as typeof globalThis & { [SHARED]?: WeakMap<object, MagpieState> };
174
+ const states = globals[SHARED] ??= new WeakMap();
175
+ const identity = catalog.identity;
176
+ let state = states.get(identity);
177
+ if (!state) states.set(identity, state = createState());
178
+ let service = instances.get(identity);
179
+ if (!service) instances.set(identity, service = createMagpieService(catalog, undefined, undefined, state));
180
+ return service;
181
+ }
@@ -0,0 +1,43 @@
1
+ import type { MagpieCard, MagpieWindow } from "./data.ts";
2
+ import { groupCards } from "./view.ts";
3
+
4
+ interface Reading {
5
+ percent?: number;
6
+ stale: boolean;
7
+ }
8
+
9
+ /** 底部仅展示 OpenAI:同账户取瓶颈窗口,再取已知账户最大值。 */
10
+ export function quotaSummary(cards: readonly MagpieCard[]): string | undefined {
11
+ const group = groupCards(cards).find(group => group.name === "OpenAI / Codex");
12
+ const readings = (group?.cards ?? []).filter(card => !card.held && !card.needsAccessKey).map(cardReading);
13
+ const known = readings.filter((reading): reading is Reading & { percent: number } => reading.percent !== undefined);
14
+ // 当前读数优先,避免一个失败账户的旧高值盖过正常账户的新低值。
15
+ const fresh = known.filter(reading => !reading.stale);
16
+ const usable = fresh.length ? fresh : known;
17
+ if (!usable.length) return;
18
+ const best = Math.max(...usable.map(reading => reading.percent));
19
+ const value = best === Infinity ? "∞" : `${Math.round(best * 100) / 100}%`;
20
+ return `剩余:OpenAI ${value}${fresh.length ? "" : "(旧)"}`;
21
+ }
22
+
23
+ function cardReading(card: MagpieCard): Reading {
24
+ // 独立图片通道与额外消费行不是账户的共同额度限制。
25
+ const windows = (card.windows ?? []).filter(window => !window.lane && !window.extra && !window.text);
26
+ const percentages = windows.map(windowRemaining);
27
+ return {
28
+ percent: percentages.length && percentages.every(percent => percent !== undefined)
29
+ ? Math.min(...percentages) : undefined,
30
+ stale: Boolean(card.error?.trim() || card.asOf?.trim()),
31
+ };
32
+ }
33
+
34
+ function windowRemaining(window: MagpieWindow): number | undefined {
35
+ if (window.unlimited) return Infinity;
36
+ // 没有总量的钱包 used/remaining 不是百分比。
37
+ if (window.balance !== undefined && !(window.limit !== undefined && window.limit > 0)) return;
38
+ const used = window.used;
39
+ if (used !== undefined && (used < 0 || used > 100)) return;
40
+ const remaining = window.remaining ?? (used === undefined ? undefined : 100 - used);
41
+ if (remaining === undefined || remaining < 0 || remaining > 100) return;
42
+ return remaining;
43
+ }
@@ -0,0 +1,79 @@
1
+ import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
2
+ import type { MagpieCard, MagpieStatusline } from "./data.ts";
3
+ import { cardDetails, cardLabel, groupCards, statusDetails } from "./view.ts";
4
+ import type { MagpieSnapshot, RefreshTarget } from "./service.ts";
5
+
6
+ export function snapshotLines<T>(snapshot: MagpieSnapshot<T>): string[] {
7
+ return [
8
+ ...(snapshot.error ? [snapshot.error] : []),
9
+ ...(snapshot.fetchedAt === undefined ? [] : [`状态获取时间:${new Date(snapshot.fetchedAt).toLocaleString()}`]),
10
+ ...(snapshot.data === undefined ? ["尚无可用读数。"] : []),
11
+ ];
12
+ }
13
+
14
+ export async function showStatus(ui: ExtensionUIContext, snapshot: MagpieSnapshot<MagpieStatusline>, signal: AbortSignal) {
15
+ if (signal.aborted) return;
16
+ await ui.select("Magpie 状态(选择任一行关闭)", [
17
+ ...snapshotLines(snapshot), ...(snapshot.data ? statusDetails(snapshot.data) : []),
18
+ ], { signal });
19
+ }
20
+
21
+ export async function showCards(ui: ExtensionUIContext, snapshot: MagpieSnapshot<MagpieCard[]>, signal: AbortSignal) {
22
+ const cards = snapshot.data;
23
+ if (!cards?.length) {
24
+ if (!signal.aborted) await ui.select("Magpie 额度", [...snapshotLines(snapshot), "当前没有可见额度卡片。"], { signal });
25
+ return;
26
+ }
27
+ const groups = groupCards(cards);
28
+ while (!signal.aborted) {
29
+ const labels = groups.map((group, i) => `${i + 1}. ${group.name} · ${group.cards.length} 条源记录`);
30
+ const choice = await ui.select(`Magpie 额度${snapshot.error ? "(沿用旧读数,本次查询失败)" : ""}`,
31
+ [...labels, "查看读取信息", "返回"], { signal });
32
+ if (signal.aborted || !choice || choice === "返回") return;
33
+ if (choice === "查看读取信息") {
34
+ await ui.select("读取信息", [...snapshotLines(snapshot), "各卡片读数时间见详情;比例与不同账户资源不相加。"], { signal });
35
+ continue;
36
+ }
37
+ const group = groups[labels.indexOf(choice)];
38
+ if (!group) return;
39
+ const sources = new Map<string, MagpieCard[]>();
40
+ for (const card of group.cards) {
41
+ const source = card.from || (card.provider.includes("/") ? card.provider.slice(0, card.provider.lastIndexOf("/")) : "当前网关");
42
+ const entries = sources.get(source) ?? [];
43
+ entries.push(card);
44
+ sources.set(source, entries);
45
+ }
46
+ const names = [...sources.keys()];
47
+ const source = await ui.select(`${group.name} · 来源`, [...names, "返回"], { signal });
48
+ if (signal.aborted || !source || source === "返回") continue;
49
+ const entries = sources.get(source)!;
50
+ const accounts = entries.map((card, i) => cardLabel(card, i));
51
+ const account = await ui.select(`${group.name} · ${source}`, [...accounts, "返回"], { signal });
52
+ if (signal.aborted || !account || account === "返回") continue;
53
+ const card = entries[accounts.indexOf(account)];
54
+ if (card) await ui.select("额度详情(选择任一行返回)", cardDetails(card), { signal });
55
+ }
56
+ }
57
+
58
+ /** 选择的是协议匹配范围;同名卡片和未展示的匹配记录都可能被刷新。 */
59
+ export async function chooseRefresh(ui: ExtensionUIContext, cards: MagpieCard[], signal: AbortSignal):
60
+ Promise<{ target?: RefreshTarget } | undefined> {
61
+ const labels = cards.map((card, i) => cardLabel(card, i));
62
+ const choice = await ui.select("刷新上游额度 · 选择影响范围", ["全部可见额度", ...labels], { signal });
63
+ if (signal.aborted || !choice) return;
64
+ const card = cards[labels.indexOf(choice)];
65
+ const target = card ? { provider: card.provider, ...(card.user ? { user: card.user } : {}) } : undefined;
66
+ const description = target
67
+ ? `provider=${target.provider}\n${target.user ? `账户匹配:${target.user}(忽略大小写,同名多卡可能共同刷新)` : "未限定账户,将刷新该 provider 的全部可见账户"}`
68
+ : "将刷新当前密钥可见的全部额度卡片";
69
+ if (await ui.confirm("确认刷新上游额度", `${description}\n这是请求供应商重读,不保证读数时间变化;不消耗重置权益。`, { signal }) && !signal.aborted)
70
+ return { target };
71
+ }
72
+
73
+ export function unchangedReadTimes(previous: MagpieCard[] | undefined, next: MagpieCard[] | undefined): boolean {
74
+ if (!previous?.length || !next || previous.length !== next.length) return false;
75
+ const signature = (cards: MagpieCard[]) => cards.map(card =>
76
+ JSON.stringify([card.provider, card.user, card.plan, card.kind, card.from, card.readAt, card.asOf])).sort();
77
+ const before = signature(previous);
78
+ return signature(next).every((value, index) => value === before[index]);
79
+ }
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Magpie 额度卡片的纯展示投影:分组、标签与逐条明细。
3
+ *
4
+ * 这里不读取配置、不发请求,也不补充读数:输入是 data.ts 已校验的保真卡片,
5
+ * 输出是给菜单/详情直接使用的文本。数组顺序、对象引用和未知字段都保持原样,
6
+ * 同一 provider/user 的多张卡片各自渲染,绝不相加或去重。
7
+ */
8
+ import type {
9
+ MagpieBalancePart,
10
+ MagpieCard,
11
+ MagpieEstimate,
12
+ MagpieResetCredits,
13
+ MagpieStatusline,
14
+ MagpieWindow,
15
+ } from "./data.ts";
16
+
17
+ export interface MagpieCardGroup {
18
+ name: string;
19
+ cards: MagpieCard[];
20
+ }
21
+
22
+ /** 已证实的厂商/产品族。Magpie 的 provider 对订阅常是产品标识(codex、kimi-code),
23
+ * 对套餐/余额是渠道标识;远程卡片被改写成 `远程/provider`(可能链式),
24
+ * 真实产品在最后一个路径段,因此只据末段与已知产品对照,不做启发式猜测。 */
25
+ const VENDOR_FAMILIES: Readonly<Record<string, string>> = {
26
+ codex: "OpenAI / Codex",
27
+ claude: "Anthropic / Claude",
28
+ minimax: "MiniMax",
29
+ "minimax-cn": "MiniMax",
30
+ deepseek: "DeepSeek",
31
+ kimi: "Moonshot / Kimi",
32
+ "kimi-code": "Moonshot / Kimi",
33
+ "kimi-code-cn": "Moonshot / Kimi",
34
+ moonshot: "Moonshot / Kimi",
35
+ "moonshot-cn": "Moonshot / Kimi",
36
+ };
37
+
38
+ function nonEmpty(value: string | undefined): string | undefined {
39
+ const text = value?.trim();
40
+ return text ? text : undefined;
41
+ }
42
+
43
+ /** 完整来源:远程卡片保留“远程 Magpie 名/provider”,不按展示名改写成厂商。 */
44
+ function sourceOf(card: MagpieCard): string {
45
+ const from = nonEmpty(card.from);
46
+ if (from && !card.provider.startsWith(`${from}/`)) return `${from}/${card.provider}`;
47
+ return card.provider;
48
+ }
49
+
50
+ function isRemote(card: MagpieCard): boolean {
51
+ return Boolean(nonEmpty(card.from)) || card.provider.includes("/");
52
+ }
53
+
54
+ /** 远程 provider 形如 `远程/product`,可链式;末段与 provider 自身同属于产品标识。 */
55
+ function productSegment(provider: string): string {
56
+ return provider.slice(provider.lastIndexOf("/") + 1);
57
+ }
58
+
59
+ /** 已知产品族优先:远程 codex 与本地 codex 同属 OpenAI / Codex,来源由组内再分。 */
60
+ function groupName(card: MagpieCard): string {
61
+ const family = VENDOR_FAMILIES[productSegment(card.provider).toLowerCase()];
62
+ if (family) return family;
63
+ return isRemote(card) ? sourceOf(card) : card.provider;
64
+ }
65
+
66
+ /** 按厂商/产品族分组;未知产品与未知远程来源保持自身名称,组内顺序按首次出现。 */
67
+ export function groupCards(cards: readonly MagpieCard[]): MagpieCardGroup[] {
68
+ const groups = new Map<string, MagpieCardGroup>();
69
+ for (const card of cards) {
70
+ const name = groupName(card);
71
+ let group = groups.get(name);
72
+ if (!group) {
73
+ group = { name, cards: [] };
74
+ groups.set(name, group);
75
+ }
76
+ group.cards.push(card);
77
+ }
78
+ return [...groups.values()];
79
+ }
80
+
81
+ /** 卡片标签;同名卡片由调用方传入的列表下标区分,不合并记录。 */
82
+ export function cardLabel(card: MagpieCard, index?: number): string {
83
+ const parts: string[] = [];
84
+ const add = (value: string | undefined): void => {
85
+ const text = nonEmpty(value);
86
+ if (text && !parts.includes(text)) parts.push(text);
87
+ };
88
+ add(card.name);
89
+ add(card.alias);
90
+ add(card.user);
91
+ add(card.plan);
92
+ if (isRemote(card)) add(sourceOf(card));
93
+ if (!parts.length) add(card.provider);
94
+ const label = parts.join(" · ");
95
+ return index === undefined ? label : `${label}(#${index + 1})`;
96
+ }
97
+
98
+ function kindLabel(kind: string | undefined): string | undefined {
99
+ switch (kind) {
100
+ case "subscription": return "订阅账户";
101
+ case "plan": return "密钥套餐";
102
+ case "balance": return "密钥余额";
103
+ default: return nonEmpty(kind);
104
+ }
105
+ }
106
+
107
+ function withUnit(value: number, unit: string | undefined): string {
108
+ return unit ? `${value} ${unit}` : String(value);
109
+ }
110
+
111
+ function round2(value: number): number {
112
+ return Math.round(value * 100) / 100;
113
+ }
114
+
115
+ // 输入已经在 data.ts 入口完成类型降级;这里只按语义判断(文本行、无总量钱包、有效百分比),不重复校验类型。
116
+ function windowLine(window: MagpieWindow): string {
117
+ const name = nonEmpty(window.name) ?? "未命名窗口";
118
+ const details: string[] = [];
119
+ const display = nonEmpty(window.display);
120
+ if (display) details.push(display);
121
+ const unlimited = window.unlimited === true;
122
+ const isText = window.text === true;
123
+ const wallet = window.balance;
124
+ const limit = window.limit !== undefined && window.limit > 0 ? window.limit : undefined;
125
+ const unit = nonEmpty(window.unit);
126
+ const used = window.used;
127
+
128
+ if (unlimited) details.push("无限额");
129
+ if (isText) {
130
+ // 文本行的 used 不是占比;没有 display 时只能说读数未知,不能补成满额。
131
+ details.push(display ? "文本行(used 不是占比)" : "文本读数未知(used 不是占比)");
132
+ } else if (!unlimited) {
133
+ // 钱包窗口没有总量时,used=0 不代表未使用,只有 amount/limit 才构成占比。
134
+ let remainingShown = false;
135
+ const percentReadable = used !== undefined && used >= 0 && used <= 100 && (wallet === undefined || limit !== undefined);
136
+ if (used !== undefined && percentReadable) {
137
+ details.push(`已用 ${used}%`);
138
+ const remaining = window.remaining ?? round2(100 - used);
139
+ details.push(`剩余 ${remaining}%`);
140
+ } else if (used !== undefined && (used < 0 || used > 100)) {
141
+ details.push(`used=${used}(超出百分比范围,不是有效读数)`);
142
+ } else if (used === undefined) {
143
+ // 入口可能因数据异常剔除 used;remaining 仍是可消费读数时不能一起丢掉。
144
+ const remaining = window.remaining;
145
+ if (remaining !== undefined && remaining >= 0 && remaining <= 100 && (wallet === undefined || limit !== undefined)) {
146
+ details.push(`剩余 ${remaining}%`);
147
+ remainingShown = true;
148
+ }
149
+ }
150
+ if (wallet !== undefined) details.push(`钱包余额 ${withUnit(wallet, unit)}`);
151
+ if (limit !== undefined) {
152
+ // 入口可能剔除异常 amount;缺失是未知,不能补成 0。
153
+ const amount = window.amount !== undefined ? withUnit(window.amount, unit) : "未知";
154
+ details.push(`计量 ${amount} / ${withUnit(limit, unit)}`);
155
+ }
156
+ if (!display && wallet === undefined && limit === undefined && used === undefined && !remainingShown) details.push("读数未知");
157
+ }
158
+ if (window.resetsAt) details.push(`重置 ${window.resetsAt}`);
159
+ if (window.runsOut !== undefined || window.runsOutAt) {
160
+ const runsOut = window.runsOut !== undefined ? withUnit(window.runsOut, unit) : "数量未知";
161
+ details.push(`到期失效 ${runsOut}${window.runsOutAt ? `(${window.runsOutAt})` : "(时间未知)"}`);
162
+ }
163
+ if (window.spent !== undefined || window.spentSince) {
164
+ const spent = window.spent !== undefined ? withUnit(window.spent, unit) : "数量未知";
165
+ details.push(`本周期已花费 ${spent}${window.spentSince ? `(自 ${window.spentSince})` : ""}`);
166
+ }
167
+ if (window.pool) details.push(`共享池 ${window.pool}`);
168
+ if (window.lane) details.push(`通道 ${window.lane}`);
169
+ if (window.family) details.push(`族 ${window.family}`);
170
+ return `${name}:${details.join(";")}`;
171
+ }
172
+
173
+ function balancePartLine(part: MagpieBalancePart): string {
174
+ const label = nonEmpty(part.label);
175
+ const percent = part.percent !== undefined ? `(${part.percent}%)` : "";
176
+ const error = nonEmpty(part.error) ? `;读取错误:${part.error}` : "";
177
+ const expires = nonEmpty(part.expires) ? `;到期 ${part.expires}` : "";
178
+ return `余额分项:${part.text}${label ? `(${label})` : ""}${percent}${expires}${error}`;
179
+ }
180
+
181
+ function estimateLine(estimate: MagpieEstimate): string {
182
+ const since = nonEmpty(estimate.from) ?? nonEmpty(estimate.at) ?? "未知时间";
183
+ const currency = nonEmpty(estimate.currency);
184
+ const currencyNote = currency ? `(${currency})` : "";
185
+ const left = estimate.left !== null && estimate.left !== undefined ? withUnit(estimate.left, undefined) : undefined;
186
+ return `估算余额(非厂商读数):设定 ${estimate.set},自 ${since} 起已用 ${estimate.spent}${left === undefined ? "" : `,剩余 ${left}`}${currencyNote}`;
187
+ }
188
+
189
+ function renewLabel(renew: string | undefined): string {
190
+ if (renew === "auto") return "自动续期";
191
+ if (renew === "off") return "不续期";
192
+ return "续期状态未知";
193
+ }
194
+
195
+ function resetsLine(resets: MagpieResetCredits): string {
196
+ const parts = [`重置权益:${resets.count} 次`];
197
+ if (resets.until) parts.push(`最近至 ${resets.until}`);
198
+ if (resets.byWindow) {
199
+ const windows: string[] = [];
200
+ if (resets.fiveHour !== undefined) windows.push(`五小时 ${resets.fiveHour}`);
201
+ if (resets.weekly !== undefined) windows.push(`每周 ${resets.weekly}`);
202
+ if (windows.length) parts.push(`按窗口(${windows.join(",")})`);
203
+ }
204
+ if (resets.team) parts.push("团队套餐");
205
+ return parts.join(";");
206
+ }
207
+
208
+ /** 余额、分项、共享余额、估算与重置权益;都按源记录各自展示,不相加。 */
209
+ function fundsLines(card: MagpieCard): string[] {
210
+ const lines: string[] = [];
211
+ if (nonEmpty(card.balance)) lines.push(`余额:${card.balance}(仅此记录,不与同厂商其他卡片相加)`);
212
+ const parts = [...(card.balanceSplit ?? []), ...(card.balanceParts ?? [])];
213
+ if (parts.length) {
214
+ lines.push("余额分项(同一笔余额的拆分,不与余额或其他卡片相加):");
215
+ for (const part of parts) lines.push(balancePartLine(part));
216
+ }
217
+ if (card.sharedBalance) lines.push(`共享余额:与「${card.sharedBalance}」共用,不能按卡片重复相加。`);
218
+ if (card.estimate) lines.push(estimateLine(card.estimate));
219
+ if (card.resets) {
220
+ lines.push(resetsLine(card.resets));
221
+ for (const reset of card.resets.each ?? []) {
222
+ const window = nonEmpty(reset.window);
223
+ lines.push(`权益项:${nonEmpty(reset.until) ?? "无到期时间"}${window ? `(${window})` : ""}`);
224
+ }
225
+ }
226
+ return lines;
227
+ }
228
+
229
+ /** 逐条卡片明细;账户、读数时间、错误、余额与权益都按源记录展示。 */
230
+ export function cardDetails(card: MagpieCard): string[] {
231
+ const lines: string[] = [];
232
+ lines.push(`来源:${sourceOf(card)}`);
233
+ const kind = kindLabel(card.kind);
234
+ if (kind) lines.push(`类型:${kind}`);
235
+ lines.push(`账户:${nonEmpty(card.user) ?? "未提供"}`);
236
+ if (card.alias) lines.push(`账户别名:${card.alias}`);
237
+ if (card.seat) lines.push(`代替的密钥套餐:${card.seat}`);
238
+ lines.push(`套餐:${nonEmpty(card.plan) ?? "未提供"}`);
239
+ if (card.until) lines.push(`付费有效期至:${card.until}(${renewLabel(card.renew)})`);
240
+ if (card.held) lines.push("该账户当前未被网关派发(held)。");
241
+ if (card.needsAccessKey) lines.push("缺少该账户的读取密钥,额度未取得。");
242
+ lines.push(`读数时间:${nonEmpty(card.readAt) ?? "未提供"}`);
243
+ if (card.asOf) lines.push(`旧读数时间:${card.asOf}(沿用此前读数)`);
244
+ if (card.readDeferred) lines.push("本次未主动读取(沿用缓存)。");
245
+ if (nonEmpty(card.error)) lines.push(`本次记录错误:${card.error}`);
246
+ lines.push(...fundsLines(card));
247
+ const windows = card.windows;
248
+ if (windows == null) lines.push("窗口:未提供(不能视为无限额或满额)");
249
+ else if (!windows.length) lines.push("窗口:未返回(可能是余额卡、尚无读数或未取得窗口)");
250
+ else for (const window of windows) lines.push(`窗口:${windowLine(window)}`);
251
+ if (card.lastServedAt) lines.push(`最近经网关答复:${card.lastServedAt}`);
252
+ return lines;
253
+ }
254
+
255
+ /** 状态行明细;模型名只称为网关报告值,成员判定留给路由数据。 */
256
+ export function statusDetails(status: MagpieStatusline): string[] {
257
+ const lines: string[] = [];
258
+ lines.push(`模型(网关状态报告值):${status.model || "未提供"}`);
259
+ lines.push("该模型名可能是请求名回退,不能证明实际执行的成员。");
260
+ const text = nonEmpty(status.text);
261
+ if (text) lines.push(`网关状态行:${text}`);
262
+ if (!status.accounts.length) lines.push("账户卡片:未返回(不代表没有账户或额度)。");
263
+ else {
264
+ const failed = status.accounts.filter(account => nonEmpty(account.error)).length;
265
+ lines.push(`账户卡片:${status.accounts.length} 条${failed ? `,其中 ${failed} 条带本次错误` : ""}。`);
266
+ for (const [index, account] of status.accounts.entries()) {
267
+ lines.push(`${cardLabel(account, index)} · 读数时间:${account.readAt || account.asOf || "未提供"}`);
268
+ if (account.asOf) lines.push(`沿用旧读数:${account.asOf}`);
269
+ if (account.error) lines.push(`本次记录错误:${account.error}`);
270
+ }
271
+ }
272
+ return lines;
273
+ }
@@ -20,23 +20,27 @@ interface RecoveryRound {
20
20
  promise: Promise<GatewayCatalogOutcome>;
21
21
  }
22
22
 
23
+ export interface GatewayCatalogRecoveryState {
24
+ active?: RecoveryRound;
25
+ }
26
+
23
27
  /** 进程共享服务内的一轮恢复;新加入者不延长截止,手动获取不触发重试。 */
24
- export function createGatewayCatalogRecovery(options: { onIdle?(): void } = {}) {
25
- let active: RecoveryRound | undefined;
28
+ export function createGatewayCatalogRecovery(options: { state?: GatewayCatalogRecoveryState; onIdle?(): void } = {}) {
29
+ const state = options.state ?? {};
26
30
  return {
27
- stop() { active?.controller.abort(); active = undefined; options.onIdle?.(); },
28
- hasParticipants: () => !!active && !active.controller.signal.aborted && active.waiters > 0,
31
+ stop() { state.active?.controller.abort(); state.active = undefined; options.onIdle?.(); },
32
+ hasParticipants: () => !!state.active && !state.active.controller.signal.aborted && state.active.waiters > 0,
29
33
  join(
30
34
  request: (signal: AbortSignal) => Promise<GatewayCatalogOutcome>,
31
35
  fallback: () => GatewayCatalogOutcome,
32
36
  signal?: AbortSignal,
33
37
  ): Promise<GatewayCatalogOutcome> {
34
38
  if (signal?.aborted) return Promise.reject(cancelled());
35
- if (active?.controller.signal.aborted) active = undefined;
36
- if (!active) {
39
+ if (state.active?.controller.signal.aborted) state.active = undefined;
40
+ if (!state.active) {
37
41
  const round: RecoveryRound = { controller: new AbortController(), waiters: 0, participants: new Set(),
38
42
  promise: Promise.resolve({ networkAttempted: false, networkSucceeded: false, failed: true, retryable: true }) };
39
- active = round;
43
+ state.active = round;
40
44
  let deadline: ReturnType<typeof setTimeout> | undefined;
41
45
  let wake: ReturnType<typeof setTimeout> | undefined;
42
46
  let cancelWait: (() => void) | undefined;
@@ -82,10 +86,10 @@ export function createGatewayCatalogRecovery(options: { onIdle?(): void } = {})
82
86
  clearTimeout(wake);
83
87
  cancelWait?.();
84
88
  round.controller.signal.removeEventListener("abort", abort);
85
- if (active === round) { active = undefined; options.onIdle?.(); }
89
+ if (state.active === round) { state.active = undefined; options.onIdle?.(); }
86
90
  });
87
91
  }
88
- const round = active;
92
+ const round = state.active;
89
93
  const participant = { request };
90
94
  round.participants.add(participant);
91
95
  round.waiters++;