pi-tsgw 3.4.0 → 3.5.0

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,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,261 @@
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
+ const percentReadable = used !== undefined && used >= 0 && used <= 100 && (wallet === undefined || limit !== undefined);
135
+ if (used !== undefined && percentReadable) {
136
+ details.push(`已用 ${used}%`);
137
+ const remaining = window.remaining ?? round2(100 - used);
138
+ details.push(`剩余 ${remaining}%`);
139
+ } else if (used !== undefined && (used < 0 || used > 100)) {
140
+ details.push(`used=${used}(超出百分比范围,不是有效读数)`);
141
+ }
142
+ 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("读数未知");
145
+ }
146
+ if (window.resetsAt) details.push(`重置 ${window.resetsAt}`);
147
+ if (window.runsOut !== undefined || window.runsOutAt) {
148
+ const runsOut = window.runsOut !== undefined ? withUnit(window.runsOut, unit) : "数量未知";
149
+ details.push(`到期失效 ${runsOut}${window.runsOutAt ? `(${window.runsOutAt})` : "(时间未知)"}`);
150
+ }
151
+ if (window.spent !== undefined || window.spentSince) {
152
+ const spent = window.spent !== undefined ? withUnit(window.spent, unit) : "数量未知";
153
+ details.push(`本周期已花费 ${spent}${window.spentSince ? `(自 ${window.spentSince})` : ""}`);
154
+ }
155
+ if (window.pool) details.push(`共享池 ${window.pool}`);
156
+ if (window.lane) details.push(`通道 ${window.lane}`);
157
+ if (window.family) details.push(`族 ${window.family}`);
158
+ return `${name}:${details.join(";")}`;
159
+ }
160
+
161
+ function balancePartLine(part: MagpieBalancePart): string {
162
+ const label = nonEmpty(part.label);
163
+ const percent = part.percent !== undefined ? `(${part.percent}%)` : "";
164
+ const error = nonEmpty(part.error) ? `;读取错误:${part.error}` : "";
165
+ const expires = nonEmpty(part.expires) ? `;到期 ${part.expires}` : "";
166
+ return `余额分项:${part.text}${label ? `(${label})` : ""}${percent}${expires}${error}`;
167
+ }
168
+
169
+ function estimateLine(estimate: MagpieEstimate): string {
170
+ const since = nonEmpty(estimate.from) ?? nonEmpty(estimate.at) ?? "未知时间";
171
+ const currency = nonEmpty(estimate.currency);
172
+ const currencyNote = currency ? `(${currency})` : "";
173
+ const left = estimate.left !== null && estimate.left !== undefined ? withUnit(estimate.left, undefined) : undefined;
174
+ return `估算余额(非厂商读数):设定 ${estimate.set},自 ${since} 起已用 ${estimate.spent}${left === undefined ? "" : `,剩余 ${left}`}${currencyNote}`;
175
+ }
176
+
177
+ function renewLabel(renew: string | undefined): string {
178
+ if (renew === "auto") return "自动续期";
179
+ if (renew === "off") return "不续期";
180
+ return "续期状态未知";
181
+ }
182
+
183
+ function resetsLine(resets: MagpieResetCredits): string {
184
+ const parts = [`重置权益:${resets.count} 次`];
185
+ if (resets.until) parts.push(`最近至 ${resets.until}`);
186
+ if (resets.byWindow) {
187
+ const windows: string[] = [];
188
+ if (resets.fiveHour !== undefined) windows.push(`五小时 ${resets.fiveHour}`);
189
+ if (resets.weekly !== undefined) windows.push(`每周 ${resets.weekly}`);
190
+ if (windows.length) parts.push(`按窗口(${windows.join(",")})`);
191
+ }
192
+ if (resets.team) parts.push("团队套餐");
193
+ return parts.join(";");
194
+ }
195
+
196
+ /** 余额、分项、共享余额、估算与重置权益;都按源记录各自展示,不相加。 */
197
+ function fundsLines(card: MagpieCard): string[] {
198
+ const lines: string[] = [];
199
+ if (nonEmpty(card.balance)) lines.push(`余额:${card.balance}(仅此记录,不与同厂商其他卡片相加)`);
200
+ const parts = [...(card.balanceSplit ?? []), ...(card.balanceParts ?? [])];
201
+ if (parts.length) {
202
+ lines.push("余额分项(同一笔余额的拆分,不与余额或其他卡片相加):");
203
+ for (const part of parts) lines.push(balancePartLine(part));
204
+ }
205
+ if (card.sharedBalance) lines.push(`共享余额:与「${card.sharedBalance}」共用,不能按卡片重复相加。`);
206
+ if (card.estimate) lines.push(estimateLine(card.estimate));
207
+ if (card.resets) {
208
+ lines.push(resetsLine(card.resets));
209
+ for (const reset of card.resets.each ?? []) {
210
+ const window = nonEmpty(reset.window);
211
+ lines.push(`权益项:${nonEmpty(reset.until) ?? "无到期时间"}${window ? `(${window})` : ""}`);
212
+ }
213
+ }
214
+ return lines;
215
+ }
216
+
217
+ /** 逐条卡片明细;账户、读数时间、错误、余额与权益都按源记录展示。 */
218
+ export function cardDetails(card: MagpieCard): string[] {
219
+ const lines: string[] = [];
220
+ lines.push(`来源:${sourceOf(card)}`);
221
+ const kind = kindLabel(card.kind);
222
+ if (kind) lines.push(`类型:${kind}`);
223
+ lines.push(`账户:${nonEmpty(card.user) ?? "未提供"}`);
224
+ if (card.alias) lines.push(`账户别名:${card.alias}`);
225
+ if (card.seat) lines.push(`代替的密钥套餐:${card.seat}`);
226
+ lines.push(`套餐:${nonEmpty(card.plan) ?? "未提供"}`);
227
+ if (card.until) lines.push(`付费有效期至:${card.until}(${renewLabel(card.renew)})`);
228
+ if (card.held) lines.push("该账户当前未被网关派发(held)。");
229
+ if (card.needsAccessKey) lines.push("缺少该账户的读取密钥,额度未取得。");
230
+ lines.push(`读数时间:${nonEmpty(card.readAt) ?? "未提供"}`);
231
+ if (card.asOf) lines.push(`旧读数时间:${card.asOf}(沿用此前读数)`);
232
+ if (card.readDeferred) lines.push("本次未主动读取(沿用缓存)。");
233
+ if (nonEmpty(card.error)) lines.push(`本次记录错误:${card.error}`);
234
+ lines.push(...fundsLines(card));
235
+ const windows = card.windows;
236
+ if (windows == null) lines.push("窗口:未提供(不能视为无限额或满额)");
237
+ else if (!windows.length) lines.push("窗口:未返回(可能是余额卡、尚无读数或未取得窗口)");
238
+ else for (const window of windows) lines.push(`窗口:${windowLine(window)}`);
239
+ if (card.lastServedAt) lines.push(`最近经网关答复:${card.lastServedAt}`);
240
+ return lines;
241
+ }
242
+
243
+ /** 状态行明细;模型名只称为网关报告值,成员判定留给路由数据。 */
244
+ export function statusDetails(status: MagpieStatusline): string[] {
245
+ const lines: string[] = [];
246
+ lines.push(`模型(网关状态报告值):${status.model || "未提供"}`);
247
+ lines.push("该模型名可能是请求名回退,不能证明实际执行的成员。");
248
+ const text = nonEmpty(status.text);
249
+ if (text) lines.push(`网关状态行:${text}`);
250
+ if (!status.accounts.length) lines.push("账户卡片:未返回(不代表没有账户或额度)。");
251
+ else {
252
+ const failed = status.accounts.filter(account => nonEmpty(account.error)).length;
253
+ lines.push(`账户卡片:${status.accounts.length} 条${failed ? `,其中 ${failed} 条带本次错误` : ""}。`);
254
+ for (const [index, account] of status.accounts.entries()) {
255
+ lines.push(`${cardLabel(account, index)} · 读数时间:${account.readAt || account.asOf || "未提供"}`);
256
+ if (account.asOf) lines.push(`沿用旧读数:${account.asOf}`);
257
+ if (account.error) lines.push(`本次记录错误:${account.error}`);
258
+ }
259
+ }
260
+ return lines;
261
+ }
@@ -76,6 +76,8 @@ function createService(root: string, scope: string, cacheFilePath: string) {
76
76
  let valid = true;
77
77
  let snapshot: GatewayCatalogSnapshot | undefined;
78
78
  let task: FetchTask | undefined;
79
+ const listeners = new Set<() => void>();
80
+ const changed = () => { for (const listener of listeners) listener(); };
79
81
  const recovery = createGatewayCatalogRecovery({ onIdle: () => {
80
82
  if (task?.waiters === 0 && !task.cacheSelected) task.controller.abort();
81
83
  } });
@@ -86,8 +88,11 @@ function createService(root: string, scope: string, cacheFilePath: string) {
86
88
  const read = (key: string): GatewayCatalogSnapshot | undefined => {
87
89
  check(key);
88
90
  const local = getCachedGatewayModelIds(root, key, { cacheFilePath });
89
- if (local && (!snapshot || local.storedAt > snapshot.storedAt))
90
- snapshot = { ids: [...local.ids], storedAt: local.storedAt, source: "cache" };
91
+ if (local && (!snapshot || local.storedAt > snapshot.storedAt)) {
92
+ snapshot = { ids: [...local.ids], storedAt: local.storedAt, source: "cache",
93
+ ...(local.magpie ? { magpie: local.magpie } : {}) };
94
+ changed();
95
+ }
91
96
  return snapshot ? copy(snapshot) : undefined;
92
97
  };
93
98
  const currentOutcome = (networkAttempted: boolean, networkSucceeded: boolean,
@@ -98,7 +103,12 @@ function createService(root: string, scope: string, cacheFilePath: string) {
98
103
 
99
104
  const api = {
100
105
  scope,
106
+ subscribe(listener: () => void): () => void {
107
+ listeners.add(listener);
108
+ return () => { listeners.delete(listener); };
109
+ },
101
110
  valid: () => valid,
111
+ isMagpie: () => valid && snapshot?.magpie === true,
102
112
  read,
103
113
  fetching: () => !!task?.networkStarted && !task.controller.signal.aborted,
104
114
  refreshKind: () => task && !task.controller.signal.aborted ? (task.force ? "force" : "normal") : undefined,
@@ -113,6 +123,8 @@ function createService(root: string, scope: string, cacheFilePath: string) {
113
123
  task?.controller.abort();
114
124
  task = undefined;
115
125
  snapshot = undefined;
126
+ changed();
127
+ listeners.clear();
116
128
  },
117
129
  /** 后台通过仍活跃实例的宿主服务发起单次获取,联网许可和凭据仍交宿主。 */
118
130
  recoverUsing(run: (signal: AbortSignal) => Promise<GatewayCatalogOutcome>, signal?: AbortSignal): Promise<GatewayCatalogOutcome> {
@@ -169,8 +181,11 @@ function createService(root: string, scope: string, cacheFilePath: string) {
169
181
  const code = result.ok ? result.fallbackStatus : result.status;
170
182
  return currentOutcome(true, false, true, code !== 401 && code !== 403);
171
183
  }
172
- if (!snapshot || result.storedAt >= snapshot.storedAt)
173
- snapshot = { ids: [...result.ids], storedAt: result.storedAt, source: result.cached ? "cache" : "network" };
184
+ if (!snapshot || result.storedAt >= snapshot.storedAt) {
185
+ snapshot = { ids: [...result.ids], storedAt: result.storedAt, source: result.cached ? "cache" : "network",
186
+ ...(result.magpie ? { magpie: result.magpie } : {}) };
187
+ changed();
188
+ }
174
189
  return currentOutcome(true, !result.cached);
175
190
  });
176
191
  // 即使底层忽略取消,取消仍立即释放共享槽;迟到结果不能提交。
@@ -192,7 +207,7 @@ function createService(root: string, scope: string, cacheFilePath: string) {
192
207
  export type GatewayCatalogService = ReturnType<typeof createService>;
193
208
 
194
209
  interface ServiceRegistry {
195
- version: 4;
210
+ version: 6;
196
211
  /** 每个 agent-dir 的唯一缓存路径一个当前槽,不按密钥维护多个目录。 */
197
212
  slots: Map<string, GatewayCatalogService>;
198
213
  }
@@ -203,8 +218,8 @@ const REGISTRY = Symbol.for("pi-tsgw:gateway-catalog");
203
218
  export function getGatewayCatalogService(root: string, key: string, cacheFilePath: string): GatewayCatalogService {
204
219
  const globals = globalThis as typeof globalThis & { [REGISTRY]?: ServiceRegistry };
205
220
  let registry = globals[REGISTRY];
206
- if (registry && registry.version !== 4) throw new Error("TSGW 目录共享状态版本不兼容,请重启宿主。");
207
- registry ??= globals[REGISTRY] = { version: 4, slots: new Map() };
221
+ if (registry && registry.version !== 6) throw new Error("TSGW 目录共享状态版本不兼容,请重启宿主。");
222
+ registry ??= globals[REGISTRY] = { version: 6, slots: new Map() };
208
223
  const path = resolve(cacheFilePath);
209
224
  const scope = gatewayModelCacheScope(root, key);
210
225
  let service = registry.slots.get(path);
@@ -7,6 +7,7 @@ import {
7
7
  writeFileSync,
8
8
  } from "node:fs";
9
9
  import { dirname, resolve } from "node:path";
10
+ import { parseGatewayModelList } from "./gateway-model-list.ts";
10
11
 
11
12
  export const DEFAULT_GATEWAY_MODEL_TIMEOUT_MS = 5_000;
12
13
  export const DEFAULT_GATEWAY_MODEL_CACHE_TTL_MS = 24 * 60 * 60 * 1_000;
@@ -39,7 +40,7 @@ export interface GetGatewayModelIdsOptions extends FetchGatewayModelIdsOptions {
39
40
  }
40
41
 
41
42
  export type FetchGatewayModelIdsResult =
42
- | { ok: true; ids: string[] }
43
+ | { ok: true; ids: string[]; magpie?: true }
43
44
  | {
44
45
  ok: false;
45
46
  reason: GatewayModelFailureReason;
@@ -50,17 +51,19 @@ export type FetchGatewayModelIdsResult =
50
51
  export interface ModelCacheEntry {
51
52
  ids: string[];
52
53
  storedAt: number;
54
+ magpie?: true;
53
55
  }
54
56
 
55
57
  export interface ModelCache {
56
58
  get(): ModelCacheEntry | undefined;
57
- set(ids: readonly string[], now?: number): void;
59
+ set(ids: readonly string[], now?: number, magpie?: true): void;
58
60
  isFresh(now?: number): boolean;
59
61
  }
60
62
 
61
63
  export interface LoadedGatewayModelCache {
62
64
  ids: string[];
63
65
  fresh: boolean;
66
+ magpie?: true;
64
67
  }
65
68
 
66
69
  export type CachedGatewayModelIds = ModelCacheEntry & { fresh: boolean };
@@ -77,6 +80,7 @@ export type GetGatewayModelIdsResult =
77
80
  cached: boolean;
78
81
  stale: boolean;
79
82
  storedAt: number;
83
+ magpie?: true;
80
84
  fallbackReason?: GatewayModelFailureReason;
81
85
  fallbackStatus?: number;
82
86
  }
@@ -96,16 +100,6 @@ function modelsUrl(baseUrl: string): string {
96
100
  return `${baseUrl.replace(/\/+$/, "")}/v1/models`;
97
101
  }
98
102
 
99
- function uniqueModelIds(data: unknown[]): string[] {
100
- const ids = new Set<string>();
101
- for (const item of data) {
102
- if (!item || typeof item !== "object") continue;
103
- const id = (item as { id?: unknown }).id;
104
- if (typeof id === "string" && id.trim()) ids.add(id.trim());
105
- }
106
- return Array.from(ids);
107
- }
108
-
109
103
  /** 加载网关提供的 OpenAI 兼容模型列表。 */
110
104
  export async function fetchGatewayModelIds(
111
105
  baseUrl: string,
@@ -159,13 +153,7 @@ export async function fetchGatewayModelIds(
159
153
 
160
154
  if (timedOut) return { ok: false, reason: "timeout" };
161
155
  if (opts.signal?.aborted) return { ok: false, reason: "aborted" };
162
- if (!payload || typeof payload !== "object")
163
- return { ok: false, reason: "invalid-data" };
164
- const data = (payload as { data?: unknown }).data;
165
- if (!Array.isArray(data)) return { ok: false, reason: "invalid-data" };
166
- const ids = uniqueModelIds(data);
167
- if (ids.length === 0) return { ok: false, reason: "empty" };
168
- return { ok: true, ids };
156
+ return parseGatewayModelList(payload);
169
157
  } finally {
170
158
  clearTimeout(timeout);
171
159
  opts.signal?.removeEventListener("abort", abortFromCaller);
@@ -182,11 +170,11 @@ export function createModelCache(
182
170
  return {
183
171
  get() {
184
172
  return entry
185
- ? { ids: [...entry.ids], storedAt: entry.storedAt }
173
+ ? { ...entry, ids: [...entry.ids] }
186
174
  : undefined;
187
175
  },
188
- set(ids, now = Date.now()) {
189
- entry = { ids: [...ids], storedAt: now };
176
+ set(ids, now = Date.now(), magpie) {
177
+ entry = { ids: [...ids], storedAt: now, ...(magpie ? { magpie } : {}) };
190
178
  },
191
179
  isFresh(now = Date.now()) {
192
180
  if (!entry) return false;
@@ -208,10 +196,11 @@ function readStoredGatewayModelCache(
208
196
  try {
209
197
  const payload: unknown = JSON.parse(readFileSync(filePath, "utf8"));
210
198
  if (!payload || typeof payload !== "object") return undefined;
211
- const { storedAt, ids, scope: storedScope } = payload as {
199
+ const { storedAt, ids, scope: storedScope, magpie } = payload as {
212
200
  scope?: unknown;
213
201
  storedAt?: unknown;
214
202
  ids?: unknown;
203
+ magpie?: unknown;
215
204
  };
216
205
  if (
217
206
  typeof storedScope !== "string" || !storedScope ||
@@ -226,6 +215,7 @@ function readStoredGatewayModelCache(
226
215
  scope: storedScope,
227
216
  storedAt,
228
217
  ids: Array.from(new Set(ids.map((id) => id.trim()))),
218
+ ...(magpie === true ? { magpie } : {}),
229
219
  };
230
220
  } catch {
231
221
  return undefined;
@@ -238,7 +228,8 @@ function readGatewayModelCacheEntry(
238
228
  ): ModelCacheEntry | undefined {
239
229
  const snapshot = readStoredGatewayModelCache(filePath);
240
230
  if (!scope || snapshot?.scope !== scope) return undefined;
241
- return { storedAt: snapshot.storedAt, ids: snapshot.ids };
231
+ const { scope: _scope, ...entry } = snapshot;
232
+ return entry;
242
233
  }
243
234
 
244
235
  /** 刷新后的文件摘要;可同时核对当前配置及已应用的完整模型 ID 快照。 */
@@ -273,13 +264,14 @@ export function saveGatewayModelCache(
273
264
  scope: string,
274
265
  ids: readonly string[],
275
266
  now = Date.now(),
267
+ magpie?: true,
276
268
  ): void {
277
269
  const temporaryPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
278
270
  try {
279
271
  mkdirSync(dirname(filePath), { recursive: true });
280
272
  writeFileSync(
281
273
  temporaryPath,
282
- JSON.stringify({ scope, storedAt: now, ids: [...ids] }),
274
+ JSON.stringify({ scope, storedAt: now, ids: [...ids], ...(magpie ? { magpie } : {}) }),
283
275
  { encoding: "utf8", mode: 0o600 },
284
276
  );
285
277
  renameSync(temporaryPath, filePath);
@@ -305,6 +297,7 @@ export function loadGatewayModelCache(
305
297
  return {
306
298
  ids: [...entry.ids],
307
299
  fresh: isCacheEntryFresh(entry, now, ttl),
300
+ ...(entry.magpie ? { magpie: entry.magpie } : {}),
308
301
  };
309
302
  }
310
303
 
@@ -373,8 +366,9 @@ export function getCachedGatewayModelIds(
373
366
  // 选中更新的磁盘快照时同步共享内存,避免磁盘随后损坏或删除时回退旧内存。
374
367
  // 仅预热内存,不写磁盘,也不改变原始获取时间。
375
368
  if (!memory || selected.entry.storedAt > memory.storedAt)
376
- cacheFor(cacheKey).set(selected.entry.ids, selected.entry.storedAt);
369
+ cacheFor(cacheKey).set(selected.entry.ids, selected.entry.storedAt, selected.entry.magpie);
377
370
  return {
371
+ ...selected.entry,
378
372
  ids: [...selected.entry.ids],
379
373
  storedAt: selected.entry.storedAt,
380
374
  fresh: selected.fresh,
@@ -402,8 +396,9 @@ export async function getGatewayModelIds(
402
396
  key, opts.cacheFilePath, ttlMs, now,
403
397
  );
404
398
  if (!opts.force && local?.fresh) {
405
- cache.set(local.entry.ids, local.entry.storedAt);
399
+ cache.set(local.entry.ids, local.entry.storedAt, local.entry.magpie);
406
400
  return {
401
+ ...local.entry,
407
402
  ok: true,
408
403
  ids: [...local.entry.ids],
409
404
  cached: true,
@@ -453,12 +448,12 @@ export async function getGatewayModelIds(
453
448
  // 以后启动的请求为准,即使较新的请求失败或取消。
454
449
  // 被取代的成功请求仍向调用者返回结果,但不写入缓存。
455
450
  if (latestRequests.get(cacheKey) === request.revision) {
456
- cache.set(fetched.ids, request.storedAt);
451
+ cache.set(fetched.ids, request.storedAt, fetched.magpie);
457
452
  if (diskPath && latestDiskRequests.get(diskPath) === request.revision)
458
- saveGatewayModelCache(diskPath, key, fetched.ids, request.storedAt);
453
+ saveGatewayModelCache(diskPath, key, fetched.ids, request.storedAt, fetched.magpie);
459
454
  }
460
455
  return {
461
- ok: true,
456
+ ...fetched,
462
457
  ids: [...fetched.ids],
463
458
  cached: false,
464
459
  stale: false,
@@ -472,6 +467,7 @@ export async function getGatewayModelIds(
472
467
  );
473
468
  if (fallback) {
474
469
  return {
470
+ ...fallback.entry,
475
471
  ok: true,
476
472
  ids: [...fallback.entry.ids],
477
473
  storedAt: fallback.entry.storedAt,
@@ -0,0 +1,20 @@
1
+ import type { FetchGatewayModelIdsResult } from "./gateway-catalog.ts";
2
+
3
+ /** 只用目录项的 Magpie 特征做简单识别,不承担网关身份认证。 */
4
+ export function parseGatewayModelList(payload: unknown): FetchGatewayModelIdsResult {
5
+ if (!payload || typeof payload !== "object")
6
+ return { ok: false, reason: "invalid-data" };
7
+ const data = (payload as { data?: unknown }).data;
8
+ if (!Array.isArray(data)) return { ok: false, reason: "invalid-data" };
9
+ const ids = new Set<string>();
10
+ let magpie: true | undefined;
11
+ for (const item of data) {
12
+ if (!item || typeof item !== "object") continue;
13
+ const { id, magpie_label: label } = item as { id?: unknown; magpie_label?: unknown };
14
+ if (typeof id !== "string" || !id.trim()) continue;
15
+ ids.add(id.trim());
16
+ if (typeof label === "string") magpie = true;
17
+ }
18
+ if (!ids.size) return { ok: false, reason: "empty" };
19
+ return { ok: true, ids: [...ids], ...(magpie ? { magpie } : {}) };
20
+ }
@@ -5,9 +5,16 @@ export function registerPrompts(pi: ExtensionAPI): void {
5
5
  pi.on("before_agent_start", (event) => {
6
6
  if (event.systemPromptOptions) {
7
7
  event.systemPromptOptions.sections.tsgw_memory = MEMORY_RULES;
8
- return;
8
+ }
9
+ // 读取注入分区后的完整提示词,避免 customPrompt 跳过宿主默认分区。
10
+ const prompt = event.systemPromptOptions
11
+ ? event.systemPrompt
12
+ : `${event.systemPrompt}\n\n${MEMORY_RULES}`;
13
+ const opening = "You are a coding assistant running inside pi, a coding agent harness.";
14
+ if (prompt.startsWith(opening)) {
15
+ return { systemPrompt: `You are an AI agent.${prompt.slice(opening.length)}` };
9
16
  }
10
17
  // 保留已声明支持的旧宿主提示词接口。
11
- return { systemPrompt: `${event.systemPrompt}\n\n${MEMORY_RULES}` };
18
+ if (!event.systemPromptOptions) return { systemPrompt: prompt };
12
19
  });
13
20
  }
@@ -77,6 +77,9 @@ export function createCatalogState(options: {
77
77
 
78
78
  return {
79
79
  models: () => models,
80
+ /** 从进程共享服务读取,其他实例刷新后立即生效。 */
81
+ isMagpie: () => service?.isMagpie() ?? false,
82
+ gateway: () => service,
80
83
  status: () => status,
81
84
  outcome(failed = false): GatewayCatalogOutcome {
82
85
  return { ...(service?.peek() ? { snapshot: service.peek() } : {}),
@@ -84,7 +87,7 @@ export function createCatalogState(options: {
84
87
  },
85
88
  matches(entry?: GatewayCatalogSnapshot): boolean {
86
89
  const current = snapshot;
87
- return !!entry && !!current && entry.storedAt === current.storedAt &&
90
+ return !!entry && !!current && entry.storedAt === current.storedAt && entry.magpie === current.magpie &&
88
91
  entry.ids.length === current.ids.length && entry.ids.every((id, index) => id === current.ids[index]);
89
92
  },
90
93
  recoverUsing(run: (signal: AbortSignal) => Promise<GatewayCatalogOutcome>, signal?: AbortSignal) {