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 OpenCode CLI agent (#17345)

AmAzing-5f1b9dcee498
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index c9849771e9c..f51e0c14e02 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -102,9 +102,16 @@ describe('hetero exec command', () => {
stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
mockResolveHeteroSpawnCommand.mockReset();
mockResolveHeteroSpawnCommand.mockImplementation(
- async (agentType: 'amp' | 'claude-code' | 'codex', command?: string) => ({
+ async (agentType: 'amp' | 'claude-code' | 'codex' | 'opencode', command?: string) => ({
command:
- command ?? (agentType === 'amp' ? 'amp' : agentType === 'codex' ? 'codex' : 'claude'),
+ command ??
+ (agentType === 'amp'
+ ? 'amp'
+ : agentType === 'codex'
+ ? 'codex'
+ : agentType === 'opencode'
+ ? 'opencode'
+ : 'claude'),
}),
);
mockSpawnAgent.mockReset();
@@ -350,6 +357,39 @@ describe('hetero exec command', () => {
);
});
+ it('runs OpenCode with model, resume, and native args while ignoring effort and speed', async () => {
+ mockSpawnAgent.mockReturnValue(createFakeHandle());
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'opencode',
+ '--prompt',
+ 'do thing',
+ '--resume',
+ 'session-open-1',
+ '--model',
+ 'anthropic/claude-sonnet-4',
+ '--effort',
+ 'high',
+ '--speed',
+ 'fast',
+ '--agent-arg=--variant',
+ '--agent-arg=max',
+ ]);
+
+ expect(mockResolveHeteroSpawnCommand).toHaveBeenCalledWith('opencode', undefined);
+ expect(mockSpawnAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentType: 'opencode',
+ command: 'opencode',
+ extraArgs: ['--variant', 'max', '--model', 'anthropic/claude-sonnet-4'],
+ resumeSessionId: 'session-open-1',
+ }),
+ );
+ });
+
it('streams events to stdout as JSONL, one line per event', async () => {
const events = [
{ data: { foo: 1 }, operationId: 'op-1', stepIndex: 0, timestamp: 1, type: 'stream_start' },
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index c0123184a38..5b117de73ea 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -28,7 +28,7 @@ import { CoalescingBatchIngester } from '../utils/CoalescingBatchIngester';
import { log } from '../utils/logger';
import { TrpcIngestSink } from '../utils/TrpcIngestSink';
-const SUPPORTED_AGENT_TYPES = new Set(['amp', 'claude-code', 'codex']);
+const SUPPORTED_AGENT_TYPES = new Set(['amp', 'claude-code', 'codex', 'opencode']);
const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';
const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';
@@ -123,10 +123,12 @@ const buildExtraArgs = (
: []),
...(options.speed ? ['-c', `${CODEX_SERVICE_TIER_CONFIG_KEY}="${options.speed}"`] : []),
]
- : [
- ...(options.model ? ['--model', options.model] : []),
- ...(options.effort ? ['--effort', options.effort] : []),
- ];
+ : options.type === 'claude-code'
+ ? [
+ ...(options.model ? ['--model', options.model] : []),
+ ...(options.effort ? ['--effort', options.effort] : []),
+ ]
+ : [...(options.model ? ['--model', options.model] : [])];
const extraArgs = [...(options.agentArg ?? []), ...selectorArgs];
return extraArgs.length > 0 ? extraArgs : undefined;
@@ -377,7 +379,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
// Build the ingest sink — no-op for standalone mode, real tRPC sink for
// server-ingest mode. The tRPC client reads LOBEHUB_JWT (operation-scoped
// JWT injected by the server) for authentication.
- const agentType = options.type as 'amp' | 'claude-code' | 'codex';
+ const agentType = options.type as 'amp' | 'claude-code' | 'codex' | 'opencode';
let sink: TrpcIngestSink | undefined;
let serverIngester: CoalescingBatchIngester | undefined;
// Uploader for tool_result images (CC `Read` on an image file). Reuses the
@@ -881,7 +883,7 @@ export function registerHeteroCommand(program: Command) {
const hetero = program
.command('hetero')
.description(
- 'Run heterogeneous agent CLIs (Amp / Claude Code / Codex) and stream their output',
+ 'Run heterogeneous agent CLIs (Amp / Claude Code / Codex / OpenCode) and stream their output',
);
hetero
@@ -915,7 +917,7 @@ export function registerHeteroCommand(program: Command) {
)
.option(
'-c, --command <bin>',
- 'Override the agent CLI binary name (default: `amp`, `claude`, or `codex`)',
+ 'Override the agent CLI binary name (default: `amp`, `claude`, `codex`, or `opencode`)',
)
.option(
'--operation-id <id>',
diff --git a/apps/cli/src/utils/TrpcIngestSink.ts b/apps/cli/src/utils/TrpcIngestSink.ts
index 6391c524c90..b3256198334 100644
--- a/apps/cli/src/utils/TrpcIngestSink.ts
+++ b/apps/cli/src/utils/TrpcIngestSink.ts
@@ -13,7 +13,7 @@ import type { IngestSink } from './BatchIngester';
export class TrpcIngestSink implements IngestSink {
constructor(
private readonly client: TrpcClient,
- private readonly agentType: 'amp' | 'claude-code' | 'codex',
+ private readonly agentType: 'amp' | 'claude-code' | 'codex' | 'opencode',
private readonly operationId: string,
private readonly topicId: string,
private readonly assistantMessageId?: string,
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index 5e239250623..602e2284060 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -13,6 +13,7 @@ import type {
CodexQuotaSnapshot,
CodexRateLimitResetResult,
HeterogeneousAgentSessionError,
+ HeterogeneousCliAgentType,
} from '@lobechat/electron-client-ipc';
import {
AMP_CLI_INSTALL_COMMANDS,
@@ -22,6 +23,8 @@ import {
CODEX_CLI_INSTALL_COMMANDS,
CODEX_CLI_INSTALL_DOCS_URL,
HeterogeneousAgentSessionErrorCode,
+ OPENCODE_CLI_INSTALL_COMMANDS,
+ OPENCODE_CLI_INSTALL_DOCS_URL,
} from '@lobechat/electron-client-ipc';
import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';
import type { McpToolResult } from '@lobechat/heterogeneous-agents/builtinMcp';
@@ -135,7 +138,7 @@ const waitForHeteroSessionCompleteGrace = () =>
interface StartSessionParams {
/** Agent type key (e.g., 'claude-code'). Defaults to 'claude-code'. */
- agentType?: string;
+ agentType?: HeterogeneousCliAgentType;
/** Additional CLI arguments */
args?: string[];
/** Command to execute */
@@ -239,7 +242,7 @@ interface SessionInfo {
interface AgentSession {
agentSessionId?: string;
- agentType: string;
+ agentType: HeterogeneousCliAgentType;
args: string[];
/**
* True when *we* initiated the kill (cancelSession / stopSession / before-quit).
@@ -358,6 +361,9 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
case 'codex': {
return 'codex';
}
+ case 'opencode': {
+ return 'opencode';
+ }
default: {
return 'claude';
}
@@ -403,6 +409,19 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
};
}
+ private buildOpenCodeCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {
+ const command = this.resolveSessionCommand(session);
+
+ return {
+ agentType: 'opencode',
+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,
+ command,
+ docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,
+ installCommands: OPENCODE_CLI_INSTALL_COMMANDS,
+ message: `OpenCode CLI was not found. Install it and make sure \`${command}\` can be executed.`,
+ };
+ }
+
private buildCliMissingError(session: AgentSession): HeterogeneousAgentSessionError | undefined {
switch (session.agentType) {
case 'amp': {
@@ -414,6 +433,9 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
case 'codex': {
return this.buildCodexCliMissingError(session);
}
+ case 'opencode': {
+ return this.buildOpenCodeCliMissingError(session);
+ }
default: {
return;
}
@@ -460,6 +482,17 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
stderr,
};
}
+ case 'opencode': {
+ return {
+ agentType: 'opencode',
+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,
+ command,
+ docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,
+ message:
+ 'OpenCode could not authenticate. Sign in again or refresh its credentials, then retry.',
+ stderr,
+ };
+ }
default: {
return;
}
@@ -613,17 +646,16 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
? 'claude'
: session.agentType === 'codex'
? 'codex'
- : undefined;
+ : session.agentType === 'opencode'
+ ? 'opencode'
+ : undefined;
if (!defaultCommand) return;
const command = this.resolveSessionCommand(session);
const status =
command === defaultCommand
? await this.app.binaryManager?.detect?.(defaultCommand, true)
- : await detectHeterogeneousCliCommand(
- session.agentType as 'amp' | 'claude-code' | 'codex',
- command,
- );
+ : await detectHeterogeneousCliCommand(session.agentType, command);
if (!status || status.available) {
// Spawn through the detector-resolved absolute path when the configured
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 0aacd195c22..a55663c3bce 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -824,6 +824,26 @@ describe('HeterogeneousAgentCtr', () => {
expect(spawnCalls).toHaveLength(0);
});
+ it('fails fast with OpenCode install guidance when OpenCode is unavailable', async () => {
+ const detect = vi.fn().mockResolvedValue({ available: false });
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ binaryManager: { detect },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'opencode',
+ command: 'opencode',
+ });
+
+ await expect(
+ ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),
+ ).rejects.toThrow('OpenCode CLI was not found');
+
+ expect(detect).toHaveBeenCalledWith('opencode', true);
+ expect(spawnCalls).toHaveLength(0);
+ });
+
it('fails fast when a customized Claude command is unavailable instead of checking the default detector', async () => {
execFileMock.mockImplementation(
(
diff --git a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts
index 8bebb40eb20..da26a68cc4b 100644
--- a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts
+++ b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts
@@ -170,6 +170,20 @@ describe('cliAgentBinaries', () => {
platformMock.mockReturnValue('darwin');
});
+ it('detects OpenCode through the shared command/version probe', async () => {
+ callExecFile('/Users/test/.opencode/bin/opencode\n');
+ callExecFile('1.18.3');
+
+ const { opencodeBinary } = await import('../cliAgentBinaries');
+ const status = await opencodeBinary.detect();
+
+ expect(status).toMatchObject({
+ available: true,
+ path: '/Users/test/.opencode/bin/opencode',
+ version: '1.18.3',
+ });
+ });
+
it('runs the binary directly via execFile (no shell)', async () => {
callExecFile('/usr/local/bin/claude\n');
callExecFile('1.2.3 (Claude Code)');
diff --git a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
index dd41252ca16..95c8def2494 100644
--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
@@ -87,6 +87,17 @@ export const ampBinary: BinarySpec = {
priority: 3,
};
+/**
+ * OpenCode CLI
+ * @see https://opencode.ai/docs
+ */
+export const opencodeBinary: BinarySpec = {
+ description: 'OpenCode - Open source agentic coding CLI',
+ detect: () => detectHeterogeneousCliCommand('opencode', 'opencode'),
+ name: 'opencode',
+ priority: 4,
+};
+
/**
* Google Gemini CLI
* @see https://github.com/google-gemini/gemini-cli
@@ -95,7 +106,7 @@ export const geminiCliBinary: BinarySpec = defineValidatedBinary({
candidates: ['gemini'],
description: 'Gemini CLI - Google agentic coding CLI',
name: 'gemini',
- priority: 4,
+ priority: 5,
validateKeywords: ['gemini'],
});
@@ -107,7 +118,7 @@ export const qwenCodeBinary: BinarySpec = defineValidatedBinary({
candidates: ['qwen'],
description: 'Qwen Code - Alibaba Qwen agentic coding CLI',
name: 'qwen',
- priority: 5,
+ priority: 6,
validateKeywords: ['qwen'],
});
@@ -119,7 +130,7 @@ export const kimiCliBinary: BinarySpec = defineValidatedBinary({
candidates: ['kimi'],
description: 'Kimi CLI - Moonshot AI agentic coding CLI',
name: 'kimi',
- priority: 6,
+ priority: 7,
validateKeywords: ['kimi'],
});
@@ -130,7 +141,7 @@ export const kimiCliBinary: BinarySpec = defineValidatedBinary({
*/
export const aiderBinary: BinarySpec = defineCommandBinary('aider', {
description: 'Aider - AI pair programming in your terminal',
- priority: 7,
+ priority: 8,
});
/**
@@ -140,6 +151,7 @@ export const cliAgentBinaries: BinarySpec[] = [
claudeCodeBinary,
codexBinary,
ampBinary,
+ opencodeBinary,
geminiCliBinary,
qwenCodeBinary,
kimiCliBinary,
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/opencode.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/opencode.test.ts
new file mode 100644
index 00000000000..900c4ffa3d6
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/opencode.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { getHeterogeneousAgentDriver } from '../index';
+import type {
+ HeterogeneousAgentBuildPlanHelpers,
+ HeterogeneousAgentBuildPlanParams,
+} from '../types';
+import { opencodeDriver } from './opencode';
+
+const buildAgentInput = vi.fn(async () => ({
+ args: ['--file', '/tmp/image.png'],
+ stdin: 'raw prompt',
+}));
+const helpers: HeterogeneousAgentBuildPlanHelpers = { buildAgentInput };
+
+const buildParams = (
+ overrides: Partial<HeterogeneousAgentBuildPlanParams> = {},
+): HeterogeneousAgentBuildPlanParams => ({
+ args: [],
+ helpers,
+ promptInput: 'raw prompt',
+ ...overrides,
+});
+
+describe('opencodeDriver', () => {
+ it('is registered and composes base, resume, configured, and input args in order', async () => {
+ expect(getHeterogeneousAgentDriver('opencode')).toBe(opencodeDriver);
+
+ const plan = await opencodeDriver.buildSpawnPlan(
+ buildParams({ args: ['--model', 'provider/model'], resumeSessionId: 'session-exact' }),
+ );
+
+ expect(buildAgentInput).toHaveBeenCalledWith('opencode', 'raw prompt');
+ expect(plan).toEqual({
+ args: [
+ 'run',
+ '--format',
+ 'json',
+ '--thinking',
+ '--auto',
+ '--session',
+ 'session-exact',
+ '--model',
+ 'provider/model',
+ '--file',
+ '/tmp/image.png',
+ ],
+ stdinPayload: 'raw prompt',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/opencode.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/opencode.ts
new file mode 100644
index 00000000000..027003fbf04
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/opencode.ts
@@ -0,0 +1,24 @@
+import { OPENCODE_BASE_ARGS } from '@lobechat/heterogeneous-agents/spawn';
+
+import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';
+
+export const opencodeDriver: HeterogeneousAgentDriver = {
+ async buildSpawnPlan({
+ args,
+ helpers,
+ promptInput,
+ resumeSessionId,
+ }: HeterogeneousAgentBuildPlanParams) {
+ const inputPlan = await helpers.buildAgentInput('opencode', promptInput);
+
+ return {
+ args: [
+ ...OPENCODE_BASE_ARGS,
+ ...(resumeSessionId ? ['--session', resumeSessionId] : []),
+ ...args,
+ ...inputPlan.args,
+ ],
+ stdinPayload: inputPlan.stdin,
+ };
+ },
+};
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts
index acbf8c52e25..7189b4a12cd 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts
@@ -1,12 +1,14 @@
import { ampDriver } from './drivers/amp';
import { claudeCodeDriver } from './drivers/claudeCode';
import { codexDriver } from './drivers/codex';
+import { opencodeDriver } from './drivers/opencode';
import type { HeterogeneousAgentDriver } from './types';
const heterogeneousAgentDrivers: Record<string, HeterogeneousAgentDriver> = {
'amp': ampDriver,
'claude-code': claudeCodeDriver,
'codex': codexDriver,
+ 'opencode': opencodeDriver,
};
export const getHeterogeneousAgentDriver = (agentType: string): HeterogeneousAgentDriver => {
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
index da4844195de..c6cd1c9e18c 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
@@ -95,6 +95,24 @@ describe('aiAgentRouter.heteroIngest / heteroFinish', () => {
});
});
+ it('accepts OpenCode event batches from a device CLI', async () => {
+ const events = [buildEvent('stream_start', 0)];
+
+ await createCaller().heteroIngest({
+ agentType: 'opencode',
+ events,
+ operationId: 'op-opencode',
+ topicId: 'topic-1',
+ });
+
+ expect(mockHeteroIngest).toHaveBeenCalledWith({
+ agentType: 'opencode',
+ events,
+ operationId: 'op-opencode',
+ topicId: 'topic-1',
+ });
+ });
+
it('wraps service errors into INTERNAL_SERVER_ERROR so the CLI ingester retries', async () => {
mockHeteroIngest.mockRejectedValueOnce(new Error('redis down'));
@@ -153,6 +171,23 @@ describe('aiAgentRouter.heteroIngest / heteroFinish', () => {
});
});
+ it('accepts an OpenCode session id for subsequent device resume', async () => {
+ await createCaller().heteroFinish({
+ agentType: 'opencode',
+ operationId: 'op-opencode',
+ result: 'success',
+ sessionId: 'open-session-1',
+ topicId: 'topic-1',
+ });
+
+ expect(mockHeteroFinish).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentType: 'opencode',
+ sessionId: 'open-session-1',
+ }),
+ );
+ });
+
it('passes through error classification', async () => {
await createCaller().heteroFinish({
agentType: 'codex',
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 9289d36f015..704455cdf4d 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -455,7 +455,7 @@ const AgentStreamEventSchema = z.object({
* → topic reverse-lookup is unreliable per design decision).
*/
const HeteroIngestSchema = z.object({
- agentType: z.enum(['amp', 'claude-code', 'codex']),
+ agentType: z.enum(['amp', 'claude-code', 'codex', 'opencode']),
/** 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. */
@@ -472,7 +472,7 @@ const HeteroIngestSchema = z.object({
* (CC's per-cwd id), kept here so the server can resume next time.
*/
const HeteroFinishSchema = z.object({
- agentType: z.enum(['amp', 'claude-code', 'codex']),
+ agentType: z.enum(['amp', 'claude-code', 'codex', 'opencode']),
error: z
.object({
/**
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index f834f3d5ee7..9c84e48c88f 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -24,7 +24,7 @@ const {
mockSpawnHeteroSandbox: vi.fn().mockResolvedValue(undefined),
}));
-// Local hetero (claude-code / codex) now seeds publishAgentRuntimeInit so the
+// Local hetero (claude-code / codex / opencode) seeds publishAgentRuntimeInit so the
// agent-gateway DO reports `running` on a later reconnect. Stub the factory so
// the assertion below can verify the init, and so the real one (which probes
// Redis synchronously) doesn't throw a server-env error in the test env.
@@ -371,6 +371,51 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
expect(dispatchParams.args).toEqual(['--model', 'opus', '--effort', 'high']);
});
+ it('dispatches OpenCode to a bound device with its model args', async () => {
+ heteroAgentConfig.model = 'opencode';
+ heteroAgentConfig.provider = 'opencode';
+ heteroAgentConfig.agencyConfig = {
+ boundDeviceId: 'device-1',
+ executionTarget: 'device',
+ heterogeneousProvider: {
+ model: 'anthropic/claude-sonnet-4',
+ type: 'opencode',
+ },
+ } as any;
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Use OpenCode on my device',
+ });
+
+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentType: 'opencode',
+ args: ['--model', 'anthropic/claude-sonnet-4'],
+ deviceId: 'device-1',
+ }),
+ );
+ expect(mockSpawnHeteroSandbox).not.toHaveBeenCalled();
+ });
+
+ it('never falls back to a cloud sandbox for unbound OpenCode', async () => {
+ heteroAgentConfig.model = 'opencode';
+ heteroAgentConfig.provider = 'opencode';
+ heteroAgentConfig.agencyConfig = {
+ executionTarget: 'sandbox',
+ heterogeneousProvider: { type: 'opencode' },
+ } as any;
+
+ const result = await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Do not run OpenCode in cloud',
+ });
+
+ expect(result).toEqual(expect.objectContaining({ status: 'error', success: false }));
+ expect(mockDispatchAgentRun).not.toHaveBeenCalled();
+ expect(mockSpawnHeteroSandbox).not.toHaveBeenCalled();
+ });
+
describe('image delivery to the dispatched CLI', () => {
it('should resolve image attachments and pass imageList to the sandbox dispatch', async () => {
mockResolveAttachmentsByFileIds.mockResolvedValue({
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index a44dfbac945..23d6f1a4a2a 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1614,16 +1614,16 @@ export class AiAgentService {
// 3.5. Hetero-agent early exit — local CLI and remote platform agents bypass the
// server-side LLM pipeline. After topic + message creation we hand off to
// the device gateway (desktop) or cloud sandbox, which will push events
- // back via `heteroIngest` / `heteroFinish` (claude-code / codex) or
+ // back via `heteroIngest` / `heteroFinish` (claude-code / codex / opencode) or
// `agentNotify.notify` (openclaw / hermes).
//
// Detection: prefer agencyConfig.heterogeneousProvider.type (set by the UI),
// fall back to model field for backwards compatibility.
- const HETERO_AGENT_MODELS = new Set<string>(['amp', 'claude-code', 'codex']);
+ const HETERO_AGENT_MODELS = new Set<string>(['amp', 'claude-code', 'codex', 'opencode']);
const heteroProviderType = agentConfig.agencyConfig?.heterogeneousProvider?.type;
const isHeteroAgent = !!heteroProviderType || HETERO_AGENT_MODELS.has(model);
const heteroType = (heteroProviderType ?? model) as
- 'amp' | 'claude-code' | 'codex' | 'hermes' | 'openclaw';
+ 'amp' | 'claude-code' | 'codex' | 'hermes' | 'openclaw' | 'opencode';
// ── Shared turn setup (runs for BOTH hetero and normal agents) ──────────
// Everything up to and including persisting the turn is identical for both
@@ -1903,7 +1903,10 @@ export class AiAgentService {
? runAttachments.imageList.map((image) => ({ id: image.id, url: image.url }))
: undefined;
const heteroExecArgs =
- heteroType === 'amp' || heteroType === 'claude-code' || heteroType === 'codex'
+ heteroType === 'amp' ||
+ heteroType === 'claude-code' ||
+ heteroType === 'codex' ||
+ heteroType === 'opencode'
? buildHeteroExecArgs(
agentConfig.agencyConfig?.heterogeneousProvider?.type === heteroType
? agentConfig.agencyConfig.heterogeneousProvider
@@ -2084,20 +2087,21 @@ export class AiAgentService {
};
}
} else {
- // Local CLI hetero (Amp / Claude Code / Codex) — fork between device dispatch
+ // Local CLI hetero (Amp / Claude Code / Codex / OpenCode) — fork between device dispatch
// and cloud sandbox via the shared execution plan:
// - requestedDeviceId (topic-level override) always wins
// - executionTarget 'device' → dispatch to boundDeviceId (errors if unset)
// - executionTarget 'local' + boundDeviceId (desktop sync opened on web)
// → dispatch to that device
// - everything else ('sandbox' / unbound 'local' / 'none' / unset) → cloud
- // sandbox (the server can't spawn locally, and a hetero agent must
- // execute somewhere)
+ // sandbox when the provider supports it; Amp and OpenCode remain
+ // unrouted because they require a local or connected device
// `onlineDeviceIds` is intentionally omitted: hetero dispatch trusts
// the binding and fails loudly at the gateway if the device is offline.
- // `canUseDevice` degrades device-capable targets to the sandbox for
- // denied senders (e.g. external bot users) — without it a synced
- // local/device binding would let them run on the owner's machine.
+ // `canUseDevice` degrades device-capable targets to the sandbox when
+ // available, or leaves device-only providers unrouted, for denied
+ // senders (e.g. external bot users). Without this a synced local/device
+ // binding would let them run on the owner's machine.
// Register the op with the agent-gateway DO before dispatch, mirroring
// the remote-hetero branch above. Local CLI hetero (claude-code / codex)
@@ -2132,7 +2136,7 @@ export class AiAgentService {
isHetero: true,
clientExecutionAvailable: false,
requestedDeviceId,
- sandboxExecutionAvailable: heteroType !== 'amp',
+ sandboxExecutionAvailable: heteroType === 'claude-code' || heteroType === 'codex',
trigger: requestTriggerMetadata?.trigger,
});
@@ -2144,7 +2148,7 @@ export class AiAgentService {
agentId: resolvedAgentId,
assistantMessageId: assistantMessageRecord.id,
detail:
- heteroType === 'amp'
+ heteroType === 'amp' || heteroType === 'opencode'
? 'No device bound. Pick a local or connected device in the Execution Device switcher.'
: 'No device bound. Pick a device in the Execution Device switcher, or switch to Cloud sandbox.',
message: 'No bound device for hetero agent',
@@ -2247,9 +2251,8 @@ export class AiAgentService {
};
}
} else {
- if (heteroType === 'amp') {
- const message =
- 'Amp requires a local or connected device; cloud sandbox execution is not supported.';
+ if (heteroType === 'amp' || heteroType === 'opencode') {
+ const message = `${heteroType === 'amp' ? 'Amp' : 'OpenCode'} requires a local or connected device; cloud sandbox execution is not supported.`;
await this.finalizeHeteroDispatchError({
agentId: resolvedAgentId,
assistantMessageId: assistantMessageRecord.id,
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index d87a266a40c..a14d95265e3 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -22,7 +22,7 @@ import { HeteroTraceRecorder } from './HeteroTraceRecorder';
const log = debug('lobe-server:hetero-agent-service');
-export type HeterogeneousAgentType = 'amp' | 'claude-code' | 'codex';
+export type HeterogeneousAgentType = 'amp' | 'claude-code' | 'codex' | 'opencode';
export type HeterogeneousFinishResult = 'success' | 'error' | 'cancelled';
@@ -74,7 +74,7 @@ export interface HeterogeneousAgentServiceOptions {
/**
* Server-side ingest handler for heterogeneous agent CLIs (`lh hetero exec`
- * for Amp / Claude Code / Codex). Receives `AgentStreamEvent` batches from the
+ * for Amp / Claude Code / Codex / OpenCode). Receives `AgentStreamEvent` batches from the
* producer and republishes them through the existing `StreamEventManager`
* fanout, so renderer-side gateway WS subscribers see the same wire shape
* regardless of whether the run came from the agent gateway or a CLI process.
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index b925ea8e8b5..a00f7b27669 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -344,7 +344,6 @@
"heteroAgent.codexQuota.tooltip": "View Codex quota",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} earned in total",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} earned in total",
- "heteroAgent.executionTarget.ampSandboxUnsupported": "Amp currently runs only on a local or connected device",
"heteroAgent.executionTarget.auto": "Auto",
"heteroAgent.executionTarget.autoDesc": "Use an online device automatically, picking one when several are available",
"heteroAgent.executionTarget.downloadDesktop": "Get Desktop App",
@@ -366,6 +365,7 @@
"heteroAgent.executionTarget.personalGroup": "Private Devices",
"heteroAgent.executionTarget.sandbox": "Cloud Sandbox",
"heteroAgent.executionTarget.sandboxDesc": "Run in an ephemeral cloud sandbox",
+ "heteroAgent.executionTarget.sandboxUnsupported": "{{name}} currently runs only on a local or connected device",
"heteroAgent.executionTarget.title": "Execution Device",
"heteroAgent.executionTarget.unknownDevice": "Unknown device",
"heteroAgent.executionTarget.workspaceGroup": "Workspace Devices",
@@ -612,6 +612,7 @@
"newClaudeCodeAgent": "Add Claude Code",
"newCodexAgent": "Add Codex",
"newGroupChat": "Create Group",
+ "newOpenCodeAgent": "Add OpenCode",
"newPage": "Create Page",
"newPlatformAgent": "Connect Agent",
"noAgentsYet": "This group has no members yet. Click the + button to invite agents.",
@@ -628,6 +629,15 @@
"opStatusTray.steps": "steps",
"opStatusTray.tokens": "tokens",
"openInNewWindow": "Open in New Window",
+ "opencodeInstallGuide.actions.openDocs": "Open Install Guide",
+ "opencodeInstallGuide.actions.openSystemTools": "Open System Tools",
+ "opencodeInstallGuide.afterInstall": "After installing, run OpenCode once to sign in, then retry your message or click Re-detect in System Tools.",
+ "opencodeInstallGuide.desc": "OpenCode needs its CLI to run locally. Install it and make sure the opencode command is available in your PATH.",
+ "opencodeInstallGuide.installWithBrew": "Alternative install",
+ "opencodeInstallGuide.installWithNpm": "Recommended install",
+ "opencodeInstallGuide.menuNotification.title": "OpenCode CLI not found",
+ "opencodeInstallGuide.reason": "LobeHub could not start OpenCode: {{message}}",
+ "opencodeInstallGuide.title": "Install OpenCode CLI",
"operation.contextCompression": "Context too long, compressing history...",
"operation.execAgentRuntime": "Preparing response",
"operation.execClientSubAgent": "Running sub-agent",
@@ -648,13 +658,11 @@
"platformAgent.create.back": "Back",
"platformAgent.create.checkFailed": "Check failed",
"platformAgent.create.checking": "Checking availability...",
- "platformAgent.create.comingSoon": "Coming Soon",
"platformAgent.create.create": "Connect",
"platformAgent.create.creating": "Connecting...",
"platformAgent.create.desc.amp": "Connect to Amp running on one of your devices",
"platformAgent.create.desc.hermes": "Connect to Hermes running on one of your devices",
"platformAgent.create.desc.openclaw": "Connect to OpenClaw running on one of your devices",
- "platformAgent.create.desc.opencode": "Connect to OpenCode running on one of your devices",
"platformAgent.create.descriptionPlaceholder": "Brief description (optional)",
"platformAgent.create.downloadDesktop": "Download Desktop App",
"platformAgent.create.fetchingProfile": "Fetching profile...",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 5377a56c5aa..e25ffffc6b3 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -344,7 +344,6 @@
"heteroAgent.codexQuota.tooltip": "查看 Codex 额度",
"heteroAgent.codexQuota.totalEarned_one": "累计获得 {{count}} 次",
"heteroAgent.codexQuota.totalEarned_other": "累计获得 {{count}} 次",
- "heteroAgent.executionTarget.ampSandboxUnsupported": "Amp 目前仅支持在本地设备或已连接设备上运行",
"heteroAgent.executionTarget.auto": "自动",
"heteroAgent.executionTarget.autoDesc": "自动使用在线设备,有多台时择一使用",
"heteroAgent.executionTarget.downloadDesktop": "下载桌面端",
@@ -366,6 +365,7 @@
"heteroAgent.executionTarget.personalGroup": "私人设备",
"heteroAgent.executionTarget.sandbox": "云端沙箱",
"heteroAgent.executionTarget.sandboxDesc": "在临时云端沙箱中运行",
+ "heteroAgent.executionTarget.sandboxUnsupported": "{{name}} 目前仅支持在本地设备或已连接设备上运行",
"heteroAgent.executionTarget.title": "执行设备",
"heteroAgent.executionTarget.unknownDevice": "未知设备",
"heteroAgent.executionTarget.workspaceGroup": "工作区设备",
@@ -612,6 +612,7 @@
"newClaudeCodeAgent": "添加 Claude Code",
"newCodexAgent": "添加 Codex",
"newGroupChat": "创建群组",
+ "newOpenCodeAgent": "添加 OpenCode",
"newPage": "创建文稿",
"newPlatformAgent": "接入助理",
"noAgentsYet": "这个群组还没有成员。点击「+」邀请助理加入",
@@ -628,6 +629,15 @@
"opStatusTray.steps": "步",
"opStatusTray.tokens": "tokens",
"openInNewWindow": "在新窗口打开",
+ "opencodeInstallGuide.actions.openDocs": "打开安装指南",
+ "opencodeInstallGuide.actions.openSystemTools": "打开系统工具",
+ "opencodeInstallGuide.afterInstall": "安装后,请运行一次 OpenCode 完成登录,然后重试消息或在系统工具中点击「重新检测」。",
+ "opencodeInstallGuide.desc": "OpenCode 需要通过本地 CLI 运行。请完成安装,并确保 PATH 中可以执行 opencode 命令。",
+ "opencodeInstallGuide.installWithBrew": "其他安装方式",
+ "opencodeInstallGuide.installWithNpm": "推荐安装方式",
+ "opencodeInstallGuide.menuNotification.title": "未找到 OpenCode CLI",
+ "opencodeInstallGuide.reason": "LobeHub 无法启动 OpenCode:{{message}}",
+ "opencodeInstallGuide.title": "安装 OpenCode CLI",
"operation.contextCompression": "上下文过长,正在压缩历史记录……",
"operation.execAgentRuntime": "准备响应中",
"operation.execClientSubAgent": "运行子代理中",
@@ -648,13 +658,11 @@
"platformAgent.create.back": "上一步",
"platformAgent.create.checkFailed": "检测失败",
"platformAgent.create.checking": "正在检测可用性...",
- "platformAgent.create.comingSoon": "即将推出",
"platformAgent.create.create": "接入",
"platformAgent.create.creating": "接入中...",
"platformAgent.create.desc.amp": "接入你设备上运行的 Amp",
"platformAgent.create.desc.hermes": "接入你设备上运行的 Hermes",
"platformAgent.create.desc.openclaw": "接入你设备上运行的 OpenClaw",
- "platformAgent.create.desc.opencode": "接入你设备上运行的 OpenCode",
"platformAgent.create.descriptionPlaceholder": "简短描述(可选)",
"platformAgent.create.downloadDesktop": "下载桌面端",
"platformAgent.create.fetchingProfile": "正在读取配置...",
diff --git a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts b/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts
index 204bb2caefc..a16768cd042 100644
--- a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts
+++ b/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts
@@ -5,7 +5,7 @@
* whether a target agent is fit for a job — typically "can this agent fix a bug
* in a real codebase?". For a normal model-backed agent the answer lives in
* `model` / `provider` / `plugins`. For a **heterogeneous** agent (an external
- * CLI/runtime such as Claude Code or Codex) those fields are misleading: the
+ * CLI/runtime such as Claude Code, Codex, or OpenCode) those fields are misleading: the
* agent brings its own toolset and ignores the plugin list, so we must instead
* describe what the external runtime is and what it can do.
*
diff --git a/packages/electron-client-ipc/src/types/binary.ts b/packages/electron-client-ipc/src/types/binary.ts
index 9f3b80d429f..cfdae4b0f4b 100644
--- a/packages/electron-client-ipc/src/types/binary.ts
+++ b/packages/electron-client-ipc/src/types/binary.ts
@@ -23,7 +23,7 @@ export interface BinaryInfo {
priority?: number;
}
-export type HeterogeneousCliAgentType = 'amp' | 'claude-code' | 'codex';
+export type HeterogeneousCliAgentType = 'amp' | 'claude-code' | 'codex' | 'opencode';
export interface DetectHeterogeneousAgentCommandParams {
agentType: HeterogeneousCliAgentType;
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index 4ae46f5857c..0f0d70a6221 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -1,3 +1,5 @@
+import type { HeterogeneousCliAgentType } from './binary';
+
export const AMP_CLI_INSTALL_DOCS_URL = 'https://ampcode.com/manual';
export const AMP_CLI_INSTALL_COMMANDS = [
@@ -21,6 +23,12 @@ export const CODEX_CLI_INSTALL_COMMANDS = [
'brew install --cask codex',
] as const;
+export const OPENCODE_CLI_INSTALL_DOCS_URL = 'https://opencode.ai/docs';
+
+export const OPENCODE_CLI_INSTALL_COMMANDS = [
+ 'curl -fsSL https://opencode.ai/install | bash',
+] as const;
+
export const HeterogeneousAgentSessionErrorCode = {
AuthRequired: 'auth_required',
CliNotFound: 'cli_not_found',
@@ -125,7 +133,7 @@ export interface ClaudeCodeQuotaSnapshot {
}
export interface HeterogeneousAgentSessionError {
- agentType?: string;
+ agentType?: HeterogeneousCliAgentType;
code?: HeterogeneousAgentSessionErrorCode | string;
command?: string;
/** Diagnostic context from the CLI's terminal event (subtype, HTTP status, turn count, …). */
diff --git a/packages/heterogeneous-agents/src/adapters/__fixtures__/opencode/basic.jsonl b/packages/heterogeneous-agents/src/adapters/__fixtures__/opencode/basic.jsonl
new file mode 100644
index 00000000000..7cdd1d3aae7
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/__fixtures__/opencode/basic.jsonl
@@ -0,0 +1,7 @@
+{"type":"step_start","timestamp":1,"sessionID":"ses_open_1","part":{"id":"part-start-1","sessionID":"ses_open_1","messageID":"msg-1","type":"step-start"}}
+{"type":"reasoning","timestamp":2,"sessionID":"ses_open_1","part":{"id":"part-reason-1","sessionID":"ses_open_1","messageID":"msg-1","type":"reasoning","text":"I should inspect it.","time":{"start":1,"end":2}}}
+{"type":"text","timestamp":3,"sessionID":"ses_open_1","part":{"id":"part-text-1","sessionID":"ses_open_1","messageID":"msg-1","type":"text","text":"First answer.","time":{"start":2,"end":3}}}
+{"type":"step_finish","timestamp":4,"sessionID":"ses_open_1","part":{"id":"part-finish-1","sessionID":"ses_open_1","messageID":"msg-1","type":"step-finish","reason":"tool-calls","cost":0.012,"tokens":{"total":205,"input":100,"output":50,"reasoning":20,"cache":{"read":30,"write":5}}}}
+{"type":"step_start","timestamp":5,"sessionID":"ses_open_1","part":{"id":"part-start-2","sessionID":"ses_open_1","messageID":"msg-2","type":"step-start"}}
+{"type":"text","timestamp":6,"sessionID":"ses_open_1","part":{"id":"part-text-2","sessionID":"ses_open_1","messageID":"msg-2","type":"text","text":"Second answer.","time":{"start":5,"end":6}}}
+{"type":"step_finish","timestamp":7,"sessionID":"ses_open_1","part":{"id":"part-finish-2","sessionID":"ses_open_1","messageID":"msg-2","type":"step-finish","reason":"stop","cost":0.003,"tokens":{"input":20,"output":10,"reasoning":0,"cache":{"read":50,"write":0}}}}
diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.ts
index 42c7c9e4893..3357ee86436 100644
--- a/packages/heterogeneous-agents/src/adapters/index.ts
+++ b/packages/heterogeneous-agents/src/adapters/index.ts
@@ -1,3 +1,4 @@
export { AmpAdapter } from './amp';
export { ClaudeCodeAdapter, ClaudeCodeSdkAdapter } from './claudeCode';
export { CodexAdapter } from './codex';
+export { OpenCodeAdapter } from './opencode';
diff --git a/packages/heterogeneous-agents/src/adapters/opencode.test.ts b/packages/heterogeneous-agents/src/adapters/opencode.test.ts
new file mode 100644
index 00000000000..a4be6b79d17
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/opencode.test.ts
@@ -0,0 +1,158 @@
+import { readFile } from 'node:fs/promises';
+
+import { describe, expect, it } from 'vitest';
+
+import { OpenCodeAdapter } from './opencode';
+
+const adaptJsonl = async (adapter: OpenCodeAdapter, fixture: string) => {
+ const jsonl = await readFile(
+ new URL(`./__fixtures__/opencode/${fixture}`, import.meta.url),
+ 'utf8',
+ );
+ return jsonl
+ .trim()
+ .split('\n')
+ .flatMap((line) => adapter.adapt(JSON.parse(line)));
+};
+
+describe('OpenCodeAdapter', () => {
+ it('maps completed text/reasoning blocks and multi-step usage', async () => {
+ const adapter = new OpenCodeAdapter();
+ const events = await adaptJsonl(adapter, 'basic.jsonl');
+
+ expect(adapter.sessionId).toBe('ses_open_1');
+ expect(events.map(({ type }) => type)).toEqual([
+ 'stream_start',
+ 'stream_chunk',
+ 'stream_chunk',
+ 'step_complete',
+ 'stream_end',
+ 'stream_start',
+ 'stream_chunk',
+ 'step_complete',
+ ]);
+ expect(events[1].data).toEqual({ chunkType: 'reasoning', reasoning: 'I should inspect it.' });
+ expect(events[2].data).toEqual({ chunkType: 'text', content: 'First answer.' });
+ expect(events[3].data).toEqual({
+ costUsd: 0.012,
+ phase: 'turn_metadata',
+ provider: 'opencode',
+ usage: {
+ inputCachedTokens: 30,
+ inputCacheMissTokens: 100,
+ inputWriteCacheTokens: 5,
+ outputReasoningTokens: 20,
+ outputTextTokens: 50,
+ totalInputTokens: 135,
+ totalOutputTokens: 70,
+ totalTokens: 205,
+ },
+ });
+ expect(events[7].data.usage).toMatchObject({
+ inputCacheMissTokens: 20,
+ totalInputTokens: 70,
+ totalOutputTokens: 10,
+ totalTokens: 80,
+ });
+ expect(events[7].stepIndex).toBe(1);
+ });
+
+ it.each([
+ ['completed', { output: 'done' }, false, 'done'],
+ ['error', { error: 'permission denied' }, true, 'permission denied'],
+ ])('maps a terminal %s tool exactly once', (status, result, isError, content) => {
+ const adapter = new OpenCodeAdapter();
+ const raw = {
+ part: {
+ callID: 'call-1',
+ id: 'part-tool-1',
+ state: { input: { path: '/tmp/a' }, status, ...result },
+ tool: 'read',
+ type: 'tool',
+ },
+ sessionID: 'ses-tools',
+ type: 'tool_use',
+ };
+
+ const events = adapter.adapt(raw);
+ expect(events.map(({ type }) => type)).toEqual(['stream_chunk', 'tool_result', 'tool_end']);
+ expect(events[0].data.toolsCalling[0]).toMatchObject({
+ apiName: 'read',
+ arguments: '{"path":"/tmp/a"}',
+ id: 'call-1',
+ identifier: 'opencode',
+ });
+ expect(events[1].data).toMatchObject({ content, isError, toolCallId: 'call-1' });
+ expect(events[2].data).toEqual({ isSuccess: !isError, toolCallId: 'call-1' });
+ expect(adapter.adapt(raw)).toEqual([]);
+ });
+
+ it('suppresses duplicate completed part ids', () => {
+ const adapter = new OpenCodeAdapter();
+ const raw = {
+ part: { id: 'text-1', text: 'hello', type: 'text' },
+ sessionID: 'ses-duplicate',
+ type: 'text',
+ };
+ expect(adapter.adapt(raw)).toHaveLength(1);
+ expect(adapter.adapt(raw)).toEqual([]);
+ });
+
+ it('captures session id and emits a normalized fatal error', () => {
+ const adapter = new OpenCodeAdapter();
+ const events = adapter.adapt({
+ error: { data: { message: 'Provider unavailable', statusCode: 503 }, name: 'ProviderError' },
+ sessionID: 'ses-error',
+ type: 'error',
+ });
+
+ expect(adapter.sessionId).toBe('ses-error');
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({
+ data: { agentType: 'opencode', message: 'Provider unavailable' },
+ type: 'error',
+ });
+ expect(adapter.adapt({ error: { data: { message: 'duplicate' } }, type: 'error' })).toEqual([]);
+ });
+
+ it('classifies provider authentication failures for the shared status guide', () => {
+ const adapter = new OpenCodeAdapter();
+ const events = adapter.adapt({
+ error: {
+ data: { message: 'No API key configured', providerID: 'anthropic' },
+ name: 'ProviderAuthError',
+ },
+ sessionID: 'ses-auth',
+ type: 'error',
+ });
+
+ expect(events[0]).toMatchObject({
+ data: {
+ agentType: 'opencode',
+ code: 'auth_required',
+ docsUrl: 'https://opencode.ai/docs',
+ },
+ type: 'error',
+ });
+ });
+
+ it('ignores malformed and unknown input', () => {
+ const adapter = new OpenCodeAdapter();
+ expect(adapter.adapt(null)).toEqual([]);
+ expect(adapter.adapt('bad')).toEqual([]);
+ expect(adapter.adapt({ type: 'future_event' })).toEqual([]);
+ expect(adapter.adapt({ part: {}, type: 'text' })).toEqual([]);
+ });
+
+ it('flushes only an open stream and never synthesizes runtime completion', () => {
+ const adapter = new OpenCodeAdapter();
+ expect(adapter.flush()).toEqual([]);
+ adapter.adapt({
+ part: { id: 'start-1', type: 'step-start' },
+ sessionID: 'ses-flush',
+ type: 'step_start',
+ });
+ expect(adapter.flush().map(({ type }) => type)).toEqual(['stream_end']);
+ expect(adapter.flush()).toEqual([]);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/adapters/opencode.ts b/packages/heterogeneous-agents/src/adapters/opencode.ts
new file mode 100644
index 00000000000..f3c8fc7567e
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/opencode.ts
@@ -0,0 +1,210 @@
+import type {
+ AgentEventAdapter,
+ HeterogeneousAgentEvent,
+ HeterogeneousTerminalErrorData,
+ StepCompleteData,
+ StreamStartData,
+ ToolCallPayload,
+ ToolResultData,
+ UsageData,
+} from '../types';
+
+const OPENCODE_IDENTIFIER = 'opencode';
+const OPENCODE_CLI_INSTALL_DOCS_URL = 'https://opencode.ai/docs';
+const AUTH_REQUIRED_PATTERNS = [
+ /authentication/i,
+ /not authenticated/i,
+ /unauthorized/i,
+ /invalid.*(?:credential|token|key)/i,
+];
+
+const finiteNumber = (value: unknown): number =>
+ typeof value === 'number' && Number.isFinite(value) ? value : 0;
+
+const toUsageData = (tokens: any): UsageData => {
+ const input = finiteNumber(tokens?.input);
+ const output = finiteNumber(tokens?.output);
+ const reasoning = finiteNumber(tokens?.reasoning);
+ const cacheRead = finiteNumber(tokens?.cache?.read);
+ const cacheWrite = finiteNumber(tokens?.cache?.write);
+ const totalInput = input + cacheRead + cacheWrite;
+ const totalOutput = output + reasoning;
+
+ return {
+ inputCachedTokens: cacheRead,
+ inputCacheMissTokens: input,
+ inputWriteCacheTokens: cacheWrite,
+ outputReasoningTokens: reasoning,
+ outputTextTokens: output,
+ totalInputTokens: totalInput,
+ totalOutputTokens: totalOutput,
+ totalTokens: finiteNumber(tokens?.total) || totalInput + totalOutput,
+ };
+};
+
+const errorMessage = (error: any): string =>
+ (typeof error?.data?.message === 'string' && error.data.message) ||
+ (typeof error?.message === 'string' && error.message) ||
+ (typeof error?.name === 'string' && error.name) ||
+ 'OpenCode execution failed';
+
+const isAuthError = (error: any, message: string): boolean =>
+ error?.name === 'ProviderAuthError' ||
+ error?.data?.statusCode === 401 ||
+ AUTH_REQUIRED_PATTERNS.some((pattern) => pattern.test(message));
+
+/** Maps OpenCode's completed-part JSONL protocol into shared stream events. */
+export class OpenCodeAdapter implements AgentEventAdapter {
+ sessionId?: string;
+
+ private completedPartIds = new Set<string>();
+ private completedToolCallIds = new Set<string>();
+ private started = false;
+ private stepIndex = 0;
+ private streamOpen = false;
+ private terminalErrorEmitted = false;
+
+ adapt(raw: any): HeterogeneousAgentEvent[] {
+ if (!raw || typeof raw !== 'object') return [];
+ if (typeof raw.sessionID === 'string') this.sessionId = raw.sessionID;
+
+ switch (raw.type) {
+ case 'step_start': {
+ return this.handleStepStart(raw.part);
+ }
+ case 'step_finish': {
+ return this.handleStepFinish(raw.part);
+ }
+ case 'text':
+ case 'reasoning': {
+ return this.handleContent(raw.type, raw.part);
+ }
+ case 'tool_use': {
+ return this.handleTool(raw.part);
+ }
+ case 'error': {
+ return this.handleError(raw.error);
+ }
+ default: {
+ return [];
+ }
+ }
+ }
+
+ flush(): HeterogeneousAgentEvent[] {
+ if (!this.streamOpen) return [];
+ this.streamOpen = false;
+ return [this.makeEvent('stream_end', {})];
+ }
+
+ private handleStepStart(part: any): HeterogeneousAgentEvent[] {
+ if (!part || part.type !== 'step-start' || !part.id || this.completedPartIds.has(part.id)) {
+ return [];
+ }
+ this.completedPartIds.add(part.id);
+
+ const events: HeterogeneousAgentEvent[] = [];
+ if (this.started) {
+ if (this.streamOpen) events.push(this.makeEvent('stream_end', {}));
+ this.stepIndex += 1;
+ } else {
+ this.started = true;
+ }
+ this.streamOpen = true;
+ const data: StreamStartData = { provider: OPENCODE_IDENTIFIER, sessionId: this.sessionId };
+ events.push(this.makeEvent('stream_start', data));
+ return events;
+ }
+
+ private handleContent(type: 'reasoning' | 'text', part: any): HeterogeneousAgentEvent[] {
+ if (!part || part.type !== type || !part.id || this.completedPartIds.has(part.id)) return [];
+ this.completedPartIds.add(part.id);
+ if (typeof part.text !== 'string' || !part.text) return [];
+
+ return [
+ this.makeEvent(
+ 'stream_chunk',
+ type === 'text'
+ ? { chunkType: 'text', content: part.text }
+ : { chunkType: 'reasoning', reasoning: part.text },
+ ),
+ ];
+ }
+
+ private handleStepFinish(part: any): HeterogeneousAgentEvent[] {
+ if (!part || part.type !== 'step-finish' || !part.id || this.completedPartIds.has(part.id)) {
+ return [];
+ }
+ this.completedPartIds.add(part.id);
+ const data: StepCompleteData = {
+ costUsd: finiteNumber(part.cost),
+ phase: 'turn_metadata',
+ provider: OPENCODE_IDENTIFIER,
+ usage: toUsageData(part.tokens),
+ };
+ return [this.makeEvent('step_complete', data)];
+ }
+
+ private handleTool(part: any): HeterogeneousAgentEvent[] {
+ const state = part?.state;
+ const callId = part?.callID;
+ if (
+ part?.type !== 'tool' ||
+ typeof callId !== 'string' ||
+ this.completedToolCallIds.has(callId) ||
+ (state?.status !== 'completed' && state?.status !== 'error')
+ ) {
+ return [];
+ }
+ this.completedToolCallIds.add(callId);
+ if (part.id) this.completedPartIds.add(part.id);
+
+ const tool: ToolCallPayload = {
+ apiName: typeof part.tool === 'string' ? part.tool : 'unknown',
+ arguments: JSON.stringify(state.input ?? {}),
+ id: callId,
+ identifier: OPENCODE_IDENTIFIER,
+ type: 'default',
+ };
+ const isError = state.status === 'error';
+ const result: ToolResultData = {
+ content: isError ? String(state.error ?? '') : String(state.output ?? ''),
+ isError,
+ toolCallId: callId,
+ };
+
+ return [
+ this.makeEvent('stream_chunk', { chunkType: 'tools_calling', toolsCalling: [tool] }),
+ this.makeEvent('tool_result', result),
+ this.makeEvent('tool_end', { isSuccess: !isError, toolCallId: callId }),
+ ];
+ }
+
+ private handleError(error: any): HeterogeneousAgentEvent[] {
+ if (this.terminalErrorEmitted) return [];
+ this.terminalErrorEmitted = true;
+ const message = errorMessage(error);
+ const authRequired = isAuthError(error, message);
+ const data: HeterogeneousTerminalErrorData = {
+ agentType: OPENCODE_IDENTIFIER,
+ clearEchoedContent: true,
+ ...(authRequired ? { code: 'auth_required', docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL } : {}),
+ details: error && typeof error === 'object' ? error : undefined,
+ message: authRequired
+ ? 'OpenCode could not authenticate. Sign in again or refresh its credentials, then retry.'
+ : message,
+ stderr: message,
+ };
+ const events: HeterogeneousAgentEvent[] = [];
+ if (this.streamOpen) {
+ this.streamOpen = false;
+ events.push(this.makeEvent('stream_end', {}));
+ }
+ events.push(this.makeEvent('error', data));
+ return events;
+ }
+
+ private makeEvent(type: HeterogeneousAgentEvent['type'], data: any): HeterogeneousAgentEvent {
+ return { data, stepIndex: this.stepIndex, timestamp: Date.now(), type };
+ }
+}
diff --git a/packages/heterogeneous-agents/src/client/index.ts b/packages/heterogeneous-agents/src/client/index.ts
index 6b1b6b19b61..d10dc4b2763 100644
--- a/packages/heterogeneous-agents/src/client/index.ts
+++ b/packages/heterogeneous-agents/src/client/index.ts
@@ -1,5 +1,5 @@
import type { IconType } from '@lobehub/icons';
-import { Amp, ClaudeCode, Codex, getLobeIconCDN } from '@lobehub/icons';
+import { Amp, ClaudeCode, Codex, getLobeIconCDN, OpenCode } from '@lobehub/icons';
import {
getHeterogeneousAgentConfig,
@@ -19,6 +19,7 @@ const heterogeneousAgentIcons = {
'amp': Amp,
'claude-code': ClaudeCode,
'codex': Codex,
+ 'opencode': OpenCode,
} as const satisfies Record<HeterogeneousAgentConfig['type'], IconType>;
const createAgentAvatar = (iconId: string) =>
diff --git a/packages/heterogeneous-agents/src/config.test.ts b/packages/heterogeneous-agents/src/config.test.ts
index 6518ce03dc3..9f7c278963b 100644
--- a/packages/heterogeneous-agents/src/config.test.ts
+++ b/packages/heterogeneous-agents/src/config.test.ts
@@ -13,6 +13,7 @@ describe('heterogeneous agent config', () => {
'claude-code',
'codex',
'amp',
+ 'opencode',
]);
});
@@ -32,6 +33,11 @@ describe('heterogeneous agent config', () => {
title: 'Amp',
type: 'amp',
});
+ expect(getHeterogeneousAgentConfig('opencode')).toMatchObject({
+ command: 'opencode',
+ title: 'OpenCode',
+ type: 'opencode',
+ });
});
it('derives display labels from the shared config source', () => {
@@ -45,8 +51,10 @@ describe('heterogeneous agent config', () => {
});
});
- it('classifies AMP as a local CLI rather than a remote platform', () => {
+ it('classifies local CLIs separately from remote platforms', () => {
expect(isRemoteHeterogeneousType('amp')).toBe(false);
+ expect(isRemoteHeterogeneousType('opencode')).toBe(false);
expect(isRemoteHeterogeneousType('openclaw')).toBe(true);
+ expect(isRemoteHeterogeneousType('hermes')).toBe(true);
});
});
diff --git a/packages/heterogeneous-agents/src/config.ts b/packages/heterogeneous-agents/src/config.ts
index 9f2e2ee3392..b5bab4878f4 100644
--- a/packages/heterogeneous-agents/src/config.ts
+++ b/packages/heterogeneous-agents/src/config.ts
@@ -1,7 +1,8 @@
-export type HeterogeneousAgentMenuLabelKey = 'newAmpAgent' | 'newClaudeCodeAgent' | 'newCodexAgent';
+export type HeterogeneousAgentMenuLabelKey =
+ 'newAmpAgent' | 'newClaudeCodeAgent' | 'newCodexAgent' | 'newOpenCodeAgent';
/**
- * Config for local CLI hetero agents (Amp, Claude Code, Codex) that run as
+ * Config for local CLI hetero agents (Amp, Claude Code, Codex, OpenCode) that run as
* desktop subprocesses via Electron IPC. Remote device agents (openclaw,
* hermes) have their own setup flow and are not listed here.
*/
@@ -11,7 +12,7 @@ export interface HeterogeneousAgentConfig {
menuKey: string;
menuLabelKey: HeterogeneousAgentMenuLabelKey;
title: string;
- type: 'amp' | 'claude-code' | 'codex';
+ type: 'amp' | 'claude-code' | 'codex' | 'opencode';
}
export const HETEROGENEOUS_AGENT_CONFIGS = [
@@ -39,6 +40,14 @@ export const HETEROGENEOUS_AGENT_CONFIGS = [
title: 'Amp',
type: 'amp',
},
+ {
+ command: 'opencode',
+ iconId: 'OpenCode',
+ menuKey: 'newOpenCodeAgent',
+ menuLabelKey: 'newOpenCodeAgent',
+ title: 'OpenCode',
+ type: 'opencode',
+ },
] as const satisfies readonly HeterogeneousAgentConfig[];
export const getHeterogeneousAgentConfig = (type: string) =>
@@ -53,13 +62,12 @@ export const getHeterogeneousAgentConfig = (type: string) =>
*/
export interface RemoteHeterogeneousAgentConfig {
title: string;
- type: 'hermes' | 'opencode' | 'openclaw';
+ type: 'hermes' | 'openclaw';
}
export const REMOTE_HETEROGENEOUS_AGENT_CONFIGS = [
{ title: 'OpenClaw', type: 'openclaw' },
{ title: 'Hermes', type: 'hermes' },
- { title: 'OpenCode', type: 'opencode' },
] as const satisfies readonly RemoteHeterogeneousAgentConfig[];
/** Union of all local CLI hetero types. */
@@ -74,6 +82,6 @@ export type HeterogeneousAgentType = LocalHeterogeneousAgentType | RemoteHeterog
const REMOTE_HETERO_TYPES = new Set<string>(REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((c) => c.type));
-/** Returns true when `type` identifies a remote platform agent (openclaw, hermes, …). */
+/** Returns true when `type` identifies a remote platform agent (OpenClaw or Hermes). */
export const isRemoteHeterogeneousType = (type: string): type is RemoteHeterogeneousAgentType =>
REMOTE_HETERO_TYPES.has(type);
diff --git a/packages/heterogeneous-agents/src/registry.test.ts b/packages/heterogeneous-agents/src/registry.test.ts
index e40ca09dc33..2b215235386 100644
--- a/packages/heterogeneous-agents/src/registry.test.ts
+++ b/packages/heterogeneous-agents/src/registry.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { AmpAdapter, ClaudeCodeAdapter, CodexAdapter } from './adapters';
+import { AmpAdapter, ClaudeCodeAdapter, CodexAdapter, OpenCodeAdapter } from './adapters';
import { createAdapter, listAgentTypes } from './registry';
describe('registry', () => {
@@ -20,6 +20,10 @@ describe('registry', () => {
expect(adapter).toBeInstanceOf(CodexAdapter);
});
+ it('creates an OpenCodeAdapter for "opencode"', () => {
+ expect(createAdapter('opencode')).toBeInstanceOf(OpenCodeAdapter);
+ });
+
it('throws for unknown agent type', () => {
expect(() => createAdapter('unknown-agent')).toThrow('Unknown agent type: "unknown-agent"');
});
@@ -31,6 +35,7 @@ describe('registry', () => {
expect(types).toContain('amp');
expect(types).toContain('claude-code');
expect(types).toContain('codex');
+ expect(types).toContain('opencode');
});
});
});
diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.ts
index ef1eee01f32..74bde5ef36b 100644
--- a/packages/heterogeneous-agents/src/registry.ts
+++ b/packages/heterogeneous-agents/src/registry.ts
@@ -5,7 +5,13 @@
* by registering here — no other code changes needed.
*/
-import { AmpAdapter, ClaudeCodeAdapter, ClaudeCodeSdkAdapter, CodexAdapter } from './adapters';
+import {
+ AmpAdapter,
+ ClaudeCodeAdapter,
+ ClaudeCodeSdkAdapter,
+ CodexAdapter,
+ OpenCodeAdapter,
+} from './adapters';
import type { AgentEventAdapter } from './types';
interface AgentRegistryEntry {
@@ -25,6 +31,9 @@ const registry: Record<string, AgentRegistryEntry> = {
'codex': {
createAdapter: () => new CodexAdapter(),
},
+ 'opencode': {
+ createAdapter: () => new OpenCodeAdapter(),
+ },
// 'kimi-cli': { createAdapter: () => new KimiCLIAdapter() },
};
diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
index 97a552b1ca9..ebf6d5308c4 100644
--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
@@ -21,6 +21,13 @@ describe('isHeteroStatusGuideErrorData', () => {
message: 'usage limit reached',
}),
).toBe(true);
+ expect(
+ isHeteroStatusGuideErrorData({
+ agentType: 'opencode',
+ code: 'auth_required',
+ message: 'ProviderAuthError',
+ }),
+ ).toBe(true);
});
it('rejects payloads missing the agentType/code pair or outside the guide sets', () => {
@@ -67,6 +74,17 @@ describe('classifyHeteroProcessFailure', () => {
expect(result?.message).toContain('`codex`');
});
+ it('classifies a missing OpenCode binary for the install guide', () => {
+ const result = classifyHeteroProcessFailure({
+ agentType: 'opencode',
+ detail: 'Error: spawn opencode ENOENT',
+ errnoCode: 'ENOENT',
+ });
+
+ expect(result).toMatchObject({ agentType: 'opencode', code: 'cli_not_found' });
+ expect(result?.message).toContain('`opencode`');
+ });
+
it('does NOT treat an in-run ENOENT (no spawn context) as cli_not_found', () => {
const result = classifyHeteroProcessFailure({
agentType: 'claude-code',
diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
index 4cc45809a81..2d97127c262 100644
--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
@@ -44,6 +44,8 @@ const CLI_NOT_FOUND_MESSAGES: Record<string, string> = {
'Claude Code CLI was not found on the machine running this agent. Install it and make sure `claude` can be executed.',
'codex':
'Codex CLI was not found on the machine running this agent. Install it and make sure `codex` can be executed.',
+ 'opencode':
+ 'OpenCode CLI was not found on the machine running this agent. Install it and make sure `opencode` can be executed.',
};
const AUTH_REQUIRED_MESSAGES: Record<string, string> = {
@@ -51,6 +53,8 @@ const AUTH_REQUIRED_MESSAGES: Record<string, string> = {
'Claude Code could not authenticate on the machine running this agent. Sign in again or refresh its credentials, then retry.',
'codex':
'Codex could not authenticate on the machine running this agent. Sign in again or refresh its credentials, then retry.',
+ 'opencode':
+ 'OpenCode could not authenticate on the machine running this agent. Sign in again or refresh its credentials, then retry.',
};
/**
@@ -65,7 +69,7 @@ const STATUS_GUIDE_ERROR_CODES = new Set([
'overloaded',
'rate_limit',
]);
-const STATUS_GUIDE_AGENT_TYPES = new Set(['amp', 'claude-code', 'codex']);
+const STATUS_GUIDE_AGENT_TYPES = new Set(['amp', 'claude-code', 'codex', 'opencode']);
/**
* Whether a terminal error payload (an adapter's in-stream `error` event data,
@@ -88,7 +92,7 @@ export const isHeteroStatusGuideErrorData = (
};
export interface ClassifyHeteroProcessFailureParams {
- /** Adapter type key — only `claude-code` / `codex` have a status guide. */
+ /** Adapter type key for a local CLI with a status guide. */
agentType: string;
/** Stderr tail / flattened error message to pattern-match. */
detail?: string;
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 182010eaf82..cb71c0a2547 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -78,6 +78,7 @@ export {
CODEX_DEFAULT_EXECUTION_ARGS,
CODEX_EXECUTION_MODE_FLAGS,
CODEX_REQUIRED_ARGS,
+ OPENCODE_BASE_ARGS,
spawnAgent,
type SpawnAgentHandle,
type SpawnAgentOptions,
diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts
index f6138cf120c..899f1c91c71 100644
--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts
@@ -242,6 +242,35 @@ describe('buildAgentInput', () => {
});
});
+ describe('opencode', () => {
+ it('uses raw text stdin and repeatable --file flags', async () => {
+ const filePath = path.join(tmp, 'opencode.png');
+ await writeFile(filePath, PNG_BYTES);
+ const plan = await buildAgentInput('opencode', [
+ { text: 'first', type: 'text' },
+ { source: { path: filePath, type: 'path' }, type: 'image' },
+ { text: 'second', type: 'text' },
+ ]);
+
+ expect(plan).toEqual({ args: ['--file', filePath], stdin: 'first\n\nsecond' });
+ });
+
+ it('materializes base64 images through the shared path-input helper', async () => {
+ const plan = await buildAgentInput(
+ 'opencode',
+ [
+ {
+ source: { data: PNG_BYTES.toString('base64'), mediaType: 'image/png', type: 'base64' },
+ type: 'image',
+ },
+ ],
+ { cacheDir: tmp },
+ );
+ expect(plan.args[0]).toBe('--file');
+ expect(plan.args[1]).toMatch(/\.png$/);
+ });
+ });
+
it('throws on unknown agent types', async () => {
await expect(buildAgentInput('kimi-cli', 'hi')).rejects.toThrow(/unsupported agent type/);
});
diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts
index e86f5533fd9..cf81d5dcb04 100644
--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts
+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts
@@ -12,7 +12,7 @@ import { materializeImageToPath, normalizeImage } from './normalizeImage';
export interface BuildAgentInputOptions extends NormalizeImageOptions {
/**
- * Directory used to materialize images for path-based agents (Codex). When
+ * Directory used to materialize images for path-based agents (Codex/OpenCode). When
* unset, falls back to `cacheDir`, then to a per-agent subdirectory under
* the OS tmpdir. Path-input images skip materialization entirely.
*/
@@ -82,7 +82,7 @@ const buildClaudeCodeStdin = async (
};
};
-const resolveCodexImagePaths = async (
+const resolvePathInputImagePaths = async (
blocks: AgentContentBlock[],
options: BuildAgentInputOptions,
): Promise<string[]> => {
@@ -113,7 +113,7 @@ const buildCodexInput = async (
options: BuildAgentInputOptions,
): Promise<AgentInputPlan> => {
const text = collectText(blocks);
- const imagePaths = await resolveCodexImagePaths(blocks, options);
+ const imagePaths = await resolvePathInputImagePaths(blocks, options);
return {
args: imagePaths.flatMap((p) => ['--image', p]),
@@ -121,6 +121,17 @@ const buildCodexInput = async (
};
};
+const buildOpenCodeInput = async (
+ blocks: AgentContentBlock[],
+ options: BuildAgentInputOptions,
+): Promise<AgentInputPlan> => {
+ const imagePaths = await resolvePathInputImagePaths(blocks, options);
+ return {
+ args: imagePaths.flatMap((imagePath) => ['--file', imagePath]),
+ stdin: collectText(blocks),
+ };
+};
+
/**
* Convert a unified `AgentPromptInput` into the per-agent stdin payload + any
* extra CLI args required to attach images. The single source of truth for
@@ -128,6 +139,7 @@ const buildCodexInput = async (
*
* - `amp` / `claude-code`: stream-json on stdin with text + base64 image content blocks
* - `codex`: raw text on stdin + repeatable `--image <path>` flags
+ * - `opencode`: raw text on stdin + repeatable `--file <path>` flags
*
* Path-mode agents materialize URL / base64 images via `materializeImageToPath`
* into `imageMaterializeDir` (defaults to `cacheDir` then `os.tmpdir()`).
@@ -147,6 +159,9 @@ export const buildAgentInput = async (
case 'codex': {
return buildCodexInput(blocks, options);
}
+ case 'opencode': {
+ return buildOpenCodeInput(blocks, options);
+ }
default: {
throw new Error(`buildAgentInput: unsupported agent type "${agentType}"`);
}
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
index f2b00f365ce..ecef4826d3c 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
@@ -90,6 +90,45 @@ describe('resolveCliCommand', () => {
expect(execMock).not.toHaveBeenCalled();
});
+ it('resolves and validates OpenCode using its bare semver output', async () => {
+ callExecFile('/Users/x/.opencode/bin/opencode\n');
+ callExecFile('1.18.3');
+
+ const { detectHeterogeneousCliCommand } = await importModule();
+ const status = await detectHeterogeneousCliCommand('opencode', 'opencode');
+
+ expect(status).toMatchObject({
+ available: true,
+ path: '/Users/x/.opencode/bin/opencode',
+ version: '1.18.3',
+ });
+ });
+
+ it('finds OpenCode in its well-known user-local install path', async () => {
+ const originalPath = process.env.PATH;
+ const originalShell = process.env.SHELL;
+ process.env.PATH = '/usr/bin:/bin';
+ delete process.env.SHELL;
+
+ try {
+ callExecFileError(new Error('not found')); // which opencode
+ callExecFile('1.18.3'); // ~/.opencode/bin/opencode --version
+
+ const { detectHeterogeneousCliCommand } = await importModule();
+ const status = await detectHeterogeneousCliCommand('opencode', 'opencode');
+
+ expect(status).toMatchObject({
+ available: true,
+ path: path.join(os.homedir(), '.opencode', 'bin', 'opencode'),
+ version: '1.18.3',
+ });
+ } finally {
+ process.env.PATH = originalPath;
+ if (originalShell === undefined) delete process.env.SHELL;
+ else process.env.SHELL = originalShell;
+ }
+ });
+
it('falls through a PATH `codex` that fails validation to the ChatGPT.app bundled CLI', async () => {
const originalPath = process.env.PATH;
const originalShell = process.env.SHELL;
@@ -260,6 +299,11 @@ describe('resolveCliCommand', () => {
expect(resolved.command).toBe('/Users/x/.local/bin/amp');
});
+ it('defines opencode as the default OpenCode command', async () => {
+ const { DEFAULT_HETERO_COMMAND } = await importModule();
+ expect(DEFAULT_HETERO_COMMAND.opencode).toBe('opencode');
+ });
+
it('resolves the default bare command to the validated absolute path', async () => {
callExecFile('/usr/local/bin/codex\n');
callExecFile('codex-cli 0.142.5');
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
index 90b723771e7..3515ef06a06 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
@@ -4,7 +4,7 @@ import path from 'node:path';
import { promisify } from 'node:util';
/**
- * Shared resolver for the external CLI-agent binaries (Amp / Claude Code / Codex).
+ * Shared resolver for external CLI-agent binaries (Amp / Claude Code / Codex / OpenCode).
*
* This is the single source of truth for "given a command name, where is the
* runnable binary?". It's consumed by BOTH spawn sites:
@@ -20,7 +20,7 @@ import { promisify } from 'node:util';
const execFilePromise = promisify(execFile);
const execPromise = promisify(exec);
-export type HeterogeneousCliAgentType = 'amp' | 'claude-code' | 'codex';
+export type HeterogeneousCliAgentType = 'amp' | 'claude-code' | 'codex' | 'opencode';
/**
* Resolution result. A structural subset of the desktop `BinaryManager`'s
@@ -43,7 +43,8 @@ export interface CliCommandStatus {
interface ValidateOptions {
validateFlag?: string;
- validateKeywords: string[];
+ validateKeywords?: string[];
+ validatePattern?: RegExp;
}
interface ResolvedCommand {
@@ -178,8 +179,8 @@ const resolveCommandPath = async (command: string): Promise<ResolvedCommand | un
/**
* Resolve a command via which/where, then confirm it's the binary we expect by
- * matching `--version` output against a keyword (avoids collisions with an
- * unrelated executable of the same name).
+ * matching `--version` output against a keyword or output pattern (avoids
+ * collisions with an unrelated executable of the same name).
*/
export const detectValidatedCommand = async (
command: string,
@@ -189,7 +190,7 @@ export const detectValidatedCommand = async (
if (!trimmedCommand) return { available: false };
if (isWindows() && WINDOWS_SHELL_METAS.test(trimmedCommand)) return { available: false };
- const { validateFlag = '--version', validateKeywords } = options;
+ const { validateFlag = '--version', validateKeywords, validatePattern } = options;
// Resolve via where/which BEFORE invoking. On Windows this is what discovers
// npm-installed shims like `claude.cmd` under %APPDATA%\npm — `execFile`
@@ -214,8 +215,12 @@ export const detectValidatedCommand = async (
});
const output = `${stdout}\n${stderr}`.trim();
const loweredOutput = output.toLowerCase();
+ const matchesKeyword = validateKeywords?.some((keyword) =>
+ loweredOutput.includes(keyword.toLowerCase()),
+ );
+ const matchesPattern = validatePattern?.test(output);
- if (!validateKeywords.some((keyword) => loweredOutput.includes(keyword.toLowerCase()))) {
+ if (!matchesKeyword && !matchesPattern) {
return { available: false };
}
@@ -245,6 +250,11 @@ const HETEROGENEOUS_CLI_AGENT_OPTIONS = {
'codex': {
validateKeywords: ['codex'],
},
+ 'opencode': {
+ // OpenCode prints only a bare version (for example `1.18.3`) for
+ // `--version`, without a product-name prefix.
+ validatePattern: /^v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/,
+ },
} as const satisfies Record<HeterogeneousCliAgentType, ValidateOptions>;
// The default (bare) command each agent type is shipped to run. The well-known
@@ -254,6 +264,7 @@ export const DEFAULT_HETERO_COMMAND: Record<HeterogeneousCliAgentType, string> =
'amp': 'amp',
'claude-code': 'claude',
'codex': 'codex',
+ 'opencode': 'opencode',
};
// Well-known absolute install locations probed when a bare command isn't on
@@ -297,6 +308,17 @@ const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[
];
});
}
+ case 'opencode': {
+ if (platform() !== 'darwin' && platform() !== 'linux') return [];
+
+ return [
+ path.join(homedir(), '.opencode', 'bin', 'opencode'),
+ path.join(homedir(), '.local', 'bin', 'opencode'),
+ path.join(homedir(), '.bun', 'bin', 'opencode'),
+ path.join(homedir(), '.npm-global', 'bin', 'opencode'),
+ path.join(homedir(), 'Library', 'pnpm', 'opencode'),
+ ];
+ }
default: {
return [];
}
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
index ce1d1a6e5a2..b930db45071 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
@@ -284,6 +284,58 @@ describe('spawnAgent', () => {
expect(args.at(-1)).toBe('-');
});
+ it('spawns OpenCode fresh with JSON thinking/auto flags and raw stdin', async () => {
+ nextFakeProc = createFakeProc().proc;
+ const { OPENCODE_BASE_ARGS, spawnAgent } = await import('./spawnAgent');
+ await spawnAgent({
+ agentType: 'opencode',
+ extraArgs: ['--model', 'anthropic/claude-sonnet-4'],
+ operationId: 'op-open',
+ prompt: 'hello opencode',
+ });
+
+ expect(spawnCalls[0]).toMatchObject({ command: 'opencode' });
+ expect(spawnCalls[0].args).toEqual([
+ ...OPENCODE_BASE_ARGS,
+ '--model',
+ 'anthropic/claude-sonnet-4',
+ ]);
+ expect((nextFakeProc as any).stdin.write.mock.calls[0][0]).toBe('hello opencode');
+ });
+
+ it('spawns OpenCode resume with --session and --file before extra args', async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'lobe-opencode-spawn-'));
+ tempDirs.push(dir);
+ const imagePath = path.join(dir, 'input.png');
+ await writeFile(imagePath, 'image');
+ nextFakeProc = createFakeProc().proc;
+ const { spawnAgent } = await import('./spawnAgent');
+ await spawnAgent({
+ agentType: 'opencode',
+ extraArgs: ['--model', 'openai/gpt-5'],
+ operationId: 'op-open',
+ prompt: [
+ { text: 'continue', type: 'text' },
+ { source: { path: imagePath, type: 'path' }, type: 'image' },
+ ],
+ resumeSessionId: 'ses_previous',
+ });
+
+ expect(spawnCalls[0].args).toEqual([
+ 'run',
+ '--format',
+ 'json',
+ '--thinking',
+ '--auto',
+ '--session',
+ 'ses_previous',
+ '--file',
+ imagePath,
+ '--model',
+ 'openai/gpt-5',
+ ]);
+ });
+
it('seeds a real Codex resumed stream with the previous cumulative usage from the session file', async () => {
const threadId = '019dba1e-eec2-7a22-bdfb-ac6175e03081';
const realCodexFixture = await readFile(
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index 7c840018058..2759a685f39 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -10,7 +10,7 @@ import type { AgentPromptInput, BuildAgentInputOptions } from './input';
import { buildAgentInput } from './input';
export interface SpawnAgentOptions {
- /** Agent type key (`'amp'` | `'claude-code'` | `'codex'`). */
+ /** Agent type key (`'amp'` | `'claude-code'` | `'codex'` | `'opencode'`). */
agentType: string;
/**
* Override the CLI binary name. Defaults to the agent's standard executable.
@@ -176,6 +176,8 @@ export const AMP_BASE_ARGS = [
'--no-archive-after-execute',
] as const;
+export const OPENCODE_BASE_ARGS = ['run', '--format', 'json', '--thinking', '--auto'] as const;
+
const hasAnyFlag = (args: string[], flags: readonly string[]) =>
args.some((arg) => flags.includes(arg as (typeof flags)[number]));
@@ -224,6 +226,13 @@ const buildAmpArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawnArgsP
: executionArgs;
};
+const buildOpenCodeArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawnArgsParams) => [
+ ...OPENCODE_BASE_ARGS,
+ ...(resumeSessionId ? ['--session', resumeSessionId] : []),
+ ...inputArgs,
+ ...extraArgs,
+];
+
const buildSpawnArgs = (params: BuildSpawnArgsParams): string[] => {
switch (params.agentType) {
case 'amp': {
@@ -235,6 +244,9 @@ const buildSpawnArgs = (params: BuildSpawnArgsParams): string[] => {
case 'codex': {
return buildCodexArgs(params);
}
+ case 'opencode': {
+ return buildOpenCodeArgs(params);
+ }
default: {
throw new Error(`spawnAgent: unsupported agent type "${params.agentType}"`);
}
@@ -249,6 +261,9 @@ const defaultCommand = (agentType: string): string => {
case 'codex': {
return 'codex';
}
+ case 'opencode': {
+ return 'opencode';
+ }
default: {
return 'claude';
}
@@ -283,7 +298,7 @@ const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {
};
/**
- * Spawn an external agent CLI (Amp, Claude Code, or Codex) and yield its stream as
+ * Spawn an external agent CLI (Amp, Claude Code, Codex, or OpenCode) and yield its stream as
* unified `AgentStreamEvent`s. Used by `lh hetero exec` for both standalone
* terminal runs and (later) sandbox-driven runs that ingest into the server.
*
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index c57b1351136..ec707905131 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -7,7 +7,8 @@
*
* Architecture:
* Claude Code stream-json ──→ ClaudeCodeAdapter ──→ HeterogeneousAgentEvent[]
- * Codex CLI output ──→ CodexAdapter ──→ HeterogeneousAgentEvent[] (future)
+ * Codex CLI output ──→ CodexAdapter ──→ HeterogeneousAgentEvent[]
+ * OpenCode JSONL ──→ OpenCodeAdapter ──→ HeterogeneousAgentEvent[]
* ACP JSON-RPC ──→ ACPAdapter ──→ HeterogeneousAgentEvent[] (future)
*/
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 3157627d0eb..5e3d649ae06 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -381,8 +381,8 @@ export default {
'heteroAgent.cloudRepo.notSet': 'No repo selected',
'heteroAgent.cloudRepo.noRepos': 'No repositories configured. Add them in agent settings.',
'heteroAgent.cloudRepo.multiSelected': '{{count}} repos selected',
- 'heteroAgent.executionTarget.ampSandboxUnsupported':
- 'Amp currently runs only on a local or connected device',
+ 'heteroAgent.executionTarget.sandboxUnsupported':
+ '{{name}} currently runs only on a local or connected device',
'heteroAgent.executionTarget.auto': 'Auto',
'heteroAgent.executionTarget.autoDesc':
'Use an online device automatically, picking one when several are available',
@@ -698,11 +698,23 @@ export default {
'codexInstallGuide.menuNotification.title': 'Codex CLI not found',
'codexInstallGuide.reason': 'LobeHub could not start Codex: {{message}}',
'codexInstallGuide.title': 'Install Codex CLI',
+ 'opencodeInstallGuide.actions.openDocs': 'Open Install Guide',
+ 'opencodeInstallGuide.actions.openSystemTools': 'Open System Tools',
+ 'opencodeInstallGuide.afterInstall':
+ 'After installing, run OpenCode once to sign in, then retry your message or click Re-detect in System Tools.',
+ 'opencodeInstallGuide.desc':
+ 'OpenCode needs its CLI to run locally. Install it and make sure the opencode command is available in your PATH.',
+ 'opencodeInstallGuide.installWithBrew': 'Alternative install',
+ 'opencodeInstallGuide.installWithNpm': 'Recommended install',
+ 'opencodeInstallGuide.menuNotification.title': 'OpenCode CLI not found',
+ 'opencodeInstallGuide.reason': 'LobeHub could not start OpenCode: {{message}}',
+ 'opencodeInstallGuide.title': 'Install OpenCode CLI',
'addAgentFromMarket': 'Add from Market',
'newAgent': 'Create Agent',
'newAmpAgent': 'Add Amp',
'newClaudeCodeAgent': 'Add Claude Code',
'newCodexAgent': 'Add Codex',
+ 'newOpenCodeAgent': 'Add OpenCode',
'newPlatformAgent': 'Connect Agent',
'newGroupChat': 'Create Group',
'agent.publishToWorkspace': 'Publish to Workspace',
@@ -735,7 +747,6 @@ export default {
'platformAgent.create.desc.openclaw': 'Connect to OpenClaw running on one of your devices',
'platformAgent.create.desc.hermes': 'Connect to Hermes running on one of your devices',
'platformAgent.create.desc.amp': 'Connect to Amp running on one of your devices',
- 'platformAgent.create.desc.opencode': 'Connect to OpenCode running on one of your devices',
// Connect agent: shared device status label (used in Select option labels)
'platformAgent.device.online': 'Online',
@@ -767,7 +778,6 @@ export default {
'platformAgent.create.versionTooLow': 'lh version is too low',
'platformAgent.create.versionTooLowHint': 'Update lh to the latest version:',
'platformAgent.create.upgradeCmd': 'npm install -g @lobehub/cli',
- 'platformAgent.create.comingSoon': 'Coming Soon',
// Connect agent device guard banner
'platformAgent.deviceGuard.deviceOffline.title': 'Device not connected',
diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.ts
index 4cc58e4dfa5..90ca30e2ad0 100644
--- a/packages/types/src/agent/agencyConfig.test.ts
+++ b/packages/types/src/agent/agencyConfig.test.ts
@@ -78,6 +78,52 @@ describe('buildHeteroSpawnArgs', () => {
expect(buildHeteroExecArgs(provider)).toEqual(['--agent-arg=--mode', '--agent-arg=high']);
});
+ it('forwards OpenCode native args and an explicit provider/model selection', () => {
+ const provider: HeterogeneousProviderConfig = {
+ args: ['--variant', 'high'],
+ model: 'anthropic/claude-sonnet-4',
+ type: 'opencode',
+ };
+
+ expect(buildHeteroSpawnArgs(provider)).toEqual([
+ '--variant',
+ 'high',
+ '--model',
+ 'anthropic/claude-sonnet-4',
+ ]);
+ expect(buildHeteroExecArgs(provider)).toEqual([
+ '--agent-arg=--variant',
+ '--agent-arg=high',
+ '--model',
+ 'anthropic/claude-sonnet-4',
+ ]);
+ });
+
+ it('does not duplicate an OpenCode model already present in native args', () => {
+ const provider: HeterogeneousProviderConfig = {
+ args: ['--model=google/gemini-2.5-pro'],
+ model: 'anthropic/claude-sonnet-4',
+ type: 'opencode',
+ };
+
+ expect(buildHeteroSpawnArgs(provider)).toEqual(['--model=google/gemini-2.5-pro']);
+ expect(buildHeteroExecArgs(provider)).toEqual(['--agent-arg=--model=google/gemini-2.5-pro']);
+ });
+
+ it('honors the OpenCode short model flag in native args', () => {
+ const provider: HeterogeneousProviderConfig = {
+ args: ['-m', 'google/gemini-2.5-pro'],
+ model: 'anthropic/claude-sonnet-4',
+ type: 'opencode',
+ };
+
+ expect(buildHeteroSpawnArgs(provider)).toEqual(['-m', 'google/gemini-2.5-pro']);
+ expect(buildHeteroExecArgs(provider)).toEqual([
+ '--agent-arg=-m',
+ '--agent-arg=google/gemini-2.5-pro',
+ ]);
+ });
+
it('preserves Claude Code defaults when model/effort have not been selected', () => {
expect(buildHeteroSpawnArgs({ type: 'claude-code' })).toBeUndefined();
expect(buildHeteroSpawnArgs({ args: ['--verbose'], type: 'claude-code' })).toEqual([
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index 9c14e2a77b4..e4761437ee2 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -98,10 +98,11 @@ const CODEX_FAST_SERVICE_TIER_VALUES = ['fast', 'priority'] as const;
*
* Two families of hetero agents are supported:
*
- * - **Local CLI** (`amp` | `claude-code` | `codex`): spawned as a child process on the
- * desktop; uses `command`, `args`, `env`, `systemContext`.
+ * - **Local CLI** (`amp` | `claude-code` | `codex` | `opencode`): spawned as a child
+ * process on the desktop or a connected device; uses `command`, `args`, `env`,
+ * `systemContext`.
*
- * - **Remote platform** (`openclaw` | `hermes` | `opencode`): dispatched to a machine
+ * - **Remote platform** (`openclaw` | `hermes`): dispatched to a machine
* connected via `lh connect`; device is identified by `LobeAgentAgencyConfig.boundDeviceId`.
* `platformAgentId` selects the named agent on the remote platform (defaults to `'main'`).
*/
@@ -168,6 +169,7 @@ interface CodexSelectionSource {
const CODEX_CONFIG_FLAGS = ['-c', '--config'] as const;
const CODEX_MODEL_FLAGS = ['-m', '--model'] as const;
const HETERO_EXEC_AGENT_ARG_FLAG = '--agent-arg';
+const OPENCODE_MODEL_FLAGS = ['-m', '--model'] as const;
const hasCliFlag = (args: string[], flag: string): boolean =>
args.some((arg) => arg === flag || arg.startsWith(`${flag}=`));
@@ -386,7 +388,8 @@ export const codexModelSupportsFastSpeed = (model: string): boolean =>
* For `claude-code` and `codex`, the chat-input selector persists explicit
* `model` + `effort` selections on the provider config; this is the single
* place that maps those stored settings onto provider-specific argv for direct
- * local desktop spawns.
+ * local desktop spawns. OpenCode currently has no dedicated selector, but a
+ * programmatically stored `model` is forwarded using its native `--model` flag.
* Missing/default settings are resolved by the UI helpers for display only.
* They are not appended here because CLI overrides must not mask each CLI's
* own settings/env/account defaults. User-authored `args` win, so there is
@@ -400,7 +403,13 @@ export const buildHeteroSpawnArgs = (
provider: HeterogeneousProviderConfig | undefined | null,
): string[] | undefined => {
if (!provider) return undefined;
- if (provider.type !== 'claude-code' && provider.type !== 'codex') return provider.args;
+ if (
+ provider.type !== 'claude-code' &&
+ provider.type !== 'codex' &&
+ provider.type !== 'opencode'
+ ) {
+ return provider.args;
+ }
const baseArgs = provider.args ?? [];
const extraArgs: string[] = [];
@@ -433,6 +442,17 @@ export const buildHeteroSpawnArgs = (
}
}
+ if (provider.type === 'opencode') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, OPENCODE_MODEL_FLAGS)
+ ) {
+ extraArgs.push('--model', model);
+ }
+ }
+
if (extraArgs.length === 0) return provider.args;
return [...baseArgs, ...extraArgs];
};
@@ -445,13 +465,18 @@ export const buildHeteroSpawnArgs = (
* encoded with `--agent-arg=<arg>` so wrapper flags such as `-c, --command`
* never collide with Codex/Claude flags. Keep selector overrides in the
* wrapper's `--model` / `--effort` form; `lh hetero exec` translates them into
- * native Codex config immediately before `spawnAgent`.
+ * native provider arguments immediately before `spawnAgent`.
*/
export const buildHeteroExecArgs = (
provider: HeterogeneousProviderConfig | undefined | null,
): string[] | undefined => {
if (!provider) return undefined;
- if (provider.type !== 'amp' && provider.type !== 'claude-code' && provider.type !== 'codex') {
+ if (
+ provider.type !== 'amp' &&
+ provider.type !== 'claude-code' &&
+ provider.type !== 'codex' &&
+ provider.type !== 'opencode'
+ ) {
return provider.args;
}
@@ -495,6 +520,17 @@ export const buildHeteroExecArgs = (
}
}
+ if (provider.type === 'opencode') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, OPENCODE_MODEL_FLAGS)
+ ) {
+ selectorArgs.push('--model', model);
+ }
+ }
+
const args = [...wrapperArgs, ...selectorArgs];
return args.length > 0 ? args : undefined;
};
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index dae5df39438..0d8dddd2e1b 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -2,7 +2,10 @@
import { SiApple, SiLinux } from '@icons-pack/react-simple-icons';
import { isDesktop } from '@lobechat/const';
-import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
+import {
+ HETEROGENEOUS_TYPE_LABELS,
+ isRemoteHeterogeneousType,
+} from '@lobechat/heterogeneous-agents';
import type { DeviceExecutionTarget } from '@lobechat/types';
import { Microsoft } from '@lobehub/icons';
import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
@@ -27,7 +30,10 @@ import { DOWNLOAD_URL } from '@/const/url';
import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import {
+ isHeterogeneousSandboxExecutionAvailable,
+ resolveExecutionTarget,
+} from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
@@ -363,7 +369,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// (plain chat, no execution environment) isn't a valid target for them: hide
// the option and never fall back to / honour a stale stored `'none'`.
const isHetero = !!heteroType;
- const supportsSandbox = heteroType !== 'amp';
+ const supportsSandbox = isHeterogeneousSandboxExecutionAvailable(heteroType);
// Workspace-keyed SWR fetch — the raw lambdaQuery key has no workspace
// dimension, so the picker kept showing the previous workspace's pool after
@@ -388,15 +394,15 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
workspaceScoped,
});
- // Amp cannot fall back to the cloud sandbox. When a web/legacy config has no
- // usable device target, open the picker once so `none` is an explicit setup
- // prompt rather than a disabled-but-active sandbox row.
+ // Device-only CLIs cannot fall back to the cloud sandbox. When a web/legacy
+ // config has no usable device target, open the picker once so `none` is an
+ // explicit setup prompt rather than a disabled-but-active sandbox row.
useEffect(() => {
- if (heteroType !== 'amp') return;
+ if (supportsSandbox) return;
if (isWorkspacePreferenceLoading) return;
if (executionTarget !== 'none') return;
setOpen(true);
- }, [executionTarget, heteroType, isWorkspacePreferenceLoading]);
+ }, [executionTarget, isWorkspacePreferenceLoading, supportsSandbox]);
const selectExecutionTarget = useSelectExecutionTarget(agentId);
const handleSelect = useCallback(
@@ -619,7 +625,8 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
desc={t(
supportsSandbox
? 'heteroAgent.executionTarget.sandboxDesc'
- : 'heteroAgent.executionTarget.ampSandboxUnsupported',
+ : 'heteroAgent.executionTarget.sandboxUnsupported',
+ { name: heteroType ? HETEROGENEOUS_TYPE_LABELS[heteroType] : undefined },
)}
onClick={() => void handleSelect('sandbox')}
/>
diff --git a/src/features/Conversation/Error/heterogeneous.ts b/src/features/Conversation/Error/heterogeneous.ts
index afe1dfe5fc4..e23229c9db9 100644
--- a/src/features/Conversation/Error/heterogeneous.ts
+++ b/src/features/Conversation/Error/heterogeneous.ts
@@ -26,7 +26,10 @@ export const isHeterogeneousAgentStatusGuideError = (
const { agentType, code } = value as Partial<HeterogeneousAgentSessionError>;
return (
- (agentType === 'amp' || agentType === 'claude-code' || agentType === 'codex') &&
+ (agentType === 'amp' ||
+ agentType === 'claude-code' ||
+ agentType === 'codex' ||
+ agentType === 'opencode') &&
typeof code === 'string' &&
HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES.has(code)
);
diff --git a/src/features/CreatePlatformAgent/index.tsx b/src/features/CreatePlatformAgent/index.tsx
index 41e0544e84f..a0cd7126935 100644
--- a/src/features/CreatePlatformAgent/index.tsx
+++ b/src/features/CreatePlatformAgent/index.tsx
@@ -80,15 +80,6 @@ const styles = createStaticStyles(({ css }) => ({
border-color: ${cssVar.colorPrimary};
background: ${cssVar.colorPrimaryBg};
}
-
- &[data-disabled='true'] {
- cursor: not-allowed;
- opacity: 0.5;
-
- &:hover {
- border-color: ${cssVar.colorBorderSecondary};
- }
- }
`,
platformDesc: css`
font-size: 13px;
@@ -112,8 +103,6 @@ interface CreatePlatformAgentContentProps {
visibility?: 'private' | 'public';
}
-const COMING_SOON_PLATFORMS = new Set<RemoteHeterogeneousAgentType>(['opencode']);
-
const CreatePlatformAgentContent = memo<CreatePlatformAgentContentProps>(
({ groupId, visibility }) => {
const { t } = useTranslation('chat');
@@ -146,7 +135,6 @@ const CreatePlatformAgentContent = memo<CreatePlatformAgentContentProps>(
const [checkingCapability, setCheckingCapability] = useState(false);
const platformDefs = REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((c) => ({
- comingSoon: COMING_SOON_PLATFORMS.has(c.type),
desc: t(`platformAgent.create.desc.${c.type}`),
name: c.title,
type: c.type,
@@ -172,7 +160,14 @@ const CreatePlatformAgentContent = memo<CreatePlatformAgentContentProps>(
} else if (!fetchingProfile && !agentName) {
setAgentName(selectedPlatformDef.name);
}
- }, [step, agentProfile, fetchingProfile]);
+ }, [
+ agentDescription,
+ agentName,
+ agentProfile,
+ fetchingProfile,
+ selectedPlatformDef.name,
+ step,
+ ]);
const handlePlatformChange = useCallback((type: RemoteHeterogeneousAgentType) => {
setPlatform(type);
@@ -343,23 +338,18 @@ const CreatePlatformAgentContent = memo<CreatePlatformAgentContentProps>(
{platformDefs.map((def) => (
<div
className={styles.platformCard}
- data-disabled={def.comingSoon}
- data-selected={!def.comingSoon && platform === def.type}
+ data-selected={platform === def.type}
key={def.type}
role="button"
- tabIndex={def.comingSoon ? -1 : 0}
- onClick={() => !def.comingSoon && handlePlatformChange(def.type)}
+ tabIndex={0}
+ onClick={() => handlePlatformChange(def.type)}
onKeyDown={(e) => {
- if (!def.comingSoon && (e.key === 'Enter' || e.key === ' '))
- handlePlatformChange(def.type);
+ if (e.key === 'Enter' || e.key === ' ') handlePlatformChange(def.type);
}}
>
<Flexbox horizontal align="center" gap={8}>
<Icon icon={MonitorSmartphone} size={18} />
<span className={styles.platformName}>{def.name}</span>
- {def.comingSoon && (
- <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgent.create.comingSoon')}</Tag>
- )}
</Flexbox>
<span className={styles.platformDesc}>{def.desc}</span>
</div>
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx
index 00dd2ea55aa..4a9dc229889 100644
--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx
@@ -5,8 +5,10 @@ import {
CLAUDE_CODE_CLI_INSTALL_DOCS_URL,
CODEX_CLI_INSTALL_COMMANDS,
CODEX_CLI_INSTALL_DOCS_URL,
+ OPENCODE_CLI_INSTALL_COMMANDS,
+ OPENCODE_CLI_INSTALL_DOCS_URL,
} from '@lobechat/electron-client-ipc';
-import { Amp, ClaudeCode, Codex } from '@lobehub/icons';
+import { Amp, ClaudeCode, Codex, OpenCode } from '@lobehub/icons';
import {
type HeterogeneousAgentGuideConfig,
@@ -39,6 +41,14 @@ export const HETEROGENEOUS_AGENT_GUIDE_CONFIG = {
title: 'Codex',
translationPrefix: 'codexInstallGuide',
},
+ 'opencode': {
+ docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,
+ icon: OpenCode,
+ installCommands: OPENCODE_CLI_INSTALL_COMMANDS,
+ signInCommand: 'opencode auth login',
+ title: 'OpenCode',
+ translationPrefix: 'opencodeInstallGuide',
+ },
} as const satisfies Record<SupportedHeterogeneousAgentType, HeterogeneousAgentGuideConfig>;
export const isSupportedHeterogeneousAgentType = (
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts
index 101816b4fd7..a883cdbc94c 100644
--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts
@@ -41,7 +41,12 @@ export interface HeterogeneousAgentStatusGuideProps {
variant?: HeterogeneousAgentStatusGuideVariant;
}
-export const SUPPORTED_HETEROGENEOUS_AGENT_TYPES = ['amp', 'claude-code', 'codex'] as const;
+export const SUPPORTED_HETEROGENEOUS_AGENT_TYPES = [
+ 'amp',
+ 'claude-code',
+ 'codex',
+ 'opencode',
+] as const;
export type SupportedHeterogeneousAgentType = (typeof SUPPORTED_HETEROGENEOUS_AGENT_TYPES)[number];
diff --git a/src/features/Recommendations/actions/heteroAgent.ts b/src/features/Recommendations/actions/heteroAgent.ts
index 6cd86fed125..388290c943c 100644
--- a/src/features/Recommendations/actions/heteroAgent.ts
+++ b/src/features/Recommendations/actions/heteroAgent.ts
@@ -1,5 +1,5 @@
import type { HeterogeneousAgentClientConfig } from '@lobechat/heterogeneous-agents/client';
-import { Amp, ClaudeCode, Codex } from '@lobehub/icons';
+import { Amp, ClaudeCode, Codex, OpenCode } from '@lobehub/icons';
import { createElement } from 'react';
import type { RecommendedAction } from './types';
@@ -8,6 +8,7 @@ const avatarIcons = {
'amp': Amp.Avatar,
'claude-code': ClaudeCode.Avatar,
'codex': Codex.Avatar,
+ 'opencode': OpenCode.Avatar,
} as const satisfies Record<HeterogeneousAgentClientConfig['type'], unknown>;
/**
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 68d484ede19..5eb1ada290c 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -17,6 +17,10 @@ const ampCfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfi
heterogeneousProvider: { command: 'amp', type: 'amp' },
...over,
});
+const openCodeCfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig => ({
+ heterogeneousProvider: { command: 'opencode', type: 'opencode' },
+ ...over,
+});
describe('resolveWorkspaceScoped', () => {
it('preserves shared-row coercion until a workspace member explicitly selects a target', () => {
@@ -136,9 +140,12 @@ describe('resolveExecutionTarget', () => {
});
describe('hetero providers without sandbox execution', () => {
- it('keeps an unconfigured Amp agent pending on web instead of defaulting to sandbox', () => {
+ it.each([
+ ['Amp', ampCfg],
+ ['OpenCode', openCodeCfg],
+ ] as const)('keeps an unconfigured %s agent pending on web', (_name, providerCfg) => {
expect(
- resolveExecutionTarget(ampCfg(), {
+ resolveExecutionTarget(providerCfg(), {
clientExecutionAvailable: false,
isHetero: true,
}),
@@ -146,7 +153,7 @@ describe('resolveExecutionTarget', () => {
// Desktop can still run the CLI in-process, so its default remains local.
expect(
- resolveExecutionTarget(ampCfg(), {
+ resolveExecutionTarget(providerCfg(), {
clientExecutionAvailable: true,
isHetero: true,
}),
@@ -164,6 +171,17 @@ describe('resolveExecutionTarget', () => {
}
});
+ it('normalizes unsupported OpenCode sandbox and unbound web-local targets to pending', () => {
+ for (const executionTarget of ['sandbox', 'local'] as const) {
+ expect(
+ resolveExecutionTarget(openCodeCfg({ executionTarget }), {
+ clientExecutionAvailable: false,
+ isHetero: true,
+ }),
+ ).toBe('none');
+ }
+ });
+
it('still routes a bound Amp desktop-local selection to its device on web', () => {
expect(
resolveExecutionTarget(ampCfg({ boundDeviceId: 'device-a', executionTarget: 'local' }), {
@@ -847,16 +865,22 @@ describe('resolveExecutionPlan', () => {
}
});
- it('keeps Amp non-device targets pending instead of constructing a sandbox plan', () => {
- for (const executionTarget of ['local', 'none', 'sandbox', undefined] as const) {
- const plan: ExecutionPlan = resolveExecutionPlan({
- agencyConfig: executionTarget ? ampCfg({ executionTarget }) : ampCfg(),
- clientExecutionAvailable: false,
- isHetero: true,
- });
- expect(plan).toEqual({ kind: 'none', target: 'none' });
- }
- });
+ it.each([
+ ['Amp', ampCfg],
+ ['OpenCode', openCodeCfg],
+ ] as const)(
+ 'keeps %s non-device targets pending instead of constructing a sandbox plan',
+ (_name, providerCfg) => {
+ for (const executionTarget of ['local', 'none', 'sandbox', undefined] as const) {
+ const plan: ExecutionPlan = resolveExecutionPlan({
+ agencyConfig: executionTarget ? providerCfg({ executionTarget }) : providerCfg(),
+ clientExecutionAvailable: false,
+ isHetero: true,
+ });
+ expect(plan).toEqual({ kind: 'none', target: 'none' });
+ }
+ },
+ );
it('uses an explicit sandbox capability override for legacy model-only Amp agents', () => {
expect(
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index 0cf96a48e23..08cc3e4e7f7 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -80,9 +80,10 @@ export interface ResolveExecutionTargetOptions {
isHetero?: boolean;
/**
* Whether this heterogeneous provider can execute in the server cloud
- * sandbox. Defaults to `false` for Amp (which currently requires a local or
- * connected device) and `true` otherwise. Callers that only know the provider
- * through a legacy model discriminator can override the inferred capability.
+ * sandbox. Defaults to `false` for Amp and OpenCode (which currently require
+ * a local or connected device) and `true` otherwise. Callers that only know
+ * the provider through a legacy model discriminator can override the inferred
+ * capability.
*/
sandboxExecutionAvailable?: boolean;
/**
@@ -109,6 +110,10 @@ export interface ResolveExecutionTargetOptions {
workspaceScoped?: boolean;
}
+/** Whether a heterogeneous provider can run in LobeHub's cloud sandbox. */
+export const isHeterogeneousSandboxExecutionAvailable = (type: string | undefined): boolean =>
+ type !== 'amp' && type !== 'opencode';
+
/**
* Single source of truth for where an agent executes — one global
* `agencyConfig.executionTarget` drives both desktop and web.
@@ -169,7 +174,8 @@ export const resolveExecutionTarget = (
// environment.
const clientAvailable = clientExecutionAvailable && !workspaceScoped;
const sandboxAvailable =
- sandboxExecutionAvailable ?? agencyConfig?.heterogeneousProvider?.type !== 'amp';
+ sandboxExecutionAvailable ??
+ isHeterogeneousSandboxExecutionAvailable(agencyConfig?.heterogeneousProvider?.type);
const stored = agencyConfig?.executionTarget;
let effective = stored ?? (clientAvailable ? 'local' : 'none');
if (
@@ -398,7 +404,8 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut
workspaceScoped,
});
const sandboxAvailable =
- sandboxExecutionAvailable ?? agencyConfig?.heterogeneousProvider?.type !== 'amp';
+ sandboxExecutionAvailable ??
+ isHeterogeneousSandboxExecutionAvailable(agencyConfig?.heterogeneousProvider?.type);
const wantsDevice =
!!requestedDeviceId || target === 'device' || target === 'local' || target === 'auto';
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index 49373232aa3..bcd9eb18cb7 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -20,7 +20,10 @@ import { ChatInput } from '@/features/Conversation';
import { contextSelectors, useConversationStore } from '@/features/Conversation/store';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import {
+ isHeterogeneousSandboxExecutionAvailable,
+ resolveExecutionTarget,
+} from '@/helpers/executionTarget';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useRemoteAgentDeviceGuard } from '@/hooks/useRemoteAgentDeviceGuard';
import { useChatStore } from '@/store/chat';
@@ -104,7 +107,10 @@ const HeterogeneousChatInput = memo(() => {
workspaceScoped,
});
const isRemoteAgent = !!providerType && isRemoteHeterogeneousType(providerType);
- const ampDeviceSelectionRequired = providerType === 'amp' && executionTarget === 'none';
+ const deviceSelectionRequired =
+ !!providerType &&
+ !isHeterogeneousSandboxExecutionAvailable(providerType) &&
+ executionTarget === 'none';
// The model + thinking-effort selector only applies to local-CLI providers
// (claude-code / codex) and only when this surface actually dispatches the run.
@@ -196,7 +202,7 @@ const HeterogeneousChatInput = memo(() => {
const renderCloudConfigGuard = () => {
// Until the override loads, `isDeviceExecution` may be a false negative —
// don't flash the cloud-config prompt for what turns out to be a device run.
- if (isPreferenceLoading || ampDeviceSelectionRequired || isDeviceExecution || isConfigured) {
+ if (isPreferenceLoading || deviceSelectionRequired || isDeviceExecution || isConfigured) {
return null;
}
@@ -213,13 +219,15 @@ const HeterogeneousChatInput = memo(() => {
);
};
- const renderAmpDeviceGuard = () => {
- if (!ampDeviceSelectionRequired) return null;
+ const renderDeviceSelectionGuard = () => {
+ if (!deviceSelectionRequired) return null;
return (
<GuardBanner
- hint={t('heteroAgent.executionTarget.ampSandboxUnsupported')}
title={t('platformAgent.deviceGuard.noDevice.title')}
+ hint={t('heteroAgent.executionTarget.sandboxUnsupported', {
+ name: providerType ? HETEROGENEOUS_TYPE_LABELS[providerType] : undefined,
+ })}
/>
);
};
@@ -230,15 +238,15 @@ const HeterogeneousChatInput = memo(() => {
// known yet, so neither guard can vouch for the run.
const inputDisabled =
isPreferenceLoading ||
- ampDeviceSelectionRequired ||
+ deviceSelectionRequired ||
(!isConfigured && !isDeviceExecution) ||
deviceBlocked;
const hasGuard =
- ampDeviceSelectionRequired || deviceBlocked || (!isConfigured && !isDeviceExecution);
+ deviceSelectionRequired || deviceBlocked || (!isConfigured && !isDeviceExecution);
return (
<Flexbox>
- {renderAmpDeviceGuard()}
+ {renderDeviceSelectionGuard()}
{renderCloudConfigGuard()}
{renderDeviceGuard()}
<ChatInput
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 0315be4dac2..9048e6c37eb 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
@@ -23,13 +23,18 @@ vi.mock('@lobechat/heterogeneous-agents/client', () => ({
icon: () => <span>Claude Code Icon</span>,
title: 'Claude Code',
}
- : {
- command: 'codex',
- icon: () => <span>Codex Icon</span>,
- title: 'Codex',
- },
- isRemoteHeterogeneousType: (type: string) =>
- ['openclaw', 'hermes', 'amp', 'opencode'].includes(type),
+ : type === 'opencode'
+ ? {
+ command: 'opencode',
+ icon: () => <span>OpenCode Icon</span>,
+ title: 'OpenCode',
+ }
+ : {
+ command: 'codex',
+ icon: () => <span>Codex Icon</span>,
+ title: 'Codex',
+ },
+ isRemoteHeterogeneousType: (type: string) => ['openclaw', 'hermes'].includes(type),
}));
vi.mock('@lobehub/ui', () => ({
@@ -163,6 +168,32 @@ describe('HeterogeneousAgentStatusCard', () => {
expect(screen.queryByDisplayValue('codex')).not.toBeInTheDocument();
});
+ it('detects OpenCode and shows its install guide when unavailable', async () => {
+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: false });
+
+ const provider = {
+ command: 'opencode',
+ type: 'opencode',
+ } satisfies HeterogeneousProviderConfig;
+
+ render(
+ <MemoryRouter>
+ <HeterogeneousAgentStatusCard provider={provider} />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => {
+ expect(detectHeterogeneousAgentCommand).toHaveBeenCalledWith({
+ agentType: 'opencode',
+ command: 'opencode',
+ });
+ });
+
+ expect(screen.getByText('OpenCode CLI')).toBeInTheDocument();
+ expect(screen.getByText('OpenCode CLI is unavailable')).toBeInTheDocument();
+ expect(screen.getByText('opencode Install Guide')).toBeInTheDocument();
+ });
+
it('shows the embedded Claude Code 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 30cb9327f46..a31703ec2ac 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
@@ -233,7 +233,10 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
const displayName = providerConfig?.title || provider.type;
const AgentIcon = providerConfig?.icon;
const showCliInstallGuide =
- (provider.type === 'amp' || provider.type === 'claude-code' || provider.type === 'codex') &&
+ (provider.type === 'amp' ||
+ provider.type === 'claude-code' ||
+ provider.type === 'codex' ||
+ provider.type === 'opencode') &&
!detecting &&
!status?.available &&
!isUsingCustomCommand;
@@ -254,7 +257,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
}, [provider.type, resolvedCommand]);
const detect = useCallback(async () => {
- // Remote platform agents (openclaw, hermes, opencode, …) have no local CLI to detect.
+ // Remote platform agents (openclaw, hermes, …) have no local CLI to detect.
if (isRemoteHeterogeneousType(provider.type) || !isDesktop || !resolvedCommand) {
setDetecting(false);
return;
diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx
index f61c942b3db..b53c2c4df75 100644
--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx
+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx
@@ -52,6 +52,16 @@ vi.mock('@lobechat/heterogeneous-agents/client', () => ({
title: 'Amp',
type: 'amp',
},
+ {
+ avatar: 'opencode-avatar',
+ command: 'opencode',
+ icon: () => null,
+ iconId: 'OpenCode',
+ menuKey: 'newOpenCodeAgent',
+ menuLabelKey: 'newOpenCodeAgent',
+ title: 'OpenCode',
+ type: 'opencode',
+ },
],
}));
@@ -178,6 +188,7 @@ describe('useCreateMenuItems', () => {
'newClaudeCodeAgent',
'newCodexAgent',
'newAmpAgent',
+ 'newOpenCodeAgent',
'divider',
'addAgentFromMarket',
]);
@@ -305,4 +316,31 @@ describe('useCreateMenuItems', () => {
groupId: undefined,
});
});
+
+ it('creates OpenCode as an independent local CLI agent', async () => {
+ const { result } = renderHook(() => useCreateMenuItems());
+
+ const openCodeItem = result.current
+ .createHeterogeneousAgentMenuItems()
+ .find((item) => isActionItem(item) && item.key === 'newOpenCodeAgent');
+
+ if (!isActionItem(openCodeItem)) throw new Error('Expected OpenCode menu item');
+
+ await act(async () => {
+ await openCodeItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });
+ });
+
+ expect(createAgentMock).toHaveBeenCalledWith({
+ config: {
+ agencyConfig: {
+ heterogeneousProvider: { command: 'opencode', type: 'opencode' },
+ },
+ avatar: 'opencode-avatar',
+ provider: 'opencode',
+ systemRole: '',
+ title: 'OpenCode',
+ },
+ groupId: undefined,
+ });
+ });
});
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 1ca3e329679..098e06a241d 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -9,6 +9,7 @@ import {
CODEX_CLI_INSTALL_DOCS_URL,
type HeterogeneousAgentSessionError,
HeterogeneousAgentSessionErrorCode,
+ OPENCODE_CLI_INSTALL_DOCS_URL,
} from '@lobechat/electron-client-ipc';
import {
createMainAgentRunState,
@@ -94,7 +95,7 @@ const CLI_AUTH_REQUIRED_PATTERNS = [
const AMP_AUTH_REQUIRED_PATTERNS = [/please (?:log|sign) in/i, /amp_api_key/i] as const;
const buildCliAuthRequiredSessionError = (
- agentType: 'amp' | 'claude-code' | 'codex',
+ agentType: 'amp' | 'claude-code' | 'codex' | 'opencode',
rawMessage: string,
): HeterogeneousAgentSessionError => {
switch (agentType) {
@@ -128,6 +129,16 @@ const buildCliAuthRequiredSessionError = (
stderr: rawMessage,
};
}
+ case 'opencode': {
+ return {
+ agentType,
+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,
+ docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,
+ message:
+ 'OpenCode could not authenticate. Sign in again or refresh its credentials, then retry.',
+ stderr: rawMessage,
+ };
+ }
}
};
@@ -137,7 +148,14 @@ const maybeClassifyCliAuthRequiredError = (
error: unknown,
agentType?: string,
): HeterogeneousAgentSessionError | undefined => {
- if (agentType !== 'amp' && agentType !== 'claude-code' && agentType !== 'codex') return;
+ if (
+ agentType !== 'amp' &&
+ agentType !== 'claude-code' &&
+ agentType !== 'codex' &&
+ agentType !== 'opencode'
+ ) {
+ return;
+ }
const message =
error instanceof Error
@@ -187,6 +205,9 @@ const getDefaultHeterogeneousCommand = (agentType: string): string => {
case 'codex': {
return 'codex';
}
+ case 'opencode': {
+ return 'opencode';
+ }
default: {
return 'claude';
}
diff --git a/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts
index 45c0cc786a8..5c42ab60c83 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { claudeCodeExecutor, codexExecutor } from '../heteroCli';
+import { claudeCodeExecutor, codexExecutor, openCodeExecutor } from '../heteroCli';
const detectMocks = vi.hoisted(() => ({
recordGitCommandEffects: vi.fn(),
@@ -29,6 +29,7 @@ describe('heteroCli executors', () => {
it('registers the CLI adapter identifiers and exposes no invokable APIs', () => {
expect(claudeCodeExecutor.identifier).toBe('claude-code');
expect(codexExecutor.identifier).toBe('codex');
+ expect(openCodeExecutor.identifier).toBe('opencode');
// Empty apiEnum → never treated as an invokable client tool.
expect(claudeCodeExecutor.hasApi('Bash')).toBe(false);
expect(claudeCodeExecutor.getApiNames()).toEqual([]);
@@ -58,6 +59,22 @@ describe('heteroCli executors', () => {
});
});
+ it('observes OpenCode bash calls for worktree side effects', async () => {
+ await openCodeExecutor.onAfterCall!(
+ call({
+ apiName: 'bash',
+ identifier: 'opencode',
+ params: { command: 'git worktree add /tmp/opencode-wt' },
+ }),
+ );
+
+ expect(detectMocks.recordGitCommandEffects).toHaveBeenCalledWith({
+ command: 'git worktree add /tmp/opencode-wt',
+ resultContent: '',
+ topicId: 't1',
+ });
+ });
+
it('passes shell output through for branch and PR detection', async () => {
await claudeCodeExecutor.onAfterCall!(
call({
diff --git a/src/store/tool/slices/builtin/executors/heteroCli.ts b/src/store/tool/slices/builtin/executors/heteroCli.ts
index 40872be33ff..0c18348a1f1 100644
--- a/src/store/tool/slices/builtin/executors/heteroCli.ts
+++ b/src/store/tool/slices/builtin/executors/heteroCli.ts
@@ -9,7 +9,7 @@ import {
/**
* Hook-only executor for a heterogeneous CLI agent's tool identifier
- * (`amp` / `claude-code` / `codex` — set by the adapters in
+ * (`amp` / `claude-code` / `codex` / `opencode` — set by the adapters in
* `packages/heterogeneous-agents/src/adapters/*`). These agents run their OWN
* tools, so this executor is NEVER invoked: `apiEnum` is empty → `hasApi()` is
* always false → the client-tool dispatch (`hasExecutor`) never routes to
@@ -52,7 +52,7 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {
protected readonly apiEnum = EMPTY_API_ENUM;
/**
- * @param identifier The CLI adapter's tool identifier (`amp` / `claude-code` / `codex`).
+ * @param identifier The CLI adapter's tool identifier.
* @param shellApiNames The adapter's shell / run-command tool api name(s). Side
* effects are constrained to THIS tool first, then handled uniformly — we don't
* sniff every tool call's params.
@@ -95,10 +95,12 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {
};
}
-// AMP's shell tool is `shell_command`; CC's is `Bash`; Codex's is `command_execution`.
+// AMP's shell tool is `shell_command`; CC's is `Bash`; Codex's is
+// `command_execution`; OpenCode's is `bash`.
export const ampExecutor = new HeteroCliExecutor('amp', new Set(['shell_command']));
export const claudeCodeExecutor = new HeteroCliExecutor('claude-code', new Set(['Bash']), {
enter: 'EnterWorktree',
exit: 'ExitWorktree',
});
export const codexExecutor = new HeteroCliExecutor('codex', new Set(['command_execution']));
+export const openCodeExecutor = new HeteroCliExecutor('opencode', new Set(['bash']));
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index 2fe5ecb5b43..e0891e47446 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -21,7 +21,7 @@ import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';
import { taskExecutor } from '@lobechat/builtin-tool-task/client/executor';
import type { BuiltinToolContext, BuiltinToolResult, IBuiltinToolExecutor } from '../types';
-import { ampExecutor, claudeCodeExecutor, codexExecutor } from './heteroCli';
+import { ampExecutor, claudeCodeExecutor, codexExecutor, openCodeExecutor } from './heteroCli';
import { activatorExecutor } from './lobe-activator';
import { agentDocumentsExecutor } from './lobe-agent-documents';
import { messageExecutor } from './lobe-message';
@@ -153,6 +153,7 @@ export const registerBuiltinToolExecutors = (): void => {
ampExecutor,
claudeCodeExecutor,
codexExecutor,
+ openCodeExecutor,
agentBuilderExecutor,
agentDocumentsExecutor,
agentManagementExecutor,