@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.
- package/README.md +29 -0
- package/bin/zmux-darwin-arm64 +0 -0
- package/bin/ztc-audio-darwin-arm64 +0 -0
- package/bin/ztc-capture-darwin-arm64 +0 -0
- package/bin/ztc-tui-darwin-arm64 +0 -0
- package/bin/zterm-darwin-arm64 +2 -2
- package/dist/App.js +4 -0
- package/dist/agent/agent.js +5 -2
- package/dist/agent/backends/anthropic.js +4 -1
- package/dist/agent/backends/bedrock.js +4 -1
- package/dist/agent/backends/codex_app_server.js +6 -2
- package/dist/agent/backends/gemini.d.ts +9 -0
- package/dist/agent/backends/gemini.js +77 -39
- package/dist/agent/backends/openai_format.d.ts +17 -1
- package/dist/agent/backends/openai_format.js +122 -24
- package/dist/agent/backends/openai_responses.d.ts +15 -3
- package/dist/agent/backends/openai_responses.js +32 -8
- package/dist/agent/backends/request_metrics.js +7 -6
- package/dist/agent/backends/tool_result_images.d.ts +114 -0
- package/dist/agent/backends/tool_result_images.js +201 -0
- package/dist/agent/backends/types.d.ts +5 -0
- package/dist/agent/backends/zerg-api.js +4 -2
- package/dist/agent/backends/zrouter_stream.d.ts +47 -0
- package/dist/agent/backends/zrouter_stream.js +244 -54
- package/dist/agent/request_encoder.d.ts +6 -2
- package/dist/agent/request_encoder.js +24 -34
- package/dist/agent/runtime/evidence.d.ts +6 -0
- package/dist/agent/runtime/evidence.js +23 -1
- package/dist/agent/runtime/tool_runtime.js +30 -17
- package/dist/agent/subagent.js +7 -8
- package/dist/agent/tool_response_store.js +3 -3
- package/dist/agent/tool_result_parsing.d.ts +22 -0
- package/dist/agent/tool_result_parsing.js +51 -0
- package/dist/agent/tools/recall_tool_response.js +24 -0
- package/dist/cli_ratatui.js +4 -0
- package/dist/headless.js +6 -0
- package/dist/types.d.ts +5 -0
- package/dist/utils/compaction.js +30 -4
- package/dist/zlm-embed.mjs +651 -194
- package/package.json +9 -34
|
@@ -3,6 +3,7 @@ import { isDeepStrictEqual } from 'node:util';
|
|
|
3
3
|
import { responsesReasoning } from './responses_reasoning.js';
|
|
4
4
|
import { BaseBackend } from './base.js';
|
|
5
5
|
import { parseTokenUsage } from './token_usage.js';
|
|
6
|
+
import { fittedBody, OPENAI_IMAGE_LIMITS, olderToolImages, olderToolImagesLine, planToolImages, TOOL_IMAGE_BUDGET } from './tool_result_images.js';
|
|
6
7
|
function isRecord(value) {
|
|
7
8
|
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
8
9
|
}
|
|
@@ -168,9 +169,22 @@ export async function readBoundedProviderError(response) {
|
|
|
168
169
|
}
|
|
169
170
|
}
|
|
170
171
|
// ─── Exported helpers for input/output conversion ───────────────────
|
|
171
|
-
/**
|
|
172
|
-
|
|
172
|
+
/**
|
|
173
|
+
* A tool image inside function_call_output: the image, or text in its place. An image older than the latest the
|
|
174
|
+
* request carries reads '[image]', but for the turn's last one, which reads the turn's one line (LINE).
|
|
175
|
+
*/
|
|
176
|
+
function toolImageInput(sent, line) {
|
|
177
|
+
if (sent.kind === 'image')
|
|
178
|
+
return { type: 'input_image', image_url: `data:${sent.mediaType};base64,${sent.data}` };
|
|
179
|
+
return { type: 'input_text', text: sent.kind === 'note' ? sent.text : line ?? '[image]' };
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Convert internal LlmMessage[] into Responses API input items. A tool's images stay inside its function_call_output,
|
|
183
|
+
* only the latest SENT of a type and size TOOL_IMAGES allows (see tool_result_images.ts); false sends them as '[image]'.
|
|
184
|
+
*/
|
|
185
|
+
export function buildResponsesInput(messages, toolImages = OPENAI_IMAGE_LIMITS, sent = TOOL_IMAGE_BUDGET) {
|
|
173
186
|
const input = [];
|
|
187
|
+
const images = planToolImages(messages, toolImages || undefined, sent);
|
|
174
188
|
for (const msg of messages) {
|
|
175
189
|
if (msg.role === 'assistant' && msg.responseItems?.length) {
|
|
176
190
|
const items = msg.responseItems;
|
|
@@ -199,6 +213,10 @@ export function buildResponsesInput(messages) {
|
|
|
199
213
|
}
|
|
200
214
|
const userParts = [];
|
|
201
215
|
let hasImage = false;
|
|
216
|
+
// The turn's older images cost it one line, in place of the last one's '[image]'.
|
|
217
|
+
const olderCount = olderToolImages(msg.content, images);
|
|
218
|
+
const lastOlder = msg.content.flatMap(block => block.type === 'tool_result' && typeof block.content !== 'string'
|
|
219
|
+
? block.content.filter(part => part.type === 'image' && images(part).kind === 'older') : []).at(-1);
|
|
202
220
|
for (const block of msg.content) {
|
|
203
221
|
switch (block.type) {
|
|
204
222
|
case 'text':
|
|
@@ -222,10 +240,10 @@ export function buildResponsesInput(messages) {
|
|
|
222
240
|
const resultText = typeof block.content === 'string'
|
|
223
241
|
? block.content
|
|
224
242
|
: block.content.map(b => b.type === 'text' ? b.text : '[image]').join('\n');
|
|
225
|
-
const parts = Array.isArray(block.content)
|
|
243
|
+
const parts = toolImages && Array.isArray(block.content)
|
|
226
244
|
&& block.content.some(part => part.type === 'image') ? block.content.map(part => part.type === 'text'
|
|
227
245
|
? { type: 'input_text', text: block.is_error && !/^error\b/i.test(part.text) ? `Error: ${part.text}` : part.text }
|
|
228
|
-
:
|
|
246
|
+
: toolImageInput(images(part), part === lastOlder ? olderToolImagesLine(olderCount) : undefined)) : undefined;
|
|
229
247
|
input.push({
|
|
230
248
|
type: 'function_call_output',
|
|
231
249
|
call_id: block.tool_use_id,
|
|
@@ -554,6 +572,7 @@ export class OpenAIResponsesBackend extends BaseBackend {
|
|
|
554
572
|
extraHeaders;
|
|
555
573
|
extraBody;
|
|
556
574
|
fetcher;
|
|
575
|
+
toolImages;
|
|
557
576
|
constructor(config) {
|
|
558
577
|
super();
|
|
559
578
|
this.apiKey = config.apiKey;
|
|
@@ -563,10 +582,11 @@ export class OpenAIResponsesBackend extends BaseBackend {
|
|
|
563
582
|
this.fetcher = config.fetcher ?? ((...args) => fetch(...args));
|
|
564
583
|
this.preservesNativeHistory = config.preserveNativeHistory ?? false;
|
|
565
584
|
this.reasoningFromRequestOnly = config.reasoningFromRequestOnly ?? false;
|
|
585
|
+
this.toolImages = config.toolImages ?? OPENAI_IMAGE_LIMITS;
|
|
566
586
|
}
|
|
567
|
-
/** Build the Responses API request body, optionally in streaming mode. */
|
|
568
|
-
buildBody(request, stream) {
|
|
569
|
-
const input = buildResponsesInput(request.messages);
|
|
587
|
+
/** Build the Responses API request body, optionally in streaming mode, with at most SENT of the latest tool images. */
|
|
588
|
+
buildBody(request, stream, sent = TOOL_IMAGE_BUDGET) {
|
|
589
|
+
const input = buildResponsesInput(request.messages, this.toolImages, sent);
|
|
570
590
|
const tools = request.tools.map(t => ({
|
|
571
591
|
type: 'function',
|
|
572
592
|
name: t.name,
|
|
@@ -607,6 +627,10 @@ export class OpenAIResponsesBackend extends BaseBackend {
|
|
|
607
627
|
body.text = { format: request.outputFormat };
|
|
608
628
|
return body;
|
|
609
629
|
}
|
|
630
|
+
/** The request body as sent, within the largest request the provider takes (Router's Atlas service): fittedBody. */
|
|
631
|
+
serializeBody(request, stream) {
|
|
632
|
+
return fittedBody((this.toolImages || undefined)?.maxRequestBytes, sent => JSON.stringify(this.buildBody(request, stream, sent)));
|
|
633
|
+
}
|
|
610
634
|
/** POST to /responses, throwing a descriptive error on transport / API failure. */
|
|
611
635
|
async fetchResponses(request, stream) {
|
|
612
636
|
const url = `${this.baseUrl}/responses`;
|
|
@@ -619,7 +643,7 @@ export class OpenAIResponsesBackend extends BaseBackend {
|
|
|
619
643
|
Authorization: `Bearer ${this.apiKey}`,
|
|
620
644
|
...this.extraHeaders,
|
|
621
645
|
},
|
|
622
|
-
body:
|
|
646
|
+
body: this.serializeBody(request, stream),
|
|
623
647
|
signal: request.signal,
|
|
624
648
|
redirect: 'error',
|
|
625
649
|
});
|
|
@@ -20,16 +20,17 @@ class RequestMeter {
|
|
|
20
20
|
fetch = async (url, init) => {
|
|
21
21
|
const headers = new Headers(init?.headers);
|
|
22
22
|
headers.set('X-Zerg-Request-ID', this.metrics.requestId);
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
// A request that names its turn keeps it: Zerg Router's backend sends a turn Router refused again as a new one.
|
|
24
|
+
const turn = headers.get('X-Zerg-Turn-ID') ?? this.request.transportTurnId;
|
|
25
|
+
let attempt;
|
|
26
|
+
if (turn) {
|
|
27
|
+
attempt = {
|
|
25
28
|
attemptId: randomUUID(),
|
|
26
29
|
...(headers.get('x-zerg-resume-after')
|
|
27
30
|
? { resumeAfter: headers.get('x-zerg-resume-after') }
|
|
28
31
|
: {}),
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
if (this.request.transportTurnId && attempt) {
|
|
32
|
-
headers.set('X-Zerg-Turn-ID', this.request.transportTurnId);
|
|
32
|
+
};
|
|
33
|
+
headers.set('X-Zerg-Turn-ID', turn);
|
|
33
34
|
headers.set('X-Zerg-Attempt-ID', attempt.attemptId);
|
|
34
35
|
this.metrics.transportAttempts?.push(attempt);
|
|
35
36
|
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What becomes of an image a tool returned, on every wire format.
|
|
3
|
+
*
|
|
4
|
+
* Chat Completions takes a tool result as text only, and so do Gemini (as ZTC sends tool results there) and a
|
|
5
|
+
* chat-only model's flattened history: there the image reads '[image]'. For a model known to take images, the image
|
|
6
|
+
* itself follows that turn's tool results, each one named by its call. The Responses API takes images inside
|
|
7
|
+
* function_call_output and keeps them there, and Anthropic, Bedrock and the ZergAI platform inside the tool result
|
|
8
|
+
* (withToolImagesInResults).
|
|
9
|
+
*
|
|
10
|
+
* Each later request resends what history holds, so a request carries only the latest TOOL_IMAGE_BUDGET images. An
|
|
11
|
+
* older one, whatever its size, costs no more than its '[image]' placeholder and one short line for its whole tool turn
|
|
12
|
+
* (olderToolImagesLine), so a long session's images don't each cost a caption and a note on every request; one of the
|
|
13
|
+
* latest larger than the provider takes becomes a note in its place; a media type the provider doesn't take keeps only
|
|
14
|
+
* its '[image]' placeholder. A provider that also limits the whole request (Router's Atlas service),
|
|
15
|
+
* or the images in it, a person's own included (Zerg Router, Gemini), gets only as many of the latest as fit.
|
|
16
|
+
*/
|
|
17
|
+
import type { LlmMessage, RequestContentBlock, ToolResultImageBlock } from './types.js';
|
|
18
|
+
/** What a provider documents as image input. */
|
|
19
|
+
export interface ToolImageLimits {
|
|
20
|
+
/** Media types it takes. */
|
|
21
|
+
readonly mediaTypes: readonly string[];
|
|
22
|
+
/** The longest base64 payload of one image it takes. ZTC's own TOOL_IMAGE_BASE64_CAP applies when lower. */
|
|
23
|
+
readonly maxBase64Chars: number;
|
|
24
|
+
/** The largest request body it takes, in bytes, when it limits the whole request: the latest images give way to it. */
|
|
25
|
+
readonly maxRequestBytes?: number;
|
|
26
|
+
/** The most images one request may carry, a person's own included: the latest tool images give way to it. */
|
|
27
|
+
readonly maxImages?: number;
|
|
28
|
+
/** The most image bytes, decoded, one request may carry, a person's own included: the latest tool images give way. */
|
|
29
|
+
readonly maxImageBytes?: number;
|
|
30
|
+
}
|
|
31
|
+
/** How many of the latest tool images one request carries. */
|
|
32
|
+
export declare const TOOL_IMAGE_BUDGET = 3;
|
|
33
|
+
/** ZTC sends no image with more base64 than this, whatever the provider takes. */
|
|
34
|
+
export declare const TOOL_IMAGE_BASE64_CAP: number;
|
|
35
|
+
export declare const OLDER_TOOL_IMAGE_NOTE = "[image omitted: older than the last 3 images]";
|
|
36
|
+
/** The one line a tool turn's COUNT older images cost it, in place of a caption and a note for each. */
|
|
37
|
+
export declare function olderToolImagesLine(count: number): string;
|
|
38
|
+
/** OpenAI Chat Completions and Responses: PNG, JPEG, WEBP and GIF, up to 50 MB of image input per request. */
|
|
39
|
+
export declare const OPENAI_IMAGE_LIMITS: ToolImageLimits;
|
|
40
|
+
/**
|
|
41
|
+
* Zerg Router, its chat completions and the Responses route a person's own sign-in takes to Sol: the same types, at
|
|
42
|
+
* most 10 MiB per image once decoded (its image-fetcher.ts).
|
|
43
|
+
*/
|
|
44
|
+
export declare const ROUTER_IMAGE_LIMITS: ToolImageLimits;
|
|
45
|
+
/**
|
|
46
|
+
* Anthropic's Messages API, whose tool_result carries a tool's images: PNG, JPEG, GIF and WebP, at most 5 MB of base64
|
|
47
|
+
* an image. In a request with more than 20 images, tool results' included, every image has a tighter size limit, and
|
|
48
|
+
* one past it refuses the request: a request carries at most 20. The ZergAI platform takes Anthropic's messages too.
|
|
49
|
+
*/
|
|
50
|
+
export declare const ANTHROPIC_IMAGE_LIMITS: ToolImageLimits;
|
|
51
|
+
/** Bedrock's Converse API: the same types, at most 3.75 MB an image (5 MB of base64) and 20 images a request. */
|
|
52
|
+
export declare const BEDROCK_IMAGE_LIMITS: ToolImageLimits;
|
|
53
|
+
/**
|
|
54
|
+
* Gemini: PNG, JPEG and WEBP, not GIF, and a request of at most 20 MB in all, its text, its system instruction and every
|
|
55
|
+
* inline image's base64 together: the latest images give way to the rest of the request.
|
|
56
|
+
*/
|
|
57
|
+
export declare const GEMINI_IMAGE_LIMITS: ToolImageLimits;
|
|
58
|
+
/**
|
|
59
|
+
* What a Zerg Router chat model takes, given UPSTREAM, the provider its catalog says serves it. Router itself takes at
|
|
60
|
+
* most 8 images a request, each at most 10 MiB and all of them at most 40 MiB once decoded, a person's own included (its
|
|
61
|
+
* image-fetcher.ts, which its Anthropic and Gemini translations apply, refusing with HTTP 413). The upstream's own limits
|
|
62
|
+
* apply too: Anthropic takes an image of at most 5 MB, and Gemini no GIF and a request of at most 20 MB, which Router's
|
|
63
|
+
* translation of the request about matches.
|
|
64
|
+
*/
|
|
65
|
+
export declare function routerChatImageLimits(upstream: string): ToolImageLimits;
|
|
66
|
+
/**
|
|
67
|
+
* Router's Atlas service, which only its service accounts (ZTC's required Router profile) reach: at most 2 MiB of data
|
|
68
|
+
* URL per image, its prefix included, 8 images in a request's input, a person's own included, and 8 MiB of request
|
|
69
|
+
* body (atlas-service-policy.ts, service-accounts.ts).
|
|
70
|
+
*/
|
|
71
|
+
export declare const ATLAS_IMAGE_LIMITS: ToolImageLimits;
|
|
72
|
+
/** What a request that may reach any of several providers takes: what each of their LIMITS takes. */
|
|
73
|
+
export declare function strictestImageLimits(limits: readonly [ToolImageLimits, ...ToolImageLimits[]]): ToolImageLimits;
|
|
74
|
+
/**
|
|
75
|
+
* One tool image in this request: the image itself, a note in its place, only its '[image]' placeholder, or an image
|
|
76
|
+
* older than the latest the request carries, which its tool turn's one line covers (olderToolImagesLine).
|
|
77
|
+
*/
|
|
78
|
+
export type ToolImage = {
|
|
79
|
+
readonly kind: 'image';
|
|
80
|
+
readonly mediaType: string;
|
|
81
|
+
readonly data: string;
|
|
82
|
+
} | {
|
|
83
|
+
readonly kind: 'note';
|
|
84
|
+
readonly text: string;
|
|
85
|
+
} | {
|
|
86
|
+
readonly kind: 'placeholder';
|
|
87
|
+
} | {
|
|
88
|
+
readonly kind: 'older';
|
|
89
|
+
};
|
|
90
|
+
/** The text that names the call an image came from, just before the image or the note in its place. */
|
|
91
|
+
export declare function toolImageCaption(toolUseId: string): string;
|
|
92
|
+
/** What a tool image with more base64 than CAP reads, in place of the image. */
|
|
93
|
+
export declare function tooLargeToolImageNote(cap: number): string;
|
|
94
|
+
/** What each image in MESSAGES' tool results becomes in this request (see plan): by default, its placeholder. */
|
|
95
|
+
export declare function planToolImages(messages: readonly LlmMessage[], limits: ToolImageLimits | undefined, sent?: number): (image: ToolResultImageBlock) => ToolImage;
|
|
96
|
+
/** How many of the images in BLOCKS' tool results are older than the latest the request carries (see plan). */
|
|
97
|
+
export declare function olderToolImages(blocks: readonly RequestContentBlock[], images: (image: ToolResultImageBlock) => ToolImage): number;
|
|
98
|
+
/**
|
|
99
|
+
* MESSAGES as a wire that carries a tool's images inside its result sends them (Anthropic, Bedrock, the ZergAI
|
|
100
|
+
* platform): an image IMAGES sends stays, and any other reads, in its place, its note, '[image]', or for the last of a
|
|
101
|
+
* turn's older images, the turn's one line (olderToolImagesLine).
|
|
102
|
+
*/
|
|
103
|
+
export declare function withToolImagesInResults(messages: readonly LlmMessage[], images: (image: ToolResultImageBlock) => ToolImage): LlmMessage[];
|
|
104
|
+
/**
|
|
105
|
+
* Whether a request with LIMITS sends any of MESSAGES' tool images as an image, not a note or its placeholder, with at
|
|
106
|
+
* most SENT of them.
|
|
107
|
+
*/
|
|
108
|
+
export declare function sendsToolImages(messages: readonly LlmMessage[], limits: ToolImageLimits | undefined, sent?: number): boolean;
|
|
109
|
+
/**
|
|
110
|
+
* A request body as sent: BUILD's with as many of the latest tool images as it may carry. Past MAX_REQUEST_BYTES (a
|
|
111
|
+
* provider that limits the whole request: Router's Atlas service, Gemini) the oldest of them give way, one at a time,
|
|
112
|
+
* until it fits or none is left: text alone that long goes as it is.
|
|
113
|
+
*/
|
|
114
|
+
export declare function fittedBody(maxRequestBytes: number | undefined, build: (sent: number) => string): string;
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** How many of the latest tool images one request carries. */
|
|
2
|
+
export const TOOL_IMAGE_BUDGET = 3;
|
|
3
|
+
/** ZTC sends no image with more base64 than this, whatever the provider takes. */
|
|
4
|
+
export const TOOL_IMAGE_BASE64_CAP = 8 * 1024 * 1024;
|
|
5
|
+
export const OLDER_TOOL_IMAGE_NOTE = `[image omitted: older than the last ${TOOL_IMAGE_BUDGET} images]`;
|
|
6
|
+
/** The one line a tool turn's COUNT older images cost it, in place of a caption and a note for each. */
|
|
7
|
+
export function olderToolImagesLine(count) {
|
|
8
|
+
return count === 1 ? OLDER_TOOL_IMAGE_NOTE : `[${count} images omitted: older than the last ${TOOL_IMAGE_BUDGET} images]`;
|
|
9
|
+
}
|
|
10
|
+
const MIB = 1024 * 1024;
|
|
11
|
+
const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
|
|
12
|
+
/** OpenAI Chat Completions and Responses: PNG, JPEG, WEBP and GIF, up to 50 MB of image input per request. */
|
|
13
|
+
export const OPENAI_IMAGE_LIMITS = { mediaTypes: IMAGE_TYPES, maxBase64Chars: 50_000_000 };
|
|
14
|
+
/**
|
|
15
|
+
* Zerg Router, its chat completions and the Responses route a person's own sign-in takes to Sol: the same types, at
|
|
16
|
+
* most 10 MiB per image once decoded (its image-fetcher.ts).
|
|
17
|
+
*/
|
|
18
|
+
export const ROUTER_IMAGE_LIMITS = { mediaTypes: IMAGE_TYPES, maxBase64Chars: Math.ceil(10 * MIB / 3) * 4 };
|
|
19
|
+
/**
|
|
20
|
+
* Anthropic's Messages API, whose tool_result carries a tool's images: PNG, JPEG, GIF and WebP, at most 5 MB of base64
|
|
21
|
+
* an image. In a request with more than 20 images, tool results' included, every image has a tighter size limit, and
|
|
22
|
+
* one past it refuses the request: a request carries at most 20. The ZergAI platform takes Anthropic's messages too.
|
|
23
|
+
*/
|
|
24
|
+
export const ANTHROPIC_IMAGE_LIMITS = { mediaTypes: IMAGE_TYPES, maxBase64Chars: 5 * MIB, maxImages: 20 };
|
|
25
|
+
/** Bedrock's Converse API: the same types, at most 3.75 MB an image (5 MB of base64) and 20 images a request. */
|
|
26
|
+
export const BEDROCK_IMAGE_LIMITS = { mediaTypes: IMAGE_TYPES, maxBase64Chars: 5 * MIB, maxImages: 20 };
|
|
27
|
+
/**
|
|
28
|
+
* Gemini: PNG, JPEG and WEBP, not GIF, and a request of at most 20 MB in all, its text, its system instruction and every
|
|
29
|
+
* inline image's base64 together: the latest images give way to the rest of the request.
|
|
30
|
+
*/
|
|
31
|
+
export const GEMINI_IMAGE_LIMITS = {
|
|
32
|
+
mediaTypes: ['image/png', 'image/jpeg', 'image/webp'], maxBase64Chars: 20_000_000, maxRequestBytes: 20_000_000,
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* What a Zerg Router chat model takes, given UPSTREAM, the provider its catalog says serves it. Router itself takes at
|
|
36
|
+
* most 8 images a request, each at most 10 MiB and all of them at most 40 MiB once decoded, a person's own included (its
|
|
37
|
+
* image-fetcher.ts, which its Anthropic and Gemini translations apply, refusing with HTTP 413). The upstream's own limits
|
|
38
|
+
* apply too: Anthropic takes an image of at most 5 MB, and Gemini no GIF and a request of at most 20 MB, which Router's
|
|
39
|
+
* translation of the request about matches.
|
|
40
|
+
*/
|
|
41
|
+
export function routerChatImageLimits(upstream) {
|
|
42
|
+
const router = { ...ROUTER_IMAGE_LIMITS, maxImages: 8, maxImageBytes: 40 * MIB };
|
|
43
|
+
if (upstream === 'anthropic')
|
|
44
|
+
return { ...router, maxBase64Chars: 5 * MIB };
|
|
45
|
+
if (upstream === 'gemini')
|
|
46
|
+
return { ...router, mediaTypes: GEMINI_IMAGE_LIMITS.mediaTypes, maxRequestBytes: GEMINI_IMAGE_LIMITS.maxRequestBytes };
|
|
47
|
+
return router;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Router's Atlas service, which only its service accounts (ZTC's required Router profile) reach: at most 2 MiB of data
|
|
51
|
+
* URL per image, its prefix included, 8 images in a request's input, a person's own included, and 8 MiB of request
|
|
52
|
+
* body (atlas-service-policy.ts, service-accounts.ts).
|
|
53
|
+
*/
|
|
54
|
+
export const ATLAS_IMAGE_LIMITS = {
|
|
55
|
+
mediaTypes: IMAGE_TYPES, maxBase64Chars: 2 * 1024 * 1024 - 'data:image/jpeg;base64,'.length, maxImages: 8, maxRequestBytes: 8 * 1024 * 1024,
|
|
56
|
+
};
|
|
57
|
+
/** The smaller of two optional limits; none when neither has one. */
|
|
58
|
+
function tighter(a, b) {
|
|
59
|
+
return a === undefined ? b : b === undefined ? a : Math.min(a, b);
|
|
60
|
+
}
|
|
61
|
+
/** What a request that may reach any of several providers takes: what each of their LIMITS takes. */
|
|
62
|
+
export function strictestImageLimits(limits) {
|
|
63
|
+
return limits.reduce((a, b) => {
|
|
64
|
+
const maxRequestBytes = tighter(a.maxRequestBytes, b.maxRequestBytes);
|
|
65
|
+
const maxImages = tighter(a.maxImages, b.maxImages);
|
|
66
|
+
const maxImageBytes = tighter(a.maxImageBytes, b.maxImageBytes);
|
|
67
|
+
return { mediaTypes: a.mediaTypes.filter(type => b.mediaTypes.includes(type)), maxBase64Chars: Math.min(a.maxBase64Chars, b.maxBase64Chars),
|
|
68
|
+
...(maxRequestBytes === undefined ? {} : { maxRequestBytes }), ...(maxImages === undefined ? {} : { maxImages }),
|
|
69
|
+
...(maxImageBytes === undefined ? {} : { maxImageBytes }) };
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
const PLACEHOLDER = { kind: 'placeholder' };
|
|
73
|
+
const OLDER = { kind: 'older' };
|
|
74
|
+
/** The text that names the call an image came from, just before the image or the note in its place. */
|
|
75
|
+
export function toolImageCaption(toolUseId) {
|
|
76
|
+
return `Image from tool call ${toolUseId}:`;
|
|
77
|
+
}
|
|
78
|
+
/** A size in MB: 8 MiB reads "8", and the Atlas limit just under 2 MiB reads "2". */
|
|
79
|
+
function megabytes(size) {
|
|
80
|
+
return String(Number((size / (1024 * 1024)).toFixed(1)));
|
|
81
|
+
}
|
|
82
|
+
/** What a tool image with more base64 than CAP reads, in place of the image. */
|
|
83
|
+
export function tooLargeToolImageNote(cap) {
|
|
84
|
+
return `[image omitted: larger than the ${megabytes(cap)} MB limit]`;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* What each image in MESSAGES' tool results becomes in this request, for those that become more than their
|
|
88
|
+
* placeholder. Without LIMITS the model isn't known to take images, and none does. With them, the latest
|
|
89
|
+
* TOOL_IMAGE_BUDGET images of a type the provider takes, whatever their size, are the request's latest: an older one is
|
|
90
|
+
* covered by its tool turn's one line, however large. Of the latest, one larger than the provider takes is a note in
|
|
91
|
+
* its place, and the rest are sent while they fit, newest first: at most SENT of them, and fewer when the whole request
|
|
92
|
+
* would be larger than LIMITS.maxRequestBytes (SENT is then fewer), or the request's images, a person's own (outside
|
|
93
|
+
* tool results) included, more or larger than LIMITS takes. Each of the latest that had no room says why.
|
|
94
|
+
*/
|
|
95
|
+
function plan(messages, limits, sent) {
|
|
96
|
+
const planned = new Map();
|
|
97
|
+
if (limits) {
|
|
98
|
+
const cap = Math.min(limits.maxBase64Chars, TOOL_IMAGE_BASE64_CAP);
|
|
99
|
+
const tooLarge = { kind: 'note', text: tooLargeToolImageNote(cap) };
|
|
100
|
+
const noRoom = { kind: 'note',
|
|
101
|
+
text: `[image omitted: the request would exceed the ${megabytes(limits.maxRequestBytes ?? 0)} MB limit]` };
|
|
102
|
+
const tooMany = { kind: 'note', text: `[image omitted: the request would carry more than ${limits.maxImages} images]` };
|
|
103
|
+
const tooHeavy = { kind: 'note',
|
|
104
|
+
text: `[image omitted: the request's images would exceed ${megabytes(limits.maxImageBytes ?? 0)} MB]` };
|
|
105
|
+
const taken = [];
|
|
106
|
+
let ownImages = 0;
|
|
107
|
+
let ownBytes = 0;
|
|
108
|
+
for (const message of messages) {
|
|
109
|
+
if (typeof message.content === 'string')
|
|
110
|
+
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')
|
|
117
|
+
continue;
|
|
118
|
+
for (const part of block.content) {
|
|
119
|
+
if (part.type === 'image' && limits.mediaTypes.includes(part.source.media_type))
|
|
120
|
+
taken.push(part);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const firstLatest = Math.max(0, taken.length - TOOL_IMAGE_BUDGET);
|
|
125
|
+
for (const part of taken.slice(0, firstLatest))
|
|
126
|
+
planned.set(part, OLDER);
|
|
127
|
+
// The newest of the latest first, while they fit; once one has no room, nor do the older ones.
|
|
128
|
+
let roomImages = (limits.maxImages ?? Infinity) - ownImages;
|
|
129
|
+
let roomBytes = (limits.maxImageBytes ?? Infinity) - ownBytes;
|
|
130
|
+
let carried = 0;
|
|
131
|
+
let blocked;
|
|
132
|
+
for (const part of taken.slice(firstLatest).reverse()) {
|
|
133
|
+
if (part.source.data.length > cap) {
|
|
134
|
+
planned.set(part, tooLarge);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
const bytes = Buffer.byteLength(part.source.data, 'base64');
|
|
138
|
+
blocked ??= carried >= sent ? noRoom : roomImages <= 0 ? tooMany : bytes > roomBytes ? tooHeavy : undefined;
|
|
139
|
+
if (blocked) {
|
|
140
|
+
planned.set(part, blocked);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
planned.set(part, { kind: 'image', mediaType: part.source.media_type, data: part.source.data });
|
|
144
|
+
carried += 1;
|
|
145
|
+
roomImages -= 1;
|
|
146
|
+
roomBytes -= bytes;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return planned;
|
|
150
|
+
}
|
|
151
|
+
/** What each image in MESSAGES' tool results becomes in this request (see plan): by default, its placeholder. */
|
|
152
|
+
export function planToolImages(messages, limits, sent = TOOL_IMAGE_BUDGET) {
|
|
153
|
+
const planned = plan(messages, limits, sent);
|
|
154
|
+
return image => planned.get(image) ?? PLACEHOLDER;
|
|
155
|
+
}
|
|
156
|
+
/** How many of the images in BLOCKS' tool results are older than the latest the request carries (see plan). */
|
|
157
|
+
export function olderToolImages(blocks, images) {
|
|
158
|
+
return blocks.reduce((count, block) => block.type !== 'tool_result' || typeof block.content === 'string' ? count
|
|
159
|
+
: count + block.content.filter(part => part.type === 'image' && images(part).kind === 'older').length, 0);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* MESSAGES as a wire that carries a tool's images inside its result sends them (Anthropic, Bedrock, the ZergAI
|
|
163
|
+
* platform): an image IMAGES sends stays, and any other reads, in its place, its note, '[image]', or for the last of a
|
|
164
|
+
* turn's older images, the turn's one line (olderToolImagesLine).
|
|
165
|
+
*/
|
|
166
|
+
export function withToolImagesInResults(messages, images) {
|
|
167
|
+
return messages.map(message => {
|
|
168
|
+
if (typeof message.content === 'string')
|
|
169
|
+
return message;
|
|
170
|
+
const older = olderToolImages(message.content, images);
|
|
171
|
+
const lastOlder = message.content.flatMap(block => block.type === 'tool_result' && typeof block.content !== 'string'
|
|
172
|
+
? block.content.filter(part => part.type === 'image' && images(part).kind === 'older') : []).at(-1);
|
|
173
|
+
return { ...message, content: message.content.map(block => block.type !== 'tool_result' || typeof block.content === 'string' ? block
|
|
174
|
+
: { ...block, content: block.content.map(part => {
|
|
175
|
+
if (part.type !== 'image')
|
|
176
|
+
return part;
|
|
177
|
+
const sent = images(part);
|
|
178
|
+
if (sent.kind === 'image')
|
|
179
|
+
return part;
|
|
180
|
+
return { type: 'text', text: sent.kind === 'note' ? sent.text : part === lastOlder ? olderToolImagesLine(older) : '[image]' };
|
|
181
|
+
}) }) };
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Whether a request with LIMITS sends any of MESSAGES' tool images as an image, not a note or its placeholder, with at
|
|
186
|
+
* most SENT of them.
|
|
187
|
+
*/
|
|
188
|
+
export function sendsToolImages(messages, limits, sent = TOOL_IMAGE_BUDGET) {
|
|
189
|
+
return [...plan(messages, limits, sent).values()].some(image => image.kind === 'image');
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* A request body as sent: BUILD's with as many of the latest tool images as it may carry. Past MAX_REQUEST_BYTES (a
|
|
193
|
+
* provider that limits the whole request: Router's Atlas service, Gemini) the oldest of them give way, one at a time,
|
|
194
|
+
* until it fits or none is left: text alone that long goes as it is.
|
|
195
|
+
*/
|
|
196
|
+
export function fittedBody(maxRequestBytes, build) {
|
|
197
|
+
let body = build(TOOL_IMAGE_BUDGET);
|
|
198
|
+
for (let sent = TOOL_IMAGE_BUDGET - 1; sent >= 0 && Buffer.byteLength(body) > (maxRequestBytes ?? Infinity); sent--)
|
|
199
|
+
body = build(sent);
|
|
200
|
+
return body;
|
|
201
|
+
}
|
|
@@ -266,6 +266,11 @@ export interface BackendRequest {
|
|
|
266
266
|
reason: string;
|
|
267
267
|
rateLimited?: boolean;
|
|
268
268
|
}) => void;
|
|
269
|
+
/**
|
|
270
|
+
* Something the person should see once in their transcript about how their requests are sent (Router refusing tool
|
|
271
|
+
* images, which go no more): display-only, never sent to the model. Optional; a backend without one says nothing.
|
|
272
|
+
*/
|
|
273
|
+
onNotice?: (message: string) => void;
|
|
269
274
|
/** Per HTTP attempt diagnostics for Router and OpenAI-compatible transports. */
|
|
270
275
|
onMetrics?: (metrics: RequestMetrics) => void;
|
|
271
276
|
/**
|
|
@@ -4,6 +4,7 @@ import { inferDefaultProvider } from '../../config/defaults.js';
|
|
|
4
4
|
import { buildKimiRequestParams } from './kimi_params.js';
|
|
5
5
|
import { parseSSEStream } from './sse.js';
|
|
6
6
|
import { createZrouterEventMapper } from './zrouter_events.js';
|
|
7
|
+
import { ANTHROPIC_IMAGE_LIMITS, planToolImages, withToolImagesInResults } from './tool_result_images.js';
|
|
7
8
|
/**
|
|
8
9
|
* Backend that routes LLM requests through the Zerg API.
|
|
9
10
|
*
|
|
@@ -30,8 +31,9 @@ export class ZergAPIBackend extends BaseBackend {
|
|
|
30
31
|
return false;
|
|
31
32
|
}
|
|
32
33
|
buildBody(request, stream) {
|
|
33
|
-
// Convert messages to API format
|
|
34
|
-
|
|
34
|
+
// Convert messages to API format. A tool's images go in its tool_result, the latest few within the limits of
|
|
35
|
+
// Anthropic's messages, which the platform takes (tool_result_images.ts).
|
|
36
|
+
const messages = withToolImagesInResults(request.messages, planToolImages(request.messages, ANTHROPIC_IMAGE_LIMITS)).map(msg => {
|
|
35
37
|
const converted = {
|
|
36
38
|
role: msg.role,
|
|
37
39
|
content: typeof msg.content === 'string'
|
|
@@ -86,6 +86,10 @@ export declare class ZRouterStreamBackend implements AgentBackend {
|
|
|
86
86
|
handlesTransportRetries(): boolean;
|
|
87
87
|
allowsRequestRetryAfterFailure(request: BackendRequest): boolean;
|
|
88
88
|
private usesNativeResponses;
|
|
89
|
+
/**
|
|
90
|
+
* The native Responses backend for REQUEST, and whether its request carries a tool image. WITHOUT_TOOL_IMAGES sends
|
|
91
|
+
* none, as a request Router refused for them goes again.
|
|
92
|
+
*/
|
|
89
93
|
private nativeResponses;
|
|
90
94
|
/**
|
|
91
95
|
* Stop the provider stream of an abandoned turn. Without it Router keeps
|
|
@@ -95,7 +99,43 @@ export declare class ZRouterStreamBackend implements AgentBackend {
|
|
|
95
99
|
*/
|
|
96
100
|
cancelTurn(request: BackendRequest): Promise<void>;
|
|
97
101
|
getModelCapabilities(model: string): RouterModelCapabilities | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* The models REQUEST may reach, as Router's route-engine.ts builds its chain: its own (PRIMARY), then its plan's
|
|
104
|
+
* fallbacks unless the plan turns them off. A fallback is `provider/model` or a model of the request's provider; one
|
|
105
|
+
* the catalog doesn't list is undefined.
|
|
106
|
+
*/
|
|
107
|
+
private routeModels;
|
|
108
|
+
/** The fallbacks REQUEST's route plan reaches, as written: none when it has no plan or turns them off. */
|
|
109
|
+
private planFallbacks;
|
|
110
|
+
/**
|
|
111
|
+
* What toolImagesRefused knows this request's route, account, provider and model by, and its plan's fallbacks: Router
|
|
112
|
+
* doesn't say which model of a plan refused, so a refusal on a plan is that plan's, not its model's alone.
|
|
113
|
+
*/
|
|
114
|
+
private toolImagesKey;
|
|
115
|
+
/**
|
|
116
|
+
* Whether Router refused REQUEST, which carried tool images, for something they can cause (toolImageRefusal): then
|
|
117
|
+
* the caller sends it once more without them, and until ZTC restarts its route, account, provider and model get no
|
|
118
|
+
* tool images, which is said once.
|
|
119
|
+
*/
|
|
120
|
+
private refusedForToolImages;
|
|
121
|
+
/** What the person is told when Router refused REQUEST's route its tool images, for REASON. */
|
|
122
|
+
private toolImagesNotice;
|
|
123
|
+
/** Tell REQUEST's transcript, once, that Router refused its route its tool images: not only the Logs tab. */
|
|
124
|
+
private tellToolImagesRefused;
|
|
125
|
+
/**
|
|
126
|
+
* Whether REQUEST's tool images go no more because Router refused its route them. When the request would have carried
|
|
127
|
+
* one within TAKES (a refusal another request met first), its transcript is told.
|
|
128
|
+
*/
|
|
129
|
+
private toolImagesGoNoMore;
|
|
130
|
+
/**
|
|
131
|
+
* The chat completions body for REQUEST, with at most SENT of the latest tool images, whether it carries one, and
|
|
132
|
+
* what the route takes as one. WITHOUT_TOOL_IMAGES sends none, as a request Router refused for them goes again.
|
|
133
|
+
*/
|
|
98
134
|
private buildOpenAIBody;
|
|
135
|
+
/**
|
|
136
|
+
* The body as sent, and whether it carries a tool image; WITHOUT_TOOL_IMAGES as buildOpenAIBody takes it. A route
|
|
137
|
+
* whose models limit the whole request (Gemini) gets only as many of the latest tool images as fit (fittedBody).
|
|
138
|
+
*/
|
|
99
139
|
private serializeBody;
|
|
100
140
|
private buildHeaders;
|
|
101
141
|
/**
|
|
@@ -125,11 +165,18 @@ export declare class ZRouterStreamBackend implements AgentBackend {
|
|
|
125
165
|
private hostPolicyTurn;
|
|
126
166
|
prepareTurn(options: BackendTurnOptions): Promise<PreparedBackendTurn | undefined>;
|
|
127
167
|
generate(request: BackendRequest): Promise<BackendResponse>;
|
|
168
|
+
/** REQUEST's answer; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
|
|
128
169
|
private generateResponse;
|
|
129
170
|
private parseOpenAIResponse;
|
|
130
171
|
generateStream(request: BackendRequest): AsyncIterable<StreamEvent>;
|
|
131
172
|
/** A stream the process gate admits; Router answering with output clears whatever held it. */
|
|
132
173
|
private gatedStream;
|
|
174
|
+
/**
|
|
175
|
+
* REQUEST as a streamed turn Router refused for its tool images goes again: a turn of its own, since Router keeps a
|
|
176
|
+
* streamed turn's body under its id, which cancelling the first turn stops (cancelTurn).
|
|
177
|
+
*/
|
|
178
|
+
private resentTurn;
|
|
179
|
+
/** REQUEST's stream; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
|
|
133
180
|
private streamResponse;
|
|
134
181
|
}
|
|
135
182
|
/**
|