@zergai/ztc 0.24.0-beta.1 → 0.25.0-beta.1

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.
Files changed (40) hide show
  1. package/README.md +29 -0
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/App.js +4 -0
  8. package/dist/agent/agent.js +5 -2
  9. package/dist/agent/backends/anthropic.js +4 -1
  10. package/dist/agent/backends/bedrock.js +4 -1
  11. package/dist/agent/backends/codex_app_server.js +6 -2
  12. package/dist/agent/backends/gemini.d.ts +9 -0
  13. package/dist/agent/backends/gemini.js +77 -39
  14. package/dist/agent/backends/openai_format.d.ts +17 -1
  15. package/dist/agent/backends/openai_format.js +122 -24
  16. package/dist/agent/backends/openai_responses.d.ts +15 -3
  17. package/dist/agent/backends/openai_responses.js +32 -8
  18. package/dist/agent/backends/request_metrics.js +7 -6
  19. package/dist/agent/backends/tool_result_images.d.ts +114 -0
  20. package/dist/agent/backends/tool_result_images.js +201 -0
  21. package/dist/agent/backends/types.d.ts +5 -0
  22. package/dist/agent/backends/zerg-api.js +4 -2
  23. package/dist/agent/backends/zrouter_stream.d.ts +47 -0
  24. package/dist/agent/backends/zrouter_stream.js +244 -54
  25. package/dist/agent/request_encoder.d.ts +6 -2
  26. package/dist/agent/request_encoder.js +24 -34
  27. package/dist/agent/runtime/evidence.d.ts +6 -0
  28. package/dist/agent/runtime/evidence.js +23 -1
  29. package/dist/agent/runtime/tool_runtime.js +30 -17
  30. package/dist/agent/subagent.js +7 -8
  31. package/dist/agent/tool_response_store.js +3 -3
  32. package/dist/agent/tool_result_parsing.d.ts +22 -0
  33. package/dist/agent/tool_result_parsing.js +51 -0
  34. package/dist/agent/tools/recall_tool_response.js +24 -0
  35. package/dist/cli_ratatui.js +4 -0
  36. package/dist/headless.js +6 -0
  37. package/dist/types.d.ts +5 -0
  38. package/dist/utils/compaction.js +30 -4
  39. package/dist/zlm-embed.mjs +651 -194
  40. package/package.json +9 -34
@@ -53,6 +53,154 @@ var init_transport_errors = __esm({
53
53
  }
54
54
  });
55
55
 
56
+ // src/agent/backends/tool_result_images.ts
57
+ function olderToolImagesLine(count3) {
58
+ return count3 === 1 ? OLDER_TOOL_IMAGE_NOTE : `[${count3} images omitted: older than the last ${TOOL_IMAGE_BUDGET} images]`;
59
+ }
60
+ function routerChatImageLimits(upstream) {
61
+ const router = { ...ROUTER_IMAGE_LIMITS, maxImages: 8, maxImageBytes: 40 * MIB };
62
+ if (upstream === "anthropic") return { ...router, maxBase64Chars: 5 * MIB };
63
+ if (upstream === "gemini") return { ...router, mediaTypes: GEMINI_IMAGE_LIMITS.mediaTypes, maxRequestBytes: GEMINI_IMAGE_LIMITS.maxRequestBytes };
64
+ return router;
65
+ }
66
+ function tighter(a, b) {
67
+ return a === void 0 ? b : b === void 0 ? a : Math.min(a, b);
68
+ }
69
+ function strictestImageLimits(limits) {
70
+ return limits.reduce((a, b) => {
71
+ const maxRequestBytes = tighter(a.maxRequestBytes, b.maxRequestBytes);
72
+ const maxImages = tighter(a.maxImages, b.maxImages);
73
+ const maxImageBytes = tighter(a.maxImageBytes, b.maxImageBytes);
74
+ return {
75
+ mediaTypes: a.mediaTypes.filter((type) => b.mediaTypes.includes(type)),
76
+ maxBase64Chars: Math.min(a.maxBase64Chars, b.maxBase64Chars),
77
+ ...maxRequestBytes === void 0 ? {} : { maxRequestBytes },
78
+ ...maxImages === void 0 ? {} : { maxImages },
79
+ ...maxImageBytes === void 0 ? {} : { maxImageBytes }
80
+ };
81
+ });
82
+ }
83
+ function toolImageCaption(toolUseId) {
84
+ return `Image from tool call ${toolUseId}:`;
85
+ }
86
+ function megabytes(size) {
87
+ return String(Number((size / (1024 * 1024)).toFixed(1)));
88
+ }
89
+ function tooLargeToolImageNote(cap) {
90
+ return `[image omitted: larger than the ${megabytes(cap)} MB limit]`;
91
+ }
92
+ function plan(messages, limits, sent) {
93
+ const planned = /* @__PURE__ */ new Map();
94
+ if (limits) {
95
+ const cap = Math.min(limits.maxBase64Chars, TOOL_IMAGE_BASE64_CAP);
96
+ const tooLarge = { kind: "note", text: tooLargeToolImageNote(cap) };
97
+ const noRoom = {
98
+ kind: "note",
99
+ text: `[image omitted: the request would exceed the ${megabytes(limits.maxRequestBytes ?? 0)} MB limit]`
100
+ };
101
+ const tooMany = { kind: "note", text: `[image omitted: the request would carry more than ${limits.maxImages} images]` };
102
+ const tooHeavy = {
103
+ kind: "note",
104
+ text: `[image omitted: the request's images would exceed ${megabytes(limits.maxImageBytes ?? 0)} MB]`
105
+ };
106
+ const taken = [];
107
+ let ownImages = 0;
108
+ let ownBytes = 0;
109
+ for (const message of messages) {
110
+ if (typeof message.content === "string") continue;
111
+ for (const block of message.content) {
112
+ if (block.type === "image") {
113
+ ownImages += 1;
114
+ ownBytes += Buffer.byteLength(block.data, "base64");
115
+ }
116
+ if (block.type !== "tool_result" || typeof block.content === "string") continue;
117
+ for (const part of block.content) {
118
+ if (part.type === "image" && limits.mediaTypes.includes(part.source.media_type)) taken.push(part);
119
+ }
120
+ }
121
+ }
122
+ const firstLatest = Math.max(0, taken.length - TOOL_IMAGE_BUDGET);
123
+ for (const part of taken.slice(0, firstLatest)) planned.set(part, OLDER);
124
+ let roomImages = (limits.maxImages ?? Infinity) - ownImages;
125
+ let roomBytes = (limits.maxImageBytes ?? Infinity) - ownBytes;
126
+ let carried = 0;
127
+ let blocked;
128
+ for (const part of taken.slice(firstLatest).reverse()) {
129
+ if (part.source.data.length > cap) {
130
+ planned.set(part, tooLarge);
131
+ continue;
132
+ }
133
+ const bytes4 = Buffer.byteLength(part.source.data, "base64");
134
+ blocked ??= carried >= sent ? noRoom : roomImages <= 0 ? tooMany : bytes4 > roomBytes ? tooHeavy : void 0;
135
+ if (blocked) {
136
+ planned.set(part, blocked);
137
+ continue;
138
+ }
139
+ planned.set(part, { kind: "image", mediaType: part.source.media_type, data: part.source.data });
140
+ carried += 1;
141
+ roomImages -= 1;
142
+ roomBytes -= bytes4;
143
+ }
144
+ }
145
+ return planned;
146
+ }
147
+ function planToolImages(messages, limits, sent = TOOL_IMAGE_BUDGET) {
148
+ const planned = plan(messages, limits, sent);
149
+ return (image) => planned.get(image) ?? PLACEHOLDER;
150
+ }
151
+ function olderToolImages(blocks, images) {
152
+ return blocks.reduce((count3, block) => block.type !== "tool_result" || typeof block.content === "string" ? count3 : count3 + block.content.filter((part) => part.type === "image" && images(part).kind === "older").length, 0);
153
+ }
154
+ function withToolImagesInResults(messages, images) {
155
+ return messages.map((message) => {
156
+ if (typeof message.content === "string") return message;
157
+ const older = olderToolImages(message.content, images);
158
+ const lastOlder = message.content.flatMap((block) => block.type === "tool_result" && typeof block.content !== "string" ? block.content.filter((part) => part.type === "image" && images(part).kind === "older") : []).at(-1);
159
+ return { ...message, content: message.content.map((block) => block.type !== "tool_result" || typeof block.content === "string" ? block : { ...block, content: block.content.map((part) => {
160
+ if (part.type !== "image") return part;
161
+ const sent = images(part);
162
+ if (sent.kind === "image") return part;
163
+ return { type: "text", text: sent.kind === "note" ? sent.text : part === lastOlder ? olderToolImagesLine(older) : "[image]" };
164
+ }) }) };
165
+ });
166
+ }
167
+ function sendsToolImages(messages, limits, sent = TOOL_IMAGE_BUDGET) {
168
+ return [...plan(messages, limits, sent).values()].some((image) => image.kind === "image");
169
+ }
170
+ function fittedBody(maxRequestBytes, build) {
171
+ let body = build(TOOL_IMAGE_BUDGET);
172
+ for (let sent = TOOL_IMAGE_BUDGET - 1; sent >= 0 && Buffer.byteLength(body) > (maxRequestBytes ?? Infinity); sent--) body = build(sent);
173
+ return body;
174
+ }
175
+ var TOOL_IMAGE_BUDGET, TOOL_IMAGE_BASE64_CAP, OLDER_TOOL_IMAGE_NOTE, MIB, IMAGE_TYPES, OPENAI_IMAGE_LIMITS, ROUTER_IMAGE_LIMITS, ANTHROPIC_IMAGE_LIMITS, BEDROCK_IMAGE_LIMITS, GEMINI_IMAGE_LIMITS, ATLAS_IMAGE_LIMITS, PLACEHOLDER, OLDER;
176
+ var init_tool_result_images = __esm({
177
+ "src/agent/backends/tool_result_images.ts"() {
178
+ "use strict";
179
+ TOOL_IMAGE_BUDGET = 3;
180
+ TOOL_IMAGE_BASE64_CAP = 8 * 1024 * 1024;
181
+ OLDER_TOOL_IMAGE_NOTE = `[image omitted: older than the last ${TOOL_IMAGE_BUDGET} images]`;
182
+ MIB = 1024 * 1024;
183
+ IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
184
+ OPENAI_IMAGE_LIMITS = { mediaTypes: IMAGE_TYPES, maxBase64Chars: 5e7 };
185
+ ROUTER_IMAGE_LIMITS = { mediaTypes: IMAGE_TYPES, maxBase64Chars: Math.ceil(10 * MIB / 3) * 4 };
186
+ ANTHROPIC_IMAGE_LIMITS = { mediaTypes: IMAGE_TYPES, maxBase64Chars: 5 * MIB, maxImages: 20 };
187
+ BEDROCK_IMAGE_LIMITS = { mediaTypes: IMAGE_TYPES, maxBase64Chars: 5 * MIB, maxImages: 20 };
188
+ GEMINI_IMAGE_LIMITS = {
189
+ mediaTypes: ["image/png", "image/jpeg", "image/webp"],
190
+ maxBase64Chars: 2e7,
191
+ maxRequestBytes: 2e7
192
+ };
193
+ ATLAS_IMAGE_LIMITS = {
194
+ mediaTypes: IMAGE_TYPES,
195
+ maxBase64Chars: 2 * 1024 * 1024 - "data:image/jpeg;base64,".length,
196
+ maxImages: 8,
197
+ maxRequestBytes: 8 * 1024 * 1024
198
+ };
199
+ PLACEHOLDER = { kind: "placeholder" };
200
+ OLDER = { kind: "older" };
201
+ }
202
+ });
203
+
56
204
  // src/agent/backends/bedrock.ts
57
205
  function loadBedrockSdk() {
58
206
  bedrockSdk ??= import("@aws-sdk/client-bedrock-runtime").catch(() => {
@@ -130,7 +278,8 @@ function buildInput(request2) {
130
278
  if (!request2.model.trim()) throw new Error("Bedrock model is not configured");
131
279
  return {
132
280
  modelId: request2.model,
133
- messages: request2.messages.map((message) => ({ role: message.role, content: requestContent(message.content) })),
281
+ // A tool's images go in its toolResult, the latest few within Bedrock's limits (tool_result_images.ts).
282
+ messages: withToolImagesInResults(request2.messages, planToolImages(request2.messages, BEDROCK_IMAGE_LIMITS)).map((message) => ({ role: message.role, content: requestContent(message.content) })),
134
283
  inferenceConfig: { maxTokens: request2.maxTokens },
135
284
  ...request2.system ? { system: [{ text: request2.system }] } : {},
136
285
  ...request2.tools.length ? { toolConfig: { tools: request2.tools.map((tool) => ({ toolSpec: {
@@ -150,6 +299,7 @@ var init_bedrock = __esm({
150
299
  "src/agent/backends/bedrock.ts"() {
151
300
  "use strict";
152
301
  init_transport_errors();
302
+ init_tool_result_images();
153
303
  BedrockBackend = class {
154
304
  client;
155
305
  region;
@@ -1299,8 +1449,13 @@ async function readBoundedProviderError(response) {
1299
1449
  return `Provider response exceeded ${MAX_PROVIDER_ERROR_BYTES} bytes; body omitted.`;
1300
1450
  }
1301
1451
  }
1302
- function buildResponsesInput(messages) {
1452
+ function toolImageInput(sent, line) {
1453
+ if (sent.kind === "image") return { type: "input_image", image_url: `data:${sent.mediaType};base64,${sent.data}` };
1454
+ return { type: "input_text", text: sent.kind === "note" ? sent.text : line ?? "[image]" };
1455
+ }
1456
+ function buildResponsesInput(messages, toolImages = OPENAI_IMAGE_LIMITS, sent = TOOL_IMAGE_BUDGET) {
1303
1457
  const input2 = [];
1458
+ const images = planToolImages(messages, toolImages || void 0, sent);
1304
1459
  for (const msg of messages) {
1305
1460
  if (msg.role === "assistant" && msg.responseItems?.length) {
1306
1461
  const items = msg.responseItems;
@@ -1326,6 +1481,8 @@ function buildResponsesInput(messages) {
1326
1481
  }
1327
1482
  const userParts = [];
1328
1483
  let hasImage = false;
1484
+ const olderCount = olderToolImages(msg.content, images);
1485
+ const lastOlder = msg.content.flatMap((block) => block.type === "tool_result" && typeof block.content !== "string" ? block.content.filter((part) => part.type === "image" && images(part).kind === "older") : []).at(-1);
1329
1486
  for (const block of msg.content) {
1330
1487
  switch (block.type) {
1331
1488
  case "text":
@@ -1345,12 +1502,12 @@ function buildResponsesInput(messages) {
1345
1502
  });
1346
1503
  break;
1347
1504
  case "tool_result": {
1348
- const resultText = typeof block.content === "string" ? block.content : block.content.map((b) => b.type === "text" ? b.text : "[image]").join("\n");
1349
- const parts = Array.isArray(block.content) && block.content.some((part) => part.type === "image") ? block.content.map((part) => part.type === "text" ? { type: "input_text", text: block.is_error && !/^error\b/i.test(part.text) ? `Error: ${part.text}` : part.text } : { type: "input_image", image_url: `data:${part.source.media_type};base64,${part.source.data}` }) : void 0;
1505
+ const resultText2 = typeof block.content === "string" ? block.content : block.content.map((b) => b.type === "text" ? b.text : "[image]").join("\n");
1506
+ const parts = toolImages && Array.isArray(block.content) && block.content.some((part) => part.type === "image") ? block.content.map((part) => part.type === "text" ? { type: "input_text", text: block.is_error && !/^error\b/i.test(part.text) ? `Error: ${part.text}` : part.text } : toolImageInput(images(part), part === lastOlder ? olderToolImagesLine(olderCount) : void 0)) : void 0;
1350
1507
  input2.push({
1351
1508
  type: "function_call_output",
1352
1509
  call_id: block.tool_use_id,
1353
- output: parts ?? (block.is_error && !/^error\b/i.test(resultText) ? `Error: ${resultText}` : resultText)
1510
+ output: parts ?? (block.is_error && !/^error\b/i.test(resultText2) ? `Error: ${resultText2}` : resultText2)
1354
1511
  });
1355
1512
  break;
1356
1513
  }
@@ -1603,6 +1760,7 @@ var init_openai_responses = __esm({
1603
1760
  init_responses_reasoning();
1604
1761
  init_base();
1605
1762
  init_token_usage();
1763
+ init_tool_result_images();
1606
1764
  MAX_RESPONSES_RESPONSE_BYTES = 64 * 1024 * 1024;
1607
1765
  MAX_PROVIDER_ERROR_BYTES = 64 * 1024;
1608
1766
  MAX_RESPONSES_SSE_EVENT_BYTES = 8 * 1024 * 1024;
@@ -1620,6 +1778,7 @@ var init_openai_responses = __esm({
1620
1778
  extraHeaders;
1621
1779
  extraBody;
1622
1780
  fetcher;
1781
+ toolImages;
1623
1782
  constructor(config2) {
1624
1783
  super();
1625
1784
  this.apiKey = config2.apiKey;
@@ -1629,10 +1788,11 @@ var init_openai_responses = __esm({
1629
1788
  this.fetcher = config2.fetcher ?? ((...args) => fetch(...args));
1630
1789
  this.preservesNativeHistory = config2.preserveNativeHistory ?? false;
1631
1790
  this.reasoningFromRequestOnly = config2.reasoningFromRequestOnly ?? false;
1791
+ this.toolImages = config2.toolImages ?? OPENAI_IMAGE_LIMITS;
1632
1792
  }
1633
- /** Build the Responses API request body, optionally in streaming mode. */
1634
- buildBody(request2, stream) {
1635
- const input2 = buildResponsesInput(request2.messages);
1793
+ /** Build the Responses API request body, optionally in streaming mode, with at most SENT of the latest tool images. */
1794
+ buildBody(request2, stream, sent = TOOL_IMAGE_BUDGET) {
1795
+ const input2 = buildResponsesInput(request2.messages, this.toolImages, sent);
1636
1796
  const tools = request2.tools.map((t) => ({
1637
1797
  type: "function",
1638
1798
  name: t.name,
@@ -1666,6 +1826,10 @@ var init_openai_responses = __esm({
1666
1826
  if (request2.outputFormat) body.text = { format: request2.outputFormat };
1667
1827
  return body;
1668
1828
  }
1829
+ /** The request body as sent, within the largest request the provider takes (Router's Atlas service): fittedBody. */
1830
+ serializeBody(request2, stream) {
1831
+ return fittedBody((this.toolImages || void 0)?.maxRequestBytes, (sent) => JSON.stringify(this.buildBody(request2, stream, sent)));
1832
+ }
1669
1833
  /** POST to /responses, throwing a descriptive error on transport / API failure. */
1670
1834
  async fetchResponses(request2, stream) {
1671
1835
  const url2 = `${this.baseUrl}/responses`;
@@ -1678,7 +1842,7 @@ var init_openai_responses = __esm({
1678
1842
  Authorization: `Bearer ${this.apiKey}`,
1679
1843
  ...this.extraHeaders
1680
1844
  },
1681
- body: JSON.stringify(this.buildBody(request2, stream)),
1845
+ body: this.serializeBody(request2, stream),
1682
1846
  signal: request2.signal,
1683
1847
  redirect: "error"
1684
1848
  });
@@ -1883,8 +2047,8 @@ function needsRetiredRouteMove(saved2) {
1883
2047
  function hasRetiredSettings(saved2) {
1884
2048
  const pool = isRecord2(saved2.accounts) ? saved2.accounts : void 0;
1885
2049
  const accounts = Array.isArray(pool?.accounts) ? pool.accounts : [];
1886
- const plan = isRecord2(saved2.zrouterRoutePlan) ? saved2.zrouterRoutePlan : void 0;
1887
- const fallbacks = Array.isArray(plan?.fallbacks) ? plan.fallbacks : [];
2050
+ const plan2 = isRecord2(saved2.zrouterRoutePlan) ? saved2.zrouterRoutePlan : void 0;
2051
+ const fallbacks = Array.isArray(plan2?.fallbacks) ? plan2.fallbacks : [];
1888
2052
  return isRetiredProvider(saved2.provider) || isRetiredProvider(saved2.simProvider) || hasRetiredKey(saved2.apiKeys) || hasRetiredKey(saved2.apiKeyEnv) || hasRetiredKey(saved2.codexEffortByProvider) || isRecord2(saved2.codexEffortByModel) && Object.keys(saved2.codexEffortByModel).some(isRetiredModel) || fallbacks.some((entry) => typeof entry === "string" && isRetiredProvider(entry.split("/")[0])) || accounts.some((account) => isRecord2(account) && isRetiredProvider(account.provider)) || hasRetiredKey(pool?.activePerProvider) || pool?.rotation !== void 0;
1889
2053
  }
1890
2054
  function withoutRetiredSecrets(saved2) {
@@ -2206,6 +2370,7 @@ var init_anthropic = __esm({
2206
2370
  init_sse();
2207
2371
  init_openai_responses();
2208
2372
  init_retired_routes();
2373
+ init_tool_result_images();
2209
2374
  EXTENDED_CACHE_BETA = "extended-cache-ttl-2025-04-11";
2210
2375
  AnthropicBackend = class {
2211
2376
  preservesNativeHistory;
@@ -2256,7 +2421,8 @@ var init_anthropic = __esm({
2256
2421
  buildBody(request2) {
2257
2422
  const cc = this.cacheControl;
2258
2423
  const hasSystem = typeof request2.system === "string" && request2.system.length > 0;
2259
- const messages = request2.messages.map((message) => ({
2424
+ const sent = withToolImagesInResults(request2.messages, planToolImages(request2.messages, ANTHROPIC_IMAGE_LIMITS));
2425
+ const messages = sent.map((message) => ({
2260
2426
  role: message.role,
2261
2427
  content: typeof message.content === "string" ? message.content : message.content.filter((block) => block.type !== "responses_reasoning").map((block) => {
2262
2428
  if (block.type === "text") {
@@ -2895,12 +3061,14 @@ var init_request_metrics = __esm({
2895
3061
  fetch = async (url2, init) => {
2896
3062
  const headers = new Headers(init?.headers);
2897
3063
  headers.set("X-Zerg-Request-ID", this.metrics.requestId);
2898
- const attempt = this.request.transportTurnId ? {
2899
- attemptId: randomUUID2(),
2900
- ...headers.get("x-zerg-resume-after") ? { resumeAfter: headers.get("x-zerg-resume-after") } : {}
2901
- } : void 0;
2902
- if (this.request.transportTurnId && attempt) {
2903
- headers.set("X-Zerg-Turn-ID", this.request.transportTurnId);
3064
+ const turn = headers.get("X-Zerg-Turn-ID") ?? this.request.transportTurnId;
3065
+ let attempt;
3066
+ if (turn) {
3067
+ attempt = {
3068
+ attemptId: randomUUID2(),
3069
+ ...headers.get("x-zerg-resume-after") ? { resumeAfter: headers.get("x-zerg-resume-after") } : {}
3070
+ };
3071
+ headers.set("X-Zerg-Turn-ID", turn);
2904
3072
  headers.set("X-Zerg-Attempt-ID", attempt.attemptId);
2905
3073
  this.metrics.transportAttempts?.push(attempt);
2906
3074
  }
@@ -2967,17 +3135,82 @@ var init_request_metrics = __esm({
2967
3135
  });
2968
3136
 
2969
3137
  // src/agent/backends/openai_format.ts
2970
- function buildOpenAIMessages(request2) {
3138
+ function resultText(block) {
3139
+ return typeof block.content === "string" ? block.content : block.content.map((part) => part.type === "text" ? part.text || "" : "[image]").join("\n");
3140
+ }
3141
+ function toolImageParts(block, images) {
3142
+ if (typeof block.content === "string") return [];
3143
+ return block.content.flatMap((part) => {
3144
+ if (part.type !== "image") return [];
3145
+ const sent = images(part);
3146
+ if (sent.kind === "placeholder" || sent.kind === "older") return [];
3147
+ return [{ type: "text", text: toolImageCaption(block.tool_use_id) }, sent.kind === "image" ? { type: "image_url", image_url: { url: `data:${sent.mediaType};base64,${sent.data}` } } : { type: "text", text: sent.text }];
3148
+ });
3149
+ }
3150
+ function olderImagesPart(blocks, images) {
3151
+ const older = olderToolImages(blocks, images);
3152
+ return older > 0 ? [{ type: "text", text: olderToolImagesLine(older) }] : [];
3153
+ }
3154
+ function mediaPart(block) {
3155
+ if (block.type === "image") return { type: "image_url", image_url: { url: `data:${block.mediaType};base64,${block.data}` } };
3156
+ if (block.type === "video") return { type: "video_url", video_url: { url: `data:${block.mediaType};base64,${block.data}` } };
3157
+ return void 0;
3158
+ }
3159
+ function flattenedContent(blocks, images) {
3160
+ const items = [];
3161
+ const media = [];
3162
+ let following = [];
3163
+ let older = olderImagesPart(blocks, images);
3164
+ for (const block of blocks) {
3165
+ if (block.type === "tool_result") {
3166
+ items.push(`Previous tool result (${block.tool_use_id}): ${resultText(block)}`);
3167
+ following.push(...older, ...toolImageParts(block, images));
3168
+ older = [];
3169
+ continue;
3170
+ }
3171
+ if (following.length > 0) items.push(following);
3172
+ following = [];
3173
+ if (block.type === "tool_use") items.push(`Previous tool call ${block.name} (${block.id}): ${JSON.stringify(block.input)}`);
3174
+ else if (block.type === "text") items.push(block.text);
3175
+ else {
3176
+ const part = mediaPart(block);
3177
+ if (part) media.push(part);
3178
+ }
3179
+ }
3180
+ if (following.length > 0) items.push(following);
3181
+ const texts = items.filter((item) => typeof item === "string");
3182
+ if (texts.length === items.length && media.length === 0) return texts.join("\n");
3183
+ return [...items.flatMap((item) => typeof item === "string" ? [{ type: "text", text: item }] : item), ...media];
3184
+ }
3185
+ function contentParts(content2) {
3186
+ if (Array.isArray(content2)) return content2;
3187
+ return typeof content2 === "string" && content2.length > 0 ? [{ type: "text", text: content2 }] : [];
3188
+ }
3189
+ function buildOpenAIMessages(request2, options = {}) {
2971
3190
  const out = [
2972
3191
  { role: "system", content: request2.system }
2973
3192
  ];
3193
+ const images = planToolImages(request2.messages, options.toolImages, options.sent);
3194
+ let pending2 = [];
3195
+ const push = (message) => {
3196
+ if (pending2.length > 0 && message.role !== "tool") {
3197
+ if (message.role === "user") message.content = [...pending2, ...contentParts(message.content)];
3198
+ else out.push({ role: "user", content: pending2 });
3199
+ pending2 = [];
3200
+ }
3201
+ out.push(message);
3202
+ };
2974
3203
  const withReasoning = (m, msg) => {
2975
3204
  if (msg.role === "assistant" && msg.reasoning) m.reasoning_content = msg.reasoning;
2976
3205
  return m;
2977
3206
  };
2978
3207
  for (const msg of request2.messages) {
2979
3208
  if (typeof msg.content === "string") {
2980
- out.push(withReasoning({ role: msg.role, content: msg.content }, msg));
3209
+ push(withReasoning({ role: msg.role, content: msg.content }, msg));
3210
+ continue;
3211
+ }
3212
+ if (options.flattenToolHistory) {
3213
+ push(withReasoning({ role: msg.role, content: flattenedContent(msg.content, images) }, msg));
2981
3214
  continue;
2982
3215
  }
2983
3216
  const textParts = [];
@@ -2990,17 +3223,10 @@ function buildOpenAIMessages(request2) {
2990
3223
  } else if (block.type === "tool_use") {
2991
3224
  toolUses.push({ id: block.id, name: block.name, input: block.input });
2992
3225
  } else if (block.type === "tool_result") {
2993
- toolResults.push({ tool_use_id: block.tool_use_id, content: block.content, is_error: block.is_error });
2994
- } else if (block.type === "image") {
2995
- mediaParts.push({
2996
- type: "image_url",
2997
- image_url: { url: `data:${block.mediaType};base64,${block.data}` }
2998
- });
2999
- } else if (block.type === "video") {
3000
- mediaParts.push({
3001
- type: "video_url",
3002
- video_url: { url: `data:${block.mediaType};base64,${block.data}` }
3003
- });
3226
+ toolResults.push(block);
3227
+ } else {
3228
+ const part = mediaPart(block);
3229
+ if (part) mediaParts.push(part);
3004
3230
  }
3005
3231
  }
3006
3232
  if (msg.role === "assistant" && toolUses.length > 0) {
@@ -3019,25 +3245,27 @@ function buildOpenAIMessages(request2) {
3019
3245
  if (msg.reasoning) {
3020
3246
  assistantMsg.reasoning_content = msg.reasoning;
3021
3247
  }
3022
- out.push(assistantMsg);
3248
+ push(assistantMsg);
3023
3249
  continue;
3024
3250
  }
3025
3251
  if (toolResults.length > 0) {
3252
+ pending2.push(...olderImagesPart(msg.content, images));
3026
3253
  for (const tr of toolResults) {
3027
- const resultText = typeof tr.content === "string" ? tr.content : tr.content.map((b) => b.type === "text" ? b.text || "" : "[image]").join("\n");
3028
- out.push({
3254
+ const text5 = resultText(tr);
3255
+ push({
3029
3256
  role: "tool",
3030
3257
  tool_call_id: tr.tool_use_id,
3031
- content: tr.is_error && !/^error\b/i.test(resultText) ? `Error: ${resultText}` : resultText
3258
+ content: tr.is_error && !/^error\b/i.test(text5) ? `Error: ${text5}` : text5
3032
3259
  });
3260
+ pending2.push(...toolImageParts(tr, images));
3033
3261
  }
3034
3262
  if (textParts.length > 0 || mediaParts.length > 0) {
3035
3263
  if (mediaParts.length > 0) {
3036
3264
  const parts = textParts.map((t) => ({ type: "text", text: t }));
3037
3265
  parts.push(...mediaParts);
3038
- out.push({ role: "user", content: parts });
3266
+ push({ role: "user", content: parts });
3039
3267
  } else {
3040
- out.push({ role: "user", content: textParts.join("\n") });
3268
+ push({ role: "user", content: textParts.join("\n") });
3041
3269
  }
3042
3270
  }
3043
3271
  continue;
@@ -3045,11 +3273,12 @@ function buildOpenAIMessages(request2) {
3045
3273
  if (mediaParts.length > 0) {
3046
3274
  const parts = textParts.map((t) => ({ type: "text", text: t }));
3047
3275
  parts.push(...mediaParts);
3048
- out.push(withReasoning({ role: msg.role, content: parts }, msg));
3276
+ push(withReasoning({ role: msg.role, content: parts }, msg));
3049
3277
  } else {
3050
- out.push(withReasoning({ role: msg.role, content: textParts.join("\n") }, msg));
3278
+ push(withReasoning({ role: msg.role, content: textParts.join("\n") }, msg));
3051
3279
  }
3052
3280
  }
3281
+ if (pending2.length > 0) out.push({ role: "user", content: pending2 });
3053
3282
  return out;
3054
3283
  }
3055
3284
  function buildOpenAIToolDefs(tools) {
@@ -3065,6 +3294,7 @@ function buildOpenAIToolDefs(tools) {
3065
3294
  var init_openai_format = __esm({
3066
3295
  "src/agent/backends/openai_format.ts"() {
3067
3296
  "use strict";
3297
+ init_tool_result_images();
3068
3298
  }
3069
3299
  });
3070
3300
 
@@ -3468,53 +3698,24 @@ var init_gemini = __esm({
3468
3698
  "use strict";
3469
3699
  init_model_contracts();
3470
3700
  init_base();
3701
+ init_tool_result_images();
3471
3702
  GeminiBackend = class extends BaseBackend {
3472
3703
  apiKey;
3473
3704
  apiEndpoint;
3705
+ toolImages;
3474
3706
  constructor(config2) {
3475
3707
  super();
3476
3708
  this.apiKey = config2.apiKey;
3477
3709
  this.apiEndpoint = config2.apiEndpoint || "https://generativelanguage.googleapis.com/v1beta/models";
3710
+ this.toolImages = config2.toolImages ?? GEMINI_IMAGE_LIMITS;
3478
3711
  }
3479
3712
  async generate(request2) {
3480
3713
  const url2 = `${this.apiEndpoint}/${encodeURIComponent(request2.model)}:generateContent?key=${this.apiKey}`;
3481
- const mapParts = (content2) => {
3482
- if (typeof content2 === "string") {
3483
- return [{ text: content2 }];
3484
- }
3485
- return content2.filter((block) => block.type !== "thinking" && block.type !== "redacted_thinking" && block.type !== "responses_reasoning").map((block) => {
3486
- if (block.type === "text") {
3487
- return { text: block.text };
3488
- }
3489
- if (block.type === "tool_result") {
3490
- const resultText = typeof block.content === "string" ? block.content : block.content.map((b) => b.type === "text" ? b.text : "[image]").join("\n");
3491
- return { text: `Function ${block.tool_use_id} ${block.is_error ? "error" : "result"}: ${resultText}` };
3492
- }
3493
- if (block.type === "tool_use") {
3494
- return { functionCall: { name: block.name, args: block.input } };
3495
- }
3496
- return { inlineData: { mimeType: block.mediaType, data: block.data } };
3497
- });
3498
- };
3499
- const body = {
3500
- ...reasoningRequestParams("gemini", request2.model, request2.codexEffort),
3501
- systemInstruction: { parts: [{ text: request2.system }] },
3502
- contents: request2.messages.map((m) => ({
3503
- role: m.role === "assistant" ? "model" : "user",
3504
- parts: mapParts(m.content)
3505
- })),
3506
- tools: [{
3507
- functionDeclarations: request2.tools.map((t) => ({
3508
- name: t.name,
3509
- description: t.description,
3510
- parameters: t.parameters
3511
- }))
3512
- }]
3513
- };
3714
+ const body = fittedBody((this.toolImages || void 0)?.maxRequestBytes, (sent) => JSON.stringify(this.buildBody(request2, sent)));
3514
3715
  const response = await fetch(url2, {
3515
3716
  method: "POST",
3516
3717
  headers: { "Content-Type": "application/json" },
3517
- body: JSON.stringify(body),
3718
+ body,
3518
3719
  signal: request2.signal
3519
3720
  });
3520
3721
  if (!response.ok) {
@@ -3551,6 +3752,64 @@ var init_gemini = __esm({
3551
3752
  usage: data.usageMetadata ? { inputTokens, outputTokens, totalTokens } : void 0
3552
3753
  };
3553
3754
  }
3755
+ /** REQUEST's body, with at most SENT of the latest tool images. */
3756
+ buildBody(request2, sent) {
3757
+ const images = planToolImages(request2.messages, this.toolImages || void 0, sent);
3758
+ const imageParts = (block) => typeof block.content === "string" ? [] : block.content.flatMap((part) => {
3759
+ if (part.type !== "image") return [];
3760
+ const sent2 = images(part);
3761
+ if (sent2.kind === "placeholder" || sent2.kind === "older") return [];
3762
+ return [
3763
+ { text: toolImageCaption(block.tool_use_id) },
3764
+ sent2.kind === "image" ? { inlineData: { mimeType: sent2.mediaType, data: sent2.data } } : { text: sent2.text }
3765
+ ];
3766
+ });
3767
+ const mapParts = (content2) => {
3768
+ if (typeof content2 === "string") {
3769
+ return [{ text: content2 }];
3770
+ }
3771
+ const parts = [];
3772
+ let following = [];
3773
+ const olderCount = olderToolImages(content2, images);
3774
+ let older = olderCount > 0 ? [{ text: olderToolImagesLine(olderCount) }] : [];
3775
+ for (const block of content2) {
3776
+ if (block.type === "thinking" || block.type === "redacted_thinking" || block.type === "responses_reasoning") continue;
3777
+ if (block.type === "tool_result") {
3778
+ const resultText2 = typeof block.content === "string" ? block.content : block.content.map((b) => b.type === "text" ? b.text : "[image]").join("\n");
3779
+ parts.push({ text: `Function ${block.tool_use_id} ${block.is_error ? "error" : "result"}: ${resultText2}` });
3780
+ following.push(...older, ...imageParts(block));
3781
+ older = [];
3782
+ continue;
3783
+ }
3784
+ parts.push(...following);
3785
+ following = [];
3786
+ if (block.type === "text") {
3787
+ parts.push({ text: block.text });
3788
+ } else if (block.type === "tool_use") {
3789
+ parts.push({ functionCall: { name: block.name, args: block.input } });
3790
+ } else {
3791
+ parts.push({ inlineData: { mimeType: block.mediaType, data: block.data } });
3792
+ }
3793
+ }
3794
+ parts.push(...following);
3795
+ return parts;
3796
+ };
3797
+ return {
3798
+ ...reasoningRequestParams("gemini", request2.model, request2.codexEffort),
3799
+ systemInstruction: { parts: [{ text: request2.system }] },
3800
+ contents: request2.messages.map((m) => ({
3801
+ role: m.role === "assistant" ? "model" : "user",
3802
+ parts: mapParts(m.content)
3803
+ })),
3804
+ tools: [{
3805
+ functionDeclarations: request2.tools.map((t) => ({
3806
+ name: t.name,
3807
+ description: t.description,
3808
+ parameters: t.parameters
3809
+ }))
3810
+ }]
3811
+ };
3812
+ }
3554
3813
  };
3555
3814
  }
3556
3815
  });
@@ -4866,6 +5125,9 @@ function buildCodexAppServerEnv(codexHome, base = process.env) {
4866
5125
  ]) delete env[name2];
4867
5126
  return env;
4868
5127
  }
5128
+ function withoutToolImages(content2) {
5129
+ return content2.map((part) => part.type === "text" ? part : { type: "text", text: "[image]" });
5130
+ }
4869
5131
  function sha1(value) {
4870
5132
  return createHash4("sha1").update(value).digest("hex");
4871
5133
  }
@@ -5982,7 +6244,7 @@ var init_codex_app_server = __esm({
5982
6244
  if (typeof message.content === "string") return message.content;
5983
6245
  return message.content.filter((block) => block.type !== "image").map((block) => {
5984
6246
  if (block.type === "text") return block.text;
5985
- if (block.type === "tool_result") return typeof block.content === "string" ? block.content : JSON.stringify(block.content);
6247
+ if (block.type === "tool_result") return typeof block.content === "string" ? block.content : JSON.stringify(withoutToolImages(block.content));
5986
6248
  if (block.type === "tool_use") return JSON.stringify({ tool: block.name, input: block.input });
5987
6249
  return `[${block.type}]`;
5988
6250
  }).join("\n");
@@ -6020,7 +6282,7 @@ var init_codex_app_server = __esm({
6020
6282
  return {
6021
6283
  type: block.type,
6022
6284
  toolUseId: block.tool_use_id,
6023
- content: block.content,
6285
+ content: typeof block.content === "string" ? block.content : withoutToolImages(block.content),
6024
6286
  trust: "untrusted_external_data"
6025
6287
  };
6026
6288
  }
@@ -7559,9 +7821,39 @@ function parseImageToolResult(content2) {
7559
7821
  }
7560
7822
  return null;
7561
7823
  }
7824
+ function imageResultCaption(image) {
7825
+ return image.description || "Screenshot captured";
7826
+ }
7827
+ function isImageEnvelope(content2) {
7828
+ return ENVELOPE_START.test(content2);
7829
+ }
7830
+ function toolResultText(content2) {
7831
+ const image = parseImageToolResult(content2);
7832
+ if (image) return `${imageResultCaption(image)}
7833
+ [image]`;
7834
+ if (!isImageEnvelope(content2)) return content2;
7835
+ const description = ENVELOPE_DESCRIPTION.exec(content2)?.[1];
7836
+ let caption = "";
7837
+ try {
7838
+ caption = description === void 0 ? "" : JSON.parse(`"${description}"`);
7839
+ } catch {
7840
+ }
7841
+ return caption ? `${caption}
7842
+ [image]` : "[image]";
7843
+ }
7844
+ function withToolResultNote(content2, note, lead = "") {
7845
+ if (!note && !lead) return content2;
7846
+ if (parseImageToolResult(content2) === null) return `${lead}${content2}${note}`;
7847
+ const envelope = JSON.parse(content2);
7848
+ const description = typeof envelope.description === "string" ? envelope.description : "";
7849
+ return JSON.stringify({ ...envelope, description: `${lead}${description}${note}` });
7850
+ }
7851
+ var ENVELOPE_START, ENVELOPE_DESCRIPTION;
7562
7852
  var init_tool_result_parsing = __esm({
7563
7853
  "src/agent/tool_result_parsing.ts"() {
7564
7854
  "use strict";
7855
+ ENVELOPE_START = /^\{"type":"image","mediaType":"[^"\\]{0,100}","data":"/;
7856
+ ENVELOPE_DESCRIPTION = /","description":"((?:[^"\\]|\\.)*)"/;
7565
7857
  }
7566
7858
  });
7567
7859
 
@@ -8507,7 +8799,7 @@ ${EVIDENCE_RULES}
8507
8799
  };
8508
8800
  if (compact.kind === "observation") {
8509
8801
  const toolCallId = compact.source.toolCallId;
8510
- compact.excerpt = toolCallId && options.toolCallsInContext?.has(toolCallId) ? EXCERPT_IN_CONTEXT : prefix2(compact.excerpt, 512);
8802
+ compact.excerpt = toolCallId && options.toolCallsInContext?.has(toolCallId) ? EXCERPT_IN_CONTEXT : prefix2(toolResultText(compact.excerpt), 512);
8511
8803
  } else {
8512
8804
  if (compact.kind === "user_instruction") {
8513
8805
  compact.originalTextBytes ??= bytes2(compact.text);
@@ -8570,6 +8862,19 @@ Earlier evidence blocks in this conversation still apply; ${unchanged} unchanged
8570
8862
  ${omissions.join("; ")}.` : ""}`;
8571
8863
  return header + selected.sort((a, b) => a.index - b.index).map((row) => row.text).join("\n") + footer;
8572
8864
  }
8865
+ function evidenceContextForRequest(block) {
8866
+ return block.split("\n").map((line) => {
8867
+ let row;
8868
+ try {
8869
+ row = line.startsWith("{") ? JSON.parse(line) : void 0;
8870
+ } catch {
8871
+ return line;
8872
+ }
8873
+ const excerpt = row?.excerpt;
8874
+ if (row?.kind !== "observation" || typeof excerpt !== "string" || toolResultText(excerpt) === excerpt) return line;
8875
+ return JSON.stringify({ ...row, excerpt: prefix2(toolResultText(excerpt), 512) });
8876
+ }).join("\n");
8877
+ }
8573
8878
  function parseEvidenceSnapshot(value) {
8574
8879
  try {
8575
8880
  if (bytes2(JSON.stringify(value)) > EVIDENCE_MAX_SNAPSHOT_BYTES) return null;
@@ -8613,6 +8918,7 @@ var init_evidence = __esm({
8613
8918
  "src/agent/runtime/evidence.ts"() {
8614
8919
  "use strict";
8615
8920
  init_checked_commands();
8921
+ init_tool_result_parsing();
8616
8922
  init_verifier_contract();
8617
8923
  init_benchmark_comparison();
8618
8924
  init_source_verification_contract();
@@ -9378,7 +9684,7 @@ var init_tool_response_store = __esm({
9378
9684
  id: meta3.observation_id,
9379
9685
  recordedAt: meta3.timestamp,
9380
9686
  source: { origin: "host_tool", ...sourcePath ? { path: sourcePath } : {}, ...ephemeral ? {} : context?.source, toolCallId: toolUseId, toolName },
9381
- excerpt: ephemeral ? EPHEMERAL_TOOL_PLACEHOLDER : content2,
9687
+ excerpt: ephemeral ? EPHEMERAL_TOOL_PLACEHOLDER : toolResultText(content2),
9382
9688
  resultSha256: sha2564,
9383
9689
  resultBytes: Buffer.byteLength(content2),
9384
9690
  partial: partial2,
@@ -9522,7 +9828,7 @@ var init_tool_response_store = __esm({
9522
9828
  kind: "observation",
9523
9829
  recordedAt: record11.meta.timestamp,
9524
9830
  source: { origin: "legacy", toolCallId: id, toolName: record11.meta.tool_name, ...record11.meta.source_path ? { path: record11.meta.source_path } : {} },
9525
- excerpt: record11.content,
9831
+ excerpt: toolResultText(record11.content),
9526
9832
  resultSha256: record11.meta.result_sha256,
9527
9833
  resultBytes: Buffer.byteLength(record11.content),
9528
9834
  partial: Boolean(record11.meta.partial),
@@ -13044,6 +13350,7 @@ var init_zerg_api = __esm({
13044
13350
  init_kimi_params();
13045
13351
  init_sse();
13046
13352
  init_zrouter_events();
13353
+ init_tool_result_images();
13047
13354
  }
13048
13355
  });
13049
13356
 
@@ -13587,6 +13894,21 @@ import { randomUUID as randomUUID4 } from "node:crypto";
13587
13894
  function isPinnableDecoration(value) {
13588
13895
  return value !== void 0 && PINNABLE_DECORATION.test(value);
13589
13896
  }
13897
+ function toolImageRefusal(error62) {
13898
+ if (error62 instanceof RouterRefusalError) return TOOL_IMAGE_REFUSALS.has(error62.refusal.code) ? error62.refusal.code : void 0;
13899
+ const native = error62 instanceof Error ? /^API error \((\d{3})\): ([\s\S]*)$/.exec(error62.message) : null;
13900
+ const failure2 = error62 instanceof BackendHttpError ? { status: error62.status, body: error62.body } : native ? { status: Number(native[1]), body: native[2] } : void 0;
13901
+ if (failure2?.status === 413) return "HTTP 413";
13902
+ return failure2?.status === 400 && refusesImages(failure2.body) ? "HTTP 400" : void 0;
13903
+ }
13904
+ function refusesImages(body) {
13905
+ try {
13906
+ const parsed = JSON.parse(body);
13907
+ return IMAGE_REFUSAL_MESSAGES.has(parsed?.statusMessage) || IMAGE_REFUSAL_MESSAGES.has(parsed?.message) || IMAGE_REFUSAL_MESSAGES.has(parsed?.error?.message);
13908
+ } catch {
13909
+ return false;
13910
+ }
13911
+ }
13590
13912
  function sameRouterModel(catalog, provider, previous, selected) {
13591
13913
  const resolved = catalog && resolveRouterModel(catalog, provider, previous);
13592
13914
  if (resolved) return resolved.id === selected;
@@ -13753,17 +14075,7 @@ function normalizeHeaderValue(value, label, maxLength) {
13753
14075
  }
13754
14076
  return normalized;
13755
14077
  }
13756
- function chatOnlyRequest(request2) {
13757
- return { ...request2, tools: [], messages: request2.messages.map((message) => ({
13758
- ...message,
13759
- content: typeof message.content === "string" ? message.content : message.content.map((block) => {
13760
- if (block.type === "tool_use") return { type: "text", text: `Previous tool call ${block.name} (${block.id}): ${JSON.stringify(block.input)}` };
13761
- if (block.type === "tool_result") return { type: "text", text: `Previous tool result (${block.tool_use_id}): ${typeof block.content === "string" ? block.content : block.content.map((part) => part.type === "text" ? part.text : "[image]").join("\n")}` };
13762
- return block;
13763
- })
13764
- })) };
13765
- }
13766
- var ZROUTER_HEADERS_TIMEOUT_MS, routerClientSession, ROUTER_PIN_MAX_LENGTH, PINNABLE_DECORATION, DEFAULT_RECONNECT_ATTEMPTS, DEFAULT_RECONNECT_BASE_MS, DEFAULT_RECONNECT_CAP_MS, MAX_RECONNECT_ATTEMPTS, MAX_RECONNECT_MS, ZRouterStreamBackend, RouterAuthenticationError;
14078
+ var ZROUTER_HEADERS_TIMEOUT_MS, routerClientSession, ROUTER_PIN_MAX_LENGTH, PINNABLE_DECORATION, TOOL_IMAGE_REFUSALS, IMAGE_REFUSAL_MESSAGES, toolImagesRefused, toolImagesTold, resentTurns, DEFAULT_RECONNECT_ATTEMPTS, DEFAULT_RECONNECT_BASE_MS, DEFAULT_RECONNECT_CAP_MS, MAX_RECONNECT_ATTEMPTS, MAX_RECONNECT_MS, ZRouterStreamBackend, RouterAuthenticationError;
13767
14079
  var init_zrouter_stream = __esm({
13768
14080
  "src/agent/backends/zrouter_stream.ts"() {
13769
14081
  "use strict";
@@ -13774,6 +14086,7 @@ var init_zrouter_stream = __esm({
13774
14086
  init_types();
13775
14087
  init_sse();
13776
14088
  init_openai_format();
14089
+ init_tool_result_images();
13777
14090
  init_kimi_params();
13778
14091
  init_debug_log();
13779
14092
  init_zrouter_events();
@@ -13793,6 +14106,16 @@ var init_zrouter_stream = __esm({
13793
14106
  routerClientSession = randomUUID4();
13794
14107
  ROUTER_PIN_MAX_LENGTH = 128;
13795
14108
  PINNABLE_DECORATION = /^[A-Za-z0-9._:-]{1,64}$/;
14109
+ TOOL_IMAGE_REFUSALS = /* @__PURE__ */ new Set([
14110
+ "router_usage_unpriced",
14111
+ "router_usage_budget_exceeded",
14112
+ "router_usage_token_limit_exceeded",
14113
+ "personal_token_quota_exceeded"
14114
+ ]);
14115
+ IMAGE_REFUSAL_MESSAGES = /* @__PURE__ */ new Set(["Model does not support images", "Atlas images must be bounded inline image data"]);
14116
+ toolImagesRefused = /* @__PURE__ */ new Map();
14117
+ toolImagesTold = /* @__PURE__ */ new Set();
14118
+ resentTurns = /* @__PURE__ */ new Map();
13796
14119
  DEFAULT_RECONNECT_ATTEMPTS = 120;
13797
14120
  DEFAULT_RECONNECT_BASE_MS = 1e3;
13798
14121
  DEFAULT_RECONNECT_CAP_MS = 3e4;
@@ -13887,7 +14210,11 @@ var init_zrouter_stream = __esm({
13887
14210
  }
13888
14211
  return this.provider === "openai" && request2.model === "gpt-6.1-sol";
13889
14212
  }
13890
- async nativeResponses(request2, fetcher) {
14213
+ /**
14214
+ * The native Responses backend for REQUEST, and whether its request carries a tool image. WITHOUT_TOOL_IMAGES sends
14215
+ * none, as a request Router refused for them goes again.
14216
+ */
14217
+ async nativeResponses(request2, fetcher, withoutToolImages2 = false) {
13891
14218
  const contract = modelContract("openai", request2.model);
13892
14219
  const effort = request2.codexEffort ?? "low";
13893
14220
  if (process.env.ZTC_ROUTER_REQUIRED === "1" && (effort !== "low" || request2.codexFastMode)) {
@@ -13904,9 +14231,13 @@ var init_zrouter_stream = __esm({
13904
14231
  try {
13905
14232
  const headers = await this.buildHeaders(request2);
13906
14233
  headers["X-Zerg-Request-Timeout-Ms"] = String(timeoutMs);
14234
+ if (request2.transportTurnId) headers["X-Zerg-Turn-ID"] = request2.transportTurnId;
14235
+ const takes = this.getModelCapabilities(request2.model)?.images === false ? void 0 : process.env.ZTC_ROUTER_REQUIRED === "1" ? ATLAS_IMAGE_LIMITS : ROUTER_IMAGE_LIMITS;
14236
+ const toolImages = withoutToolImages2 || this.toolImagesGoNoMore(request2, takes) ? false : takes ?? false;
13907
14237
  return {
13908
14238
  request: { ...request2, signal, codexEffort: effort },
13909
14239
  dispose: () => clearTimeout(timer),
14240
+ carriesToolImages: toolImages !== false && sendsToolImages(request2.messages, toolImages),
13910
14241
  backend: new OpenAIResponsesBackend({
13911
14242
  apiKey: "",
13912
14243
  baseUrl: `${this.proxyUrl}/v1`,
@@ -13914,6 +14245,7 @@ var init_zrouter_stream = __esm({
13914
14245
  fetcher,
13915
14246
  preserveNativeHistory: true,
13916
14247
  reasoningFromRequestOnly: true,
14248
+ toolImages,
13917
14249
  extraBody: { provider: "openai", store: false, include: ["reasoning.encrypted_content"] }
13918
14250
  })
13919
14251
  };
@@ -13933,7 +14265,7 @@ var init_zrouter_stream = __esm({
13933
14265
  const headers = await this.buildHeaders(request2);
13934
14266
  const response = await fetch(`${this.proxyUrl}/v1/chat/turns/cancel`, {
13935
14267
  method: "POST",
13936
- headers: { ...headers, "X-Zerg-Turn-ID": request2.transportTurnId },
14268
+ headers: { ...headers, "X-Zerg-Turn-ID": resentTurns.get(request2.transportTurnId) ?? request2.transportTurnId },
13937
14269
  signal: AbortSignal.timeout(1e4)
13938
14270
  });
13939
14271
  await response.body?.cancel();
@@ -13941,7 +14273,75 @@ var init_zrouter_stream = __esm({
13941
14273
  getModelCapabilities(model) {
13942
14274
  return this.catalog?.version === 1 ? resolveRouterModel(this.catalog, this.provider, model)?.capabilities : void 0;
13943
14275
  }
13944
- buildOpenAIBody(request2) {
14276
+ /**
14277
+ * The models REQUEST may reach, as Router's route-engine.ts builds its chain: its own (PRIMARY), then its plan's
14278
+ * fallbacks unless the plan turns them off. A fallback is `provider/model` or a model of the request's provider; one
14279
+ * the catalog doesn't list is undefined.
14280
+ */
14281
+ routeModels(request2, primary) {
14282
+ const plan2 = request2.routePlan;
14283
+ if (!plan2 || plan2.allow_fallbacks === false) return [primary];
14284
+ return [primary, ...plan2.fallbacks.filter(Boolean).map((candidate) => {
14285
+ const slash = candidate.indexOf("/");
14286
+ const named = slash > 0 ? candidate.slice(0, slash) : void 0;
14287
+ return named && (resolveRouterModel(this.catalog, named, candidate) ?? resolveRouterModel(this.catalog, named, candidate.slice(slash + 1))) || resolveRouterModel(this.catalog, primary.owned_by, candidate);
14288
+ })];
14289
+ }
14290
+ /** The fallbacks REQUEST's route plan reaches, as written: none when it has no plan or turns them off. */
14291
+ planFallbacks(request2) {
14292
+ const plan2 = request2.routePlan;
14293
+ return plan2 && plan2.allow_fallbacks !== false ? plan2.fallbacks.filter(Boolean) : [];
14294
+ }
14295
+ /**
14296
+ * What toolImagesRefused knows this request's route, account, provider and model by, and its plan's fallbacks: Router
14297
+ * doesn't say which model of a plan refused, so a refusal on a plan is that plan's, not its model's alone.
14298
+ */
14299
+ toolImagesKey(request2) {
14300
+ const { route, account, provider, model } = this.gateTarget(request2);
14301
+ return JSON.stringify([route, account, provider, model, ...this.planFallbacks(request2)]);
14302
+ }
14303
+ /**
14304
+ * Whether Router refused REQUEST, which carried tool images, for something they can cause (toolImageRefusal): then
14305
+ * the caller sends it once more without them, and until ZTC restarts its route, account, provider and model get no
14306
+ * tool images, which is said once.
14307
+ */
14308
+ refusedForToolImages(request2, error62) {
14309
+ const reason = toolImageRefusal(error62);
14310
+ if (reason === void 0) return false;
14311
+ const key = this.toolImagesKey(request2);
14312
+ if (!toolImagesRefused.has(key)) {
14313
+ toolImagesRefused.set(key, reason);
14314
+ runtimeDiag("warn", `[ztc] ${this.toolImagesNotice(request2, reason)}`);
14315
+ }
14316
+ this.tellToolImagesRefused(request2, key);
14317
+ return true;
14318
+ }
14319
+ /** What the person is told when Router refused REQUEST's route its tool images, for REASON. */
14320
+ toolImagesNotice(request2, reason) {
14321
+ return `Zerg Router refused a request to ${this.provider}/${request2.model} that carried tool images (${reason}), so ZTC sent it again without them. Until ZTC restarts, that model gets a tool's image as [image]${this.planFallbacks(request2).length ? " on that route plan" : ""}.`;
14322
+ }
14323
+ /** Tell REQUEST's transcript, once, that Router refused its route its tool images: not only the Logs tab. */
14324
+ tellToolImagesRefused(request2, key) {
14325
+ const reason = toolImagesRefused.get(key);
14326
+ if (reason === void 0 || !request2.onNotice || toolImagesTold.has(key)) return;
14327
+ toolImagesTold.add(key);
14328
+ request2.onNotice(this.toolImagesNotice(request2, reason));
14329
+ }
14330
+ /**
14331
+ * Whether REQUEST's tool images go no more because Router refused its route them. When the request would have carried
14332
+ * one within TAKES (a refusal another request met first), its transcript is told.
14333
+ */
14334
+ toolImagesGoNoMore(request2, takes, sent) {
14335
+ const key = this.toolImagesKey(request2);
14336
+ if (!toolImagesRefused.has(key)) return false;
14337
+ if (sendsToolImages(request2.messages, takes, sent)) this.tellToolImagesRefused(request2, key);
14338
+ return true;
14339
+ }
14340
+ /**
14341
+ * The chat completions body for REQUEST, with at most SENT of the latest tool images, whether it carries one, and
14342
+ * what the route takes as one. WITHOUT_TOOL_IMAGES sends none, as a request Router refused for them goes again.
14343
+ */
14344
+ buildOpenAIBody(request2, withoutToolImages2, sent = TOOL_IMAGE_BUDGET) {
13945
14345
  if (this.catalog?.version === 1) {
13946
14346
  const descriptor2 = resolveRouterModel(this.catalog, this.provider, request2.model);
13947
14347
  if (!descriptor2?.capabilities?.chat) throw new RequestRefusedError("This model is no longer in the Router chat catalog. Refresh /model.");
@@ -13957,7 +14357,8 @@ var init_zrouter_stream = __esm({
13957
14357
  const [kind, item] = media.type === "image" ? ["images", "image"] : ["video", "video"];
13958
14358
  throw new RequestRefusedError(`${descriptor2.display_name ?? request2.model} does not take ${kind}. Choose a model that does with /model, or send the message without the ${item}.`);
13959
14359
  }
13960
- const prepared = caps.tools === false ? chatOnlyRequest(request2) : request2;
14360
+ const chatOnly = caps.tools === false;
14361
+ const prepared = chatOnly ? { ...request2, tools: [] } : request2;
13961
14362
  const outputLimit = clampCompletionTokens(request2.model, request2.maxTokens) ?? clampCompletionTokens(request2.model, caps.max_output_tokens);
13962
14363
  const openRouter = descriptor2.owned_by === "openrouter" ? this.openRouterPreferences?.() : void 0;
13963
14364
  const pinned = openRouter?.providers?.[descriptor2.id];
@@ -13971,16 +14372,22 @@ var init_zrouter_stream = __esm({
13971
14372
  ...pinned ? { provider: pinned.tag, fallbacks: pinned.fallbacks } : {},
13972
14373
  ...routerLimits(openRouter.limits, openRouter.modelLimits?.[descriptor2.id])
13973
14374
  };
13974
- return {
14375
+ const route = this.routeModels(request2, descriptor2);
14376
+ const takes = route.every((model) => model?.capabilities?.images === true) ? strictestImageLimits(route.map((model) => routerChatImageLimits(model.owned_by))) : void 0;
14377
+ const toolImages = withoutToolImages2 || this.toolImagesGoNoMore(prepared, takes, sent) ? void 0 : takes;
14378
+ const carriesToolImages = sendsToolImages(prepared.messages, toolImages, sent);
14379
+ return { carriesToolImages, toolImages, body: {
13975
14380
  provider: descriptor2.owned_by,
13976
14381
  model: `${descriptor2.id}${variant}`,
13977
14382
  ...routing && Object.keys(routing).length ? { openrouter: routing } : {},
13978
- ...request2.routePlan ? { route: request2.routePlan } : {},
14383
+ // With no plan Router takes the deck's or the workspace's stored default plan, whose fallbacks ZTC can't see:
14384
+ // a request carrying tool images says it has none, so they reach its model alone.
14385
+ ...request2.routePlan ? { route: request2.routePlan } : carriesToolImages ? { route: { allow_fallbacks: false } } : {},
13979
14386
  ...outputLimit === void 0 ? {} : { max_output_tokens: outputLimit },
13980
14387
  ...caps.reasoning && request2.codexEffort ? { reasoning_effort: request2.codexEffort } : {},
13981
- messages: buildOpenAIMessages(prepared),
14388
+ messages: buildOpenAIMessages(prepared, { flattenToolHistory: chatOnly, toolImages, sent }),
13982
14389
  ...prepared.tools.length ? { tools: buildOpenAIToolDefs(prepared.tools) } : {}
13983
- };
14390
+ } };
13984
14391
  }
13985
14392
  if (this.provider === "modal" && !/^modal\//i.test(request2.model)) {
13986
14393
  request2 = { ...request2, model: `modal/${request2.model}` };
@@ -13997,7 +14404,7 @@ var init_zrouter_stream = __esm({
13997
14404
  request2.maxTokens === void 0 ? void 0 : Math.min(request2.maxTokens, limit)
13998
14405
  );
13999
14406
  const tokenParam = effectiveMaxTokens === void 0 ? {} : useCompletionTokens ? { max_completion_tokens: effectiveMaxTokens } : { max_tokens: effectiveMaxTokens };
14000
- return {
14407
+ return { carriesToolImages: false, body: {
14001
14408
  provider: this.provider,
14002
14409
  model: request2.model,
14003
14410
  ...request2.routePlan ? { route: request2.routePlan } : {},
@@ -14005,15 +14412,19 @@ var init_zrouter_stream = __esm({
14005
14412
  ...request2.codexEffort && modelContract(this.provider, request2.model, "chat_tools")?.reasoningEfforts.includes(request2.codexEffort) ? { reasoning_effort: request2.codexEffort } : {},
14006
14413
  messages: buildOpenAIMessages(request2),
14007
14414
  ...request2.tools.length > 0 ? { tools: buildOpenAIToolDefs(request2.tools) } : {}
14008
- };
14415
+ } };
14009
14416
  }
14010
- serializeBody(request2, stream = false) {
14011
- const body = {
14012
- ...this.buildOpenAIBody(request2),
14013
- ...stream ? { stream: true } : {}
14014
- };
14015
- const serialized = JSON.stringify(body);
14016
- if (body.model === "modal/deepseek-v4.1-flash" || body.model === "fireworks/deepseek-v4p1-flash") {
14417
+ /**
14418
+ * The body as sent, and whether it carries a tool image; WITHOUT_TOOL_IMAGES as buildOpenAIBody takes it. A route
14419
+ * whose models limit the whole request (Gemini) gets only as many of the latest tool images as fit (fittedBody).
14420
+ */
14421
+ serializeBody(request2, stream, withoutToolImages2) {
14422
+ let built = this.buildOpenAIBody(request2, withoutToolImages2);
14423
+ const serialized = fittedBody(built.toolImages?.maxRequestBytes, (sent) => {
14424
+ if (sent !== TOOL_IMAGE_BUDGET) built = this.buildOpenAIBody(request2, withoutToolImages2, sent);
14425
+ return JSON.stringify({ ...built.body, ...stream ? { stream: true } : {} });
14426
+ });
14427
+ if (built.body.model === "modal/deepseek-v4.1-flash" || built.body.model === "fireworks/deepseek-v4p1-flash") {
14017
14428
  const pending2 = [JSON.parse(serialized)];
14018
14429
  let values = 1;
14019
14430
  while (pending2.length > 0) {
@@ -14027,7 +14438,7 @@ var init_zrouter_stream = __esm({
14027
14438
  }
14028
14439
  }
14029
14440
  }
14030
- return serialized;
14441
+ return { body: serialized, carriesToolImages: built.carriesToolImages };
14031
14442
  }
14032
14443
  async buildHeaders(request2) {
14033
14444
  const { token, workspaceId } = this.authTokenProvider ? { token: await this.authTokenProvider(), workspaceId: this.workspaceId } : this.signIn();
@@ -14175,18 +14586,21 @@ var init_zrouter_stream = __esm({
14175
14586
  }
14176
14587
  });
14177
14588
  }
14178
- async generateResponse(request2, fetcher) {
14589
+ /** REQUEST's answer; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
14590
+ async generateResponse(request2, fetcher, withoutToolImages2 = false) {
14179
14591
  if (this.usesNativeResponses(request2)) {
14180
- const native = await this.nativeResponses(request2, fetcher);
14592
+ const native = await this.nativeResponses(request2, fetcher, withoutToolImages2);
14181
14593
  try {
14182
14594
  return await native.backend.generate(native.request);
14183
14595
  } catch (error62) {
14184
- throw nativeRouterFailure(error62, this.refusalRequest(), this.signInTarget());
14596
+ const failure2 = nativeRouterFailure(error62, this.refusalRequest(), this.signInTarget());
14597
+ if (!native.carriesToolImages || !this.refusedForToolImages(request2, failure2)) throw failure2;
14185
14598
  } finally {
14186
14599
  native.dispose();
14187
14600
  }
14601
+ return this.generateResponse(request2, fetcher, true);
14188
14602
  }
14189
- const body = this.serializeBody(request2);
14603
+ const { body, carriesToolImages } = this.serializeBody(request2, false, withoutToolImages2);
14190
14604
  const headers = await this.buildHeaders(request2);
14191
14605
  runtimeDiag("info", `[ztc] zrouter dispatch ${JSON.stringify({
14192
14606
  endpoint: this.endpointFor(),
@@ -14202,7 +14616,7 @@ var init_zrouter_stream = __esm({
14202
14616
  });
14203
14617
  if (!response.ok) {
14204
14618
  const failure2 = await readHttpErrorBody(response, request2.signal);
14205
- throw routerFailure(response.status, failure2.body, {
14619
+ const error62 = routerFailure(response.status, failure2.body, {
14206
14620
  headers,
14207
14621
  response,
14208
14622
  bodyReadState: failure2.bodyReadState,
@@ -14210,6 +14624,8 @@ var init_zrouter_stream = __esm({
14210
14624
  ownSignIn: this.signInTarget(),
14211
14625
  provider: this.provider
14212
14626
  });
14627
+ if (carriesToolImages && this.refusedForToolImages(request2, error62)) return this.generateResponse(request2, fetcher, true);
14628
+ throw error62;
14213
14629
  }
14214
14630
  const data = await response.json();
14215
14631
  const parsed = this.parseOpenAIResponse(data);
@@ -14274,19 +14690,37 @@ var init_zrouter_stream = __esm({
14274
14690
  throw error62;
14275
14691
  }
14276
14692
  }
14277
- async *streamResponse(request2, fetcher) {
14693
+ /**
14694
+ * REQUEST as a streamed turn Router refused for its tool images goes again: a turn of its own, since Router keeps a
14695
+ * streamed turn's body under its id, which cancelling the first turn stops (cancelTurn).
14696
+ */
14697
+ resentTurn(request2) {
14698
+ if (!request2.transportTurnId) return request2;
14699
+ const turn = randomUUID4();
14700
+ resentTurns.set(request2.transportTurnId, turn);
14701
+ return { ...request2, transportTurnId: turn };
14702
+ }
14703
+ /** REQUEST's stream; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
14704
+ async *streamResponse(request2, fetcher, withoutToolImages2 = false) {
14278
14705
  if (this.usesNativeResponses(request2)) {
14279
- const native = await this.nativeResponses(request2, fetcher);
14706
+ const native = await this.nativeResponses(request2, fetcher, withoutToolImages2);
14707
+ let answered = false;
14280
14708
  try {
14281
- yield* native.backend.generateStream(native.request);
14709
+ for await (const event of native.backend.generateStream(native.request)) {
14710
+ answered ||= event.type !== "heartbeat";
14711
+ yield event;
14712
+ }
14713
+ return;
14282
14714
  } catch (error62) {
14283
- throw nativeRouterFailure(error62, this.refusalRequest(), this.signInTarget());
14715
+ const failure2 = nativeRouterFailure(error62, this.refusalRequest(), this.signInTarget());
14716
+ if (answered || !native.carriesToolImages || !this.refusedForToolImages(request2, failure2)) throw failure2;
14284
14717
  } finally {
14285
14718
  native.dispose();
14286
14719
  }
14720
+ yield* this.streamResponse(this.resentTurn(request2), fetcher, true);
14287
14721
  return;
14288
14722
  }
14289
- const body = this.serializeBody(request2, true);
14723
+ const { body, carriesToolImages } = this.serializeBody(request2, true, withoutToolImages2);
14290
14724
  const mapEvent = createZrouterEventMapper();
14291
14725
  let resumeAfter;
14292
14726
  let emittedMappedEvent = false;
@@ -14300,6 +14734,7 @@ var init_zrouter_stream = __esm({
14300
14734
  for (let attempt = 1; attempt <= policy.attempts; attempt++) {
14301
14735
  try {
14302
14736
  const headers = await this.buildHeaders(request2);
14737
+ if (request2.transportTurnId) headers["X-Zerg-Turn-ID"] = request2.transportTurnId;
14303
14738
  if (resumeAfter) headers["X-Zerg-Resume-After"] = resumeAfter;
14304
14739
  const response = await fetchWithHeadersTimeout(fetcher, this.endpointFor(), {
14305
14740
  method: "POST",
@@ -14359,6 +14794,10 @@ var init_zrouter_stream = __esm({
14359
14794
  }
14360
14795
  return;
14361
14796
  } catch (error62) {
14797
+ if (carriesToolImages && !emittedMappedEvent && this.refusedForToolImages(request2, error62)) {
14798
+ yield* this.streamResponse(this.resentTurn(request2), fetcher, true);
14799
+ return;
14800
+ }
14362
14801
  const retryable = !routerTurnEnded && !(error62 instanceof RouterRefusalError) && (error62 instanceof BackendHttpError ? resumeAfter !== void 0 && isRetryableResumeStatus(error62) : isTransportError(error62));
14363
14802
  if (request2.signal?.aborted || !retryable || !request2.transportTurnId || emittedMappedEvent && (!resumeSupported || !resumeAfter)) {
14364
14803
  throw error62;
@@ -15726,7 +16165,7 @@ function buildBubblewrapArgs(command, cwd, profile, env = process.env) {
15726
16165
  args.push("--chdir", cwd, "--", "/bin/sh", "-c", command);
15727
16166
  return args;
15728
16167
  }
15729
- function writeAudit(command, plan, options) {
16168
+ function writeAudit(command, plan2, options) {
15730
16169
  const auditDir = options.sandbox?.auditDir || join13(homedir6(), ".ztc", "sandbox", "audits");
15731
16170
  mkdirSync4(auditDir, { recursive: true, mode: 448 });
15732
16171
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -15735,14 +16174,14 @@ function writeAudit(command, plan, options) {
15735
16174
  schema_version: 1,
15736
16175
  created_at: createdAt,
15737
16176
  command,
15738
- cwd: plan.cwd,
15739
- backend: plan.backend,
15740
- enforcement: plan.enforcement,
16177
+ cwd: plan2.cwd,
16178
+ backend: plan2.backend,
16179
+ enforcement: plan2.enforcement,
15741
16180
  profile_id: options.profileId || null,
15742
- allowed_paths: allowedRoots(options.profile, plan.cwd),
15743
- denied_paths: deniedRoots(options.profile, plan.cwd),
16181
+ allowed_paths: allowedRoots(options.profile, plan2.cwd),
16182
+ denied_paths: deniedRoots(options.profile, plan2.cwd),
15744
16183
  network_hosts: options.profile?.networkHosts || null,
15745
- notes: plan.notes
16184
+ notes: plan2.notes
15746
16185
  }, null, 2), { encoding: "utf-8", mode: 384, flag: "wx" });
15747
16186
  return auditPath;
15748
16187
  }
@@ -15762,10 +16201,10 @@ function buildSandboxCommandPlan(command, cwd, options = {}) {
15762
16201
  }
15763
16202
  const backend = platformBackend({ ...options, sandbox });
15764
16203
  const requireOs = Boolean(sandbox.requireOsEnforcement || options.profile?.sandbox?.requireOsEnforcement);
15765
- let plan;
16204
+ let plan2;
15766
16205
  if (backend === "seatbelt") {
15767
16206
  if (process.platform !== "darwin" || !commandExists("sandbox-exec")) {
15768
- plan = {
16207
+ plan2 = {
15769
16208
  executable: "/bin/sh",
15770
16209
  args: ["-c", command],
15771
16210
  cwd,
@@ -15775,7 +16214,7 @@ function buildSandboxCommandPlan(command, cwd, options = {}) {
15775
16214
  };
15776
16215
  } else {
15777
16216
  const { path: profilePath, cleanup } = writeSeatbeltProfile(options.profile, cwd, options.env);
15778
- plan = {
16217
+ plan2 = {
15779
16218
  executable: "/usr/bin/sandbox-exec",
15780
16219
  args: ["-f", profilePath, "/bin/sh", "-c", command],
15781
16220
  cwd,
@@ -15787,7 +16226,7 @@ function buildSandboxCommandPlan(command, cwd, options = {}) {
15787
16226
  }
15788
16227
  } else if (backend === "bubblewrap") {
15789
16228
  if (process.platform !== "linux" || !commandExists("bwrap")) {
15790
- plan = {
16229
+ plan2 = {
15791
16230
  executable: "/bin/sh",
15792
16231
  args: ["-c", command],
15793
16232
  cwd,
@@ -15796,7 +16235,7 @@ function buildSandboxCommandPlan(command, cwd, options = {}) {
15796
16235
  notes: ["Linux bubblewrap requested but bwrap is unavailable on this host."]
15797
16236
  };
15798
16237
  } else {
15799
- plan = {
16238
+ plan2 = {
15800
16239
  executable: "bwrap",
15801
16240
  args: buildBubblewrapArgs(command, cwd, options.profile, options.env),
15802
16241
  cwd,
@@ -15806,7 +16245,7 @@ function buildSandboxCommandPlan(command, cwd, options = {}) {
15806
16245
  };
15807
16246
  }
15808
16247
  } else if (backend === "windows-job") {
15809
- plan = {
16248
+ plan2 = {
15810
16249
  executable: process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "/bin/sh",
15811
16250
  args: process.platform === "win32" ? ["/d", "/s", "/c", command] : ["-c", command],
15812
16251
  cwd,
@@ -15815,7 +16254,7 @@ function buildSandboxCommandPlan(command, cwd, options = {}) {
15815
16254
  notes: ["Windows job-object lifecycle sandbox is partial; AppContainer filesystem/network isolation is not active yet."]
15816
16255
  };
15817
16256
  } else {
15818
- plan = {
16257
+ plan2 = {
15819
16258
  executable: "/bin/sh",
15820
16259
  args: ["-c", command],
15821
16260
  cwd,
@@ -15824,16 +16263,16 @@ function buildSandboxCommandPlan(command, cwd, options = {}) {
15824
16263
  notes: ["No OS sandbox backend is available for this platform."]
15825
16264
  };
15826
16265
  }
15827
- if (plan.enforcement !== "os" && requireOs) {
15828
- throw new Error(`OS sandbox enforcement required but unavailable: ${plan.notes.join(" ")}`);
16266
+ if (plan2.enforcement !== "os" && requireOs) {
16267
+ throw new Error(`OS sandbox enforcement required but unavailable: ${plan2.notes.join(" ")}`);
15829
16268
  }
15830
16269
  try {
15831
- plan.auditPath = writeAudit(command, plan, { ...options, sandbox });
16270
+ plan2.auditPath = writeAudit(command, plan2, { ...options, sandbox });
15832
16271
  } catch (error62) {
15833
- plan.cleanup?.();
16272
+ plan2.cleanup?.();
15834
16273
  throw error62;
15835
16274
  }
15836
- return plan;
16275
+ return plan2;
15837
16276
  }
15838
16277
 
15839
16278
  // src/utils/shell.ts
@@ -15851,16 +16290,16 @@ function quote(value) {
15851
16290
  var CheckedShellCoordinator = class {
15852
16291
  constructor(value, publish2) {
15853
16292
  this.publish = publish2;
15854
- const plan = parseCheckedCommandPlan(value);
15855
- if (!plan) throw new Error("run_command: invalid checked plan");
15856
- this.plan = plan;
15857
- this.description = JSON.stringify(plan);
16293
+ const plan2 = parseCheckedCommandPlan(value);
16294
+ if (!plan2) throw new Error("run_command: invalid checked plan");
16295
+ this.plan = plan2;
16296
+ this.description = JSON.stringify(plan2);
15858
16297
  this.result = {
15859
16298
  schema_version: 1,
15860
16299
  status: "incomplete",
15861
16300
  verification: "unknown",
15862
16301
  plan_sha256: createHash8("sha256").update(this.description).digest("hex"),
15863
- steps: plan.steps.map((step) => ({
16302
+ steps: plan2.steps.map((step) => ({
15864
16303
  id: step.id,
15865
16304
  status: "unknown",
15866
16305
  stages: step.pipeline.map((stage) => ({
@@ -15870,7 +16309,7 @@ var CheckedShellCoordinator = class {
15870
16309
  }))
15871
16310
  }))
15872
16311
  };
15873
- const script = ["set +e", "set +o pipefail", ...plan.steps.flatMap((step, index) => [
16312
+ const script = ["set +e", "set +o pipefail", ...plan2.steps.flatMap((step, index) => [
15874
16313
  step.pipeline.map((stage) => `(exec -- ${[stage.executable, ...stage.args].map(quote).join(" ")}) 3>&- 4>&-`).join(" | "),
15875
16314
  'ztc_checked_codes=("${PIPESTATUS[@]}")',
15876
16315
  `printf '%s:%s\\n' '${index}' "\${ztc_checked_codes[*]}" >&3 || exit 125`,
@@ -40723,7 +41162,11 @@ var RequestEncoder = class {
40723
41162
  // block (content must be a string for the API), not as undefined —
40724
41163
  // which would crash parseImageToolResult and silently degrade the
40725
41164
  // whole message to plain text, breaking tool_use/tool_result pairing.
40726
- content: this.emittedToolResult(r.tool_use_id, presentToolResult(this.toolNames.get(r.tool_use_id) ?? "", verdict?.get(r.tool_use_id) ?? this.deps.renderForContext(r.tool_use_id) ?? r.content ?? "") + (typeof r.context_annotation === "string" ? r.context_annotation : "")),
41165
+ // The annotation (the repeat guard's note) goes in an image result's description, so the result stays an image.
41166
+ content: this.emittedToolResult(r.tool_use_id, withToolResultNote(presentToolResult(
41167
+ this.toolNames.get(r.tool_use_id) ?? "",
41168
+ verdict?.get(r.tool_use_id) ?? this.deps.renderForContext(r.tool_use_id) ?? r.content ?? ""
41169
+ ), typeof r.context_annotation === "string" ? r.context_annotation : "")),
40727
41170
  // The full copy keeps the result as the tool returned it, not as it is shown.
40728
41171
  ...typeof r.content === "string" ? { source: r.content } : {}
40729
41172
  }));
@@ -40821,40 +41264,13 @@ var RequestEncoder = class {
40821
41264
  }
40822
41265
  return blocks;
40823
41266
  }
40824
- parseToolResultForImages(result) {
40825
- const img = parseImageToolResult(result);
40826
- if (!img) return { hasImage: false, text: result };
40827
- return {
40828
- hasImage: true,
40829
- imageData: { mediaType: img.mediaType, data: img.data },
40830
- text: img.description || "Screenshot captured"
40831
- };
40832
- }
40833
41267
  buildToolResultBlocks(toolResults) {
40834
41268
  return toolResults.map((result) => {
40835
- const parsed = this.parseToolResultForImages(result.content);
40836
- if (parsed.hasImage && parsed.imageData) {
40837
- return {
40838
- type: "tool_result",
40839
- tool_use_id: result.tool_use_id,
40840
- ...result.is_error === void 0 ? {} : { is_error: result.is_error },
40841
- content: [
40842
- { type: "text", text: parsed.text },
40843
- {
40844
- type: "image",
40845
- source: {
40846
- type: "base64",
40847
- media_type: parsed.imageData.mediaType,
40848
- data: parsed.imageData.data
40849
- }
40850
- }
40851
- ]
40852
- };
40853
- }
40854
- let content2 = result.content;
41269
+ if (parseImageToolResult(result.content)) return toolResultBlock(result.tool_use_id, result.content, result.is_error);
41270
+ let content2 = toolResultText(result.content);
40855
41271
  const frozen = this.deps.frozenResultContent?.(result.tool_use_id);
40856
41272
  if (frozen !== void 0) {
40857
- content2 = frozen;
41273
+ content2 = toolResultText(frozen);
40858
41274
  } else if (!this.deps.currentTurnToolIds.has(result.tool_use_id) && !this.deps.selectorVerdict?.has(result.tool_use_id) && content2.length > STABLE_RESULT_LIMIT) {
40859
41275
  const copy = this.deps.saveFullResult?.(result.tool_use_id, result.source ?? content2) ?? null;
40860
41276
  content2 = content2.slice(0, OLD_RESULT_CAP) + `
@@ -40872,6 +41288,18 @@ var RequestEncoder = class {
40872
41288
  });
40873
41289
  }
40874
41290
  };
41291
+ function toolResultBlock(toolUseId, content2, isError) {
41292
+ const image = parseImageToolResult(content2);
41293
+ return {
41294
+ type: "tool_result",
41295
+ tool_use_id: toolUseId,
41296
+ ...isError === void 0 ? {} : { is_error: isError },
41297
+ content: image ? [
41298
+ { type: "text", text: imageResultCaption(image) },
41299
+ { type: "image", source: { type: "base64", media_type: image.mediaType, data: image.data } }
41300
+ ] : toolResultText(content2)
41301
+ };
41302
+ }
40875
41303
  function nativeHistoryContextId(system, tools) {
40876
41304
  return createHash16("sha256").update(JSON.stringify({ system, tools })).digest("hex");
40877
41305
  }
@@ -41460,6 +41888,19 @@ init_capabilities();
41460
41888
  import { createHash as createHash17 } from "node:crypto";
41461
41889
  import { readFile as readFile4 } from "node:fs/promises";
41462
41890
  init_tool_response_store();
41891
+ init_tool_result_parsing();
41892
+ function recalledImage(id, content2, meta3) {
41893
+ const image = parseImageToolResult(content2);
41894
+ if (image) {
41895
+ return JSON.stringify({
41896
+ type: "image",
41897
+ mediaType: image.mediaType,
41898
+ data: image.data,
41899
+ description: `Recalled tool result ${id}: ${image.description ?? ""}`
41900
+ });
41901
+ }
41902
+ return isImageEnvelope(content2) ? JSON.stringify({ ok: true, tool_use_id: id, ...meta3 ? { meta: meta3 } : {}, content: toolResultText(content2), complete: true }) : null;
41903
+ }
41463
41904
  var recallToolResponseTool2 = captureHelperRequirements({
41464
41905
  capabilities: ["file_read" /* FILE_READ */],
41465
41906
  definition: {
@@ -41496,6 +41937,9 @@ var recallToolResponseTool2 = captureHelperRequirements({
41496
41937
  if (maxBytes !== void 0 && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || maxBytes > 32768)) throw new RangeError("maxBytes must be an integer between 1 and 32768");
41497
41938
  if (cursor !== void 0 && (!Number.isSafeInteger(cursor) || cursor < 0)) throw new RangeError("cursor must be a nonnegative safe byte offset");
41498
41939
  const store = context.toolResponseStore;
41940
+ const stored = part === "result" && !store.getMeta(id)?.ephemeral ? await store.get(id) : null;
41941
+ const image = stored === null ? null : recalledImage(id, stored, store.getMeta(id));
41942
+ if (image !== null) return image;
41499
41943
  const chunk = part === "result" ? await store.getChunk(id, { cursor, maxBytes }) : null;
41500
41944
  if (chunk !== null) {
41501
41945
  if (chunk.complete && args.cursor === void 0 && args.max_bytes === void 0) store.markRecalled(id);
@@ -41536,6 +41980,8 @@ var recallToolResponseTool2 = captureHelperRequirements({
41536
41980
  });
41537
41981
  }
41538
41982
  const copied = file2 ? readCopyChunk(file2, cursor, maxBytes) : null;
41983
+ const copiedImage = file2 && copied && part === "result" && isImageEnvelope(readCopyChunk(file2, 0, 256)?.content ?? "") ? recalledImage(id, await readFile4(file2, "utf8")) : null;
41984
+ if (copiedImage !== null) return copiedImage;
41539
41985
  if (file2 && copied) {
41540
41986
  return JSON.stringify({ ok: true, tool_use_id: id, part, file: file2, ...copied, availability: "copy" });
41541
41987
  }
@@ -42004,13 +42450,13 @@ var quote2 = (value) => `'${value.replace(/'/g, `'"'"'`)}'`;
42004
42450
  async function runCPUWorkload(workload, context) {
42005
42451
  if (context.signal?.aborted) return { outcome: "cancelled", output: "", executionPolicyId: null };
42006
42452
  if (process.platform === "win32") return { outcome: "unknown", output: "", executionPolicyId: null };
42007
- const plan = buildSandboxCommandPlan(`exec ${quote2(process.execPath)} --input-type=module -e ${quote2(SCRIPT)}`, context.cwd, context.commandPolicy);
42008
- const executionPolicyId = cpuHash(JSON.stringify({ backend: plan.backend, enforcement: plan.enforcement, policy: context.commandPolicy ?? null }));
42453
+ const plan2 = buildSandboxCommandPlan(`exec ${quote2(process.execPath)} --input-type=module -e ${quote2(SCRIPT)}`, context.cwd, context.commandPolicy);
42454
+ const executionPolicyId = cpuHash(JSON.stringify({ backend: plan2.backend, enforcement: plan2.enforcement, policy: context.commandPolicy ?? null }));
42009
42455
  return new Promise((resolve24) => {
42010
42456
  let outcome;
42011
42457
  let output2 = "";
42012
42458
  let outputBytes = 0;
42013
- const child = spawn3(plan.executable, plan.args, { cwd: plan.cwd, env: {}, detached: true, stdio: ["pipe", "pipe", "ignore"] });
42459
+ const child = spawn3(plan2.executable, plan2.args, { cwd: plan2.cwd, env: {}, detached: true, stdio: ["pipe", "pipe", "ignore"] });
42014
42460
  const stop = (reason) => {
42015
42461
  if (outcome !== void 0) return;
42016
42462
  outcome = reason;
@@ -42233,6 +42679,8 @@ var compareBenchmarksTool = Object.freeze({
42233
42679
  });
42234
42680
 
42235
42681
  // src/agent/runtime/tool_runtime.ts
42682
+ init_tool_result_parsing();
42683
+ init_tool_result_images();
42236
42684
  function getTool(name2, tools) {
42237
42685
  return tools.find((t) => t.definition.name === name2);
42238
42686
  }
@@ -42297,8 +42745,20 @@ function buildHookText(messages) {
42297
42745
  function prependMessages(base, messages) {
42298
42746
  if (messages.length === 0) return base;
42299
42747
  const prefix3 = buildHookText(messages);
42300
- return base ? `${prefix3}
42301
- ${base}` : prefix3;
42748
+ return base ? withToolResultNote(base, "", `${prefix3}
42749
+ `) : prefix3;
42750
+ }
42751
+ var TOOL_OUTPUT_CAP = 8e4;
42752
+ function capToolText(text5) {
42753
+ if (text5.length <= TOOL_OUTPUT_CAP) return text5;
42754
+ const HEAD = Math.floor(TOOL_OUTPUT_CAP * 0.8);
42755
+ const TAIL = TOOL_OUTPUT_CAP - HEAD;
42756
+ const totalLines = text5.split("\n").length;
42757
+ return text5.slice(0, HEAD) + `
42758
+
42759
+ [output truncated: ${text5.length.toLocaleString()} chars / ~${totalLines.toLocaleString()} lines \u2014 showing first ${HEAD.toLocaleString()} and last ${TAIL.toLocaleString()} chars]
42760
+
42761
+ ` + text5.slice(-TAIL);
42302
42762
  }
42303
42763
  function normalizeChangedPath(path2, cwd) {
42304
42764
  const rel = relative6(cwd, resolve19(cwd, path2));
@@ -42719,20 +43179,13 @@ async function executeToolWithRuntime(name2, args, options) {
42719
43179
  });
42720
43180
  }
42721
43181
  if (tool?.isErrorResult?.(output2)) throw new Error(output2);
42722
- const TOOL_OUTPUT_CAP = 8e4;
42723
43182
  output2 = augmentReadResultWithIntent(name2, effectiveArgs, output2, cwd);
42724
- let resultContent = output2;
42725
- const contentTruncated2 = resultContent.length > TOOL_OUTPUT_CAP || reportsOwnTruncation(output2);
42726
- if (resultContent.length > TOOL_OUTPUT_CAP) {
42727
- const HEAD = Math.floor(TOOL_OUTPUT_CAP * 0.8);
42728
- const TAIL = TOOL_OUTPUT_CAP - HEAD;
42729
- const totalLines = resultContent.split("\n").length;
42730
- resultContent = resultContent.slice(0, HEAD) + `
42731
-
42732
- [output truncated: ${resultContent.length.toLocaleString()} chars / ~${totalLines.toLocaleString()} lines \u2014 showing first ${HEAD.toLocaleString()} and last ${TAIL.toLocaleString()} chars]
42733
-
42734
- ` + resultContent.slice(-TAIL);
42735
- }
43183
+ const image = parseImageToolResult(output2);
43184
+ const description = image?.description ?? "";
43185
+ const words = image ? capToolText(description) : "";
43186
+ let resultContent = image === null ? capToolText(output2) : image.data.length > TOOL_IMAGE_BASE64_CAP ? capToolText(`${imageResultCaption(image)}
43187
+ ${tooLargeToolImageNote(TOOL_IMAGE_BASE64_CAP)}`) : words === description ? output2 : JSON.stringify({ ...JSON.parse(output2), description: words });
43188
+ const contentTruncated2 = resultContent !== output2 || reportsOwnTruncation(output2);
42736
43189
  const changedPaths = extractChangedPaths(capabilities, output2, cwd);
42737
43190
  const intentChangedPaths = hostControlPlaneWrite ? [] : maybeAutoUpdateIntents({
42738
43191
  cwd,
@@ -42745,7 +43198,7 @@ async function executeToolWithRuntime(name2, args, options) {
42745
43198
  try {
42746
43199
  await options.onLocalFileChange(allChangedPaths, cwd);
42747
43200
  } catch {
42748
- resultContent += "\nLocal workspace evidence unavailable; the file write already completed.";
43201
+ resultContent = withToolResultNote(resultContent, "\nLocal workspace evidence unavailable; the file write already completed.");
42749
43202
  }
42750
43203
  }
42751
43204
  if (options.hooks) {
@@ -42915,6 +43368,7 @@ init_token_usage();
42915
43368
  init_compaction();
42916
43369
  init_router_required();
42917
43370
  init_completion_state();
43371
+ init_tool_result_parsing();
42918
43372
  function resolvePromptPrefixId(messages) {
42919
43373
  const head = messages.find((message) => message.role !== "system" && message.role !== "tool");
42920
43374
  return head?.metadata?.compactionSummary === true ? head.id : void 0;
@@ -44149,9 +44603,10 @@ ${currentCoverage.length - rows.length} additional applicability checks omitted.
44149
44603
  timestamp: message.timestamp,
44150
44604
  metadata: { synthetic: true, hostContext: true }
44151
44605
  }] : [], ...typeof observations === "string" ? [{
44606
+ // A block an older ZTC stamped can hold the start of an image result's base64: it goes as that result's text.
44152
44607
  id: `${message.id}_evidence`,
44153
44608
  role: "user",
44154
- content: observations,
44609
+ content: evidenceContextForRequest(observations),
44155
44610
  timestamp: message.timestamp,
44156
44611
  metadata: { synthetic: true, hostContext: true }
44157
44612
  }] : [], ...typeof applicability === "string" ? [{
@@ -46022,6 +46477,8 @@ ${this.runtimeContext}` : this.config.systemPrompt;
46022
46477
  onActivity: () => {
46023
46478
  if (providerAttemptActive && !signal?.aborted && !attemptController.signal.aborted) touchActivity();
46024
46479
  },
46480
+ // The transcript shows it once; the model never gets it.
46481
+ onNotice: (message) => this.emit({ type: "notice", message }),
46025
46482
  // A backend reconnect is a sign of life too: the Router is still holding
46026
46483
  // the turn, so the inactivity guard must not fire during the backoff.
46027
46484
  onTransportRetry: (info) => {
@@ -46947,7 +47404,7 @@ var invokeSkillTool = makeInvokeSkillTool(resolveAmbientSkills);
46947
47404
  // src/zlm.ts
46948
47405
  var ZLM_EMBED_API_VERSION = "zerglang.ztc-embed/1";
46949
47406
  var ZLM_STDIO_PROTOCOL = "zerglang.ztc-host/1";
46950
- var ZLM_ZTC_VERSION = true ? "0.24.0-beta.1" : "development";
47407
+ var ZLM_ZTC_VERSION = true ? "0.25.0-beta.1" : "development";
46951
47408
  var ZLM_MAX_HOST_TOOLS = 64;
46952
47409
  var ZLM_MAX_SYSTEM_PROMPT_BYTES = 128 * 1024;
46953
47410
  var ZLM_HOST_APPROVAL_CAPABILITIES = Object.freeze([