pi-antigravity-bridge 0.1.6 → 0.1.8

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/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.8] - 2026-11-22
4
+
5
+ ### Added
6
+
7
+ - 自动为注册到 Pi 的 Antigravity 模型补充官方参考定价,并按单价计算每步与累计费用,同时为已有旧缓存自动补全价格数据。
8
+ - 适配 `pi-traffic-optimization` 扩展:支持在批量上下文归档后按需瘦身会话、保留完整 `ctx://` 句柄与 `context_recall` 召回指引,以及关闭优化后恢复完整上下文。
9
+
10
+ ### Changed
11
+
12
+ - 将 MCP 工具声明中的字面量联合参数规整为标准枚举类型,提升 `context_recall` 等扩展工具的参数可见性与校验提示准确度。
13
+ - 收紧大批量多工具调用拆分时的预留切片总扣减规模,降低对 Pi 原生缓存未命中统计的干扰。
14
+
15
+ ### Fixed
16
+
17
+ - 修复真实 `0%` 缓存未命中后缓存基准未清零,导致回退路径沿用旧高命中率或被整轮累计均值覆盖的问题。
18
+ - 修复跨生成残留切片混入新生成以及多条上游生成叠加混算导致缓存命中率与输出统计失真的问题。
19
+ - 修复中间工具步在本地会话记录延迟落盘时缺少重试的问题,并移除未观测缓存前的固定 85% 估算。
20
+ - 修复 `pi-traffic-optimization` 压缩图片(PNG 转 WebP)或归档历史图片后会话摘要失配导致误拆热缓存与重启恢复锚点失效的问题。
21
+
22
+ ## [0.1.7] - 2026-11-21
23
+
24
+ ### Changed
25
+
26
+ - 精简底部状态栏展示内容,移除与 Pi 重复的上下文窗口大小与用量显示。
27
+ - 为本地模型目录缓存增加 6 小时自动后台刷新,并在 `/agy sessions` 导入会话时保留历史工具调用记录与模型切换提示。
28
+ - 扩展 MCP 工具参数预校验支持局部 `$ref` / `$defs` 与 `allOf` 结构。
29
+
30
+ ### Fixed
31
+
32
+ - 修复工具执行期间修改 `AGENTS.md` 或 `SKILL.md` 导致当前轮次挂起超时并异常重建会话的问题。
33
+ - 修复默认 `processPerSession: true` 下通过 `tool_search` 或跨轮次动态新增工具无法同步至当前会话的问题。
34
+ - 修复多步工具调用末步及切片耗尽时输出 Token 归零、缓存命中率消失以及思考 Token 大于总输出 Token 的统计异常。
35
+ - 修复 `hybrid` 与 `agy-tools` 模式下读取含 `pi_tools` 路径文件时原生工具调用被误判吞掉,以及参数校验失败后后续工具延迟增加的问题。
36
+ - 修复开启 `agy-tools` 且桥接 Pi MCP 时强制启用原本未开启的 `codemode` 并在切回模式后残留的问题。
37
+ - 修复按 `Esc` 中断轮次后立即重发消息丢失热缓存会话的问题。
38
+ - 修复 `/compact` 摘要请求缺失摘要约束指令,以及无工具首轮包含摘要关键词的普通提问被误判为一次性辅助请求的问题。
39
+ - 修复 `agy-tools` 纯 Diff 更新清空先前流式文本输出、工具边界转向超时控制流穿透、自定义 `agyCustomAgent` 在开启挂载时失效及退出阶段子进程与定时器泄漏的问题。
40
+ - 修复 Windows 包装脚本特殊字符参数转义及 SQLite WAL 并发锁超时问题。
41
+
3
42
  ## [0.1.6] - 2026-11-21
4
43
 
5
44
  ### Fixed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-antigravity-bridge",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Google Antigravity CLI (agy acp) agent backend bridge for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -149,12 +149,13 @@ export interface AgySpawnSpec {
149
149
  }
150
150
 
151
151
  /**
152
- * 为 Windows `cmd.exe /d /s /c` 安全引用单个命令行参数(处理含空格路径与双引号,且无需设置 `shell: true`,彻底规避 Node 22+ DEP0190)。
152
+ * 为 Windows `cmd.exe /d /s /c` 安全引用单个命令行参数(处理含空格、管道、环境变量符号 `%` 及分隔符参数,无需设置 `shell: true`,规避 Node 22+ DEP0190)。
153
153
  */
154
154
  export function quoteWindowsCmdArg(arg: string): string {
155
155
  if (arg.length === 0) return '""';
156
- if (!/[\s"&|<>^()]/.test(arg)) return arg;
157
- return `"${arg.replace(/"/g, '""')}"`;
156
+ const escapedPercents = arg.replace(/%/g, "%%");
157
+ if (!/[\s"&|<>^()!;,=%]/.test(escapedPercents)) return escapedPercents;
158
+ return `"${escapedPercents.replace(/"/g, '""')}"`;
158
159
  }
159
160
 
160
161
  /**
@@ -23,7 +23,7 @@ import {
23
23
 
24
24
  export const BRIDGE_AGENT_NAME = "pi-bridge";
25
25
  export const CLIENT_INFO_NAME = "pi-antigravity-bridge";
26
- export const CLIENT_INFO_VERSION = "0.1.6";
26
+ export const CLIENT_INFO_VERSION = "0.1.7";
27
27
 
28
28
  export class AcpRpcError extends Error {
29
29
  readonly code: number;
@@ -81,9 +81,57 @@ interface PendingRpc {
81
81
  cleanupAbort?: () => void;
82
82
  }
83
83
 
84
+ /** 读取用户在 `<geminiDir>/config/agents/` 中显式配置的自定义 Agent 文件(若存在),以便在附加挂载插件时完整保留其定义 */
85
+ function readUserCustomAgentFile(
86
+ geminiDir: string,
87
+ userAgentName: string,
88
+ ): { frontmatterLines: string[]; body: string } | undefined {
89
+ const candidates = [
90
+ path.join(geminiDir, "config", "agents", userAgentName, "agent.md"),
91
+ path.join(geminiDir, "config", "agents", `${userAgentName}.md`),
92
+ ];
93
+ for (const candidate of candidates) {
94
+ try {
95
+ if (!fs.existsSync(candidate) || !fs.statSync(candidate).isFile()) continue;
96
+ const raw = fs.readFileSync(candidate, "utf8");
97
+ const fmMatch = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
98
+ if (fmMatch) {
99
+ const lines = fmMatch[1].split(/\r?\n/);
100
+ return { frontmatterLines: lines, body: fmMatch[2] };
101
+ }
102
+ return { frontmatterLines: [], body: raw };
103
+ } catch {
104
+ // 读取失败则继续检查下一候选路径
105
+ }
106
+ }
107
+ return undefined;
108
+ }
109
+
110
+ /** 从已有 YAML frontmatter 行中剔除指定顶层键(含多行列表值)以便安全合并挂载覆盖项 */
111
+ function stripYamlTopLevelKeys(lines: readonly string[], keysToRemove: ReadonlySet<string>): string[] {
112
+ const kept: string[] = [];
113
+ let skippingBlock = false;
114
+ for (const line of lines) {
115
+ const isTopLevel = line.length > 0 && !/^\s/.test(line) && !line.startsWith("#");
116
+ if (isTopLevel) {
117
+ const colonIdx = line.indexOf(":");
118
+ const key = colonIdx !== -1 ? line.slice(0, colonIdx).trim() : "";
119
+ if (keysToRemove.has(key)) {
120
+ skippingBlock = true;
121
+ continue;
122
+ }
123
+ skippingBlock = false;
124
+ }
125
+ if (!skippingBlock) {
126
+ kept.push(line);
127
+ }
128
+ }
129
+ return kept;
130
+ }
131
+
84
132
  /**
85
133
  * 判断该进程配置是否需要生成纯 YAML Frontmatter 的轻量挂载 Agent 文件。
86
- * Markdown 正文严格保持为空,绝不覆写或注入任何系统提示词。
134
+ * Markdown 正文严格保持为空(仅在合并用户显式指定的 `agyCustomAgent` 时原样保留用户自定义文件内容),绝不覆写或注入任何系统提示词。
87
135
  */
88
136
  function resolveManagedAgentMaterialization(
89
137
  profile: AcpProcessProfile,
@@ -92,6 +140,8 @@ function resolveManagedAgentMaterialization(
92
140
  profile.userAgentName &&
93
141
  !profile.disableBuiltinTools &&
94
142
  !profile.excludeDefaultComponents &&
143
+ profile.inheritCustomizations &&
144
+ profile.inheritMcp &&
95
145
  profile.mountedPluginPaths.length === 0
96
146
  ) {
97
147
  return { effectiveAgentName: profile.userAgentName };
@@ -108,10 +158,23 @@ function resolveManagedAgentMaterialization(
108
158
  return { effectiveAgentName: profile.userAgentName };
109
159
  }
110
160
 
161
+ const userCustomAgent =
162
+ profile.userAgentName && !profile.disableBuiltinTools
163
+ ? readUserCustomAgentFile(profile.geminiDir, profile.userAgentName)
164
+ : undefined;
165
+
111
166
  const specHash = crypto
112
167
  .createHash("sha256")
113
168
  .update(
114
169
  JSON.stringify({
170
+ userAgentName: profile.userAgentName ?? "",
171
+ userAgentBodyHash: userCustomAgent
172
+ ? crypto
173
+ .createHash("sha256")
174
+ .update(userCustomAgent.frontmatterLines.join("\n") + "\n---\n" + userCustomAgent.body)
175
+ .digest("hex")
176
+ .slice(0, 12)
177
+ : "",
115
178
  disableBuiltinTools: profile.disableBuiltinTools,
116
179
  excludeDefaultComponents: profile.excludeDefaultComponents,
117
180
  inheritCustomizations: profile.inheritCustomizations,
@@ -123,6 +186,7 @@ function resolveManagedAgentMaterialization(
123
186
  .slice(0, 10);
124
187
 
125
188
  const agentName =
189
+ !profile.userAgentName &&
126
190
  profile.disableBuiltinTools &&
127
191
  profile.excludeDefaultComponents &&
128
192
  !profile.inheritCustomizations &&
@@ -134,35 +198,64 @@ function resolveManagedAgentMaterialization(
134
198
  const agentDir = path.join(profile.geminiDir, "config", "agents", agentName);
135
199
  const agentFile = path.join(agentDir, "agent.md");
136
200
 
137
- const yamlLines: string[] = [
138
- "---",
139
- `name: ${agentName}`,
140
- "description: Configuration and customization mount profile for Pi Antigravity Bridge.",
141
- "mainAgent: true",
142
- "subagent: false",
143
- ];
144
-
145
- if (profile.disableBuiltinTools) {
146
- yamlLines.push("tools: []");
147
- }
148
- if (profile.excludeDefaultComponents) {
149
- yamlLines.push("excludeDefaultComponents: true");
150
- }
151
- if (!profile.inheritCustomizations) {
152
- yamlLines.push("inheritCustomizations: false");
153
- }
154
- if (!profile.inheritMcp) {
155
- yamlLines.push("inheritMcp: false");
156
- }
157
- if (profile.mountedPluginPaths.length > 0) {
158
- yamlLines.push("plugins:");
159
- for (const pluginPath of profile.mountedPluginPaths) {
160
- yamlLines.push(` - ${JSON.stringify(pluginPath)}`);
201
+ let desired: string;
202
+ if (userCustomAgent) {
203
+ const keysToReplace = new Set<string>(["name"]);
204
+ if (!profile.inheritCustomizations) keysToReplace.add("inheritCustomizations");
205
+ if (!profile.inheritMcp) keysToReplace.add("inheritMcp");
206
+ if (profile.mountedPluginPaths.length > 0) keysToReplace.add("plugins");
207
+
208
+ const mergedLines = [
209
+ "---",
210
+ `name: ${agentName}`,
211
+ ...stripYamlTopLevelKeys(userCustomAgent.frontmatterLines, keysToReplace),
212
+ ];
213
+ if (!profile.inheritCustomizations) {
214
+ mergedLines.push("inheritCustomizations: false");
215
+ }
216
+ if (!profile.inheritMcp) {
217
+ mergedLines.push("inheritMcp: false");
218
+ }
219
+ if (profile.mountedPluginPaths.length > 0) {
220
+ mergedLines.push("plugins:");
221
+ for (const pluginPath of profile.mountedPluginPaths) {
222
+ mergedLines.push(` - ${JSON.stringify(pluginPath)}`);
223
+ }
161
224
  }
225
+ mergedLines.push("---");
226
+ desired = userCustomAgent.body
227
+ ? `${mergedLines.join("\n")}\n${userCustomAgent.body}`
228
+ : `${mergedLines.join("\n")}\n`;
229
+ } else {
230
+ const yamlLines: string[] = [
231
+ "---",
232
+ `name: ${agentName}`,
233
+ "description: Configuration and customization mount profile for Pi Antigravity Bridge.",
234
+ "mainAgent: true",
235
+ "subagent: false",
236
+ ];
237
+
238
+ if (profile.disableBuiltinTools) {
239
+ yamlLines.push("tools: []");
240
+ }
241
+ if (profile.excludeDefaultComponents) {
242
+ yamlLines.push("excludeDefaultComponents: true");
243
+ }
244
+ if (!profile.inheritCustomizations) {
245
+ yamlLines.push("inheritCustomizations: false");
246
+ }
247
+ if (!profile.inheritMcp) {
248
+ yamlLines.push("inheritMcp: false");
249
+ }
250
+ if (profile.mountedPluginPaths.length > 0) {
251
+ yamlLines.push("plugins:");
252
+ for (const pluginPath of profile.mountedPluginPaths) {
253
+ yamlLines.push(` - ${JSON.stringify(pluginPath)}`);
254
+ }
255
+ }
256
+ yamlLines.push("---", "");
257
+ desired = yamlLines.join("\n");
162
258
  }
163
- yamlLines.push("---", "");
164
-
165
- let desired = yamlLines.join("\n");
166
259
  if (agentName === BRIDGE_AGENT_NAME) {
167
260
  try {
168
261
  const bundledAssetPath = path.resolve(
@@ -549,9 +642,14 @@ export class AcpClientConnection {
549
642
  if (this.isAlive) {
550
643
  await new Promise<void>((resolve) => {
551
644
  let settled = false;
645
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
552
646
  const finish = () => {
553
647
  if (settled) return;
554
648
  settled = true;
649
+ if (killTimer) {
650
+ clearTimeout(killTimer);
651
+ killTimer = undefined;
652
+ }
555
653
  resolve();
556
654
  };
557
655
 
@@ -562,12 +660,13 @@ export class AcpClientConnection {
562
660
  // 忽略管道关闭异常
563
661
  }
564
662
 
565
- setTimeout(() => {
663
+ killTimer = setTimeout(() => {
566
664
  if (!settled) {
567
665
  this.forceKillProcessTree();
568
666
  finish();
569
667
  }
570
668
  }, 1_500);
669
+ killTimer.unref();
571
670
  });
572
671
  }
573
672
 
@@ -790,13 +889,18 @@ export function resolveProcessProfileForConfig(
790
889
  export class AcpProcessManager {
791
890
  private readonly pool = new Map<string, AcpClientConnection>();
792
891
  private readonly initializing = new Map<string, Promise<AcpClientConnection>>();
892
+ private readonly initializingConns = new Set<AcpClientConnection>();
793
893
  private sharedHandlers: AcpServerHandlers = {};
894
+ private disposeEpoch = 0;
794
895
 
795
896
  setHandlers(handlers: AcpServerHandlers): void {
796
897
  this.sharedHandlers = handlers;
797
898
  for (const conn of this.pool.values()) {
798
899
  conn.setHandlers(handlers);
799
900
  }
901
+ for (const conn of this.initializingConns) {
902
+ conn.setHandlers(handlers);
903
+ }
800
904
  }
801
905
 
802
906
  resolveBinary(config: BridgeConfig): ResolvedBinary {
@@ -833,18 +937,27 @@ export class AcpProcessManager {
833
937
 
834
938
  let initTask = this.initializing.get(key);
835
939
  if (!initTask) {
940
+ const epochAtStart = this.disposeEpoch;
836
941
  initTask = (async () => {
837
942
  const binary = this.resolveBinary(config);
838
943
  const conn = new AcpClientConnection(binary, profile, this.sharedHandlers);
944
+ this.initializingConns.add(conn);
839
945
  try {
840
946
  await conn.ensureInitialized();
947
+ if (this.disposeEpoch !== epochAtStart) {
948
+ await conn.dispose();
949
+ throw new Error("Antigravity ACP 进程池已关闭");
950
+ }
841
951
  this.pool.set(key, conn);
842
952
  return conn;
843
953
  } catch (error) {
844
954
  await conn.dispose();
845
955
  throw error;
846
956
  } finally {
847
- this.initializing.delete(key);
957
+ this.initializingConns.delete(conn);
958
+ if (this.initializing.get(key) === initTask) {
959
+ this.initializing.delete(key);
960
+ }
848
961
  }
849
962
  })();
850
963
  this.initializing.set(key, initTask);
@@ -860,12 +973,19 @@ export class AcpProcessManager {
860
973
  this.pool.delete(key);
861
974
  }
862
975
  }
976
+ this.initializingConns.delete(target);
863
977
  await target.dispose();
864
978
  }
865
979
 
866
980
  async disposeAll(): Promise<void> {
867
- const connections = Array.from(this.pool.values());
981
+ this.disposeEpoch++;
982
+ const connections = new Set<AcpClientConnection>([
983
+ ...this.pool.values(),
984
+ ...this.initializingConns.values(),
985
+ ]);
868
986
  this.pool.clear();
869
- await Promise.allSettled(connections.map((conn) => conn.dispose()));
987
+ this.initializing.clear();
988
+ this.initializingConns.clear();
989
+ await Promise.allSettled(Array.from(connections, (conn) => conn.dispose()));
870
990
  }
871
991
  }
@@ -322,6 +322,8 @@ export type AcpSessionUpdatePayload =
322
322
  | {
323
323
  sessionUpdate: "tool_call";
324
324
  toolCallId: string;
325
+ name?: string;
326
+ args?: unknown;
325
327
  title?: string;
326
328
  kind?: AcpToolKind;
327
329
  status?: AcpToolStatus;
@@ -333,6 +335,8 @@ export type AcpSessionUpdatePayload =
333
335
  | {
334
336
  sessionUpdate: "tool_call_update";
335
337
  toolCallId: string;
338
+ name?: string;
339
+ args?: unknown;
336
340
  title?: string;
337
341
  kind?: AcpToolKind;
338
342
  status?: AcpToolStatus;
@@ -1,6 +1,11 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { ThinkingLevel, ThinkingLevelMap } from "@earendil-works/pi-ai";
4
+ import {
5
+ type BuiltinProvider,
6
+ getBuiltinModels,
7
+ getBuiltinProviders,
8
+ } from "@earendil-works/pi-ai/providers/all";
4
9
  import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
5
10
 
6
11
  export type ChatModelConfig = Extract<ProviderModelConfig, { reasoning: boolean }>;
@@ -33,6 +38,143 @@ const EFFORT_ORDER: readonly EffortSuffix[] = [
33
38
  "max",
34
39
  ];
35
40
 
41
+ const ZERO_MODEL_COST: ChatModelConfig["cost"] = {
42
+ input: 0,
43
+ output: 0,
44
+ cacheRead: 0,
45
+ cacheWrite: 0,
46
+ };
47
+
48
+ /** 从 Pi 内置官方目录查找参考定价时的 Provider 优先级(优先官方直连定价,规避区域溢价与批量折扣条目) */
49
+ const PRICING_PROVIDER_PRIORITY: readonly string[] = [
50
+ "google",
51
+ "anthropic",
52
+ "google-vertex",
53
+ "openai",
54
+ "radius",
55
+ "groq",
56
+ "together",
57
+ "openrouter",
58
+ ];
59
+
60
+ let cachedBuiltinCostIndex: Map<string, ChatModelConfig["cost"]> | undefined;
61
+
62
+ function cloneModelCost(cost: ChatModelConfig["cost"]): ChatModelConfig["cost"] {
63
+ return {
64
+ input: cost.input,
65
+ output: cost.output,
66
+ cacheRead: cost.cacheRead,
67
+ cacheWrite: cost.cacheWrite,
68
+ ...(cost.tiers && cost.tiers.length > 0
69
+ ? { tiers: cost.tiers.map((tier) => ({ ...tier })) }
70
+ : {}),
71
+ };
72
+ }
73
+
74
+ function hasNonZeroModelCost(cost: ChatModelConfig["cost"] | undefined): boolean {
75
+ if (!cost) return false;
76
+ return cost.input > 0 || cost.output > 0 || cost.cacheRead > 0 || cost.cacheWrite > 0;
77
+ }
78
+
79
+ function getBuiltinCostIndex(): Map<string, ChatModelConfig["cost"]> {
80
+ if (cachedBuiltinCostIndex) {
81
+ return cachedBuiltinCostIndex;
82
+ }
83
+ const index = new Map<string, ChatModelConfig["cost"]>();
84
+ try {
85
+ const availableProviders = new Set<string>(getBuiltinProviders());
86
+ for (const provider of PRICING_PROVIDER_PRIORITY) {
87
+ if (!availableProviders.has(provider)) continue;
88
+ const models = getBuiltinModels(provider as BuiltinProvider);
89
+ for (const m of models) {
90
+ const rawId = m.id.toLowerCase();
91
+ if (rawId.includes(":batch") || rawId.endsWith("-batch")) continue;
92
+ if (!hasNonZeroModelCost(m.cost)) continue;
93
+ if (!index.has(rawId)) {
94
+ index.set(rawId, m.cost);
95
+ }
96
+ const slashIdx = rawId.lastIndexOf("/");
97
+ if (slashIdx !== -1 && slashIdx < rawId.length - 1) {
98
+ const bareId = rawId.slice(slashIdx + 1);
99
+ if (!index.has(bareId)) {
100
+ index.set(bareId, m.cost);
101
+ }
102
+ }
103
+ }
104
+ }
105
+ } catch {
106
+ // 若上游 pi-ai 目录结构变化则安全回退至零费用,绝不阻塞模型注册
107
+ }
108
+ cachedBuiltinCostIndex = index;
109
+ return index;
110
+ }
111
+
112
+ function buildPricingLookupCandidates(modelId: string, displayName?: string): string[] {
113
+ const candidates: string[] = [];
114
+ const push = (id: string) => {
115
+ const normalized = id.trim().toLowerCase();
116
+ if (normalized && !candidates.includes(normalized)) {
117
+ candidates.push(normalized);
118
+ }
119
+ };
120
+
121
+ const raw = modelId.trim().toLowerCase();
122
+ const bases: string[] = [raw];
123
+
124
+ // 去除 -thinking 尾缀(如 claude-opus-4-6-thinking -> claude-opus-4-6)
125
+ if (raw.endsWith("-thinking") && raw.length > "-thinking".length) {
126
+ bases.push(raw.slice(0, -"-thinking".length));
127
+ }
128
+ // 去除固定单档位后缀(如 gpt-oss-120b-medium -> gpt-oss-120b)
129
+ const effortSplit = splitEffortSuffix(raw);
130
+ if (effortSplit) {
131
+ bases.push(effortSplit.baseId);
132
+ }
133
+
134
+ for (const base of bases) {
135
+ push(base);
136
+ // 点号/连字符版本互转(如 claude-sonnet-4.6 <-> claude-sonnet-4-6)
137
+ const dashedVer = base.replace(/(\d)\.(\d)/g, "$1-$2");
138
+ const dottedVer = base.replace(/-(\d+)-(\d+)(?=$|-)/g, "-$1.$2");
139
+ push(dashedVer);
140
+ push(dottedVer);
141
+ if (!base.endsWith("-preview")) {
142
+ push(`${base}-preview`);
143
+ }
144
+ }
145
+
146
+ // Antigravity Orchestrator 封装项按底层对应代号匹配 Gemini 4 同级参考定价
147
+ if (raw.includes("orchestrator")) {
148
+ const hint = `${raw} ${(displayName ?? "").toLowerCase()}`;
149
+ const flavorMatch = hint.match(/\b(neon|carbon|argon|hydrogen)\b/);
150
+ if (flavorMatch) {
151
+ push(`gemini-4-${flavorMatch[1]}`);
152
+ } else {
153
+ push("gemini-4-carbon");
154
+ }
155
+ }
156
+
157
+ return candidates;
158
+ }
159
+
160
+ /**
161
+ * 从 Pi 内置模型目录动态解析 Antigravity 模型对应的官方参考定价(美元/百万 Token,含缓存读写与阶梯价)。
162
+ * 订阅制账号在 Pi 状态栏中会自动附加 `(sub)` 标记,并支持 `/model`、`/usage` 与缓存浪费统计展示。
163
+ */
164
+ export function resolveBuiltinModelCost(
165
+ modelId: string,
166
+ displayName?: string,
167
+ ): ChatModelConfig["cost"] {
168
+ const index = getBuiltinCostIndex();
169
+ for (const key of buildPricingLookupCandidates(modelId, displayName)) {
170
+ const matched = index.get(key);
171
+ if (matched) {
172
+ return cloneModelCost(matched);
173
+ }
174
+ }
175
+ return cloneModelCost(ZERO_MODEL_COST);
176
+ }
177
+
36
178
  export interface DiscoveredCatalogSnapshot {
37
179
  version: 1;
38
180
  updatedAt: number;
@@ -151,12 +293,7 @@ function makeChatModelConfig(
151
293
  reasoning: hasReasoning,
152
294
  thinkingLevelMap: hasReasoning ? buildThinkingLevelMap(efforts) : undefined,
153
295
  input: specs.supportsImage ? ["text", "image"] : ["text"],
154
- cost: {
155
- input: 0,
156
- output: 0,
157
- cacheRead: 0,
158
- cacheWrite: 0,
159
- },
296
+ cost: resolveBuiltinModelCost(id, name),
160
297
  contextWindow: specs.contextWindow,
161
298
  maxTokens: specs.maxTokens,
162
299
  };
@@ -289,9 +426,10 @@ export function readCachedCatalog(env: NodeJS.ProcessEnv = process.env): Discove
289
426
  if (!fs.existsSync(cachePath)) return undefined;
290
427
  const raw = JSON.parse(fs.readFileSync(cachePath, "utf8")) as DiscoveredCatalogSnapshot;
291
428
  if (raw?.version === 1 && Array.isArray(raw.models) && raw.models.length > 0) {
292
- // 应用最新观测到的窗口校准
429
+ // 应用最新观测到的窗口校准,并为旧版零费用缓存自动补全 Pi 内置目录参考定价
293
430
  const calibrated = raw.models.map((m) => ({
294
431
  ...m,
432
+ cost: hasNonZeroModelCost(m.cost) ? m.cost : resolveBuiltinModelCost(m.id, m.name),
295
433
  contextWindow: getObservedContextWindow(m.id) ?? m.contextWindow,
296
434
  }));
297
435
  return { ...raw, models: calibrated };
@@ -317,9 +455,14 @@ export function writeCachedCatalog(
317
455
  }
318
456
 
319
457
  const CATALOG_FRESH_TTL_MS = 15_000;
320
- let inFlightCatalogProbe: Promise<DiscoveredCatalogSnapshot> | undefined;
321
- let lastLiveProbeSnapshot: DiscoveredCatalogSnapshot | undefined;
322
- let lastLiveProbeAt = 0;
458
+ const liveProbeStateByCachePath = new Map<
459
+ string,
460
+ {
461
+ inFlight?: Promise<DiscoveredCatalogSnapshot>;
462
+ lastSnapshot?: DiscoveredCatalogSnapshot;
463
+ lastAt: number;
464
+ }
465
+ >();
323
466
 
324
467
  function raceCatalogProbeWithSignal<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
325
468
  if (!signal) return promise;
@@ -380,6 +523,8 @@ export function removeEmptyProbeSessionFiles(config: BridgeConfig, sessionId: st
380
523
  export interface ProbeCatalogOptions {
381
524
  signal?: AbortSignal;
382
525
  force?: boolean;
526
+ /** 可选环境变量覆盖(主要用于隔离模型缓存写入目录,避免测试覆写用户全局缓存) */
527
+ env?: NodeJS.ProcessEnv;
383
528
  }
384
529
 
385
530
  /**
@@ -401,16 +546,25 @@ export async function probeLiveAntigravityCatalog(
401
546
  throw opts.signal.reason ?? new Error("模型探测已取消");
402
547
  }
403
548
 
549
+ const cacheKey = resolveModelCachePath(opts.env);
550
+ let state = liveProbeStateByCachePath.get(cacheKey);
404
551
  if (
405
552
  !opts.force &&
406
- lastLiveProbeSnapshot &&
407
- Date.now() - lastLiveProbeAt < CATALOG_FRESH_TTL_MS
553
+ state?.lastSnapshot &&
554
+ Date.now() - state.lastAt < CATALOG_FRESH_TTL_MS
408
555
  ) {
409
- return lastLiveProbeSnapshot;
556
+ return state.lastSnapshot;
557
+ }
558
+
559
+ if (!state) {
560
+ state = { lastAt: 0 };
561
+ liveProbeStateByCachePath.set(cacheKey, state);
410
562
  }
411
563
 
412
- if (!inFlightCatalogProbe) {
413
- inFlightCatalogProbe = (async () => {
564
+ let inFlight = state.inFlight;
565
+ if (!inFlight) {
566
+ const targetState = state;
567
+ inFlight = (async () => {
414
568
  const conn = await processManager.acquire(config, undefined);
415
569
  const sessionRes = await conn.request<AcpSessionNewResult>(
416
570
  "session/new",
@@ -433,9 +587,9 @@ export async function probeLiveAntigravityCatalog(
433
587
  models: models.length > 0 ? models : getSeedModels(),
434
588
  modelEfforts,
435
589
  };
436
- writeCachedCatalog(snapshot);
437
- lastLiveProbeSnapshot = snapshot;
438
- lastLiveProbeAt = Date.now();
590
+ writeCachedCatalog(snapshot, opts.env);
591
+ targetState.lastSnapshot = snapshot;
592
+ targetState.lastAt = Date.now();
439
593
  return snapshot;
440
594
  } finally {
441
595
  if (sessionRes.sessionId) {
@@ -444,11 +598,12 @@ export async function probeLiveAntigravityCatalog(
444
598
  }
445
599
  }
446
600
  })().finally(() => {
447
- inFlightCatalogProbe = undefined;
601
+ targetState.inFlight = undefined;
448
602
  });
603
+ targetState.inFlight = inFlight;
449
604
  }
450
605
 
451
- return raceCatalogProbeWithSignal(inFlightCatalogProbe, opts.signal);
606
+ return raceCatalogProbeWithSignal(inFlight, opts.signal);
452
607
  }
453
608
 
454
609
  export interface ResolvedModelSelection {
package/src/index.ts CHANGED
@@ -39,6 +39,7 @@ import { updateAntigravityStatusBar } from "./ui/status-bar.ts";
39
39
 
40
40
  const SENTINEL_API_KEY = "agy-managed";
41
41
  const TEN_YEARS_MS = 10 * 365 * 24 * 60 * 60 * 1000;
42
+ const MODEL_CACHE_STALE_MS = 6 * 60 * 60 * 1000;
42
43
 
43
44
  /**
44
45
  * 读取 Pi 的 `trust.json` 判断指定工作目录在 `resources_discover` 早期阶段是否已被授予项目信任。
@@ -266,8 +267,13 @@ export default function antigravityBridgeExtension(pi: ExtensionAPI): void {
266
267
  coordinator.setActiveContext(ctx);
267
268
  toolActivation.syncForContext(ctx, currentConfig);
268
269
 
269
- // 若首次加载尚无本地缓存快照,复用内置 Singleflight 静默探测一次模型目录
270
- if (!cachedCatalog) {
270
+ // 若首次加载尚无本地缓存快照或缓存已超过 6 小时,复用内置 Singleflight 后台静默探测一次最新模型目录
271
+ const diskCache = readCachedCatalog();
272
+ const isCacheStale =
273
+ !diskCache ||
274
+ typeof diskCache.updatedAt !== "number" ||
275
+ Date.now() - diskCache.updatedAt > MODEL_CACHE_STALE_MS;
276
+ if (isCacheStale) {
271
277
  void refreshAndReRegisterModels(ctx).catch(() => {});
272
278
  }
273
279
  });