pi-antigravity-bridge 0.1.7 → 0.1.8

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,24 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.8] - 2026-11-22
4
+
5
+ ### Added
6
+
7
+ - 自动为注册到 Pi 的 Antigravity 模型补充官方参考定价,并按单价计算每步与累计费用,同时为已有旧缓存自动补全价格数据。
8
+ - 适配 `pi-traffic-optimization` 扩展:支持在批量上下文归档后按需瘦身会话、保留完整 `ctx://` 句柄与 `context_recall` 召回指引,以及关闭优化后恢复完整上下文。
9
+
10
+ ### Changed
11
+
12
+ - 将 MCP 工具声明中的字面量联合参数规整为标准枚举类型,提升 `context_recall` 等扩展工具的参数可见性与校验提示准确度。
13
+ - 收紧大批量多工具调用拆分时的预留切片总扣减规模,降低对 Pi 原生缓存未命中统计的干扰。
14
+
15
+ ### Fixed
16
+
17
+ - 修复真实 `0%` 缓存未命中后缓存基准未清零,导致回退路径沿用旧高命中率或被整轮累计均值覆盖的问题。
18
+ - 修复跨生成残留切片混入新生成以及多条上游生成叠加混算导致缓存命中率与输出统计失真的问题。
19
+ - 修复中间工具步在本地会话记录延迟落盘时缺少重试的问题,并移除未观测缓存前的固定 85% 估算。
20
+ - 修复 `pi-traffic-optimization` 压缩图片(PNG 转 WebP)或归档历史图片后会话摘要失配导致误拆热缓存与重启恢复锚点失效的问题。
21
+
3
22
  ## [0.1.7] - 2026-11-21
4
23
 
5
24
  ### Changed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-antigravity-bridge",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "Google Antigravity CLI (agy acp) agent backend bridge for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -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
- /** JSON Schema 清洗:剥离 TypeBox Symbol 及可能触发上游严格解析器异常的非标准顶层元字段 */
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: {} })) as Record<
60
- string,
61
- unknown
62
- >;
63
- delete cloned.$schema;
64
- if (!cloned.type && cloned.properties) {
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(toolName, normalizedArgs, toolDef.parameters);
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);
@@ -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
  }
@@ -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.");
@@ -24,11 +24,82 @@ export function extractVisibleMessages(
24
24
  );
25
25
  }
26
26
 
27
+ const TRAFFIC_OPT_TOOL_PLACEHOLDER_REGEX =
28
+ /^\[(?:已归档|历史 recall 页)\s+(ctx:\/\/tool\/[a-f0-9]{16,64})\]/;
29
+ const TRAFFIC_OPT_IMAGE_PLACEHOLDER_REGEX =
30
+ /^\[已归档图片\s+(ctx:\/\/image\/[a-f0-9]{16,64})\]/;
31
+
32
+ /** 判断文本块是否为 `pi-traffic-optimization` 归档投影生成的工具/recall 页占位符 */
33
+ export function isTrafficOptToolPlaceholder(text: string): boolean {
34
+ return TRAFFIC_OPT_TOOL_PLACEHOLDER_REGEX.test(text);
35
+ }
36
+
37
+ /** 判断文本块是否为 `pi-traffic-optimization` 归档投影生成的图片占位符 */
38
+ export function isTrafficOptImagePlaceholder(text: string): boolean {
39
+ return TRAFFIC_OPT_IMAGE_PLACEHOLDER_REGEX.test(text);
40
+ }
41
+
42
+ export interface TrafficOptProjectionState {
43
+ /** 消息序列中存在的归档投影占位符总数(工具结果、历史 recall 页与图片) */
44
+ archivedCount: number;
45
+ /** 有序归档占位符集合的确定性 SHA-256 指纹(无投影时为空字符串) */
46
+ projectionDigest: string;
47
+ }
48
+
49
+ /**
50
+ * 扫描模型可见消息中的 `pi-traffic-optimization` 归档投影状态,
51
+ * 用于在批量 GC 触发后精准检测投影变化并驱动有状态 AGY 会话按需瘦身重建,同时在非 GC 轮次零打扰热缓存。
52
+ */
53
+ export function inspectTrafficOptProjectionState(
54
+ visibleMessages: readonly (UserMessage | AssistantMessage | ToolResultMessage)[],
55
+ ): TrafficOptProjectionState {
56
+ const entries: string[] = [];
57
+ for (let i = 0; i < visibleMessages.length; i++) {
58
+ const msg = visibleMessages[i];
59
+ if (msg.role === "toolResult") {
60
+ for (let j = 0; j < msg.content.length; j++) {
61
+ const part = msg.content[j];
62
+ if (part.type !== "text") continue;
63
+ const toolMatch = TRAFFIC_OPT_TOOL_PLACEHOLDER_REGEX.exec(part.text);
64
+ if (toolMatch) {
65
+ entries.push(`t:${msg.toolCallId}:${j}:${toolMatch[1]}`);
66
+ continue;
67
+ }
68
+ const imgMatch = TRAFFIC_OPT_IMAGE_PLACEHOLDER_REGEX.exec(part.text);
69
+ if (imgMatch) {
70
+ entries.push(`ti:${msg.toolCallId}:${j}:${imgMatch[1]}`);
71
+ }
72
+ }
73
+ } else if (msg.role === "user" && Array.isArray(msg.content)) {
74
+ for (let j = 0; j < msg.content.length; j++) {
75
+ const part = msg.content[j];
76
+ if (part.type !== "text") continue;
77
+ const imgMatch = TRAFFIC_OPT_IMAGE_PLACEHOLDER_REGEX.exec(part.text);
78
+ if (imgMatch) {
79
+ entries.push(`ui:${i}:${j}:${imgMatch[1]}`);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ if (entries.length === 0) {
85
+ return { archivedCount: 0, projectionDigest: "" };
86
+ }
87
+ const hash = crypto.createHash("sha256");
88
+ for (const item of entries) {
89
+ hash.update(`${item}\n`);
90
+ }
91
+ return {
92
+ archivedCount: entries.length,
93
+ projectionDigest: hash.digest("hex"),
94
+ };
95
+ }
96
+
27
97
  /**
28
98
  * 提取对话结构身份特征用于会话连续性与分支锚点校验。
29
- * 对 `ToolResultMessage` 与历史图片块仅采集不可变结构标识(`toolCallId`、`toolName`、`isError` 与图片占位标记),
30
- * 确保 `pi-traffic-optimization`(工具输出归档投影)或 `pi-orca-images`(历史图片重压缩)等 `context` 阶段钩子改写载荷后,
31
- * 仍能 100% 精确命中活跃会话与历史锚点,绝不误拆健康热缓存会话。
99
+ * 对 `ToolResultMessage` 与历史图片块仅采集不可变结构标识(忽略图片压缩后的 `mimeType` 变更,
100
+ * 并将用户图片归档占位符归一为 `{ type: "image" }`),
101
+ * 确保 `pi-traffic-optimization`(图片 WebP 压缩、工具输出/图片归档投影)或 `pi-orca-images` 等 `context` 钩子改写载荷后,
102
+ * 原始 `turn_end` 锚点与投影后的 `streamSimple` 上下文仍 100% 精确匹配,绝不误拆健康热缓存会话。
32
103
  */
33
104
  function canonicalizeMessage(msg: UserMessage | AssistantMessage | ToolResultMessage): unknown {
34
105
  if (msg.role === "user") {
@@ -38,8 +109,8 @@ function canonicalizeMessage(msg: UserMessage | AssistantMessage | ToolResultMes
38
109
  return {
39
110
  role: "user",
40
111
  parts: msg.content.map((part) =>
41
- part.type === "image"
42
- ? { type: "image", mimeType: part.mimeType }
112
+ part.type === "image" || isTrafficOptImagePlaceholder(part.text)
113
+ ? { type: "image" }
43
114
  : { type: "text", text: part.text },
44
115
  ),
45
116
  };
@@ -231,6 +302,8 @@ export function buildDetachedToolResultBlocks(
231
302
 
232
303
  /** 历史检查点重放文本最大 UTF-8 字节预算(严防超出后端单次 Prompt 上限导致尾部最新用户提问被硬截断) */
233
304
  export const MAX_FRESH_REPLAY_HISTORY_BYTES = 120_000;
305
+ /** 当历史已由 `pi-traffic-optimization` 归档瘦身时适当放宽重放预算,尽量完整保留全部紧凑 `ctx://` 句柄 */
306
+ export const MAX_PROJECTED_REPLAY_HISTORY_BYTES = 180_000;
234
307
  /** 历史检查点重放最多保留的近期历史图片数(更早图片转为占位文本,防单行 JSON-RPC 体积失控) */
235
308
  const MAX_FRESH_REPLAY_HISTORY_IMAGES = 6;
236
309
  const MAX_SINGLE_REPLAY_TOOL_TEXT_BYTES = 4_000;
@@ -311,11 +384,14 @@ function serializeReplayHistoryEntry(
311
384
  .filter((c): c is TextContent => c.type === "text")
312
385
  .map((c) => c.text)
313
386
  .join("\n");
314
- const cappedTexts = truncateUtf8Middle(
315
- rawTexts,
316
- MAX_SINGLE_REPLAY_TOOL_TEXT_BYTES,
317
- "\n...[tool output truncated in replay]...\n",
318
- );
387
+ // 对 pi-traffic-optimization 已生成的紧凑 ctx:// 归档占位符保留原文不裁切,确保 handle 与 context_recall 指引完整
388
+ const cappedTexts = isTrafficOptToolPlaceholder(rawTexts)
389
+ ? rawTexts
390
+ : truncateUtf8Middle(
391
+ rawTexts,
392
+ MAX_SINGLE_REPLAY_TOOL_TEXT_BYTES,
393
+ "\n...[tool output truncated in replay]...\n",
394
+ );
319
395
  entryBlocks.push({
320
396
  type: "text",
321
397
  text: `<tool_result id="${msg.toolCallId}" tool="${msg.toolName}" status="${status}">\n${cappedTexts}\n</tool_result>`,
@@ -343,11 +419,16 @@ function serializeReplayHistoryEntry(
343
419
  */
344
420
  export function buildFreshReplayPromptBlocks(
345
421
  visibleMessages: readonly (UserMessage | AssistantMessage | ToolResultMessage)[],
346
- maxHistoryBytes = MAX_FRESH_REPLAY_HISTORY_BYTES,
422
+ maxHistoryBytes?: number,
347
423
  ): AcpPromptBlock[] {
348
424
  if (visibleMessages.length === 0) {
349
425
  return [{ type: "text", text: "Continue." }];
350
426
  }
427
+ const effectiveMaxHistoryBytes =
428
+ maxHistoryBytes ??
429
+ (inspectTrafficOptProjectionState(visibleMessages).archivedCount > 0
430
+ ? MAX_PROJECTED_REPLAY_HISTORY_BYTES
431
+ : MAX_FRESH_REPLAY_HISTORY_BYTES);
351
432
 
352
433
  // 若仅有单轮用户消息,直接原样发送无需包裹检查点标签
353
434
  const allUsers = visibleMessages.every((m) => m.role === "user");
@@ -383,7 +464,7 @@ export function buildFreshReplayPromptBlocks(
383
464
  }
384
465
  if (
385
466
  selectedReversed.length > 0 &&
386
- usedHistoryBytes + serialized.textBytes > maxHistoryBytes
467
+ usedHistoryBytes + serialized.textBytes > effectiveMaxHistoryBytes
387
468
  ) {
388
469
  omittedCount = i + 1;
389
470
  break;
@@ -75,7 +75,9 @@ import {
75
75
  convertUserMessagesToPromptBlocks,
76
76
  extractAuxiliaryTaskInstructions,
77
77
  extractVisibleMessages,
78
+ inspectTrafficOptProjectionState,
78
79
  isAuxiliarySingleTurnRequest,
80
+ type TrafficOptProjectionState,
79
81
  } from "./reconcile.ts";
80
82
 
81
83
  type PumpQueueItem =
@@ -184,6 +186,9 @@ interface ManagedSessionLedger {
184
186
  appliedExecMode?: string;
185
187
  syncedMessageCount: number;
186
188
  syncedTranscriptDigest: string;
189
+ /** 当前 AGY 会话实际承载的 `pi-traffic-optimization` 归档投影指纹与计数 */
190
+ syncedProjectionDigest: string;
191
+ syncedProjectedCount: number;
187
192
  usedTokens?: number;
188
193
  windowSize?: number;
189
194
  /** 当前会话已进入后端 Prompt Cache 的前缀 Token 水位(供无本地库回退路径估算缓存命中率) */
@@ -209,6 +214,33 @@ interface ManagedSessionLedger {
209
214
 
210
215
  const DEFAULT_SESSION_KEY = "__default_pi_session__";
211
216
 
217
+ /**
218
+ * 判断是否应因 `pi-traffic-optimization` 归档投影状态变更而按需重建瘦身后的 AGY 会话:
219
+ * - 非 GC 轮次(投影指纹一致或无新归档)严格返回 `false`,零打扰热缓存;
220
+ * - 发生批量 GC 归档(新增归档 >= 4 项,或已用窗口 >= 32k 且有新增归档)时返回 `true`,让 AGY 真实释放旧工具输出与旧图片上下文;
221
+ * - 用户关闭 `/traffic-opt` 恢复完整上下文(原会话承载归档占位符且现已全部恢复原文)时返回 `true`,重建完整上下文。
222
+ */
223
+ function shouldRebuildForProjectionSync(
224
+ syncedDigest: string,
225
+ syncedCount: number,
226
+ current: TrafficOptProjectionState,
227
+ usedTokens?: number,
228
+ ): boolean {
229
+ if (current.projectionDigest === syncedDigest) {
230
+ return false;
231
+ }
232
+ const delta = current.archivedCount - syncedCount;
233
+ if (delta > 0) {
234
+ if (delta >= 4) return true;
235
+ if (typeof usedTokens === "number" && usedTokens >= 32_000) return true;
236
+ return false;
237
+ }
238
+ if (syncedCount > 0 && current.archivedCount === 0) {
239
+ return true;
240
+ }
241
+ return false;
242
+ }
243
+
212
244
  /**
213
245
  * 双模会话与流式推理总协调器。
214
246
  * 统一调度模式 B(`pi-tools`)、模式 A(`agy-tools`)与混合模式(`hybrid`)。
@@ -365,6 +397,12 @@ export class TurnCoordinator {
365
397
  messageCount: ledger.syncedMessageCount,
366
398
  mountDigest: ledger.mountDigest,
367
399
  toolsDigest: ledger.toolsDigest,
400
+ ...(ledger.syncedProjectedCount > 0
401
+ ? {
402
+ projectionDigest: ledger.syncedProjectionDigest,
403
+ projectedCount: ledger.syncedProjectedCount,
404
+ }
405
+ : {}),
368
406
  dbCheckpoint,
369
407
  };
370
408
 
@@ -414,10 +452,7 @@ export class TurnCoordinator {
414
452
  this.abortLedgerTurnNonBlocking(ledger);
415
453
  }
416
454
 
417
- private abortLedgerTurnNonBlocking(
418
- ledger: ManagedSessionLedger,
419
- preserveSlicePool = false,
420
- ): void {
455
+ private abortLedgerTurnNonBlocking(ledger: ManagedSessionLedger): void {
421
456
  this.httpMcpBridge.markSessionTurnCancelled(ledger.agySessionId);
422
457
  this.mirrorBroker.abortSessionCalls(ledger.agySessionId, "Aborted");
423
458
  for (const [, parked] of ledger.parkedCalls) {
@@ -427,9 +462,7 @@ export class TurnCoordinator {
427
462
  });
428
463
  }
429
464
  ledger.parkedCalls.clear();
430
- if (!preserveSlicePool) {
431
- ledger.pendingGenSlicePool = undefined;
432
- }
465
+ ledger.pendingGenSlicePool = undefined;
433
466
  if (ledger.activePump) {
434
467
  ledger.activePump.finished = true;
435
468
  }
@@ -755,7 +788,7 @@ export class TurnCoordinator {
755
788
  if (existing.activePump) {
756
789
  const { trailingUsers } = this.collectRecentToolResultsAndSteeringUsers(visibleMessages);
757
790
  if (trailingUsers.length > 0) {
758
- this.abortLedgerTurnNonBlocking(existing, true);
791
+ this.abortLedgerTurnNonBlocking(existing);
759
792
  const idleOk = await this.waitForInFlightPrompt(existing, 2_500, options?.signal);
760
793
  if (!idleOk) {
761
794
  if (options?.signal?.aborted) {
@@ -799,6 +832,7 @@ export class TurnCoordinator {
799
832
  const mountInfo = prepareCustomizationMount(context.messages, this.currentConfig, cwd);
800
833
 
801
834
  // 2c. 连续正常追问:先确认上一轮在途请求已完全收敛;若底层卡死则自动驱逐重建,否则直接复用会话与缓存
835
+ let skipAnchorRestoreForProjectionSync = false;
802
836
  const idleCandidate = this.ledgers.get(piSessionKey);
803
837
  if (
804
838
  idleCandidate &&
@@ -819,7 +853,20 @@ export class TurnCoordinator {
819
853
  visibleMessages,
820
854
  );
821
855
  if (continuationPrompts) {
822
- if (idleCandidate.toolsDigest === toolsDigest) {
856
+ const prefixProjection = inspectTrafficOptProjectionState(
857
+ visibleMessages.slice(0, idleCandidate.syncedMessageCount),
858
+ );
859
+ if (
860
+ shouldRebuildForProjectionSync(
861
+ idleCandidate.syncedProjectionDigest,
862
+ idleCandidate.syncedProjectedCount,
863
+ prefixProjection,
864
+ idleCandidate.usedTokens,
865
+ )
866
+ ) {
867
+ // pi-traffic-optimization 触发批量 GC(或用户关闭优化恢复原文):在空闲轮次边界重建瘦身/还原后的新 AGY 会话
868
+ skipAnchorRestoreForProjectionSync = true;
869
+ } else if (idleCandidate.toolsDigest === toolsDigest) {
823
870
  await this.executePromptOnLedger(
824
871
  idleCandidate,
825
872
  continuationPrompts,
@@ -829,31 +876,31 @@ export class TurnCoordinator {
829
876
  options,
830
877
  );
831
878
  return;
832
- }
833
-
834
- // 跨轮次仅动态工具集合变化:优先通过活跃 SSE 或原地 session/resume 重拉 tools/list,零历史丢失
835
- const syncedTools = await this.syncLedgerToolsBetweenTurns(
836
- idleCandidate,
837
- hostMcpTools,
838
- toolsDigest,
839
- options?.signal,
840
- );
841
- if (syncedTools) {
842
- await this.executePromptOnLedger(
879
+ } else {
880
+ // 跨轮次仅动态工具集合变化:优先通过活跃 SSE 或原地 session/resume 重拉 tools/list,零历史丢失
881
+ const syncedTools = await this.syncLedgerToolsBetweenTurns(
843
882
  idleCandidate,
844
- continuationPrompts,
845
- visibleMessages,
846
- writer,
847
- model,
848
- options,
883
+ hostMcpTools,
884
+ toolsDigest,
885
+ options?.signal,
849
886
  );
850
- return;
887
+ if (syncedTools) {
888
+ await this.executePromptOnLedger(
889
+ idleCandidate,
890
+ continuationPrompts,
891
+ visibleMessages,
892
+ writer,
893
+ model,
894
+ options,
895
+ );
896
+ return;
897
+ }
851
898
  }
852
899
  }
853
900
  }
854
901
  }
855
902
 
856
- // 3. 会话不存在、工具集/模式变更或历史分支偏离:安全拆解旧会话并按三级状态机重建/恢复
903
+ // 3. 会话不存在、工具集/模式变更、归档投影瘦身或历史分支偏离:安全拆解旧会话并按三级状态机重建/恢复
857
904
  const stillExisting = this.ledgers.get(piSessionKey);
858
905
  if (stillExisting) {
859
906
  const settled = await this.waitForInFlightPrompt(stillExisting, 1_500, options?.signal);
@@ -875,6 +922,7 @@ export class TurnCoordinator {
875
922
  mountDigest: mountInfo.mountDigest,
876
923
  additionalDirectories: mountInfo.additionalDirectories,
877
924
  workspaceContextBlock: mountInfo.workspaceContextBlock,
925
+ skipAnchorRestore: skipAnchorRestoreForProjectionSync,
878
926
  signal: options?.signal,
879
927
  });
880
928
 
@@ -1260,7 +1308,7 @@ export class TurnCoordinator {
1260
1308
  } finally {
1261
1309
  ledger.steeringCutInPending = false;
1262
1310
  }
1263
- this.abortLedgerTurnNonBlocking(ledger, true);
1311
+ this.abortLedgerTurnNonBlocking(ledger);
1264
1312
  const idleOk = await this.waitForInFlightPrompt(ledger, 2_500, options?.signal);
1265
1313
  if (!idleOk) {
1266
1314
  if (options?.signal?.aborted) {
@@ -1332,7 +1380,7 @@ export class TurnCoordinator {
1332
1380
  } finally {
1333
1381
  ledger.steeringCutInPending = false;
1334
1382
  }
1335
- this.abortLedgerTurnNonBlocking(ledger, true);
1383
+ this.abortLedgerTurnNonBlocking(ledger);
1336
1384
  const idleOk = await this.waitForInFlightPrompt(ledger, 2_500, options?.signal);
1337
1385
  if (idleOk) {
1338
1386
  const reloaded = await this.reloadLedgerSessionForTools(
@@ -1414,6 +1462,7 @@ export class TurnCoordinator {
1414
1462
  mountDigest: string;
1415
1463
  additionalDirectories: string[];
1416
1464
  workspaceContextBlock?: string;
1465
+ skipAnchorRestore?: boolean;
1417
1466
  signal?: AbortSignal;
1418
1467
  }): Promise<{ ledger: ManagedSessionLedger; initialPromptBlocks: AcpPromptBlock[] }> {
1419
1468
  const conn = await this.processManager.acquire(
@@ -1515,9 +1564,10 @@ export class TurnCoordinator {
1515
1564
  .slice(tailStartIdx)
1516
1565
  .filter((m): m is UserMessage => m.role === "user");
1517
1566
 
1567
+ const priorProjection = inspectTrafficOptProjectionState(priorHistory);
1518
1568
  const branchEntries = this.activeContext?.sessionManager?.getBranch?.() ?? [];
1519
1569
  const anchorMatch =
1520
- priorHistory.length > 0 && pendingUserMessages.length > 0
1570
+ !params.skipAnchorRestore && priorHistory.length > 0 && pendingUserMessages.length > 0
1521
1571
  ? findBranchAnchorForHistory({
1522
1572
  branchEntries,
1523
1573
  priorMessages: priorHistory,
@@ -1532,9 +1582,19 @@ export class TurnCoordinator {
1532
1582
 
1533
1583
  let sessionInfo: AcpSessionNewResult | undefined;
1534
1584
  let initialPromptBlocks: AcpPromptBlock[] | undefined;
1585
+ let syncedProjectionDigest = priorProjection.projectionDigest;
1586
+ let syncedProjectedCount = priorProjection.archivedCount;
1535
1587
 
1536
- // 路径 1:精确命中分支末尾锚点 -> 调用 session/resume 零历史回放开销恢复
1537
- if (anchorMatch.kind === "exact" && conn.capabilities?.sessionCapabilities?.resume) {
1588
+ // 路径 1:精确命中分支末尾锚点且未发生需同步的新一轮归档 GC -> 调用 session/resume 零历史回放开销恢复
1589
+ if (
1590
+ anchorMatch.kind === "exact" &&
1591
+ conn.capabilities?.sessionCapabilities?.resume &&
1592
+ !shouldRebuildForProjectionSync(
1593
+ anchorMatch.anchor.projectionDigest ?? "",
1594
+ anchorMatch.anchor.projectedCount ?? 0,
1595
+ priorProjection,
1596
+ )
1597
+ ) {
1538
1598
  try {
1539
1599
  sessionInfo = await conn.request<AcpSessionResumeResult>(
1540
1600
  "session/resume",
@@ -1547,42 +1607,64 @@ export class TurnCoordinator {
1547
1607
  { timeoutMs: 20_000, signal: params.signal },
1548
1608
  );
1549
1609
  initialPromptBlocks = convertUserMessagesToPromptBlocks(pendingUserMessages);
1610
+ syncedProjectionDigest = anchorMatch.anchor.projectionDigest ?? "";
1611
+ syncedProjectedCount = anchorMatch.anchor.projectedCount ?? 0;
1550
1612
  } catch {
1551
1613
  sessionInfo = undefined;
1552
1614
  }
1553
1615
  }
1554
1616
 
1555
- // 路径 2:命中历史中间锚点 -> 只读 VACUUM INTO 快照分叉截断 + session/resume
1617
+ // 路径 2:命中历史中间锚点且锚点前缀未落后于新一轮归档 GC -> 只读 VACUUM INTO 快照分叉截断 + session/resume
1556
1618
  if (
1557
1619
  !sessionInfo &&
1558
1620
  anchorMatch.kind === "forkable" &&
1559
1621
  anchorMatch.anchor.dbCheckpoint &&
1560
1622
  conn.capabilities?.sessionCapabilities?.resume
1561
1623
  ) {
1562
- const forkedId = await forkSqliteConversationAtCheckpoint(
1563
- this.currentConfig,
1564
- anchorMatch.anchor.agySessionId,
1565
- anchorMatch.anchor.dbCheckpoint,
1624
+ const forkPrefixProjection = inspectTrafficOptProjectionState(
1625
+ priorHistory.slice(0, anchorMatch.anchor.messageCount),
1566
1626
  );
1567
- if (forkedId) {
1568
- try {
1569
- sessionInfo = await conn.request<AcpSessionResumeResult>(
1570
- "session/resume",
1571
- {
1572
- sessionId: forkedId,
1573
- cwd: params.cwd,
1574
- mcpServers,
1575
- additionalDirectories: addDirs,
1576
- },
1577
- { timeoutMs: 20_000, signal: params.signal },
1578
- );
1579
- const remainingAfterFork = params.visibleMessages.slice(
1580
- anchorMatch.anchor.messageCount,
1581
- );
1582
- initialPromptBlocks = buildFreshReplayPromptBlocks(remainingAfterFork);
1583
- } catch {
1584
- sessionInfo = undefined;
1585
- removeEmptyProbeSessionFiles(this.currentConfig, forkedId);
1627
+ const forkStaleByProjection = shouldRebuildForProjectionSync(
1628
+ anchorMatch.anchor.projectionDigest ?? "",
1629
+ anchorMatch.anchor.projectedCount ?? 0,
1630
+ forkPrefixProjection,
1631
+ );
1632
+ if (!forkStaleByProjection) {
1633
+ const forkedId = await forkSqliteConversationAtCheckpoint(
1634
+ this.currentConfig,
1635
+ anchorMatch.anchor.agySessionId,
1636
+ anchorMatch.anchor.dbCheckpoint,
1637
+ );
1638
+ if (forkedId) {
1639
+ try {
1640
+ sessionInfo = await conn.request<AcpSessionResumeResult>(
1641
+ "session/resume",
1642
+ {
1643
+ sessionId: forkedId,
1644
+ cwd: params.cwd,
1645
+ mcpServers,
1646
+ additionalDirectories: addDirs,
1647
+ },
1648
+ { timeoutMs: 20_000, signal: params.signal },
1649
+ );
1650
+ const remainingAfterFork = params.visibleMessages.slice(
1651
+ anchorMatch.anchor.messageCount,
1652
+ );
1653
+ initialPromptBlocks = buildFreshReplayPromptBlocks(remainingAfterFork);
1654
+ if (
1655
+ forkPrefixProjection.projectionDigest ===
1656
+ (anchorMatch.anchor.projectionDigest ?? "")
1657
+ ) {
1658
+ syncedProjectionDigest = priorProjection.projectionDigest;
1659
+ syncedProjectedCount = priorProjection.archivedCount;
1660
+ } else {
1661
+ syncedProjectionDigest = anchorMatch.anchor.projectionDigest ?? "";
1662
+ syncedProjectedCount = anchorMatch.anchor.projectedCount ?? 0;
1663
+ }
1664
+ } catch {
1665
+ sessionInfo = undefined;
1666
+ removeEmptyProbeSessionFiles(this.currentConfig, forkedId);
1667
+ }
1586
1668
  }
1587
1669
  }
1588
1670
  }
@@ -1609,6 +1691,8 @@ export class TurnCoordinator {
1609
1691
  initialPromptBlocks = params.workspaceContextBlock
1610
1692
  ? [{ type: "text", text: params.workspaceContextBlock }, ...replayBlocks]
1611
1693
  : replayBlocks;
1694
+ syncedProjectionDigest = priorProjection.projectionDigest;
1695
+ syncedProjectedCount = priorProjection.archivedCount;
1612
1696
  }
1613
1697
 
1614
1698
  conn.trackSession(sessionInfo.sessionId);
@@ -1643,6 +1727,8 @@ export class TurnCoordinator {
1643
1727
  availableModels: sessionInfo.models?.availableModels ?? [],
1644
1728
  syncedMessageCount: priorHistory.length,
1645
1729
  syncedTranscriptDigest: computeTranscriptDigest(priorHistory),
1730
+ syncedProjectionDigest,
1731
+ syncedProjectedCount,
1646
1732
  cachedPrefixTokens: 0,
1647
1733
  lastConsumedStepIdx: initialMaxStepIdx,
1648
1734
  tier,
@@ -2074,7 +2160,10 @@ export class TurnCoordinator {
2074
2160
  ) {
2075
2161
  const raw = convertAcpUsageToPiUsage(item.response.usage);
2076
2162
  const rawPromptTotal = raw.input + raw.cacheRead + raw.cacheWrite;
2077
- if (rawPromptTotal > 0 && raw.cacheRead > 0) {
2163
+ if (
2164
+ rawPromptTotal > 0 &&
2165
+ (pump.intermediateStepCount === 0 || !pump.hasSqliteGenTelemetry)
2166
+ ) {
2078
2167
  ledger.lastObservedCacheRatio = Math.min(
2079
2168
  1,
2080
2169
  Math.max(0, raw.cacheRead / rawPromptTotal),
@@ -2087,6 +2176,7 @@ export class TurnCoordinator {
2087
2176
  if (writer.estimatedOutputTokens > 0) {
2088
2177
  writer.appendTextDelta("\n\n");
2089
2178
  }
2179
+ ledger.pendingGenSlicePool = undefined;
2090
2180
  pump.accountedOutputTokens = 0;
2091
2181
  pump.intermediateStepCount = 0;
2092
2182
  pump.lastAccountedWindowUsed = undefined;
@@ -2150,20 +2240,30 @@ export class TurnCoordinator {
2150
2240
 
2151
2241
  /**
2152
2242
  * 为多步工具调用循环中的单个中间 `toolUse` 步构建精确归因 `Usage`:
2153
- * 1. 优先从会话只读 SQLite `steps.metadata` 与 `step_payload`(`step_type = 15`)直接提取上游逐次生成明细与该次生成的工具总数;
2154
- * 2. 若单次模型生成包含多个顺序执行的工具调用,按精确整数守恒池向后续子步预留等比例切片(`<= 1000` Token),使每一步均具备有效提示词与真实命中率,彻底消除 UI 状态栏缓存命中率闪烁消失且保证累计 Token 100% 守恒;
2155
- * 3. 在无本地库的环境下平滑回退至窗口差分估算。
2243
+ * 1. 优先从会话只读 SQLite `steps.metadata` 与 `step_payload`(`step_type = 15`)提取当前最新一次生成的上游明细与工具总数(非切片路径带短 WAL 重试,避免大 WAL 锁竞争误落回退);
2244
+ * 2. 若单次模型生成包含多个顺序执行的工具调用,按整数守恒池向后续子步预留等比例切片(单切片 `<= 1000`、总预留控制 `<= 1000`),保持缓存命中率稳定、累计守恒且降低对 Pi `cache-stats` 的干扰;
2245
+ * 3. 在无本地库的环境下仅依据真实观测到的上游命中率(含 `0%` 未命中)平滑回退,绝不凭空伪造命中率。
2156
2246
  */
2157
2247
  private async buildIntermediateStepUsage(
2158
2248
  ledger: ManagedSessionLedger,
2159
2249
  pump: ActiveTurnPump,
2160
2250
  writer: StepStreamWriter,
2161
2251
  ): Promise<Usage> {
2162
- const dbGens = await readSqliteGenerationUsagesSince(
2163
- this.currentConfig,
2164
- ledger.agySessionId,
2165
- ledger.lastConsumedStepIdx,
2166
- );
2252
+ const hasPendingSlices =
2253
+ ledger.pendingGenSlicePool !== undefined &&
2254
+ ledger.pendingGenSlicePool.remainingSlices > 0;
2255
+ const dbGens = hasPendingSlices
2256
+ ? await readSqliteGenerationUsagesSince(
2257
+ this.currentConfig,
2258
+ ledger.agySessionId,
2259
+ ledger.lastConsumedStepIdx,
2260
+ )
2261
+ : await readSqliteGenerationUsagesSinceWithRetry(
2262
+ this.currentConfig,
2263
+ ledger.agySessionId,
2264
+ ledger.lastConsumedStepIdx,
2265
+ [20, 40],
2266
+ );
2167
2267
 
2168
2268
  const liveWindowUsed =
2169
2269
  typeof ledger.usedTokens === "number" && ledger.usedTokens > 0
@@ -2171,56 +2271,35 @@ export class TurnCoordinator {
2171
2271
  : 0;
2172
2272
 
2173
2273
  if (dbGens.length > 0) {
2174
- const carry = this.drainPendingSlicePool(ledger);
2175
- const gensToAccount =
2176
- !pump.hasSqliteGenTelemetry && pump.intermediateStepCount > 0
2177
- ? [dbGens[dbGens.length - 1]]
2178
- : dbGens;
2274
+ // 新生成已落盘,丢弃上一生成未耗尽的旧切片池,绝不跨生成混算污染当次缓存命中率
2275
+ ledger.pendingGenSlicePool = undefined;
2179
2276
  pump.hasSqliteGenTelemetry = true;
2180
2277
  pump.intermediateStepCount++;
2181
2278
  if (liveWindowUsed > 0) {
2182
2279
  pump.lastAccountedWindowUsed = liveWindowUsed;
2183
2280
  }
2184
- ledger.lastConsumedStepIdx = dbGens[dbGens.length - 1].stepIdx;
2185
-
2186
- let genInput = 0;
2187
- let genOutput = 0;
2188
- let genCacheWrite = 0;
2189
- let genCacheRead = 0;
2190
- let thoughtSum = 0;
2191
- let hasThought = false;
2192
- for (const g of gensToAccount) {
2193
- genInput += g.inputTokens;
2194
- genOutput += g.outputTokens;
2195
- genCacheWrite += g.cacheWriteTokens;
2196
- genCacheRead += g.cacheReadTokens;
2197
- if (g.thoughtTokens !== undefined) {
2198
- hasThought = true;
2199
- thoughtSum += g.thoughtTokens;
2200
- }
2201
- }
2281
+
2282
+ // 始终以最新一条真实生成作为本步归因,避免多行叠加混算导致虚假均值命中率
2283
+ const lastGen = dbGens[dbGens.length - 1];
2284
+ ledger.lastConsumedStepIdx = lastGen.stepIdx;
2285
+
2286
+ const genInput = lastGen.inputTokens;
2287
+ const genOutput = lastGen.outputTokens;
2288
+ const genCacheWrite = lastGen.cacheWriteTokens;
2289
+ const genCacheRead = lastGen.cacheReadTokens;
2290
+ const hasThought = lastGen.thoughtTokens !== undefined;
2291
+ const thoughtSum = lastGen.thoughtTokens ?? 0;
2202
2292
 
2203
2293
  const genPromptSum = genInput + genCacheRead + genCacheWrite;
2204
- if (genPromptSum > 0 && genCacheRead > 0) {
2294
+ if (genPromptSum > 0) {
2205
2295
  ledger.lastObservedCacheRatio = Math.min(1, Math.max(0, genCacheRead / genPromptSum));
2206
2296
  }
2207
- // 多条 SQLite 生成并入单步时,上下文窗口基数取最新一条生成的窗口值,杜绝无 usage_update 时窗口翻倍误触发压缩
2208
- const lastGen = gensToAccount[gensToAccount.length - 1];
2209
- const latestGenWindowTotal =
2210
- lastGen.inputTokens +
2211
- lastGen.cacheReadTokens +
2212
- lastGen.cacheWriteTokens +
2213
- lastGen.outputTokens;
2297
+
2298
+ const latestGenWindowTotal = genPromptSum + genOutput;
2214
2299
  const effectiveWindow = liveWindowUsed > 0 ? liveWindowUsed : latestGenWindowTotal;
2215
2300
  pump.accountedOutputTokens += genOutput;
2216
2301
  ledger.cachedPrefixTokens = Math.max(ledger.cachedPrefixTokens, effectiveWindow);
2217
2302
 
2218
- const totalIn = genInput + carry.input;
2219
- const totalCr = genCacheRead + carry.cacheRead;
2220
- const totalCw = genCacheWrite + carry.cacheWrite;
2221
- const totalOut = genOutput + carry.output;
2222
- const totalPrompt = totalIn + totalCr + totalCw;
2223
-
2224
2303
  const emittedToolCount = Math.max(
2225
2304
  1,
2226
2305
  writer.message.content.filter((b) => b.type === "toolCall").length,
@@ -2228,20 +2307,29 @@ export class TurnCoordinator {
2228
2307
  const plannedTools = lastGen.plannedToolCalls ?? 1;
2229
2308
  const remainingSlices = Math.max(0, plannedTools - emittedToolCount);
2230
2309
 
2231
- if (remainingSlices > 0 && totalPrompt >= (remainingSlices + 1) * 20) {
2232
- const sliceBudget = Math.min(1_000, Math.floor(totalPrompt / (remainingSlices + 1)));
2233
- const ratioCr = totalPrompt > 0 ? totalCr / totalPrompt : 0;
2234
- const ratioCw = totalPrompt > 0 ? totalCw / totalPrompt : 0;
2310
+ if (remainingSlices > 0 && genPromptSum >= (remainingSlices + 1) * 20) {
2311
+ // 尽量将全部预留切片总扣减控制在 <= 1000(低于 Pi cache-stats 的 1024 噪声门限),
2312
+ // 且单切片保持在 [100, 1000] 内兼顾状态栏显示精度与不自触发假未命中告警
2313
+ const targetPerSlice = Math.min(
2314
+ 1_000,
2315
+ Math.max(100, Math.floor(1_000 / remainingSlices)),
2316
+ );
2317
+ const sliceBudget = Math.min(
2318
+ targetPerSlice,
2319
+ Math.floor(genPromptSum / (remainingSlices + 1)),
2320
+ );
2321
+ const ratioCr = genPromptSum > 0 ? genCacheRead / genPromptSum : 0;
2322
+ const ratioCw = genPromptSum > 0 ? genCacheWrite / genPromptSum : 0;
2235
2323
  const perCr = Math.round(sliceBudget * ratioCr);
2236
2324
  const perCw = Math.min(sliceBudget - perCr, Math.round(sliceBudget * ratioCw));
2237
2325
  const perIn = Math.max(0, sliceBudget - perCr - perCw);
2238
2326
 
2239
- const resCr = Math.min(totalCr, remainingSlices * perCr);
2240
- const resCw = Math.min(totalCw, remainingSlices * perCw);
2241
- const resIn = Math.min(totalIn, remainingSlices * perIn);
2327
+ const resCr = Math.min(genCacheRead, remainingSlices * perCr);
2328
+ const resCw = Math.min(genCacheWrite, remainingSlices * perCw);
2329
+ const resIn = Math.min(genInput, remainingSlices * perIn);
2242
2330
  // 严格保证第 1 步 output >= reasoning,仅在扣除思考 Token 仍有余量时才向后续切片预留 output
2243
2331
  const minStepOut = Math.max(1, hasThought ? thoughtSum : 1);
2244
- const resOut = Math.min(remainingSlices, Math.max(0, totalOut - minStepOut));
2332
+ const resOut = Math.min(remainingSlices, Math.max(0, genOutput - minStepOut));
2245
2333
 
2246
2334
  ledger.pendingGenSlicePool = {
2247
2335
  remainingSlices,
@@ -2252,24 +2340,24 @@ export class TurnCoordinator {
2252
2340
  windowTotal: effectiveWindow,
2253
2341
  };
2254
2342
 
2255
- const stepOut = Math.max(1, totalOut - resOut);
2343
+ const stepOut = Math.max(1, genOutput - resOut);
2256
2344
  return {
2257
- input: totalIn - resIn,
2345
+ input: genInput - resIn,
2258
2346
  output: stepOut,
2259
- cacheRead: totalCr - resCr,
2260
- cacheWrite: totalCw - resCw,
2347
+ cacheRead: genCacheRead - resCr,
2348
+ cacheWrite: genCacheWrite - resCw,
2261
2349
  reasoning: hasThought ? Math.min(stepOut, thoughtSum) : undefined,
2262
2350
  totalTokens: effectiveWindow,
2263
2351
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
2264
2352
  };
2265
2353
  }
2266
2354
 
2267
- const finalStepOut = Math.max(1, totalOut);
2355
+ const finalStepOut = Math.max(1, genOutput);
2268
2356
  return {
2269
- input: totalIn,
2357
+ input: genInput,
2270
2358
  output: finalStepOut,
2271
- cacheRead: totalCr,
2272
- cacheWrite: totalCw,
2359
+ cacheRead: genCacheRead,
2360
+ cacheWrite: genCacheWrite,
2273
2361
  reasoning: hasThought ? Math.min(finalStepOut, thoughtSum) : undefined,
2274
2362
  totalTokens: effectiveWindow,
2275
2363
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
@@ -2307,10 +2395,13 @@ export class TurnCoordinator {
2307
2395
  };
2308
2396
  }
2309
2397
 
2310
- // 切片池耗尽或无本地库回退路径下的同次生成拆分步:若会话已有缓存命中记录,返回极小整数比例样本维持 UI 缓存命中率不闪烁
2311
- if (ledger.lastObservedCacheRatio !== undefined && ledger.lastObservedCacheRatio > 0) {
2398
+ // 切片池耗尽或无本地库回退路径下的同次生成拆分步:若会话已有真实缓存观测值(含 0%),返回极小整数比例样本维持 UI 显示稳定
2399
+ if (ledger.lastObservedCacheRatio !== undefined) {
2312
2400
  const win = liveWindowUsed > 0 ? liveWindowUsed : ledger.cachedPrefixTokens;
2313
- const cr = Math.max(1, Math.min(100, Math.round(100 * ledger.lastObservedCacheRatio)));
2401
+ const cr =
2402
+ ledger.lastObservedCacheRatio > 0
2403
+ ? Math.max(1, Math.min(100, Math.round(100 * ledger.lastObservedCacheRatio)))
2404
+ : 0;
2314
2405
  return {
2315
2406
  input: 100 - cr,
2316
2407
  output: 0,
@@ -2351,13 +2442,11 @@ export class TurnCoordinator {
2351
2442
  const prevCachedPrefix = ledger.cachedPrefixTokens;
2352
2443
  const stepTotal = Math.max(output + 1, liveWindowUsed || prevCachedPrefix + output);
2353
2444
  const promptTokens = Math.max(1, stepTotal - output);
2354
- let cacheRead = 0;
2355
- if (ledger.lastObservedCacheRatio !== undefined && ledger.lastObservedCacheRatio > 0) {
2356
- cacheRead = Math.min(promptTokens, Math.round(promptTokens * ledger.lastObservedCacheRatio));
2357
- } else if (prevCachedPrefix > 0) {
2358
- // 无历史命中率时按前序已缓存前缀的保守折算估算,避免 100% 虚高或首轮冷启动把后续锁死为 0%
2359
- cacheRead = Math.min(promptTokens, Math.round(Math.min(promptTokens, prevCachedPrefix) * 0.85));
2360
- }
2445
+ // 仅依据已真实观测到的上游缓存命中率折算(含 0% 未命中);尚未获得任何上游缓存遥测时绝不硬编码伪造命中率
2446
+ const cacheRead =
2447
+ ledger.lastObservedCacheRatio !== undefined
2448
+ ? Math.min(promptTokens, Math.round(promptTokens * ledger.lastObservedCacheRatio))
2449
+ : 0;
2361
2450
  const input = Math.max(0, promptTokens - cacheRead);
2362
2451
  const totalTokens = input + cacheRead + output;
2363
2452
  ledger.cachedPrefixTokens = Math.max(prevCachedPrefix, totalTokens);
@@ -2375,8 +2464,8 @@ export class TurnCoordinator {
2375
2464
 
2376
2465
  /**
2377
2466
  * 为最终 `stop` 步校准 `Usage`:
2378
- * 1. 优先读取本地 SQLite `steps.metadata` 中末步真实生成明细(精确匹配上游单步命中率与真实 `output`);
2379
- * 2. 回退路径下:单步轮次保留官方汇总,多步轮次采用末步自身估算 `output` 与当前窗口对齐,绝不将整轮累计 `output` 余量倒灌至最后一条消息。
2467
+ * 1. 优先读取本地 SQLite `steps.metadata` 中末步真实生成明细(精确匹配上游单步命中率与真实 `output`,含 `0%` 未命中且不混入跨生成旧切片);
2468
+ * 2. 回退路径下:单步轮次或无 SQLite 环境才从 `acpUsage` 更新观测比率,多步 SQLite WAL 延迟回退时保留精确单步观测比率且绝不将整轮累计 `output` 余量倒灌至最后一条消息。
2380
2469
  */
2381
2470
  private async buildFinalStepUsage(
2382
2471
  ledger: ManagedSessionLedger,
@@ -2386,9 +2475,6 @@ export class TurnCoordinator {
2386
2475
  ): Promise<Usage> {
2387
2476
  const raw = convertAcpUsageToPiUsage(acpUsage);
2388
2477
  const rawPromptTotal = raw.input + raw.cacheRead + raw.cacheWrite;
2389
- if (rawPromptTotal > 0 && raw.cacheRead > 0) {
2390
- ledger.lastObservedCacheRatio = Math.min(1, Math.max(0, raw.cacheRead / rawPromptTotal));
2391
- }
2392
2478
 
2393
2479
  const liveWindowUsed =
2394
2480
  typeof ledger.usedTokens === "number" && ledger.usedTokens > 0
@@ -2402,50 +2488,33 @@ export class TurnCoordinator {
2402
2488
  );
2403
2489
 
2404
2490
  if (dbGens.length > 0) {
2405
- const carry = this.drainPendingSlicePool(ledger);
2406
- const gensToAccount =
2407
- !pump.hasSqliteGenTelemetry && pump.intermediateStepCount > 0
2408
- ? [dbGens[dbGens.length - 1]]
2409
- : dbGens;
2491
+ // 新生成已落盘,丢弃上一生成未耗尽的旧切片池并取最新一条真实生成,确保末步命中率与输出 100% 纯净
2492
+ ledger.pendingGenSlicePool = undefined;
2410
2493
  pump.hasSqliteGenTelemetry = true;
2411
- ledger.lastConsumedStepIdx = dbGens[dbGens.length - 1].stepIdx;
2412
-
2413
- let input = 0;
2414
- let output = 0;
2415
- let cacheWrite = 0;
2416
- let cacheRead = 0;
2417
- let thoughtSum = 0;
2418
- let hasThought = false;
2419
- for (const g of gensToAccount) {
2420
- input += g.inputTokens;
2421
- output += g.outputTokens;
2422
- cacheWrite += g.cacheWriteTokens;
2423
- cacheRead += g.cacheReadTokens;
2424
- if (g.thoughtTokens !== undefined) {
2425
- hasThought = true;
2426
- thoughtSum += g.thoughtTokens;
2427
- }
2428
- }
2429
- const promptSum = input + cacheRead + cacheWrite;
2430
- if (promptSum > 0 && cacheRead > 0) {
2431
- ledger.lastObservedCacheRatio = Math.min(1, Math.max(0, cacheRead / promptSum));
2494
+ const lastGen = dbGens[dbGens.length - 1];
2495
+ ledger.lastConsumedStepIdx = lastGen.stepIdx;
2496
+
2497
+ const promptSum =
2498
+ lastGen.inputTokens + lastGen.cacheReadTokens + lastGen.cacheWriteTokens;
2499
+ if (promptSum > 0) {
2500
+ ledger.lastObservedCacheRatio = Math.min(
2501
+ 1,
2502
+ Math.max(0, lastGen.cacheReadTokens / promptSum),
2503
+ );
2432
2504
  }
2433
- const lastGen = gensToAccount[gensToAccount.length - 1];
2434
- const latestGenWindowTotal =
2435
- lastGen.inputTokens +
2436
- lastGen.cacheReadTokens +
2437
- lastGen.cacheWriteTokens +
2438
- lastGen.outputTokens;
2505
+ const latestGenWindowTotal = promptSum + lastGen.outputTokens;
2439
2506
  const effectiveWindow = liveWindowUsed ?? latestGenWindowTotal;
2440
2507
  ledger.cachedPrefixTokens = effectiveWindow;
2441
2508
 
2442
- const totalOut = output + carry.output;
2509
+ const hasThought = lastGen.thoughtTokens !== undefined;
2443
2510
  return {
2444
- input: input + carry.input,
2445
- output: totalOut,
2446
- cacheRead: cacheRead + carry.cacheRead,
2447
- cacheWrite: cacheWrite + carry.cacheWrite,
2448
- reasoning: hasThought ? Math.min(totalOut, thoughtSum) : undefined,
2511
+ input: lastGen.inputTokens,
2512
+ output: lastGen.outputTokens,
2513
+ cacheRead: lastGen.cacheReadTokens,
2514
+ cacheWrite: lastGen.cacheWriteTokens,
2515
+ reasoning: hasThought
2516
+ ? Math.min(lastGen.outputTokens, lastGen.thoughtTokens!)
2517
+ : undefined,
2449
2518
  totalTokens: effectiveWindow,
2450
2519
  cost: raw.cost,
2451
2520
  };
@@ -2468,12 +2537,20 @@ export class TurnCoordinator {
2468
2537
  if (
2469
2538
  writer.estimatedOutputTokens === 0 &&
2470
2539
  raw.output === 0 &&
2471
- !(ledger.lastObservedCacheRatio !== undefined && ledger.lastObservedCacheRatio > 0)
2540
+ ledger.lastObservedCacheRatio === undefined
2472
2541
  ) {
2473
2542
  return createZeroUsage();
2474
2543
  }
2475
2544
  }
2476
2545
 
2546
+ // 仅在单步轮次或无 SQLite 遥测时才从整轮汇总 acpUsage 更新观测比率(含 0%),避免多步累计均值污染 SQLite 单步基准
2547
+ if (
2548
+ rawPromptTotal > 0 &&
2549
+ (pump.intermediateStepCount === 0 || !pump.hasSqliteGenTelemetry)
2550
+ ) {
2551
+ ledger.lastObservedCacheRatio = Math.min(1, Math.max(0, raw.cacheRead / rawPromptTotal));
2552
+ }
2553
+
2477
2554
  const cacheRatio = ledger.lastObservedCacheRatio ?? 0;
2478
2555
 
2479
2556
  // 情况 A:单步无中间工具调用
@@ -1,16 +1,17 @@
1
- import type {
2
- Api,
3
- AssistantMessage,
4
- AssistantMessageEventStream,
5
- JsonObject,
6
- Model,
7
- ModelThinkingLevel,
8
- ThinkingContent,
9
- TextContent,
10
- ToolCall,
11
- Usage,
1
+ import {
2
+ calculateCost,
3
+ createAssistantMessageEventStream,
4
+ type Api,
5
+ type AssistantMessage,
6
+ type AssistantMessageEventStream,
7
+ type JsonObject,
8
+ type Model,
9
+ type ModelThinkingLevel,
10
+ type ThinkingContent,
11
+ type TextContent,
12
+ type ToolCall,
13
+ type Usage,
12
14
  } from "@earendil-works/pi-ai";
13
- import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
14
15
  import type { AcpPromptStopReason, AcpPromptUsage } from "../acp/protocol.ts";
15
16
 
16
17
  /**
@@ -215,6 +216,7 @@ export function convertAcpUsageToPiUsage(acpUsage?: AcpPromptUsage): Usage {
215
216
  export class StepStreamWriter {
216
217
  readonly stream: AssistantMessageEventStream;
217
218
  readonly message: AssistantMessage;
219
+ private readonly model: Model<Api>;
218
220
  private started = false;
219
221
  private terminated = false;
220
222
  private openBlock?: { kind: "thinking" | "text"; index: number };
@@ -231,6 +233,7 @@ export class StepStreamWriter {
231
233
  thinkingLevel?: ModelThinkingLevel;
232
234
  } = {},
233
235
  ) {
236
+ this.model = model;
234
237
  this.stream = createAssistantMessageEventStream();
235
238
  this.message = {
236
239
  role: "assistant",
@@ -452,8 +455,9 @@ export class StepStreamWriter {
452
455
  this.closeOpenBlock();
453
456
 
454
457
  if (stepUsage) {
455
- this.message.usage = stepUsage;
458
+ this.message.usage = { ...stepUsage, cost: { ...stepUsage.cost } };
456
459
  }
460
+ calculateCost(this.model, this.message.usage);
457
461
  this.message.stopReason = "toolUse";
458
462
  this.terminated = true;
459
463
  this.stream.push({
@@ -484,10 +488,11 @@ export class StepStreamWriter {
484
488
  this.message.endTurn = reason === "stop";
485
489
 
486
490
  if (usageOrRaw && "cost" in usageOrRaw && "cacheRead" in usageOrRaw) {
487
- this.message.usage = usageOrRaw;
491
+ this.message.usage = { ...usageOrRaw, cost: { ...usageOrRaw.cost } };
488
492
  } else {
489
493
  this.message.usage = convertAcpUsageToPiUsage(usageOrRaw as AcpPromptUsage | undefined);
490
494
  }
495
+ calculateCost(this.model, this.message.usage);
491
496
 
492
497
  this.terminated = true;
493
498
  this.stream.push({