Skip to content

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

✨ feat(cli): add agent transfer and move-group commands (#22923)

YuTengjing6ff88dcf08c4
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index 9f74efd9bdf..4e5a3a59d58 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 { registerAgentMoveCommands } from './agent/move';
import { resolveAgentId } from './agent/resolveAgentId';
import { registerAgentRunCommand } from './agent/run';
import { registerAgentSpaceFsCommand } from './agent/spaceFs';
@@ -447,6 +448,10 @@ export function registerAgentCommand(program: Command) {
console.log(`${pc.green('βœ“')} Unpinned agent ${pc.bold(agentId)}`);
});
+ // ── transfer / move-group ───────────────────────────
+
+ registerAgentMoveCommands(agent);
+
// ── kb-files ───────────────────────────────────────
agent
diff --git a/apps/cli/src/commands/agent/move.test.ts b/apps/cli/src/commands/agent/move.test.ts
new file mode 100644
index 00000000000..c4b2433bb77
--- /dev/null
+++ b/apps/cli/src/commands/agent/move.test.ts
@@ -0,0 +1,144 @@
+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 { registerAgentMoveCommands } from './move';
+
+const { mockTrpcClient, mockConfirm } = vi.hoisted(() => ({
+ mockConfirm: vi.fn(),
+ mockTrpcClient: {
+ agent: { transferAgents: { mutate: vi.fn() } },
+ home: { updateAgentSessionGroupId: { mutate: vi.fn() } },
+ workspace: { list: { query: vi.fn() } },
+ },
+}));
+
+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn(async () => mockTrpcClient) }));
+vi.mock('../../utils/format', async (importOriginal) => ({
+ ...(await importOriginal<typeof FormatModule>()),
+ confirm: mockConfirm,
+}));
+
+const WORKSPACES = [{ id: 'ws-1', name: 'Team', slug: 'team' }];
+
+describe('agent transfer / move-group', () => {
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
+ vi.spyOn(log, 'error').mockImplementation(() => {});
+ mockTrpcClient.workspace.list.query.mockResolvedValue(WORKSPACES);
+ mockConfirm.mockResolvedValue(true);
+ mockTrpcClient.home.updateAgentSessionGroupId.mutate.mockResolvedValue({ id: 'a1' });
+ mockTrpcClient.agent.transferAgents.mutate.mockResolvedValue([
+ { agentId: 'a1', slug: null, transferJobId: 'job-1' },
+ ]);
+ });
+
+ afterEach(() => {
+ consoleSpy.mockRestore();
+ exitSpy.mockRestore();
+ });
+
+ const run = (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerAgentMoveCommands(program.command('agent'));
+ return program.parseAsync(['node', 'test', 'agent', ...args]);
+ };
+
+ describe('transfer', () => {
+ it('resolves a workspace slug to its id before transferring', async () => {
+ await run('transfer', 'a1', 'a2', '--to', 'team', '--visibility', 'public', '--yes');
+
+ expect(mockConfirm).not.toHaveBeenCalled();
+ expect(mockTrpcClient.agent.transferAgents.mutate).toHaveBeenCalledWith({
+ agentIds: ['a1', 'a2'],
+ targetVisibility: 'public',
+ targetWorkspaceId: 'ws-1',
+ });
+ });
+
+ it('defaults to private visibility when transferring to a workspace', async () => {
+ await run('transfer', 'a1', '--to', 'team', '--yes');
+
+ expect(mockTrpcClient.agent.transferAgents.mutate).toHaveBeenCalledWith({
+ agentIds: ['a1'],
+ targetVisibility: 'private',
+ targetWorkspaceId: 'ws-1',
+ });
+ });
+
+ it('transfers to the personal account with a null target', async () => {
+ await run('transfer', 'a1', '--personal', '--yes');
+
+ expect(mockTrpcClient.workspace.list.query).not.toHaveBeenCalled();
+ expect(mockTrpcClient.agent.transferAgents.mutate).toHaveBeenCalledWith({
+ agentIds: ['a1'],
+ targetVisibility: undefined,
+ targetWorkspaceId: null,
+ });
+ });
+
+ it('does nothing when the confirmation is declined', async () => {
+ mockConfirm.mockResolvedValue(false);
+
+ await run('transfer', 'a1', '--to', 'ws-1');
+
+ expect(mockConfirm).toHaveBeenCalled();
+ expect(mockTrpcClient.agent.transferAgents.mutate).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['no target', ['transfer', 'a1', '--yes']],
+ ['both targets', ['transfer', 'a1', '--to', 'team', '--personal', '--yes']],
+ ['visibility with --personal', ['transfer', 'a1', '--personal', '--visibility', 'public']],
+ ])('rejects %s', async (_, args) => {
+ await run(...args);
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.agent.transferAgents.mutate).not.toHaveBeenCalled();
+ });
+
+ it('prints the server results with --json', async () => {
+ await run('transfer', 'a1', '--personal', '--yes', '--json');
+
+ expect(JSON.parse(consoleSpy.mock.calls[0][0])).toEqual([
+ { agentId: 'a1', slug: null, transferJobId: 'job-1' },
+ ]);
+ });
+ });
+
+ describe('move-group', () => {
+ it('moves an agent into a group', async () => {
+ await run('move-group', 'a1', 'g1');
+
+ expect(mockTrpcClient.home.updateAgentSessionGroupId.mutate).toHaveBeenCalledWith({
+ agentId: 'a1',
+ sessionGroupId: 'g1',
+ });
+ });
+
+ it('removes the agent from its group with `default`', async () => {
+ await run('move-group', 'a1', 'default');
+
+ expect(mockTrpcClient.home.updateAgentSessionGroupId.mutate).toHaveBeenCalledWith({
+ agentId: 'a1',
+ sessionGroupId: null,
+ });
+ });
+
+ it('fails when no agent matched in the current scope', async () => {
+ mockTrpcClient.home.updateAgentSessionGroupId.mutate.mockResolvedValue(undefined);
+
+ await run('move-group', 'missing', 'g1');
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(consoleSpy).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/cli/src/commands/agent/move.ts b/apps/cli/src/commands/agent/move.ts
new file mode 100644
index 00000000000..fad5c5ebbc2
--- /dev/null
+++ b/apps/cli/src/commands/agent/move.ts
@@ -0,0 +1,137 @@
+/**
+ * `lh agent transfer ...` / `lh agent move-group ...` β€” where an agent lives.
+ *
+ * Mirrors the sidebar's "Transfer to…" and "Move to group" menu items:
+ *
+ * - `transfer` rehomes agents (with their topics, messages and tasks) from the
+ * current scope (`workspace use` / `LOBEHUB_WORKSPACE_ID`, else personal) to
+ * another workspace or to the personal account, via `agent.transferAgents`.
+ * - `move-group` sets the sidebar group (`agents.sessionGroupId`) inside the
+ * current scope, via `home.updateAgentSessionGroupId`.
+ */
+import type { Command } from 'commander';
+import { Option } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../../api/client';
+import { resolveWorkspace } from '../../api/workspaceRef';
+import { confirm, outputJson } from '../../utils/format';
+import { log } from '../../utils/logger';
+
+const TRANSFER_VISIBILITIES = ['private', 'public'] as const;
+type TransferVisibility = (typeof TRANSFER_VISIBILITIES)[number];
+
+/** Same sentinel the sidebar uses for "not in any group". */
+const DEFAULT_GROUP = 'default';
+
+interface TransferOptions {
+ json?: string | boolean;
+ personal?: boolean;
+ to?: string;
+ visibility?: TransferVisibility;
+ yes?: boolean;
+}
+
+export function registerAgentMoveCommands(agent: Command) {
+ // ── transfer ──────────────────────────────────────────
+
+ agent
+ .command('transfer <agentIds...>')
+ .description(
+ 'Move agents (with their conversations) from the current scope to another workspace or your personal account',
+ )
+ .option('--to <workspace>', 'Target workspace id or slug')
+ .option('--personal', 'Move to your personal account')
+ .addOption(
+ new Option(
+ '--visibility <visibility>',
+ 'Visibility in the target workspace: `private` (only you) or `public` (workspace members)',
+ ).choices(TRANSFER_VISIBILITIES),
+ )
+ .option('--yes', 'Skip confirmation prompt')
+ .option('--json [fields]', 'Output the transfer results as JSON, optionally selecting fields')
+ .action(async (agentIds: string[], options: TransferOptions) => {
+ if (Boolean(options.to) === Boolean(options.personal)) {
+ log.error('Specify exactly one target: --to <workspace> or --personal.');
+ process.exit(1);
+ return;
+ }
+ if (options.personal && options.visibility) {
+ log.error('--visibility only applies when transferring to a workspace.');
+ process.exit(1);
+ return;
+ }
+
+ // Resolve before confirming so a typo fails without a prompt, and a slug
+ // is never sent where the server expects an id.
+ const target = options.to ? await resolveWorkspace(options.to) : null;
+ // Omitting visibility makes the server keep the row's stored value, and a
+ // personal agent stores `public` β€” so an unflagged move would share it
+ // with every member. Default to `private`, as the web Transfer modal does.
+ const visibility = target ? (options.visibility ?? 'private') : undefined;
+ const targetLabel = target
+ ? `workspace ${target.name} (${target.slug}) as ${visibility}`
+ : 'personal account';
+
+ if (!options.yes) {
+ const confirmed = await confirm(
+ `Transfer ${agentIds.length} agent(s) and their conversations to ${targetLabel}?`,
+ );
+ if (!confirmed) {
+ console.log('Cancelled.');
+ return;
+ }
+ }
+
+ const client = await getTrpcClient();
+ const results = await client.agent.transferAgents.mutate({
+ agentIds,
+ targetVisibility: visibility,
+ targetWorkspaceId: target?.id ?? null,
+ });
+
+ if (options.json !== undefined) {
+ const fields = typeof options.json === 'string' ? options.json : undefined;
+ outputJson(results, fields);
+ return;
+ }
+
+ for (const r of results) {
+ console.log(`${pc.green('βœ“')} Transferred agent ${pc.bold(r.agentId)} to ${targetLabel}`);
+ }
+ // History is rehomed by a background job; the agents are usable now.
+ const jobId = results[0]?.transferJobId;
+ if (jobId)
+ console.log(pc.dim(` Conversation history is migrating in background (job ${jobId})`));
+ });
+
+ // ── move-group ────────────────────────────────────────
+
+ agent
+ .command('move-group <agentId> <groupId>')
+ .description(
+ `Move an agent into a sidebar group (see \`lh session-group list\`); pass \`${DEFAULT_GROUP}\` to remove it from any group`,
+ )
+ .action(async (agentId: string, groupId: string) => {
+ const sessionGroupId = groupId === DEFAULT_GROUP ? null : groupId;
+
+ const client = await getTrpcClient();
+ const updated = await client.home.updateAgentSessionGroupId.mutate({
+ agentId,
+ sessionGroupId,
+ });
+ // The update matches no row for an unknown id or one outside the current
+ // scope, and returns nothing instead of throwing.
+ if (!updated) {
+ log.error(`Agent not found in the current scope: ${agentId}`);
+ process.exit(1);
+ return;
+ }
+
+ console.log(
+ sessionGroupId
+ ? `${pc.green('βœ“')} Moved agent ${pc.bold(agentId)} to group ${pc.bold(sessionGroupId)}`
+ : `${pc.green('βœ“')} Removed agent ${pc.bold(agentId)} from its group`,
+ );
+ });
+}