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 --visibility and --json to lh agent create (#22801)

Rdmclin2f6f0de5d7dee
diff --git a/.agents/skills/cli/references/agent.md b/.agents/skills/cli/references/agent.md
index b2b90f3ce7a..db17fed987e 100644
--- a/.agents/skills/cli/references/agent.md
+++ b/.agents/skills/cli/references/agent.md
@@ -30,7 +30,7 @@ View agent configuration details. `agentId` may be omitted when `-s, --slug` is
lh agent view [agentId] [-s <slug>] [--json [fields]]
```
-**Displays**: Title, description, model, provider, system role, plugins, tools.
+**Displays**: Title, description, visibility (workspace agents only), model, provider, system role, plugins, tools.
---
@@ -39,19 +39,23 @@ lh agent view [agentId] [-s <slug>] [--json [fields]]
Create a new agent.
```bash
-lh agent create [-t <title>] [-d <desc>] [-m <model>] [-p <provider>] [-s <role>] [--group <groupId>]
+lh agent create [-t <title>] [-d <desc>] [-m <model>] [-p <provider>] [-s <role>] [--group <groupId>] [--visibility <private|public>] [--json [fields]]
```
-| Option | Description | Required |
-| --------------------------- | -------------- | -------- |
-| `-t, --title <title>` | Agent title | No |
-| `-d, --description <desc>` | Description | No |
-| `-m, --model <model>` | Model ID | No |
-| `-p, --provider <provider>` | Provider ID | No |
-| `-s, --system-role <role>` | System prompt | No |
-| `--group <groupId>` | Agent group ID | No |
+| Option | Description | Required |
+| --------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -------- |
+| `-t, --title <title>` | Agent title | No |
+| `-d, --description <desc>` | Description | No |
+| `-m, --model <model>` | Model ID | No |
+| `-p, --provider <provider>` | Provider ID | No |
+| `-s, --system-role <role>` | System prompt | No |
+| `--group <groupId>` | Agent group ID | No |
+| `--visibility <visibility>` | Who can see the agent in a workspace: `private` (only you) or `public` (workspace members). Omit to keep the server default | No |
+| `--json [fields]` | Print the created agent as JSON, optionally selecting fields (e.g. `--json id,visibility`) | No |
-**Output**: Created agent ID and session ID.
+The workspace comes from the current scope (`LOBEHUB_WORKSPACE_ID` or `lh workspace use`); `--visibility` only chooses who inside that scope can see the agent. An invalid value exits 1 before any request is sent.
+
+**Output**: Without `--json`, the created agent ID, its session ID when there is one, the requested visibility, and the agent URL. With `--json`, an object `{ id, sessionId?, title, url, visibility, workspaceId }`. `visibility` and `workspaceId` are read back from the server after creation, so they are the stored values (server default or folder-inherited included), not an echo of the flag. If that read-back fails, the agent still exists: `id` is printed, `visibility` and `workspaceId` are `null`, and a warning goes to stderr. Do not retry the create in that case.
---
diff --git a/apps/cli/src/commands/agent.create.test.ts b/apps/cli/src/commands/agent.create.test.ts
new file mode 100644
index 00000000000..3eb4a594593
--- /dev/null
+++ b/apps/cli/src/commands/agent.create.test.ts
@@ -0,0 +1,186 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as WorkspaceModule from '../api/workspace';
+import { log } from '../utils/logger';
+import { registerAgentCommand } from './agent';
+
+const { mockTrpcClient } = vi.hoisted(() => ({
+ mockTrpcClient: {
+ agent: {
+ createAgent: { mutate: vi.fn() },
+ getAgentConfigById: { query: vi.fn() },
+ },
+ },
+}));
+
+const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
+ getTrpcClient: vi.fn(),
+}));
+
+vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+// Personal scope, so the app URL does not depend on the shell's LOBEHUB_WORKSPACE_ID.
+vi.mock('../api/workspace', async (importOriginal) => ({
+ ...(await importOriginal<typeof WorkspaceModule>()),
+ resolveWorkspaceId: () => undefined,
+}));
+
+describe('agent create', () => {
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ mockTrpcClient.agent.createAgent.mutate.mockReset();
+ mockTrpcClient.agent.getAgentConfigById.query.mockReset();
+ });
+
+ afterEach(() => {
+ consoleSpy.mockRestore();
+ });
+
+ function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ registerAgentCommand(program);
+ return program;
+ }
+
+ it('should create an agent', async () => {
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({
+ agentId: 'a-new',
+ sessionId: 's1',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'create',
+ '--title',
+ 'My Agent',
+ '--model',
+ 'gpt-4',
+ ]);
+
+ expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ config: expect.objectContaining({ model: 'gpt-4', title: 'My Agent' }),
+ }),
+ );
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('a-new'));
+ });
+
+ it('omits visibility when the flag is not passed, keeping the server default', async () => {
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'a-new' });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'agent', 'create', '--title', 'x']);
+
+ const input = mockTrpcClient.agent.createAgent.mutate.mock.calls[0][0];
+ expect(input).not.toHaveProperty('visibility');
+ expect(mockTrpcClient.agent.getAgentConfigById.query).not.toHaveBeenCalled();
+ });
+
+ it.each(['private', 'public'])('passes --visibility %s through to the server', async (v) => {
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'a-new' });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'agent', 'create', '-t', 'x', '--visibility', v]);
+
+ expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledWith({
+ config: { title: 'x' },
+ visibility: v,
+ });
+ expect(consoleSpy).toHaveBeenCalledWith(` Visibility: ${v}`);
+ });
+
+ it('rejects an unknown --visibility value before calling the server', async () => {
+ const program = createProgram();
+ program.exitOverride();
+ program.commands.forEach((c) => c.exitOverride());
+ const agentCmd = program.commands.find((c) => c.name() === 'agent')!;
+ agentCmd.commands.forEach((c) => c.exitOverride().configureOutput({ writeErr: () => {} }));
+
+ await expect(
+ program.parseAsync(['node', 'test', 'agent', 'create', '-t', 'x', '--visibility', 'team']),
+ ).rejects.toThrow(/Allowed choices are private, public/);
+ expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();
+ });
+
+ it('prints the created agent as JSON with the persisted visibility', async () => {
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'a-new' });
+ mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({
+ id: 'a-new',
+ title: 'x',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'create',
+ '-t',
+ 'x',
+ '--visibility',
+ 'private',
+ '--json',
+ ]);
+
+ expect(mockTrpcClient.agent.getAgentConfigById.query).toHaveBeenCalledWith({
+ agentId: 'a-new',
+ });
+ expect(consoleSpy).toHaveBeenCalledTimes(1);
+ const output = JSON.parse(consoleSpy.mock.calls[0][0]);
+ expect(output).toEqual({
+ id: 'a-new',
+ title: 'x',
+ url: expect.stringContaining('/agent/a-new'),
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('reports the server-chosen visibility in JSON when the flag is omitted', async () => {
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'a-new' });
+ mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({
+ id: 'a-new',
+ visibility: 'public',
+ workspaceId: null,
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'agent', 'create', '--json', 'id,visibility']);
+
+ const output = JSON.parse(consoleSpy.mock.calls[0][0]);
+ expect(output).toEqual({ id: 'a-new', visibility: 'public' });
+ });
+
+ it('still prints the id when the read-back fails, without echoing the flag', async () => {
+ const warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => {});
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'a-new' });
+ mockTrpcClient.agent.getAgentConfigById.query.mockRejectedValue(new Error('fetch failed'));
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'create',
+ '-t',
+ 'x',
+ '--visibility',
+ 'private',
+ '--json',
+ 'id,visibility',
+ ]);
+
+ expect(JSON.parse(consoleSpy.mock.calls[0][0])).toEqual({ id: 'a-new', visibility: null });
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('could not read it back'));
+ warnSpy.mockRestore();
+ });
+});
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.ts
index d2ad74bb260..aa231b5a6e8 100644
--- a/apps/cli/src/commands/agent.test.ts
+++ b/apps/cli/src/commands/agent.test.ts
@@ -278,34 +278,6 @@ describe('agent command', () => {
});
});
- describe('create', () => {
- it('should create an agent', async () => {
- mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({
- agentId: 'a-new',
- sessionId: 's1',
- });
-
- const program = createProgram();
- await program.parseAsync([
- 'node',
- 'test',
- 'agent',
- 'create',
- '--title',
- 'My Agent',
- '--model',
- 'gpt-4',
- ]);
-
- expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledWith(
- expect.objectContaining({
- config: expect.objectContaining({ model: 'gpt-4', title: 'My Agent' }),
- }),
- );
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('a-new'));
- });
- });
-
describe('edit', () => {
it('should update agent config', async () => {
mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index ba3197dca87..9f74efd9bdf 100644
--- a/apps/cli/src/commands/agent.ts
+++ b/apps/cli/src/commands/agent.ts
@@ -1,7 +1,7 @@
import { readFile } from 'node:fs/promises';
import { AgentGraphSchema } from '@lobechat/types/agent/graph';
-import { type Command, InvalidArgumentError } from 'commander';
+import { type Command, InvalidArgumentError, Option } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
@@ -43,6 +43,10 @@ const readJsonObjectFile = async (
return parsed as Record<string, unknown>;
};
+/** Values `agent.createAgent` accepts for `visibility`; omit it to keep the server default. */
+const AGENT_VISIBILITIES = ['private', 'public'] as const;
+type AgentVisibility = (typeof AGENT_VISIBILITIES)[number];
+
const readAgencyConfig = (agencyConfigFile: string): Promise<Record<string, unknown>> =>
readJsonObjectFile(agencyConfigFile, 'agencyConfig');
@@ -154,6 +158,8 @@ export function registerAgentCommand(program: Command) {
if (r.description || r.meta?.description) meta.push(r.description || r.meta.description);
if (r.model) meta.push(`Model: ${r.model}`);
if (r.provider) meta.push(`Provider: ${r.provider}`);
+ // Visibility only means something inside a workspace.
+ if (r.workspaceId && r.visibility) meta.push(`Visibility: ${r.visibility}`);
if (meta.length > 0) console.log(pc.dim(meta.join(' · ')));
if (r.systemRole) {
@@ -175,14 +181,23 @@ export function registerAgentCommand(program: Command) {
.option('-p, --provider <provider>', 'Provider ID')
.option('-s, --system-role <role>', 'System role prompt')
.option('--group <groupId>', 'Group ID')
+ .addOption(
+ new Option(
+ '--visibility <visibility>',
+ 'Who can see the agent in a workspace: `private` (only you) or `public` (workspace members). Omit to use the server default',
+ ).choices(AGENT_VISIBILITIES),
+ )
+ .option('--json [fields]', 'Output the created agent as JSON, optionally selecting fields')
.action(
async (options: {
description?: string;
group?: string;
+ json?: string | boolean;
model?: string;
provider?: string;
systemRole?: string;
title?: string;
+ visibility?: AgentVisibility;
}) => {
const client = await getTrpcClient();
const buildUrl = await resolveAppUrlBuilder(client);
@@ -196,13 +211,46 @@ export function registerAgentCommand(program: Command) {
const input: Record<string, any> = { config };
if (options.group) input.groupId = options.group;
+ // Passed through as-is. When omitted the key is left out entirely so the
+ // server keeps deciding (its default, or the folder's visibility).
+ if (options.visibility) input.visibility = options.visibility;
const result = await client.agent.createAgent.mutate(input as any);
const r = result as any;
const agentId = r.agentId || r.id;
const url = buildUrl(`/agent/${encodeURIComponent(agentId)}`);
+
+ if (options.json !== undefined) {
+ // `createAgent` only returns the id, so read the stored row back: the
+ // visibility reported here is what the server persisted (default or
+ // folder-inherited included), never an echo of the flag. The agent
+ // already exists at this point, so a failed read-back must still print
+ // its id (with `visibility: null`) — exiting non-zero would invite the
+ // caller to retry and create a duplicate.
+ let created: any = null;
+ try {
+ created = await client.agent.getAgentConfigById.query({ agentId });
+ } catch (error) {
+ log.warn(`Created ${agentId}, but could not read it back: ${(error as Error).message}`);
+ }
+ const fields = typeof options.json === 'string' ? options.json : undefined;
+ outputJson(
+ {
+ id: agentId,
+ ...(r.sessionId ? { sessionId: r.sessionId } : {}),
+ title: created?.title ?? options.title ?? null,
+ url,
+ visibility: created?.visibility ?? null,
+ workspaceId: created?.workspaceId ?? null,
+ },
+ fields,
+ );
+ return;
+ }
+
console.log(`${pc.green('✓')} Created agent ${pc.bold(agentId)}`);
if (r.sessionId) console.log(` Session: ${r.sessionId}`);
+ if (options.visibility) console.log(` Visibility: ${options.visibility}`);
console.log(`${pc.bold('agent')}: ${url}`);
},
);