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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +29 -0
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/App.js +4 -0
  8. package/dist/agent/agent.js +5 -2
  9. package/dist/agent/backends/anthropic.js +4 -1
  10. package/dist/agent/backends/bedrock.js +4 -1
  11. package/dist/agent/backends/codex_app_server.js +6 -2
  12. package/dist/agent/backends/gemini.d.ts +9 -0
  13. package/dist/agent/backends/gemini.js +77 -39
  14. package/dist/agent/backends/openai_format.d.ts +17 -1
  15. package/dist/agent/backends/openai_format.js +122 -24
  16. package/dist/agent/backends/openai_responses.d.ts +15 -3
  17. package/dist/agent/backends/openai_responses.js +32 -8
  18. package/dist/agent/backends/request_metrics.js +7 -6
  19. package/dist/agent/backends/tool_result_images.d.ts +114 -0
  20. package/dist/agent/backends/tool_result_images.js +201 -0
  21. package/dist/agent/backends/types.d.ts +5 -0
  22. package/dist/agent/backends/zerg-api.js +4 -2
  23. package/dist/agent/backends/zrouter_stream.d.ts +47 -0
  24. package/dist/agent/backends/zrouter_stream.js +244 -54
  25. package/dist/agent/request_encoder.d.ts +6 -2
  26. package/dist/agent/request_encoder.js +24 -34
  27. package/dist/agent/runtime/evidence.d.ts +6 -0
  28. package/dist/agent/runtime/evidence.js +23 -1
  29. package/dist/agent/runtime/tool_runtime.js +30 -17
  30. package/dist/agent/subagent.js +7 -8
  31. package/dist/agent/tool_response_store.js +3 -3
  32. package/dist/agent/tool_result_parsing.d.ts +22 -0
  33. package/dist/agent/tool_result_parsing.js +51 -0
  34. package/dist/agent/tools/recall_tool_response.js +24 -0
  35. package/dist/cli_ratatui.js +4 -0
  36. package/dist/headless.js +6 -0
  37. package/dist/types.d.ts +5 -0
  38. package/dist/utils/compaction.js +30 -4
  39. package/dist/zlm-embed.mjs +651 -194
  40. package/package.json +9 -34
@@ -16,6 +16,8 @@ import { ztcCommandCapabilities, ztcCommandTool } from '../tools/ztc_command.js'
16
16
  import { verifyArtifactTool } from '../tools/verify_artifact.js';
17
17
  import { benchmarkCPUTool } from '../tools/benchmark_cpu.js';
18
18
  import { compareBenchmarksTool } from '../tools/compare_benchmarks.js';
19
+ import { imageResultCaption, parseImageToolResult, withToolResultNote } from '../tool_result_parsing.js';
20
+ import { TOOL_IMAGE_BASE64_CAP, tooLargeToolImageNote } from '../backends/tool_result_images.js';
19
21
  function getTool(name, tools) {
20
22
  return tools.find(t => t.definition.name === name);
21
23
  }
@@ -91,7 +93,23 @@ function prependMessages(base, messages) {
91
93
  if (messages.length === 0)
92
94
  return base;
93
95
  const prefix = buildHookText(messages);
94
- return base ? `${prefix}\n${base}` : prefix;
96
+ // An image result keeps its image: the words go before its description.
97
+ return base ? withToolResultNote(base, '', `${prefix}\n`) : prefix;
98
+ }
99
+ // Global output cap: prevent any single tool result from dominating the context window. Claude Code caps at ~100K
100
+ // chars; we use 80K (~20K tokens). The model gets the head + tail of large outputs to preserve both the beginning
101
+ // (headers, structure) and end (final status, errors).
102
+ const TOOL_OUTPUT_CAP = 80_000;
103
+ /** TEXT within the tool output cap: when longer, its first 64,000 and last 16,000 characters and a line saying so. */
104
+ function capToolText(text) {
105
+ if (text.length <= TOOL_OUTPUT_CAP)
106
+ return text;
107
+ const HEAD = Math.floor(TOOL_OUTPUT_CAP * 0.8);
108
+ const TAIL = TOOL_OUTPUT_CAP - HEAD;
109
+ const totalLines = text.split('\n').length;
110
+ return text.slice(0, HEAD)
111
+ + `\n\n[output truncated: ${text.length.toLocaleString()} chars / ~${totalLines.toLocaleString()} lines — showing first ${HEAD.toLocaleString()} and last ${TAIL.toLocaleString()} chars]\n\n`
112
+ + text.slice(-TAIL);
95
113
  }
96
114
  function normalizeChangedPath(path, cwd) {
97
115
  const rel = relative(cwd, resolve(cwd, path));
@@ -575,24 +593,19 @@ export async function executeToolWithRuntime(name, args, options) {
575
593
  }
576
594
  if (tool?.isErrorResult?.(output))
577
595
  throw new Error(output);
578
- // Global output cap: prevent any single tool result from dominating the
579
- // context window. Claude Code caps at ~100K chars; we use 80K (~20K tokens).
580
- // The model gets the head + tail of large outputs to preserve both the
581
- // beginning (headers, structure) and end (final status, errors).
582
- const TOOL_OUTPUT_CAP = 80_000;
583
596
  output = augmentReadResultWithIntent(name, effectiveArgs, output, cwd);
584
- let resultContent = output;
597
+ // An image result isn't text: a cut one would reach the model as its base64 text. It keeps its image whole, which
598
+ // each request sends only within the provider's limits, and its words are cut as any tool's text is. One larger
599
+ // than any request sends is its words and a note.
600
+ const image = parseImageToolResult(output);
601
+ const description = image?.description ?? '';
602
+ const words = image ? capToolText(description) : '';
603
+ let resultContent = image === null ? capToolText(output)
604
+ : image.data.length > TOOL_IMAGE_BASE64_CAP ? capToolText(`${imageResultCaption(image)}\n${tooLargeToolImageNote(TOOL_IMAGE_BASE64_CAP)}`)
605
+ : words === description ? output : JSON.stringify({ ...JSON.parse(output), description: words });
585
606
  // A result the tool cut itself (read_file, run_command report truncated: true) is partial too. read_file now
586
607
  // stays under the cap (2026-10-27), so the cap alone no longer marks a truncated read.
587
- const contentTruncated = resultContent.length > TOOL_OUTPUT_CAP || reportsOwnTruncation(output);
588
- if (resultContent.length > TOOL_OUTPUT_CAP) {
589
- const HEAD = Math.floor(TOOL_OUTPUT_CAP * 0.8);
590
- const TAIL = TOOL_OUTPUT_CAP - HEAD;
591
- const totalLines = resultContent.split('\n').length;
592
- resultContent = resultContent.slice(0, HEAD)
593
- + `\n\n[output truncated: ${resultContent.length.toLocaleString()} chars / ~${totalLines.toLocaleString()} lines — showing first ${HEAD.toLocaleString()} and last ${TAIL.toLocaleString()} chars]\n\n`
594
- + resultContent.slice(-TAIL);
595
- }
608
+ const contentTruncated = resultContent !== output || reportsOwnTruncation(output);
596
609
  const changedPaths = extractChangedPaths(capabilities, output, cwd);
597
610
  // The plan artifact is host control-plane state outside the workspace.
598
611
  // Auto-intents would turn this exact-one-file exception into a second
@@ -613,7 +626,7 @@ export async function executeToolWithRuntime(name, args, options) {
613
626
  catch {
614
627
  // The write has committed. An observation-store error must not invite
615
628
  // replay of the successful mutation by presenting it as a tool failure.
616
- resultContent += '\nLocal workspace evidence unavailable; the file write already completed.';
629
+ resultContent = withToolResultNote(resultContent, '\nLocal workspace evidence unavailable; the file write already completed.');
617
630
  }
618
631
  }
619
632
  if (options.hooks) {
@@ -25,7 +25,8 @@ import { awaitManagedCommandProgress, formatManagedCommandObservations } from '.
25
25
  import { scheduleToolBatch, commandStillRunning } from './runtime/tool_scheduler.js';
26
26
  import { configStore } from '../config.js';
27
27
  import { hostModelContextBudget, hostModelContextError } from './host_model_context.js';
28
- import { RequestEncoder, nativeHistoryContextId } from './request_encoder.js';
28
+ import { RequestEncoder, nativeHistoryContextId, toolResultBlock } from './request_encoder.js';
29
+ import { withToolResultNote } from './tool_result_parsing.js';
29
30
  import { presentToolResult, toolCallNames } from './tool_result_presentation.js';
30
31
  import { ToolResponseIntegrityError, ToolResponseStore } from './tool_response_store.js';
31
32
  import { formatEvidenceContext } from './runtime/evidence.js';
@@ -489,11 +490,13 @@ export class SubAgent {
489
490
  await this.toolResponseStore.flush();
490
491
  retainingSource = false;
491
492
  publishEvidence();
493
+ const shown = result.isError ? `Error: ${rendered}` : rendered;
492
494
  return {
493
495
  is_error: result.isError,
494
496
  tool_use_id: toolBlock.id,
495
497
  managedCommand: result.managedCommand,
496
- content: applyRepeatGuard(toolBlock.name, toolBlock.input, result.isError ? `Error: ${rendered}` : rendered, result.isError ? undefined : result.managedCommand),
498
+ // The repeat guard's note goes in an image result's description, so the result stays an image.
499
+ content: withToolResultNote(shown, applyRepeatGuard(toolBlock.name, toolBlock.input, shown, result.isError ? undefined : result.managedCommand).slice(shown.length)),
497
500
  };
498
501
  }
499
502
  catch (err) {
@@ -793,12 +796,8 @@ export class SubAgent {
793
796
  const toolResults = JSON.parse(m.content);
794
797
  return {
795
798
  role: 'user',
796
- content: toolResults.map(tr => ({
797
- type: 'tool_result',
798
- tool_use_id: tr.tool_use_id,
799
- content: presentToolResult(toolNames.get(tr.tool_use_id) ?? '', tr.content),
800
- is_error: tr.is_error,
801
- }))
799
+ // An image result goes as its text and the image, as the main loop's encoder sends it.
800
+ content: toolResults.map(tr => toolResultBlock(tr.tool_use_id, presentToolResult(toolNames.get(tr.tool_use_id) ?? '', tr.content), tr.is_error))
802
801
  };
803
802
  }
804
803
  catch {
@@ -18,7 +18,7 @@ import { writeFileAtomic } from '../utils/atomic_write.js';
18
18
  import { debugLog } from '../debug/logger.js';
19
19
  import { environmentEphemeralToolNames, environmentEphemeralToolRules, isEphemeralToolCall, EPHEMERAL_TOOL_PLACEHOLDER, validateEphemeralToolNames, validateEphemeralToolRules } from '../utils/ephemeral_tools.js';
20
20
  import { compressToolResult, hashToolResultBody, isReadToolName, } from './tool_compression.js';
21
- import { parseImageToolResult } from './tool_result_parsing.js';
21
+ import { parseImageToolResult, toolResultText } from './tool_result_parsing.js';
22
22
  import { CORE_DISCOVERY_TOOL_NAMES } from './tools/deferred.js';
23
23
  import { RESULT_EMIT_CAP_TOKENS } from './result_emit_cap.js';
24
24
  import { readBoundedSource, SourceAdmissionError } from './tool_response_source.js';
@@ -680,7 +680,7 @@ export class ToolResponseStore {
680
680
  }
681
681
  this.evidence.observe({ id: meta.observation_id, recordedAt: meta.timestamp,
682
682
  source: { origin: 'host_tool', ...(sourcePath ? { path: sourcePath } : {}), ...(ephemeral ? {} : context?.source), toolCallId: toolUseId, toolName },
683
- excerpt: ephemeral ? EPHEMERAL_TOOL_PLACEHOLDER : content, resultSha256: sha256, resultBytes: Buffer.byteLength(content), partial,
683
+ excerpt: ephemeral ? EPHEMERAL_TOOL_PLACEHOLDER : toolResultText(content), resultSha256: sha256, resultBytes: Buffer.byteLength(content), partial,
684
684
  isError: Boolean(context?.isError), availability: 'memory',
685
685
  ...(ephemeral || context?.source?.job?.cursor === undefined ? {} : { cursor: context.source.job.cursor }) });
686
686
  const observed = this.evidence.getSnapshot().records.find(record => record.id === meta.observation_id);
@@ -844,7 +844,7 @@ export class ToolResponseStore {
844
844
  const observation = record.observation ?? {
845
845
  id: record.meta.observation_id, kind: 'observation', recordedAt: record.meta.timestamp,
846
846
  source: { origin: 'legacy', toolCallId: id, toolName: record.meta.tool_name, ...(record.meta.source_path ? { path: record.meta.source_path } : {}) },
847
- excerpt: record.content, resultSha256: record.meta.result_sha256, resultBytes: Buffer.byteLength(record.content),
847
+ excerpt: toolResultText(record.content), resultSha256: record.meta.result_sha256, resultBytes: Buffer.byteLength(record.content),
848
848
  partial: Boolean(record.meta.partial), isError: Boolean(record.meta.is_error), availability: 'persisted', verification: 'unknown',
849
849
  };
850
850
  this.evidence.observe({ ...observation, availability: 'persisted' });
@@ -2,6 +2,13 @@
2
2
  * Shared parser for image-bearing tool results. Used by the agent to build
3
3
  * `image` blocks for the API, and by the offload store to force-inline image
4
4
  * results (placeholders would drop the image data before rendering).
5
+ *
6
+ * A tool returns its image as one JSON envelope (`{"type":"image","mediaType",
7
+ * "data","description"}`). The envelope only ever reaches a model as an image or
8
+ * as its text and '[image]': never as the envelope's text, whose base64 a model
9
+ * reads as tens of thousands of tokens of noise. Whatever adds words to a result
10
+ * adds them to the envelope's description (withToolResultNote), and whatever turns
11
+ * a result into text for a model takes its text form (toolResultText).
5
12
  */
6
13
  export interface ToolResultImage {
7
14
  mediaType: string;
@@ -11,3 +18,18 @@ export interface ToolResultImage {
11
18
  path?: string;
12
19
  }
13
20
  export declare function parseImageToolResult(content: string): ToolResultImage | null;
21
+ /** The words that go with an image result's image: its description. */
22
+ export declare function imageResultCaption(image: Pick<ToolResultImage, 'description'>): string;
23
+ /** Whether CONTENT starts as an image result ZTC writes: whole, or as an older ZTC cut it short. */
24
+ export declare function isImageEnvelope(content: string): boolean;
25
+ /**
26
+ * A tool result as text for a model: an image result's description and '[image]', and anything else as it is. An image
27
+ * result an older ZTC cut short, or added words to, no longer reads as an image: it reads as its description, when
28
+ * that survived, and '[image]'. Its base64 never stays.
29
+ */
30
+ export declare function toolResultText(content: string): string;
31
+ /**
32
+ * CONTENT with NOTE added after it, or LEAD before it. An image result keeps its image: the words go in its
33
+ * description, which a model reads with the image. Anything else gets them as text.
34
+ */
35
+ export declare function withToolResultNote(content: string, note: string, lead?: string): string;
@@ -2,6 +2,13 @@
2
2
  * Shared parser for image-bearing tool results. Used by the agent to build
3
3
  * `image` blocks for the API, and by the offload store to force-inline image
4
4
  * results (placeholders would drop the image data before rendering).
5
+ *
6
+ * A tool returns its image as one JSON envelope (`{"type":"image","mediaType",
7
+ * "data","description"}`). The envelope only ever reaches a model as an image or
8
+ * as its text and '[image]': never as the envelope's text, whose base64 a model
9
+ * reads as tens of thousands of tokens of noise. Whatever adds words to a result
10
+ * adds them to the envelope's description (withToolResultNote), and whatever turns
11
+ * a result into text for a model takes its text form (toolResultText).
5
12
  */
6
13
  export function parseImageToolResult(content) {
7
14
  try {
@@ -20,3 +27,47 @@ export function parseImageToolResult(content) {
20
27
  }
21
28
  return null;
22
29
  }
30
+ /** The words that go with an image result's image: its description. */
31
+ export function imageResultCaption(image) {
32
+ return image.description || 'Screenshot captured';
33
+ }
34
+ /** How every tool image envelope ZTC writes starts: its type, media type and the start of its base64. */
35
+ const ENVELOPE_START = /^\{"type":"image","mediaType":"[^"\\]{0,100}","data":"/;
36
+ /** Whether CONTENT starts as an image result ZTC writes: whole, or as an older ZTC cut it short. */
37
+ export function isImageEnvelope(content) {
38
+ return ENVELOPE_START.test(content);
39
+ }
40
+ /** An envelope's description, wherever in what is left of it. */
41
+ const ENVELOPE_DESCRIPTION = /","description":"((?:[^"\\]|\\.)*)"/;
42
+ /**
43
+ * A tool result as text for a model: an image result's description and '[image]', and anything else as it is. An image
44
+ * result an older ZTC cut short, or added words to, no longer reads as an image: it reads as its description, when
45
+ * that survived, and '[image]'. Its base64 never stays.
46
+ */
47
+ export function toolResultText(content) {
48
+ const image = parseImageToolResult(content);
49
+ if (image)
50
+ return `${imageResultCaption(image)}\n[image]`;
51
+ if (!isImageEnvelope(content))
52
+ return content;
53
+ const description = ENVELOPE_DESCRIPTION.exec(content)?.[1];
54
+ let caption = '';
55
+ try {
56
+ caption = description === undefined ? '' : JSON.parse(`"${description}"`);
57
+ }
58
+ catch { /* cut inside an escape */ }
59
+ return caption ? `${caption}\n[image]` : '[image]';
60
+ }
61
+ /**
62
+ * CONTENT with NOTE added after it, or LEAD before it. An image result keeps its image: the words go in its
63
+ * description, which a model reads with the image. Anything else gets them as text.
64
+ */
65
+ export function withToolResultNote(content, note, lead = '') {
66
+ if (!note && !lead)
67
+ return content;
68
+ if (parseImageToolResult(content) === null)
69
+ return `${lead}${content}${note}`;
70
+ const envelope = JSON.parse(content);
71
+ const description = typeof envelope.description === 'string' ? envelope.description : '';
72
+ return JSON.stringify({ ...envelope, description: `${lead}${description}${note}` });
73
+ }
@@ -18,7 +18,22 @@ import { readFile } from 'node:fs/promises';
18
18
  import { ToolCapability } from '../runtime/capabilities.js';
19
19
  import { captureHelperRequirements } from './helper_requirements.js';
20
20
  import { describeOffloadPlaceholderFormat } from '../tool_response_store.js';
21
+ import { isImageEnvelope, parseImageToolResult, toolResultText } from '../tool_result_parsing.js';
21
22
  import { copyMatchesDigest, COPY_PARTS, findCopy, readCopyChunk, saveCopy } from '../../utils/tool_output_copies.js';
23
+ /**
24
+ * An image result as recall gives it back: its image, which each request sends as an image or as '[image]' after its
25
+ * text, or for one an older ZTC cut short, whose image is lost, its text form. Its base64 as text would reach the model
26
+ * as tens of thousands of tokens of noise. Null for any other result.
27
+ */
28
+ function recalledImage(id, content, meta) {
29
+ const image = parseImageToolResult(content);
30
+ if (image) {
31
+ return JSON.stringify({ type: 'image', mediaType: image.mediaType, data: image.data,
32
+ description: `Recalled tool result ${id}: ${image.description ?? ''}` });
33
+ }
34
+ return isImageEnvelope(content)
35
+ ? JSON.stringify({ ok: true, tool_use_id: id, ...(meta ? { meta } : {}), content: toolResultText(content), complete: true }) : null;
36
+ }
22
37
  export const recallToolResponseTool = captureHelperRequirements({
23
38
  capabilities: [ToolCapability.FILE_READ],
24
39
  definition: {
@@ -65,6 +80,10 @@ export const recallToolResponseTool = captureHelperRequirements({
65
80
  if (cursor !== undefined && (!Number.isSafeInteger(cursor) || cursor < 0))
66
81
  throw new RangeError('cursor must be a nonnegative safe byte offset');
67
82
  const store = context.toolResponseStore;
83
+ const stored = part === 'result' && !store.getMeta(id)?.ephemeral ? await store.get(id) : null;
84
+ const image = stored === null ? null : recalledImage(id, stored, store.getMeta(id));
85
+ if (image !== null)
86
+ return image;
68
87
  const chunk = part === 'result' ? await store.getChunk(id, { cursor, maxBytes }) : null;
69
88
  if (chunk !== null) {
70
89
  // Mark recalled so the selector treats this entry as priority-4 from now
@@ -98,6 +117,11 @@ export const recallToolResponseTool = captureHelperRequirements({
98
117
  error: 'the copy at this file does not match the result recorded for this call; it was changed or belongs to another result' });
99
118
  }
100
119
  const copied = file ? readCopyChunk(file, cursor, maxBytes) : null;
120
+ // A copy of an image result, which an older ZTC wrote, comes back as the result itself does.
121
+ const copiedImage = file && copied && part === 'result' && isImageEnvelope(readCopyChunk(file, 0, 256)?.content ?? '')
122
+ ? recalledImage(id, await readFile(file, 'utf8')) : null;
123
+ if (copiedImage !== null)
124
+ return copiedImage;
101
125
  if (file && copied) {
102
126
  return JSON.stringify({ ok: true, tool_use_id: id, part, file, ...copied, availability: 'copy' });
103
127
  }
@@ -12194,6 +12194,10 @@ export class RatatuiApp {
12194
12194
  content: event.reason ? `Auto-continuing — ${event.reason}` : 'Auto-continuing...',
12195
12195
  });
12196
12196
  break;
12197
+ case 'notice':
12198
+ // Display-only: the agent sends the model no system line, and a local-only one no recap or summary reads.
12199
+ this.addSystemMessage(event.message, { localOnly: true });
12200
+ break;
12197
12201
  case 'api_retry': {
12198
12202
  // The request is asked again: an answer its last attempt showed, which the agent withdrew, goes first.
12199
12203
  const dropped = this.dropWithdrawnAnswer(withdrawnAnswer);
package/dist/headless.js CHANGED
@@ -903,6 +903,12 @@ export class HeadlessApp {
903
903
  data: { status: 'auto_continue' },
904
904
  });
905
905
  break;
906
+ case 'notice':
907
+ // The notice's diagnostic already went to stderr; a JSON consumer gets it as a status.
908
+ if (this.options.json) {
909
+ this.output({ type: 'status', timestamp: new Date().toISOString(), data: { status: 'notice', message: event.message } });
910
+ }
911
+ break;
906
912
  case 'api_retry':
907
913
  // Without this a run retrying a failing provider prints nothing and
908
914
  // looks hung until its wall-clock timeout (the TUI already shows it).
package/dist/types.d.ts CHANGED
@@ -393,6 +393,11 @@ export type AgentEvent = {
393
393
  } | {
394
394
  type: 'auto_continue';
395
395
  reason?: string;
396
+ }
397
+ /** A line for the person's transcript only (onNotice): display-only, never sent to the model. */
398
+ | {
399
+ type: 'notice';
400
+ message: string;
396
401
  } | {
397
402
  type: 'error';
398
403
  error: string;
@@ -9,6 +9,7 @@ import { createRouterJevAsker } from './jev_client.js';
9
9
  import { DEFAULT_JEV_SETTINGS } from '../config/compaction.js';
10
10
  import { requiredRouterModel } from '../config/router_required.js';
11
11
  import { isIncompleteModelResponse } from '../agent/completion_state.js';
12
+ import { toolResultText } from '../agent/tool_result_parsing.js';
12
13
  /**
13
14
  * The prompt-prefix identity of a conversation, or undefined while that prefix is
14
15
  * still the one the conversation started with.
@@ -114,7 +115,7 @@ function toolCallRecords(message) {
114
115
  return message.toolCalls.slice(-6).map((call) => {
115
116
  const outcome = call.error || call.result;
116
117
  const detail = outcome
117
- ? truncate(outcome, 600)
118
+ ? truncate(toolResultText(outcome), 600)
118
119
  : truncate(JSON.stringify(call.args ?? {}), 300);
119
120
  return JSON.stringify({ name: call.name, callId: call.id, detail });
120
121
  }).join(',');
@@ -127,6 +128,27 @@ function serializeSummaryRecord(record) {
127
128
  .replace(/\u2028/g, '\\u2028')
128
129
  .replace(/\u2029/g, '\\u2029');
129
130
  }
131
+ /** A tool-result message's content with each result as its text form: an image as its text and '[image]'. */
132
+ function resultsAsText(content) {
133
+ let results;
134
+ try {
135
+ results = JSON.parse(content);
136
+ }
137
+ catch {
138
+ return toolResultText(content);
139
+ }
140
+ if (!Array.isArray(results))
141
+ return toolResultText(content);
142
+ let changed = false;
143
+ const shown = results.map(result => {
144
+ const text = result && typeof result === 'object' ? result.content : undefined;
145
+ if (typeof text !== 'string' || toolResultText(text) === text)
146
+ return result;
147
+ changed = true;
148
+ return { ...result, content: toolResultText(text) };
149
+ });
150
+ return changed ? JSON.stringify(shown) : content;
151
+ }
130
152
  function renderSummaryMessage(message, max = MAX_CONDENSED_MESSAGE_CHARS) {
131
153
  const toolResult = isToolResultMessage(message);
132
154
  const role = toolResult
@@ -136,7 +158,7 @@ function renderSummaryMessage(message, max = MAX_CONDENSED_MESSAGE_CHARS) {
136
158
  : message.role === 'assistant'
137
159
  ? 'assistant'
138
160
  : 'tool_evidence';
139
- const parts = [message.content.trim(), toolCallRecords(message)].filter(Boolean);
161
+ const parts = [(toolResult ? resultsAsText(message.content) : message.content).trim(), toolCallRecords(message)].filter(Boolean);
140
162
  return truncate(serializeSummaryRecord({
141
163
  role,
142
164
  identity: summaryIdentity(message),
@@ -305,7 +327,9 @@ export function condenseRecapConversation(messages) {
305
327
  || message.role === 'tool'
306
328
  || message.role === 'system')
307
329
  .map((message) => {
308
- if (message.role === 'tool') {
330
+ // A tool-result row, the agent's (role user) or the TUI's (role tool), goes as its results' text form: an image
331
+ // result as its text and '[image]', never its base64.
332
+ if (isToolResultMessage(message)) {
309
333
  return condenseToolMessage(message);
310
334
  }
311
335
  return serializeSummaryRecord({
@@ -568,8 +592,10 @@ export function modelHandoffSummarizer(backend, model, options) {
568
592
  ],
569
593
  signal: controller.signal,
570
594
  });
595
+ // Without an encoded request (the library's compaction) each row goes as text: a tool-result row as its results'
596
+ // text form, so an image result reads as its text and '[image]', never as its base64.
571
597
  let history = options.request?.messages ?? messages.flatMap((message) => (message.role === 'user' || message.role === 'assistant'
572
- ? [{ role: message.role, content: message.content }] : []));
598
+ ? [{ role: message.role, content: isToolResultMessage(message) ? resultsAsText(message.content) : message.content }] : []));
573
599
  let lastError;
574
600
  try {
575
601
  for (let attempt = 0; attempt <= MAX_HANDOFF_OVERFLOW_RETRIES; attempt++) {