π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(hetero-agent): support multimodal input across CLI / shared spawn / desktop (#14433)
Arvin Xu10300ba0e14a
diff --git a/apps/cli/man/man1/lh.1 b/apps/cli/man/man1/lh.1index 37a5b05e514..1aa6461a34a 100644--- a/apps/cli/man/man1/lh.1+++ b/apps/cli/man/man1/lh.1@@ -1,6 +1,6 @@.\" Code generated by `npm run man:generate`; DO NOT EDIT..\" Manual command details come from the Commander command tree.-.TH LH 1 "" "@lobehub/cli 0.0.8" "User Commands"+.TH LH 1 "" "@lobehub/cli 0.0.10" "User Commands".SH NAMElh \- LobeHub CLI \- manage and connect to LobeHub services.SH SYNOPSIS@@ -77,6 +77,9 @@ Generate content (text, image, video, speech) Alias: gen..B fileManage files.TP+.B hetero+Run heterogeneous agent CLIs (Claude Code / Codex) and stream their output+.TP.B skillManage agent skills.TPdiff --git a/apps/cli/package.json b/apps/cli/package.jsonindex bacf6446f01..d9bc1792bb0 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -1,6 +1,6 @@{"name": "@lobehub/cli",- "version": "0.0.8",+ "version": "0.0.10","type": "module","bin": {"lh": "./dist/index.js",diff --git a/apps/cli/pnpm-workspace.yaml b/apps/cli/pnpm-workspace.yamlindex fe07df92c18..d6353f9d7ec 100644--- a/apps/cli/pnpm-workspace.yaml+++ b/apps/cli/pnpm-workspace.yaml@@ -3,5 +3,8 @@ packages:- '../../packages/device-gateway-client'- '../../packages/heterogeneous-agents'- '../../packages/local-file-shell'+ - '../../packages/types'+ - '../../packages/model-bank'+ - '../../packages/business/const'- '../../packages/file-loaders'- '.'diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 19f8d1e15fa..d6d9b287721 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -19,9 +19,11 @@ vi.mock('../utils/logger', () => ({}));/**- * Build a fake `SpawnAgentHandle`. The async iterable yields `events`- * synchronously and ends, so the command's `for await (const event of ...)`- * loop terminates without hanging the test.+ * Build a Promise resolving to a fake `SpawnAgentHandle`. `spawnAgent` itself+ * is async, so test mocks return the handle wrapped β same iterable contract,+ * just behind one microtask. The async iterable yields `events` synchronously+ * and ends, so the command's `for await (const event of ...)` loop terminates+ * without hanging the test.*/const createFakeHandle = ({events = [] as any[],@@ -52,13 +54,13 @@ const createFakeHandle = ({},};- return {+ return Promise.resolve({events: eventsIter,exit: Promise.resolve({ code: exitCode, signal }),kill: vi.fn(),pid: 12_345,stderr,- };+ });};describe('hetero exec command', () => {@@ -214,4 +216,129 @@ describe('hetero exec command', () => {await runCmd(['hetero', 'exec', '--type', 'claude-code', '--prompt', 'hi']);expect(exitSpy).toHaveBeenCalledWith(130);});++ it('combines --prompt + --image into mixed content blocks', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'claude-code',+ '--prompt',+ 'describe',+ '--image',+ './fixture-a.png',+ '--image',+ 'https://cdn.example/fixture-b.png',+ ]);++ const call = mockSpawnAgent.mock.calls[0][0];+ expect(Array.isArray(call.prompt)).toBe(true);+ expect(call.prompt).toEqual([+ { text: 'describe', type: 'text' },+ // Path is resolved against process.cwd() β match by suffix to be CI-portable.+ {+ source: expect.objectContaining({ type: 'path' }),+ type: 'image',+ },+ {+ source: { type: 'url', url: 'https://cdn.example/fixture-b.png' },+ type: 'image',+ },+ ]);+ expect(call.prompt[1].source.path).toMatch(/fixture-a\.png$/);+ });++ it('parses a data: URL --image into a base64 source', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ const dataUrl = `data:image/png;base64,${Buffer.from([0x89, 0x50, 0x4e, 0x47]).toString('base64')}`;+ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'claude-code',+ '--prompt',+ 'see',+ '--image',+ dataUrl,+ ]);++ const call = mockSpawnAgent.mock.calls[0][0];+ expect(call.prompt[1]).toEqual({+ source: {+ data: Buffer.from([0x89, 0x50, 0x4e, 0x47]).toString('base64'),+ mediaType: 'image/png',+ type: 'base64',+ },+ type: 'image',+ });+ });++ it('reads multimodal content from --input-json <file>', async () => {+ const { mkdtemp, writeFile, rm } = await import('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const path = await import('node:path');+ const dir = await mkdtemp(`${tmpdir()}/hetero-input-json-`);+ const file = path.join(dir, 'input.json');+ await writeFile(+ file,+ JSON.stringify([+ { text: 'analyze', type: 'text' },+ { source: { type: 'url', url: 'https://x/y.png' }, type: 'image' },+ ]),+ );++ mockSpawnAgent.mockReturnValue(createFakeHandle());+ try {+ await runCmd(['hetero', 'exec', '--type', 'claude-code', '--input-json', file]);+ } finally {+ await rm(dir, { force: true, recursive: true });+ }++ const call = mockSpawnAgent.mock.calls[0][0];+ expect(call.prompt).toEqual([+ { text: 'analyze', type: 'text' },+ { source: { type: 'url', url: 'https://x/y.png' }, type: 'image' },+ ]);+ });++ it('reports spawnAgent rejections (e.g. missing --image path) as a clean error + exit(1)', async () => {+ // spawnAgent is now async and can reject during image normalization β+ // missing local --image paths, fetch failures, etc. The CLI must catch+ // these and exit with a friendly message instead of crashing on an+ // unhandled rejection.+ mockSpawnAgent.mockReturnValue(+ Promise.reject(new Error('ENOENT: no such file or directory, open /missing.png')),+ );++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'claude-code',+ '--prompt',+ 'see',+ '--image',+ '/missing.png',+ ]);++ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('rejects --prompt + --input-json (mutually exclusive)', async () => {+ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'claude-code',+ '--prompt',+ 'hi',+ '--input-json',+ '/tmp/bogus.json',+ ]);+ expect(exitSpy).toHaveBeenCalledWith(2);+ expect(mockSpawnAgent).not.toHaveBeenCalled();+ });});diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex a613c5dd429..ffc04653b7f 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -1,5 +1,12 @@import { randomUUID } from 'node:crypto';+import { readFile } from 'node:fs/promises';+import path from 'node:path';+import type {+ AgentContentBlock,+ AgentImageSource,+ AgentPromptInput,+} from '@lobechat/heterogeneous-agents/spawn';import { spawnAgent } from '@lobechat/heterogeneous-agents/spawn';import type { Command } from 'commander';@@ -10,16 +17,16 @@ const SUPPORTED_AGENT_TYPES = new Set(['claude-code', 'codex']);interface ExecOptions {command?: string;cwd?: string;+ image?: string[];+ inputJson?: string;operationId?: string;prompt?: string;resume?: string;type: string;}-/**- * Read all of stdin to a string. Used when `--prompt -` (or `--prompt` is- * omitted) to pull the user prompt from a pipe / heredoc.- */+const collectImage = (value: string, previous: string[] = []): string[] => [...previous, value];+const readStdin = async (): Promise<string> => {const chunks: Buffer[] = [];for await (const chunk of process.stdin) {@@ -28,9 +35,117 @@ const readStdin = async (): Promise<string> => {return Buffer.concat(chunks).toString('utf8');};-const resolvePrompt = async (raw: string | undefined): Promise<string> => {- if (raw === undefined || raw === '-') return readStdin();- return raw;+/**+ * Resolve a raw `--input-json` argument: `'-'` (or empty) reads stdin, anything+ * else is treated as a filesystem path.+ */+const readInputJson = async (location: string): Promise<string> => {+ if (location === '-' || location === '') return readStdin();+ return readFile(location, 'utf8');+};++const looksLikeJsonInput = (value: string): boolean => {+ const trimmed = value.trimStart();+ return trimmed.startsWith('{') || trimmed.startsWith('[');+};++/**+ * Convert an `--image <value>` argument into an image source. Recognized+ * shapes: `https?://...` URL, `data:` URL, otherwise a filesystem path+ * resolved relative to the CLI's cwd.+ */+const parseImageArg = (value: string): AgentImageSource => {+ if (/^https?:\/\//i.test(value)) return { type: 'url', url: value };+ if (value.startsWith('data:')) {+ const match = value.match(/^data:([^;,]+);base64,(.+)$/);+ if (!match) {+ throw new Error(`Invalid data URL for --image: ${value.slice(0, 40)}β¦`);+ }+ return { data: match[2]!, mediaType: match[1]!, type: 'base64' };+ }+ return { path: path.resolve(process.cwd(), value), type: 'path' };+};++/**+ * Best-effort coercion of a JSON-decoded value into an `AgentPromptInput`.+ * Accepts:+ * - `'plain text'` β single text block+ * - `[{ type: 'text', text }, { type: 'image', source }]` β content blocks+ * - `{ content: [...] }` (Anthropic message shape) β unwraps `content`+ * - `{ type: 'text', ... } | { type: 'image', ... }` β single block+ */+const coerceJsonPrompt = (parsed: unknown): AgentPromptInput => {+ if (typeof parsed === 'string') return parsed;+ if (Array.isArray(parsed)) return parsed as AgentContentBlock[];+ if (parsed && typeof parsed === 'object') {+ const obj = parsed as Record<string, unknown>;+ if (Array.isArray(obj.content)) return obj.content as AgentContentBlock[];+ if (obj.type === 'text' || obj.type === 'image') return [obj as AgentContentBlock];+ }+ throw new Error(+ 'Invalid --input-json shape: expected a string, array of content blocks, ' ++ 'or `{ content: [...] }` envelope.',+ );+};++interface ResolvedPrompt {+ /** Human-readable description for the empty-input check. */+ describe: () => string;+ prompt: AgentPromptInput;+}++const buildPromptFromText = (text: string, images: string[]): ResolvedPrompt => {+ if (images.length === 0) {+ return { describe: () => text.trim(), prompt: text };+ }+ const blocks: AgentContentBlock[] = [];+ if (text.length > 0) blocks.push({ text, type: 'text' });+ for (const image of images) {+ blocks.push({ source: parseImageArg(image), type: 'image' });+ }+ return {+ describe: () =>+ blocks+ .map((b) => (b.type === 'text' ? b.text.trim() : '[image]'))+ .filter(Boolean)+ .join(' ')+ .trim(),+ prompt: blocks,+ };+};++/**+ * Decide which input mode the user requested and produce a unified prompt.+ *+ * Mode resolution (mutually exclusive):+ * 1. `--input-json` β read JSON file or stdin, parse to content blocks+ * 2. `--prompt` (with optional `--image` flags) β text + images+ * 3. (default) read stdin: auto-detect JSON vs plain text by first char+ */+const resolvePrompt = async (options: ExecOptions): Promise<ResolvedPrompt> => {+ const images = options.image ?? [];++ if (options.inputJson !== undefined) {+ if (options.prompt !== undefined) {+ throw new Error('--prompt and --input-json are mutually exclusive.');+ }+ if (images.length > 0) {+ throw new Error('--image cannot be combined with --input-json (put images in the JSON).');+ }+ const raw = await readInputJson(options.inputJson);+ return { describe: () => raw.trim(), prompt: coerceJsonPrompt(JSON.parse(raw)) };+ }++ if (options.prompt !== undefined && options.prompt !== '-') {+ return buildPromptFromText(options.prompt, images);+ }++ // No --prompt or --prompt -: read stdin and auto-detect.+ const raw = await readStdin();+ if (looksLikeJsonInput(raw)) {+ return { describe: () => raw.trim(), prompt: coerceJsonPrompt(JSON.parse(raw)) };+ }+ return buildPromptFromText(raw, images);};const exec = async (options: ExecOptions): Promise<void> => {@@ -41,9 +156,18 @@ const exec = async (options: ExecOptions): Promise<void> => {process.exit(2);}- const prompt = await resolvePrompt(options.prompt);- if (!prompt.trim()) {- log.error('Empty prompt. Pass --prompt <text> or pipe content via stdin.');+ let resolved: ResolvedPrompt;+ try {+ resolved = await resolvePrompt(options);+ } catch (err) {+ log.error(err instanceof Error ? err.message : String(err));+ process.exit(2);+ }++ if (!resolved.describe()) {+ log.error(+ 'Empty prompt. Pass --prompt <text>, --image <path>, --input-json <file|->, or pipe content via stdin.',+ );process.exit(2);}@@ -53,14 +177,24 @@ const exec = async (options: ExecOptions): Promise<void> => {// server-allocated id.const operationId = options.operationId || randomUUID();- const handle = spawnAgent({- agentType: options.type,- command: options.command,- cwd: options.cwd || process.cwd(),- operationId,- prompt,- resumeSessionId: options.resume,- });+ // `spawnAgent` is async and can reject DURING image normalization β fetch+ // failures, missing local --image paths, decode errors. Surface those as a+ // clean error + exit code instead of an unhandled promise rejection / stack+ // trace, mirroring the validation try/catch above.+ let handle: Awaited<ReturnType<typeof spawnAgent>>;+ try {+ handle = await spawnAgent({+ agentType: options.type,+ command: options.command,+ cwd: options.cwd || process.cwd(),+ operationId,+ prompt: resolved.prompt,+ resumeSessionId: options.resume,+ });+ } catch (err) {+ log.error('Failed to start agent:', err instanceof Error ? err.message : String(err));+ process.exit(1);+ }// Forward the child's stderr to ours so users see CLI errors / warnings// (auth prompts, missing-binary errors, etc.) in the terminal.@@ -117,6 +251,15 @@ export function registerHeteroCommand(program: Command) {).requiredOption('-t, --type <type>', `Agent type: ${[...SUPPORTED_AGENT_TYPES].join(' | ')}`).option('-p, --prompt [text]', 'Prompt text. Pass `-` (or omit the value) to read from stdin.')+ .option(+ '-i, --image <path|url>',+ 'Attach an image (repeatable). Accepts a local path, http(s) URL, or data: URL.',+ collectImage,+ )+ .option(+ '--input-json <path>',+ 'Read full multimodal prompt as JSON content blocks from a file. Use `-` for stdin.',+ ).option('-r, --resume <sessionId>', 'Resume an existing agent session by its native id').option('-d, --cwd <path>', 'Working directory for the spawned agent (default: process.cwd())').option(diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 57e1bade824..b9306979207 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -1,7 +1,7 @@import type { ChildProcess } from 'node:child_process';import { spawn } from 'node:child_process';-import { createHash, randomUUID } from 'node:crypto';-import { access, appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';+import { randomUUID } from 'node:crypto';+import { access, appendFile, mkdir, writeFile } from 'node:fs/promises';import path from 'node:path';import type { Readable, Writable } from 'node:stream';import { finished as streamFinished } from 'node:stream/promises';@@ -14,7 +14,13 @@ import {CODEX_CLI_INSTALL_DOCS_URL,HeterogeneousAgentSessionErrorCode,} from '@lobechat/electron-client-ipc';-import { AgentStreamPipeline } from '@lobechat/heterogeneous-agents/spawn';+import type { AgentContentBlock } from '@lobechat/heterogeneous-agents/spawn';+import {+ AgentStreamPipeline,+ buildAgentInput,+ materializeImageToPath,+ normalizeImage,+} from '@lobechat/heterogeneous-agents/spawn';import { app as electronApp, BrowserWindow } from 'electron';import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';@@ -50,16 +56,6 @@ const CODEX_RESUME_CWD_MISMATCH_PATTERNS = [/** Directory under appStoragePath for caching downloaded files */const FILE_CACHE_DIR = 'heteroAgent/files';const CLI_TRACE_DIR = '.heerogeneous-tracing';-const IMAGE_EXTENSIONS_BY_MIME = {- 'image/gif': '.gif',- 'image/jpg': '.jpg',- 'image/jpeg': '.jpg',- 'image/pjpeg': '.jpg',- 'image/png': '.png',- 'image/webp': '.webp',- 'image/x-png': '.png',-} as const satisfies Record<string, string>;-const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);const CODEX_STDERR_STATUS_LINE = 'Reading prompt from stdin...';const CODEX_WARN_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+WARN\s+/;const CODEX_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+(?:DEBUG|ERROR|INFO|TRACE|WARN)\s+/;@@ -578,125 +574,56 @@ export default class HeterogeneousAgentCtr extends ControllerModule {}/**- * Derive a filesystem-safe cache key for attachments.- *- * Never use the raw image id as a path segment β upstream callers can persist- * arbitrary ids and path.join would treat traversal sequences as real- * directories. A stable hash preserves cache hits without trusting the id as a- * filename.+ * Convert a desktop image attachment list into shared content blocks. Each+ * attachment's id is preserved as the cache key so repeated prompts hit the+ * same on-disk entries.*/- private getImageCacheKey(imageId: string): string {- return createHash('sha256').update(imageId).digest('hex');+ private toImageContentBlocks(+ imageList: HeterogeneousAgentImageAttachment[],+ ): AgentContentBlock[] {+ return imageList.map((image) => ({+ source: { id: image.id, type: 'url', url: image.url },+ type: 'image',+ }));}/**- * Download an image by URL, with local disk cache keyed by id.+ * Build a Claude Code stream-json user message with text + base64 images.+ * Delegates to the shared `buildAgentInput`; the desktop wrapper exists only+ * to preserve the helper signature consumed by existing drivers.*/- private async resolveImage(- image: HeterogeneousAgentImageAttachment,- ): Promise<{ buffer: Buffer; mimeType: string }> {- const cacheDir = this.fileCacheDir;- const cacheKey = this.getImageCacheKey(image.id);- const metaPath = path.join(cacheDir, `${cacheKey}.meta`);- const dataPath = path.join(cacheDir, cacheKey);-- // Check cache first- try {- const metaRaw = await readFile(metaPath, 'utf8');- const meta = JSON.parse(metaRaw);- const buffer = await readFile(dataPath);- logger.debug('Image cache hit:', image.id);- return { buffer, mimeType: meta.mimeType || 'image/png' };- } catch {- // Cache miss β download- }-- logger.info('Downloading image:', image.id);-- const res = await fetch(image.url);- if (!res.ok)- throw new Error(`Failed to download image ${image.id}: ${res.status} ${res.statusText}`);-- const arrayBuffer = await res.arrayBuffer();- const buffer = Buffer.from(arrayBuffer);- const mimeType = res.headers.get('content-type') || 'image/png';-- // Write to cache- await mkdir(cacheDir, { recursive: true });- await writeFile(dataPath, buffer);- await writeFile(metaPath, JSON.stringify({ id: image.id, mimeType }));- logger.debug('Image cached:', image.id, `${buffer.length} bytes`);-- return { buffer, mimeType };- }-- private normalizeMimeType(mimeType: string): string {- return mimeType.split(';')[0]?.trim().toLowerCase() || '';- }-- private guessImageExtensionByBuffer(buffer: Buffer): string | undefined {- if (buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) return '.png';- if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) return '.jpg';-- const gifSignature = buffer.subarray(0, 6).toString('ascii');- if (gifSignature === 'GIF87a' || gifSignature === 'GIF89a') return '.gif';-- if (- buffer.subarray(0, 4).toString('ascii') === 'RIFF' &&- buffer.subarray(8, 12).toString('ascii') === 'WEBP'- ) {- return '.webp';- }- }-- private guessImageExtension(- mimeType: string,- image: HeterogeneousAgentImageAttachment,- buffer: Buffer,- ): string | undefined {- const knownByMime = IMAGE_EXTENSIONS_BY_MIME[this.normalizeMimeType(mimeType)];- if (knownByMime) return knownByMime;-- try {- const pathname = new URL(image.url).pathname;- const ext = path.extname(pathname).toLowerCase();- if (ext) return ext === '.jpeg' ? '.jpg' : ext;- } catch {- // Fall through to byte sniffing below.- }+ private async buildStreamJsonInput(+ prompt: string,+ imageList: HeterogeneousAgentImageAttachment[] = [],+ ): Promise<string> {+ const blocks: AgentContentBlock[] = [];+ if (prompt && prompt.length > 0) blocks.push({ text: prompt, type: 'text' });+ blocks.push(...this.toImageContentBlocks(imageList));- return this.guessImageExtensionByBuffer(buffer);+ const plan = await buildAgentInput('claude-code', blocks, { cacheDir: this.fileCacheDir });+ return plan.stdin;}/**- * Materialize an image attachment into a stable local file path so CLIs like- * Codex can consume it through `--image <file>`.+ * Materialize image attachments into stable filesystem paths for path-mode+ * agents (Codex `--image <file>`). Fails the prompt if any image cannot be+ * fetched / decoded β partially-attached prompts confuse the agent more+ * than they help.*/- private async resolveCliImagePath(image: HeterogeneousAgentImageAttachment): Promise<string> {- const { buffer, mimeType } = await this.resolveImage(image);- const cacheKey = this.getImageCacheKey(image.id);- const ext = this.guessImageExtension(mimeType, image, buffer);- if (!ext) {- throw new Error(`Unsupported image type for ${image.id}`);- }-- const filePath = path.join(this.fileCacheDir, `${cacheKey}${ext}`);-- try {- await access(filePath);- } catch {- await mkdir(this.fileCacheDir, { recursive: true });- await writeFile(filePath, buffer);- }-- return filePath;- }-private async resolveCliImagePaths(imageList: HeterogeneousAgentImageAttachment[] = [],): Promise<string[]> {+ if (imageList.length === 0) return [];++ const cacheDir = this.fileCacheDir;const results = await Promise.allSettled(- imageList.map((image) => this.resolveCliImagePath(image)),+ imageList.map(async (image) => {+ const normalized = await normalizeImage(+ { id: image.id, type: 'url', url: image.url },+ { cacheDir },+ );+ return materializeImageToPath(normalized, cacheDir);+ }),);const imagePaths: string[] = [];@@ -722,38 +649,6 @@ export default class HeterogeneousAgentCtr extends ControllerModule {return imagePaths;}- /**- * Build a stream-json user message with text + optional image content blocks.- */- private async buildStreamJsonInput(- prompt: string,- imageList: HeterogeneousAgentImageAttachment[] = [],- ): Promise<string> {- const content: any[] = [];- if (prompt && prompt.length > 0) content.push({ text: prompt, type: 'text' });-- for (const image of imageList) {- try {- const { buffer, mimeType } = await this.resolveImage(image);- content.push({- source: {- data: buffer.toString('base64'),- media_type: mimeType,- type: 'base64',- },- type: 'image',- });- } catch (err) {- logger.error(`Failed to resolve image ${image.id}:`, err);- }- }-- return `${JSON.stringify({- message: { content, role: 'user' },- type: 'user',- })}\n`;- }-// βββ IPC methods βββ/**diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 61f403dfe09..cf4f56da470 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -118,13 +118,24 @@ describe('HeterogeneousAgentCtr', () => {await rm(appStoragePath, { force: true, recursive: true });});- describe('resolveImage', () => {+ describe('image cache (delegates to shared `normalizeImage`)', () => {+ // Image fetch + cache moved to `@lobechat/heterogeneous-agents/spawn`'s+ // `normalizeImage`. The desktop controller passes its own cacheDir so the+ // path-traversal invariant β id segments like `../../foo` MUST be hashed,+ // never used as path segments β is enforced by the shared helper. Verify+ // that invariant against the same cacheDir the controller would use.+ const fixtureCacheDir = (storage: string) => path.join(storage, 'heteroAgent/files');+ const importNormalize = async () => {+ const { mkdir } = await import('node:fs/promises');+ const mod = await import('@lobechat/heterogeneous-agents/spawn');+ return { mkdir, normalizeImage: mod.normalizeImage };+ };+it('stores traversal-looking ids inside the cache root via a stable hash key', async () => {- const ctr = new HeterogeneousAgentCtr({- appStoragePath,- storeManager: { get: vi.fn() },- } as any);- const cacheDir = path.join(appStoragePath, 'heteroAgent/files');+ const { mkdir, normalizeImage } = await importNormalize();+ const cacheDir = fixtureCacheDir(appStoragePath);+ await mkdir(cacheDir, { recursive: true });+const escapedTargetName = `${path.basename(appStoragePath)}-outside-storage`;const escapePath = path.join(cacheDir, `../../../${escapedTargetName}`);@@ -134,10 +145,14 @@ describe('HeterogeneousAgentCtr', () => {// best-effort cleanup}- await (ctr as any).resolveImage({- id: `../../../${escapedTargetName}`,- url: 'data:text/plain;base64,T1VUU0lERQ==',- });+ await normalizeImage(+ {+ id: `../../../${escapedTargetName}`,+ type: 'url',+ url: 'data:text/plain;base64,T1VUU0lERQ==',+ },+ { cacheDir, fetcher: (async () => new Response('OUTSIDE', { status: 200 })) as any },+ );const cacheEntries = await readdir(cacheDir);@@ -153,11 +168,10 @@ describe('HeterogeneousAgentCtr', () => {});it('does not trust pre-seeded out-of-root traversal cache files as cache hits', async () => {- const ctr = new HeterogeneousAgentCtr({- appStoragePath,- storeManager: { get: vi.fn() },- } as any);- const cacheDir = path.join(appStoragePath, 'heteroAgent/files');+ const { mkdir, normalizeImage } = await importNormalize();+ const cacheDir = fixtureCacheDir(appStoragePath);+ await mkdir(cacheDir, { recursive: true });+const traversalId = '../../preexisting-secret';const outOfRootDataPath = path.join(cacheDir, traversalId);const outOfRootMetaPath = path.join(cacheDir, `${traversalId}.meta`);@@ -168,13 +182,20 @@ describe('HeterogeneousAgentCtr', () => {JSON.stringify({ id: traversalId, mimeType: 'text/plain' }),);- const result = await (ctr as any).resolveImage({- id: traversalId,- url: 'data:text/plain;base64,SUdOT1JFRA==',- });+ const result = await normalizeImage(+ { id: traversalId, type: 'url', url: 'data:text/plain;base64,SUdOT1JFRA==' },+ {+ cacheDir,+ fetcher: (async () =>+ new Response('IGNORED', {+ headers: { 'content-type': 'text/plain' },+ status: 200,+ })) as any,+ },+ );expect(Buffer.from(result.buffer).toString('utf8')).toBe('IGNORED');- expect(result.mimeType).toBe('text/plain');+ expect(result.mediaType).toBe('text/plain');await expect(readFile(outOfRootDataPath, 'utf8')).resolves.toBe('SECRET');});});diff --git a/packages/builtin-tools/src/github/RunCommandInspector.tsx b/packages/builtin-tools/src/github/RunCommandInspector.tsxindex b04d7c4d000..e82ebca8554 100644--- a/packages/builtin-tools/src/github/RunCommandInspector.tsx+++ b/packages/builtin-tools/src/github/RunCommandInspector.tsx@@ -58,7 +58,9 @@ const GithubRunCommandInspector = memo<BuiltinInspectorProps<GithubRunCommandArgs, GithubRunCommandState>>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {const command = args?.command || partialArgs?.command || '';+ const description = args?.description || partialArgs?.description || '';const subcommand = getGhSubcommand(command);+ const label = description || subcommand;const pulse = isArgumentsStreaming || isLoading;const isSuccess = pluginState?.success ?? pluginState?.exitCode === 0;@@ -68,9 +70,9 @@ const GithubRunCommandInspector = memo<<div className={cx(inspectorTextStyles.root, pulse && shinyTextStyles.shinyText)}><Github className={styles.icon} size={14} /><span className={styles.ghPrefix}>gh</span>- {subcommand && (+ {label && (<span className={styles.chip}>- <span className={styles.command}>{subcommand}</span>+ <span className={styles.command}>{label}</span></span>)}{hasResult ? (diff --git a/packages/builtin-tools/src/github/RunCommandRender.tsx b/packages/builtin-tools/src/github/RunCommandRender.tsxindex 373aa51f7f4..0424c65f49c 100644--- a/packages/builtin-tools/src/github/RunCommandRender.tsx+++ b/packages/builtin-tools/src/github/RunCommandRender.tsx@@ -62,8 +62,10 @@ const GithubRunCommandRender = memo<BuiltinRenderProps<GithubRunCommandArgs, GithubRunCommandState>>(({ args, content, pluginState }) => {const rawCommand = args?.command || '';+ const description = args?.description || '';const normalized = normalizeGhCommand(rawCommand);const subcommand = getGhSubcommand(rawCommand);+ const headerLabel = description || subcommand || normalized || 'command';const output = getGithubOutput(pluginState, content);const stderr = pluginState?.stderr || '';@@ -87,7 +89,7 @@ const GithubRunCommandRender = memo<header={<Flexbox horizontal align={'center'} className={styles.headerRow} wrap={'wrap'}><span className={styles.ghPrefix}>gh</span>- <span className={styles.headerCommand}>{subcommand || normalized || 'command'}</span>+ <span className={styles.headerCommand}>{headerLabel}</span>{success !== undefined && (<spanclassName={`${styles.exitCode} ${diff --git a/packages/builtin-tools/src/github/utils.ts b/packages/builtin-tools/src/github/utils.tsindex 42b8e3d94f2..ce041fe1740 100644--- a/packages/builtin-tools/src/github/utils.ts+++ b/packages/builtin-tools/src/github/utils.ts@@ -2,6 +2,7 @@export interface GithubRunCommandArgs {command?: string;+ description?: string;}export interface GithubRunCommandState {diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex 49b40563fee..3b1ad4fde0d 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -14,6 +14,20 @@*/export { AgentStreamPipeline, type AgentStreamPipelineOptions } from './agentStreamPipeline';export { CodexFileChangeTracker } from './codexFileChangeTracker';+export {+ type AgentContentBlock,+ type AgentImageBlock,+ type AgentImageSource,+ type AgentInputPlan,+ type AgentPromptInput,+ type AgentTextBlock,+ buildAgentInput,+ type BuildAgentInputOptions,+ materializeImageToPath,+ type NormalizedImage,+ normalizeImage,+ type NormalizeImageOptions,+} from './input';export { JsonlStreamProcessor } from './jsonlProcessor';export { spawnAgent, type SpawnAgentHandle, type SpawnAgentOptions } from './spawnAgent';export { toStreamEvent } from './streamEvent';diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.tsnew file mode 100644index 00000000000..b217fb27492--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts@@ -0,0 +1,217 @@+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { buildAgentInput } from './buildAgentInput';++const PNG_BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x10]);++describe('buildAgentInput', () => {+ let tmp: string;++ beforeEach(async () => {+ tmp = await mkdtemp(path.join(tmpdir(), 'build-agent-input-'));+ });++ afterEach(async () => {+ await rm(tmp, { force: true, recursive: true });+ vi.restoreAllMocks();+ });++ describe('claude-code', () => {+ it('wraps a plain-string prompt as a single text block in stream-json', async () => {+ const plan = await buildAgentInput('claude-code', 'hello world');+ expect(plan.args).toEqual([]);+ const msg = JSON.parse(plan.stdin.trim());+ expect(msg).toEqual({+ message: { content: [{ text: 'hello world', type: 'text' }], role: 'user' },+ type: 'user',+ });+ });++ it('preserves user-specified content-block order', async () => {+ const plan = await buildAgentInput('claude-code', [+ {+ source: { data: PNG_BYTES.toString('base64'), mediaType: 'image/png', type: 'base64' },+ type: 'image',+ },+ { text: 'after', type: 'text' },+ ]);+ const msg = JSON.parse(plan.stdin.trim());+ expect(msg.message.content.map((b: any) => b.type)).toEqual(['image', 'text']);+ });++ it('inlines base64 image bytes with the correct media_type field', async () => {+ const plan = await buildAgentInput('claude-code', [+ { text: 'see', type: 'text' },+ {+ source: { data: PNG_BYTES.toString('base64'), mediaType: 'image/png', type: 'base64' },+ type: 'image',+ },+ ]);+ const msg = JSON.parse(plan.stdin.trim());+ expect(msg.message.content[1]).toEqual({+ source: {+ data: PNG_BYTES.toString('base64'),+ media_type: 'image/png',+ type: 'base64',+ },+ type: 'image',+ });+ });++ it('reads a path source from disk and inlines as base64', async () => {+ const filePath = path.join(tmp, 'fixture.png');+ await writeFile(filePath, PNG_BYTES);++ const plan = await buildAgentInput('claude-code', [+ { source: { path: filePath, type: 'path' }, type: 'image' },+ ]);+ const msg = JSON.parse(plan.stdin.trim());+ expect(msg.message.content[0]).toEqual({+ source: {+ data: PNG_BYTES.toString('base64'),+ media_type: 'image/png',+ type: 'base64',+ },+ type: 'image',+ });+ });++ it('falls back to byte sniffing when the URL response Content-Type is generic (octet-stream)', async () => {+ // CDNs / object stores commonly default to application/octet-stream when+ // they strip the original Content-Type. Trusting that header verbatim+ // would serialize `media_type: "application/octet-stream"` into stream-+ // json, which Claude API rejects β sniff the bytes instead.+ const fetcher = vi.fn(+ async () =>+ new Response(PNG_BYTES, {+ headers: { 'content-type': 'application/octet-stream' },+ status: 200,+ }),+ ) as unknown as typeof fetch;++ const plan = await buildAgentInput(+ 'claude-code',+ [{ source: { type: 'url', url: 'https://x/y' }, type: 'image' }],+ { fetcher },+ );+ const msg = JSON.parse(plan.stdin.trim());+ expect(msg.message.content[0].source.media_type).toBe('image/png');+ });++ it('upgrades a base64 source declared as octet-stream to its sniffed image type', async () => {+ const plan = await buildAgentInput('claude-code', [+ {+ source: {+ data: PNG_BYTES.toString('base64'),+ mediaType: 'application/octet-stream',+ type: 'base64',+ },+ type: 'image',+ },+ ]);+ const msg = JSON.parse(plan.stdin.trim());+ expect(msg.message.content[0].source.media_type).toBe('image/png');+ });++ it('prefers the URL extension hint over a generic Content-Type header', async () => {+ const fetcher = vi.fn(+ async () =>+ // No content-type at all + bytes are unrecognized β but URL has .jpg.+ new Response(Buffer.from('garbage'), {+ headers: { 'content-type': 'application/octet-stream' },+ status: 200,+ }),+ ) as unknown as typeof fetch;++ const plan = await buildAgentInput(+ 'claude-code',+ [{ source: { type: 'url', url: 'https://x/photo.jpg' }, type: 'image' }],+ { fetcher },+ );+ const msg = JSON.parse(plan.stdin.trim());+ expect(msg.message.content[0].source.media_type).toBe('image/jpeg');+ });++ it('fetches a URL via the injected fetcher and caches the bytes when cacheDir is set', async () => {+ const fetcher = vi.fn(+ async () =>+ new Response(PNG_BYTES, { headers: { 'content-type': 'image/png' }, status: 200 }),+ ) as unknown as typeof fetch;++ const plan = await buildAgentInput(+ 'claude-code',+ [{ source: { id: 'img-1', type: 'url', url: 'https://x/y.png' }, type: 'image' }],+ { cacheDir: tmp, fetcher },+ );+ const msg = JSON.parse(plan.stdin.trim());+ expect(msg.message.content[0].source.data).toBe(PNG_BYTES.toString('base64'));+ expect(fetcher).toHaveBeenCalledTimes(1);++ // Second call hits the disk cache β fetcher must not be invoked again.+ await buildAgentInput(+ 'claude-code',+ [{ source: { id: 'img-1', type: 'url', url: 'https://x/y.png' }, type: 'image' }],+ { cacheDir: tmp, fetcher },+ );+ expect(fetcher).toHaveBeenCalledTimes(1);+ });+ });++ describe('codex', () => {+ it('puts text on stdin and emits no --image flags when there are no images', async () => {+ const plan = await buildAgentInput('codex', 'just text');+ expect(plan.stdin).toBe('just text');+ expect(plan.args).toEqual([]);+ });++ it('joins multiple text blocks with double newlines on stdin', async () => {+ const plan = await buildAgentInput('codex', [+ { text: 'first', type: 'text' },+ { text: 'second', type: 'text' },+ ]);+ expect(plan.stdin).toBe('first\n\nsecond');+ });++ it('materializes base64 images into cacheDir and emits --image <path> per image', async () => {+ const plan = await buildAgentInput(+ 'codex',+ [+ { text: 'inspect', type: 'text' },+ {+ source: { data: PNG_BYTES.toString('base64'), mediaType: 'image/png', type: 'base64' },+ type: 'image',+ },+ ],+ { cacheDir: tmp },+ );++ expect(plan.stdin).toBe('inspect');+ expect(plan.args[0]).toBe('--image');+ const imagePath = plan.args[1]!;+ expect(imagePath.startsWith(tmp)).toBe(true);+ expect(imagePath.endsWith('.png')).toBe(true);+ const written = await readFile(imagePath);+ expect(written.equals(PNG_BYTES)).toBe(true);+ });++ it('passes a path-source image straight through without re-materializing', async () => {+ const filePath = path.join(tmp, 'on-disk.png');+ await writeFile(filePath, PNG_BYTES);++ const plan = await buildAgentInput(+ 'codex',+ [{ source: { path: filePath, type: 'path' }, type: 'image' }],+ { cacheDir: tmp },+ );+ expect(plan.args).toEqual(['--image', filePath]);+ });+ });++ it('throws on unknown agent types', async () => {+ await expect(buildAgentInput('kimi-cli', 'hi')).rejects.toThrow(/unsupported agent type/);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.tsnew file mode 100644index 00000000000..90f3ea7244a--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts@@ -0,0 +1,141 @@+import { tmpdir } from 'node:os';+import path from 'node:path';++import type { NormalizedImage, NormalizeImageOptions } from './normalizeImage';+import { materializeImageToPath, normalizeImage } from './normalizeImage';+import type { AgentContentBlock, AgentImageBlock, AgentPromptInput, AgentTextBlock } from './types';++export interface BuildAgentInputOptions extends NormalizeImageOptions {+ /**+ * Directory used to materialize images for path-based agents (Codex). When+ * unset, falls back to `cacheDir`, then to a per-agent subdirectory under+ * the OS tmpdir. Path-input images skip materialization entirely.+ */+ imageMaterializeDir?: string;+}++/**+ * Result of preparing input for a child agent process.+ *+ * `args` is appended to the agent's CLI argv (e.g. Codex `--image <path>`+ * pairs); `stdin` is the payload written to the child's stdin (stream-json+ * for Claude Code, raw text for Codex).+ */+export interface AgentInputPlan {+ args: string[];+ stdin: string;+}++const toBlocks = (input: AgentPromptInput): AgentContentBlock[] => {+ if (typeof input === 'string') return input ? [{ text: input, type: 'text' }] : [];+ return input;+};++const isTextBlock = (b: AgentContentBlock): b is AgentTextBlock => b.type === 'text';+const isImageBlock = (b: AgentContentBlock): b is AgentImageBlock => b.type === 'image';++const collectText = (blocks: AgentContentBlock[]): string =>+ blocks+ .filter(isTextBlock)+ .map((b) => b.text)+ .filter((t) => t.length > 0)+ .join('\n\n');++const buildClaudeCodeStdin = async (+ blocks: AgentContentBlock[],+ options: BuildAgentInputOptions,+): Promise<AgentInputPlan> => {+ const content: Array<+ | { text: string; type: 'text' }+ | { source: { data: string; media_type: string; type: 'base64' }; type: 'image' }+ > = [];++ for (const block of blocks) {+ if (isTextBlock(block)) {+ if (block.text.length > 0) content.push({ text: block.text, type: 'text' });+ continue;+ }+ if (isImageBlock(block)) {+ const image = await normalizeImage(block.source, options);+ content.push({+ source: {+ data: image.buffer.toString('base64'),+ media_type: image.mediaType,+ type: 'base64',+ },+ type: 'image',+ });+ }+ }++ return {+ args: [],+ stdin: `${JSON.stringify({+ message: { content, role: 'user' },+ type: 'user',+ })}\n`,+ };+};++const resolveCodexImagePaths = async (+ blocks: AgentContentBlock[],+ options: BuildAgentInputOptions,+): Promise<string[]> => {+ const imageBlocks = blocks.filter(isImageBlock);+ if (imageBlocks.length === 0) return [];++ const materializeDir =+ options.imageMaterializeDir ||+ options.cacheDir ||+ path.join(tmpdir(), 'lobehub-hetero-agent-images');++ const normalized: NormalizedImage[] = await Promise.all(+ imageBlocks.map((b) => normalizeImage(b.source, options)),+ );++ return Promise.all(normalized.map((img) => materializeImageToPath(img, materializeDir)));+};++const buildCodexInput = async (+ blocks: AgentContentBlock[],+ options: BuildAgentInputOptions,+): Promise<AgentInputPlan> => {+ const text = collectText(blocks);+ const imagePaths = await resolveCodexImagePaths(blocks, options);++ return {+ args: imagePaths.flatMap((p) => ['--image', p]),+ stdin: text,+ };+};++/**+ * Convert a unified `AgentPromptInput` into the per-agent stdin payload + any+ * extra CLI args required to attach images. The single source of truth for+ * how each external agent CLI receives multimodal input.+ *+ * - `claude-code`: stream-json on stdin with text + base64 image content blocks+ * - `codex`: raw text on stdin + repeatable `--image <path>` flags+ *+ * Path-mode agents materialize URL / base64 images via `materializeImageToPath`+ * into `imageMaterializeDir` (defaults to `cacheDir` then `os.tmpdir()`).+ */+export const buildAgentInput = async (+ agentType: string,+ prompt: AgentPromptInput,+ options: BuildAgentInputOptions = {},+): Promise<AgentInputPlan> => {+ const blocks = toBlocks(prompt);++ switch (agentType) {+ case 'claude-code': {+ return buildClaudeCodeStdin(blocks, options);+ }+ case 'codex': {+ return buildCodexInput(blocks, options);+ }+ default: {+ throw new Error(`buildAgentInput: unsupported agent type "${agentType}"`);+ }+ }+};diff --git a/packages/heterogeneous-agents/src/spawn/input/index.ts b/packages/heterogeneous-agents/src/spawn/input/index.tsnew file mode 100644index 00000000000..01b7f01f22b--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/input/index.ts@@ -0,0 +1,18 @@+export {+ type AgentInputPlan,+ buildAgentInput,+ type BuildAgentInputOptions,+} from './buildAgentInput';+export {+ materializeImageToPath,+ type NormalizedImage,+ normalizeImage,+ type NormalizeImageOptions,+} from './normalizeImage';+export type {+ AgentContentBlock,+ AgentImageBlock,+ AgentImageSource,+ AgentPromptInput,+ AgentTextBlock,+} from './types';diff --git a/packages/heterogeneous-agents/src/spawn/input/normalizeImage.ts b/packages/heterogeneous-agents/src/spawn/input/normalizeImage.tsnew file mode 100644index 00000000000..0a66ce75685--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/input/normalizeImage.ts@@ -0,0 +1,242 @@+import { createHash } from 'node:crypto';+import { access, mkdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';++import type { AgentImageSource } from './types';++export interface NormalizedImage {+ buffer: Buffer;+ mediaType: string;+ /**+ * Filesystem path when one is known. Set when the source was already a+ * path, or after `materializeImageToPath` writes the buffer to a cache dir.+ */+ path?: string;+}++export interface NormalizeImageOptions {+ /**+ * On-disk cache directory for fetched URLs. When set, downloaded bytes are+ * persisted by sha256(id || url) so repeated normalizations of the same+ * image avoid re-fetching. Path-only sources never write here.+ */+ cacheDir?: string;+ /** Override `fetch` (tests / proxy injection). Defaults to the global. */+ fetcher?: typeof fetch;+}++const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);++const EXT_BY_MEDIA_TYPE: Record<string, string> = {+ 'image/gif': '.gif',+ 'image/jpeg': '.jpg',+ 'image/jpg': '.jpg',+ 'image/pjpeg': '.jpg',+ 'image/png': '.png',+ 'image/webp': '.webp',+ 'image/x-png': '.png',+};++const MEDIA_TYPE_BY_EXT: Record<string, string> = {+ '.gif': 'image/gif',+ '.jpeg': 'image/jpeg',+ '.jpg': 'image/jpeg',+ '.png': 'image/png',+ '.webp': 'image/webp',+};++const sha256Hex = (input: string): string => createHash('sha256').update(input).digest('hex');++const normalizeMediaType = (raw: string | undefined | null): string => {+ if (!raw) return '';+ return raw.split(';')[0]?.trim().toLowerCase() ?? '';+};++const guessMediaTypeFromBuffer = (buffer: Buffer): string | undefined => {+ if (buffer.length >= PNG_SIG.length && buffer.subarray(0, PNG_SIG.length).equals(PNG_SIG)) {+ return 'image/png';+ }+ if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {+ return 'image/jpeg';+ }+ if (buffer.length >= 6) {+ const head = buffer.subarray(0, 6).toString('ascii');+ if (head === 'GIF87a' || head === 'GIF89a') return 'image/gif';+ }+ if (+ buffer.length >= 12 &&+ buffer.subarray(0, 4).toString('ascii') === 'RIFF' &&+ buffer.subarray(8, 12).toString('ascii') === 'WEBP'+ ) {+ return 'image/webp';+ }+ return undefined;+};++const guessMediaTypeFromUrl = (url: string): string | undefined => {+ try {+ const ext = path.extname(new URL(url).pathname).toLowerCase();+ return MEDIA_TYPE_BY_EXT[ext];+ } catch {+ return undefined;+ }+};++const cacheKeyForUrl = (source: { id?: string; url: string }): string =>+ sha256Hex(source.id || source.url);++const isRecognizedImageMediaType = (mediaType: string): boolean =>+ Boolean(EXT_BY_MEDIA_TYPE[mediaType]);++/**+ * Choose the most trustworthy image media type given the available signals.+ *+ * Generic / non-image header values (`application/octet-stream`, `text/plain`,+ * empty) are common from CDNs that strip extensions and fall back to a default+ * Content-Type β we'd rather sniff the URL extension or PNG/JPEG/GIF/WebP byte+ * signatures than serialize an unrecognized type into a `media_type` field+ * that downstream agents (Claude API) will reject.+ *+ * Resolution order:+ * 1. Header type, only if it's a recognized image/* we know how to extension-map+ * 2. URL extension hint+ * 3. Byte-signature sniff+ * 4. Raw header value as a last resort (preserves whatever the server claimed+ * so the caller at least sees the original signal)+ * 5. `image/png` fallback+ */+const pickImageMediaType = (+ rawHeaderType: string | undefined | null,+ url: string | undefined,+ buffer: Buffer,+): string => {+ const headerType = normalizeMediaType(rawHeaderType);+ if (headerType && isRecognizedImageMediaType(headerType)) return headerType;++ const urlType = url ? guessMediaTypeFromUrl(url) : undefined;+ if (urlType) return urlType;++ const sniffed = guessMediaTypeFromBuffer(buffer);+ if (sniffed) return sniffed;++ return headerType || 'image/png';+};++const fetchUrlImage = async (+ source: { id?: string; url: string },+ options: NormalizeImageOptions,+): Promise<NormalizedImage> => {+ const fetcher = options.fetcher ?? fetch;+ const cacheDir = options.cacheDir;++ if (cacheDir) {+ const key = cacheKeyForUrl(source);+ const dataPath = path.join(cacheDir, key);+ const metaPath = path.join(cacheDir, `${key}.meta`);+ try {+ const meta = JSON.parse(await readFile(metaPath, 'utf8')) as { mediaType?: string };+ const buffer = await readFile(dataPath);+ const mediaType = pickImageMediaType(meta.mediaType, source.url, buffer);+ return { buffer, mediaType };+ } catch {+ // cache miss β fall through to fetch+ }+ }++ const res = await fetcher(source.url);+ if (!res.ok) {+ throw new Error(+ `Failed to fetch image at ${source.url}: ${res.status} ${res.statusText || ''}`.trim(),+ );+ }+ const buffer = Buffer.from(await res.arrayBuffer());+ const mediaType = pickImageMediaType(res.headers.get('content-type'), source.url, buffer);++ if (cacheDir) {+ const key = cacheKeyForUrl(source);+ await mkdir(cacheDir, { recursive: true });+ await writeFile(path.join(cacheDir, key), buffer);+ await writeFile(+ path.join(cacheDir, `${key}.meta`),+ JSON.stringify({ id: source.id, mediaType }),+ );+ }++ return { buffer, mediaType };+};++const readPathImage = async (filePath: string): Promise<NormalizedImage> => {+ const buffer = await readFile(filePath);+ const ext = path.extname(filePath).toLowerCase();+ const mediaType =+ MEDIA_TYPE_BY_EXT[ext] || guessMediaTypeFromBuffer(buffer) || 'application/octet-stream';+ return { buffer, mediaType, path: filePath };+};++const decodeBase64Image = (data: string, mediaType: string): NormalizedImage => {+ const buffer = Buffer.from(data, 'base64');+ // The caller's declared mediaType wins only when it's a recognized image+ // type β base64 sources commonly default to `application/octet-stream` from+ // upstream encoders, which would otherwise serialize into a `media_type`+ // that downstream agents (Claude API) reject.+ const resolved = pickImageMediaType(mediaType, undefined, buffer);+ return { buffer, mediaType: resolved };+};++/**+ * Resolve an image source into raw bytes + media type. URL sources may hit a+ * disk cache when `cacheDir` is provided; path sources are read in place;+ * base64 is decoded synchronously.+ */+export const normalizeImage = async (+ source: AgentImageSource,+ options: NormalizeImageOptions = {},+): Promise<NormalizedImage> => {+ switch (source.type) {+ case 'url': {+ return fetchUrlImage(source, options);+ }+ case 'path': {+ return readPathImage(source.path);+ }+ case 'base64': {+ return decodeBase64Image(source.data, source.mediaType);+ }+ }+};++/**+ * Materialize a normalized image to disk so a path-based agent (Codex+ * `--image <file>`) can consume it. If the image already has a `path`, that+ * path is returned as-is. Otherwise the buffer is written into `cacheDir`+ * keyed by content, with an extension derived from the media type β falling+ * back to byte-signature sniffing when the media type is generic+ * (`application/octet-stream` etc.) but the bytes are a recognizable image.+ */+export const materializeImageToPath = async (+ image: NormalizedImage,+ cacheDir: string,+): Promise<string> => {+ if (image.path) return image.path;++ const ext =+ EXT_BY_MEDIA_TYPE[normalizeMediaType(image.mediaType)] ||+ EXT_BY_MEDIA_TYPE[guessMediaTypeFromBuffer(image.buffer) ?? ''];+ if (!ext) {+ throw new Error(`Unsupported image media type for path materialization: ${image.mediaType}`);+ }++ const key = sha256Hex(+ `${image.mediaType}:${image.buffer.length}:${image.buffer.subarray(0, 64).toString('hex')}`,+ );+ const filePath = path.join(cacheDir, `${key}${ext}`);++ try {+ await access(filePath);+ } catch {+ await mkdir(cacheDir, { recursive: true });+ await writeFile(filePath, image.buffer);+ }++ return filePath;+};diff --git a/packages/heterogeneous-agents/src/spawn/input/types.ts b/packages/heterogeneous-agents/src/spawn/input/types.tsnew file mode 100644index 00000000000..ed8785a2354--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/input/types.ts@@ -0,0 +1,41 @@+/**+ * Source of an image for an agent prompt. Three input shapes are supported so+ * callers can pass whatever they have: a URL (CDN attachments), a local path+ * (terminal `--image ./pic.png`), or already-decoded base64 (programmatic).+ */+export type AgentImageSource =+ | {+ /** Stable id for cache dedupe. Falls back to a hash of the url. */+ id?: string;+ type: 'url';+ url: string;+ }+ | {+ path: string;+ type: 'path';+ }+ | {+ data: string;+ /** Mime type, e.g. `'image/png'`. */+ mediaType: string;+ type: 'base64';+ };++export interface AgentTextBlock {+ text: string;+ type: 'text';+}++export interface AgentImageBlock {+ source: AgentImageSource;+ type: 'image';+}++export type AgentContentBlock = AgentTextBlock | AgentImageBlock;++/**+ * Prompt input shape for `spawnAgent`. A plain string is sugar for a single+ * text block; the array form supports mixed text + image content. Order is+ * preserved when serialized to the agent's stdin / CLI flags.+ */+export type AgentPromptInput = string | AgentContentBlock[];diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.tsindex 73edbb3fca6..4640bff17ba 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts@@ -89,7 +89,7 @@ describe('spawnAgent', () => {nextFakeProc = fake.proc;const { spawnAgent } = await import('./spawnAgent');- const handle = spawnAgent({+ const handle = await spawnAgent({agentType: 'claude-code',operationId: 'op-1',prompt: 'do a thing',@@ -124,7 +124,7 @@ describe('spawnAgent', () => {it('appends --resume <id> for claude when resuming a session', async () => {nextFakeProc = createFakeProc().proc;const { spawnAgent } = await import('./spawnAgent');- spawnAgent({+ await spawnAgent({agentType: 'claude-code',operationId: 'op-1',prompt: 'continue',@@ -140,7 +140,7 @@ describe('spawnAgent', () => {it('builds codex args with `exec` + json + skip-git-repo-check + full-auto', async () => {nextFakeProc = createFakeProc().proc;const { spawnAgent } = await import('./spawnAgent');- spawnAgent({ agentType: 'codex', operationId: 'op-1', prompt: 'hello' });+ await spawnAgent({ agentType: 'codex', operationId: 'op-1', prompt: 'hello' });const { args, command } = spawnCalls[0];expect(command).toBe('codex');@@ -153,7 +153,7 @@ describe('spawnAgent', () => {it('uses codex `exec resume` form with thread id + `-` stdin marker on resume', async () => {nextFakeProc = createFakeProc().proc;const { spawnAgent } = await import('./spawnAgent');- spawnAgent({+ await spawnAgent({agentType: 'codex',operationId: 'op-1',prompt: 'continue',@@ -166,10 +166,74 @@ describe('spawnAgent', () => {expect(args.at(-1)).toBe('-');});+ it('serializes multimodal content blocks into the CC stream-json user message', async () => {+ nextFakeProc = createFakeProc().proc;+ const { spawnAgent } = await import('./spawnAgent');+ const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00]);+ await spawnAgent({+ agentType: 'claude-code',+ operationId: 'op-1',+ prompt: [+ { text: 'describe this', type: 'text' },+ {+ source: { data: pngBytes.toString('base64'), mediaType: 'image/png', type: 'base64' },+ type: 'image',+ },+ ],+ });++ // The mock's fake stdin captures everything written.+ const stdinPayload = (nextFakeProc as any).stdin.write.mock.calls[0][0] as string;+ const userMsg = JSON.parse(stdinPayload.trim());+ expect(userMsg.message.content).toEqual([+ { text: 'describe this', type: 'text' },+ {+ source: {+ data: pngBytes.toString('base64'),+ media_type: 'image/png',+ type: 'base64',+ },+ type: 'image',+ },+ ]);+ });++ it('renders codex multimodal input as text-on-stdin + repeatable --image flags', async () => {+ nextFakeProc = createFakeProc().proc;+ const os = await import('node:os');+ const fsp = await import('node:fs/promises');+ const cacheDir = await fsp.mkdtemp(`${os.tmpdir()}/spawn-agent-codex-`);++ const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00]);+ const { spawnAgent } = await import('./spawnAgent');+ await spawnAgent({+ agentType: 'codex',+ inputOptions: { cacheDir },+ operationId: 'op-1',+ prompt: [+ { text: 'look', type: 'text' },+ {+ source: { data: pngBytes.toString('base64'), mediaType: 'image/png', type: 'base64' },+ type: 'image',+ },+ ],+ });++ const { args } = spawnCalls[0];+ const imageIdx = args.indexOf('--image');+ expect(imageIdx).toBeGreaterThan(-1);+ const materializedPath = args[imageIdx + 1]!;+ expect(materializedPath.startsWith(cacheDir)).toBe(true);+ expect(materializedPath.endsWith('.png')).toBe(true);+ // Codex receives the prompt text on stdin.+ const stdinPayload = (nextFakeProc as any).stdin.write.mock.calls[0][0] as string;+ expect(stdinPayload).toBe('look');+ });+it('honors a custom --command override + extraArgs', async () => {nextFakeProc = createFakeProc().proc;const { spawnAgent } = await import('./spawnAgent');- spawnAgent({+ await spawnAgent({agentType: 'claude-code',command: '/usr/local/bin/claude-wrapped',extraArgs: ['--my-flag', 'x'],@@ -183,12 +247,12 @@ describe('spawnAgent', () => {expect(args).toContain('x');});- it('throws on unknown agent type', async () => {+ it('rejects with an error on unknown agent type', async () => {nextFakeProc = createFakeProc().proc;const { spawnAgent } = await import('./spawnAgent');- expect(() =>+ await expect(spawnAgent({ agentType: 'kimi-cli', operationId: 'op-1', prompt: 'hi' }),- ).toThrowError(/unsupported agent type/);+ ).rejects.toThrow(/unsupported agent type/);});it('events iterator drains all pipeline events including the trailing flush', async () => {@@ -196,7 +260,7 @@ describe('spawnAgent', () => {nextFakeProc = fake.proc;const { spawnAgent } = await import('./spawnAgent');- const handle = spawnAgent({+ const handle = await spawnAgent({agentType: 'claude-code',operationId: 'op-7',prompt: 'go',@@ -257,7 +321,11 @@ describe('spawnAgent', () => {const fake = createFakeProc();nextFakeProc = fake.proc;const { spawnAgent } = await import('./spawnAgent');- const handle = spawnAgent({ agentType: 'claude-code', operationId: 'op-1', prompt: 'go' });+ const handle = await spawnAgent({+ agentType: 'claude-code',+ operationId: 'op-1',+ prompt: 'go',+ });// Fire two chunks back-to-back BEFORE 'end'. Both `pipeline.push()` calls// are now in flight; without serialization, B's events would queue first.@@ -309,7 +377,11 @@ describe('spawnAgent', () => {const fake = createFakeProc();nextFakeProc = fake.proc;const { spawnAgent } = await import('./spawnAgent');- const handle = spawnAgent({ agentType: 'claude-code', operationId: 'op-1', prompt: 'go' });+ const handle = await spawnAgent({+ agentType: 'claude-code',+ operationId: 'op-1',+ prompt: 'go',+ });// 'end' fires immediately after the chunk write β pipeline.push() is still// pending. The fix must keep the iterator open until that push resolves.@@ -330,7 +402,7 @@ describe('spawnAgent', () => {nextFakeProc = fake.proc;const { spawnAgent } = await import('./spawnAgent');- const handle = spawnAgent({+ const handle = await spawnAgent({agentType: 'claude-code',operationId: 'op-1',prompt: 'go',diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 8ad029a370d..031d9b0e85f 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -4,6 +4,8 @@ import { spawn } from 'node:child_process';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { AgentStreamPipeline } from './agentStreamPipeline';+import type { AgentPromptInput, BuildAgentInputOptions } from './input';+import { buildAgentInput } from './input';export interface SpawnAgentOptions {/** Agent type key (`'claude-code'` | `'codex'`). */@@ -20,6 +22,12 @@ export interface SpawnAgentOptions {env?: Record<string, string>;/** Extra CLI arguments appended after the agent's preset flags. */extraArgs?: string[];+ /**+ * Image normalization options (URL fetch + on-disk cache + path+ * materialization). Forwarded to `buildAgentInput`. When `prompt` is a+ * plain string this is unused.+ */+ inputOptions?: BuildAgentInputOptions;/*** Operation id stamped onto every emitted `AgentStreamEvent`. For ingest-* connected runs this is the server-allocated op id; for standalone runs@@ -27,8 +35,12 @@ export interface SpawnAgentOptions {* events still carry the conventional shape.*/operationId: string;- /** User prompt text. Always passed via stdin (CC: stream-json; Codex: raw). */- prompt: string;+ /**+ * User prompt. A plain string is sugar for a single text block; the array+ * form supports mixed text + image content blocks (URL / path / base64).+ * Translated to per-agent stdin + CLI flags via `buildAgentInput`.+ */+ prompt: AgentPromptInput;/** Resume an existing agent session by its native session id (CC) / thread id (Codex). */resumeSessionId?: string;}@@ -77,28 +89,38 @@ const CLAUDE_CODE_BASE_ARGS = [const CODEX_REQUIRED_ARGS = ['--json', '--skip-git-repo-check', '--full-auto'] as const;-const buildClaudeCodeArgs = (resumeSessionId: string | undefined, extraArgs: string[]) => [+const buildClaudeCodeArgs = (+ resumeSessionId: string | undefined,+ inputArgs: string[],+ extraArgs: string[],+) => [...CLAUDE_CODE_BASE_ARGS,...(resumeSessionId ? ['--resume', resumeSessionId] : []),+ ...inputArgs,...extraArgs,];-const buildCodexArgs = (resumeSessionId: string | undefined, extraArgs: string[]) =>+const buildCodexArgs = (+ resumeSessionId: string | undefined,+ inputArgs: string[],+ extraArgs: string[],+) =>resumeSessionId- ? ['exec', 'resume', ...CODEX_REQUIRED_ARGS, ...extraArgs, resumeSessionId, '-']- : ['exec', ...CODEX_REQUIRED_ARGS, ...extraArgs];+ ? ['exec', 'resume', ...CODEX_REQUIRED_ARGS, ...inputArgs, ...extraArgs, resumeSessionId, '-']+ : ['exec', ...CODEX_REQUIRED_ARGS, ...inputArgs, ...extraArgs];const buildSpawnArgs = (agentType: string,resumeSessionId: string | undefined,+ inputArgs: string[],extraArgs: string[],): string[] => {switch (agentType) {case 'claude-code': {- return buildClaudeCodeArgs(resumeSessionId, extraArgs);+ return buildClaudeCodeArgs(resumeSessionId, inputArgs, extraArgs);}case 'codex': {- return buildCodexArgs(resumeSessionId, extraArgs);+ return buildCodexArgs(resumeSessionId, inputArgs, extraArgs);}default: {throw new Error(`spawnAgent: unsupported agent type "${agentType}"`);@@ -106,18 +128,6 @@ const buildSpawnArgs = (}};-const buildStdinPayload = (agentType: string, prompt: string): string => {- if (agentType === 'claude-code') {- return `${JSON.stringify({- message: { content: [{ text: prompt, type: 'text' }], role: 'user' },- type: 'user',- })}\n`;- }- // Codex reads the prompt as plain text from stdin (the `-` positional in- // resume mode also reads from stdin).- return prompt;-};-const defaultCommand = (agentType: string): string => (agentType === 'codex' ? 'codex' : 'claude');const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {@@ -152,17 +162,24 @@ const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {* unified `AgentStreamEvent`s. Used by `lh hetero exec` for both standalone* terminal runs and (later) sandbox-driven runs that ingest into the server.*- * Stays minimal on purpose β no image attachment, no on-disk tracing, no- * proxy env composition, no CLI-not-found classification. Those host- * concerns live in the desktop main controller, which does NOT use this- * function (it instantiates `AgentStreamPipeline` directly with its own- * spawn logic). The CLI sandbox is a smaller environment where the minimal- * surface is correct.+ * Stays minimal on purpose β no on-disk tracing, no proxy env composition,+ * no CLI-not-found classification. Those host concerns live in the desktop+ * main controller, which has its own spawn logic on top. The CLI sandbox is+ * a smaller environment where the minimal surface is correct.+ *+ * Returns a Promise because image normalization (URL fetch / file read) is+ * async; the spawn itself happens after the input plan is resolved so a+ * failed image fetch surfaces before the child starts.*/-export const spawnAgent = (options: SpawnAgentOptions): SpawnAgentHandle => {+export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentHandle> => {const command = options.command || defaultCommand(options.agentType);- const args = buildSpawnArgs(options.agentType, options.resumeSessionId, options.extraArgs ?? []);- const stdinPayload = buildStdinPayload(options.agentType, options.prompt);+ const inputPlan = await buildAgentInput(options.agentType, options.prompt, options.inputOptions);+ const args = buildSpawnArgs(+ options.agentType,+ options.resumeSessionId,+ inputPlan.args,+ options.extraArgs ?? [],+ );const cwd = options.cwd || process.cwd();const proc = spawn(command, args, {@@ -173,7 +190,7 @@ export const spawnAgent = (options: SpawnAgentOptions): SpawnAgentHandle => {});if (proc.stdin) {- proc.stdin.write(stdinPayload, () => {+ proc.stdin.write(inputPlan.stdin, () => {proc.stdin?.end();});}diff --git a/packages/types/package.json b/packages/types/package.jsonindex dfbd02a150e..3ed432afdea 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -10,8 +10,6 @@"test:update": "vitest -u"},"dependencies": {- "@lobechat/python-interpreter": "workspace:*",- "@lobechat/web-crawler": "workspace:*","@lobehub/market-sdk": "0.33.3","@lobehub/market-types": "^1.12.3","model-bank": "workspace:*",diff --git a/packages/types/src/tool/crawler.ts b/packages/types/src/tool/crawler.tsindex 58adfe0e3fe..e99a6ff2616 100644--- a/packages/types/src/tool/crawler.ts+++ b/packages/types/src/tool/crawler.ts@@ -1,4 +1,26 @@-import type { CrawlErrorResult, CrawlSuccessResult } from '@lobechat/web-crawler';+export interface CrawlSuccessResult {+ content?: string;+ contentType: 'text' | 'json';+ description?: string;+ length?: number;+ siteName?: string;+ title?: string;+ url: string;+}++export interface CrawlErrorResult {+ content: string;+ errorMessage?: string;+ errorType?: string;+ url?: string;+}++export interface CrawlUniformResult {+ crawler: string;+ data: CrawlSuccessResult | CrawlErrorResult;+ originalUrl: string;+ transformedUrl?: string;+}export interface CrawlSinglePageQuery {url: string;diff --git a/packages/types/src/tool/interpreter.ts b/packages/types/src/tool/interpreter.tsindex 2efa851bdd6..cd62395645e 100644--- a/packages/types/src/tool/interpreter.ts+++ b/packages/types/src/tool/interpreter.ts@@ -1,5 +1,3 @@-import type { PythonResult } from '@lobechat/python-interpreter';-export interface CodeInterpreterParams {code: string;packages: string[];@@ -12,6 +10,17 @@ export interface CodeInterpreterFileItem {previewUrl?: string;}+export interface PythonOutput {+ data: string;+ type: 'stdout' | 'stderr';+}++export interface PythonResult {+ output?: PythonOutput[];+ result?: string;+ success: boolean;+}+export interface CodeInterpreterResponse extends PythonResult {files?: CodeInterpreterFileItem[];}diff --git a/packages/types/src/tool/search/index.ts b/packages/types/src/tool/search/index.tsindex 175b9887652..b04d84e6a95 100644--- a/packages/types/src/tool/search/index.ts+++ b/packages/types/src/tool/search/index.ts@@ -1,6 +1,4 @@-import type { CrawlUniformResult } from '@lobechat/web-crawler';--import type { CrawlMultiPagesQuery } from '../crawler';+import type { CrawlMultiPagesQuery, CrawlUniformResult } from '../crawler';export interface SearchParams {searchCategories?: string[];