🤯 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(agent): scope `lh` to the run's workspace and resolve it in every shell form (#17915)
Rdmclin2b121160d7fc6
diff --git a/apps/cli/src/api/client.test.ts b/apps/cli/src/api/client.test.tsnew file mode 100644index 00000000000..f039e5b37d7--- /dev/null+++ b/apps/cli/src/api/client.test.ts@@ -0,0 +1,73 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mockCreateTRPCClient = vi.hoisted(() => vi.fn(() => ({ marker: 'client' })));+const mockHttpLink = vi.hoisted(() => vi.fn((opts: unknown) => opts));++vi.mock('@trpc/client', () => ({+ createTRPCClient: mockCreateTRPCClient,+ httpLink: mockHttpLink,+}));++vi.mock('../auth/refresh', () => ({+ getValidToken: vi.fn(),+}));++vi.mock('../settings', () => ({+ resolveServerUrl: () => 'https://app.lobehub.com',+}));++vi.mock('../utils/logger', () => ({+ log: { error: vi.fn() },+}));++const headersOfLastLink = () => (mockHttpLink.mock.calls.at(-1)![0] as any).headers;++describe('api/client workspace scoping', () => {+ const originalJwt = process.env.LOBEHUB_JWT;+ const originalWorkspaceId = process.env.LOBEHUB_WORKSPACE_ID;++ beforeEach(() => {+ vi.clearAllMocks();+ vi.resetModules();+ process.env.LOBEHUB_JWT = 'env-jwt';+ delete process.env.LOBEHUB_WORKSPACE_ID;+ });++ afterEach(() => {+ if (originalJwt === undefined) delete process.env.LOBEHUB_JWT;+ else process.env.LOBEHUB_JWT = originalJwt;++ if (originalWorkspaceId === undefined) delete process.env.LOBEHUB_WORKSPACE_ID;+ else process.env.LOBEHUB_WORKSPACE_ID = originalWorkspaceId;+ });++ // The tools router is workspace aware like lambda; without the header every+ // `lh search` ran against personal scope and billed the personal budget.+ it('scopes the tools client to the run workspace', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'workspace-1';++ const { getToolsTrpcClient } = await import('./client');+ await getToolsTrpcClient();++ expect(headersOfLastLink()).toMatchObject({ 'X-Workspace-Id': 'workspace-1' });+ });++ it('omits the header for the tools client in personal mode', async () => {+ const { getToolsTrpcClient } = await import('./client');+ await getToolsTrpcClient();++ expect(headersOfLastLink()).not.toHaveProperty('X-Workspace-Id');+ });++ it('caches tools clients per workspace instead of returning the first one forever', async () => {+ const { getToolsTrpcClient } = await import('./client');++ const personal = await getToolsTrpcClient();+ const scoped = await getToolsTrpcClient('workspace-1');+ const scopedAgain = await getToolsTrpcClient('workspace-1');++ expect(mockCreateTRPCClient).toHaveBeenCalledTimes(2);+ expect(scoped).toBe(scopedAgain);+ expect(scoped).not.toBe(personal);+ });+});diff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.tsindex ae826ea0f34..a932cd66015 100644--- a/apps/cli/src/api/client.ts+++ b/apps/cli/src/api/client.ts@@ -15,7 +15,7 @@ export type ToolsTrpcClient = ReturnType<typeof createTRPCClient<ToolsRouter>>;const PERSONAL_KEY = '__personal__';const _clients = new Map<string, TrpcClient>();-let _toolsClient: ToolsTrpcClient | undefined;+const _toolsClients = new Map<string, ToolsTrpcClient>();async function getAuthAndServer(): Promise<{ headers: Record<string, string>; serverUrl: string }> {// LOBEHUB_JWT + LOBEHUB_SERVER env vars (used by server-side sandbox execution)@@ -107,19 +107,29 @@ export function createLambdaClient(});}-export async function getToolsTrpcClient(): Promise<ToolsTrpcClient> {- if (_toolsClient) return _toolsClient;+/**+ * Same workspace scoping as `getTrpcClient` — the tools router is workspace+ * aware too, and dropping the header here silently ran every tools call+ * (web/local search, market) against personal scope, which also mis-attributes+ * the spend.+ */+export async function getToolsTrpcClient(workspaceId?: string): Promise<ToolsTrpcClient> {+ const wsId = resolveWorkspaceId(workspaceId);+ const cacheKey = wsId ?? PERSONAL_KEY;+ const cached = _toolsClients.get(cacheKey);+ if (cached) return cached;const { headers, serverUrl } = await getAuthAndServer();- _toolsClient = createTRPCClient<ToolsRouter>({+ const client = createTRPCClient<ToolsRouter>({links: [httpLink({- headers,+ headers: withWorkspaceHeader(headers, wsId),transformer: superjson,url: `${serverUrl}/trpc/tools`,}),],});+ _toolsClients.set(cacheKey, client);- return _toolsClient;+ return client;}diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.tsindex 920e239bbc5..d6a7fa7244f 100644--- a/apps/cli/src/commands/agent.test.ts+++ b/apps/cli/src/commands/agent.test.ts@@ -455,6 +455,127 @@ describe('agent command', () => {expect(exitSpy).toHaveBeenCalledWith(1);expect(mockTrpcClient.agent.updateAgentConfig.mutate).not.toHaveBeenCalled();});++ // The dedicated flags cover six fields; everything else an agent may want+ // to change about itself (opening message, tags, params, …) had no CLI+ // path, even though `agent.updateAgentConfig` is a passthrough server-side.+ it('should send arbitrary config fields from --config-file', async () => {+ mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});+ const configFile = await writeGraphFixture({+ openingMessage: 'Hi! Ask me about deploys.',+ tags: ['devops'],+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'edit',+ 'a1',+ '--config-file',+ configFile,+ ]);++ expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({+ agentId: 'a1',+ value: { openingMessage: 'Hi! Ask me about deploys.', tags: ['devops'] },+ });+ });++ it('should let explicit flags win over --config-file', async () => {+ mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});+ const configFile = await writeGraphFixture({+ description: 'from file',+ title: 'from file',+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'edit',+ 'a1',+ '--config-file',+ configFile,+ '--title',+ 'from flag',+ ]);++ expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({+ agentId: 'a1',+ value: { description: 'from file', title: 'from flag' },+ });+ });++ it('should merge graph flags into a chatConfig supplied by --config-file', async () => {+ mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});+ const configFile = await writeGraphFixture({ chatConfig: { historyCount: 12 } });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'edit',+ 'a1',+ '--config-file',+ configFile,+ '--enable-graph',+ ]);++ expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({+ agentId: 'a1',+ value: { chatConfig: { enableGraphMode: true, historyCount: 12 } },+ });+ });++ it('should reject a non-object --config-file before updating', async () => {+ const configFile = await writeGraphFixture(['not', 'an', 'object']);++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'edit',+ 'a1',+ '--config-file',+ configFile,+ ]);++ expect(log.error).toHaveBeenCalledWith(+ expect.stringContaining('agent config JSON must be a plain object'),+ );+ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(mockTrpcClient.agent.updateAgentConfig.mutate).not.toHaveBeenCalled();+ });++ // Without this the caller can only assume the write landed — which is+ // exactly how a silently mis-scoped edit goes unnoticed.+ it('should print the updated agent with --json', async () => {+ mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({+ agent: { id: 'a1', title: 'Updated' },+ success: true,+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'edit',+ 'a1',+ '--title',+ 'Updated',+ '--json',+ ]);++ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify({ id: 'a1', title: 'Updated' }, null, 2),+ );+ });});describe('delete', () => {diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.tsindex 6503ef04d13..6d2fcb37658 100644--- a/apps/cli/src/commands/agent.ts+++ b/apps/cli/src/commands/agent.ts@@ -32,17 +32,23 @@ const readGraphConfig = async (graphFile: string): Promise<unknown> => {return result.data;};-const readAgencyConfig = async (agencyConfigFile: string): Promise<Record<string, unknown>> => {- const content = await readFile(agencyConfigFile, 'utf8');+const readJsonObjectFile = async (+ filePath: string,+ label: string,+): Promise<Record<string, unknown>> => {+ const content = await readFile(filePath, 'utf8');const parsed = JSON.parse(content);if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {- throw new Error('agencyConfig JSON must be a plain object');+ throw new Error(`${label} JSON must be a plain object`);}return parsed as Record<string, unknown>;};+const readAgencyConfig = (agencyConfigFile: string): Promise<Record<string, unknown>> =>+ readJsonObjectFile(agencyConfigFile, 'agencyConfig');+export function registerAgentCommand(program: Command) {const agent = program.command('agent').description('Manage agents');registerAgentSpaceFsCommand(agent);@@ -187,15 +193,22 @@ export function registerAgentCommand(program: Command) {'--agency-config-file <path>','agencyConfig JSON file, deep-merged into the agent (send `null` to clear a nested key)',)+ .option(+ '--config-file <path>',+ 'Agent config JSON file for fields without a dedicated flag (openingMessage, openingQuestions, tags, avatar, params, chatConfig, …). Deep-merged server-side; identity fields (id/slug/userId/workspaceId/visibility) are rejected. Explicit flags win over this file.',+ )+ .option('--json [fields]', 'Output the updated agent as JSON, optionally selecting fields').action(async (agentIdArg: string | undefined,options: {agencyConfigFile?: string;+ configFile?: string;description?: string;disableGraph?: boolean;enableGraph?: boolean;graphFile?: string;+ json?: string | boolean;model?: string;provider?: string;slug?: string;@@ -204,6 +217,19 @@ export function registerAgentCommand(program: Command) {},) => {const value: Record<string, any> = {};++ // Read first so the explicit flags below overwrite it — the file is the+ // broad brush, the flags are the precise correction.+ if (options.configFile) {+ try {+ Object.assign(value, await readJsonObjectFile(options.configFile, 'agent config'));+ } catch (error) {+ log.error(`Failed to read agent config JSON: ${(error as Error).message}`);+ process.exit(1);+ return;+ }+ }+if (options.title) value.title = options.title;if (options.description) value.description = options.description;if (options.model) value.model = options.model;@@ -228,7 +254,11 @@ export function registerAgentCommand(program: Command) {return;}}- if (Object.keys(chatConfig).length > 0) value.chatConfig = chatConfig;+ // Merged, not replaced: `--config-file` may carry other chatConfig keys+ // and the graph flags should only override the ones they own.+ if (Object.keys(chatConfig).length > 0) {+ value.chatConfig = { ...(value.chatConfig as object | undefined), ...chatConfig };+ }// agencyConfig is deep-merged server-side, so a nested key is removed by// sending it as `null` (e.g. `{ "heterogeneousProvider": null }`); omitted keys are kept.@@ -244,7 +274,7 @@ export function registerAgentCommand(program: Command) {if (Object.keys(value).length === 0) {log.error(- 'No changes specified. Use --title, --description, --model, --provider, --system-role, --graph-file, --enable-graph, --disable-graph, or --agency-config-file.',+ 'No changes specified. Use --title, --description, --model, --provider, --system-role, --graph-file, --enable-graph, --disable-graph, --agency-config-file, or --config-file.',);process.exit(1);return;@@ -252,7 +282,14 @@ export function registerAgentCommand(program: Command) {const client = await getTrpcClient();const agentId = await resolveAgentId(client, { agentId: agentIdArg, slug: options.slug });- await client.agent.updateAgentConfig.mutate({ agentId, value });+ const result: any = await client.agent.updateAgentConfig.mutate({ agentId, value });++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(result?.agent ?? result, fields);+ return;+ }+console.log(`${pc.green('✓')} Updated agent ${pc.bold(agentId)}`);},);diff --git a/apps/cli/src/commands/config.test.ts b/apps/cli/src/commands/config.test.tsindex 670a1a1ffe8..83fe54ad1d3 100644--- a/apps/cli/src/commands/config.test.ts+++ b/apps/cli/src/commands/config.test.ts@@ -28,8 +28,10 @@ vi.mock('../utils/logger', () => ({describe('config command', () => {let consoleSpy: ReturnType<typeof vi.spyOn>;+ const originalWorkspaceId = process.env.LOBEHUB_WORKSPACE_ID;beforeEach(() => {+ delete process.env.LOBEHUB_WORKSPACE_ID;consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});mockGetTrpcClient.mockResolvedValue(mockTrpcClient);mockTrpcClient.user.getUserState.query.mockReset();@@ -41,6 +43,8 @@ describe('config command', () => {afterEach(() => {consoleSpy.mockRestore();+ if (originalWorkspaceId === undefined) delete process.env.LOBEHUB_WORKSPACE_ID;+ else process.env.LOBEHUB_WORKSPACE_ID = originalWorkspaceId;});function createProgram() {@@ -73,7 +77,43 @@ describe('config command', () => {const program = createProgram();await program.parseAsync(['node', 'test', 'whoami', '--json']);- expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(state, null, 2));+ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify({ ...state, scope: 'personal', workspaceId: null }, null, 2),+ );+ });++ // Every command resolves its scope from this env var, so reporting it is+ // what lets a caller — usually an agent editing its own config — tell a+ // real "not found" from "I'm looking in the wrong workspace".+ it('should report the active workspace scope', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws-42';+ mockTrpcClient.user.getUserState.query.mockResolvedValue({ userId: 'u1' });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'whoami']);++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('workspace ws-42'));+ });++ it('should report personal scope when no workspace is set', async () => {+ mockTrpcClient.user.getUserState.query.mockResolvedValue({ userId: 'u1' });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'whoami']);++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('personal'));+ });++ it('should carry the workspace scope into --json output', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws-42';+ mockTrpcClient.user.getUserState.query.mockResolvedValue({ userId: 'u1' });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'whoami', '--json']);++ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify({ userId: 'u1', scope: 'workspace', workspaceId: 'ws-42' }, null, 2),+ );});});diff --git a/apps/cli/src/commands/config.ts b/apps/cli/src/commands/config.tsindex ca197a8b1e3..84d9cf7898c 100644--- a/apps/cli/src/commands/config.ts+++ b/apps/cli/src/commands/config.ts@@ -2,6 +2,7 @@ import type { Command } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';+import { resolveWorkspaceId } from '../api/workspace';import {type BoxTableRow,formatCost,@@ -22,9 +23,21 @@ export function registerConfigCommand(program: Command) {const client = await getTrpcClient();const state = await client.user.getUserState.query();+ // Every command resolves its scope the same way, so reporting it here is+ // what lets a caller (usually an agent editing its own config) tell a+ // genuine "not found" from "I'm looking in the wrong workspace".+ const workspaceId = resolveWorkspaceId();+if (options.json !== undefined) {const fields = typeof options.json === 'string' ? options.json : undefined;- outputJson(state, fields);+ outputJson(+ {+ ...(state as any),+ scope: workspaceId ? 'workspace' : 'personal',+ workspaceId: workspaceId ?? null,+ },+ fields,+ );return;}@@ -35,6 +48,9 @@ export function registerConfigCommand(program: Command) {if (s.email) console.log(` Email: ${s.email}`);if (s.userId) console.log(` User ID: ${s.userId}`);if (s.subscriptionPlan) console.log(` Plan: ${s.subscriptionPlan}`);+ console.log(+ ` Scope: ${workspaceId ? `workspace ${workspaceId}` : pc.dim('personal (no workspace scope)')}`,+ );});// ── usage ─────────────────────────────────────────────@@ -46,154 +62,163 @@ export function registerConfigCommand(program: Command) {.option('--agent-id <id>', 'Filter usage to a single agent').option('--daily', 'Group by day').option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')- .action(async (options: { agentId?: string; daily?: boolean; json?: string | boolean; month?: string }) => {- const client = await getTrpcClient();+ .action(+ async (options: {+ agentId?: string;+ daily?: boolean;+ json?: string | boolean;+ month?: string;+ }) => {+ const client = await getTrpcClient();++ const input: { agentId?: string; mo?: string } = {};+ if (options.month) input.mo = options.month;+ if (options.agentId) input.agentId = options.agentId;++ if (options.json !== undefined) {+ let jsonResult: any;+ if (options.daily) {+ jsonResult = await client.usage.findAndGroupByDay.query(input);+ } else {+ jsonResult = await client.usage.findByMonth.query(input);+ }+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(jsonResult, fields);+ return;+ }- const input: { agentId?: string; mo?: string } = {};- if (options.month) input.mo = options.month;- if (options.agentId) input.agentId = options.agentId;+ // Always fetch daily-grouped data for table display+ const result: any = await client.usage.findAndGroupByDay.query(input);- if (options.json !== undefined) {- let jsonResult: any;- if (options.daily) {- jsonResult = await client.usage.findAndGroupByDay.query(input);- } else {- jsonResult = await client.usage.findByMonth.query(input);+ if (!result) {+ console.log('No usage data available.');+ return;}- const fields = typeof options.json === 'string' ? options.json : undefined;- outputJson(jsonResult, fields);- return;- }-- // Always fetch daily-grouped data for table display- const result: any = await client.usage.findAndGroupByDay.query(input);- if (!result) {- console.log('No usage data available.');- return;- }+ // Normalize result to an array of daily logs+ const logs: any[] = Array.isArray(result) ? result : [result];- // Normalize result to an array of daily logs- const logs: any[] = Array.isArray(result) ? result : [result];+ // Filter out days with zero activity for cleaner output+ const activeLogs = logs.filter(+ (l: any) => (l.totalTokens || 0) > 0 || (l.totalRequests || 0) > 0,+ );- // Filter out days with zero activity for cleaner output- const activeLogs = logs.filter(- (l: any) => (l.totalTokens || 0) > 0 || (l.totalRequests || 0) > 0,- );+ if (activeLogs.length === 0) {+ console.log('No usage data available.');+ return;+ }- if (activeLogs.length === 0) {- console.log('No usage data available.');- return;- }+ // Build table columns+ const columns = [+ { align: 'left' as const, header: 'Date', key: 'date' },+ { align: 'left' as const, header: 'Models', key: 'models' },+ { align: 'right' as const, header: 'Input', key: 'input' },+ { align: 'right' as const, header: 'Output', key: 'output' },+ { align: 'right' as const, header: ['Total', 'Tokens'], key: 'total' },+ { align: 'right' as const, header: 'Requests', key: 'requests' },+ { align: 'right' as const, header: ['Cost', '(USD)'], key: 'cost' },+ ];++ // Totals+ let sumInput = 0;+ let sumOutput = 0;+ let sumTotal = 0;+ let sumRequests = 0;+ let sumCost = 0;++ const rows: BoxTableRow[] = activeLogs.map((log: any) => {+ const records: any[] = log.records || [];++ // Aggregate tokens+ let inputTokens = 0;+ let outputTokens = 0;+ for (const r of records) {+ inputTokens += r.totalInputTokens || 0;+ outputTokens += r.totalOutputTokens || 0;+ }+ const totalTokens = log.totalTokens || inputTokens + outputTokens;+ const cost = log.totalSpend || 0;+ const requests = log.totalRequests || 0;++ sumInput += inputTokens;+ sumOutput += outputTokens;+ sumTotal += totalTokens;+ sumRequests += requests;+ sumCost += cost;++ // Unique models+ const modelSet = new Set<string>();+ for (const r of records) {+ if (r.model) modelSet.add(r.model);+ }+ const modelList = [...modelSet].sort().map((m) => `- ${m}`);++ return {+ cost: formatCost(cost),+ date: log.day || '',+ input: formatNumber(inputTokens),+ models: modelList.length > 0 ? modelList : ['-'],+ output: formatNumber(outputTokens),+ requests: formatNumber(requests),+ total: formatNumber(totalTokens),+ };+ });- // Build table columns- const columns = [- { align: 'left' as const, header: 'Date', key: 'date' },- { align: 'left' as const, header: 'Models', key: 'models' },- { align: 'right' as const, header: 'Input', key: 'input' },- { align: 'right' as const, header: 'Output', key: 'output' },- { align: 'right' as const, header: ['Total', 'Tokens'], key: 'total' },- { align: 'right' as const, header: 'Requests', key: 'requests' },- { align: 'right' as const, header: ['Cost', '(USD)'], key: 'cost' },- ];-- // Totals- let sumInput = 0;- let sumOutput = 0;- let sumTotal = 0;- let sumRequests = 0;- let sumCost = 0;-- const rows: BoxTableRow[] = activeLogs.map((log: any) => {- const records: any[] = log.records || [];-- // Aggregate tokens- let inputTokens = 0;- let outputTokens = 0;- for (const r of records) {- inputTokens += r.totalInputTokens || 0;- outputTokens += r.totalOutputTokens || 0;- }- const totalTokens = log.totalTokens || inputTokens + outputTokens;- const cost = log.totalSpend || 0;- const requests = log.totalRequests || 0;-- sumInput += inputTokens;- sumOutput += outputTokens;- sumTotal += totalTokens;- sumRequests += requests;- sumCost += cost;-- // Unique models- const modelSet = new Set<string>();- for (const r of records) {- if (r.model) modelSet.add(r.model);- }- const modelList = [...modelSet].sort().map((m) => `- ${m}`);-- return {- cost: formatCost(cost),- date: log.day || '',- input: formatNumber(inputTokens),- models: modelList.length > 0 ? modelList : ['-'],- output: formatNumber(outputTokens),- requests: formatNumber(requests),- total: formatNumber(totalTokens),- };- });-- // Total row- rows.push({- cost: pc.bold(formatCost(sumCost)),- date: pc.bold('Total'),- input: pc.bold(formatNumber(sumInput)),- models: '',- output: pc.bold(formatNumber(sumOutput)),- requests: pc.bold(formatNumber(sumRequests)),- total: pc.bold(formatNumber(sumTotal)),- });-- const monthLabel = options.month || new Date().toISOString().slice(0, 7);- const mode = options.daily ? 'Daily' : 'Monthly';- printBoxTable(columns, rows, `LobeHub Token Usage Report - ${mode} (${monthLabel})`);-- // Calendar heatmap - fetch past 12 months- const now = new Date();- const rangeStart = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate() + 1);- let yearLogs: any[];-- try {- // Try single-request endpoint first- yearLogs = await client.usage.findAndGroupByDateRange.query({- agentId: input.agentId,- endAt: now.toISOString().slice(0, 10),- startAt: rangeStart.toISOString().slice(0, 10),+ // Total row+ rows.push({+ cost: pc.bold(formatCost(sumCost)),+ date: pc.bold('Total'),+ input: pc.bold(formatNumber(sumInput)),+ models: '',+ output: pc.bold(formatNumber(sumOutput)),+ requests: pc.bold(formatNumber(sumRequests)),+ total: pc.bold(formatNumber(sumTotal)),});- } catch {- // Fallback: fetch each month concurrently- const monthKeys: string[] = [];- for (let i = 11; i >= 0; i--) {- const d = new Date(now.getFullYear(), now.getMonth() - i, 1);- monthKeys.push(d.toISOString().slice(0, 7));++ const monthLabel = options.month || new Date().toISOString().slice(0, 7);+ const mode = options.daily ? 'Daily' : 'Monthly';+ printBoxTable(columns, rows, `LobeHub Token Usage Report - ${mode} (${monthLabel})`);++ // Calendar heatmap - fetch past 12 months+ const now = new Date();+ const rangeStart = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate() + 1);+ let yearLogs: any[];++ try {+ // Try single-request endpoint first+ yearLogs = await client.usage.findAndGroupByDateRange.query({+ agentId: input.agentId,+ endAt: now.toISOString().slice(0, 10),+ startAt: rangeStart.toISOString().slice(0, 10),+ });+ } catch {+ // Fallback: fetch each month concurrently+ const monthKeys: string[] = [];+ for (let i = 11; i >= 0; i--) {+ const d = new Date(now.getFullYear(), now.getMonth() - i, 1);+ monthKeys.push(d.toISOString().slice(0, 7));+ }+ const results = await Promise.all(+ monthKeys.map((mo) =>+ client.usage.findAndGroupByDay.query({ agentId: input.agentId, mo }),+ ),+ );+ yearLogs = results.flat();}- const results = await Promise.all(- monthKeys.map((mo) => client.usage.findAndGroupByDay.query({ agentId: input.agentId, mo })),- );- yearLogs = results.flat();- }- const calendarData = (Array.isArray(yearLogs) ? yearLogs : [])- .filter((log: any) => log.day)- .map((log: any) => ({- day: log.day,- value: log.totalTokens || 0,- }));+ const calendarData = (Array.isArray(yearLogs) ? yearLogs : [])+ .filter((log: any) => log.day)+ .map((log: any) => ({+ day: log.day,+ value: log.totalTokens || 0,+ }));- const yearTotal = calendarData.reduce((acc: number, d: any) => acc + d.value, 0);+ const yearTotal = calendarData.reduce((acc: number, d: any) => acc + d.value, 0);- printCalendarHeatmap(calendarData, {- label: `Past 12 months: ${formatNumber(yearTotal)} tokens`,- title: 'Activity (past 12 months)',- });- });+ printCalendarHeatmap(calendarData, {+ label: `Past 12 months: ${formatNumber(yearTotal)} tokens`,+ title: 'Activity (past 12 months)',+ });+ },+ );}diff --git a/apps/server/src/routers/tools/market.test.ts b/apps/server/src/routers/tools/market.test.tsindex 0be933e69ef..6f448d3b60c 100644--- a/apps/server/src/routers/tools/market.test.ts+++ b/apps/server/src/routers/tools/market.test.ts@@ -64,7 +64,8 @@ describe('tools marketRouter', () => {workspaceId: 'workspace-1',} as any);mockPreprocessLhCommand.mockResolvedValue({- command: 'LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent view agt_1',+ command:+ 'lh() { LOBEHUB_WORKSPACE_ID=\'workspace-1\' npx -y @lobehub/cli "$@"; }\nlh agent view agt_1',isLhCommand: true,skipSkillLookup: true,});@@ -82,7 +83,8 @@ describe('tools marketRouter', () => {'workspace-1',);expect(mockSandboxCallTool).toHaveBeenCalledWith('runCommand', {- command: 'LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent view agt_1',+ command:+ 'lh() { LOBEHUB_WORKSPACE_ID=\'workspace-1\' npx -y @lobehub/cli "$@"; }\nlh agent view agt_1',});});diff --git a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.tsindex 93edf1e4362..d3fda0b1128 100644--- a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest';-import { preprocessLhCommand } from '../preprocessLhCommand';+import { buildDeviceLhEnv, isLhCommand, preprocessLhCommand } from '../preprocessLhCommand';const mockSignUserJWT = vi.hoisted(() => vi.fn().mockResolvedValue('mock-jwt-token'));@@ -16,7 +16,9 @@ vi.mock('@/utils/env', () => ({isDev: false,}));-const ENV_PREFIX = 'LOBEHUB_JWT=mock-jwt-token LOBEHUB_SERVER=https://app.lobehub.com';+const CREDS = "LOBEHUB_JWT='mock-jwt-token' LOBEHUB_SERVER='https://app.lobehub.com'";+/** The shim, with credentials scoped to the `npx` process rather than exported. */+const shim = (extraEnv = '') => `lh() { ${CREDS}${extraEnv} npx -y @lobehub/cli "$@"; }`;describe('preprocessLhCommand', () => {it('should return unchanged command for non-lh commands', async () => {@@ -27,61 +29,54 @@ describe('preprocessLhCommand', () => {expect(result.command).toBe('echo hello');});- it('should rewrite a single lh command', async () => {+ it('should prepend the auth shim and keep the command verbatim', async () => {const result = await preprocessLhCommand('lh topic list --json', 'user-1');expect(result.isLhCommand).toBe(true);expect(result.skipSkillLookup).toBe(true);- expect(result.command).toBe(`${ENV_PREFIX} npx -y @lobehub/cli topic list --json`);+ expect(result.command).toBe(`${shim()}\nlh topic list --json`);});it('should inject workspace scope for lh commands from workspace runs', async () => {const result = await preprocessLhCommand('lh agent view agt_123', 'user-1', 'workspace-1');expect(result.command).toBe(- `${ENV_PREFIX} LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent view agt_123`,+ `${shim(" LOBEHUB_WORKSPACE_ID='workspace-1'")}\nlh agent view agt_123`,);});- it('should rewrite all lh commands chained with &&', async () => {+ it('should emit the JWT once regardless of how many lh calls the script makes', async () => {const cmd = 'lh topic list --page 1 && lh topic list --page 2 && echo "done"';const result = await preprocessLhCommand(cmd, 'user-1');- expect(result.command).toBe(- `${ENV_PREFIX} npx -y @lobehub/cli topic list --page 1 && ${ENV_PREFIX} npx -y @lobehub/cli topic list --page 2 && echo "done"`,- );+ expect(result.command).toBe(`${shim()}\n${cmd}`);+ expect(result.command.match(/mock-jwt-token/g)).toHaveLength(1);});- it('should rewrite lh commands chained with ||', async () => {- const cmd = 'lh foo || lh bar';- const result = await preprocessLhCommand(cmd, 'user-1');-- expect(result.command).toBe(- `${ENV_PREFIX} npx -y @lobehub/cli foo || ${ENV_PREFIX} npx -y @lobehub/cli bar`,- );+ // Regression: the shim briefly used `export`, which put a full user auth+ // token in the environment of every command the model wrote — one+ // `echo $LOBEHUB_JWT` or `curl` away from exfiltration, and handed out even+ // to a script that merely mentions `lh` in quoted text, since detection is+ // deliberately permissive. Credentials must stay assignment-prefixed to the+ // `npx` process inside the function body.+ it('should keep credentials out of the parent shell environment', async () => {+ const result = await preprocessLhCommand('lh topic list && echo "$LOBEHUB_JWT"', 'user-1');++ expect(result.command).not.toContain('export ');++ const [shimLine] = result.command.split('\n');+ // The only occurrence of the token is inside the function body, prefixed to+ // `npx` — so it scopes to that one process and nothing else inherits it.+ expect(shimLine).toMatch(/^lh\(\) \{ .*LOBEHUB_JWT='mock-jwt-token'.* npx -y @lobehub\/cli/);+ expect(result.command.slice(shimLine.length)).not.toContain('mock-jwt-token');});- it('should rewrite lh commands chained with ;', async () => {- const cmd = 'lh foo; lh bar';- const result = await preprocessLhCommand(cmd, 'user-1');-- expect(result.command).toBe(- `${ENV_PREFIX} npx -y @lobehub/cli foo; ${ENV_PREFIX} npx -y @lobehub/cli bar`,- );- });+ it('should shell-escape values containing quotes', async () => {+ mockSignUserJWT.mockResolvedValueOnce("jwt-with-'quote");- it('should not replace lh inside other words', async () => {- const result = await preprocessLhCommand('echoalhough', 'user-1');+ const result = await preprocessLhCommand('lh topic list', 'user-1');- expect(result.isLhCommand).toBe(false);- expect(result.command).toBe('echoalhough');- });-- it('should handle bare lh command', async () => {- const result = await preprocessLhCommand('lh', 'user-1');-- expect(result.isLhCommand).toBe(true);- expect(result.command).toBe(`${ENV_PREFIX} npx -y @lobehub/cli`);+ expect(result.command).toContain(String.raw`LOBEHUB_JWT='jwt-with-'\''quote'`);});it('should return error when JWT signing fails', async () => {@@ -94,3 +89,78 @@ describe('preprocessLhCommand', () => {expect(result.command).toBe('lh topic list');});});++describe('isLhCommand', () => {+ // Every form below used to fall through the old+ // `/(?:^|&&|\|\||;)\s*lh(?:\s|$)/` pattern, leaving `lh` unresolved in the+ // sandbox. The multi-line one is the regression that broke self-editing:+ // "view yourself, then edit yourself" is naturally written as two lines.+ it.each([+ ['bare', 'lh'],+ ['leading whitespace', ' lh agent list'],+ ['after &&', 'cd /tmp && lh agent view agt_1'],+ ['after ||', 'lh agent view agt_1 || lh agent list'],+ ['after ;', 'lh a; lh b'],+ ['second line of a script', 'lh agent view agt_1 --json\nlh agent edit agt_1 -t x'],+ ['piped', 'lh agent view agt_1 --json | jq .title'],+ ['command substitution', 'echo $(lh agent view agt_1 --json)'],+ ['backticks', 'echo `lh agent list`'],+ ['subshell', '(lh agent view agt_1)'],+ ['brace group', '{ lh agent list; }'],+ ['loop body', 'for i in 1 2; do lh agent list; done'],+ ['if condition', 'if lh agent view agt_1; then echo ok; fi'],+ ['same-line case arm', 'case "$scope" in workspace) lh whoami ;; esac'],+ ['multiple case arms', 'case $x in a) lh agent list ;; b) lh topic list ;; esac'],+ ['inline env assignment', 'LOBEHUB_WORKSPACE_ID=ws lh agent list'],+ ['quoted inline assignment', 'FOO="a b" lh agent list'],+ // `!` and `time` are reserved words, so the shell still resolves `lh`+ // through the injected function — missing them left the command running as+ // a bare `lh` (not found in the sandbox, unscoped on a device).+ ['negated', '! lh whoami'],+ ['negated if condition', 'if ! lh whoami; then echo no; fi'],+ ['negated while condition', 'while ! lh agent list; do sleep 1; done'],+ ['negated after &&', 'cd /tmp && ! lh agent view agt_1'],+ ['timed', 'time lh agent list'],+ ['negated and timed', '! time lh agent list'],+ ['negated with inline assignment', '! FOO=1 lh agent list'],+ ])('detects %s', (_label, command) => {+ expect(isLhCommand(command)).toBe(true);+ });++ it.each([+ ['plain command', 'echo hello'],+ ['substring of a word', 'echoalhough'],+ ['npm script name', 'npm run lhtest'],+ ['a local script of the same name', './lh agent list'],+ ['a path segment', 'ls /opt/lh'],+ // `time` is matched as a whole word only.+ ['a word merely ending in time', 'notime lh'],+ ])('does not detect %s', (_label, command) => {+ expect(isLhCommand(command)).toBe(false);+ });+});++describe('buildDeviceLhEnv', () => {+ it('scopes the run to its workspace', () => {+ expect(buildDeviceLhEnv('ws-1')).toEqual({ LOBEHUB_WORKSPACE_ID: 'ws-1' });+ });++ it('never ships the caller JWT onto the device', () => {+ expect(buildDeviceLhEnv('ws-1')).not.toHaveProperty('LOBEHUB_JWT');+ });++ it('returns undefined for personal runs', () => {+ expect(buildDeviceLhEnv(undefined)).toBeUndefined();+ });++ // Regression: this used to be gated on `isLhCommand(command)`, so an `lh`+ // the command reached indirectly got no scope and silently fell back to the+ // device credentials' personal tenancy. The device merges env into the+ // spawned process, so setting it unconditionally is what covers these.+ it('scopes commands that reach lh indirectly, which no detector could match', () => {+ for (const command of ["bash -lc 'lh whoami'", 'make deploy', './sync.sh', 'npm run sync']) {+ expect(isLhCommand(command)).toBe(false);+ expect(buildDeviceLhEnv('ws-1')).toEqual({ LOBEHUB_WORKSPACE_ID: 'ws-1' });+ }+ });+});diff --git a/apps/server/src/services/toolExecution/preprocessLhCommand.ts b/apps/server/src/services/toolExecution/preprocessLhCommand.tsindex 8c81180e2d0..02f33dd3e4d 100644--- a/apps/server/src/services/toolExecution/preprocessLhCommand.ts+++ b/apps/server/src/services/toolExecution/preprocessLhCommand.ts@@ -15,21 +15,108 @@ export interface PreprocessResult {}/**- * Detect and preprocess `lh` CLI commands.- * - Replaces `lh` with `npx -y @lobehub/cli`- * - Injects LOBEHUB_JWT, LOBEHUB_SERVER, and optional workspace scope env vars- * - Signals caller to skip skill DB lookup+ * `lh` in shell **command position**. Matches at the start of the script or+ * right after a separator / opening construct, allowing inline `VAR=value`+ * assignments in between (`FOO=1 lh agent list`).+ *+ * Command-position openers covered: newline, `;`, `&` (also the second `&` of+ * `&&`), `|` (also `||`), `(` (also the `(` of `$(`), `)` (a `case` arm), a+ * backtick, `{`, and the compound-command keywords. That set is what makes+ * multi-line scripts, pipelines, command substitution, subshells, loops and+ * `case` statements resolve — the previous pattern only knew `^`, `&&`, `||`+ * and `;` on a single line, so everything after the first line of a `view` →+ * `edit` script fell through unhandled.+ *+ * Between the opener and `lh` the pattern also allows the `!` and `time`+ * prefixes (`if ! lh whoami; then …`, `time lh agent list`) and inline+ * `VAR=value` assignments. `!` and `time` are the only command prefixes worth+ * matching: they are shell reserved words, so the shell still resolves `lh`+ * through the injected function. Prefixes that fork an external command —+ * `env`, `nohup`, `xargs`, and POSIX `command` / `exec`, which bypass function+ * lookup by definition — could never see a shell function anyway, so matching+ * them would inject a shim that cannot help.+ *+ * This is a DETECTION-only heuristic: the command itself is never rewritten+ * (see `preprocessLhCommand`), so a false positive costs one harmless shim+ * while a false negative costs a broken `lh` invocation. Erring permissive is+ * therefore the right trade — e.g. `echo 'a && lh b'` matches even though the+ * `lh` is quoted text.+ */+const LH_COMMAND_PATTERN =+ /(?:^|[\n;&|()`{]|\b(?:do|then|else|if|elif|while|until)\b)[\t ]*(?:(?:!|\btime)[\t ]+)*(?:[A-Za-z_]\w*=(?:'[^']*'|"[^"]*"|[^\s'"&;|]*)[\t ]+)*lh(?=[\s;&|)]|$)/;++export const isLhCommand = (command: string): boolean => LH_COMMAND_PATTERN.test(command);++/**+ * Env overrides for a workspace run executing ON THE USER'S DEVICE rather than+ * in the sandbox.+ *+ * A device shell has its own `lh` and its own stored credentials, so nothing+ * needs rewriting there — but without `LOBEHUB_WORKSPACE_ID` the CLI resolves+ * to personal scope, and a workspace agent asked to edit itself silently reads+ * and writes the wrong tenancy instead of failing.+ *+ * Applied to EVERY command of a workspace run, deliberately not gated on+ * `isLhCommand`. The device merges this into the spawned process environment,+ * so every descendant inherits it — which is the only way to reach an `lh` the+ * command invokes indirectly: `bash -lc 'lh whoami'`, a shell script, a+ * Makefile target, an npm script. Command-position detection sees none of+ * those, and unlike the sandbox path there is nothing here worth gating: this+ * mints no credential, it exports a non-secret scope id that only the LobeHub+ * CLI reads, so setting it on a command that never calls `lh` costs nothing.+ *+ * `LOBEHUB_JWT` is deliberately NOT sent: on a personal device the stored+ * credentials already are the caller's, so it buys nothing, while a workspace+ * device belongs to another member and shipping the caller's token onto their+ * machine would be a real credential leak. Auth stays with the device; only the+ * scope travels. A device owner who is not a member of that workspace now gets+ * an explicit error rather than a silent personal-scope write.+ */+export const buildDeviceLhEnv = (+ workspaceId: string | undefined,+): Record<string, string> | undefined =>+ workspaceId ? { LOBEHUB_WORKSPACE_ID: workspaceId } : undefined;++/** POSIX single-quoting, safe for any value including quotes and newlines. */+const shellSingleQuote = (value: string): string => `'${value.replaceAll("'", String.raw`'\''`)}'`;++/**+ * Detect and prepare `lh` CLI commands for execution in the cloud sandbox.+ *+ * Instead of rewriting every `lh` occurrence (which can only ever cover the+ * shell forms the regex happens to know), the command is left **byte-identical**+ * and a one-line shim is prepended:+ *+ * ```sh+ * lh() { LOBEHUB_JWT='…' LOBEHUB_SERVER='…' LOBEHUB_WORKSPACE_ID='…' npx -y @lobehub/cli "$@"; }+ * <original command>+ * ```+ *+ * A POSIX shell function is visible to subshells and command substitution, so+ * this resolves `lh` in every form the model can write — pipelines, `$(lh …)`,+ * `for … do lh …`, and every line of a multi-line script — while emitting the+ * JWT exactly once instead of per occurrence.+ *+ * The credentials are assignment-prefixed to `npx` INSIDE the function rather+ * than `export`ed around the script. Exporting would put a full user auth token+ * in the environment of every command the model wrote, where any later `env`,+ * `echo $LOBEHUB_JWT`, `curl` or child process could read and exfiltrate it —+ * and since detection is deliberately permissive, a script that merely mentions+ * `lh` in quoted text would get one too. Prefixing an external command is+ * well-defined POSIX and scopes the value to that one `npx` process. Nothing is+ * lost: the shim is a shell function, so it was never visible to a child shell+ * process (`sh -c 'lh …'`) that an exported variable would have reached.+ *+ * `LOBEHUB_WORKSPACE_ID` is what keeps a workspace run's CLI calls in the+ * workspace: without it the CLI resolves to personal scope and a workspace+ * agent cannot even find itself.*/export const preprocessLhCommand = async (command: string,userId: string,workspaceId?: string,): Promise<PreprocessResult> => {- // Match `lh` at the start of the command or after shell operators (&&, ||, ;)- const lhPattern = /(?:^|&&|\|\||;)\s*lh(?:\s|$)/;- const isLhCommand = lhPattern.test(command);-- if (!isLhCommand) {+ if (!isLhCommand(command)) {return { command, isLhCommand: false, skipSkillLookup: false };}@@ -38,21 +125,22 @@ export const preprocessLhCommand = async (const serverUrl = isDev ? OFFICIAL_URL : appEnv.APP_URL;- const envParts = [`LOBEHUB_JWT=${jwt}`, `LOBEHUB_SERVER=${serverUrl}`];- if (workspaceId) envParts.push(`LOBEHUB_WORKSPACE_ID=${workspaceId}`);- const envPrefix = envParts.join(' ');+ const envAssignments = [+ `LOBEHUB_JWT=${shellSingleQuote(jwt)}`,+ `LOBEHUB_SERVER=${shellSingleQuote(serverUrl)}`,+ ...(workspaceId ? [`LOBEHUB_WORKSPACE_ID=${shellSingleQuote(workspaceId)}`] : []),+ ].join(' ');- // Replace `lh` in all sub-commands separated by &&, ||, or ;- const rewritten = command.replaceAll(- /(^|&&|\|\||;)(\s*)lh(\s|$)/g,- `$1$2${envPrefix} npx -y @lobehub/cli$3`,+ // Newline-separated (not `;`-separated) so a command whose first line is a+ // comment or a shebang cannot swallow the shim.+ const finalCommand = [`lh() { ${envAssignments} npx -y @lobehub/cli "$@"; }`, command].join(+ '\n',);- const finalCommand = rewritten;log(- 'Intercepted lh command for user %s, rewritten to: %s',+ 'Intercepted lh command for user %s (workspace %s), shim injected',userId,- finalCommand.replace(jwt, '<redacted>'),+ workspaceId ?? 'personal',);return { command: finalCommand, isLhCommand: true, skipSkillLookup: true };diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.tsnew file mode 100644index 00000000000..515d4c86fde--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts@@ -0,0 +1,139 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => {+ // A class instance, like the real `createSandboxService` returns — a spread+ // wrapper would silently drop these prototype methods.+ class FakeSandboxService {+ callTool = vi.fn();+ exportAndUploadFile = vi.fn();+ }++ return {+ createSandboxService: vi.fn(),+ FakeSandboxService,+ preprocessLhCommand: vi.fn(),+ sandboxService: new FakeSandboxService(),+ };+});++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(() => ({})),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn(() => ({})),+}));++vi.mock('@/server/services/sandbox', () => ({+ createSandboxService: mocks.createSandboxService,+}));++vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({+ isLhCommand: (command: string) => command.startsWith('lh'),+ preprocessLhCommand: mocks.preprocessLhCommand,+}));++const buildContext = (overrides: Record<string, unknown> = {}) =>+ ({+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ ...overrides,+ }) as never;++describe('cloudSandboxRuntime', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.createSandboxService.mockReturnValue(mocks.sandboxService);+ mocks.sandboxService.callTool.mockResolvedValue({+ result: { exitCode: 0, output: 'ok', stdout: 'ok', success: true },+ success: true,+ });+ mocks.preprocessLhCommand.mockImplementation(async (command: string) => ({+ command,+ isLhCommand: false,+ skipSkillLookup: false,+ }));+ });++ // The cloud-sandbox tool exposes its own `runCommand` alongside the skills+ // tool's, and nothing in either manifest tells the model they resolve `lh`+ // differently — so an `lh` command landing here used to hit a sandbox with no+ // CLI, no credentials and no workspace scope.+ it('preprocesses lh commands with the run workspace scope', async () => {+ mocks.preprocessLhCommand.mockResolvedValueOnce({+ command:+ 'lh() { LOBEHUB_WORKSPACE_ID=\'ws-42\' npx -y @lobehub/cli "$@"; }\nlh agent edit agt_1 -t x',+ isLhCommand: true,+ skipSkillLookup: true,+ });++ const { cloudSandboxRuntime } = await import('../cloudSandbox');+ const runtime = cloudSandboxRuntime.factory(buildContext({ workspaceId: 'ws-42' }));++ await runtime.runCommand({ command: 'lh agent edit agt_1 -t x', description: 'edit self' });++ expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(+ 'lh agent edit agt_1 -t x',+ 'user-1',+ 'ws-42',+ );+ expect(mocks.sandboxService.callTool).toHaveBeenCalledWith(+ 'runCommand',+ expect.objectContaining({+ command:+ 'lh() { LOBEHUB_WORKSPACE_ID=\'ws-42\' npx -y @lobehub/cli "$@"; }\nlh agent edit agt_1 -t x',+ }),+ );+ });++ it('leaves non-shell tools untouched', async () => {+ const { cloudSandboxRuntime } = await import('../cloudSandbox');+ const runtime = cloudSandboxRuntime.factory(buildContext());++ await runtime.executeCode({ code: 'print(1)', language: 'python' });++ expect(mocks.preprocessLhCommand).not.toHaveBeenCalled();+ expect(mocks.sandboxService.callTool).toHaveBeenCalledWith('executeCode', {+ code: 'print(1)',+ language: 'python',+ });+ });++ it('surfaces a preprocessing auth failure instead of running the raw command', async () => {+ mocks.preprocessLhCommand.mockResolvedValueOnce({+ command: 'lh agent list',+ error: 'Failed to authenticate for CLI execution',+ isLhCommand: true,+ skipSkillLookup: true,+ });++ const { cloudSandboxRuntime } = await import('../cloudSandbox');+ const runtime = cloudSandboxRuntime.factory(buildContext({ workspaceId: 'ws-42' }));++ const result = await runtime.runCommand({ command: 'lh agent list', description: 'list' });++ expect(mocks.sandboxService.callTool).not.toHaveBeenCalled();+ expect(result.state).toMatchObject({ success: false });+ });++ it('keeps delegating exportAndUploadFile through the wrapper', async () => {+ mocks.sandboxService.exportAndUploadFile.mockResolvedValue({+ filename: 'result.csv',+ success: true,+ url: 'https://files.example.com/result.csv',+ });++ const { cloudSandboxRuntime } = await import('../cloudSandbox');+ const runtime = cloudSandboxRuntime.factory(buildContext());++ await runtime.exportFile({ path: './out/result.csv' });++ expect(mocks.sandboxService.exportAndUploadFile).toHaveBeenCalledWith(+ './out/result.csv',+ 'result.csv',+ undefined,+ );+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.tsindex f78d978cc6d..4a3655b6ed7 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts@@ -316,4 +316,79 @@ describe('localSystemRuntime', () => {expect(parseArgs()).toEqual({ command: 'pwd' });});});++ // A device shell runs the user's own `lh` against their stored credentials,+ // which default to PERSONAL scope — so a workspace agent asking the CLI to+ // edit itself silently read and wrote the wrong tenancy.+ describe('lh workspace scope on device commands', () => {+ const parseArgs = () => JSON.parse(mockExecuteToolCall.mock.calls[0][1].arguments);++ const buildProxy = (context: Partial<ToolExecutionContext>) => {+ mockExecuteToolCall.mockResolvedValue({ content: '', success: true });+ return localSystemRuntime.factory({+ activeDeviceId: 'device-1',+ toolManifestMap: {},+ userId: 'user-1',+ ...context,+ });+ };++ it('injects the workspace scope into lh commands', async () => {+ const proxy = buildProxy({ workspaceId: 'ws-42' });+ await proxy[LocalSystemApiName.runCommand]({ command: 'lh agent edit agt_1 -t x' });++ expect(parseArgs().env).toEqual({ LOBEHUB_WORKSPACE_ID: 'ws-42' });+ });++ it('never sends the caller JWT to the device', async () => {+ const proxy = buildProxy({ workspaceId: 'ws-42' });+ await proxy[LocalSystemApiName.runCommand]({ command: 'lh agent list' });++ expect(parseArgs().env).not.toHaveProperty('LOBEHUB_JWT');+ });++ it('keeps the scope on a personal-scope device, which is addressed personally but still edits workspace content', async () => {+ const proxy = buildProxy({ activeDeviceScope: 'personal', workspaceId: 'ws-42' });+ await proxy[LocalSystemApiName.runCommand]({ command: 'lh agent edit agt_1 -t x' });++ // Gateway addressing drops the workspace (no `workspace:<id>` connection+ // for this device) — the CONTENT scope must not follow it down.+ expect(mockExecuteToolCall.mock.calls[0][0].workspaceId).toBeUndefined();+ expect(parseArgs().env).toEqual({ LOBEHUB_WORKSPACE_ID: 'ws-42' });+ });++ // Regression: injection used to be gated on detecting `lh` in command+ // position, so a command that reaches `lh` through a child shell, a script+ // or a Makefile got no scope and silently used the device credentials'+ // personal tenancy. The device merges env into the spawned process, so+ // every descendant inherits it — which is the only way to cover these.+ it.each([+ ['child shell', "bash -lc 'lh whoami'"],+ ['shell script', './sync.sh'],+ ['makefile target', 'make deploy'],+ ['npm script', 'npm run sync'],+ ])('scopes a workspace run invoking lh via a %s', async (_label, command) => {+ const proxy = buildProxy({ workspaceId: 'ws-42' });+ await proxy[LocalSystemApiName.runCommand]({ command });++ expect(parseArgs().env).toEqual({ LOBEHUB_WORKSPACE_ID: 'ws-42' });+ });++ it('does not inject in a personal run', async () => {+ const proxy = buildProxy({});+ await proxy[LocalSystemApiName.runCommand]({ command: 'lh agent list' });++ expect(parseArgs()).toEqual({ command: 'lh agent list' });+ });++ it('lets a model-supplied env win', async () => {+ const proxy = buildProxy({ workspaceId: 'ws-42' });+ await proxy[LocalSystemApiName.runCommand]({+ command: 'lh agent list',+ env: { LOBEHUB_WORKSPACE_ID: 'ws-explicit' },+ });++ expect(parseArgs().env).toEqual({ LOBEHUB_WORKSPACE_ID: 'ws-explicit' });+ });+ });});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.tsindex 9756528a187..d84081d1eb2 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => {};return {+ buildDeviceLhEnv: vi.fn(),checkHash: vi.fn(),createSandboxService: vi.fn(() => sandboxService),executeToolCall: vi.fn(),@@ -26,6 +27,7 @@ const mocks = vi.hoisted(() => {findAll: vi.fn(),findById: vi.fn(),findByName: vi.fn(),+ isLhCommand: vi.fn(),getAgentConfigById: vi.fn(),getAgentSkills: vi.fn(),getUserSettings: vi.fn(),@@ -33,6 +35,7 @@ const mocks = vi.hoisted(() => {prepareSkillDirectory: vi.fn(),preprocessLhCommand: vi.fn(),readResource: vi.fn(),+ resolveContentWorkspaceId: vi.fn(),resolveRunWorkspaceId: vi.fn(),sandboxService,};@@ -102,6 +105,8 @@ vi.mock('@/server/services/skill/resource', () => ({}));vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({+ buildDeviceLhEnv: mocks.buildDeviceLhEnv,+ isLhCommand: mocks.isLhCommand,preprocessLhCommand: mocks.preprocessLhCommand,}));@@ -113,6 +118,7 @@ vi.mock('@/server/services/deviceGateway', () => ({}));vi.mock('../resolveWorkspaceScope', () => ({+ resolveContentWorkspaceId: mocks.resolveContentWorkspaceId,resolveRunWorkspaceId: mocks.resolveRunWorkspaceId,}));@@ -138,11 +144,17 @@ describe('skillsRuntime', () => {});mocks.getAgentSkills.mockResolvedValue([]);mocks.getUserSettings.mockResolvedValue({ market: { accessToken: 'market-token' } });- mocks.preprocessLhCommand.mockResolvedValue({- command: 'echo ok',+ // Pass-through by default: the runtime now routes both runCommand and+ // execScript through preprocessing, so a fixed return value would rewrite+ // every command in the suite.+ mocks.preprocessLhCommand.mockImplementation(async (command: string) => ({+ command,isLhCommand: false,skipSkillLookup: false,- });+ }));+ mocks.isLhCommand.mockReturnValue(false);+ mocks.buildDeviceLhEnv.mockReturnValue(undefined);+ mocks.resolveContentWorkspaceId.mockResolvedValue(undefined);mocks.resolveRunWorkspaceId.mockResolvedValue(undefined);mocks.sandboxService.callTool.mockResolvedValue({result: {@@ -244,7 +256,8 @@ describe('skillsRuntime', () => {isLhCommand: true,skipSkillLookup: true,});- mocks.resolveRunWorkspaceId.mockResolvedValueOnce('workspace-1');+ mocks.isLhCommand.mockReturnValue(true);+ mocks.resolveContentWorkspaceId.mockResolvedValueOnce('workspace-1');const { skillsRuntime } = await import('../skills');const runtime = await skillsRuntime.factory({@@ -257,7 +270,7 @@ describe('skillsRuntime', () => {await runtime.runCommand({ command: 'lh agent edit agt_123 -s "new prompt"' });- expect(mocks.resolveRunWorkspaceId).toHaveBeenCalledWith(+ expect(mocks.resolveContentWorkspaceId).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-1' }),);expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(@@ -267,6 +280,105 @@ describe('skillsRuntime', () => {);});+ // The client-side executor (routers/tools/market.ts) has always preprocessed+ // execScript too; on Cloud, where gateway mode routes through this runtime+ // instead, `lh` inside execScript reached the sandbox raw — no CLI, no+ // credentials, no workspace scope.+ it('preprocesses lh commands passed to execScript, not just runCommand', async () => {+ mocks.preprocessLhCommand.mockResolvedValueOnce({+ command:+ 'lh() { LOBEHUB_WORKSPACE_ID=\'workspace-1\' npx -y @lobehub/cli "$@"; }\nlh agent edit agt_123 -t x',+ isLhCommand: true,+ skipSkillLookup: true,+ });++ const { skillsRuntime } = await import('../skills');+ const runtime = await skillsRuntime.factory({+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });++ await runtime.execScript({+ activatedSkills: [],+ command: 'lh agent edit agt_123 -t x',+ description: 'Edit myself',+ });++ expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(+ 'lh agent edit agt_123 -t x',+ 'user-1',+ 'workspace-1',+ );+ expect(mocks.sandboxService.callTool).toHaveBeenCalledWith(+ 'execScript',+ expect.objectContaining({+ command:+ 'lh() { LOBEHUB_WORKSPACE_ID=\'workspace-1\' npx -y @lobehub/cli "$@"; }\nlh agent edit agt_123 -t x',+ }),+ );+ });++ it('surfaces a preprocessing auth failure from execScript instead of running raw', async () => {+ mocks.preprocessLhCommand.mockResolvedValueOnce({+ command: 'lh agent list',+ error: 'Failed to authenticate for CLI execution',+ isLhCommand: true,+ skipSkillLookup: true,+ });++ const { skillsRuntime } = await import('../skills');+ const runtime = await skillsRuntime.factory({+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });++ const result = await runtime.execScript({+ activatedSkills: [],+ command: 'lh agent list',+ description: 'List agents',+ });++ expect(mocks.sandboxService.callTool).not.toHaveBeenCalled();+ expect(result.state).toMatchObject({ success: false });+ });++ it('scopes device-routed execScript lh commands to the run workspace', async () => {+ mocks.buildDeviceLhEnv.mockReturnValue({ LOBEHUB_WORKSPACE_ID: 'workspace-1' });+ mocks.resolveContentWorkspaceId.mockResolvedValue('workspace-1');+ mocks.executeToolCall.mockResolvedValue({+ state: { exitCode: 0, stdout: 'ok', success: true },+ success: true,+ });++ const { skillsRuntime } = await import('../skills');+ const runtime = await skillsRuntime.factory({+ activeDeviceId: 'device-1',+ agentId: 'agent-1',+ operationId: 'op-1',+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });++ await runtime.execScript({+ activatedSkills: [],+ command: 'lh agent edit agt_123 -t x',+ description: 'Edit myself',+ });++ const [, toolCall] = mocks.executeToolCall.mock.calls.at(-1)!;+ expect(JSON.parse(toolCall.arguments).env).toEqual({ LOBEHUB_WORKSPACE_ID: 'workspace-1' });+ // Auth stays with the device — the caller's token must not travel there.+ expect(JSON.parse(toolCall.arguments).env).not.toHaveProperty('LOBEHUB_JWT');+ });+describe('disabled skill enforcement', () => {it('refuses to activate a DB skill the agent has disabled, even though it exists', async () => {mocks.getAgentConfigById.mockResolvedValue({diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.tsindex af0eb23ca53..11a3cd04e20 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts@@ -1,12 +1,61 @@-import { CloudSandboxIdentifier } from '@lobechat/builtin-tool-cloud-sandbox';+import { CloudSandboxIdentifier, type ISandboxService } from '@lobechat/builtin-tool-cloud-sandbox';import { CloudSandboxExecutionRuntime } from '@lobechat/builtin-tool-cloud-sandbox/executionRuntime';import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';import { createSandboxService } from '@/server/services/sandbox';+import {+ isLhCommand,+ preprocessLhCommand,+} from '@/server/services/toolExecution/preprocessLhCommand';+import { resolveContentWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';+/** Sandbox tools whose `command` param can carry an `lh` invocation. */+const SHELL_TOOL_NAMES = new Set(['execScript', 'runCommand']);++/**+ * Wrap a sandbox service so shell tools get the same `lh` prelude as the skills+ * runtime and the client-side executor (`routers/tools/market.ts`).+ *+ * Without this the sandbox has no `lh` binary and no credentials at all, so a+ * model that reaches for the cloud-sandbox shell instead of the skills one —+ * both expose a `runCommand` and nothing tells the model they differ — gets a+ * bare `lh: not found` for a command the platform advertises.+ */+const withLhPreprocessing = (+ service: ISandboxService,+ resolve: {+ userId: string;+ workspaceId: () => Promise<string | undefined>;+ },+): ISandboxService => ({+ // Delegated explicitly rather than spread: `createSandboxService` returns a+ // class instance, whose methods live on the prototype and would be dropped.+ callTool: async (toolName, params) => {+ const command = params?.command;+ if (!SHELL_TOOL_NAMES.has(toolName) || typeof command !== 'string') {+ return service.callTool(toolName, params);+ }++ const workspaceId = isLhCommand(command) ? await resolve.workspaceId() : undefined;+ const result = await preprocessLhCommand(command, resolve.userId, workspaceId);++ if (result.error) {+ return {+ error: { message: result.error, name: 'AuthError' },+ result: null,+ success: false,+ };+ }++ return service.callTool(toolName, { ...params, command: result.command });+ },+ exportAndUploadFile: (path, filename, options) =>+ service.exportAndUploadFile(path, filename, options),+});+/*** CloudSandbox Server Runtime* Per-request runtime (needs topicId, userId)@@ -31,7 +80,14 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {userId: context.userId,});- return new CloudSandboxExecutionRuntime(sandboxService);+ let workspaceIdPromise: Promise<string | undefined> | undefined;++ return new CloudSandboxExecutionRuntime(+ withLhPreprocessing(sandboxService, {+ userId: context.userId,+ workspaceId: () => (workspaceIdPromise ??= resolveContentWorkspaceId(context)),+ }),+ );},identifier: CloudSandboxIdentifier,};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.tsindex 6969e283927..8c373555f4e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts@@ -5,8 +5,9 @@ import {} from '@lobechat/builtin-tool-local-system';import { deviceGateway } from '@/server/services/deviceGateway';+import { buildDeviceLhEnv } from '@/server/services/toolExecution/preprocessLhCommand';-import { resolveRunWorkspaceId } from './resolveWorkspaceScope';+import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';/**@@ -58,6 +59,14 @@ export const localSystemRuntime: ServerRuntimeRegistration = {let workspaceIdPromise: Promise<string | undefined> | undefined;const getDeviceWorkspaceId = () => (workspaceIdPromise ??= resolveRunWorkspaceId(context));+ // Content scope — which workspace's data a command operates on — is a+ // different question from which gateway pool addresses the device, so it+ // must NOT reuse `getDeviceWorkspaceId` (that one intentionally returns+ // undefined for a personal-scope device).+ let contentWorkspaceIdPromise: Promise<string | undefined> | undefined;+ const getContentWorkspaceId = () =>+ (contentWorkspaceIdPromise ??= resolveContentWorkspaceId(context));+const proxy: Record<string, (args: any) => Promise<any>> = {};for (const api of LocalSystemManifest.api) {@@ -69,11 +78,22 @@ export const localSystemRuntime: ServerRuntimeRegistration = {// packaged desktop instead of the user's actual workspace).const scopeValue: unknown = workingDirArg ? args?.[workingDirArg] : undefined;const needsInjection = scopeValue == null || scopeValue === '.';- const finalArgs =+ let finalArgs =workingDirArg && context.workingDirectory && needsInjection? { ...args, [workingDirArg]: context.workingDirectory }: args;+ // A device shell has its own `lh`, so nothing is rewritten — but the+ // CLI would resolve to the device credentials' PERSONAL scope, which is+ // how a workspace agent ends up unable to find (or edit) itself. Set on+ // every command, so an `lh` reached indirectly (`bash -lc 'lh …'`, a+ // script, a Makefile) inherits the scope too. The model's own `env`+ // wins: it may be deliberately overriding the scope.+ if (api.name === LocalSystemApiName.runCommand && typeof finalArgs?.command === 'string') {+ const lhEnv = buildDeviceLhEnv(await getContentWorkspaceId());+ if (lhEnv) finalArgs = { ...finalArgs, env: { ...lhEnv, ...finalArgs.env } };+ }+return deviceGateway.executeToolCall({deviceId: context.activeDeviceId!,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.ts b/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.tsindex ef1056b75b5..f4727ec275b 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.ts@@ -13,28 +13,24 @@ type DeviceScopeContext = Pick<>;/**- * The workspace scope a device tool call should run under: the run-scoped+ * The workspace whose CONTENT this run reads and writes: the run-scoped* `context.workspaceId`, or — when that was lost on the way to this tool call* (some dispatch / resume paths do not thread it through to* `ToolExecutionContext`) — the running agent's durable `workspace_id`.*- * Both device runtimes resolve scope through this single path so a run stays- * consistent: `remote-device` lists/activates the workspace device, and the- * `local-system` filesystem/shell calls that follow route to the same- * `workspace:<id>` gateway pool instead of silently falling back to the personal- * pool. Unscoped lookup by id on purpose: the run already authorized this agent,- * we only read which workspace it belongs to.+ * Unscoped lookup by id on purpose: the run already authorized this agent, we+ * only read which workspace it belongs to.*- * EXCEPTION: a run whose active device is PERSONAL-scope (a workspace agent- * routed to the caller's own machine via the per-user `local` override,- *) must be addressed through the personal `(userId, deviceId)`- * pool — that device has no connection under the `workspace:<id>` principal,- * so a workspace-addressed call would simply miss it.+ * Deliberately free of the personal-device exception in `resolveRunWorkspaceId`+ * below — that exception is about which gateway pool to ADDRESS, which is a+ * different question from which workspace's data a call operates on. A+ * workspace agent routed to the caller's own machine still edits workspace+ * content, so `lh` running there must carry `LOBEHUB_WORKSPACE_ID` or the CLI+ * silently resolves to personal scope and the agent cannot even find itself.*/-export const resolveRunWorkspaceId = async (- context: DeviceScopeContext,+export const resolveContentWorkspaceId = async (+ context: Pick<DeviceScopeContext, 'agentId' | 'serverDB' | 'workspaceId'>,): Promise<string | undefined> => {- if (context.activeDeviceScope === 'personal') return undefined;if (context.workspaceId) return context.workspaceId;const { agentId, serverDB } = context;@@ -52,3 +48,26 @@ export const resolveRunWorkspaceId = async (return undefined;}};++/**+ * The workspace principal a device tool call should be ADDRESSED under.+ *+ * Both device runtimes resolve scope through this single path so a run stays+ * consistent: `remote-device` lists/activates the workspace device, and the+ * `local-system` filesystem/shell calls that follow route to the same+ * `workspace:<id>` gateway pool instead of silently falling back to the personal+ * pool.+ *+ * EXCEPTION: a run whose active device is PERSONAL-scope (a workspace agent+ * routed to the caller's own machine via the per-user `local` override,+ *) must be addressed through the personal `(userId, deviceId)`+ * pool — that device has no connection under the `workspace:<id>` principal,+ * so a workspace-addressed call would simply miss it.+ */+export const resolveRunWorkspaceId = async (+ context: DeviceScopeContext,+): Promise<string | undefined> => {+ if (context.activeDeviceScope === 'personal') return undefined;++ return resolveContentWorkspaceId(context);+};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.tsindex 201aec71f6e..14e2d9c5650 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts@@ -35,9 +35,13 @@ import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';import { createSandboxService, normalizeSandboxCommandResult } from '@/server/services/sandbox';import { SkillResourceService } from '@/server/services/skill/resource';-import { preprocessLhCommand } from '@/server/services/toolExecution/preprocessLhCommand';+import {+ buildDeviceLhEnv,+ isLhCommand,+ preprocessLhCommand,+} from '@/server/services/toolExecution/preprocessLhCommand';-import { resolveRunWorkspaceId } from './resolveWorkspaceScope';+import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';const log = debug('lobe-server:skills-runtime');@@ -95,10 +99,6 @@ const LEGACY_DEVICE_CLIENT = Symbol('legacy-device-client');const LEGACY_FALLBACK_NOTE ="Note: the user's device client is outdated and does not support on-device skill execution, so this command ran in the cloud sandbox instead. Tell the user to update their LobeHub app to run skills on their device.";-const LH_COMMAND_PATTERN = /(?:^|&&|\|\||;)\s*lh(?:\s|$)/;--const isLhCommand = (command: string) => LH_COMMAND_PATTERN.test(command);-class SkillServerRuntimeService implements SkillRuntimeService {private agentId?: string;private resourceService: SkillResourceService;@@ -162,13 +162,31 @@ class SkillServerRuntimeService implements SkillRuntimeService {};private resolveWorkspaceId = async (): Promise<string | undefined> => {- return resolveRunWorkspaceId({+ return resolveContentWorkspaceId({agentId: this.agentId,serverDB: this.serverDB,workspaceId: this.workspaceId,});};+ /**+ * Rewrite an `lh` command for sandbox execution: prepend the auth ++ * workspace-scope prelude so the CLI runs as this user, against this run's+ * workspace. Shared by `runCommand` and `execScript` — the model picks+ * between them by manifest wording alone (`execScript` is the one described+ * as "run the CLI commands a skill's instructions tell you to"), so a hole in+ * either one is a hole in the whole `lh` surface.+ */+ private preprocessSandboxCommand = async (+ command: string,+ ): Promise<{ command: string; error?: string }> => {+ const workspaceId =+ this.workspaceId ?? (isLhCommand(command) ? await this.resolveWorkspaceId() : undefined);+ const result = await preprocessLhCommand(command, this.userId, workspaceId);++ return { command: result.command, error: result.error };+ };+readResource = async (id: string, path: string): Promise<SkillResourceContent> => {const skill = await this.skillModel.findById(id);if (!skill) throw new Error(`Skill not found: ${id}`);@@ -196,11 +214,8 @@ class SkillServerRuntimeService implements SkillRuntimeService {throw new Error('topicId is required for runCommand');}- // Preprocess lh commands: rewrite to npx @lobehub/cli + inject auth env vars- const workspaceId =- this.workspaceId ??- (isLhCommand(options.command) ? await this.resolveWorkspaceId() : undefined);- const lhResult = await preprocessLhCommand(options.command, this.userId, workspaceId);+ // Preprocess lh commands: resolve `lh` to the CLI + inject auth/workspace env+ const lhResult = await this.preprocessSandboxCommand(options.command);if (lhResult.error) {return {executionEnv: 'sandbox',@@ -393,6 +408,10 @@ class SkillServerRuntimeService implements SkillRuntimeService {}const cwd = runDir ?? device.workingDirectory;+ // Content scope, NOT the gateway-addressing scope resolved above: a+ // workspace agent routed to the caller's own machine is still editing+ // workspace content.+ const deviceLhEnv = buildDeviceLhEnv(await this.resolveWorkspaceId());const response = await deviceGateway.executeToolCall({deviceId: device.deviceId,@@ -408,6 +427,9 @@ class SkillServerRuntimeService implements SkillRuntimeService {arguments: JSON.stringify({command,...(cwd && { cwd }),+ // Keep `lh` on the device in this run's workspace instead of the+ // device credentials' personal scope.+ ...(deviceLhEnv && { env: deviceLhEnv }),...(device.executionTimeoutMs && { timeout: device.executionTimeoutMs }),}),identifier: LocalSystemIdentifier,@@ -505,10 +527,24 @@ class SkillServerRuntimeService implements SkillRuntimeService {throw new Error('topicId is required for execScript');}+ // Same `lh` handling as runCommand — the client-side executor+ // (`routers/tools/market.ts`) has always preprocessed both tools, and+ // gateway runs must not behave differently.+ const lhResult = await this.preprocessSandboxCommand(command);+ if (lhResult.error) {+ return {+ executionEnv: 'sandbox',+ exitCode: 1,+ output: '',+ stderr: lhResult.error,+ success: false,+ };+ }+try {const enhancedParams: Record<string, unknown> = {activatedSkills,- command,+ command: lhResult.command,description,};diff --git a/locales/ar/common.json b/locales/ar/common.jsonindex ac895425605..80c2b7c90a3 100644--- a/locales/ar/common.json+++ b/locales/ar/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "تحديث متوفر","upgradeVersion.newVersion": "تحديث متوفر: {{version}}","upgradeVersion.serverVersion": "الخادم: {{version}}",+ "userPanel.accountSetting": "إعدادات الحساب","userPanel.anonymousNickName": "مستخدم مجهول","userPanel.billing": "إدارة الفوترة","userPanel.cloud": "تشغيل {{name}}",diff --git a/locales/bg-BG/common.json b/locales/bg-BG/common.jsonindex 7b8028250c5..17133b6cca3 100644--- a/locales/bg-BG/common.json+++ b/locales/bg-BG/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Налична е актуализация","upgradeVersion.newVersion": "Налична е актуализация: {{version}}","upgradeVersion.serverVersion": "Сървър: {{version}}",+ "userPanel.accountSetting": "Настройки на акаунта","userPanel.anonymousNickName": "Анонимен потребител","userPanel.billing": "Управление на плащания","userPanel.cloud": "Стартирай {{name}}",diff --git a/locales/de-DE/common.json b/locales/de-DE/common.jsonindex 496203957d1..6eede00e9b9 100644--- a/locales/de-DE/common.json+++ b/locales/de-DE/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Aktualisierung verfügbar","upgradeVersion.newVersion": "Neue Version verfügbar: {{version}}","upgradeVersion.serverVersion": "Server: {{version}}",+ "userPanel.accountSetting": "Kontoeinstellungen","userPanel.anonymousNickName": "Anonymer Benutzer","userPanel.billing": "Abrechnungsverwaltung","userPanel.cloud": "{{name}} starten",diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex 6d6f8bfbb18..159e3b89f0b 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -520,6 +520,7 @@"upgradeVersion.hasNew": "Update available","upgradeVersion.newVersion": "Update available: {{version}}","upgradeVersion.serverVersion": "Server: {{version}}",+ "userPanel.accountSetting": "Account Settings","userPanel.anonymousNickName": "Anonymous User","userPanel.billing": "Billing","userPanel.cloud": "Launch {{name}}",diff --git a/locales/es-ES/common.json b/locales/es-ES/common.jsonindex 874dd948274..dcd1e2df466 100644--- a/locales/es-ES/common.json+++ b/locales/es-ES/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Actualización disponible","upgradeVersion.newVersion": "Actualización disponible: {{version}}","upgradeVersion.serverVersion": "Servidor: {{version}}",+ "userPanel.accountSetting": "Configuración de la cuenta","userPanel.anonymousNickName": "Usuario anónimo","userPanel.billing": "Gestión de facturación","userPanel.cloud": "Lanzar {{name}}",diff --git a/locales/fa-IR/common.json b/locales/fa-IR/common.jsonindex efbd6883cdd..264aef8effc 100644--- a/locales/fa-IR/common.json+++ b/locales/fa-IR/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "بهروزرسانی در دسترس است","upgradeVersion.newVersion": "بهروزرسانی در دسترس: {{version}}","upgradeVersion.serverVersion": "سرور: {{version}}",+ "userPanel.accountSetting": "تنظیمات حساب","userPanel.anonymousNickName": "کاربر ناشناس","userPanel.billing": "مدیریت صورتحساب","userPanel.cloud": "اجرای {{name}}",diff --git a/locales/fr-FR/common.json b/locales/fr-FR/common.jsonindex bfe98d76460..1055d6d5e64 100644--- a/locales/fr-FR/common.json+++ b/locales/fr-FR/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Mise à jour disponible","upgradeVersion.newVersion": "Mise à jour disponible : {{version}}","upgradeVersion.serverVersion": "Serveur : {{version}}",+ "userPanel.accountSetting": "Paramètres du compte","userPanel.anonymousNickName": "Utilisateur anonyme","userPanel.billing": "Gestion de la facturation","userPanel.cloud": "Lancer {{name}}",diff --git a/locales/it-IT/common.json b/locales/it-IT/common.jsonindex 3b99c4af4b3..eff9ab6f6a8 100644--- a/locales/it-IT/common.json+++ b/locales/it-IT/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Aggiornamento disponibile","upgradeVersion.newVersion": "Aggiornamento disponibile: {{version}}","upgradeVersion.serverVersion": "Server: {{version}}",+ "userPanel.accountSetting": "Impostazioni dell'account","userPanel.anonymousNickName": "Utente anonimo","userPanel.billing": "Gestione fatturazione","userPanel.cloud": "Avvia {{name}}",diff --git a/locales/ja-JP/common.json b/locales/ja-JP/common.jsonindex 3bdd121505a..27ad3ca8811 100644--- a/locales/ja-JP/common.json+++ b/locales/ja-JP/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "アップデートがあります","upgradeVersion.newVersion": "利用可能なアップデート:{{version}}","upgradeVersion.serverVersion": "サーバー:{{version}}",+ "userPanel.accountSetting": "アカウント設定","userPanel.anonymousNickName": "匿名ユーザー","userPanel.billing": "請求管理","userPanel.cloud": "{{name}} を体験",diff --git a/locales/ko-KR/common.json b/locales/ko-KR/common.jsonindex 862c435ed00..a6abe2af2ca 100644--- a/locales/ko-KR/common.json+++ b/locales/ko-KR/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "업데이트 가능","upgradeVersion.newVersion": "사용 가능한 업데이트: {{version}}","upgradeVersion.serverVersion": "서버: {{version}}",+ "userPanel.accountSetting": "계정 설정","userPanel.anonymousNickName": "익명 사용자","userPanel.billing": "청구 관리","userPanel.cloud": "{{name}} 체험하기",diff --git a/locales/nl-NL/common.json b/locales/nl-NL/common.jsonindex 6811543d1e5..63794141734 100644--- a/locales/nl-NL/common.json+++ b/locales/nl-NL/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Update beschikbaar","upgradeVersion.newVersion": "Update beschikbaar: {{version}}","upgradeVersion.serverVersion": "Server: {{version}}",+ "userPanel.accountSetting": "Accountinstellingen","userPanel.anonymousNickName": "Anonieme gebruiker","userPanel.billing": "Facturatiebeheer","userPanel.cloud": "Start {{name}}",diff --git a/locales/pl-PL/common.json b/locales/pl-PL/common.jsonindex f5ccf299c22..b1b4aa47a71 100644--- a/locales/pl-PL/common.json+++ b/locales/pl-PL/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Dostępna aktualizacja","upgradeVersion.newVersion": "Dostępna aktualizacja: {{version}}","upgradeVersion.serverVersion": "Serwer: {{version}}",+ "userPanel.accountSetting": "Ustawienia konta","userPanel.anonymousNickName": "Użytkownik anonimowy","userPanel.billing": "Zarządzanie płatnościami","userPanel.cloud": "Uruchom {{name}}",diff --git a/locales/pt-BR/common.json b/locales/pt-BR/common.jsonindex aca0093650b..aa63eb46847 100644--- a/locales/pt-BR/common.json+++ b/locales/pt-BR/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Atualização disponível","upgradeVersion.newVersion": "Atualização disponível: {{version}}","upgradeVersion.serverVersion": "Servidor: {{version}}",+ "userPanel.accountSetting": "Configurações da Conta","userPanel.anonymousNickName": "Usuário Anônimo","userPanel.billing": "Gerenciamento de Pagamentos","userPanel.cloud": "Iniciar {{name}}",diff --git a/locales/ru-RU/common.json b/locales/ru-RU/common.jsonindex 1f2f98470e1..aa269b69d5d 100644--- a/locales/ru-RU/common.json+++ b/locales/ru-RU/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Доступно обновление","upgradeVersion.newVersion": "Доступно обновление: {{version}}","upgradeVersion.serverVersion": "Сервер: {{version}}",+ "userPanel.accountSetting": "Настройки аккаунта","userPanel.anonymousNickName": "Анонимный пользователь","userPanel.billing": "Управление оплатой","userPanel.cloud": "Запустить {{name}}",diff --git a/locales/tr-TR/common.json b/locales/tr-TR/common.jsonindex 830a7f7a52b..ee16f778adc 100644--- a/locales/tr-TR/common.json+++ b/locales/tr-TR/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Güncelleme mevcut","upgradeVersion.newVersion": "Yeni sürüm mevcut: {{version}}","upgradeVersion.serverVersion": "Sunucu: {{version}}",+ "userPanel.accountSetting": "Hesap Ayarları","userPanel.anonymousNickName": "Anonim Kullanıcı","userPanel.billing": "Faturalandırma Yönetimi","userPanel.cloud": "{{name}}'i Başlat",diff --git a/locales/vi-VN/common.json b/locales/vi-VN/common.jsonindex 9268537a18f..744e82f1155 100644--- a/locales/vi-VN/common.json+++ b/locales/vi-VN/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "Có bản cập nhật mới","upgradeVersion.newVersion": "Có bản cập nhật mới: {{version}}","upgradeVersion.serverVersion": "Máy chủ: {{version}}",+ "userPanel.accountSetting": "Cài đặt tài khoản","userPanel.anonymousNickName": "Người dùng ẩn danh","userPanel.billing": "Quản lý thanh toán","userPanel.cloud": "Khởi chạy {{name}}",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 6998e6c0aab..6b3d2c75589 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -520,6 +520,7 @@"upgradeVersion.hasNew": "有可用更新","upgradeVersion.newVersion": "可用更新版本:{{version}}","upgradeVersion.serverVersion": "服务端:{{version}}",+ "userPanel.accountSetting": "账户设置","userPanel.anonymousNickName": "匿名用户","userPanel.billing": "账单","userPanel.cloud": "体验 {{name}}",diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.jsonindex 00ad1fe1cea..57526720a5f 100644--- a/locales/zh-TW/common.json+++ b/locales/zh-TW/common.json@@ -523,6 +523,7 @@"upgradeVersion.hasNew": "有可用的更新","upgradeVersion.newVersion": "有可用的更新:{{version}}","upgradeVersion.serverVersion": "伺服器版本:{{version}}",+ "userPanel.accountSetting": "帳戶設定","userPanel.anonymousNickName": "匿名使用者","userPanel.billing": "帳單管理","userPanel.cloud": "體驗 {{name}}",diff --git a/packages/builtin-skills/src/lobehub/references/agent.ts b/packages/builtin-skills/src/lobehub/references/agent.tsindex 6b4d91132f9..c781aa35e6d 100644--- a/packages/builtin-skills/src/lobehub/references/agent.ts+++ b/packages/builtin-skills/src/lobehub/references/agent.ts@@ -7,17 +7,40 @@ Manage agents (AI assistants with custom configurations).- \`lh agent list [-L <limit>] [-k <keyword>]\` - List agents- \`lh agent view [agentId] [-s <slug>]\` - View agent configuration- \`lh agent create -t <title> [-d <description>] [-m <model>] [-p <provider>] [-s <systemRole>]\` - Create agent-- \`lh agent edit [agentId] [-t <title>] [-d <description>] [-m <model>] [-s <systemRole>]\` - Update agent+- \`lh agent edit [agentId] [-t <title>] [-d <description>] [-m <model>] [-s <systemRole>] [--config-file <path>] [--json]\` - Update agent- \`lh agent delete <agentId> [--yes]\` - Delete agent- \`lh agent duplicate <agentId> [-t <title>]\` - Duplicate agent- \`lh agent run -a <agentId> -p <prompt> [-t <topicId>] [--replay]\` - Run agent with a prompt- \`lh agent status <operationId> [--history]\` - Check agent operation status+## Editing your own configuration++You can edit yourself: pass your own agent id (already given to you in the+identity table) to \`lh agent edit\`.++Fields without a dedicated flag (\`openingMessage\`, \`openingQuestions\`, \`tags\`,+\`avatar\`, \`backgroundColor\`, \`params\`, \`chatConfig\`, …) go through+\`--config-file\`, which is deep-merged into the existing config — omitted keys+are kept:++\`\`\`bash+echo '{"openingMessage":"Hi! Ask me about deploys.","tags":["devops"]}' > /tmp/cfg.json+lh agent edit <agentId> --config-file /tmp/cfg.json --json+\`\`\`++Identity fields (\`id\`, \`slug\`, \`userId\`, \`workspaceId\`, \`visibility\`) are+rejected by the server — use the dedicated commands for those.++Add \`--json\` to get the updated agent back, so you can confirm the change+actually landed instead of assuming it did.+## Tips- Use \`--slug\` to reference agents by slug instead of ID- \`lh agent run --replay\` replays the full conversation output- \`lh agent status --history\` shows operation execution history+- Commands run in the same workspace as you. \`lh whoami\` prints that scope —+ check it first if an agent, topic or file you expect to exist reports "not found"`;export default content;diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex 0c64c431be7..6ef7b976e4b 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -615,6 +615,7 @@ export default {'upgradeVersion.hasNew': 'Update available','upgradeVersion.newVersion': 'Update available: {{version}}','upgradeVersion.serverVersion': 'Server: {{version}}',+ 'userPanel.accountSetting': 'Account Settings','userPanel.anonymousNickName': 'Anonymous User','userPanel.billing': 'Billing','userPanel.cloud': 'Launch {{name}}',diff --git a/src/business/client/features/User/UserPanelAccountSection.tsx b/src/business/client/features/User/UserPanelAccountSection.tsxnew file mode 100644index 00000000000..b95ba1ff517--- /dev/null+++ b/src/business/client/features/User/UserPanelAccountSection.tsx@@ -0,0 +1,16 @@+import { memo } from 'react';++export interface UserPanelAccountSectionProps {+ /** Called right before navigating away, so the host popover can close itself. */+ onNavigate?: () => void;+}++/**+ * Bottom slot of the user panel, below the sign-out menu. The community build+ * has no secondary account surface to link to, so it renders nothing.+ */+const UserPanelAccountSection = memo<UserPanelAccountSectionProps>(() => null);++UserPanelAccountSection.displayName = 'UserPanelAccountSection';++export default UserPanelAccountSection;diff --git a/src/features/User/UserPanel/PanelContent.tsx b/src/features/User/UserPanel/PanelContent.tsxindex 9bb06939265..b4847d95b45 100644--- a/src/features/User/UserPanel/PanelContent.tsx+++ b/src/features/User/UserPanel/PanelContent.tsx@@ -2,6 +2,7 @@ import { Flexbox } from '@lobehub/ui';import { type FC } from 'react';import BusinessPanelContent from '@/business/client/features/User/BusinessPanelContent';+import UserPanelAccountSection from '@/business/client/features/User/UserPanelAccountSection';import UserPanelStatistics from '@/business/client/features/User/UserPanelStatistics';import UserPanelWorkspaceSection from '@/business/client/features/User/UserPanelWorkspaceSection';import Menu, { type MenuProps } from '@/components/Menu';@@ -70,6 +71,8 @@ const PanelContent: FC<{ closePopover: () => void }> = ({ closePopover }) => {)}<Menu items={[...(mainItems ?? []), ...(logoutItems ?? [])]} onClick={handleMenuClick} />++ <UserPanelAccountSection onNavigate={closePopover} /></Flexbox>);};