pi-tsgw 3.5.0 → 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.
package/README.md CHANGED
@@ -28,7 +28,7 @@ pi install npm:pi-tsgw
28
28
  使用 `/tsgw` 查看目录状态,`/tsgw-refresh` 强制刷新。
29
29
  网关目录含 `magpie_label` 时自动识别为 Magpie,识别结果随目录缓存并在当前宿主进程内共享。识别后可在 `/tsgw` 查看状态与按厂商/来源展开的额度、重新读取卡片或明确确认刷新上游;普通查看只读网关缓存,刷新按 provider/账户匹配范围执行,同名卡片可能共同刷新。
30
30
 
31
- 使用该网关的正常用户任务完成后,异步读取一次全局额度卡片,同一网关和凭据在当前宿主进程内共享读数与 60 秒复用窗口;切换会话或模型保留已有读数,空闲不轮询,不自动刷新供应商。底部按厂商显示最高已知剩余比例:先取每个账户共同限制窗口中的最低值,再取同厂商账户的最高值;厂商组无百分比时按原单位展示余额,未知与旧读数单独标记,不跨账户相加。完整窗口、读数时间和会话状态仍可在 `/tsgw` 查看;状态报告的模型名可能是请求别名,不代表实际路由成员。
31
+ 使用该网关的正常用户任务完成后,异步读取一次全局额度卡片,同一网关和凭据在当前宿主进程内共享读数与 60 秒复用窗口;切换会话或模型保留已有读数,空闲不轮询,不自动刷新供应商。底部仅显示 OpenAI 的最高已知剩余比例:先取每个账户共同限制窗口中的最低值,再取可用 OpenAI 账户的最高值;无有效读数时隐藏额度项,有效旧读数标记为旧。其他厂商及余额在详情中查看,不跨账户相加。完整窗口、读数时间和会话状态仍可在 `/tsgw` 查看;状态报告的模型名可能是请求别名,不代表实际路由成员。
32
32
 
33
33
  网关追踪头默认开启:`AH-Thread-Id` 和 `X-Magpie-Session` 使用真实会话 ID,`AH-Trace-Id` 关联真实用户消息;压缩、摘要等请求不冒充用户消息追踪。仅补充指向已配置网关的 `tsgw` 聊天请求,保留调用方已有同名头。可在 `settings.json` 的 `tsgw` 中设置 `"traceHeaders": false` 关闭插件补头,但不禁用宿主原生会话头或网关侧记录;网关已开启对话记录时,会话标识可能使其归集并保存对话。
34
34
 
@@ -118,8 +118,10 @@ export function registerMagpie(pi: ExtensionAPI, options: {
118
118
  const service = currentService();
119
119
  if (!service) return;
120
120
  const snapshot = service.cards();
121
- if (!snapshot.data) return snapshot.error ? "额度读取失败" : "剩余:?";
122
- return `${quotaSummary(snapshot.data)}${snapshot.error ? "(旧)" : ""}`;
121
+ if (!snapshot.data) return;
122
+ const summary = quotaSummary(snapshot.data);
123
+ if (!summary) return;
124
+ return snapshot.error ? `${summary}(旧)` : summary;
123
125
  },
124
126
  async handle(choice: string, ctx: ExtensionCommandContext): Promise<void> {
125
127
  if (![STATUS, CARDS, RELOAD, REFRESH].includes(choice) || !ctx.hasUI) return;
@@ -7,8 +7,12 @@
7
7
  *
8
8
  * 卡片窗口是 `QuotaWindow`(没有 `remaining`);状态行账户是额度报告 `Quota`
9
9
  * (窗口另有 `remaining`),因此同一个保真卡片类型同时容纳两套窗口字段。
10
- * 解析只校验已知字段的类型与必需字段,未知字段原样保留并共享同一引用,
11
- * 不补窗口、不补读数,也不把缺失值当成 0 或 100%。
10
+ *
11
+ * 额度是参考快照:厂商身份和可解释读数是核心,附加展示/辅助字段允许陈旧、
12
+ * 缺失或类型漂移。入口只做一次校验,已知字段异常时局部剔除或把读数降为未知,
13
+ * 无法识别 provider 的卡片跳过;顶层列表缺失或不可识别仍明确失败,避免无效
14
+ * 响应冒充空成功。合法对象保持原引用,需要修改时最小 copy-on-write,未知字段
15
+ * 随浅拷贝保留引用;不补窗口、不补读数,也不把缺失值当成 0 或 100%。
12
16
  */
13
17
 
14
18
  /** 卡片已知字段均可缺失;未知字段通过索引签名原样保留。 */
@@ -83,6 +87,7 @@ export interface MagpieResetCredits extends Record<string, unknown> {
83
87
  * 一张额度卡片。`provider` 是 Magpie 的渠道标识(订阅常是 Agent ID),
84
88
  * 不必等于厂商名;`from` 是远程 Magpie 名称。同一 `provider/user`
85
89
  * 仍可能对应多张独立卡片,调用方不得据此覆盖或相加。
90
+ * `provider` 缺失或不可识别的卡片在入口跳过;其余已知字段异常只做局部降级。
86
91
  */
87
92
  export interface MagpieCard extends Record<string, unknown> {
88
93
  provider: string;
@@ -116,12 +121,13 @@ export interface MagpieCard extends Record<string, unknown> {
116
121
  }
117
122
 
118
123
  /**
119
- * statusline 响应。`model` 可能回退为请求名,不证明实际成员;
120
- * `accounts` 是额度报告口径的卡片,窗口另含 `remaining`。
124
+ * statusline 响应。`text`/`model` 只是展示信息,缺失或类型异常按未提供处理;
125
+ * `accounts` 是额度报告口径的卡片列表,缺失或非数组仍视为顶层形状错误。
126
+ * `model` 可能回退为请求名,不证明实际成员。
121
127
  */
122
128
  export interface MagpieStatusline extends Record<string, unknown> {
123
- text: string;
124
- model: string;
129
+ text?: string;
130
+ model?: string;
125
131
  accounts: MagpieCard[];
126
132
  }
127
133
 
@@ -138,126 +144,242 @@ function invalid(where: string, detail: string): never {
138
144
  }
139
145
 
140
146
  function asRecord(value: unknown, where: string): Record<string, unknown> {
141
- if (typeof value !== "object" || value === null || Array.isArray(value)) invalid(where, "必须是 JSON 对象。");
142
- return value as Record<string, unknown>;
147
+ if (!isRecord(value)) invalid(where, "必须是 JSON 对象。");
148
+ return value;
149
+ }
150
+
151
+ function isRecord(value: unknown): value is Record<string, unknown> {
152
+ return typeof value === "object" && value !== null && !Array.isArray(value);
143
153
  }
144
154
 
145
- function checkString(item: Record<string, unknown>, key: string, where: string): void {
146
- const value = item[key];
147
- if (value !== undefined && typeof value !== "string") invalid(where, `的 ${key} 必须是字符串。`);
155
+ function isFiniteNumber(value: unknown): value is number {
156
+ return typeof value === "number" && Number.isFinite(value);
148
157
  }
149
158
 
150
- function checkNumber(item: Record<string, unknown>, key: string, where: string): void {
151
- const value = item[key];
152
- if (value !== undefined && (typeof value !== "number" || !Number.isFinite(value))) invalid(where, `的 ${key} 必须是有限数值。`);
159
+ /**
160
+ * 惰性 copy-on-write:只有确实需要剔除或替换字段时才复制对象。
161
+ * 浅拷贝保留未知字段及其引用;没有改动时调用方继续返回原对象。
162
+ */
163
+ function editor(record: Record<string, unknown>) {
164
+ let copy: Record<string, unknown> | undefined;
165
+ const current = (): Record<string, unknown> => copy ?? record;
166
+ return {
167
+ value: current,
168
+ changed: (): boolean => copy !== undefined,
169
+ drop(key: string): void {
170
+ if (!Object.hasOwn(current(), key)) return;
171
+ copy ??= { ...record };
172
+ delete copy[key];
173
+ },
174
+ set(key: string, value: unknown): void {
175
+ if (Object.hasOwn(current(), key) && current()[key] === value) return;
176
+ copy ??= { ...record };
177
+ copy[key] = value;
178
+ },
179
+ };
153
180
  }
154
181
 
155
- function checkRequiredNumber(item: Record<string, unknown>, key: string, where: string): void {
156
- if (typeof item[key] !== "number" || !Number.isFinite(item[key] as number)) invalid(where, `缺少 ${key} 数值。`);
182
+ function dropWrongStrings(target: ReturnType<typeof editor>, keys: readonly string[]): void {
183
+ for (const key of keys) {
184
+ const value = target.value()[key];
185
+ if (value !== undefined && typeof value !== "string") target.drop(key);
186
+ }
157
187
  }
158
188
 
159
- function checkBoolean(item: Record<string, unknown>, key: string, where: string): void {
160
- const value = item[key];
161
- if (value !== undefined && typeof value !== "boolean") invalid(where, `的 ${key} 必须是布尔值。`);
189
+ function dropWrongNumbers(target: ReturnType<typeof editor>, keys: readonly string[]): void {
190
+ for (const key of keys) {
191
+ const value = target.value()[key];
192
+ if (value !== undefined && !isFiniteNumber(value)) target.drop(key);
193
+ }
194
+ }
195
+
196
+ function dropWrongBooleans(target: ReturnType<typeof editor>, keys: readonly string[]): void {
197
+ for (const key of keys) {
198
+ const value = target.value()[key];
199
+ if (value !== undefined && typeof value !== "boolean") target.drop(key);
200
+ }
162
201
  }
163
202
 
164
203
  const WINDOW_STRINGS = ["name", "display", "resetsAt", "unit", "pool", "lane", "family", "holdsWhy", "spentSince", "runsOutAt"] as const;
165
204
  const WINDOW_NUMBERS = ["used", "remaining", "amount", "limit", "balance", "spent", "runsOut", "resetSecs"] as const;
166
205
  const WINDOW_BOOLEANS = ["text", "unlimited", "credits", "extra", "capped"] as const;
167
206
 
168
- function checkWindow(value: unknown, where: string): MagpieWindow {
169
- const window = asRecord(value, where);
170
- for (const key of WINDOW_STRINGS) checkString(window, key, where);
171
- for (const key of WINDOW_NUMBERS) checkNumber(window, key, where);
172
- for (const key of WINDOW_BOOLEANS) checkBoolean(window, key, where);
173
- return window as MagpieWindow;
207
+ function sanitizeWindow(value: unknown): MagpieWindow {
208
+ // 窗口本身无法识别时保留一个未知窗口占位,避免汇总把剩余窗口当成完整额度。
209
+ if (!isRecord(value)) return {};
210
+ const target = editor(value);
211
+ const original = target.value();
212
+ // 文本行、无限额、独立通道、额外消费和钱包都会改变 used 的语义。标记存在但
213
+ // 类型异常时不能只删标记,否则 used=0 可能被误算成剩余 100%;清空读数降为未知。
214
+ const readingsUnknown =
215
+ (original.text !== undefined && typeof original.text !== "boolean") ||
216
+ (original.unlimited !== undefined && typeof original.unlimited !== "boolean") ||
217
+ (original.extra !== undefined && typeof original.extra !== "boolean") ||
218
+ (original.lane !== undefined && typeof original.lane !== "string") ||
219
+ (original.balance !== undefined && !isFiniteNumber(original.balance));
220
+ dropWrongStrings(target, WINDOW_STRINGS);
221
+ dropWrongNumbers(target, WINDOW_NUMBERS);
222
+ dropWrongBooleans(target, WINDOW_BOOLEANS);
223
+ if (readingsUnknown) {
224
+ target.drop("used");
225
+ target.drop("remaining");
226
+ }
227
+ return target.value() as MagpieWindow;
174
228
  }
175
229
 
176
- function checkWindows(item: Record<string, unknown>, where: string): void {
177
- const value = item.windows;
230
+ function sanitizeWindows(value: unknown): { value: MagpieWindow[] | null | undefined; changed: boolean } {
178
231
  // null 是协议可能输出的“未提供窗口”,保留原值,不改成 []、也不当作满额。
179
- if (value === undefined || value === null) return;
180
- if (!Array.isArray(value)) invalid(where, "的 windows 必须是数组或 null。");
181
- value.forEach((window, index) => checkWindow(window, `${where}第 ${index + 1} 个窗口`));
232
+ if (value === undefined || value === null) return { value, changed: false };
233
+ if (!Array.isArray(value)) return { value: undefined, changed: true };
234
+ let changed = false;
235
+ const windows = value.map(item => {
236
+ const window = sanitizeWindow(item);
237
+ if (window !== item) changed = true;
238
+ return window;
239
+ });
240
+ return { value: changed ? windows : value as MagpieWindow[], changed };
182
241
  }
183
242
 
184
- function checkBalanceParts(item: Record<string, unknown>, key: string, where: string): void {
185
- const value = item[key];
243
+ function sanitizeBalanceParts(value: unknown): MagpieBalancePart[] | undefined {
186
244
  if (value === undefined) return;
187
- if (!Array.isArray(value)) invalid(where, `的 ${key} 必须是数组。`);
188
- value.forEach((part, index) => {
189
- const at = `${where}的 ${key} 第 ${index + 1} 项`;
190
- const record = asRecord(part, at);
191
- if (typeof record.text !== "string") invalid(at, "缺少 text 字符串。");
192
- for (const field of ["label", "error", "expires"]) checkString(record, field, at);
193
- checkNumber(record, "percent", at);
194
- });
245
+ if (!Array.isArray(value)) return;
246
+ let changed = false;
247
+ const parts: MagpieBalancePart[] = [];
248
+ for (const item of value) {
249
+ if (!isRecord(item) || typeof item.text !== "string") {
250
+ changed = true;
251
+ continue;
252
+ }
253
+ const target = editor(item);
254
+ dropWrongStrings(target, ["label", "error", "expires"]);
255
+ dropWrongNumbers(target, ["percent"]);
256
+ if (target.changed()) changed = true;
257
+ parts.push(target.value() as MagpieBalancePart);
258
+ }
259
+ return changed ? parts : value as MagpieBalancePart[];
195
260
  }
196
261
 
197
- function checkEstimate(item: Record<string, unknown>, where: string): void {
198
- const value = item.estimate;
199
- if (value === undefined) return;
200
- const at = `${where}的 estimate`;
201
- const estimate = asRecord(value, at);
202
- checkRequiredNumber(estimate, "set", at);
203
- checkRequiredNumber(estimate, "spent", at);
204
- for (const key of ["rate"]) checkNumber(estimate, key, at);
205
- for (const key of ["at", "currency", "from", "next"]) checkString(estimate, key, at);
206
- const left = estimate.left;
207
- if (left !== undefined && left !== null && (typeof left !== "number" || !Number.isFinite(left))) invalid(at, "的 left 必须是有限数值或 null。");
262
+ function sanitizeEstimate(value: unknown): MagpieEstimate | undefined {
263
+ // set/spent 是估算可解释的最小前提;缺失或异常时整项降级,不编造读数。
264
+ if (!isRecord(value) || !isFiniteNumber(value.set) || !isFiniteNumber(value.spent)) return;
265
+ const target = editor(value);
266
+ dropWrongNumbers(target, ["rate"]);
267
+ dropWrongStrings(target, ["at", "currency", "from", "next"]);
268
+ const left = target.value().left;
269
+ if (left !== undefined && left !== null && !isFiniteNumber(left)) target.drop("left");
270
+ return target.value() as MagpieEstimate;
208
271
  }
209
272
 
210
- function checkResets(item: Record<string, unknown>, where: string): void {
211
- const value = item.resets;
212
- if (value === undefined) return;
213
- const at = `${where}的 resets`;
214
- const resets = asRecord(value, at);
215
- checkRequiredNumber(resets, "count", at);
216
- checkString(resets, "until", at);
217
- for (const key of ["fiveHour", "weekly"]) checkNumber(resets, key, at);
218
- for (const key of ["byWindow", "team"]) checkBoolean(resets, key, at);
219
- const each = resets.each;
220
- if (each === undefined) return;
221
- if (!Array.isArray(each)) invalid(at, "的 each 必须是数组。");
222
- each.forEach((card, index) => {
223
- const whereCard = `${at} 第 ${index + 1} 项`;
224
- const record = asRecord(card, whereCard);
225
- for (const key of ["until", "window", "id"]) checkString(record, key, whereCard);
226
- });
273
+ function sanitizeResets(value: unknown): MagpieResetCredits | undefined {
274
+ // count 是重置权益条目的核心;不可解释时整项降级,不凭 each 长度补 count。
275
+ if (!isRecord(value) || !isFiniteNumber(value.count)) return;
276
+ const target = editor(value);
277
+ dropWrongStrings(target, ["until"]);
278
+ dropWrongNumbers(target, ["fiveHour", "weekly"]);
279
+ dropWrongBooleans(target, ["byWindow", "team"]);
280
+ const each = target.value().each;
281
+ if (each !== undefined) {
282
+ if (!Array.isArray(each)) target.drop("each");
283
+ else {
284
+ let changed = false;
285
+ const cards: MagpieResetCard[] = [];
286
+ for (const item of each) {
287
+ if (!isRecord(item)) {
288
+ changed = true;
289
+ continue;
290
+ }
291
+ const card = editor(item);
292
+ dropWrongStrings(card, ["until", "window", "id"]);
293
+ if (card.changed()) changed = true;
294
+ cards.push(card.value() as MagpieResetCard);
295
+ }
296
+ if (changed) target.set("each", cards);
297
+ }
298
+ }
299
+ return target.value() as MagpieResetCredits;
227
300
  }
228
301
 
229
302
  const CARD_STRINGS = ["name", "user", "plan", "from", "kind", "readAt", "asOf", "error", "balance", "alias", "seat", "sharedBalance", "until", "renew", "lastServedAt"] as const;
230
303
  const CARD_BOOLEANS = ["readDeferred", "held", "last", "pluginError", "needsAccessKey"] as const;
304
+ const MALFORMED_READING = "记录字段异常,读数按旧读数处理。";
305
+
306
+ function replaceNested(target: ReturnType<typeof editor>, key: string, original: unknown, next: unknown): void {
307
+ if (original === undefined) return;
308
+ if (next === undefined) target.drop(key);
309
+ else if (next !== original) target.set(key, next);
310
+ }
311
+
312
+ function sanitizeCard(value: unknown): MagpieCard | undefined {
313
+ // provider 是卡片身份;无法识别时无法分组、刷新或解释读数,只跳过这一条。
314
+ if (!isRecord(value) || typeof value.provider !== "string" || !value.provider.trim()) return;
315
+ const target = editor(value);
316
+ const original = target.value();
317
+ const errorMalformed = original.error !== undefined && typeof original.error !== "string";
318
+ const asOfMalformed = original.asOf !== undefined && typeof original.asOf !== "string";
319
+ const heldMalformed = original.held !== undefined && typeof original.held !== "boolean";
320
+ const accessKeyMalformed = original.needsAccessKey !== undefined && typeof original.needsAccessKey !== "boolean";
321
+ dropWrongStrings(target, CARD_STRINGS);
322
+ dropWrongBooleans(target, CARD_BOOLEANS);
323
+ // error/asOf 是“读数可能陈旧”的语义标记;类型异常时保留一个通用错误标记,
324
+ // 避免删掉后旧读数被当成新鲜读数展示。
325
+ if (errorMalformed || (asOfMalformed && original.error === undefined)) target.set("error", MALFORMED_READING);
326
+ // 派发/密钥状态无法解释时保留参考读数并标记不确定,不能编造停派或缺密钥事实。
327
+ if (heldMalformed || accessKeyMalformed)
328
+ target.set("error", "账户状态字段异常,额度仅供参考。");
231
329
 
232
- function checkCard(value: unknown, where: string): MagpieCard {
233
- const card = asRecord(value, where);
234
- if (typeof card.provider !== "string" || !card.provider.trim()) invalid(where, "缺少非空的 provider 字符串。");
235
- for (const key of CARD_STRINGS) checkString(card, key, where);
236
- for (const key of CARD_BOOLEANS) checkBoolean(card, key, where);
237
- checkWindows(card, where);
238
- checkBalanceParts(card, "balanceSplit", where);
239
- checkBalanceParts(card, "balanceParts", where);
240
- checkEstimate(card, where);
241
- checkResets(card, where);
242
- return card as MagpieCard;
330
+ if (original.windows !== undefined) {
331
+ const windows = sanitizeWindows(original.windows);
332
+ if (windows.value === undefined) target.drop("windows");
333
+ else if (windows.changed) target.set("windows", windows.value);
334
+ }
335
+ replaceNested(target, "balanceSplit", original.balanceSplit, sanitizeBalanceParts(original.balanceSplit));
336
+ replaceNested(target, "balanceParts", original.balanceParts, sanitizeBalanceParts(original.balanceParts));
337
+ replaceNested(target, "estimate", original.estimate, sanitizeEstimate(original.estimate));
338
+ replaceNested(target, "resets", original.resets, sanitizeResets(original.resets));
339
+ return target.value() as MagpieCard;
243
340
  }
244
341
 
245
- /** 解析 `/v1/magpie/quotas/cards` 响应;返回的卡片与原始对象共享引用。 */
342
+ /**
343
+ * 解析 `/v1/magpie/quotas/cards` 响应。无法识别 provider 的卡片跳过;其余卡片
344
+ * 局部降级。全部合法时返回原始数组及卡片引用,否则返回保留原引用的新数组。
345
+ */
246
346
  export function parseCards(value: unknown): MagpieCard[] {
247
347
  const payload = asRecord(value, "cards 响应");
248
- if (payload.object !== "list") invalid("cards 响应", "缺少 object:\"list\"。");
249
348
  if (!Array.isArray(payload.data)) invalid("cards 响应", "data 必须是数组。");
250
- payload.data.forEach((card, index) => checkCard(card, `cards 响应第 ${index + 1} 条卡片`));
251
- return payload.data as MagpieCard[];
349
+ let changed = false;
350
+ const cards: MagpieCard[] = [];
351
+ for (const item of payload.data) {
352
+ const card = sanitizeCard(item);
353
+ if (!card) {
354
+ changed = true;
355
+ continue;
356
+ }
357
+ if (card !== item) changed = true;
358
+ cards.push(card);
359
+ }
360
+ return changed ? cards : payload.data as MagpieCard[];
252
361
  }
253
362
 
254
- /** 解析 `/v1/magpie/statusline?format=json` 响应;账户按保真卡片校验。 */
363
+ /** 解析 `/v1/magpie/statusline?format=json` 响应;展示字段降级,账户按保真卡片处理。 */
255
364
  export function parseStatusline(value: unknown): MagpieStatusline {
256
365
  const payload = asRecord(value, "statusline 响应");
257
- for (const key of ["text", "model"]) {
258
- if (typeof payload[key] !== "string") invalid("statusline 响应", `缺少 ${key} 字符串。`);
259
- }
260
366
  if (!Array.isArray(payload.accounts)) invalid("statusline 响应", "accounts 必须是数组。");
261
- payload.accounts.forEach((account, index) => checkCard(account, `statusline 响应 accounts 第 ${index + 1} 条卡片`));
262
- return payload as MagpieStatusline;
367
+ const target = editor(payload);
368
+ for (const key of ["text", "model"] as const) {
369
+ const current = target.value()[key];
370
+ if (current !== undefined && typeof current !== "string") target.drop(key);
371
+ }
372
+ let accountsChanged = false;
373
+ const accounts: MagpieCard[] = [];
374
+ for (const item of payload.accounts) {
375
+ const card = sanitizeCard(item);
376
+ if (!card) {
377
+ accountsChanged = true;
378
+ continue;
379
+ }
380
+ if (card !== item) accountsChanged = true;
381
+ accounts.push(card);
382
+ }
383
+ if (accountsChanged) target.set("accounts", accounts);
384
+ return target.value() as MagpieStatusline;
263
385
  }
@@ -23,18 +23,24 @@ interface Resource<T> {
23
23
  blocked?: boolean;
24
24
  task?: Task<T>;
25
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
+ }
26
34
  const TTL = 60_000;
27
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
+ });
28
39
 
29
40
  /** 只共享同一目录作用域的内存读数,不保存宿主上下文或常驻明文凭据。 */
30
41
  export function createMagpieService(catalog: Pick<GatewayCatalogService, "valid" | "isMagpie">,
31
- fetcher: typeof fetch = (...args) => globalThis.fetch(...args), now = Date.now) {
32
- const cards = resource<MagpieCard[]>();
33
- const listeners = new Set<() => void>();
34
- const sessions = new Map<string, Resource<MagpieStatusline>>();
35
- let statusBlocked = false;
36
- let refresh: { target?: RefreshTarget; task: Task<MagpieCard[]> } | undefined;
37
- let cardsRevision = 0;
42
+ fetcher: typeof fetch = (...args) => globalThis.fetch(...args), now = Date.now, state = createState()) {
43
+ const { cards, listeners, sessions } = state;
38
44
  const valid = () => catalog.valid() && catalog.isMagpie();
39
45
  const session = (id: string) => {
40
46
  let state = sessions.get(id);
@@ -88,51 +94,51 @@ export function createMagpieService(catalog: Pick<GatewayCatalogService, "valid"
88
94
  async readStatus(id: string, request: MagpieRequest,
89
95
  options: { force?: boolean; automatic?: boolean; signal?: AbortSignal } = {}): Promise<MagpieSnapshot<MagpieStatusline>> {
90
96
  if (!valid() || options.signal?.aborted) return {};
91
- const state = session(id);
92
- if (state.task?.controller.signal.aborted) state.task = undefined;
93
- if (state.task) return wait(state.task, options.signal);
94
- if (options.automatic && (statusBlocked ||
95
- (state.attemptedAt !== undefined && now() - state.attemptedAt < TTL))) return state.snapshot;
96
- if (!options.force && state.snapshot.fetchedAt !== undefined && now() - state.snapshot.fetchedAt < TTL)
97
- return state.snapshot;
98
- const task = start(state, request, `statusline?format=json&session=${encodeURIComponent(id)}`, parseStatusline, "GET");
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");
99
105
  const result = await wait(task, options.signal);
100
- statusBlocked = state.blocked === true;
106
+ state.statusBlocked = statusState.blocked === true;
101
107
  if (result.status === 401 || result.status === 403)
102
108
  for (const other of sessions.values()) other.snapshot = { error: result.error, status: result.status };
103
109
  return result;
104
110
  },
105
111
  readCards(request: MagpieRequest, options: { force?: boolean; automatic?: boolean; signal?: AbortSignal } = {}): Promise<MagpieSnapshot<MagpieCard[]>> {
106
112
  if (!valid() || options.signal?.aborted) return Promise.resolve({});
107
- if (refresh?.task.controller.signal.aborted) refresh = undefined;
113
+ if (state.refresh?.task.controller.signal.aborted) state.refresh = undefined;
108
114
  if (cards.task?.controller.signal.aborted) cards.task = undefined;
109
- if (refresh) return wait(refresh.task, options.signal);
115
+ if (state.refresh) return wait(state.refresh.task, options.signal);
110
116
  if (cards.task) return wait(cards.task, options.signal);
111
117
  if (options.automatic && (cards.blocked ||
112
118
  (cards.attemptedAt !== undefined && now() - cards.attemptedAt < TTL))) return Promise.resolve(cards.snapshot);
113
119
  if (!options.force && cards.snapshot.fetchedAt !== undefined && now() - cards.snapshot.fetchedAt < TTL)
114
120
  return Promise.resolve(cards.snapshot);
115
- const revision = cardsRevision;
116
- return wait(start(cards, request, "quotas/cards", parseCards, "GET", () => revision === cardsRevision), options.signal);
121
+ const revision = state.cardsRevision;
122
+ return wait(start(cards, request, "quotas/cards", parseCards, "GET", () => revision === state.cardsRevision), options.signal);
117
123
  },
118
124
  refreshCards(request: MagpieRequest, target?: RefreshTarget, signal?: AbortSignal): Promise<MagpieSnapshot<MagpieCard[]>> {
119
125
  if (!valid() || signal?.aborted) return Promise.resolve({});
120
- if (refresh?.task.controller.signal.aborted) refresh = undefined;
121
- if (refresh) {
122
- const current = refresh.target;
126
+ if (state.refresh?.task.controller.signal.aborted) state.refresh = undefined;
127
+ if (state.refresh) {
128
+ const current = state.refresh.target;
123
129
  if (!current || (target && current.provider === target.provider &&
124
- (!current.user || current.user.toLowerCase() === target.user?.toLowerCase()))) return wait(refresh.task, signal);
130
+ (!current.user || current.user.toLowerCase() === target.user?.toLowerCase()))) return wait(state.refresh.task, signal);
125
131
  return Promise.resolve({ ...cards.snapshot, error: "另一范围的额度刷新正在进行,请完成后再操作。" });
126
132
  }
127
- cardsRevision++;
133
+ state.cardsRevision++;
128
134
  const query = new URLSearchParams();
129
135
  if (target) {
130
136
  query.set("provider", target.provider);
131
137
  if (target.user) query.set("user", target.user);
132
138
  }
133
139
  const task = start(cards, request, `quotas/refresh${query.size ? `?${query}` : ""}`, parseCards, "POST");
134
- refresh = { target, task };
135
- void task.promise.finally(() => { if (refresh?.task === task) refresh = undefined; });
140
+ state.refresh = { target, task };
141
+ void task.promise.finally(() => { if (state.refresh?.task === task) state.refresh = undefined; });
136
142
  return wait(task, signal);
137
143
  },
138
144
  };
@@ -161,11 +167,15 @@ function wait<T>(task: Task<T>, signal?: AbortSignal): Promise<MagpieSnapshot<T>
161
167
 
162
168
  export type MagpieService = ReturnType<typeof createMagpieService>;
163
169
  const SHARED = Symbol.for("pi-tsgw:magpie-state");
164
- /** 用目录服务对象本身作为作用域,沿用其跨工厂和凭据切换失效语义。 */
170
+ const instances = new WeakMap<object, MagpieService>();
171
+ /** 稳定目录状态关联额度数据;服务包装与解析方法使用当前模块的代码。 */
165
172
  export function getMagpieService(catalog: GatewayCatalogService): MagpieService {
166
- const globals = globalThis as typeof globalThis & { [SHARED]?: WeakMap<GatewayCatalogService, MagpieService> };
167
- const services = globals[SHARED] ??= new WeakMap();
168
- let service = services.get(catalog);
169
- if (!service) services.set(catalog, service = createMagpieService(catalog));
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));
170
180
  return service;
171
181
  }
@@ -1,57 +1,32 @@
1
1
  import type { MagpieCard, MagpieWindow } from "./data.ts";
2
2
  import { groupCards } from "./view.ts";
3
3
 
4
- const SHORT_NAMES: Readonly<Record<string, string>> = {
5
- "OpenAI / Codex": "OpenAI",
6
- "Anthropic / Claude": "Claude",
7
- "Moonshot / Kimi": "Kimi",
8
- };
9
-
10
4
  interface Reading {
11
5
  percent?: number;
12
- balances: string[];
13
6
  stale: boolean;
14
7
  }
15
8
 
16
- /** 同账户取瓶颈窗口,同厂商取已知账户最大值;金额只展示,不相加或折算。 */
17
- export function quotaSummary(cards: readonly MagpieCard[]): string {
18
- const groups = groupCards(cards);
19
- if (!groups.length) return "剩余:?";
20
- return `剩余:${groups.map(group => {
21
- const readings = group.cards.filter(card => !card.held && !card.needsAccessKey).map(cardReading);
22
- const known = readings.filter(reading => reading.percent !== undefined || reading.balances.length);
23
- // 当前读数优先,避免一个失败账户的旧高值盖过正常账户的新低值。
24
- const fresh = known.filter(reading => !reading.stale);
25
- const usable = fresh.length ? fresh : known;
26
- const percentages = usable.flatMap(reading => reading.percent === undefined ? [] : [reading.percent]);
27
- const parts: string[] = [];
28
- if (percentages.length) {
29
- const best = Math.max(...percentages);
30
- parts.push(best === Infinity ? "∞" : `${Math.round(best * 100) / 100}%`);
31
- } else parts.push(...new Set(usable.flatMap(reading => reading.balances)));
32
- if (!parts.length) parts.push("?");
33
- else if (readings.some(reading => reading.percent === undefined && !reading.balances.length)) parts.push("?");
34
- const stale = usable.length && !fresh.length ? "(旧)" : "";
35
- return `${SHORT_NAMES[group.name] ?? group.name} ${parts.join("/")}${stale}`;
36
- }).join(" · ")}`.replace(/[\r\n]+/g, " ");
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 ? "" : "(旧)"}`;
37
21
  }
38
22
 
39
23
  function cardReading(card: MagpieCard): Reading {
40
- const balances: string[] = [];
41
- if (card.balance?.trim()) balances.push(card.balance.trim());
42
24
  // 独立图片通道与额外消费行不是账户的共同额度限制。
43
25
  const windows = (card.windows ?? []).filter(window => !window.lane && !window.extra && !window.text);
44
- const percentages: number[] = [];
45
- let unknown = false;
46
- for (const window of windows) {
47
- if (window.balance !== undefined) balances.push(`${window.balance}${window.unit ? ` ${window.unit}` : ""}`);
48
- const percent = windowRemaining(window);
49
- if (percent !== undefined) percentages.push(percent);
50
- else if (window.balance === undefined) unknown = true;
51
- }
26
+ const percentages = windows.map(windowRemaining);
52
27
  return {
53
- percent: !unknown && percentages.length ? Math.min(...percentages) : undefined,
54
- balances,
28
+ percent: percentages.length && percentages.every(percent => percent !== undefined)
29
+ ? Math.min(...percentages) : undefined,
55
30
  stale: Boolean(card.error?.trim() || card.asOf?.trim()),
56
31
  };
57
32
  }
@@ -112,7 +112,7 @@ function round2(value: number): number {
112
112
  return Math.round(value * 100) / 100;
113
113
  }
114
114
 
115
- // 输入已由 data.ts 校验,这里只按语义判断(文本行、无总量钱包、有效百分比),不重复校验类型。
115
+ // 输入已经在 data.ts 入口完成类型降级;这里只按语义判断(文本行、无总量钱包、有效百分比),不重复校验类型。
116
116
  function windowLine(window: MagpieWindow): string {
117
117
  const name = nonEmpty(window.name) ?? "未命名窗口";
118
118
  const details: string[] = [];
@@ -131,6 +131,7 @@ function windowLine(window: MagpieWindow): string {
131
131
  details.push(display ? "文本行(used 不是占比)" : "文本读数未知(used 不是占比)");
132
132
  } else if (!unlimited) {
133
133
  // 钱包窗口没有总量时,used=0 不代表未使用,只有 amount/limit 才构成占比。
134
+ let remainingShown = false;
134
135
  const percentReadable = used !== undefined && used >= 0 && used <= 100 && (wallet === undefined || limit !== undefined);
135
136
  if (used !== undefined && percentReadable) {
136
137
  details.push(`已用 ${used}%`);
@@ -138,10 +139,21 @@ function windowLine(window: MagpieWindow): string {
138
139
  details.push(`剩余 ${remaining}%`);
139
140
  } else if (used !== undefined && (used < 0 || used > 100)) {
140
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
+ }
141
149
  }
142
150
  if (wallet !== undefined) details.push(`钱包余额 ${withUnit(wallet, unit)}`);
143
- if (limit !== undefined) details.push(`计量 ${withUnit(window.amount ?? 0, unit)} / ${withUnit(limit, unit)}`);
144
- if (!display && wallet === undefined && limit === undefined && used === undefined) details.push("读数未知");
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("读数未知");
145
157
  }
146
158
  if (window.resetsAt) details.push(`重置 ${window.resetsAt}`);
147
159
  if (window.runsOut !== undefined || window.runsOutAt) {
@@ -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++;
@@ -1,5 +1,6 @@
1
1
  import { resolve } from "node:path";
2
2
  import { createGatewayCatalogRecovery } from "./gateway-catalog-recovery.ts";
3
+ import { getGatewayCatalogRegistry, type GatewayCatalogState, type CatalogFetchTask as FetchTask } from "./gateway-catalog-shared.ts";
3
4
  import {
4
5
  DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS,
5
6
  gatewayModelCacheScope,
@@ -21,15 +22,6 @@ export interface GatewayCatalogOutcome {
21
22
  failed: boolean;
22
23
  }
23
24
 
24
- interface FetchTask {
25
- controller: AbortController;
26
- force: boolean;
27
- networkStarted: boolean;
28
- cacheSelected: boolean;
29
- waiters: number;
30
- promise: Promise<GatewayCatalogOutcome>;
31
- }
32
-
33
25
  export function catalogCancelledError(): Error {
34
26
  const error = new Error("TSGW 模型目录获取已取消。");
35
27
  error.name = "AbortError";
@@ -71,70 +63,69 @@ function waitForTask(task: FetchTask, signal: AbortSignal | undefined, valid: ()
71
63
  });
72
64
  }
73
65
 
74
- /** 原始目录的共享服务,不保存 UI、过滤配置、宿主 context 或常驻明文密钥。 */
75
- function createService(root: string, scope: string, cacheFilePath: string) {
76
- let valid = true;
77
- let snapshot: GatewayCatalogSnapshot | undefined;
78
- let task: FetchTask | undefined;
79
- const listeners = new Set<() => void>();
80
- const changed = () => { for (const listener of listeners) listener(); };
81
- const recovery = createGatewayCatalogRecovery({ onIdle: () => {
82
- if (task?.waiters === 0 && !task.cacheSelected) task.controller.abort();
66
+ /** 当前模块的方法包装共享状态,不保存 UI、过滤配置、宿主 context 或常驻明文密钥。 */
67
+ function createService(root: string, cacheFilePath: string, state: GatewayCatalogState) {
68
+ const { scope } = state;
69
+ const changed = () => { for (const listener of state.listeners) listener(); };
70
+ const recovery = createGatewayCatalogRecovery({ state: state.recovery, onIdle: () => {
71
+ if (state.task?.waiters === 0 && !state.task.cacheSelected) state.task.controller.abort();
83
72
  } });
84
73
 
85
74
  const check = (key: string): void => {
86
- if (!valid || gatewayModelCacheScope(root, key) !== scope) throw catalogCancelledError();
75
+ if (!state.valid || gatewayModelCacheScope(root, key) !== scope) throw catalogCancelledError();
87
76
  };
88
77
  const read = (key: string): GatewayCatalogSnapshot | undefined => {
89
78
  check(key);
90
79
  const local = getCachedGatewayModelIds(root, key, { cacheFilePath });
91
- if (local && (!snapshot || local.storedAt > snapshot.storedAt)) {
92
- snapshot = { ids: [...local.ids], storedAt: local.storedAt, source: "cache",
80
+ if (local && (!state.snapshot || local.storedAt > state.snapshot.storedAt)) {
81
+ state.snapshot = { ids: [...local.ids], storedAt: local.storedAt, source: "cache",
93
82
  ...(local.magpie ? { magpie: local.magpie } : {}) };
94
83
  changed();
95
84
  }
96
- return snapshot ? copy(snapshot) : undefined;
85
+ return state.snapshot ? copy(state.snapshot) : undefined;
97
86
  };
98
87
  const currentOutcome = (networkAttempted: boolean, networkSucceeded: boolean,
99
88
  failed = false, retryable = true): GatewayCatalogOutcome => ({
100
- ...(snapshot ? { snapshot: copy(snapshot) } : {}),
89
+ ...(state.snapshot ? { snapshot: copy(state.snapshot) } : {}),
101
90
  networkAttempted, networkSucceeded, failed, retryable,
102
91
  });
103
92
 
104
93
  const api = {
105
94
  scope,
95
+ /** 方法包装可更新,额度共享始终关联这一份稳定状态。 */
96
+ identity: state as object,
106
97
  subscribe(listener: () => void): () => void {
107
- listeners.add(listener);
108
- return () => { listeners.delete(listener); };
98
+ state.listeners.add(listener);
99
+ return () => { state.listeners.delete(listener); };
109
100
  },
110
- valid: () => valid,
111
- isMagpie: () => valid && snapshot?.magpie === true,
101
+ valid: () => state.valid,
102
+ isMagpie: () => state.valid && state.snapshot?.magpie === true,
112
103
  read,
113
- fetching: () => !!task?.networkStarted && !task.controller.signal.aborted,
114
- refreshKind: () => task && !task.controller.signal.aborted ? (task.force ? "force" : "normal") : undefined,
115
- summary(minimumStoredAt = 0, applied = snapshot) {
116
- if (!valid || !applied) return undefined;
104
+ fetching: () => !!state.task?.networkStarted && !state.task.controller.signal.aborted,
105
+ refreshKind: () => state.task && !state.task.controller.signal.aborted ? (state.task.force ? "force" : "normal") : undefined,
106
+ summary(minimumStoredAt = 0, applied = state.snapshot) {
107
+ if (!state.valid || !applied) return undefined;
117
108
  const result = readGatewayModelCacheSummary(cacheFilePath, minimumStoredAt, scope, applied.ids);
118
109
  return result?.storedAt === applied.storedAt ? result : undefined;
119
110
  },
120
111
  invalidate() {
121
- valid = false;
112
+ state.valid = false;
122
113
  recovery.stop();
123
- task?.controller.abort();
124
- task = undefined;
125
- snapshot = undefined;
114
+ state.task?.controller.abort();
115
+ state.task = undefined;
116
+ state.snapshot = undefined;
126
117
  changed();
127
- listeners.clear();
118
+ state.listeners.clear();
128
119
  },
129
120
  /** 后台通过仍活跃实例的宿主服务发起单次获取,联网许可和凭据仍交宿主。 */
130
121
  recoverUsing(run: (signal: AbortSignal) => Promise<GatewayCatalogOutcome>, signal?: AbortSignal): Promise<GatewayCatalogOutcome> {
131
- if (!valid) return Promise.reject(catalogCancelledError());
122
+ if (!state.valid) return Promise.reject(catalogCancelledError());
132
123
  return recovery.join(run, () => currentOutcome(false, false, true), signal).then(outcome => {
133
- if (!valid || signal?.aborted) throw catalogCancelledError();
124
+ if (!state.valid || signal?.aborted) throw catalogCancelledError();
134
125
  return outcome;
135
126
  });
136
127
  },
137
- peek: () => snapshot ? copy(snapshot) : undefined,
128
+ peek: () => state.snapshot ? copy(state.snapshot) : undefined,
138
129
  recover(key: string, signal?: AbortSignal): Promise<GatewayCatalogOutcome> {
139
130
  try { check(key); } catch (error) { return Promise.reject(error); }
140
131
  return recovery.join(
@@ -150,19 +141,19 @@ function createService(root: string, scope: string, cacheFilePath: string) {
150
141
  read(key);
151
142
  return Promise.resolve(currentOutcome(false, false));
152
143
  }
153
- if (task?.controller.signal.aborted) task = undefined;
154
- if (task?.cacheSelected && options.force) {
144
+ if (state.task?.controller.signal.aborted) state.task = undefined;
145
+ if (state.task?.cacheSelected && options.force) {
155
146
  // 缓存决定已经完成;这次 force 不能被旧缓存结果吞掉。
156
- return task.promise.then(() => api.request(key, options));
147
+ return state.task.promise.then(() => api.request(key, options));
157
148
  }
158
- if (task) {
159
- task.force ||= options.force === true;
160
- return waitForTask(task, options.signal, () => valid, recovery.hasParticipants);
149
+ if (state.task) {
150
+ state.task.force ||= options.force === true;
151
+ return waitForTask(state.task, options.signal, () => state.valid, recovery.hasParticipants);
161
152
  }
162
153
  const controller = new AbortController();
163
154
  const active: FetchTask = { controller, force: options.force === true,
164
155
  networkStarted: false, cacheSelected: false, waiters: 0, promise: Promise.resolve(currentOutcome(false, false)) };
165
- task = active;
156
+ state.task = active;
166
157
  // 微任务内才决定缓存/网络,使同批 force 能提升尚未决策的 normal。
167
158
  const execute = Promise.resolve().then(async () => {
168
159
  controller.signal.throwIfAborted();
@@ -175,14 +166,14 @@ function createService(root: string, scope: string, cacheFilePath: string) {
175
166
  const result = await getGatewayModelIds(root, key, {
176
167
  cacheFilePath, force: true, signal: controller.signal,
177
168
  });
178
- if (!valid || task !== active || controller.signal.aborted) throw catalogCancelledError();
169
+ if (!state.valid || state.task !== active || controller.signal.aborted) throw catalogCancelledError();
179
170
  if (!result.ok || result.stale) {
180
171
  read(key);
181
172
  const code = result.ok ? result.fallbackStatus : result.status;
182
173
  return currentOutcome(true, false, true, code !== 401 && code !== 403);
183
174
  }
184
- if (!snapshot || result.storedAt >= snapshot.storedAt) {
185
- snapshot = { ids: [...result.ids], storedAt: result.storedAt, source: result.cached ? "cache" : "network",
175
+ if (!state.snapshot || result.storedAt >= state.snapshot.storedAt) {
176
+ state.snapshot = { ids: [...result.ids], storedAt: result.storedAt, source: result.cached ? "cache" : "network",
186
177
  ...(result.magpie ? { magpie: result.magpie } : {}) };
187
178
  changed();
188
179
  }
@@ -196,9 +187,9 @@ function createService(root: string, scope: string, cacheFilePath: string) {
196
187
  });
197
188
  active.promise = Promise.race([execute, aborted]).finally(() => {
198
189
  if (onAbort) controller.signal.removeEventListener("abort", onAbort);
199
- if (task === active) task = undefined;
190
+ if (state.task === active) state.task = undefined;
200
191
  });
201
- return waitForTask(active, options.signal, () => valid, recovery.hasParticipants);
192
+ return waitForTask(active, options.signal, () => state.valid, recovery.hasParticipants);
202
193
  },
203
194
  };
204
195
  return api;
@@ -206,27 +197,24 @@ function createService(root: string, scope: string, cacheFilePath: string) {
206
197
 
207
198
  export type GatewayCatalogService = ReturnType<typeof createService>;
208
199
 
209
- interface ServiceRegistry {
210
- version: 6;
211
- /** 每个 agent-dir 的唯一缓存路径一个当前槽,不按密钥维护多个目录。 */
212
- slots: Map<string, GatewayCatalogService>;
213
- }
200
+ const services = new WeakMap<GatewayCatalogState, GatewayCatalogService>();
214
201
 
215
- const REGISTRY = Symbol.for("pi-tsgw:gateway-catalog");
216
-
217
- /** 跨工厂调用与 jiti 重导入复用;不同 agent-dir 仅作宿主存储边界隔离。 */
202
+ /** 当前模块复用自己的方法包装;跨重导入共用稳定状态与实际 GET。 */
218
203
  export function getGatewayCatalogService(root: string, key: string, cacheFilePath: string): GatewayCatalogService {
219
- const globals = globalThis as typeof globalThis & { [REGISTRY]?: ServiceRegistry };
220
- let registry = globals[REGISTRY];
221
- if (registry && registry.version !== 6) throw new Error("TSGW 目录共享状态版本不兼容,请重启宿主。");
222
- registry ??= globals[REGISTRY] = { version: 6, slots: new Map() };
204
+ const registry = getGatewayCatalogRegistry();
223
205
  const path = resolve(cacheFilePath);
224
206
  const scope = gatewayModelCacheScope(root, key);
225
- let service = registry.slots.get(path);
226
- if (!service || service.scope !== scope || !service.valid()) {
227
- service?.invalidate();
228
- service = createService(root, scope, path);
229
- registry.slots.set(path, service);
207
+ let state = registry.slots.get(path);
208
+ if (!state || state.scope !== scope || !state.valid) {
209
+ if (state) {
210
+ let previous = services.get(state);
211
+ previous ??= createService(root, path, state);
212
+ previous.invalidate();
213
+ }
214
+ state = { scope, valid: true, listeners: new Set(), recovery: {} };
215
+ registry.slots.set(path, state);
230
216
  }
217
+ let service = services.get(state);
218
+ if (!service) services.set(state, service = createService(root, path, state));
231
219
  return service;
232
220
  }
@@ -0,0 +1,56 @@
1
+ import type { FetchGatewayModelIdsResult, ModelCacheEntry } from "./gateway-catalog.ts";
2
+ import type { GatewayCatalogOutcome, GatewayCatalogSnapshot } from "./gateway-catalog-service.ts";
3
+ import type { GatewayCatalogRecoveryState } from "./gateway-catalog-recovery.ts";
4
+
5
+ export interface CatalogFetchTask {
6
+ controller: AbortController;
7
+ force: boolean;
8
+ networkStarted: boolean;
9
+ cacheSelected: boolean;
10
+ waiters: number;
11
+ promise: Promise<GatewayCatalogOutcome>;
12
+ }
13
+
14
+ export interface GatewayCatalogState {
15
+ scope: string;
16
+ valid: boolean;
17
+ snapshot?: GatewayCatalogSnapshot;
18
+ task?: CatalogFetchTask;
19
+ listeners: Set<() => void>;
20
+ recovery: GatewayCatalogRecoveryState;
21
+ }
22
+
23
+ interface CacheRequest {
24
+ promise: Promise<FetchGatewayModelIdsResult>;
25
+ revision: number;
26
+ storedAt: number;
27
+ }
28
+
29
+ interface GatewayCatalogRegistry {
30
+ /** 目录与额度共用的核心契约标记;仅不兼容变更时改变,执行方法与可选字段不参与。 */
31
+ schema: 1;
32
+ /** 每条规范化缓存路径只持有一个当前网关身份;会话退出不清空其他实例的数据。 */
33
+ slots: Map<string, GatewayCatalogState>;
34
+ cache: {
35
+ entries: Map<string, ModelCacheEntry>;
36
+ inFlight: Map<string, CacheRequest>;
37
+ latest: Map<string, number>;
38
+ latestDisk: Map<string, number>;
39
+ revision: number;
40
+ };
41
+ }
42
+
43
+ const REGISTRY = Symbol.for("pi-tsgw:gateway-catalog");
44
+
45
+ /** 跨重导入只保留数据与在途协调记录,服务方法由当前模块创建。 */
46
+ export function getGatewayCatalogRegistry(): GatewayCatalogRegistry {
47
+ const globals = globalThis as typeof globalThis & { [REGISTRY]?: GatewayCatalogRegistry };
48
+ const existing = globals[REGISTRY];
49
+ if (existing && existing.schema !== 1)
50
+ throw new Error("TSGW 共享数据契约不兼容,请重启宿主以统一状态。");
51
+ return globals[REGISTRY] ??= {
52
+ schema: 1,
53
+ slots: new Map(),
54
+ cache: { entries: new Map(), inFlight: new Map(), latest: new Map(), latestDisk: new Map(), revision: 0 },
55
+ };
56
+ }
@@ -8,6 +8,7 @@ import {
8
8
  } from "node:fs";
9
9
  import { dirname, resolve } from "node:path";
10
10
  import { parseGatewayModelList } from "./gateway-model-list.ts";
11
+ import { getGatewayCatalogRegistry } from "./gateway-catalog-shared.ts";
11
12
 
12
13
  export const DEFAULT_GATEWAY_MODEL_TIMEOUT_MS = 5_000;
13
14
  export const DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS = 24 * 60 * 60 * 1_000;
@@ -48,6 +49,7 @@ export type FetchGatewayModelIdsResult =
48
49
  detail?: string;
49
50
  };
50
51
 
52
+ /** 网关仅提供可选模型 ID;规格与使用策略由本地目录定义,其余字段只辅助缓存和附加能力。 */
51
53
  export interface ModelCacheEntry {
52
54
  ids: string[];
53
55
  storedAt: number;
@@ -301,29 +303,12 @@ export function loadGatewayModelCache(
301
303
  };
302
304
  }
303
305
 
304
- const gatewayCaches = new Map<string, ModelCache>();
305
- interface PendingRequest {
306
- promise: Promise<FetchGatewayModelIdsResult>;
307
- revision: number;
308
- storedAt: number;
309
- }
310
- const inFlightRequests = new Map<string, PendingRequest>();
311
- const latestRequests = new Map<string, number>();
312
- // 每个规范化路径仅有一个磁盘缓存槽,与内存缓存作用域相互独立。
313
- const latestDiskRequests = new Map<string, number>();
314
- let revision = 0;
315
-
316
306
  function memoryCacheKey(scope: string, filePath?: string): string {
317
307
  return filePath ? `${scope}\0${resolve(filePath)}` : scope;
318
308
  }
319
309
 
320
- function cacheFor(key: string): ModelCache {
321
- let cache = gatewayCaches.get(key);
322
- if (!cache) {
323
- cache = createModelCache();
324
- gatewayCaches.set(key, cache);
325
- }
326
- return cache;
310
+ function storeMemoryCache(key: string, entry: ModelCacheEntry): void {
311
+ getGatewayCatalogRegistry().cache.entries.set(key, { ...entry, ids: [...entry.ids] });
327
312
  }
328
313
 
329
314
  function selectLatestGatewayModelCacheEntry(
@@ -332,7 +317,7 @@ function selectLatestGatewayModelCacheEntry(
332
317
  ttlMs: number,
333
318
  now: number,
334
319
  ): { entry: ModelCacheEntry; fresh: boolean } | undefined {
335
- const memory = gatewayCaches.get(memoryCacheKey(key, cacheFilePath))?.get();
320
+ const memory = getGatewayCatalogRegistry().cache.entries.get(memoryCacheKey(key, cacheFilePath));
336
321
  const disk = cacheFilePath
337
322
  ? readGatewayModelCacheEntry(cacheFilePath, key)
338
323
  : undefined;
@@ -355,7 +340,7 @@ export function getCachedGatewayModelIds(
355
340
  ): CachedGatewayModelIds | undefined {
356
341
  const key = gatewayModelCacheScope(baseUrl, apiKey);
357
342
  const cacheKey = memoryCacheKey(key, opts.cacheFilePath);
358
- const memory = gatewayCaches.get(cacheKey)?.get();
343
+ const memory = getGatewayCatalogRegistry().cache.entries.get(cacheKey);
359
344
  const selected = selectLatestGatewayModelCacheEntry(
360
345
  key,
361
346
  opts.cacheFilePath,
@@ -366,7 +351,7 @@ export function getCachedGatewayModelIds(
366
351
  // 选中更新的磁盘快照时同步共享内存,避免磁盘随后损坏或删除时回退旧内存。
367
352
  // 仅预热内存,不写磁盘,也不改变原始获取时间。
368
353
  if (!memory || selected.entry.storedAt > memory.storedAt)
369
- cacheFor(cacheKey).set(selected.entry.ids, selected.entry.storedAt, selected.entry.magpie);
354
+ storeMemoryCache(cacheKey, selected.entry);
370
355
  return {
371
356
  ...selected.entry,
372
357
  ids: [...selected.entry.ids],
@@ -391,12 +376,12 @@ export async function getGatewayModelIds(
391
376
  const key = gatewayModelCacheScope(baseUrl, apiKey);
392
377
  const ttlMs = checkedTtl(opts.ttlMs);
393
378
  const cacheKey = memoryCacheKey(key, opts.cacheFilePath);
394
- const cache = cacheFor(cacheKey);
379
+ const cache = getGatewayCatalogRegistry().cache;
395
380
  const local = selectLatestGatewayModelCacheEntry(
396
381
  key, opts.cacheFilePath, ttlMs, now,
397
382
  );
398
383
  if (!opts.force && local?.fresh) {
399
- cache.set(local.entry.ids, local.entry.storedAt, local.entry.magpie);
384
+ storeMemoryCache(cacheKey, local.entry);
400
385
  return {
401
386
  ...local.entry,
402
387
  ok: true,
@@ -412,25 +397,25 @@ export async function getGatewayModelIds(
412
397
  // Pi 可能已替换该次刷新。只有不带信号的调用共享进行中的请求;
413
398
  // 可取消的调用独立发起获取请求。
414
399
  const shareRequest = opts.signal === undefined;
415
- let request = shareRequest ? inFlightRequests.get(requestKey) : undefined;
400
+ let request = shareRequest ? cache.inFlight.get(requestKey) : undefined;
416
401
  if (!request) {
417
- const requestRevision = ++revision;
402
+ const requestRevision = ++cache.revision;
418
403
  request = {
419
404
  revision: requestRevision,
420
405
  storedAt: now,
421
406
  promise: fetchGatewayModelIds(baseUrl, apiKey, opts),
422
407
  };
423
- if (shareRequest) inFlightRequests.set(requestKey, request);
408
+ if (shareRequest) cache.inFlight.set(requestKey, request);
424
409
  }
425
410
 
426
411
  // 请求可跨路径复用,但内存写入屏障按各自路径独立登记。
427
- latestRequests.set(cacheKey, Math.max(latestRequests.get(cacheKey) ?? 0, request.revision));
412
+ cache.latest.set(cacheKey, Math.max(cache.latest.get(cacheKey) ?? 0, request.revision));
428
413
  const diskPath = opts.cacheFilePath ? resolve(opts.cacheFilePath) : undefined;
429
414
  if (diskPath) {
430
415
  // 登记每个订阅者的路径,包括目标路径不同的共享请求。
431
416
  // 加入较旧请求时,不得回退较新的版本屏障。
432
- latestDiskRequests.set(diskPath, Math.max(
433
- latestDiskRequests.get(diskPath) ?? 0, request.revision,
417
+ cache.latestDisk.set(diskPath, Math.max(
418
+ cache.latestDisk.get(diskPath) ?? 0, request.revision,
434
419
  ));
435
420
  }
436
421
 
@@ -438,8 +423,8 @@ export async function getGatewayModelIds(
438
423
  try {
439
424
  fetched = await request.promise;
440
425
  } finally {
441
- if (shareRequest && inFlightRequests.get(requestKey) === request)
442
- inFlightRequests.delete(requestKey);
426
+ if (shareRequest && cache.inFlight.get(requestKey) === request)
427
+ cache.inFlight.delete(requestKey);
443
428
  }
444
429
 
445
430
  // 取消后绝不回退或写入,即使获取器忽略了取消信号。
@@ -447,9 +432,9 @@ export async function getGatewayModelIds(
447
432
  if (fetched.ok) {
448
433
  // 以后启动的请求为准,即使较新的请求失败或取消。
449
434
  // 被取代的成功请求仍向调用者返回结果,但不写入缓存。
450
- if (latestRequests.get(cacheKey) === request.revision) {
451
- cache.set(fetched.ids, request.storedAt, fetched.magpie);
452
- if (diskPath && latestDiskRequests.get(diskPath) === request.revision)
435
+ if (cache.latest.get(cacheKey) === request.revision) {
436
+ storeMemoryCache(cacheKey, { ids: fetched.ids, storedAt: request.storedAt, ...(fetched.magpie ? { magpie: fetched.magpie } : {}) });
437
+ if (diskPath && cache.latestDisk.get(diskPath) === request.revision)
453
438
  saveGatewayModelCache(diskPath, key, fetched.ids, request.storedAt, fetched.magpie);
454
439
  }
455
440
  return {
@@ -1,6 +1,7 @@
1
1
  import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
2
2
  import { effectiveModelsForGateway, type ModelFilter } from "#tsgw/models/catalog";
3
3
  import { DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS } from "#tsgw/models/gateway-catalog";
4
+ import { getGatewayCatalogRegistry } from "#tsgw/models/gateway-catalog-shared";
4
5
  import {
5
6
  catalogCancelledError,
6
7
  getGatewayCatalogService,
@@ -39,6 +40,8 @@ export function createCatalogState(options: {
39
40
  initialKey?: string;
40
41
  onChange(): void;
41
42
  }) {
43
+ // 破坏性契约变更在加载入口明确提示,避免无初始凭据时被后续刷新错误吞掉。
44
+ getGatewayCatalogRegistry();
42
45
  const { root, filter, cacheFilePath, imagesEnabled, classifiersEnabled } = options;
43
46
  let models = effectiveModelsForGateway(root, filter, undefined, imagesEnabled, classifiersEnabled);
44
47
  let status: CatalogStatus = { count: models.length, source: "empty", loading: false };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tsgw",
3
- "version": "3.5.0",
3
+ "version": "3.5.1",
4
4
  "description": "面向 TOSSP AIH gateway 的 Pi 扩展:按厂商维护聊天与图片模型目录及思考策略,支持四种聊天协议、图片生成与编辑工具,以及原生 System One 分类模型。",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -28,7 +28,7 @@
28
28
  ]
29
29
  },
30
30
  "scripts": {
31
- "test": "tsc -p tsconfig.test.json && node scripts/prepare-test-runtime.mjs && node dist/extensions/provider/index.test.js && node dist/extensions/provider/tracing.test.js && node dist/extensions/provider/tracing-host.test.js && node dist/extensions/provider/startup-catalog.test.js && node dist/extensions/provider/catalog-state.test.js && node --test dist/extensions/magpie/data.test.js dist/extensions/magpie/view.test.js dist/extensions/magpie/summary.test.js dist/extensions/magpie/service.test.js dist/extensions/magpie/controller.test.js && node dist/extensions/magpie/host.test.js && node dist/extensions/models/gateway-catalog-service.test.js && node dist/extensions/models/gateway-catalog-recovery.test.js && node dist/extensions/provider/catalog-coordinator.test.js && node dist/extensions/provider/catalog-coordination.test.js && node dist/extensions/provider/catalog-recovery.test.js && node dist/extensions/provider/catalog-host.test.js && node dist/extensions/provider/catalog-preemption-host.test.js && node dist/extensions/provider/classifier-host.test.js && node dist/extensions/delegation/policy.test.js && node dist/extensions/delegation/index.test.js && node dist/extensions/delegation/failure.test.js && node dist/extensions/delegation/parallel.test.js && node dist/extensions/delegation/parallel-host.test.js && node dist/extensions/delegation/host-integration.test.js && node dist/extensions/agents/install.test.js && node dist/extensions/agents/host-integration.test.js && node dist/extensions/prompts.test.js && node dist/extensions/provider/status.test.js && node dist/extensions/search/index.test.js && node dist/extensions/search/proxy.test.js && node dist/extensions/search/host-integration.test.js && node dist/extensions/provider/status-integration.test.js && node dist/extensions/provider/catalog-lifecycle.test.js && node dist/extensions/models/gateway-catalog-metadata.test.js && node dist/extensions/models/gateway-catalog-policy.test.js && node dist/extensions/models/operations.test.js && node dist/extensions/models/catalog.test.js && node dist/extensions/models/web-search.test.js && node dist/extensions/models/gateway-catalog.test.js && node dist/extensions/models/gateway-catalog-isolation.test.js && node dist/extensions/models/vendor-strategies.test.js && node dist/extensions/models/minimax-protocol.test.js && node dist/extensions/models/anthropic-threads.test.js && node dist/extensions/models/grok-new.test.js && node dist/extensions/models/openai-terra.test.js && node dist/extensions/models/gemini-new.test.js && node dist/extensions/models/longcat-new.test.js && node dist/extensions/models/capabilities.test.js && node dist/extensions/models/classifier-catalog.test.js && node dist/extensions/models/adapter/classifiers/adapter.test.js && node dist/extensions/models/image-catalog.test.js && node dist/extensions/models/adapter/images/parameters.test.js && node dist/extensions/models/adapter/images/input-budget.test.js && node dist/extensions/models/adapter/images/edit-request.test.js && node dist/extensions/models/adapter/images/image-data.test.js && node dist/extensions/models/adapter/images/response.test.js && node dist/extensions/models/adapter/images/stream-response.test.js && node dist/extensions/models/adapter/images/adapter.test.js && node dist/extensions/images/tool-files.test.js && node dist/extensions/images/tools.test.js && node dist/extensions/images/host-integration.test.js && node dist/extensions/images/tools-host.test.js && node dist/index.test.js && node dist/extensions/skills.test.js && node dist/extensions/skill-resources.test.js && node dist/extensions/upload/protocol.test.js && node dist/extensions/upload/schema.test.js && node dist/extensions/upload/uploader.test.js && node dist/extensions/upload/transport.test.js && node dist/extensions/upload/host-integration.test.js && node dist/extensions/upload/readiness-host.test.js && node dist/extensions/config.test.js && node dist/extensions/email/config.test.js && node dist/extensions/email/cache.test.js && node dist/extensions/email/imap-session.test.js && node dist/extensions/email/query.test.js && node dist/extensions/email/reader.test.js && node dist/extensions/email/body.test.js && node dist/extensions/email/mutations.test.js && node dist/extensions/email/mutations-safety.test.js && node dist/extensions/email/smtp.test.js && node dist/extensions/email/schema.test.js && node dist/extensions/email/tools.test.js && node dist/extensions/email/host-integration.test.js && node dist/extensions/email/file-access.test.js && node dist/extensions/email/reader-integrity.test.js && node dist/extensions/dav/config.test.js && node dist/extensions/dav/client.test.js && node dist/extensions/dav/write-transport.test.js && node dist/extensions/dav/calendar.test.js && node dist/extensions/dav/calendar-read-integrity.test.js && node dist/extensions/dav/calendar-write.test.js && node dist/extensions/dav/calendar-write-validation.test.js && node dist/extensions/dav/contacts.test.js && node dist/extensions/dav/contact-actions.test.js && node dist/extensions/dav/contact-integrity.test.js && node dist/extensions/dav/tools.test.js && node dist/extensions/dav/host-integration.test.js",
31
+ "test": "tsc -p tsconfig.test.json && node scripts/prepare-test-runtime.mjs && node dist/extensions/provider/index.test.js && node dist/extensions/provider/tracing.test.js && node dist/extensions/provider/tracing-host.test.js && node dist/extensions/provider/startup-catalog.test.js && node dist/extensions/provider/catalog-state.test.js && node --test dist/extensions/magpie/data.test.js dist/extensions/magpie/view.test.js dist/extensions/magpie/summary.test.js dist/extensions/magpie/service.test.js dist/extensions/magpie/controller.test.js && node dist/extensions/magpie/host.test.js && node dist/extensions/models/gateway-catalog-service.test.js && node dist/extensions/models/gateway-catalog-reload.test.js && node dist/extensions/models/gateway-catalog-recovery.test.js && node dist/extensions/provider/catalog-coordinator.test.js && node dist/extensions/provider/catalog-coordination.test.js && node dist/extensions/provider/catalog-recovery.test.js && node dist/extensions/provider/catalog-host.test.js && node dist/extensions/provider/catalog-preemption-host.test.js && node dist/extensions/provider/classifier-host.test.js && node dist/extensions/delegation/policy.test.js && node dist/extensions/delegation/index.test.js && node dist/extensions/delegation/failure.test.js && node dist/extensions/delegation/parallel.test.js && node dist/extensions/delegation/parallel-host.test.js && node dist/extensions/delegation/host-integration.test.js && node dist/extensions/agents/install.test.js && node dist/extensions/agents/host-integration.test.js && node dist/extensions/prompts.test.js && node dist/extensions/provider/status.test.js && node dist/extensions/search/index.test.js && node dist/extensions/search/proxy.test.js && node dist/extensions/search/host-integration.test.js && node dist/extensions/provider/status-integration.test.js && node dist/extensions/provider/catalog-lifecycle.test.js && node dist/extensions/models/gateway-catalog-metadata.test.js && node dist/extensions/models/gateway-catalog-policy.test.js && node dist/extensions/models/operations.test.js && node dist/extensions/models/catalog.test.js && node dist/extensions/models/web-search.test.js && node dist/extensions/models/gateway-catalog.test.js && node dist/extensions/models/gateway-catalog-isolation.test.js && node dist/extensions/models/vendor-strategies.test.js && node dist/extensions/models/minimax-protocol.test.js && node dist/extensions/models/anthropic-threads.test.js && node dist/extensions/models/grok-new.test.js && node dist/extensions/models/openai-terra.test.js && node dist/extensions/models/gemini-new.test.js && node dist/extensions/models/longcat-new.test.js && node dist/extensions/models/capabilities.test.js && node dist/extensions/models/classifier-catalog.test.js && node dist/extensions/models/adapter/classifiers/adapter.test.js && node dist/extensions/models/image-catalog.test.js && node dist/extensions/models/adapter/images/parameters.test.js && node dist/extensions/models/adapter/images/input-budget.test.js && node dist/extensions/models/adapter/images/edit-request.test.js && node dist/extensions/models/adapter/images/image-data.test.js && node dist/extensions/models/adapter/images/response.test.js && node dist/extensions/models/adapter/images/stream-response.test.js && node dist/extensions/models/adapter/images/adapter.test.js && node dist/extensions/images/tool-files.test.js && node dist/extensions/images/tools.test.js && node dist/extensions/images/host-integration.test.js && node dist/extensions/images/tools-host.test.js && node dist/index.test.js && node dist/extensions/skills.test.js && node dist/extensions/skill-resources.test.js && node dist/extensions/upload/protocol.test.js && node dist/extensions/upload/schema.test.js && node dist/extensions/upload/uploader.test.js && node dist/extensions/upload/transport.test.js && node dist/extensions/upload/host-integration.test.js && node dist/extensions/upload/readiness-host.test.js && node dist/extensions/config.test.js && node dist/extensions/email/config.test.js && node dist/extensions/email/cache.test.js && node dist/extensions/email/imap-session.test.js && node dist/extensions/email/query.test.js && node dist/extensions/email/reader.test.js && node dist/extensions/email/body.test.js && node dist/extensions/email/mutations.test.js && node dist/extensions/email/mutations-safety.test.js && node dist/extensions/email/smtp.test.js && node dist/extensions/email/schema.test.js && node dist/extensions/email/tools.test.js && node dist/extensions/email/host-integration.test.js && node dist/extensions/email/file-access.test.js && node dist/extensions/email/reader-integrity.test.js && node dist/extensions/dav/config.test.js && node dist/extensions/dav/client.test.js && node dist/extensions/dav/write-transport.test.js && node dist/extensions/dav/calendar.test.js && node dist/extensions/dav/calendar-read-integrity.test.js && node dist/extensions/dav/calendar-write.test.js && node dist/extensions/dav/calendar-write-validation.test.js && node dist/extensions/dav/contacts.test.js && node dist/extensions/dav/contact-actions.test.js && node dist/extensions/dav/contact-integrity.test.js && node dist/extensions/dav/tools.test.js && node dist/extensions/dav/host-integration.test.js",
32
32
  "test:upload:live": "tsc -p tsconfig.test.json && node scripts/prepare-test-runtime.mjs && node dist/extensions/upload/live.test.js"
33
33
  },
34
34
  "peerDependencies": {