pi-antigravity-bridge 0.1.15 → 0.1.17

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,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [Unreleased]
4
+
5
+ ## [0.1.17] - 2026-11-28
6
+
7
+ ### Fixed
8
+
9
+ - 修复会话恢复时长命令输出、文件读取结果和工具调用参数被提前截断的问题。回放在上下文预算内保留这些内容和 Pi 已保存的可见思考文本。
10
+
11
+ ## [0.1.16] - 2026-11-25
12
+
13
+ ### Fixed
14
+
15
+ - 工具审批未完成导致回复为空时,Pi 会提示需要确认或未获批准的原因。
16
+ - 修复会话数据库初始化失败后首条消息仍发往故障会话的问题。恢复没有持久化记录的会话时,保留 Pi 的对话历史。
17
+ - 修复回到旧分支时混入其他分支对话的问题。
18
+ - 修复后端取消被显示为成功,以及发送前中断后续聊丢失历史的问题。
19
+ - 修复自动续接或会话数据库延迟创建时的流量漏记和重计。
20
+
3
21
  ## [0.1.15] - 2026-11-24
4
22
 
5
23
  ### 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.17",
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
  }
@@ -318,11 +318,10 @@ const MAX_PRELOAD_TOTAL_HISTORY_BYTES = 2_400_000;
318
318
  const MAX_FRESH_REPLAY_HISTORY_IMAGES = 6;
319
319
  /** 每张内联图片在单步预算中预留的保守 token 占位 */
320
320
  const ESTIMATED_IMAGE_BLOCK_TOKENS = 1_000;
321
+ // 单步剩余预算装不下完整条目时,保留头尾供公开协议降级使用。
321
322
  const MAX_SINGLE_REPLAY_TOOL_TEXT_BYTES = 4_000;
323
+ const MAX_SINGLE_REPLAY_TOOL_ARGS_BYTES = 2_000;
322
324
  const MAX_SINGLE_REPLAY_MESSAGE_TEXT_BYTES = 16_000;
323
- /** 多步预注入模式下允许保留更完整的单条历史消息与工具输出 */
324
- const MAX_PRELOAD_SINGLE_TOOL_TEXT_BYTES = 16_000;
325
- const MAX_PRELOAD_SINGLE_MESSAGE_TEXT_BYTES = 48_000;
326
325
 
327
326
  /** 写入本地新建 SQLite 会话的一对预注入历史步(严格满足 `user -> assistant` 交替角色约束) */
328
327
  export interface PreloadedSqliteTurn {
@@ -552,42 +551,27 @@ export function splitTextToSafeChunks(
552
551
  return chunks;
553
552
  }
554
553
 
555
- interface SerializedReplayEntry {
556
- blocks: AcpPromptBlock[];
557
- textBytes: number;
558
- tokens: number;
559
- }
560
-
561
554
  function serializeReplayHistoryEntry(
562
555
  msg: UserMessage | AssistantMessage | ToolResultMessage,
563
- limits: {
564
- maxMessageBytes: number;
565
- maxToolBytes: number;
566
- } = {
567
- maxMessageBytes: MAX_SINGLE_REPLAY_MESSAGE_TEXT_BYTES,
568
- maxToolBytes: MAX_SINGLE_REPLAY_TOOL_TEXT_BYTES,
569
- },
570
- ): SerializedReplayEntry {
556
+ truncateForFallback = false,
557
+ ): AcpPromptBlock[] {
571
558
  const entryBlocks: AcpPromptBlock[] = [];
559
+ const serializeText = (text: string, maxBytes: number, marker: string): string =>
560
+ truncateForFallback ? truncateUtf8Middle(text, maxBytes, marker) : text;
572
561
 
573
562
  if (msg.role === "user") {
563
+ const serializeUserText = (text: string) => serializeText(
564
+ text,
565
+ MAX_SINGLE_REPLAY_MESSAGE_TEXT_BYTES,
566
+ "\n...[earlier user text truncated in replay]...\n",
567
+ );
574
568
  if (typeof msg.content === "string") {
575
- const trimmed = truncateUtf8Middle(
576
- msg.content,
577
- limits.maxMessageBytes,
578
- "\n...[earlier user text truncated in replay]...\n",
579
- );
580
- entryBlocks.push({ type: "text", text: `<user>\n${trimmed}\n</user>` });
569
+ entryBlocks.push({ type: "text", text: `<user>\n${serializeUserText(msg.content)}\n</user>` });
581
570
  } else {
582
571
  entryBlocks.push({ type: "text", text: "<user>" });
583
572
  for (const part of msg.content) {
584
573
  if (part.type === "text") {
585
- const trimmed = truncateUtf8Middle(
586
- part.text,
587
- limits.maxMessageBytes,
588
- "\n...[earlier user text truncated in replay]...\n",
589
- );
590
- entryBlocks.push({ type: "text", text: trimmed });
574
+ entryBlocks.push({ type: "text", text: serializeUserText(part.text) });
591
575
  } else if (part.type === "image") {
592
576
  entryBlocks.push({ type: "image", data: part.data, mimeType: part.mimeType });
593
577
  }
@@ -598,17 +582,21 @@ function serializeReplayHistoryEntry(
598
582
  const segs: string[] = [];
599
583
  for (const part of msg.content) {
600
584
  if (part.type === "text" && part.text.trim()) {
601
- segs.push(
602
- truncateUtf8Middle(
603
- part.text,
604
- limits.maxMessageBytes,
605
- "\n...[assistant text truncated in replay]...\n",
606
- ),
585
+ segs.push(serializeText(
586
+ part.text,
587
+ MAX_SINGLE_REPLAY_MESSAGE_TEXT_BYTES,
588
+ "\n...[assistant text truncated in replay]...\n",
589
+ ));
590
+ } else if (part.type === "thinking" && !part.redacted && part.thinking.trim()) {
591
+ const thinking = serializeText(
592
+ part.thinking,
593
+ MAX_SINGLE_REPLAY_MESSAGE_TEXT_BYTES,
594
+ "\n...[assistant thinking truncated in replay]...\n",
607
595
  );
596
+ segs.push(`<thinking>\n${thinking}\n</thinking>`);
608
597
  } else if (part.type === "toolCall") {
609
- const rawArgs = JSON.stringify(part.arguments);
610
- const safeArgs = truncateUtf8Middle(rawArgs, 2_000, "...[truncated]...");
611
- segs.push(`<tool_call id="${part.id}" name="${part.name}">${safeArgs}</tool_call>`);
598
+ const args = serializeText(JSON.stringify(part.arguments), MAX_SINGLE_REPLAY_TOOL_ARGS_BYTES, "...[truncated]...");
599
+ segs.push(`<tool_call id="${part.id}" name="${part.name}">${args}</tool_call>`);
612
600
  }
613
601
  }
614
602
  if (segs.length > 0) {
@@ -626,9 +614,9 @@ function serializeReplayHistoryEntry(
626
614
  // 对 pi-traffic-optimization 已生成的紧凑 ctx:// 归档占位符保留原文不裁切,确保 handle 与 context_recall 指引完整
627
615
  let cappedTexts = isTrafficOptToolPlaceholder(rawTexts)
628
616
  ? rawTexts
629
- : truncateUtf8Middle(
617
+ : serializeText(
630
618
  rawTexts,
631
- limits.maxToolBytes,
619
+ MAX_SINGLE_REPLAY_TOOL_TEXT_BYTES,
632
620
  "\n...[tool output truncated in replay]...\n",
633
621
  );
634
622
  // 若仅单图归档的工具结果因正文过长被截断,补回被裁掉的 ctx://image/ 归档句柄行,避免模型丢失图片引用
@@ -651,15 +639,47 @@ function serializeReplayHistoryEntry(
651
639
  }
652
640
  }
653
641
 
654
- let textBytes = 0;
655
- let tokens = 0;
656
- for (const b of entryBlocks) {
657
- if (b.type === "text") {
658
- textBytes += Buffer.byteLength(b.text, "utf8") + 1;
659
- tokens += estimateStepTokens(b.text) + 1;
642
+ return entryBlocks;
643
+ }
644
+
645
+ /** 从最近历史开始使用剩余单步预算,优先保留完整条目。 */
646
+ function selectSingleStepReplayHistory(
647
+ history: readonly (UserMessage | AssistantMessage | ToolResultMessage)[],
648
+ maxBytes: number,
649
+ maxTokens: number,
650
+ ): { blocks: AcpPromptBlock[]; omittedCount: number; truncated: boolean } {
651
+ const selected: AcpPromptBlock[][] = [];
652
+ let usedImages = 0;
653
+ let omittedCount = 0;
654
+ let truncated = false;
655
+ for (let i = history.length - 1; i >= 0; i--) {
656
+ let fitted = false;
657
+ for (const truncateEntry of [false, true]) {
658
+ let entryImages = 0;
659
+ const blocks = serializeReplayHistoryEntry(history[i], truncateEntry).map((block): AcpPromptBlock => {
660
+ if (block.type !== "image") return block;
661
+ if (usedImages + entryImages < MAX_FRESH_REPLAY_HISTORY_IMAGES) {
662
+ entryImages++;
663
+ return block;
664
+ }
665
+ return { type: "text", text: `[earlier ${block.mimeType} image omitted in replay]` };
666
+ });
667
+ const size = measurePromptBlocksSize(blocks);
668
+ if (size.bytes > maxBytes || size.tokens > maxTokens) continue;
669
+ selected.push(blocks);
670
+ maxBytes -= size.bytes;
671
+ maxTokens -= size.tokens;
672
+ usedImages += entryImages;
673
+ truncated ||= truncateEntry;
674
+ fitted = true;
675
+ break;
676
+ }
677
+ if (!fitted) {
678
+ omittedCount = i + 1;
679
+ break;
660
680
  }
661
681
  }
662
- return { blocks: entryBlocks, textBytes, tokens };
682
+ return { blocks: selected.reverse().flat(), omittedCount, truncated };
663
683
  }
664
684
 
665
685
  function splitHistoryAndActiveTail(
@@ -907,75 +927,31 @@ export function buildFreshReplayPlan(options: FreshReplayPlanOptions): FreshRepl
907
927
  maxStepTokens - fallbackWsTokens - safeTailMeasured.tokens - wrapperTokens,
908
928
  );
909
929
 
910
- let singleStepOmittedCount = 0;
930
+ const singleStepHistory = selectSingleStepReplayHistory(
931
+ tailRequiredShrinkInSingleStep ? [] : historySlice,
932
+ availSingleHistoryBytes,
933
+ availSingleHistoryTokens,
934
+ );
911
935
  const singleStepFallbackBlocks: AcpPromptBlock[] = [];
912
936
  if (fallbackWorkspaceText) {
913
937
  singleStepFallbackBlocks.push({ type: "text", text: fallbackWorkspaceText });
914
938
  }
915
-
916
- if (historySlice.length > 0 && !tailRequiredShrinkInSingleStep) {
917
- const selectedReversed: AcpPromptBlock[][] = [];
918
- let usedBytes = 0;
919
- let usedTokens = 0;
920
- let usedImages = 0;
921
-
922
- for (let i = historySlice.length - 1; i >= 0; i--) {
923
- const serialized = serializeReplayHistoryEntry(historySlice[i]);
924
- if (serialized.blocks.length === 0) continue;
925
-
926
- const imageCountInEntry = serialized.blocks.filter((b) => b.type === "image").length;
927
- const keptImagesInEntry = Math.max(
928
- 0,
929
- Math.min(imageCountInEntry, MAX_FRESH_REPLAY_HISTORY_IMAGES - usedImages),
930
- );
931
- const entryTokens = serialized.tokens + keptImagesInEntry * ESTIMATED_IMAGE_BLOCK_TOKENS;
932
-
933
- if (
934
- usedBytes + serialized.textBytes > availSingleHistoryBytes ||
935
- usedTokens + entryTokens > availSingleHistoryTokens
936
- ) {
937
- singleStepOmittedCount = i + 1;
938
- break;
939
- }
940
-
941
- const cappedBlocks: AcpPromptBlock[] = serialized.blocks.map((block) => {
942
- if (block.type !== "image") return block;
943
- if (usedImages < MAX_FRESH_REPLAY_HISTORY_IMAGES) {
944
- usedImages++;
945
- return block;
946
- }
947
- return {
948
- type: "text",
949
- text: `[earlier ${block.mimeType} image omitted in replay]`,
950
- };
939
+ if (singleStepHistory.blocks.length > 0 || singleStepHistory.omittedCount > 0) {
940
+ singleStepFallbackBlocks.push({ type: "text", text: headerText });
941
+ if (singleStepHistory.omittedCount > 0) {
942
+ singleStepFallbackBlocks.push({
943
+ type: "text",
944
+ text: `[Note: ${singleStepHistory.omittedCount} earlier historical messages were omitted to stay within the single-step prompt size budget.]`,
951
945
  });
952
- selectedReversed.push(cappedBlocks);
953
- usedBytes += serialized.textBytes;
954
- usedTokens += entryTokens;
955
- }
956
-
957
- if (selectedReversed.length > 0 || singleStepOmittedCount > 0) {
958
- singleStepFallbackBlocks.push({ type: "text", text: headerText });
959
- if (singleStepOmittedCount > 0) {
960
- singleStepFallbackBlocks.push({
961
- type: "text",
962
- text: `[Note: ${singleStepOmittedCount} earlier historical messages were omitted to stay within the single-step prompt size budget.]`,
963
- });
964
- }
965
- for (let i = selectedReversed.length - 1; i >= 0; i--) {
966
- singleStepFallbackBlocks.push(...selectedReversed[i]);
967
- }
968
- singleStepFallbackBlocks.push({ type: "text", text: footerText });
969
946
  }
970
- } else if (historySlice.length > 0) {
971
- singleStepOmittedCount = historySlice.length;
947
+ singleStepFallbackBlocks.push(...singleStepHistory.blocks, { type: "text", text: footerText });
972
948
  }
973
-
974
949
  singleStepFallbackBlocks.push(...safeSingleStepTailBlocks);
975
950
 
976
- // 若单步即可无省略装下全部历史与末尾提问,直接返回(零 SQLite 预注入开销)
951
+ // 只有原文全部放得下时才直接发送。单步降级发生的裁剪也应触发分段计划。
977
952
  if (
978
- singleStepOmittedCount === 0 &&
953
+ singleStepHistory.omittedCount === 0 &&
954
+ !singleStepHistory.truncated &&
979
955
  !tailRequiredShrinkInSingleStep &&
980
956
  !workspaceRequiredShrinkInSingleStep
981
957
  ) {
@@ -1002,7 +978,7 @@ export function buildFreshReplayPlan(options: FreshReplayPlanOptions): FreshRepl
1002
978
  options.maxTotalHistoryBytes ??
1003
979
  Math.min(MAX_PRELOAD_TOTAL_HISTORY_BYTES, totalHistoryTokenBudget * 4);
1004
980
 
1005
- const preloadEntriesReversed: { text: string; bytes: number; tokens: number }[] = [];
981
+ const preloadEntriesReversed: string[] = [];
1006
982
  const preservedRecentHistoryImages: Array<{
1007
983
  block: Extract<AcpPromptBlock, { type: "image" }>;
1008
984
  source:
@@ -1015,19 +991,17 @@ export function buildFreshReplayPlan(options: FreshReplayPlanOptions): FreshRepl
1015
991
 
1016
992
  for (let i = historySlice.length - 1; i >= 0; i--) {
1017
993
  const historyMsg = historySlice[i];
1018
- const serialized = serializeReplayHistoryEntry(historyMsg, {
1019
- maxMessageBytes: MAX_PRELOAD_SINGLE_MESSAGE_TEXT_BYTES,
1020
- maxToolBytes: MAX_PRELOAD_SINGLE_TOOL_TEXT_BYTES,
1021
- });
1022
- if (serialized.blocks.length === 0) continue;
994
+ const blocks = serializeReplayHistoryEntry(historyMsg);
995
+ if (blocks.length === 0) continue;
1023
996
 
1024
997
  const textSegments: string[] = [];
1025
- for (const block of serialized.blocks) {
998
+ const entryImages: typeof preservedRecentHistoryImages = [];
999
+ for (const block of blocks) {
1026
1000
  if (block.type === "text") {
1027
1001
  textSegments.push(block.text);
1028
1002
  } else if (block.type === "image") {
1029
- if (preservedRecentHistoryImages.length < MAX_FRESH_REPLAY_HISTORY_IMAGES) {
1030
- preservedRecentHistoryImages.push({
1003
+ if (preservedRecentHistoryImages.length + entryImages.length < MAX_FRESH_REPLAY_HISTORY_IMAGES) {
1004
+ entryImages.push({
1031
1005
  block,
1032
1006
  source:
1033
1007
  historyMsg.role === "toolResult"
@@ -1045,20 +1019,34 @@ export function buildFreshReplayPlan(options: FreshReplayPlanOptions): FreshRepl
1045
1019
  }
1046
1020
  }
1047
1021
  }
1048
- const entryText = textSegments.join("\n");
1049
- const entryBytes = Buffer.byteLength(entryText, "utf8") + 1;
1050
- const entryTokens = estimateStepTokens(entryText) + 1;
1022
+ let entryText = textSegments.join("\n");
1023
+ let entryBytes = Buffer.byteLength(entryText, "utf8") + 1;
1024
+ let entryTokens = estimateStepTokens(entryText) + 1;
1051
1025
 
1026
+ // 最近一条就超过历史总预算时,尽量保留其首尾,避免整个最近上下文被丢弃。
1027
+ if (
1028
+ preloadEntriesReversed.length === 0 &&
1029
+ (entryBytes > totalHistoryByteBudget || entryTokens > totalHistoryTokenBudget)
1030
+ ) {
1031
+ entryText = truncateTextMiddleToSafeBudget(
1032
+ entryText,
1033
+ totalHistoryByteBudget - 1,
1034
+ totalHistoryTokenBudget - 1,
1035
+ "\n...[history entry truncated to stay within model context budget]...\n",
1036
+ );
1037
+ entryBytes = Buffer.byteLength(entryText, "utf8") + 1;
1038
+ entryTokens = estimateStepTokens(entryText) + 1;
1039
+ }
1052
1040
  if (
1053
- preloadEntriesReversed.length > 0 &&
1054
- (totalUsedHistoryBytes + entryBytes > totalHistoryByteBudget ||
1055
- totalUsedHistoryTokens + entryTokens > totalHistoryTokenBudget)
1041
+ totalUsedHistoryBytes + entryBytes > totalHistoryByteBudget ||
1042
+ totalUsedHistoryTokens + entryTokens > totalHistoryTokenBudget
1056
1043
  ) {
1057
1044
  omittedMessageCount = i + 1;
1058
1045
  break;
1059
1046
  }
1060
1047
 
1061
- preloadEntriesReversed.push({ text: entryText, bytes: entryBytes, tokens: entryTokens });
1048
+ preloadEntriesReversed.push(entryText);
1049
+ preservedRecentHistoryImages.push(...entryImages);
1062
1050
  totalUsedHistoryBytes += entryBytes;
1063
1051
  totalUsedHistoryTokens += entryTokens;
1064
1052
  }
@@ -1112,7 +1100,7 @@ export function buildFreshReplayPlan(options: FreshReplayPlanOptions): FreshRepl
1112
1100
  );
1113
1101
  }
1114
1102
  for (const entry of chronologicalEntries) {
1115
- appendAtomicPiece(entry.text);
1103
+ appendAtomicPiece(entry);
1116
1104
  }
1117
1105
  flushChunk();
1118
1106
 
@@ -1267,63 +1255,19 @@ export function buildFreshReplayPromptBlocks(
1267
1255
  const blocks: AcpPromptBlock[] = [];
1268
1256
 
1269
1257
  if (historySlice.length > 0) {
1270
- const selectedReversed: AcpPromptBlock[][] = [];
1271
- let usedHistoryBytes = 0;
1272
- let usedHistoryTokens = 0;
1273
- let usedHistoryImages = 0;
1274
- let omittedCount = 0;
1275
-
1276
- for (let i = historySlice.length - 1; i >= 0; i--) {
1277
- const serialized = serializeReplayHistoryEntry(historySlice[i]);
1278
- if (serialized.blocks.length === 0) {
1279
- continue;
1280
- }
1281
- const imageCountInEntry = serialized.blocks.filter((b) => b.type === "image").length;
1282
- const keptImagesInEntry = Math.max(
1283
- 0,
1284
- Math.min(imageCountInEntry, MAX_FRESH_REPLAY_HISTORY_IMAGES - usedHistoryImages),
1285
- );
1286
- const entryTokens = serialized.tokens + keptImagesInEntry * ESTIMATED_IMAGE_BLOCK_TOKENS;
1287
-
1288
- if (
1289
- selectedReversed.length > 0 &&
1290
- (usedHistoryBytes + serialized.textBytes > cappedHistoryBytes ||
1291
- usedHistoryTokens + entryTokens > effectiveMaxHistoryTokens)
1292
- ) {
1293
- omittedCount = i + 1;
1294
- break;
1295
- }
1296
- const cappedBlocks: AcpPromptBlock[] = serialized.blocks.map((block) => {
1297
- if (block.type !== "image") return block;
1298
- if (usedHistoryImages < MAX_FRESH_REPLAY_HISTORY_IMAGES) {
1299
- usedHistoryImages++;
1300
- return block;
1301
- }
1302
- return {
1303
- type: "text",
1304
- text: `[earlier ${block.mimeType} image omitted in replay]`,
1305
- };
1306
- });
1307
- selectedReversed.push(cappedBlocks);
1308
- usedHistoryBytes += serialized.textBytes;
1309
- usedHistoryTokens += entryTokens;
1310
- }
1311
-
1258
+ const selected = selectSingleStepReplayHistory(historySlice, cappedHistoryBytes, effectiveMaxHistoryTokens);
1312
1259
  blocks.push({
1313
1260
  type: "text",
1314
1261
  text: "<conversation-checkpoint>\nThe following is the prior conversation transcript from this session (preserved across model switch, compaction, or branch navigation):",
1315
1262
  });
1316
1263
 
1317
- if (omittedCount > 0) {
1264
+ if (selected.omittedCount > 0) {
1318
1265
  blocks.push({
1319
1266
  type: "text",
1320
- text: `[Note: ${omittedCount} earlier historical messages were omitted to stay within the prompt replay size budget.]`,
1267
+ text: `[Note: ${selected.omittedCount} earlier historical messages were omitted to stay within the prompt replay size budget.]`,
1321
1268
  });
1322
1269
  }
1323
-
1324
- for (let i = selectedReversed.length - 1; i >= 0; i--) {
1325
- blocks.push(...selectedReversed[i]);
1326
- }
1270
+ blocks.push(...selected.blocks);
1327
1271
 
1328
1272
  blocks.push({
1329
1273
  type: "text",
@@ -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",