π€― 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(cli): add `lh agent connect` to connect external agent CLIs (#23752)
Arvin Xu7c10840d8a18
diff --git a/.agents/skills/cli/references/agent.md b/.agents/skills/cli/references/agent.mdindex db17fed987e..790d4d8fdba 100644--- a/.agents/skills/cli/references/agent.md+++ b/.agents/skills/cli/references/agent.md@@ -59,6 +59,28 @@ The workspace comes from the current scope (`LOBEHUB_WORKSPACE_ID` or `lh worksp---+## `lh agent connect [types...]`++Connect external agent CLIs (Claude Code, Codex, Antigravity, OpenClaw, β¦) as agents bound to a device: the CLI form of the Web "Connect agent" wizard, creating the same agent config.++```bash+lh agent connect [types...] [--device <deviceId>] [--visibility <private|public>] [-n <name>] [-d <desc>] [--yes] [--json [fields]]+```++| Option | Description |+| --------------------------- | --------------------------------------------------------------------------------------------------- |+| `types...` | Agent types to connect (e.g. `antigravity`, `claude-code`); omit to connect every one found |+| `--device <deviceId>` | Bind to this device instead of this machine (see `lh device list`) |+| `--visibility <visibility>` | Inside a workspace: `private` (default, only you) or `public` (workspace members) |+| `-n, --name <name>` | Agent name; only with exactly one type |+| `-d, --description <desc>` | Agent description; only with exactly one type |+| `--yes` | Skip the confirmation prompt (required without an interactive terminal) |+| `--json [fields]` | Print `{ created: [{ id, title, type, url, version? }], deviceId, skipped: [{ id, title, type }] }` |++The device defaults to this machine in the current scope's pool: its workspace device inside a workspace (only workspace devices qualify there), else its personal device. It must be connected (`lh connect`, or `lh connect --workspace <id>` for a workspace) and online. The device is scanned through the server, so a named type that is not installed there fails with the scan's reason. Types you already have an agent for on the device are skipped (teammates' agents on a shared workspace device do not count), so rerunning connects only what is missing. The scan checks the binary only: an agent CLI that needs sign-in (Antigravity, Codex, β¦) must be signed in on the device before its first run.++---+## `lh agent edit [agentId]`Update an existing agent. `agentId` may be omitted when `--slug` is given instead (note: unlikediff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.tsindex b7b54772deb..6d463ee4eac 100644--- a/apps/cli/src/commands/agent.ts+++ b/apps/cli/src/commands/agent.ts@@ -9,6 +9,7 @@ import { colorStatus, readOperationStatus } from '../utils/agentRunOutcome';import { confirm, outputJson, printTable, truncate } from '../utils/format';import { log } from '../utils/logger';import { registerAgentAccountCommand, registerAgentInboxCommand } from './agent/account';+import { registerAgentConnectCommand } from './agent/connect';import { registerAgentMoveCommands } from './agent/move';import { resolveAgentId } from './agent/resolveAgentId';import { registerAgentRunCommand } from './agent/run';@@ -481,6 +482,10 @@ export function registerAgentCommand(program: Command) {registerAgentMoveCommands(agent);+ // ββ connect βββββββββββββββββββββββββββββββββββββββββ++ registerAgentConnectCommand(agent);+// ββ kb-files βββββββββββββββββββββββββββββββββββββββagentdiff --git a/apps/cli/src/commands/agent/connect.test.ts b/apps/cli/src/commands/agent/connect.test.tsnew file mode 100644index 00000000000..442e6d48235--- /dev/null+++ b/apps/cli/src/commands/agent/connect.test.ts@@ -0,0 +1,288 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type * as FormatModule from '../../utils/format';+import { log } from '../../utils/logger';+import { registerAgentConnectCommand } from './connect';++const { mockTrpcClient, mockConfirm, mockWorkspaceId } = vi.hoisted(() => ({+ mockConfirm: vi.fn(),+ mockTrpcClient: {+ agent: { createAgent: { mutate: vi.fn() }, getAgentConfigById: { query: vi.fn() } },+ device: {+ getAgentProfile: { query: vi.fn() },+ getDeviceActivity: { query: vi.fn() },+ listDevices: { query: vi.fn() },+ scanAgents: { query: vi.fn() },+ },+ user: { getUserState: { query: vi.fn() } },+ },+ mockWorkspaceId: { current: undefined as string | undefined },+}));++vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn(async () => mockTrpcClient) }));+vi.mock('../../api/workspace', () => ({ resolveWorkspaceId: () => mockWorkspaceId.current }));+vi.mock('../../device/register', () => ({+ resolveDeviceIdentity: (userId?: string) =>+ userId ? { deviceId: `personal-${userId}`, identitySource: 'machine' } : undefined,+ resolveWorkspaceDeviceIdentity: (workspaceId: string) => ({+ deviceId: `ws-${workspaceId}`,+ identitySource: 'machine',+ }),+}));+vi.mock('../../settings', () => ({ loadOrCreateConnectionId: () => 'conn-1' }));+vi.mock('../task/url', () => ({+ resolveAppUrlBuilder: async () => (path: string) => `https://app.test${path}`,+}));+vi.mock('../../utils/format', async (importOriginal) => ({+ ...(await importOriginal<typeof FormatModule>()),+ confirm: mockConfirm,+}));++const PERSONAL_DEVICE = {+ deviceId: 'personal-u1',+ hostname: 'mac',+ online: true,+ scope: 'personal',+};+const WORKSPACE_DEVICE = { deviceId: 'ws-ws1', hostname: 'mac', online: true, scope: 'workspace' };++describe('agent connect', () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let exitSpy: ReturnType<typeof vi.spyOn>;+ let errorSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ vi.clearAllMocks();+ mockWorkspaceId.current = undefined;+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);+ errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});+ vi.spyOn(log, 'warn').mockImplementation(() => {});+ mockConfirm.mockResolvedValue(true);+ mockTrpcClient.user.getUserState.query.mockResolvedValue({ fullName: 'Arvin', userId: 'u1' });+ mockTrpcClient.device.listDevices.query.mockResolvedValue([PERSONAL_DEVICE, WORKSPACE_DEVICE]);+ mockTrpcClient.device.scanAgents.query.mockResolvedValue({+ agents: {+ 'antigravity': { available: true, version: '1.5.14' },+ 'claude-code': { available: true, version: '2.0.0' },+ 'codex': { available: false, reason: 'codex not found' },+ },+ });+ mockTrpcClient.device.getDeviceActivity.query.mockResolvedValue({ agents: [] });+ let n = 0;+ mockTrpcClient.agent.createAgent.mutate.mockImplementation(async () => ({+ agentId: `agt_${++n}`,+ }));+ });++ afterEach(() => {+ consoleSpy.mockRestore();+ exitSpy.mockRestore();+ });++ const run = (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerAgentConnectCommand(program.command('agent'));+ return program.parseAsync(['node', 'test', 'agent', 'connect', ...args]).catch(() => {});+ };++ const createdConfigs = () =>+ mockTrpcClient.agent.createAgent.mutate.mock.calls.map(([input]) => input);++ it('binds a named agent to this machine with the wizard config', async () => {+ await run('antigravity', '--yes');++ expect(mockConfirm).not.toHaveBeenCalled();+ expect(mockTrpcClient.device.scanAgents.query).toHaveBeenCalledWith({+ deviceId: 'personal-u1',+ });+ expect(createdConfigs()).toEqual([+ {+ config: expect.objectContaining({+ agencyConfig: {+ boundDeviceId: 'personal-u1',+ executionTarget: 'device',+ heterogeneousProvider: { command: 'agy', type: 'antigravity' },+ },+ name: 'Antigravity',+ provider: 'antigravity',+ title: 'Antigravity',+ }),+ },+ ]);+ });++ it('connects every available agent when no type is named', async () => {+ await run('--yes');++ expect(createdConfigs().map((input) => input.config.provider)).toEqual([+ 'antigravity',+ 'claude-code',+ ]);+ });++ it('binds the workspace device and prefixes a shared agent with its owner', async () => {+ mockWorkspaceId.current = 'ws1';++ await run('claude-code', '--visibility', 'public', '--yes');++ expect(createdConfigs()).toEqual([+ {+ config: expect.objectContaining({+ agencyConfig: expect.objectContaining({ boundDeviceId: 'ws-ws1' }),+ name: 'Arvinβs Claude Code',+ }),+ visibility: 'public',+ },+ ]);+ });++ it('refuses a personal device inside a workspace', async () => {+ mockWorkspaceId.current = 'ws1';+ mockTrpcClient.device.listDevices.query.mockResolvedValue([PERSONAL_DEVICE]);++ await run('antigravity', '--yes');++ expect(errorSpy).toHaveBeenCalledWith('This machine is not connected to workspace ws1.');+ expect(mockTrpcClient.device.scanAgents.query).not.toHaveBeenCalled();+ expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();+ });++ it('fails when the named agent is not installed on the device', async () => {+ await run('codex', '--yes');++ expect(errorSpy).toHaveBeenCalledWith('Codex was not found on the device: codex not found');+ expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();+ });++ it('fails on an offline device before scanning', async () => {+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { ...PERSONAL_DEVICE, online: false },+ ]);++ await run('antigravity', '--yes');++ expect(errorSpy).toHaveBeenCalledWith('Device mac is offline.');+ expect(mockTrpcClient.device.scanAgents.query).not.toHaveBeenCalled();+ });++ it('creates nothing when the confirmation is declined', async () => {+ mockConfirm.mockResolvedValue(false);++ await run('antigravity');++ expect(mockConfirm).toHaveBeenCalled();+ expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();+ });++ it('skips agent types already connected to the device', async () => {+ mockTrpcClient.device.getDeviceActivity.query.mockResolvedValue({+ agents: [{ id: 'agt_old' }],+ });+ mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({+ agencyConfig: { heterogeneousProvider: { type: 'antigravity' } },+ userId: 'u1',+ });+ const jsonSpy = vi.fn();+ consoleSpy.mockImplementation(jsonSpy);++ await run('--yes', '--json');++ expect(createdConfigs().map((input) => input.config.provider)).toEqual(['claude-code']);+ expect(JSON.parse(jsonSpy.mock.calls[0][0])).toEqual({+ created: [expect.objectContaining({ id: 'agt_1', type: 'claude-code', version: '2.0.0' })],+ deviceId: 'personal-u1',+ skipped: [{ id: 'agt_old', title: 'Antigravity', type: 'antigravity' }],+ });+ });++ it("does not skip a teammate's agent on a shared device", async () => {+ mockTrpcClient.device.getDeviceActivity.query.mockResolvedValue({+ agents: [{ id: 'agt_ann' }],+ });+ mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({+ agencyConfig: { heterogeneousProvider: { type: 'antigravity' } },+ userId: 'ann',+ });++ await run('antigravity', '--yes');++ expect(createdConfigs()).toHaveLength(1);+ });++ it('still connects when the existing-agent lookup fails', async () => {+ mockTrpcClient.device.getDeviceActivity.query.mockRejectedValue(new Error('boom'));++ await run('antigravity', '--yes');++ expect(createdConfigs()).toHaveLength(1);+ });++ it('rejects an unknown type before touching the network', async () => {+ await run('claud', '--yes');++ expect(errorSpy).toHaveBeenCalledWith('Unknown agent type: claud');+ expect(mockTrpcClient.device.listDevices.query).not.toHaveBeenCalled();+ });++ it('binds an explicit --device of the current pool', async () => {+ const other = { deviceId: 'dev-2', friendlyName: 'Build box', online: true, scope: 'personal' };+ mockTrpcClient.device.listDevices.query.mockResolvedValue([PERSONAL_DEVICE, other]);++ await run('antigravity', '--device', 'dev-2', '--yes');++ expect(mockTrpcClient.device.scanAgents.query).toHaveBeenCalledWith({ deviceId: 'dev-2' });+ expect(createdConfigs()[0].config.agencyConfig.boundDeviceId).toBe('dev-2');+ });++ it('prefills a platform agent from its device profile', async () => {+ mockTrpcClient.device.scanAgents.query.mockResolvedValue({+ agents: { openclaw: { available: true } },+ });+ mockTrpcClient.device.getAgentProfile.query.mockResolvedValue({+ description: 'My claw',+ title: 'Clawd',+ });++ await run('openclaw', '--yes');++ expect(mockTrpcClient.device.getAgentProfile.query).toHaveBeenCalledWith({+ deviceId: 'personal-u1',+ platform: 'openclaw',+ });+ expect(createdConfigs()[0].config).toMatchObject({+ agencyConfig: {+ boundDeviceId: 'personal-u1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'openclaw' },+ },+ description: 'My claw',+ name: 'Clawd',+ title: 'Clawd',+ });+ });++ it('reports the agents created before a failure', async () => {+ const warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => {});+ mockTrpcClient.agent.createAgent.mutate+ .mockResolvedValueOnce({ agentId: 'agt_a' })+ .mockRejectedValueOnce(new Error('quota'));++ await run('--yes');++ expect(warnSpy).toHaveBeenCalledWith('Created before the failure: agt_a');+ expect(errorSpy).toHaveBeenCalledWith('Failed to create the Claude Code agent: quota');+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('rejects --name with several types', async () => {+ await run('antigravity', 'claude-code', '--name', 'Mine', '--yes');++ expect(errorSpy).toHaveBeenCalledWith(+ '--name and --description need exactly one agent type, e.g. lh agent connect codex',+ );+ expect(mockTrpcClient.device.listDevices.query).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/agent/connect.ts b/apps/cli/src/commands/agent/connect.tsnew file mode 100644index 00000000000..fe23550f83f--- /dev/null+++ b/apps/cli/src/commands/agent/connect.ts@@ -0,0 +1,348 @@+/**+ * `lh agent connect [types...]` β the CLI counterpart of the Web "Connect+ * agent" wizard: scan a connected device for external agent CLIs (Claude Code,+ * Codex, Antigravity, β¦) and create one agent per pick, bound to that device.+ *+ * The device is this machine by default, in the pool of the current scope: a+ * workspace device inside a workspace, else the personal one. Both the scan+ * (`device.scanAgents`) and the agent config (`buildConnectAgentConfig`) are+ * the ones the wizard uses, so a CLI-created agent matches a wizard-created one.+ */+import type { HeterogeneousAgentScanMap } from '@lobechat/heterogeneous-agents';+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';+import type { ConnectableAgentDescriptor } from '@lobechat/heterogeneous-agents/connectAgent';+import {+ buildConnectAgentConfig,+ CONNECTABLE_AGENT_DESCRIPTORS,+ connectedAgentDefaultName,+ getConnectableAgentDescriptor,+} from '@lobechat/heterogeneous-agents/connectAgent';+import type { Command } from 'commander';+import { Option } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../api/client';+import { resolveWorkspaceId } from '../../api/workspace';+import { resolveDeviceIdentity, resolveWorkspaceDeviceIdentity } from '../../device/register';+import { loadOrCreateConnectionId } from '../../settings';+import { confirm, outputJson, printTable } from '../../utils/format';+import { log } from '../../utils/logger';+import { resolveAppUrlBuilder } from '../task/url';++const VISIBILITIES = ['private', 'public'] as const;+type Visibility = (typeof VISIBILITIES)[number];++interface ConnectOptions {+ description?: string;+ device?: string;+ json?: string | boolean;+ name?: string;+ visibility?: Visibility;+ yes?: boolean;+}++interface DeviceRow {+ deviceId: string;+ friendlyName?: string | null;+ hostname?: string | null;+ online?: boolean;+ scope?: 'personal' | 'workspace';+}++const fail = (message: string, hint?: string): never => {+ log.error(message);+ if (hint) console.log(pc.dim(hint));+ process.exit(1);+ // `process.exit` is mocked in tests; stop the action there too.+ throw new Error(message);+};++/** Same label as the Web wizard. */+const deviceLabel = (device: DeviceRow) =>+ device.friendlyName || device.hostname || device.deviceId;++const connectHint = (workspaceId?: string) =>+ workspaceId+ ? `Connect this machine to the workspace first: lh connect --workspace ${workspaceId}`+ : 'Connect this machine first: lh connect';++/**+ * The device to bind: `--device`, else this machine's identity in the current+ * scope's pool. Inside a workspace only workspace devices qualify, as in the+ * wizard's picker β a personal device is not reachable by the workspace.+ */+const resolveTargetDevice = async (+ devices: DeviceRow[],+ options: { deviceId?: string; userId?: string; workspaceId?: string },+): Promise<DeviceRow> => {+ const { deviceId, userId, workspaceId } = options;+ const eligible = workspaceId ? devices.filter((d) => d.scope === 'workspace') : devices;++ if (deviceId) {+ const device = eligible.find((d) => d.deviceId === deviceId);+ if (!device) {+ fail(+ workspaceId+ ? `Device ${deviceId} is not a device of workspace ${workspaceId}.`+ : `Device ${deviceId} not found.`,+ 'List the devices you can bind with: lh device list',+ );+ }+ return device!;+ }++ const ownId = workspaceId+ ? resolveWorkspaceDeviceIdentity(workspaceId, undefined, loadOrCreateConnectionId()).deviceId+ : resolveDeviceIdentity(userId)?.deviceId;+ const device = ownId ? eligible.find((d) => d.deviceId === ownId) : undefined;+ if (!device) {+ fail(+ workspaceId+ ? `This machine is not connected to workspace ${workspaceId}.`+ : 'This machine is not connected to LobeHub.',+ `${connectHint(workspaceId)}\nOr bind another device with --device <deviceId> (see lh device list).`,+ );+ }+ return device!;+};++/** Resolve the named types before any network call, so a typo fails first. */+const resolveNamedProviders = (types: string[]): ConnectableAgentDescriptor[] =>+ [...new Set(types)].map((type) => {+ const descriptor = getConnectableAgentDescriptor(type);+ if (!descriptor) {+ fail(+ `Unknown agent type: ${type}`,+ `Known types: ${CONNECTABLE_AGENT_DESCRIPTORS.map((d) => d.type).join(', ')}`,+ );+ }+ return descriptor!;+ });++/** The descriptors to connect: the named ones, else everything the scan found. */+const selectAvailable = (+ named: ConnectableAgentDescriptor[],+ agents: HeterogeneousAgentScanMap,+): ConnectableAgentDescriptor[] => {+ if (named.length === 0) {+ return CONNECTABLE_AGENT_DESCRIPTORS.filter((d) => agents[d.type]?.available);+ }++ for (const descriptor of named) {+ const status = agents[descriptor.type];+ if (!status?.available) {+ fail(+ `${descriptor.title} was not found on the device${status?.reason ? `: ${status.reason}` : '.'}`,+ 'Install it on that device (or put it on its PATH), then rerun.',+ );+ }+ }+ return named;+};++/**+ * Agent types the caller already has an agent for on the device, so a rerun+ * connects only what is missing. Teammates' agents on a shared workspace device+ * do not count: each member connects their own. Best effort: when the lookup fails the+ * command still connects, it just cannot skip duplicates.+ */+const findConnectedAgents = async (+ client: Awaited<ReturnType<typeof getTrpcClient>>,+ deviceId: string,+ userId: string | undefined,+): Promise<Map<string, string>> => {+ const connected = new Map<string, string>();+ try {+ const { agents } = (await client.device.getDeviceActivity.query({ deviceId })) as {+ agents: Array<{ id: string }>;+ };+ const configs = await Promise.all(+ agents.map((agent) => client.agent.getAgentConfigById.query({ agentId: agent.id })),+ );+ configs.forEach((config: any, index: number) => {+ const type = config?.agencyConfig?.heterogeneousProvider?.type;+ if (!type || connected.has(type) || config.userId !== userId) return;+ connected.set(type, agents[index].id);+ });+ } catch (error) {+ log.warn(+ `Could not list the agents already on this device, so duplicates are not skipped: ${(error as Error).message}`,+ );+ }+ return connected;+};++export function registerAgentConnectCommand(agent: Command) {+ agent+ .command('connect [types...]')+ .description(+ 'Scan a connected device for external agent CLIs (Claude Code, Codex, Antigravity, β¦) and create agents bound to it',+ )+ .option(+ '--device <deviceId>',+ 'Bind to this device instead of this machine (see lh device list)',+ )+ .addOption(+ new Option(+ '--visibility <visibility>',+ 'Who can see the agents in a workspace: `private` (only you) or `public` (workspace members)',+ )+ .choices(VISIBILITIES)+ .default('private'),+ )+ .option('-n, --name <name>', 'Agent name (only when connecting one agent)')+ .option('-d, --description <desc>', 'Agent description (only when connecting one agent)')+ .option('--yes', 'Skip confirmation prompt')+ .option('--json [fields]', 'Output the created agents as JSON, optionally selecting fields')+ .addHelpText(+ 'after',+ `+Examples:+ lh agent connect Connect every agent CLI found on this machine+ (types already connected to it are skipped)+ lh agent connect antigravity --yes Connect Antigravity without prompting+ lh agent connect codex --visibility public --device <deviceId>`,+ )+ .action(async (types: string[], options: ConnectOptions) => {+ if ((options.name || options.description) && types.length !== 1) {+ fail('--name and --description need exactly one agent type, e.g. lh agent connect codex');+ }+ const named = resolveNamedProviders(types);++ const client = await getTrpcClient();+ const workspaceId = resolveWorkspaceId();++ const [user, devices] = await Promise.all([+ client.user.getUserState.query() as Promise<any>,+ client.device.listDevices.query() as Promise<DeviceRow[]>,+ ]);++ const device = await resolveTargetDevice(devices, {+ deviceId: options.device,+ userId: user?.userId,+ workspaceId,+ });+ if (!device.online) {+ fail(+ `Device ${deviceLabel(device)} is offline.`,+ options.device ? 'Run lh connect on that device, then rerun.' : connectHint(workspaceId),+ );+ }++ const scan = await client.device.scanAgents.query({ deviceId: device.deviceId });+ if (scan.error) fail(`Could not scan ${deviceLabel(device)}: ${scan.error}`);++ const label = deviceLabel(device);+ const available = selectAvailable(named, scan.agents);+ if (available.length === 0) {+ fail(+ `No external agent CLI found on ${label}.`,+ `Supported: ${CONNECTABLE_AGENT_DESCRIPTORS.map((d) => d.title).join(', ')}`,+ );+ }++ const connected = await findConnectedAgents(client, device.deviceId, user?.userId);+ const skipped = available+ .filter((p) => connected.has(p.type))+ .map((p) => ({ id: connected.get(p.type)!, title: p.title, type: p.type }));+ // `--json` keeps stdout parseable; skipped agents are in its payload instead.+ if (options.json === undefined) {+ for (const s of skipped) {+ log.info(`${s.title} is already connected to ${label} (${s.id}); skipping.`);+ }+ }+ const providers = available.filter((p) => !connected.has(p.type));++ // Visibility only exists inside a workspace; personal agents are the owner's.+ const visibility = workspaceId ? options.visibility : undefined;++ if (providers.length > 0 && !options.yes) {+ const names = providers.map((p) => p.title).join(', ');+ const where = workspaceId ? ` in workspace ${workspaceId} as ${visibility}` : '';+ const confirmed = await confirm(+ `Create ${providers.length} agent(s) bound to ${label}${where}: ${names}?`,+ );+ if (!confirmed) {+ console.log('Cancelled.');+ return;+ }+ }++ const buildUrl = await resolveAppUrlBuilder(client);+ const ownerName = user?.fullName || user?.username;+ const created: Array<{+ id: string;+ title: string;+ type: string;+ url: string;+ version?: string;+ }> = [];++ // Sequential: a failure stops before creating the rest; a rerun skips the+ // ones already created, since they are now bound to the device.+ for (const provider of providers) {+ const profile =+ provider.kind === 'platform' && isRemoteHeterogeneousType(provider.type)+ ? await client.device.getAgentProfile+ .query({ deviceId: device.deviceId, platform: provider.type })+ .catch(() => undefined)+ : undefined;+ const config = buildConnectAgentConfig({+ overrides: { description: options.description, name: options.name },+ profile,+ provider,+ target: { deviceId: device.deviceId, kind: 'device' },+ });+ const title =+ config.name ||+ connectedAgentDefaultName({+ ownerName,+ productTitle: config.title,+ visibility,+ workspaceId,+ }) ||+ provider.title;++ try {+ const result = (await client.agent.createAgent.mutate({+ config: { ...config, name: title },+ ...(visibility ? { visibility } : {}),+ } as any)) as { agentId?: string; id?: string };+ const id = (result.agentId || result.id)!;+ created.push({+ id,+ title,+ type: provider.type,+ url: buildUrl(`/agent/${encodeURIComponent(id)}`),+ version: scan.agents[provider.type]?.version,+ });+ } catch (error) {+ if (created.length > 0) {+ log.warn(`Created before the failure: ${created.map((c) => c.id).join(', ')}`);+ }+ fail(`Failed to create the ${provider.title} agent: ${(error as Error).message}`);+ }+ }++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson({ created, deviceId: device.deviceId, skipped }, fields);+ return;+ }++ if (created.length === 0) {+ console.log(`${pc.green('β')} Everything found on ${pc.bold(label)} is already connected.`);+ return;+ }+ console.log(`${pc.green('β')} Connected ${created.length} agent(s) on ${pc.bold(label)}:`);+ printTable(+ created.map((c) => [c.title, c.type, c.version ?? '', c.id, c.url]),+ ['NAME', 'TYPE', 'VERSION', 'ID', 'URL'],+ );+ console.log(+ pc.dim(+ 'An agent CLI that needs sign-in (e.g. Antigravity, Codex) must be signed in on the device before its first run.',+ ),+ );+ });+}diff --git a/packages/heterogeneous-agents/browser-entries.json b/packages/heterogeneous-agents/browser-entries.jsonindex 2ef2b273fef..942be8d38e8 100644--- a/packages/heterogeneous-agents/browser-entries.json+++ b/packages/heterogeneous-agents/browser-entries.json@@ -4,6 +4,7 @@"./client","./codexAppServerArgs","./codexPlanMode",+ "./connectAgent","./errors","./quota"]diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.jsonindex 1a0bf32d7e7..1566ca7125b 100644--- a/packages/heterogeneous-agents/package.json+++ b/packages/heterogeneous-agents/package.json@@ -14,6 +14,7 @@"./codexAppServerArgs": "./src/codex/appServerArgs.ts","./codexAppServerParams": "./src/codex/appServerParams.ts","./codexPlanMode": "./src/codexPlanMode/index.ts",+ "./connectAgent": "./src/connectAgent.ts","./models": "./src/models/index.ts","./processFailure": "./src/spawn/classifyProcessFailure.ts","./protocol": "./src/protocol/index.ts",diff --git a/packages/heterogeneous-agents/src/client/DroidIcon.tsx b/packages/heterogeneous-agents/src/client/DroidIcon.tsxindex 2e3959b440f..7aa0aa057dc 100644--- a/packages/heterogeneous-agents/src/client/DroidIcon.tsx+++ b/packages/heterogeneous-agents/src/client/DroidIcon.tsx@@ -2,7 +2,9 @@ import type { IconType } from '@lobehub/icons';import type { ImgHTMLAttributes } from 'react';import { memo } from 'react';-export const DROID_AVATAR_URL = 'https://factory.ai/favicon.svg';+import { DROID_AVATAR_URL } from '../connectAgent';++export { DROID_AVATAR_URL };interface DroidAvatarProps extends Omit<ImgHTMLAttributes<HTMLImageElement>,diff --git a/packages/heterogeneous-agents/src/client/index.ts b/packages/heterogeneous-agents/src/client/index.tsindex 48852511ee9..7c05ca15732 100644--- a/packages/heterogeneous-agents/src/client/index.ts+++ b/packages/heterogeneous-agents/src/client/index.ts@@ -8,7 +8,6 @@ import {Cursor,DeepSeek,Devin,- getLobeIconCDN,GithubCopilot,Grok,Kimi,@@ -25,6 +24,7 @@ import {isRemoteHeterogeneousType,LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS,} from '../config';+import { getHeterogeneousAgentAvatar } from '../connectAgent';import { DROID_AVATAR_URL, DroidIcon } from './DroidIcon';export { DROID_AVATAR_URL, DroidIcon, isLocalRuntimeHeterogeneousType, isRemoteHeterogeneousType };@@ -58,24 +58,16 @@ const heterogeneousAgentIcons = {'trae': Trae,} as const satisfies Record<HeterogeneousAgentClientConfig['type'], IconType>;-const createAgentAvatar = (iconId: string) =>- iconId === 'Droid'- ? DROID_AVATAR_URL- : getLobeIconCDN(iconId, {- cdn: 'aliyun',- format: 'avatar',- });-export const HETEROGENEOUS_AGENT_CLIENT_CONFIGS = HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({...config,- avatar: createAgentAvatar(config.iconId),+ avatar: getHeterogeneousAgentAvatar(config.iconId),icon: heterogeneousAgentIcons[config.type],})) as readonly HeterogeneousAgentClientConfig[];export const LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CLIENT_CONFIGS =LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({...config,- avatar: createAgentAvatar(config.iconId),+ avatar: getHeterogeneousAgentAvatar(config.iconId),icon: DeepSeek,})) as readonly LocalRuntimeHeterogeneousAgentClientConfig[];@@ -88,7 +80,7 @@ export const getHeterogeneousAgentClientConfig = (type: string) => {return {...config,- avatar: createAgentAvatar(config.iconId),+ avatar: getHeterogeneousAgentAvatar(config.iconId),icon: heterogeneousAgentIcons[config.type as keyof typeof heterogeneousAgentIcons],} satisfies HeterogeneousAgentClientConfig;};diff --git a/packages/heterogeneous-agents/src/connectAgent.test.ts b/packages/heterogeneous-agents/src/connectAgent.test.tsnew file mode 100644index 00000000000..97bb9d2a085--- /dev/null+++ b/packages/heterogeneous-agents/src/connectAgent.test.ts@@ -0,0 +1,121 @@+import { describe, expect, it } from 'vitest';++import {+ buildConnectAgentConfig,+ CONNECTABLE_AGENT_DESCRIPTORS,+ connectedAgentDefaultName,+ DROID_AVATAR_URL,+ getConnectableAgentDescriptor,+} from './connectAgent';++const device = { deviceId: 'dev-1', kind: 'device' } as const;++describe('CONNECTABLE_AGENT_DESCRIPTORS', () => {+ it('lists every kind with a stable shape', () => {+ expect(getConnectableAgentDescriptor('antigravity')).toMatchObject({+ avatar: expect.stringContaining('/avatars/antigravity.webp'),+ command: 'agy',+ kind: 'cli',+ title: 'Antigravity',+ });+ expect(getConnectableAgentDescriptor('deepseek-harness')?.kind).toBe('runtime');+ expect(getConnectableAgentDescriptor('openclaw')).toEqual({+ kind: 'platform',+ title: expect.any(String),+ type: 'openclaw',+ });+ expect(getConnectableAgentDescriptor('droid')?.avatar).toBe(DROID_AVATAR_URL);+ });++ it('has one row per type', () => {+ const types = CONNECTABLE_AGENT_DESCRIPTORS.map((d) => d.type);+ expect(new Set(types).size).toBe(types.length);+ });+});++describe('buildConnectAgentConfig', () => {+ it('binds a cli agent to a device with its spawn command', () => {+ expect(+ buildConnectAgentConfig({+ overrides: { description: ' Mine ', name: ' Agy ' },+ provider: getConnectableAgentDescriptor('antigravity')!,+ target: device,+ }),+ ).toMatchObject({+ agencyConfig: {+ boundDeviceId: 'dev-1',+ executionTarget: 'device',+ heterogeneousProvider: { command: 'agy', type: 'antigravity' },+ },+ description: 'Mine',+ name: 'Agy',+ provider: 'antigravity',+ systemRole: '',+ title: 'Antigravity',+ });+ });++ it('leaves a runtime agent command to launch resolution', () => {+ const config = buildConnectAgentConfig({+ provider: getConnectableAgentDescriptor('deepseek-harness')!,+ target: { kind: 'local' },+ });++ expect(config.agencyConfig).toEqual({+ heterogeneousProvider: { command: undefined, type: 'deepseek-harness' },+ });+ });++ it('prefills a platform agent from its device profile', () => {+ expect(+ buildConnectAgentConfig({+ profile: { avatar: 'a.png', description: 'Claw', title: 'Clawd' },+ provider: getConnectableAgentDescriptor('openclaw')!,+ target: device,+ }),+ ).toEqual({+ agencyConfig: {+ boundDeviceId: 'dev-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'openclaw' },+ },+ avatar: 'a.png',+ description: 'Claw',+ name: undefined,+ provider: 'openclaw',+ title: 'Clawd',+ });+ });+});++describe('connectedAgentDefaultName', () => {+ it('uses the product title outside a shared workspace agent', () => {+ expect(connectedAgentDefaultName({ ownerName: 'Arvin', productTitle: 'Codex' })).toBe('Codex');+ expect(+ connectedAgentDefaultName({+ ownerName: 'Arvin',+ productTitle: 'Codex',+ visibility: 'private',+ workspaceId: 'ws',+ }),+ ).toBe('Codex');+ });++ it('prefixes a shared workspace agent with its owner', () => {+ expect(+ connectedAgentDefaultName({+ ownerName: ' Arvin ',+ productTitle: 'Codex',+ visibility: 'public',+ workspaceId: 'ws',+ }),+ ).toBe('Arvinβs Codex');+ expect(+ connectedAgentDefaultName({ productTitle: 'Codex', visibility: 'public', workspaceId: 'ws' }),+ ).toBe('Codex');+ });++ it('returns undefined without a product title', () => {+ expect(connectedAgentDefaultName({ productTitle: ' ' })).toBeUndefined();+ });+});diff --git a/packages/heterogeneous-agents/src/connectAgent.ts b/packages/heterogeneous-agents/src/connectAgent.tsnew file mode 100644index 00000000000..c0cabee1e10--- /dev/null+++ b/packages/heterogeneous-agents/src/connectAgent.ts@@ -0,0 +1,166 @@+import { getLobeIconCDN } from '@lobehub/icons/es/features/getLobeIconCDN';++import type { HeterogeneousAgentType, RemoteHeterogeneousAgentType } from './config';+import {+ HETEROGENEOUS_AGENT_CONFIGS,+ isRemoteHeterogeneousType,+ LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS,+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS,+} from './config';++/**+ * React-free agent-creation contract shared by the Web "Connect agent" wizard+ * and `lh agent connect`, so both create the same agent row for the same pick.+ * Import it from `@lobechat/heterogeneous-agents/connectAgent`.+ */++export const DROID_AVATAR_URL = 'https://factory.ai/favicon.svg';++export const getHeterogeneousAgentAvatar = (iconId: string) =>+ iconId === 'Droid'+ ? DROID_AVATAR_URL+ : getLobeIconCDN(iconId, {+ cdn: 'aliyun',+ format: 'avatar',+ });++/**+ * One connectable agent. `kind` mirrors the domain split: `cli` agents use+ * stream adapters, `runtime` agents are LobeHub-shipped local runtimes, and+ * `platform` agents use the notify-based task runner on a bound device.+ */+export interface ConnectableAgentDescriptor {+ /** CDN avatar to stamp on created cli agents (platform agents use the device profile's). */+ avatar?: string;+ /** Spawn command β cli and runtime providers. */+ command?: string;+ kind: 'cli' | 'platform' | 'runtime';+ title: string;+ type: HeterogeneousAgentType;+}++export const CONNECTABLE_AGENT_DESCRIPTORS: ConnectableAgentDescriptor[] = [+ ...HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({+ avatar: getHeterogeneousAgentAvatar(config.iconId),+ command: config.defaultCommand,+ kind: 'cli' as const,+ title: config.title,+ type: config.type,+ })),+ ...LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({+ avatar: getHeterogeneousAgentAvatar(config.iconId),+ command: config.defaultCommand,+ kind: 'runtime' as const,+ title: config.title,+ type: config.type,+ })),+ ...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({+ kind: 'platform' as const,+ title: config.title,+ type: config.type,+ })),+];++export const getConnectableAgentDescriptor = (type: string) =>+ CONNECTABLE_AGENT_DESCRIPTORS.find((descriptor) => descriptor.type === type);++export interface ConnectAgentProfile {+ avatar?: string;+ description?: string;+ title?: string;+}++export type ConnectAgentTarget = { deviceId: string; kind: 'device' } | { kind: 'local' };++export interface BuildConnectAgentConfigOptions {+ overrides?: { description?: string; name?: string };+ profile?: ConnectAgentProfile;+ provider: ConnectableAgentDescriptor;+ target: ConnectAgentTarget;+}++export const buildPlatformAgencyConfig = (+ type: RemoteHeterogeneousAgentType,+ target: ConnectAgentTarget,+) => ({+ ...(target.kind === 'device'+ ? { boundDeviceId: target.deviceId, executionTarget: 'device' as const }+ : undefined),+ heterogeneousProvider: { type },+});++export const buildConnectAgentConfig = ({+ overrides,+ profile,+ provider,+ target,+}: BuildConnectAgentConfigOptions) => {+ const name = overrides?.name?.trim() || undefined;++ if (provider.kind === 'platform' && isRemoteHeterogeneousType(provider.type)) {+ return {+ agencyConfig: buildPlatformAgencyConfig(provider.type, target),+ avatar: profile?.avatar || undefined,+ description: (overrides?.description ?? profile?.description)?.trim() || undefined,+ name,+ // Same stamp as the CLI branch below: readers that attribute a run by the+ // agent's provider (topic model snapshot, agent list, message tags) must+ // see `openclaw`/`hermes`, not the inherited default chat provider.+ provider: provider.type,+ title: profile?.title || provider.title,+ };+ }++ // A runtime's command is only what the scan probes; launch resolves it itself.+ const command = provider.kind === 'cli' ? provider.command : undefined;+ const base = {+ avatar: provider.avatar,+ description: overrides?.description?.trim() || undefined,+ name,+ provider: provider.type,+ systemRole: '',+ title: provider.title,+ };++ if (target.kind === 'device') {+ return {+ ...base,+ agencyConfig: {+ boundDeviceId: target.deviceId,+ executionTarget: 'device' as const,+ heterogeneousProvider: { command, type: provider.type },+ },+ };+ }++ return {+ ...base,+ agencyConfig: {+ heterogeneousProvider: { command, type: provider.type },+ },+ };+};++/**+ * Default name of a connected agent: the product title, owner-prefixed for a+ * workspace agent members can see ("Arvinβs Codex"), so a shared sidebar tells+ * apart the same CLI connected by different people.+ */+export const connectedAgentDefaultName = ({+ ownerName,+ productTitle,+ visibility,+ workspaceId,+}: {+ ownerName?: string | null;+ productTitle?: string;+ visibility?: 'private' | 'public';+ workspaceId?: string | null;+}): string | undefined => {+ const product = productTitle?.trim();+ if (!product) return undefined;+ if (!workspaceId || visibility === 'private') return product;++ const owner = ownerName?.trim();+ return owner ? `${owner}βs ${product}` : product;+};diff --git a/src/features/ConnectAgent/providers.ts b/src/features/ConnectAgent/providers.tsindex 7d47073ebdd..481ee92fe87 100644--- a/src/features/ConnectAgent/providers.ts+++ b/src/features/ConnectAgent/providers.ts@@ -4,15 +4,9 @@ import type {LocalRuntimeHeterogeneousAgentType,RemoteHeterogeneousAgentType,} from '@lobechat/heterogeneous-agents';-import {- isRemoteHeterogeneousType,- REMOTE_HETEROGENEOUS_AGENT_CONFIGS,-} from '@lobechat/heterogeneous-agents';-import {- DroidIcon,- HETEROGENEOUS_AGENT_CLIENT_CONFIGS,- LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CLIENT_CONFIGS,-} from '@lobechat/heterogeneous-agents/client';+import { DroidIcon } from '@lobechat/heterogeneous-agents/client';+import type { ConnectableAgentDescriptor } from '@lobechat/heterogeneous-agents/connectAgent';+import { CONNECTABLE_AGENT_DESCRIPTORS } from '@lobechat/heterogeneous-agents/connectAgent';import {Amp,Antigravity,@@ -33,14 +27,20 @@ import {Trae,} from '@lobehub/icons';+export type {+ BuildConnectAgentConfigOptions,+ ConnectAgentProfile,+} from '@lobechat/heterogeneous-agents/connectAgent';+export {+ buildConnectAgentConfig,+ buildPlatformAgencyConfig,+} from '@lobechat/heterogeneous-agents/connectAgent';+/**- * One row in the connect wizard's agent inventory. `kind` mirrors the domain- * split: `cli` agents use stream adapters, while `platform` agents use the- * notify-based task runner on this desktop or a bound device.+ * One row in the connect wizard's agent inventory: the shared descriptor plus+ * the brand icon the wizard renders.*/-export interface ConnectableProvider {- /** CDN avatar to stamp on created cli agents (platform agents use the device profile's). */- avatar?: string;+export interface ConnectableProvider extends ConnectableAgentDescriptor {/** Compound brand icon module β render via `icon.Avatar`. */brand:| typeof Amp@@ -61,24 +61,6 @@ export interface ConnectableProvider {| typeof Pi| typeof Qoder| typeof Trae;- /** Spawn command β cli and runtime providers. */- command?: string;- kind: 'cli' | 'platform' | 'runtime';- title: string;- type: HeterogeneousAgentType;-}--export interface ConnectAgentProfile {- avatar?: string;- description?: string;- title?: string;-}--interface BuildConnectAgentConfigOptions {- overrides?: { description?: string; name?: string };- profile?: ConnectAgentProfile;- provider: ConnectableProvider;- target: { deviceId: string; kind: 'device' } | { kind: 'local' };}const CLI_BRANDS: Record<LocalHeterogeneousAgentType, ConnectableProvider['brand']> = {@@ -108,92 +90,15 @@ const RUNTIME_BRANDS: Record<LocalRuntimeHeterogeneousAgentType, ConnectableProv'deepseek-harness': DeepSeek,};-export const CONNECTABLE_PROVIDERS: ConnectableProvider[] = [- ...HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map((config) => ({- avatar: config.avatar,- brand: CLI_BRANDS[config.type],- command: config.defaultCommand,- kind: 'cli' as const,- title: config.title,- type: config.type,- })),- ...LOCAL_RUNTIME_HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map((config) => ({- avatar: config.avatar,- brand: RUNTIME_BRANDS[config.type],- command: config.defaultCommand,- kind: 'runtime' as const,- title: config.title,- type: config.type,- })),- ...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({- brand: PLATFORM_BRANDS[config.type],- kind: 'platform' as const,- title: config.title,- type: config.type,- })),-];+const BRANDS = {+ ...CLI_BRANDS,+ ...PLATFORM_BRANDS,+ ...RUNTIME_BRANDS,+} satisfies Record<ConnectableAgentDescriptor['type'], ConnectableProvider['brand']>;++export const CONNECTABLE_PROVIDERS: ConnectableProvider[] = CONNECTABLE_AGENT_DESCRIPTORS.map(+ (descriptor) => ({ ...descriptor, brand: BRANDS[descriptor.type] }),+);export const getConnectableProvider = (type: HeterogeneousAgentType) =>CONNECTABLE_PROVIDERS.find((provider) => provider.type === type);--export const buildPlatformAgencyConfig = (- type: RemoteHeterogeneousAgentType,- target: { deviceId: string; kind: 'device' } | { kind: 'local' },-) => ({- ...(target.kind === 'device'- ? { boundDeviceId: target.deviceId, executionTarget: 'device' as const }- : undefined),- heterogeneousProvider: { type },-});--export const buildConnectAgentConfig = ({- overrides,- profile,- provider,- target,-}: BuildConnectAgentConfigOptions) => {- const name = overrides?.name?.trim() || undefined;-- if (provider.kind === 'platform' && isRemoteHeterogeneousType(provider.type)) {- return {- agencyConfig: buildPlatformAgencyConfig(provider.type, target),- avatar: profile?.avatar || undefined,- description: (overrides?.description ?? profile?.description)?.trim() || undefined,- name,- // Same stamp as the CLI branch below: readers that attribute a run by the- // agent's provider (topic model snapshot, agent list, message tags) must- // see `openclaw`/`hermes`, not the inherited default chat provider.- provider: provider.type,- title: profile?.title || provider.title,- };- }-- // A runtime's command is only what the scan probes; launch resolves it itself.- const command = provider.kind === 'cli' ? provider.command : undefined;- const base = {- avatar: provider.avatar,- description: overrides?.description?.trim() || undefined,- name,- provider: provider.type,- systemRole: '',- title: provider.title,- };-- if (target.kind === 'device') {- return {- ...base,- agencyConfig: {- boundDeviceId: target.deviceId,- executionTarget: 'device' as const,- heterogeneousProvider: { command, type: provider.type },- },- };- }-- return {- ...base,- agencyConfig: {- heterogeneousProvider: { command, type: provider.type },- },- };-};diff --git a/src/store/agent/utils/heteroAgentDefaultName.ts b/src/store/agent/utils/heteroAgentDefaultName.tsindex 8e7008bd75b..3237de6b349 100644--- a/src/store/agent/utils/heteroAgentDefaultName.ts+++ b/src/store/agent/utils/heteroAgentDefaultName.ts@@ -1,3 +1,5 @@+import { connectedAgentDefaultName } from '@lobechat/heterogeneous-agents/connectAgent';+import { getUserStoreState } from '@/store/user';import { authSelectors, userProfileSelectors } from '@/store/user/selectors';@@ -20,15 +22,15 @@ export const heteroAgentDefaultName = ({visibility,workspaceId,}: HeteroAgentDefaultNameOptions): string | undefined => {- const product = productTitle?.trim();- if (!product) return undefined;-- if (!workspaceId || visibility === 'private') return product;-const userStore = getUserStoreState();- const owner = authSelectors.isLogin(userStore)- ? userProfileSelectors.nickName(userStore)?.trim()+ const ownerName = authSelectors.isLogin(userStore)+ ? userProfileSelectors.nickName(userStore): undefined;- return owner ? `${owner}βs ${product}` : product;+ return connectedAgentDefaultName({+ ownerName,+ productTitle: productTitle ?? undefined,+ visibility,+ workspaceId,+ });};