🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(heterogeneous-agent): add Amp CLI support (#17223)
AmAzing-142e2be5b704
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex e7b7ec87bed..f0b76c35e80 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -102,8 +102,9 @@ describe('hetero exec command', () => {stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);mockResolveHeteroSpawnCommand.mockReset();mockResolveHeteroSpawnCommand.mockImplementation(- async (agentType: 'claude-code' | 'codex', command?: string) => ({- command: command ?? (agentType === 'codex' ? 'codex' : 'claude'),+ async (agentType: 'amp' | 'claude-code' | 'codex', command?: string) => ({+ command:+ command ?? (agentType === 'amp' ? 'amp' : agentType === 'codex' ? 'codex' : 'claude'),}),);mockSpawnAgent.mockReset();@@ -321,6 +322,34 @@ describe('hetero exec command', () => {});});+ it('runs AMP and forwards only native agent args', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'amp',+ '--prompt',+ 'do thing',+ '--model',+ 'ignored-by-wrapper',+ '--effort',+ 'high',+ '--agent-arg=--mode',+ '--agent-arg=high',+ ]);++ expect(mockResolveHeteroSpawnCommand).toHaveBeenCalledWith('amp', undefined);+ expect(mockSpawnAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentType: 'amp',+ command: 'amp',+ extraArgs: ['--mode', 'high'],+ }),+ );+ });+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.tsindex 949e5c70b7c..e8a5cfe1066 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -22,7 +22,7 @@ import { getTrpcClient } from '../api/client';import { log } from '../utils/logger';import { TrpcIngestSink } from '../utils/TrpcIngestSink';-const SUPPORTED_AGENT_TYPES = new Set(['claude-code', 'codex']);+const SUPPORTED_AGENT_TYPES = new Set(['amp', 'claude-code', 'codex']);const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';@@ -107,18 +107,20 @@ const buildExtraArgs = (options: Pick<ExecOptions, 'agentArg' | 'effort' | 'model' | 'speed' | 'type'>,): string[] | undefined => {const selectorArgs =- options.type === 'codex'- ? [- ...(options.model ? ['--model', options.model] : []),- ...(options.effort- ? ['-c', `${CODEX_REASONING_EFFORT_CONFIG_KEY}="${options.effort}"`]- : []),- ...(options.speed ? ['-c', `${CODEX_SERVICE_TIER_CONFIG_KEY}="${options.speed}"`] : []),- ]- : [- ...(options.model ? ['--model', options.model] : []),- ...(options.effort ? ['--effort', options.effort] : []),- ];+ options.type === 'amp'+ ? []+ : options.type === 'codex'+ ? [+ ...(options.model ? ['--model', options.model] : []),+ ...(options.effort+ ? ['-c', `${CODEX_REASONING_EFFORT_CONFIG_KEY}="${options.effort}"`]+ : []),+ ...(options.speed ? ['-c', `${CODEX_SERVICE_TIER_CONFIG_KEY}="${options.speed}"`] : []),+ ]+ : [+ ...(options.model ? ['--model', options.model] : []),+ ...(options.effort ? ['--effort', options.effort] : []),+ ];const extraArgs = [...(options.agentArg ?? []), ...selectorArgs];return extraArgs.length > 0 ? extraArgs : undefined;@@ -474,7 +476,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 'claude-code' | 'codex';+ const agentType = options.type as 'amp' | 'claude-code' | 'codex';let sink: TrpcIngestSink | undefined;let serverIngester: SerialServerIngester | undefined;// Uploader for tool_result images (CC `Read` on an image file). Reuses the@@ -805,7 +807,7 @@ const exec = async (options: ExecOptions): Promise<void> => {...(askMcpConfigPath ? ['--mcp-config', askMcpConfigPath] : []),];// Resolve the CLI binary once, up front, and reuse it for both the initial- // run and the resume-retry. For the default bare command (`codex`/`claude`)+ // run and the resume-retry. For the default bare command (`amp`/`codex`/`claude`)// this finds the validated binary — including an app-bundled Codex CLI when// a broken `codex` shim shadows PATH — so sandbox/terminal runs no longer// ENOENT on a stale global install. Custom commands are used verbatim.@@ -926,7 +928,9 @@ const exec = async (options: ExecOptions): Promise<void> => {export function registerHeteroCommand(program: Command) {const hetero = program.command('hetero')- .description('Run heterogeneous agent CLIs (Claude Code / Codex) and stream their output');+ .description(+ 'Run heterogeneous agent CLIs (Amp / Claude Code / Codex) and stream their output',+ );hetero.command('exec')@@ -959,7 +963,7 @@ export function registerHeteroCommand(program: Command) {).option('-c, --command <bin>',- 'Override the agent CLI binary name (default: `claude` or `codex`)',+ 'Override the agent CLI binary name (default: `amp`, `claude`, or `codex`)',).option('--operation-id <id>',diff --git a/apps/cli/src/utils/TrpcIngestSink.ts b/apps/cli/src/utils/TrpcIngestSink.tsindex 2436bee3ddf..6391c524c90 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: 'claude-code' | 'codex',+ private readonly agentType: 'amp' | 'claude-code' | 'codex',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.tsindex 6093da2fabf..9f8c6b2b545 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -14,6 +14,8 @@ import type {HeterogeneousAgentSessionError,} from '@lobechat/electron-client-ipc';import {+ AMP_CLI_INSTALL_COMMANDS,+ AMP_CLI_INSTALL_DOCS_URL,CLAUDE_CODE_CLI_INSTALL_COMMANDS,CLAUDE_CODE_CLI_INSTALL_DOCS_URL,CODEX_CLI_INSTALL_COMMANDS,@@ -104,6 +106,7 @@ const CLI_AUTH_REQUIRED_PATTERNS = [/\bunauthorized\b/i,/\b401\b/,] as const;+const AMP_AUTH_REQUIRED_PATTERNS = [/please (?:log|sign) in/i, /amp_api_key/i] as const;const CODEX_RESUME_CWD_MISMATCH_PATTERNS = [/working directory/i,/\bcwd\b/i,@@ -337,7 +340,30 @@ export default class HeterogeneousAgentCtr extends ControllerModule {const resolvedCommand = session.command.trim();if (resolvedCommand) return resolvedCommand;- return session.agentType === 'codex' ? 'codex' : 'claude';+ switch (session.agentType) {+ case 'amp': {+ return 'amp';+ }+ case 'codex': {+ return 'codex';+ }+ default: {+ return 'claude';+ }+ }+ }++ private buildAmpCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {+ const command = this.resolveSessionCommand(session);++ return {+ agentType: 'amp',+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,+ command,+ docsUrl: AMP_CLI_INSTALL_DOCS_URL,+ installCommands: AMP_CLI_INSTALL_COMMANDS,+ message: `Amp CLI was not found. Install it and make sure \`${command}\` can be executed.`,+ };}private buildCodexCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {@@ -368,6 +394,9 @@ export default class HeterogeneousAgentCtr extends ControllerModule {private buildCliMissingError(session: AgentSession): HeterogeneousAgentSessionError | undefined {switch (session.agentType) {+ case 'amp': {+ return this.buildAmpCliMissingError(session);+ }case 'claude-code': {return this.buildClaudeCodeCliMissingError(session);}@@ -387,6 +416,17 @@ export default class HeterogeneousAgentCtr extends ControllerModule {const command = this.resolveSessionCommand(session);switch (session.agentType) {+ case 'amp': {+ return {+ agentType: 'amp',+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ command,+ docsUrl: AMP_CLI_INSTALL_DOCS_URL,+ message:+ 'Amp could not authenticate. Run `amp login` or configure AMP_API_KEY, then retry.',+ stderr,+ };+ }case 'claude-code': {return {agentType: 'claude-code',@@ -484,7 +524,12 @@ export default class HeterogeneousAgentCtr extends ControllerModule {): HeterogeneousAgentSessionError | undefined {const message = this.getErrorMessage(error);- if (!message || !CLI_AUTH_REQUIRED_PATTERNS.some((pattern) => pattern.test(message))) return;+ if (!message) return;+ const patterns =+ session.agentType === 'amp'+ ? [...CLI_AUTH_REQUIRED_PATTERNS, ...AMP_AUTH_REQUIRED_PATTERNS]+ : CLI_AUTH_REQUIRED_PATTERNS;+ if (!patterns.some((pattern) => pattern.test(message))) return;return this.buildCliAuthRequiredError(session, message);}@@ -551,11 +596,13 @@ export default class HeterogeneousAgentCtr extends ControllerModule {session: AgentSession,): Promise<HeterogeneousAgentSessionError | undefined> {const defaultCommand =- session.agentType === 'claude-code'- ? 'claude'- : session.agentType === 'codex'- ? 'codex'- : undefined;+ session.agentType === 'amp'+ ? 'amp'+ : session.agentType === 'claude-code'+ ? 'claude'+ : session.agentType === 'codex'+ ? 'codex'+ : undefined;if (!defaultCommand) return;const command = this.resolveSessionCommand(session);@@ -563,7 +610,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {command === defaultCommand? await this.app.binaryManager?.detect?.(defaultCommand, true): await detectHeterogeneousCliCommand(- session.agentType === 'claude-code' ? 'claude-code' : 'codex',+ session.agentType as 'amp' | 'claude-code' | 'codex',command,);diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex b49c1f24a5e..c5d11b91ccf 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -681,6 +681,23 @@ describe('HeterogeneousAgentCtr', () => {expect(spawnCalls).toHaveLength(0);});+ it('fails fast with AMP-specific install guidance when AMP 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: 'amp', command: 'amp' });++ await expect(+ ctr.sendPrompt({ operationId: 'op-test', prompt: 'hello', sessionId }),+ ).rejects.toThrow('Amp CLI was not found');++ expect(detect).toHaveBeenCalledWith('amp', 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/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.tsindex e2ee30db46f..dd41252ca16 100644--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts@@ -76,6 +76,17 @@ export const codexBinary: BinarySpec = {priority: 2,};+/**+ * Amp CLI+ * @see https://ampcode.com/manual+ */+export const ampBinary: BinarySpec = {+ description: 'Amp - Sourcegraph agentic coding CLI',+ detect: () => detectHeterogeneousCliCommand('amp', 'amp'),+ name: 'amp',+ priority: 3,+};+/*** Google Gemini CLI* @see https://github.com/google-gemini/gemini-cli@@ -84,7 +95,7 @@ export const geminiCliBinary: BinarySpec = defineValidatedBinary({candidates: ['gemini'],description: 'Gemini CLI - Google agentic coding CLI',name: 'gemini',- priority: 3,+ priority: 4,validateKeywords: ['gemini'],});@@ -96,7 +107,7 @@ export const qwenCodeBinary: BinarySpec = defineValidatedBinary({candidates: ['qwen'],description: 'Qwen Code - Alibaba Qwen agentic coding CLI',name: 'qwen',- priority: 4,+ priority: 5,validateKeywords: ['qwen'],});@@ -108,7 +119,7 @@ export const kimiCliBinary: BinarySpec = defineValidatedBinary({candidates: ['kimi'],description: 'Kimi CLI - Moonshot AI agentic coding CLI',name: 'kimi',- priority: 5,+ priority: 6,validateKeywords: ['kimi'],});@@ -119,7 +130,7 @@ export const kimiCliBinary: BinarySpec = defineValidatedBinary({*/export const aiderBinary: BinarySpec = defineCommandBinary('aider', {description: 'Aider - AI pair programming in your terminal',- priority: 6,+ priority: 7,});/**@@ -128,6 +139,7 @@ export const aiderBinary: BinarySpec = defineCommandBinary('aider', {export const cliAgentBinaries: BinarySpec[] = [claudeCodeBinary,codexBinary,+ ampBinary,geminiCliBinary,qwenCodeBinary,kimiCliBinary,diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/amp.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/amp.test.tsnew file mode 100644index 00000000000..944b838cb8d--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/amp.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it, vi } from 'vitest';++import type {+ HeterogeneousAgentBuildPlanHelpers,+ HeterogeneousAgentBuildPlanParams,+} from '../types';+import { ampDriver } from './amp';++const buildAgentInput = vi.fn(async () => ({+ args: [],+ stdin: '{"type":"user","message":{"content":[]}}\n',+}));++const stubHelpers: HeterogeneousAgentBuildPlanHelpers = { buildAgentInput };++const buildParams = (+ overrides: Partial<HeterogeneousAgentBuildPlanParams> = {},+): HeterogeneousAgentBuildPlanParams => ({+ args: [],+ helpers: stubHelpers,+ promptInput: 'hi',+ ...overrides,+});++describe('ampDriver', () => {+ it('uses AMP private headless stream-json flags and input plan', async () => {+ const plan = await ampDriver.buildSpawnPlan(buildParams({ args: ['--mode', 'high'] }));++ expect(buildAgentInput).toHaveBeenCalledWith('amp', 'hi');+ expect(plan.stdinPayload).toContain('"type":"user"');+ expect(plan.args).toEqual([+ '--execute',+ '--stream-json-thinking',+ '--stream-json-input',+ '--visibility',+ 'private',+ '--no-ide',+ '--no-notifications',+ '--no-archive-after-execute',+ '--mode',+ 'high',+ ]);+ });++ it('uses AMP thread continuation syntax without changing other drivers', async () => {+ const plan = await ampDriver.buildSpawnPlan(+ buildParams({ resumeSessionId: 'T-existing-thread' }),+ );++ expect(plan.args.slice(0, 4)).toEqual([+ 'threads',+ 'continue',+ 'T-existing-thread',+ '--execute',+ ]);+ });+});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/amp.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/amp.tsnew file mode 100644index 00000000000..4814a627246--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/amp.ts@@ -0,0 +1,25 @@+import { AMP_BASE_ARGS } from '@lobechat/heterogeneous-agents/spawn';++import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';++export const ampDriver: HeterogeneousAgentDriver = {+ async buildSpawnPlan({+ args,+ helpers,+ promptInput,+ resumeSessionId,+ }: HeterogeneousAgentBuildPlanParams) {+ const { args: inputArgs, stdin: stdinPayload } = await helpers.buildAgentInput(+ 'amp',+ promptInput,+ );+ const executionArgs = [...AMP_BASE_ARGS, ...inputArgs, ...args];++ return {+ args: resumeSessionId+ ? ['threads', 'continue', resumeSessionId, ...executionArgs]+ : executionArgs,+ stdinPayload,+ };+ },+};diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts b/apps/desktop/src/main/modules/heterogeneousAgent/index.tsindex 2e654f9ebf6..acbf8c52e25 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts@@ -1,8 +1,10 @@+import { ampDriver } from './drivers/amp';import { claudeCodeDriver } from './drivers/claudeCode';import { codexDriver } from './drivers/codex';import type { HeterogeneousAgentDriver } from './types';const heterogeneousAgentDrivers: Record<string, HeterogeneousAgentDriver> = {+ 'amp': ampDriver,'claude-code': claudeCodeDriver,'codex': codexDriver,};diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 52cdeb60ae3..5a01c824257 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -453,7 +453,7 @@ const AgentStreamEventSchema = z.object({* → topic reverse-lookup is unreliable per design decision).*/const HeteroIngestSchema = z.object({- agentType: z.enum(['claude-code', 'codex']),+ agentType: z.enum(['amp', 'claude-code', 'codex']),/** 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. */@@ -470,7 +470,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(['claude-code', 'codex']),+ agentType: z.enum(['amp', 'claude-code', 'codex']),error: z.object({message: z.string(),diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex e508c3b7f61..e931fe4d305 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1597,7 +1597,7 @@ export class AiAgentService {!!botContext,);- // 3.5. Hetero-agent early exit — Claude Code / Codex / OpenClaw / Hermes agents bypass the+ // 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@@ -1605,11 +1605,11 @@ export class AiAgentService {//// Detection: prefer agencyConfig.heterogeneousProvider.type (set by the UI),// fall back to model field for backwards compatibility.- const HETERO_AGENT_MODELS = new Set<string>(['claude-code', 'codex']);+ const HETERO_AGENT_MODELS = new Set<string>(['amp', 'claude-code', 'codex']);const heteroProviderType = agentConfig.agencyConfig?.heterogeneousProvider?.type;const isHeteroAgent = !!heteroProviderType || HETERO_AGENT_MODELS.has(model);const heteroType = (heteroProviderType ?? model) as- 'claude-code' | 'codex' | 'hermes' | 'openclaw';+ 'amp' | 'claude-code' | 'codex' | 'hermes' | 'openclaw';// ── Shared turn setup (runs for BOTH hetero and normal agents) ──────────// Everything up to and including persisting the turn is identical for both@@ -1889,7 +1889,7 @@ export class AiAgentService {? runAttachments.imageList.map((image) => ({ id: image.id, url: image.url })): undefined;const heteroExecArgs =- heteroType === 'claude-code' || heteroType === 'codex'+ heteroType === 'amp' || heteroType === 'claude-code' || heteroType === 'codex'? buildHeteroExecArgs(agentConfig.agencyConfig?.heterogeneousProvider?.type === heteroType? agentConfig.agencyConfig.heterogeneousProvider@@ -2070,7 +2070,7 @@ export class AiAgentService {};}} else {- // Local CLI hetero (claude-code / codex) — fork between device dispatch+ // Local CLI hetero (Amp / Claude Code / Codex) — 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)@@ -2118,6 +2118,7 @@ export class AiAgentService {isHetero: true,clientExecutionAvailable: false,requestedDeviceId,+ sandboxExecutionAvailable: heteroType !== 'amp',trigger: requestTriggerMetadata?.trigger,});@@ -2129,7 +2130,9 @@ export class AiAgentService {agentId: resolvedAgentId,assistantMessageId: assistantMessageRecord.id,detail:- 'No device bound. Pick a device in the Execution Device switcher, or switch to Cloud sandbox.',+ heteroType === 'amp'+ ? 'No device bound. Pick a local or connected device in the Execution Device switcher.'+ : 'No device bound. Pick a device in the Execution Device switcher, or switch to Cloud sandbox.',message: 'No bound device for hetero agent',operationId,topicId,@@ -2230,7 +2233,34 @@ export class AiAgentService {};}} else {- // Cloud sandbox path — only for local CLI agents (claude-code / codex).+ if (heteroType === 'amp') {+ const message =+ 'Amp requires a local or connected device; cloud sandbox execution is not supported.';+ await this.finalizeHeteroDispatchError({+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ detail: message,+ message,+ operationId,+ topicId,+ });+ return {+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: message,+ message,+ operationId,+ status: 'error',+ success: false,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: userMessageRecord?.id ?? parentMessageId ?? '',+ };+ }++ // Cloud sandbox path — only for sandbox-provisioned local CLI agents.// Remote agents (openclaw / hermes) always require a bound device.// Lazy-loaded on purpose: `sandboxRunner` pulls the sandbox-service graph// (which eagerly touches server-only ModelRuntime env at module init), sodiff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 240b0bebac0..098c5adffc7 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 = 'claude-code' | 'codex';+export type HeterogeneousAgentType = 'amp' | 'claude-code' | 'codex';export type HeterogeneousFinishResult = 'success' | 'error' | 'cancelled';@@ -69,7 +69,7 @@ export interface HeterogeneousAgentServiceOptions {/*** Server-side ingest handler for heterogeneous agent CLIs (`lh hetero exec`- * for Claude Code / Codex). Receives `AgentStreamEvent` batches from the+ * for Amp / Claude Code / Codex). 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.jsonindex 77bbeb0f7d2..63e1ef2a1a2 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -50,6 +50,15 @@"agentSignal.receipts.skill.detail": "Self-refined how this agent handles similar requests","agentSignal.receipts.skill.title": "Auto-learned a new skill","agents": "Agents",+ "ampInstallGuide.actions.openDocs": "Open Install Guide",+ "ampInstallGuide.actions.openSystemTools": "Open System Tools",+ "ampInstallGuide.afterInstall": "After installing, run `amp login`, then retry your message or click Re-detect in System Tools.",+ "ampInstallGuide.desc": "Amp needs the Amp CLI to run locally. Install it and make sure the `amp` command is available in your PATH.",+ "ampInstallGuide.installWithBrew": "Homebrew (macOS)",+ "ampInstallGuide.installWithNpm": "Recommended install",+ "ampInstallGuide.menuNotification.title": "Amp CLI not found",+ "ampInstallGuide.reason": "LobeHub could not start Amp: {{message}}",+ "ampInstallGuide.title": "Install Amp CLI","artifact.generating": "Generating","artifact.inThread": "Cannot view in subtopic, please switch to the main conversation area to open","artifact.thinking": "Thinking",@@ -316,6 +325,7 @@"heteroAgent.codexQuota.resetCredits_zero": "No rate-limit resets available","heteroAgent.codexQuota.title": "Codex quota","heteroAgent.codexQuota.tooltip": "View Codex quota",+ "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",@@ -574,6 +584,7 @@"minimap.senderAssistant": "Agent","minimap.senderUser": "You","newAgent": "Create Agent",+ "newAmpAgent": "Add Amp","newClaudeCodeAgent": "Add Claude Code","newCodexAgent": "Add Codex","newGroupChat": "Create Group",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex b27303e981d..1ddc7cafc5c 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -50,6 +50,15 @@"agentSignal.receipts.skill.detail": "已自主优化处理相似请求的方式","agentSignal.receipts.skill.title": "已自动习得新技能","agents": "助理",+ "ampInstallGuide.actions.openDocs": "打开安装指南",+ "ampInstallGuide.actions.openSystemTools": "打开系统工具",+ "ampInstallGuide.afterInstall": "安装完成后,请运行 `amp login` 登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",+ "ampInstallGuide.desc": "Amp 需要本地安装 Amp CLI 才能运行。请先安装,并确保 `amp` 命令已加入 PATH。",+ "ampInstallGuide.installWithBrew": "Homebrew 安装(macOS)",+ "ampInstallGuide.installWithNpm": "推荐安装方式",+ "ampInstallGuide.menuNotification.title": "未找到 Amp CLI",+ "ampInstallGuide.reason": "LobeHub 无法启动 Amp:{{message}}",+ "ampInstallGuide.title": "安装 Amp CLI","artifact.generating": "生成中","artifact.inThread": "子话题中暂不支持查看。请回到主对话区打开","artifact.thinking": "思考中",@@ -316,6 +325,7 @@"heteroAgent.codexQuota.resetCredits_zero": "暂无可用额度重置","heteroAgent.codexQuota.title": "Codex 额度","heteroAgent.codexQuota.tooltip": "查看 Codex 额度",+ "heteroAgent.executionTarget.ampSandboxUnsupported": "Amp 目前仅支持在本地设备或已连接设备上运行","heteroAgent.executionTarget.auto": "自动","heteroAgent.executionTarget.autoDesc": "自动使用在线设备,有多台时择一使用","heteroAgent.executionTarget.downloadDesktop": "下载桌面端",@@ -574,6 +584,7 @@"minimap.senderAssistant": "助理","minimap.senderUser": "你","newAgent": "创建助理",+ "newAmpAgent": "添加 Amp","newClaudeCodeAgent": "添加 Claude Code","newCodexAgent": "添加 Codex","newGroupChat": "创建群组",diff --git a/packages/electron-client-ipc/src/types/binary.ts b/packages/electron-client-ipc/src/types/binary.tsindex 1c5562bd8c6..9f3b80d429f 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 = 'claude-code' | 'codex';+export type HeterogeneousCliAgentType = 'amp' | 'claude-code' | 'codex';export interface DetectHeterogeneousAgentCommandParams {agentType: HeterogeneousCliAgentType;diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.tsindex 73941ad0864..e48c652a916 100644--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts@@ -1,3 +1,10 @@+export const AMP_CLI_INSTALL_DOCS_URL = 'https://ampcode.com/manual';++export const AMP_CLI_INSTALL_COMMANDS = [+ 'curl -fsSL https://ampcode.com/install.sh | bash',+ 'brew install ampcode/tap/ampcode',+] as const;+export const CLAUDE_CODE_CLI_INSTALL_DOCS_URL ='https://docs.anthropic.com/en/docs/claude-code/setup';diff --git a/packages/heterogeneous-agents/src/adapters/amp.test.ts b/packages/heterogeneous-agents/src/adapters/amp.test.tsnew file mode 100644index 00000000000..1a439c354a1--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/amp.test.ts@@ -0,0 +1,279 @@+import { describe, expect, it } from 'vitest';++import { AmpAdapter } from './amp';++const init = {+ agent_mode: 'medium',+ session_id: 'T-amp-123',+ subtype: 'init',+ type: 'system',+};++const assistant = (content: unknown[], usage?: Record<string, number>) => ({+ message: {+ content,+ role: 'assistant',+ ...(usage ? { usage } : {}),+ },+ type: 'assistant',+});++describe('AmpAdapter', () => {+ it('maps init, assistant text, and a successful result without borrowing another provider', () => {+ const adapter = new AmpAdapter();++ const start = adapter.adapt(init);+ const text = adapter.adapt(assistant([{ text: 'hello from Amp', type: 'text' }]));+ const end = adapter.adapt({+ duration_ms: 1200,+ is_error: false,+ num_turns: 1,+ result: 'hello from Amp',+ session_id: 'T-amp-123',+ subtype: 'success',+ type: 'result',+ });++ expect(adapter.sessionId).toBe('T-amp-123');+ expect(start).toHaveLength(1);+ expect(start[0]).toMatchObject({+ data: { provider: 'amp', sessionId: 'T-amp-123' },+ stepIndex: 0,+ type: 'stream_start',+ });+ expect(text).toEqual([+ expect.objectContaining({+ data: { chunkType: 'text', content: 'hello from Amp' },+ stepIndex: 0,+ type: 'stream_chunk',+ }),+ ]);+ expect(end.map((event) => event.type)).toEqual([+ 'stream_end',+ 'visible_output_end',+ 'agent_runtime_end',+ ]);+ });++ it('keeps tool lifecycle and the post-tool assistant in separate steps', () => {+ const adapter = new AmpAdapter();+ adapter.adapt(init);++ const toolTurn = adapter.adapt(+ assistant([+ {+ id: 'toolu_amp_1',+ input: { cmd: 'pwd' },+ name: 'shell_command',+ type: 'tool_use',+ },+ ]),+ );+ const resultTurn = adapter.adapt({+ message: {+ content: [+ {+ content: '/workspace',+ is_error: false,+ tool_use_id: 'toolu_amp_1',+ type: 'tool_result',+ },+ ],+ role: 'user',+ },+ type: 'user',+ });+ const finalTurn = adapter.adapt(assistant([{ text: 'Done.', type: 'text' }]));++ expect(toolTurn.map((event) => event.type)).toEqual(['stream_chunk', 'tool_start']);+ expect(toolTurn[0]).toMatchObject({+ data: {+ chunkType: 'tools_calling',+ toolsCalling: [+ {+ apiName: 'shell_command',+ arguments: '{\n "cmd": "pwd"\n}',+ id: 'toolu_amp_1',+ identifier: 'amp',+ type: 'default',+ },+ ],+ },+ stepIndex: 0,+ });+ expect(resultTurn.map((event) => event.type)).toEqual(['tool_result', 'tool_end']);+ expect(resultTurn[1]).toMatchObject({+ data: {+ isSuccess: true,+ payload: { toolCalling: { id: 'toolu_amp_1', identifier: 'amp' } },+ result: { content: '/workspace', success: true },+ toolCallId: 'toolu_amp_1',+ },+ });+ expect(finalTurn.map((event) => event.type)).toEqual([+ 'stream_end',+ 'stream_start',+ 'stream_chunk',+ ]);+ expect(finalTurn[1]).toMatchObject({+ data: { newStep: true, provider: 'amp', sessionId: 'T-amp-123' },+ stepIndex: 1,+ });+ expect(finalTurn[2]).toMatchObject({+ data: { chunkType: 'text', content: 'Done.' },+ stepIndex: 1,+ });+ });++ it('normalizes AMP usage including cache reads and writes', () => {+ const adapter = new AmpAdapter();+ adapter.adapt(init);++ const events = adapter.adapt(+ assistant([{ thinking: 'checking', type: 'thinking' }], {+ cache_creation_input_tokens: 13,+ cache_read_input_tokens: 29,+ input_tokens: 101,+ output_tokens: 17,+ }),+ );++ expect(events[0]).toMatchObject({+ data: { chunkType: 'reasoning', reasoning: 'checking' },+ type: 'stream_chunk',+ });+ expect(events[1]).toMatchObject({+ data: {+ phase: 'turn_metadata',+ provider: 'amp',+ usage: {+ inputCachedTokens: 29,+ inputCacheMissTokens: 101,+ inputWriteCacheTokens: 13,+ outputTextTokens: 17,+ totalInputTokens: 143,+ totalOutputTokens: 17,+ totalTokens: 160,+ },+ },+ type: 'step_complete',+ });+ });++ it('treats an error result as terminal even when AMP may exit with code zero', () => {+ const adapter = new AmpAdapter();+ adapter.adapt(init);++ const events = adapter.adapt({+ duration_ms: 42,+ error: 'Invalid JSON input on stdin',+ is_error: true,+ num_turns: 0,+ session_id: 'T-amp-123',+ subtype: 'error_during_execution',+ type: 'result',+ });++ expect(events.map((event) => event.type)).toEqual([+ 'stream_end',+ 'visible_output_end',+ 'error',+ ]);+ expect(events.at(-1)?.data).toMatchObject({+ agentType: 'amp',+ clearEchoedContent: true,+ details: {+ durationMs: 42,+ numTurns: 0,+ sessionId: 'T-amp-123',+ subtype: 'error_during_execution',+ },+ error: 'Invalid JSON input on stdin',+ message: 'Invalid JSON input on stdin',+ });+ });++ it('routes subagent events with synthetic turn ids and one-time spawn metadata', () => {+ const adapter = new AmpAdapter();+ adapter.adapt(init);+ adapter.adapt(+ assistant([+ {+ id: 'toolu_task_1',+ input: {+ description: 'Inspect tests',+ prompt: 'Find the failing test',+ subagent_type: 'explore',+ },+ name: 'Task',+ type: 'tool_use',+ },+ ]),+ );++ const first = adapter.adapt({+ ...assistant([{ text: 'Looking now.', type: 'text' }]),+ parent_tool_use_id: 'toolu_task_1',+ });+ const second = adapter.adapt({+ ...assistant([{ text: 'Found it.', type: 'text' }]),+ parent_tool_use_id: 'toolu_task_1',+ });++ expect(first[0]).toMatchObject({+ data: {+ content: 'Looking now.',+ subagent: {+ parentToolCallId: 'toolu_task_1',+ spawnMetadata: {+ description: 'Inspect tests',+ prompt: 'Find the failing test',+ subagentType: 'explore',+ },+ subagentMessageId: 'amp:toolu_task_1:1',+ },+ },+ stepIndex: 0,+ type: 'stream_chunk',+ });+ expect(second[0]).toMatchObject({+ data: {+ content: 'Found it.',+ subagent: {+ parentToolCallId: 'toolu_task_1',+ subagentMessageId: 'amp:toolu_task_1:2',+ },+ },+ stepIndex: 0,+ });+ expect(second[0].data.subagent.spawnMetadata).toBeUndefined();+ });++ it('flushes unfinished tools as unsuccessful without ending another provider runtime', () => {+ const adapter = new AmpAdapter();+ adapter.adapt(init);+ adapter.adapt(+ assistant([+ {+ id: 'toolu_pending',+ input: { cmd: 'long-task' },+ name: 'shell_command',+ type: 'tool_use',+ },+ ]),+ );++ const events = adapter.flush();++ expect(events).toHaveLength(1);+ expect(events[0]).toMatchObject({+ data: {+ isSuccess: false,+ payload: { toolCalling: { id: 'toolu_pending', identifier: 'amp' } },+ toolCallId: 'toolu_pending',+ },+ type: 'tool_end',+ });+ expect(adapter.flush()).toEqual([]);+ });+});diff --git a/packages/heterogeneous-agents/src/adapters/amp.ts b/packages/heterogeneous-agents/src/adapters/amp.tsnew file mode 100644index 00000000000..43ee9c834a6--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/amp.ts@@ -0,0 +1,563 @@+import { imagePlaceholder } from '../imageEcho';+import type {+ AgentEventAdapter,+ HeterogeneousAgentEvent,+ HeterogeneousTerminalErrorData,+ HeterogeneousToolResultImage,+ StepCompleteData,+ StreamChunkData,+ StreamStartData,+ SubagentEventContext,+ SubagentSpawnMetadata,+ ToolCallPayload,+ ToolResultData,+ UsageData,+} from '../types';++const AMP_IDENTIFIER = 'amp';+const AMP_DOCS_URL = 'https://ampcode.com/manual';++interface AmpUsage {+ cache_creation_input_tokens?: number;+ cache_read_input_tokens?: number;+ input_tokens?: number;+ output_tokens?: number;+}++interface NormalizedToolResult {+ content: string;+ images: HeterogeneousToolResultImage[];+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const stringifyUnknown = (value: unknown): string => {+ if (typeof value === 'string') return value;+ if (value === undefined || value === null) return '';++ try {+ return JSON.stringify(value, null, 2);+ } catch {+ return String(value);+ }+};++const toFiniteNumber = (value: unknown): number | undefined =>+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;++const toUsageData = (value: unknown): UsageData | undefined => {+ if (!isRecord(value)) return;++ const usage = value as AmpUsage;+ const inputCacheMissTokens = toFiniteNumber(usage.input_tokens) ?? 0;+ const inputCachedTokens = toFiniteNumber(usage.cache_read_input_tokens) ?? 0;+ const inputWriteCacheTokens = toFiniteNumber(usage.cache_creation_input_tokens) ?? 0;+ const totalOutputTokens = toFiniteNumber(usage.output_tokens) ?? 0;+ const hasUsage = [+ usage.input_tokens,+ usage.cache_read_input_tokens,+ usage.cache_creation_input_tokens,+ usage.output_tokens,+ ].some((tokenCount) => toFiniteNumber(tokenCount) !== undefined);++ if (!hasUsage) return;++ const totalInputTokens = inputCacheMissTokens + inputCachedTokens + inputWriteCacheTokens;++ return {+ ...(inputCachedTokens > 0 ? { inputCachedTokens } : {}),+ inputCacheMissTokens,+ ...(inputWriteCacheTokens > 0 ? { inputWriteCacheTokens } : {}),+ outputTextTokens: totalOutputTokens,+ totalInputTokens,+ totalOutputTokens,+ totalTokens: totalInputTokens + totalOutputTokens,+ };+};++const normalizeToolResult = (value: unknown): NormalizedToolResult => {+ if (typeof value === 'string') return { content: value, images: [] };+ if (!Array.isArray(value)) return { content: stringifyUnknown(value), images: [] };++ const images: HeterogeneousToolResultImage[] = [];+ const content = value+ .map((item) => {+ if (typeof item === 'string') return item;+ if (!isRecord(item)) return stringifyUnknown(item);++ if (item.type === 'tool_reference' && typeof item.tool_name === 'string') {+ return item.tool_name;+ }++ if (item.type === 'image') {+ const source = isRecord(item.source) ? item.source : undefined;+ const mediaType = typeof source?.media_type === 'string' ? source.media_type : 'image';++ if (source?.type === 'base64' && typeof source.data === 'string') {+ images.push({ data: source.data, mediaType });+ }++ return imagePlaceholder(mediaType);+ }++ if (typeof item.text === 'string') return item.text;+ if (typeof item.content === 'string') return item.content;++ return stringifyUnknown(item);+ })+ .filter(Boolean)+ .join('\n');++ return { content, images };+};++const toToolPayload = (block: Record<string, unknown>): ToolCallPayload | undefined => {+ if (typeof block.id !== 'string' || typeof block.name !== 'string') return;++ return {+ apiName: block.name,+ arguments: stringifyUnknown(block.input ?? {}),+ id: block.id,+ identifier: AMP_IDENTIFIER,+ type: 'default',+ };+};++const getErrorText = (value: unknown): string | undefined => {+ if (typeof value === 'string' && value.trim()) return value.trim();+ if (!isRecord(value)) return;++ for (const key of ['message', 'error', 'detail', 'stderr']) {+ const nested = getErrorText(value[key]);+ if (nested) return nested;+ }+};++const getTerminalMessage = (raw: Record<string, unknown>): string =>+ getErrorText(raw.error) ||+ getErrorText(raw.result) ||+ getErrorText(raw.message) ||+ 'Amp stopped before completing the request.';++const buildTerminalError = (raw: Record<string, unknown>): HeterogeneousTerminalErrorData => {+ const message = getTerminalMessage(raw);+ const isAuthError =+ /not authenticated|authentication|unauthorized|sign in|log in|amp_api_key|\b401\b/i.test(+ message,+ );+ const isRateLimitError = /rate[ -]?limit|too many requests|\b429\b/i.test(message);+ const details = {+ ...(toFiniteNumber(raw.duration_ms) === undefined+ ? {}+ : { durationMs: toFiniteNumber(raw.duration_ms) }),+ ...(toFiniteNumber(raw.num_turns) === undefined+ ? {}+ : { numTurns: toFiniteNumber(raw.num_turns) }),+ ...(typeof raw.session_id === 'string' ? { sessionId: raw.session_id } : {}),+ ...(typeof raw.subtype === 'string' ? { subtype: raw.subtype } : {}),+ };++ return {+ agentType: AMP_IDENTIFIER,+ clearEchoedContent: true,+ ...(isAuthError ? { code: 'auth_required', docsUrl: AMP_DOCS_URL } : {}),+ ...(isRateLimitError+ ? {+ code: 'rate_limit',+ docsUrl: AMP_DOCS_URL,+ rateLimitInfo: { status: 'rejected' },+ }+ : {}),+ details,+ error: getErrorText(raw.error),+ message,+ stderr: typeof raw.stderr === 'string' ? raw.stderr : undefined,+ };+};++/**+ * Adapter for AMP's `--stream-json-thinking --stream-json-input` protocol.+ *+ * AMP resembles Anthropic's message block format, but its live stream omits+ * assistant message ids and reports terminal failures through a JSON `result`+ * event even when the process exit code is zero. Keeping this adapter separate+ * prevents those semantics from leaking into Claude Code's mature state machine.+ */+export class AmpAdapter implements AgentEventAdapter {+ private announcedSubagentSpawns = new Set<string>();+ private completedToolCalls = new Set<string>();+ private hasMainAssistantTurn = false;+ private mainToolInputsById = new Map<string, Record<string, unknown>>();+ private pendingToolCalls = new Set<string>();+ private started = false;+ private stepIndex = 0;+ private subagentTurnCounters = new Map<string, number>();+ private terminalEmitted = false;+ private toolCallsByTurn = new Map<string, ToolCallPayload[]>();+ private toolPayloadById = new Map<string, ToolCallPayload>();+ private toolSubagentById = new Map<string, SubagentEventContext>();+ sessionId?: string;++ adapt(raw: any): HeterogeneousAgentEvent[] {+ if (!isRecord(raw)) return [];++ this.captureSessionId(raw);++ switch (raw.type) {+ case 'system': {+ return this.handleSystem(raw);+ }+ case 'assistant': {+ return this.handleAssistant(raw);+ }+ case 'user': {+ return this.handleUser(raw);+ }+ case 'result': {+ return this.handleResult(raw);+ }+ default: {+ return [];+ }+ }+ }++ flush(): HeterogeneousAgentEvent[] {+ return this.drainPendingToolEndEvents();+ }++ private captureSessionId(raw: Record<string, unknown>): void {+ if (typeof raw.session_id === 'string' && raw.session_id) {+ this.sessionId = raw.session_id;+ }+ }++ private handleSystem(raw: Record<string, unknown>): HeterogeneousAgentEvent[] {+ if (raw.subtype !== 'init') return [];+ if (this.started) return [];++ this.started = true;+ return [this.makeEvent('stream_start', this.getStreamStartData())];+ }++ private handleAssistant(raw: Record<string, unknown>): HeterogeneousAgentEvent[] {+ const message = isRecord(raw.message) ? raw.message : undefined;+ const content = Array.isArray(message?.content)+ ? message.content+ : typeof message?.content === 'string'+ ? [{ text: message.content, type: 'text' }]+ : [];+ const parentToolCallId =+ typeof raw.parent_tool_use_id === 'string' ? raw.parent_tool_use_id : undefined;++ if (parentToolCallId) {+ return this.handleSubagentAssistant(parentToolCallId, content, message?.usage ?? raw.usage);+ }++ const events = this.openMainAssistantTurn();+ const turnKey = `main:${this.stepIndex}`;++ for (const block of content) {+ if (!isRecord(block)) continue;++ if (block.type === 'thinking' && typeof block.thinking === 'string' && block.thinking) {+ events.push(+ this.makeEvent('stream_chunk', {+ chunkType: 'reasoning',+ reasoning: block.thinking,+ } satisfies StreamChunkData),+ );+ continue;+ }++ if (block.type === 'text' && typeof block.text === 'string' && block.text) {+ events.push(+ this.makeEvent('stream_chunk', {+ chunkType: 'text',+ content: block.text,+ } satisfies StreamChunkData),+ );+ continue;+ }++ if (block.type === 'tool_use') {+ const tool = toToolPayload(block);+ if (!tool) continue;++ if (isRecord(block.input)) this.mainToolInputsById.set(tool.id, block.input);+ events.push(...this.emitToolCall(tool, turnKey));+ }+ }++ const usage = toUsageData(message?.usage ?? raw.usage);+ if (usage) {+ events.push(+ this.makeEvent('step_complete', {+ phase: 'turn_metadata',+ provider: AMP_IDENTIFIER,+ usage,+ } satisfies StepCompleteData),+ );+ }++ return events;+ }++ private handleSubagentAssistant(+ parentToolCallId: string,+ content: unknown[],+ rawUsage: unknown,+ ): HeterogeneousAgentEvent[] {+ const turnNumber = (this.subagentTurnCounters.get(parentToolCallId) ?? 0) + 1;+ this.subagentTurnCounters.set(parentToolCallId, turnNumber);+ const subagentMessageId = `amp:${parentToolCallId}:${turnNumber}`;+ const subagent: SubagentEventContext = { parentToolCallId, subagentMessageId };+ const turnKey = `subagent:${subagentMessageId}`;+ const events: HeterogeneousAgentEvent[] = [];++ for (const block of content) {+ if (!isRecord(block)) continue;++ if (block.type === 'thinking' && typeof block.thinking === 'string' && block.thinking) {+ events.push(+ this.makeEvent('stream_chunk', {+ chunkType: 'reasoning',+ reasoning: block.thinking,+ subagent,+ } satisfies StreamChunkData),+ );+ continue;+ }++ if (block.type === 'text' && typeof block.text === 'string' && block.text) {+ events.push(+ this.makeEvent('stream_chunk', {+ chunkType: 'text',+ content: block.text,+ subagent,+ } satisfies StreamChunkData),+ );+ continue;+ }++ if (block.type === 'tool_use') {+ const tool = toToolPayload(block);+ if (!tool) continue;+ events.push(...this.emitToolCall(tool, turnKey, subagent));+ }+ }++ const usage = toUsageData(rawUsage);+ if (usage) {+ events.push(+ this.makeEvent('step_complete', {+ phase: 'turn_metadata',+ provider: AMP_IDENTIFIER,+ subagent,+ usage,+ }),+ );+ }++ this.attachSpawnMetadata(events, parentToolCallId);+ return events;+ }++ private handleUser(raw: Record<string, unknown>): HeterogeneousAgentEvent[] {+ const message = isRecord(raw.message) ? raw.message : undefined;+ if (!Array.isArray(message?.content)) return [];++ const parentToolCallId =+ typeof raw.parent_tool_use_id === 'string' ? raw.parent_tool_use_id : undefined;+ const subagent: SubagentEventContext | undefined = parentToolCallId+ ? { parentToolCallId }+ : undefined;+ const events: HeterogeneousAgentEvent[] = [];++ for (const block of message.content) {+ if (!isRecord(block) || block.type !== 'tool_result') continue;+ if (typeof block.tool_use_id !== 'string') continue;++ const toolCallId = block.tool_use_id;+ const normalized = normalizeToolResult(block.content);+ const pluginState = normalized.images.length > 0 ? { images: normalized.images } : undefined;+ const isError = block.is_error === true;+ const resultData: ToolResultData = {+ content: normalized.content,+ isError,+ ...(pluginState ? { pluginState } : {}),+ ...(subagent ? { subagent } : {}),+ toolCallId,+ };++ events.push(this.makeEvent('tool_result', resultData));++ if (!this.completedToolCalls.has(toolCallId)) {+ this.completedToolCalls.add(toolCallId);+ this.pendingToolCalls.delete(toolCallId);+ events.push(+ this.makeEvent(+ 'tool_end',+ this.buildToolEndData(toolCallId, !isError, normalized.content, pluginState, subagent),+ ),+ );+ }+ }++ if (parentToolCallId) this.attachSpawnMetadata(events, parentToolCallId);+ return events;+ }++ private handleResult(raw: Record<string, unknown>): HeterogeneousAgentEvent[] {+ if (this.terminalEmitted) return [];+ this.terminalEmitted = true;++ const events = this.drainPendingToolEndEvents();+ if (this.started) {+ events.push(this.makeEvent('stream_end', {}));+ events.push(this.makeEvent('visible_output_end', {}));+ }++ const subtype = typeof raw.subtype === 'string' ? raw.subtype : '';+ const isError = raw.is_error === true || subtype.toLowerCase().includes('error');+ events.push(+ isError+ ? this.makeEvent('error', buildTerminalError(raw))+ : this.makeEvent('agent_runtime_end', {}),+ );+ this.clearRunState();++ return events;+ }++ private openMainAssistantTurn(): HeterogeneousAgentEvent[] {+ if (!this.started) {+ this.started = true;+ this.hasMainAssistantTurn = true;+ return [this.makeEvent('stream_start', this.getStreamStartData())];+ }++ if (!this.hasMainAssistantTurn) {+ this.hasMainAssistantTurn = true;+ return [];+ }++ this.stepIndex += 1;+ return [+ this.makeEvent('stream_end', {}),+ this.makeEvent('stream_start', this.getStreamStartData({ newStep: true })),+ ];+ }++ private emitToolCall(+ tool: ToolCallPayload,+ turnKey: string,+ subagent?: SubagentEventContext,+ ): HeterogeneousAgentEvent[] {+ const tools = this.toolCallsByTurn.get(turnKey) ?? [];+ if (tools.some((existingTool) => existingTool.id === tool.id)) return [];++ const cumulativeTools = [...tools, tool];+ this.toolCallsByTurn.set(turnKey, cumulativeTools);+ this.toolPayloadById.set(tool.id, tool);+ this.pendingToolCalls.add(tool.id);+ if (subagent) this.toolSubagentById.set(tool.id, subagent);++ return [+ this.makeEvent('stream_chunk', {+ chunkType: 'tools_calling',+ ...(subagent ? { subagent } : {}),+ toolsCalling: cumulativeTools,+ } satisfies StreamChunkData),+ this.makeEvent('tool_start', {+ ...(subagent ? { subagent } : {}),+ toolCalling: tool,+ }),+ ];+ }++ private buildToolEndData(+ toolCallId: string,+ isSuccess: boolean,+ content = '',+ pluginState?: Record<string, unknown>,+ explicitSubagent?: SubagentEventContext,+ ): Record<string, unknown> {+ const toolCalling = this.toolPayloadById.get(toolCallId);+ const subagent = explicitSubagent ?? this.toolSubagentById.get(toolCallId);++ return {+ isSuccess,+ ...(toolCalling ? { payload: { toolCalling } } : {}),+ result: {+ content,+ success: isSuccess,+ ...(pluginState ? { state: pluginState } : {}),+ },+ ...(subagent ? { subagent } : {}),+ toolCallId,+ };+ }++ private drainPendingToolEndEvents(): HeterogeneousAgentEvent[] {+ const events = [...this.pendingToolCalls].map((toolCallId) =>+ this.makeEvent('tool_end', this.buildToolEndData(toolCallId, false)),+ );++ this.pendingToolCalls.clear();+ return events;+ }++ private attachSpawnMetadata(events: HeterogeneousAgentEvent[], parentToolCallId: string): void {+ if (events.length === 0 || this.announcedSubagentSpawns.has(parentToolCallId)) return;++ const spawnMetadata = this.buildSpawnMetadata(parentToolCallId);+ if (!spawnMetadata) return;++ const firstEvent = events[0];+ const firstSubagent = isRecord(firstEvent.data?.subagent)+ ? firstEvent.data.subagent+ : { parentToolCallId };+ firstEvent.data = {+ ...firstEvent.data,+ subagent: { ...firstSubagent, spawnMetadata },+ };+ this.announcedSubagentSpawns.add(parentToolCallId);+ }++ private buildSpawnMetadata(parentToolCallId: string): SubagentSpawnMetadata | undefined {+ const input = this.mainToolInputsById.get(parentToolCallId);+ if (!input) return;++ return {+ description: typeof input.description === 'string' ? input.description : undefined,+ prompt: typeof input.prompt === 'string' ? input.prompt : undefined,+ subagentType: typeof input.subagent_type === 'string' ? input.subagent_type : undefined,+ };+ }++ private getStreamStartData(extra: Record<string, unknown> = {}): StreamStartData {+ return {+ provider: AMP_IDENTIFIER,+ sessionId: this.sessionId,+ ...extra,+ };+ }++ private clearRunState(): void {+ this.mainToolInputsById.clear();+ this.toolCallsByTurn.clear();+ this.toolPayloadById.clear();+ this.toolSubagentById.clear();+ }++ private makeEvent(type: HeterogeneousAgentEvent['type'], data: any): HeterogeneousAgentEvent {+ return {+ data,+ stepIndex: this.stepIndex,+ timestamp: Date.now(),+ type,+ };+ }+}diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.tsindex e7ee36820c5..42c7c9e4893 100644--- a/packages/heterogeneous-agents/src/adapters/index.ts+++ b/packages/heterogeneous-agents/src/adapters/index.ts@@ -1,2 +1,3 @@+export { AmpAdapter } from './amp';export { ClaudeCodeAdapter, ClaudeCodeSdkAdapter } from './claudeCode';export { CodexAdapter } from './codex';diff --git a/packages/heterogeneous-agents/src/client/index.ts b/packages/heterogeneous-agents/src/client/index.tsindex acaa0c93ebb..6b1b6b19b61 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 { ClaudeCode, Codex, getLobeIconCDN } from '@lobehub/icons';+import { Amp, ClaudeCode, Codex, getLobeIconCDN } from '@lobehub/icons';import {getHeterogeneousAgentConfig,@@ -16,6 +16,7 @@ export interface HeterogeneousAgentClientConfig extends HeterogeneousAgentConfig}const heterogeneousAgentIcons = {+ 'amp': Amp,'claude-code': ClaudeCode,'codex': Codex,} as const satisfies Record<HeterogeneousAgentConfig['type'], IconType>;diff --git a/packages/heterogeneous-agents/src/config.test.ts b/packages/heterogeneous-agents/src/config.test.tsindex 01565225b2d..6518ce03dc3 100644--- a/packages/heterogeneous-agents/src/config.test.ts+++ b/packages/heterogeneous-agents/src/config.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from 'vitest';-import { getHeterogeneousAgentConfig, HETEROGENEOUS_AGENT_CONFIGS } from './config';+import {+ getHeterogeneousAgentConfig,+ HETEROGENEOUS_AGENT_CONFIGS,+ isRemoteHeterogeneousType,+} from './config';import { HETEROGENEOUS_TYPE_LABELS } from './labels';describe('heterogeneous agent config', () => {@@ -8,6 +12,7 @@ describe('heterogeneous agent config', () => {expect(HETEROGENEOUS_AGENT_CONFIGS.map((config) => config.type)).toEqual(['claude-code','codex',+ 'amp',]);});@@ -22,6 +27,11 @@ describe('heterogeneous agent config', () => {title: 'Codex',type: 'codex',});+ expect(getHeterogeneousAgentConfig('amp')).toMatchObject({+ command: 'amp',+ title: 'Amp',+ type: 'amp',+ });});it('derives display labels from the shared config source', () => {@@ -34,4 +44,9 @@ describe('heterogeneous agent config', () => {'opencode': 'OpenCode',});});++ it('classifies AMP as a local CLI rather than a remote platform', () => {+ expect(isRemoteHeterogeneousType('amp')).toBe(false);+ expect(isRemoteHeterogeneousType('openclaw')).toBe(true);+ });});diff --git a/packages/heterogeneous-agents/src/config.ts b/packages/heterogeneous-agents/src/config.tsindex fdeb9498a7b..9f2e2ee3392 100644--- a/packages/heterogeneous-agents/src/config.ts+++ b/packages/heterogeneous-agents/src/config.ts@@ -1,7 +1,7 @@-export type HeterogeneousAgentMenuLabelKey = 'newClaudeCodeAgent' | 'newCodexAgent';+export type HeterogeneousAgentMenuLabelKey = 'newAmpAgent' | 'newClaudeCodeAgent' | 'newCodexAgent';/**- * Config for local CLI hetero agents (Claude Code, Codex) that run as+ * Config for local CLI hetero agents (Amp, Claude Code, Codex) 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 +11,7 @@ export interface HeterogeneousAgentConfig {menuKey: string;menuLabelKey: HeterogeneousAgentMenuLabelKey;title: string;- type: 'claude-code' | 'codex';+ type: 'amp' | 'claude-code' | 'codex';}export const HETEROGENEOUS_AGENT_CONFIGS = [@@ -31,6 +31,14 @@ export const HETEROGENEOUS_AGENT_CONFIGS = [title: 'Codex',type: 'codex',},+ {+ command: 'amp',+ iconId: 'Amp',+ menuKey: 'newAmpAgent',+ menuLabelKey: 'newAmpAgent',+ title: 'Amp',+ type: 'amp',+ },] as const satisfies readonly HeterogeneousAgentConfig[];export const getHeterogeneousAgentConfig = (type: string) =>@@ -45,13 +53,12 @@ export const getHeterogeneousAgentConfig = (type: string) =>*/export interface RemoteHeterogeneousAgentConfig {title: string;- type: 'amp' | 'hermes' | 'opencode' | 'openclaw';+ type: 'hermes' | 'opencode' | 'openclaw';}export const REMOTE_HETEROGENEOUS_AGENT_CONFIGS = [{ title: 'OpenClaw', type: 'openclaw' },{ title: 'Hermes', type: 'hermes' },- { title: 'Amp', type: 'amp' },{ title: 'OpenCode', type: 'opencode' },] as const satisfies readonly RemoteHeterogeneousAgentConfig[];diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex 1abfaa140ff..2d585788c73 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -1,4 +1,4 @@-export { ClaudeCodeAdapter } from './adapters';+export { AmpAdapter, ClaudeCodeAdapter } from './adapters';export type {HeterogeneousAgentType,LocalHeterogeneousAgentType,diff --git a/packages/heterogeneous-agents/src/registry.test.ts b/packages/heterogeneous-agents/src/registry.test.tsindex c3828020a2e..e40ca09dc33 100644--- a/packages/heterogeneous-agents/src/registry.test.ts+++ b/packages/heterogeneous-agents/src/registry.test.ts@@ -1,10 +1,15 @@import { describe, expect, it } from 'vitest';-import { ClaudeCodeAdapter, CodexAdapter } from './adapters';+import { AmpAdapter, ClaudeCodeAdapter, CodexAdapter } from './adapters';import { createAdapter, listAgentTypes } from './registry';describe('registry', () => {describe('createAdapter', () => {+ it('creates an AmpAdapter for "amp"', () => {+ const adapter = createAdapter('amp');+ expect(adapter).toBeInstanceOf(AmpAdapter);+ });+it('creates a ClaudeCodeAdapter for "claude-code"', () => {const adapter = createAdapter('claude-code');expect(adapter).toBeInstanceOf(ClaudeCodeAdapter);@@ -21,8 +26,9 @@ describe('registry', () => {});describe('listAgentTypes', () => {- it('includes claude-code', () => {+ it('includes every local CLI adapter', () => {const types = listAgentTypes();+ expect(types).toContain('amp');expect(types).toContain('claude-code');expect(types).toContain('codex');});diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.tsindex 797c5b118aa..ef1eee01f32 100644--- a/packages/heterogeneous-agents/src/registry.ts+++ b/packages/heterogeneous-agents/src/registry.ts@@ -5,7 +5,7 @@* by registering here — no other code changes needed.*/-import { ClaudeCodeAdapter, ClaudeCodeSdkAdapter, CodexAdapter } from './adapters';+import { AmpAdapter, ClaudeCodeAdapter, ClaudeCodeSdkAdapter, CodexAdapter } from './adapters';import type { AgentEventAdapter } from './types';interface AgentRegistryEntry {@@ -13,6 +13,9 @@ interface AgentRegistryEntry {}const registry: Record<string, AgentRegistryEntry> = {+ 'amp': {+ createAdapter: () => new AmpAdapter(),+ },'claude-code': {createAdapter: () => new ClaudeCodeAdapter(),},diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex c3c85415157..88c17e169b8 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -67,6 +67,7 @@ export { JsonlStreamProcessor } from './jsonlProcessor';// import time. Import it from the dedicated `@lobechat/heterogeneous-agents/// resolveCliCommand` subpath instead.export {+ AMP_BASE_ARGS,CLAUDE_CODE_BASE_ARGS,CODEX_BYPASS_APPROVALS_AND_SANDBOX_ARG,CODEX_DEFAULT_EXECUTION_ARGS,diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.tsindex b217fb27492..f6138cf120c 100644--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts@@ -161,6 +161,37 @@ describe('buildAgentInput', () => {});});+ describe('amp', () => {+ it('uses AMP stream-json input with text and inline images', async () => {+ const plan = await buildAgentInput('amp', [+ { text: 'inspect', type: 'text' },+ {+ source: { data: PNG_BYTES.toString('base64'), mediaType: 'image/png', type: 'base64' },+ type: 'image',+ },+ ]);++ expect(plan.args).toEqual([]);+ expect(JSON.parse(plan.stdin.trim())).toEqual({+ message: {+ content: [+ { text: 'inspect', type: 'text' },+ {+ source: {+ data: PNG_BYTES.toString('base64'),+ media_type: 'image/png',+ type: 'base64',+ },+ type: 'image',+ },+ ],+ role: 'user',+ },+ type: 'user',+ });+ });+ });+describe('codex', () => {it('puts text on stdin and emits no --image flags when there are no images', async () => {const plan = await buildAgentInput('codex', 'just text');diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.tsindex a33982a3a7c..e86f5533fd9 100644--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts@@ -24,7 +24,7 @@ export interface BuildAgentInputOptions extends NormalizeImageOptions {** `args` is appended to the agent's CLI argv (e.g. Codex `--image <path>`* pairs); `stdin` is the payload written to the child's stdin (stream-json- * for Claude Code, raw text for Codex).+ * for Amp / Claude Code, raw text for Codex).*/export interface AgentInputPlan {args: string[];@@ -126,7 +126,7 @@ const buildCodexInput = async (* extra CLI args required to attach images. The single source of truth for* how each external agent CLI receives multimodal input.*- * - `claude-code`: stream-json on stdin with text + base64 image content blocks+ * - `amp` / `claude-code`: stream-json on stdin with text + base64 image content blocks* - `codex`: raw text on stdin + repeatable `--image <path>` flags** Path-mode agents materialize URL / base64 images via `materializeImageToPath`@@ -140,6 +140,7 @@ export const buildAgentInput = async (const blocks = toBlocks(prompt);switch (agentType) {+ case 'amp':case 'claude-code': {return buildClaudeCodeStdin(blocks, options);}diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.tsindex 80a5db76cd2..f2b00f365ce 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts@@ -61,6 +61,21 @@ describe('resolveCliCommand', () => {platformMock.mockReturnValue('darwin');});+ it('resolves AMP on PATH and validates its help banner', async () => {+ callExecFile('/Users/x/.local/bin/amp\n');+ callExecFile('Amp CLI\n\nUsage: amp [options] [command]');++ const { detectHeterogeneousCliCommand } = await importModule();+ const status = await detectHeterogeneousCliCommand('amp', 'amp');++ expect(status).toMatchObject({+ available: true,+ path: '/Users/x/.local/bin/amp',+ version: 'Amp CLI',+ });+ expect(execFileMock.mock.calls[1]![1]).toEqual(['--help']);+ });+it('resolves `codex` on PATH and validates it via execFile (no shell)', async () => {callExecFile('/usr/local/bin/codex\n');callExecFile('codex-cli 0.142.5');@@ -235,6 +250,16 @@ describe('resolveCliCommand', () => {platformMock.mockReturnValue('darwin');});+ it('uses amp as the default command for the AMP adapter', async () => {+ callExecFile('/Users/x/.local/bin/amp\n');+ callExecFile('Amp CLI');++ const { resolveHeteroSpawnCommand } = await importModule();+ const resolved = await resolveHeteroSpawnCommand('amp', undefined);++ expect(resolved.command).toBe('/Users/x/.local/bin/amp');+ });+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.tsindex 32176704ff2..90b723771e7 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 (Claude Code / Codex).+ * Shared resolver for the external CLI-agent binaries (Amp / Claude Code / Codex).** 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 = 'claude-code' | 'codex';+export type HeterogeneousCliAgentType = 'amp' | 'claude-code' | 'codex';/*** Resolution result. A structural subset of the desktop `BinaryManager`'s@@ -235,6 +235,10 @@ export const detectValidatedCommand = async (};const HETEROGENEOUS_CLI_AGENT_OPTIONS = {+ 'amp': {+ validateFlag: '--help',+ validateKeywords: ['Amp CLI'],+ },'claude-code': {validateKeywords: ['claude code'],},@@ -247,6 +251,7 @@ const HETEROGENEOUS_CLI_AGENT_OPTIONS = {// fallback locations below hold *this* binary, so they may only be probed when// the requested command is the default — never for a custom command.export const DEFAULT_HETERO_COMMAND: Record<HeterogeneousCliAgentType, string> = {+ 'amp': 'amp','claude-code': 'claude','codex': 'codex',};@@ -257,6 +262,17 @@ export const DEFAULT_HETERO_COMMAND: Record<HeterogeneousCliAgentType, string> =// desktop app bundles a functional CLI inside its app bundle without symlinking it.const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[] => {switch (agentType) {+ case 'amp': {+ if (platform() !== 'darwin' && platform() !== 'linux') return [];++ return [+ path.join(homedir(), '.local', 'bin', 'amp'),+ path.join(homedir(), '.amp', 'bin', 'amp'),+ path.join(homedir(), '.bun', 'bin', 'amp'),+ path.join(homedir(), '.npm-global', 'bin', 'amp'),+ path.join(homedir(), 'Library', 'pnpm', 'amp'),+ ];+ }case 'claude-code': {if (platform() !== 'darwin' && platform() !== 'linux') return [];diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.tsindex 0c518865e9a..ce1d1a6e5a2 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts@@ -17,8 +17,7 @@ const execFileMock = vi.mocked(childProcess.execFile);const callExecFile = (stdout: string) => {execFileMock.mockImplementationOnce(((...args: unknown[]) => {const callback = [...args].reverse().find((arg) => typeof arg === 'function') as- | ((error: Error | null, stdout: string) => void)- | undefined;+ ((error: Error | null, stdout: string) => void) | undefined;callback?.(null, stdout);return {} as childProcess.ChildProcess;}) as typeof childProcess.execFile);@@ -182,6 +181,48 @@ describe('spawnAgent', () => {expect(args[resumeIdx + 1]).toBe('cc-prev-123');});+ it('spawns AMP with its private headless stream-json protocol', async () => {+ nextFakeProc = createFakeProc().proc;+ const { spawnAgent } = await import('./spawnAgent');+ await spawnAgent({ agentType: 'amp', operationId: 'op-amp', prompt: 'hello' });++ const { args, command } = spawnCalls[0];+ expect(command).toBe('amp');+ expect(args).toEqual([+ '--execute',+ '--stream-json-thinking',+ '--stream-json-input',+ '--visibility',+ 'private',+ '--no-ide',+ '--no-notifications',+ '--no-archive-after-execute',+ ]);+ expect(JSON.parse((nextFakeProc as any).stdin.write.mock.calls[0][0].trim())).toMatchObject({+ message: { content: [{ text: 'hello', type: 'text' }], role: 'user' },+ type: 'user',+ });+ });++ it('uses `threads continue <id>` before AMP execution flags on resume', async () => {+ nextFakeProc = createFakeProc().proc;+ const { spawnAgent } = await import('./spawnAgent');+ await spawnAgent({+ agentType: 'amp',+ operationId: 'op-amp',+ prompt: 'continue',+ resumeSessionId: 'T-previous',+ });++ expect(spawnCalls[0].args.slice(0, 4)).toEqual([+ 'threads',+ 'continue',+ 'T-previous',+ '--execute',+ ]);+ expect(spawnCalls[0].args).toContain('--stream-json-input');+ });+it('builds codex args with `exec` + json + skip-git-repo-check + bypass approvals/sandbox', async () => {nextFakeProc = createFakeProc().proc;const { spawnAgent } = await import('./spawnAgent');diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex feef5d0f8c9..7c840018058 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -10,11 +10,11 @@ import type { AgentPromptInput, BuildAgentInputOptions } from './input';import { buildAgentInput } from './input';export interface SpawnAgentOptions {- /** Agent type key (`'claude-code'` | `'codex'`). */+ /** Agent type key (`'amp'` | `'claude-code'` | `'codex'`). */agentType: string;/**- * Override the CLI binary name. Defaults to `'claude'` for `claude-code`,- * `'codex'` for `codex`. Use this when the binary lives at a non-default+ * Override the CLI binary name. Defaults to the agent's standard executable.+ * Use this when the binary lives at a non-default* path or is wrapped by a launcher.*/command?: string;@@ -160,6 +160,22 @@ export const CODEX_EXECUTION_MODE_FLAGS = ['-s',] as const;+/**+ * Headless, private AMP execution flags shared by desktop and `lh hetero exec`.+ * AMP's stream-json protocol reports terminal failures as JSON even when the+ * process exits with code 0, so the dedicated adapter owns result validation.+ */+export const AMP_BASE_ARGS = [+ '--execute',+ '--stream-json-thinking',+ '--stream-json-input',+ '--visibility',+ 'private',+ '--no-ide',+ '--no-notifications',+ '--no-archive-after-execute',+] as const;+const hasAnyFlag = (args: string[], flags: readonly string[]) =>args.some((arg) => flags.includes(arg as (typeof flags)[number]));@@ -200,8 +216,19 @@ const buildCodexArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawnArg: ['exec', ...optionArgs];};+const buildAmpArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawnArgsParams) => {+ const executionArgs = [...AMP_BASE_ARGS, ...inputArgs, ...extraArgs];++ return resumeSessionId+ ? ['threads', 'continue', resumeSessionId, ...executionArgs]+ : executionArgs;+};+const buildSpawnArgs = (params: BuildSpawnArgsParams): string[] => {switch (params.agentType) {+ case 'amp': {+ return buildAmpArgs(params);+ }case 'claude-code': {return buildClaudeCodeArgs(params);}@@ -214,7 +241,19 @@ const buildSpawnArgs = (params: BuildSpawnArgsParams): string[] => {}};-const defaultCommand = (agentType: string): string => (agentType === 'codex' ? 'codex' : 'claude');+const defaultCommand = (agentType: string): string => {+ switch (agentType) {+ case 'amp': {+ return 'amp';+ }+ case 'codex': {+ return 'codex';+ }+ default: {+ return 'claude';+ }+ }+};const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {if (!proc.pid || proc.killed) return;@@ -244,7 +283,7 @@ const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {};/**- * Spawn an external agent CLI (Claude Code or Codex) and yield its stream as+ * Spawn an external agent CLI (Amp, Claude Code, or Codex) 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/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 65acc73ea0b..e85fdc93028 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -360,6 +360,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.auto': 'Auto','heteroAgent.executionTarget.autoDesc':'Use an online device automatically, picking one when several are available',@@ -584,6 +586,17 @@ export default {"Skill wasn't added. Retry, or create an Agent anyway.",'createModal.skillSuggestion.title': 'A Skill may fit better','createModal.title': 'What should this Agent do?',+ 'ampInstallGuide.actions.openDocs': 'Open Install Guide',+ 'ampInstallGuide.actions.openSystemTools': 'Open System Tools',+ 'ampInstallGuide.afterInstall':+ 'After installing, run `amp login`, then retry your message or click Re-detect in System Tools.',+ 'ampInstallGuide.desc':+ 'Amp needs the Amp CLI to run locally. Install it and make sure the `amp` command is available in your PATH.',+ 'ampInstallGuide.installWithBrew': 'Homebrew (macOS)',+ 'ampInstallGuide.installWithNpm': 'Recommended install',+ 'ampInstallGuide.menuNotification.title': 'Amp CLI not found',+ 'ampInstallGuide.reason': 'LobeHub could not start Amp: {{message}}',+ 'ampInstallGuide.title': 'Install Amp CLI','claudeCodeInstallGuide.actions.openDocs': 'Open Install Guide','claudeCodeInstallGuide.actions.openSystemTools': 'Open System Tools','claudeCodeInstallGuide.afterInstall':@@ -662,6 +675,7 @@ export default {'codexInstallGuide.title': 'Install Codex CLI','addAgentFromMarket': 'Add from Market','newAgent': 'Create Agent',+ 'newAmpAgent': 'Add Amp','newClaudeCodeAgent': 'Add Claude Code','newCodexAgent': 'Add Codex','newPlatformAgent': 'Connect Agent',diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.tsindex 4b147fa4542..4cc58e4dfa5 100644--- a/packages/types/src/agent/agencyConfig.test.ts+++ b/packages/types/src/agent/agencyConfig.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';+import type { HeterogeneousProviderConfig } from './agencyConfig';import {buildHeteroExecArgs,buildHeteroSpawnArgs,@@ -70,6 +71,13 @@ describe('buildHeteroSpawnArgs', () => {]);});+ it('passes AMP native args through direct spawns and encodes them for lh hetero exec', () => {+ const provider: HeterogeneousProviderConfig = { args: ['--mode', 'high'], type: 'amp' };++ expect(buildHeteroSpawnArgs(provider)).toEqual(['--mode', 'high']);+ expect(buildHeteroExecArgs(provider)).toEqual(['--agent-arg=--mode', '--agent-arg=high']);+ });+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.tsindex 6c5d026f95e..45002ed0004 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -98,10 +98,10 @@ const CODEX_FAST_SERVICE_TIER_VALUES = ['fast', 'priority'] as const;** Two families of hetero agents are supported:*- * - **Local CLI** (`claude-code` | `codex`): spawned as a child process on the+ * - **Local CLI** (`amp` | `claude-code` | `codex`): spawned as a child process on the* desktop; uses `command`, `args`, `env`, `systemContext`.*- * - **Remote device** (`openclaw` | `hermes` | `amp` | `opencode`): dispatched to a machine+ * - **Remote platform** (`openclaw` | `hermes` | `opencode`): 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'`).*/@@ -451,7 +451,9 @@ export const buildHeteroExecArgs = (provider: HeterogeneousProviderConfig | undefined | null,): string[] | undefined => {if (!provider) return undefined;- if (provider.type !== 'claude-code' && provider.type !== 'codex') return provider.args;+ if (provider.type !== 'amp' && provider.type !== 'claude-code' && provider.type !== 'codex') {+ return provider.args;+ }const baseArgs = provider.args ?? [];const wrapperArgs = baseArgs.map((arg) => `${HETERO_EXEC_AGENT_ARG_FLAG}=${arg}`);diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex b2e3ebb2783..e5618bc0048 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -355,11 +355,12 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {const heteroType = agencyConfig?.heterogeneousProvider?.type;const boundDeviceId = agencyConfig?.boundDeviceId;- // Heterogeneous agents (Claude Code / Codex — remote types already early-return+ // Local heterogeneous agents (remote types already early-return// below) bring their own toolchain and must execute somewhere, so `'none'`// (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';// Workspace-keyed SWR fetch — the raw lambdaQuery key has no workspace// dimension, so the picker kept showing the previous workspace's pool after@@ -388,6 +389,16 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {isHetero,});+ // 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.+ useEffect(() => {+ if (heteroType !== 'amp') return;+ if (isWorkspacePreferenceLoading) return;+ if (executionTarget !== 'none') return;+ setOpen(true);+ }, [executionTarget, heteroType, isWorkspacePreferenceLoading]);+const selectExecutionTarget = useSelectExecutionTarget(agentId);const handleSelect = useCallback(async (target: DeviceExecutionTarget, deviceId?: string) => {@@ -603,9 +614,14 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {) : null}<OptionRowactive={isActive('sandbox')}- desc={t('heteroAgent.executionTarget.sandboxDesc')}+ disabled={!supportsSandbox}icon={<Icon icon={BoxIcon} size={14} />}label={t('heteroAgent.executionTarget.sandbox')}+ desc={t(+ supportsSandbox+ ? 'heteroAgent.executionTarget.sandboxDesc'+ : 'heteroAgent.executionTarget.ampSandboxUnsupported',+ )}onClick={() => void handleSelect('sandbox')}/>{deviceRows.length > 0 ? (diff --git a/src/features/Conversation/Error/heterogeneous.ts b/src/features/Conversation/Error/heterogeneous.tsindex c6da4adc972..afe1dfe5fc4 100644--- a/src/features/Conversation/Error/heterogeneous.ts+++ b/src/features/Conversation/Error/heterogeneous.ts@@ -5,7 +5,7 @@ import {import type { UIChatMessage } from '@lobechat/types';/**- * Heterogeneous-agent (Claude Code / Codex) session errors that render the+ * Heterogeneous CLI-agent session errors that render the* dedicated status-guide card (auth required, CLI missing, overload, rate* limit). Kept in this dependency-free module so non-React callers (e.g. the* message action bar) can branch on them without pulling the whole Error UI@@ -26,7 +26,7 @@ export const isHeterogeneousAgentStatusGuideError = (const { agentType, code } = value as Partial<HeterogeneousAgentSessionError>;return (- (agentType === 'claude-code' || agentType === 'codex') &&+ (agentType === 'amp' || agentType === 'claude-code' || agentType === 'codex') &&typeof code === 'string' &&HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES.has(code));diff --git a/src/features/CreatePlatformAgent/index.tsx b/src/features/CreatePlatformAgent/index.tsxindex c51b1afd741..7b75b9fd08d 100644--- a/src/features/CreatePlatformAgent/index.tsx+++ b/src/features/CreatePlatformAgent/index.tsx@@ -112,7 +112,7 @@ interface CreatePlatformAgentContentProps {visibility?: 'private' | 'public';}-const COMING_SOON_PLATFORMS = new Set<RemoteHeterogeneousAgentType>(['amp', 'opencode']);+const COMING_SOON_PLATFORMS = new Set<RemoteHeterogeneousAgentType>(['opencode']);const CreatePlatformAgentContent = memo<CreatePlatformAgentContentProps>(({ groupId, visibility }) => {diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsxindex e2f77407fae..00dd2ea55aa 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx@@ -1,10 +1,12 @@import {+ AMP_CLI_INSTALL_COMMANDS,+ AMP_CLI_INSTALL_DOCS_URL,CLAUDE_CODE_CLI_INSTALL_COMMANDS,CLAUDE_CODE_CLI_INSTALL_DOCS_URL,CODEX_CLI_INSTALL_COMMANDS,CODEX_CLI_INSTALL_DOCS_URL,} from '@lobechat/electron-client-ipc';-import { ClaudeCode, Codex } from '@lobehub/icons';+import { Amp, ClaudeCode, Codex } from '@lobehub/icons';import {type HeterogeneousAgentGuideConfig,@@ -13,6 +15,14 @@ import {} from './types';export const HETEROGENEOUS_AGENT_GUIDE_CONFIG = {+ 'amp': {+ docsUrl: AMP_CLI_INSTALL_DOCS_URL,+ icon: Amp,+ installCommands: AMP_CLI_INSTALL_COMMANDS,+ signInCommand: 'amp login',+ title: 'Amp',+ translationPrefix: 'ampInstallGuide',+ },'claude-code': {docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,icon: ClaudeCode,diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.tsindex 80188904efe..6a0f1e9721f 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts@@ -40,7 +40,7 @@ export interface HeterogeneousAgentStatusGuideProps {variant?: HeterogeneousAgentStatusGuideVariant;}-export const SUPPORTED_HETEROGENEOUS_AGENT_TYPES = ['claude-code', 'codex'] as const;+export const SUPPORTED_HETEROGENEOUS_AGENT_TYPES = ['amp', 'claude-code', 'codex'] as const;export type SupportedHeterogeneousAgentType = (typeof SUPPORTED_HETEROGENEOUS_AGENT_TYPES)[number];diff --git a/src/features/Recommendations/actions/heteroAgent.test.ts b/src/features/Recommendations/actions/heteroAgent.test.tsnew file mode 100644index 00000000000..a00e1b0ec3e--- /dev/null+++ b/src/features/Recommendations/actions/heteroAgent.test.ts@@ -0,0 +1,15 @@+import { HETEROGENEOUS_AGENT_CLIENT_CONFIGS } from '@lobechat/heterogeneous-agents/client';+import { isValidElement } from 'react';+import { describe, expect, it } from 'vitest';++import { buildHeteroAgentAction } from './heteroAgent';++describe('buildHeteroAgentAction', () => {+ it.each(HETEROGENEOUS_AGENT_CLIENT_CONFIGS)('builds a valid icon for $type', (config) => {+ const { icon } = buildHeteroAgentAction(config);++ expect(isValidElement(icon)).toBe(true);+ if (!isValidElement(icon)) throw new Error(`Expected a React element for ${config.type}`);+ expect(icon.type).toBeDefined();+ });+});diff --git a/src/features/Recommendations/actions/heteroAgent.ts b/src/features/Recommendations/actions/heteroAgent.tsindex 01dff98ab5f..6cd86fed125 100644--- a/src/features/Recommendations/actions/heteroAgent.ts+++ b/src/features/Recommendations/actions/heteroAgent.ts@@ -1,10 +1,11 @@-import { type HeterogeneousAgentClientConfig } from '@lobechat/heterogeneous-agents/client';-import { ClaudeCode, Codex } from '@lobehub/icons';+import type { HeterogeneousAgentClientConfig } from '@lobechat/heterogeneous-agents/client';+import { Amp, ClaudeCode, Codex } from '@lobehub/icons';import { createElement } from 'react';import type { RecommendedAction } from './types';const avatarIcons = {+ 'amp': Amp.Avatar,'claude-code': ClaudeCode.Avatar,'codex': Codex.Avatar,} as const satisfies Record<HeterogeneousAgentClientConfig['type'], unknown>;diff --git a/src/features/Recommendations/hooks/useHeteroDetections.ts b/src/features/Recommendations/hooks/useHeteroDetections.tsindex 757c13e8dec..5a46c68e83c 100644--- a/src/features/Recommendations/hooks/useHeteroDetections.ts+++ b/src/features/Recommendations/hooks/useHeteroDetections.ts@@ -9,7 +9,7 @@ import { binaryService } from '@/services/electron/binary';import type { HeteroDetectionMap } from '../actions/types';/**- * Probe local Claude Code / Codex CLIs in parallel and cache the result.+ * Probe local heterogeneous agent CLIs in parallel and cache the result.** Returns an empty map on non-desktop runtimes so callers can skip without a* branch on every read. The Electron tool detector caches its own results, sodiff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.tsindex 3ab05e0f21a..a40342ce3cb 100644--- a/src/helpers/executionTarget.test.ts+++ b/src/helpers/executionTarget.test.ts@@ -12,6 +12,10 @@ import {} from './executionTarget';const cfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig => ({ ...over });+const ampCfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig => ({+ heterogeneousProvider: { command: 'amp', type: 'amp' },+ ...over,+});describe('resolveExecutionTarget', () => {it('returns the stored target verbatim when set', () => {@@ -120,6 +124,55 @@ describe('resolveExecutionTarget', () => {).toBe('sandbox');});+ describe('hetero providers without sandbox execution', () => {+ it('keeps an unconfigured Amp agent pending on web instead of defaulting to sandbox', () => {+ expect(+ resolveExecutionTarget(ampCfg(), {+ clientExecutionAvailable: false,+ isHetero: true,+ }),+ ).toBe('none');++ // Desktop can still run the CLI in-process, so its default remains local.+ expect(+ resolveExecutionTarget(ampCfg(), {+ clientExecutionAvailable: true,+ isHetero: true,+ }),+ ).toBe('local');+ });++ it('normalizes unsupported Amp sandbox and unbound web-local targets to pending', () => {+ for (const executionTarget of ['sandbox', 'local'] as const) {+ expect(+ resolveExecutionTarget(ampCfg({ 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' }), {+ clientExecutionAvailable: false,+ isHetero: true,+ }),+ ).toBe('device');+ });++ it('accepts an explicit capability override for legacy model-only configs', () => {+ expect(+ resolveExecutionTarget(undefined, {+ clientExecutionAvailable: false,+ isHetero: true,+ sandboxExecutionAvailable: false,+ }),+ ).toBe('none');+ });+ });+describe('workspaceScoped — a workspace agent never executes on the member client', () => {it('suppresses the desktop `local` default (unset → none, hetero → sandbox)', () => {expect(@@ -782,6 +835,28 @@ describe('resolveExecutionPlan', () => {expect(plan).toEqual({ kind: 'sandbox', target: 'sandbox' });}});++ 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('uses an explicit sandbox capability override for legacy model-only Amp agents', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: undefined,+ clientExecutionAvailable: false,+ isHetero: true,+ sandboxExecutionAvailable: false,+ }),+ ).toEqual({ kind: 'none', target: 'none' });+ });});});diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.tsindex 65009162ac9..9bc482ab639 100644--- a/src/helpers/executionTarget.ts+++ b/src/helpers/executionTarget.ts@@ -61,11 +61,19 @@ export interface ResolveExecutionTargetOptions {*/deviceRoutingAvailable?: boolean;/**- * Heterogeneous agents (Claude Code / Codex) bring their own toolchain and- * must execute somewhere, so `'none'` is not a valid target for them: it- * coerces to `'local'` on desktop and `'sandbox'` on web.+ * Heterogeneous agents bring their own toolchain and must execute somewhere,+ * so `'none'` normally coerces to `'local'` on desktop and `'sandbox'` on+ * web. A provider without sandbox support keeps `'none'` as a pending device+ * selection instead.*/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.+ */+ sandboxExecutionAvailable?: boolean;/*** What initiated the run. A `bot` trigger has no UI to pick a device, and* `local` (in-process IPC) is unreachable from the cloud bot server — so a@@ -82,9 +90,10 @@ export interface ResolveExecutionTargetOptions {* would silently run the shared agent on whichever personal machine opened* it. Treats client execution as unavailable: an unset target no longer* defaults to `local`, and a stored `local` (synced from before the agent- * joined the workspace) coerces to `sandbox` — or, for hetero agents, to- * `device` when a (grandfathered) `boundDeviceId` pins a machine, matching- * the write-time guard in `AgentModel.assertWorkspaceDeviceBinding`.+ * joined the workspace) coerces to `sandbox` when supported (otherwise+ * `none`) — or, for hetero agents, to `device` when a (grandfathered)+ * `boundDeviceId` pins a machine, matching the write-time guard in+ * `AgentModel.assertWorkspaceDeviceBinding`.*/workspaceScoped?: boolean;}@@ -119,8 +128,10 @@ export interface ResolveExecutionTargetOptions {* This upgrade is gated on `deviceRoutingAvailable` (or `isHetero`): the run* can only reach the bound device if a device-gateway exists to route it. Web* display sites pass `!!serverConfig.agentGatewayUrl` (cloud always has one);- * a no-gateway self-host has no route, so its bound `local` stays `sandbox`.- * An UNBOUND `local` (no `boundDeviceId`) always falls back to `sandbox` on web.+ * a no-gateway self-host has no route, so its bound `local` stays `sandbox`+ * when the provider supports it. An UNBOUND `local` (no `boundDeviceId`) falls+ * back to `sandbox` on web, or to the pending `none` state for device-only+ * providers.* Server callers leave `deviceRoutingAvailable` unset — with a gateway they* already pass `clientExecutionAvailable: true` and skip this branch, so it is* inert server-side and never diverts a no-gateway run away from `sandbox`.@@ -137,6 +148,7 @@ export const resolveExecutionTarget = (clientExecutionAvailable,deviceRoutingAvailable,isHetero,+ sandboxExecutionAvailable,trigger,workspaceScoped,}: ResolveExecutionTargetOptions,@@ -144,6 +156,8 @@ export const resolveExecutionTarget = (// A workspace agent never executes on the current member's own client — see// `workspaceScoped` above. Same coercions as a client-less environment.const clientAvailable = clientExecutionAvailable && !workspaceScoped;+ const sandboxAvailable =+ sandboxExecutionAvailable ?? agencyConfig?.heterogeneousProvider?.type !== 'amp';const stored = agencyConfig?.executionTarget;let effective = stored ?? (clientAvailable ? 'local' : 'none');if (@@ -154,8 +168,15 @@ export const resolveExecutionTarget = () {return 'device';}- if (isHetero && effective === 'none') effective = clientAvailable ? 'local' : 'sandbox';- if (!clientAvailable && effective === 'local') return 'sandbox';+ if (isHetero && effective === 'none') {+ if (clientAvailable) effective = 'local';+ else if (sandboxAvailable) effective = 'sandbox';+ }+ // Never leave an unsupported sandbox target active. `none` is a pending+ // selection for hetero providers without cloud execution: the UI blocks the+ // run and prompts for a local or connected device.+ if (!sandboxAvailable && effective === 'sandbox') effective = 'none';+ if (!clientAvailable && effective === 'local') return sandboxAvailable ? 'sandbox' : 'none';// Bot trigger: a `local` target can't run in-process from the cloud bot// server, so it has to reach a real device. If the user pinned a specific// machine (the switcher persists that desktop's own `deviceId` as@@ -301,6 +322,8 @@ export interface ResolveExecutionPlanParams {* of the stored target.*/requestedDeviceId?: string;+ /** See {@link ResolveExecutionTargetOptions.sandboxExecutionAvailable}. */+ sandboxExecutionAvailable?: boolean;/*** What initiated this run. Bot triggers have no UI to pick a device, so a* stored `local` target (in-process IPC, unreachable from the cloud bot@@ -343,6 +366,7 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): ExecutisHetero,onlineDeviceIds,requestedDeviceId,+ sandboxExecutionAvailable,trigger,workspaceScoped,} = params;@@ -357,18 +381,21 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Executconst target = resolveExecutionTarget(agencyConfig, {isHetero,clientExecutionAvailable,+ sandboxExecutionAvailable,trigger,workspaceScoped,});+ const sandboxAvailable =+ sandboxExecutionAvailable ?? agencyConfig?.heterogeneousProvider?.type !== 'amp';const wantsDevice =!!requestedDeviceId || target === 'device' || target === 'local' || target === 'auto';if (!wantsDevice || !canUseDevice) {if (target === 'sandbox') return { kind: 'sandbox', target: 'sandbox' };- // Hetero agents must execute somewhere — a device-capable target denied- // by the access policy falls back to the cloud sandbox (which never- // touches user machines) instead of the hetero-invalid `none`.- if (isHetero) return { kind: 'sandbox', target: 'sandbox' };+ // Hetero agents that support cloud execution fall back to the sandbox when+ // no device can run. Device-only providers stay pending at `none` so the+ // caller can require an explicit local/connected-device selection.+ if (isHetero && sandboxAvailable) return { kind: 'sandbox', target: 'sandbox' };// a device-capable target denied by the access policy degrades to plain// chat — the effective target is `none`, not the stored onereturn { kind: 'none', target: 'none' };diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsxindex ee0e1ea015d..1b32e74a300 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx@@ -47,7 +47,7 @@ const leftActions: ActionKeys[] = [];* block, no oversized 24px icon) so the guard stays a compact strip instead of* eating a chunk of the conversation area.*/-const GuardBanner = memo<{ action: ReactNode; hint?: string; title: string }>(+const GuardBanner = memo<{ action?: ReactNode; hint?: string; title: string }>(({ title, hint, action }) => (<WideScreenContainer><Flexbox align={'center'} paddingBlock={'0 8px'} paddingInline={12}>@@ -106,6 +106,7 @@ const HeterogeneousChatInput = memo(() => {workspaceScoped: isWorkspaceAgent,});const isRemoteAgent = !!providerType && isRemoteHeterogeneousType(providerType);+ const ampDeviceSelectionRequired = providerType === 'amp' && 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.@@ -197,7 +198,9 @@ 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 || isDeviceExecution || isConfigured) return null;+ if (isPreferenceLoading || ampDeviceSelectionRequired || isDeviceExecution || isConfigured) {+ return null;+ }return (<GuardBanner@@ -212,16 +215,32 @@ const HeterogeneousChatInput = memo(() => {);};+ const renderAmpDeviceGuard = () => {+ if (!ampDeviceSelectionRequired) return null;++ return (+ <GuardBanner+ hint={t('heteroAgent.executionTarget.ampSandboxUnsupported')}+ title={t('platformAgent.deviceGuard.noDevice.title')}+ />+ );+ };+// Device execution doesn't use the cloud sandbox, so it doesn't need cloud// credentials — only the sandbox path gates on `isConfigured`. While the// workspace preference loads, keep send disabled: the effective target isn't// known yet, so neither guard can vouch for the run.const inputDisabled =- isPreferenceLoading || (!isConfigured && !isDeviceExecution) || deviceBlocked;- const hasGuard = deviceBlocked || (!isConfigured && !isDeviceExecution);+ isPreferenceLoading ||+ ampDeviceSelectionRequired ||+ (!isConfigured && !isDeviceExecution) ||+ deviceBlocked;+ const hasGuard =+ ampDeviceSelectionRequired || deviceBlocked || (!isConfigured && !isDeviceExecution);return (<Flexbox>+ {renderAmpDeviceGuard()}{renderCloudConfigGuard()}{renderDeviceGuard()}<ChatInputdiff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsxindex bc8d8e3c1df..30cb9327f46 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx@@ -233,7 +233,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(const displayName = providerConfig?.title || provider.type;const AgentIcon = providerConfig?.icon;const showCliInstallGuide =- (provider.type === 'claude-code' || provider.type === 'codex') &&+ (provider.type === 'amp' || provider.type === 'claude-code' || provider.type === 'codex') &&!detecting &&!status?.available &&!isUsingCustomCommand;@@ -254,7 +254,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(}, [provider.type, resolvedCommand]);const detect = useCallback(async () => {- // Remote platform agents (openclaw, hermes, amp, opencode, …) have no local CLI to detect.+ // Remote platform agents (openclaw, hermes, opencode, …) 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.tsxindex ca2b8e07a69..65f73d85c05 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx@@ -42,6 +42,16 @@ vi.mock('@lobechat/heterogeneous-agents/client', () => ({title: 'Codex',type: 'codex',},+ {+ avatar: 'amp-avatar',+ command: 'amp',+ icon: () => null,+ iconId: 'Amp',+ menuKey: 'newAmpAgent',+ menuLabelKey: 'newAmpAgent',+ title: 'Amp',+ type: 'amp',+ },],}));@@ -167,6 +177,7 @@ describe('useCreateMenuItems', () => {'divider','newClaudeCodeAgent','newCodexAgent',+ 'newAmpAgent','divider','addAgentFromMarket',]);@@ -257,4 +268,29 @@ describe('useCreateMenuItems', () => {expect(refreshAgentListMock).toHaveBeenCalled();expect(navigateMock).toHaveBeenCalledWith('/agent/agent-codex');});++ it('creates AMP as an independent local CLI agent', async () => {+ const { result } = renderHook(() => useCreateMenuItems());++ const ampItem = result.current+ .createHeterogeneousAgentMenuItems()+ .find((item) => isActionItem(item) && item.key === 'newAmpAgent');++ if (!isActionItem(ampItem)) throw new Error('Expected AMP menu item');++ await act(async () => {+ await ampItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });+ });++ expect(createAgentMock).toHaveBeenCalledWith({+ config: {+ agencyConfig: { heterogeneousProvider: { command: 'amp', type: 'amp' } },+ avatar: 'amp-avatar',+ provider: 'amp',+ systemRole: '',+ title: 'Amp',+ },+ groupId: undefined,+ });+ });});diff --git a/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts b/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.tsindex 6b26d994cce..fb9197b3ee8 100644--- a/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts+++ b/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts@@ -110,14 +110,19 @@ export const selectRuntimeType = (if (ctx.heterogeneousProvider && isRemoteHeterogeneousType(ctx.heterogeneousProvider.type)) {return 'gateway';}- // Local CLI hetero (claude-code / codex) — route by the resolved execution+ // Local CLI hetero (Amp / Claude Code / Codex) — route by the resolved execution// target (shared resolution with the server / the device switcher UI):// `device` / `sandbox` need server-side dispatch; `local` runs in-process on- // the desktop. On web, unbound `local` resolves to sandbox, while a desktop- // `local` selection synced with boundDeviceId resolves to device dispatch.+ // the desktop. On web, unbound `local` resolves to sandbox when supported+ // (otherwise the pending `none` state), while a desktop `local` selection+ // synced with boundDeviceId resolves to device dispatch.if (ctx.heterogeneousProvider) {const target = resolveExecutionTarget(- { boundDeviceId: ctx.boundDeviceId, executionTarget: ctx.executionTarget },+ {+ boundDeviceId: ctx.boundDeviceId,+ executionTarget: ctx.executionTarget,+ heterogeneousProvider: ctx.heterogeneousProvider,+ },// on the client the desktop build IS where local execution is available{isHetero: true,diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 96fd85300c7..da170e615d6 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -4,6 +4,7 @@ import type {AgentStreamEvent,} from '@lobechat/agent-gateway-client';import {+ AMP_CLI_INSTALL_DOCS_URL,CLAUDE_CODE_CLI_INSTALL_DOCS_URL,CODEX_CLI_INSTALL_DOCS_URL,type HeterogeneousAgentSessionError,@@ -89,21 +90,45 @@ const CLI_AUTH_REQUIRED_PATTERNS = [/\bunauthorized\b/i,/\b401\b/,] as const;+const AMP_AUTH_REQUIRED_PATTERNS = [/please (?:log|sign) in/i, /amp_api_key/i] as const;const buildCliAuthRequiredSessionError = (- agentType: 'claude-code' | 'codex',+ agentType: 'amp' | 'claude-code' | 'codex',rawMessage: string,-): HeterogeneousAgentSessionError => ({- agentType,- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- docsUrl:- agentType === 'claude-code' ? CLAUDE_CODE_CLI_INSTALL_DOCS_URL : CODEX_CLI_INSTALL_DOCS_URL,- message:- agentType === 'claude-code'- ? 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.'- : 'Codex could not authenticate. Sign in again or refresh its credentials, then retry.',- stderr: rawMessage,-});+): HeterogeneousAgentSessionError => {+ switch (agentType) {+ case 'amp': {+ return {+ agentType,+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ docsUrl: AMP_CLI_INSTALL_DOCS_URL,+ message:+ 'Amp could not authenticate. Run `amp login` or configure AMP_API_KEY, then retry.',+ stderr: rawMessage,+ };+ }+ case 'claude-code': {+ return {+ agentType,+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,+ message:+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',+ stderr: rawMessage,+ };+ }+ case 'codex': {+ return {+ agentType,+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,+ docsUrl: CODEX_CLI_INSTALL_DOCS_URL,+ message:+ 'Codex could not authenticate. Sign in again or refresh its credentials, then retry.',+ stderr: rawMessage,+ };+ }+ }+};const normalizeErrorText = (value?: string) => value?.replaceAll(/\s+/g, ' ').trim();@@ -111,7 +136,7 @@ const maybeClassifyCliAuthRequiredError = (error: unknown,agentType?: string,): HeterogeneousAgentSessionError | undefined => {- if (agentType !== 'claude-code' && agentType !== 'codex') return;+ if (agentType !== 'amp' && agentType !== 'claude-code' && agentType !== 'codex') return;const message =error instanceof Error@@ -125,7 +150,12 @@ const maybeClassifyCliAuthRequiredError = (? error.message: undefined;- if (!message || !CLI_AUTH_REQUIRED_PATTERNS.some((pattern) => pattern.test(message))) return;+ if (!message) return;+ const patterns =+ agentType === 'amp'+ ? [...CLI_AUTH_REQUIRED_PATTERNS, ...AMP_AUTH_REQUIRED_PATTERNS]+ : CLI_AUTH_REQUIRED_PATTERNS;+ if (!patterns.some((pattern) => pattern.test(message))) return;return buildCliAuthRequiredSessionError(agentType, message);};@@ -148,6 +178,20 @@ const shouldSuppressTerminalErrorEcho = (content: string, error: ChatMessageErroreturn !!normalizedContent && !!normalizedRawError && normalizedContent === normalizedRawError;};+const getDefaultHeterogeneousCommand = (agentType: string): string => {+ switch (agentType) {+ case 'amp': {+ return 'amp';+ }+ case 'codex': {+ return 'codex';+ }+ default: {+ return 'claude';+ }+ }+};+const toHeterogeneousAgentMessageError = (error: unknown, agentType?: string): ChatMessageError => {const authRequiredError = maybeClassifyCliAuthRequiredError(error, agentType);if (authRequiredError) {@@ -1675,7 +1719,7 @@ export const executeHeterogeneousAgent = async (const result = await heterogeneousAgentService.startSession({agentType: adapterType,args: buildHeteroSpawnArgs(heterogeneousProvider),- command: heterogeneousProvider.command || (adapterType === 'codex' ? 'codex' : 'claude'),+ command: heterogeneousProvider.command || getDefaultHeterogeneousCommand(adapterType),cwd: workingDirectory,env: {// Tell the CLI which LobeHub conversation it is running inside. The childdiff --git a/src/store/tool/slices/builtin/executors/heteroCli.ts b/src/store/tool/slices/builtin/executors/heteroCli.tsindex 8f67934856e..40872be33ff 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- * (`claude-code` / `codex` — set by the adapters in+ * (`amp` / `claude-code` / `codex` — 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 (`claude-code` / `codex`).+ * @param identifier The CLI adapter's tool identifier (`amp` / `claude-code` / `codex`).* @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,7 +95,8 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {};}-// CC's shell tool is `Bash`; Codex's is `command_execution`.+// AMP's shell tool is `shell_command`; CC's is `Bash`; Codex's is `command_execution`.+export const ampExecutor = new HeteroCliExecutor('amp', new Set(['shell_command']));export const claudeCodeExecutor = new HeteroCliExecutor('claude-code', new Set(['Bash']), {enter: 'EnterWorktree',exit: 'ExitWorktree',diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.tsindex 17ec32e98dc..eb9fa1d73df 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 { claudeCodeExecutor, codexExecutor } from './heteroCli';+import { ampExecutor, claudeCodeExecutor, codexExecutor } from './heteroCli';import { activatorExecutor } from './lobe-activator';import { agentDocumentsExecutor } from './lobe-agent-documents';import { messageExecutor } from './lobe-message';@@ -139,8 +139,9 @@ export const registerBuiltinToolExecutors = (): void => {if (executorsRegistered) return;registerExecutors([- // Hook-only executors for heterogeneous CLI agents (Claude Code / Codex) —+ // Hook-only executors for heterogeneous CLI agents —// observe their shell tool results via `onAfterCall` (never invoked).+ ampExecutor,claudeCodeExecutor,codexExecutor,agentBuilderExecutor,