@zergai/ztc 0.24.1-dev.202611171004 → 0.25.1-dev.202611191430

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 +2 -2
package/README.md CHANGED
@@ -430,6 +430,35 @@ for Status recovery, resume refusals, receipt handling, and verification limits.
430
430
  Other terminals, tmux, ZTC child panes and ZTC Desktop show a 24-bit
431
431
  half-block preview.
432
432
  `ZTC_IMAGE_PROTOCOL=kitty` or `=blocks` overrides the detection.
433
+ - **Images tools return reach the model** — Anthropic, Bedrock, the ZergAI
434
+ platform and the Responses API carry a tool's image in its result. A Zerg
435
+ Router model whose model list says it takes images, and Gemini, get it right
436
+ after that turn's tool results, named by the tool call; any other model reads
437
+ `[image]` there. A request carries only the latest 3 tool images, whatever
438
+ their size, in PNG, JPEG, WebP or (except on Gemini) GIF: one of them over 8 MB
439
+ of base64, or over what its provider takes, becomes a note, and older ones
440
+ cost their tool turn one short line between them. A request's images, pasted
441
+ ones included, stay within what its provider takes: Anthropic and Bedrock 20
442
+ images of 5 MB of base64 each; a Router chat model 8 images, 10 MB each and 40
443
+ MB in all, and less when its provider takes less (Anthropic 5 MB an image);
444
+ Gemini, through Router or directly, a request of 20 MB in all, its text
445
+ included: the oldest of the latest tool images give way to what fits. A
446
+ request with a Router route plan carries them only when every model the route
447
+ may reach takes images, within the tightest of their limits; one with no plan
448
+ that carries them tells Router it has no fallbacks, so the stored default
449
+ plan can't pass them on. Router's Atlas service, behind
450
+ `ZTC_ROUTER_REQUIRED=1`, takes at most 2 MB an image, 8 images and 8 MB a
451
+ request, so there the oldest of those images gives way until the request
452
+ fits. If Router refuses a request for what its tool images can cause (a
453
+ spending limit that needs a cost Router can't bound for an image, a token
454
+ limit or quota, too many or too large media), ZTC sends it again without
455
+ them, says so once in the transcript (a line no model, recap or summary
456
+ reads), and that model reads `[image]` until ZTC restarts. A tool's image
457
+ never reaches a model as text: an image result's image is never cut, only its
458
+ words, as any tool's text is, and wherever a model reads a result as text (a
459
+ delegated worker, the evidence block, a compaction's summary or handoff, the
460
+ post-turn recap, a fresh Codex thread, a session an older ZTC saved) an image
461
+ reads as its text and `[image]`.
433
462
 
434
463
  ---
435
464
 
Binary file
Binary file
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/zterm-darwin-arm64
3
- size: 34042768 bytes
4
- sha256: 186fc0e33e5bf0d35a40c9126561084293fcdef7f07ab37077ae241f7fddb2c9
3
+ size: 34075648 bytes
4
+ sha256: 006bc863a7ff67186b3e0c702abc11898840faf0cdb2342e0a69b1c771aa374b
package/dist/App.js CHANGED
@@ -2047,6 +2047,10 @@ export const App = () => {
2047
2047
  : [...prev, { role: 'system', content, metadata: { apiRetry: true }, id: generateId(), timestamp: new Date() }];
2048
2048
  });
2049
2049
  break;
2050
+ case 'notice':
2051
+ // Display-only: the agent sends the model no system line, and a local-only one no recap or summary reads.
2052
+ addMessage({ role: 'system', content: event.message, metadata: { localOnly: true } });
2053
+ break;
2050
2054
  case 'error':
2051
2055
  setAgentState({ status: 'error', error: event.error });
2052
2056
  break;
@@ -34,7 +34,7 @@ import { getRequestToolDefinitions } from './tools/deferred.js';
34
34
  import { isToolResultMessage } from '../utils/tool_result_message.js';
35
35
  import { getLatestTodos } from './tools/todo.js';
36
36
  import { ToolResponseStore, ToolResponseIntegrityError, describeOffloadPlaceholderFormat } from './tool_response_store.js';
37
- import { formatEvidenceContext } from './runtime/evidence.js';
37
+ import { evidenceContextForRequest, formatEvidenceContext } from './runtime/evidence.js';
38
38
  import { captureNativeReport, NativeObservationLimitError } from './runtime/provider_native_evidence.js';
39
39
  import { projectCurrentVerification } from './runtime/source_verification.js';
40
40
  import { sessionEvidenceTool } from './tools/session_evidence.js';
@@ -1158,7 +1158,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1158
1158
  id: `${message.id}_execution`, role: 'user', content: facts, timestamp: message.timestamp,
1159
1159
  metadata: { synthetic: true, hostContext: true },
1160
1160
  }] : []), ...(typeof observations === 'string' ? [{
1161
- id: `${message.id}_evidence`, role: 'user', content: observations, timestamp: message.timestamp,
1161
+ // A block an older ZTC stamped can hold the start of an image result's base64: it goes as that result's text.
1162
+ id: `${message.id}_evidence`, role: 'user', content: evidenceContextForRequest(observations), timestamp: message.timestamp,
1162
1163
  metadata: { synthetic: true, hostContext: true },
1163
1164
  }] : []), ...(typeof applicability === 'string' ? [{
1164
1165
  id: `${message.id}_verification`, role: 'user', content: applicability, timestamp: message.timestamp,
@@ -3090,6 +3091,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3090
3091
  if (providerAttemptActive && !signal?.aborted && !attemptController.signal.aborted)
3091
3092
  touchActivity();
3092
3093
  },
3094
+ // The transcript shows it once; the model never gets it.
3095
+ onNotice: message => this.emit({ type: 'notice', message }),
3093
3096
  // A backend reconnect is a sign of life too: the Router is still holding
3094
3097
  // the turn, so the inactivity guard must not fire during the backoff.
3095
3098
  onTransportRetry: (info) => {
@@ -3,6 +3,7 @@ import { modelContract } from '@zerg/model-contracts';
3
3
  import { parseSSEStream } from './sse.js';
4
4
  import { readBoundedProviderError } from './openai_responses.js';
5
5
  import { CLAUDE_CODE_TOKEN_NOT_SENT, isClaudeCodeToken } from '../../config/retired_routes.js';
6
+ import { ANTHROPIC_IMAGE_LIMITS, planToolImages, withToolImagesInResults } from './tool_result_images.js';
6
7
  /**
7
8
  * A credential this backend may send, or undefined for a Claude Code sign-in
8
9
  * token: Anthropic reserves subscription sign-in for Claude Code itself, so
@@ -121,7 +122,9 @@ export class AnthropicBackend {
121
122
  buildBody(request) {
122
123
  const cc = this.cacheControl;
123
124
  const hasSystem = typeof request.system === 'string' && request.system.length > 0;
124
- const messages = request.messages.map(message => ({
125
+ // A tool's images go in its tool_result, the latest few within Anthropic's limits (tool_result_images.ts).
126
+ const sent = withToolImagesInResults(request.messages, planToolImages(request.messages, ANTHROPIC_IMAGE_LIMITS));
127
+ const messages = sent.map(message => ({
125
128
  role: message.role,
126
129
  content: typeof message.content === 'string'
127
130
  ? message.content
@@ -1,4 +1,5 @@
1
1
  import { IncompleteStreamError } from './transport_errors.js';
2
+ import { BEDROCK_IMAGE_LIMITS, planToolImages, withToolImagesInResults } from './tool_result_images.js';
2
3
  let bedrockSdk;
3
4
  // Loaded on first use: the backend registry is in every runtime's module
4
5
  // closure, including the headless package, which does not ship the AWS SDK.
@@ -69,7 +70,9 @@ function buildInput(request) {
69
70
  throw new Error('Bedrock model is not configured');
70
71
  return {
71
72
  modelId: request.model,
72
- messages: request.messages.map(message => ({ role: message.role, content: requestContent(message.content) })),
73
+ // A tool's images go in its toolResult, the latest few within Bedrock's limits (tool_result_images.ts).
74
+ messages: withToolImagesInResults(request.messages, planToolImages(request.messages, BEDROCK_IMAGE_LIMITS))
75
+ .map(message => ({ role: message.role, content: requestContent(message.content) })),
73
76
  inferenceConfig: { maxTokens: request.maxTokens },
74
77
  ...(request.system ? { system: [{ text: request.system }] } : {}),
75
78
  ...(request.tools.length ? { toolConfig: { tools: request.tools.map(tool => ({ toolSpec: {
@@ -40,6 +40,10 @@ export function buildCodexAppServerEnv(codexHome, base = process.env) {
40
40
  return env;
41
41
  }
42
42
  /** Stable sha1 hex digest of a string — used to fingerprint reusable thread state. */
43
+ /** A tool result's parts with each image as '[image]': a fresh thread's replay is text, and base64 in it is noise. */
44
+ function withoutToolImages(content) {
45
+ return content.map(part => part.type === 'text' ? part : { type: 'text', text: '[image]' });
46
+ }
43
47
  function sha1(value) {
44
48
  return createHash('sha1').update(value).digest('hex');
45
49
  }
@@ -1243,7 +1247,7 @@ export class CodexAppServerClient {
1243
1247
  if (block.type === 'text')
1244
1248
  return block.text;
1245
1249
  if (block.type === 'tool_result')
1246
- return typeof block.content === 'string' ? block.content : JSON.stringify(block.content);
1250
+ return typeof block.content === 'string' ? block.content : JSON.stringify(withoutToolImages(block.content));
1247
1251
  if (block.type === 'tool_use')
1248
1252
  return JSON.stringify({ tool: block.name, input: block.input });
1249
1253
  return `[${block.type}]`;
@@ -1284,7 +1288,7 @@ export class CodexAppServerClient {
1284
1288
  return {
1285
1289
  type: block.type,
1286
1290
  toolUseId: block.tool_use_id,
1287
- content: block.content,
1291
+ content: typeof block.content === 'string' ? block.content : withoutToolImages(block.content),
1288
1292
  trust: 'untrusted_external_data',
1289
1293
  };
1290
1294
  }
@@ -1,13 +1,22 @@
1
1
  import { BackendRequest, BackendResponse } from './types.js';
2
2
  import { BaseBackend } from './base.js';
3
+ import { type ToolImageLimits } from './tool_result_images.js';
3
4
  interface GeminiConfig {
4
5
  apiKey: string;
5
6
  apiEndpoint?: string;
7
+ /**
8
+ * What the model takes as an image after a tool's result; false sends a tool's images as '[image]' text. Defaults to
9
+ * Gemini's limits: ZTC sends a person's image to every Gemini model as it is.
10
+ */
11
+ toolImages?: ToolImageLimits | false;
6
12
  }
7
13
  export declare class GeminiBackend extends BaseBackend {
8
14
  private apiKey;
9
15
  private apiEndpoint;
16
+ private readonly toolImages;
10
17
  constructor(config: GeminiConfig);
11
18
  generate(request: BackendRequest): Promise<BackendResponse>;
19
+ /** REQUEST's body, with at most SENT of the latest tool images. */
20
+ private buildBody;
12
21
  }
13
22
  export {};
@@ -1,57 +1,24 @@
1
1
  import { reasoningRequestParams } from '@zerg/model-contracts';
2
2
  import { BaseBackend } from './base.js';
3
+ import { fittedBody, GEMINI_IMAGE_LIMITS, olderToolImages, olderToolImagesLine, planToolImages, toolImageCaption } from './tool_result_images.js';
3
4
  export class GeminiBackend extends BaseBackend {
4
5
  apiKey;
5
6
  apiEndpoint;
7
+ toolImages;
6
8
  constructor(config) {
7
9
  super();
8
10
  this.apiKey = config.apiKey;
9
11
  this.apiEndpoint = config.apiEndpoint || 'https://generativelanguage.googleapis.com/v1beta/models';
12
+ this.toolImages = config.toolImages ?? GEMINI_IMAGE_LIMITS;
10
13
  }
11
14
  async generate(request) {
12
15
  const url = `${this.apiEndpoint}/${encodeURIComponent(request.model)}:generateContent?key=${this.apiKey}`;
13
- const mapParts = (content) => {
14
- if (typeof content === 'string') {
15
- return [{ text: content }];
16
- }
17
- return content.filter(block => block.type !== 'thinking' && block.type !== 'redacted_thinking' && block.type !== 'responses_reasoning').map(block => {
18
- if (block.type === 'text') {
19
- return { text: block.text };
20
- }
21
- if (block.type === 'tool_result') {
22
- // Gemini handles function responses differently - convert to text for now
23
- const resultText = typeof block.content === 'string'
24
- ? block.content
25
- : block.content.map(b => b.type === 'text' ? b.text : '[image]').join('\n');
26
- return { text: `Function ${block.tool_use_id} ${block.is_error ? 'error' : 'result'}: ${resultText}` };
27
- }
28
- if (block.type === 'tool_use') {
29
- // Convert tool_use to function call format for Gemini
30
- return { functionCall: { name: block.name, args: block.input } };
31
- }
32
- // Image or video block - Gemini uses inlineData for both
33
- return { inlineData: { mimeType: block.mediaType, data: block.data } };
34
- });
35
- };
36
- const body = {
37
- ...reasoningRequestParams('gemini', request.model, request.codexEffort),
38
- systemInstruction: { parts: [{ text: request.system }] },
39
- contents: request.messages.map(m => ({
40
- role: m.role === 'assistant' ? 'model' : 'user',
41
- parts: mapParts(m.content)
42
- })),
43
- tools: [{
44
- functionDeclarations: request.tools.map(t => ({
45
- name: t.name,
46
- description: t.description,
47
- parameters: t.parameters
48
- }))
49
- }]
50
- };
16
+ // Gemini limits the whole request: the oldest of the latest tool images give way until it fits (fittedBody).
17
+ const body = fittedBody((this.toolImages || undefined)?.maxRequestBytes, sent => JSON.stringify(this.buildBody(request, sent)));
51
18
  const response = await fetch(url, {
52
19
  method: 'POST',
53
20
  headers: { 'Content-Type': 'application/json' },
54
- body: JSON.stringify(body),
21
+ body,
55
22
  signal: request.signal,
56
23
  });
57
24
  if (!response.ok) {
@@ -88,4 +55,75 @@ export class GeminiBackend extends BaseBackend {
88
55
  usage: data.usageMetadata ? { inputTokens, outputTokens, totalTokens } : undefined
89
56
  };
90
57
  }
58
+ /** REQUEST's body, with at most SENT of the latest tool images. */
59
+ buildBody(request, sent) {
60
+ const images = planToolImages(request.messages, this.toolImages || undefined, sent);
61
+ // A tool result goes as text, where an image reads '[image]'; the image itself follows in caption and inlineData
62
+ // parts (see tool_result_images.ts).
63
+ const imageParts = (block) => typeof block.content === 'string' ? [] : block.content.flatMap(part => {
64
+ if (part.type !== 'image')
65
+ return [];
66
+ const sent = images(part);
67
+ // An image older than the latest the request carries: its turn's one line covers it.
68
+ if (sent.kind === 'placeholder' || sent.kind === 'older')
69
+ return [];
70
+ return [{ text: toolImageCaption(block.tool_use_id) },
71
+ sent.kind === 'image' ? { inlineData: { mimeType: sent.mediaType, data: sent.data } } : { text: sent.text }];
72
+ });
73
+ const mapParts = (content) => {
74
+ if (typeof content === 'string') {
75
+ return [{ text: content }];
76
+ }
77
+ const parts = [];
78
+ // The images of the tool results just mapped: after that turn's results, before what follows in the same turn.
79
+ let following = [];
80
+ // The turn's older images cost it one line, before the images of its first run of results.
81
+ const olderCount = olderToolImages(content, images);
82
+ let older = olderCount > 0 ? [{ text: olderToolImagesLine(olderCount) }] : [];
83
+ for (const block of content) {
84
+ if (block.type === 'thinking' || block.type === 'redacted_thinking' || block.type === 'responses_reasoning')
85
+ continue;
86
+ if (block.type === 'tool_result') {
87
+ // Gemini handles function responses differently - convert to text for now
88
+ const resultText = typeof block.content === 'string'
89
+ ? block.content
90
+ : block.content.map(b => b.type === 'text' ? b.text : '[image]').join('\n');
91
+ parts.push({ text: `Function ${block.tool_use_id} ${block.is_error ? 'error' : 'result'}: ${resultText}` });
92
+ following.push(...older, ...imageParts(block));
93
+ older = [];
94
+ continue;
95
+ }
96
+ parts.push(...following);
97
+ following = [];
98
+ if (block.type === 'text') {
99
+ parts.push({ text: block.text });
100
+ }
101
+ else if (block.type === 'tool_use') {
102
+ // Convert tool_use to function call format for Gemini
103
+ parts.push({ functionCall: { name: block.name, args: block.input } });
104
+ }
105
+ else {
106
+ // Image or video block - Gemini uses inlineData for both
107
+ parts.push({ inlineData: { mimeType: block.mediaType, data: block.data } });
108
+ }
109
+ }
110
+ parts.push(...following);
111
+ return parts;
112
+ };
113
+ return {
114
+ ...reasoningRequestParams('gemini', request.model, request.codexEffort),
115
+ systemInstruction: { parts: [{ text: request.system }] },
116
+ contents: request.messages.map(m => ({
117
+ role: m.role === 'assistant' ? 'model' : 'user',
118
+ parts: mapParts(m.content)
119
+ })),
120
+ tools: [{
121
+ functionDeclarations: request.tools.map(t => ({
122
+ name: t.name,
123
+ description: t.description,
124
+ parameters: t.parameters
125
+ }))
126
+ }]
127
+ };
128
+ }
91
129
  }
@@ -1,5 +1,17 @@
1
1
  import { BackendRequest } from './types.js';
2
2
  import { ToolDefinition } from '../../types.js';
3
+ import { type ToolImageLimits } from './tool_result_images.js';
4
+ export interface OpenAIMessageOptions {
5
+ /** What the model takes as an image, when it is known to take images. Absent, a tool's image stays '[image]'. */
6
+ toolImages?: ToolImageLimits;
7
+ /**
8
+ * A chat-only model: Router refuses tool_calls and role=tool history for it, so earlier tool calls and results go
9
+ * as readable text. Only the wire changes; the saved history keeps its tool blocks.
10
+ */
11
+ flattenToolHistory?: boolean;
12
+ /** How many of the latest tool images may go (see tool_result_images.ts): by default, all the budget allows. */
13
+ sent?: number;
14
+ }
3
15
  /**
4
16
  * Convert a BackendRequest into the OpenAI Chat Completions `messages` array
5
17
  * (system message first), preserving tool-calling structure.
@@ -8,7 +20,11 @@ import { ToolDefinition } from '../../types.js';
8
20
  * OpenAI expects assistant.tool_calls + separate role=tool messages. This is the
9
21
  * single source of truth shared by the direct OpenAI-compatible backend and the
10
22
  * ZRouter proxy backend so both speak proper tool semantics (not flattened text).
23
+ *
24
+ * A tool message carries only text, so a tool's image reads '[image]' in it. With `toolImages`, the images follow
25
+ * that turn's tool messages in a user message of their own, or at the start of the user message that follows (never
26
+ * two user messages in a row, which some providers refuse). Only the latest few go: see tool_result_images.ts.
11
27
  */
12
- export declare function buildOpenAIMessages(request: BackendRequest): Record<string, unknown>[];
28
+ export declare function buildOpenAIMessages(request: BackendRequest, options?: OpenAIMessageOptions): Record<string, unknown>[];
13
29
  /** Convert tool definitions to OpenAI function-tool format. */
14
30
  export declare function buildOpenAIToolDefs(tools: ToolDefinition[]): Array<Record<string, unknown>>;
@@ -1,3 +1,85 @@
1
+ import { olderToolImages, olderToolImagesLine, planToolImages, toolImageCaption } from './tool_result_images.js';
2
+ /** A tool result as text: each image in it reads '[image]'. */
3
+ function resultText(block) {
4
+ return typeof block.content === 'string'
5
+ ? block.content
6
+ : block.content.map(part => part.type === 'text' ? (part.text || '') : '[image]').join('\n');
7
+ }
8
+ /**
9
+ * The parts that follow a tool result for its images: each one named by its call, then the image or its note. An
10
+ * image older than the latest the request carries has none: its turn's one line covers it (olderImagesPart).
11
+ */
12
+ function toolImageParts(block, images) {
13
+ if (typeof block.content === 'string')
14
+ return [];
15
+ return block.content.flatMap(part => {
16
+ if (part.type !== 'image')
17
+ return [];
18
+ const sent = images(part);
19
+ if (sent.kind === 'placeholder' || sent.kind === 'older')
20
+ return [];
21
+ return [{ type: 'text', text: toolImageCaption(block.tool_use_id) }, sent.kind === 'image'
22
+ ? { type: 'image_url', image_url: { url: `data:${sent.mediaType};base64,${sent.data}` } }
23
+ : { type: 'text', text: sent.text }];
24
+ });
25
+ }
26
+ /** The one line a turn's tool results' older images cost it, if it has any. */
27
+ function olderImagesPart(blocks, images) {
28
+ const older = olderToolImages(blocks, images);
29
+ return older > 0 ? [{ type: 'text', text: olderToolImagesLine(older) }] : [];
30
+ }
31
+ function mediaPart(block) {
32
+ if (block.type === 'image')
33
+ return { type: 'image_url', image_url: { url: `data:${block.mediaType};base64,${block.data}` } };
34
+ if (block.type === 'video')
35
+ return { type: 'video_url', video_url: { url: `data:${block.mediaType};base64,${block.data}` } };
36
+ return undefined;
37
+ }
38
+ /**
39
+ * A message's content for a chat-only model: tool calls and results as text, in place, and a result's images right
40
+ * after that turn's results. Without such images it is what any plain message is: its text, or its text parts and then
41
+ * its own images.
42
+ */
43
+ function flattenedContent(blocks, images) {
44
+ // Each block's text in order, and after a run of tool results the image parts of that run.
45
+ const items = [];
46
+ const media = [];
47
+ let following = [];
48
+ // The turn's older images cost it one line, before the images of its first run of results.
49
+ let older = olderImagesPart(blocks, images);
50
+ for (const block of blocks) {
51
+ if (block.type === 'tool_result') {
52
+ items.push(`Previous tool result (${block.tool_use_id}): ${resultText(block)}`);
53
+ following.push(...older, ...toolImageParts(block, images));
54
+ older = [];
55
+ continue;
56
+ }
57
+ if (following.length > 0)
58
+ items.push(following);
59
+ following = [];
60
+ if (block.type === 'tool_use')
61
+ items.push(`Previous tool call ${block.name} (${block.id}): ${JSON.stringify(block.input)}`);
62
+ else if (block.type === 'text')
63
+ items.push(block.text);
64
+ else {
65
+ const part = mediaPart(block);
66
+ if (part)
67
+ media.push(part);
68
+ }
69
+ }
70
+ if (following.length > 0)
71
+ items.push(following);
72
+ const texts = items.filter((item) => typeof item === 'string');
73
+ if (texts.length === items.length && media.length === 0)
74
+ return texts.join('\n');
75
+ return [...items.flatMap(item => typeof item === 'string' ? [{ type: 'text', text: item }] : item), ...media];
76
+ }
77
+ /** CONTENT as content parts: a string is one text part, an empty one none. */
78
+ function contentParts(content) {
79
+ if (Array.isArray(content))
80
+ return content;
81
+ return typeof content === 'string' && content.length > 0 ? [{ type: 'text', text: content }] : [];
82
+ }
1
83
  /**
2
84
  * Convert a BackendRequest into the OpenAI Chat Completions `messages` array
3
85
  * (system message first), preserving tool-calling structure.
@@ -6,11 +88,28 @@
6
88
  * OpenAI expects assistant.tool_calls + separate role=tool messages. This is the
7
89
  * single source of truth shared by the direct OpenAI-compatible backend and the
8
90
  * ZRouter proxy backend so both speak proper tool semantics (not flattened text).
91
+ *
92
+ * A tool message carries only text, so a tool's image reads '[image]' in it. With `toolImages`, the images follow
93
+ * that turn's tool messages in a user message of their own, or at the start of the user message that follows (never
94
+ * two user messages in a row, which some providers refuse). Only the latest few go: see tool_result_images.ts.
9
95
  */
10
- export function buildOpenAIMessages(request) {
96
+ export function buildOpenAIMessages(request, options = {}) {
11
97
  const out = [
12
98
  { role: 'system', content: request.system },
13
99
  ];
100
+ const images = planToolImages(request.messages, options.toolImages, options.sent);
101
+ // The image parts of the tool results just sent, for the user message after that turn's tool messages.
102
+ let pending = [];
103
+ const push = (message) => {
104
+ if (pending.length > 0 && message.role !== 'tool') {
105
+ if (message.role === 'user')
106
+ message.content = [...pending, ...contentParts(message.content)];
107
+ else
108
+ out.push({ role: 'user', content: pending });
109
+ pending = [];
110
+ }
111
+ out.push(message);
112
+ };
14
113
  // Attach assistant reasoning_content where present (Kimi/Moonshot thinking
15
114
  // models reject prior assistant turns that omit it). Applied to ALL assistant
16
115
  // shapes so a plain assistant turn doesn't silently drop its reasoning.
@@ -21,7 +120,11 @@ export function buildOpenAIMessages(request) {
21
120
  };
22
121
  for (const msg of request.messages) {
23
122
  if (typeof msg.content === 'string') {
24
- out.push(withReasoning({ role: msg.role, content: msg.content }, msg));
123
+ push(withReasoning({ role: msg.role, content: msg.content }, msg));
124
+ continue;
125
+ }
126
+ if (options.flattenToolHistory) {
127
+ push(withReasoning({ role: msg.role, content: flattenedContent(msg.content, images) }, msg));
25
128
  continue;
26
129
  }
27
130
  const textParts = [];
@@ -36,19 +139,12 @@ export function buildOpenAIMessages(request) {
36
139
  toolUses.push({ id: block.id, name: block.name, input: block.input });
37
140
  }
38
141
  else if (block.type === 'tool_result') {
39
- toolResults.push({ tool_use_id: block.tool_use_id, content: block.content, is_error: block.is_error });
142
+ toolResults.push(block);
40
143
  }
41
- else if (block.type === 'image') {
42
- mediaParts.push({
43
- type: 'image_url',
44
- image_url: { url: `data:${block.mediaType};base64,${block.data}` },
45
- });
46
- }
47
- else if (block.type === 'video') {
48
- mediaParts.push({
49
- type: 'video_url',
50
- video_url: { url: `data:${block.mediaType};base64,${block.data}` },
51
- });
144
+ else {
145
+ const part = mediaPart(block);
146
+ if (part)
147
+ mediaParts.push(part);
52
148
  }
53
149
  }
54
150
  // Assistant message with tool_use → OpenAI tool_calls format
@@ -68,20 +164,20 @@ export function buildOpenAIMessages(request) {
68
164
  if (msg.reasoning) {
69
165
  assistantMsg.reasoning_content = msg.reasoning;
70
166
  }
71
- out.push(assistantMsg);
167
+ push(assistantMsg);
72
168
  continue;
73
169
  }
74
170
  // User message with tool_result → OpenAI role=tool messages
75
171
  if (toolResults.length > 0) {
172
+ pending.push(...olderImagesPart(msg.content, images));
76
173
  for (const tr of toolResults) {
77
- const resultText = typeof tr.content === 'string'
78
- ? tr.content
79
- : tr.content.map(b => b.type === 'text' ? (b.text || '') : '[image]').join('\n');
80
- out.push({
174
+ const text = resultText(tr);
175
+ push({
81
176
  role: 'tool',
82
177
  tool_call_id: tr.tool_use_id,
83
- content: tr.is_error && !/^error\b/i.test(resultText) ? `Error: ${resultText}` : resultText,
178
+ content: tr.is_error && !/^error\b/i.test(text) ? `Error: ${text}` : text,
84
179
  });
180
+ pending.push(...toolImageParts(tr, images));
85
181
  }
86
182
  // A tool_result merged with a later real user message: OpenAI still
87
183
  // requires the tool messages first.
@@ -89,10 +185,10 @@ export function buildOpenAIMessages(request) {
89
185
  if (mediaParts.length > 0) {
90
186
  const parts = textParts.map(t => ({ type: 'text', text: t }));
91
187
  parts.push(...mediaParts);
92
- out.push({ role: 'user', content: parts });
188
+ push({ role: 'user', content: parts });
93
189
  }
94
190
  else {
95
- out.push({ role: 'user', content: textParts.join('\n') });
191
+ push({ role: 'user', content: textParts.join('\n') });
96
192
  }
97
193
  }
98
194
  continue;
@@ -101,12 +197,14 @@ export function buildOpenAIMessages(request) {
101
197
  if (mediaParts.length > 0) {
102
198
  const parts = textParts.map(t => ({ type: 'text', text: t }));
103
199
  parts.push(...mediaParts);
104
- out.push(withReasoning({ role: msg.role, content: parts }, msg));
200
+ push(withReasoning({ role: msg.role, content: parts }, msg));
105
201
  }
106
202
  else {
107
- out.push(withReasoning({ role: msg.role, content: textParts.join('\n') }, msg));
203
+ push(withReasoning({ role: msg.role, content: textParts.join('\n') }, msg));
108
204
  }
109
205
  }
206
+ if (pending.length > 0)
207
+ out.push({ role: 'user', content: pending });
110
208
  return out;
111
209
  }
112
210
  /** Convert tool definitions to OpenAI function-tool format. */
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { BackendRequest, BackendResponse, LlmMessage, StreamEvent } from './types.js';
16
16
  import { BaseBackend } from './base.js';
17
+ import { type ToolImageLimits } from './tool_result_images.js';
17
18
  interface OpenAIResponsesConfig {
18
19
  apiKey: string;
19
20
  baseUrl?: string;
@@ -26,6 +27,11 @@ interface OpenAIResponsesConfig {
26
27
  preserveNativeHistory?: boolean;
27
28
  /** Validated host routing owns reasoning instead of ambient direct-provider overrides. */
28
29
  reasoningFromRequestOnly?: boolean;
30
+ /**
31
+ * What the model takes as an image in a tool's output; false sends a tool's images as '[image]' text. Defaults to
32
+ * OpenAI's limits: every model on the Responses API takes images.
33
+ */
34
+ toolImages?: ToolImageLimits | false;
29
35
  }
30
36
  interface ResponsesOutputText {
31
37
  type: 'output_text';
@@ -115,8 +121,11 @@ interface InputFunctionCallOutput {
115
121
  output: string | InputContentPart[];
116
122
  }
117
123
  type InputItem = InputUserMessage | InputAssistantMessage | InputFunctionCall | InputFunctionCallOutput | Record<string, unknown>;
118
- /** Convert internal LlmMessage[] into Responses API input items. */
119
- export declare function buildResponsesInput(messages: LlmMessage[]): InputItem[];
124
+ /**
125
+ * Convert internal LlmMessage[] into Responses API input items. A tool's images stay inside its function_call_output,
126
+ * only the latest SENT of a type and size TOOL_IMAGES allows (see tool_result_images.ts); false sends them as '[image]'.
127
+ */
128
+ export declare function buildResponsesInput(messages: LlmMessage[], toolImages?: ToolImageLimits | false, sent?: number): InputItem[];
120
129
  /** Parse Responses API output into internal BackendResponse. */
121
130
  export declare function parseResponsesOutput(data: {
122
131
  status?: string;
@@ -150,9 +159,12 @@ export declare class OpenAIResponsesBackend extends BaseBackend {
150
159
  private extraHeaders;
151
160
  private extraBody;
152
161
  private fetcher;
162
+ private readonly toolImages;
153
163
  constructor(config: OpenAIResponsesConfig);
154
- /** Build the Responses API request body, optionally in streaming mode. */
164
+ /** Build the Responses API request body, optionally in streaming mode, with at most SENT of the latest tool images. */
155
165
  private buildBody;
166
+ /** The request body as sent, within the largest request the provider takes (Router's Atlas service): fittedBody. */
167
+ private serializeBody;
156
168
  /** POST to /responses, throwing a descriptive error on transport / API failure. */
157
169
  private fetchResponses;
158
170
  generate(request: BackendRequest): Promise<BackendResponse>;