pi-antigravity-bridge 0.1.9 → 0.1.11
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 +22 -0
- package/package.json +1 -1
- package/src/acp/binary-resolver.ts +3 -1
- package/src/acp/process-manager.ts +45 -13
- package/src/index.ts +15 -3
- package/src/session/checkpoint-sync.ts +263 -4
- package/src/session/reconcile.ts +63 -9
- package/src/session/turn-coordinator.ts +483 -327
- package/src/tools/agy-mirror-tools.ts +63 -5
- package/src/tools/agy-renderers.ts +1 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.1.11] - 2026-11-22
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- 完善与 `pi-traffic-optimization` 等观测扩展的协同:上报宿主 MCP 工具结果回传、投影同步状态、多步预注入历史负载与辅助请求状态。
|
|
8
|
+
- 延长模板会话库落盘等待窗口,并统一解析 `agy_read` 等镜像工具中的 `file://` 路径与行范围参数。
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- 修复单图归档工具结果在超长重放截断时可能丢失 `ctx://image/` 句柄,以及多步预注入保留的历史图片缺少来源标签的问题。
|
|
13
|
+
- 修复大量图片搭配短文本触发单步上限时无故裁切短文本的问题。
|
|
14
|
+
- 修复会话恢复阶段用户中断后继续执行后续恢复步骤,以及初始化中途失败残留本地 MCP 会话绑定的问题。
|
|
15
|
+
- 修复前序请求超时未收敛时重叠发送请求、辅助请求未将模型拒绝或取消判为错误或中止,以及切换模型后迟到用量通知改写新模型上下文窗口的问题。
|
|
16
|
+
- 修复 `agy-tools` 与 `hybrid` 模式跳过受损历史库自愈校验、POSIX 退出清理可能跳过强杀信号、后台模型刷新未随会话关闭取消,以及 Windows 命令行参数尾部反斜杠转义错误的问题。
|
|
17
|
+
|
|
18
|
+
## [0.1.10] - 2026-11-22
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
|
|
22
|
+
- 修复 `pi-tools` 模式下触发超长历史重建或辅助请求时,新建会话未保留禁用内置工具配置而意外启用 Antigravity 原生工具与内置工作流的问题。
|
|
23
|
+
- 修复从 `0.1.9` 受影响的旧会话恢复时继续沿用原生工具配置的问题,在下次对话时自动重建并恢复纯净 `pi-tools` 模式。
|
|
24
|
+
|
|
3
25
|
## [0.1.9] - 2026-11-22
|
|
4
26
|
|
|
5
27
|
### Changed
|
package/package.json
CHANGED
|
@@ -155,7 +155,9 @@ export function quoteWindowsCmdArg(arg: string): string {
|
|
|
155
155
|
if (arg.length === 0) return '""';
|
|
156
156
|
const escapedPercents = arg.replace(/%/g, "%%");
|
|
157
157
|
if (!/[\s"&|<>^()!;,=%]/.test(escapedPercents)) return escapedPercents;
|
|
158
|
-
|
|
158
|
+
const escapedQuotes = escapedPercents.replace(/(\\*)"/g, '$1$1""');
|
|
159
|
+
const escapedTrailingBackslashes = escapedQuotes.replace(/(\\+)$/, "$1$1");
|
|
160
|
+
return `"${escapedTrailingBackslashes}"`;
|
|
159
161
|
}
|
|
160
162
|
|
|
161
163
|
/**
|
|
@@ -21,9 +21,22 @@ import {
|
|
|
21
21
|
NdjsonLineParser,
|
|
22
22
|
} from "./protocol.ts";
|
|
23
23
|
|
|
24
|
+
function readPackageVersion(): string {
|
|
25
|
+
try {
|
|
26
|
+
const raw = fs.readFileSync(new URL("../../package.json", import.meta.url), "utf8");
|
|
27
|
+
const parsed = JSON.parse(raw) as { version?: unknown };
|
|
28
|
+
if (typeof parsed.version === "string" && parsed.version.trim().length > 0) {
|
|
29
|
+
return parsed.version.trim();
|
|
30
|
+
}
|
|
31
|
+
} catch {
|
|
32
|
+
// 忽略读取异常,回退默认版本号
|
|
33
|
+
}
|
|
34
|
+
return "0.1.10";
|
|
35
|
+
}
|
|
36
|
+
|
|
24
37
|
export const BRIDGE_AGENT_NAME = "pi-bridge";
|
|
25
38
|
export const CLIENT_INFO_NAME = "pi-antigravity-bridge";
|
|
26
|
-
export const CLIENT_INFO_VERSION =
|
|
39
|
+
export const CLIENT_INFO_VERSION = readPackageVersion();
|
|
27
40
|
|
|
28
41
|
export class AcpRpcError extends Error {
|
|
29
42
|
readonly code: number;
|
|
@@ -640,20 +653,20 @@ export class AcpClientConnection {
|
|
|
640
653
|
}
|
|
641
654
|
|
|
642
655
|
if (this.isAlive) {
|
|
643
|
-
await new Promise<
|
|
656
|
+
const exitedGracefully = await new Promise<boolean>((resolve) => {
|
|
644
657
|
let settled = false;
|
|
645
658
|
let killTimer: ReturnType<typeof setTimeout> | undefined;
|
|
646
|
-
const finish = () => {
|
|
659
|
+
const finish = (graceful: boolean) => {
|
|
647
660
|
if (settled) return;
|
|
648
661
|
settled = true;
|
|
649
662
|
if (killTimer) {
|
|
650
663
|
clearTimeout(killTimer);
|
|
651
664
|
killTimer = undefined;
|
|
652
665
|
}
|
|
653
|
-
resolve();
|
|
666
|
+
resolve(graceful);
|
|
654
667
|
};
|
|
655
668
|
|
|
656
|
-
this.proc.once("close", finish);
|
|
669
|
+
this.proc.once("close", () => finish(true));
|
|
657
670
|
try {
|
|
658
671
|
this.proc.stdin.end();
|
|
659
672
|
} catch {
|
|
@@ -662,12 +675,15 @@ export class AcpClientConnection {
|
|
|
662
675
|
|
|
663
676
|
killTimer = setTimeout(() => {
|
|
664
677
|
if (!settled) {
|
|
665
|
-
|
|
666
|
-
finish();
|
|
678
|
+
finish(false);
|
|
667
679
|
}
|
|
668
680
|
}, 1_500);
|
|
669
681
|
killTimer.unref();
|
|
670
682
|
});
|
|
683
|
+
|
|
684
|
+
if (!exitedGracefully && this.proc.exitCode === null) {
|
|
685
|
+
await this.forceKillProcessTree();
|
|
686
|
+
}
|
|
671
687
|
}
|
|
672
688
|
|
|
673
689
|
this.closed = true;
|
|
@@ -683,7 +699,7 @@ export class AcpClientConnection {
|
|
|
683
699
|
void this.managedAgentDir;
|
|
684
700
|
}
|
|
685
701
|
|
|
686
|
-
private forceKillProcessTree(): void {
|
|
702
|
+
private async forceKillProcessTree(): Promise<void> {
|
|
687
703
|
const pid = this.proc.pid;
|
|
688
704
|
if (!pid) return;
|
|
689
705
|
|
|
@@ -717,11 +733,27 @@ export class AcpClientConnection {
|
|
|
717
733
|
};
|
|
718
734
|
|
|
719
735
|
sendPosixGroupOrPid("SIGTERM");
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
736
|
+
if (this.proc.exitCode !== null) {
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
await new Promise<void>((resolve) => {
|
|
741
|
+
let done = false;
|
|
742
|
+
const finish = () => {
|
|
743
|
+
if (done) return;
|
|
744
|
+
done = true;
|
|
745
|
+
clearTimeout(timer);
|
|
746
|
+
this.proc.off("close", finish);
|
|
747
|
+
resolve();
|
|
748
|
+
};
|
|
749
|
+
const timer = setTimeout(() => {
|
|
750
|
+
if (this.proc.exitCode === null) {
|
|
751
|
+
sendPosixGroupOrPid("SIGKILL");
|
|
752
|
+
}
|
|
753
|
+
finish();
|
|
754
|
+
}, 500);
|
|
755
|
+
this.proc.once("close", finish);
|
|
756
|
+
});
|
|
725
757
|
}
|
|
726
758
|
|
|
727
759
|
private writeJson(payload: unknown): void {
|
package/src/index.ts
CHANGED
|
@@ -219,13 +219,21 @@ export default function antigravityBridgeExtension(pi: ExtensionAPI): void {
|
|
|
219
219
|
pi.registerToolRenderer(createAgyToolRendererResolver());
|
|
220
220
|
|
|
221
221
|
// 3. 注册 `/agy` 命令族
|
|
222
|
-
|
|
222
|
+
let backgroundRefreshController: AbortController | undefined;
|
|
223
|
+
const refreshAndReRegisterModels = async (
|
|
224
|
+
ctx: ExtensionContext,
|
|
225
|
+
overrideSignal?: AbortSignal,
|
|
226
|
+
): Promise<number> => {
|
|
227
|
+
const signal = overrideSignal ?? ctx.signal;
|
|
223
228
|
const snapshot = await probeLiveAntigravityCatalog(
|
|
224
229
|
processManager,
|
|
225
230
|
coordinator.config,
|
|
226
231
|
ctx.cwd,
|
|
227
|
-
{ signal
|
|
232
|
+
{ signal, force: true },
|
|
228
233
|
);
|
|
234
|
+
if (signal?.aborted) {
|
|
235
|
+
return currentModels.length;
|
|
236
|
+
}
|
|
229
237
|
if (snapshot.tier) {
|
|
230
238
|
coordinator.setLatestTier(snapshot.tier);
|
|
231
239
|
}
|
|
@@ -274,7 +282,9 @@ export default function antigravityBridgeExtension(pi: ExtensionAPI): void {
|
|
|
274
282
|
typeof diskCache.updatedAt !== "number" ||
|
|
275
283
|
Date.now() - diskCache.updatedAt > MODEL_CACHE_STALE_MS;
|
|
276
284
|
if (isCacheStale) {
|
|
277
|
-
|
|
285
|
+
backgroundRefreshController?.abort();
|
|
286
|
+
backgroundRefreshController = new AbortController();
|
|
287
|
+
void refreshAndReRegisterModels(ctx, backgroundRefreshController.signal).catch(() => {});
|
|
278
288
|
}
|
|
279
289
|
});
|
|
280
290
|
|
|
@@ -330,6 +340,8 @@ export default function antigravityBridgeExtension(pi: ExtensionAPI): void {
|
|
|
330
340
|
});
|
|
331
341
|
|
|
332
342
|
pi.on("session_shutdown", async () => {
|
|
343
|
+
backgroundRefreshController?.abort();
|
|
344
|
+
backgroundRefreshController = undefined;
|
|
333
345
|
await coordinator.dispose();
|
|
334
346
|
});
|
|
335
347
|
}
|
|
@@ -39,6 +39,8 @@ export interface AgySessionAnchor {
|
|
|
39
39
|
projectionDigest?: string;
|
|
40
40
|
/** 可选:该 AGY 会话实际承载的 `pi-traffic-optimization` 归档占位符总数 */
|
|
41
41
|
projectedCount?: number;
|
|
42
|
+
/** 可选:该锚点落盘时后端已使用的上下文 token 水位(供恢复时评估是否因归档投影重建) */
|
|
43
|
+
usedTokens?: number;
|
|
42
44
|
/** 可选的本地 SQLite 会话数据库检查点水位 */
|
|
43
45
|
dbCheckpoint?: SqliteDbCheckpoint;
|
|
44
46
|
}
|
|
@@ -666,9 +668,14 @@ export async function forkSqliteConversationAtCheckpoint(
|
|
|
666
668
|
}
|
|
667
669
|
}
|
|
668
670
|
|
|
671
|
+
let origTrajectoryId: string | undefined;
|
|
669
672
|
let dstDb: import("node:sqlite").DatabaseSync | undefined;
|
|
670
673
|
try {
|
|
671
674
|
dstDb = openSqliteWithTimeout(sqlite, targetDbPath, false);
|
|
675
|
+
const origMeta = dstDb
|
|
676
|
+
.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1")
|
|
677
|
+
.get() as { trajectory_id?: string } | undefined;
|
|
678
|
+
origTrajectoryId = origMeta?.trajectory_id;
|
|
672
679
|
dstDb.exec("BEGIN IMMEDIATE");
|
|
673
680
|
dstDb.prepare("DELETE FROM steps WHERE idx >= ?").run(checkpoint.steps);
|
|
674
681
|
dstDb.prepare("DELETE FROM parent_references WHERE idx >= ?").run(checkpoint.steps);
|
|
@@ -683,6 +690,7 @@ export async function forkSqliteConversationAtCheckpoint(
|
|
|
683
690
|
dstDb
|
|
684
691
|
.prepare("UPDATE trajectory_meta SET trajectory_id = ?, cascade_id = ?")
|
|
685
692
|
.run(forkedSessionId, forkedSessionId);
|
|
693
|
+
rewriteMetadataBlobUuids(dstDb, [sourceSessionId, origTrajectoryId], forkedSessionId);
|
|
686
694
|
dstDb.exec("COMMIT");
|
|
687
695
|
return forkedSessionId;
|
|
688
696
|
} catch {
|
|
@@ -762,11 +770,262 @@ export function encodePlannerResponseStepPayload(text: string): Buffer {
|
|
|
762
770
|
}
|
|
763
771
|
|
|
764
772
|
/**
|
|
765
|
-
*
|
|
766
|
-
*
|
|
767
|
-
|
|
773
|
+
* 校验已有本地会话库是否携带有效的 `trajectory_metadata_blob`(以及 `pi-tools` 模式下必需的 `pi-bridge` 标识)。
|
|
774
|
+
* 用于在恢复或分叉历史锚点前自动识别并隔离旧版无元数据裸库,避免 `session/resume` 回退启用 Antigravity 原生内置工具。
|
|
775
|
+
*/
|
|
776
|
+
export async function hasValidAgentMetadataBlob(
|
|
777
|
+
config: BridgeConfig,
|
|
778
|
+
agySessionId: string,
|
|
779
|
+
requiredAgentSubstring?: string,
|
|
780
|
+
): Promise<boolean> {
|
|
781
|
+
if (!agySessionId) return true;
|
|
782
|
+
const dbPath = path.join(resolveAgyConversationsDir(config), `${agySessionId}.db`);
|
|
783
|
+
if (!fs.existsSync(dbPath)) {
|
|
784
|
+
return true;
|
|
785
|
+
}
|
|
786
|
+
const sqlite = await loadNodeSqlite();
|
|
787
|
+
if (!sqlite) return true;
|
|
788
|
+
|
|
789
|
+
let db: import("node:sqlite").DatabaseSync | undefined;
|
|
790
|
+
try {
|
|
791
|
+
db = openSqliteWithTimeout(sqlite, dbPath, true, 500);
|
|
792
|
+
const hasBlobTable = db
|
|
793
|
+
.prepare(
|
|
794
|
+
"SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = 'trajectory_metadata_blob'",
|
|
795
|
+
)
|
|
796
|
+
.get();
|
|
797
|
+
if (!hasBlobTable) {
|
|
798
|
+
return true;
|
|
799
|
+
}
|
|
800
|
+
const rows = db
|
|
801
|
+
.prepare("SELECT data FROM trajectory_metadata_blob WHERE data IS NOT NULL AND length(data) > 0")
|
|
802
|
+
.all() as Array<{ data: Uint8Array }>;
|
|
803
|
+
if (rows.length === 0) {
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
if (requiredAgentSubstring) {
|
|
807
|
+
return rows.some((row) =>
|
|
808
|
+
Buffer.from(row.data).toString("utf8").includes(requiredAgentSubstring),
|
|
809
|
+
);
|
|
810
|
+
}
|
|
811
|
+
return true;
|
|
812
|
+
} catch {
|
|
813
|
+
return true;
|
|
814
|
+
} finally {
|
|
815
|
+
try {
|
|
816
|
+
db?.close();
|
|
817
|
+
} catch {
|
|
818
|
+
// 忽略
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* 在克隆出的 `.db` 的 `trajectory_metadata_blob` 中将旧 UUID 等长替换为新 UUID。
|
|
825
|
+
* 仅对长度完全相等的 ASCII UUID 执行原位字节替换,不破坏 Protobuf 长度前缀编码。
|
|
826
|
+
*/
|
|
827
|
+
function rewriteMetadataBlobUuids(
|
|
828
|
+
db: import("node:sqlite").DatabaseSync,
|
|
829
|
+
oldIds: readonly (string | undefined)[],
|
|
830
|
+
newId: string,
|
|
831
|
+
): void {
|
|
832
|
+
const hasBlobTable = db
|
|
833
|
+
.prepare(
|
|
834
|
+
"SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = 'trajectory_metadata_blob'",
|
|
835
|
+
)
|
|
836
|
+
.get();
|
|
837
|
+
if (!hasBlobTable) return;
|
|
838
|
+
|
|
839
|
+
const targets = Array.from(
|
|
840
|
+
new Set(
|
|
841
|
+
oldIds.filter(
|
|
842
|
+
(id): id is string =>
|
|
843
|
+
typeof id === "string" && id.length === newId.length && id !== newId,
|
|
844
|
+
),
|
|
845
|
+
),
|
|
846
|
+
);
|
|
847
|
+
if (targets.length === 0) return;
|
|
848
|
+
|
|
849
|
+
const newBytes = Buffer.from(newId, "ascii");
|
|
850
|
+
const rows = db
|
|
851
|
+
.prepare("SELECT id, data FROM trajectory_metadata_blob WHERE data IS NOT NULL")
|
|
852
|
+
.all() as Array<{ id: string; data: Uint8Array }>;
|
|
853
|
+
const updateStmt = db.prepare("UPDATE trajectory_metadata_blob SET data = ? WHERE id = ?");
|
|
854
|
+
|
|
855
|
+
for (const row of rows) {
|
|
856
|
+
const buf = Buffer.from(row.data);
|
|
857
|
+
let changed = false;
|
|
858
|
+
for (const oldId of targets) {
|
|
859
|
+
const oldBytes = Buffer.from(oldId, "ascii");
|
|
860
|
+
let offset = 0;
|
|
861
|
+
while ((offset = buf.indexOf(oldBytes, offset)) !== -1) {
|
|
862
|
+
newBytes.copy(buf, offset);
|
|
863
|
+
offset += newBytes.length;
|
|
864
|
+
changed = true;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
if (changed) {
|
|
868
|
+
updateStmt.run(buf, row.id);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* 基于刚刚由官方 `agy session/new` 创建的空白模板会话数据库,通过只读 `VACUUM INTO` 克隆出全新 UUID 的
|
|
875
|
+
* 会话库并写入多步预注入 `(USER_INPUT, PLANNER_RESPONSE)` 历史分片。
|
|
768
876
|
*
|
|
769
|
-
*
|
|
877
|
+
* 与从零建表不同,该方法完整保留 `agy` 原生写入 `trajectory_metadata_blob` 的 `CustomAgentSpec`
|
|
878
|
+
* (如 `pi-tools` 模式下的 `pi-bridge` 禁用内置工具与默认组件规格、挂载插件、工作区 URI 与权限策略),
|
|
879
|
+
* 防止 `session/resume` 找不到 Agent 元数据时回退启用 Antigravity 原生内置工具与工作流。
|
|
880
|
+
*/
|
|
881
|
+
export async function cloneTemplateSqliteConversationWithPreload(
|
|
882
|
+
config: BridgeConfig,
|
|
883
|
+
templateSessionId: string,
|
|
884
|
+
turns: readonly PreloadedSqliteTurn[],
|
|
885
|
+
options?: { signal?: AbortSignal },
|
|
886
|
+
): Promise<string | undefined> {
|
|
887
|
+
if (!config.enableSqliteFork || !templateSessionId || turns.length === 0) {
|
|
888
|
+
return undefined;
|
|
889
|
+
}
|
|
890
|
+
const sqlite = await loadNodeSqlite();
|
|
891
|
+
if (!sqlite) return undefined;
|
|
892
|
+
|
|
893
|
+
const convDir = resolveAgyConversationsDir(config);
|
|
894
|
+
const templateDbPath = path.join(convDir, `${templateSessionId}.db`);
|
|
895
|
+
|
|
896
|
+
// 等待刚刚关闭的模板会话完成 SQLite/WAL 落盘(最长 1200ms,快速轮询并响应取消信号)
|
|
897
|
+
const deadline = Date.now() + 1_200;
|
|
898
|
+
let templateReady = false;
|
|
899
|
+
while (!options?.signal?.aborted) {
|
|
900
|
+
if (fs.existsSync(templateDbPath)) {
|
|
901
|
+
let probeDb: import("node:sqlite").DatabaseSync | undefined;
|
|
902
|
+
try {
|
|
903
|
+
probeDb = openSqliteWithTimeout(sqlite, templateDbPath, true, 300);
|
|
904
|
+
if (verifyRequiredTables(probeDb)) {
|
|
905
|
+
const hasBlobTable = probeDb
|
|
906
|
+
.prepare(
|
|
907
|
+
"SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = 'trajectory_metadata_blob'",
|
|
908
|
+
)
|
|
909
|
+
.get();
|
|
910
|
+
if (hasBlobTable) {
|
|
911
|
+
const blobRow = probeDb
|
|
912
|
+
.prepare(
|
|
913
|
+
"SELECT count(*) AS c FROM trajectory_metadata_blob WHERE data IS NOT NULL AND length(data) > 0",
|
|
914
|
+
)
|
|
915
|
+
.get() as { c?: number } | undefined;
|
|
916
|
+
if (Number(blobRow?.c ?? 0) > 0) {
|
|
917
|
+
templateReady = true;
|
|
918
|
+
break;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
} catch {
|
|
923
|
+
// 模板仍在 WAL 刷盘中,短等后重试
|
|
924
|
+
} finally {
|
|
925
|
+
try {
|
|
926
|
+
probeDb?.close();
|
|
927
|
+
} catch {
|
|
928
|
+
// 忽略
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
if (Date.now() >= deadline) {
|
|
933
|
+
break;
|
|
934
|
+
}
|
|
935
|
+
await sleepWithAbort(20, options?.signal);
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
if (!templateReady || options?.signal?.aborted) {
|
|
939
|
+
return undefined;
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
const clonedSessionId = crypto.randomUUID();
|
|
943
|
+
const targetDbPath = path.join(convDir, `${clonedSessionId}.db`);
|
|
944
|
+
const escapedTarget = targetDbPath.replace(/'/g, "''");
|
|
945
|
+
|
|
946
|
+
let srcDb: import("node:sqlite").DatabaseSync | undefined;
|
|
947
|
+
try {
|
|
948
|
+
srcDb = openSqliteWithTimeout(sqlite, templateDbPath, true);
|
|
949
|
+
srcDb.exec(`VACUUM INTO '${escapedTarget}'`);
|
|
950
|
+
} catch {
|
|
951
|
+
cleanupDbFilesSafe(targetDbPath);
|
|
952
|
+
return undefined;
|
|
953
|
+
} finally {
|
|
954
|
+
try {
|
|
955
|
+
srcDb?.close();
|
|
956
|
+
} catch {
|
|
957
|
+
// 忽略
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
let dstDb: import("node:sqlite").DatabaseSync | undefined;
|
|
962
|
+
try {
|
|
963
|
+
dstDb = openSqliteWithTimeout(sqlite, targetDbPath, false);
|
|
964
|
+
const origMeta = dstDb
|
|
965
|
+
.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1")
|
|
966
|
+
.get() as { trajectory_id?: string } | undefined;
|
|
967
|
+
|
|
968
|
+
dstDb.exec("BEGIN IMMEDIATE");
|
|
969
|
+
dstDb.prepare("DELETE FROM steps").run();
|
|
970
|
+
dstDb.prepare("DELETE FROM parent_references").run();
|
|
971
|
+
const hasBattleTable = dstDb
|
|
972
|
+
.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = 'battle_mode_infos'")
|
|
973
|
+
.get();
|
|
974
|
+
if (hasBattleTable) {
|
|
975
|
+
dstDb.prepare("DELETE FROM battle_mode_infos").run();
|
|
976
|
+
}
|
|
977
|
+
dstDb.prepare("DELETE FROM gen_metadata").run();
|
|
978
|
+
dstDb.prepare("DELETE FROM executor_metadata").run();
|
|
979
|
+
dstDb
|
|
980
|
+
.prepare("UPDATE trajectory_meta SET trajectory_id = ?, cascade_id = ?")
|
|
981
|
+
.run(clonedSessionId, clonedSessionId);
|
|
982
|
+
rewriteMetadataBlobUuids(
|
|
983
|
+
dstDb,
|
|
984
|
+
[templateSessionId, origMeta?.trajectory_id],
|
|
985
|
+
clonedSessionId,
|
|
986
|
+
);
|
|
987
|
+
|
|
988
|
+
const insertStep = dstDb.prepare(
|
|
989
|
+
"INSERT INTO steps (idx, step_type, status, has_subtrajectory, step_payload, step_format) VALUES (?, ?, ?, 0, ?, 0)",
|
|
990
|
+
);
|
|
991
|
+
let idx = 0;
|
|
992
|
+
for (const turn of turns) {
|
|
993
|
+
insertStep.run(
|
|
994
|
+
idx++,
|
|
995
|
+
CORTEX_STEP_TYPE_USER_INPUT,
|
|
996
|
+
CORTEX_STEP_STATUS_DONE,
|
|
997
|
+
encodeUserInputStepPayload(turn.userText),
|
|
998
|
+
);
|
|
999
|
+
insertStep.run(
|
|
1000
|
+
idx++,
|
|
1001
|
+
CORTEX_STEP_TYPE_PLANNER_RESPONSE,
|
|
1002
|
+
CORTEX_STEP_STATUS_DONE,
|
|
1003
|
+
encodePlannerResponseStepPayload(turn.assistantAckText),
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
dstDb.exec("COMMIT");
|
|
1007
|
+
return clonedSessionId;
|
|
1008
|
+
} catch {
|
|
1009
|
+
try {
|
|
1010
|
+
dstDb?.exec("ROLLBACK");
|
|
1011
|
+
} catch {
|
|
1012
|
+
// 忽略
|
|
1013
|
+
}
|
|
1014
|
+
cleanupDbFilesSafe(targetDbPath);
|
|
1015
|
+
return undefined;
|
|
1016
|
+
} finally {
|
|
1017
|
+
try {
|
|
1018
|
+
dstDb?.close();
|
|
1019
|
+
} catch {
|
|
1020
|
+
// 忽略
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* 新建一个独立 UUID 的 AGY 本地 SQLite 会话数据库,并将超长历史的多个安全分片以
|
|
1027
|
+
* `(USER_INPUT, PLANNER_RESPONSE)` 交替步预注入 `steps` 表(底层最小建库实现;生产路径请优先使用
|
|
1028
|
+
* `cloneTemplateSqliteConversationWithPreload` 以保留 `agy` 原生 `trajectory_metadata_blob` Agent 规格)。
|
|
770
1029
|
*/
|
|
771
1030
|
export async function createPreloadedSqliteConversation(
|
|
772
1031
|
config: BridgeConfig,
|
package/src/session/reconcile.ts
CHANGED
|
@@ -624,13 +624,22 @@ function serializeReplayHistoryEntry(
|
|
|
624
624
|
.map((c) => c.text)
|
|
625
625
|
.join("\n");
|
|
626
626
|
// 对 pi-traffic-optimization 已生成的紧凑 ctx:// 归档占位符保留原文不裁切,确保 handle 与 context_recall 指引完整
|
|
627
|
-
|
|
627
|
+
let cappedTexts = isTrafficOptToolPlaceholder(rawTexts)
|
|
628
628
|
? rawTexts
|
|
629
629
|
: truncateUtf8Middle(
|
|
630
630
|
rawTexts,
|
|
631
631
|
limits.maxToolBytes,
|
|
632
632
|
"\n...[tool output truncated in replay]...\n",
|
|
633
633
|
);
|
|
634
|
+
// 若仅单图归档的工具结果因正文过长被截断,补回被裁掉的 ctx://image/ 归档句柄行,避免模型丢失图片引用
|
|
635
|
+
if (cappedTexts !== rawTexts) {
|
|
636
|
+
const missingImagePlaceholders = rawTexts
|
|
637
|
+
.split("\n")
|
|
638
|
+
.filter((line) => isTrafficOptImagePlaceholder(line) && !cappedTexts.includes(line));
|
|
639
|
+
if (missingImagePlaceholders.length > 0) {
|
|
640
|
+
cappedTexts = `${cappedTexts}\n${missingImagePlaceholders.join("\n")}`;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
634
643
|
entryBlocks.push({
|
|
635
644
|
type: "text",
|
|
636
645
|
text: `<tool_result id="${msg.toolCallId}" tool="${msg.toolName}" status="${status}">\n${cappedTexts}\n</tool_result>`,
|
|
@@ -741,15 +750,28 @@ export function buildPromptBlocksPreloadPlan(
|
|
|
741
750
|
512,
|
|
742
751
|
Math.floor((maxStepTokens - wrapperOverheadTokens) * 0.9),
|
|
743
752
|
);
|
|
753
|
+
const minProtectedTextBytes = Math.min(chunkBytesLimit, 16_384);
|
|
754
|
+
const minProtectedTextTokens = Math.min(chunkTokensLimit, 4_096);
|
|
744
755
|
const finalTextBytesLimit = Math.max(
|
|
745
|
-
|
|
756
|
+
minProtectedTextBytes,
|
|
746
757
|
Math.min(chunkBytesLimit, maxStepBytes - nonTextMeasured.bytes - wrapperOverheadBytes),
|
|
747
758
|
);
|
|
748
759
|
const finalTextTokensLimit = Math.max(
|
|
749
|
-
|
|
760
|
+
minProtectedTextTokens,
|
|
750
761
|
Math.min(chunkTokensLimit, maxStepTokens - nonTextMeasured.tokens - wrapperOverheadTokens),
|
|
751
762
|
);
|
|
752
763
|
|
|
764
|
+
// 若超限纯粹源自图片数量过多而文本本身位于保护预算内,原样保留块结构,避免无意义裁切短文本
|
|
765
|
+
const combinedTextBytes = Buffer.byteLength(combinedText, "utf8");
|
|
766
|
+
const combinedTextTokens = estimateStepTokens(combinedText);
|
|
767
|
+
if (combinedTextBytes <= finalTextBytesLimit && combinedTextTokens <= finalTextTokensLimit) {
|
|
768
|
+
return {
|
|
769
|
+
preloadedTurns: [],
|
|
770
|
+
finalPromptBlocks: [...promptBlocks],
|
|
771
|
+
singleStepFallbackBlocks: [...promptBlocks],
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
|
|
753
775
|
// 单步安全降级块:保留头部 35% 与末尾 65%(优先保住末尾问题与输出格式要求)
|
|
754
776
|
const fallbackText = truncateTextMiddleToSafeBudget(
|
|
755
777
|
combinedText,
|
|
@@ -981,13 +1003,19 @@ export function buildFreshReplayPlan(options: FreshReplayPlanOptions): FreshRepl
|
|
|
981
1003
|
Math.min(MAX_PRELOAD_TOTAL_HISTORY_BYTES, totalHistoryTokenBudget * 4);
|
|
982
1004
|
|
|
983
1005
|
const preloadEntriesReversed: { text: string; bytes: number; tokens: number }[] = [];
|
|
984
|
-
const preservedRecentHistoryImages:
|
|
1006
|
+
const preservedRecentHistoryImages: Array<{
|
|
1007
|
+
block: Extract<AcpPromptBlock, { type: "image" }>;
|
|
1008
|
+
source:
|
|
1009
|
+
| { kind: "toolResult"; toolCallId: string; toolName: string; status: "ok" | "error" }
|
|
1010
|
+
| { kind: "user" };
|
|
1011
|
+
}> = [];
|
|
985
1012
|
let totalUsedHistoryBytes = 0;
|
|
986
1013
|
let totalUsedHistoryTokens = 0;
|
|
987
1014
|
let omittedMessageCount = 0;
|
|
988
1015
|
|
|
989
1016
|
for (let i = historySlice.length - 1; i >= 0; i--) {
|
|
990
|
-
const
|
|
1017
|
+
const historyMsg = historySlice[i];
|
|
1018
|
+
const serialized = serializeReplayHistoryEntry(historyMsg, {
|
|
991
1019
|
maxMessageBytes: MAX_PRELOAD_SINGLE_MESSAGE_TEXT_BYTES,
|
|
992
1020
|
maxToolBytes: MAX_PRELOAD_SINGLE_TOOL_TEXT_BYTES,
|
|
993
1021
|
});
|
|
@@ -999,7 +1027,18 @@ export function buildFreshReplayPlan(options: FreshReplayPlanOptions): FreshRepl
|
|
|
999
1027
|
textSegments.push(block.text);
|
|
1000
1028
|
} else if (block.type === "image") {
|
|
1001
1029
|
if (preservedRecentHistoryImages.length < MAX_FRESH_REPLAY_HISTORY_IMAGES) {
|
|
1002
|
-
preservedRecentHistoryImages.push(
|
|
1030
|
+
preservedRecentHistoryImages.push({
|
|
1031
|
+
block,
|
|
1032
|
+
source:
|
|
1033
|
+
historyMsg.role === "toolResult"
|
|
1034
|
+
? {
|
|
1035
|
+
kind: "toolResult",
|
|
1036
|
+
toolCallId: historyMsg.toolCallId,
|
|
1037
|
+
toolName: historyMsg.toolName,
|
|
1038
|
+
status: historyMsg.isError ? "error" : "ok",
|
|
1039
|
+
}
|
|
1040
|
+
: { kind: "user" },
|
|
1041
|
+
});
|
|
1003
1042
|
textSegments.push(`[attached recent ${block.mimeType} image from history]`);
|
|
1004
1043
|
} else {
|
|
1005
1044
|
textSegments.push(`[earlier ${block.mimeType} image omitted in replay]`);
|
|
@@ -1141,14 +1180,29 @@ export function buildFreshReplayPlan(options: FreshReplayPlanOptions): FreshRepl
|
|
|
1141
1180
|
if (workspaceContextBlock && !workspacePlaced) {
|
|
1142
1181
|
finalCandidateBlocks.push({ type: "text", text: workspaceContextBlock });
|
|
1143
1182
|
}
|
|
1144
|
-
//
|
|
1183
|
+
// 仅在剩余预算充足时附带少量近期历史图片(保留来源标签),绝不挤爆末尾用户提问
|
|
1145
1184
|
if (preservedRecentHistoryImages.length > 0) {
|
|
1185
|
+
const wrappedHistoryImageBlocks: AcpPromptBlock[] = [];
|
|
1186
|
+
for (const item of [...preservedRecentHistoryImages].reverse()) {
|
|
1187
|
+
if (item.source.kind === "toolResult") {
|
|
1188
|
+
wrappedHistoryImageBlocks.push({
|
|
1189
|
+
type: "text",
|
|
1190
|
+
text: `<tool_result id="${item.source.toolCallId}" tool="${item.source.toolName}" status="${item.source.status}">\n[recent image preserved from history]\n</tool_result>`,
|
|
1191
|
+
});
|
|
1192
|
+
} else {
|
|
1193
|
+
wrappedHistoryImageBlocks.push({
|
|
1194
|
+
type: "text",
|
|
1195
|
+
text: "[recent user image preserved from history]",
|
|
1196
|
+
});
|
|
1197
|
+
}
|
|
1198
|
+
wrappedHistoryImageBlocks.push(item.block);
|
|
1199
|
+
}
|
|
1146
1200
|
const tailWithImgs = measurePromptBlocksSize([
|
|
1147
|
-
...
|
|
1201
|
+
...wrappedHistoryImageBlocks,
|
|
1148
1202
|
...rawTailBlocks,
|
|
1149
1203
|
]);
|
|
1150
1204
|
if (tailWithImgs.bytes <= maxStepBytes && tailWithImgs.tokens <= maxStepTokens) {
|
|
1151
|
-
finalCandidateBlocks.push(...
|
|
1205
|
+
finalCandidateBlocks.push(...wrappedHistoryImageBlocks);
|
|
1152
1206
|
}
|
|
1153
1207
|
}
|
|
1154
1208
|
finalCandidateBlocks.push(...rawTailBlocks);
|