π€― 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
β»οΈ refactor: implement cloud hetero agent exec pipeline (step 3 + step 4) (#14486)
LiJianf934e2ff46bd
diff --git a/apps/cli/man/man1/lh.1 b/apps/cli/man/man1/lh.1index 220217c240a..076cfaa495e 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.11" "User Commands"+.TH LH 1 "" "@lobehub/cli 0.0.14" "User Commands".SH NAMElh \- LobeHub CLI \- manage and connect to LobeHub services.SH SYNOPSISdiff --git a/apps/cli/package.json b/apps/cli/package.jsonindex cc19ecd563d..1eea6e62276 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -1,6 +1,6 @@{"name": "@lobehub/cli",- "version": "0.0.11",+ "version": "0.0.14","type": "module","bin": {"lh": "./dist/index.js",diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex ffc04653b7f..05bb004f82a 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -10,7 +10,10 @@ import type {import { spawnAgent } from '@lobechat/heterogeneous-agents/spawn';import type { Command } from 'commander';+import { getTrpcClient } from '../api/client';+import { BatchIngester, NoopIngestSink } from '../utils/BatchIngester';import { log } from '../utils/logger';+import { TrpcIngestSink } from '../utils/TrpcIngestSink';const SUPPORTED_AGENT_TYPES = new Set(['claude-code', 'codex']);@@ -21,7 +24,22 @@ interface ExecOptions {inputJson?: string;operationId?: string;prompt?: string;+ /**+ * Output rendering mode.+ * jsonl β emit each `AgentStreamEvent` as a JSONL line on stdout (default+ * when no --topic is set, or when explicitly requested).+ * none β suppress JSONL stdout; only server-ingest mode is active.+ * Default when --topic is set and running non-interactively.+ */+ render?: 'jsonl' | 'none';resume?: string;+ /**+ * Server topic id. When set, enables server-ingest mode: events are+ * batch-POSTed to `aiAgent.heteroIngest` in addition to (or instead of)+ * being written to stdout. Requires `--operation-id` to be a valid+ * server-allocated operation id.+ */+ topic?: string;type: string;}@@ -171,12 +189,35 @@ const exec = async (options: ExecOptions): Promise<void> => {process.exit(2);}- // Standalone (phase 1a): no server ingest, so the operationId is just an- // identity stamp on the JSONL stream. Generate a fresh one if the caller- // didn't provide --operation-id; phase 1b will require it as a real- // server-allocated id.+ // Server-ingest mode is active when --topic is provided.+ // --operation-id must be a server-allocated id in this mode (the server+ // generates it before spawning the process and passes it via CLI args).+ const serverIngest = !!options.topic;+ if (serverIngest && !options.operationId) {+ log.error('--operation-id is required when --topic is set (server-ingest mode).');+ process.exit(2);+ }+const operationId = options.operationId || randomUUID();+ // Determine JSONL output mode.+ // Explicit --render flag always wins. Otherwise: emit JSONL in standalone+ // mode; suppress in server-ingest mode (sink handles the data path).+ const emitJsonl = options.render === 'jsonl' || (options.render === undefined && !serverIngest);++ // Build the ingest sink β no-op for standalone mode, real tRPC sink for+ // server-ingest mode. The tRPC client reads LOBEHUB_JWT (operation-scoped+ // JWT injected by the server) for authentication.+ const agentType = options.type as 'claude-code' | 'codex';+ let sink: InstanceType<typeof TrpcIngestSink> | InstanceType<typeof NoopIngestSink>;+ if (serverIngest) {+ const client = await getTrpcClient();+ sink = new TrpcIngestSink(client, agentType, operationId, options.topic!);+ } else {+ sink = new NoopIngestSink();+ }+ const ingester = new BatchIngester(sink);+// `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@@ -203,36 +244,93 @@ const exec = async (options: ExecOptions): Promise<void> => {// Ctrl-C β SIGINT to the child's process group so the spawned CLI gets a// chance to clean up. Repeated Ctrl-C escalates to SIGKILL via the// standard "double-tap" pattern most CLIs implement themselves.+ // In server-ingest mode, drain the ingester and call heteroFinish before+ // exiting so the server knows the operation was cancelled.let interrupted = false;- const onSigint = () => {+ const onSigint = async () => {if (interrupted) {handle.kill('SIGKILL');return;}interrupted = true;handle.kill('SIGINT');+ if (serverIngest) {+ try {+ await ingester.drain();+ await sink.finish({ result: 'cancelled' });+ } catch {+ // best-effort; process is exiting anyway+ }+ }};process.on('SIGINT', onSigint);- process.on('SIGTERM', () => handle.kill('SIGTERM'));+ process.on('SIGTERM', async () => {+ handle.kill('SIGTERM');+ if (serverIngest) {+ try {+ await ingester.drain();+ await sink.finish({ result: 'cancelled' });+ } catch {+ // best-effort+ }+ }+ });- // Stream events out as JSONL on stdout. Each line is one `AgentStreamEvent`.- // Use raw write (not console.log) so we don't pull in console formatting- // and JSONL stays parseable downstream.+ // Stream events. Each event is optionally written as JSONL and always+ // pushed into the ingester (which batches and sends to the server).+ let ingestError = false;try {for await (const event of handle.events) {- process.stdout.write(`${JSON.stringify(event)}\n`);+ if (emitJsonl) {+ process.stdout.write(`${JSON.stringify(event)}\n`);+ }+ ingester.push(event);}} catch (err) {log.error('Stream error from agent process:', err instanceof Error ? err.message : String(err));+ if (serverIngest) {+ try {+ await ingester.drain();+ await sink.finish({+ result: 'error',+ error: { message: String(err), type: 'stream_error' },+ });+ } catch {+ // best-effort+ }+ }process.exit(1);} finally {process.off('SIGINT', onSigint);}- // Pass the child's exit code through. Signal-induced exits (SIGINT etc.)- // surface as `code === null` β map to 130 (POSIX convention for SIGINT).+ // Pass the child's exit code through. In server-ingest mode, drain the+ // ingester and call heteroFinish before exiting.const { code, signal } = await handle.exit;- if (code !== null) process.exit(code);++ if (serverIngest) {+ try {+ await ingester.drain();+ } catch (err) {+ log.error(+ 'Failed to flush events to server:',+ err instanceof Error ? err.message : String(err),+ );+ ingestError = true;+ }++ const exitedClean = !ingestError && (code === 0 || signal === 'SIGTERM');+ try {+ await sink.finish({+ result: exitedClean ? 'success' : 'error',+ sessionId: handle.sessionId,+ });+ } catch (err) {+ log.error('Failed to send heteroFinish:', err instanceof Error ? err.message : String(err));+ }+ }++ if (code !== null) process.exit(ingestError ? 1 : code);if (signal === 'SIGINT') process.exit(130);if (signal === 'SIGTERM') process.exit(143);if (signal === 'SIGKILL') process.exit(137);@@ -268,7 +366,15 @@ export function registerHeteroCommand(program: Command) {).option('--operation-id <id>',- 'Operation id stamped onto every emitted event. Generated as a uuid if omitted (phase 1a).',+ 'Operation id stamped onto every emitted event. Required in server-ingest mode (--topic). Generated as a UUID if omitted (standalone).',+ )+ .option(+ '--topic <topicId>',+ 'Server topic id. Enables server-ingest mode: events are batch-POSTed to aiAgent.heteroIngest. Requires --operation-id.',+ )+ .option(+ '--render <mode>',+ 'Output mode: jsonl (emit events as JSONL on stdout) | none (suppress stdout). Defaults to jsonl in standalone, none in server-ingest mode.',).action(exec);}diff --git a/apps/cli/src/utils/BatchIngester.ts b/apps/cli/src/utils/BatchIngester.tsnew file mode 100644index 00000000000..52d1452cc7e--- /dev/null+++ b/apps/cli/src/utils/BatchIngester.ts@@ -0,0 +1,99 @@+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';++export interface IngestSink {+ finish: (params: {+ error?: { message: string; type: string };+ result: 'cancelled' | 'error' | 'success';+ sessionId?: string;+ }) => Promise<void>;+ ingest: (events: AgentStreamEvent[]) => Promise<void>;+}++export class NoopIngestSink implements IngestSink {+ async finish(_params: Parameters<IngestSink['finish']>[0]): Promise<void> {}+ async ingest(_events: AgentStreamEvent[]): Promise<void> {}+}++const MAX_BATCH = 50;+const FLUSH_INTERVAL_MS = 250;+const MAX_RETRIES = 5;++const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));++/**+ * Buffers `AgentStreamEvent`s and flushes them in batches to an `IngestSink`.+ *+ * Flush triggers:+ * - Buffer reaches MAX_BATCH (50) β immediate flush+ * - FLUSH_INTERVAL_MS (250ms) timer fires β flush whatever is buffered+ *+ * Each batch is retried up to MAX_RETRIES (5) times with exponential back-off+ * starting at 500ms, doubling up to 8s. After the final retry the error is+ * stored and re-thrown by `drain()`, allowing the caller to call+ * `sink.finish({ result: 'error' })` and exit(1).+ *+ * Call order: push() repeatedly β drain() once (before finish()).+ */+export class BatchIngester {+ private buffer: AgentStreamEvent[] = [];+ private fatalError: Error | null = null;+ private inflightFlush: Promise<void> = Promise.resolve();+ private timer: ReturnType<typeof setTimeout> | null = null;++ constructor(private readonly sink: IngestSink) {}++ push(event: AgentStreamEvent): void {+ if (this.fatalError) return;+ this.buffer.push(event);+ if (this.buffer.length >= MAX_BATCH) {+ if (this.timer) {+ clearTimeout(this.timer);+ this.timer = null;+ }+ this.triggerFlush();+ } else if (!this.timer) {+ this.timer = setTimeout(() => {+ this.timer = null;+ this.triggerFlush();+ }, FLUSH_INTERVAL_MS);+ }+ }++ /** Flush remaining buffer and wait for all in-flight sends to settle. */+ async drain(): Promise<void> {+ if (this.timer) {+ clearTimeout(this.timer);+ this.timer = null;+ }+ this.triggerFlush();+ await this.inflightFlush;+ if (this.fatalError) throw this.fatalError;+ }++ private async sendWithRetry(batch: AgentStreamEvent[]): Promise<void> {+ let delay = 500;+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {+ try {+ await this.sink.ingest(batch);+ return;+ } catch (err) {+ if (attempt === MAX_RETRIES) {+ this.fatalError = err instanceof Error ? err : new Error(String(err));+ throw this.fatalError;+ }+ await sleep(delay);+ delay = Math.min(delay * 2, 8_000);+ }+ }+ }++ private triggerFlush(): void {+ if (this.fatalError || this.buffer.length === 0) return;+ const batch = this.buffer.splice(0);+ this.inflightFlush = this.inflightFlush+ .then(() => this.sendWithRetry(batch))+ .catch(() => {+ // fatalError is already set; drain() re-throws it+ });+ }+}diff --git a/apps/cli/src/utils/TrpcIngestSink.ts b/apps/cli/src/utils/TrpcIngestSink.tsnew file mode 100644index 00000000000..1a097b670dd--- /dev/null+++ b/apps/cli/src/utils/TrpcIngestSink.ts@@ -0,0 +1,38 @@+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';++import type { TrpcClient } from '../api/client';+import type { IngestSink } from './BatchIngester';++/**+ * `IngestSink` implementation that forwards batches to the server via tRPC+ * (`aiAgent.heteroIngest` / `aiAgent.heteroFinish`).+ *+ * The CLI authenticates using the `LOBEHUB_JWT` env var (operation-scoped JWT+ * injected by the server before spawning the sandbox / desktop process).+ */+export class TrpcIngestSink implements IngestSink {+ constructor(+ private readonly client: TrpcClient,+ private readonly agentType: 'claude-code' | 'codex',+ private readonly operationId: string,+ private readonly topicId: string,+ ) {}++ async finish(params: Parameters<IngestSink['finish']>[0]): Promise<void> {+ await this.client.aiAgent.heteroFinish.mutate({+ agentType: this.agentType,+ operationId: this.operationId,+ topicId: this.topicId,+ ...params,+ });+ }++ async ingest(events: AgentStreamEvent[]): Promise<void> {+ await this.client.aiAgent.heteroIngest.mutate({+ agentType: this.agentType,+ events: events as any,+ operationId: this.operationId,+ topicId: this.topicId,+ });+ }+}diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex e62852145c6..ce93c2fd1c1 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -1,7 +1,9 @@+import type { AgentRunRequestMessage } from '@lobechat/device-gateway-client';import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';import GatewayConnectionService from '@/services/gatewayConnectionSrv';+import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';import { ControllerModule, IpcMethod } from './index';import LocalFileCtr from './LocalFileCtr';import RemoteServerConfigCtr from './RemoteServerConfigCtr';@@ -33,6 +35,10 @@ export default class GatewayConnectionCtr extends ControllerModule {return this.app.getController(ShellCommandCtr);}+ private get heterogeneousAgentCtr() {+ return this.app.getController(HeterogeneousAgentCtr);+ }+// βββ Lifecycle βββafterAppReady() {@@ -47,6 +53,9 @@ export default class GatewayConnectionCtr extends ControllerModule {// Wire up tool call handlersrv.setToolCallHandler((apiName, args) => this.executeToolCall(apiName, args));+ // Wire up agent run handler+ srv.setAgentRunHandler((request) => this.executeAgentRun(request));+// Auto-connect if already logged inthis.tryAutoConnect();}@@ -108,6 +117,45 @@ export default class GatewayConnectionCtr extends ControllerModule {await this.service.connect();}+ // βββ Agent Run Routing βββ++ private async executeAgentRun(+ request: AgentRunRequestMessage,+ ): Promise<{ reason?: string; status: 'accepted' | 'rejected' }> {+ try {+ const ctr = this.heterogeneousAgentCtr;++ // Create a session for the hetero agent.+ const { sessionId } = await ctr.startSession({+ agentType: request.agentType,+ args: [],+ command: request.agentType === 'codex' ? 'codex' : 'claude',+ cwd: request.cwd,+ // Inject LOBEHUB_JWT so the CLI authenticates against heteroIngest.+ env: { LOBEHUB_JWT: request.jwt },+ resumeSessionId: request.resumeSessionId,+ });++ // Fire-and-forget: sendPrompt runs the CLI until completion.+ ctr+ .sendPrompt({+ operationId: request.operationId,+ prompt: request.prompt,+ sessionId,+ })+ .catch((err: Error) => {+ // Errors are surfaced via heteroFinish on the server side.+ // Log locally for desktop debugging only.+ console.error('[GatewayConnectionCtr] agent run failed:', err.message);+ });++ return { status: 'accepted' };+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err);+ return { reason, status: 'rejected' };+ }+ }+// βββ Tool Call Routing βββprivate async executeToolCall(apiName: string, args: any): Promise<unknown> {diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.tsindex 9a6154f6c10..d3ca9b525d7 100644--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';import os from 'node:os';import type {+ AgentRunRequestMessage,SystemInfoRequestMessage,ToolCallRequestMessage,} from '@lobechat/device-gateway-client';@@ -21,6 +22,10 @@ interface ToolCallHandler {(apiName: string, args: any): Promise<unknown>;}+interface AgentRunHandler {+ (request: AgentRunRequestMessage): Promise<{ reason?: string; status: 'accepted' | 'rejected' }>;+}+/*** GatewayConnectionService*@@ -35,6 +40,7 @@ export default class GatewayConnectionService extends ServiceModule {private tokenProvider: (() => Promise<string | null>) | null = null;private tokenRefresher: (() => Promise<{ error?: string; success: boolean }>) | null = null;private toolCallHandler: ToolCallHandler | null = null;+ private agentRunHandler: AgentRunHandler | null = null;// βββ Configuration βββ@@ -59,6 +65,10 @@ export default class GatewayConnectionService extends ServiceModule {this.toolCallHandler = handler;}+ setAgentRunHandler(handler: AgentRunHandler) {+ this.agentRunHandler = handler;+ }+// βββ Device ID βββloadOrCreateDeviceId() {@@ -178,6 +188,10 @@ export default class GatewayConnectionService extends ServiceModule {this.handleSystemInfoRequest(client, request);});+ client.on('agent_run_request', (request) => {+ this.handleAgentRunRequest(client, request);+ });+client.on('auth_expired', () => {logger.warn('Received auth_expired, will reconnect with refreshed token');this.handleAuthExpired();@@ -239,6 +253,30 @@ export default class GatewayConnectionService extends ServiceModule {});}+ // βββ Agent Run βββ++ private handleAgentRunRequest = async (+ client: GatewayClient,+ request: AgentRunRequestMessage,+ ) => {+ logger.info(+ `Received agent_run_request: operationId=${request.operationId} type=${request.agentType}`,+ );++ if (!this.agentRunHandler) {+ logger.warn('No agent run handler configured, rejecting request');+ client.sendAgentRunAck({+ operationId: request.operationId,+ reason: 'no handler',+ status: 'rejected',+ });+ return;+ }++ const result = await this.agentRunHandler(request);+ client.sendAgentRunAck({ operationId: request.operationId, ...result });+ };+// βββ Tool Call Routing βββprivate handleToolCallRequest = async (diff --git a/apps/device-gateway/src/DeviceGatewayDO.ts b/apps/device-gateway/src/DeviceGatewayDO.tsindex 791248fa6f8..b193f4765d8 100644--- a/apps/device-gateway/src/DeviceGatewayDO.ts+++ b/apps/device-gateway/src/DeviceGatewayDO.ts@@ -2,7 +2,7 @@ import { DurableObject } from 'cloudflare:workers';import { Hono } from 'hono';import { resolveSocketAuth, verifyApiKeyToken, verifyDesktopToken } from './auth';-import type { DeviceAttachment, Env } from './types';+import type { AgentRunRequestMessage, DeviceAttachment, Env } from './types';const AUTH_TIMEOUT = 10_000; // 10s to authenticate after connectconst HEARTBEAT_TIMEOUT = 90_000; // 90s without heartbeat β close@@ -31,6 +31,9 @@ export class DeviceGatewayDO extends DurableObject<Env> {.post('/api/device/system-info', async (c) => {return this.handleSystemInfo(c.req.raw);})+ .post('/api/device/agent/run', async (c) => {+ return this.handleAgentRun(c.req.raw);+ }).all('/api/device/devices', async () => {const sockets = this.getAuthenticatedSockets();const devices = sockets.map((ws) => ws.deserializeAttachment() as DeviceAttachment);@@ -102,12 +105,16 @@ export class DeviceGatewayDO extends DurableObject<Env> {if (!att.authenticated) return;// βββ Business messages (authenticated only) βββ- if (data.type === 'tool_call_response' || data.type === 'system_info_response') {- const pending = this.pendingRequests.get(data.requestId);+ if (+ data.type === 'tool_call_response' ||+ data.type === 'system_info_response' ||+ data.type === 'agent_run_ack'+ ) {+ const pending = this.pendingRequests.get(data.requestId ?? data.operationId);if (pending) {clearTimeout(pending.timer);- pending.resolve(data.result);- this.pendingRequests.delete(data.requestId);+ pending.resolve(data.type === 'agent_run_ack' ? data : data.result);+ this.pendingRequests.delete(data.requestId ?? data.operationId);}}@@ -278,6 +285,60 @@ export class DeviceGatewayDO extends DurableObject<Env> {}}+ // βββ Agent Run RPC βββ++ private async handleAgentRun(request: Request): Promise<Response> {+ const sockets = this.getAuthenticatedSockets();+ if (sockets.length === 0) {+ return Response.json({ error: 'DEVICE_OFFLINE', success: false }, { status: 503 });+ }++ const body = (await request.json()) as {+ agentType: 'claude-code' | 'codex';+ cwd?: string;+ deviceId?: string;+ jwt: string;+ operationId: string;+ prompt: string;+ resumeSessionId?: string;+ timeout?: number;+ topicId: string;+ };+ const { deviceId, timeout = 10_000, ...runParams } = body;++ const targetWs = deviceId+ ? sockets.find((ws) => {+ const att = ws.deserializeAttachment() as DeviceAttachment;+ return att.deviceId === deviceId;+ })+ : sockets[0];++ if (!targetWs) {+ return Response.json({ error: 'DEVICE_NOT_FOUND', success: false }, { status: 503 });+ }++ try {+ const ack = await new Promise<{ status: string }>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pendingRequests.delete(runParams.operationId);+ reject(new Error('TIMEOUT'));+ }, timeout);++ this.pendingRequests.set(runParams.operationId, { resolve, timer });++ const msg: AgentRunRequestMessage = { type: 'agent_run_request', ...runParams };+ targetWs.send(JSON.stringify(msg));+ });++ if (ack.status === 'rejected') {+ return Response.json({ error: 'DEVICE_REJECTED', success: false }, { status: 422 });+ }+ return Response.json({ success: true });+ } catch (err) {+ return Response.json({ error: (err as Error).message, success: false }, { status: 504 });+ }+ }+// βββ Tool Call RPC βββprivate async handleToolCall(request: Request): Promise<Response> {diff --git a/apps/device-gateway/src/types.ts b/apps/device-gateway/src/types.tsindex 7fb79821a44..73098fa52ac 100644--- a/apps/device-gateway/src/types.ts+++ b/apps/device-gateway/src/types.ts@@ -92,12 +92,42 @@ export interface SystemInfoRequestMessage {type: 'system_info_request';}+/**+ * CF β Desktop: request the desktop to spawn `lh hetero exec` for a+ * heterogeneous agent run. The JWT is operation-scoped (4h TTL) and only+ * grants `heteroIngest` / `heteroFinish` for this operationId.+ */+export interface AgentRunRequestMessage {+ agentType: 'claude-code' | 'codex';+ /** Working directory to pass to `lh hetero exec --cwd`. */+ cwd?: string;+ /** Operation-scoped JWT signed by the server β inject as LOBEHUB_JWT env. */+ jwt: string;+ operationId: string;+ /** Plain-text prompt to pass via `lh hetero exec --prompt`. */+ prompt: string;+ /** Native CLI session id for `lh hetero exec --resume`. */+ resumeSessionId?: string;+ topicId: string;+ type: 'agent_run_request';+}++/** Desktop β CF: acknowledgement for an `agent_run_request`. */+export interface AgentRunAckMessage {+ operationId: string;+ reason?: string;+ status: 'accepted' | 'rejected';+ type: 'agent_run_ack';+}+export type ClientMessage =+ | AgentRunAckMessage| AuthMessage| HeartbeatMessage| SystemInfoResponseMessage| ToolCallResponseMessage;export type ServerMessage =+ | AgentRunRequestMessage| AuthExpiredMessage| AuthFailedMessage| AuthSuccessMessagediff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.tsindex 9bbfc733cc1..76abfad379b 100644--- a/packages/device-gateway-client/src/client.ts+++ b/packages/device-gateway-client/src/client.ts@@ -5,6 +5,8 @@ import os from 'node:os';import WebSocket from 'ws';import type {+ AgentRunAckMessage,+ AgentRunRequestMessage,ClientMessage,ConnectionStatus,GatewayClientEvents,@@ -151,6 +153,13 @@ export class GatewayClient extends EventEmitter {});}+ sendAgentRunAck(response: Omit<AgentRunAckMessage, 'type'>): void {+ this.sendMessage({+ ...response,+ type: 'agent_run_ack',+ });+ }+// βββ Connection Logic βββprivate doConnect() {@@ -252,6 +261,11 @@ export class GatewayClient extends EventEmitter {break;}+ case 'agent_run_request': {+ this.emit('agent_run_request', message as AgentRunRequestMessage);+ break;+ }+case 'auth_expired': {this.logger.warn('Received auth_expired from gateway');this.emit('auth_expired');diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex 6aefb44bfd1..90a9bd2cb79 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -73,6 +73,27 @@ export class GatewayHttpClient {};}+ async dispatchAgentRun(params: {+ agentType: 'claude-code' | 'codex';+ cwd?: string;+ deviceId?: string;+ jwt: string;+ operationId: string;+ prompt: string;+ resumeSessionId?: string;+ timeout?: number;+ topicId: string;+ userId: string;+ }): Promise<{ success: boolean; error?: string }> {+ const { userId: _userId, ...body } = params;+ const res = await this.post('/api/device/agent/run', body);+ if (!res.ok) {+ const text = await res.text().catch(() => '');+ return { error: text || `HTTP ${res.status}`, success: false };+ }+ return { success: true };+ }+async getDeviceSystemInfo(userId: string,deviceId: string,diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex 3354999514b..26444d13b94 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -88,12 +88,34 @@ export interface SystemInfoResponseMessage {type: 'system_info_response';}+/** Server β Client: request the desktop to spawn `lh hetero exec`. */+export interface AgentRunRequestMessage {+ agentType: 'claude-code' | 'codex';+ cwd?: string;+ jwt: string;+ operationId: string;+ prompt: string;+ resumeSessionId?: string;+ topicId: string;+ type: 'agent_run_request';+}++/** Client β Server: acknowledgement for an agent_run_request. */+export interface AgentRunAckMessage {+ operationId: string;+ reason?: string;+ status: 'accepted' | 'rejected';+ type: 'agent_run_ack';+}+export type ClientMessage =+ | AgentRunAckMessage| AuthMessage| HeartbeatMessage| SystemInfoResponseMessage| ToolCallResponseMessage;export type ServerMessage =+ | AgentRunRequestMessage| AuthExpiredMessage| AuthFailedMessage| AuthSuccessMessage@@ -111,6 +133,7 @@ export type ConnectionStatus =| 'reconnecting';export interface GatewayClientEvents {+ agent_run_request: (request: AgentRunRequestMessage) => void;auth_expired: () => void;auth_failed: (reason: string) => void;connected: () => void;diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 031d9b0e85f..c085dc41bfe 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -68,6 +68,13 @@ export interface SpawnAgentHandle {kill: (signal?: NodeJS.Signals) => void;/** Spawned child PID, undefined if spawn failed pre-PID. */pid: number | undefined;+ /**+ * The agent's native session id, extracted from the `system:init` event.+ * Available after the `events` async iterable has been fully consumed.+ * Used by `lh hetero exec` to pass `sessionId` to `heteroFinish` so the+ * server can persist it for `--resume` on the next turn.+ */+ readonly sessionId: string | undefined;/*** The child's stderr stream β caller can pipe to its own stderr or* collect for error reporting. The pipeline does not consume stderr.@@ -83,10 +90,23 @@ const CLAUDE_CODE_BASE_ARGS = ['stream-json','--verbose','--include-partial-messages',- '--permission-mode',- 'bypassPermissions',] as const;+// bypassPermissions is blocked when running as root (e.g. cloud sandbox).+// Fall back to acceptEdits + pre-approved tools so the agent can still run+// headlessly without interactive permission prompts.+const isRunningAsRoot = () => process.getuid?.() === 0;++const CLAUDE_CODE_PERMISSION_ARGS = (): string[] =>+ isRunningAsRoot()+ ? [+ '--permission-mode',+ 'acceptEdits',+ '--allowed-tools',+ 'Bash,Read,Write,Edit,MultiEdit,WebSearch,mcp__*',+ ]+ : ['--permission-mode', 'bypassPermissions'];+const CODEX_REQUIRED_ARGS = ['--json', '--skip-git-repo-check', '--full-auto'] as const;const buildClaudeCodeArgs = (@@ -95,6 +115,7 @@ const buildClaudeCodeArgs = (extraArgs: string[],) => [...CLAUDE_CODE_BASE_ARGS,+ ...CLAUDE_CODE_PERMISSION_ARGS(),...(resumeSessionId ? ['--resume', resumeSessionId] : []),...inputArgs,...extraArgs,@@ -302,6 +323,9 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentexit,kill: (signal: NodeJS.Signals = 'SIGINT') => killProcessTree(proc, signal),pid: proc.pid,+ get sessionId() {+ return pipeline.sessionId;+ },stderr,};};diff --git a/src/server/globalConfig/index.ts b/src/server/globalConfig/index.tsindex 18e03be9163..4dea609606a 100644--- a/src/server/globalConfig/index.ts+++ b/src/server/globalConfig/index.ts@@ -97,10 +97,8 @@ export const getServerGlobalConfig = async () => {}: undefined),- // Expose Agent Gateway URL to client when queue-based agent runtime is enabled- ...(appEnv.enableQueueAgentRuntime && appEnv.AGENT_GATEWAY_URL- ? { agentGatewayUrl: appEnv.AGENT_GATEWAY_URL }- : undefined),+ // Expose Agent Gateway URL to client (used by hetero agents; also required for queue mode)+ ...(appEnv.AGENT_GATEWAY_URL ? { agentGatewayUrl: appEnv.AGENT_GATEWAY_URL } : undefined),image: cleanObject({defaultImageNum: imageEnv.AI_IMAGE_DEFAULT_IMAGE_NUM,diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex f2405c87dd7..980c3726666 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -69,6 +69,7 @@ import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';import { DocumentService } from '@/server/services/document';import { FileService } from '@/server/services/file';+import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';import { KlavisService } from '@/server/services/klavis';import { MarketService } from '@/server/services/market';import { deviceProxy } from '@/server/services/toolExecution/deviceProxy';@@ -622,6 +623,140 @@ export class AiAgentService {const model = agentConfig.model!;const provider = agentConfig.provider!;+ // 3.5. Hetero-agent early exit β Claude Code / Codex agents bypass the+ // server-side LLM pipeline. After topic + message creation we hand off to+ // the device gateway (desktop) or cloud sandbox, which will push events+ // back via `heteroIngest` / `heteroFinish`.+ //+ // Detection: prefer agencyConfig.heterogeneousProvider.type (set by the UI),+ // fall back to model field for backwards compatibility.+ const HETERO_AGENT_MODELS = new Set<string>(['claude-code', 'codex']);+ const heteroProviderType = agentConfig.agencyConfig?.heterogeneousProvider?.type;+ const isHeteroAgent = !!heteroProviderType || HETERO_AGENT_MODELS.has(model);+ if (isHeteroAgent) {+ const heteroType = (heteroProviderType ?? model) as 'claude-code' | 'codex';+ const operationId = nanoid();++ // Create user message so the conversation is visible in the UI immediately.+ const userMsg = effectiveResume+ ? undefined+ : await this.messageModel.create({+ agentId: resolvedAgentId,+ content: prompt,+ role: 'user',+ threadId: appContext?.threadId ?? undefined,+ topicId,+ });++ // Create an assistant message placeholder (shows spinner in the UI).+ const assistantMsg = await this.messageModel.create({+ agentId: resolvedAgentId,+ content: LOADING_FLAT,+ model,+ parentId: parentMessageId ?? userMsg?.id,+ provider,+ role: 'assistant',+ threadId: appContext?.threadId ?? undefined,+ topicId,+ });+ assistantMessageRef.current = assistantMsg.id;++ // Read resume session id for next-turn continuity.+ const heteroService = new HeterogeneousAgentService(this.db, this.userId);+ const resumeSessionId = await heteroService.getHeterogeneousResumeSessionId(topicId);+ // Sign an operation-scoped JWT so the CLI can authenticate against+ // heteroIngest / heteroFinish without full user credentials.+ let operationJwt: string;+ try {+ operationJwt = await signUserJWT(this.userId);+ } catch (err) {+ log('execAgent: failed to sign operation JWT for hetero run: %O', err);+ throw new Error('Failed to sign operation JWT for hetero agent', { cause: err });+ }++ const heteroParams = {+ agentType: heteroType,+ jwt: operationJwt,+ operationId,+ prompt,+ resumeSessionId,+ topicId,+ userId: this.userId,+ };++ // Seed topic.metadata.runningOperation so heteroIngest can validate the operation.+ await this.topicModel.updateMetadata(topicId, {+ runningOperation: {+ assistantMessageId: assistantMsg.id,+ operationId,+ scope: appContext?.scope ?? undefined,+ threadId: appContext?.threadId ?? undefined,+ },+ });++ if (requestedDeviceId) {+ // Dispatch to the user's connected desktop via device-gateway.+ const result = await deviceProxy.dispatchAgentRun({+ ...heteroParams,+ deviceId: requestedDeviceId,+ });+ if (!result.success) {+ log('execAgent: hetero device dispatch failed: %s', result.error);+ await this.messageModel.update(assistantMsg.id, {+ content: '',+ error: {+ body: { detail: result.error },+ message: result.error ?? 'Device dispatch failed',+ type: 'ServerAgentRuntimeError',+ },+ });+ return {+ agentId: resolvedAgentId,+ assistantMessageId: assistantMsg.id,+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: result.error,+ message: 'Hetero agent device dispatch failed',+ operationId,+ status: 'error',+ success: false,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: userMsg?.id ?? parentMessageId ?? '',+ };+ }+ } else {+ // Cloud sandbox path β fire-and-forget; errors surfaced via heteroFinish.+ const { spawnHeteroSandbox } =+ await import('@/server/services/heterogeneousAgent/sandboxRunner');+ spawnHeteroSandbox({ ...heteroParams, marketService: this.marketService }).catch((err) => {+ log('execAgent: hetero sandbox spawn failed: %O', err);+ });+ }++ let gatewayToken: string | undefined;+ try {+ gatewayToken = await signUserJWT(this.userId);+ } catch {+ // non-critical+ }++ return {+ agentId: resolvedAgentId,+ assistantMessageId: assistantMsg.id,+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'Hetero agent dispatched successfully',+ operationId,+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: gatewayToken,+ topicId,+ userMessageId: userMsg?.id ?? parentMessageId ?? '',+ };+ }+// 4. Fetch user settings (memory config + timezone)// Agent-level memory config takes priority; fallback to user-level settingconst agentMemoryEnabled = agentConfig.chatConfig?.memory?.enabled;diff --git a/src/server/services/heterogeneousAgent/sandboxRunner.ts b/src/server/services/heterogeneousAgent/sandboxRunner.tsnew file mode 100644index 00000000000..41341ca34de--- /dev/null+++ b/src/server/services/heterogeneousAgent/sandboxRunner.ts@@ -0,0 +1,94 @@+import debug from 'debug';++import { appEnv } from '@/envs/app';+import type { MarketService } from '@/server/services/market';++const log = debug('lobe-server:hetero-sandbox-runner');++export interface SandboxRunParams {+ agentType: 'claude-code' | 'codex';+ cwd?: string;+ /** Operation-scoped JWT injected as LOBEHUB_JWT env in the sandbox. */+ jwt: string;+ marketService: MarketService;+ operationId: string;+ prompt: string;+ resumeSessionId?: string;+ topicId: string;+ userId: string;+}++/**+ * Launches `lh hetero exec` inside the cloud sandbox via `runCommand`.+ *+ * Uses the same MarketService path as ServerSandboxService.callTool β+ * `marketService.getSDK().plugins.runBuildInTool('runCommand', params, ctx)`.+ *+ * The sandbox container already has `lh` (the LobeHub CLI) installed.+ * The operation-scoped JWT is injected as `LOBEHUB_JWT` so the CLI can+ * authenticate against `heteroIngest` / `heteroFinish` without user creds.+ *+ * Fire-and-forget: the caller does NOT await this β the sandbox pushes events+ * back to the server via `heteroIngest` tRPC batches independently.+ */+export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<void> {+ const {+ agentType,+ cwd,+ jwt,+ marketService,+ operationId,+ prompt,+ resumeSessionId,+ topicId,+ userId,+ } = params;++ // Build the `lh hetero exec` command string.+ // Prompt is passed via --input-json stdin ('-') to avoid shell quoting issues+ // with arbitrary user text in --prompt.+ const args = [+ 'lh',+ 'hetero',+ 'exec',+ '--type',+ agentType,+ '--operation-id',+ operationId,+ '--topic',+ topicId,+ '--render',+ 'none',+ '--input-json',+ '-',+ ];+ if (resumeSessionId) {+ args.push('--resume', resumeSessionId);+ }+ if (cwd) {+ args.push('--cwd', cwd);+ }++ // Encode the prompt as base64 to avoid all shell quoting issues.+ // echo + shell quoting mangled inner JSON quotes; base64 is quote-safe.+ const stdinPayload = JSON.stringify(prompt);+ const base64Payload = Buffer.from(stdinPayload).toString('base64');++ // LOBEHUB_HETERO_SERVER_URL overrides the server URL for local dev/testing+ // (e.g. a cloudflare tunnel). APP_URL is NOT used here because it's tied to+ // auth callbacks and must stay as localhost in dev.+ const serverUrl = process.env.LOBEHUB_HETERO_SERVER_URL ?? appEnv.APP_URL;+ const shellCommand = `echo ${base64Payload} | base64 -d | LOBEHUB_JWT=${JSON.stringify(jwt)} LOBEHUB_SERVER=${JSON.stringify(serverUrl)} ${args.join(' ')}`;++ log(+ 'spawnHeteroSandbox: userId=%s op=%s type=%s topic=%s',+ userId,+ operationId,+ agentType,+ topicId,+ );++ await marketService+ .getSDK()+ .plugins.runBuildInTool('runCommand', { command: shellCommand } as any, { topicId, userId });+}diff --git a/src/server/services/toolExecution/deviceProxy.ts b/src/server/services/toolExecution/deviceProxy.tsindex e0fc9f034a2..2f371068fe5 100644--- a/src/server/services/toolExecution/deviceProxy.ts+++ b/src/server/services/toolExecution/deviceProxy.ts@@ -66,6 +66,29 @@ export class DeviceProxy {}}+ async dispatchAgentRun(params: {+ agentType: 'claude-code' | 'codex';+ cwd?: string;+ deviceId?: string;+ jwt: string;+ operationId: string;+ prompt: string;+ resumeSessionId?: string;+ topicId: string;+ userId: string;+ }): Promise<{ error?: string; success: boolean }> {+ const client = this.getClient();+ if (!client) return { error: 'GATEWAY_NOT_CONFIGURED', success: false };++ try {+ return await client.dispatchAgentRun(params);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('dispatchAgentRun: error β %s', message);+ return { error: message, success: false };+ }+ }+async executeToolCall(params: { deviceId: string; userId: string },toolCall: { apiName: string; arguments: string; identifier: string },