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.

πŸ› fix(agent): persist & deliver image attachments for device/sandbox hetero runs (#15685)

Arvin Xu61586b937721
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index 2c270cf4137..f0a79b5e762 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -302,6 +302,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
{
agentType: request.agentType,
cwd: request.cwd,
+ imageList: request.imageList,
jwt: request.jwt,
operationId: request.operationId,
prompt: request.prompt,
diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.ts
index 611eb2f3f48..fe756b9a9d8 100644
--- a/apps/cli/src/device/agentRun.test.ts
+++ b/apps/cli/src/device/agentRun.test.ts
@@ -122,4 +122,24 @@ describe('spawnHeteroAgentRun', () => {
]),
);
});
+
+ it('appends image blocks to stdin when imageList is provided', async () => {
+ const child = makeFakeChild();
+ spawnMock.mockReturnValue(child);
+
+ const ackPromise = spawnHeteroAgentRun({
+ ...baseParams,
+ imageList: [{ id: 'file-1', url: 'https://signed/a.png' }],
+ prompt: 'look at this',
+ });
+ child.emit('spawn');
+ await ackPromise;
+
+ expect(child.stdin.write).toHaveBeenCalledWith(
+ JSON.stringify([
+ { text: 'look at this', type: 'text' },
+ { source: { id: 'file-1', type: 'url', url: 'https://signed/a.png' }, type: 'image' },
+ ]),
+ );
+ });
});
diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.ts
index 7951d1368cf..1bbe8ee3d2c 100644
--- a/apps/cli/src/device/agentRun.ts
+++ b/apps/cli/src/device/agentRun.ts
@@ -1,8 +1,15 @@
import { spawn } from 'node:child_process';
+import {
+ buildHeteroExecStdinPayload,
+ type HeteroExecImageRef,
+} from '@lobechat/heterogeneous-agents/protocol';
+
export interface SpawnHeteroAgentRunParams {
agentType: string;
cwd?: string;
+ /** Image attachments (signed URLs) appended as image content blocks. */
+ imageList?: HeteroExecImageRef[];
jwt: string;
operationId: string;
prompt: string;
@@ -46,6 +53,7 @@ export function spawnHeteroAgentRun(
const {
agentType,
cwd,
+ imageList,
jwt,
operationId,
prompt,
@@ -77,15 +85,11 @@ export function spawnHeteroAgentRun(
...(resumeSessionId ? ['--resume', resumeSessionId] : []),
];
- // With systemContext, send a content-block array so the agent sees the
- // context block first, then the user's actual prompt β€” mirrors the desktop
- // path. `lh hetero exec` coerces both shapes via coerceJsonPrompt.
- const stdinPayload = systemContext
- ? JSON.stringify([
- { text: systemContext, type: 'text' },
- { text: prompt, type: 'text' },
- ])
- : JSON.stringify(prompt);
+ // systemContext / image attachments turn the payload into a content-block
+ // array: context block first, then the user's prompt, then images β€” mirrors
+ // the desktop path. `lh hetero exec` coerces both shapes via
+ // coerceJsonPrompt.
+ const stdinPayload = buildHeteroExecStdinPayload({ imageList, prompt, systemContext });
return new Promise<AgentRunAckResult>((resolve) => {
let settled = false;
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index a7ccec003ba..940e4bbad45 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -301,6 +301,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
this.heterogeneousAgentCtr.spawnLhHeteroExec({
agentType: request.agentType,
cwd: request.cwd,
+ imageList: request.imageList,
jwt: request.jwt,
operationId: request.operationId,
prompt: request.prompt,
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index c283cdf9f63..31d611a999d 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -18,7 +18,12 @@ import {
} from '@lobechat/electron-client-ipc';
import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';
import { AskUserMcpServer } from '@lobechat/heterogeneous-agents/askUser';
-import type { AgentContentBlock, AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
+import type {
+ AgentContentBlock,
+ HeteroExecImageRef,
+} from '@lobechat/heterogeneous-agents/protocol';
+import { buildHeteroExecStdinPayload } from '@lobechat/heterogeneous-agents/protocol';
+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
import {
AgentStreamPipeline,
buildAgentInput,
@@ -1424,6 +1429,8 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
spawnLhHeteroExec(params: {
agentType: string;
cwd?: string;
+ /** Image attachments (signed URLs) appended as image content blocks. */
+ imageList?: HeteroExecImageRef[];
jwt: string;
operationId: string;
prompt: string;
@@ -1435,6 +1442,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
const {
agentType,
cwd,
+ imageList,
jwt,
operationId,
prompt,
@@ -1487,16 +1495,11 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
stdio: ['pipe', 'inherit', 'inherit'],
});
- // When systemContext is provided, send a content-block array so CC sees the
- // context block first, then the user's actual message β€” mirrors
- // spawnHeteroSandbox. lh handles JSON arrays via coerceJsonPrompt, so no lh
- // changes are required.
- const stdinPayload = systemContext
- ? JSON.stringify([
- { text: systemContext, type: 'text' },
- { text: prompt, type: 'text' },
- ])
- : JSON.stringify(prompt);
+ // systemContext / image attachments turn the payload into a content-block
+ // array so CC sees the context block first, then the user's message, then
+ // the images β€” mirrors spawnHeteroSandbox. lh handles both shapes via
+ // coerceJsonPrompt, so no lh changes are required.
+ const stdinPayload = buildHeteroExecStdinPayload({ imageList, prompt, systemContext });
child.stdin.write(stdinPayload);
child.stdin.end();
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
new file mode 100644
index 00000000000..c760c1d9e08
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -0,0 +1,293 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+
+const { mockMessageCreate, mockResolveAttachmentMetadata, mockSpawnHeteroSandbox } = vi.hoisted(
+ () => ({
+ mockMessageCreate: vi.fn(),
+ mockResolveAttachmentMetadata: vi.fn(),
+ mockSpawnHeteroSandbox: vi.fn().mockResolvedValue(undefined),
+ }),
+);
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/libs/trpc/utils/internalJwt', () => ({
+ signOperationJwt: vi.fn().mockResolvedValue('op-jwt'),
+ signUserJWT: vi.fn().mockResolvedValue('user-jwt'),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({
+ create: mockMessageCreate,
+ query: vi.fn().mockResolvedValue([]),
+ update: vi.fn().mockResolvedValue({}),
+ })),
+}));
+
+const heteroAgentConfig = {
+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },
+ chatConfig: {},
+ files: [],
+ id: 'agent-1',
+ knowledgeBases: [],
+ model: 'claude-code',
+ plugins: [],
+ provider: 'anthropic',
+ systemRole: 'You are a helpful assistant',
+};
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(() => ({
+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(() => ({
+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),
+ })),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(() => ({
+ query: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+const topicMock = {
+ create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),
+ findById: vi.fn().mockResolvedValue(undefined),
+ updateMetadata: vi.fn().mockResolvedValue(undefined),
+};
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(() => topicMock),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ })),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(() => ({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ market: {
+ creds: {
+ get: vi.fn(),
+ list: vi.fn().mockResolvedValue({ data: [] }),
+ },
+ },
+ })),
+}));
+
+vi.mock('@/server/services/heterogeneousAgent', () => ({
+ HeterogeneousAgentService: vi.fn().mockImplementation(() => ({
+ getHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),
+ })),
+}));
+
+vi.mock('@/server/services/heterogeneousAgent/sandboxRunner', () => ({
+ spawnHeteroSandbox: mockSpawnHeteroSandbox,
+}));
+
+vi.mock('@/server/services/file/resolveAttachments', () => ({
+ resolveAttachmentMetadata: mockResolveAttachmentMetadata,
+ resolveAttachmentsByFileIds: vi.fn().mockResolvedValue({
+ fileList: [],
+ imageList: [],
+ orderedFileIds: [],
+ videoList: [],
+ warnings: [],
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({
+ createOperation: vi.fn().mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ }),
+ })),
+}));
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ isConfigured: false,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+describe('AiAgentService.execAgent - hetero early-exit file attachments', () => {
+ let service: AiAgentService;
+ const mockDb = {} as any;
+ const userId = 'test-user-id';
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ topicMock.create.mockResolvedValue({ id: 'topic-1', metadata: undefined });
+ topicMock.findById.mockResolvedValue(undefined);
+ topicMock.updateMetadata.mockResolvedValue(undefined);
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockResolveAttachmentMetadata.mockResolvedValue([]);
+ mockSpawnHeteroSandbox.mockResolvedValue(undefined);
+
+ service = new AiAgentService(mockDb, userId);
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ const findUserMessageCreate = () =>
+ mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');
+
+ it('should attach fileIds to the user message (SPA gateway device/sandbox mode)', async () => {
+ // regression: the hetero early exit used to create the user message
+ // without `files`, so images attached in device mode were never linked
+ // via messagesFiles and disappeared after the optimistic message was
+ // replaced by the server snapshot.
+ await service.execAgent({
+ agentId: 'agent-1',
+ fileIds: ['file-1', 'file-2'],
+ prompt: 'Look at this image',
+ });
+
+ const userCall = findUserMessageCreate();
+ expect(userCall).toBeDefined();
+ expect(userCall![0].files).toEqual(['file-1', 'file-2']);
+ });
+
+ it('should dedupe repeated fileIds (messagesFiles PK is fileId+messageId)', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ fileIds: ['file-1', 'file-1', 'file-2'],
+ prompt: 'Look at this image',
+ });
+
+ const userCall = findUserMessageCreate();
+ expect(userCall![0].files).toEqual(['file-1', 'file-2']);
+ });
+
+ it('should leave files undefined when no fileIds are provided', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'No attachments here',
+ });
+
+ const userCall = findUserMessageCreate();
+ expect(userCall).toBeDefined();
+ expect(userCall![0].files).toBeUndefined();
+ });
+
+ it('should leave files undefined when fileIds is an empty array', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ fileIds: [],
+ prompt: 'No attachments here',
+ });
+
+ const userCall = findUserMessageCreate();
+ expect(userCall![0].files).toBeUndefined();
+ });
+
+ describe('image delivery to the dispatched CLI', () => {
+ it('should resolve image attachments and pass imageList to the sandbox dispatch', async () => {
+ mockResolveAttachmentMetadata.mockResolvedValue([
+ {
+ fileType: 'image/png',
+ id: 'file-1',
+ name: 'screenshot.png',
+ size: 100,
+ url: 'https://signed/file-1.png',
+ },
+ {
+ fileType: 'application/pdf',
+ id: 'file-2',
+ name: 'doc.pdf',
+ size: 200,
+ url: 'https://signed/file-2.pdf',
+ },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ fileIds: ['file-1', 'file-2'],
+ prompt: 'Look at this image',
+ });
+
+ expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(
+ expect.objectContaining({
+ imageList: [{ id: 'file-1', url: 'https://signed/file-1.png' }],
+ }),
+ );
+ });
+
+ it('should pass imageList undefined when attachments contain no images', async () => {
+ mockResolveAttachmentMetadata.mockResolvedValue([
+ {
+ fileType: 'application/pdf',
+ id: 'file-2',
+ name: 'doc.pdf',
+ size: 200,
+ url: 'https://signed/file-2.pdf',
+ },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ fileIds: ['file-2'],
+ prompt: 'Read this doc',
+ });
+
+ expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(
+ expect.objectContaining({ imageList: undefined }),
+ );
+ });
+
+ it('should not block the run when attachment resolution fails', async () => {
+ mockResolveAttachmentMetadata.mockRejectedValue(new Error('S3 down'));
+
+ const result = await service.execAgent({
+ agentId: 'agent-1',
+ fileIds: ['file-1'],
+ prompt: 'Look at this image',
+ });
+
+ expect(result.success).toBe(true);
+ // Persistence is independent of URL resolution β€” files still attached.
+ const userCall = findUserMessageCreate();
+ expect(userCall![0].files).toEqual(['file-1']);
+ expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(
+ expect.objectContaining({ imageList: undefined }),
+ );
+ });
+
+ it('should not resolve attachments when no fileIds are provided', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'No attachments here',
+ });
+
+ expect(mockResolveAttachmentMetadata).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 7bfcf8559e4..88201d8bae4 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -97,7 +97,10 @@ import { shouldSuppressSignal } from '@/server/services/agentSignal/suppressSign
import { deviceGateway } from '@/server/services/deviceGateway';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
-import { resolveAttachmentsByFileIds } from '@/server/services/file/resolveAttachments';
+import {
+ resolveAttachmentMetadata,
+ resolveAttachmentsByFileIds,
+} from '@/server/services/file/resolveAttachments';
import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';
import type { ConversationHistoryEntry } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
import { KlavisService } from '@/server/services/klavis';
@@ -878,11 +881,19 @@ export class AiAgentService {
const operationId = nanoid();
// Create user message so the conversation is visible in the UI immediately.
+ // Attach already-uploaded files (`fileIds` from the SPA gateway path) the
+ // same way `sendMessageInServer` does on the local-mode path β€” without
+ // the messagesFiles relation the attachment disappears as soon as the
+ // optimistic client message is replaced by the server snapshot.
const userMsg = runFromHistory
? undefined
: await this.messageModel.create({
agentId: resolvedAgentId,
content: prompt,
+ files:
+ attachedFileIds && attachedFileIds.length > 0
+ ? Array.from(new Set(attachedFileIds))
+ : undefined,
role: 'user',
threadId: appContext?.threadId ?? undefined,
topicId,
@@ -986,10 +997,34 @@ export class AiAgentService {
repos: topicRepos,
});
+ // Resolve image attachments into signed URLs for the dispatched CLI β€”
+ // mirrors the local-mode path, where the client feeds the persisted
+ // message's imageList into `sendPrompt` for vision. Metadata-only
+ // (no document parsing) and non-fatal: a resolution failure must not
+ // block the run, the text prompt still works without the images.
+ let heteroImageList: Array<{ id: string; url: string }> | undefined;
+ if (attachedFileIds && attachedFileIds.length > 0) {
+ try {
+ const attachmentMeta = await resolveAttachmentMetadata({
+ db: this.db,
+ fileIds: attachedFileIds,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ const images = attachmentMeta
+ .filter((file) => (file.fileType || '').startsWith('image'))
+ .map((file) => ({ id: file.id, url: file.url }));
+ if (images.length > 0) heteroImageList = images;
+ } catch (err) {
+ log('execAgent: failed to resolve hetero image attachments: %O', err);
+ }
+ }
+
const heteroParams = {
agentType: heteroType,
assistantMessageId: assistantMsg.id,
githubToken,
+ imageList: heteroImageList,
jwt: operationJwt,
operationId,
prompt,
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 84093b9efad..3d200d16875 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -642,6 +642,8 @@ export class DeviceGateway {
agentType: HeterogeneousAgentType;
cwd?: string;
deviceId?: string;
+ /** Image attachments forwarded to the device as fetchable (signed) URLs. */
+ imageList?: Array<{ id?: string; url: string }>;
jwt: string;
operationId: string;
prompt: string;
diff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts
index b1dfbfa4aae..536eec91684 100644
--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts
+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts
@@ -1,3 +1,11 @@
+// IMPORTANT: import from `/protocol`, NOT `/spawn` β€” the spawn barrel drags
+// fs-heavy machinery into the Next.js server bundle, and its dynamic
+// `process.cwd()`-rooted fs calls make Vercel's file tracing pull the whole
+// repo source tree into every serverless function (250 MB limit blowout).
+import {
+ buildHeteroExecStdinPayload,
+ type HeteroExecImageRef,
+} from '@lobechat/heterogeneous-agents/protocol';
import debug from 'debug';
import { appEnv } from '@/envs/app';
@@ -15,6 +23,12 @@ export interface SandboxRunParams {
cwd?: string;
/** GitHub OAuth token for cloning private repos. */
githubToken?: string;
+ /**
+ * Image attachments from the user message, as URLs the sandbox can fetch
+ * (signed S3 URLs). Appended as image content blocks after the prompt so
+ * the CLI gets vision input.
+ */
+ imageList?: HeteroExecImageRef[];
/** Operation-scoped JWT injected as LOBEHUB_JWT env in the sandbox. */
jwt: string;
marketService: MarketService;
@@ -153,16 +167,14 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<void
// Encode the prompt as base64 to avoid all shell quoting issues.
// echo + shell quoting mangled inner JSON quotes; base64 is quote-safe.
- // When systemContext is provided, send a content-block array so CC sees the
- // context block first, then the user's actual message. lh already handles
- // JSON arrays via coerceJsonPrompt β€” no lh changes required.
- const { systemContext } = params;
- const stdinPayload = systemContext
- ? JSON.stringify([
- { text: systemContext, type: 'text' },
- { text: prompt, type: 'text' },
- ])
- : JSON.stringify(prompt);
+ // systemContext / image attachments turn the payload into a content-block
+ // array. lh already handles both shapes via coerceJsonPrompt β€” no lh
+ // changes required.
+ const stdinPayload = buildHeteroExecStdinPayload({
+ imageList: params.imageList,
+ prompt,
+ systemContext: params.systemContext,
+ });
const base64Payload = Buffer.from(stdinPayload).toString('base64');
// LOBEHUB_HETERO_SERVER_URL overrides the server URL for local dev/testing
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 1b8d08c288e..23170357895 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -183,6 +183,8 @@ export class GatewayHttpClient {
agentType: string;
cwd?: string;
deviceId?: string;
+ /** Image attachments forwarded into the `agent_run_request` message. */
+ imageList?: Array<{ id?: string; url: string }>;
jwt: string;
operationId: string;
prompt: string;
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 0333e20815b..5a729ccf222 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -196,6 +196,13 @@ export interface RpcResponseMessage {
export interface AgentRunRequestMessage {
agentType: string;
cwd?: string;
+ /**
+ * Image attachments from the user message, as URLs the device can fetch
+ * (signed S3 URLs). Appended as image content blocks after the prompt so
+ * the CLI gets vision input β€” mirrors the desktop local-mode
+ * `sendPrompt(imageList)` path. Optional β€” omitted for older servers.
+ */
+ imageList?: Array<{ id?: string; url: string }>;
jwt: string;
operationId: string;
prompt: string;
diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.json
index 4a9f6a65b9c..f18a3fb17b0 100644
--- a/packages/heterogeneous-agents/package.json
+++ b/packages/heterogeneous-agents/package.json
@@ -2,10 +2,12 @@
"name": "@lobechat/heterogeneous-agents",
"version": "1.0.0",
"private": true,
+ "sideEffects": false,
"exports": {
".": "./src/index.ts",
"./askUser": "./src/askUser/index.ts",
"./client": "./src/client/index.ts",
+ "./protocol": "./src/protocol/index.ts",
"./spawn": "./src/spawn/index.ts"
},
"main": "./src/index.ts",
diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts
new file mode 100644
index 00000000000..096a856088b
--- /dev/null
+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildHeteroExecStdinPayload } from './execStdinPayload';
+
+describe('buildHeteroExecStdinPayload', () => {
+ it('returns a plain JSON string when no systemContext or images', () => {
+ const payload = buildHeteroExecStdinPayload({ prompt: 'hello' });
+ expect(payload).toBe(JSON.stringify('hello'));
+ expect(JSON.parse(payload)).toBe('hello');
+ });
+
+ it('builds a content-block array with systemContext first', () => {
+ const payload = buildHeteroExecStdinPayload({ prompt: 'hello', systemContext: 'ctx' });
+ expect(JSON.parse(payload)).toEqual([
+ { text: 'ctx', type: 'text' },
+ { text: 'hello', type: 'text' },
+ ]);
+ });
+
+ it('appends image blocks after the prompt', () => {
+ const payload = buildHeteroExecStdinPayload({
+ imageList: [{ id: 'file-1', url: 'https://x/a.png' }],
+ prompt: 'look at this',
+ });
+ expect(JSON.parse(payload)).toEqual([
+ { text: 'look at this', type: 'text' },
+ { source: { id: 'file-1', type: 'url', url: 'https://x/a.png' }, type: 'image' },
+ ]);
+ });
+
+ it('orders systemContext, prompt, then images', () => {
+ const payload = buildHeteroExecStdinPayload({
+ imageList: [{ id: 'file-1', url: 'https://x/a.png' }, { url: 'https://x/b.jpg' }],
+ prompt: 'compare these',
+ systemContext: 'ctx',
+ });
+ expect(JSON.parse(payload)).toEqual([
+ { text: 'ctx', type: 'text' },
+ { text: 'compare these', type: 'text' },
+ { source: { id: 'file-1', type: 'url', url: 'https://x/a.png' }, type: 'image' },
+ { source: { type: 'url', url: 'https://x/b.jpg' }, type: 'image' },
+ ]);
+ });
+
+ it('treats an empty imageList like no images', () => {
+ const payload = buildHeteroExecStdinPayload({ imageList: [], prompt: 'hello' });
+ expect(payload).toBe(JSON.stringify('hello'));
+ });
+});
diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts
new file mode 100644
index 00000000000..69398585891
--- /dev/null
+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts
@@ -0,0 +1,43 @@
+import type { AgentContentBlock } from './types';
+
+/**
+ * Image attachment reference carried through the hetero dispatch protocols
+ * (gateway `agent_run_request`, sandbox runner). The URL must be fetchable by
+ * the executing CLI (e.g. a signed S3 URL) β€” `lh hetero exec` resolves it via
+ * `normalizeImage` into base64 (Claude Code) or a materialized file path
+ * (Codex `--image`).
+ */
+export interface HeteroExecImageRef {
+ /** Stable file id, forwarded into the image source for cache dedupe. */
+ id?: string;
+ /** Resolved URL the executing CLI can fetch. */
+ url: string;
+}
+
+/**
+ * Build the `--input-json` stdin payload for a dispatched `lh hetero exec`
+ * run. Shared by every dispatch site (desktop `spawnLhHeteroExec`, the
+ * `lh connect` daemon's agent-run handler, and the server sandbox runner) so
+ * the payload shape can't drift between them.
+ *
+ * Plain prompt with no context/images stays a JSON string (the historical
+ * shape); anything richer becomes a content-block array, which
+ * `lh hetero exec` coerces via `coerceJsonPrompt` β€” systemContext first, then
+ * the user prompt, then image blocks.
+ */
+export const buildHeteroExecStdinPayload = (params: {
+ imageList?: HeteroExecImageRef[];
+ prompt: string;
+ systemContext?: string;
+}): string => {
+ const { imageList = [], prompt, systemContext } = params;
+ if (!systemContext && imageList.length === 0) return JSON.stringify(prompt);
+
+ const blocks: AgentContentBlock[] = [];
+ if (systemContext) blocks.push({ text: systemContext, type: 'text' });
+ blocks.push({ text: prompt, type: 'text' });
+ for (const image of imageList) {
+ blocks.push({ source: { id: image.id, type: 'url', url: image.url }, type: 'image' });
+ }
+ return JSON.stringify(blocks);
+};
diff --git a/packages/heterogeneous-agents/src/protocol/index.ts b/packages/heterogeneous-agents/src/protocol/index.ts
new file mode 100644
index 00000000000..4edc9d4d4c3
--- /dev/null
+++ b/packages/heterogeneous-agents/src/protocol/index.ts
@@ -0,0 +1,17 @@
+/**
+ * Wire contract between hetero dispatch sites and the executing
+ * `lh hetero exec` CLI. Pure and isomorphic β€” no fs, no process, no node-only
+ * imports β€” so any dispatcher (desktop main, `lh connect` daemon, server
+ * sandbox runner) can depend on it without dragging in the spawn machinery.
+ *
+ * Executor-side helpers that materialize this contract (`normalizeImage`,
+ * `buildAgentInput`, `spawnAgent`, …) live under `./spawn` instead.
+ */
+export { buildHeteroExecStdinPayload, type HeteroExecImageRef } from './execStdinPayload';
+export type {
+ AgentContentBlock,
+ AgentImageBlock,
+ AgentImageSource,
+ AgentPromptInput,
+ AgentTextBlock,
+} from './types';
diff --git a/packages/heterogeneous-agents/src/spawn/input/types.ts b/packages/heterogeneous-agents/src/protocol/types.ts
similarity index 100%
rename from packages/heterogeneous-agents/src/spawn/input/types.ts
rename to packages/heterogeneous-agents/src/protocol/types.ts
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 467170be0e5..32fc9188c8b 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -34,6 +34,8 @@ export {
type AgentTextBlock,
buildAgentInput,
type BuildAgentInputOptions,
+ buildHeteroExecStdinPayload,
+ type HeteroExecImageRef,
materializeImageToPath,
type NormalizedImage,
normalizeImage,
diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts
index 90f3ea7244a..ec8c4d0f8f2 100644
--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts
+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts
@@ -1,9 +1,14 @@
import { tmpdir } from 'node:os';
import path from 'node:path';
+import type {
+ AgentContentBlock,
+ AgentImageBlock,
+ AgentPromptInput,
+ AgentTextBlock,
+} from '../../protocol';
import type { NormalizedImage, NormalizeImageOptions } from './normalizeImage';
import { materializeImageToPath, normalizeImage } from './normalizeImage';
-import type { AgentContentBlock, AgentImageBlock, AgentPromptInput, AgentTextBlock } from './types';
export interface BuildAgentInputOptions extends NormalizeImageOptions {
/**
diff --git a/packages/heterogeneous-agents/src/spawn/input/index.ts b/packages/heterogeneous-agents/src/spawn/input/index.ts
index 01b7f01f22b..27f0e28d053 100644
--- a/packages/heterogeneous-agents/src/spawn/input/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/input/index.ts
@@ -1,3 +1,16 @@
+// The wire contract (stdin payload builder + content-block types) lives in
+// `../../protocol` so dispatch-only consumers (server sandbox runner) can
+// import it without bundling the fs-heavy spawn machinery. Re-exported here
+// so executor-side callers keep a single `./spawn` entry.
+export {
+ type AgentContentBlock,
+ type AgentImageBlock,
+ type AgentImageSource,
+ type AgentPromptInput,
+ type AgentTextBlock,
+ buildHeteroExecStdinPayload,
+ type HeteroExecImageRef,
+} from '../../protocol';
export {
type AgentInputPlan,
buildAgentInput,
@@ -9,10 +22,3 @@ export {
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.ts
index 0a66ce75685..7c417465514 100644
--- a/packages/heterogeneous-agents/src/spawn/input/normalizeImage.ts
+++ b/packages/heterogeneous-agents/src/spawn/input/normalizeImage.ts
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
-import type { AgentImageSource } from './types';
+import type { AgentImageSource } from '../../protocol';
export interface NormalizedImage {
buffer: Buffer;