pi-antigravity-bridge 0.1.7 → 0.1.9
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 +31 -0
- package/package.json +1 -1
- package/src/catalog/model-discovery.ts +145 -7
- package/src/mcp/http-mcp-bridge.ts +121 -12
- package/src/session/checkpoint-sync.ts +270 -1
- package/src/session/customization-mounter.ts +5 -0
- package/src/session/reconcile.ts +886 -47
- package/src/session/turn-coordinator.ts +630 -225
- package/src/stream/event-mapper.ts +19 -14
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.1.9] - 2026-11-22
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- 扩展超长历史重放、单次超长用户输入及 `/compact` 等长文本辅助请求的上下文容量,自动分段载入以突破单条 64k 输入限制,充分利用模型完整上下文窗口。
|
|
8
|
+
- 在降级至单步重放路径时动态扣除工作区上下文与末尾提问占用,优先保留最新对话与末尾用户提问。
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- 修复长会话重建、分支恢复或超长输入场景下触发 `agy` 单步 64k 上限导致末尾最新提问被截断丢失的问题。
|
|
13
|
+
- 修复超长文本自动分段在 Emoji 等多字节字符边界处可能出现卡死的问题。
|
|
14
|
+
|
|
15
|
+
## [0.1.8] - 2026-11-22
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- 自动为注册到 Pi 的 Antigravity 模型补充官方参考定价,并按单价计算每步与累计费用,同时为已有旧缓存自动补全价格数据。
|
|
20
|
+
- 适配 `pi-traffic-optimization` 扩展:支持在批量上下文归档后按需瘦身会话、保留完整 `ctx://` 句柄与 `context_recall` 召回指引,以及关闭优化后恢复完整上下文。
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- 将 MCP 工具声明中的字面量联合参数规整为标准枚举类型,提升 `context_recall` 等扩展工具的参数可见性与校验提示准确度。
|
|
25
|
+
- 收紧大批量多工具调用拆分时的预留切片总扣减规模,降低对 Pi 原生缓存未命中统计的干扰。
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
|
|
29
|
+
- 修复真实 `0%` 缓存未命中后缓存基准未清零,导致回退路径沿用旧高命中率或被整轮累计均值覆盖的问题。
|
|
30
|
+
- 修复跨生成残留切片混入新生成以及多条上游生成叠加混算导致缓存命中率与输出统计失真的问题。
|
|
31
|
+
- 修复中间工具步在本地会话记录延迟落盘时缺少重试的问题,并移除未观测缓存前的固定 85% 估算。
|
|
32
|
+
- 修复 `pi-traffic-optimization` 压缩图片(PNG 转 WebP)或归档历史图片后会话摘要失配导致误拆热缓存与重启恢复锚点失效的问题。
|
|
33
|
+
|
|
3
34
|
## [0.1.7] - 2026-11-21
|
|
4
35
|
|
|
5
36
|
### Changed
|
package/package.json
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import type { ThinkingLevel, ThinkingLevelMap } from "@earendil-works/pi-ai";
|
|
4
|
+
import {
|
|
5
|
+
type BuiltinProvider,
|
|
6
|
+
getBuiltinModels,
|
|
7
|
+
getBuiltinProviders,
|
|
8
|
+
} from "@earendil-works/pi-ai/providers/all";
|
|
4
9
|
import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
|
|
5
10
|
|
|
6
11
|
export type ChatModelConfig = Extract<ProviderModelConfig, { reasoning: boolean }>;
|
|
@@ -33,6 +38,143 @@ const EFFORT_ORDER: readonly EffortSuffix[] = [
|
|
|
33
38
|
"max",
|
|
34
39
|
];
|
|
35
40
|
|
|
41
|
+
const ZERO_MODEL_COST: ChatModelConfig["cost"] = {
|
|
42
|
+
input: 0,
|
|
43
|
+
output: 0,
|
|
44
|
+
cacheRead: 0,
|
|
45
|
+
cacheWrite: 0,
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** 从 Pi 内置官方目录查找参考定价时的 Provider 优先级(优先官方直连定价,规避区域溢价与批量折扣条目) */
|
|
49
|
+
const PRICING_PROVIDER_PRIORITY: readonly string[] = [
|
|
50
|
+
"google",
|
|
51
|
+
"anthropic",
|
|
52
|
+
"google-vertex",
|
|
53
|
+
"openai",
|
|
54
|
+
"radius",
|
|
55
|
+
"groq",
|
|
56
|
+
"together",
|
|
57
|
+
"openrouter",
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
let cachedBuiltinCostIndex: Map<string, ChatModelConfig["cost"]> | undefined;
|
|
61
|
+
|
|
62
|
+
function cloneModelCost(cost: ChatModelConfig["cost"]): ChatModelConfig["cost"] {
|
|
63
|
+
return {
|
|
64
|
+
input: cost.input,
|
|
65
|
+
output: cost.output,
|
|
66
|
+
cacheRead: cost.cacheRead,
|
|
67
|
+
cacheWrite: cost.cacheWrite,
|
|
68
|
+
...(cost.tiers && cost.tiers.length > 0
|
|
69
|
+
? { tiers: cost.tiers.map((tier) => ({ ...tier })) }
|
|
70
|
+
: {}),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function hasNonZeroModelCost(cost: ChatModelConfig["cost"] | undefined): boolean {
|
|
75
|
+
if (!cost) return false;
|
|
76
|
+
return cost.input > 0 || cost.output > 0 || cost.cacheRead > 0 || cost.cacheWrite > 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function getBuiltinCostIndex(): Map<string, ChatModelConfig["cost"]> {
|
|
80
|
+
if (cachedBuiltinCostIndex) {
|
|
81
|
+
return cachedBuiltinCostIndex;
|
|
82
|
+
}
|
|
83
|
+
const index = new Map<string, ChatModelConfig["cost"]>();
|
|
84
|
+
try {
|
|
85
|
+
const availableProviders = new Set<string>(getBuiltinProviders());
|
|
86
|
+
for (const provider of PRICING_PROVIDER_PRIORITY) {
|
|
87
|
+
if (!availableProviders.has(provider)) continue;
|
|
88
|
+
const models = getBuiltinModels(provider as BuiltinProvider);
|
|
89
|
+
for (const m of models) {
|
|
90
|
+
const rawId = m.id.toLowerCase();
|
|
91
|
+
if (rawId.includes(":batch") || rawId.endsWith("-batch")) continue;
|
|
92
|
+
if (!hasNonZeroModelCost(m.cost)) continue;
|
|
93
|
+
if (!index.has(rawId)) {
|
|
94
|
+
index.set(rawId, m.cost);
|
|
95
|
+
}
|
|
96
|
+
const slashIdx = rawId.lastIndexOf("/");
|
|
97
|
+
if (slashIdx !== -1 && slashIdx < rawId.length - 1) {
|
|
98
|
+
const bareId = rawId.slice(slashIdx + 1);
|
|
99
|
+
if (!index.has(bareId)) {
|
|
100
|
+
index.set(bareId, m.cost);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
} catch {
|
|
106
|
+
// 若上游 pi-ai 目录结构变化则安全回退至零费用,绝不阻塞模型注册
|
|
107
|
+
}
|
|
108
|
+
cachedBuiltinCostIndex = index;
|
|
109
|
+
return index;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function buildPricingLookupCandidates(modelId: string, displayName?: string): string[] {
|
|
113
|
+
const candidates: string[] = [];
|
|
114
|
+
const push = (id: string) => {
|
|
115
|
+
const normalized = id.trim().toLowerCase();
|
|
116
|
+
if (normalized && !candidates.includes(normalized)) {
|
|
117
|
+
candidates.push(normalized);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const raw = modelId.trim().toLowerCase();
|
|
122
|
+
const bases: string[] = [raw];
|
|
123
|
+
|
|
124
|
+
// 去除 -thinking 尾缀(如 claude-opus-4-6-thinking -> claude-opus-4-6)
|
|
125
|
+
if (raw.endsWith("-thinking") && raw.length > "-thinking".length) {
|
|
126
|
+
bases.push(raw.slice(0, -"-thinking".length));
|
|
127
|
+
}
|
|
128
|
+
// 去除固定单档位后缀(如 gpt-oss-120b-medium -> gpt-oss-120b)
|
|
129
|
+
const effortSplit = splitEffortSuffix(raw);
|
|
130
|
+
if (effortSplit) {
|
|
131
|
+
bases.push(effortSplit.baseId);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
for (const base of bases) {
|
|
135
|
+
push(base);
|
|
136
|
+
// 点号/连字符版本互转(如 claude-sonnet-4.6 <-> claude-sonnet-4-6)
|
|
137
|
+
const dashedVer = base.replace(/(\d)\.(\d)/g, "$1-$2");
|
|
138
|
+
const dottedVer = base.replace(/-(\d+)-(\d+)(?=$|-)/g, "-$1.$2");
|
|
139
|
+
push(dashedVer);
|
|
140
|
+
push(dottedVer);
|
|
141
|
+
if (!base.endsWith("-preview")) {
|
|
142
|
+
push(`${base}-preview`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Antigravity Orchestrator 封装项按底层对应代号匹配 Gemini 4 同级参考定价
|
|
147
|
+
if (raw.includes("orchestrator")) {
|
|
148
|
+
const hint = `${raw} ${(displayName ?? "").toLowerCase()}`;
|
|
149
|
+
const flavorMatch = hint.match(/\b(neon|carbon|argon|hydrogen)\b/);
|
|
150
|
+
if (flavorMatch) {
|
|
151
|
+
push(`gemini-4-${flavorMatch[1]}`);
|
|
152
|
+
} else {
|
|
153
|
+
push("gemini-4-carbon");
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return candidates;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* 从 Pi 内置模型目录动态解析 Antigravity 模型对应的官方参考定价(美元/百万 Token,含缓存读写与阶梯价)。
|
|
162
|
+
* 订阅制账号在 Pi 状态栏中会自动附加 `(sub)` 标记,并支持 `/model`、`/usage` 与缓存浪费统计展示。
|
|
163
|
+
*/
|
|
164
|
+
export function resolveBuiltinModelCost(
|
|
165
|
+
modelId: string,
|
|
166
|
+
displayName?: string,
|
|
167
|
+
): ChatModelConfig["cost"] {
|
|
168
|
+
const index = getBuiltinCostIndex();
|
|
169
|
+
for (const key of buildPricingLookupCandidates(modelId, displayName)) {
|
|
170
|
+
const matched = index.get(key);
|
|
171
|
+
if (matched) {
|
|
172
|
+
return cloneModelCost(matched);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return cloneModelCost(ZERO_MODEL_COST);
|
|
176
|
+
}
|
|
177
|
+
|
|
36
178
|
export interface DiscoveredCatalogSnapshot {
|
|
37
179
|
version: 1;
|
|
38
180
|
updatedAt: number;
|
|
@@ -151,12 +293,7 @@ function makeChatModelConfig(
|
|
|
151
293
|
reasoning: hasReasoning,
|
|
152
294
|
thinkingLevelMap: hasReasoning ? buildThinkingLevelMap(efforts) : undefined,
|
|
153
295
|
input: specs.supportsImage ? ["text", "image"] : ["text"],
|
|
154
|
-
cost:
|
|
155
|
-
input: 0,
|
|
156
|
-
output: 0,
|
|
157
|
-
cacheRead: 0,
|
|
158
|
-
cacheWrite: 0,
|
|
159
|
-
},
|
|
296
|
+
cost: resolveBuiltinModelCost(id, name),
|
|
160
297
|
contextWindow: specs.contextWindow,
|
|
161
298
|
maxTokens: specs.maxTokens,
|
|
162
299
|
};
|
|
@@ -289,9 +426,10 @@ export function readCachedCatalog(env: NodeJS.ProcessEnv = process.env): Discove
|
|
|
289
426
|
if (!fs.existsSync(cachePath)) return undefined;
|
|
290
427
|
const raw = JSON.parse(fs.readFileSync(cachePath, "utf8")) as DiscoveredCatalogSnapshot;
|
|
291
428
|
if (raw?.version === 1 && Array.isArray(raw.models) && raw.models.length > 0) {
|
|
292
|
-
//
|
|
429
|
+
// 应用最新观测到的窗口校准,并为旧版零费用缓存自动补全 Pi 内置目录参考定价
|
|
293
430
|
const calibrated = raw.models.map((m) => ({
|
|
294
431
|
...m,
|
|
432
|
+
cost: hasNonZeroModelCost(m.cost) ? m.cost : resolveBuiltinModelCost(m.id, m.name),
|
|
295
433
|
contextWindow: getObservedContextWindow(m.id) ?? m.contextWindow,
|
|
296
434
|
}));
|
|
297
435
|
return { ...raw, models: calibrated };
|
|
@@ -53,18 +53,123 @@ interface PendingAnnouncementWaiter {
|
|
|
53
53
|
timer: ReturnType<typeof setTimeout>;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
function inferLiteralJsonType(value: unknown): string | undefined {
|
|
57
|
+
if (typeof value === "string") return "string";
|
|
58
|
+
if (typeof value === "boolean") return "boolean";
|
|
59
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
60
|
+
return Number.isInteger(value) ? "integer" : "number";
|
|
61
|
+
}
|
|
62
|
+
if (value === null) return "null";
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isPureLiteralSchemaBranch(
|
|
67
|
+
node: unknown,
|
|
68
|
+
): node is Record<string, unknown> & { const: unknown } {
|
|
69
|
+
if (!node || typeof node !== "object" || Array.isArray(node)) return false;
|
|
70
|
+
const rec = node as Record<string, unknown>;
|
|
71
|
+
if (!("const" in rec)) return false;
|
|
72
|
+
for (const key of Object.keys(rec)) {
|
|
73
|
+
if (key !== "const" && key !== "type" && key !== "description" && key !== "title") {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function normalizeJsonSchemaNode(node: unknown, depth = 0): unknown {
|
|
81
|
+
if (depth > 16 || !node || typeof node !== "object") {
|
|
82
|
+
return node;
|
|
83
|
+
}
|
|
84
|
+
if (Array.isArray(node)) {
|
|
85
|
+
return node.map((item) => normalizeJsonSchemaNode(item, depth + 1));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const rec = { ...(node as Record<string, unknown>) };
|
|
89
|
+
delete rec.$schema;
|
|
90
|
+
|
|
91
|
+
// 将 TypeBox Type.Union([Type.Literal(...), ...]) 生成的 anyOf/oneOf 常量联合折叠为标准 type + enum,
|
|
92
|
+
// 避免 Gemini / AGY MCP 协议转换器丢弃 anyOf 导致枚举参数退化为空对象 {}(如 context_recall 的 part/imageVersion/view)
|
|
93
|
+
for (const unionKey of ["anyOf", "oneOf"] as const) {
|
|
94
|
+
const branches = rec[unionKey];
|
|
95
|
+
if (Array.isArray(branches) && branches.length > 0 && branches.every(isPureLiteralSchemaBranch)) {
|
|
96
|
+
const values = branches.map((b) => b.const);
|
|
97
|
+
const inferredTypes = new Set(
|
|
98
|
+
values
|
|
99
|
+
.map((v) => inferLiteralJsonType(v))
|
|
100
|
+
.filter((t): t is string => t !== undefined),
|
|
101
|
+
);
|
|
102
|
+
delete rec[unionKey];
|
|
103
|
+
rec.enum = values;
|
|
104
|
+
if (!rec.type && inferredTypes.size === 1) {
|
|
105
|
+
rec.type = Array.from(inferredTypes)[0];
|
|
106
|
+
} else if (
|
|
107
|
+
!rec.type &&
|
|
108
|
+
inferredTypes.size === 2 &&
|
|
109
|
+
inferredTypes.has("integer") &&
|
|
110
|
+
inferredTypes.has("number")
|
|
111
|
+
) {
|
|
112
|
+
rec.type = "number";
|
|
113
|
+
}
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if ("const" in rec && !Array.isArray(rec.enum)) {
|
|
119
|
+
const val = rec.const;
|
|
120
|
+
delete rec.const;
|
|
121
|
+
rec.enum = [val];
|
|
122
|
+
if (!rec.type) {
|
|
123
|
+
const inferred = inferLiteralJsonType(val);
|
|
124
|
+
if (inferred) rec.type = inferred;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (!rec.type && rec.properties && typeof rec.properties === "object") {
|
|
129
|
+
rec.type = "object";
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (rec.properties && typeof rec.properties === "object" && !Array.isArray(rec.properties)) {
|
|
133
|
+
const nextProps: Record<string, unknown> = {};
|
|
134
|
+
for (const [k, v] of Object.entries(rec.properties as Record<string, unknown>)) {
|
|
135
|
+
nextProps[k] = normalizeJsonSchemaNode(v, depth + 1);
|
|
136
|
+
}
|
|
137
|
+
rec.properties = nextProps;
|
|
138
|
+
}
|
|
139
|
+
if (rec.items && typeof rec.items === "object") {
|
|
140
|
+
rec.items = normalizeJsonSchemaNode(rec.items, depth + 1);
|
|
141
|
+
}
|
|
142
|
+
if (rec.additionalProperties && typeof rec.additionalProperties === "object") {
|
|
143
|
+
rec.additionalProperties = normalizeJsonSchemaNode(rec.additionalProperties, depth + 1);
|
|
144
|
+
}
|
|
145
|
+
for (const compositeKey of ["anyOf", "oneOf", "allOf"] as const) {
|
|
146
|
+
if (Array.isArray(rec[compositeKey])) {
|
|
147
|
+
rec[compositeKey] = (rec[compositeKey] as unknown[]).map((b) =>
|
|
148
|
+
normalizeJsonSchemaNode(b, depth + 1),
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
for (const defsKey of ["$defs", "definitions"] as const) {
|
|
153
|
+
if (rec[defsKey] && typeof rec[defsKey] === "object" && !Array.isArray(rec[defsKey])) {
|
|
154
|
+
const nextDefs: Record<string, unknown> = {};
|
|
155
|
+
for (const [k, v] of Object.entries(rec[defsKey] as Record<string, unknown>)) {
|
|
156
|
+
nextDefs[k] = normalizeJsonSchemaNode(v, depth + 1);
|
|
157
|
+
}
|
|
158
|
+
rec[defsKey] = nextDefs;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return rec;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** JSON Schema 清洗:剥离 TypeBox Symbol、非标准顶层元字段并将字面量 anyOf/oneOf 规整为标准 enum */
|
|
57
165
|
export function sanitizeJsonSchemaForMcp(rawSchema: unknown): Record<string, unknown> {
|
|
58
166
|
try {
|
|
59
|
-
const cloned = JSON.parse(JSON.stringify(rawSchema ?? { type: "object", properties: {} }))
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
cloned.type = "object";
|
|
66
|
-
}
|
|
67
|
-
return cloned;
|
|
167
|
+
const cloned = JSON.parse(JSON.stringify(rawSchema ?? { type: "object", properties: {} }));
|
|
168
|
+
const normalized = normalizeJsonSchemaNode(cloned);
|
|
169
|
+
if (normalized && typeof normalized === "object" && !Array.isArray(normalized)) {
|
|
170
|
+
return normalized as Record<string, unknown>;
|
|
171
|
+
}
|
|
172
|
+
return { type: "object", properties: {} };
|
|
68
173
|
} catch {
|
|
69
174
|
return { type: "object", properties: {} };
|
|
70
175
|
}
|
|
@@ -618,9 +723,13 @@ export class LocalHttpMcpBridge {
|
|
|
618
723
|
return;
|
|
619
724
|
}
|
|
620
725
|
|
|
621
|
-
// 1. 对齐宿主工具的参数预处理与 JSON Schema
|
|
726
|
+
// 1. 对齐宿主工具的参数预处理与 JSON Schema 参数预校验(与 tools/list 暴露的规整 Schema 保持一致)
|
|
622
727
|
const normalizedArgs = normalizeHostToolArguments(toolName, rawArgs, toolDef);
|
|
623
|
-
const validation = validateToolArguments(
|
|
728
|
+
const validation = validateToolArguments(
|
|
729
|
+
toolName,
|
|
730
|
+
normalizedArgs,
|
|
731
|
+
sanitizeJsonSchemaForMcp(toolDef.parameters),
|
|
732
|
+
);
|
|
624
733
|
if (!validation.valid) {
|
|
625
734
|
binding.onRejectedCall?.(toolName);
|
|
626
735
|
res.writeHead(200);
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
type ToolMode,
|
|
9
9
|
resolveAgyConversationsDir,
|
|
10
10
|
} from "../config.ts";
|
|
11
|
-
import { computeTranscriptDigest } from "./reconcile.ts";
|
|
11
|
+
import { computeTranscriptDigest, type PreloadedSqliteTurn } from "./reconcile.ts";
|
|
12
12
|
|
|
13
13
|
export const AGY_SESSION_ANCHOR_CUSTOM_TYPE = "antigravity-acp-state";
|
|
14
14
|
|
|
@@ -35,6 +35,10 @@ export interface AgySessionAnchor {
|
|
|
35
35
|
toolsDigest: string;
|
|
36
36
|
/** 是否为通过 `/agy sessions` 刚导入尚未经历首轮请求对齐的原始会话锚点 */
|
|
37
37
|
importedRaw?: boolean;
|
|
38
|
+
/** 可选:该 AGY 会话实际承载的 `pi-traffic-optimization` 归档投影指纹 */
|
|
39
|
+
projectionDigest?: string;
|
|
40
|
+
/** 可选:该 AGY 会话实际承载的 `pi-traffic-optimization` 归档占位符总数 */
|
|
41
|
+
projectedCount?: number;
|
|
38
42
|
/** 可选的本地 SQLite 会话数据库检查点水位 */
|
|
39
43
|
dbCheckpoint?: SqliteDbCheckpoint;
|
|
40
44
|
}
|
|
@@ -698,6 +702,271 @@ export async function forkSqliteConversationAtCheckpoint(
|
|
|
698
702
|
}
|
|
699
703
|
}
|
|
700
704
|
|
|
705
|
+
const CORTEX_STEP_TYPE_USER_INPUT = 14;
|
|
706
|
+
const CORTEX_STEP_TYPE_PLANNER_RESPONSE = 15;
|
|
707
|
+
const CORTEX_STEP_STATUS_DONE = 3;
|
|
708
|
+
const CORTEX_TRAJECTORY_TYPE_INTERACTIVE_CASCADE = 4;
|
|
709
|
+
const CORTEX_TRAJECTORY_SOURCE_CLI = 17;
|
|
710
|
+
|
|
711
|
+
function encodeProtobufVarint(value: number | bigint): Buffer {
|
|
712
|
+
let v = typeof value === "bigint" ? value : BigInt(value);
|
|
713
|
+
const out: number[] = [];
|
|
714
|
+
while (v >= 0x80n) {
|
|
715
|
+
out.push(Number((v & 0x7fn) | 0x80n));
|
|
716
|
+
v >>= 7n;
|
|
717
|
+
}
|
|
718
|
+
out.push(Number(v));
|
|
719
|
+
return Buffer.from(out);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function encodeProtobufVarintField(fieldNo: number, value: number | bigint): Buffer {
|
|
723
|
+
return Buffer.concat([encodeProtobufVarint((fieldNo << 3) | 0), encodeProtobufVarint(value)]);
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
function encodeProtobufBytesField(fieldNo: number, payload: Buffer | string): Buffer {
|
|
727
|
+
const buf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload, "utf8");
|
|
728
|
+
return Buffer.concat([
|
|
729
|
+
encodeProtobufVarint((fieldNo << 3) | 2),
|
|
730
|
+
encodeProtobufVarint(buf.length),
|
|
731
|
+
buf,
|
|
732
|
+
]);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/** 构造 AGY `CortexStep`(`USER_INPUT`)最小标准 Protobuf 载荷 */
|
|
736
|
+
export function encodeUserInputStepPayload(text: string): Buffer {
|
|
737
|
+
// CortexStepUserInput: field 2 = user_response, field 3 = items (TextOrScopeItem { field 1 = text })
|
|
738
|
+
const textItem = encodeProtobufBytesField(1, text);
|
|
739
|
+
const userInput = Buffer.concat([
|
|
740
|
+
encodeProtobufBytesField(2, text),
|
|
741
|
+
encodeProtobufBytesField(3, textItem),
|
|
742
|
+
]);
|
|
743
|
+
return Buffer.concat([
|
|
744
|
+
encodeProtobufVarintField(1, CORTEX_STEP_TYPE_USER_INPUT),
|
|
745
|
+
encodeProtobufVarintField(4, CORTEX_STEP_STATUS_DONE),
|
|
746
|
+
encodeProtobufBytesField(19, userInput),
|
|
747
|
+
]);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** 构造 AGY `CortexStep`(`PLANNER_RESPONSE`)最小标准 Protobuf 载荷 */
|
|
751
|
+
export function encodePlannerResponseStepPayload(text: string): Buffer {
|
|
752
|
+
// CortexStepPlannerResponse: field 1 = response, field 8 = modified_response
|
|
753
|
+
const plannerResponse = Buffer.concat([
|
|
754
|
+
encodeProtobufBytesField(1, text),
|
|
755
|
+
encodeProtobufBytesField(8, text),
|
|
756
|
+
]);
|
|
757
|
+
return Buffer.concat([
|
|
758
|
+
encodeProtobufVarintField(1, CORTEX_STEP_TYPE_PLANNER_RESPONSE),
|
|
759
|
+
encodeProtobufVarintField(4, CORTEX_STEP_STATUS_DONE),
|
|
760
|
+
encodeProtobufBytesField(20, plannerResponse),
|
|
761
|
+
]);
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* 新建一个独立 UUID 的 AGY 本地 SQLite 会话数据库,并将超长历史的多个安全分片以
|
|
766
|
+
* `(USER_INPUT, PLANNER_RESPONSE)` 交替步预注入 `steps` 表,供随后通过 `session/resume`
|
|
767
|
+
* 零额外 LLM 调用直接恢复,规避 `agy` 单条 `USER_INPUT` 64,000 token 截断上限。
|
|
768
|
+
*
|
|
769
|
+
* 严格仅新建独立 UUID 文件,永不改动任何已有会话库;任何异常均立即清理临时文件并返回 `undefined`。
|
|
770
|
+
*/
|
|
771
|
+
export async function createPreloadedSqliteConversation(
|
|
772
|
+
config: BridgeConfig,
|
|
773
|
+
turns: readonly PreloadedSqliteTurn[],
|
|
774
|
+
): Promise<string | undefined> {
|
|
775
|
+
if (!config.enableSqliteFork || turns.length === 0) {
|
|
776
|
+
return undefined;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
const sqlite = await loadNodeSqlite();
|
|
780
|
+
if (!sqlite) return undefined;
|
|
781
|
+
|
|
782
|
+
const convDir = resolveAgyConversationsDir(config);
|
|
783
|
+
try {
|
|
784
|
+
fs.mkdirSync(convDir, { recursive: true });
|
|
785
|
+
} catch {
|
|
786
|
+
return undefined;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
const sessionId = crypto.randomUUID();
|
|
790
|
+
const dbPath = path.join(convDir, `${sessionId}.db`);
|
|
791
|
+
|
|
792
|
+
let db: import("node:sqlite").DatabaseSync | undefined;
|
|
793
|
+
try {
|
|
794
|
+
db = openSqliteWithTimeout(sqlite, dbPath, false);
|
|
795
|
+
db.exec(`
|
|
796
|
+
PRAGMA user_version = 1;
|
|
797
|
+
CREATE TABLE trajectory_meta (
|
|
798
|
+
trajectory_id text,
|
|
799
|
+
cascade_id text,
|
|
800
|
+
trajectory_type integer,
|
|
801
|
+
source integer,
|
|
802
|
+
PRIMARY KEY (trajectory_id)
|
|
803
|
+
);
|
|
804
|
+
CREATE TABLE steps (
|
|
805
|
+
idx integer,
|
|
806
|
+
step_type integer NOT NULL DEFAULT 0,
|
|
807
|
+
status integer NOT NULL DEFAULT 0,
|
|
808
|
+
has_subtrajectory numeric NOT NULL DEFAULT false,
|
|
809
|
+
metadata blob,
|
|
810
|
+
error_details blob,
|
|
811
|
+
permissions blob,
|
|
812
|
+
task_details blob,
|
|
813
|
+
render_info blob,
|
|
814
|
+
step_payload blob,
|
|
815
|
+
step_format integer NOT NULL DEFAULT 0,
|
|
816
|
+
PRIMARY KEY (idx)
|
|
817
|
+
);
|
|
818
|
+
CREATE INDEX idx_steps_status ON steps(status);
|
|
819
|
+
CREATE INDEX idx_steps_step_type ON steps(step_type);
|
|
820
|
+
CREATE TABLE gen_metadata (
|
|
821
|
+
idx integer,
|
|
822
|
+
data blob,
|
|
823
|
+
size integer NOT NULL DEFAULT 0,
|
|
824
|
+
PRIMARY KEY (idx)
|
|
825
|
+
);
|
|
826
|
+
CREATE TABLE executor_metadata (
|
|
827
|
+
idx integer,
|
|
828
|
+
data blob,
|
|
829
|
+
PRIMARY KEY (idx)
|
|
830
|
+
);
|
|
831
|
+
CREATE TABLE parent_references (
|
|
832
|
+
idx integer,
|
|
833
|
+
data blob,
|
|
834
|
+
PRIMARY KEY (idx)
|
|
835
|
+
);
|
|
836
|
+
CREATE TABLE trajectory_metadata_blob (
|
|
837
|
+
id text DEFAULT "main",
|
|
838
|
+
data blob,
|
|
839
|
+
PRIMARY KEY (id)
|
|
840
|
+
);
|
|
841
|
+
CREATE TABLE battle_mode_infos (
|
|
842
|
+
idx integer,
|
|
843
|
+
data blob,
|
|
844
|
+
PRIMARY KEY (idx)
|
|
845
|
+
);
|
|
846
|
+
`);
|
|
847
|
+
|
|
848
|
+
db.exec("BEGIN IMMEDIATE");
|
|
849
|
+
db.prepare(
|
|
850
|
+
"INSERT INTO trajectory_meta (trajectory_id, cascade_id, trajectory_type, source) VALUES (?, ?, ?, ?)",
|
|
851
|
+
).run(
|
|
852
|
+
sessionId,
|
|
853
|
+
sessionId,
|
|
854
|
+
CORTEX_TRAJECTORY_TYPE_INTERACTIVE_CASCADE,
|
|
855
|
+
CORTEX_TRAJECTORY_SOURCE_CLI,
|
|
856
|
+
);
|
|
857
|
+
|
|
858
|
+
const insertStep = db.prepare(
|
|
859
|
+
"INSERT INTO steps (idx, step_type, status, has_subtrajectory, step_payload, step_format) VALUES (?, ?, ?, 0, ?, 0)",
|
|
860
|
+
);
|
|
861
|
+
let idx = 0;
|
|
862
|
+
for (const turn of turns) {
|
|
863
|
+
insertStep.run(
|
|
864
|
+
idx++,
|
|
865
|
+
CORTEX_STEP_TYPE_USER_INPUT,
|
|
866
|
+
CORTEX_STEP_STATUS_DONE,
|
|
867
|
+
encodeUserInputStepPayload(turn.userText),
|
|
868
|
+
);
|
|
869
|
+
insertStep.run(
|
|
870
|
+
idx++,
|
|
871
|
+
CORTEX_STEP_TYPE_PLANNER_RESPONSE,
|
|
872
|
+
CORTEX_STEP_STATUS_DONE,
|
|
873
|
+
encodePlannerResponseStepPayload(turn.assistantAckText),
|
|
874
|
+
);
|
|
875
|
+
}
|
|
876
|
+
db.exec("COMMIT");
|
|
877
|
+
return sessionId;
|
|
878
|
+
} catch {
|
|
879
|
+
try {
|
|
880
|
+
db?.exec("ROLLBACK");
|
|
881
|
+
} catch {
|
|
882
|
+
// 忽略
|
|
883
|
+
}
|
|
884
|
+
cleanupDbFilesSafe(dbPath);
|
|
885
|
+
return undefined;
|
|
886
|
+
} finally {
|
|
887
|
+
try {
|
|
888
|
+
db?.close();
|
|
889
|
+
} catch {
|
|
890
|
+
// 忽略
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* 向刚通过 `forkSqliteConversationAtCheckpoint` 克隆出的新分叉 `.db` 末尾追加预注入分片步。
|
|
897
|
+
* 仅用于尚未被 `agy` 打开的新分叉副本,严禁对正在运行的原库直接调用。
|
|
898
|
+
*/
|
|
899
|
+
export async function appendPreloadedTurnsToSqliteConversation(
|
|
900
|
+
config: BridgeConfig,
|
|
901
|
+
forkedSessionId: string,
|
|
902
|
+
turns: readonly PreloadedSqliteTurn[],
|
|
903
|
+
): Promise<boolean> {
|
|
904
|
+
if (!config.enableSqliteFork || !forkedSessionId || turns.length === 0) {
|
|
905
|
+
return false;
|
|
906
|
+
}
|
|
907
|
+
const dbPath = path.join(resolveAgyConversationsDir(config), `${forkedSessionId}.db`);
|
|
908
|
+
if (!fs.existsSync(dbPath)) {
|
|
909
|
+
return false;
|
|
910
|
+
}
|
|
911
|
+
const sqlite = await loadNodeSqlite();
|
|
912
|
+
if (!sqlite) return false;
|
|
913
|
+
|
|
914
|
+
let db: import("node:sqlite").DatabaseSync | undefined;
|
|
915
|
+
try {
|
|
916
|
+
db = openSqliteWithTimeout(sqlite, dbPath, false);
|
|
917
|
+
if (!verifyRequiredTables(db)) {
|
|
918
|
+
return false;
|
|
919
|
+
}
|
|
920
|
+
const lastRow = db
|
|
921
|
+
.prepare("SELECT idx, step_type FROM steps ORDER BY idx DESC LIMIT 1")
|
|
922
|
+
.get() as { idx?: number; step_type?: number } | undefined;
|
|
923
|
+
let nextIdx = typeof lastRow?.idx === "number" ? lastRow.idx + 1 : 0;
|
|
924
|
+
|
|
925
|
+
db.exec("BEGIN IMMEDIATE");
|
|
926
|
+
const insertStep = db.prepare(
|
|
927
|
+
"INSERT INTO steps (idx, step_type, status, has_subtrajectory, step_payload, step_format) VALUES (?, ?, ?, 0, ?, 0)",
|
|
928
|
+
);
|
|
929
|
+
// 若原分叉尾部停在 USER_INPUT,先补一条中性 PLANNER_RESPONSE 保持严格交替角色合法性
|
|
930
|
+
if (lastRow?.step_type === CORTEX_STEP_TYPE_USER_INPUT) {
|
|
931
|
+
insertStep.run(
|
|
932
|
+
nextIdx++,
|
|
933
|
+
CORTEX_STEP_TYPE_PLANNER_RESPONSE,
|
|
934
|
+
CORTEX_STEP_STATUS_DONE,
|
|
935
|
+
encodePlannerResponseStepPayload("Continuing session context."),
|
|
936
|
+
);
|
|
937
|
+
}
|
|
938
|
+
for (const turn of turns) {
|
|
939
|
+
insertStep.run(
|
|
940
|
+
nextIdx++,
|
|
941
|
+
CORTEX_STEP_TYPE_USER_INPUT,
|
|
942
|
+
CORTEX_STEP_STATUS_DONE,
|
|
943
|
+
encodeUserInputStepPayload(turn.userText),
|
|
944
|
+
);
|
|
945
|
+
insertStep.run(
|
|
946
|
+
nextIdx++,
|
|
947
|
+
CORTEX_STEP_TYPE_PLANNER_RESPONSE,
|
|
948
|
+
CORTEX_STEP_STATUS_DONE,
|
|
949
|
+
encodePlannerResponseStepPayload(turn.assistantAckText),
|
|
950
|
+
);
|
|
951
|
+
}
|
|
952
|
+
db.exec("COMMIT");
|
|
953
|
+
return true;
|
|
954
|
+
} catch {
|
|
955
|
+
try {
|
|
956
|
+
db?.exec("ROLLBACK");
|
|
957
|
+
} catch {
|
|
958
|
+
// 忽略
|
|
959
|
+
}
|
|
960
|
+
return false;
|
|
961
|
+
} finally {
|
|
962
|
+
try {
|
|
963
|
+
db?.close();
|
|
964
|
+
} catch {
|
|
965
|
+
// 忽略
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
|
|
701
970
|
function cleanupDbFilesSafe(baseDbPath: string): void {
|
|
702
971
|
for (const ext of ["", "-wal", "-shm", "-journal"]) {
|
|
703
972
|
try {
|
|
@@ -327,6 +327,11 @@ function buildPureModeToolGuidelines(declaredTools: readonly Tool[]): string[] {
|
|
|
327
327
|
"Use edit for targeted changes. Batch changes to one file in a single call; each edits[].oldText must exactly and uniquely match the original file.",
|
|
328
328
|
);
|
|
329
329
|
}
|
|
330
|
+
if (names.has("context_recall")) {
|
|
331
|
+
guidelines.push(
|
|
332
|
+
"For archived historical tool outputs or images referencing ctx:// handles, prefer context_recall over re-reading files or re-running commands unless current live state is explicitly required.",
|
|
333
|
+
);
|
|
334
|
+
}
|
|
330
335
|
|
|
331
336
|
guidelines.push("Be concise in your responses.");
|
|
332
337
|
guidelines.push("Show file paths clearly when working with files without forcing file:// URLs.");
|