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.

πŸ› fix(agent): preserve workspace scope for lh agent edits (#16930)

AmAzing-e3c2e97dcf36
diff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.ts
index 330857ed342..ae826ea0f34 100644
--- a/apps/cli/src/api/client.ts
+++ b/apps/cli/src/api/client.ts
@@ -8,6 +8,7 @@ import { getValidToken } from '../auth/refresh';
import { CLI_API_KEY_ENV } from '../constants/auth';
import { resolveServerUrl } from '../settings';
import { log } from '../utils/logger';
+import { resolveWorkspaceId, withWorkspaceHeader } from './workspace';
export type TrpcClient = ReturnType<typeof createTRPCClient<LambdaRouter>>;
export type ToolsTrpcClient = ReturnType<typeof createTRPCClient<ToolsRouter>>;
@@ -16,7 +17,7 @@ const PERSONAL_KEY = '__personal__';
const _clients = new Map<string, TrpcClient>();
let _toolsClient: ToolsTrpcClient | undefined;
-async function getAuthAndServer() {
+async function getAuthAndServer(): Promise<{ headers: Record<string, string>; serverUrl: string }> {
// LOBEHUB_JWT + LOBEHUB_SERVER env vars (used by server-side sandbox execution)
const envJwt = process.env.LOBEHUB_JWT;
if (envJwt) {
@@ -54,21 +55,6 @@ async function getAuthAndServer() {
};
}
-/**
- * Resolve the workspace scope for outbound tRPC calls.
- *
- * Precedence: explicit caller arg β†’ `LOBEHUB_WORKSPACE_ID` env (inherited
- * from a workspace-dispatched parent process, e.g. openclaw spawned by the
- * device's `runHeteroTask`) β†’ personal mode. Without this, agentNotify
- * callbacks on workspace topics would resolve through personal-mode
- * TopicModel and 404.
- */
-function resolveWorkspaceId(explicit?: string): string | undefined {
- if (explicit) return explicit;
- const fromEnv = process.env.LOBEHUB_WORKSPACE_ID;
- return fromEnv && fromEnv.length > 0 ? fromEnv : undefined;
-}
-
export async function getTrpcClient(workspaceId?: string): Promise<TrpcClient> {
const wsId = resolveWorkspaceId(workspaceId);
const cacheKey = wsId ?? PERSONAL_KEY;
@@ -79,7 +65,7 @@ export async function getTrpcClient(workspaceId?: string): Promise<TrpcClient> {
const client = createTRPCClient<LambdaRouter>({
links: [
httpLink({
- headers: wsId ? { ...headers, 'X-Workspace-Id': wsId } : headers,
+ headers: withWorkspaceHeader(headers, wsId),
transformer: superjson,
url: `${serverUrl}/trpc/lambda`,
}),
@@ -108,11 +94,16 @@ export function createLambdaClient(
): TrpcClient {
const headers: Record<string, string> = {
...(auth.tokenType === 'apiKey' ? { 'X-API-Key': auth.token } : { 'Oidc-Auth': auth.token }),
- ...(workspaceId ? { 'X-Workspace-Id': workspaceId } : {}),
};
return createTRPCClient<LambdaRouter>({
- links: [httpLink({ headers, transformer: superjson, url: `${auth.serverUrl}/trpc/lambda` })],
+ links: [
+ httpLink({
+ headers: workspaceId ? { ...headers, 'X-Workspace-Id': workspaceId } : headers,
+ transformer: superjson,
+ url: `${auth.serverUrl}/trpc/lambda`,
+ }),
+ ],
});
}
diff --git a/apps/cli/src/api/http.test.ts b/apps/cli/src/api/http.test.ts
new file mode 100644
index 00000000000..2d475447b6b
--- /dev/null
+++ b/apps/cli/src/api/http.test.ts
@@ -0,0 +1,82 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mockGetValidToken = vi.hoisted(() => vi.fn());
+const mockResolveServerUrl = vi.hoisted(() => vi.fn(() => 'https://app.lobehub.com'));
+
+vi.mock('../auth/refresh', () => ({
+ getValidToken: mockGetValidToken,
+}));
+
+vi.mock('../settings', () => ({
+ resolveServerUrl: mockResolveServerUrl,
+}));
+
+vi.mock('../utils/logger', () => ({
+ log: { error: vi.fn() },
+}));
+
+describe('api/http auth helpers', () => {
+ const originalJwt = process.env.LOBEHUB_JWT;
+ const originalWorkspaceId = process.env.LOBEHUB_WORKSPACE_ID;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ delete process.env.LOBEHUB_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;
+ });
+
+ it('should use env JWT and workspace scope for webapi auth', async () => {
+ process.env.LOBEHUB_JWT = 'env-jwt';
+ process.env.LOBEHUB_WORKSPACE_ID = 'workspace-1';
+
+ const { getAuthInfo } = await import('./http');
+ const result = await getAuthInfo();
+
+ expect(result).toEqual({
+ accessToken: 'env-jwt',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Oidc-Auth': 'env-jwt',
+ 'X-Workspace-Id': 'workspace-1',
+ },
+ serverUrl: 'https://app.lobehub.com',
+ });
+ expect(mockGetValidToken).not.toHaveBeenCalled();
+ });
+
+ it('should add workspace scope when using stored OIDC credentials for webapi auth', async () => {
+ process.env.LOBEHUB_WORKSPACE_ID = 'workspace-1';
+ mockGetValidToken.mockResolvedValue({
+ credentials: { accessToken: 'stored-jwt' },
+ });
+
+ const { getAuthInfo } = await import('./http');
+ const result = await getAuthInfo();
+
+ expect(result.headers).toMatchObject({
+ 'Oidc-Auth': 'stored-jwt',
+ 'X-Workspace-Id': 'workspace-1',
+ });
+ });
+
+ it('should add workspace scope to agent stream auth headers', async () => {
+ process.env.LOBEHUB_JWT = 'env-jwt';
+ process.env.LOBEHUB_WORKSPACE_ID = 'workspace-1';
+
+ const { getAgentStreamAuthInfo } = await import('./http');
+ const result = await getAgentStreamAuthInfo();
+
+ expect(result.headers).toEqual({
+ 'Oidc-Auth': 'env-jwt',
+ 'X-Workspace-Id': 'workspace-1',
+ });
+ });
+});
diff --git a/apps/cli/src/api/http.ts b/apps/cli/src/api/http.ts
index 35637aef365..76920520241 100644
--- a/apps/cli/src/api/http.ts
+++ b/apps/cli/src/api/http.ts
@@ -2,6 +2,7 @@ import { getValidToken } from '../auth/refresh';
import { CLI_API_KEY_ENV } from '../constants/auth';
import { resolveServerUrl } from '../settings';
import { log } from '../utils/logger';
+import { withWorkspaceHeader } from './workspace';
export interface AuthInfo {
accessToken: string;
@@ -10,7 +11,23 @@ export interface AuthInfo {
serverUrl: string;
}
-export async function getAuthInfo(): Promise<AuthInfo> {
+export async function getAuthInfo(workspaceId?: string): Promise<AuthInfo> {
+ const serverUrl = resolveServerUrl();
+ const envJwt = process.env.LOBEHUB_JWT;
+ if (envJwt) {
+ return {
+ accessToken: envJwt,
+ headers: withWorkspaceHeader(
+ {
+ 'Content-Type': 'application/json',
+ 'Oidc-Auth': envJwt,
+ },
+ workspaceId,
+ ),
+ serverUrl,
+ };
+ }
+
const result = await getValidToken();
if (!result) {
if (process.env[CLI_API_KEY_ENV]) {
@@ -25,14 +42,16 @@ export async function getAuthInfo(): Promise<AuthInfo> {
}
const accessToken = result!.credentials.accessToken;
- const serverUrl = resolveServerUrl();
return {
accessToken,
- headers: {
- 'Content-Type': 'application/json',
- 'Oidc-Auth': accessToken,
- },
+ headers: withWorkspaceHeader(
+ {
+ 'Content-Type': 'application/json',
+ 'Oidc-Auth': accessToken,
+ },
+ workspaceId,
+ ),
serverUrl,
};
}
@@ -55,13 +74,13 @@ export interface AgentStreamAuthInfo {
tokenType: AgentStreamTokenType;
}
-export async function getAgentStreamAuthInfo(): Promise<AgentStreamAuthInfo> {
+export async function getAgentStreamAuthInfo(workspaceId?: string): Promise<AgentStreamAuthInfo> {
const serverUrl = resolveServerUrl();
const envJwt = process.env.LOBEHUB_JWT;
if (envJwt) {
return {
- headers: { 'Oidc-Auth': envJwt },
+ headers: withWorkspaceHeader({ 'Oidc-Auth': envJwt }, workspaceId),
serverUrl,
token: envJwt,
tokenType: 'jwt',
@@ -71,7 +90,7 @@ export async function getAgentStreamAuthInfo(): Promise<AgentStreamAuthInfo> {
const envApiKey = process.env[CLI_API_KEY_ENV];
if (envApiKey) {
return {
- headers: { 'X-API-Key': envApiKey },
+ headers: withWorkspaceHeader({ 'X-API-Key': envApiKey }, workspaceId),
serverUrl,
token: envApiKey,
tokenType: 'apiKey',
@@ -92,7 +111,7 @@ export async function getAgentStreamAuthInfo(): Promise<AgentStreamAuthInfo> {
}
return {
- headers: { 'Oidc-Auth': result.credentials.accessToken },
+ headers: withWorkspaceHeader({ 'Oidc-Auth': result.credentials.accessToken }, workspaceId),
serverUrl,
token: result.credentials.accessToken,
tokenType: 'jwt',
diff --git a/apps/cli/src/api/workspace.ts b/apps/cli/src/api/workspace.ts
new file mode 100644
index 00000000000..492f2502aff
--- /dev/null
+++ b/apps/cli/src/api/workspace.ts
@@ -0,0 +1,20 @@
+export const WORKSPACE_ID_HEADER = 'X-Workspace-Id';
+
+/**
+ * Resolve the workspace scope for outbound API calls.
+ *
+ * Precedence: explicit caller arg -> `LOBEHUB_WORKSPACE_ID` env -> personal mode.
+ */
+export function resolveWorkspaceId(explicit?: string): string | undefined {
+ if (explicit) return explicit;
+ const fromEnv = process.env.LOBEHUB_WORKSPACE_ID;
+ return fromEnv && fromEnv.length > 0 ? fromEnv : undefined;
+}
+
+export function withWorkspaceHeader(
+ headers: Record<string, string>,
+ workspaceId?: string,
+): Record<string, string> {
+ const resolvedWorkspaceId = resolveWorkspaceId(workspaceId);
+ return resolvedWorkspaceId ? { ...headers, [WORKSPACE_ID_HEADER]: resolvedWorkspaceId } : headers;
+}
diff --git a/apps/server/src/routers/tools/market.test.ts b/apps/server/src/routers/tools/market.test.ts
index 04967e7b2d4..0be933e69ef 100644
--- a/apps/server/src/routers/tools/market.test.ts
+++ b/apps/server/src/routers/tools/market.test.ts
@@ -3,6 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { marketRouter } from './market';
+const mockPreprocessLhCommand = vi.hoisted(() => vi.fn());
+const mockSandboxCallTool = vi.hoisted(() => vi.fn());
+const mockCreateSandboxService = vi.hoisted(() =>
+ vi.fn(() => ({
+ callTool: mockSandboxCallTool,
+ })),
+);
const mockMarketSDK = vi.hoisted(() => ({
skills: {
callTool: vi.fn(),
@@ -29,6 +36,18 @@ vi.mock('@/libs/trpc/lambda/middleware/marketSDK', () => ({
requireMarketAuth: vi.fn((opts: any) => opts.next({ ctx: opts.ctx })),
}));
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn(() => ({})),
+}));
+
+vi.mock('@/server/services/sandbox', () => ({
+ createSandboxService: mockCreateSandboxService,
+}));
+
+vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({
+ preprocessLhCommand: mockPreprocessLhCommand,
+}));
+
vi.mock('debug', () => ({
default: vi.fn(() => vi.fn()),
}));
@@ -38,6 +57,35 @@ describe('tools marketRouter', () => {
vi.clearAllMocks();
});
+ it('should pass workspace scope when preprocessing sandbox lh commands', async () => {
+ const caller = marketRouter.createCaller({
+ serverDB: {},
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ } as any);
+ mockPreprocessLhCommand.mockResolvedValue({
+ command: 'LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent view agt_1',
+ isLhCommand: true,
+ skipSkillLookup: true,
+ });
+ mockSandboxCallTool.mockResolvedValue({ result: { ok: true }, success: true });
+
+ await caller.execInSandbox({
+ params: { command: 'lh agent view agt_1' },
+ toolName: 'runCommand',
+ topicId: 'topic-1',
+ });
+
+ expect(mockPreprocessLhCommand).toHaveBeenCalledWith(
+ 'lh agent view agt_1',
+ 'user-1',
+ 'workspace-1',
+ );
+ expect(mockSandboxCallTool).toHaveBeenCalledWith('runCommand', {
+ command: 'LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent view agt_1',
+ });
+ });
+
it('should fall back to static tools when live discovery fails', async () => {
const caller = marketRouter.createCaller({ userId: 'user-1' } as any);
mockMarketSDK.skills.listLiveTools.mockRejectedValue(new Error('Live discovery failed'));
diff --git a/apps/server/src/routers/tools/market.ts b/apps/server/src/routers/tools/market.ts
index 8f1975674cd..89a9dc7ce21 100644
--- a/apps/server/src/routers/tools/market.ts
+++ b/apps/server/src/routers/tools/market.ts
@@ -192,7 +192,11 @@ const execInSandboxHandler = async ({
// Preprocess lh commands: rewrite to npx @lobehub/cli + inject auth env vars
if ((toolName === 'execScript' || toolName === 'runCommand') && params.command) {
- const lhResult = await preprocessLhCommand(params.command, userId);
+ const lhResult = await preprocessLhCommand(
+ params.command,
+ userId,
+ ctx.workspaceId ?? undefined,
+ );
if (lhResult.error) {
return {
diff --git a/apps/server/src/services/agent/index.test.ts b/apps/server/src/services/agent/index.test.ts
index 76bf36ac7cc..a8e61004e25 100644
--- a/apps/server/src/services/agent/index.test.ts
+++ b/apps/server/src/services/agent/index.test.ts
@@ -651,4 +651,25 @@ describe('AgentService', () => {
});
});
});
+
+ describe('updateAgentConfig', () => {
+ it('should throw when the updated agent cannot be read back', async () => {
+ const mockAgentModel = {
+ getAgentConfigById: vi.fn().mockResolvedValue(null),
+ updateConfig: vi.fn().mockResolvedValue(undefined),
+ };
+
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (parseAgentConfig as any).mockReturnValue({});
+
+ const newService = new AgentService(mockDb, mockUserId);
+
+ await expect(
+ newService.updateAgentConfig('missing-agent', { systemRole: 'new prompt' }),
+ ).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ message: 'Agent not found',
+ });
+ });
+ });
});
diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.ts
index 51b4f70d4e7..a43eee45db2 100644
--- a/apps/server/src/services/agent/index.ts
+++ b/apps/server/src/services/agent/index.ts
@@ -4,6 +4,7 @@ import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';
import { type LobeChatDatabase } from '@lobechat/database';
import { type AgentItem, type LobeAgentConfig } from '@lobechat/types';
import { cleanObject, merge } from '@lobechat/utils';
+import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { type PartialDeep } from 'type-fest';
@@ -232,6 +233,7 @@ export class AgentService {
// 2. Query and return updated data (with default config merged)
const agent = await this.getAgentConfigById(agentId);
+ if (!agent) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
return { agent: agent as any, success: true };
}
diff --git a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts
index ddba8cc76f7..93edf1e4362 100644
--- a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts
@@ -35,6 +35,14 @@ describe('preprocessLhCommand', () => {
expect(result.command).toBe(`${ENV_PREFIX} npx -y @lobehub/cli 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`,
+ );
+ });
+
it('should rewrite all lh commands chained with &&', async () => {
const cmd = 'lh topic list --page 1 && lh topic list --page 2 && echo "done"';
const result = await preprocessLhCommand(cmd, 'user-1');
diff --git a/apps/server/src/services/toolExecution/preprocessLhCommand.ts b/apps/server/src/services/toolExecution/preprocessLhCommand.ts
index 59c0656aed5..a76ef06a585 100644
--- a/apps/server/src/services/toolExecution/preprocessLhCommand.ts
+++ b/apps/server/src/services/toolExecution/preprocessLhCommand.ts
@@ -16,12 +16,13 @@ export interface PreprocessResult {
/**
* Detect and preprocess `lh` CLI commands.
* - Replaces `lh` with `npx -y @lobehub/cli`
- * - Injects LOBEHUB_JWT and LOBEHUB_SERVER env vars
+ * - Injects LOBEHUB_JWT, LOBEHUB_SERVER, and optional workspace scope env vars
* - Signals caller to skip skill DB lookup
*/
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|$)/;
@@ -36,7 +37,9 @@ export const preprocessLhCommand = async (
const serverUrl = isDev ? 'https://app.lobehub.com' : appEnv.APP_URL;
- const envPrefix = `LOBEHUB_JWT=${jwt} LOBEHUB_SERVER=${serverUrl}`;
+ const envParts = [`LOBEHUB_JWT=${jwt}`, `LOBEHUB_SERVER=${serverUrl}`];
+ if (workspaceId) envParts.push(`LOBEHUB_WORKSPACE_ID=${workspaceId}`);
+ const envPrefix = envParts.join(' ');
// Replace `lh` in all sub-commands separated by &&, ||, or ;
const rewritten = command.replaceAll(
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
index ad50390ba31..9756528a187 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
@@ -31,7 +31,9 @@ const mocks = vi.hoisted(() => {
getUserSettings: vi.fn(),
marketService: {},
prepareSkillDirectory: vi.fn(),
+ preprocessLhCommand: vi.fn(),
readResource: vi.fn(),
+ resolveRunWorkspaceId: vi.fn(),
sandboxService,
};
});
@@ -99,6 +101,10 @@ vi.mock('@/server/services/skill/resource', () => ({
})),
}));
+vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({
+ preprocessLhCommand: mocks.preprocessLhCommand,
+}));
+
vi.mock('@/server/services/deviceGateway', () => ({
deviceGateway: {
executeToolCall: mocks.executeToolCall,
@@ -107,7 +113,7 @@ vi.mock('@/server/services/deviceGateway', () => ({
}));
vi.mock('../resolveWorkspaceScope', () => ({
- resolveRunWorkspaceId: vi.fn(async () => undefined),
+ resolveRunWorkspaceId: mocks.resolveRunWorkspaceId,
}));
describe('skillsRuntime', () => {
@@ -132,6 +138,12 @@ describe('skillsRuntime', () => {
});
mocks.getAgentSkills.mockResolvedValue([]);
mocks.getUserSettings.mockResolvedValue({ market: { accessToken: 'market-token' } });
+ mocks.preprocessLhCommand.mockResolvedValue({
+ command: 'echo ok',
+ isLhCommand: false,
+ skipSkillLookup: false,
+ });
+ mocks.resolveRunWorkspaceId.mockResolvedValue(undefined);
mocks.sandboxService.callTool.mockResolvedValue({
result: {
exitCode: 0,
@@ -198,6 +210,63 @@ describe('skillsRuntime', () => {
expect(result.state).toMatchObject({ executionEnv: 'sandbox' });
});
+ it('passes workspace scope when preprocessing sandbox lh commands', async () => {
+ mocks.preprocessLhCommand.mockResolvedValueOnce({
+ command: 'LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent edit agt_123',
+ 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.runCommand({ command: 'lh agent edit agt_123 -s "new prompt"' });
+
+ expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(
+ 'lh agent edit agt_123 -s "new prompt"',
+ 'user-1',
+ 'workspace-1',
+ );
+ expect(mocks.sandboxService.callTool).toHaveBeenCalledWith('runCommand', {
+ command: 'LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent edit agt_123',
+ });
+ });
+
+ it('recovers workspace scope for sandbox lh commands when context lost it', async () => {
+ mocks.preprocessLhCommand.mockResolvedValueOnce({
+ command: 'LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent edit agt_123',
+ isLhCommand: true,
+ skipSkillLookup: true,
+ });
+ mocks.resolveRunWorkspaceId.mockResolvedValueOnce('workspace-1');
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ agentId: 'agent-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ await runtime.runCommand({ command: 'lh agent edit agt_123 -s "new prompt"' });
+
+ expect(mocks.resolveRunWorkspaceId).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1' }),
+ );
+ expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(
+ 'lh agent edit agt_123 -s "new prompt"',
+ 'user-1',
+ 'workspace-1',
+ );
+ });
+
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/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index 6bdbb59b494..201aec71f6e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -95,7 +95,12 @@ 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;
private skillModel: AgentSkillModel;
private marketService: MarketService;
@@ -104,10 +109,12 @@ class SkillServerRuntimeService implements SkillRuntimeService {
private serverDB: LobeChatDatabase;
private topicId?: string;
private userId: string;
+ private workspaceId?: string;
private device?: SkillDeviceExecution;
private disabledSkillIds: Set<string>;
constructor(options: {
+ agentId?: string;
device?: SkillDeviceExecution;
/**
* Identifiers the agent has explicitly disabled (`agents.plugins` tri-state)
@@ -124,7 +131,9 @@ class SkillServerRuntimeService implements SkillRuntimeService {
skillModel: AgentSkillModel;
topicId?: string;
userId: string;
+ workspaceId?: string;
}) {
+ this.agentId = options.agentId;
this.skillModel = options.skillModel;
this.resourceService = options.resourceService;
this.marketService = options.marketService;
@@ -133,6 +142,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
this.serverDB = options.serverDB;
this.topicId = options.topicId;
this.userId = options.userId;
+ this.workspaceId = options.workspaceId;
this.device = options.device;
this.disabledSkillIds = options.disabledSkillIds ?? new Set();
}
@@ -151,6 +161,14 @@ class SkillServerRuntimeService implements SkillRuntimeService {
return skill && this.disabledSkillIds.has(skill.identifier) ? undefined : skill;
};
+ private resolveWorkspaceId = async (): Promise<string | undefined> => {
+ return resolveRunWorkspaceId({
+ agentId: this.agentId,
+ serverDB: this.serverDB,
+ workspaceId: this.workspaceId,
+ });
+ };
+
readResource = async (id: string, path: string): Promise<SkillResourceContent> => {
const skill = await this.skillModel.findById(id);
if (!skill) throw new Error(`Skill not found: ${id}`);
@@ -179,7 +197,10 @@ class SkillServerRuntimeService implements SkillRuntimeService {
}
// Preprocess lh commands: rewrite to npx @lobehub/cli + inject auth env vars
- const lhResult = await preprocessLhCommand(options.command, this.userId);
+ const workspaceId =
+ this.workspaceId ??
+ (isLhCommand(options.command) ? await this.resolveWorkspaceId() : undefined);
+ const lhResult = await preprocessLhCommand(options.command, this.userId, workspaceId);
if (lhResult.error) {
return {
executionEnv: 'sandbox',
@@ -650,6 +671,7 @@ export const skillsRuntime: ServerRuntimeRegistration = {
: undefined;
const service = new SkillServerRuntimeService({
+ agentId: context.agentId,
device,
disabledSkillIds,
fileModel,
@@ -660,6 +682,7 @@ export const skillsRuntime: ServerRuntimeRegistration = {
skillModel,
topicId: context.topicId,
userId: context.userId,
+ workspaceId: context.workspaceId,
});
// Surface this agent's skill-bundle documents as `BuiltinSkill`-shaped