Skip to content

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

✨ feat(hetero): add DeepSeek Harness adapter (#18333)

Arvin Xu050cee839133
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 97f71419290..97fe162e285 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -10,15 +10,20 @@ import type * as HeteroSpawn from '@lobechat/heterogeneous-agents/spawn';
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { HeteroTraceRecorder } from '../utils/HeteroTraceRecorder';
import { registerHeteroCommand, SUPPORTED_AGENT_TYPES } from './hetero';
-const { mockCreatePiRpcAgentHandle, mockResolveHeteroSpawnCommand, mockSpawnAgent } = vi.hoisted(
- () => ({
- mockCreatePiRpcAgentHandle: vi.fn(),
- mockResolveHeteroSpawnCommand: vi.fn(),
- mockSpawnAgent: vi.fn(),
- }),
-);
+const {
+ mockCreatePiRpcAgentHandle,
+ mockResolveHeteroSpawnCommand,
+ mockSpawnAgent,
+ mockSpawnDshAcpSession,
+} = vi.hoisted(() => ({
+ mockCreatePiRpcAgentHandle: vi.fn(),
+ mockResolveHeteroSpawnCommand: vi.fn(),
+ mockSpawnAgent: vi.fn(),
+ mockSpawnDshAcpSession: vi.fn(),
+}));
const { mockGetTrpcClient, mockHeteroFinishMutate, mockHeteroIngestMutate } = vi.hoisted(() => ({
mockGetTrpcClient: vi.fn(),
mockHeteroFinishMutate: vi.fn(),
@@ -30,6 +35,7 @@ const { mockGetTrpcClient, mockHeteroFinishMutate, mockHeteroIngestMutate } = vi
vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => ({
...(await importOriginal<typeof HeteroSpawn>()),
spawnAgent: mockSpawnAgent,
+ spawnDshAcpSession: mockSpawnDshAcpSession,
}));
vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({
@@ -129,6 +135,7 @@ describe('hetero exec command', () => {
);
mockCreatePiRpcAgentHandle.mockReset();
mockSpawnAgent.mockReset();
+ mockSpawnDshAcpSession.mockReset();
mockHeteroIngestMutate.mockReset();
mockHeteroFinishMutate.mockReset();
mockGetTrpcClient.mockReset();
@@ -279,9 +286,9 @@ describe('hetero exec command', () => {
},
);
- it('supports exactly the local agent descriptor types', () => {
+ it('supports every local descriptor type plus the bundled DeepSeek Harness runtime', () => {
expect([...SUPPORTED_AGENT_TYPES].toSorted()).toEqual(
- HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type).toSorted(),
+ [...HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type), 'deepseek-harness'].toSorted(),
);
});
@@ -493,6 +500,179 @@ describe('hetero exec command', () => {
);
});
+ it('runs DeepSeek Harness through its dsh CLI acp-profile session', async () => {
+ const dispose = vi.fn().mockResolvedValue(undefined);
+ const prompt = vi.fn(async function* () {
+ yield {
+ data: { model: 'deepseek-chat', provider: 'deepseek-harness' },
+ operationId: 'op-dsh',
+ type: 'stream_start',
+ };
+ yield {
+ data: { finishReason: 'stop' },
+ operationId: 'op-dsh',
+ type: 'agent_runtime_end',
+ };
+ });
+ mockSpawnDshAcpSession.mockReturnValue({ dispose, prompt, sessionId: 'dsh-session-1' });
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'deepseek-harness',
+ '--prompt',
+ 'say hi',
+ '--cwd',
+ '/tmp/work',
+ '--model',
+ 'deepseek-chat',
+ ]);
+
+ expect(mockSpawnDshAcpSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cwd: '/tmp/work',
+ model: 'deepseek-chat',
+ resumeSessionId: undefined,
+ }),
+ );
+ expect(prompt).toHaveBeenCalledWith('say hi');
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(mockSpawnAgent).not.toHaveBeenCalled();
+ expect(exitSpy).toHaveBeenCalledWith(0);
+ });
+
+ it('resumes the harness session named by --resume and reports it on finish', async () => {
+ vi.spyOn(HeteroTraceRecorder.prototype, 'finalize').mockResolvedValue(undefined);
+ mockSpawnDshAcpSession.mockReturnValue({
+ dispose: vi.fn().mockResolvedValue(undefined),
+ prompt: vi.fn(async function* () {
+ yield { data: {}, operationId: 'op-1', type: 'agent_runtime_end' };
+ }),
+ sessionId: 'dsh-prev',
+ });
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'deepseek-harness',
+ '--prompt',
+ 'next',
+ '--resume',
+ 'dsh-prev',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-1',
+ ]);
+
+ expect(mockSpawnDshAcpSession).toHaveBeenCalledWith(
+ expect.objectContaining({ resumeSessionId: 'dsh-prev' }),
+ );
+ expect(mockHeteroFinishMutate).toHaveBeenCalledWith(
+ expect.objectContaining({ result: 'success', sessionId: 'dsh-prev' }),
+ );
+ });
+
+ it('passes the conversation identity into a server-ingest DeepSeek Harness run', async () => {
+ vi.spyOn(HeteroTraceRecorder.prototype, 'finalize').mockResolvedValue(undefined);
+ mockSpawnDshAcpSession.mockReturnValue({
+ dispose: vi.fn().mockResolvedValue(undefined),
+ prompt: vi.fn(async function* () {
+ yield { data: {}, operationId: 'op-1', type: 'agent_runtime_end' };
+ }),
+ });
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'deepseek-harness',
+ '--prompt',
+ 'hi',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-1',
+ ]);
+
+ expect(mockSpawnDshAcpSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ env: { LOBEHUB_OPERATION_ID: 'op-1', LOBEHUB_TOPIC_ID: 'topic-1' },
+ }),
+ );
+ });
+
+ it('records and finalizes the local trace for a DeepSeek Harness run', async () => {
+ const observe = vi.spyOn(HeteroTraceRecorder.prototype, 'observe').mockImplementation(() => {});
+ const finalize = vi
+ .spyOn(HeteroTraceRecorder.prototype, 'finalize')
+ .mockResolvedValue(undefined);
+ mockSpawnDshAcpSession.mockReturnValue({
+ dispose: vi.fn().mockResolvedValue(undefined),
+ prompt: vi.fn(async function* () {
+ yield { data: {}, operationId: 'op-dsh', type: 'stream_start' };
+ yield { data: {}, operationId: 'op-dsh', type: 'agent_runtime_end' };
+ }),
+ });
+
+ await runCmd(['hetero', 'exec', '--type', 'deepseek-harness', '--prompt', 'say hi']);
+
+ expect(observe.mock.calls.map(([event]) => event.type)).toEqual([
+ 'stream_start',
+ 'agent_runtime_end',
+ ]);
+ expect(finalize).toHaveBeenCalledWith({ error: undefined, result: 'success' });
+ expect(exitSpy).toHaveBeenCalledWith(0);
+ });
+
+ it('stops a DeepSeek Harness run as soon as the server discards its output', async () => {
+ vi.spyOn(HeteroTraceRecorder.prototype, 'finalize').mockResolvedValue(undefined);
+ mockHeteroIngestMutate.mockResolvedValue({ accepted: false, reason: 'stale-operation' });
+
+ let markKilled!: () => void;
+ const killed = new Promise<void>((resolve) => {
+ markKilled = resolve;
+ });
+ const dispose = vi.fn(async () => markKilled());
+ mockSpawnDshAcpSession.mockReturnValue({
+ dispose,
+ // A long-running harness: one event, then nothing until it is disposed.
+ prompt: vi.fn(async function* () {
+ yield {
+ data: { chunkType: 'text', content: 'working' },
+ operationId: 'op-1',
+ type: 'stream_chunk',
+ };
+ await killed;
+ throw new Error('harness runtime exited (code null, signal SIGTERM)');
+ }),
+ });
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'deepseek-harness',
+ '--prompt',
+ 'hi',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-1',
+ ]);
+
+ expect(dispose).toHaveBeenCalled();
+ expect(mockHeteroFinishMutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: expect.objectContaining({ message: expect.stringContaining('stale-operation') }),
+ result: 'error',
+ }),
+ );
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ }, 10_000);
+
it('runs Kimi Code with its default command and forwards model but not effort', async () => {
mockSpawnAgent.mockReturnValue(createFakeHandle());
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 189faa99239..fc45ac092d0 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -32,6 +32,7 @@ import {
createFileStoreImageUploader,
isHeteroStatusGuideErrorData,
spawnAgent,
+ spawnDshAcpSession,
} from '@lobechat/heterogeneous-agents/spawn';
import { isRecord } from '@lobechat/utils/object';
import type { Command } from 'commander';
@@ -45,7 +46,11 @@ import { createOperationTokenRenewal } from '../utils/OperationTokenRenewal';
import { createLocalTraceStore } from '../utils/traceStore';
import { TrpcIngestSink } from '../utils/TrpcIngestSink';
-export const SUPPORTED_AGENT_TYPES = new Set<string>(LOCAL_HETEROGENEOUS_AGENT_TYPES);
+const DSH_AGENT_TYPE = 'deepseek-harness';
+export const SUPPORTED_AGENT_TYPES = new Set<string>([
+ ...LOCAL_HETEROGENEOUS_AGENT_TYPES,
+ DSH_AGENT_TYPE,
+]);
/**
* Extra env for the spawned agent process.
@@ -73,7 +78,10 @@ export const buildAgentProcessEnv = ({
};
return Object.keys(env).length > 0 ? env : undefined;
};
-const SUPPORTED_AGENT_TITLES = HETEROGENEOUS_AGENT_CONFIGS.map(({ title }) => title).join(' / ');
+const SUPPORTED_AGENT_TITLES = [
+ ...HETEROGENEOUS_AGENT_CONFIGS.map(({ title }) => title),
+ 'DeepSeek Harness',
+].join(' / ');
const SUPPORTED_AGENT_COMMANDS = HETEROGENEOUS_AGENT_CONFIGS.map(
({ defaultCommand }) => `\`${defaultCommand}\``,
).join(', ');
@@ -465,7 +473,7 @@ class RawStreamDump {
}
const exec = async (options: ExecOptions): Promise<void> => {
- if (!isLocalHeterogeneousType(options.type)) {
+ if (!SUPPORTED_AGENT_TYPES.has(options.type)) {
log.error(
`Unsupported --type "${options.type}". Supported: ${[...SUPPORTED_AGENT_TYPES].join(', ')}`,
);
@@ -592,6 +600,126 @@ const exec = async (options: ExecOptions): Promise<void> => {
})
: undefined;
+ // DSH is a protocol runtime (its `acp` profile) with no CLI descriptor. Keep
+ // it on the same public `hetero exec` surface, but drive its ACP session
+ // directly instead of passing it through `spawnAgent`.
+ if (agentType === DSH_AGENT_TYPE) {
+ const hasImages =
+ typeof resolved.prompt !== 'string' &&
+ resolved.prompt.some((block) => block.type === 'image');
+ if (hasImages) {
+ log.error('DeepSeek Harness currently accepts text prompts only.');
+ process.exit(2);
+ }
+
+ const prompt =
+ typeof resolved.prompt === 'string'
+ ? resolved.prompt
+ : resolved.prompt
+ .map((block) => (block.type === 'text' ? block.text : ''))
+ .filter(Boolean)
+ .join('\n');
+ let session: ReturnType<typeof spawnDshAcpSession> | undefined;
+ let exitCode = 0;
+ // Same contract as `runOneAgent`: once the server discards this run's
+ // output, stop the harness instead of letting it keep calling the model
+ // and running tools until natural idle.
+ let ingestLoss: Error | undefined;
+ abortForIngestLoss = (error) => {
+ if (ingestLoss) return;
+ ingestLoss = error;
+ log.error('Server is discarding this run output, stopping the agent:', error.message);
+ void session?.dispose().catch(() => {});
+ };
+
+ try {
+ session = spawnDshAcpSession({
+ args: options.agentArg,
+ clientVersion: 'lobehub-cli',
+ command: options.command,
+ cwd: options.cwd || process.cwd(),
+ // Same identity echo as the CLI agents, so `lh` commands the harness
+ // runs for this conversation can name its operation and topic.
+ env: buildAgentProcessEnv({
+ operationId: serverIngest ? operationId : undefined,
+ topicId: options.topic,
+ }),
+ model: options.model,
+ operationId,
+ // `--resume` continues the persisted harness session.
+ resumeSessionId: options.resume,
+ });
+ // The loss may have landed (via the heartbeat) before the turn started.
+ if (ingestLoss) throw ingestLoss;
+
+ let terminalError: string | undefined;
+ for await (const event of session.prompt(prompt)) {
+ if (event.type === 'error') {
+ const data = event.data as Record<string, unknown> | undefined;
+ terminalError = String(data?.message ?? data?.error ?? '') || 'DSH execution failed';
+ }
+ if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
+ operationHeartbeat?.observe(event);
+ traceRecorder.observe(event);
+ serverIngester?.push(event);
+ if (ingestLoss) break;
+ }
+ if (ingestLoss) throw ingestLoss;
+
+ operationHeartbeat?.stop();
+ await serverIngester?.drain();
+ const finishError = terminalError
+ ? { message: terminalError, type: 'AgentRuntimeError' }
+ : undefined;
+ // Before the sink, so a failing server call still leaves a snapshot.
+ await traceRecorder.finalize({
+ error: finishError,
+ result: terminalError ? 'error' : 'success',
+ });
+ if (sink) {
+ await sink.finish({
+ error: finishError,
+ result: terminalError ? 'error' : 'success',
+ sessionId: session.sessionId,
+ });
+ }
+ if (terminalError) exitCode = 1;
+ } catch (caught) {
+ exitCode = 1;
+ // A killed runtime reports its own exit; the ingest loss is the real cause.
+ const error = ingestLoss ?? caught;
+ const message = error instanceof Error ? error.message : String(error);
+ log.error('DeepSeek Harness execution failed:', message);
+ operationHeartbeat?.stop();
+ await traceRecorder.finalize({
+ error: { message, type: 'AgentRuntimeError' },
+ result: 'error',
+ });
+ if (sink) {
+ await serverIngester?.drain().catch(() => {});
+ await sink
+ .finish({
+ error: { message, type: 'AgentRuntimeError' },
+ result: 'error',
+ sessionId: session?.sessionId ?? options.resume,
+ })
+ .catch(() => {});
+ }
+ } finally {
+ abortForIngestLoss = undefined;
+ operationTokenRenewal?.stop();
+ await session?.dispose().catch(() => {});
+ }
+
+ process.exit(exitCode);
+ }
+
+ // The public set also contains runtime-backed providers such as DSH. Past
+ // this branch the existing spawn pipeline requires a descriptor-backed CLI.
+ if (!isLocalHeterogeneousType(agentType)) {
+ throw new TypeError(`Unsupported CLI-backed heterogeneous agent type: ${agentType}`);
+ }
+
// ─── AskUserQuestion MCP — remote Human-in-the-loop ────────────────────────
//
// Mount the same `lobe_cc` MCP server the desktop app uses, but resolve the
@@ -1310,7 +1438,7 @@ export function registerHeteroCommand(program: Command) {
)
.option(
'-c, --command <bin>',
- `Override the agent CLI binary name (defaults: ${SUPPORTED_AGENT_COMMANDS})`,
+ `Override the agent runtime binary (CLI defaults: ${SUPPORTED_AGENT_COMMANDS}; DeepSeek Harness defaults to 'dsh --profile acp')`,
)
.option(
'--operation-id <id>',
diff --git a/apps/cli/src/utils/TrpcIngestSink.ts b/apps/cli/src/utils/TrpcIngestSink.ts
index d3fb1c70f30..61786f08642 100644
--- a/apps/cli/src/utils/TrpcIngestSink.ts
+++ b/apps/cli/src/utils/TrpcIngestSink.ts
@@ -1,4 +1,7 @@
-import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
+import type {
+ LocalHeterogeneousAgentType,
+ LocalRuntimeHeterogeneousAgentType,
+} from '@lobechat/heterogeneous-agents';
import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
import type { TrpcClient } from '../api/client';
@@ -14,7 +17,7 @@ import type { IngestAck, IngestSink } from './BatchIngester';
export class TrpcIngestSink implements IngestSink {
constructor(
private readonly client: TrpcClient,
- private readonly agentType: LocalHeterogeneousAgentType,
+ private readonly agentType: LocalHeterogeneousAgentType | LocalRuntimeHeterogeneousAgentType,
private readonly operationId: string,
private readonly topicId: string,
private readonly assistantMessageId?: string,
diff --git a/apps/desktop/src/main/controllers/BinaryCtr.ts b/apps/desktop/src/main/controllers/BinaryCtr.ts
index dbaf0f12434..f1f8f429cea 100644
--- a/apps/desktop/src/main/controllers/BinaryCtr.ts
+++ b/apps/desktop/src/main/controllers/BinaryCtr.ts
@@ -7,9 +7,11 @@ import type {
} from '@lobechat/electron-client-ipc';
import {
getHeterogeneousAgentConfigOrThrow,
+ isLocalRuntimeHeterogeneousType,
isRemoteHeterogeneousType,
} from '@lobechat/heterogeneous-agents';
import { resolveRemotePlatformCommand } from '@lobechat/heterogeneous-agents/scanHost';
+import { detectDshCommand, DSH_COMMAND } from '@lobechat/heterogeneous-agents/spawn';
import type { BinaryCategory, BinaryStatus } from '@/core/infrastructure/BinaryManager';
import { detectHeterogeneousCliCommand, invalidateLoginShellPathCache } from '@/modules/binaries';
@@ -48,6 +50,13 @@ export default class BinaryCtr extends ControllerModule {
params: DetectHeterogeneousAgentCommandParams,
): Promise<BinaryStatus> {
logger.debug('Detecting heterogeneous agent command:', params);
+ if (isLocalRuntimeHeterogeneousType(params.agentType)) {
+ // DeepSeek Harness is the user-installed `dsh` CLI. Probe it the way the
+ // launch path does, so the wizard never offers an agent that cannot run;
+ // drop the cached login-shell PATH so a Rescan sees a fresh install.
+ invalidateLoginShellPathCache();
+ return detectDshCommand(params.command?.trim() || DSH_COMMAND);
+ }
if (isRemoteHeterogeneousType(params.agentType)) {
return resolveRemotePlatformCommand(params.agentType);
}
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 9b738b3a100..87eb2d307e6 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -13,17 +13,21 @@ import type {
CodexQuotaSnapshot,
CodexRateLimitResetResult,
HeterogeneousAgentSessionError,
- HeterogeneousCliAgentType,
KimiCodeQuotaSnapshot,
} from '@lobechat/electron-client-ipc';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc/types/heterogeneous-agent';
-import type { HeterogeneousProviderBindingReference } from '@lobechat/heterogeneous-agents';
+import type {
+ HeterogeneousAgentType,
+ HeterogeneousProviderBindingReference,
+} from '@lobechat/heterogeneous-agents';
import {
buildHeterogeneousAgentAuthRequiredError,
buildHeterogeneousAgentCliNotFoundError,
formatHeterogeneousProviderBindingError,
getHeterogeneousAgentConfigOrThrow,
isHeterogeneousAgentAuthRequired,
+ isLocalHeterogeneousType,
+ isLocalRuntimeHeterogeneousType,
isServerDefaultHeterogeneousAgentType,
resolveHeterogeneousAgentCommand,
resolveHeterogeneousProviderBinding,
@@ -59,7 +63,11 @@ import {
PiRpcSession,
type PiRpcSessionCallbacks,
} from '@lobechat/heterogeneous-agents/rpc';
-import type { AgentStreamEvent, UsageData } from '@lobechat/heterogeneous-agents/spawn';
+import type {
+ AgentStreamEvent,
+ DshAcpSessionHandle,
+ UsageData,
+} from '@lobechat/heterogeneous-agents/spawn';
import {
AcpRpcResponseError,
AgentStreamPipeline,
@@ -82,8 +90,10 @@ import {
CodexThreadSession,
createFileStoreImageUploader,
CursorAcpSession,
+ detectDshCommand,
DevinAcpSession,
DroidAcpSession,
+ DSH_COMMAND,
ensureClaudeCodeResumeTranscript,
getCodexAppServerUnsupportedArgs,
GrokAcpSession,
@@ -97,6 +107,7 @@ import {
resolveClaudeCodeTranscriptPath,
resolveCliSpawnPlan,
resolveCodexInitialModel,
+ spawnDshAcpSession,
TraeAcpSession,
} from '@lobechat/heterogeneous-agents/spawn';
import {
@@ -256,10 +267,7 @@ const PI_RPC_POOL_DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
const waitForHeteroSessionCompleteGrace = () =>
new Promise<void>((resolve) => setTimeout(resolve, HETERO_SESSION_COMPLETE_GRACE_MS));
-export const redactPromptArgs = (
- args: string[],
- agentType: HeterogeneousCliAgentType,
-): string[] => {
+export const redactPromptArgs = (args: string[], agentType: HeterogeneousAgentType): string[] => {
let redactNext = false;
const supportsShortPromptFlag = agentType === 'kimi-code';
@@ -285,7 +293,7 @@ export const redactPromptArgs = (
interface StartSessionParams {
/** Agent type key (e.g., 'claude-code'). Defaults to 'claude-code'. */
- agentType?: HeterogeneousCliAgentType;
+ agentType?: HeterogeneousAgentType;
/** Additional CLI arguments */
args?: string[];
/** Command to execute */
@@ -467,7 +475,7 @@ export interface SessionInfo {
interface AgentSession {
agentSessionId?: string;
- agentType: HeterogeneousCliAgentType;
+ agentType: HeterogeneousAgentType;
appServerSession?: CodexThreadSession;
args: string[];
/**
@@ -484,6 +492,7 @@ interface AgentSession {
cwd?: string;
devinAcpSession?: DevinAcpSession;
droidAcpSession?: DroidAcpSession;
+ dshSession?: DshAcpSessionHandle;
env?: Record<string, string>;
grokAcpSession?: GrokAcpSession;
hostedProviderBinding?: HostedProviderBinding;
@@ -675,7 +684,7 @@ export default class HeterogeneousAgentCtr {
* future agent adopting an RPC mode only adds one entry — no dispatch edit.
*/
private readonly runtimeDispatchers: Partial<
- Record<HeterogeneousCliAgentType, HeterogeneousRuntimeDispatcher>
+ Record<HeterogeneousAgentType, HeterogeneousRuntimeDispatcher>
> = {
'claude-code': async (params, session) => {
if (!(session.useClaudeCodeSdk || this.isClaudeCodeSdkLabEnabled)) return false;
@@ -727,6 +736,10 @@ export default class HeterogeneousAgentCtr {
await this.sendPromptWithDroidAcp(params, session);
return true;
},
+ 'deepseek-harness': async (params, session) => {
+ await this.sendPromptWithDsh(params, session);
+ return true;
+ },
'grok-build': async (params, session) => {
await this.sendPromptWithGrokAcp(params, session);
return true;
@@ -797,6 +810,7 @@ export default class HeterogeneousAgentCtr {
);
private resolveSessionCommand(session: AgentSession): string {
+ if (isLocalRuntimeHeterogeneousType(session.agentType)) return 'DeepSeek Harness';
return resolveHeterogeneousAgentCommand(session.agentType, session.command);
}
@@ -1099,6 +1113,8 @@ export default class HeterogeneousAgentCtr {
return this.buildWorkingDirectoryMissingError(session, workingDirectory);
}
+ if (!isLocalHeterogeneousType(session.agentType)) return;
+
const defaultCommand = getHeterogeneousAgentConfigOrThrow(session.agentType).defaultCommand;
const command = this.resolveSessionCommand(session);
@@ -1666,10 +1682,14 @@ export default class HeterogeneousAgentCtr {
async startSession(params: StartSessionParams): Promise<StartSessionResult> {
const sessionId = randomUUID();
const agentType = params.agentType || 'claude-code';
- const driver = getHeterogeneousAgentDriver(agentType);
+ // Protocol-driven runtimes (DeepSeek Harness) have no CLI driver and no
+ // provider-binding support; they authenticate through their own env.
+ const driver = isLocalRuntimeHeterogeneousType(agentType)
+ ? undefined
+ : getHeterogeneousAgentDriver(agentType);
let hostedProviderBinding: HostedProviderBinding | undefined;
- if (params.providerBinding && params.providerBinding.kind !== 'server-default') {
+ if (driver && params.providerBinding && params.providerBinding.kind !== 'server-default') {
const bindingRuntime = await getProviderBindingRuntime(
this.remoteServerAuth,
params.providerBinding,
@@ -1708,7 +1728,7 @@ export default class HeterogeneousAgentCtr {
logger.info('Removed stale provider-binding profiles:', removedProfiles);
})
.catch((error) => logger.warn('Provider-binding profile GC failed:', error));
- } else if (params.providerBinding?.kind === 'server-default') {
+ } else if (driver && params.providerBinding?.kind === 'server-default') {
const model = params.providerBinding.apiConfig.model;
// Codex and Pi describe the model to the CLI from its card. Best-effort:
// a model described without its card still runs (on default window and
@@ -1887,8 +1907,7 @@ export default class HeterogeneousAgentCtr {
// SDK) select themselves via the runtime registry. A dispatcher that
// returns `true` handled the prompt; `false` falls through to the generic
// CLI spawn below.
- const runtimeDispatcher =
- this.runtimeDispatchers[session.agentType as HeterogeneousCliAgentType];
+ const runtimeDispatcher = this.runtimeDispatchers[session.agentType];
if (runtimeDispatcher && (await runtimeDispatcher(params, session))) return;
// Stand up the AskUserQuestion MCP bridge for supported prompts BEFORE
@@ -2081,6 +2100,95 @@ export default class HeterogeneousAgentCtr {
this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
}
+ private async sendPromptWithDsh(params: SendPromptParams, session: AgentSession): Promise<void> {
+ if (params.imageList?.length) {
+ throw new Error('DeepSeek Harness currently supports text prompts only.');
+ }
+
+ const cwd = this.resolveSessionWorkingDirectory(session);
+ const env = this.buildSessionSpawnEnv(session) as Record<string, string>;
+ // DSH is the user-installed DeepSeek Harness CLI, served through its `acp`
+ // profile. A GUI-launched app inherits a lean PATH, so resolve it the way
+ // the other CLI agents are resolved (login-shell PATH fallback) and spawn
+ // with the PATH it was found under.
+ const dsh = await detectDshCommand(session.command?.trim() || DSH_COMMAND, env);
+ if (!dsh.available || !dsh.path) {
+ // A CLI that was found but rejected (too old) carries its own reason.
+ throw new Error(
+ dsh.path && dsh.error
+ ? dsh.error
+ : `DeepSeek Harness CLI (dsh) not found${dsh.error ? `: ${dsh.error}` : ''}. Install it with: npm i -g @deepseek-ai/dsh`,
+ );
+ }
+ if (dsh.resolvedPathEnv) env.PATH = dsh.resolvedPathEnv;
+ // Same semantic prompt as every other transport: session-scoped context
+ // (the `lh` guide) only opens a new session, never a resumed one.
+ const prompt = buildHeterogeneousPrompt({
+ isNewSession: this.needsSessionIntroduction(session),
+ prompt: params.prompt,
+ systemContext: params.systemContext,
+ })
+ .flatMap((block) => (block.type === 'text' ? [block.text] : []))
+ .join('\n\n');
+
+ try {
+ const dshSession = spawnDshAcpSession({
+ clientVersion: electronApp.getVersion(),
+ command: dsh.path,
+ cwd,
+ env,
+ model: session.model,
+ onSessionId: (agentSessionId) => {
+ session.agentSessionId = agentSessionId;
+ },
+ operationId: params.operationId,
+ // A resumed topic continues its persisted harness session.
+ resumeSessionId: session.agentSessionId,
+ });
+ session.dshSession = dshSession;
+
+ // Stop pressed before launch: nothing has spawned yet. The `finally`
+ // below still disposes the handle.
+ if (session.cancelledByUs) {
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ return;
+ }
+
+ for await (const event of dshSession.prompt(prompt)) {
+ this.broadcast('heteroAgentEvent', { event, sessionId: session.sessionId });
+ }
+
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ } catch (error) {
+ if (session.cancelledByUs) {
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ return;
+ }
+
+ const message = this.getErrorMessage(error) || 'DeepSeek Harness execution failed';
+ const sessionError: HeterogeneousAgentSessionError = {
+ agentType: 'deepseek-harness',
+ code: /DEEPSEEK_API_KEY|api key|401|unauthorized/i.test(message)
+ ? HeterogeneousAgentSessionErrorCode.AuthRequired
+ : undefined,
+ docsUrl: 'https://platform.deepseek.com/api_keys',
+ message: /DEEPSEEK_API_KEY|api key|401|unauthorized/i.test(message)
+ ? 'DeepSeek Harness could not authenticate. Configure the DeepSeek API key in Provider Settings, then retry.'
+ : message,
+ stderr: message,
+ };
+ this.broadcast('heteroAgentSessionError', {
+ error: sessionError,
+ sessionId: session.sessionId,
+ });
+ throw new Error(sessionError.message, { cause: error });
+ } finally {
+ const dshSession = session.dshSession;
+ session.dshSession = undefined;
+ await dshSession?.dispose().catch(() => {});
+ }
+ }
+
private async sendPromptWithClaudeSdk(
params: SendPromptParams,
session: AgentSession,
@@ -3974,6 +4082,10 @@ export default class HeterogeneousAgentCtr {
if (!session) return;
session.cancelledByUs = true;
+ if (session.dshSession) {
+ await session.dshSession.dispose();
+ return;
+ }
if (session.devinAcpSession) {
session.devinAcpSession.interrupt();
return;
@@ -4048,6 +4160,11 @@ export default class HeterogeneousAgentCtr {
const session = this.sessions.get(params.sessionId);
if (!session) return;
+ if (session.dshSession) {
+ session.cancelledByUs = true;
+ await session.dshSession.dispose();
+ session.dshSession = undefined;
+ }
if (session.devinAcpSession) {
session.cancelledByUs = true;
session.devinAcpSession.close();
@@ -4203,6 +4320,14 @@ export default class HeterogeneousAgentCtr {
session.cancelledByUs = true;
session.sdkSession.close();
}
+ // A plain-spawned DSH runtime is not reaped with its parent, and stdin
+ // EOF alone starts an unbounded disposal — wait for its bounded
+ // shutdown → SIGTERM → SIGKILL so its tools stop writing to the workspace.
+ if (session.dshSession) {
+ session.cancelledByUs = true;
+ piClosing.push(session.dshSession.dispose());
+ session.dshSession = undefined;
+ }
if (session.process && !session.process.killed) {
session.cancelledByUs = true;
this.killProcessTree(session.process, 'SIGTERM');
diff --git a/apps/desktop/src/main/controllers/__tests__/BinaryCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/BinaryCtr.test.ts
index c77c36e98d4..bb92c808616 100644
--- a/apps/desktop/src/main/controllers/__tests__/BinaryCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/BinaryCtr.test.ts
@@ -1,4 +1,4 @@
-import { mkdtemp, rm } from 'node:fs/promises';
+import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
@@ -57,4 +57,35 @@ describe('BinaryCtr', () => {
await expect(manager.detect('codex')).resolves.toMatchObject(detectedStatus);
expect(detectSpec).toHaveBeenCalledTimes(2);
});
+
+ it('probes the user-installed dsh CLI instead of assuming DeepSeek Harness is present', async () => {
+ const controller = new BinaryCtr({} as App);
+ const dsh = path.join(cacheRoot, 'dsh');
+ await writeFile(dsh, '#!/bin/sh\necho 0.2.0-rc.2\n');
+ await chmod(dsh, 0o755);
+
+ await expect(
+ controller.detectHeterogeneousAgentCommand({ agentType: 'deepseek-harness', command: dsh }),
+ ).resolves.toMatchObject({ available: true, version: '0.2.0-rc.2' });
+ await expect(
+ controller.detectHeterogeneousAgentCommand({
+ agentType: 'deepseek-harness',
+ command: path.join(cacheRoot, 'missing-dsh'),
+ }),
+ ).resolves.toMatchObject({ available: false });
+ });
+
+ it('reports an installed dsh without the acp profile as needing an update', async () => {
+ const controller = new BinaryCtr({} as App);
+ const dsh = path.join(cacheRoot, 'dsh');
+ await writeFile(dsh, '#!/bin/sh\necho 0.0.1\n');
+ await chmod(dsh, 0o755);
+
+ await expect(
+ controller.detectHeterogeneousAgentCommand({ agentType: 'deepseek-harness', command: dsh }),
+ ).resolves.toMatchObject({
+ available: false,
+ error: expect.stringMatching(/0\.0\.1 is too old.*npm i -g @deepseek-ai\/dsh/),
+ });
+ });
});
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 525408fa11d..0a60a159842 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -196,6 +196,10 @@ const {
devinAcpSessionConstructMock,
devinAcpSessionInterruptMock,
devinAcpSessionRunMock,
+ dshDetectMock,
+ dshDisposeMock,
+ dshPromptMock,
+ dshSpawnMock,
grokAcpSessionCloseMock,
grokAcpSessionConstructMock,
grokAcpSessionInterruptMock,
@@ -236,6 +240,10 @@ const {
devinAcpSessionConstructMock: vi.fn(),
devinAcpSessionInterruptMock: vi.fn(),
devinAcpSessionRunMock: vi.fn(),
+ dshDetectMock: vi.fn(),
+ dshDisposeMock: vi.fn(),
+ dshPromptMock: vi.fn(),
+ dshSpawnMock: vi.fn(),
grokAcpSessionCloseMock: vi.fn(),
grokAcpSessionConstructMock: vi.fn(),
grokAcpSessionInterruptMock: vi.fn(),
@@ -609,6 +617,8 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
CursorAcpSession: MockCursorAcpSession,
DroidAcpSession: MockDroidAcpSession,
DevinAcpSession: MockDevinAcpSession,
+ detectDshCommand: dshDetectMock,
+ spawnDshAcpSession: dshSpawnMock,
isCodexAppServerCompatibilityError: (error: Error) =>
error.name === 'CodexAppServerConnectionError',
GrokAcpSession: MockGrokAcpSession,
@@ -785,6 +795,23 @@ describe('HeterogeneousAgentCtr', () => {
devinAcpSessionConstructMock.mockReset();
devinAcpSessionInterruptMock.mockReset();
devinAcpSessionRunMock.mockReset();
+ dshDetectMock.mockReset();
+ dshDetectMock.mockResolvedValue({
+ available: true,
+ path: '/usr/local/bin/dsh',
+ resolvedPathEnv: '/usr/local/bin:/usr/bin',
+ version: '0.2.0-rc.2',
+ });
+ dshDisposeMock.mockReset();
+ dshDisposeMock.mockResolvedValue(undefined);
+ dshPromptMock.mockReset();
+ dshSpawnMock.mockReset();
+ dshSpawnMock.mockReturnValue({ dispose: dshDisposeMock, prompt: dshPromptMock });
+ dshPromptMock.mockImplementation(async function* () {
+ // The session's pipeline already stamps the operation onto each event.
+ yield { data: { text: 'DSH UI OK' }, operationId: 'op-dsh', type: 'content_delta' };
+ yield { data: { reason: 'complete' }, operationId: 'op-dsh', type: 'agent_runtime_end' };
+ });
grokAcpSessionCloseMock.mockReset();
grokAcpSessionConstructMock.mockReset();
grokAcpSessionInterruptMock.mockReset();
@@ -1338,6 +1365,205 @@ describe('HeterogeneousAgentCtr', () => {
});
});
+ describe('sendPrompt (deepseek-harness)', () => {
+ it('drives the installed dsh CLI acp profile and broadcasts unified stream events', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([{ isDestroyed: () => false, webContents: { send } }]);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'deepseek-harness',
+ command: '',
+ cwd: '/workspace',
+ env: { DEEPSEEK_API_KEY: 'test-key' },
+ initialModel: 'deepseek-chat',
+ });
+
+ await ctr.sendPrompt({
+ operationId: 'op-dsh',
+ prompt: 'hello',
+ sessionId,
+ systemContext: 'follow project rules',
+ });
+
+ // An empty renderer command falls back to the `dsh` binary, resolved
+ // through the login-shell PATH a GUI launch otherwise lacks.
+ expect(dshDetectMock).toHaveBeenCalledWith(
+ 'dsh',
+ expect.objectContaining({ DEEPSEEK_API_KEY: 'test-key' }),
+ );
+ expect(dshSpawnMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ command: '/usr/local/bin/dsh',
+ cwd: '/workspace',
+ env: expect.objectContaining({
+ DEEPSEEK_API_KEY: 'test-key',
+ PATH: '/usr/local/bin:/usr/bin',
+ }),
+ model: 'deepseek-chat',
+ operationId: 'op-dsh',
+ resumeSessionId: undefined,
+ }),
+ );
+ expect(dshPromptMock).toHaveBeenCalledWith(
+ `follow project rules\n\n${lobeHubCliGuide}\n\nhello`,
+ );
+ expect(send).toHaveBeenCalledWith(
+ 'heteroAgentEvent',
+ expect.objectContaining({
+ event: expect.objectContaining({ operationId: 'op-dsh', type: 'content_delta' }),
+ sessionId,
+ }),
+ );
+ expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });
+ expect(dshDisposeMock).toHaveBeenCalledOnce();
+ });
+
+ it('does not re-send the session introduction when resuming a dsh session', async () => {
+ mockGetAllWindows.mockReturnValue([]);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'deepseek-harness',
+ command: '',
+ cwd: '/workspace',
+ resumeSessionId: 'dsh-prev',
+ });
+
+ await ctr.sendPrompt({
+ operationId: 'op-dsh',
+ prompt: 'next turn',
+ sessionId,
+ systemContext: 'follow project rules',
+ });
+
+ expect(dshSpawnMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resumeSessionId: 'dsh-prev' }),
+ );
+ expect(dshPromptMock).toHaveBeenCalledWith('follow project rules\n\nnext turn');
+ });
+
+ it('records the harness session id so the next turn resumes it', async () => {
+ mockGetAllWindows.mockReturnValue([]);
+ dshSpawnMock.mockImplementationOnce((options: { onSessionId: (id: string) => void }) => ({
+ dispose: dshDisposeMock,
+ prompt: async function* () {
+ options.onSessionId('dsh-session-new');
+ yield {
+ data: {},
+ operationId: 'op-dsh',
+ stepIndex: 0,
+ timestamp: 0,
+ type: 'stream_start',
+ };
+ },
+ }));
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'deepseek-harness',
+ command: '',
+ cwd: '/workspace',
+ });
+
+ await ctr.sendPrompt({ operationId: 'op-dsh', prompt: 'hello', sessionId });
+
+ await expect(ctr.getSessionInfo({ sessionId })).resolves.toMatchObject({
+ agentSessionId: 'dsh-session-new',
+ });
+ });
+
+ it('fails the turn with an install hint when the dsh CLI is missing', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([{ isDestroyed: () => false, webContents: { send } }]);
+ dshDetectMock.mockResolvedValueOnce({ available: false, error: 'not found' });
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'deepseek-harness',
+ command: '',
+ cwd: '/workspace',
+ initialModel: 'deepseek-chat',
+ });
+
+ await expect(
+ ctr.sendPrompt({ operationId: 'op-dsh', prompt: 'hello', sessionId }),
+ ).rejects.toThrow(/npm i -g @deepseek-ai\/dsh/);
+ expect(dshSpawnMock).not.toHaveBeenCalled();
+ });
+
+ it('fails the turn with the update hint when the installed dsh is too old', async () => {
+ mockGetAllWindows.mockReturnValue([]);
+ dshDetectMock.mockResolvedValueOnce({
+ available: false,
+ error: 'DeepSeek Harness CLI 0.0.1 is too old; LobeHub needs 0.2.0 or newer.',
+ path: '/Users/me/.local/bin/dsh',
+ version: '0.0.1',
+ });
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'deepseek-harness',
+ command: '',
+ cwd: '/workspace',
+ });
+
+ await expect(
+ ctr.sendPrompt({ operationId: 'op-dsh', prompt: 'hello', sessionId }),
+ ).rejects.toThrow('DeepSeek Harness CLI 0.0.1 is too old; LobeHub needs 0.2.0 or newer.');
+ expect(dshSpawnMock).not.toHaveBeenCalled();
+ });
+
+ it('does not launch the runtime when Stop lands before it starts', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([{ isDestroyed: () => false, webContents: { send } }]);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'deepseek-harness',
+ command: '',
+ cwd: '/workspace',
+ initialModel: 'deepseek-chat',
+ });
+
+ let finishDetect!: () => void;
+ dshDetectMock.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishDetect = () =>
+ resolve({
+ available: true,
+ path: '/usr/local/bin/dsh',
+ resolvedPathEnv: '/usr/local/bin:/usr/bin',
+ });
+ }),
+ );
+
+ const sending = ctr.sendPrompt({ operationId: 'op-dsh', prompt: 'hello', sessionId });
+ await vi.waitFor(() => expect(dshDetectMock).toHaveBeenCalled());
+ // No handle exists yet, so cancel can only record the intent.
+ await ctr.cancelSession({ sessionId });
+ finishDetect();
+ await sending;
+
+ expect(dshPromptMock).not.toHaveBeenCalled();
+ expect(dshDisposeMock).toHaveBeenCalledOnce();
+ expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });
+ });
+ });
+
describe('sendPrompt (claude-code)', () => {
beforeEach(() => {
spawnCalls.length = 0;
@@ -5544,6 +5770,41 @@ describe('HeterogeneousAgentCtr', () => {
expect(event.preventDefault).not.toHaveBeenCalled();
});
+ it('before-quit waits for a running DSH runtime to dispose before quitting', async () => {
+ const electron = (await import('electron')) as any;
+ electron.app.on.mockClear();
+ electron.app.quit.mockClear();
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'deepseek-harness',
+ command: '',
+ cwd: '/workspace',
+ });
+ const session = (ctr as any).sessions.get(sessionId);
+ let finishDispose!: () => void;
+ const dispose = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishDispose = resolve;
+ }),
+ );
+ session.dshSession = { dispose, prompt: dshPromptMock };
+
+ ctr.afterAppReady();
+ const beforeQuit = captureRegisteredHandler(electron.app.on, 'before-quit');
+ beforeQuit({ preventDefault: vi.fn() });
+
+ expect(dispose).toHaveBeenCalledOnce();
+ expect(session.cancelledByUs).toBe(true);
+ await Promise.resolve();
+ expect(electron.app.quit).not.toHaveBeenCalled();
+ finishDispose();
+ await vi.waitFor(() => expect(electron.app.quit).toHaveBeenCalledOnce());
+ });
+
it('before-quit closes a running TRAE ACP session', async () => {
const electron = (await import('electron')) as any;
electron.app.on.mockClear();
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 57b575565c3..028a15e23aa 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -18,7 +18,7 @@ import {
entityIdPattern,
initialTopicMetadataSchema,
isServerDefaultHeterogeneousRelayInvocation,
- LocalHeterogeneousAgentTypeSchema,
+ LocalExecutionHeterogeneousAgentTypeSchema,
RequestTrigger,
ThreadStatus,
ThreadType,
@@ -1752,7 +1752,7 @@ const AgentStreamEventSchema = z.object({
* → topic reverse-lookup is unreliable per design decision).
*/
const HeteroIngestSchema = z.object({
- agentType: LocalHeterogeneousAgentTypeSchema,
+ agentType: LocalExecutionHeterogeneousAgentTypeSchema,
/** Initial assistant placeholder message id forwarded from the sandbox env var.
* When present, `loadOrCreateState` uses it directly and skips the DB read of
* topic.metadata.runningOperation, eliminating the replica-lag race condition. */
@@ -1769,7 +1769,7 @@ const HeteroIngestSchema = z.object({
* (CC's per-cwd id), kept here so the server can resume next time.
*/
const HeteroFinishSchema = z.object({
- agentType: LocalHeterogeneousAgentTypeSchema,
+ agentType: LocalExecutionHeterogeneousAgentTypeSchema,
/** Initial assistant placeholder forwarded by the producer. Unlike the live
* ingest path, finish may arrive after gateway session completion has already
* cleared topic.metadata.runningOperation, so this is the durable fallback
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 9f96c5d990c..2486bf56e20 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -1,7 +1,10 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { type ISnapshotStore, parseOperationId } from '@lobechat/agent-tracing';
import type { LobeChatDatabase } from '@lobechat/database';
-import { type LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
+import {
+ type LocalHeterogeneousAgentType,
+ type LocalRuntimeHeterogeneousAgentType,
+} from '@lobechat/heterogeneous-agents';
import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';
import {
classifyHeteroProcessFailure,
@@ -33,7 +36,9 @@ import { HeteroTraceRecorder } from './HeteroTraceRecorder';
const log = debug('lobe-server:hetero-agent-service');
-export type HeterogeneousAgentType = LocalHeterogeneousAgentType;
+/** Producers that stream through `heteroIngest`: local CLIs and bundled runtimes. */
+export type HeterogeneousAgentType =
+ LocalHeterogeneousAgentType | LocalRuntimeHeterogeneousAgentType;
export type HeterogeneousFinishResult = 'success' | 'error' | 'cancelled';
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index c43471ab842..916226eae3d 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -261,6 +261,7 @@
"connectAgent.providerDesc.codebuddy": "Tencent coding agent CLI",
"connectAgent.providerDesc.codex": "OpenAI coding agent CLI",
"connectAgent.providerDesc.cursor": "Cursor coding agent CLI",
+ "connectAgent.providerDesc.deepseek-harness": "DeepSeek Harness agent (dsh CLI) with tools and subagents",
"connectAgent.providerDesc.devin": "Cognition coding agent CLI",
"connectAgent.providerDesc.droid": "Factory coding agent CLI",
"connectAgent.providerDesc.grok-build": "xAI coding agent CLI",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 064f7a3cf46..297b08eed45 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -809,6 +809,11 @@
"heterogeneousStatus.detecting": "Detecting {{name}} CLI...",
"heterogeneousStatus.plan.label": "Plan",
"heterogeneousStatus.redetect": "Re-detect",
+ "heterogeneousStatus.runtime.bundled": "dsh CLI",
+ "heterogeneousStatus.runtime.configure": "Provider Settings",
+ "heterogeneousStatus.runtime.description": "Requires the DeepSeek Harness CLI: npm i -g @deepseek-ai/dsh",
+ "heterogeneousStatus.runtime.keyMissing": "Configure the DeepSeek provider API key",
+ "heterogeneousStatus.runtime.keyReady": "Using the DeepSeek provider API key",
"heterogeneousStatus.unavailable": "{{name}} CLI not found. Please install or configure it.",
"hotkey.clearBinding": "Clear binding",
"hotkey.conflicts": "Conflicts with existing hotkeys",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 68641e03a46..543d21c9f8c 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -261,6 +261,7 @@
"connectAgent.providerDesc.codebuddy": "腾讯编码助理 CLI",
"connectAgent.providerDesc.codex": "OpenAI 编码助理 CLI",
"connectAgent.providerDesc.cursor": "Cursor 编码助理 CLI",
+ "connectAgent.providerDesc.deepseek-harness": "DeepSeek Harness Agent(dsh CLI),支持工具调用和子 Agent",
"connectAgent.providerDesc.devin": "Cognition 编码助理 CLI",
"connectAgent.providerDesc.droid": "Factory 编码助理 CLI",
"connectAgent.providerDesc.grok-build": "xAI 编码助理 CLI",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index d89f7828cc6..376a808f8b4 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -809,6 +809,11 @@
"heterogeneousStatus.detecting": "正在检测 {{name}} CLI…",
"heterogeneousStatus.plan.label": "方案",
"heterogeneousStatus.redetect": "重新检测",
+ "heterogeneousStatus.runtime.bundled": "dsh CLI",
+ "heterogeneousStatus.runtime.configure": "服务商设置",
+ "heterogeneousStatus.runtime.description": "需要安装 DeepSeek Harness CLI:npm i -g @deepseek-ai/dsh",
+ "heterogeneousStatus.runtime.keyMissing": "请配置 DeepSeek 服务商 API Key",
+ "heterogeneousStatus.runtime.keyReady": "已复用 DeepSeek 服务商 API Key",
"heterogeneousStatus.unavailable": "未检测到 {{name}} CLI,请先安装或配置",
"hotkey.clearBinding": "清除绑定",
"hotkey.conflicts": "与现有快捷键冲突",
diff --git a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts b/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts
index c43023acdc6..06a1dd0f541 100644
--- a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts
+++ b/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts
@@ -29,7 +29,7 @@ interface HeteroTypeProfile {
/** Friendly product name. */
displayName: string;
/** Local child-process CLI vs. an agent dispatched to a remote device. */
- kind: 'cli' | 'remote';
+ kind: 'cli' | 'remote' | 'runtime';
}
const CODING_CAPABILITIES = [
@@ -76,6 +76,13 @@ const HETERO_PROFILES: Record<HeteroType, HeteroTypeProfile> = {
displayName: 'Cursor',
kind: 'cli',
},
+ 'deepseek-harness': {
+ capabilities: [...CODING_CAPABILITIES, 'subagents'],
+ description:
+ 'DeepSeek Harness — LobeHub’s built-in DeepSeek agent runtime. It can inspect and modify a working directory, run shell commands, use structured tools, and delegate work to subagents without requiring an external CLI installation.',
+ displayName: 'DeepSeek Harness',
+ kind: 'runtime',
+ },
'droid': {
capabilities: CODING_CAPABILITIES,
description:
@@ -171,8 +178,8 @@ export interface HeteroAgentRuntimeDescriptor {
displayName: string;
/** Where the agent executes. */
executionTarget?: DeviceExecutionTarget;
- /** Local CLI child-process vs. remote device runtime. */
- kind: 'cli' | 'remote';
+ /** External CLI, bundled local runtime, or remote device runtime. */
+ kind: 'cli' | 'remote' | 'runtime';
/** Runtime type identifier (e.g. `claude-code`, `codex`). */
type: HeteroType;
}
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index 01773f6d84b..5aac13f24a0 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -1,10 +1,9 @@
+import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import type {
CodexQuotaSnapshot,
CodexRateLimitResetOutcome,
} from '@lobechat/heterogeneous-agents/quota';
-import type { HeterogeneousCliAgentType } from './binary';
-
export {
AMP_CLI_INSTALL_COMMANDS,
AMP_CLI_INSTALL_DOCS_URL,
@@ -88,7 +87,7 @@ export interface CodexRateLimitResetResult {
}
export interface HeterogeneousAgentSessionError {
- agentType?: HeterogeneousCliAgentType;
+ agentType?: HeterogeneousAgentType;
code?: HeterogeneousAgentSessionErrorCode | string;
command?: string;
/** Diagnostic context from the CLI's terminal event (subtype, HTTP status, turn count, …). */
@@ -129,5 +128,6 @@ export interface HeterogeneousAgentRuntimeStatus {
| 'codex-app-server'
| 'cursor-acp'
| 'droid-acp'
+ | 'dsh-jsonrpc'
| 'trae-acp';
}
diff --git a/packages/heterogeneous-agents/src/adapters/dshAcp.ts b/packages/heterogeneous-agents/src/adapters/dshAcp.ts
new file mode 100644
index 00000000000..9135c484a6a
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/dshAcp.ts
@@ -0,0 +1,12 @@
+import { TraeAcpAdapter } from './traeAcp';
+
+/**
+ * Maps DeepSeek Harness's standard ACP session updates into the shared event
+ * protocol. Its `usage_update` reports context occupancy only, so no per-turn
+ * token usage crosses.
+ */
+export class DshAcpAdapter extends TraeAcpAdapter {
+ constructor() {
+ super({ eventPrefix: 'dsh', provider: 'deepseek-harness' });
+ }
+}
diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.ts
index 7d7911fe776..ded292cb171 100644
--- a/packages/heterogeneous-agents/src/adapters/index.ts
+++ b/packages/heterogeneous-agents/src/adapters/index.ts
@@ -5,8 +5,9 @@ export { CodexAdapter } from './codex';
export { CodexAppServerAdapter } from './codexAppServer';
export { CursorAdapter } from './cursor';
export { CursorAcpAdapter } from './cursorAcp';
-export { DroidAcpAdapter } from './droidAcp';
export { DevinAcpAdapter } from './devinAcp';
+export { DroidAcpAdapter } from './droidAcp';
+export { DshAcpAdapter } from './dshAcp';
export { GrokBuildAdapter } from './grokBuild';
export { KimiCodeAdapter } from './kimiCode';
export { OpenCodeAdapter } from './opencode';
diff --git a/packages/heterogeneous-agents/src/client/index.ts b/packages/heterogeneous-agents/src/client/index.ts
index ef2520a60de..e8d53b7882f 100644
--- a/packages/heterogeneous-agents/src/client/index.ts
+++ b/packages/heterogeneous-agents/src/client/index.ts
@@ -5,6 +5,7 @@ import {
CodeBuddy,
Codex,
Cursor,
+ DeepSeek,
Devin,
getLobeIconCDN,
Grok,
@@ -18,17 +19,25 @@ import {
import {
getHeterogeneousAgentConfig,
HETEROGENEOUS_AGENT_CONFIGS,
+ isLocalRuntimeHeterogeneousType,
isRemoteHeterogeneousType,
+ LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS,
} from '../config';
import { DROID_AVATAR_URL, DroidIcon } from './DroidIcon';
-export { DROID_AVATAR_URL, DroidIcon, isRemoteHeterogeneousType };
+export { DROID_AVATAR_URL, DroidIcon, isLocalRuntimeHeterogeneousType, isRemoteHeterogeneousType };
export type HeterogeneousAgentClientConfig = (typeof HETEROGENEOUS_AGENT_CONFIGS)[number] & {
avatar: string;
icon: IconType;
};
+export type LocalRuntimeHeterogeneousAgentClientConfig =
+ (typeof LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS)[number] & {
+ avatar: string;
+ icon: IconType;
+ };
+
const heterogeneousAgentIcons = {
'amp': Amp,
'claude-code': ClaudeCode,
@@ -59,10 +68,19 @@ export const HETEROGENEOUS_AGENT_CLIENT_CONFIGS = HETEROGENEOUS_AGENT_CONFIGS.ma
icon: heterogeneousAgentIcons[config.type],
})) as readonly HeterogeneousAgentClientConfig[];
+export const LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CLIENT_CONFIGS =
+ LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({
+ ...config,
+ avatar: createAgentAvatar(config.iconId),
+ icon: DeepSeek,
+ })) as readonly LocalRuntimeHeterogeneousAgentClientConfig[];
+
export const getHeterogeneousAgentClientConfig = (type: string) => {
const config = getHeterogeneousAgentConfig(type);
- if (!config) return undefined;
+ if (!config) {
+ return LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CLIENT_CONFIGS.find((item) => item.type === type);
+ }
return {
...config,
diff --git a/packages/heterogeneous-agents/src/config.ts b/packages/heterogeneous-agents/src/config.ts
index 3d984ec0d86..8152d190467 100644
--- a/packages/heterogeneous-agents/src/config.ts
+++ b/packages/heterogeneous-agents/src/config.ts
@@ -4,12 +4,15 @@ import type {
HeterogeneousAgentType,
LocalHeterogeneousAgentDescriptor,
LocalHeterogeneousAgentType,
+ LocalRuntimeHeterogeneousAgentDescriptor,
+ LocalRuntimeHeterogeneousAgentType,
RemoteHeterogeneousAgentDescriptor,
RemoteHeterogeneousAgentType,
} from '@lobechat/types';
import {
HETEROGENEOUS_AGENT_CONFIGS,
LOCAL_HETEROGENEOUS_AGENT_TYPES,
+ LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS,
REMOTE_HETEROGENEOUS_AGENT_CONFIGS,
} from '@lobechat/types';
@@ -19,12 +22,15 @@ export type {
HeterogeneousAgentType,
LocalHeterogeneousAgentDescriptor,
LocalHeterogeneousAgentType,
+ LocalRuntimeHeterogeneousAgentDescriptor,
+ LocalRuntimeHeterogeneousAgentType,
RemoteHeterogeneousAgentDescriptor,
RemoteHeterogeneousAgentType,
};
export {
HETEROGENEOUS_AGENT_CONFIGS,
LOCAL_HETEROGENEOUS_AGENT_TYPES,
+ LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS,
REMOTE_HETEROGENEOUS_AGENT_CONFIGS,
};
@@ -37,6 +43,9 @@ const LOCAL_HETERO_TYPES = new Set<string>(LOCAL_HETEROGENEOUS_AGENT_TYPES);
const REMOTE_HETERO_TYPES = new Set<string>(
REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),
);
+const LOCAL_RUNTIME_HETERO_TYPES = new Set<string>(
+ LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),
+);
export const isLocalHeterogeneousType = (type: string): type is LocalHeterogeneousAgentType =>
LOCAL_HETERO_TYPES.has(type);
@@ -44,6 +53,10 @@ export const isLocalHeterogeneousType = (type: string): type is LocalHeterogeneo
export const isRemoteHeterogeneousType = (type: string): type is RemoteHeterogeneousAgentType =>
REMOTE_HETERO_TYPES.has(type);
+export const isLocalRuntimeHeterogeneousType = (
+ type: string,
+): type is LocalRuntimeHeterogeneousAgentType => LOCAL_RUNTIME_HETERO_TYPES.has(type);
+
export const getHeterogeneousAgentConfig = (type: string) =>
HETEROGENEOUS_AGENT_CONFIGS.find((config) => config.type === type);
diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.ts
index f059a799aca..35b334ca1a6 100644
--- a/packages/heterogeneous-agents/src/index.ts
+++ b/packages/heterogeneous-agents/src/index.ts
@@ -12,6 +12,8 @@ export type {
HeterogeneousAgentType,
LocalHeterogeneousAgentDescriptor,
LocalHeterogeneousAgentType,
+ LocalRuntimeHeterogeneousAgentDescriptor,
+ LocalRuntimeHeterogeneousAgentType,
RemoteHeterogeneousAgentDescriptor,
RemoteHeterogeneousAgentType,
} from './config';
@@ -37,8 +39,10 @@ export {
HETEROGENEOUS_AGENT_CONFIGS,
isHeterogeneousAgentAuthRequired,
isLocalHeterogeneousType,
+ isLocalRuntimeHeterogeneousType,
isRemoteHeterogeneousType,
LOCAL_HETEROGENEOUS_AGENT_TYPES,
+ LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS,
OPENCODE_CLI_INSTALL_COMMANDS,
OPENCODE_CLI_INSTALL_DOCS_URL,
PI_CLI_INSTALL_COMMANDS,
diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.ts
index cb981ae890d..86e910997f8 100644
--- a/packages/heterogeneous-agents/src/registry.ts
+++ b/packages/heterogeneous-agents/src/registry.ts
@@ -13,8 +13,9 @@ import {
CodexAdapter,
CursorAcpAdapter,
CursorAdapter,
- DroidAcpAdapter,
DevinAcpAdapter,
+ DroidAcpAdapter,
+ DshAcpAdapter,
GrokBuildAdapter,
KimiCodeAdapter,
OpenCodeAdapter,
@@ -82,6 +83,14 @@ const runtimeAdapterRegistry = {
'droid-acp': {
createAdapter: () => new DroidAcpAdapter(),
},
+ /**
+ * DeepSeek Harness over its `acp` profile. Registered here rather than in
+ * `localAgentRegistry` because it carries no local CLI install/auth
+ * descriptor: LobeHub drives the user-installed `dsh` as a protocol runtime.
+ */
+ 'deepseek-harness': {
+ createAdapter: () => new DshAcpAdapter(),
+ },
} satisfies Record<string, AgentRegistryEntry>;
const registry: Record<string, AgentRegistryEntry> = {
diff --git a/packages/heterogeneous-agents/src/spawn/__fixtures__/dshAcp/acp-bash-tool.jsonl b/packages/heterogeneous-agents/src/spawn/__fixtures__/dshAcp/acp-bash-tool.jsonl
new file mode 100644
index 00000000000..07a99d5eadb
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/__fixtures__/dshAcp/acp-bash-tool.jsonl
@@ -0,0 +1,5 @@
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"usage_update","used":7079,"size":1000000}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_ET_5a3EUJFO1XsD4QZQIq1q9196","title":"bash","kind":"other","status":"in_progress","rawInput":{"command":"echo dsh-acp-proof-0207","description":"Echo verification string"}}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_ET_5a3EUJFO1XsD4QZQIq1q9196","status":"completed","content":[{"type":"content","content":{"type":"text","text":"dsh-acp-proof-0207\n"}}]}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","messageId":"e1f80770-75cc-4a06-95ea-ecdadf1db5b8","content":{"type":"text","text":"dsh-acp-proof-0207"}}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"usage_update","used":7109,"size":1000000}}}
diff --git a/packages/heterogeneous-agents/src/spawn/__fixtures__/dshAcp/acp-subagent.jsonl b/packages/heterogeneous-agents/src/spawn/__fixtures__/dshAcp/acp-subagent.jsonl
new file mode 100644
index 00000000000..c6259b5e6b5
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/__fixtures__/dshAcp/acp-subagent.jsonl
@@ -0,0 +1,6 @@
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_thought_chunk","messageId":"300f3be4-0775-4c16-9690-08b0387de3ef","content":{"type":"text","text":"The user wants me to delegate to a subagent: have it reply with exactly \"child answer 42\". Then tell what it said.\n\nSimple. Use subagent with run_in_background false since I need the result."}}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"usage_update","used":7161,"size":1000000}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_00_wlOVgO0Ys3iXV7Xv1rVg9261","title":"subagent","kind":"other","status":"in_progress","rawInput":{"description":"Reply exact phrase","prompt":"Reply with exactly the following text and nothing else, no quotes, no punctuation, no additional words:\n\nchild answer 42","run_in_background":false}}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_00_wlOVgO0Ys3iXV7Xv1rVg9261","status":"completed","content":[{"type":"content","content":{"type":"text","text":"child answer 42"}}]}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","messageId":"271a084b-e62f-4b79-bc17-f4a315e11d76","content":{"type":"text","text":"The subagent said exactly:\n\n> child answer 42"}}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"usage_update","used":7197,"size":1000000}}}
diff --git a/packages/heterogeneous-agents/src/spawn/__fixtures__/dshAcp/acp-text-turn.jsonl b/packages/heterogeneous-agents/src/spawn/__fixtures__/dshAcp/acp-text-turn.jsonl
new file mode 100644
index 00000000000..3c3cd418a2b
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/__fixtures__/dshAcp/acp-text-turn.jsonl
@@ -0,0 +1,2 @@
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","messageId":"610e6531-b1d0-41b7-8021-3ac83501e804","content":{"type":"text","text":"ACP profile OK"}}}}
+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"usage_update","used":7049,"size":1000000}}}
diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.e2e.test.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.e2e.test.ts
new file mode 100644
index 00000000000..b277aa1fb56
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.e2e.test.ts
@@ -0,0 +1,88 @@
+import { mkdtemp, readFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { describe, expect, it } from 'vitest';
+
+import { spawnDshAcpSession } from './dshAcpSession';
+
+/**
+ * End-to-end against a REAL DeepSeek Harness runtime — real model calls and
+ * real tool execution, across separate runtime processes the way LobeHub runs
+ * every turn.
+ *
+ * Self-skips without `DEEPSEEK_API_KEY`. Requires the official DeepSeek Harness
+ * CLI (`npm i -g @deepseek-ai/dsh`) on PATH, or `DSH_BIN` pointing at another
+ * install. Point `DSH_HOME` at a scratch directory to keep its sessions out of
+ * your own harness history.
+ */
+
+const runnable = Boolean(process.env.DEEPSEEK_API_KEY);
+
+const turn = async (
+ cwd: string,
+ prompt: string,
+ resumeSessionId?: string,
+): Promise<{ events: AgentStreamEvent[]; sessionId?: string }> => {
+ const handle = spawnDshAcpSession({
+ ...(process.env.DSH_BIN ? { command: process.env.DSH_BIN } : {}),
+ cwd,
+ operationId: 'op-e2e',
+ resumeSessionId,
+ });
+ const events: AgentStreamEvent[] = [];
+ try {
+ for await (const event of handle.prompt(prompt)) events.push(event);
+ } finally {
+ await handle.dispose();
+ }
+ return { events, sessionId: handle.sessionId };
+};
+
+const textOf = (events: AgentStreamEvent[]): string =>
+ events
+ .filter((e) => e.type === 'stream_chunk' && (e.data as any).chunkType === 'text')
+ .map((e) => (e.data as any).content)
+ .join('');
+
+describe.runIf(runnable)('spawnDshAcpSession — live harness', () => {
+ it('continues the same conversation from a new runtime process', async () => {
+ const cwd = await mkdtemp(path.join(tmpdir(), 'dsh-e2e-'));
+
+ const first = await turn(cwd, 'Remember the code word PELICAN. Reply only OK.');
+ expect(first.sessionId).toBeTruthy();
+ expect(first.events.filter((e) => e.type === 'error')).toHaveLength(0);
+
+ const second = await turn(
+ cwd,
+ 'What was the code word? Reply with just the word.',
+ first.sessionId,
+ );
+ expect(second.sessionId).toBe(first.sessionId);
+ expect(textOf(second.events)).toContain('PELICAN');
+ }, 240_000);
+
+ it('runs a tool inside the workspace and pairs its call with the result', async () => {
+ const cwd = await mkdtemp(path.join(tmpdir(), 'dsh-e2e-'));
+
+ const { events } = await turn(
+ cwd,
+ 'Use the bash tool to run `echo dsh-e2e-proof > proof.txt && cat proof.txt`, then reply with just its output.',
+ );
+
+ expect(events.filter((e) => e.type === 'tool_start')).toHaveLength(
+ events.filter((e) => e.type === 'tool_end').length,
+ );
+ expect(events.find((e) => e.type === 'tool_result')?.data).toMatchObject({
+ content: expect.stringContaining('dsh-e2e-proof'),
+ });
+ expect(await readFile(path.join(cwd, 'proof.txt'), 'utf8')).toContain('dsh-e2e-proof');
+ }, 240_000);
+});
+
+describe.skipIf(runnable)('spawnDshAcpSession — live harness (not runnable here)', () => {
+ it('needs DEEPSEEK_API_KEY and the dsh CLI', () => {
+ expect(runnable).toBe(false);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.test.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.test.ts
new file mode 100644
index 00000000000..988d430eb5f
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.test.ts
@@ -0,0 +1,267 @@
+import { chmod, mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { describe, expect, it, vi } from 'vitest';
+
+import { DSH_ACP_PROFILE_ARGS, spawnDshAcpSession } from './dshAcpSession';
+
+const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), '__fixtures__/dshAcp');
+
+const MODEL_CONFIG = [
+ {
+ category: 'model',
+ currentValue: '["deepseek-official","deepseek-v4-flash"]',
+ id: 'model',
+ options: [
+ {
+ group: 'deepseek-official',
+ name: 'DeepSeek',
+ options: [
+ { name: 'deepseek-v4-flash', value: '["deepseek-official","deepseek-v4-flash"]' },
+ { name: 'DeepSeek-V4-Pro', value: '["deepseek-official","deepseek-v4-pro"]' },
+ ],
+ },
+ ],
+ type: 'select',
+ },
+];
+
+/**
+ * A stand-in `dsh --profile acp`: answers the ACP lifecycle and, on
+ * `session/prompt`, replays `session/update` notifications recorded from the
+ * real 0.2.0-rc.2 runtime. Every request it receives is logged for assertions.
+ */
+const FAKE_RUNTIME = `
+const fs = require('node:fs');
+const [, , profileFlag, profile] = process.argv;
+const log = (frame) => fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify({ argv: [profileFlag, profile], frame }) + '\\n');
+const send = (frame) => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...frame }) + '\\n');
+const config = JSON.parse(process.env.FAKE_CONFIG);
+let pendingPrompt;
+let buffer = '';
+process.stdin.on('data', (chunk) => {
+ buffer += chunk.toString('utf8');
+ const lines = buffer.split('\\n');
+ buffer = lines.pop();
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ const frame = JSON.parse(line);
+ log(frame);
+ const { id, method, params } = frame;
+ if (method === 'initialize') {
+ const sessionCapabilities = process.env.FAKE_NO_RESUME ? {} : { close: {}, list: {}, resume: {} };
+ send({ id, result: { agentCapabilities: { sessionCapabilities }, authMethods: [], protocolVersion: 1 } });
+ } else if (method === 'session/new') {
+ send({ id, result: { configOptions: config, sessionId: 'dsh-new' } });
+ } else if (method === 'session/resume') {
+ send({ id, result: { configOptions: config } });
+ } else if (method === 'session/set_config_option') {
+ send({ id, result: { configOptions: config } });
+ } else if (method === 'session/prompt') {
+ if (process.env.FAKE_HANG) { pendingPrompt = id; continue; }
+ const recorded = fs.readFileSync(process.env.FAKE_FIXTURE, 'utf8').trim().split('\\n');
+ for (const update of recorded) process.stdout.write(update.split('{{sessionId}}').join(params.sessionId) + '\\n');
+ send({ id, result: { stopReason: 'end_turn' } });
+ } else if (method === 'session/cancel') {
+ if (pendingPrompt !== undefined) send({ id: pendingPrompt, result: { stopReason: 'cancelled' } });
+ }
+ }
+});
+`;
+
+interface RunOptions {
+ env?: Record<string, string>;
+ fixture?: string;
+ model?: string;
+ resumeSessionId?: string;
+}
+
+const start = async ({
+ env = {},
+ fixture = 'acp-text-turn',
+ model,
+ resumeSessionId,
+}: RunOptions) => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'dsh-acp-'));
+ const logPath = path.join(dir, 'requests.jsonl');
+ const command = path.join(dir, 'dsh');
+ await writeFile(command, `#!${process.execPath}\n${FAKE_RUNTIME}`);
+ await chmod(command, 0o755);
+ const handle = spawnDshAcpSession({
+ command,
+ cwd: dir,
+ env: {
+ FAKE_CONFIG: JSON.stringify(MODEL_CONFIG),
+ FAKE_FIXTURE: path.join(FIXTURES, `${fixture}.jsonl`),
+ FAKE_LOG: logPath,
+ ...env,
+ },
+ model,
+ operationId: 'op-dsh',
+ resumeSessionId,
+ });
+ return { dir, handle, logPath };
+};
+
+const collect = async (handle: ReturnType<typeof spawnDshAcpSession>, text = 'hello') => {
+ const events: AgentStreamEvent[] = [];
+ for await (const event of handle.prompt(text)) events.push(event);
+ return events;
+};
+
+const requestsOf = async (logPath: string) =>
+ (await readFile(logPath, 'utf8'))
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line) as { argv: string[]; frame: any });
+
+const methodsOf = async (logPath: string) =>
+ (await requestsOf(logPath)).map(({ frame }) => frame.method);
+
+const textOf = (events: AgentStreamEvent[]) =>
+ events
+ .filter((e) => e.type === 'stream_chunk' && (e.data as any).chunkType === 'text')
+ .map((e) => (e.data as any).content)
+ .join('');
+
+describe('spawnDshAcpSession', () => {
+ it('opens a new harness session on the acp profile and streams the reply', async () => {
+ const { handle, logPath } = await start({});
+
+ const events = await collect(handle, 'say it');
+
+ const requests = await requestsOf(logPath);
+ expect(requests[0].argv).toEqual([...DSH_ACP_PROFILE_ARGS]);
+ expect(requests.map(({ frame }) => frame.method)).toEqual([
+ 'initialize',
+ 'session/new',
+ 'session/prompt',
+ ]);
+ expect(requests[2].frame.params).toEqual({
+ prompt: [{ text: 'say it', type: 'text' }],
+ sessionId: 'dsh-new',
+ });
+ expect(handle.sessionId).toBe('dsh-new');
+ expect(textOf(events)).toBe('ACP profile OK');
+ expect(events.find((e) => e.type === 'stream_start')?.data).toMatchObject({
+ model: 'deepseek-v4-flash',
+ provider: 'deepseek-harness',
+ sessionId: 'dsh-new',
+ });
+ expect(events.every((e) => e.operationId === 'op-dsh')).toBe(true);
+ expect(events.at(-1)?.type).toBe('agent_runtime_end');
+ });
+
+ it('pairs a tool call with its result across the two model steps it spans', async () => {
+ const { handle } = await start({ fixture: 'acp-bash-tool' });
+
+ const events = await collect(handle);
+
+ const toolStart = events.find((e) => e.type === 'tool_start');
+ expect((toolStart?.data as any).toolCalling).toMatchObject({
+ apiName: 'bash',
+ identifier: 'deepseek-harness',
+ });
+ expect(events.find((e) => e.type === 'tool_result')?.data).toMatchObject({
+ content: 'dsh-acp-proof-0207\n',
+ isError: false,
+ });
+ expect(textOf(events)).toBe('dsh-acp-proof-0207');
+ expect(events.filter((e) => e.type === 'stream_start').map((e) => e.stepIndex)).toEqual([0, 1]);
+ });
+
+ it('shows a delegated subagent as its tool call and final answer', async () => {
+ const { handle } = await start({ fixture: 'acp-subagent' });
+
+ const events = await collect(handle);
+
+ expect((events.find((e) => e.type === 'tool_start')?.data as any).toolCalling.apiName).toBe(
+ 'subagent',
+ );
+ expect(events.find((e) => e.type === 'tool_result')?.data).toMatchObject({
+ content: 'child answer 42',
+ });
+ });
+
+ it('continues a persisted harness session with session/resume', async () => {
+ const { dir, handle, logPath } = await start({ resumeSessionId: 'dsh-prev' });
+
+ await collect(handle);
+
+ const requests = await requestsOf(logPath);
+ expect(requests.map(({ frame }) => frame.method)).toEqual([
+ 'initialize',
+ 'session/resume',
+ 'session/prompt',
+ ]);
+ expect(requests[1].frame.params).toEqual({ cwd: dir, mcpServers: [], sessionId: 'dsh-prev' });
+ expect(requests[2].frame.params.sessionId).toBe('dsh-prev');
+ expect(handle.sessionId).toBe('dsh-prev');
+ });
+
+ it('refuses to resume on a runtime that cannot, instead of opening a blank session', async () => {
+ const { handle, logPath } = await start({
+ env: { FAKE_NO_RESUME: '1' },
+ resumeSessionId: 'dsh-prev',
+ });
+
+ await expect(collect(handle)).rejects.toThrow(/cannot resume.*npm i -g @deepseek-ai\/dsh/);
+ expect(await methodsOf(logPath)).toEqual(['initialize']);
+ });
+
+ it('switches to a requested model the runtime offers', async () => {
+ const { handle, logPath } = await start({ model: 'deepseek-v4-pro' });
+
+ const events = await collect(handle);
+
+ const setConfig = (await requestsOf(logPath)).find(
+ ({ frame }) => frame.method === 'session/set_config_option',
+ );
+ expect(setConfig?.frame.params).toEqual({
+ configId: 'model',
+ sessionId: 'dsh-new',
+ value: '["deepseek-official","deepseek-v4-pro"]',
+ });
+ expect(events.find((e) => e.type === 'stream_start')?.data).toMatchObject({
+ model: 'deepseek-v4-pro',
+ });
+ });
+
+ it('keeps the harness default for a model it does not offer', async () => {
+ const { handle, logPath } = await start({ model: 'deepseek-chat' });
+
+ await collect(handle);
+
+ expect(await methodsOf(logPath)).not.toContain('session/set_config_option');
+ });
+
+ it('cancels a running turn on dispose', async () => {
+ const { handle, logPath } = await start({ env: { FAKE_HANG: '1' } });
+
+ const events: AgentStreamEvent[] = [];
+ const draining = (async () => {
+ for await (const event of handle.prompt('long task')) events.push(event);
+ })();
+ await vi.waitFor(async () => expect(await methodsOf(logPath)).toContain('session/prompt'), {
+ timeout: 5000,
+ });
+
+ await handle.dispose();
+ await draining;
+
+ expect(await methodsOf(logPath)).toContain('session/cancel');
+ expect(events.at(-1)?.data).toMatchObject({ reason: 'interrupted' });
+ });
+
+ it('never launches the runtime when disposed before the turn starts', async () => {
+ const { handle } = await start({});
+
+ await handle.dispose();
+
+ expect(await collect(handle)).toEqual([]);
+ expect(handle.sessionId).toBeUndefined();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts
new file mode 100644
index 00000000000..5bcc69bfdc0
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts
@@ -0,0 +1,382 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { isRecord } from '@lobechat/utils/object';
+
+import type { AcpAgentSessionOptions } from './acpAgentSession';
+import {
+ ACP_PROTOCOL_VERSION,
+ AcpAgentSession,
+ selectAcpPermissionOption,
+} from './acpAgentSession';
+import type { AcpRpcMessage } from './acpStdioClient';
+import { AcpServerRequestError } from './acpStdioClient';
+import type { CliCommandStatus } from './resolveCliCommand';
+import { detectValidatedCommand } from './resolveCliCommand';
+
+/**
+ * DeepSeek Harness over the Agent Client Protocol.
+ *
+ * The runtime is the user-installed DeepSeek Harness CLI (`@deepseek-ai/dsh`)
+ * serving its shipped `acp` profile on stdio. That profile — unlike the `sdk`
+ * profile — implements `session/resume`, so a conversation continues the same
+ * persisted harness session across processes, which is how LobeHub runs every
+ * turn. Nothing from `@deepseek-ai/*` ships with LobeHub.
+ */
+
+/** The official DeepSeek Harness CLI executable (`npm i -g @deepseek-ai/dsh`). */
+export const DSH_COMMAND = 'dsh';
+
+/** `dsh --version` prints a bare semantic version (e.g. `0.2.0-rc.2`). */
+export const DSH_VERSION_PATTERN = /^v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/;
+
+/** First release whose CLI ships the `acp` profile with `session/resume`. */
+export const DSH_MIN_VERSION = '0.2.0';
+
+/** Compare release numbers only, so `0.2.0-rc.2` already counts as 0.2. */
+const isSupportedDshVersion = (version: string | undefined): boolean => {
+ const parts = version
+ ?.match(/(\d+)\.(\d+)\.(\d+)/)
+ ?.slice(1)
+ .map(Number);
+ if (!parts) return false;
+ const minimum = DSH_MIN_VERSION.split('.').map(Number);
+ for (const [index, part] of parts.entries()) {
+ if (part !== minimum[index]) return part > minimum[index];
+ }
+ return true;
+};
+
+/**
+ * Find a `dsh` that can run LobeHub turns. An older CLI still answers
+ * `--version` but has no `acp` profile, so it is reported unavailable here
+ * rather than failing every turn after the agent was created.
+ */
+export const detectDshCommand = async (
+ command: string = DSH_COMMAND,
+ env?: NodeJS.ProcessEnv,
+): Promise<CliCommandStatus> => {
+ const status = await detectValidatedCommand(
+ command,
+ { validatePattern: DSH_VERSION_PATTERN },
+ env,
+ );
+ if (!status.available || isSupportedDshVersion(status.version)) return status;
+ return {
+ ...status,
+ available: false,
+ error: `DeepSeek Harness CLI ${status.version} is too old; LobeHub needs ${DSH_MIN_VERSION} or newer. Update it with: npm i -g @deepseek-ai/dsh`,
+ };
+};
+
+/** Select the CLI's shipped ACP profile, served on stdio until disconnect. */
+export const DSH_ACP_PROFILE_ARGS: readonly string[] = ['--profile', 'acp'];
+
+/** The profile boots its plugin tree before answering `initialize`. */
+const DSH_REQUEST_TIMEOUT_MS = 60_000;
+
+/** How long `dispose` waits for a cancelled turn to wind down before killing it. */
+const DISPOSE_GRACE_MS = 5000;
+
+const DSH_MODEL_CONFIG_ID = 'model';
+
+interface DshInitializeResult {
+ agentCapabilities?: { sessionCapabilities?: { resume?: unknown } };
+ protocolVersion?: number | string;
+}
+
+interface DshConfigOption {
+ currentValue?: unknown;
+ id?: unknown;
+ options?: unknown;
+}
+
+interface DshSessionResult {
+ configOptions?: DshConfigOption[];
+ sessionId?: string;
+}
+
+export interface DshAcpSessionOptions extends AcpAgentSessionOptions {
+ /**
+ * Model to select, by name (`deepseek-v4-pro`). A name the runtime does not
+ * offer keeps the harness's own default rather than failing the turn.
+ */
+ model?: string;
+ prompt: string;
+}
+
+/**
+ * The harness encodes each model choice as a JSON `[provider, model]` pair;
+ * `config` options group them by provider.
+ */
+const modelChoices = (configOptions: DshConfigOption[] | undefined) => {
+ const option = configOptions?.find(({ id }) => id === DSH_MODEL_CONFIG_ID);
+ const flatten = (entries: unknown): { name?: string; value: string }[] =>
+ Array.isArray(entries)
+ ? entries.flatMap((entry) => {
+ if (!isRecord(entry)) return [];
+ if (Array.isArray(entry.options)) return flatten(entry.options);
+ return typeof entry.value === 'string'
+ ? [
+ {
+ name: typeof entry.name === 'string' ? entry.name : undefined,
+ value: entry.value,
+ },
+ ]
+ : [];
+ })
+ : [];
+ return {
+ choices: flatten(option?.options),
+ current: typeof option?.currentValue === 'string' ? option.currentValue : undefined,
+ };
+};
+
+/** The model name inside a `[provider, model]` choice value. */
+const modelOf = (value: string | undefined): string | undefined => {
+ if (!value) return;
+ try {
+ const parsed = JSON.parse(value);
+ if (Array.isArray(parsed) && typeof parsed[1] === 'string') return parsed[1];
+ } catch {
+ // Not the encoded pair; treat the raw value as the model name.
+ }
+ return value;
+};
+
+/** DeepSeek Harness's ACP lifecycle on the shared session base. */
+export class DshAcpSession extends AcpAgentSession<DshInitializeResult, DshAcpSessionOptions> {
+ constructor(options: DshAcpSessionOptions) {
+ super(
+ { ...options, requestTimeoutMs: options.requestTimeoutMs ?? DSH_REQUEST_TIMEOUT_MS },
+ {
+ args: [...DSH_ACP_PROFILE_ARGS, ...options.args],
+ pipeline: { agentType: 'deepseek-harness', cwd: options.cwd },
+ processLabel: 'DeepSeek Harness ACP',
+ transport: 'acp-stdio',
+ },
+ );
+ }
+
+ get sessionId(): string | undefined {
+ return this.acpSessionId;
+ }
+
+ protected buildInitializeParams(): unknown {
+ return {
+ clientCapabilities: { fs: {}, terminal: false },
+ clientInfo: { name: 'lobehub', version: this.options.clientVersion },
+ protocolVersion: ACP_PROTOCOL_VERSION,
+ };
+ }
+
+ protected validateInitialized(initialized: DshInitializeResult): void {
+ if (
+ initialized.protocolVersion !== ACP_PROTOCOL_VERSION &&
+ initialized.protocolVersion !== String(ACP_PROTOCOL_VERSION)
+ ) {
+ throw new Error(
+ `Unsupported DeepSeek Harness ACP protocol version: ${String(initialized.protocolVersion)}`,
+ );
+ }
+ if (
+ this.options.resumeSessionId &&
+ !initialized.agentCapabilities?.sessionCapabilities?.resume
+ ) {
+ throw new Error(
+ 'This DeepSeek Harness CLI cannot resume sessions. Update it with: npm i -g @deepseek-ai/dsh',
+ );
+ }
+ }
+
+ protected async establishSession(_initialized: DshInitializeResult): Promise<string> {
+ const params = { cwd: this.options.cwd, mcpServers: [] };
+ const resumeSessionId = this.options.resumeSessionId;
+ const result = resumeSessionId
+ ? await this.client.request<DshSessionResult>('session/resume', {
+ ...params,
+ sessionId: resumeSessionId,
+ })
+ : await this.client.request<DshSessionResult>('session/new', params);
+
+ const sessionId = resumeSessionId ?? result?.sessionId;
+ if (!sessionId) throw new Error('DeepSeek Harness ACP returned no session id');
+ this.acpSessionId = sessionId;
+
+ const model = await this.selectModel(sessionId, result?.configOptions);
+ await this.pushToPipeline({ model, sessionId, type: 'dsh_session' });
+ this.options.onSessionId(sessionId);
+ return sessionId;
+ }
+
+ protected buildPromptParams(sessionId: string): unknown {
+ return { prompt: [{ text: this.options.prompt, type: 'text' }], sessionId };
+ }
+
+ protected override async settlePrompt(result: unknown): Promise<void> {
+ await this.client.drain();
+ await this.pushToPipeline({
+ stopReason: isRecord(result) ? result.stopReason : undefined,
+ type: 'dsh_prompt_completed',
+ });
+ }
+
+ protected async onRunFailure(error: Error): Promise<void> {
+ await this.pushToPipeline({ message: error.message, type: 'dsh_error' });
+ await this.emitEvents(await this.pipeline.flush());
+ }
+
+ protected async handleAgentMessage(message: AcpRpcMessage): Promise<void> {
+ if (message.method !== 'session/update') return;
+ const update = (message.params as { update?: unknown } | undefined)?.update;
+ if (isRecord(update)) await this.pushToPipeline(update);
+ }
+
+ /**
+ * LobeHub runs agents headless. The harness's default `workspace-write`
+ * preset does not ask for workspace edits; anything it still escalates is
+ * allowed once, the same unattended policy the other ACP agents use.
+ */
+ protected handleServerRequest(message: AcpRpcMessage): unknown {
+ if (message.method === 'session/request_permission') {
+ const optionId = selectAcpPermissionOption(message.params, [
+ ({ kind }) => kind === 'allow_once',
+ ({ kind }) => kind === 'allow_always',
+ ]);
+ return { outcome: optionId ? { optionId, outcome: 'selected' } : { outcome: 'cancelled' } };
+ }
+ throw new AcpServerRequestError(-32_601, `Unsupported ACP client request: ${message.method}`);
+ }
+
+ /** Switch to the requested model when the runtime offers it; report the model in effect. */
+ private async selectModel(
+ sessionId: string,
+ configOptions: DshConfigOption[] | undefined,
+ ): Promise<string | undefined> {
+ const { choices, current } = modelChoices(configOptions);
+ const wanted = this.options.model?.trim();
+ const choice = wanted
+ ? choices.find(({ name, value }) => name === wanted || modelOf(value) === wanted)
+ : undefined;
+ if (!choice || choice.value === current) return modelOf(current);
+
+ await this.client.request('session/set_config_option', {
+ configId: DSH_MODEL_CONFIG_ID,
+ sessionId,
+ value: choice.value,
+ });
+ return modelOf(choice.value);
+ }
+}
+
+export interface SpawnDshAcpSessionOptions {
+ /** Extra runtime arguments, appended after the `acp` profile selection. */
+ args?: string[];
+ clientVersion?: string;
+ /** The `dsh` executable (name on PATH or absolute path). Defaults to {@link DSH_COMMAND}. */
+ command?: string;
+ /** Agent workspace; also the harness session `cwd` a resume must match. */
+ cwd: string;
+ env?: Record<string, string>;
+ model?: string;
+ /** Called as soon as the turn's harness session is established. */
+ onSessionId?: (sessionId: string) => void;
+ operationId?: string;
+ /** Harness session to continue. Omit to open a new one. */
+ resumeSessionId?: string;
+}
+
+export interface DshAcpSessionHandle {
+ /** Stop the runtime: cancel any running turn, then kill it after a grace period. */
+ dispose: () => Promise<void>;
+ /** Run one turn and stream its events. A handle runs a single turn. */
+ prompt: (text: string) => AsyncGenerator<AgentStreamEvent>;
+ /** The harness session this turn ran on, once it is established. */
+ readonly sessionId: string | undefined;
+}
+
+/**
+ * Prepare one DeepSeek Harness turn. The runtime starts when `prompt` is
+ * iterated, so a caller can still back out (e.g. a Stop before launch) without
+ * having spawned anything.
+ */
+export const spawnDshAcpSession = (options: SpawnDshAcpSessionOptions): DshAcpSessionHandle => {
+ let session: DshAcpSession | undefined;
+ let running: Promise<void> | undefined;
+ let disposed = false;
+
+ const dispose = async () => {
+ disposed = true;
+ if (!session || !running) return;
+ session.interrupt();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const grace = new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, DISPOSE_GRACE_MS);
+ });
+ await Promise.race([running.catch(() => {}), grace]);
+ clearTimeout(timer);
+ session.close('SIGKILL');
+ };
+
+ async function* prompt(text: string): AsyncGenerator<AgentStreamEvent> {
+ if (session) throw new Error('A DeepSeek Harness handle runs a single turn');
+ if (disposed) return;
+
+ const queue: AgentStreamEvent[] = [];
+ let wake: (() => void) | undefined;
+ const notify = () => {
+ wake?.();
+ wake = undefined;
+ };
+
+ session = new DshAcpSession({
+ args: options.args ?? [],
+ clientVersion: options.clientVersion ?? '0.0.0',
+ commandPath: options.command ?? DSH_COMMAND,
+ cwd: options.cwd,
+ env: { ...process.env, ...options.env },
+ model: options.model,
+ onEvents: (events) => {
+ queue.push(...events);
+ notify();
+ },
+ onRawMessage: () => {},
+ onRuntimeStatus: () => {},
+ onSessionId: (sessionId) => options.onSessionId?.(sessionId),
+ onStderr: () => {},
+ operationId: options.operationId ?? '',
+ prompt: text,
+ resumeSessionId: options.resumeSessionId,
+ sessionId: options.resumeSessionId ?? '',
+ });
+
+ let settled = false;
+ let failure: unknown;
+ running = session.run().then(
+ () => {
+ settled = true;
+ notify();
+ },
+ (error) => {
+ settled = true;
+ failure = error;
+ notify();
+ },
+ );
+
+ while (true) {
+ while (queue.length > 0) yield queue.shift()!;
+ if (settled) break;
+ await new Promise<void>((resolve) => {
+ wake = resolve;
+ });
+ }
+ if (failure && !disposed) throw failure;
+ }
+
+ return {
+ dispose,
+ prompt,
+ get sessionId() {
+ return session?.sessionId;
+ },
+ };
+};
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 0582fc9dc05..a9d28c96cee 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -107,6 +107,18 @@ export {
type ListDroidAcpModelsOptions,
parseDroidAcpModelCatalog,
} from './droidAcpSession';
+export {
+ detectDshCommand,
+ DSH_ACP_PROFILE_ARGS,
+ DSH_COMMAND,
+ DSH_MIN_VERSION,
+ DSH_VERSION_PATTERN,
+ DshAcpSession,
+ type DshAcpSessionHandle,
+ type DshAcpSessionOptions,
+ spawnDshAcpSession,
+ type SpawnDshAcpSessionOptions,
+} from './dshAcpSession';
export {
createFileStoreImageUploader,
type FileStoreCreateFileInput,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index d480b24adab..f74bd1de4fa 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1397,6 +1397,8 @@ export default {
'connectAgent.create.openChat': 'Open Chat',
'connectAgent.create.done': 'Done',
'connectAgent.providerDesc.claude-code': 'Anthropic coding agent CLI',
+ 'connectAgent.providerDesc.deepseek-harness':
+ 'DeepSeek Harness agent (dsh CLI) with tools and subagents',
'connectAgent.providerDesc.codebuddy': 'Tencent coding agent CLI',
'connectAgent.providerDesc.codex': 'OpenAI coding agent CLI',
'connectAgent.providerDesc.cursor': 'Cursor coding agent CLI',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 27deda0c7e0..70fa7f3e11c 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -507,6 +507,12 @@ export default {
'heterogeneousStatus.plan.label': 'Plan',
'heterogeneousStatus.redetect': 'Re-detect',
'heterogeneousStatus.unavailable': '{{name}} CLI not found. Please install or configure it.',
+ 'heterogeneousStatus.runtime.bundled': 'dsh CLI',
+ 'heterogeneousStatus.runtime.description':
+ 'Requires the DeepSeek Harness CLI: npm i -g @deepseek-ai/dsh',
+ 'heterogeneousStatus.runtime.keyReady': 'Using the DeepSeek provider API key',
+ 'heterogeneousStatus.runtime.keyMissing': 'Configure the DeepSeek provider API key',
+ 'heterogeneousStatus.runtime.configure': 'Provider Settings',
// Heterogeneous agent — Cloud tab (web environment config)
'heterogeneousStatus.cloud.tabLabel': 'Cloud',
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index 876dc78f8a9..f89256f4b9c 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -5,6 +5,7 @@ import { hasAnyCliFlag, hasCliConfigKey, hasCliFlag } from './heteroCliArgs';
import type { HeterogeneousAgentType, LocalHeterogeneousAgentType } from './heterogeneousAgent';
import {
HETEROGENEOUS_AGENT_CONFIGS,
+ LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS,
REMOTE_HETEROGENEOUS_AGENT_CONFIGS,
} from './heterogeneousAgent';
import type {
@@ -373,6 +374,7 @@ export const applyTopicModelToHeterogeneousProvider = (
const HETEROGENEOUS_AGENT_TYPES = new Set<string>([
...HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),
+ ...LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),
...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),
]);
diff --git a/packages/types/src/agent/heterogeneousAgent.ts b/packages/types/src/agent/heterogeneousAgent.ts
index 5ade849b1f6..ed4f4e40272 100644
--- a/packages/types/src/agent/heterogeneousAgent.ts
+++ b/packages/types/src/agent/heterogeneousAgent.ts
@@ -414,6 +414,44 @@ export interface RemoteHeterogeneousAgentDescriptor {
type: string;
}
+/**
+ * A runtime LobeHub drives over a protocol instead of parsing a CLI's JSONL
+ * dialect — the DeepSeek Harness CLI (`dsh`) serving its `acp` profile over
+ * stdio. The `dsh` executable is user-installed; nothing ships with
+ * LobeHub.
+ */
+export interface LocalRuntimeHeterogeneousAgentDescriptor {
+ /** Executable the user installs; probed before the runtime is offered. */
+ defaultCommand: string;
+ defaultModel: string;
+ defaultTopicGroupMode?: TopicGroupMode;
+ iconId: string;
+ kind: 'local-runtime';
+ title: string;
+ type: string;
+}
+
+export const LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS = [
+ {
+ defaultCommand: 'dsh',
+ defaultModel: 'deepseek-v4-flash',
+ defaultTopicGroupMode: 'byProject',
+ iconId: 'DeepSeek',
+ kind: 'local-runtime',
+ title: 'DeepSeek Harness',
+ type: 'deepseek-harness',
+ },
+] as const satisfies readonly LocalRuntimeHeterogeneousAgentDescriptor[];
+
+/**
+ * Every agent type that runs on the producer's machine and streams through
+ * `heteroIngest` / `heteroFinish`: descriptor-backed CLIs plus protocol-driven runtimes.
+ */
+export const LocalExecutionHeterogeneousAgentTypeSchema = z.enum([
+ ...LOCAL_HETEROGENEOUS_AGENT_TYPES,
+ ...LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),
+]);
+
export const REMOTE_HETEROGENEOUS_AGENT_CONFIGS = [
{
cli: {
@@ -443,11 +481,15 @@ export const REMOTE_HETEROGENEOUS_AGENT_CONFIGS = [
export type HeterogeneousAgentDescriptor =
| (typeof HETEROGENEOUS_AGENT_CONFIGS)[number]
+ | (typeof LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS)[number]
| (typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number];
export type HeterogeneousAgentMenuLabelKey =
(typeof HETEROGENEOUS_AGENT_CONFIGS)[number]['menuLabelKey'];
export type LocalHeterogeneousAgentType = (typeof HETEROGENEOUS_AGENT_CONFIGS)[number]['type'];
+export type LocalRuntimeHeterogeneousAgentType =
+ (typeof LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS)[number]['type'];
export type RemoteHeterogeneousAgentType =
(typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number]['type'];
-export type HeterogeneousAgentType = LocalHeterogeneousAgentType | RemoteHeterogeneousAgentType;
+export type HeterogeneousAgentType =
+ LocalHeterogeneousAgentType | LocalRuntimeHeterogeneousAgentType | RemoteHeterogeneousAgentType;
diff --git a/src/features/ConnectAgent/providers.ts b/src/features/ConnectAgent/providers.ts
index 6cf0b59f8a0..6aa36b54f8c 100644
--- a/src/features/ConnectAgent/providers.ts
+++ b/src/features/ConnectAgent/providers.ts
@@ -1,6 +1,7 @@
import type {
HeterogeneousAgentType,
LocalHeterogeneousAgentType,
+ LocalRuntimeHeterogeneousAgentType,
RemoteHeterogeneousAgentType,
} from '@lobechat/heterogeneous-agents';
import {
@@ -10,6 +11,7 @@ import {
import {
DroidIcon,
HETEROGENEOUS_AGENT_CLIENT_CONFIGS,
+ LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CLIENT_CONFIGS,
} from '@lobechat/heterogeneous-agents/client';
import {
Amp,
@@ -17,6 +19,7 @@ import {
CodeBuddy,
Codex,
Cursor,
+ DeepSeek,
Devin,
Grok,
HermesAgent,
@@ -43,6 +46,7 @@ export interface ConnectableProvider {
| typeof CodeBuddy
| typeof Codex
| typeof Cursor
+ | typeof DeepSeek
| typeof DroidIcon
| typeof Devin
| typeof Grok
@@ -53,9 +57,9 @@ export interface ConnectableProvider {
| typeof Pi
| typeof Qoder
| typeof Trae;
- /** Spawn command — cli providers only. */
+ /** Spawn command — cli and runtime providers. */
command?: string;
- kind: 'cli' | 'platform';
+ kind: 'cli' | 'platform' | 'runtime';
title: string;
type: HeterogeneousAgentType;
}
@@ -94,6 +98,10 @@ const PLATFORM_BRANDS: Record<RemoteHeterogeneousAgentType, ConnectableProvider[
openclaw: OpenClaw,
};
+const RUNTIME_BRANDS: Record<LocalRuntimeHeterogeneousAgentType, ConnectableProvider['brand']> = {
+ 'deepseek-harness': DeepSeek,
+};
+
export const CONNECTABLE_PROVIDERS: ConnectableProvider[] = [
...HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map((config) => ({
avatar: config.avatar,
@@ -103,6 +111,14 @@ export const CONNECTABLE_PROVIDERS: ConnectableProvider[] = [
title: config.title,
type: config.type,
})),
+ ...LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map((config) => ({
+ avatar: config.avatar,
+ brand: RUNTIME_BRANDS[config.type],
+ command: config.defaultCommand,
+ kind: 'runtime' as const,
+ title: config.title,
+ type: config.type,
+ })),
...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({
brand: PLATFORM_BRANDS[config.type],
kind: 'platform' as const,
@@ -146,6 +162,8 @@ export const buildConnectAgentConfig = ({
};
}
+ // A runtime's command is only what the scan probes; launch resolves it itself.
+ const command = provider.kind === 'cli' ? provider.command : undefined;
const base = {
avatar: provider.avatar,
description: overrides?.description?.trim() || undefined,
@@ -161,7 +179,7 @@ export const buildConnectAgentConfig = ({
agencyConfig: {
boundDeviceId: target.deviceId,
executionTarget: 'device' as const,
- heterogeneousProvider: { command: provider.command, type: provider.type },
+ heterogeneousProvider: { command, type: provider.type },
},
};
}
@@ -169,7 +187,7 @@ export const buildConnectAgentConfig = ({
return {
...base,
agencyConfig: {
- heterogeneousProvider: { command: provider.command, type: provider.type },
+ heterogeneousProvider: { command, type: provider.type },
},
};
};
diff --git a/src/features/ConnectAgent/useAgentScan.test.ts b/src/features/ConnectAgent/useAgentScan.test.ts
index 5a8c4a6544e..b31db526ce7 100644
--- a/src/features/ConnectAgent/useAgentScan.test.ts
+++ b/src/features/ConnectAgent/useAgentScan.test.ts
@@ -26,6 +26,10 @@ describe('scanLocal', () => {
const agents = await scanLocal();
+ expect(agents['deepseek-harness']).toEqual({
+ available: true,
+ version: 'deepseek-harness-version',
+ });
expect(agents.openclaw).toEqual({ available: true, version: 'openclaw-version' });
expect(agents.hermes).toEqual({ available: true, version: 'hermes-version' });
expect(detectHeterogeneousAgentCommand).toHaveBeenCalledWith({
@@ -38,6 +42,25 @@ describe('scanLocal', () => {
});
});
+ it('reports DeepSeek Harness unavailable when the dsh CLI is not installed', async () => {
+ detectHeterogeneousAgentCommand.mockImplementation(async ({ agentType }) =>
+ agentType === 'deepseek-harness'
+ ? { available: false, error: 'dsh not found' }
+ : { available: true },
+ );
+
+ const agents = await scanLocal();
+
+ expect(detectHeterogeneousAgentCommand).toHaveBeenCalledWith({
+ agentType: 'deepseek-harness',
+ command: 'dsh',
+ });
+ expect(agents['deepseek-harness']).toMatchObject({
+ available: false,
+ reason: 'dsh not found',
+ });
+ });
+
it('preserves detector and IPC failure reasons', async () => {
detectHeterogeneousAgentCommand.mockImplementation(async ({ agentType }) => {
if (agentType === 'openclaw') {
@@ -80,6 +103,18 @@ describe('buildPlatformAgencyConfig', () => {
});
describe('buildConnectAgentConfig', () => {
+ it('creates the DeepSeek runtime without persisting its probe command', () => {
+ const provider = getConnectableProvider('deepseek-harness')!;
+ const config = buildConnectAgentConfig({ provider, target: { kind: 'local' } });
+
+ expect(config).toMatchObject({
+ agencyConfig: { heterogeneousProvider: { type: 'deepseek-harness' } },
+ provider: 'deepseek-harness',
+ title: 'DeepSeek Harness',
+ });
+ expect(config.agencyConfig.heterogeneousProvider.command).toBeUndefined();
+ });
+
it('stores a customized label as the personal name without overwriting the platform profile', () => {
const provider = getConnectableProvider('hermes')!;
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
index 59c0bc44bf5..6d77feb591a 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
@@ -17,42 +17,48 @@ vi.mock('@lobechat/const', () => ({
vi.mock('@lobechat/heterogeneous-agents/client', () => ({
getHeterogeneousAgentClientConfig: (type: string) =>
- type === 'claude-code'
+ type === 'deepseek-harness'
? {
- defaultCommand: 'claude',
- icon: () => <span>Claude Code Icon</span>,
- title: 'Claude Code',
+ icon: () => <span>DeepSeek Icon</span>,
+ title: 'DeepSeek Harness',
}
- : type === 'droid'
+ : type === 'claude-code'
? {
- defaultCommand: 'droid',
- icon: () => <span>Factory Droid Icon</span>,
- title: 'Factory Droid',
+ defaultCommand: 'claude',
+ icon: () => <span>Claude Code Icon</span>,
+ title: 'Claude Code',
}
- : type === 'kimi-code'
+ : type === 'droid'
? {
- defaultCommand: 'kimi',
- icon: () => <span>Kimi Code Icon</span>,
- title: 'Kimi Code',
+ defaultCommand: 'droid',
+ icon: () => <span>Factory Droid Icon</span>,
+ title: 'Factory Droid',
}
- : type === 'opencode'
+ : type === 'kimi-code'
? {
- defaultCommand: 'opencode',
- icon: () => <span>OpenCode Icon</span>,
- title: 'OpenCode',
+ defaultCommand: 'kimi',
+ icon: () => <span>Kimi Code Icon</span>,
+ title: 'Kimi Code',
}
- : type === 'pi'
+ : type === 'opencode'
? {
- defaultCommand: 'pi',
- icon: () => <span>Pi Icon</span>,
- title: 'Pi',
+ defaultCommand: 'opencode',
+ icon: () => <span>OpenCode Icon</span>,
+ title: 'OpenCode',
}
- : {
- defaultCommand: 'codex',
- icon: () => <span>Codex Icon</span>,
- title: 'Codex',
- },
+ : type === 'pi'
+ ? {
+ defaultCommand: 'pi',
+ icon: () => <span>Pi Icon</span>,
+ title: 'Pi',
+ }
+ : {
+ defaultCommand: 'codex',
+ icon: () => <span>Codex Icon</span>,
+ title: 'Codex',
+ },
isRemoteHeterogeneousType: (type: string) => ['openclaw', 'hermes'].includes(type),
+ isLocalRuntimeHeterogeneousType: (type: string) => type === 'deepseek-harness',
}));
vi.mock('@lobehub/ui', async (importOriginal) => ({
@@ -247,7 +253,23 @@ const claudeServerModels = [{ model: 'claude-sonnet-4-6' }, { model: 'claude-hai
const codexServerModels = [{ model: 'gpt-5.4' }];
+vi.mock('@/store/aiInfra/slices/aiProvider/selectors', () => ({
+ aiProviderSelectors: { providerKeyVaults: () => () => ({ apiKey: 'configured' }) },
+}));
+
describe('HeterogeneousAgentStatusCard', () => {
+ it('shows the bundled runtime and provider-key state without probing a CLI', () => {
+ render(
+ <MemoryRouter>
+ <HeterogeneousAgentStatusCard provider={{ type: 'deepseek-harness' }} />
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByText('DeepSeek Harness')).toBeInTheDocument();
+ expect(screen.getByText('heterogeneousStatus.runtime.keyReady')).toBeInTheDocument();
+ expect(detectHeterogeneousAgentCommand).not.toHaveBeenCalled();
+ });
+
it('shows the embedded Codex install guide when the CLI is unavailable', async () => {
detectHeterogeneousAgentCommand.mockResolvedValue({ available: false });
getClaudeAuthStatus.mockResolvedValue(null);
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
index 9581a9bb3bc..8ca34ee851a 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
@@ -5,6 +5,7 @@ import { type BinaryStatus, type ClaudeAuthStatus } from '@lobechat/electron-cli
import { isHeterogeneousProviderBindingSupported } from '@lobechat/heterogeneous-agents';
import {
getHeterogeneousAgentClientConfig,
+ isLocalRuntimeHeterogeneousType,
isRemoteHeterogeneousType,
} from '@lobechat/heterogeneous-agents/client';
import type {
@@ -15,7 +16,7 @@ import type {
import { CopyButton, Flexbox, Icon, Tooltip, TooltipGroup } from '@lobehub/ui';
import { ActionIcon, Button, Input, Segmented, Select, Spin, Tag, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { PencilLine, RefreshCw, XCircle } from 'lucide-react';
+import { CheckCircle2, KeyRound, PencilLine, RefreshCw, XCircle } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -32,6 +33,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import { usePermission } from '@/hooks/usePermission';
import { binaryService } from '@/services/electron/binary';
import { useAiInfraStore } from '@/store/aiInfra';
+import { aiProviderSelectors } from '@/store/aiInfra/slices/aiProvider/selectors';
const COMMAND_LINE_HEIGHT = 28;
const SERVER_DEFAULT_PROVIDER_VALUE = 'server-default';
@@ -207,7 +209,59 @@ interface HeterogeneousAgentStatusCardProps {
serverDefaultUnavailableReason?: string;
}
-const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
+const LocalRuntimeStatusCard = memo<{ provider: HeterogeneousProviderConfig }>(({ provider }) => {
+ const { t } = useTranslation('setting');
+ const navigate = useWorkspaceAwareNavigate();
+ const keyVault = useAiInfraStore(aiProviderSelectors.providerKeyVaults('deepseek'));
+ const configured = Boolean(keyVault?.apiKey);
+ const providerConfig = getHeterogeneousAgentClientConfig(provider.type);
+ const AgentIcon = providerConfig?.icon;
+
+ return (
+ <Flexbox className={styles.card} gap={12}>
+ <div className={styles.cardHeader}>
+ <div className={styles.cardTitleWrap}>
+ <div className={styles.cardTitle}>
+ {AgentIcon && <AgentIcon size={16} />}
+ <Text strong>{providerConfig?.title || provider.type}</Text>
+ </div>
+ <Flexbox horizontal align="center" className={styles.metaRow} gap={8}>
+ <Tag color="success" style={{ marginInlineEnd: 0 }}>
+ {t('heterogeneousStatus.runtime.bundled')}
+ </Tag>
+ <Text className={styles.metaText}>{t('heterogeneousStatus.runtime.description')}</Text>
+ </Flexbox>
+ </div>
+ </div>
+ <div className={styles.detailList}>
+ <div className={styles.detailRow}>
+ <Text className={styles.detailLabel}>{t('heterogeneousStatus.auth.label')}</Text>
+ <Flexbox horizontal align="center" flex={1} gap={8} justify="space-between">
+ <Flexbox horizontal align="center" gap={8}>
+ <Icon
+ color={configured ? 'var(--ant-color-success)' : 'var(--ant-color-warning)'}
+ icon={configured ? CheckCircle2 : KeyRound}
+ size={16}
+ />
+ <Text>
+ {t(
+ configured
+ ? 'heterogeneousStatus.runtime.keyReady'
+ : 'heterogeneousStatus.runtime.keyMissing',
+ )}
+ </Text>
+ </Flexbox>
+ <Button size="small" onClick={() => navigate('/settings/provider/deepseek')}>
+ {t('heterogeneousStatus.runtime.configure')}
+ </Button>
+ </Flexbox>
+ </div>
+ </div>
+ </Flexbox>
+ );
+});
+
+const CliHeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
({
apiModeAvailable = false,
apiModeWorkspaceBlocked = false,
@@ -225,7 +279,8 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
const navigate = useWorkspaceAwareNavigate();
const { allowed: canEdit } = usePermission('edit_own_content');
const providerConfig = getHeterogeneousAgentClientConfig(provider.type);
- const defaultCommand = providerConfig?.defaultCommand || '';
+ const defaultCommand =
+ providerConfig && 'defaultCommand' in providerConfig ? providerConfig.defaultCommand : '';
const resolvedCommand = provider.command?.trim() || defaultCommand;
const isUsingCustomCommand = resolvedCommand !== defaultCommand;
const [status, setStatus] = useState<BinaryStatus | undefined>();
@@ -895,6 +950,16 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
},
);
+CliHeterogeneousAgentStatusCard.displayName = 'CliHeterogeneousAgentStatusCard';
+
+const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>((props) =>
+ isLocalRuntimeHeterogeneousType(props.provider.type) ? (
+ <LocalRuntimeStatusCard provider={props.provider} />
+ ) : (
+ <CliHeterogeneousAgentStatusCard {...props} />
+ ),
+);
+
HeterogeneousAgentStatusCard.displayName = 'HeterogeneousAgentStatusCard';
export default HeterogeneousAgentStatusCard;
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 349e32e022c..6d8cb6a39bc 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -61,6 +61,7 @@ import {
setHeteroSessionBindingKeyForWorkingDirectory,
setHeteroSessionIdForWorkingDirectory,
} from '@/helpers/heteroSessionByWorkingDirectory';
+import { createPayloadWithKeyVaults } from '@/services/_auth';
import { agentQuotaService } from '@/services/agentQuota';
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
import {
@@ -2014,6 +2015,10 @@ export const executeHeterogeneousAgent = async (
// over both provenance and account routing.
...heterogeneousProvider.env,
};
+ if (adapterType === 'deepseek-harness' && !sessionEnv.DEEPSEEK_API_KEY) {
+ const deepSeekAuth = createPayloadWithKeyVaults('deepseek');
+ if (deepSeekAuth.apiKey) sessionEnv.DEEPSEEK_API_KEY = deepSeekAuth.apiKey;
+ }
const spawnArgs = buildHeteroSpawnArgs(heterogeneousProvider);
const providerBinding = serverDefaultBindingActive
@@ -2034,11 +2039,17 @@ export const executeHeterogeneousAgent = async (
const result = await heterogeneousAgentService.startSession({
agentType: isLocalHeterogeneousType(adapterType) ? adapterType : undefined,
args: spawnArgs,
- command: resolveHeterogeneousAgentCommand(adapterType, heterogeneousProvider.command),
+ command:
+ adapterType === 'deepseek-harness'
+ ? ''
+ : resolveHeterogeneousAgentCommand(adapterType, heterogeneousProvider.command),
cwd: workingDirectory,
env: sessionEnv,
initialModel:
- (adapterType === 'devin' || adapterType === 'droid' || adapterType === 'trae') &&
+ (adapterType === 'devin' ||
+ adapterType === 'droid' ||
+ adapterType === 'trae' ||
+ adapterType === 'deepseek-harness') &&
!providerBindingActive &&
heterogeneousProvider.model &&
heterogeneousProvider.model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION