pi-antigravity-bridge 0.1.15 → 0.1.16

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,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [Unreleased]
4
+
5
+ ## [0.1.16] - 2026-11-25
6
+
7
+ ### Fixed
8
+
9
+ - 工具审批未完成导致回复为空时,Pi 会提示需要确认或未获批准的原因。
10
+ - 修复会话数据库初始化失败后首条消息仍发往故障会话的问题。恢复没有持久化记录的会话时,保留 Pi 的对话历史。
11
+ - 修复回到旧分支时混入其他分支对话的问题。
12
+ - 修复后端取消被显示为成功,以及发送前中断后续聊丢失历史的问题。
13
+ - 修复自动续接或会话数据库延迟创建时的流量漏记和重计。
14
+
3
15
  ## [0.1.15] - 2026-11-24
4
16
 
5
17
  ### Changed
package/README.md CHANGED
@@ -54,7 +54,7 @@ pi remove npm:pi-antigravity-bridge
54
54
 
55
55
  1. 确保本机 `agy` 已登录(若尚未登录,可在终端运行 `agy acp --login`,或在启动 `pi` 后执行 `/agy login`)。
56
56
  2. 启动 `pi`,输入 `/model` 并选择 `antigravity` 分组下的模型(如 `gemini-4-neon`、`gemini-4-carbon`、`claude-sonnet-5-5`)。
57
- 3. 使用快捷键循环切换 Thinking 档位,直接开始对话。
57
+ 3. 使用快捷键循环切换 Thinking 档位,直接开始对话。Antigravity 要求工具审批时,在 Pi 中选择批准或拒绝。非交互模式没有审批界面。
58
58
 
59
59
  ## 斜杠命令
60
60
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-antigravity-bridge",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
4
4
  "description": "Google Antigravity CLI (agy acp) agent backend bridge for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -154,7 +154,7 @@ function openSqliteWithTimeout(
154
154
  ? new sqlite.DatabaseSync(dbPath, { readOnly: true })
155
155
  : new sqlite.DatabaseSync(dbPath);
156
156
  try {
157
- db.exec(`PRAGMA busy_timeout = ${Math.max(100, Math.floor(busyTimeoutMs))}`);
157
+ db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.floor(busyTimeoutMs))}`);
158
158
  } catch {
159
159
  // 忽略只读连接或特殊环境下 PRAGMA 不可用异常
160
160
  }
@@ -194,6 +194,26 @@ function verifyRequiredTables(db: import("node:sqlite").DatabaseSync): boolean {
194
194
  return REQUIRED_TABLES.every((req) => names.has(req));
195
195
  }
196
196
 
197
+ /** 新会话返回成功时,只读检查已落地的轨迹库是否缺少必需表。 */
198
+ export async function hasIncompleteSqliteConversationSchema(
199
+ config: BridgeConfig,
200
+ agySessionId: string,
201
+ ): Promise<boolean> {
202
+ if (!hasLocalConversationDb(config, agySessionId)) return false;
203
+ const sqlite = await loadNodeSqlite();
204
+ if (!sqlite) return false;
205
+ const dbPath = path.join(resolveAgyConversationsDir(config), `${agySessionId}.db`);
206
+ let db: import("node:sqlite").DatabaseSync | undefined;
207
+ try {
208
+ db = openSqliteWithTimeout(sqlite, dbPath, true, 0);
209
+ return !verifyRequiredTables(db);
210
+ } catch {
211
+ return false;
212
+ } finally {
213
+ db?.close();
214
+ }
215
+ }
216
+
197
217
  export interface SqliteGenerationUsage {
198
218
  stepIdx: number;
199
219
  inputTokens: number;
@@ -246,9 +266,8 @@ export interface SqliteUpstreamRequestSnapshot {
246
266
  }
247
267
 
248
268
  export interface SqliteUpstreamQueryResult {
249
- latest?: SqliteUpstreamRequestSnapshot;
269
+ snapshots: SqliteUpstreamRequestSnapshot[];
250
270
  maxGenIdx: number;
251
- newGenCount: number;
252
271
  }
253
272
 
254
273
  function readProtobufVarint(buf: Uint8Array, offset: number): [number, number] | undefined {
@@ -977,17 +996,14 @@ export async function readCurrentMaxSqliteGenIdx(
977
996
  }
978
997
  }
979
998
 
980
- /**
981
- * 以只读方式读取指定 `gen_metadata` 水位之后新产生的最新上游完整请求快照。
982
- * 若本地库不存在或无新生成,返回 `newGenCount: 0`;在 WAL 尚未完成落盘时支持短退避重试。
983
- */
984
- export async function readLatestSqliteUpstreamRequestSince(
999
+ /** 以只读方式按代次提取上游请求快照,WAL 尚未落盘时短暂重试。 */
1000
+ export async function readSqliteUpstreamRequestsSince(
985
1001
  config: BridgeConfig,
986
1002
  agySessionId: string,
987
1003
  afterGenIdx: number,
988
1004
  retryDelaysMs: readonly number[] = [20, 40],
989
1005
  ): Promise<SqliteUpstreamQueryResult> {
990
- const empty: SqliteUpstreamQueryResult = { maxGenIdx: afterGenIdx, newGenCount: 0 };
1006
+ const empty: SqliteUpstreamQueryResult = { maxGenIdx: afterGenIdx, snapshots: [] };
991
1007
  if (!agySessionId) return empty;
992
1008
  const dbPath = path.join(resolveAgyConversationsDir(config), `${agySessionId}.db`);
993
1009
  if (!fs.existsSync(dbPath)) return empty;
@@ -997,25 +1013,17 @@ export async function readLatestSqliteUpstreamRequestSince(
997
1013
  const probeOnce = (): SqliteUpstreamQueryResult => {
998
1014
  let db: import("node:sqlite").DatabaseSync | undefined;
999
1015
  try {
1000
- db = openSqliteWithTimeout(sqlite, dbPath, true, 300);
1001
- const meta = db
1002
- .prepare(
1003
- "SELECT COALESCE(MAX(idx), -1) AS maxIdx, COUNT(*) AS newCount FROM gen_metadata WHERE idx > ?",
1004
- )
1005
- .get(afterGenIdx) as { maxIdx?: number; newCount?: number } | undefined;
1006
- const newGenCount = Number(meta?.newCount ?? 0);
1007
- const maxGenIdx = typeof meta?.maxIdx === "number" ? meta.maxIdx : afterGenIdx;
1008
- if (newGenCount <= 0 || maxGenIdx <= afterGenIdx) {
1009
- return { maxGenIdx: afterGenIdx, newGenCount: 0 };
1016
+ db = openSqliteWithTimeout(sqlite, dbPath, true, 100);
1017
+ // 先读取索引,再逐条解析,避免同时加载多条可能含有大图的请求。
1018
+ const rows = db.prepare("SELECT idx FROM gen_metadata WHERE idx > ? ORDER BY idx").all(afterGenIdx) as { idx: number }[];
1019
+ const selectData = db.prepare("SELECT data FROM gen_metadata WHERE idx = ?");
1020
+ const snapshots: SqliteUpstreamRequestSnapshot[] = [];
1021
+ for (const { idx } of rows) {
1022
+ const row = selectData.get(idx) as { data?: Uint8Array | null } | undefined;
1023
+ const snapshot = row?.data?.length ? parseGenMetadataUpstreamRequest(row.data, idx) : undefined;
1024
+ if (snapshot) snapshots.push(snapshot);
1010
1025
  }
1011
- const latestRow = db
1012
- .prepare("SELECT idx, data FROM gen_metadata WHERE idx = ?")
1013
- .get(maxGenIdx) as { idx: number; data?: Uint8Array | null } | undefined;
1014
- const latest =
1015
- latestRow?.data && latestRow.data.byteLength > 0
1016
- ? parseGenMetadataUpstreamRequest(latestRow.data, latestRow.idx)
1017
- : undefined;
1018
- return { latest, maxGenIdx, newGenCount };
1026
+ return { snapshots, maxGenIdx: rows.at(-1)?.idx ?? afterGenIdx };
1019
1027
  } catch {
1020
1028
  return empty;
1021
1029
  } finally {
@@ -1028,15 +1036,11 @@ export async function readLatestSqliteUpstreamRequestSince(
1028
1036
  };
1029
1037
 
1030
1038
  const first = probeOnce();
1031
- if (first.latest || first.newGenCount > 0) {
1032
- return first;
1033
- }
1039
+ if (first.maxGenIdx > afterGenIdx) return first;
1034
1040
  for (const delay of retryDelaysMs) {
1035
1041
  await new Promise((r) => setTimeout(r, delay));
1036
1042
  const next = probeOnce();
1037
- if (next.latest || next.newGenCount > 0) {
1038
- return next;
1039
- }
1043
+ if (next.maxGenIdx > afterGenIdx) return next;
1040
1044
  }
1041
1045
  return empty;
1042
1046
  }
@@ -1110,6 +1114,14 @@ export async function waitForSqliteToolStepsSettled(
1110
1114
  }
1111
1115
  }
1112
1116
 
1117
+ function readSqliteWatermarks(db: import("node:sqlite").DatabaseSync): Omit<SqliteDbCheckpoint, "fingerprint"> {
1118
+ return db.prepare(`SELECT
1119
+ (SELECT COALESCE(MAX(idx) + 1, 0) FROM steps) AS steps,
1120
+ (SELECT COALESCE(MAX(idx) + 1, 0) FROM gen_metadata) AS generations,
1121
+ (SELECT COALESCE(MAX(idx) + 1, 0) FROM executor_metadata) AS executions
1122
+ `).get() as Omit<SqliteDbCheckpoint, "fingerprint">;
1123
+ }
1124
+
1113
1125
  /**
1114
1126
  * 以只读模式采集 AGY 会话 SQLite 数据库的当前高水位检查点。
1115
1127
  * 遇到文件不存在、WAL 锁冲突或跨版本表结构差异时静默返回 `undefined`。
@@ -1118,9 +1130,7 @@ export async function captureSqliteCheckpoint(
1118
1130
  config: BridgeConfig,
1119
1131
  agySessionId: string,
1120
1132
  ): Promise<SqliteDbCheckpoint | undefined> {
1121
- if (!config.enableSqliteFork || !agySessionId) {
1122
- return undefined;
1123
- }
1133
+ if (!agySessionId) return undefined;
1124
1134
  const dbPath = path.join(resolveAgyConversationsDir(config), `${agySessionId}.db`);
1125
1135
  if (!fs.existsSync(dbPath)) {
1126
1136
  return undefined;
@@ -1136,28 +1146,11 @@ export async function captureSqliteCheckpoint(
1136
1146
  return undefined;
1137
1147
  }
1138
1148
 
1139
- const stepsRow = db
1140
- .prepare("SELECT COALESCE(MAX(idx) + 1, 0) AS n FROM steps")
1141
- .get() as { n: number };
1142
- const genRow = db
1143
- .prepare("SELECT COALESCE(MAX(idx) + 1, 0) AS n FROM gen_metadata")
1144
- .get() as { n: number };
1145
- const execRow = db
1146
- .prepare("SELECT COALESCE(MAX(idx) + 1, 0) AS n FROM executor_metadata")
1147
- .get() as { n: number };
1148
-
1149
- const steps = Number(stepsRow?.n ?? 0);
1150
- if (steps <= 0) {
1151
- return undefined;
1152
- }
1153
-
1154
- const fingerprint = computeStepsPrefixFingerprint(db, steps);
1155
- return {
1156
- steps,
1157
- generations: Number(genRow?.n ?? 0),
1158
- executions: Number(execRow?.n ?? 0),
1159
- fingerprint,
1160
- };
1149
+ // 水位和步骤指纹取自同一个 WAL 读快照。
1150
+ db.exec("BEGIN");
1151
+ const watermarks = readSqliteWatermarks(db);
1152
+ if (watermarks.steps <= 0) return undefined;
1153
+ return { ...watermarks, fingerprint: computeStepsPrefixFingerprint(db, watermarks.steps) };
1161
1154
  } catch {
1162
1155
  return undefined;
1163
1156
  } finally {
@@ -1200,17 +1193,6 @@ export async function forkSqliteConversationAtCheckpoint(
1200
1193
  if (!verifyRequiredTables(srcDb)) {
1201
1194
  return undefined;
1202
1195
  }
1203
- const currentStepsRow = srcDb
1204
- .prepare("SELECT COALESCE(MAX(idx) + 1, 0) AS n FROM steps")
1205
- .get() as { n: number };
1206
- if (Number(currentStepsRow?.n ?? 0) < checkpoint.steps) {
1207
- return undefined;
1208
- }
1209
- const actualPrefixFp = computeStepsPrefixFingerprint(srcDb, checkpoint.steps);
1210
- if (actualPrefixFp !== checkpoint.fingerprint) {
1211
- return undefined;
1212
- }
1213
-
1214
1196
  srcDb.exec(`VACUUM INTO '${escapedTarget}'`);
1215
1197
  } catch {
1216
1198
  cleanupDbFilesSafe(targetDbPath);
@@ -1227,6 +1209,16 @@ export async function forkSqliteConversationAtCheckpoint(
1227
1209
  let dstDb: import("node:sqlite").DatabaseSync | undefined;
1228
1210
  try {
1229
1211
  dstDb = openSqliteWithTimeout(sqlite, targetDbPath, false);
1212
+ // 在副本上校验检查点,原库可以在复制期间继续接收写入。
1213
+ const watermarks = readSqliteWatermarks(dstDb);
1214
+ if (
1215
+ watermarks.steps < checkpoint.steps ||
1216
+ watermarks.generations < checkpoint.generations ||
1217
+ watermarks.executions < checkpoint.executions ||
1218
+ computeStepsPrefixFingerprint(dstDb, checkpoint.steps) !== checkpoint.fingerprint
1219
+ ) {
1220
+ throw new Error("SQLite 会话副本与历史检查点不匹配");
1221
+ }
1230
1222
  const origMeta = dstDb
1231
1223
  .prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1")
1232
1224
  .get() as { trajectory_id?: string } | undefined;
@@ -1250,17 +1242,18 @@ export async function forkSqliteConversationAtCheckpoint(
1250
1242
  return forkedSessionId;
1251
1243
  } catch {
1252
1244
  try {
1253
- dstDb?.exec("ROLLBACK");
1245
+ dstDb?.close();
1254
1246
  } catch {
1255
- // 忽略
1247
+ // 忽略关闭异常
1256
1248
  }
1249
+ dstDb = undefined;
1257
1250
  cleanupDbFilesSafe(targetDbPath);
1258
1251
  return undefined;
1259
1252
  } finally {
1260
1253
  try {
1261
1254
  dstDb?.close();
1262
1255
  } catch {
1263
- // 忽略
1256
+ // 忽略关闭异常
1264
1257
  }
1265
1258
  }
1266
1259
  }
@@ -24,6 +24,7 @@ import type {
24
24
  AcpPromptBlock,
25
25
  AcpPromptResponse,
26
26
  AcpPromptUsage,
27
+ AcpRequestPermissionParams,
27
28
  AcpSessionNewResult,
28
29
  AcpSessionResumeResult,
29
30
  AcpSessionUpdateNotification,
@@ -39,7 +40,6 @@ import {
39
40
  } from "../catalog/model-discovery.ts";
40
41
  import {
41
42
  type BridgeConfig,
42
- resolveAgyConversationsDir,
43
43
  resolveEffectiveFlags,
44
44
  type ToolMode,
45
45
  } from "../config.ts";
@@ -66,16 +66,18 @@ import {
66
66
  import {
67
67
  AGY_SESSION_ANCHOR_CUSTOM_TYPE,
68
68
  type AgySessionAnchor,
69
+ type SqliteUpstreamRequestSnapshot,
69
70
  appendPreloadedTurnsToSqliteConversation,
70
71
  captureSqliteCheckpoint,
71
72
  cloneTemplateSqliteConversationWithPreload,
72
73
  findBranchAnchorForHistory,
73
74
  forkSqliteConversationAtCheckpoint,
75
+ hasIncompleteSqliteConversationSchema,
74
76
  hasLocalConversationDb,
75
77
  hasValidAgentMetadataBlob,
76
78
  readCurrentMaxSqliteGenIdx,
77
79
  readCurrentMaxSqliteStepIdx,
78
- readLatestSqliteUpstreamRequestSince,
80
+ readSqliteUpstreamRequestsSince,
79
81
  readSqliteGenerationUsagesSince,
80
82
  readSqliteGenerationUsagesSinceWithRetry,
81
83
  waitForSqliteToolStepsSettled,
@@ -230,6 +232,7 @@ interface ActiveTurnPump {
230
232
  readonly queue: AsyncEventQueue<PumpQueueItem>;
231
233
  finished: boolean;
232
234
  cancelledByHoldTimeout: boolean;
235
+ permissionDeclined?: string;
233
236
  /** 本轮前序中间 `toolUse` 步已经记账的输出 Token 累计数 */
234
237
  accountedOutputTokens: number;
235
238
  /** 本轮已完成的中间 `toolUse` 推理步计数 */
@@ -285,6 +288,8 @@ interface ManagedSessionLedger {
285
288
  lastSelectedModelId?: string;
286
289
  /** 本次随 SQLite 多步预注入一起写入、尚未在下一条 `session/prompt` 的 `onPayload` 中通告的分片列表 */
287
290
  pendingPreloadedTurns?: readonly PreloadedSqliteTurn[];
291
+ /** 有历史待首条提示重放,完成前不能按热会话续接。 */
292
+ initialReplayPending: boolean;
288
293
  syncedMessageCount: number;
289
294
  syncedTranscriptDigest: string;
290
295
  /** 当前 AGY 会话实际承载的 `pi-traffic-optimization` 归档投影指纹与计数 */
@@ -377,7 +382,7 @@ export class TurnCoordinator {
377
382
 
378
383
  this.processManager.setHandlers({
379
384
  onSessionUpdate: (notification) => this.handleSessionUpdate(notification),
380
- onRequestPermission: (params) => this.mirrorBroker.handlePermissionRequest(params),
385
+ onRequestPermission: (params) => this.handlePermissionRequest(params),
381
386
  onElicitationCreate: (params) => this.mirrorBroker.handleElicitationRequest(params),
382
387
  });
383
388
  }
@@ -482,7 +487,7 @@ export class TurnCoordinator {
482
487
  }
483
488
 
484
489
  const settled = await this.waitForInFlightPrompt(ledger, 1_500);
485
- if (!settled || ledger.activePump || ledger.parkedCalls.size > 0) {
490
+ if (!settled || ledger.initialReplayPending || ledger.activePump || ledger.parkedCalls.size > 0) {
486
491
  return;
487
492
  }
488
493
 
@@ -1116,7 +1121,7 @@ export class TurnCoordinator {
1116
1121
  ledger: ManagedSessionLedger,
1117
1122
  visibleMessages: readonly (UserMessage | AssistantMessage | ToolResultMessage)[],
1118
1123
  ): AcpPromptBlock[] | undefined {
1119
- if (visibleMessages.length <= ledger.syncedMessageCount) {
1124
+ if (ledger.initialReplayPending || visibleMessages.length <= ledger.syncedMessageCount) {
1120
1125
  return undefined;
1121
1126
  }
1122
1127
  const prefix = visibleMessages.slice(0, ledger.syncedMessageCount);
@@ -1390,7 +1395,7 @@ export class TurnCoordinator {
1390
1395
  if (
1391
1396
  !ledger.conn.isAlive ||
1392
1397
  !ledger.conn.capabilities?.sessionCapabilities?.resume ||
1393
- !hasLocalConversationDb(this.currentConfig, ledger.agySessionId)
1398
+ (await readCurrentMaxSqliteStepIdx(this.currentConfig, ledger.agySessionId)) < 0
1394
1399
  ) {
1395
1400
  return false;
1396
1401
  }
@@ -1811,7 +1816,6 @@ export class TurnCoordinator {
1811
1816
  currentProjectionForMcp.projectionDigest === ledger.syncedProjectionDigest;
1812
1817
  const willCutInAny =
1813
1818
  willCutInForSteer || willCutInForToolsReload || willCutInForDeferredOutputs;
1814
- const hasUpstreamDb = this.isLocalSqliteUpstreamLikelyAvailable(ledger.agySessionId);
1815
1819
 
1816
1820
  if (options?.onResponse && settledMcpIds.length > 0) {
1817
1821
  const responseHeaders: Record<string, string> = {
@@ -1829,12 +1833,8 @@ export class TurnCoordinator {
1829
1833
  if (willCutInAny) {
1830
1834
  responseHeaders["x-acp-mcp-cutin"] = "1";
1831
1835
  }
1832
- if (hasUpstreamDb) {
1833
- responseHeaders["x-acp-upstream-pending"] = "1";
1834
- if (!willCutInAny) {
1835
- pump.awaitingUpstreamTelemetry = true;
1836
- }
1837
- }
1836
+ responseHeaders["x-acp-upstream-pending"] = "1";
1837
+ if (!willCutInAny) pump.awaitingUpstreamTelemetry = true;
1838
1838
  await options.onResponse(
1839
1839
  {
1840
1840
  status: 200,
@@ -2255,10 +2255,38 @@ export class TurnCoordinator {
2255
2255
  let sessionInfo: AcpSessionNewResult | undefined;
2256
2256
  let initialPromptBlocks: AcpPromptBlock[] | undefined;
2257
2257
  let appliedPreloadedTurns: readonly PreloadedSqliteTurn[] | undefined;
2258
+ let priorHistoryRestored = false;
2258
2259
  let syncedProjectionDigest = priorProjection.projectionDigest;
2259
2260
  let syncedProjectedCount = priorProjection.archivedCount;
2260
2261
 
2261
- // 路径 1:精确命中分支末尾锚点且未发生需同步的新一轮归档 GC -> 调用 session/resume 零历史回放开销恢复
2262
+ if (anchorMatch.kind === "exact" && conn.capabilities?.sessionCapabilities?.resume) {
2263
+ const { anchor } = anchorMatch;
2264
+ const saved = anchor.dbCheckpoint;
2265
+ if (saved) {
2266
+ const current = await captureSqliteCheckpoint(this.currentConfig, anchor.agySessionId);
2267
+ if (
2268
+ !current ||
2269
+ current.steps < saved.steps ||
2270
+ current.generations < saved.generations ||
2271
+ current.executions < saved.executions
2272
+ ) {
2273
+ anchorMatch = { kind: "none" };
2274
+ } else if (
2275
+ current.steps > saved.steps ||
2276
+ current.generations > saved.generations ||
2277
+ current.executions > saved.executions
2278
+ ) {
2279
+ // Pi 仍指向历史节点时,已有新写入的轨迹只能从旧检查点分叉。
2280
+ anchorMatch = this.currentConfig.enableSqliteFork ? { kind: "forkable", anchor } : { kind: "none" };
2281
+ } else if (current.fingerprint !== saved.fingerprint) {
2282
+ anchorMatch = { kind: "none" };
2283
+ }
2284
+ } else if (!anchor.importedRaw || (await readCurrentMaxSqliteStepIdx(this.currentConfig, anchor.agySessionId)) < 0) {
2285
+ // 无检查点的旧桥接锚点无法校验轨迹位置。原生导入仍读取非空源会话。
2286
+ anchorMatch = { kind: "none" };
2287
+ }
2288
+ }
2289
+
2262
2290
  if (
2263
2291
  anchorMatch.kind === "exact" &&
2264
2292
  conn.capabilities?.sessionCapabilities?.resume &&
@@ -2334,6 +2362,7 @@ export class TurnCoordinator {
2334
2362
  { timeoutMs: 20_000, signal: params.signal },
2335
2363
  );
2336
2364
  initialPromptBlocks = pendingPlan.finalPromptBlocks;
2365
+ priorHistoryRestored = true;
2337
2366
  syncedProjectionDigest = anchorMatch.anchor.projectionDigest ?? "";
2338
2367
  syncedProjectedCount = anchorMatch.anchor.projectedCount ?? 0;
2339
2368
  } catch (error) {
@@ -2457,15 +2486,26 @@ export class TurnCoordinator {
2457
2486
  }
2458
2487
 
2459
2488
  if (!sessionInfo || !initialPromptBlocks) {
2460
- sessionInfo = await conn.request<AcpSessionNewResult>(
2489
+ const openSession = () => conn.request<AcpSessionNewResult>(
2461
2490
  "session/new",
2462
- {
2463
- cwd: params.cwd,
2464
- mcpServers,
2465
- additionalDirectories: addDirs,
2466
- },
2491
+ { cwd: params.cwd, mcpServers, additionalDirectories: addDirs },
2467
2492
  { timeoutMs: 25_000, signal: params.signal },
2468
2493
  );
2494
+ sessionInfo = await openSession();
2495
+ if (!params.signal?.aborted && await hasIncompleteSqliteConversationSchema(this.currentConfig, sessionInfo.sessionId)) {
2496
+ // agy 建表失败时仍可能返回 sessionId。首条用户请求发出前最多重建一次。
2497
+ const incompleteSessionId = sessionInfo.sessionId;
2498
+ try {
2499
+ sessionInfo = await openSession();
2500
+ await conn.closeSessionSafe(incompleteSessionId);
2501
+ } catch (error) {
2502
+ if (params.signal?.aborted) {
2503
+ void conn.closeSessionSafe(incompleteSessionId);
2504
+ throw error;
2505
+ }
2506
+ // 首个会话仍可对话,后端重建失败时沿用现有会话。
2507
+ }
2508
+ }
2469
2509
  initialPromptBlocks =
2470
2510
  replayPlan.preloadedTurns.length > 0
2471
2511
  ? replayPlan.singleStepFallbackBlocks
@@ -2511,6 +2551,7 @@ export class TurnCoordinator {
2511
2551
  configOptions: sessionInfo.configOptions ?? [],
2512
2552
  availableModels: sessionInfo.models?.availableModels ?? [],
2513
2553
  pendingPreloadedTurns: appliedPreloadedTurns,
2554
+ initialReplayPending: priorHistory.length > 0 && !priorHistoryRestored,
2514
2555
  syncedMessageCount: priorHistory.length,
2515
2556
  syncedTranscriptDigest: computeTranscriptDigest(priorHistory),
2516
2557
  syncedProjectionDigest,
@@ -2708,38 +2749,13 @@ export class TurnCoordinator {
2708
2749
 
2709
2750
  const preloadedTurns = ledger.pendingPreloadedTurns;
2710
2751
  ledger.pendingPreloadedTurns = undefined;
2711
- let outboundPayload: {
2712
- sessionId: string;
2713
- prompt: AcpPromptBlock[];
2714
- preloadedTurns?: readonly PreloadedSqliteTurn[];
2715
- } = {
2752
+ const outboundPayload = {
2716
2753
  sessionId: ledger.agySessionId,
2717
- prompt: promptBlocks.length > 0 ? promptBlocks : [{ type: "text", text: "Continue." }],
2718
- ...(preloadedTurns && preloadedTurns.length > 0 ? { preloadedTurns } : {}),
2754
+ prompt: promptBlocks.length > 0 ? promptBlocks : [{ type: "text" as const, text: "Continue." }],
2755
+ ...(preloadedTurns?.length ? { preloadedTurns } : {}),
2719
2756
  };
2720
-
2721
- if (options?.onPayload) {
2722
- const replaced = await options.onPayload(outboundPayload, model);
2723
- if (
2724
- replaced &&
2725
- typeof replaced === "object" &&
2726
- "prompt" in (replaced as Record<string, unknown>)
2727
- ) {
2728
- outboundPayload = replaced as typeof outboundPayload;
2729
- }
2730
- }
2731
-
2732
- if (options?.signal?.aborted || writer.isTerminated) {
2733
- if (!writer.isTerminated) {
2734
- writer.fail("aborted", "Request aborted by user");
2735
- }
2736
- return;
2737
- }
2738
-
2739
2757
  const currentProjection = inspectTrafficOptProjectionState(visibleMessagesBeforeAssistant);
2740
- const isProjectionSynced =
2741
- currentProjection.projectionDigest === ledger.syncedProjectionDigest;
2742
- const willReportUpstream = this.isLocalSqliteUpstreamLikelyAvailable(ledger.agySessionId);
2758
+ const isProjectionSynced = currentProjection.projectionDigest === ledger.syncedProjectionDigest;
2743
2759
 
2744
2760
  const pump: ActiveTurnPump = {
2745
2761
  queue: new AsyncEventQueue<PumpQueueItem>(),
@@ -2752,32 +2768,11 @@ export class TurnCoordinator {
2752
2768
  emittedMcpCallIds: new Set<string>(),
2753
2769
  deferredMcpOutputs: [],
2754
2770
  autoContinuedTurnCount: 0,
2755
- awaitingUpstreamTelemetry: willReportUpstream,
2771
+ awaitingUpstreamTelemetry: false,
2756
2772
  lastStepProjectionSynced: isProjectionSynced,
2757
2773
  lastStepUsedSlicePool: false,
2758
2774
  };
2759
- ledger.activePump = pump;
2760
- this.startTrackedSessionPrompt(ledger, pump, {
2761
- sessionId: outboundPayload.sessionId,
2762
- prompt: outboundPayload.prompt,
2763
- });
2764
-
2765
- if (options?.onResponse) {
2766
- const headers: Record<string, string> = {
2767
- "x-acp-session-id": ledger.agySessionId,
2768
- "x-acp-projection-synced": isProjectionSynced ? "1" : "0",
2769
- };
2770
- if (willReportUpstream) {
2771
- headers["x-acp-upstream-pending"] = "1";
2772
- }
2773
- await options.onResponse(
2774
- {
2775
- status: 200,
2776
- headers,
2777
- },
2778
- model,
2779
- );
2780
- }
2775
+ if (!(await this.startObservedSessionPrompt(ledger, pump, outboundPayload, writer, model, options))) return;
2781
2776
 
2782
2777
  writer.ensureStarted();
2783
2778
 
@@ -2788,6 +2783,58 @@ export class TurnCoordinator {
2788
2783
  }
2789
2784
  }
2790
2785
 
2786
+ private async handlePermissionRequest(params: AcpRequestPermissionParams) {
2787
+ const pump = this.ledgersByAgyId.get(params.sessionId)?.activePump;
2788
+ const canPrompt = this.activeContext?.hasUI ?? false;
2789
+ const result = await this.mirrorBroker.handlePermissionRequest(params);
2790
+ const selection = result.outcome;
2791
+ const rejected = selection.outcome === "cancelled" || params.options.some(
2792
+ (option) => option.optionId === selection.optionId &&
2793
+ (option.kind === "reject_once" || option.kind === "reject_always"),
2794
+ );
2795
+ if (pump && rejected) {
2796
+ const title = params.toolCall?.title ?? "Antigravity 工具";
2797
+ pump.permissionDeclined = canPrompt
2798
+ ? `工具未获批准:${title}`
2799
+ : `「${title}」需要批准。请在 Pi 交互模式中重试并确认。`;
2800
+ }
2801
+ return result;
2802
+ }
2803
+
2804
+ private async startObservedSessionPrompt(
2805
+ ledger: ManagedSessionLedger,
2806
+ pump: ActiveTurnPump,
2807
+ payload: { sessionId: string; prompt: AcpPromptBlock[]; preloadedTurns?: readonly PreloadedSqliteTurn[] },
2808
+ writer: StepStreamWriter,
2809
+ model: Model<Api>,
2810
+ options?: SimpleStreamOptions,
2811
+ ): Promise<boolean> {
2812
+ const replaced = await options?.onPayload?.(payload, model);
2813
+ if (replaced && typeof replaced === "object" && "prompt" in replaced) {
2814
+ payload = replaced as typeof payload;
2815
+ }
2816
+ if (options?.signal?.aborted || writer.isTerminated) {
2817
+ if (!writer.isTerminated) writer.fail("aborted", "Request aborted by user");
2818
+ return false;
2819
+ }
2820
+ ledger.activePump = pump;
2821
+ const { sessionId, prompt } = payload;
2822
+ this.startTrackedSessionPrompt(ledger, pump, { sessionId, prompt });
2823
+ if (options?.onResponse) {
2824
+ // 轨迹库可能直到收到 prompt 才出现。本地载荷先暂存到观测结束。
2825
+ pump.awaitingUpstreamTelemetry = true;
2826
+ await options.onResponse({
2827
+ status: 200,
2828
+ headers: {
2829
+ "x-acp-session-id": ledger.agySessionId,
2830
+ "x-acp-projection-synced": pump.lastStepProjectionSynced ? "1" : "0",
2831
+ "x-acp-upstream-pending": "1",
2832
+ },
2833
+ }, model);
2834
+ }
2835
+ return true;
2836
+ }
2837
+
2791
2838
  private async consumePumpForSingleStep(
2792
2839
  ledger: ManagedSessionLedger,
2793
2840
  pump: ActiveTurnPump,
@@ -2980,7 +3027,10 @@ export class TurnCoordinator {
2980
3027
  model.contextWindow = ledger.windowSize;
2981
3028
  }
2982
3029
 
2983
- if (item.response.stopReason === "cancelled" && signal?.aborted) {
3030
+ if (item.response.stopReason === "cancelled") {
3031
+ if (!signal?.aborted) {
3032
+ await this.emitUpstreamTelemetryForStep(ledger, pump, model, options, { status: 499 });
3033
+ }
2984
3034
  ledger.activePump = undefined;
2985
3035
  writer.fail("aborted", "Request aborted");
2986
3036
  return;
@@ -2994,6 +3044,13 @@ export class TurnCoordinator {
2994
3044
  return;
2995
3045
  }
2996
3046
 
3047
+ if (pump.permissionDeclined && !writer.message.content.some((b) => b.type === "text" && b.text.trim())) {
3048
+ await this.emitUpstreamTelemetryForStep(ledger, pump, model, options, { status: 403 });
3049
+ ledger.activePump = undefined;
3050
+ writer.fail("error", pump.permissionDeclined);
3051
+ return;
3052
+ }
3053
+
2997
3054
  // 当单次连续工具循环触及 agy 单轮最大生成次数限制(max_turn_requests)时,在同一热会话上自动无感续接
2998
3055
  if (
2999
3056
  ledger.toolMode === "pi-tools" &&
@@ -3001,14 +3058,16 @@ export class TurnCoordinator {
3001
3058
  !signal?.aborted &&
3002
3059
  pump.autoContinuedTurnCount < MAX_AUTO_CONTINUED_TURN_REQUESTS
3003
3060
  ) {
3061
+ // 先结算当前请求。后续请求缺少快照时只回退其自身的本地载荷。
3062
+ await this.emitUpstreamTelemetryForStep(ledger, pump, model, options, { status: 200 });
3063
+ if (signal?.aborted || writer.isTerminated) return;
3004
3064
  pump.autoContinuedTurnCount++;
3005
- if (this.isLocalSqliteUpstreamLikelyAvailable(ledger.agySessionId)) {
3006
- pump.awaitingUpstreamTelemetry = true;
3007
- }
3008
- this.startTrackedSessionPrompt(ledger, pump, {
3065
+ pump.lastStepUsedSlicePool = false;
3066
+ const started = await this.startObservedSessionPrompt(ledger, pump, {
3009
3067
  sessionId: ledger.agySessionId,
3010
3068
  prompt: [{ type: "text", text: "Continue from where you left off." }],
3011
- });
3069
+ }, writer, model, options);
3070
+ if (!started) return;
3012
3071
  continue;
3013
3072
  }
3014
3073
 
@@ -3069,46 +3128,39 @@ export class TurnCoordinator {
3069
3128
  model: Model<Api>,
3070
3129
  options: SimpleStreamOptions | undefined,
3071
3130
  ): Promise<void> {
3072
- if (!hasLocalConversationDb(this.currentConfig, ledger.agySessionId)) {
3073
- return;
3074
- }
3075
- const query = await readLatestSqliteUpstreamRequestSince(
3131
+ if (!options?.onResponse || !hasLocalConversationDb(this.currentConfig, ledger.agySessionId)) return;
3132
+ const query = await readSqliteUpstreamRequestsSince(
3076
3133
  this.currentConfig,
3077
3134
  ledger.agySessionId,
3078
3135
  ledger.lastReportedUpstreamGenIdx,
3079
3136
  [],
3080
3137
  );
3081
- if (query.newGenCount <= 0) {
3082
- return;
3083
- }
3084
- ledger.lastReportedUpstreamGenIdx = Math.max(
3085
- ledger.lastReportedUpstreamGenIdx,
3086
- query.maxGenIdx,
3087
- );
3088
- if (query.latest && options?.onResponse) {
3089
- await options.onResponse(
3090
- {
3091
- status: 499,
3092
- headers: {
3093
- "x-acp-session-id": ledger.agySessionId,
3094
- "x-acp-transport": "acp-upstream",
3095
- "x-acp-upstream-detached": "1",
3096
- "x-acp-upstream-gen-count": String(Math.max(1, query.newGenCount)),
3097
- "x-acp-upstream-snapshot": JSON.stringify(query.latest),
3098
- },
3099
- },
3100
- model,
3101
- );
3102
- }
3138
+ ledger.lastReportedUpstreamGenIdx = query.maxGenIdx;
3139
+ await this.emitUpstreamSnapshots(query.snapshots, 499, {
3140
+ "x-acp-session-id": ledger.agySessionId,
3141
+ "x-acp-upstream-detached": "1",
3142
+ }, model, options.onResponse);
3103
3143
  }
3104
3144
 
3105
- private isLocalSqliteUpstreamLikelyAvailable(agySessionId: string): boolean {
3106
- if (!agySessionId) return false;
3107
- if (hasLocalConversationDb(this.currentConfig, agySessionId)) return true;
3108
- try {
3109
- return fs.existsSync(resolveAgyConversationsDir(this.currentConfig));
3110
- } catch {
3111
- return false;
3145
+ private async emitUpstreamSnapshots(
3146
+ snapshots: readonly SqliteUpstreamRequestSnapshot[],
3147
+ status: number,
3148
+ headers: Record<string, string>,
3149
+ model: Model<Api>,
3150
+ onResponse: NonNullable<SimpleStreamOptions["onResponse"]>,
3151
+ ): Promise<void> {
3152
+ for (const [index, snapshot] of snapshots.entries()) {
3153
+ const isLast = index === snapshots.length - 1;
3154
+ await onResponse({
3155
+ status: isLast ? status : 200,
3156
+ headers: {
3157
+ ...headers,
3158
+ "x-acp-transport": "acp-upstream",
3159
+ "x-acp-model-id": model.id,
3160
+ "x-acp-upstream-snapshot": JSON.stringify(snapshot),
3161
+ ...(!isLast ? { "x-acp-upstream-intermediate": "1" } : {}),
3162
+ },
3163
+ }, model);
3112
3164
  }
3113
3165
  }
3114
3166
 
@@ -3140,37 +3192,21 @@ export class TurnCoordinator {
3140
3192
  : pump.hasSqliteGenTelemetry
3141
3193
  ? [15]
3142
3194
  : [20, 40];
3195
+ const lastGenIdx = ledger.lastReportedUpstreamGenIdx;
3143
3196
  const query = hasDb
3144
- ? await readLatestSqliteUpstreamRequestSince(
3145
- this.currentConfig,
3146
- ledger.agySessionId,
3147
- ledger.lastReportedUpstreamGenIdx,
3148
- retryDelays,
3149
- )
3150
- : { maxGenIdx: ledger.lastReportedUpstreamGenIdx, newGenCount: 0 };
3197
+ ? await readSqliteUpstreamRequestsSince(this.currentConfig, ledger.agySessionId, lastGenIdx, retryDelays)
3198
+ : { maxGenIdx: lastGenIdx, snapshots: [] };
3199
+ ledger.lastReportedUpstreamGenIdx = query.maxGenIdx;
3151
3200
 
3152
- if (query.latest) {
3153
- ledger.lastReportedUpstreamGenIdx = Math.max(
3154
- ledger.lastReportedUpstreamGenIdx,
3155
- query.maxGenIdx,
3156
- );
3157
- await options.onResponse(
3158
- {
3159
- status: params.status,
3160
- headers: {
3161
- "x-acp-session-id": ledger.agySessionId,
3162
- "x-acp-transport": "acp-upstream",
3163
- "x-acp-projection-synced": projectionHeader,
3164
- "x-acp-upstream-gen-count": String(Math.max(1, query.newGenCount)),
3165
- "x-acp-upstream-snapshot": JSON.stringify(query.latest),
3166
- },
3167
- },
3168
- model,
3169
- );
3201
+ if (query.snapshots.length > 0) {
3202
+ await this.emitUpstreamSnapshots(query.snapshots, params.status, {
3203
+ "x-acp-session-id": ledger.agySessionId,
3204
+ "x-acp-projection-synced": projectionHeader,
3205
+ }, model, options.onResponse);
3170
3206
  return;
3171
3207
  }
3172
3208
 
3173
- if (query.newGenCount === 0 && pump.lastStepUsedSlicePool) {
3209
+ if (query.maxGenIdx === lastGenIdx && pump.lastStepUsedSlicePool) {
3174
3210
  await options.onResponse(
3175
3211
  {
3176
3212
  status: params.status,
@@ -3614,6 +3650,7 @@ export class TurnCoordinator {
3614
3650
  return;
3615
3651
  }
3616
3652
  const full = [...priorMessages, finalAssistantMessage];
3653
+ ledger.initialReplayPending = false;
3617
3654
  ledger.syncedMessageCount = full.length;
3618
3655
  ledger.syncedTranscriptDigest = computeTranscriptDigest(full);
3619
3656
  }
@@ -3777,110 +3814,45 @@ export class TurnCoordinator {
3777
3814
  }
3778
3815
  return;
3779
3816
  }
3780
- const auxWillReportUpstream =
3781
- this.isLocalSqliteUpstreamLikelyAvailable(tempSessionId);
3782
- if (options?.onResponse) {
3783
- const auxHeaders: Record<string, string> = {
3784
- "x-acp-session-id": tempSessionId,
3785
- "x-acp-auxiliary": "1",
3786
- };
3787
- if (auxWillReportUpstream) {
3788
- auxHeaders["x-acp-upstream-pending"] = "1";
3789
- }
3790
- await options.onResponse(
3791
- {
3792
- status: 200,
3793
- headers: auxHeaders,
3794
- },
3795
- model,
3796
- );
3797
- }
3817
+ const auxHeaders = { "x-acp-session-id": tempSessionId, "x-acp-auxiliary": "1" };
3818
+ await options?.onResponse?.({
3819
+ status: 200,
3820
+ headers: { ...auxHeaders, "x-acp-upstream-pending": "1" },
3821
+ }, model);
3798
3822
  writer.ensureStarted();
3823
+ const reportAuxiliaryUpstream = async (status: number, retryDelays: number[]) => {
3824
+ if (!options?.onResponse) return;
3825
+ const { snapshots } = await readSqliteUpstreamRequestsSince(
3826
+ this.currentConfig, tempSessionId, -1, retryDelays,
3827
+ );
3828
+ if (snapshots.length > 0) {
3829
+ await this.emitUpstreamSnapshots(snapshots, status, auxHeaders, model, options.onResponse);
3830
+ } else {
3831
+ await options.onResponse({
3832
+ status,
3833
+ headers: { ...auxHeaders, "x-acp-transport": "acp-upstream-unavailable" },
3834
+ }, model);
3835
+ }
3836
+ };
3799
3837
  let promptRes: AcpPromptResponse;
3800
3838
  try {
3801
3839
  promptRes = await conn.request<AcpPromptResponse>(
3802
3840
  "session/prompt",
3803
- {
3804
- sessionId: auxOutboundPayload.sessionId,
3805
- prompt: auxOutboundPayload.prompt,
3806
- },
3841
+ { sessionId: auxOutboundPayload.sessionId, prompt: auxOutboundPayload.prompt },
3807
3842
  { signal: options?.signal },
3808
3843
  );
3809
3844
  } catch (auxError) {
3810
- if (options?.onResponse && auxWillReportUpstream) {
3811
- const auxErrMsg =
3812
- auxError instanceof Error ? auxError.message : String(auxError);
3813
- const statusMatch = /\b([45]\d\d)\b/.exec(auxErrMsg);
3814
- const auxStatus = statusMatch ? Number(statusMatch[1]) : 500;
3815
- const auxQuery = await readLatestSqliteUpstreamRequestSince(
3816
- this.currentConfig,
3817
- tempSessionId,
3818
- -1,
3819
- [],
3820
- );
3821
- await options.onResponse(
3822
- {
3823
- status: auxStatus,
3824
- headers: auxQuery.latest
3825
- ? {
3826
- "x-acp-session-id": tempSessionId,
3827
- "x-acp-auxiliary": "1",
3828
- "x-acp-transport": "acp-upstream",
3829
- "x-acp-upstream-gen-count": String(Math.max(1, auxQuery.newGenCount)),
3830
- "x-acp-upstream-snapshot": JSON.stringify(auxQuery.latest),
3831
- }
3832
- : {
3833
- "x-acp-session-id": tempSessionId,
3834
- "x-acp-auxiliary": "1",
3835
- "x-acp-transport": "acp-upstream-unavailable",
3836
- },
3837
- },
3838
- model,
3839
- );
3840
- }
3845
+ const message = auxError instanceof Error ? auxError.message : String(auxError);
3846
+ const statusMatch = /\b([45]\d\d)\b/.exec(message);
3847
+ await reportAuxiliaryUpstream(statusMatch ? Number(statusMatch[1]) : 500, []);
3841
3848
  throw auxError;
3842
3849
  }
3843
- if (options?.onResponse && auxWillReportUpstream) {
3844
- const auxStatus = detectedQuotaErr
3845
- ? 429
3846
- : promptRes.stopReason === "refusal"
3847
- ? 400
3848
- : 200;
3849
- const auxQuery = await readLatestSqliteUpstreamRequestSince(
3850
- this.currentConfig,
3851
- tempSessionId,
3852
- -1,
3853
- [20, 40],
3854
- );
3855
- if (auxQuery.latest) {
3856
- await options.onResponse(
3857
- {
3858
- status: auxStatus,
3859
- headers: {
3860
- "x-acp-session-id": tempSessionId,
3861
- "x-acp-auxiliary": "1",
3862
- "x-acp-transport": "acp-upstream",
3863
- "x-acp-upstream-gen-count": String(Math.max(1, auxQuery.newGenCount)),
3864
- "x-acp-upstream-snapshot": JSON.stringify(auxQuery.latest),
3865
- },
3866
- },
3867
- model,
3868
- );
3869
- } else {
3870
- await options.onResponse(
3871
- {
3872
- status: auxStatus,
3873
- headers: {
3874
- "x-acp-session-id": tempSessionId,
3875
- "x-acp-auxiliary": "1",
3876
- "x-acp-transport": "acp-upstream-unavailable",
3877
- },
3878
- },
3879
- model,
3880
- );
3881
- }
3882
- }
3883
- await cleanupTempSession();
3850
+ let status = 200;
3851
+ if (detectedQuotaErr) status = 429;
3852
+ else if (promptRes.stopReason === "cancelled") status = 499;
3853
+ else if (promptRes.stopReason === "refusal") status = 400;
3854
+ await reportAuxiliaryUpstream(status, [20, 40]);
3855
+
3884
3856
  if (detectedQuotaErr) {
3885
3857
  writer.fail("error", `Antigravity quota exhausted (429): ${detectedQuotaErr}`);
3886
3858
  return;
@@ -3893,6 +3865,8 @@ export class TurnCoordinator {
3893
3865
  writer.fail("error", "Model refused the request");
3894
3866
  return;
3895
3867
  }
3868
+ // 成功结果交回 Pi 前收好临时会话,避免下一次压缩看到尚未清理的快照。
3869
+ await cleanupTempSession();
3896
3870
  const { quotaError } = writer.finishTurn(promptRes.stopReason, promptRes.usage);
3897
3871
  if (quotaError) {
3898
3872
  writer.fail("error", `Antigravity quota exhausted (429): ${quotaError}`);
@@ -504,8 +504,8 @@ export class AgyTurnMirrorBroker {
504
504
  return { outcome: { outcome: "cancelled" } };
505
505
  }
506
506
 
507
- const idx = labels.indexOf(selectedLabel);
508
- const chosen = idx >= 0 ? params.options[idx] : params.options[0];
507
+ const chosen = params.options[labels.indexOf(selectedLabel)];
508
+ if (!chosen) return { outcome: { outcome: "cancelled" } };
509
509
  return {
510
510
  outcome: {
511
511
  outcome: "selected",