pi-antigravity-bridge 0.1.14 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.15] - 2026-11-24
4
+
5
+ ### Changed
6
+
7
+ - 优化 `pi-tools` 模式下大体积工具文本输出的回传链路,完整保留超过 10 KB 的文件读取、命令执行、脚本与 MCP 工具输出,减少大文件分段重复读取次数并保持当前会话缓存命中。
8
+ - 完善 `pi-tools` 模式工作区上下文挂载:支持透传 `codemode` 及第三方扩展工具的使用指引、用户附加提示词与扩展自定义上下文区块,并补充 Pi MCP 服务器与资源的访问引导。
9
+ - 为名称超长的直通 MCP 工具自动生成兼容长度限制的调用别名并在执行时还原原始工具名,同时缩短单次工具调用的聚合等待时间并缓存历史图片摘要以降低多步工具循环开销。
10
+ - 在单轮连续工具调用达到后端单次步数上限时自动续接当前会话,避免长任务中途静默停止。
11
+
12
+ ### Fixed
13
+
14
+ - 修复 `pi-tools` 模式下禁用内置工具后仍残留 `list_resources`、`read_resource` 与 `manage_task` 原生工具的问题,避免误调不可用的资源接口或拖慢后续工具响应。
15
+ - 修复工具请求体在跨网络分片传输中文或 Emoji 等多字节 UTF-8 字符时可能产生乱码导致写入损坏或编辑匹配失败的问题。
16
+ - 修复并发执行多个慢速工具触发挂起超时剥离时可能遗漏同批部分工具执行结果的问题。
17
+ - 修复运行中切换工具、转向输入或回传大尺寸结果时,未等待正在写入的工具记录完成后再收口旧请求导致的偶发结果丢失问题。
18
+ - 修复上游网络流瞬断自动重试时将瞬时错误提示拼入模型回复正文,以及误将失败重试记录计入用量统计的问题。
19
+ - 修复模型向可选参数传入 `null` 或字符串化数组/对象导致参数校验失败重试、根级 `$ref` Schema 校验不完整、同名子串工具前置宣告误匹配,以及 `processPerSession: false` 模式下鉴权或服务异常未返回标准错误响应的问题。
20
+
3
21
  ## [0.1.14] - 2026-11-22
4
22
 
5
23
  ### Added
@@ -4,6 +4,10 @@ description: Tool execution bridge agent for Pi.
4
4
  mainAgent: true
5
5
  subagent: false
6
6
  tools: []
7
+ disabledTools:
8
+ - list_resources
9
+ - read_resource
10
+ - manage_task
7
11
  excludeDefaultComponents: true
8
12
  inheritCustomizations: false
9
13
  inheritMcp: false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-antigravity-bridge",
3
- "version": "0.1.14",
3
+ "version": "0.1.15",
4
4
  "description": "Google Antigravity CLI (agy acp) agent backend bridge for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -193,6 +193,7 @@ function resolveManagedAgentMaterialization(
193
193
  inheritCustomizations: profile.inheritCustomizations,
194
194
  inheritMcp: profile.inheritMcp,
195
195
  mountedPluginPaths: profile.mountedPluginPaths,
196
+ agentSchemaRev: 2,
196
197
  }),
197
198
  )
198
199
  .digest("hex")
@@ -249,7 +250,13 @@ function resolveManagedAgentMaterialization(
249
250
  ];
250
251
 
251
252
  if (profile.disableBuiltinTools) {
252
- yamlLines.push("tools: []");
253
+ yamlLines.push(
254
+ "tools: []",
255
+ "disabledTools:",
256
+ " - list_resources",
257
+ " - read_resource",
258
+ " - manage_task",
259
+ );
253
260
  }
254
261
  if (profile.excludeDefaultComponents) {
255
262
  yamlLines.push("excludeDefaultComponents: true");
@@ -1,11 +1,14 @@
1
1
  import * as crypto from "node:crypto";
2
2
  import * as http from "node:http";
3
+ import { StringDecoder } from "node:string_decoder";
3
4
  import type { ImageContent, JsonObject, TextContent, Tool } from "@earendil-works/pi-ai";
4
5
  import type { AcpMcpServerSpec } from "../acp/protocol.ts";
5
- import { validateToolArguments } from "./schema-validator.ts";
6
+ import { resolveLocalSchemaRef, validateToolArguments } from "./schema-validator.ts";
6
7
  import { buildInlineStdioShimCommand } from "./stdio-shim.ts";
7
8
 
8
9
  export const MCP_SERVER_NAME = "pi_tools";
10
+ /** 预留 `mcp_pi_tools_`(13 字符)前缀后,暴露给上游模型函数名的最大安全长度(总长 <= 63 < 64) */
11
+ export const MAX_MCP_EXPOSED_TOOL_NAME_LEN = 50;
9
12
 
10
13
  export interface McpToolResultPayload {
11
14
  content: Array<TextContent | ImageContent>;
@@ -175,15 +178,50 @@ export function sanitizeJsonSchemaForMcp(rawSchema: unknown): Record<string, unk
175
178
  }
176
179
  }
177
180
 
181
+ /**
182
+ * 为超长宿主工具名(如长命名空间的直通 MCP 工具)生成满足上游 64 字符上限的确定性短别名;
183
+ * 常规长度工具名(`<= 50` 字符)保持原名零改动。
184
+ */
185
+ export function toExposedMcpToolName(originalName: string): string {
186
+ if (originalName.length <= MAX_MCP_EXPOSED_TOOL_NAME_LEN) {
187
+ return originalName;
188
+ }
189
+ const sanitized = originalName.replace(/[^a-zA-Z0-9_-]/g, "_");
190
+ const hash8 = crypto.createHash("sha256").update(originalName).digest("hex").slice(0, 8);
191
+ const head = sanitized.slice(0, 22).replace(/_+$/, "");
192
+ const tail = sanitized.slice(-17).replace(/^_+/, "");
193
+ return `${head}_${tail}_${hash8}`.slice(0, MAX_MCP_EXPOSED_TOOL_NAME_LEN);
194
+ }
195
+
178
196
  function normalizeMatchToken(name: string): string {
179
197
  return name.toLowerCase().replace(/[^a-z0-9]/g, "");
180
198
  }
181
199
 
182
- function doesAnnouncementMatchTool(announced: string, toolName: string): boolean {
183
- if (!announced) return true;
184
- const a = normalizeMatchToken(announced);
185
- const t = normalizeMatchToken(toolName);
186
- return a.includes(t) || t.includes(a);
200
+ function extractAnnouncedBareToolToken(raw: string): string {
201
+ const trimmed = raw.trim();
202
+ if (!trimmed) return "";
203
+ const prefixedMatch = /\bmcp_pi_tools_([a-zA-Z0-9_.-]+)\b/i.exec(trimmed);
204
+ if (prefixedMatch?.[1]) {
205
+ return normalizeMatchToken(prefixedMatch[1]);
206
+ }
207
+ const stripped = trimmed
208
+ .replace(/^mcp_pi_tools_/i, "")
209
+ .replace(/^pi_tools[:/]/i, "");
210
+ if (/\s/.test(stripped)) {
211
+ return "";
212
+ }
213
+ return normalizeMatchToken(stripped);
214
+ }
215
+
216
+ export function doesAnnouncementMatchTool(announced: string, toolName: string): boolean {
217
+ const trimmed = announced.trim();
218
+ if (!trimmed) return true;
219
+ const a = extractAnnouncedBareToolToken(trimmed);
220
+ if (!a) return false;
221
+ const origNorm = normalizeMatchToken(toolName);
222
+ if (a === origNorm) return true;
223
+ const exposedNorm = normalizeMatchToken(toExposedMcpToolName(toolName));
224
+ return a === exposedNorm;
187
225
  }
188
226
 
189
227
  function isSingleEditReplacement(value: unknown): value is { oldText: string; newText: string } {
@@ -194,13 +232,134 @@ function isSingleEditReplacement(value: unknown): value is { oldText: string; ne
194
232
  return typeof rec.oldText === "string" && typeof rec.newText === "string";
195
233
  }
196
234
 
235
+ function schemaAllowsType(
236
+ propSchema: Record<string, unknown>,
237
+ targetType: "null" | "string" | "array" | "object",
238
+ rootSchema: Record<string, unknown>,
239
+ depth = 0,
240
+ ): boolean {
241
+ if (depth > 8) return false;
242
+ if (typeof propSchema.$ref === "string") {
243
+ const resolved = resolveLocalSchemaRef(propSchema.$ref, rootSchema);
244
+ if (resolved && schemaAllowsType(resolved, targetType, rootSchema, depth + 1)) {
245
+ return true;
246
+ }
247
+ }
248
+ if (targetType === "null" && propSchema.const === null) return true;
249
+ if (Array.isArray(propSchema.enum)) {
250
+ if (targetType === "null" && propSchema.enum.includes(null)) return true;
251
+ if (targetType === "string" && propSchema.enum.some((v) => typeof v === "string")) return true;
252
+ }
253
+ const t = propSchema.type;
254
+ if (t === targetType) return true;
255
+ if (Array.isArray(t) && t.includes(targetType)) return true;
256
+ if (targetType === "object" && !t && propSchema.properties && typeof propSchema.properties === "object") {
257
+ return true;
258
+ }
259
+ for (const key of ["anyOf", "oneOf", "allOf"] as const) {
260
+ const branches = propSchema[key];
261
+ if (Array.isArray(branches)) {
262
+ for (const b of branches) {
263
+ if (
264
+ b &&
265
+ typeof b === "object" &&
266
+ !Array.isArray(b) &&
267
+ schemaAllowsType(b as Record<string, unknown>, targetType, rootSchema, depth + 1)
268
+ ) {
269
+ return true;
270
+ }
271
+ }
272
+ }
273
+ }
274
+ return false;
275
+ }
276
+
277
+ function normalizeArgsAgainstSchema(
278
+ node: unknown,
279
+ schema: Record<string, unknown>,
280
+ rootSchema: Record<string, unknown>,
281
+ depth = 0,
282
+ ): unknown {
283
+ if (depth > 8 || !node || typeof node !== "object" || Array.isArray(node)) {
284
+ return node;
285
+ }
286
+ const targetSchema =
287
+ typeof schema.$ref === "string"
288
+ ? (resolveLocalSchemaRef(schema.$ref, rootSchema) ?? schema)
289
+ : schema;
290
+ const props =
291
+ targetSchema.properties &&
292
+ typeof targetSchema.properties === "object" &&
293
+ !Array.isArray(targetSchema.properties)
294
+ ? (targetSchema.properties as Record<string, unknown>)
295
+ : undefined;
296
+ if (!props) return node;
297
+
298
+ const requiredSet = new Set(
299
+ Array.isArray(targetSchema.required)
300
+ ? targetSchema.required.filter((k): k is string => typeof k === "string")
301
+ : [],
302
+ );
303
+
304
+ const out: Record<string, unknown> = { ...(node as Record<string, unknown>) };
305
+ for (const [key, val] of Object.entries(out)) {
306
+ const propSchemaRaw = props[key];
307
+ if (!propSchemaRaw || typeof propSchemaRaw !== "object" || Array.isArray(propSchemaRaw)) {
308
+ continue;
309
+ }
310
+ const propSchema = propSchemaRaw as Record<string, unknown>;
311
+
312
+ // 剥离模型在非必填且非 nullable 字段上误传的显式 null
313
+ if (
314
+ val === null &&
315
+ !requiredSet.has(key) &&
316
+ !schemaAllowsType(propSchema, "null", rootSchema)
317
+ ) {
318
+ delete out[key];
319
+ continue;
320
+ }
321
+
322
+ // 将模型误传为 JSON 字符串的数组或对象参数自动反序列化
323
+ if (
324
+ typeof val === "string" &&
325
+ !schemaAllowsType(propSchema, "string", rootSchema)
326
+ ) {
327
+ const trimmed = val.trim();
328
+ const expectsArray = schemaAllowsType(propSchema, "array", rootSchema);
329
+ const expectsObject = schemaAllowsType(propSchema, "object", rootSchema);
330
+ if ((expectsArray && trimmed.startsWith("[")) || (expectsObject && trimmed.startsWith("{"))) {
331
+ try {
332
+ const parsed: unknown = JSON.parse(trimmed);
333
+ if (expectsArray && Array.isArray(parsed)) {
334
+ out[key] = parsed;
335
+ continue;
336
+ }
337
+ if (expectsObject && parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
338
+ out[key] = normalizeArgsAgainstSchema(parsed, propSchema, rootSchema, depth + 1);
339
+ continue;
340
+ }
341
+ } catch {
342
+ // 保留原字符串交由后续校验生成错误反馈
343
+ }
344
+ }
345
+ }
346
+
347
+ if (val && typeof val === "object" && !Array.isArray(val)) {
348
+ out[key] = normalizeArgsAgainstSchema(val, propSchema, rootSchema, depth + 1);
349
+ }
350
+ }
351
+ return out;
352
+ }
353
+
197
354
  /**
198
- * 在 JSON Schema 预校验前对齐原生 Pi 工具的参数容错归一化(如 `edit` 工具对字符串化 `edits`、单对象 `edits` 或顶层 `oldText/newText` 的兼容转换)。
355
+ * 在 JSON Schema 预校验前对齐原生 Pi 工具的参数容错归一化
356
+ *(含可选字段显式 `null` 剥离、字符串化对象/数组解析,以及 `edit` 工具对单对象 `edits` 或顶层 `oldText/newText` 的兼容转换)。
199
357
  */
200
- function normalizeHostToolArguments(
358
+ export function normalizeHostToolArguments(
201
359
  toolName: string,
202
360
  rawArgs: JsonObject,
203
361
  toolDef: Tool,
362
+ sanitizedSchema?: Record<string, unknown>,
204
363
  ): JsonObject {
205
364
  let current: unknown = { ...rawArgs };
206
365
  const maybeWithPrepare = toolDef as Tool & {
@@ -241,6 +400,11 @@ function normalizeHostToolArguments(
241
400
  current = args;
242
401
  }
243
402
 
403
+ if (current && typeof current === "object" && !Array.isArray(current)) {
404
+ const schema = sanitizedSchema ?? sanitizeJsonSchemaForMcp(toolDef.parameters);
405
+ current = normalizeArgsAgainstSchema(current, schema, schema, 0);
406
+ }
407
+
244
408
  if (current && typeof current === "object" && !Array.isArray(current)) {
245
409
  return current as JsonObject;
246
410
  }
@@ -462,15 +626,7 @@ export class LocalHttpMcpBridge {
462
626
  }
463
627
  }
464
628
 
465
- private waitForAnnouncementPairing(
466
- toolName: string,
467
- agySessionId: string | undefined,
468
- windowMs = 2_000,
469
- ): Promise<boolean> {
470
- if (agySessionId && this.cancelledSessions.has(agySessionId)) {
471
- return Promise.resolve(false);
472
- }
473
-
629
+ private consumeMatchingAnnouncement(toolName: string, agySessionId: string | undefined): boolean {
474
630
  const now = Date.now();
475
631
  this.pruneExpiredAnnouncements(now);
476
632
  const existingIdx = this.recentAnnouncements.findIndex(
@@ -480,6 +636,21 @@ export class LocalHttpMcpBridge {
480
636
  );
481
637
  if (existingIdx !== -1) {
482
638
  this.recentAnnouncements.splice(existingIdx, 1);
639
+ return true;
640
+ }
641
+ return false;
642
+ }
643
+
644
+ private waitForAnnouncementPairing(
645
+ toolName: string,
646
+ agySessionId: string | undefined,
647
+ windowMs = 2_000,
648
+ ): Promise<boolean> {
649
+ if (agySessionId && this.cancelledSessions.has(agySessionId)) {
650
+ return Promise.resolve(false);
651
+ }
652
+
653
+ if (this.consumeMatchingAnnouncement(toolName, agySessionId)) {
483
654
  return Promise.resolve(true);
484
655
  }
485
656
 
@@ -567,9 +738,11 @@ export class LocalHttpMcpBridge {
567
738
 
568
739
  let rawBody = "";
569
740
  try {
741
+ const bodyDecoder = new StringDecoder("utf8");
570
742
  for await (const chunk of req) {
571
- rawBody += typeof chunk === "string" ? chunk : (chunk as Buffer).toString("utf8");
743
+ rawBody += typeof chunk === "string" ? chunk : bodyDecoder.write(chunk as Buffer);
572
744
  }
745
+ rawBody += bodyDecoder.end();
573
746
  } catch {
574
747
  res.writeHead(400);
575
748
  res.end();
@@ -644,11 +817,16 @@ export class LocalHttpMcpBridge {
644
817
  }
645
818
 
646
819
  if (method === "tools/list") {
647
- const toolsList = binding.tools.map((tool) => ({
648
- name: tool.name,
649
- description: tool.description || tool.name,
650
- inputSchema: sanitizeJsonSchemaForMcp(tool.parameters),
651
- }));
820
+ const toolsList = binding.tools.map((tool) => {
821
+ const exposedName = toExposedMcpToolName(tool.name);
822
+ const baseDesc = tool.description || tool.name;
823
+ return {
824
+ name: exposedName,
825
+ description:
826
+ exposedName !== tool.name ? `[Original tool: ${tool.name}] ${baseDesc}` : baseDesc,
827
+ inputSchema: sanitizeJsonSchemaForMcp(tool.parameters),
828
+ };
829
+ });
652
830
  res.writeHead(200);
653
831
  res.end(
654
832
  JSON.stringify({
@@ -682,7 +860,7 @@ export class LocalHttpMcpBridge {
682
860
  binding: SessionMcpBinding,
683
861
  res: http.ServerResponse,
684
862
  ): Promise<void> {
685
- const toolName = typeof params.name === "string" ? params.name : "";
863
+ const incomingName = typeof params.name === "string" ? params.name : "";
686
864
  const rawArgs =
687
865
  params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments)
688
866
  ? (params.arguments as JsonObject)
@@ -701,9 +879,12 @@ export class LocalHttpMcpBridge {
701
879
  : undefined) ??
702
880
  binding.agySessionId;
703
881
 
704
- const toolDef = binding.tools.find((t) => t.name === toolName);
882
+ const toolDef = binding.tools.find(
883
+ (t) => t.name === incomingName || toExposedMcpToolName(t.name) === incomingName,
884
+ );
705
885
  if (!toolDef) {
706
- binding.onRejectedCall?.(toolName);
886
+ this.consumeMatchingAnnouncement(incomingName, rootConvId);
887
+ binding.onRejectedCall?.(incomingName);
707
888
  res.writeHead(200);
708
889
  res.end(
709
890
  JSON.stringify({
@@ -714,7 +895,7 @@ export class LocalHttpMcpBridge {
714
895
  content: [
715
896
  {
716
897
  type: "text",
717
- text: `Unknown tool "${toolName}". Available tools: ${binding.tools.map((t) => t.name).join(", ")}`,
898
+ text: `Unknown tool "${incomingName}". Available tools: ${binding.tools.map((t) => toExposedMcpToolName(t.name)).join(", ")}`,
718
899
  },
719
900
  ],
720
901
  },
@@ -723,14 +904,14 @@ export class LocalHttpMcpBridge {
723
904
  return;
724
905
  }
725
906
 
907
+ const toolName = toolDef.name;
908
+ const sanitizedSchema = sanitizeJsonSchemaForMcp(toolDef.parameters);
909
+
726
910
  // 1. 对齐宿主工具的参数预处理与 JSON Schema 参数预校验(与 tools/list 暴露的规整 Schema 保持一致)
727
- const normalizedArgs = normalizeHostToolArguments(toolName, rawArgs, toolDef);
728
- const validation = validateToolArguments(
729
- toolName,
730
- normalizedArgs,
731
- sanitizeJsonSchemaForMcp(toolDef.parameters),
732
- );
911
+ const normalizedArgs = normalizeHostToolArguments(toolName, rawArgs, toolDef, sanitizedSchema);
912
+ const validation = validateToolArguments(toolName, normalizedArgs, sanitizedSchema);
733
913
  if (!validation.valid) {
914
+ this.consumeMatchingAnnouncement(toolName, rootConvId);
734
915
  binding.onRejectedCall?.(toolName);
735
916
  res.writeHead(200);
736
917
  res.end(
@@ -45,10 +45,13 @@ function deepEqualPrimitiveOrJson(a: unknown, b: unknown): boolean {
45
45
  }
46
46
  }
47
47
 
48
- function resolveLocalSchemaRef(
48
+ export function resolveLocalSchemaRef(
49
49
  ref: string,
50
50
  rootSchema: Record<string, unknown>,
51
51
  ): Record<string, unknown> | undefined {
52
+ if (ref === "#") {
53
+ return rootSchema;
54
+ }
52
55
  if (!ref.startsWith("#/")) return undefined;
53
56
  const parts = ref
54
57
  .slice(2)
@@ -118,7 +121,17 @@ function validateNode(
118
121
  if (typeof schema.$ref === "string" && refDepth < 8) {
119
122
  const resolved = resolveLocalSchemaRef(schema.$ref, rootSchema);
120
123
  if (resolved) {
124
+ const issueCountBefore = issues.length;
121
125
  validateNode(value, resolved, currentPath, issues, rootSchema, refDepth + 1);
126
+ if (issues.length > issueCountBefore) {
127
+ return;
128
+ }
129
+ const hasSiblingConstraint = Object.keys(schema).some(
130
+ (k) => k !== "$ref" && k !== "description" && k !== "title",
131
+ );
132
+ if (!hasSiblingConstraint) {
133
+ return;
134
+ }
122
135
  }
123
136
  }
124
137
 
@@ -32,6 +32,20 @@ export async function runStdioToHttpMcpShim(targetUrl: string, bearerToken: stri
32
32
  });
33
33
 
34
34
  const responseText = await response.text();
35
+ if (!response.ok) {
36
+ if (hasId) {
37
+ const errPayload = {
38
+ jsonrpc: "2.0",
39
+ id: parsed.id,
40
+ error: {
41
+ code: -32000,
42
+ message: `MCP HTTP ${response.status}: ${responseText.trim().slice(0, 240) || response.statusText}`,
43
+ },
44
+ };
45
+ process.stdout.write(`${JSON.stringify(errPayload)}\n`);
46
+ }
47
+ return;
48
+ }
35
49
  if (hasId && responseText.trim().length > 0) {
36
50
  process.stdout.write(`${responseText.trim()}\n`);
37
51
  }
@@ -148,6 +162,7 @@ export function buildInlineStdioShimCommand(
148
162
  ' try {',
149
163
  ' const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer " + token }, body: line });',
150
164
  ' const txt = (await res.text()).trim();',
165
+ ' if (!res.ok) { if (hasId) process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: "MCP HTTP " + res.status + (txt ? ": " + txt.slice(0, 240) : "") } }) + "\\n"); return; }',
151
166
  ' if (hasId && txt) process.stdout.write(txt + "\\n");',
152
167
  ' } catch (e) {',
153
168
  ' if (hasId) process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, error: { code: -32603, message: String(e) } }) + "\\n");',
@@ -473,7 +473,7 @@ export async function readSqliteGenerationUsagesSince(
473
473
  db = openSqliteWithTimeout(sqlite, dbPath, true);
474
474
  const rows = db
475
475
  .prepare(
476
- "SELECT idx, metadata, step_payload FROM steps WHERE step_type = 15 AND idx > ? AND metadata IS NOT NULL ORDER BY idx ASC",
476
+ "SELECT idx, metadata, step_payload FROM steps WHERE step_type = 15 AND status NOT IN (4, 5, 6, 7, 8, 12) AND idx > ? AND metadata IS NOT NULL ORDER BY idx ASC",
477
477
  )
478
478
  .all(afterStepIdx) as Array<{
479
479
  idx: number;
@@ -609,6 +609,36 @@ function stripHostMcpPrefix(rawName: string): string {
609
609
  return rawName.replace(/^mcp_pi_tools_/, "");
610
610
  }
611
611
 
612
+ const IMAGE_HASH_CACHE_MAX = 128;
613
+ const imageSha256Cache = new Map<string, string>();
614
+
615
+ function computeCachedImageSha256(rawSub: Uint8Array): string {
616
+ const len = rawSub.byteLength;
617
+ if (len < 4_096) {
618
+ return crypto.createHash("sha256").update(rawSub).digest("hex");
619
+ }
620
+ const mid = Math.floor(len / 2);
621
+ const headHex = Buffer.from(rawSub.subarray(0, 48)).toString("hex");
622
+ const midHex = Buffer.from(rawSub.subarray(mid - 24, mid + 24)).toString("hex");
623
+ const tailHex = Buffer.from(rawSub.subarray(len - 48, len)).toString("hex");
624
+ const cacheKey = `${len}:${headHex}:${midHex}:${tailHex}`;
625
+ const cached = imageSha256Cache.get(cacheKey);
626
+ if (cached !== undefined) {
627
+ imageSha256Cache.delete(cacheKey);
628
+ imageSha256Cache.set(cacheKey, cached);
629
+ return cached;
630
+ }
631
+ const computed = crypto.createHash("sha256").update(rawSub).digest("hex");
632
+ if (imageSha256Cache.size >= IMAGE_HASH_CACHE_MAX) {
633
+ const oldest = imageSha256Cache.keys().next().value;
634
+ if (oldest !== undefined) {
635
+ imageSha256Cache.delete(oldest);
636
+ }
637
+ }
638
+ imageSha256Cache.set(cacheKey, computed);
639
+ return computed;
640
+ }
641
+
612
642
  /**
613
643
  * 解析 AGY 本地 SQLite `gen_metadata.data`(最新代次 `field 1` 即完整 `ChatRequest` protobuf),
614
644
  * 还原发往上游云端 `streamGenerateContent` 的全量 JSON 请求体积与内容分类(支持 `pi-tools` / `agy-tools` / `hybrid` 及 Gemini/Claude 全模型)。
@@ -730,7 +760,7 @@ export function parseGenMetadataUpstreamRequest(
730
760
  text_content_utf8_bytes += Buffer.byteLength(tail, "utf8");
731
761
  if (
732
762
  tail.trim().length > 0 &&
733
- !/Please inspect the attached tool result image/i.test(tail)
763
+ !/Please (?:inspect the attached tool result|continue using the tool output)/i.test(tail)
734
764
  ) {
735
765
  trailingTool = "";
736
766
  }
@@ -845,7 +875,7 @@ export function parseGenMetadataUpstreamRequest(
845
875
  if (rawSub && rawSub.byteLength > 0 && mimeType.startsWith("image/")) {
846
876
  const decodedBytes = rawSub.byteLength;
847
877
  const base64Bytes = Math.ceil(decodedBytes / 3) * 4;
848
- const imageHash = crypto.createHash("sha256").update(rawSub).digest("hex");
878
+ const imageHash = computeCachedImageSha256(rawSub);
849
879
  let toolName = "";
850
880
  let sourceType = "user image";
851
881
  if (role === 4) {
@@ -1060,7 +1090,7 @@ export async function waitForSqliteToolStepsSettled(
1060
1090
  db = openSqliteWithTimeout(sqlite, dbPath, true, 200);
1061
1091
  const busy = db
1062
1092
  .prepare(
1063
- "SELECT 1 AS busy FROM steps WHERE step_type != 15 AND step_type != 14 AND status = 1 LIMIT 1",
1093
+ "SELECT 1 AS busy FROM steps WHERE step_type != 15 AND step_type != 14 AND status IN (1, 2, 8, 9, 11) LIMIT 1",
1064
1094
  )
1065
1095
  .get() as { busy?: number } | undefined;
1066
1096
  hasRunningTool = busy?.busy === 1;