pi-antigravity-bridge 0.1.16 → 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
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.1.17] - 2026-11-28
6
+
7
+ ### Fixed
8
+
9
+ - 修复会话恢复时长命令输出、文件读取结果和工具调用参数被提前截断的问题。回放在上下文预算内保留这些内容和 Pi 已保存的可见思考文本。
10
+
5
11
  ## [0.1.16] - 2026-11-25
6
12
 
7
13
  ### Fixed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-antigravity-bridge",
3
- "version": "0.1.16",
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",
@@ -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",