@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
|
@@ -6,6 +6,7 @@ import { BackendHttpError, readHttpErrorBody, retryAfterDelayMs } from './http_e
|
|
|
6
6
|
import { RequestRefusedError } from './types.js';
|
|
7
7
|
import { parseSSEEvents } from './sse.js';
|
|
8
8
|
import { buildOpenAIMessages, buildOpenAIToolDefs } from './openai_format.js';
|
|
9
|
+
import { ATLAS_IMAGE_LIMITS, fittedBody, ROUTER_IMAGE_LIMITS, routerChatImageLimits, sendsToolImages, strictestImageLimits, TOOL_IMAGE_BUDGET } from './tool_result_images.js';
|
|
9
10
|
import { isKimiModel } from './kimi_params.js';
|
|
10
11
|
import { runtimeDiag } from '../../utils/debug_log.js';
|
|
11
12
|
import { createZrouterEventMapper } from './zrouter_events.js';
|
|
@@ -35,6 +36,58 @@ const PINNABLE_DECORATION = /^[A-Za-z0-9._:-]{1,64}$/;
|
|
|
35
36
|
function isPinnableDecoration(value) {
|
|
36
37
|
return value !== undefined && PINNABLE_DECORATION.test(value);
|
|
37
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Router's refusals a request's tool images can cause. Router can't bound an image's cost for any provider but OpenAI,
|
|
41
|
+
* so a request with one has no price, which a dollar limit refuses when the platform pays, and holds the model's whole
|
|
42
|
+
* context window, which a token limit or the monthly quota is checked against; an image's tokens can also take a priced
|
|
43
|
+
* request past a dollar limit. Too many or too large media are a 413 (see toolImageRefusal).
|
|
44
|
+
*/
|
|
45
|
+
const TOOL_IMAGE_REFUSALS = new Set(['router_usage_unpriced', 'router_usage_budget_exceeded',
|
|
46
|
+
'router_usage_token_limit_exceeded', 'personal_token_quota_exceeded']);
|
|
47
|
+
/** Why ERROR may be Router refusing the tool images its request carried, or undefined when they can't be why. */
|
|
48
|
+
function toolImageRefusal(error) {
|
|
49
|
+
if (error instanceof RouterRefusalError)
|
|
50
|
+
return TOOL_IMAGE_REFUSALS.has(error.refusal.code) ? error.refusal.code : undefined;
|
|
51
|
+
// A chat completions failure, or one the native Responses route reports as `API error (NNN): body`.
|
|
52
|
+
const native = error instanceof Error ? /^API error \((\d{3})\): ([\s\S]*)$/.exec(error.message) : null;
|
|
53
|
+
const failure = error instanceof BackendHttpError ? { status: error.status, body: error.body }
|
|
54
|
+
: native ? { status: Number(native[1]), body: native[2] } : undefined;
|
|
55
|
+
if (failure?.status === 413)
|
|
56
|
+
return 'HTTP 413';
|
|
57
|
+
// A model the route reaches takes no images, which Router knows when a catalog older than its own doesn't
|
|
58
|
+
// (model-contract.ts), or Atlas found more images than it takes. Any other 400 is the request's own and is never sent
|
|
59
|
+
// again.
|
|
60
|
+
return failure?.status === 400 && refusesImages(failure.body) ? 'HTTP 400' : undefined;
|
|
61
|
+
}
|
|
62
|
+
/** What Router says when a request's images are what a model or its Atlas service takes none of, or no more of. */
|
|
63
|
+
const IMAGE_REFUSAL_MESSAGES = new Set(['Model does not support images', 'Atlas images must be bounded inline image data']);
|
|
64
|
+
/** Whether BODY is Router refusing a request's images, in its H3 envelope or the Responses route's. */
|
|
65
|
+
function refusesImages(body) {
|
|
66
|
+
try {
|
|
67
|
+
const parsed = JSON.parse(body);
|
|
68
|
+
return IMAGE_REFUSAL_MESSAGES.has(parsed?.statusMessage) || IMAGE_REFUSAL_MESSAGES.has(parsed?.message)
|
|
69
|
+
|| IMAGE_REFUSAL_MESSAGES.has(parsed?.error?.message);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The routes, accounts, providers and models whose request with tool images Router refused for them, each with why:
|
|
77
|
+
* until ZTC restarts, their requests carry none, from any backend.
|
|
78
|
+
*/
|
|
79
|
+
const toolImagesRefused = new Map();
|
|
80
|
+
/**
|
|
81
|
+
* Those of them whose refusal a transcript has been told of. A request without a transcript (a delegated worker's, a
|
|
82
|
+
* compaction's handoff) can meet the refusal first: the first request of a transcript that then goes without its tool
|
|
83
|
+
* images tells it.
|
|
84
|
+
*/
|
|
85
|
+
const toolImagesTold = new Set();
|
|
86
|
+
/**
|
|
87
|
+
* Streamed turns Router refused for their tool images, each with the turn it went again as, which cancelling the
|
|
88
|
+
* first stops. At most one for each refused model and request in flight then, since a refused model gets no more.
|
|
89
|
+
*/
|
|
90
|
+
const resentTurns = new Map();
|
|
38
91
|
/** Catalog identity wins; legacy namespace aliases never fold opaque ID case. */
|
|
39
92
|
function sameRouterModel(catalog, provider, previous, selected) {
|
|
40
93
|
const resolved = catalog && resolveRouterModel(catalog, provider, previous);
|
|
@@ -194,7 +247,11 @@ export class ZRouterStreamBackend {
|
|
|
194
247
|
}
|
|
195
248
|
return this.provider === 'openai' && request.model === 'gpt-6.1-sol';
|
|
196
249
|
}
|
|
197
|
-
|
|
250
|
+
/**
|
|
251
|
+
* The native Responses backend for REQUEST, and whether its request carries a tool image. WITHOUT_TOOL_IMAGES sends
|
|
252
|
+
* none, as a request Router refused for them goes again.
|
|
253
|
+
*/
|
|
254
|
+
async nativeResponses(request, fetcher, withoutToolImages = false) {
|
|
198
255
|
const contract = modelContract('openai', request.model);
|
|
199
256
|
const effort = request.codexEffort ?? 'low';
|
|
200
257
|
if (process.env.ZTC_ROUTER_REQUIRED === '1' && (effort !== 'low' || request.codexFastMode)) {
|
|
@@ -215,9 +272,20 @@ export class ZRouterStreamBackend {
|
|
|
215
272
|
try {
|
|
216
273
|
const headers = await this.buildHeaders(request);
|
|
217
274
|
headers['X-Zerg-Request-Timeout-Ms'] = String(timeoutMs);
|
|
275
|
+
// A request sent again as a turn of its own names it (streamResponse).
|
|
276
|
+
if (request.transportTurnId)
|
|
277
|
+
headers['X-Zerg-Turn-ID'] = request.transportTurnId;
|
|
278
|
+
// Unless the catalog says this model takes no images, or Router refused this route's tool images: the required
|
|
279
|
+
// profile runs on Router's Atlas service, which takes images of at most 2 MiB, 8 of them and requests of at most
|
|
280
|
+
// 8 MiB; a person's own sign-in goes through Router's regular Responses route, which has Router's usual limits.
|
|
281
|
+
const takes = this.getModelCapabilities(request.model)?.images === false ? undefined
|
|
282
|
+
: process.env.ZTC_ROUTER_REQUIRED === '1' ? ATLAS_IMAGE_LIMITS : ROUTER_IMAGE_LIMITS;
|
|
283
|
+
const toolImages = withoutToolImages || this.toolImagesGoNoMore(request, takes) ? false : takes ?? false;
|
|
218
284
|
return { request: { ...request, signal, codexEffort: effort }, dispose: () => clearTimeout(timer),
|
|
285
|
+
carriesToolImages: toolImages !== false && sendsToolImages(request.messages, toolImages),
|
|
219
286
|
backend: new OpenAIResponsesBackend({ apiKey: '', baseUrl: `${this.proxyUrl}/v1`, extraHeaders: headers, fetcher,
|
|
220
|
-
preserveNativeHistory: true, reasoningFromRequestOnly: true,
|
|
287
|
+
preserveNativeHistory: true, reasoningFromRequestOnly: true, toolImages,
|
|
288
|
+
extraBody: { provider: 'openai', store: false, include: ['reasoning.encrypted_content'] } }) };
|
|
221
289
|
}
|
|
222
290
|
catch (error) {
|
|
223
291
|
clearTimeout(timer);
|
|
@@ -234,8 +302,9 @@ export class ZRouterStreamBackend {
|
|
|
234
302
|
if (!request.transportTurnId)
|
|
235
303
|
return;
|
|
236
304
|
const headers = await this.buildHeaders(request);
|
|
305
|
+
// A turn Router refused for its tool images went again as another (streamResponse): that is the one running.
|
|
237
306
|
const response = await fetch(`${this.proxyUrl}/v1/chat/turns/cancel`, {
|
|
238
|
-
method: 'POST', headers: { ...headers, 'X-Zerg-Turn-ID': request.transportTurnId },
|
|
307
|
+
method: 'POST', headers: { ...headers, 'X-Zerg-Turn-ID': resentTurns.get(request.transportTurnId) ?? request.transportTurnId },
|
|
239
308
|
signal: AbortSignal.timeout(10_000),
|
|
240
309
|
});
|
|
241
310
|
await response.body?.cancel();
|
|
@@ -244,7 +313,82 @@ export class ZRouterStreamBackend {
|
|
|
244
313
|
return this.catalog?.version === 1
|
|
245
314
|
? resolveRouterModel(this.catalog, this.provider, model)?.capabilities : undefined;
|
|
246
315
|
}
|
|
247
|
-
|
|
316
|
+
/**
|
|
317
|
+
* The models REQUEST may reach, as Router's route-engine.ts builds its chain: its own (PRIMARY), then its plan's
|
|
318
|
+
* fallbacks unless the plan turns them off. A fallback is `provider/model` or a model of the request's provider; one
|
|
319
|
+
* the catalog doesn't list is undefined.
|
|
320
|
+
*/
|
|
321
|
+
routeModels(request, primary) {
|
|
322
|
+
const plan = request.routePlan;
|
|
323
|
+
if (!plan || plan.allow_fallbacks === false)
|
|
324
|
+
return [primary];
|
|
325
|
+
return [primary, ...plan.fallbacks.filter(Boolean).map(candidate => {
|
|
326
|
+
const slash = candidate.indexOf('/');
|
|
327
|
+
const named = slash > 0 ? candidate.slice(0, slash) : undefined;
|
|
328
|
+
return (named && (resolveRouterModel(this.catalog, named, candidate) ?? resolveRouterModel(this.catalog, named, candidate.slice(slash + 1))))
|
|
329
|
+
|| resolveRouterModel(this.catalog, primary.owned_by, candidate);
|
|
330
|
+
})];
|
|
331
|
+
}
|
|
332
|
+
/** The fallbacks REQUEST's route plan reaches, as written: none when it has no plan or turns them off. */
|
|
333
|
+
planFallbacks(request) {
|
|
334
|
+
const plan = request.routePlan;
|
|
335
|
+
return plan && plan.allow_fallbacks !== false ? plan.fallbacks.filter(Boolean) : [];
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* What toolImagesRefused knows this request's route, account, provider and model by, and its plan's fallbacks: Router
|
|
339
|
+
* doesn't say which model of a plan refused, so a refusal on a plan is that plan's, not its model's alone.
|
|
340
|
+
*/
|
|
341
|
+
toolImagesKey(request) {
|
|
342
|
+
const { route, account, provider, model } = this.gateTarget(request);
|
|
343
|
+
return JSON.stringify([route, account, provider, model, ...this.planFallbacks(request)]);
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Whether Router refused REQUEST, which carried tool images, for something they can cause (toolImageRefusal): then
|
|
347
|
+
* the caller sends it once more without them, and until ZTC restarts its route, account, provider and model get no
|
|
348
|
+
* tool images, which is said once.
|
|
349
|
+
*/
|
|
350
|
+
refusedForToolImages(request, error) {
|
|
351
|
+
const reason = toolImageRefusal(error);
|
|
352
|
+
if (reason === undefined)
|
|
353
|
+
return false;
|
|
354
|
+
const key = this.toolImagesKey(request);
|
|
355
|
+
if (!toolImagesRefused.has(key)) {
|
|
356
|
+
toolImagesRefused.set(key, reason);
|
|
357
|
+
runtimeDiag('warn', `[ztc] ${this.toolImagesNotice(request, reason)}`);
|
|
358
|
+
}
|
|
359
|
+
this.tellToolImagesRefused(request, key);
|
|
360
|
+
return true;
|
|
361
|
+
}
|
|
362
|
+
/** What the person is told when Router refused REQUEST's route its tool images, for REASON. */
|
|
363
|
+
toolImagesNotice(request, reason) {
|
|
364
|
+
return `Zerg Router refused a request to ${this.provider}/${request.model} that carried tool images (${reason}), `
|
|
365
|
+
+ `so ZTC sent it again without them. Until ZTC restarts, that model gets a tool's image as [image]${this.planFallbacks(request).length ? ' on that route plan' : ''}.`;
|
|
366
|
+
}
|
|
367
|
+
/** Tell REQUEST's transcript, once, that Router refused its route its tool images: not only the Logs tab. */
|
|
368
|
+
tellToolImagesRefused(request, key) {
|
|
369
|
+
const reason = toolImagesRefused.get(key);
|
|
370
|
+
if (reason === undefined || !request.onNotice || toolImagesTold.has(key))
|
|
371
|
+
return;
|
|
372
|
+
toolImagesTold.add(key);
|
|
373
|
+
request.onNotice(this.toolImagesNotice(request, reason));
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Whether REQUEST's tool images go no more because Router refused its route them. When the request would have carried
|
|
377
|
+
* one within TAKES (a refusal another request met first), its transcript is told.
|
|
378
|
+
*/
|
|
379
|
+
toolImagesGoNoMore(request, takes, sent) {
|
|
380
|
+
const key = this.toolImagesKey(request);
|
|
381
|
+
if (!toolImagesRefused.has(key))
|
|
382
|
+
return false;
|
|
383
|
+
if (sendsToolImages(request.messages, takes, sent))
|
|
384
|
+
this.tellToolImagesRefused(request, key);
|
|
385
|
+
return true;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* The chat completions body for REQUEST, with at most SENT of the latest tool images, whether it carries one, and
|
|
389
|
+
* what the route takes as one. WITHOUT_TOOL_IMAGES sends none, as a request Router refused for them goes again.
|
|
390
|
+
*/
|
|
391
|
+
buildOpenAIBody(request, withoutToolImages, sent = TOOL_IMAGE_BUDGET) {
|
|
248
392
|
if (this.catalog?.version === 1) {
|
|
249
393
|
const descriptor = resolveRouterModel(this.catalog, this.provider, request.model);
|
|
250
394
|
if (!descriptor?.capabilities?.chat)
|
|
@@ -263,7 +407,9 @@ export class ZRouterStreamBackend {
|
|
|
263
407
|
throw new RequestRefusedError(`${descriptor.display_name ?? request.model} does not take ${kind}. `
|
|
264
408
|
+ `Choose a model that does with /model, or send the message without the ${item}.`);
|
|
265
409
|
}
|
|
266
|
-
|
|
410
|
+
// A chat-only model gets its tool history as text and no tools; the saved history keeps its tool blocks.
|
|
411
|
+
const chatOnly = caps.tools === false;
|
|
412
|
+
const prepared = chatOnly ? { ...request, tools: [] } : request;
|
|
267
413
|
const outputLimit = clampCompletionTokens(request.model, request.maxTokens)
|
|
268
414
|
?? clampCompletionTokens(request.model, caps.max_output_tokens);
|
|
269
415
|
const openRouter = descriptor.owned_by === 'openrouter' ? this.openRouterPreferences?.() : undefined;
|
|
@@ -277,14 +423,26 @@ export class ZRouterStreamBackend {
|
|
|
277
423
|
...(openRouter.dataCollection ? { data_collection: openRouter.dataCollection } : {}),
|
|
278
424
|
...(pinned ? { provider: pinned.tag, fallbacks: pinned.fallbacks } : {}),
|
|
279
425
|
...routerLimits(openRouter.limits, openRouter.modelLimits?.[descriptor.id]) };
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
426
|
+
// The catalog's images capability, which refuses a person's image above when false, sends a tool's image only
|
|
427
|
+
// when true for every model the route may reach (Router sends each fallback the same body): an unknown model
|
|
428
|
+
// keeps '[image]', so a model that takes no images is never sent one. Neither is a model Router refused a request
|
|
429
|
+
// with tool images (refusedForToolImages). Router's media rules and each upstream's own limits bound what goes.
|
|
430
|
+
const route = this.routeModels(request, descriptor);
|
|
431
|
+
const takes = route.every(model => model?.capabilities?.images === true)
|
|
432
|
+
? strictestImageLimits(route.map(model => routerChatImageLimits(model.owned_by))) : undefined;
|
|
433
|
+
const toolImages = withoutToolImages || this.toolImagesGoNoMore(prepared, takes, sent) ? undefined : takes;
|
|
434
|
+
const carriesToolImages = sendsToolImages(prepared.messages, toolImages, sent);
|
|
435
|
+
return { carriesToolImages, toolImages, body: {
|
|
436
|
+
provider: descriptor.owned_by, model: `${descriptor.id}${variant}`,
|
|
437
|
+
...(routing && Object.keys(routing).length ? { openrouter: routing } : {}),
|
|
438
|
+
// With no plan Router takes the deck's or the workspace's stored default plan, whose fallbacks ZTC can't see:
|
|
439
|
+
// a request carrying tool images says it has none, so they reach its model alone.
|
|
440
|
+
...(request.routePlan ? { route: request.routePlan } : carriesToolImages ? { route: { allow_fallbacks: false } } : {}),
|
|
441
|
+
...(outputLimit === undefined ? {} : { max_output_tokens: outputLimit }),
|
|
442
|
+
...(caps.reasoning && request.codexEffort ? { reasoning_effort: request.codexEffort } : {}),
|
|
443
|
+
messages: buildOpenAIMessages(prepared, { flattenToolHistory: chatOnly, toolImages, sent }),
|
|
444
|
+
...(prepared.tools.length ? { tools: buildOpenAIToolDefs(prepared.tools) } : {}),
|
|
445
|
+
} };
|
|
288
446
|
}
|
|
289
447
|
// Legacy contract for older Routers only. ZTC stores the model separately from its provider. Router's global model
|
|
290
448
|
// namespace is a wire concern; keep existing namespaced IDs compatible.
|
|
@@ -313,30 +471,35 @@ export class ZRouterStreamBackend {
|
|
|
313
471
|
// Proper OpenAI tool semantics (assistant.tool_calls + role=tool messages),
|
|
314
472
|
// shared with OpenAICompatibleBackend — NOT flattened to text, so multi-turn
|
|
315
473
|
// tool calling survives the proxy round-trip.
|
|
316
|
-
return {
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
474
|
+
return { carriesToolImages: false, body: {
|
|
475
|
+
provider: this.provider,
|
|
476
|
+
model: request.model,
|
|
477
|
+
...(request.routePlan ? { route: request.routePlan } : {}),
|
|
478
|
+
...tokenParam,
|
|
479
|
+
...(request.codexEffort && modelContract(this.provider, request.model, 'chat_tools')?.reasoningEfforts.includes(request.codexEffort)
|
|
480
|
+
? { reasoning_effort: request.codexEffort } : {}),
|
|
481
|
+
messages: buildOpenAIMessages(request),
|
|
482
|
+
...(request.tools.length > 0 ? { tools: buildOpenAIToolDefs(request.tools) } : {})
|
|
483
|
+
} };
|
|
326
484
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
485
|
+
/**
|
|
486
|
+
* The body as sent, and whether it carries a tool image; WITHOUT_TOOL_IMAGES as buildOpenAIBody takes it. A route
|
|
487
|
+
* whose models limit the whole request (Gemini) gets only as many of the latest tool images as fit (fittedBody).
|
|
488
|
+
*/
|
|
489
|
+
serializeBody(request, stream, withoutToolImages) {
|
|
490
|
+
let built = this.buildOpenAIBody(request, withoutToolImages);
|
|
491
|
+
const serialized = fittedBody(built.toolImages?.maxRequestBytes, sent => {
|
|
492
|
+
if (sent !== TOOL_IMAGE_BUDGET)
|
|
493
|
+
built = this.buildOpenAIBody(request, withoutToolImages, sent);
|
|
494
|
+
return JSON.stringify({ ...built.body, ...(stream ? { stream: true } : {}) });
|
|
495
|
+
});
|
|
333
496
|
// Funded DeepSeek admission scans at most 10,000 JSON values, independently
|
|
334
497
|
// of the model's token window. A longer text history is otherwise rejected
|
|
335
498
|
// as non-text trial input, and resumable streaming masks that as a 5xx.
|
|
336
499
|
// Signal context overflow locally so hosts compact and retry, including
|
|
337
500
|
// when an agent's tool loop crosses the limit before returning to idle.
|
|
338
|
-
if (body.model === 'modal/deepseek-v4.1-flash'
|
|
339
|
-
|| body.model === 'fireworks/deepseek-v4p1-flash') {
|
|
501
|
+
if (built.body.model === 'modal/deepseek-v4.1-flash'
|
|
502
|
+
|| built.body.model === 'fireworks/deepseek-v4p1-flash') {
|
|
340
503
|
// Count the serialized wire shape: undefined properties disappear, and
|
|
341
504
|
// tool calls/results expand into separate messages during encoding.
|
|
342
505
|
const pending = [JSON.parse(serialized)];
|
|
@@ -353,7 +516,7 @@ export class ZRouterStreamBackend {
|
|
|
353
516
|
}
|
|
354
517
|
}
|
|
355
518
|
}
|
|
356
|
-
return serialized;
|
|
519
|
+
return { body: serialized, carriesToolImages: built.carriesToolImages };
|
|
357
520
|
}
|
|
358
521
|
async buildHeaders(request) {
|
|
359
522
|
const { token, workspaceId } = this.authTokenProvider
|
|
@@ -498,20 +661,25 @@ export class ZRouterStreamBackend {
|
|
|
498
661
|
}
|
|
499
662
|
});
|
|
500
663
|
}
|
|
501
|
-
|
|
664
|
+
/** REQUEST's answer; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
|
|
665
|
+
async generateResponse(request, fetcher, withoutToolImages = false) {
|
|
502
666
|
if (this.usesNativeResponses(request)) {
|
|
503
|
-
const native = await this.nativeResponses(request, fetcher);
|
|
667
|
+
const native = await this.nativeResponses(request, fetcher, withoutToolImages);
|
|
504
668
|
try {
|
|
505
669
|
return await native.backend.generate(native.request);
|
|
506
670
|
}
|
|
507
671
|
catch (error) {
|
|
508
|
-
|
|
672
|
+
const failure = nativeRouterFailure(error, this.refusalRequest(), this.signInTarget());
|
|
673
|
+
// Refused for what its tool images can cause: once more without them.
|
|
674
|
+
if (!native.carriesToolImages || !this.refusedForToolImages(request, failure))
|
|
675
|
+
throw failure;
|
|
509
676
|
}
|
|
510
677
|
finally {
|
|
511
678
|
native.dispose();
|
|
512
679
|
}
|
|
680
|
+
return this.generateResponse(request, fetcher, true);
|
|
513
681
|
}
|
|
514
|
-
const body = this.serializeBody(request);
|
|
682
|
+
const { body, carriesToolImages } = this.serializeBody(request, false, withoutToolImages);
|
|
515
683
|
const headers = await this.buildHeaders(request);
|
|
516
684
|
// Proof-chain log: the exact router endpoint + model this turn dispatches to.
|
|
517
685
|
runtimeDiag('info', `[ztc] zrouter dispatch ${JSON.stringify({
|
|
@@ -528,8 +696,12 @@ export class ZRouterStreamBackend {
|
|
|
528
696
|
});
|
|
529
697
|
if (!response.ok) {
|
|
530
698
|
const failure = await readHttpErrorBody(response, request.signal);
|
|
531
|
-
|
|
699
|
+
const error = routerFailure(response.status, failure.body, { headers, response, bodyReadState: failure.bodyReadState, request: this.refusalRequest(),
|
|
532
700
|
ownSignIn: this.signInTarget(), provider: this.provider });
|
|
701
|
+
// Refused for what its tool images can cause: once more without them.
|
|
702
|
+
if (carriesToolImages && this.refusedForToolImages(request, error))
|
|
703
|
+
return this.generateResponse(request, fetcher, true);
|
|
704
|
+
throw error;
|
|
533
705
|
}
|
|
534
706
|
const data = await response.json();
|
|
535
707
|
const parsed = this.parseOpenAIResponse(data);
|
|
@@ -604,21 +776,42 @@ export class ZRouterStreamBackend {
|
|
|
604
776
|
throw error;
|
|
605
777
|
}
|
|
606
778
|
}
|
|
607
|
-
|
|
779
|
+
/**
|
|
780
|
+
* REQUEST as a streamed turn Router refused for its tool images goes again: a turn of its own, since Router keeps a
|
|
781
|
+
* streamed turn's body under its id, which cancelling the first turn stops (cancelTurn).
|
|
782
|
+
*/
|
|
783
|
+
resentTurn(request) {
|
|
784
|
+
if (!request.transportTurnId)
|
|
785
|
+
return request;
|
|
786
|
+
const turn = randomUUID();
|
|
787
|
+
resentTurns.set(request.transportTurnId, turn);
|
|
788
|
+
return { ...request, transportTurnId: turn };
|
|
789
|
+
}
|
|
790
|
+
/** REQUEST's stream; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
|
|
791
|
+
async *streamResponse(request, fetcher, withoutToolImages = false) {
|
|
608
792
|
if (this.usesNativeResponses(request)) {
|
|
609
|
-
const native = await this.nativeResponses(request, fetcher);
|
|
793
|
+
const native = await this.nativeResponses(request, fetcher, withoutToolImages);
|
|
794
|
+
let answered = false;
|
|
610
795
|
try {
|
|
611
|
-
|
|
796
|
+
for await (const event of native.backend.generateStream(native.request)) {
|
|
797
|
+
answered ||= event.type !== 'heartbeat';
|
|
798
|
+
yield event;
|
|
799
|
+
}
|
|
800
|
+
return;
|
|
612
801
|
}
|
|
613
802
|
catch (error) {
|
|
614
|
-
|
|
803
|
+
const failure = nativeRouterFailure(error, this.refusalRequest(), this.signInTarget());
|
|
804
|
+
// Refused, before any output, for what its tool images can cause: once more without them.
|
|
805
|
+
if (answered || !native.carriesToolImages || !this.refusedForToolImages(request, failure))
|
|
806
|
+
throw failure;
|
|
615
807
|
}
|
|
616
808
|
finally {
|
|
617
809
|
native.dispose();
|
|
618
810
|
}
|
|
811
|
+
yield* this.streamResponse(this.resentTurn(request), fetcher, true);
|
|
619
812
|
return;
|
|
620
813
|
}
|
|
621
|
-
const body = this.serializeBody(request, true);
|
|
814
|
+
const { body, carriesToolImages } = this.serializeBody(request, true, withoutToolImages);
|
|
622
815
|
const mapEvent = createZrouterEventMapper();
|
|
623
816
|
let resumeAfter;
|
|
624
817
|
let emittedMappedEvent = false;
|
|
@@ -634,6 +827,9 @@ export class ZRouterStreamBackend {
|
|
|
634
827
|
for (let attempt = 1; attempt <= policy.attempts; attempt++) {
|
|
635
828
|
try {
|
|
636
829
|
const headers = await this.buildHeaders(request);
|
|
830
|
+
// The turn this request is, which the request meter stamps on it: a new one when it goes again (below).
|
|
831
|
+
if (request.transportTurnId)
|
|
832
|
+
headers['X-Zerg-Turn-ID'] = request.transportTurnId;
|
|
637
833
|
if (resumeAfter)
|
|
638
834
|
headers['X-Zerg-Resume-After'] = resumeAfter;
|
|
639
835
|
// Router answers a request without a turn id only once the provider's first bytes arrive, and that request
|
|
@@ -702,6 +898,12 @@ export class ZRouterStreamBackend {
|
|
|
702
898
|
return;
|
|
703
899
|
}
|
|
704
900
|
catch (error) {
|
|
901
|
+
// Refused, before any output, for what its tool images can cause: once more without them, as a turn of its
|
|
902
|
+
// own, since Router keeps a streamed turn's body under its id.
|
|
903
|
+
if (carriesToolImages && !emittedMappedEvent && this.refusedForToolImages(request, error)) {
|
|
904
|
+
yield* this.streamResponse(this.resentTurn(request), fetcher, true);
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
705
907
|
// Once the Router is replaying a turn we already started, the backend
|
|
706
908
|
// owns every retry: the agent cannot re-drive a turn that already
|
|
707
909
|
// emitted output. So a transient HTTP failure on a resume (the Router's
|
|
@@ -946,15 +1148,3 @@ function normalizeHeaderValue(value, label, maxLength) {
|
|
|
946
1148
|
}
|
|
947
1149
|
return normalized;
|
|
948
1150
|
}
|
|
949
|
-
/** A wire-only projection: saved tool history remains byte-for-byte intact. */
|
|
950
|
-
function chatOnlyRequest(request) {
|
|
951
|
-
return { ...request, tools: [], messages: request.messages.map(message => ({ ...message,
|
|
952
|
-
content: typeof message.content === 'string' ? message.content : message.content.map(block => {
|
|
953
|
-
if (block.type === 'tool_use')
|
|
954
|
-
return { type: 'text', text: `Previous tool call ${block.name} (${block.id}): ${JSON.stringify(block.input)}` };
|
|
955
|
-
if (block.type === 'tool_result')
|
|
956
|
-
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')}` };
|
|
957
|
-
return block;
|
|
958
|
-
}),
|
|
959
|
-
})) };
|
|
960
|
-
}
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* computes the verdict and passes it in; the encoder only assembles blocks.
|
|
17
17
|
*/
|
|
18
18
|
import { Message, ToolDefinition } from '../types.js';
|
|
19
|
-
import { LlmMessage, RequestContentBlock } from './backends/index.js';
|
|
19
|
+
import { LlmMessage, RequestContentBlock, ToolResultBlock } from './backends/index.js';
|
|
20
20
|
export interface EncodeDeps {
|
|
21
21
|
preserveNativeHistory?: boolean;
|
|
22
22
|
model?: string;
|
|
@@ -76,8 +76,12 @@ export declare class RequestEncoder {
|
|
|
76
76
|
private toContentBlocks;
|
|
77
77
|
private buildUserContentBlocks;
|
|
78
78
|
private buildAttachmentBlocks;
|
|
79
|
-
private parseToolResultForImages;
|
|
80
79
|
private buildToolResultBlocks;
|
|
81
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* A stored tool result as the request's tool_result block: an image result as its description and the image, which
|
|
83
|
+
* each backend sends as an image or as '[image]' after its text; anything else as its text (toolResultText).
|
|
84
|
+
*/
|
|
85
|
+
export declare function toolResultBlock(toolUseId: string, content: string, isError?: boolean): ToolResultBlock;
|
|
82
86
|
/** Provider reasoning binds the system prompt and ordered tool vocabulary. */
|
|
83
87
|
export declare function nativeHistoryContextId(system: string, tools: ToolDefinition[]): string;
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import { createHash } from 'node:crypto';
|
|
19
19
|
import { isMirrorMediaPath } from '../utils/mirror_media.js';
|
|
20
20
|
import { readDurableSessionImageSync, SessionMediaError } from '../session_media.js';
|
|
21
|
-
import { parseImageToolResult } from './tool_result_parsing.js';
|
|
21
|
+
import { imageResultCaption, parseImageToolResult, toolResultText, withToolResultNote } from './tool_result_parsing.js';
|
|
22
22
|
import { assistantClaimReplayContent } from './claim_observation.js';
|
|
23
23
|
import { presentToolResult, toolCallNames } from './tool_result_presentation.js';
|
|
24
24
|
import { COPY_ADVICE, resultCopyNote } from '../utils/tool_output_copies.js';
|
|
@@ -214,10 +214,11 @@ export class RequestEncoder {
|
|
|
214
214
|
// block (content must be a string for the API), not as undefined —
|
|
215
215
|
// which would crash parseImageToolResult and silently degrade the
|
|
216
216
|
// whole message to plain text, breaking tool_use/tool_result pairing.
|
|
217
|
-
|
|
217
|
+
// The annotation (the repeat guard's note) goes in an image result's description, so the result stays an image.
|
|
218
|
+
content: this.emittedToolResult(r.tool_use_id, withToolResultNote(presentToolResult(this.toolNames.get(r.tool_use_id) ?? '', verdict?.get(r.tool_use_id)
|
|
218
219
|
?? this.deps.renderForContext(r.tool_use_id)
|
|
219
220
|
?? r.content
|
|
220
|
-
?? '')
|
|
221
|
+
?? ''), typeof r.context_annotation === 'string' ? r.context_annotation : '')),
|
|
221
222
|
// The full copy keeps the result as the tool returned it, not as it is shown.
|
|
222
223
|
...(typeof r.content === 'string' ? { source: r.content } : {}),
|
|
223
224
|
}));
|
|
@@ -323,43 +324,17 @@ export class RequestEncoder {
|
|
|
323
324
|
}
|
|
324
325
|
return blocks;
|
|
325
326
|
}
|
|
326
|
-
parseToolResultForImages(result) {
|
|
327
|
-
const img = parseImageToolResult(result);
|
|
328
|
-
if (!img)
|
|
329
|
-
return { hasImage: false, text: result };
|
|
330
|
-
return {
|
|
331
|
-
hasImage: true,
|
|
332
|
-
imageData: { mediaType: img.mediaType, data: img.data },
|
|
333
|
-
text: img.description || 'Screenshot captured',
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
327
|
buildToolResultBlocks(toolResults) {
|
|
337
328
|
return toolResults.map(result => {
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
tool_use_id: result.tool_use_id,
|
|
343
|
-
...(result.is_error === undefined ? {} : { is_error: result.is_error }),
|
|
344
|
-
content: [
|
|
345
|
-
{ type: 'text', text: parsed.text },
|
|
346
|
-
{
|
|
347
|
-
type: 'image',
|
|
348
|
-
source: {
|
|
349
|
-
type: 'base64',
|
|
350
|
-
media_type: parsed.imageData.mediaType,
|
|
351
|
-
data: parsed.imageData.data
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
]
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
let content = result.content;
|
|
329
|
+
if (parseImageToolResult(result.content))
|
|
330
|
+
return toolResultBlock(result.tool_use_id, result.content, result.is_error);
|
|
331
|
+
// A result an older ZTC cut short no longer reads as an image: its text form, never its base64.
|
|
332
|
+
let content = toolResultText(result.content);
|
|
358
333
|
// Preserve frozen cache bytes first, then the aggregate selector's explicit
|
|
359
334
|
// verdict. Only unselected historical fallback content needs another cap.
|
|
360
335
|
const frozen = this.deps.frozenResultContent?.(result.tool_use_id);
|
|
361
336
|
if (frozen !== undefined) {
|
|
362
|
-
content = frozen;
|
|
337
|
+
content = toolResultText(frozen);
|
|
363
338
|
}
|
|
364
339
|
else if (!this.deps.currentTurnToolIds.has(result.tool_use_id)
|
|
365
340
|
&& !this.deps.selectorVerdict?.has(result.tool_use_id) && content.length > STABLE_RESULT_LIMIT) {
|
|
@@ -383,6 +358,21 @@ export class RequestEncoder {
|
|
|
383
358
|
});
|
|
384
359
|
}
|
|
385
360
|
}
|
|
361
|
+
/**
|
|
362
|
+
* A stored tool result as the request's tool_result block: an image result as its description and the image, which
|
|
363
|
+
* each backend sends as an image or as '[image]' after its text; anything else as its text (toolResultText).
|
|
364
|
+
*/
|
|
365
|
+
export function toolResultBlock(toolUseId, content, isError) {
|
|
366
|
+
const image = parseImageToolResult(content);
|
|
367
|
+
return {
|
|
368
|
+
type: 'tool_result',
|
|
369
|
+
tool_use_id: toolUseId,
|
|
370
|
+
...(isError === undefined ? {} : { is_error: isError }),
|
|
371
|
+
content: image ? [{ type: 'text', text: imageResultCaption(image) },
|
|
372
|
+
{ type: 'image', source: { type: 'base64', media_type: image.mediaType, data: image.data } }]
|
|
373
|
+
: toolResultText(content),
|
|
374
|
+
};
|
|
375
|
+
}
|
|
386
376
|
/** Provider reasoning binds the system prompt and ordered tool vocabulary. */
|
|
387
377
|
export function nativeHistoryContextId(system, tools) {
|
|
388
378
|
return createHash('sha256').update(JSON.stringify({ system, tools })).digest('hex');
|
|
@@ -139,5 +139,11 @@ export interface EvidenceContextOptions {
|
|
|
139
139
|
renderedEarlier?: readonly string[];
|
|
140
140
|
}
|
|
141
141
|
export declare function formatEvidenceContext(snapshot: EvidenceSnapshot, options?: EvidenceContextOptions): string;
|
|
142
|
+
/**
|
|
143
|
+
* An evidence block, as a request sends it again. A session an older ZTC saved can hold a block whose observation
|
|
144
|
+
* excerpt is the start of an image result itself, its base64 included: that excerpt goes as its text form. Any other
|
|
145
|
+
* line goes as it is.
|
|
146
|
+
*/
|
|
147
|
+
export declare function evidenceContextForRequest(block: string): string;
|
|
142
148
|
export declare function parseEvidenceSnapshot(value: unknown): EvidenceSnapshot | null;
|
|
143
149
|
export {};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseCheckedCommandResult } from './checked_commands.js';
|
|
2
|
+
import { toolResultText } from '../tool_result_parsing.js';
|
|
2
3
|
import { parseHostVerifierDecision } from './verifier_contract.js';
|
|
3
4
|
import { parseBenchmarkComparisonDecision } from './benchmark_comparison.js';
|
|
4
5
|
import { parseCommandVerificationReceipt, parseCurrentVerificationProjection } from './source_verification_contract.js';
|
|
@@ -413,8 +414,9 @@ export function formatEvidenceContext(snapshot, options = {}) {
|
|
|
413
414
|
reason: prefix(compact.source.verifier.reason, 256) };
|
|
414
415
|
if (compact.kind === 'observation') {
|
|
415
416
|
const toolCallId = compact.source.toolCallId;
|
|
417
|
+
// An older ZTC kept the start of an image result itself, its base64 included: the excerpt is its text form.
|
|
416
418
|
compact.excerpt = toolCallId && options.toolCallsInContext?.has(toolCallId)
|
|
417
|
-
? EXCERPT_IN_CONTEXT : prefix(compact.excerpt, 512);
|
|
419
|
+
? EXCERPT_IN_CONTEXT : prefix(toolResultText(compact.excerpt), 512);
|
|
418
420
|
}
|
|
419
421
|
else {
|
|
420
422
|
if (compact.kind === 'user_instruction') {
|
|
@@ -475,6 +477,26 @@ export function formatEvidenceContext(snapshot, options = {}) {
|
|
|
475
477
|
const footer = `${repeated}${omissions.length ? `\n${omissions.join('; ')}.` : ''}`;
|
|
476
478
|
return header + selected.sort((a, b) => a.index - b.index).map(row => row.text).join('\n') + footer;
|
|
477
479
|
}
|
|
480
|
+
/**
|
|
481
|
+
* An evidence block, as a request sends it again. A session an older ZTC saved can hold a block whose observation
|
|
482
|
+
* excerpt is the start of an image result itself, its base64 included: that excerpt goes as its text form. Any other
|
|
483
|
+
* line goes as it is.
|
|
484
|
+
*/
|
|
485
|
+
export function evidenceContextForRequest(block) {
|
|
486
|
+
return block.split('\n').map(line => {
|
|
487
|
+
let row;
|
|
488
|
+
try {
|
|
489
|
+
row = line.startsWith('{') ? JSON.parse(line) : undefined;
|
|
490
|
+
}
|
|
491
|
+
catch {
|
|
492
|
+
return line;
|
|
493
|
+
}
|
|
494
|
+
const excerpt = row?.excerpt;
|
|
495
|
+
if (row?.kind !== 'observation' || typeof excerpt !== 'string' || toolResultText(excerpt) === excerpt)
|
|
496
|
+
return line;
|
|
497
|
+
return JSON.stringify({ ...row, excerpt: prefix(toolResultText(excerpt), 512) });
|
|
498
|
+
}).join('\n');
|
|
499
|
+
}
|
|
478
500
|
export function parseEvidenceSnapshot(value) {
|
|
479
501
|
try {
|
|
480
502
|
if (bytes(JSON.stringify(value)) > EVIDENCE_MAX_SNAPSHOT_BYTES)
|