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.

♻️ refactor(server): split the 1208-line heteroDispatch into cohesive modules (#21149)

Arvin Xuc1fd96b45725
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
deleted file mode 100644
index f69ddb56e7e..00000000000
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ /dev/null
@@ -1,1208 +0,0 @@
-import { stripGoalCommand, withConversationGoalPrompt } from '@lobechat/builtin-tool-goal';
-import { LOADING_FLAT } from '@lobechat/const';
-import type { LobeChatDatabase } from '@lobechat/database';
-import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
-import {
- appendAttachedFilesToPrompt,
- collectHeteroAttachedFiles,
- HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
- isLocalHeterogeneousType,
- isRemoteHeterogeneousType,
-} from '@lobechat/heterogeneous-agents';
-import type {
- ExecAgentResult,
- HeterogeneousRuntimePinSources,
- HeterogeneousTopicPin,
- LobeAgentAgencyConfig,
- RequestTrigger,
-} from '@lobechat/types';
-import {
- applyTopicModelToHeterogeneousProvider,
- buildHeteroExecArgs,
- getWorkingDirEffectivePath,
- resolveHeterogeneousRuntimeConfig,
-} from '@lobechat/types';
-import { nanoid } from '@lobechat/utils';
-import debug from 'debug';
-
-import { AgentOperationModel } from '@/database/models/agentOperation';
-import { DeviceModel } from '@/database/models/device';
-import type { MessageModel } from '@/database/models/message';
-import type { TopicModel } from '@/database/models/topic';
-import { resolveExecutionPlan, resolveWorkspaceScoped } from '@/helpers/executionTarget';
-import { signHeteroOperationJWT, signUserJWT } from '@/libs/trpc/utils/internalJwt';
-import {
- createAgentStateManager,
- createStreamEventManager,
-} from '@/server/modules/AgentRuntime/factory';
-import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
-import { hookDispatcher } from '@/server/services/agentRuntime/hooks';
-import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
-import { deviceGateway } from '@/server/services/deviceGateway';
-import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
-import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';
-import type { ConversationHistoryEntry } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
-import { buildCloudHeteroContext } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
-import { buildRemoteDeviceHeteroContext } from '@/server/services/heterogeneousAgent/remoteDeviceHeteroContext';
-import type { MarketService } from '@/server/services/market';
-import {
- resolveSandboxSessionConfig,
- type SandboxSessionConfig,
-} from '@/server/services/sandbox/session';
-
-import {
- getHeterogeneousAgentTitle,
- humanizeHeteroDispatchError,
- resolveHeteroDispatchErrorType,
- supportsCloudHeterogeneousSandbox,
-} from '../helpers/heteroErrors';
-import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';
-import type {
- BindTopicWorkingDirectoryParams,
- ExecRunContext,
- InternalExecAgentParams,
-} from '../types';
-import { selectCodexDeviceDispatch } from './codexDeviceRuntime';
-import { finalizeHeteroDispatchError } from './finalizeHeteroDispatchError';
-import { heteroOperationCapabilities } from './heteroOperationCapabilities';
-import type { RunAttachments } from './turnSetup';
-import { buildViewedTaskContextPrompt, joinSystemContext } from './viewedTaskContext';
-
-const log = debug('lobe-server:ai-agent-service');
-
-export interface HeteroDispatchDeps {
- bindTopicWorkingDirectory: (params: BindTopicWorkingDirectoryParams) => Promise<void>;
- db: LobeChatDatabase;
- /**
- * With a `sandboxStorage` claim, a service whose trust token carries the
- * entitlement a persistent sandbox run needs β€” built for that run rather
- * than taken from the cache, because the claim is signed into the token.
- */
- getMarketService: (options?: {
- sandboxStorage: NonNullable<SandboxSessionConfig['claim']>;
- }) => Promise<MarketService>;
- messageModel: MessageModel;
- resolveDeviceWorkspaceId: (deviceId: string | undefined) => Promise<string | undefined>;
- topicModel: TopicModel;
- userId: string;
- withholdGatewayToken: boolean;
- workspaceId?: string;
-}
-
-/**
- * Liveness probe for the ONE dispatch failure that races a live run: the cloud
- * sandbox `runCommand` call (see the `spawnHeteroSandbox` catch below). Every
- * other `finalizeHeteroDispatchError` caller rejects synchronously, before any
- * agent process can exist, so none of them needs this.
- *
- * `runCommand` is issued with `background: true` and is supposed to return as
- * soon as the command is handed to the sandbox β€” but the sandbox gateway can
- * sit on the connection and answer `Gateway Timeout` a minute or more later,
- * long after the sandbox actually booted and started streaming events back
- * through `heteroIngest`. Finalizing on that rejection blindly treats a
- * transient gateway 504 as "the run never started": it blanks the assistant
- * message, stamps an error bubble on a turn the user already read, marks the
- * op row + its task failed, and closes the UI stream out from under a run that
- * is still producing output.
- *
- * Two cheap reads tell a stranded dispatch apart from a live one:
- *
- * 1. `agent_operations.status` β€” anything other than `running` means the run
- * reached `heteroFinish` (or a park) on its own. Nothing left to finalize.
- * 2. `topics.metadata.heteroCurrentMsgId` β€” the ingest path repoints this at
- * every assistant turn it persists, scoped by `operationId`. It naming THIS
- * operation is proof the sandbox is alive and writing.
- *
- * When neither fires the sandbox really never came up and the caller finalizes
- * as before. A run that passes this probe and then dies is not stranded: the
- * agent-gateway inactivity watchdog still reaps it through `finalizeAbandoned`.
- */
-const hasHeteroRunStarted = async (
- deps: HeteroDispatchDeps,
- params: { operationId: string; topicId: string },
-): Promise<boolean> => {
- const { operationId, topicId } = params;
-
- try {
- const operation = await new AgentOperationModel(
- deps.db,
- deps.userId,
- deps.workspaceId,
- ).findById(operationId);
-
- if (operation && operation.status !== 'running') {
- log(
- 'hasHeteroRunStarted: op=%s already settled (status=%s) β€” skipping spawn-failure finalize',
- operationId,
- operation.status,
- );
- return true;
- }
-
- const topic = await deps.topicModel.findById(topicId);
- if (topic?.metadata?.heteroCurrentMsgId?.operationId === operationId) {
- log(
- 'hasHeteroRunStarted: op=%s has ingested turns β€” skipping spawn-failure finalize',
- operationId,
- );
- return true;
- }
-
- return false;
- } catch (err) {
- // A probe that cannot read must not swallow a real spawn failure: fall
- // back to the pre-existing behaviour and finalize.
- log(
- 'hasHeteroRunStarted: probe failed for op=%s (treating as not started): %O',
- operationId,
- err,
- );
- return false;
- }
-};
-
-export interface HeteroDispatchInput {
- canManageAgent: boolean;
- effectiveRequestedDeviceId?: string;
- heterogeneousProvider?: LobeAgentAgencyConfig['heterogeneousProvider'];
- heteroType: HeterogeneousAgentType;
- hooks?: AgentHook[];
- isPublicWorkspaceAgent: boolean;
- localDeviceId?: string;
- maxSteps?: number;
- memberDeviceOverride?: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'>;
- onOperationCreated?: InternalExecAgentParams['onOperationCreated'];
- operationTaskId?: string;
- parentOperationId?: string;
- pinnedHeterogeneousTopicModel?: HeterogeneousTopicPin;
- /** Which layer supplied each pin; see `TurnSetupResult`. */
- pinnedHeterogeneousTopicSources?: HeterogeneousRuntimePinSources;
- requestedDeviceId?: string;
- requestTrigger?: RequestTrigger;
- runAttachments: Pick<RunAttachments, 'audioList' | 'fileList' | 'imageList' | 'videoList'>;
- /** Ids of the rows THIS turn just persisted (excluded from recovery history). */
- selfMessageIds: Set<string>;
- topicStartOwnerOperationId?: string;
-}
-
-/**
- * Stage 3.5 of {@link AiAgentService.execAgent}: heterogeneous-agent early
- * exit. Local CLI and remote platform 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` (amp / claude-code / codebuddy / codex / cursor / droid /
- * grok-build / kimi-code / opencode / pi / qoder / trae) or
- * `agentNotify.notify` (openclaw / hermes).
- *
- * Always returns a terminal {@link ExecAgentResult} β€” the caller's `execAgent`
- * returns it directly and never continues to the normal-agent stages.
- */
-export const dispatchHeteroAgent = async (
- deps: HeteroDispatchDeps,
- ctx: ExecRunContext,
- input: HeteroDispatchInput,
-): Promise<ExecAgentResult> => {
- const {
- agentConfig,
- appContext,
- assistantMessageId,
- canUseDevice,
- deviceAccessReason,
- parentMessageId,
- persistAgentId,
- prompt,
- resolvedAgentId,
- topicId,
- trigger,
- userMessageId,
- } = ctx;
- const {
- canManageAgent,
- effectiveRequestedDeviceId,
- heteroType,
- heterogeneousProvider,
- hooks,
- isPublicWorkspaceAgent,
- localDeviceId,
- maxSteps,
- memberDeviceOverride,
- operationTaskId,
- parentOperationId,
- pinnedHeterogeneousTopicModel,
- requestTrigger,
- requestedDeviceId,
- runAttachments,
- selfMessageIds,
- topicStartOwnerOperationId,
- } = input;
-
- const isRemoteHetero = isRemoteHeterogeneousType(heteroType);
- // Same structured shape as the built-in path (`op_{ts}_{agentId}_{topicId}_{rand}`)
- // so hetero ops aren't visually distinct bare nanoids in the trace/op tables.
- const operationId = `op_${Date.now()}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;
-
- // Retain only public configuration dimensions. CLI args and API credentials must
- // never be copied into topic metadata or an inspector response. The receipt
- // reads the same provider and pin as the dispatched CLI args below.
- const runtimeConfig = {
- fields: resolveHeterogeneousRuntimeConfig(
- heterogeneousProvider ?? { type: heteroType },
- pinnedHeterogeneousTopicModel,
- input.pinnedHeterogeneousTopicSources ?? 'topic',
- ),
- operationId,
- };
-
- // Hooks belong to this operation's lifecycle. Persist their serializable
- // form on the durable operation row before dispatch; runningOperation below
- // remains a compatibility mirror for older terminal consumers.
- hookDispatcher.register(operationId, hooks ?? []);
- const serializedHooks = hookDispatcher.getSerializedHooks(operationId);
-
- // Persist a first-class agent_operations row for the hetero run. The id is
- // generated here (authoritative) and flows through to heteroIngest /
- // heteroFinish unchanged. Without this row the run is invisible to the
- // operation lifecycle: verify (ensureForOperation), repair (parent chain),
- // judge (op.model/provider) and tracing all key off it. The durable row is
- // also an authentication prerequisite: every callback
- // re-authorizes its operation token against this exact principal. Do not
- // mint a token or dispatch/spawn when persistence fails.
- const operationPersisted = await new CompletionLifecycle(
- deps.db,
- deps.userId,
- deps.workspaceId,
- ).recordStart({
- agentId: persistAgentId,
- appContext: { ...appContext, sourceMessageId: userMessageId },
- chatGroupId: appContext?.groupId ?? null,
- maxSteps,
- metadata: {
- _hooks: serializedHooks,
- assistantMessageId,
- heterogeneousRuntimeConfig: runtimeConfig,
- },
- operationId,
- parentOperationId,
- provider: heteroType,
- taskId: operationTaskId ?? null,
- threadId: appContext?.threadId ?? null,
- topicId,
- trigger,
- });
- if (!operationPersisted) {
- hookDispatcher.unregister(operationId);
- throw new Error('Failed to persist heterogeneous agent operation');
- }
-
- await input.onOperationCreated?.(operationId);
-
- // Read resume session id for next-turn continuity.
- const heteroService = new HeterogeneousAgentService(deps.db, deps.userId, {
- workspaceId: deps.workspaceId,
- });
- 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 signHeteroOperationJWT({
- // A `/goal` run also gets `goal:manage` so it can create the goal the agent
- // supervises; the server still derives the agent and topic from this
- // operation, never from the CLI.
- capabilities: heteroOperationCapabilities(prompt),
- operationId,
- userId: deps.userId,
- workspaceId: deps.workspaceId,
- });
- } 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 });
- }
-
- // Read repos from topic metadata for sandbox setup (web/cloud only).
- const topic = await deps.topicModel.findById(topicId);
- const topicRepos: string[] = topic?.metadata?.repos ?? [];
-
- // Resolve GitHub OAuth token for the sandbox. Always attempt so CC can use
- // git / gh CLI even when no repos are pre-selected. Falls back to the
- // standard 'github' key (LobeHub OAuth connector default); agent config can
- // override via GITHUB_CRED_KEY.
- let githubToken: string | undefined;
- const githubCredKey =
- agentConfig.agencyConfig?.heterogeneousProvider?.env?.GITHUB_CRED_KEY ?? 'github';
- try {
- const marketService = await deps.getMarketService();
- // Inside a workspace, the GitHub cred must come from the workspace's shared
- // organization credentials, not the operator's personal creds.
- const credsAccessor = deps.workspaceId
- ? marketService.market.organizations.creds({ workspaceId: deps.workspaceId })
- : marketService.market.creds;
- const list = await credsAccessor.list();
- const cred = list.data?.find((c: { key: string }) => c.key === githubCredKey);
- if (cred) {
- const full = await credsAccessor.get(cred.id, { decrypt: true });
- const vals = (full as any).plaintext ?? (full as any).values ?? {};
- githubToken = vals.access_token ?? vals.token;
- }
- } catch (err) {
- log('execAgent: failed to resolve GitHub token: %O', err);
- }
-
- // Recovery history is reserved for the CLI's retry without native resume.
- // The primary resumed attempt already has native history and must not get
- // a serialized duplicate. Amp threads are server-backed, so they rely on
- // native continuation exclusively and never need this local-file fallback.
- let conversationHistory: ConversationHistoryEntry[] | undefined;
- if (heteroType !== 'amp') {
- try {
- // `allowShareVisitor`: this is the RUN's own topic, already resolved
- // and authorized upstream. An agent-share visitor run executes under
- // the creator's identity, so without the opt-in `query()`'s
- // creator-facing default would hand the agent an empty history.
- const recentMsgs = await deps.messageModel.query(
- { topicId, pageSize: 200 },
- { allowShareVisitor: true },
- );
- const turns = recentMsgs
- .filter(
- (m) =>
- (m.role === 'user' || m.role === 'assistant') &&
- !m.threadId &&
- !selfMessageIds.has(m.id) &&
- m.content &&
- m.content !== LOADING_FLAT,
- )
- .slice(-30)
- .map((m) => ({
- content: m.content ?? '',
- role: m.role as 'assistant' | 'user',
- }));
- if (turns.length > 0) conversationHistory = turns;
- } catch (err) {
- log('execAgent: failed to load conversation history for hetero context: %O', err);
- }
- }
-
- // Where a cloud-sandbox run keeps its files: the same resolution the plain
- // cloud-sandbox runtime does, so a hetero topic bound to an environment
- // instance runs in that instance rather than in a throwaway box. Only for
- // providers the cloud sandbox can host at all; device-only providers never
- // read it. Never throws β€” a failed lookup is the ephemeral sandbox.
- const sandbox = supportsCloudHeterogeneousSandbox(heteroType)
- ? await resolveSandboxSessionConfig({
- isShareVisitorRun: !!ctx.shareGate,
- serverDB: deps.db,
- topicId,
- userId: deps.userId,
- workspaceId: deps.workspaceId,
- })
- : undefined;
- const sandboxPlacement = sandbox && { cwd: sandbox.cwd, mode: sandbox.mode };
-
- // Primary context omits history (a failed native resume retries with the full
- // fallback). `/goal` and the task viewed in a Tasks side chat ride along.
- const providerContext = agentConfig.agencyConfig?.heterogeneousProvider?.systemContext;
- const viewedTaskContext = await buildViewedTaskContextPrompt(deps, appContext, operationTaskId);
- const agentSystemContext = withConversationGoalPrompt(
- joinSystemContext(providerContext, viewedTaskContext),
- prompt,
- );
- const systemContext = buildCloudHeteroContext({
- agentSystemContext,
- conversationHistory: resumeSessionId ? undefined : conversationHistory,
- githubToken,
- repos: topicRepos,
- sandbox: sandboxPlacement,
- });
- const resumeFallbackSystemContext =
- resumeSessionId && conversationHistory
- ? buildCloudHeteroContext({
- agentSystemContext,
- conversationHistory,
- githubToken,
- repos: topicRepos,
- sandbox: sandboxPlacement,
- })
- : undefined;
-
- // Feed the resolved images (signed URLs) to the dispatched CLI for vision β€”
- // mirrors the local-mode path, where the client feeds the persisted
- // message's imageList into `sendPrompt`. Reuses the shared resolution above
- // so bot/IM and SPA gateway attachments are handled identically.
- const heteroImageList =
- runAttachments.imageList && runAttachments.imageList.length > 0
- ? runAttachments.imageList.map((image) => ({ id: image.id, url: image.url }))
- : undefined;
- const heteroExecArgs = isLocalHeterogeneousType(heteroType)
- ? buildHeteroExecArgs(
- heterogeneousProvider?.type === heteroType
- ? applyTopicModelToHeterogeneousProvider(
- heterogeneousProvider,
- pinnedHeterogeneousTopicModel,
- )
- : { type: heteroType },
- )
- : undefined;
-
- const heteroParams = {
- agentType: heteroType,
- assistantMessageId,
- githubToken,
- imageList: heteroImageList,
- jwt: operationJwt,
- operationId,
- // The CLI receives only the request: `/goal` is already in the system
- // context, and Claude Code's own `/goal` command would otherwise take it.
- // Non-image attachments have no content block a CLI accepts, so they ride
- // in the prompt as download links β€” otherwise the agent never sees them.
- prompt: appendAttachedFilesToPrompt(
- stripGoalCommand(prompt),
- collectHeteroAttachedFiles(runAttachments),
- ),
- repos: topicRepos,
- resumeFallbackSystemContext,
- resumeSessionId,
- systemContext,
- topicId,
- userId: deps.userId,
- };
-
- const platformPlan = isRemoteHetero
- ? resolveExecutionPlan({
- agencyConfig: agentConfig.agencyConfig,
- canUseDevice,
- clientExecutionAvailable: Boolean(localDeviceId),
- isHetero: true,
- localDeviceId,
- requestedDeviceId: effectiveRequestedDeviceId,
- sandboxExecutionAvailable: false,
- trigger: requestTrigger,
- workspaceScoped: resolveWorkspaceScoped(
- isPublicWorkspaceAgent && !canManageAgent,
- memberDeviceOverride,
- ),
- })
- : undefined;
- const remoteDeviceId = platformPlan?.kind === 'device' ? platformPlan.deviceId : undefined;
- const remoteDeviceWorkspaceId = remoteDeviceId
- ? await deps.resolveDeviceWorkspaceId(remoteDeviceId)
- : undefined;
- const usesCallersPersonalDevice =
- platformPlan?.kind === 'device' &&
- !remoteDeviceWorkspaceId &&
- (effectiveRequestedDeviceId === remoteDeviceId ||
- (platformPlan.target === 'local' &&
- agentConfig.agencyConfig?.executionTargetSelectionPolicy !== 'fixed') ||
- (!canManageAgent && memberDeviceOverride?.boundDeviceId === remoteDeviceId));
- const remoteDeviceUserId = usesCallersPersonalDevice
- ? deps.userId
- : (agentConfig.userId ?? deps.userId);
-
- // Resolve CLI-device routing before persisting the marker. Cancellation
- // must address the same device even though local CLI agents use a different
- // dispatch transport from notify-based platform agents.
- const deviceHeteroPlan = !isRemoteHetero
- ? resolveExecutionPlan({
- agencyConfig: agentConfig.agencyConfig,
- canUseDevice,
- isHetero: true,
- clientExecutionAvailable: false,
- requestedDeviceId,
- sandboxExecutionAvailable: supportsCloudHeterogeneousSandbox(heteroType),
- trigger: requestTrigger,
- })
- : undefined;
- const cliDeviceId = deviceHeteroPlan?.kind === 'device' ? deviceHeteroPlan.deviceId : undefined;
- const cliDeviceWorkspaceId = cliDeviceId
- ? await deps.resolveDeviceWorkspaceId(cliDeviceId)
- : undefined;
-
- // Register the run's lifecycle hooks so the hetero terminal path fires
- // onComplete/onError through the same `hookDispatcher` the normal LLM
- // runtime uses β€” driving the task lifecycle (onTopicComplete) and IM bot
- // completion callbacks uniformly. The hetero block returns before
- // AgentRuntimeService (which registers hooks for normal runs), so we do it
- // here. Local mode dispatches these in-memory handlers; queue mode delivers
- // the serialized webhooks persisted on the operation row above.
- // Seed topic.metadata.runningOperation so heteroIngest can validate the
- // operation, and so every terminal site (heteroFinish, agentNotify done,
- // dispatch failure) can re-fire the serialized hooks across a process
- // boundary in queue mode.
- const childOperation = {
- assistantMessageId,
- heteroType,
- hooks: serializedHooks,
- startedAt: new Date().toISOString(),
- ...(isRemoteHetero && remoteDeviceId
- ? {
- deviceId: remoteDeviceId,
- deviceUserId: remoteDeviceUserId,
- deviceWorkspaceId: remoteDeviceWorkspaceId,
- }
- : cliDeviceId
- ? {
- deviceId: cliDeviceId,
- deviceUserId: deps.userId,
- deviceWorkspaceId: cliDeviceWorkspaceId,
- }
- : {}),
- operationId,
- orchestrationRole: appContext?.orchestrationRole,
- scope: appContext?.scope ?? undefined,
- threadId: appContext?.threadId ?? undefined,
- };
- if (topicStartOwnerOperationId) {
- const attached = await deps.topicModel.appendRunningOperationChild(
- topicId,
- topicStartOwnerOperationId,
- childOperation,
- );
- if (!attached) {
- const message = 'Group supervisor finished before this member could start.';
- // Same contract as `finalizeHeteroDispatchError`: read the hook before the
- // dispatch settles and unregisters it, so the caller learns whether this
- // failure was already announced to its own surfaces.
- const terminalReported = hookDispatcher.canDeliver(operationId, 'onComplete');
- await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId).completeOperation(
- {
- agentId: persistAgentId,
- assistantMessageId,
- error: { message, type: 'AgentRuntimeError' },
- operationId,
- orchestrationRole: appContext?.orchestrationRole,
- serializedHooks,
- topicId,
- userId: deps.userId,
- },
- 'error',
- );
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: message,
- message,
- operationId,
- status: 'error',
- success: false,
- terminalReported,
- timestamp: new Date().toISOString(),
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
- }
- } else if (appContext?.isolationThread && parentOperationId) {
- // Isolation-thread children (callAgent / callSubAgent) run on the
- // SPAWNER's topic and finish long before it does. heteroIngest and
- // heteroFinish both require this child's operationId to resolve via
- // topic.metadata.runningOperation (root or childOperations) β€” see
- // the comment above childOperation β€” or every streamed batch is
- // dropped as stale and the terminal onComplete hooks (including the
- // callAgent resume bridge) never fire. Nest under the parent's own
- // marker instead of claiming the topic-level root outright, so the
- // parent's marker survives for the rest of its still-running turn.
- const attachedToParent = await deps.topicModel.appendRunningOperationChild(
- topicId,
- parentOperationId,
- childOperation,
- );
- if (!attachedToParent) {
- // Parent isn't (or is no longer) the topic's current root marker β€”
- // e.g. a nested isolation chain, or the parent already settled.
- // Fall back to claiming the marker directly so this child is still
- // discoverable by its own operationId, rather than permanently
- // unrecognized by heteroIngest/heteroFinish.
- await deps.topicModel.updateMetadata(topicId, { runningOperation: childOperation });
- }
- } else if (!appContext?.isolationThread) {
- // The receipt previously had a separate projection write after this marker.
- // Store both together so a follow-up cannot install a new running operation
- // while retaining the previous operation's displayed configuration.
- // Task drawer follow-ups can omit taskId; receipt ownership is independent
- // of Task lifecycle association, while isolated children keep the root receipt.
- await deps.topicModel.updateMetadata(topicId, {
- heteroRuntimeConfig: runtimeConfig,
- runningOperation: childOperation,
- });
- }
-
- // Always persist operation metadata (userId/workspaceId) to the state
- // manager, not just for topic-owner-mirrored runs. `subAgentCallback`
- // (the QStash-delivered completion bridge for callAgent/callSubAgent
- // children) resolves `userId` from this same store to authorize
- // resuming the parent β€” without it, a hetero child spawned via
- // callAgent has no metadata row, the callback 401s, and the parent
- // operation is never resumed (stays parked until the inactivity
- // watchdog abandons it).
- const persistOperationMetadata = async () => {
- try {
- await createAgentStateManager().createOperationMetadata(operationId, {
- ...(topicStartOwnerOperationId && {
- mirrorToOperationId: topicStartOwnerOperationId,
- }),
- userId: deps.userId,
- workspaceId: deps.workspaceId,
- });
- } catch (err) {
- log('execAgent: failed to persist hetero operation metadata: %O', err);
- }
- };
-
- if (agentConfig.agencyConfig?.heterogeneousProvider?.authMode === 'api') {
- const terminalReported = await finalizeHeteroDispatchError(deps, {
- agentId: resolvedAgentId,
- assistantMessageId,
- detail: HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
- message: 'Provider-bound heterogeneous agents do not support this execution target',
- operationId,
- topicId,
- });
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
- message: 'Heterogeneous agent provider binding requires Desktop local execution',
- operationId,
- status: 'error',
- success: false,
- terminalReported,
- timestamp: new Date().toISOString(),
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
- }
-
- // Notify-based platform agents (openclaw / hermes) communicate back via
- // agentNotify.notify. A local run uses the requesting desktop's device ID;
- // a remote run uses agencyConfig.boundDeviceId. Both use the gateway transport,
- // so open the stream before the first notify arrives.
-
- if (isRemoteHetero) {
- // Platform task agents require either this desktop or a connected device β€” there is no sandbox to
- // degrade to, so a denied sender (external bot user) is refused
- // outright instead of reaching the owner's machine.
- if (!canUseDevice) {
- log(
- 'execAgent: device access denied for remote hetero dispatch (reason=%s)',
- deviceAccessReason,
- );
- const terminalReported = await finalizeHeteroDispatchError(deps, {
- agentId: resolvedAgentId,
- assistantMessageId,
- detail: 'This sender is not allowed to run agents on a bound device.',
- message: 'Device access denied',
- operationId,
- topicId,
- });
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: 'Device access denied',
- message: 'Remote hetero agent requires device access',
- operationId,
- status: 'error',
- success: false,
- terminalReported,
- timestamp: new Date().toISOString(),
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
- }
- if (!remoteDeviceId) {
- log('execAgent: openclaw/hermes requires a local or connected device');
- const terminalReported = await finalizeHeteroDispatchError(deps, {
- agentId: resolvedAgentId,
- assistantMessageId,
- detail: 'No local or connected device is available for this agent.',
- message: 'No execution device for platform agent',
- operationId,
- topicId,
- });
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: 'No bound device',
- message: 'Platform agent requires a local or connected device',
- operationId,
- status: 'error',
- success: false,
- terminalReported,
- timestamp: new Date().toISOString(),
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
- }
-
- // Open the stream channel so the gateway WS subscription can receive
- // notify_update events published by agentNotify.notify.
- await persistOperationMetadata();
- const streamManager = createStreamEventManager();
- await streamManager
- .publishAgentRuntimeInit(operationId, {
- agentId: resolvedAgentId,
- assistantMessageId,
- heteroType,
- mirrorToOperationId: topicStartOwnerOperationId,
- topicId,
- userId: deps.userId,
- })
- .catch((err) => log('execAgent: failed to init stream for remote hetero: %O', err));
-
- // lh connect only handles tool_call_request (not agent_run_request),
- // so we use executeToolCall with the runHeteroTask tool instead of dispatchAgentRun.
- const authorizationError = await resolveDeviceDispatchAuthorizationFailure(
- deps.db,
- deps.userId,
- remoteDeviceId,
- remoteDeviceWorkspaceId,
- );
- const result = authorizationError
- ? {
- content: 'The workspace device is no longer registered or visible for this run.',
- error: 'DEVICE_NOT_FOUND',
- errorData: authorizationError,
- success: false,
- }
- : await deviceGateway.executeToolCall(
- {
- deviceId: remoteDeviceId,
- userId: remoteDeviceUserId,
- workspaceId: remoteDeviceWorkspaceId,
- },
- {
- apiName: 'runHeteroTask',
- arguments: JSON.stringify({
- agentId: resolvedAgentId,
- agentType: heteroType,
- cwd: undefined,
- operationId,
- parentOperationId: topicStartOwnerOperationId,
- platformAgentId: agentConfig.agencyConfig?.heterogeneousProvider?.platformAgentId,
- prompt,
- taskId: operationId,
- topicId,
- // Scope notify callbacks to the same workspace as the dispatched
- // topic so agentNotify can resolve the workspace-owned topic.
- // Without this the device's notify call falls back to personal
- // mode and TopicModel.findById returns NOT_FOUND.
- workspaceId: deps.workspaceId,
- }),
- identifier: 'runHeteroTask',
- },
- 120_000, // hetero tasks can take longer than the default 30 s
- );
- if (!result.success) {
- log('execAgent: remote hetero dispatch failed: %s', result.error);
- const terminalReported = await finalizeHeteroDispatchError(deps, {
- agentId: resolvedAgentId,
- assistantMessageId,
- detail: result.error ?? 'Device dispatch failed',
- deviceRoute: remoteDeviceId
- ? {
- deviceId: remoteDeviceId,
- userId: remoteDeviceUserId,
- ...(remoteDeviceWorkspaceId ? { workspaceId: remoteDeviceWorkspaceId } : {}),
- }
- : undefined,
- errorData: result.errorData,
- errorType: resolveHeteroDispatchErrorType(result.error),
- message: humanizeHeteroDispatchError(result.error),
- operationId,
- topicId,
- });
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: result.error,
- errorData: result.errorData,
- message: 'Remote hetero agent dispatch failed',
- operationId,
- status: 'error',
- success: false,
- terminalReported,
- timestamp: new Date().toISOString(),
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
- }
- } else {
- // Local CLI hetero (Amp / Claude Code / Codex / Kimi Code / OpenCode /
- // Pi / Qoder) β€” fork between device dispatch and cloud sandbox via the
- // shared execution plan:
- // - requestedDeviceId (topic-level override) always wins
- // - executionTarget 'device' β†’ dispatch to boundDeviceId (errors if unset)
- // - executionTarget 'local' + boundDeviceId (desktop sync opened on web)
- // β†’ dispatch to that device
- // - everything else ('sandbox' / unbound 'local' / 'none' / unset) β†’ cloud
- // sandbox when the provider supports it; Amp and OpenCode remain
- // unrouted because they require a local or connected device
- // `onlineDeviceIds` is intentionally omitted: hetero dispatch trusts
- // the binding and fails loudly at the gateway if the device is offline.
- // `canUseDevice` degrades device-capable targets to the sandbox when
- // available, or leaves device-only providers unrouted, for denied
- // senders (e.g. external bot users). Without this a synced local/device
- // binding would let them run on the owner's machine.
-
- // Register the op with the agent-gateway DO before dispatch, mirroring
- // the remote-hetero branch above. Local CLI hetero (claude-code / codex)
- // streams back via heteroIngest, which forwards live events the DO can
- // relay even without an init β€” so the FIRST run renders fine. But a later
- // `reconnectToGatewayOperation` (task topic drawer open / page reload)
- // sends a `resume` that asks the DO for the op's status; with no session
- // record the DO answers terminal, the client fires `session_complete`,
- // and `onSessionComplete` clears `topic.metadata.runningOperation`. The
- // still-running CC's next heteroIngest batch then hits
- // StaleHeteroOperationError and is silently dropped β€” the agent appears
- // to stop the moment the window is opened. Seeding the init keeps the DO
- // reporting `running`, so resume stays connected and keeps streaming.
- // Best-effort: a stream-manager/Redis failure must never block dispatch β€”
- // the init only powers reconnect, not the run. `createStreamEventManager`
- // probes Redis synchronously, so guard construction too, not just publish.
- try {
- await persistOperationMetadata();
- await createStreamEventManager().publishAgentRuntimeInit(operationId, {
- agentId: resolvedAgentId,
- assistantMessageId,
- heteroType,
- mirrorToOperationId: topicStartOwnerOperationId,
- topicId,
- userId: deps.userId,
- });
- } catch (err) {
- log('execAgent: failed to init stream for local hetero: %O', err);
- }
-
- const heteroPlan = deviceHeteroPlan!;
-
- if (heteroPlan.kind !== 'sandbox') {
- const dispatchDeviceId = heteroPlan.kind === 'device' ? heteroPlan.deviceId : undefined;
- if (!dispatchDeviceId) {
- log('execAgent: hetero executionTarget=device but no boundDeviceId set');
- const terminalReported = await finalizeHeteroDispatchError(deps, {
- agentId: resolvedAgentId,
- assistantMessageId,
- detail: !supportsCloudHeterogeneousSandbox(heteroType)
- ? 'No device bound. Pick a local or connected device in the Execution Device switcher.'
- : 'No device bound. Pick a device in the Execution Device switcher, or switch to Cloud sandbox.',
- message: 'No bound device for hetero agent',
- operationId,
- topicId,
- });
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: 'No bound device',
- message: 'Hetero agent requires a bound device',
- operationId,
- status: 'error',
- success: false,
- terminalReported,
- timestamp: new Date().toISOString(),
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
- }
- const codexRuntime = await selectCodexDeviceDispatch({
- db: deps.db,
- heterogeneousProvider,
- heteroType,
- readSystemInfo: (clientKinds) =>
- deviceGateway.readDeviceSystemInfo(deps.userId, dispatchDeviceId, cliDeviceWorkspaceId, {
- clientKinds,
- }),
- resume: Boolean(resumeSessionId),
- userId: deps.userId,
- });
- if (codexRuntime.kind === 'error') {
- const terminalReported = await finalizeHeteroDispatchError(deps, {
- agentId: resolvedAgentId,
- assistantMessageId,
- detail: codexRuntime.message,
- message: 'Native Codex dispatch rejected',
- operationId,
- topicId,
- });
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: codexRuntime.message,
- message: codexRuntime.message,
- operationId,
- status: 'error',
- success: false,
- terminalReported,
- timestamp: new Date().toISOString(),
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
- }
- const nativeCodex = codexRuntime.kind === 'native' ? codexRuntime : undefined;
-
- // Resolve the working directory for the run: a topic-level override
- // wins, else the device's user-configured defaultCwd. The device row
- // lives in the DB (the gateway only knows live connections), so read
- // it directly rather than via deviceGateway.
- // The bound device may be personal (userId-scoped) or a workspace
- // device (workspace-scoped) β€” look up both so its defaultCwd resolves.
- const deviceModelForCwd = new DeviceModel(deps.db, deps.userId, deps.workspaceId);
- const boundDevice =
- (await deviceModelForCwd.findByDeviceId(dispatchDeviceId)) ??
- (await deviceModelForCwd.findWorkspaceDeviceById(dispatchDeviceId));
- const dispatchWorkspaceId = cliDeviceWorkspaceId;
- // Resolve via the shared precedence helper so dispatch, workspace-init,
- // and the new-topic backfill below all agree on the cwd.
- const deviceCwdConfig = resolveDeviceWorkingDirectoryConfig({
- deviceDefaultCwd: boundDevice?.defaultCwd,
- deviceId: dispatchDeviceId,
- devicePlatform: boundDevice?.platform,
- initialWorkingDirectory: appContext?.initialTopicMetadata?.workingDirectory,
- initialWorkingDirectoryConfig: appContext?.initialTopicMetadata?.workingDirectoryConfig,
- // The run's repos, so a directory that IS one of them is skipped: this
- // device cannot have it (`owner/repo` is a cloud repo identifier).
- repos: topicRepos,
- topicDeviceId: topic?.metadata?.boundDeviceId,
- topicWorkingDirectory: topic?.metadata?.workingDirectory,
- topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,
- workingDirByDevice: agentConfig.agencyConfig?.workingDirByDevice,
- });
- const deviceCwd = getWorkingDirEffectivePath(deviceCwdConfig);
-
- // An unbound topic has no pinned cwd yet: the directory was only
- // recorded at agent level (`workingDirByDevice`) when no topic existed.
- // Persist the resolved cwd onto the topic so the sidebar groups it
- // under the right project and the next turn reuses the same directory.
- await deps.bindTopicWorkingDirectory({
- config: deviceCwdConfig,
- currentDeviceId: topic?.metadata?.boundDeviceId,
- currentWorkingDirectory: topic?.metadata?.workingDirectory,
- deviceId: dispatchDeviceId,
- topicId,
- });
-
- // Build only device-relevant context instead of reusing the cloud-sandbox one
- // (which describes an ephemeral /workspace + pre-cloned repos and would mislead
- // the agent). The spawned CLI already receives deviceCwd as its actual cwd.
- const deviceSystemContext = buildRemoteDeviceHeteroContext({
- agentSystemContext,
- conversationHistory: resumeSessionId ? undefined : conversationHistory,
- });
- const deviceResumeFallbackSystemContext =
- resumeSessionId && conversationHistory
- ? buildRemoteDeviceHeteroContext({
- agentSystemContext,
- conversationHistory,
- })
- : undefined;
-
- const authorizationError = await resolveDeviceDispatchAuthorizationFailure(
- deps.db,
- deps.userId,
- dispatchDeviceId,
- dispatchWorkspaceId,
- );
- const result = authorizationError
- ? { error: 'DEVICE_NOT_FOUND', errorData: authorizationError, success: false }
- : await deviceGateway.dispatchAgentRun({
- ...heteroParams,
- agentId: resolvedAgentId,
- // Only a live client advertising the native protocol receives these wrapper flags.
- args: nativeCodex ? [...(heteroExecArgs ?? []), ...nativeCodex.args] : heteroExecArgs,
- clientKinds: nativeCodex?.clientKinds,
- cwd: deviceCwd,
- deviceId: dispatchDeviceId,
- resumeFallbackSystemContext: deviceResumeFallbackSystemContext,
- systemContext: deviceSystemContext,
- // Route to the workspace pool when this is a workspace device; the
- // operation JWT stays member-scoped (the run belongs to the member).
- workspaceId: dispatchWorkspaceId,
- // Topic scope for device-side heteroIngest/heteroFinish. Distinct
- // from the routing workspace above: a workspace topic on a personal
- // device still has to write back under `deps.workspaceId`.
- ingestWorkspaceId: deps.workspaceId,
- });
- if (!result.success) {
- log('execAgent: hetero device dispatch failed: %s', result.error);
- const terminalReported = await finalizeHeteroDispatchError(deps, {
- agentId: resolvedAgentId,
- assistantMessageId,
- detail: result.error ?? 'Device dispatch failed',
- deviceRoute: {
- deviceId: dispatchDeviceId,
- userId: deps.userId,
- ...(dispatchWorkspaceId ? { workspaceId: dispatchWorkspaceId } : {}),
- },
- errorData: result.errorData,
- errorType: resolveHeteroDispatchErrorType(result.error),
- message: humanizeHeteroDispatchError(result.error),
- operationId,
- topicId,
- });
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: result.error,
- errorData: result.errorData,
- message: 'Hetero agent device dispatch failed',
- operationId,
- status: 'error',
- success: false,
- terminalReported,
- timestamp: new Date().toISOString(),
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
- }
-
- // Local CLI hetero agents dispatch to a device just like remote platform
- // agents, so persist the device route after the dispatch is accepted.
- // interruptTask uses these fields to find and stop the native process.
- try {
- const patched = await deps.topicModel.patchRunningOperation(topicId, operationId, {
- deviceId: dispatchDeviceId,
- deviceWorkspaceId: dispatchWorkspaceId,
- heteroType,
- });
- log(
- 'execAgent: patch runningOperation device info=%s deviceId=%s heteroType=%s op=%s',
- patched,
- dispatchDeviceId,
- heteroType,
- operationId,
- );
- } catch (err) {
- log('execAgent: failed to patch runningOperation with device info: %O', err);
- }
- } else {
- if (!supportsCloudHeterogeneousSandbox(heteroType)) {
- const message = `${getHeterogeneousAgentTitle(heteroType)} requires a local or connected device; cloud sandbox execution is not supported.`;
- const terminalReported = await finalizeHeteroDispatchError(deps, {
- agentId: resolvedAgentId,
- assistantMessageId,
- detail: message,
- message,
- operationId,
- topicId,
- });
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: false,
- createdAt: new Date().toISOString(),
- error: message,
- message,
- operationId,
- status: 'error',
- success: false,
- terminalReported,
- timestamp: new Date().toISOString(),
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
- }
-
- // Cloud sandbox path β€” only for sandbox-provisioned local CLI agents.
- // Remote agents (openclaw / hermes) always require a bound device.
- // Lazy-loaded on purpose: `sandboxRunner` pulls the sandbox-service graph
- // (which eagerly touches server-only ModelRuntime env at module init), so
- // importing it statically would couple that whole subsystem into every
- // `aiAgent` import. Only this cloud-CLI branch needs it.
- const { spawnHeteroSandbox } =
- await import('@/server/services/heterogeneousAgent/sandboxRunner');
- // The entitlement rides on the trust token; without it the execution
- // plane routes to the ephemeral sandbox whatever the request says.
- const marketService = await deps.getMarketService(
- sandbox?.claim ? { sandboxStorage: sandbox.claim } : undefined,
- );
- // The sandbox authenticates its nested `lh` calls with this JWT. The
- // narrow `hetero-operation` token (used for the device-dispatch path
- // above) is rejected by `oidcAuth`, so CC capabilities that hit
- // user-scoped endpoints β€” e.g. uploading a `Read`-on-image result to
- // the file store for thumbnail echo β€” would 401 and silently drop.
- // Mint a user-scoped `cli-sandbox` token instead (still `sub: userId`,
- // ownership-gated on heteroIngest/heteroFinish) with a run-length TTL
- // so it outlives a multi-hour run.
- const sandboxJwt = await signUserJWT(deps.userId, '4h');
- spawnHeteroSandbox({
- ...heteroParams,
- agentType: heteroType as 'claude-code' | 'codex',
- args: heteroExecArgs,
- jwt: sandboxJwt,
- marketService,
- sandbox: sandbox && {
- cwd: sandbox.cwd,
- environment: sandbox.environment,
- mode: sandbox.mode,
- // The environment's variables, network access, maintenance command
- // and sources all ride here; dropping it starts the run with none
- // of them, and nothing reports that they were ignored.
- specification: sandbox.specification,
- workingDir: sandbox.workingDir,
- },
- workspaceId: deps.workspaceId,
- }).catch(async (err) => {
- // Fire-and-forget: execAgent has already returned `autoStarted`, and
- // the sandbox never reached the point of calling heteroFinish. Drive
- // the same terminal funnel so the stranded run surfaces an error and
- // its task is marked failed instead of hanging in `running`.
- log('execAgent: hetero sandbox spawn failed: %O', err);
-
- // ...unless the run is demonstrably alive or already finished. This
- // call is the only dispatch failure that can land AFTER the agent
- // started, so a rejection here is not by itself evidence that nothing
- // ran β€” see `hasHeteroRunStarted`.
- if (await hasHeteroRunStarted(deps, { operationId, topicId })) return;
-
- await finalizeHeteroDispatchError(deps, {
- agentId: resolvedAgentId,
- assistantMessageId,
- detail: err instanceof Error ? err.message : String(err),
- message: 'Hetero sandbox spawn failed',
- operationId,
- topicId,
- }).catch((finalizeErr) =>
- log('execAgent: sandbox-failure finalize failed: %O', finalizeErr),
- );
- });
- }
- }
-
- let gatewayToken: string | undefined;
- if (!deps.withholdGatewayToken) {
- try {
- gatewayToken = await signUserJWT(deps.userId);
- } catch {
- // non-critical
- }
- }
-
- return {
- agentId: resolvedAgentId,
- assistantMessageId,
- autoStarted: true,
- createdAt: new Date().toISOString(),
- heteroType,
- message: 'Hetero agent dispatched successfully',
- operationId,
- status: 'created',
- success: true,
- timestamp: new Date().toISOString(),
- token: gatewayToken,
- topicId,
- userMessageId: userMessageId ?? parentMessageId ?? '',
- };
-};
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
new file mode 100644
index 00000000000..f86caf9ecc8
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
@@ -0,0 +1,230 @@
+import type { ExecAgentResult } from '@lobechat/types';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
+import debug from 'debug';
+
+import { DeviceModel } from '@/database/models/device';
+import type { ExecutionPlan } from '@/helpers/executionTarget';
+import { deviceGateway } from '@/server/services/deviceGateway';
+import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
+import { buildRemoteDeviceHeteroContext } from '@/server/services/heterogeneousAgent/remoteDeviceHeteroContext';
+
+import {
+ humanizeHeteroDispatchError,
+ resolveHeteroDispatchErrorType,
+ supportsCloudHeterogeneousSandbox,
+} from '../../helpers/heteroErrors';
+import { resolveDeviceWorkingDirectoryConfig } from '../../resolveDeviceWorkingDirectory';
+import type { ExecRunContext } from '../../types';
+import { selectCodexDeviceDispatch } from '../codexDeviceRuntime';
+import type { PreparedHeteroRun } from './prepare';
+import type { HeteroDispatchDeps, HeteroDispatchInput, HeteroRun } from './types';
+import { failHeteroDispatch } from './utils';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Dispatch a local CLI hetero agent to the device its execution plan routed it
+ * to: pick the Codex runtime, resolve and bind the working directory, build the
+ * device-only system context, dispatch, and record the device route so a stop
+ * request reaches the process.
+ *
+ * Returns the terminal error result when the run cannot start, `undefined`
+ * once the device accepted it.
+ */
+export const dispatchToCliDevice = async (
+ deps: HeteroDispatchDeps,
+ run: HeteroRun,
+ params: {
+ agentConfig: ExecRunContext['agentConfig'];
+ appContext: ExecRunContext['appContext'];
+ cliDeviceWorkspaceId?: string;
+ heteroPlan: ExecutionPlan;
+ heteroType: HeteroDispatchInput['heteroType'];
+ heterogeneousProvider: HeteroDispatchInput['heterogeneousProvider'];
+ prepared: PreparedHeteroRun;
+ },
+): Promise<ExecAgentResult | undefined> => {
+ const {
+ agentConfig,
+ appContext,
+ cliDeviceWorkspaceId,
+ heteroPlan,
+ heteroType,
+ heterogeneousProvider,
+ prepared,
+ } = params;
+ const {
+ agentSystemContext,
+ conversationHistory,
+ heteroExecArgs,
+ heteroParams,
+ resumeSessionId,
+ topic,
+ topicRepos,
+ } = prepared;
+ const { agentId: resolvedAgentId, operationId, topicId } = run;
+
+ const dispatchDeviceId = heteroPlan.kind === 'device' ? heteroPlan.deviceId : undefined;
+ if (!dispatchDeviceId) {
+ log('execAgent: hetero executionTarget=device but no boundDeviceId set');
+ return failHeteroDispatch(
+ deps,
+ run,
+ {
+ detail: !supportsCloudHeterogeneousSandbox(heteroType)
+ ? 'No device bound. Pick a local or connected device in the Execution Device switcher.'
+ : 'No device bound. Pick a device in the Execution Device switcher, or switch to Cloud sandbox.',
+ message: 'No bound device for hetero agent',
+ },
+ { error: 'No bound device', message: 'Hetero agent requires a bound device' },
+ );
+ }
+ const codexRuntime = await selectCodexDeviceDispatch({
+ db: deps.db,
+ heterogeneousProvider,
+ heteroType,
+ readSystemInfo: (clientKinds) =>
+ deviceGateway.readDeviceSystemInfo(deps.userId, dispatchDeviceId, cliDeviceWorkspaceId, {
+ clientKinds,
+ }),
+ resume: Boolean(resumeSessionId),
+ userId: deps.userId,
+ });
+ if (codexRuntime.kind === 'error') {
+ return failHeteroDispatch(
+ deps,
+ run,
+ { detail: codexRuntime.message, message: 'Native Codex dispatch rejected' },
+ { error: codexRuntime.message, message: codexRuntime.message },
+ );
+ }
+ const nativeCodex = codexRuntime.kind === 'native' ? codexRuntime : undefined;
+
+ // Resolve the working directory for the run: a topic-level override
+ // wins, else the device's user-configured defaultCwd. The device row
+ // lives in the DB (the gateway only knows live connections), so read
+ // it directly rather than via deviceGateway.
+ // The bound device may be personal (userId-scoped) or a workspace
+ // device (workspace-scoped) β€” look up both so its defaultCwd resolves.
+ const deviceModelForCwd = new DeviceModel(deps.db, deps.userId, deps.workspaceId);
+ const boundDevice =
+ (await deviceModelForCwd.findByDeviceId(dispatchDeviceId)) ??
+ (await deviceModelForCwd.findWorkspaceDeviceById(dispatchDeviceId));
+ const dispatchWorkspaceId = cliDeviceWorkspaceId;
+ // Resolve via the shared precedence helper so dispatch, workspace-init,
+ // and the new-topic backfill below all agree on the cwd.
+ const deviceCwdConfig = resolveDeviceWorkingDirectoryConfig({
+ deviceDefaultCwd: boundDevice?.defaultCwd,
+ deviceId: dispatchDeviceId,
+ devicePlatform: boundDevice?.platform,
+ initialWorkingDirectory: appContext?.initialTopicMetadata?.workingDirectory,
+ initialWorkingDirectoryConfig: appContext?.initialTopicMetadata?.workingDirectoryConfig,
+ // The run's repos, so a directory that IS one of them is skipped: this
+ // device cannot have it (`owner/repo` is a cloud repo identifier).
+ repos: topicRepos,
+ topicDeviceId: topic?.metadata?.boundDeviceId,
+ topicWorkingDirectory: topic?.metadata?.workingDirectory,
+ topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,
+ workingDirByDevice: agentConfig.agencyConfig?.workingDirByDevice,
+ });
+ const deviceCwd = getWorkingDirEffectivePath(deviceCwdConfig);
+
+ // An unbound topic has no pinned cwd yet: the directory was only
+ // recorded at agent level (`workingDirByDevice`) when no topic existed.
+ // Persist the resolved cwd onto the topic so the sidebar groups it
+ // under the right project and the next turn reuses the same directory.
+ await deps.bindTopicWorkingDirectory({
+ config: deviceCwdConfig,
+ currentDeviceId: topic?.metadata?.boundDeviceId,
+ currentWorkingDirectory: topic?.metadata?.workingDirectory,
+ deviceId: dispatchDeviceId,
+ topicId,
+ });
+
+ // Build only device-relevant context instead of reusing the cloud-sandbox one
+ // (which describes an ephemeral /workspace + pre-cloned repos and would mislead
+ // the agent). The spawned CLI already receives deviceCwd as its actual cwd.
+ const deviceSystemContext = buildRemoteDeviceHeteroContext({
+ agentSystemContext,
+ conversationHistory: resumeSessionId ? undefined : conversationHistory,
+ });
+ const deviceResumeFallbackSystemContext =
+ resumeSessionId && conversationHistory
+ ? buildRemoteDeviceHeteroContext({
+ agentSystemContext,
+ conversationHistory,
+ })
+ : undefined;
+
+ const authorizationError = await resolveDeviceDispatchAuthorizationFailure(
+ deps.db,
+ deps.userId,
+ dispatchDeviceId,
+ dispatchWorkspaceId,
+ );
+ const result = authorizationError
+ ? { error: 'DEVICE_NOT_FOUND', errorData: authorizationError, success: false }
+ : await deviceGateway.dispatchAgentRun({
+ ...heteroParams,
+ agentId: resolvedAgentId,
+ // Only a live client advertising the native protocol receives these wrapper flags.
+ args: nativeCodex ? [...(heteroExecArgs ?? []), ...nativeCodex.args] : heteroExecArgs,
+ clientKinds: nativeCodex?.clientKinds,
+ cwd: deviceCwd,
+ deviceId: dispatchDeviceId,
+ resumeFallbackSystemContext: deviceResumeFallbackSystemContext,
+ systemContext: deviceSystemContext,
+ // Route to the workspace pool when this is a workspace device; the
+ // operation JWT stays member-scoped (the run belongs to the member).
+ workspaceId: dispatchWorkspaceId,
+ // Topic scope for device-side heteroIngest/heteroFinish. Distinct
+ // from the routing workspace above: a workspace topic on a personal
+ // device still has to write back under `deps.workspaceId`.
+ ingestWorkspaceId: deps.workspaceId,
+ });
+ if (!result.success) {
+ log('execAgent: hetero device dispatch failed: %s', result.error);
+ return failHeteroDispatch(
+ deps,
+ run,
+ {
+ detail: result.error ?? 'Device dispatch failed',
+ deviceRoute: {
+ deviceId: dispatchDeviceId,
+ userId: deps.userId,
+ ...(dispatchWorkspaceId ? { workspaceId: dispatchWorkspaceId } : {}),
+ },
+ errorData: result.errorData,
+ errorType: resolveHeteroDispatchErrorType(result.error),
+ message: humanizeHeteroDispatchError(result.error),
+ },
+ {
+ error: result.error,
+ errorData: result.errorData,
+ message: 'Hetero agent device dispatch failed',
+ },
+ );
+ }
+
+ // Local CLI hetero agents dispatch to a device just like remote platform
+ // agents, so persist the device route after the dispatch is accepted.
+ // interruptTask uses these fields to find and stop the native process.
+ try {
+ const patched = await deps.topicModel.patchRunningOperation(topicId, operationId, {
+ deviceId: dispatchDeviceId,
+ deviceWorkspaceId: dispatchWorkspaceId,
+ heteroType,
+ });
+ log(
+ 'execAgent: patch runningOperation device info=%s deviceId=%s heteroType=%s op=%s',
+ patched,
+ dispatchDeviceId,
+ heteroType,
+ operationId,
+ );
+ } catch (err) {
+ log('execAgent: failed to patch runningOperation with device info: %O', err);
+ }
+
+ return undefined;
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
new file mode 100644
index 00000000000..40264d7d655
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
@@ -0,0 +1,586 @@
+import { HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR } from '@lobechat/heterogeneous-agents';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ humanizeHeteroDispatchError,
+ resolveHeteroDispatchErrorType,
+} from '../../helpers/heteroErrors';
+import type { ExecRunContext } from '../../types';
+import type { HeteroDispatchDeps, HeteroDispatchInput } from '.';
+import { dispatchHeteroAgent } from '.';
+
+const mocks = vi.hoisted(() => ({
+ completeOperation: vi.fn(),
+ createOperationMetadata: vi.fn(),
+ dispatchAgentRun: vi.fn(),
+ executeToolCall: vi.fn(),
+ finalizeHeteroDispatchError: vi.fn(),
+ publishAgentRuntimeInit: vi.fn(),
+ recordStart: vi.fn(),
+ resolveDeviceDispatchAuthorizationFailure: vi.fn(),
+ resolveSandboxSessionConfig: vi.fn(),
+ selectCodexDeviceDispatch: vi.fn(),
+ signHeteroOperationJWT: vi.fn(),
+ signUserJWT: vi.fn(),
+ spawnHeteroSandbox: vi.fn(),
+}));
+
+vi.mock('@/server/services/agentRuntime/CompletionLifecycle', () => ({
+ CompletionLifecycle: vi.fn().mockImplementation(function () {
+ return { completeOperation: mocks.completeOperation, recordStart: mocks.recordStart };
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime/hooks', () => ({
+ hookDispatcher: {
+ canDeliver: vi.fn().mockReturnValue(false),
+ getSerializedHooks: vi.fn().mockReturnValue([]),
+ register: vi.fn(),
+ unregister: vi.fn(),
+ },
+}));
+
+vi.mock('@/server/services/heterogeneousAgent', () => ({
+ HeterogeneousAgentService: vi.fn().mockImplementation(function () {
+ return { getHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined) };
+ }),
+}));
+
+vi.mock('@/libs/trpc/utils/internalJwt', () => ({
+ signHeteroOperationJWT: mocks.signHeteroOperationJWT,
+ signUserJWT: mocks.signUserJWT,
+}));
+
+vi.mock('@/server/modules/AgentRuntime/factory', () => ({
+ createAgentStateManager: () => ({ createOperationMetadata: mocks.createOperationMetadata }),
+ createStreamEventManager: () => ({ publishAgentRuntimeInit: mocks.publishAgentRuntimeInit }),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ dispatchAgentRun: mocks.dispatchAgentRun,
+ executeToolCall: mocks.executeToolCall,
+ readDeviceSystemInfo: vi.fn(),
+ },
+}));
+
+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({
+ resolveDeviceDispatchAuthorizationFailure: mocks.resolveDeviceDispatchAuthorizationFailure,
+}));
+
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn().mockImplementation(function () {
+ return {
+ findByDeviceId: vi.fn().mockResolvedValue(undefined),
+ findWorkspaceDeviceById: vi.fn().mockResolvedValue(undefined),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/sandbox/session', () => ({
+ resolveSandboxSessionConfig: mocks.resolveSandboxSessionConfig,
+}));
+
+vi.mock('@/server/services/heterogeneousAgent/sandboxRunner', () => ({
+ spawnHeteroSandbox: mocks.spawnHeteroSandbox,
+}));
+
+vi.mock('../finalizeHeteroDispatchError', () => ({
+ finalizeHeteroDispatchError: mocks.finalizeHeteroDispatchError,
+}));
+
+vi.mock('../codexDeviceRuntime', () => ({
+ selectCodexDeviceDispatch: mocks.selectCodexDeviceDispatch,
+}));
+
+const createDeps = (overrides: Partial<HeteroDispatchDeps> = {}) => {
+ const topicModel = {
+ appendRunningOperationChild: vi.fn().mockResolvedValue(true),
+ findById: vi.fn().mockResolvedValue({ metadata: {} }),
+ patchRunningOperation: vi.fn().mockResolvedValue(true),
+ updateMetadata: vi.fn().mockResolvedValue(undefined),
+ };
+ const deps = {
+ bindTopicWorkingDirectory: vi.fn().mockResolvedValue(undefined),
+ db: {} as any,
+ getMarketService: vi.fn().mockRejectedValue(new Error('market unavailable')),
+ messageModel: { query: vi.fn().mockResolvedValue([]) } as any,
+ resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),
+ topicModel: topicModel as any,
+ userId: 'user-1',
+ withholdGatewayToken: false,
+ ...overrides,
+ } satisfies HeteroDispatchDeps;
+ return { deps, topicModel };
+};
+
+const createCtx = (
+ agencyConfig: Record<string, unknown>,
+ overrides: Partial<ExecRunContext> = {},
+): ExecRunContext =>
+ ({
+ agentConfig: { agencyConfig, id: 'agent-1', userId: 'author-1' },
+ assistantMessageId: 'asst-1',
+ canUseDevice: true,
+ deviceAccessReason: 'owner',
+ model: 'model',
+ parentMessageId: 'parent-1',
+ persistAgentId: 'agent-1',
+ prompt: 'hello',
+ provider: 'provider',
+ resolvedAgentId: 'agent-1',
+ runFacts: {} as any,
+ topicId: 'topic-1',
+ userMessageId: 'user-msg-1',
+ ...overrides,
+ }) as ExecRunContext;
+
+const createInput = (
+ heteroType: HeteroDispatchInput['heteroType'],
+ overrides: Partial<HeteroDispatchInput> = {},
+): HeteroDispatchInput => ({
+ canManageAgent: true,
+ heteroType,
+ isPublicWorkspaceAgent: false,
+ runAttachments: { audioList: [], fileList: [], imageList: [], videoList: [] },
+ selfMessageIds: new Set(),
+ ...overrides,
+});
+
+const errorResult = (fields: Record<string, unknown>) => ({
+ agentId: 'agent-1',
+ assistantMessageId: 'asst-1',
+ autoStarted: false,
+ createdAt: expect.any(String),
+ operationId: expect.stringMatching(/^op_\d+_agent-1_topic-1_/),
+ status: 'error',
+ success: false,
+ terminalReported: true,
+ timestamp: expect.any(String),
+ topicId: 'topic-1',
+ userMessageId: 'user-msg-1',
+ ...fields,
+});
+
+const finalizeParams = (fields: Record<string, unknown>) => ({
+ agentId: 'agent-1',
+ assistantMessageId: 'asst-1',
+ operationId: expect.stringMatching(/^op_/),
+ topicId: 'topic-1',
+ ...fields,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.recordStart.mockResolvedValue(true);
+ mocks.signHeteroOperationJWT.mockResolvedValue('op-jwt');
+ mocks.signUserJWT.mockResolvedValue('user-jwt');
+ mocks.finalizeHeteroDispatchError.mockResolvedValue(true);
+ mocks.resolveDeviceDispatchAuthorizationFailure.mockResolvedValue(undefined);
+ mocks.resolveSandboxSessionConfig.mockResolvedValue(undefined);
+ mocks.selectCodexDeviceDispatch.mockResolvedValue({ kind: 'exec' });
+ mocks.dispatchAgentRun.mockResolvedValue({ success: true });
+ mocks.executeToolCall.mockResolvedValue({ success: true });
+ mocks.spawnHeteroSandbox.mockResolvedValue(undefined);
+ mocks.publishAgentRuntimeInit.mockResolvedValue('init');
+ mocks.createOperationMetadata.mockResolvedValue(undefined);
+});
+
+describe('dispatchHeteroAgent β€” preparation failures', () => {
+ it('fails before dispatch when the operation JWT cannot be signed', async () => {
+ mocks.signHeteroOperationJWT.mockRejectedValueOnce(new Error('no key'));
+ const { deps } = createDeps();
+
+ await expect(
+ dispatchHeteroAgent(
+ deps,
+ createCtx({ heterogeneousProvider: { type: 'claude-code' } }),
+ createInput('claude-code'),
+ ),
+ ).rejects.toThrow('Failed to sign operation JWT for hetero agent');
+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();
+ expect(mocks.spawnHeteroSandbox).not.toHaveBeenCalled();
+ });
+
+ it('rejects a provider-bound (API auth) agent before any dispatch', async () => {
+ const { deps } = createDeps();
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx({
+ executionTarget: 'sandbox',
+ heterogeneousProvider: { authMode: 'api', type: 'claude-code' },
+ }),
+ createInput('claude-code'),
+ );
+
+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(
+ deps,
+ finalizeParams({
+ detail: HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
+ message: 'Provider-bound heterogeneous agents do not support this execution target',
+ }),
+ );
+ expect(result).toStrictEqual(
+ errorResult({
+ error: HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
+ message: 'Heterogeneous agent provider binding requires Desktop local execution',
+ }),
+ );
+ expect(mocks.spawnHeteroSandbox).not.toHaveBeenCalled();
+ });
+});
+
+describe('dispatchHeteroAgent β€” remote platform agents', () => {
+ const remoteConfig = (extra: Record<string, unknown> = {}) => ({
+ executionTarget: 'device',
+ heterogeneousProvider: { platformAgentId: 'platform-agent', type: 'openclaw' },
+ ...extra,
+ });
+
+ it('refuses a sender without device access', async () => {
+ const { deps } = createDeps();
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx(remoteConfig({ boundDeviceId: 'dev-1' }), { canUseDevice: false }),
+ createInput('openclaw'),
+ );
+
+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(
+ deps,
+ finalizeParams({
+ detail: 'This sender is not allowed to run agents on a bound device.',
+ message: 'Device access denied',
+ }),
+ );
+ expect(result).toStrictEqual(
+ errorResult({
+ error: 'Device access denied',
+ message: 'Remote hetero agent requires device access',
+ }),
+ );
+ expect(mocks.executeToolCall).not.toHaveBeenCalled();
+ });
+
+ it('fails when no device is available', async () => {
+ const { deps } = createDeps();
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx(remoteConfig()),
+ createInput('openclaw'),
+ );
+
+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(
+ deps,
+ finalizeParams({
+ detail: 'No local or connected device is available for this agent.',
+ message: 'No execution device for platform agent',
+ }),
+ );
+ expect(result).toStrictEqual(
+ errorResult({
+ error: 'No bound device',
+ message: 'Platform agent requires a local or connected device',
+ }),
+ );
+ });
+
+ it('settles a failed device dispatch with the routed device on the error', async () => {
+ const errorData = { code: 'DEVICE_NOT_FOUND', deviceId: 'dev-1', retryable: true };
+ mocks.executeToolCall.mockResolvedValueOnce({
+ error: 'DEVICE_NOT_FOUND',
+ errorData,
+ success: false,
+ });
+ const { deps } = createDeps();
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx(remoteConfig({ boundDeviceId: 'dev-1' })),
+ createInput('openclaw'),
+ );
+
+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(
+ deps,
+ finalizeParams({
+ detail: 'DEVICE_NOT_FOUND',
+ deviceRoute: { deviceId: 'dev-1', userId: 'author-1' },
+ errorData,
+ errorType: resolveHeteroDispatchErrorType('DEVICE_NOT_FOUND'),
+ message: humanizeHeteroDispatchError('DEVICE_NOT_FOUND'),
+ }),
+ );
+ expect(result).toStrictEqual(
+ errorResult({
+ error: 'DEVICE_NOT_FOUND',
+ errorData,
+ message: 'Remote hetero agent dispatch failed',
+ }),
+ );
+ });
+
+ it('dispatches runHeteroTask to the bound device under the author principal', async () => {
+ const { deps, topicModel } = createDeps({ workspaceId: 'ws-1' });
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx(remoteConfig({ boundDeviceId: 'dev-1' })),
+ createInput('openclaw'),
+ );
+
+ expect(mocks.executeToolCall).toHaveBeenCalledWith(
+ { deviceId: 'dev-1', userId: 'author-1', workspaceId: undefined },
+ expect.objectContaining({ apiName: 'runHeteroTask', identifier: 'runHeteroTask' }),
+ 120_000,
+ );
+ const args = JSON.parse(mocks.executeToolCall.mock.calls[0][1].arguments);
+ expect(args).toEqual({
+ agentId: 'agent-1',
+ agentType: 'openclaw',
+ operationId: result.operationId,
+ platformAgentId: 'platform-agent',
+ prompt: 'hello',
+ taskId: result.operationId,
+ topicId: 'topic-1',
+ workspaceId: 'ws-1',
+ });
+ expect(topicModel.updateMetadata).toHaveBeenCalledWith(
+ 'topic-1',
+ expect.objectContaining({
+ runningOperation: expect.objectContaining({
+ deviceId: 'dev-1',
+ deviceUserId: 'author-1',
+ heteroType: 'openclaw',
+ operationId: result.operationId,
+ }),
+ }),
+ );
+ expect(mocks.publishAgentRuntimeInit).toHaveBeenCalledTimes(1);
+ expect(result).toMatchObject({
+ autoStarted: true,
+ heteroType: 'openclaw',
+ status: 'created',
+ success: true,
+ token: 'user-jwt',
+ });
+ });
+});
+
+describe('dispatchHeteroAgent β€” local CLI agents', () => {
+ it.each([
+ [
+ 'claude-code',
+ 'No device bound. Pick a device in the Execution Device switcher, or switch to Cloud sandbox.',
+ ],
+ ['amp', 'No device bound. Pick a local or connected device in the Execution Device switcher.'],
+ ] as const)('fails an unrouted %s device run', async (heteroType, detail) => {
+ const { deps } = createDeps();
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx({ executionTarget: 'device', heterogeneousProvider: { type: heteroType } }),
+ createInput(heteroType),
+ );
+
+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(
+ deps,
+ finalizeParams({ detail, message: 'No bound device for hetero agent' }),
+ );
+ expect(result).toStrictEqual(
+ errorResult({ error: 'No bound device', message: 'Hetero agent requires a bound device' }),
+ );
+ });
+
+ it('settles a rejected native Codex selection', async () => {
+ mocks.selectCodexDeviceDispatch.mockResolvedValueOnce({
+ kind: 'error',
+ message: 'Codex is too old',
+ });
+ const { deps } = createDeps();
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx({
+ boundDeviceId: 'dev-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'codex' },
+ }),
+ createInput('codex'),
+ );
+
+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(
+ deps,
+ finalizeParams({ detail: 'Codex is too old', message: 'Native Codex dispatch rejected' }),
+ );
+ expect(result).toStrictEqual(
+ errorResult({ error: 'Codex is too old', message: 'Codex is too old' }),
+ );
+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();
+ });
+
+ it('settles a device whose dispatch authorization was revoked', async () => {
+ const errorData = { code: 'DEVICE_NOT_FOUND', deviceId: 'dev-1', retryable: true };
+ mocks.resolveDeviceDispatchAuthorizationFailure.mockResolvedValueOnce(errorData);
+ const { deps } = createDeps();
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx({
+ boundDeviceId: 'dev-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ }),
+ createInput('claude-code'),
+ );
+
+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();
+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(
+ deps,
+ finalizeParams({
+ detail: 'DEVICE_NOT_FOUND',
+ deviceRoute: { deviceId: 'dev-1', userId: 'user-1' },
+ errorData,
+ errorType: resolveHeteroDispatchErrorType('DEVICE_NOT_FOUND'),
+ message: humanizeHeteroDispatchError('DEVICE_NOT_FOUND'),
+ }),
+ );
+ expect(result).toStrictEqual(
+ errorResult({
+ error: 'DEVICE_NOT_FOUND',
+ errorData,
+ message: 'Hetero agent device dispatch failed',
+ }),
+ );
+ });
+
+ it('dispatches to the bound device and records the device route', async () => {
+ const { deps, topicModel } = createDeps({ workspaceId: 'ws-1' });
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx({
+ boundDeviceId: 'dev-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ }),
+ createInput('claude-code'),
+ );
+
+ expect(mocks.dispatchAgentRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ agentType: 'claude-code',
+ deviceId: 'dev-1',
+ ingestWorkspaceId: 'ws-1',
+ jwt: 'op-jwt',
+ operationId: result.operationId,
+ prompt: 'hello',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ workspaceId: undefined,
+ }),
+ );
+ expect(deps.bindTopicWorkingDirectory).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'dev-1', topicId: 'topic-1' }),
+ );
+ expect(topicModel.patchRunningOperation).toHaveBeenCalledWith('topic-1', result.operationId, {
+ deviceId: 'dev-1',
+ deviceWorkspaceId: undefined,
+ heteroType: 'claude-code',
+ });
+ expect(result).toMatchObject({ status: 'created', success: true, token: 'user-jwt' });
+ });
+
+ it('never routes a device-only provider to the cloud sandbox', async () => {
+ const { deps } = createDeps();
+
+ const result = await dispatchHeteroAgent(
+ deps,
+ createCtx({ executionTarget: 'sandbox', heterogeneousProvider: { type: 'amp' } }),
+ createInput('amp'),
+ );
+
+ expect(mocks.spawnHeteroSandbox).not.toHaveBeenCalled();
+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(
+ deps,
+ finalizeParams({
+ detail:
+ 'No device bound. Pick a local or connected device in the Execution Device switcher.',
+ message: 'No bound device for hetero agent',
+ }),
+ );
+ expect(result).toStrictEqual(
+ errorResult({ error: 'No bound device', message: 'Hetero agent requires a bound device' }),
+ );
+ });
+});
+
+describe('dispatchHeteroAgent β€” cloud sandbox', () => {
+ const sandboxCtx = (env?: Record<string, string>) =>
+ createCtx({
+ executionTarget: 'sandbox',
+ heterogeneousProvider: { env, type: 'claude-code' },
+ });
+
+ it('spawns the sandbox with the personal GitHub credential and a user JWT', async () => {
+ const credsList = vi.fn().mockResolvedValue({ data: [{ id: 'cred-1', key: 'github' }] });
+ const credsGet = vi.fn().mockResolvedValue({ plaintext: { access_token: 'gh-token' } });
+ const marketService = { market: { creds: { get: credsGet, list: credsList } } };
+ const { deps } = createDeps({ getMarketService: vi.fn().mockResolvedValue(marketService) });
+
+ const result = await dispatchHeteroAgent(deps, sandboxCtx(), createInput('claude-code'));
+
+ expect(credsGet).toHaveBeenCalledWith('cred-1', { decrypt: true });
+ expect(mocks.signUserJWT).toHaveBeenCalledWith('user-1', '4h');
+ expect(mocks.spawnHeteroSandbox).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentType: 'claude-code',
+ githubToken: 'gh-token',
+ jwt: 'user-jwt',
+ marketService,
+ operationId: result.operationId,
+ sandbox: undefined,
+ }),
+ );
+ expect(result).toMatchObject({ status: 'created', success: true, token: 'user-jwt' });
+ });
+
+ it('reads the GitHub credential from the workspace under a custom key', async () => {
+ const credsList = vi.fn().mockResolvedValue({ data: [{ id: 'cred-2', key: 'gh-org' }] });
+ const credsGet = vi.fn().mockResolvedValue({ values: { token: 'org-token' } });
+ const organizationCreds = vi.fn().mockReturnValue({ get: credsGet, list: credsList });
+ const marketService = { market: { organizations: { creds: organizationCreds } } };
+ const { deps } = createDeps({
+ getMarketService: vi.fn().mockResolvedValue(marketService),
+ workspaceId: 'ws-1',
+ });
+
+ await dispatchHeteroAgent(
+ deps,
+ sandboxCtx({ GITHUB_CRED_KEY: 'gh-org' }),
+ createInput('claude-code'),
+ );
+
+ expect(organizationCreds).toHaveBeenCalledWith({ workspaceId: 'ws-1' });
+ expect(credsGet).toHaveBeenCalledWith('cred-2', { decrypt: true });
+ expect(mocks.spawnHeteroSandbox).toHaveBeenCalledWith(
+ expect.objectContaining({ githubToken: 'org-token', workspaceId: 'ws-1' }),
+ );
+ });
+
+ it('withholds the gateway token when asked to', async () => {
+ const marketService = { market: { creds: { list: vi.fn().mockResolvedValue({ data: [] }) } } };
+ const { deps } = createDeps({
+ getMarketService: vi.fn().mockResolvedValue(marketService),
+ withholdGatewayToken: true,
+ });
+
+ const result = await dispatchHeteroAgent(deps, sandboxCtx(), createInput('claude-code'));
+
+ expect(mocks.signUserJWT).toHaveBeenCalledTimes(1);
+ expect(mocks.signUserJWT).toHaveBeenCalledWith('user-1', '4h');
+ expect(result).toMatchObject({ success: true, token: undefined });
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts
new file mode 100644
index 00000000000..74caf2ae69e
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts
@@ -0,0 +1,437 @@
+import {
+ HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
+ isRemoteHeterogeneousType,
+} from '@lobechat/heterogeneous-agents';
+import type { ExecAgentResult } from '@lobechat/types';
+import { resolveHeterogeneousRuntimeConfig } from '@lobechat/types';
+import { nanoid } from '@lobechat/utils';
+import debug from 'debug';
+
+import { resolveExecutionPlan, resolveWorkspaceScoped } from '@/helpers/executionTarget';
+import { signUserJWT } from '@/libs/trpc/utils/internalJwt';
+import {
+ createAgentStateManager,
+ createStreamEventManager,
+} from '@/server/modules/AgentRuntime/factory';
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
+import { hookDispatcher } from '@/server/services/agentRuntime/hooks';
+
+import { supportsCloudHeterogeneousSandbox } from '../../helpers/heteroErrors';
+import type { ExecRunContext } from '../../types';
+import { dispatchToCliDevice } from './device';
+import { prepareHeteroRun } from './prepare';
+import { dispatchToPlatformDevice } from './remote';
+import { spawnInCloudSandbox } from './sandbox';
+import type { HeteroDispatchDeps, HeteroDispatchInput, HeteroRun } from './types';
+import { failHeteroDispatch, heteroErrorResult } from './utils';
+
+export type { HeteroDispatchDeps, HeteroDispatchInput } from './types';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Stage 3.5 of {@link AiAgentService.execAgent}: heterogeneous-agent early
+ * exit. Local CLI and remote platform 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` (amp / claude-code / codebuddy / codex / cursor / droid /
+ * grok-build / kimi-code / opencode / pi / qoder / trae) or
+ * `agentNotify.notify` (openclaw / hermes).
+ *
+ * Always returns a terminal {@link ExecAgentResult} β€” the caller's `execAgent`
+ * returns it directly and never continues to the normal-agent stages.
+ */
+export const dispatchHeteroAgent = async (
+ deps: HeteroDispatchDeps,
+ ctx: ExecRunContext,
+ input: HeteroDispatchInput,
+): Promise<ExecAgentResult> => {
+ const {
+ agentConfig,
+ appContext,
+ assistantMessageId,
+ canUseDevice,
+ deviceAccessReason,
+ parentMessageId,
+ persistAgentId,
+ prompt,
+ resolvedAgentId,
+ topicId,
+ trigger,
+ userMessageId,
+ } = ctx;
+ const {
+ canManageAgent,
+ effectiveRequestedDeviceId,
+ heteroType,
+ heterogeneousProvider,
+ hooks,
+ isPublicWorkspaceAgent,
+ localDeviceId,
+ maxSteps,
+ memberDeviceOverride,
+ operationTaskId,
+ parentOperationId,
+ pinnedHeterogeneousTopicModel,
+ requestTrigger,
+ requestedDeviceId,
+ topicStartOwnerOperationId,
+ } = input;
+
+ const isRemoteHetero = isRemoteHeterogeneousType(heteroType);
+ // Same structured shape as the built-in path (`op_{ts}_{agentId}_{topicId}_{rand}`)
+ // so hetero ops aren't visually distinct bare nanoids in the trace/op tables.
+ const operationId = `op_${Date.now()}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;
+
+ // Retain only public configuration dimensions. CLI args and API credentials must
+ // never be copied into topic metadata or an inspector response. The receipt
+ // reads the same provider and pin as the dispatched CLI args below.
+ const runtimeConfig = {
+ fields: resolveHeterogeneousRuntimeConfig(
+ heterogeneousProvider ?? { type: heteroType },
+ pinnedHeterogeneousTopicModel,
+ input.pinnedHeterogeneousTopicSources ?? 'topic',
+ ),
+ operationId,
+ };
+
+ // Hooks belong to this operation's lifecycle. Persist their serializable
+ // form on the durable operation row before dispatch; runningOperation below
+ // remains a compatibility mirror for older terminal consumers.
+ hookDispatcher.register(operationId, hooks ?? []);
+ const serializedHooks = hookDispatcher.getSerializedHooks(operationId);
+
+ // Persist a first-class agent_operations row for the hetero run. The id is
+ // generated here (authoritative) and flows through to heteroIngest /
+ // heteroFinish unchanged. Without this row the run is invisible to the
+ // operation lifecycle: verify (ensureForOperation), repair (parent chain),
+ // judge (op.model/provider) and tracing all key off it. The durable row is
+ // also an authentication prerequisite: every callback
+ // re-authorizes its operation token against this exact principal. Do not
+ // mint a token or dispatch/spawn when persistence fails.
+ const operationPersisted = await new CompletionLifecycle(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).recordStart({
+ agentId: persistAgentId,
+ appContext: { ...appContext, sourceMessageId: userMessageId },
+ chatGroupId: appContext?.groupId ?? null,
+ maxSteps,
+ metadata: {
+ _hooks: serializedHooks,
+ assistantMessageId,
+ heterogeneousRuntimeConfig: runtimeConfig,
+ },
+ operationId,
+ parentOperationId,
+ provider: heteroType,
+ taskId: operationTaskId ?? null,
+ threadId: appContext?.threadId ?? null,
+ topicId,
+ trigger,
+ });
+ if (!operationPersisted) {
+ hookDispatcher.unregister(operationId);
+ throw new Error('Failed to persist heterogeneous agent operation');
+ }
+
+ await input.onOperationCreated?.(operationId);
+
+ const run: HeteroRun = {
+ agentId: resolvedAgentId,
+ assistantMessageId,
+ operationId,
+ topicId,
+ userMessageId: userMessageId ?? parentMessageId ?? '',
+ };
+
+ // Resume session, operation JWT, topic repos, GitHub token, recovery
+ // history, sandbox placement, system contexts and the CLI request.
+ const prepared = await prepareHeteroRun(deps, ctx, input, operationId);
+
+ const platformPlan = isRemoteHetero
+ ? resolveExecutionPlan({
+ agencyConfig: agentConfig.agencyConfig,
+ canUseDevice,
+ clientExecutionAvailable: Boolean(localDeviceId),
+ isHetero: true,
+ localDeviceId,
+ requestedDeviceId: effectiveRequestedDeviceId,
+ sandboxExecutionAvailable: false,
+ trigger: requestTrigger,
+ workspaceScoped: resolveWorkspaceScoped(
+ isPublicWorkspaceAgent && !canManageAgent,
+ memberDeviceOverride,
+ ),
+ })
+ : undefined;
+ const remoteDeviceId = platformPlan?.kind === 'device' ? platformPlan.deviceId : undefined;
+ const remoteDeviceWorkspaceId = remoteDeviceId
+ ? await deps.resolveDeviceWorkspaceId(remoteDeviceId)
+ : undefined;
+ const usesCallersPersonalDevice =
+ platformPlan?.kind === 'device' &&
+ !remoteDeviceWorkspaceId &&
+ (effectiveRequestedDeviceId === remoteDeviceId ||
+ (platformPlan.target === 'local' &&
+ agentConfig.agencyConfig?.executionTargetSelectionPolicy !== 'fixed') ||
+ (!canManageAgent && memberDeviceOverride?.boundDeviceId === remoteDeviceId));
+ const remoteDeviceUserId = usesCallersPersonalDevice
+ ? deps.userId
+ : (agentConfig.userId ?? deps.userId);
+
+ // Resolve CLI-device routing before persisting the marker. Cancellation
+ // must address the same device even though local CLI agents use a different
+ // dispatch transport from notify-based platform agents.
+ const deviceHeteroPlan = !isRemoteHetero
+ ? resolveExecutionPlan({
+ agencyConfig: agentConfig.agencyConfig,
+ canUseDevice,
+ isHetero: true,
+ clientExecutionAvailable: false,
+ requestedDeviceId,
+ sandboxExecutionAvailable: supportsCloudHeterogeneousSandbox(heteroType),
+ trigger: requestTrigger,
+ })
+ : undefined;
+ const cliDeviceId = deviceHeteroPlan?.kind === 'device' ? deviceHeteroPlan.deviceId : undefined;
+ const cliDeviceWorkspaceId = cliDeviceId
+ ? await deps.resolveDeviceWorkspaceId(cliDeviceId)
+ : undefined;
+
+ // Register the run's lifecycle hooks so the hetero terminal path fires
+ // onComplete/onError through the same `hookDispatcher` the normal LLM
+ // runtime uses β€” driving the task lifecycle (onTopicComplete) and IM bot
+ // completion callbacks uniformly. The hetero block returns before
+ // AgentRuntimeService (which registers hooks for normal runs), so we do it
+ // here. Local mode dispatches these in-memory handlers; queue mode delivers
+ // the serialized webhooks persisted on the operation row above.
+ // Seed topic.metadata.runningOperation so heteroIngest can validate the
+ // operation, and so every terminal site (heteroFinish, agentNotify done,
+ // dispatch failure) can re-fire the serialized hooks across a process
+ // boundary in queue mode.
+ const childOperation = {
+ assistantMessageId,
+ heteroType,
+ hooks: serializedHooks,
+ startedAt: new Date().toISOString(),
+ ...(isRemoteHetero && remoteDeviceId
+ ? {
+ deviceId: remoteDeviceId,
+ deviceUserId: remoteDeviceUserId,
+ deviceWorkspaceId: remoteDeviceWorkspaceId,
+ }
+ : cliDeviceId
+ ? {
+ deviceId: cliDeviceId,
+ deviceUserId: deps.userId,
+ deviceWorkspaceId: cliDeviceWorkspaceId,
+ }
+ : {}),
+ operationId,
+ orchestrationRole: appContext?.orchestrationRole,
+ scope: appContext?.scope ?? undefined,
+ threadId: appContext?.threadId ?? undefined,
+ };
+ if (topicStartOwnerOperationId) {
+ const attached = await deps.topicModel.appendRunningOperationChild(
+ topicId,
+ topicStartOwnerOperationId,
+ childOperation,
+ );
+ if (!attached) {
+ const message = 'Group supervisor finished before this member could start.';
+ // Same contract as `finalizeHeteroDispatchError`: read the hook before the
+ // dispatch settles and unregisters it, so the caller learns whether this
+ // failure was already announced to its own surfaces.
+ const terminalReported = hookDispatcher.canDeliver(operationId, 'onComplete');
+ await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId).completeOperation(
+ {
+ agentId: persistAgentId,
+ assistantMessageId,
+ error: { message, type: 'AgentRuntimeError' },
+ operationId,
+ orchestrationRole: appContext?.orchestrationRole,
+ serializedHooks,
+ topicId,
+ userId: deps.userId,
+ },
+ 'error',
+ );
+ return heteroErrorResult(run, { error: message, message, terminalReported });
+ }
+ } else if (appContext?.isolationThread && parentOperationId) {
+ // Isolation-thread children (callAgent / callSubAgent) run on the
+ // SPAWNER's topic and finish long before it does. heteroIngest and
+ // heteroFinish both require this child's operationId to resolve via
+ // topic.metadata.runningOperation (root or childOperations) β€” see
+ // the comment above childOperation β€” or every streamed batch is
+ // dropped as stale and the terminal onComplete hooks (including the
+ // callAgent resume bridge) never fire. Nest under the parent's own
+ // marker instead of claiming the topic-level root outright, so the
+ // parent's marker survives for the rest of its still-running turn.
+ const attachedToParent = await deps.topicModel.appendRunningOperationChild(
+ topicId,
+ parentOperationId,
+ childOperation,
+ );
+ if (!attachedToParent) {
+ // Parent isn't (or is no longer) the topic's current root marker β€”
+ // e.g. a nested isolation chain, or the parent already settled.
+ // Fall back to claiming the marker directly so this child is still
+ // discoverable by its own operationId, rather than permanently
+ // unrecognized by heteroIngest/heteroFinish.
+ await deps.topicModel.updateMetadata(topicId, { runningOperation: childOperation });
+ }
+ } else if (!appContext?.isolationThread) {
+ // The receipt previously had a separate projection write after this marker.
+ // Store both together so a follow-up cannot install a new running operation
+ // while retaining the previous operation's displayed configuration.
+ // Task drawer follow-ups can omit taskId; receipt ownership is independent
+ // of Task lifecycle association, while isolated children keep the root receipt.
+ await deps.topicModel.updateMetadata(topicId, {
+ heteroRuntimeConfig: runtimeConfig,
+ runningOperation: childOperation,
+ });
+ }
+
+ // Always persist operation metadata (userId/workspaceId) to the state
+ // manager, not just for topic-owner-mirrored runs. `subAgentCallback`
+ // (the QStash-delivered completion bridge for callAgent/callSubAgent
+ // children) resolves `userId` from this same store to authorize
+ // resuming the parent β€” without it, a hetero child spawned via
+ // callAgent has no metadata row, the callback 401s, and the parent
+ // operation is never resumed (stays parked until the inactivity
+ // watchdog abandons it).
+ const persistOperationMetadata = async () => {
+ try {
+ await createAgentStateManager().createOperationMetadata(operationId, {
+ ...(topicStartOwnerOperationId && {
+ mirrorToOperationId: topicStartOwnerOperationId,
+ }),
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ });
+ } catch (err) {
+ log('execAgent: failed to persist hetero operation metadata: %O', err);
+ }
+ };
+
+ if (agentConfig.agencyConfig?.heterogeneousProvider?.authMode === 'api') {
+ return failHeteroDispatch(
+ deps,
+ run,
+ {
+ detail: HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
+ message: 'Provider-bound heterogeneous agents do not support this execution target',
+ },
+ {
+ error: HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
+ message: 'Heterogeneous agent provider binding requires Desktop local execution',
+ },
+ );
+ }
+
+ if (isRemoteHetero) {
+ const failure = await dispatchToPlatformDevice(deps, run, {
+ agentConfig,
+ canUseDevice,
+ deviceAccessReason,
+ heteroType,
+ persistOperationMetadata,
+ prompt,
+ remoteDeviceId,
+ remoteDeviceUserId,
+ remoteDeviceWorkspaceId,
+ topicStartOwnerOperationId,
+ });
+ if (failure) return failure;
+ } else {
+ // Local CLI hetero (Amp / Claude Code / Codex / Kimi Code / OpenCode /
+ // Pi / Qoder) β€” fork between device dispatch and cloud sandbox via the
+ // shared execution plan:
+ // - requestedDeviceId (topic-level override) always wins
+ // - executionTarget 'device' β†’ dispatch to boundDeviceId (errors if unset)
+ // - executionTarget 'local' + boundDeviceId (desktop sync opened on web)
+ // β†’ dispatch to that device
+ // - everything else ('sandbox' / unbound 'local' / 'none' / unset) β†’ cloud
+ // sandbox when the provider supports it; Amp and OpenCode remain
+ // unrouted because they require a local or connected device
+ // `onlineDeviceIds` is intentionally omitted: hetero dispatch trusts
+ // the binding and fails loudly at the gateway if the device is offline.
+ // `canUseDevice` degrades device-capable targets to the sandbox when
+ // available, or leaves device-only providers unrouted, for denied
+ // senders (e.g. external bot users). Without this a synced local/device
+ // binding would let them run on the owner's machine.
+
+ // Register the op with the agent-gateway DO before dispatch, mirroring
+ // the remote-hetero branch above. Local CLI hetero (claude-code / codex)
+ // streams back via heteroIngest, which forwards live events the DO can
+ // relay even without an init β€” so the FIRST run renders fine. But a later
+ // `reconnectToGatewayOperation` (task topic drawer open / page reload)
+ // sends a `resume` that asks the DO for the op's status; with no session
+ // record the DO answers terminal, the client fires `session_complete`,
+ // and `onSessionComplete` clears `topic.metadata.runningOperation`. The
+ // still-running CC's next heteroIngest batch then hits
+ // StaleHeteroOperationError and is silently dropped β€” the agent appears
+ // to stop the moment the window is opened. Seeding the init keeps the DO
+ // reporting `running`, so resume stays connected and keeps streaming.
+ // Best-effort: a stream-manager/Redis failure must never block dispatch β€”
+ // the init only powers reconnect, not the run. `createStreamEventManager`
+ // probes Redis synchronously, so guard construction too, not just publish.
+ try {
+ await persistOperationMetadata();
+ await createStreamEventManager().publishAgentRuntimeInit(operationId, {
+ agentId: resolvedAgentId,
+ assistantMessageId,
+ heteroType,
+ mirrorToOperationId: topicStartOwnerOperationId,
+ topicId,
+ userId: deps.userId,
+ });
+ } catch (err) {
+ log('execAgent: failed to init stream for local hetero: %O', err);
+ }
+
+ const heteroPlan = deviceHeteroPlan!;
+ const failure =
+ heteroPlan.kind !== 'sandbox'
+ ? await dispatchToCliDevice(deps, run, {
+ agentConfig,
+ appContext,
+ cliDeviceWorkspaceId,
+ heteroPlan,
+ heteroType,
+ heterogeneousProvider,
+ prepared,
+ })
+ : await spawnInCloudSandbox(deps, run, { heteroType, prepared });
+ if (failure) return failure;
+ }
+
+ let gatewayToken: string | undefined;
+ if (!deps.withholdGatewayToken) {
+ try {
+ gatewayToken = await signUserJWT(deps.userId);
+ } catch {
+ // non-critical
+ }
+ }
+
+ return {
+ agentId: resolvedAgentId,
+ assistantMessageId,
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ heteroType,
+ message: 'Hetero agent dispatched successfully',
+ operationId,
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: gatewayToken,
+ topicId,
+ userMessageId: userMessageId ?? parentMessageId ?? '',
+ };
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
new file mode 100644
index 00000000000..64f7b2c14a9
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
@@ -0,0 +1,241 @@
+import { stripGoalCommand, withConversationGoalPrompt } from '@lobechat/builtin-tool-goal';
+import { LOADING_FLAT } from '@lobechat/const';
+import {
+ appendAttachedFilesToPrompt,
+ collectHeteroAttachedFiles,
+ isLocalHeterogeneousType,
+} from '@lobechat/heterogeneous-agents';
+import { applyTopicModelToHeterogeneousProvider, buildHeteroExecArgs } from '@lobechat/types';
+import debug from 'debug';
+
+import { signHeteroOperationJWT } from '@/libs/trpc/utils/internalJwt';
+import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';
+import type { ConversationHistoryEntry } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
+import { buildCloudHeteroContext } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
+import { resolveSandboxSessionConfig } from '@/server/services/sandbox/session';
+
+import { supportsCloudHeterogeneousSandbox } from '../../helpers/heteroErrors';
+import type { ExecRunContext } from '../../types';
+import { heteroOperationCapabilities } from '../heteroOperationCapabilities';
+import { buildViewedTaskContextPrompt, joinSystemContext } from '../viewedTaskContext';
+import type { HeteroDispatchDeps, HeteroDispatchInput } from './types';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Everything a dispatch target needs that does not depend on where the run
+ * goes: the resume session, the operation JWT, the topic and its repos, the
+ * GitHub token, the recovery history, the cloud-sandbox placement, the system
+ * contexts, and the CLI request itself.
+ */
+export const prepareHeteroRun = async (
+ deps: HeteroDispatchDeps,
+ ctx: Pick<
+ ExecRunContext,
+ 'agentConfig' | 'appContext' | 'assistantMessageId' | 'prompt' | 'shareGate' | 'topicId'
+ >,
+ input: Pick<
+ HeteroDispatchInput,
+ | 'heterogeneousProvider'
+ | 'heteroType'
+ | 'operationTaskId'
+ | 'pinnedHeterogeneousTopicModel'
+ | 'runAttachments'
+ | 'selfMessageIds'
+ >,
+ operationId: string,
+) => {
+ const { agentConfig, appContext, assistantMessageId, prompt, topicId } = ctx;
+ const {
+ heteroType,
+ heterogeneousProvider,
+ operationTaskId,
+ pinnedHeterogeneousTopicModel,
+ runAttachments,
+ selfMessageIds,
+ } = input;
+
+ // Read resume session id for next-turn continuity.
+ const heteroService = new HeterogeneousAgentService(deps.db, deps.userId, {
+ workspaceId: deps.workspaceId,
+ });
+ 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 signHeteroOperationJWT({
+ // A `/goal` run also gets `goal:manage` so it can create the goal the agent
+ // supervises; the server still derives the agent and topic from this
+ // operation, never from the CLI.
+ capabilities: heteroOperationCapabilities(prompt),
+ operationId,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ });
+ } 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 });
+ }
+
+ // Read repos from topic metadata for sandbox setup (web/cloud only).
+ const topic = await deps.topicModel.findById(topicId);
+ const topicRepos: string[] = topic?.metadata?.repos ?? [];
+
+ // Resolve GitHub OAuth token for the sandbox. Always attempt so CC can use
+ // git / gh CLI even when no repos are pre-selected. Falls back to the
+ // standard 'github' key (LobeHub OAuth connector default); agent config can
+ // override via GITHUB_CRED_KEY.
+ let githubToken: string | undefined;
+ const githubCredKey =
+ agentConfig.agencyConfig?.heterogeneousProvider?.env?.GITHUB_CRED_KEY ?? 'github';
+ try {
+ const marketService = await deps.getMarketService();
+ // Inside a workspace, the GitHub cred must come from the workspace's shared
+ // organization credentials, not the operator's personal creds.
+ const credsAccessor = deps.workspaceId
+ ? marketService.market.organizations.creds({ workspaceId: deps.workspaceId })
+ : marketService.market.creds;
+ const list = await credsAccessor.list();
+ const cred = list.data?.find((c: { key: string }) => c.key === githubCredKey);
+ if (cred) {
+ const full = await credsAccessor.get(cred.id, { decrypt: true });
+ const vals = (full as any).plaintext ?? (full as any).values ?? {};
+ githubToken = vals.access_token ?? vals.token;
+ }
+ } catch (err) {
+ log('execAgent: failed to resolve GitHub token: %O', err);
+ }
+
+ // Recovery history is reserved for the CLI's retry without native resume.
+ // The primary resumed attempt already has native history and must not get
+ // a serialized duplicate. Amp threads are server-backed, so they rely on
+ // native continuation exclusively and never need this local-file fallback.
+ let conversationHistory: ConversationHistoryEntry[] | undefined;
+ if (heteroType !== 'amp') {
+ try {
+ // `allowShareVisitor`: this is the RUN's own topic, already resolved
+ // and authorized upstream. An agent-share visitor run executes under
+ // the creator's identity, so without the opt-in `query()`'s
+ // creator-facing default would hand the agent an empty history.
+ const recentMsgs = await deps.messageModel.query(
+ { topicId, pageSize: 200 },
+ { allowShareVisitor: true },
+ );
+ const turns = recentMsgs
+ .filter(
+ (m) =>
+ (m.role === 'user' || m.role === 'assistant') &&
+ !m.threadId &&
+ !selfMessageIds.has(m.id) &&
+ m.content &&
+ m.content !== LOADING_FLAT,
+ )
+ .slice(-30)
+ .map((m) => ({
+ content: m.content ?? '',
+ role: m.role as 'assistant' | 'user',
+ }));
+ if (turns.length > 0) conversationHistory = turns;
+ } catch (err) {
+ log('execAgent: failed to load conversation history for hetero context: %O', err);
+ }
+ }
+
+ // Where a cloud-sandbox run keeps its files: the same resolution the plain
+ // cloud-sandbox runtime does, so a hetero topic bound to an environment
+ // instance runs in that instance rather than in a throwaway box. Only for
+ // providers the cloud sandbox can host at all; device-only providers never
+ // read it. Never throws β€” a failed lookup is the ephemeral sandbox.
+ const sandbox = supportsCloudHeterogeneousSandbox(heteroType)
+ ? await resolveSandboxSessionConfig({
+ isShareVisitorRun: !!ctx.shareGate,
+ serverDB: deps.db,
+ topicId,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ })
+ : undefined;
+ const sandboxPlacement = sandbox && { cwd: sandbox.cwd, mode: sandbox.mode };
+
+ // Primary context omits history (a failed native resume retries with the full
+ // fallback). `/goal` and the task viewed in a Tasks side chat ride along.
+ const providerContext = agentConfig.agencyConfig?.heterogeneousProvider?.systemContext;
+ const viewedTaskContext = await buildViewedTaskContextPrompt(deps, appContext, operationTaskId);
+ const agentSystemContext = withConversationGoalPrompt(
+ joinSystemContext(providerContext, viewedTaskContext),
+ prompt,
+ );
+ const systemContext = buildCloudHeteroContext({
+ agentSystemContext,
+ conversationHistory: resumeSessionId ? undefined : conversationHistory,
+ githubToken,
+ repos: topicRepos,
+ sandbox: sandboxPlacement,
+ });
+ const resumeFallbackSystemContext =
+ resumeSessionId && conversationHistory
+ ? buildCloudHeteroContext({
+ agentSystemContext,
+ conversationHistory,
+ githubToken,
+ repos: topicRepos,
+ sandbox: sandboxPlacement,
+ })
+ : undefined;
+
+ // Feed the resolved images (signed URLs) to the dispatched CLI for vision β€”
+ // mirrors the local-mode path, where the client feeds the persisted
+ // message's imageList into `sendPrompt`. Reuses the shared resolution above
+ // so bot/IM and SPA gateway attachments are handled identically.
+ const heteroImageList =
+ runAttachments.imageList && runAttachments.imageList.length > 0
+ ? runAttachments.imageList.map((image) => ({ id: image.id, url: image.url }))
+ : undefined;
+ const heteroExecArgs = isLocalHeterogeneousType(heteroType)
+ ? buildHeteroExecArgs(
+ heterogeneousProvider?.type === heteroType
+ ? applyTopicModelToHeterogeneousProvider(
+ heterogeneousProvider,
+ pinnedHeterogeneousTopicModel,
+ )
+ : { type: heteroType },
+ )
+ : undefined;
+
+ const heteroParams = {
+ agentType: heteroType,
+ assistantMessageId,
+ githubToken,
+ imageList: heteroImageList,
+ jwt: operationJwt,
+ operationId,
+ // The CLI receives only the request: `/goal` is already in the system
+ // context, and Claude Code's own `/goal` command would otherwise take it.
+ // Non-image attachments have no content block a CLI accepts, so they ride
+ // in the prompt as download links β€” otherwise the agent never sees them.
+ prompt: appendAttachedFilesToPrompt(
+ stripGoalCommand(prompt),
+ collectHeteroAttachedFiles(runAttachments),
+ ),
+ repos: topicRepos,
+ resumeFallbackSystemContext,
+ resumeSessionId,
+ systemContext,
+ topicId,
+ userId: deps.userId,
+ };
+
+ return {
+ agentSystemContext,
+ conversationHistory,
+ heteroExecArgs,
+ heteroParams,
+ resumeSessionId,
+ sandbox,
+ topic,
+ topicRepos,
+ };
+};
+
+export type PreparedHeteroRun = Awaited<ReturnType<typeof prepareHeteroRun>>;
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/remote.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/remote.ts
new file mode 100644
index 00000000000..55d24a12fc7
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/remote.ts
@@ -0,0 +1,176 @@
+import type { ExecAgentResult } from '@lobechat/types';
+import debug from 'debug';
+
+import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
+import { deviceGateway } from '@/server/services/deviceGateway';
+import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
+
+import {
+ humanizeHeteroDispatchError,
+ resolveHeteroDispatchErrorType,
+} from '../../helpers/heteroErrors';
+import type { ExecRunContext } from '../../types';
+import type { HeteroDispatchDeps, HeteroDispatchInput, HeteroRun } from './types';
+import { failHeteroDispatch } from './utils';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Notify-based platform agents (openclaw / hermes) communicate back via
+ * agentNotify.notify. A local run uses the requesting desktop's device ID;
+ * a remote run uses agencyConfig.boundDeviceId. Both use the gateway transport,
+ * so open the stream before the first notify arrives.
+ *
+ * Returns the terminal error result when the run cannot start, `undefined`
+ * once the device accepted it.
+ */
+export const dispatchToPlatformDevice = async (
+ deps: HeteroDispatchDeps,
+ run: HeteroRun,
+ params: {
+ agentConfig: ExecRunContext['agentConfig'];
+ canUseDevice: boolean;
+ deviceAccessReason: ExecRunContext['deviceAccessReason'];
+ heteroType: HeteroDispatchInput['heteroType'];
+ persistOperationMetadata: () => Promise<void>;
+ prompt: string;
+ remoteDeviceId?: string;
+ remoteDeviceUserId: string;
+ remoteDeviceWorkspaceId?: string;
+ topicStartOwnerOperationId?: string;
+ },
+): Promise<ExecAgentResult | undefined> => {
+ const {
+ agentConfig,
+ canUseDevice,
+ deviceAccessReason,
+ heteroType,
+ persistOperationMetadata,
+ prompt,
+ remoteDeviceId,
+ remoteDeviceUserId,
+ remoteDeviceWorkspaceId,
+ topicStartOwnerOperationId,
+ } = params;
+ const { agentId: resolvedAgentId, assistantMessageId, operationId, topicId } = run;
+
+ // Platform task agents require either this desktop or a connected device β€” there is no sandbox to
+ // degrade to, so a denied sender (external bot user) is refused
+ // outright instead of reaching the owner's machine.
+ if (!canUseDevice) {
+ log(
+ 'execAgent: device access denied for remote hetero dispatch (reason=%s)',
+ deviceAccessReason,
+ );
+ return failHeteroDispatch(
+ deps,
+ run,
+ {
+ detail: 'This sender is not allowed to run agents on a bound device.',
+ message: 'Device access denied',
+ },
+ { error: 'Device access denied', message: 'Remote hetero agent requires device access' },
+ );
+ }
+ if (!remoteDeviceId) {
+ log('execAgent: openclaw/hermes requires a local or connected device');
+ return failHeteroDispatch(
+ deps,
+ run,
+ {
+ detail: 'No local or connected device is available for this agent.',
+ message: 'No execution device for platform agent',
+ },
+ {
+ error: 'No bound device',
+ message: 'Platform agent requires a local or connected device',
+ },
+ );
+ }
+
+ // Open the stream channel so the gateway WS subscription can receive
+ // notify_update events published by agentNotify.notify.
+ await persistOperationMetadata();
+ const streamManager = createStreamEventManager();
+ await streamManager
+ .publishAgentRuntimeInit(operationId, {
+ agentId: resolvedAgentId,
+ assistantMessageId,
+ heteroType,
+ mirrorToOperationId: topicStartOwnerOperationId,
+ topicId,
+ userId: deps.userId,
+ })
+ .catch((err) => log('execAgent: failed to init stream for remote hetero: %O', err));
+
+ // lh connect only handles tool_call_request (not agent_run_request),
+ // so we use executeToolCall with the runHeteroTask tool instead of dispatchAgentRun.
+ const authorizationError = await resolveDeviceDispatchAuthorizationFailure(
+ deps.db,
+ deps.userId,
+ remoteDeviceId,
+ remoteDeviceWorkspaceId,
+ );
+ const result = authorizationError
+ ? {
+ content: 'The workspace device is no longer registered or visible for this run.',
+ error: 'DEVICE_NOT_FOUND',
+ errorData: authorizationError,
+ success: false,
+ }
+ : await deviceGateway.executeToolCall(
+ {
+ deviceId: remoteDeviceId,
+ userId: remoteDeviceUserId,
+ workspaceId: remoteDeviceWorkspaceId,
+ },
+ {
+ apiName: 'runHeteroTask',
+ arguments: JSON.stringify({
+ agentId: resolvedAgentId,
+ agentType: heteroType,
+ cwd: undefined,
+ operationId,
+ parentOperationId: topicStartOwnerOperationId,
+ platformAgentId: agentConfig.agencyConfig?.heterogeneousProvider?.platformAgentId,
+ prompt,
+ taskId: operationId,
+ topicId,
+ // Scope notify callbacks to the same workspace as the dispatched
+ // topic so agentNotify can resolve the workspace-owned topic.
+ // Without this the device's notify call falls back to personal
+ // mode and TopicModel.findById returns NOT_FOUND.
+ workspaceId: deps.workspaceId,
+ }),
+ identifier: 'runHeteroTask',
+ },
+ 120_000, // hetero tasks can take longer than the default 30 s
+ );
+ if (!result.success) {
+ log('execAgent: remote hetero dispatch failed: %s', result.error);
+ return failHeteroDispatch(
+ deps,
+ run,
+ {
+ detail: result.error ?? 'Device dispatch failed',
+ deviceRoute: remoteDeviceId
+ ? {
+ deviceId: remoteDeviceId,
+ userId: remoteDeviceUserId,
+ ...(remoteDeviceWorkspaceId ? { workspaceId: remoteDeviceWorkspaceId } : {}),
+ }
+ : undefined,
+ errorData: result.errorData,
+ errorType: resolveHeteroDispatchErrorType(result.error),
+ message: humanizeHeteroDispatchError(result.error),
+ },
+ {
+ error: result.error,
+ errorData: result.errorData,
+ message: 'Remote hetero agent dispatch failed',
+ },
+ );
+ }
+
+ return undefined;
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.ts
new file mode 100644
index 00000000000..5f18c8d6938
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.ts
@@ -0,0 +1,170 @@
+import type { ExecAgentResult } from '@lobechat/types';
+import debug from 'debug';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { signUserJWT } from '@/libs/trpc/utils/internalJwt';
+import { spawnHeteroSandbox } from '@/server/services/heterogeneousAgent/sandboxRunner';
+
+import {
+ getHeterogeneousAgentTitle,
+ supportsCloudHeterogeneousSandbox,
+} from '../../helpers/heteroErrors';
+import { finalizeHeteroDispatchError } from '../finalizeHeteroDispatchError';
+import type { PreparedHeteroRun } from './prepare';
+import type { HeteroDispatchDeps, HeteroDispatchInput, HeteroRun } from './types';
+import { failHeteroDispatch } from './utils';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Liveness probe for the ONE dispatch failure that races a live run: the cloud
+ * sandbox `runCommand` call (see the `spawnHeteroSandbox` catch in `spawnInCloudSandbox`). Every
+ * other `finalizeHeteroDispatchError` caller rejects synchronously, before any
+ * agent process can exist, so none of them needs this.
+ *
+ * `runCommand` is issued with `background: true` and is supposed to return as
+ * soon as the command is handed to the sandbox β€” but the sandbox gateway can
+ * sit on the connection and answer `Gateway Timeout` a minute or more later,
+ * long after the sandbox actually booted and started streaming events back
+ * through `heteroIngest`. Finalizing on that rejection blindly treats a
+ * transient gateway 504 as "the run never started": it blanks the assistant
+ * message, stamps an error bubble on a turn the user already read, marks the
+ * op row + its task failed, and closes the UI stream out from under a run that
+ * is still producing output.
+ *
+ * Two cheap reads tell a stranded dispatch apart from a live one:
+ *
+ * 1. `agent_operations.status` β€” anything other than `running` means the run
+ * reached `heteroFinish` (or a park) on its own. Nothing left to finalize.
+ * 2. `topics.metadata.heteroCurrentMsgId` β€” the ingest path repoints this at
+ * every assistant turn it persists, scoped by `operationId`. It naming THIS
+ * operation is proof the sandbox is alive and writing.
+ *
+ * When neither fires the sandbox really never came up and the caller finalizes
+ * as before. A run that passes this probe and then dies is not stranded: the
+ * agent-gateway inactivity watchdog still reaps it through `finalizeAbandoned`.
+ */
+const hasHeteroRunStarted = async (
+ deps: HeteroDispatchDeps,
+ params: { operationId: string; topicId: string },
+): Promise<boolean> => {
+ const { operationId, topicId } = params;
+
+ try {
+ const operation = await new AgentOperationModel(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).findById(operationId);
+
+ if (operation && operation.status !== 'running') {
+ log(
+ 'hasHeteroRunStarted: op=%s already settled (status=%s) β€” skipping spawn-failure finalize',
+ operationId,
+ operation.status,
+ );
+ return true;
+ }
+
+ const topic = await deps.topicModel.findById(topicId);
+ if (topic?.metadata?.heteroCurrentMsgId?.operationId === operationId) {
+ log(
+ 'hasHeteroRunStarted: op=%s has ingested turns β€” skipping spawn-failure finalize',
+ operationId,
+ );
+ return true;
+ }
+
+ return false;
+ } catch (err) {
+ // A probe that cannot read must not swallow a real spawn failure: fall
+ // back to the pre-existing behaviour and finalize.
+ log(
+ 'hasHeteroRunStarted: probe failed for op=%s (treating as not started): %O',
+ operationId,
+ err,
+ );
+ return false;
+ }
+};
+
+/**
+ * Spawn a local CLI hetero agent in the cloud sandbox. The spawn is
+ * fire-and-forget; its failure is settled in the background unless the run
+ * demonstrably started (see `hasHeteroRunStarted`).
+ *
+ * Returns the terminal error result when the provider cannot run in the cloud
+ * sandbox, `undefined` once the spawn was issued.
+ */
+export const spawnInCloudSandbox = async (
+ deps: HeteroDispatchDeps,
+ run: HeteroRun,
+ params: { heteroType: HeteroDispatchInput['heteroType']; prepared: PreparedHeteroRun },
+): Promise<ExecAgentResult | undefined> => {
+ const { heteroType, prepared } = params;
+ const { heteroExecArgs, heteroParams, sandbox } = prepared;
+ const { agentId: resolvedAgentId, assistantMessageId, operationId, topicId } = run;
+
+ if (!supportsCloudHeterogeneousSandbox(heteroType)) {
+ const message = `${getHeterogeneousAgentTitle(heteroType)} requires a local or connected device; cloud sandbox execution is not supported.`;
+ return failHeteroDispatch(deps, run, { detail: message, message }, { error: message, message });
+ }
+
+ // Cloud sandbox path β€” only for sandbox-provisioned local CLI agents.
+ // Remote agents (openclaw / hermes) always require a bound device.
+ // The entitlement rides on the trust token; without it the execution
+ // plane routes to the ephemeral sandbox whatever the request says.
+ const marketService = await deps.getMarketService(
+ sandbox?.claim ? { sandboxStorage: sandbox.claim } : undefined,
+ );
+ // The sandbox authenticates its nested `lh` calls with this JWT. The
+ // narrow `hetero-operation` token (used for the device-dispatch path
+ // above) is rejected by `oidcAuth`, so CC capabilities that hit
+ // user-scoped endpoints β€” e.g. uploading a `Read`-on-image result to
+ // the file store for thumbnail echo β€” would 401 and silently drop.
+ // Mint a user-scoped `cli-sandbox` token instead (still `sub: userId`,
+ // ownership-gated on heteroIngest/heteroFinish) with a run-length TTL
+ // so it outlives a multi-hour run.
+ const sandboxJwt = await signUserJWT(deps.userId, '4h');
+ spawnHeteroSandbox({
+ ...heteroParams,
+ agentType: heteroType as 'claude-code' | 'codex',
+ args: heteroExecArgs,
+ jwt: sandboxJwt,
+ marketService,
+ sandbox: sandbox && {
+ cwd: sandbox.cwd,
+ environment: sandbox.environment,
+ mode: sandbox.mode,
+ // The environment's variables, network access, maintenance command
+ // and sources all ride here; dropping it starts the run with none
+ // of them, and nothing reports that they were ignored.
+ specification: sandbox.specification,
+ workingDir: sandbox.workingDir,
+ },
+ workspaceId: deps.workspaceId,
+ }).catch(async (err) => {
+ // Fire-and-forget: execAgent has already returned `autoStarted`, and
+ // the sandbox never reached the point of calling heteroFinish. Drive
+ // the same terminal funnel so the stranded run surfaces an error and
+ // its task is marked failed instead of hanging in `running`.
+ log('execAgent: hetero sandbox spawn failed: %O', err);
+
+ // ...unless the run is demonstrably alive or already finished. This
+ // call is the only dispatch failure that can land AFTER the agent
+ // started, so a rejection here is not by itself evidence that nothing
+ // ran β€” see `hasHeteroRunStarted`.
+ if (await hasHeteroRunStarted(deps, { operationId, topicId })) return;
+
+ await finalizeHeteroDispatchError(deps, {
+ agentId: resolvedAgentId,
+ assistantMessageId,
+ detail: err instanceof Error ? err.message : String(err),
+ message: 'Hetero sandbox spawn failed',
+ operationId,
+ topicId,
+ }).catch((finalizeErr) => log('execAgent: sandbox-failure finalize failed: %O', finalizeErr));
+ });
+
+ return undefined;
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.ts
new file mode 100644
index 00000000000..da0af45bd28
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.ts
@@ -0,0 +1,70 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
+import type {
+ HeterogeneousRuntimePinSources,
+ HeterogeneousTopicPin,
+ LobeAgentAgencyConfig,
+ RequestTrigger,
+} from '@lobechat/types';
+
+import type { MessageModel } from '@/database/models/message';
+import type { TopicModel } from '@/database/models/topic';
+import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
+import type { MarketService } from '@/server/services/market';
+import type { SandboxSessionConfig } from '@/server/services/sandbox/session';
+
+import type { BindTopicWorkingDirectoryParams, InternalExecAgentParams } from '../../types';
+import type { RunAttachments } from '../turnSetup';
+
+export interface HeteroDispatchDeps {
+ bindTopicWorkingDirectory: (params: BindTopicWorkingDirectoryParams) => Promise<void>;
+ db: LobeChatDatabase;
+ /**
+ * With a `sandboxStorage` claim, a service whose trust token carries the
+ * entitlement a persistent sandbox run needs β€” built for that run rather
+ * than taken from the cache, because the claim is signed into the token.
+ */
+ getMarketService: (options?: {
+ sandboxStorage: NonNullable<SandboxSessionConfig['claim']>;
+ }) => Promise<MarketService>;
+ messageModel: MessageModel;
+ resolveDeviceWorkspaceId: (deviceId: string | undefined) => Promise<string | undefined>;
+ topicModel: TopicModel;
+ userId: string;
+ withholdGatewayToken: boolean;
+ workspaceId?: string;
+}
+
+export interface HeteroDispatchInput {
+ canManageAgent: boolean;
+ effectiveRequestedDeviceId?: string;
+ heterogeneousProvider?: LobeAgentAgencyConfig['heterogeneousProvider'];
+ heteroType: HeterogeneousAgentType;
+ hooks?: AgentHook[];
+ isPublicWorkspaceAgent: boolean;
+ localDeviceId?: string;
+ maxSteps?: number;
+ memberDeviceOverride?: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'>;
+ onOperationCreated?: InternalExecAgentParams['onOperationCreated'];
+ operationTaskId?: string;
+ parentOperationId?: string;
+ pinnedHeterogeneousTopicModel?: HeterogeneousTopicPin;
+ /** Which layer supplied each pin; see `TurnSetupResult`. */
+ pinnedHeterogeneousTopicSources?: HeterogeneousRuntimePinSources;
+ requestedDeviceId?: string;
+ requestTrigger?: RequestTrigger;
+ runAttachments: Pick<RunAttachments, 'audioList' | 'fileList' | 'imageList' | 'videoList'>;
+ /** Ids of the rows THIS turn just persisted (excluded from recovery history). */
+ selfMessageIds: Set<string>;
+ topicStartOwnerOperationId?: string;
+}
+
+/** The identity every terminal result and dispatch failure of one run carries. */
+export interface HeteroRun {
+ agentId: string;
+ assistantMessageId: string;
+ operationId: string;
+ topicId: string;
+ /** `userMessageId ?? parentMessageId ?? ''`, as every result reports it. */
+ userMessageId: string;
+}
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.ts
new file mode 100644
index 00000000000..da4cd0580c4
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.ts
@@ -0,0 +1,54 @@
+import type { DeviceUnavailableErrorData, ErrorType, ExecAgentResult } from '@lobechat/types';
+
+import type { DeviceDispatchRoute } from '../../helpers/heteroErrors';
+import { finalizeHeteroDispatchError } from '../finalizeHeteroDispatchError';
+import type { HeteroDispatchDeps, HeteroRun } from './types';
+
+/** The terminal error result a dispatch returns instead of starting the run. */
+export const heteroErrorResult = (
+ run: HeteroRun,
+ fields: {
+ error?: string;
+ errorData?: DeviceUnavailableErrorData;
+ message: string;
+ terminalReported: boolean;
+ },
+): ExecAgentResult => ({
+ agentId: run.agentId,
+ assistantMessageId: run.assistantMessageId,
+ autoStarted: false,
+ createdAt: new Date().toISOString(),
+ ...fields,
+ operationId: run.operationId,
+ status: 'error',
+ success: false,
+ timestamp: new Date().toISOString(),
+ topicId: run.topicId,
+ userMessageId: run.userMessageId,
+});
+
+/**
+ * Settle a dispatch that failed before the agent started (see
+ * `finalizeHeteroDispatchError`) and build the error result the caller returns.
+ */
+export const failHeteroDispatch = async (
+ deps: HeteroDispatchDeps,
+ run: HeteroRun,
+ finalize: {
+ detail: string;
+ deviceRoute?: DeviceDispatchRoute;
+ errorData?: DeviceUnavailableErrorData;
+ errorType?: ErrorType;
+ message: string;
+ },
+ result: { error?: string; errorData?: DeviceUnavailableErrorData; message: string },
+): Promise<ExecAgentResult> => {
+ const terminalReported = await finalizeHeteroDispatchError(deps, {
+ agentId: run.agentId,
+ assistantMessageId: run.assistantMessageId,
+ ...finalize,
+ operationId: run.operationId,
+ topicId: run.topicId,
+ });
+ return heteroErrorResult(run, { ...result, terminalReported });
+};