Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(hetero): echo CC Read-on-image results as uploaded thumbnails (#16786)

Arvin Xua9127598c9e0
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index fa87f6aadff..76143ce9b67 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -12,6 +12,7 @@ import type {
AgentImageSource,
AgentPromptInput,
AgentStreamEvent,
+ UploadHeterogeneousImage,
} from '@lobechat/heterogeneous-agents/spawn';
import { spawnAgent } from '@lobechat/heterogeneous-agents/spawn';
import type { Command } from 'commander';
@@ -19,11 +20,20 @@ import type { Command } from 'commander';
import { getTrpcClient } from '../api/client';
import { log } from '../utils/logger';
import { TrpcIngestSink } from '../utils/TrpcIngestSink';
+import { uploadFileBuffer } from '../utils/uploadLocalFile';
const SUPPORTED_AGENT_TYPES = new Set(['claude-code', 'codex']);
const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';
const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';
+/** Extension seed for an uploaded tool_result image, by IANA media type. */
+const IMAGE_EXT_BY_MEDIA_TYPE: Record<string, string> = {
+ 'image/gif': 'gif',
+ 'image/jpeg': 'jpg',
+ 'image/png': 'png',
+ 'image/webp': 'webp',
+};
+
/**
* Patterns that indicate a `--resume <sessionId>` run should be retried
* without `--resume`. Two classes of failure:
@@ -475,6 +485,13 @@ const exec = async (options: ExecOptions): Promise<void> => {
const agentType = options.type as 'claude-code' | 'codex';
let sink: TrpcIngestSink | undefined;
let serverIngester: SerialServerIngester | undefined;
+ // Uploader for tool_result images (CC `Read` on an image file). Reuses the
+ // CLI's authenticated lambda client so the persisted event carries a
+ // `{ fileId, url }` reference instead of heavy base64. Only wired in
+ // server-ingest mode β€” standalone runs don't persist events, so there is
+ // nothing to echo. The pipeline degrades a throw/undefined to the
+ // `[Image: …]` text placeholder, so this never fails the run.
+ let uploadImage: UploadHeterogeneousImage | undefined;
if (serverIngest) {
const client = await getTrpcClient();
sink = new TrpcIngestSink(
@@ -485,6 +502,16 @@ const exec = async (options: ExecOptions): Promise<void> => {
process.env.LOBEHUB_ASSISTANT_MESSAGE_ID,
);
serverIngester = new SerialServerIngester(sink);
+
+ uploadImage = async ({ data, mediaType }) => {
+ const ext = IMAGE_EXT_BY_MEDIA_TYPE[mediaType] ?? 'png';
+ const record = await uploadFileBuffer(await getTrpcClient(), {
+ buffer: Buffer.from(data, 'base64'),
+ fileName: `cc-read-image.${ext}`,
+ fileType: mediaType,
+ });
+ return { fileId: record.id, url: record.url };
+ };
}
// ─── AskUserQuestion MCP β€” remote Human-in-the-loop (claude-code only) ──────
@@ -795,6 +822,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
operationId,
prompt: resolved.prompt,
resumeSessionId: options.resume,
+ uploadImage,
},
interceptResume,
'attempt-1',
@@ -824,6 +852,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
extraArgs,
operationId,
prompt: resolved.prompt,
+ uploadImage,
// No resumeSessionId β€” start fresh
},
false, // no need to intercept resume errors on a fresh run
diff --git a/apps/cli/src/utils/uploadLocalFile.ts b/apps/cli/src/utils/uploadLocalFile.ts
index f87ac65f30f..a438922df43 100644
--- a/apps/cli/src/utils/uploadLocalFile.ts
+++ b/apps/cli/src/utils/uploadLocalFile.ts
@@ -47,37 +47,31 @@ export interface UploadLocalFileOptions {
parentId?: string;
}
+export interface UploadFileBufferInput {
+ /** Raw file bytes to upload. */
+ buffer: Buffer;
+ /** Display name; its extension seeds the S3 pathname. */
+ fileName: string;
+ /** MIME type sent as the S3 `Content-Type` and stored on the record. */
+ fileType: string;
+}
+
/**
- * Read a file from the local filesystem, upload it to S3 via a pre-signed URL,
- * and create the corresponding file record. Shared by `file upload` and
- * `kb upload`.
+ * Upload an in-memory buffer to S3 via a pre-signed URL and create the file
+ * record. This is the buffer-based core shared by {@link uploadLocalFile} (path
+ * source) and in-memory producers such as the heterogeneous-agent image echo.
*
- * @returns the created file record
+ * @returns the created file record (`{ id, url, ... }`)
*/
-export const uploadLocalFile = async (
+export const uploadFileBuffer = async (
client: TrpcClient,
- filePath: string,
+ { buffer, fileName, fileType }: UploadFileBufferInput,
options: UploadLocalFileOptions = {},
) => {
- const resolved = path.resolve(filePath);
- if (!fs.existsSync(resolved)) {
- throw new Error(`File not found: ${resolved}`);
- }
-
- const stat = fs.statSync(resolved);
- if (!stat.isFile()) {
- throw new Error(`Not a file: ${resolved}`);
- }
-
- const fileName = path.basename(resolved);
- const fileBuffer = fs.readFileSync(resolved);
-
// Compute SHA-256 hash for deduplication
- const hash = crypto.createHash('sha256').update(fileBuffer).digest('hex');
+ const hash = crypto.createHash('sha256').update(buffer).digest('hex');
const ext = path.extname(fileName).toLowerCase().slice(1);
- const fileType = detectMimeType(fileName);
-
const date = new Date().toLocaleDateString('en-CA'); // YYYY-MM-DD
// 1. Dedup: if the same bytes are already stored (and the object still
@@ -97,7 +91,7 @@ export const uploadLocalFile = async (
const presignedUrl = typeof presigned === 'string' ? presigned : (presigned as any).url;
const uploadRes = await fetch(presignedUrl, {
- body: fileBuffer,
+ body: buffer,
headers: { 'Content-Type': fileType },
method: 'PUT',
});
@@ -119,7 +113,39 @@ export const uploadLocalFile = async (
},
name: fileName,
parentId: options.parentId,
- size: stat.size,
+ size: buffer.length,
url: pathname,
});
};
+
+/**
+ * Read a file from the local filesystem, upload it to S3 via a pre-signed URL,
+ * and create the corresponding file record. Shared by `file upload` and
+ * `kb upload`.
+ *
+ * @returns the created file record
+ */
+export const uploadLocalFile = async (
+ client: TrpcClient,
+ filePath: string,
+ options: UploadLocalFileOptions = {},
+) => {
+ const resolved = path.resolve(filePath);
+ if (!fs.existsSync(resolved)) {
+ throw new Error(`File not found: ${resolved}`);
+ }
+
+ const stat = fs.statSync(resolved);
+ if (!stat.isFile()) {
+ throw new Error(`Not a file: ${resolved}`);
+ }
+
+ const fileName = path.basename(resolved);
+ const fileBuffer = fs.readFileSync(resolved);
+
+ return uploadFileBuffer(
+ client,
+ { buffer: fileBuffer, fileName, fileType: detectMimeType(fileName) },
+ options,
+ );
+};
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index bd16fd34c0d..2768cf69aaf 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -2031,10 +2031,20 @@ export class AiAgentService {
// `aiAgent` import. Only this cloud-CLI branch needs it.
const { spawnHeteroSandbox } =
await import('@/server/services/heterogeneousAgent/sandboxRunner');
+ // The sandbox authenticates its nested `lh` calls with this JWT. The
+ // narrow `hetero-operation` token (used for the device-dispatch path
+ // above) is rejected by `oidcAuth`, so CC capabilities that hit
+ // user-scoped endpoints β€” e.g. uploading a `Read`-on-image result to
+ // the file store for thumbnail echo β€” would 401 and silently drop.
+ // Mint a user-scoped `cli-sandbox` token instead (still `sub: userId`,
+ // ownership-gated on heteroIngest/heteroFinish) with a run-length TTL
+ // so it outlives a multi-hour run.
+ const sandboxJwt = await signUserJWT(this.userId, '4h');
spawnHeteroSandbox({
...heteroParams,
agentType: heteroType as 'claude-code' | 'codex',
args: heteroExecArgs,
+ jwt: sandboxJwt,
marketService: this.marketService,
}).catch(async (err) => {
// Fire-and-forget: execAgent has already returned `autoStarted`, and
diff --git a/packages/builtin-tool-claude-code/src/client/Render/Read/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/Read/index.tsx
index cd6e66d5573..b2974d07b06 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/Read/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/Read/index.tsx
@@ -1,7 +1,7 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Highlighter } from '@lobehub/ui';
+import { Flexbox, Highlighter, Image, PreviewGroup } from '@lobehub/ui';
import path from 'path-browserify-esm';
import { memo, useMemo } from 'react';
@@ -11,6 +11,22 @@ interface ReadArgs {
offset?: number;
}
+/**
+ * A single uploaded image echoed by `Read` on an image file. The adapter
+ * synthesizes these from CC's `image` tool_result block and the runtime
+ * pipeline uploads them, so by the time the render runs each entry carries a
+ * `url` (base64 `data` has been stripped) β€” see `HeterogeneousToolResultImage`.
+ */
+interface ReadResultImage {
+ fileId?: string;
+ mediaType?: string;
+ url?: string;
+}
+
+interface ReadPluginState {
+ images?: ReadResultImage[];
+}
+
/**
* Strip Claude Code's numbered-line prefix (e.g. `␣␣␣␣␣1\tfoo`) so the
* Highlighter can tokenize the actual source. CC always returns this `cat -n`
@@ -25,25 +41,53 @@ const stripLineNumbers = (text: string): string => {
.join('\n');
};
-const Read = memo<BuiltinRenderProps<ReadArgs>>(({ args, content }) => {
- const filePath = args?.file_path || '';
- const ext = filePath ? path.extname(filePath).slice(1).toLowerCase() : '';
-
- const source = useMemo(() => stripLineNumbers(content || ''), [content]);
- if (!source) return null;
-
- return (
- <Highlighter
- wrap
- language={ext || 'text'}
- showLanguage={false}
- style={{ maxHeight: 240, overflow: 'auto' }}
- variant={'borderless'}
- >
- {source}
- </Highlighter>
- );
-});
+const Read = memo<BuiltinRenderProps<ReadArgs, ReadPluginState>>(
+ ({ args, content, pluginState }) => {
+ const filePath = args?.file_path || '';
+ const ext = filePath ? path.extname(filePath).slice(1).toLowerCase() : '';
+
+ // `Read` on an image file yields uploaded thumbnails on `pluginState.images`
+ // instead of source text. Prefer that echo over the `[Image: …]` content
+ // placeholder the adapter leaves behind as a fallback.
+ const images = useMemo(
+ () => pluginState?.images?.filter((image) => !!image.url) ?? [],
+ [pluginState?.images],
+ );
+
+ const source = useMemo(() => stripLineNumbers(content || ''), [content]);
+
+ if (images.length > 0) {
+ return (
+ <PreviewGroup>
+ <Flexbox horizontal gap={8} style={{ flexWrap: 'wrap' }}>
+ {images.map((image, index) => (
+ <Image
+ alt={filePath || image.mediaType || ''}
+ key={image.fileId || image.url || index}
+ src={image.url}
+ style={{ borderRadius: 8, maxHeight: 240, objectFit: 'contain' }}
+ />
+ ))}
+ </Flexbox>
+ </PreviewGroup>
+ );
+ }
+
+ if (!source) return null;
+
+ return (
+ <Highlighter
+ wrap
+ language={ext || 'text'}
+ showLanguage={false}
+ style={{ maxHeight: 240, overflow: 'auto' }}
+ variant={'borderless'}
+ >
+ {source}
+ </Highlighter>
+ );
+ },
+);
Read.displayName = 'ClaudeCodeRead';
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index defe5ff0ba8..e115b6e0ee1 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -626,9 +626,11 @@ describe('ClaudeCodeAdapter', () => {
// CC's `Read` on images returns a `tool_result` whose `content` is an
// `image` block (base64). The generic mapper had no branch for it so
// resultContent collapsed to '' and the UI's StatusIndicator stuck on the
- // spinner. Minimal fix: emit a placeholder so the tool ends in completed
- // state. Image echo (thumbnails) is deferred.
- it('renders image blocks as a non-empty placeholder', () => {
+ // spinner ( minimal fix: emit an `[Image: …]` content placeholder).
+ // keeps that placeholder as the human-readable fallback AND
+ // preserves the base64 body on `pluginState.images` so the runtime
+ // pipeline can upload it and the UI can echo a thumbnail.
+ it('renders image blocks as a non-empty placeholder and preserves base64 on pluginState.images', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
adapter.adapt({
@@ -663,6 +665,9 @@ describe('ClaudeCodeAdapter', () => {
expect(result!.data.toolCallId).toBe('r1');
expect(result!.data.content).toBe('[Image: image/png]');
expect(result!.data.isError).toBe(false);
+ expect(result!.data.pluginState.images).toEqual([
+ { data: 'AAAA', mediaType: 'image/png' },
+ ]);
const end = events.find((e) => e.type === 'tool_end');
expect(end).toBeDefined();
@@ -696,6 +701,31 @@ describe('ClaudeCodeAdapter', () => {
const result = events.find((e) => e.type === 'tool_result');
expect(result!.data.content).toBe('[Image: image]');
+ expect(result!.data.pluginState.images).toEqual([{ data: 'AAAA', mediaType: 'image' }]);
+ });
+
+ it('does not set pluginState.images for a text-only tool_result', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt({ subtype: 'init', type: 'system' });
+ adapter.adapt({
+ message: {
+ id: 'msg_1',
+ content: [{ id: 'r1', input: { file_path: 'x.ts' }, name: 'Read', type: 'tool_use' }],
+ },
+ type: 'assistant',
+ });
+
+ const events = adapter.adapt({
+ message: {
+ content: [{ content: 'plain text', tool_use_id: 'r1', type: 'tool_result' }],
+ role: 'user',
+ },
+ type: 'user',
+ });
+
+ const result = events.find((e) => e.type === 'tool_result');
+ expect(result!.data.content).toBe('plain text');
+ expect(result!.data.pluginState).toBeUndefined();
});
});
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index b7154cb14c4..7b755cbdfd6 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -41,6 +41,7 @@ import type {
HeterogeneousAgentEvent,
HeterogeneousRateLimitInfo,
HeterogeneousTerminalErrorData,
+ HeterogeneousToolResultImage,
StreamChunkData,
SubagentEventContext,
SubagentSpawnMetadata,
@@ -48,6 +49,7 @@ import type {
ToolResultData,
UsageData,
} from '../types';
+import { imagePlaceholder } from '../imageEcho';
/**
* The CC tool_use `name` we synthesize `pluginState.todos` for. Inlined here
@@ -1167,6 +1169,11 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
this.hasUnhandledUserInput = true;
}
+ // `Read` on images yields `{type: 'image', source: {...}}` blocks. We
+ // gather their base64 bodies here (in the SAME pass that builds the
+ // human-readable content) so the runtime pipeline can upload them and the
+ // UI can echo a thumbnail β€” see `pluginState.images` below.
+ const images: HeterogeneousToolResultImage[] = [];
const resultContent =
typeof block.content === 'string'
? block.content
@@ -1180,12 +1187,15 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
// the UI's StatusIndicator stuck on the spinner ().
if (c?.type === 'tool_reference' && c.tool_name) return c.tool_name;
// `Read` on images yields `{type: 'image', source: {...}}` blocks
- // with no text. Drop a minimal placeholder so the tool message
- // has non-empty content (); richer image echo is a
- // follow-up that needs structured ToolResultData.
+ // with no text. Keep the `[Image: …]` placeholder as the
+ // content fallback () and preserve the base64 body on
+ // `pluginState.images` for rich echo ().
if (c?.type === 'image') {
const mediaType = c.source?.media_type || 'image';
- return `[Image: ${mediaType}]`;
+ if (c.source?.type === 'base64' && typeof c.source.data === 'string') {
+ images.push({ data: c.source.data, mediaType });
+ }
+ return imagePlaceholder(mediaType);
}
return c.text || c.content || '';
})
@@ -1222,7 +1232,14 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
? this.applyTaskToolResult(toolCallId, !!block.is_error, resultContent)
: undefined;
- const pluginState = todoWritePluginState ?? taskPluginState;
+ // Images are mutually exclusive with Todo/Task results in practice (a
+ // `Read` is neither), but merge defensively so a future producer that
+ // carries both doesn't clobber one. `data` is still raw base64 here; the
+ // runtime pipeline uploads and rewrites these entries before persistence.
+ let pluginState: Record<string, any> | undefined = todoWritePluginState ?? taskPluginState;
+ if (images.length > 0) {
+ pluginState = { ...pluginState, images };
+ }
// Emit tool_result for executor to persist content to tool message
events.push(
diff --git a/packages/heterogeneous-agents/src/imageEcho.test.ts b/packages/heterogeneous-agents/src/imageEcho.test.ts
new file mode 100644
index 00000000000..99022af7711
--- /dev/null
+++ b/packages/heterogeneous-agents/src/imageEcho.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+
+import { imageMarkdown, imagePlaceholder, rewriteImagePlaceholders } from './imageEcho';
+
+describe('imageEcho', () => {
+ it('placeholder / markdown shapes are stable', () => {
+ expect(imagePlaceholder('image/png')).toBe('[Image: image/png]');
+ expect(imageMarkdown('image/png', 'https://cdn/x.png')).toBe('![image/png](https://cdn/x.png)');
+ });
+
+ describe('rewriteImagePlaceholders', () => {
+ it('rewrites a single uploaded image into a markdown image', () => {
+ expect(
+ rewriteImagePlaceholders('[Image: image/png]', [
+ { mediaType: 'image/png', url: 'https://cdn/x.png' },
+ ]),
+ ).toBe('![image/png](https://cdn/x.png)');
+ });
+
+ it('keeps the placeholder when the image failed to upload (no url)', () => {
+ expect(rewriteImagePlaceholders('[Image: image/png]', [{ mediaType: 'image/png' }])).toBe(
+ '[Image: image/png]',
+ );
+ });
+
+ it('rewrites only the succeeded images, position-for-position', () => {
+ const content = 'before\n[Image: image/png]\nmid\n[Image: image/jpeg]\nafter';
+ expect(
+ rewriteImagePlaceholders(content, [
+ { mediaType: 'image/png', url: 'https://cdn/a.png' },
+ { mediaType: 'image/jpeg' }, // failed β€” keep placeholder
+ ]),
+ ).toBe('before\n![image/png](https://cdn/a.png)\nmid\n[Image: image/jpeg]\nafter');
+ });
+
+ it('preserves surrounding non-image text', () => {
+ expect(
+ rewriteImagePlaceholders('read the file:\n[Image: image/webp]\ndone', [
+ { mediaType: 'image/webp', url: 'https://cdn/w.webp' },
+ ]),
+ ).toBe('read the file:\n![image/webp](https://cdn/w.webp)\ndone');
+ });
+
+ it('bails out unchanged when the placeholder count does not match outcomes', () => {
+ // One placeholder but two outcomes β†’ cannot map safely β†’ leave content as-is.
+ const content = '[Image: image/png]';
+ expect(
+ rewriteImagePlaceholders(content, [
+ { mediaType: 'image/png', url: 'https://cdn/a.png' },
+ { mediaType: 'image/png', url: 'https://cdn/b.png' },
+ ]),
+ ).toBe(content);
+ });
+
+ it('returns content unchanged when there are no placeholders', () => {
+ expect(rewriteImagePlaceholders('plain text', [])).toBe('plain text');
+ });
+ });
+});
diff --git a/packages/heterogeneous-agents/src/imageEcho.ts b/packages/heterogeneous-agents/src/imageEcho.ts
new file mode 100644
index 00000000000..5260491dcb4
--- /dev/null
+++ b/packages/heterogeneous-agents/src/imageEcho.ts
@@ -0,0 +1,51 @@
+/**
+ * Shared text representation for images echoed by a tool_result (CC `Read` on
+ * an image file). The adapter emits {@link imagePlaceholder} pre-upload (it only
+ * has base64, not a URL); once the runtime pipeline uploads the image it swaps
+ * that placeholder for {@link imageMarkdown} via {@link rewriteImagePlaceholders},
+ * so a downstream model handed this history sees a real image reference instead
+ * of an opaque `[Image: …]` token.
+ *
+ * Keeping both the emit and the rewrite here means the adapter and pipeline
+ * can't drift on the placeholder shape.
+ */
+
+/** Pre-upload placeholder: the adapter has no URL yet, only the media type. */
+export const imagePlaceholder = (mediaType: string): string => `[Image: ${mediaType}]`;
+
+/** Post-upload text: a markdown image so text-only consumers/models see a real reference. */
+export const imageMarkdown = (mediaType: string, url: string): string => `![${mediaType}](${url})`;
+
+/** Outcome of uploading one image, in adapter emission order. `url` unset β‡’ upload failed/dropped. */
+export interface UploadedImageOutcome {
+ mediaType: string;
+ url?: string;
+}
+
+// Matches an `[Image: <mediaType>]` placeholder. `<mediaType>` never contains `]`.
+const IMAGE_PLACEHOLDER_RE = /\[Image: [^\]]*]/g;
+
+/**
+ * Replace each `[Image: …]` placeholder β€” in the order the adapter emitted them,
+ * which matches `outcomes` β€” with a markdown image for the images that uploaded
+ * successfully. A placeholder whose image failed to upload is left untouched, so
+ * it still signals "an image was here".
+ *
+ * Bails out unchanged when the placeholder count doesn't match `outcomes`: a
+ * mismatch means the tokens can't be safely mapped to images (e.g. the tool
+ * output happened to contain a literal `[Image: …]`), so we don't risk
+ * corrupting the content.
+ */
+export const rewriteImagePlaceholders = (
+ content: string,
+ outcomes: UploadedImageOutcome[],
+): string => {
+ const matches = content.match(IMAGE_PLACEHOLDER_RE);
+ if (!matches || matches.length !== outcomes.length) return content;
+
+ let i = 0;
+ return content.replace(IMAGE_PLACEHOLDER_RE, (original) => {
+ const outcome = outcomes[i++];
+ return outcome?.url ? imageMarkdown(outcome.mediaType, outcome.url) : original;
+ });
+};
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
index 011fe67d0ac..8a72d636024 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { AgentStreamPipeline } from './agentStreamPipeline';
@@ -21,6 +21,37 @@ const ccText = (msgId: string, text: string) =>
type: 'assistant',
})}\n`;
+const ccReadImage = (toolCallId = 'r1') =>
+ `${JSON.stringify({
+ message: {
+ content: [{ id: toolCallId, input: { file_path: 'x.png' }, name: 'Read', type: 'tool_use' }],
+ id: 'msg_read',
+ model: 'claude-sonnet-4-6',
+ role: 'assistant',
+ },
+ type: 'assistant',
+ })}\n${JSON.stringify({
+ message: {
+ content: [
+ {
+ content: [
+ { source: { data: 'AAAA', media_type: 'image/png', type: 'base64' }, type: 'image' },
+ ],
+ tool_use_id: toolCallId,
+ type: 'tool_result',
+ },
+ ],
+ role: 'user',
+ },
+ type: 'user',
+ })}\n`;
+
+const imagesOf = (events: { data?: any; type: string }[]) =>
+ events.find((e) => e.type === 'tool_result')?.data?.pluginState?.images;
+
+const contentOf = (events: { data?: any; type: string }[]) =>
+ events.find((e) => e.type === 'tool_result')?.data?.content;
+
describe('AgentStreamPipeline', () => {
it('runs JSONL β†’ adapter β†’ toStreamEvent and stamps operationId', async () => {
const pipeline = new AgentStreamPipeline({
@@ -145,4 +176,69 @@ describe('AgentStreamPipeline', () => {
expect(Array.isArray(flushed)).toBe(true);
});
+
+ describe('tool_result image upload ()', () => {
+ it('rewrites base64 pluginState.images into uploaded references', async () => {
+ const uploadImage = vi
+ .fn()
+ .mockResolvedValue({ fileId: 'file_1', url: 'https://cdn/x.png' });
+ const pipeline = new AgentStreamPipeline({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ uploadImage,
+ });
+
+ const events = await pipeline.push(init() + ccReadImage());
+
+ expect(uploadImage).toHaveBeenCalledWith({ data: 'AAAA', mediaType: 'image/png' });
+ expect(imagesOf(events)).toEqual([
+ { fileId: 'file_1', mediaType: 'image/png', url: 'https://cdn/x.png' },
+ ]);
+ // Base64 body must never survive into the persisted event.
+ expect(imagesOf(events)![0]).not.toHaveProperty('data');
+ // The `[Image: …]` placeholder is rewritten to a markdown image so a
+ // downstream model knows an image is here (and where).
+ expect(contentOf(events)).toBe('![image/png](https://cdn/x.png)');
+ });
+
+ it('drops the image when no uploader is injected (base64 never persisted)', async () => {
+ const pipeline = new AgentStreamPipeline({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ });
+
+ const events = await pipeline.push(init() + ccReadImage());
+
+ expect(imagesOf(events)).toBeUndefined();
+ });
+
+ it('drops the image and keeps streaming when the uploader throws', async () => {
+ const uploadImage = vi.fn().mockRejectedValue(new Error('boom'));
+ const pipeline = new AgentStreamPipeline({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ uploadImage,
+ });
+
+ const events = await pipeline.push(init() + ccReadImage());
+
+ expect(uploadImage).toHaveBeenCalledTimes(1);
+ expect(imagesOf(events)).toBeUndefined();
+ // The `[Image: …]` placeholder is still the content fallback.
+ expect(events.find((e) => e.type === 'tool_result')?.data?.content).toBe('[Image: image/png]');
+ });
+
+ it('drops the image when the uploader declines (returns undefined)', async () => {
+ const uploadImage = vi.fn().mockResolvedValue(undefined);
+ const pipeline = new AgentStreamPipeline({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ uploadImage,
+ });
+
+ const events = await pipeline.push(init() + ccReadImage());
+
+ expect(imagesOf(events)).toBeUndefined();
+ });
+ });
});
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
index 857646f3ec6..3e70c873573 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
@@ -1,11 +1,30 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { type UploadedImageOutcome, rewriteImagePlaceholders } from '../imageEcho';
import { createAdapter } from '../registry';
-import type { AgentEventAdapter, HeterogeneousAgentEvent, UsageData } from '../types';
+import type {
+ AgentEventAdapter,
+ HeterogeneousAgentEvent,
+ HeterogeneousToolResultImage,
+ UsageData,
+} from '../types';
import { CodexFileChangeTracker } from './codexFileChangeTracker';
import { JsonlStreamProcessor } from './jsonlProcessor';
import { toStreamEvent } from './streamEvent';
+/**
+ * Runtime-side hook that uploads a base64 image echoed by a tool_result to the
+ * file store and returns its reference. Injected by whichever runtime actually
+ * spawns the CLI (desktop main / `lh hetero exec`), because only they hold the
+ * authenticated file-store client. Return `undefined` (or throw) to signal the
+ * upload could not be done β€” the pipeline drops the image and leaves the
+ * `[Image: …]` text placeholder as the fallback.
+ */
+export type UploadHeterogeneousImage = (image: {
+ data: string;
+ mediaType: string;
+}) => Promise<{ fileId: string; url: string } | undefined>;
+
export interface AgentStreamPipelineOptions {
/** Agent type key (e.g. `claude-code`, `codex`). */
agentType: string;
@@ -17,6 +36,12 @@ export interface AgentStreamPipelineOptions {
initialModel?: string | undefined;
/** Operation id to stamp onto every emitted `AgentStreamEvent`. */
operationId: string;
+ /**
+ * Uploader for tool_result images. When omitted, `pluginState.images` base64
+ * entries are dropped (the `[Image: …]` content placeholder is the fallback)
+ * so heavy base64 never reaches persistence.
+ */
+ uploadImage?: UploadHeterogeneousImage;
}
/**
@@ -36,11 +61,13 @@ export class AgentStreamPipeline {
private readonly adapter: AgentEventAdapter;
private readonly operationId: string;
private readonly codexTracker?: CodexFileChangeTracker;
+ private readonly uploadImage?: UploadHeterogeneousImage;
private queuedEvents: AgentStreamEvent[] = [];
constructor(options: AgentStreamPipelineOptions) {
this.adapter = createAdapter(options.agentType);
this.operationId = options.operationId;
+ this.uploadImage = options.uploadImage;
this.codexTracker =
options.agentType === 'codex' ? new CodexFileChangeTracker(options.cwd) : undefined;
@@ -74,7 +101,9 @@ export class AgentStreamPipeline {
*/
async flush(): Promise<AgentStreamEvent[]> {
const trailing = await this.processPayloads(this.processor.flush());
- const flushed = this.adapter.flush().map((event) => toStreamEvent(event, this.operationId));
+ const flushedEvents = this.adapter.flush();
+ await this.uploadResultImages(flushedEvents);
+ const flushed = flushedEvents.map((event) => toStreamEvent(event, this.operationId));
return [...trailing, ...flushed];
}
@@ -95,12 +124,74 @@ export class AgentStreamPipeline {
for (const raw of payloads) {
const payload = this.codexTracker ? await this.codexTracker.track(raw as any) : raw;
- out.push(...this.toStreamEvents(this.adapter.adapt(payload)));
+ const events = this.adapter.adapt(payload);
+ await this.uploadResultImages(events);
+ out.push(...this.toStreamEvents(events));
}
return out;
}
+ /**
+ * Rewrite any `tool_result` `pluginState.images` from base64 into uploaded
+ * `{ fileId, url }` references, mutating the events in place before they are
+ * serialized. Runs on the runtime that spawned the CLI (the only place with
+ * an authenticated file-store client), so the heavy base64 never reaches the
+ * persistence sinks. Uploads that fail β€” or that have no injected uploader β€”
+ * drop the image entry; the `[Image: …]` text placeholder is the fallback.
+ *
+ * On success it also rewrites the matching `[Image: …]` placeholder in the
+ * tool_result `content` into a markdown image, so a downstream model handed
+ * this history (e.g. a summarizer, or continuing the topic on another model)
+ * knows an image is here and where β€” not just an opaque token.
+ */
+ private async uploadResultImages(events: HeterogeneousAgentEvent[]): Promise<void> {
+ for (const event of events) {
+ if (event.type !== 'tool_result') continue;
+ const pluginState = event.data?.pluginState as Record<string, any> | undefined;
+ const images = pluginState?.images as HeterogeneousToolResultImage[] | undefined;
+ if (!images?.length) continue;
+
+ const uploaded: HeterogeneousToolResultImage[] = [];
+ // One entry per original image, in emission order, so the content
+ // placeholders can be rewritten position-for-position (a failed upload
+ // leaves its `url` unset β†’ its placeholder is kept).
+ const outcomes: UploadedImageOutcome[] = [];
+ for (const image of images) {
+ // Already an uploaded reference (or nothing to upload) β€” pass through.
+ if (!image.data || image.fileId) {
+ uploaded.push(image);
+ outcomes.push({ mediaType: image.mediaType, url: image.url });
+ continue;
+ }
+ if (!this.uploadImage) {
+ outcomes.push({ mediaType: image.mediaType });
+ continue;
+ }
+ try {
+ const ref = await this.uploadImage({ data: image.data, mediaType: image.mediaType });
+ // `undefined` β†’ uploader declined; drop the entry rather than persist base64.
+ if (ref) {
+ uploaded.push({ fileId: ref.fileId, mediaType: image.mediaType, url: ref.url });
+ outcomes.push({ mediaType: image.mediaType, url: ref.url });
+ } else {
+ outcomes.push({ mediaType: image.mediaType });
+ }
+ } catch {
+ // Degrade to the `[Image: …]` placeholder rather than failing the stream.
+ outcomes.push({ mediaType: image.mediaType });
+ }
+ }
+
+ if (uploaded.length > 0) pluginState!.images = uploaded;
+ else delete pluginState!.images;
+
+ if (typeof event.data?.content === 'string') {
+ event.data.content = rewriteImagePlaceholders(event.data.content, outcomes);
+ }
+ }
+ }
+
private drainQueuedEvents(): AgentStreamEvent[] {
const events = this.queuedEvents;
this.queuedEvents = [];
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index aa5b241c650..74a3b1113c5 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -13,7 +13,11 @@
* that producers have no business pulling in).
*/
export type { UsageData } from '../types';
-export { AgentStreamPipeline, type AgentStreamPipelineOptions } from './agentStreamPipeline';
+export {
+ AgentStreamPipeline,
+ type AgentStreamPipelineOptions,
+ type UploadHeterogeneousImage,
+} from './agentStreamPipeline';
export { type CliSpawnPlan, resolveCliSpawnPlan } from './cliSpawn';
export { CodexFileChangeTracker } from './codexFileChangeTracker';
export {
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index d0c10abb6ed..feef5d0f8c9 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -3,7 +3,7 @@ import { spawn } from 'node:child_process';
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
-import { AgentStreamPipeline } from './agentStreamPipeline';
+import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';
import { resolveCliSpawnPlan } from './cliSpawn';
import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';
import type { AgentPromptInput, BuildAgentInputOptions } from './input';
@@ -61,6 +61,15 @@ export interface SpawnAgentOptions {
prompt: AgentPromptInput;
/** Resume an existing agent session by its native session id (CC) / thread id (Codex). */
resumeSessionId?: string;
+ /**
+ * Runtime uploader for tool_result images (CC `Read` on an image file). The
+ * adapter emits the raw base64 on `pluginState.images`; the pipeline calls
+ * this to swap each entry for an uploaded `{ fileId, url }` reference before
+ * the event is persisted, so heavy base64 never reaches the ingest sinks.
+ * Omit in standalone/offline runs β€” the pipeline then drops the image and
+ * leaves the `[Image: …]` text placeholder as the fallback.
+ */
+ uploadImage?: UploadHeterogeneousImage;
}
export interface SpawnAgentHandle {
@@ -284,6 +293,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
initialCumulativeUsage,
initialModel,
operationId: options.operationId,
+ uploadImage: options.uploadImage,
});
const stdout = proc.stdout!;
const stderr = proc.stderr!;
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index 7d52500065f..b155f432593 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -200,6 +200,29 @@ export interface ToolEndData {
toolCallId: string;
}
+/**
+ * A single image echoed by a heterogeneous tool_result β€” e.g. CC's `Read` on
+ * an image file, which returns an `image` content block instead of text.
+ *
+ * The adapter synthesizes these onto `pluginState.images` carrying the raw
+ * base64 `data` (it can only see the CLI payload, not the file store). The
+ * runtime-side {@link AgentStreamPipeline} then uploads each one and rewrites
+ * the entry into a `{ fileId, url }` reference, dropping `data` so the heavy
+ * base64 never reaches the persistence sinks / DB. If upload is unavailable or
+ * fails, the entry is dropped and the human-readable `[Image: …]` placeholder
+ * left in `content` is the fallback.
+ */
+export interface HeterogeneousToolResultImage {
+ /** Base64 payload β€” present pre-upload; stripped once `fileId`/`url` are set. */
+ data?: string;
+ /** File record id after upload to the file store. */
+ fileId?: string;
+ /** IANA media type, e.g. `image/png`. */
+ mediaType: string;
+ /** Remote URL after upload. */
+ url?: string;
+}
+
/** Data shape for tool_result events (ACP-specific) */
export interface ToolResultData {
content: string;
@@ -209,6 +232,10 @@ export interface ToolResultData {
* this for tools whose tool_use input *is* the target state (e.g. CC's
* TodoWrite) so consumers can render derived UI from a single message shape,
* without each consumer re-parsing tool args.
+ *
+ * Image-returning tools (CC `Read`) synthesize `pluginState.images` as
+ * {@link HeterogeneousToolResultImage}[] β€” see that type for the base64 β†’
+ * uploaded-reference lifecycle.
*/
pluginState?: Record<string, any>;
/** Subagent context if this tool_result belongs to a subagent inner tool. */
diff --git a/packages/trpc/src/utils/__tests__/internalJwt.test.ts b/packages/trpc/src/utils/__tests__/internalJwt.test.ts
index ddf39f89a49..9b7a01fe3fe 100644
--- a/packages/trpc/src/utils/__tests__/internalJwt.test.ts
+++ b/packages/trpc/src/utils/__tests__/internalJwt.test.ts
@@ -95,6 +95,16 @@ describe('internalJwt', () => {
expect(setIssuedAtMock).toHaveBeenCalled();
});
+
+ it('honors an explicit run-length expiration (e.g. a hetero sandbox run)', async () => {
+ const { signUserJWT } = await import('../internalJwt');
+
+ await signUserJWT('user-abc', '4h');
+
+ expect(setExpirationTimeMock).toHaveBeenCalledWith('4h');
+ // Still a user-scoped token, just longer-lived.
+ expect(SignJWTMock).toHaveBeenCalledWith({ purpose: 'cli-sandbox' });
+ });
});
describe('signOperationJwt', () => {
diff --git a/packages/trpc/src/utils/internalJwt.ts b/packages/trpc/src/utils/internalJwt.ts
index e408e847483..54b3e6eaa6d 100644
--- a/packages/trpc/src/utils/internalJwt.ts
+++ b/packages/trpc/src/utils/internalJwt.ts
@@ -80,18 +80,28 @@ export const signInternalJWT = async (): Promise<string> => {
};
/**
- * Sign a short-lived OIDC-compatible JWT for a given user.
+ * Sign an OIDC-compatible JWT for a given user.
* Used by server-side sandbox execution to authenticate CLI commands.
- * The token contains `sub: userId` and passes standard OIDC JWT validation.
+ * The token contains `sub: userId` and passes standard OIDC JWT validation
+ * (its `cli-sandbox` purpose is accepted by `oidcAuth`, unlike the narrow
+ * `hetero-operation` token), so the sandbox's nested `lh` calls can reach
+ * user-scoped endpoints (e.g. file upload).
+ *
+ * Defaults to a short 5-minute expiry for one-shot command auth; long-running
+ * callers (e.g. a hetero CC/Codex sandbox run that streams for hours) pass a
+ * run-length `expiration` so the token doesn't lapse mid-run.
*/
-export const signUserJWT = async (userId: string): Promise<string> => {
+export const signUserJWT = async (
+ userId: string,
+ expiration: string | number = '5m',
+): Promise<string> => {
const { key, kid } = await getSigningKey();
return new SignJWT({ purpose: 'cli-sandbox' })
.setProtectedHeader({ alg: 'RS256', kid })
.setSubject(userId)
.setIssuedAt()
- .setExpirationTime('5m')
+ .setExpirationTime(expiration)
.sign(key);
};