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): accept workspace slugs wherever --workspace is taken (#21540)

Rdmclin2e8ee5f09a7e1
diff --git a/.agents/skills/cli/SKILL.md b/.agents/skills/cli/SKILL.md
index b597568f22c..3cae97f7e03 100644
--- a/.agents/skills/cli/SKILL.md
+++ b/.agents/skills/cli/SKILL.md
@@ -137,8 +137,13 @@ apps/cli/src/
Every command runs against one scope, resolved in this order:
-1. an explicit `--workspace <id>` on the commands that take it
-2. the `LOBEHUB_WORKSPACE_ID` env var
+1. an explicit `--workspace <id|slug>` on the `workspace`, `device` and `topic`
+ commands that take it (a slug is resolved against `lh workspace list`; one
+ that matches nothing fails). A credential that cannot call `workspace.list`
+ (no `workspace:read`, such as a workspace-bound API key) skips resolution and
+ sends the value as an id with a warning, so it must pass the id.
+ `lh connect --workspace` takes an id only.
+2. the `LOBEHUB_WORKSPACE_ID` env var (an id only)
3. the scope persisted by `lh workspace use <id|slug>`
4. personal content (no workspace)
diff --git a/apps/cli/src/api/workspaceRef.test.ts b/apps/cli/src/api/workspaceRef.test.ts
new file mode 100644
index 00000000000..c368e8516b9
--- /dev/null
+++ b/apps/cli/src/api/workspaceRef.test.ts
@@ -0,0 +1,66 @@
+import { TRPCClientError } from '@trpc/client';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { log } from '../utils/logger';
+import { findWorkspace, resolveWorkspaceRef } from './workspaceRef';
+
+const { mockList } = vi.hoisted(() => ({ mockList: vi.fn() }));
+
+vi.mock('./client', () => ({
+ getTrpcClient: async () => ({ workspace: { list: { query: mockList } } }),
+}));
+
+const trpcError = (code: string) =>
+ new TRPCClientError(code, { result: { error: { data: { code } } } as never });
+
+const workspaces = [
+ { id: 'ws_1', name: 'Acme', slug: 'acme' },
+ // A slug that collides with another workspace's id must not shadow that id.
+ { id: 'ws_2', name: 'Beta', slug: 'ws_1' },
+];
+
+describe('workspaceRef', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockList.mockResolvedValue(workspaces);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('process.exit');
+ }) as never);
+ });
+
+ it('prefers an id match over a slug match', () => {
+ expect(findWorkspace(workspaces, 'ws_1')?.name).toBe('Acme');
+ });
+
+ it('resolves a slug to its id', async () => {
+ await expect(resolveWorkspaceRef('acme')).resolves.toBe('ws_1');
+ });
+
+ it('keeps an omitted value for the ambient scope without a lookup', async () => {
+ await expect(resolveWorkspaceRef(undefined)).resolves.toBeUndefined();
+ expect(mockList).not.toHaveBeenCalled();
+ });
+
+ // Credentials that cannot list workspaces keep the pre-slug behavior.
+ it('passes the value through as an id when the lookup is forbidden', async () => {
+ mockList.mockRejectedValue(trpcError('FORBIDDEN'));
+
+ await expect(resolveWorkspaceRef('ws_x')).resolves.toBe('ws_x');
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('pass the workspace id'));
+ });
+
+ // A slug forwarded after a transient failure would read the personal scope.
+ it('fails when the lookup fails for any other reason', async () => {
+ mockList.mockRejectedValue(trpcError('INTERNAL_SERVER_ERROR'));
+ await expect(resolveWorkspaceRef('acme')).rejects.toThrow('INTERNAL_SERVER_ERROR');
+
+ mockList.mockRejectedValue(new TypeError('fetch failed'));
+ await expect(resolveWorkspaceRef('acme')).rejects.toThrow('fetch failed');
+ });
+
+ it('exits when nothing matches', async () => {
+ await expect(resolveWorkspaceRef('nope')).rejects.toThrow('process.exit');
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('nope'));
+ });
+});
diff --git a/apps/cli/src/api/workspaceRef.ts b/apps/cli/src/api/workspaceRef.ts
new file mode 100644
index 00000000000..baaa8a03fe7
--- /dev/null
+++ b/apps/cli/src/api/workspaceRef.ts
@@ -0,0 +1,77 @@
+import { isTRPCClientError } from '@trpc/client';
+import pc from 'picocolors';
+
+import { log } from '../utils/logger';
+import { getTrpcClient } from './client';
+
+export interface WorkspaceRow {
+ id: string;
+ lockedOut?: boolean;
+ name: string;
+ plan?: string;
+ role?: string | null;
+ slug: string;
+ updatedAt?: Date | string;
+}
+
+export const listWorkspaces = async (): Promise<WorkspaceRow[]> => {
+ const client = await getTrpcClient();
+ return (await client.workspace.list.query()) as WorkspaceRow[];
+};
+
+/** Accept either a workspace id or its slug; an id wins when both could match. */
+export const findWorkspace = (
+ workspaces: WorkspaceRow[],
+ idOrSlug: string,
+): WorkspaceRow | undefined =>
+ workspaces.find((w) => w.id === idOrSlug) ?? workspaces.find((w) => w.slug === idOrSlug);
+
+const exitNotFound = (idOrSlug: string, workspaces: WorkspaceRow[]): never => {
+ log.error(`Workspace not found: ${idOrSlug}`);
+ if (workspaces.length > 0) {
+ console.log(pc.dim('Available:'));
+ for (const w of workspaces) console.log(pc.dim(` ${w.id} ${w.slug} ${w.name}`));
+ }
+ process.exit(1);
+};
+
+/**
+ * Resolve a workspace id or slug the caller belongs to, exiting with the
+ * available workspaces when it matches none. Cloud answers an unknown
+ * `X-Workspace-Id` by falling back to personal scope, so a slug passed through
+ * as-is would silently read the wrong tenant.
+ */
+export const resolveWorkspace = async (idOrSlug: string): Promise<WorkspaceRow> => {
+ const workspaces = await listWorkspaces();
+ return findWorkspace(workspaces, idOrSlug) ?? exitNotFound(idOrSlug, workspaces);
+};
+
+/**
+ * Turn an optional `--workspace <id|slug>` value into a workspace id. Leaves
+ * `undefined` alone so the ambient scope (env, `workspace use`) still applies.
+ * When the caller's credentials are refused `workspace.list`, the value is
+ * passed through as an id (how `--workspace` behaved before slugs) with a warning.
+ */
+export const resolveWorkspaceRef = async (idOrSlug?: string): Promise<string | undefined> => {
+ if (!idOrSlug) return undefined;
+
+ let workspaces: WorkspaceRow[];
+ try {
+ workspaces = await listWorkspaces();
+ } catch (error) {
+ // Only a scope refusal passes through. Any other failure (network, server)
+ // is not evidence the value is an id, and forwarding a slug would read the
+ // personal scope instead.
+ if (!isTRPCClientError(error) || error.data?.code !== 'FORBIDDEN') throw error;
+
+ // Keep ids working for credentials scoped below `workspace:read`, but say
+ // so: a slug sent as `X-Workspace-Id` is rejected or read the wrong scope.
+ log.debug('workspace.list failed', error);
+ log.warn(
+ `Could not look up workspaces with these credentials, so "${idOrSlug}" is used as a workspace id. If it is a slug, pass the workspace id instead.`,
+ );
+ return idOrSlug;
+ }
+
+ return findWorkspace(workspaces, idOrSlug)?.id ?? exitNotFound(idOrSlug, workspaces);
+};
diff --git a/apps/cli/src/commands/device.test.ts b/apps/cli/src/commands/device.test.ts
index a6ff018a6a1..78a2ebdd065 100644
--- a/apps/cli/src/commands/device.test.ts
+++ b/apps/cli/src/commands/device.test.ts
@@ -14,6 +14,7 @@ const { mockTrpcClient } = vi.hoisted(() => ({
removeWorkspaceDevice: { mutate: vi.fn() },
status: { query: vi.fn() },
},
+ workspace: { list: { query: vi.fn() } },
},
}));
@@ -40,6 +41,9 @@ describe('device command', () => {
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
mockConfirm.mockReset();
+ mockTrpcClient.workspace.list.query.mockResolvedValue([
+ { id: 'ws-abc', name: 'Acme', slug: 'acme' },
+ ]);
for (const method of Object.values(mockTrpcClient.device)) {
for (const fn of Object.values(method)) {
(fn as ReturnType<typeof vi.fn>).mockReset();
@@ -193,7 +197,7 @@ describe('device command', () => {
expect(mockTrpcClient.device.removeDevice.mutate).not.toHaveBeenCalled();
});
- it('should resolve the client under the workspace context when --workspace is set', async () => {
+ it('should resolve a --workspace slug to its id before acting', async () => {
mockTrpcClient.device.listDevices.query.mockResolvedValue([
{ deviceId: 'ws1', scope: 'workspace' },
]);
@@ -208,7 +212,7 @@ describe('device command', () => {
'ws1',
'--yes',
'--workspace',
- 'ws-abc',
+ 'acme',
]);
expect(mockGetTrpcClient).toHaveBeenCalledWith('ws-abc');
diff --git a/apps/cli/src/commands/device.ts b/apps/cli/src/commands/device.ts
index 7da70eb15b6..17c1880fcbc 100644
--- a/apps/cli/src/commands/device.ts
+++ b/apps/cli/src/commands/device.ts
@@ -2,6 +2,7 @@ import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
+import { resolveWorkspaceRef } from '../api/workspaceRef';
import { confirm, outputJson, printTable, timeAgo } from '../utils/format';
import { log } from '../utils/logger';
@@ -14,9 +15,9 @@ export function registerDeviceCommand(program: Command) {
.command('list')
.description('List all online devices')
.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
- .option('--workspace <id>', "List the workspace's shared devices instead of personal ones")
+ .option('--workspace <id|slug>', "List the workspace's shared devices instead of personal ones")
.action(async (options: { json?: string | boolean; workspace?: string }) => {
- const client = await getTrpcClient(options.workspace);
+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));
const all = await client.device.listDevices.query();
// With a workspace context the server returns BOTH pools (personal +
@@ -63,9 +64,9 @@ export function registerDeviceCommand(program: Command) {
.command('info <deviceId>')
.description('Show system info of a specific device')
.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
- .option('--workspace <id>', 'Reach the device through this workspace context')
+ .option('--workspace <id|slug>', 'Reach the device through this workspace context')
.action(async (deviceId: string, options: { json?: string | boolean; workspace?: string }) => {
- const client = await getTrpcClient(options.workspace);
+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));
const info = await client.device.getDeviceSystemInfo.query({ deviceId });
if (!info) {
@@ -99,7 +100,10 @@ export function registerDeviceCommand(program: Command) {
.alias('remove')
.description('Remove one or more devices from your account')
.option('--yes', 'Skip confirmation prompt')
- .option('--workspace <id>', 'Remove devices from this workspace pool (owner/enroller only)')
+ .option(
+ '--workspace <id|slug>',
+ 'Remove devices from this workspace pool (owner/enroller only)',
+ )
.action(async (deviceIds: string[], options: { workspace?: string; yes?: boolean }) => {
if (!options.yes) {
const label =
@@ -111,7 +115,7 @@ export function registerDeviceCommand(program: Command) {
}
}
- const client = await getTrpcClient(options.workspace);
+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));
// Resolve each device's scope first: workspace devices are owner-gated and
// live in a separate pool, so they need `removeWorkspaceDevice`, not the
@@ -160,9 +164,9 @@ export function registerDeviceCommand(program: Command) {
.command('status')
.description('Show device connection overview')
.option('--json', 'Output JSON')
- .option('--workspace <id>', 'Report against this workspace context')
+ .option('--workspace <id|slug>', 'Report against this workspace context')
.action(async (options: { json?: boolean; workspace?: string }) => {
- const client = await getTrpcClient(options.workspace);
+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));
const status = await client.device.status.query();
if (options.json) {
diff --git a/apps/cli/src/commands/topic.test.ts b/apps/cli/src/commands/topic.test.ts
index b29767a2787..f9a71f08fc0 100644
--- a/apps/cli/src/commands/topic.test.ts
+++ b/apps/cli/src/commands/topic.test.ts
@@ -16,6 +16,7 @@ const { mockTrpcClient } = vi.hoisted(() => ({
searchTopics: { query: vi.fn() },
updateTopic: { mutate: vi.fn() },
},
+ workspace: { list: { query: vi.fn() } },
},
}));
@@ -33,6 +34,9 @@ describe('topic command', () => {
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ mockTrpcClient.workspace.list.query.mockResolvedValue([
+ { id: 'ws_1', name: 'Acme', slug: 'acme' },
+ ]);
for (const method of Object.values(mockTrpcClient.topic)) {
for (const fn of Object.values(method)) {
(fn as ReturnType<typeof vi.fn>).mockReset();
@@ -271,6 +275,33 @@ describe('topic command', () => {
expect(mockGetTrpcClient).toHaveBeenCalledWith('ws_1');
});
+ it('resolves a --workspace slug to its id', async () => {
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'topic',
+ 'view',
+ 't1',
+ '--workspace',
+ 'acme',
+ ]);
+
+ expect(mockGetTrpcClient).toHaveBeenLastCalledWith('ws_1');
+ });
+
+ it('exits without reading when --workspace matches no workspace', async () => {
+ exitSpy.mockImplementation((() => {
+ throw new Error('process.exit');
+ }) as never);
+
+ await expect(
+ createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1', '--workspace', 'nope']),
+ ).rejects.toThrow('process.exit');
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.topic.getTopicTranscript.query).not.toHaveBeenCalled();
+ });
+
it('uses the aggregate endpoint without loading messages for --no-messages', async () => {
mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
items: [],
diff --git a/apps/cli/src/commands/topic/export.ts b/apps/cli/src/commands/topic/export.ts
index 1d4714506f8..4b4e7af2d5d 100644
--- a/apps/cli/src/commands/topic/export.ts
+++ b/apps/cli/src/commands/topic/export.ts
@@ -4,6 +4,7 @@ import type { Command } from 'commander';
import { Option } from 'commander';
import { getTrpcClient } from '../../api/client';
+import { resolveWorkspaceRef } from '../../api/workspaceRef';
import type { TopicTranscript } from './atif';
import { toAtif } from './atif';
@@ -15,9 +16,9 @@ export function registerTopicExportCommand(topic: Command) {
)
.addOption(new Option('--format <format>', 'Export format').choices(['atif']).default('atif'))
.option('-o, --output <path>', 'Write to a file instead of stdout (use - for stdout)')
- .option('--workspace <id>', 'Read the topic from this workspace')
+ .option('--workspace <id|slug>', 'Read the topic from this workspace')
.action(async (id: string, options: { output?: string; workspace?: string }) => {
- const client = await getTrpcClient(options.workspace);
+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));
let transcript: TopicTranscript | undefined;
const items: TopicTranscript['items'] = [];
do {
diff --git a/apps/cli/src/commands/topic/view.ts b/apps/cli/src/commands/topic/view.ts
index 0752e1df8e1..53047cb9a7f 100644
--- a/apps/cli/src/commands/topic/view.ts
+++ b/apps/cli/src/commands/topic/view.ts
@@ -2,6 +2,7 @@ import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
+import { resolveWorkspaceRef } from '../../api/workspaceRef';
import { timeAgo } from '../../utils/format';
import { log } from '../../utils/logger';
import { readTopicTranscript } from './readTranscript';
@@ -270,7 +271,7 @@ export function registerTopicViewCommand(topic: Command) {
.option('--no-messages', 'Skip messages, show topic metadata only')
.option('--json', 'Output JSON')
.option(
- '--workspace <id>',
+ '--workspace <id|slug>',
"Read the topic from this workspace (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')",
)
.action(async (id: string, options: TopicViewOptions) => {
@@ -278,11 +279,12 @@ export function registerTopicViewCommand(topic: Command) {
const pagination = includeMessages
? resolvePagination(options)
: { from: 1, limit: DEFAULT_LIMIT, offset: 0 };
- const client = await getTrpcClient(options.workspace);
+ const workspace = await resolveWorkspaceRef(options.workspace);
+ const client = await getTrpcClient(workspace);
const result = await readTopicTranscript(
client,
{ includeMessages, limit: pagination.limit, offset: pagination.offset, topicId: id },
- options.workspace,
+ workspace,
);
const messages = result.items as TranscriptMessage[];
diff --git a/apps/cli/src/commands/workspace.test.ts b/apps/cli/src/commands/workspace.test.ts
index 25f8d5edd60..b79c3bcbd4a 100644
--- a/apps/cli/src/commands/workspace.test.ts
+++ b/apps/cli/src/commands/workspace.test.ts
@@ -73,6 +73,10 @@ describe('workspace command', () => {
scopedTo(undefined);
mockResolveIdentityFingerprint.mockReturnValue('user:u1');
mockGetTrpcClient.mockResolvedValue(mockClient);
+ mockClient.workspace.list.query.mockResolvedValue([
+ { id: 'ws_1', name: 'Acme', role: 'owner', slug: 'acme' },
+ { id: 'ws_9', name: 'Ops', role: 'member', slug: 'ops' },
+ ]);
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
vi.spyOn(process, 'exit').mockImplementation((() => {
throw new Error('process.exit');
@@ -213,6 +217,23 @@ describe('workspace command', () => {
expect(consoleSpy).toHaveBeenCalledWith('No members found.');
});
+ it('resolves a --workspace slug to its id', async () => {
+ mockClient.workspaceMember.list.query.mockResolvedValue([]);
+
+ await run('workspace', 'members', '-w', 'ops');
+
+ expect(mockGetTrpcClient).toHaveBeenLastCalledWith('ws_9');
+ });
+
+ // Passing an unknown value through would hit a server that quietly falls
+ // back to personal scope, so it has to fail before any scoped read.
+ it('rejects a --workspace the account does not belong to', async () => {
+ await expect(run('workspace', 'members', '-w', 'nope')).rejects.toThrow('process.exit');
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('nope'));
+ expect(mockClient.workspaceMember.list.query).not.toHaveBeenCalled();
+ });
+
it('lists members of the active workspace', async () => {
scopedTo('ws_1');
mockClient.workspaceMember.list.query.mockResolvedValue([
@@ -253,6 +274,18 @@ describe('workspace command', () => {
);
});
+ it('accepts a slug as the argument', async () => {
+ mockClient.workspace.getById.query.mockResolvedValue({
+ id: 'ws_1',
+ name: 'Acme',
+ slug: 'acme',
+ });
+
+ await run('workspace', 'view', 'acme');
+
+ expect(mockGetTrpcClient).toHaveBeenLastCalledWith('ws_1');
+ });
+
it('exits when the workspace is gone', async () => {
scopedTo('ws_1');
mockClient.workspace.getById.query.mockResolvedValue(null);
diff --git a/apps/cli/src/commands/workspace.ts b/apps/cli/src/commands/workspace.ts
index cca6dd3b136..de6f757cc67 100644
--- a/apps/cli/src/commands/workspace.ts
+++ b/apps/cli/src/commands/workspace.ts
@@ -7,6 +7,12 @@ import {
resolveWorkspaceScope,
type WorkspaceScope,
} from '../api/workspace';
+import {
+ listWorkspaces,
+ resolveWorkspace,
+ resolveWorkspaceRef,
+ type WorkspaceRow,
+} from '../api/workspaceRef';
import { resolveIdentityFingerprint } from '../auth/identity';
import { CLI_PRIMARY_BIN } from '../constants/identity';
import { type ActiveWorkspaceRecord, resolveServerUrl, saveActiveWorkspace } from '../settings';
@@ -14,16 +20,6 @@ import { formatCost, outputJson, printTable, timeAgo, timeUntil, truncate } from
import { log } from '../utils/logger';
import { workspaceUrl } from './resourceUrl';
-interface WorkspaceRow {
- id: string;
- lockedOut?: boolean;
- name: string;
- plan?: string;
- role?: string | null;
- slug: string;
- updatedAt?: Date | string;
-}
-
const SCOPE_HINTS: Record<WorkspaceScope['source'], string> = {
env: 'LOBEHUB_WORKSPACE_ID',
explicit: '--workspace',
@@ -43,13 +39,14 @@ const describeScope = (scope: WorkspaceScope): string =>
* Every workspace-scoped read goes through the workspace header, so a command
* that forgets `--workspace` while the CLI sits in personal scope silently
* queries the wrong tenant. Fail loudly instead, and say how to fix it.
+ * An explicit id or slug is resolved against the caller's workspaces first.
*/
-const requireScope = (explicit?: string): string => {
- const scope = resolveWorkspaceScope(explicit);
+const requireScope = async (explicit?: string): Promise<string> => {
+ const scope = resolveWorkspaceScope(await resolveWorkspaceRef(explicit));
if (scope.workspaceId) return scope.workspaceId;
log.error(
- `No workspace scope. Pass --workspace <id>, or run '${CLI_PRIMARY_BIN} workspace use <id|slug>' first.`,
+ `No workspace scope. Pass --workspace <id|slug>, or run '${CLI_PRIMARY_BIN} workspace use <id|slug>' first.`,
);
process.exit(1);
};
@@ -93,15 +90,6 @@ const isForbidden = (error: unknown): boolean =>
error !== null &&
(error as { data?: { code?: string } }).data?.code === 'FORBIDDEN';
-const listWorkspaces = async (): Promise<WorkspaceRow[]> => {
- const client = await getTrpcClient();
- return (await client.workspace.list.query()) as WorkspaceRow[];
-};
-
-/** Accept either a workspace id or its slug, so `lh workspace use acme` works. */
-const findWorkspace = (workspaces: WorkspaceRow[], idOrSlug: string): WorkspaceRow | undefined =>
- workspaces.find((w) => w.id === idOrSlug) ?? workspaces.find((w) => w.slug === idOrSlug);
-
const planLabel = (workspace: WorkspaceRow): string => {
if (!workspace.plan) return '-';
return workspace.lockedOut ? `${workspace.plan} (inactive)` : workspace.plan;
@@ -173,18 +161,7 @@ export function registerWorkspaceCommand(program: Command) {
process.exit(1);
}
- const workspaces = await listWorkspaces();
- const match = findWorkspace(workspaces, idOrSlug);
-
- if (!match) {
- log.error(`Workspace not found: ${idOrSlug}`);
- if (workspaces.length > 0) {
- console.log(pc.dim('Available:'));
- for (const w of workspaces) console.log(pc.dim(` ${w.id} ${w.slug} ${w.name}`));
- }
- process.exit(1);
- }
-
+ const match = await resolveWorkspace(idOrSlug);
persistScope(match.id);
console.log(`Scope set to ${pc.bold(match.name)} ${pc.dim(match.id)}.`);
@@ -224,11 +201,11 @@ export function registerWorkspaceCommand(program: Command) {
});
workspace
- .command('view [workspaceId]')
+ .command('view [workspaceIdOrSlug]')
.description('View workspace detail (defaults to the active scope)')
.option('--json [fields]', 'Output JSON')
- .action(async (workspaceId: string | undefined, options: { json?: boolean | string }) => {
- const scopeId = requireScope(workspaceId);
+ .action(async (idOrSlug: string | undefined, options: { json?: boolean | string }) => {
+ const scopeId = await requireScope(idOrSlug);
const client = await getTrpcClient(scopeId);
const detail = (await client.workspace.getById.query()) as WorkspaceRow | null;
@@ -289,7 +266,7 @@ export function registerWorkspaceCommand(program: Command) {
workspace
.command('update')
.description('Update workspace profile (admin or higher)')
- .option('-w, --workspace <id>', 'Workspace to update (defaults to the active scope)')
+ .option('-w, --workspace <id|slug>', 'Workspace to update (defaults to the active scope)')
.option('-n, --name <name>', 'Display name')
.option('-s, --slug <slug>', 'URL slug')
.option('-d, --description <description>', 'Description')
@@ -314,7 +291,7 @@ export function registerWorkspaceCommand(program: Command) {
process.exit(1);
}
- const scopeId = requireScope(options.workspace);
+ const scopeId = await requireScope(options.workspace);
await (await getTrpcClient(scopeId)).workspace.update.mutate(patch);
console.log('Workspace updated.');
},
@@ -323,10 +300,10 @@ export function registerWorkspaceCommand(program: Command) {
workspace
.command('settings')
.description('Show the workspace settings blob')
- .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')
+ .option('-w, --workspace <id|slug>', 'Workspace to read (defaults to the active scope)')
.option('--json [fields]', 'Output JSON')
.action(async (options: { json?: boolean | string; workspace?: string }) => {
- const scopeId = requireScope(options.workspace);
+ const scopeId = await requireScope(options.workspace);
const settings = await (await getTrpcClient(scopeId)).workspace.getSettings.query();
if (options.json !== undefined) return outputJson(settings, options.json);
console.log(JSON.stringify(settings ?? {}, null, 2));
@@ -335,11 +312,11 @@ export function registerWorkspaceCommand(program: Command) {
workspace
.command('stats')
.description('Show workspace-wide content statistics (admin or higher)')
- .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')
+ .option('-w, --workspace <id|slug>', 'Workspace to read (defaults to the active scope)')
.option('--mine', 'Count only content you created — available to every member')
.option('--json [fields]', 'Output JSON')
.action(async (options: { json?: boolean | string; mine?: boolean; workspace?: string }) => {
- const scopeId = requireScope(options.workspace);
+ const scopeId = await requireScope(options.workspace);
const client = await getTrpcClient(scopeId);
const input = { todayStartAt: new Date(new Date().setHours(0, 0, 0, 0)).toISOString() };
// Workspace-wide totals are Admin-or-higher; members and viewers hit a bare
@@ -367,7 +344,7 @@ export function registerWorkspaceCommand(program: Command) {
workspace
.command('usage')
.description('Show workspace credit usage for the current billing window')
- .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')
+ .option('-w, --workspace <id|slug>', 'Workspace to read (defaults to the active scope)')
.option('--since <date>', 'Window start (ISO date)')
.option('--until <date>', 'Window end (ISO date)')
.option('--json [fields]', 'Output JSON')
@@ -378,7 +355,7 @@ export function registerWorkspaceCommand(program: Command) {
until?: string;
workspace?: string;
}) => {
- const scopeId = requireScope(options.workspace);
+ const scopeId = await requireScope(options.workspace);
const usage = await (
await getTrpcClient(scopeId)
).workspaceUsage.getCurrentUsage.query({ since: options.since, until: options.until });
@@ -405,10 +382,10 @@ export function registerWorkspaceCommand(program: Command) {
workspace
.command('members')
.description('List workspace members')
- .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')
+ .option('-w, --workspace <id|slug>', 'Workspace to read (defaults to the active scope)')
.option('--json [fields]', 'Output JSON')
.action(async (options: { json?: boolean | string; workspace?: string }) => {
- const scopeId = requireScope(options.workspace);
+ const scopeId = await requireScope(options.workspace);
const members = await (await getTrpcClient(scopeId)).workspaceMember.list.query({});
if (options.json !== undefined) return outputJson(members, options.json);
@@ -429,7 +406,7 @@ export function registerWorkspaceCommand(program: Command) {
workspace
.command('invite <email>')
.description('Invite a member by email (admin or higher)')
- .option('-w, --workspace <id>', 'Workspace to invite into (defaults to the active scope)')
+ .option('-w, --workspace <id|slug>', 'Workspace to invite into (defaults to the active scope)')
.option('-r, --role <role>', 'Role to grant: admin | member | viewer', 'member')
.option('--json [fields]', 'Output JSON')
.action(
@@ -444,7 +421,7 @@ export function registerWorkspaceCommand(program: Command) {
process.exit(1);
}
- const scopeId = requireScope(options.workspace);
+ const scopeId = await requireScope(options.workspace);
const invitation = await (
await getTrpcClient(scopeId)
).workspaceMember.invite.mutate({ email, role });
@@ -457,10 +434,10 @@ export function registerWorkspaceCommand(program: Command) {
workspace
.command('invitations')
.description('List pending invitations (admin or higher)')
- .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')
+ .option('-w, --workspace <id|slug>', 'Workspace to read (defaults to the active scope)')
.option('--json [fields]', 'Output JSON')
.action(async (options: { json?: boolean | string; workspace?: string }) => {
- const scopeId = requireScope(options.workspace);
+ const scopeId = await requireScope(options.workspace);
const invitations = await (
await getTrpcClient(scopeId)
).workspaceMember.listInvitations.query();
@@ -485,7 +462,7 @@ export function registerWorkspaceCommand(program: Command) {
workspace
.command('audit-log')
.description('List workspace audit-log entries (admin or higher, Business plan)')
- .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')
+ .option('-w, --workspace <id|slug>', 'Workspace to read (defaults to the active scope)')
.option('--action <action>', 'Filter by action, for example workspace.updated')
.option('--resource-type <type>', 'Filter by resource type')
.option('-q, --query <text>', 'Free-text search')
@@ -510,7 +487,7 @@ export function registerWorkspaceCommand(program: Command) {
process.exit(1);
}
- const scopeId = requireScope(options.workspace);
+ const scopeId = await requireScope(options.workspace);
const result = await (
await getTrpcClient(scopeId)
).workspaceAuditLog.list.query({
diff --git a/packages/builtin-skills/src/lobehub/references/workspace.ts b/packages/builtin-skills/src/lobehub/references/workspace.ts
index 6402dfdc31b..543ae9ef4bb 100644
--- a/packages/builtin-skills/src/lobehub/references/workspace.ts
+++ b/packages/builtin-skills/src/lobehub/references/workspace.ts
@@ -24,19 +24,22 @@ matching, say what you checked and ask. Do not report "not found" after looking
- \`lh workspace current [--json]\` - Show the scope commands run under, and where it came from
- \`lh workspace use <id|slug>\` / \`lh workspace use --personal\` - Switch the saved scope (restore it afterwards, see below)
- \`lh workspace list [--json]\` - List workspaces you belong to (id, name, slug, role, plan)
-- \`lh workspace view [workspaceId] [--json]\` - View workspace detail (defaults to the active scope)
-- \`lh workspace members [-w <id>] [--json]\` - List workspace members
-- \`lh workspace stats [-w <id>] [--mine] [--json]\` - Content statistics (admin or higher; \`--mine\` works for every member)
-- \`lh workspace usage [-w <id>] [--since <date>] [--until <date>] [--json]\` - Credit usage for the current billing window
-- \`lh workspace settings [-w <id>] [--json]\` - Show the workspace settings blob
+- \`lh workspace view [workspaceIdOrSlug] [--json]\` - View workspace detail (defaults to the active scope)
+- \`lh workspace members [-w <id|slug>] [--json]\` - List workspace members
+- \`lh workspace stats [-w <id|slug>] [--mine] [--json]\` - Content statistics (admin or higher; \`--mine\` works for every member)
+- \`lh workspace usage [-w <id|slug>] [--since <date>] [--until <date>] [--json]\` - Credit usage for the current billing window
+- \`lh workspace settings [-w <id|slug>] [--json]\` - Show the workspace settings blob
- \`lh workspace create <name> -s <slug> [-d <desc>] [--avatar <url|emoji>] [--use]\` - Create a workspace
-- \`lh workspace update [-w <id>] [-n <name>] [-s <slug>] [-d <desc>] [--avatar <url|emoji>]\` - Update the profile (admin or higher)
-- \`lh workspace invite <email> [-w <id>] [-r admin|member|viewer]\` - Invite a member (admin or higher)
-- \`lh workspace invitations [-w <id>]\` - List pending invitations (admin or higher)
-- \`lh workspace audit-log [-w <id>] [--action <a>] [--resource-type <t>] [-q <text>] [--start <date>] [--end <date>] [-L <n>]\` - Audit log (admin or higher, Business plan)
+- \`lh workspace update [-w <id|slug>] [-n <name>] [-s <slug>] [-d <desc>] [--avatar <url|emoji>]\` - Update the profile (admin or higher)
+- \`lh workspace invite <email> [-w <id|slug>] [-r admin|member|viewer]\` - Invite a member (admin or higher)
+- \`lh workspace invitations [-w <id|slug>]\` - List pending invitations (admin or higher)
+- \`lh workspace audit-log [-w <id|slug>] [--action <a>] [--resource-type <t>] [-q <text>] [--start <date>] [--end <date>] [-L <n>]\` - Audit log (admin or higher, Business plan)
\`-w\` only changes which workspace these \`lh workspace\` subcommands read. It does not
change the scope of other modules.
+A workspace slug works in place of an id for \`-w\`, \`--workspace\` and the \`view\` argument,
+so there is no need to look up the id first. Resolving a slug needs \`workspace:read\`; a
+credential without it (such as a workspace-bound API key) must pass the workspace id.
## Scope rules for agent runs
@@ -53,7 +56,7 @@ change the scope of other modules.
The saved scope is shared by every later \`lh\` command on this machine, including the
user's own. Restore it even when the work fails partway. If \`lh workspace current\`
does not change after \`use\`, this run's scope is fixed: tell the user instead of retrying.
-- \`lh topic view <id> --workspace <workspaceId>\` and \`lh topic export <id> --workspace <workspaceId>\`
+- \`lh topic view <id> --workspace <id|slug>\` and \`lh topic export <id> --workspace <id|slug>\`
read one conversation from another workspace without switching.
- Role-gated commands (admin or higher) fail with a permission error for members. Report
that error as it is. Do not retry with other flags.