Skip to content

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

✨ feat(ai-agent): inject composer- and CLI-selected skills on server runs (#20961)

Nekofdb3b97aa0f6
diff --git a/.agents/skills/cli/references/agent.md b/.agents/skills/cli/references/agent.md
index 38a256df2cd..0358ab2a46f 100644
--- a/.agents/skills/cli/references/agent.md
+++ b/.agents/skills/cli/references/agent.md
@@ -116,22 +116,24 @@ Start an agent execution. Streams over the agent gateway WebSocket by default, o
`--sse`.
```bash
-lh agent run [-a <id>] [-s <slug>] [-p <text>] [-t <id>] [--no-auto-start] [--device <target>] [--no-headless] [--json] [-v] [--replay <file>] [--sse]
+lh agent run [-a <id>] [-s <slug>] [-p <text>] [-t <id>] [--no-auto-start] [--device <target>] [--no-headless] [--tool <id>]... [--skill <id>]... [--json] [-v] [--replay <file>] [--sse]
```
-| Option | Description |
-| --------------------- | -------------------------------------------------------------------------------------- |
-| `-a, --agent-id <id>` | Agent ID to run |
-| `-s, --slug <slug>` | Agent slug (alternative to ID) |
-| `-p, --prompt <text>` | User prompt |
-| `-t, --topic-id <id>` | Reuse existing topic |
-| `--no-auto-start` | Don't auto-start the agent |
-| `--device <target>` | Target device ID, or `local` for the current connected device |
-| `--no-headless` | Wait for human approval on tool calls instead of auto-running them (default: headless) |
-| `--json` | Output full JSON event stream |
-| `-v, --verbose` | Show detailed tool call info |
-| `--replay <file>` | Replay events from saved JSON file (offline) |
-| `--sse` | Force SSE stream instead of the WebSocket gateway |
+| Option | Description |
+| --------------------- | ----------------------------------------------------------------------------------------- |
+| `-a, --agent-id <id>` | Agent ID to run |
+| `-s, --slug <slug>` | Agent slug (alternative to ID) |
+| `-p, --prompt <text>` | User prompt |
+| `-t, --topic-id <id>` | Reuse existing topic |
+| `--no-auto-start` | Don't auto-start the agent |
+| `--device <target>` | Target device ID, or `local` for the current connected device |
+| `--no-headless` | Wait for human approval on tool calls instead of auto-running them (default: headless) |
+| `--tool <id>` | Enable a tool for this run on top of the agent's own, like an @-mention (repeatable) |
+| `--skill <id>` | Load a skill for this run and the rest of its topic, like picking it in chat (repeatable) |
+| `--json` | Output full JSON event stream |
+| `-v, --verbose` | Show detailed tool call info |
+| `--replay <file>` | Replay events from saved JSON file (offline) |
+| `--sse` | Force SSE stream instead of the WebSocket gateway |
### Streaming Behavior
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index 69c1892bf8f..3283dbc18a7 100644
--- a/apps/cli/src/commands/agent.ts
+++ b/apps/cli/src/commands/agent.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { AgentGraphSchema } from '@lobechat/types/agent/graph';
@@ -6,20 +5,11 @@ import { type Command, InvalidArgumentError } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
-import { getAgentStreamAuthInfo } from '../api/http';
-import { resolveAgentGatewayUrl } from '../settings';
-import type { AgentRunOutcome } from '../utils/agentRunOutcome';
-import { AGENT_RUN_EXIT_CODES, colorStatus, readOperationStatus } from '../utils/agentRunOutcome';
-import {
- replayAgentEvents,
- streamAgentEvents,
- streamAgentEventsViaWebSocket,
-} from '../utils/agentStream';
-import { resolveLocalDeviceId } from '../utils/device';
+import { colorStatus, readOperationStatus } from '../utils/agentRunOutcome';
import { confirm, outputJson, printTable, truncate } from '../utils/format';
-import { log, setVerbose } from '../utils/logger';
+import { log } from '../utils/logger';
import { resolveAgentId } from './agent/resolveAgentId';
-import { pollAgentRunStatus, probeRunOutcome, RUN_POLL_INTERVAL_MS } from './agent/runStatus';
+import { registerAgentRunCommand } from './agent/run';
import { registerAgentSpaceFsCommand } from './agent/spaceFs';
import { resolveAppUrlBuilder } from './task/url';
@@ -367,231 +357,7 @@ export function registerAgentCommand(program: Command) {
// ── run ──────────────────────────────────────────────
- agent
- .command('run')
- .description('Run an agent with a prompt')
- .option('-a, --agent-id <id>', 'Agent ID')
- .option('-s, --slug <slug>', 'Agent slug')
- .option('-p, --prompt <text>', 'User prompt')
- .option('-t, --topic-id <id>', 'Reuse an existing topic')
- .option('--no-auto-start', 'Do not auto-start the agent')
- .option(
- '--device <target>',
- 'Target device ID, or use "local" for the current connected device',
- )
- .option(
- '--no-headless',
- "Disable headless mode: tool calls that need approval park the run for a human (default: headless β€” tools auto-run, matching the CLI's non-interactive nature). The CLI does not wait for that approval; it returns with exit code 2 and the run continues once it is answered in LobeHub",
- )
- .option('--json', 'Output full JSON event stream')
- .option('--detach', 'Start the operation and return its IDs without waiting for events')
- .option('-v, --verbose', 'Show detailed tool call info')
- .option('--replay <file>', 'Replay events from a saved JSON file (offline)')
- .option('--sse', 'Force SSE stream instead of WebSocket gateway')
- .option(
- '--timeout <seconds>',
- 'Stop waiting after this many seconds (exit code 3; the run keeps going server-side). Default: wait as long as the server reports the run active',
- parsePositiveSeconds,
- )
- .addHelpText(
- 'after',
- `
-Exit codes:
- 0 the run finished (done)
- 1 the run failed or was interrupted
- 2 the run is paused waiting for human approval / input
- 3 the outcome could not be confirmed (no or unreadable status, status checks kept failing, or --timeout reached)`,
- )
- .action(
- async (options: {
- agentId?: string;
- autoStart?: boolean;
- device?: string;
- detach?: boolean;
- headless?: boolean;
- json?: boolean;
- prompt?: string;
- replay?: string;
- slug?: string;
- sse?: boolean;
- timeout?: number;
- topicId?: string;
- verbose?: boolean;
- }) => {
- if (options.verbose) setVerbose(true);
-
- // Replay mode: render from saved JSON file, no network needed
- if (options.replay) {
- const data = readFileSync(options.replay, 'utf8');
- const events = JSON.parse(data);
- const replayed = replayAgentEvents(events, {
- json: options.json,
- verbose: options.verbose,
- });
- // A recording without a terminal event cannot tell how the run ended.
- const replayExitCode = AGENT_RUN_EXIT_CODES[(replayed ?? { kind: 'unknown' }).kind];
- if (replayExitCode !== 0) process.exitCode = replayExitCode;
- return;
- }
-
- if (!options.agentId && !options.slug) {
- log.error('Either --agent-id or --slug is required.');
- process.exit(1);
- return;
- }
- if (!options.prompt) {
- log.error('--prompt is required.');
- process.exit(1);
- return;
- }
-
- const client = await getTrpcClient();
-
- let deviceId: string | undefined;
- if (options.device !== undefined) {
- if (options.device === 'local') {
- deviceId = resolveLocalDeviceId();
- if (!deviceId) {
- log.error(
- "No local device found. Run 'lh connect' first, then retry with --device local.",
- );
- process.exit(1);
- return;
- }
- } else {
- deviceId = options.device;
- }
-
- const devices = await client.device.listDevices.query();
- const matchedDevice = devices.find(
- (device: { deviceId?: string; online?: boolean }) => device.deviceId === deviceId,
- );
- if (!matchedDevice) {
- log.error(`Device "${deviceId}" was not found. Check 'lh device list' and try again.`);
- process.exit(1);
- return;
- }
- if (!matchedDevice.online) {
- log.error(
- options.device === 'local'
- ? `Local device "${deviceId}" is not online. Reconnect with 'lh connect' and try again.`
- : `Device "${deviceId}" is not online. Bring it online and try again.`,
- );
- process.exit(1);
- return;
- }
- }
-
- // 1. Exec agent to get operationId
- const input: Record<string, any> = { prompt: options.prompt, trigger: 'cli' };
- if (options.agentId) input.agentId = options.agentId;
- if (deviceId) input.deviceId = deviceId;
- if (options.slug) input.slug = options.slug;
- if (options.topicId) input.appContext = { topicId: options.topicId };
- if (options.autoStart === false) input.autoStart = false;
- // commander's --no-headless sets `headless` to false. Anything else
- // (undefined, true) β†’ headless mode is on and tool calls auto-execute.
- if (options.headless !== false) {
- input.userInterventionConfig = { approvalMode: 'headless' };
- }
-
- const result = await client.aiAgent.execAgent.mutate(input as any);
- const r = result as any;
-
- if (!r.success) {
- log.error(`Failed to start agent: ${r.error || r.message || 'Unknown error'}`);
- process.exit(1);
- }
-
- const operationId = r.operationId;
- if (options.detach) {
- const started = {
- autoStarted: r.autoStarted,
- operationId,
- status: r.status,
- topicId: r.topicId,
- };
- if (options.json) outputJson(started);
- else log.info(`Operation: ${pc.dim(operationId)} Β· Topic: ${pc.dim(r.topicId || 'n/a')}`);
- return;
- }
- if (!options.json) {
- log.info(`Operation: ${pc.dim(operationId)} Β· Topic: ${pc.dim(r.topicId || 'n/a')}`);
- }
-
- // 2. Connect to stream (WebSocket via Gateway, or fallback to SSE)
- const { serverUrl, headers, token, tokenType } = await getAgentStreamAuthInfo();
- const agentGatewayUrl = options.sse ? undefined : resolveAgentGatewayUrl();
-
- const waitForRun = async (): Promise<AgentRunOutcome> => {
- let streamed: AgentRunOutcome | undefined;
- try {
- if (agentGatewayUrl) {
- streamed = await streamAgentEventsViaWebSocket({
- gatewayUrl: agentGatewayUrl,
- json: options.json,
- // A quiet stream is checked against the run status rather than
- // treated as finished or failed β€” a long tool call can be silent.
- onStall: () => probeRunOutcome(client, operationId, { json: options.json }),
- operationId,
- serverUrl,
- token,
- tokenType,
- verbose: options.verbose,
- });
- } else {
- const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
- streamed = await streamAgentEvents(streamUrl, headers, {
- json: options.json,
- // SSE heartbeats keep the response open even when the terminal
- // event was published before this subscription (in-memory event
- // manager), so a quiet stream is checked against the run status.
- onStall: () => probeRunOutcome(client, operationId, { json: options.json }),
- verbose: options.verbose,
- });
- }
- } catch (error) {
- // The live stream (gateway WS / SSE) dropped before the run finished β€”
- // the run may still be executing server-side, in --json mode too.
- // Fall back to polling the run status until it reaches a terminal state.
- log.warn(
- `Live stream unavailable (${(error as Error).message}). Polling run status every ${RUN_POLL_INTERVAL_MS / 1000}s…`,
- );
- return pollAgentRunStatus(client, operationId, { json: options.json });
- }
-
- // The stream closed without a terminal event: that is not a success
- // signal, so ask the server how the run actually ended.
- return streamed ?? pollAgentRunStatus(client, operationId, { json: options.json });
- };
-
- let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
- let didTimeOut = false;
- const timedOut =
- options.timeout === undefined
- ? undefined
- : new Promise<AgentRunOutcome>((resolve) => {
- timeoutTimer = setTimeout(() => {
- didTimeOut = true;
- log.error(
- `Stopped waiting after ${options.timeout}s (--timeout). The run may still be executing β€” check it with 'lh agent status ${operationId}'.`,
- );
- resolve({ kind: 'unknown' });
- }, options.timeout! * 1000);
- });
-
- const outcome = await (timedOut ? Promise.race([waitForRun(), timedOut]) : waitForRun());
- clearTimeout(timeoutTimer);
-
- const exitCode = AGENT_RUN_EXIT_CODES[outcome.kind];
- if (exitCode !== 0) {
- // A timeout leaves the stream / poll pending, so exit hard; otherwise
- // set the code and let stdout (possibly a large --json array) drain.
- if (didTimeOut) process.exit(exitCode);
- process.exitCode = exitCode;
- }
- },
- );
+ registerAgentRunCommand(agent);
// ── pin / unpin ─────────────────────────────────────
@@ -888,11 +654,3 @@ Exit codes:
},
);
}
-
-function parsePositiveSeconds(value: string): number {
- const seconds = Number(value);
- if (!Number.isFinite(seconds) || seconds <= 0) {
- throw new InvalidArgumentError('Expected a positive number of seconds.');
- }
- return seconds;
-}
diff --git a/apps/cli/src/commands/agent/run.test.ts b/apps/cli/src/commands/agent/run.test.ts
new file mode 100644
index 00000000000..cfca3b639e2
--- /dev/null
+++ b/apps/cli/src/commands/agent/run.test.ts
@@ -0,0 +1,76 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerAgentRunCommand } from './run';
+
+const { mockExecAgent, mockGetTrpcClient } = vi.hoisted(() => ({
+ mockExecAgent: vi.fn(),
+ mockGetTrpcClient: vi.fn(),
+}));
+
+vi.mock('../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+vi.mock('../../api/http', () => ({ getAgentStreamAuthInfo: vi.fn() }));
+vi.mock('../../utils/agentStream', () => ({
+ replayAgentEvents: vi.fn(),
+ streamAgentEvents: vi.fn(),
+ streamAgentEventsViaWebSocket: vi.fn(),
+}));
+vi.mock('../../utils/device', () => ({ resolveLocalDeviceId: vi.fn() }));
+
+const runAgent = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerAgentRunCommand(program.command('agent'));
+ await program.parseAsync(['node', 'lh', 'agent', 'run', '--detach', ...args]);
+ return mockExecAgent.mock.calls[0]?.[0];
+};
+
+describe('lh agent run', () => {
+ beforeEach(() => {
+ mockExecAgent.mockResolvedValue({ operationId: 'op-1', success: true, topicId: 'tpc-1' });
+ mockGetTrpcClient.mockResolvedValue({ aiAgent: { execAgent: { mutate: mockExecAgent } } });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ mockExecAgent.mockReset();
+ });
+
+ it('enables each --tool for the run, as an @-mention in chat does', async () => {
+ const input = await runAgent(
+ '--agent-id',
+ 'agt-1',
+ '--prompt',
+ 'Check the build',
+ '--tool',
+ 'lobe-computer-use',
+ '--tool',
+ 'my-mcp',
+ );
+
+ expect(input.selectedToolIds).toEqual(['lobe-computer-use', 'my-mcp']);
+ });
+
+ it('selects each --skill for the run, as picking it in chat does', async () => {
+ const input = await runAgent(
+ '--agent-id',
+ 'agt-1',
+ '--prompt',
+ 'Audit the page',
+ '--skill',
+ 'ux-audit',
+ '--skill',
+ 'agent-skills:review',
+ );
+
+ expect(input.selectedSkillIds).toEqual(['ux-audit', 'agent-skills:review']);
+ });
+
+ it('sends neither field when no tool or skill is given', async () => {
+ const input = await runAgent('--agent-id', 'agt-1', '--prompt', 'Hello');
+
+ expect(input).not.toHaveProperty('selectedToolIds');
+ expect(input).not.toHaveProperty('selectedSkillIds');
+ });
+});
diff --git a/apps/cli/src/commands/agent/run.ts b/apps/cli/src/commands/agent/run.ts
new file mode 100644
index 00000000000..42e9759e8e3
--- /dev/null
+++ b/apps/cli/src/commands/agent/run.ts
@@ -0,0 +1,271 @@
+import { readFileSync } from 'node:fs';
+
+import { type Command, InvalidArgumentError } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../../api/client';
+import { getAgentStreamAuthInfo } from '../../api/http';
+import { resolveAgentGatewayUrl } from '../../settings';
+import type { AgentRunOutcome } from '../../utils/agentRunOutcome';
+import { AGENT_RUN_EXIT_CODES } from '../../utils/agentRunOutcome';
+import {
+ replayAgentEvents,
+ streamAgentEvents,
+ streamAgentEventsViaWebSocket,
+} from '../../utils/agentStream';
+import { resolveLocalDeviceId } from '../../utils/device';
+import { outputJson } from '../../utils/format';
+import { log, setVerbose } from '../../utils/logger';
+import { pollAgentRunStatus, probeRunOutcome, RUN_POLL_INTERVAL_MS } from './runStatus';
+
+export function registerAgentRunCommand(agent: Command) {
+ agent
+ .command('run')
+ .description('Run an agent with a prompt')
+ .option('-a, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-p, --prompt <text>', 'User prompt')
+ .option('-t, --topic-id <id>', 'Reuse an existing topic')
+ .option('--no-auto-start', 'Do not auto-start the agent')
+ .option(
+ '--device <target>',
+ 'Target device ID, or use "local" for the current connected device',
+ )
+ .option(
+ '--no-headless',
+ "Disable headless mode: tool calls that need approval park the run for a human (default: headless β€” tools auto-run, matching the CLI's non-interactive nature). The CLI does not wait for that approval; it returns with exit code 2 and the run continues once it is answered in LobeHub",
+ )
+ .option(
+ '--tool <id>',
+ "Enable a tool for this run on top of the agent's own, like @-mentioning it in chat (repeatable)",
+ collectId,
+ )
+ .option(
+ '--skill <id>',
+ 'Load a skill for this run and the rest of its topic, like selecting it in chat (repeatable)',
+ collectId,
+ )
+ .option('--json', 'Output full JSON event stream')
+ .option('--detach', 'Start the operation and return its IDs without waiting for events')
+ .option('-v, --verbose', 'Show detailed tool call info')
+ .option('--replay <file>', 'Replay events from a saved JSON file (offline)')
+ .option('--sse', 'Force SSE stream instead of WebSocket gateway')
+ .option(
+ '--timeout <seconds>',
+ 'Stop waiting after this many seconds (exit code 3; the run keeps going server-side). Default: wait as long as the server reports the run active',
+ parsePositiveSeconds,
+ )
+ .addHelpText(
+ 'after',
+ `
+Exit codes:
+ 0 the run finished (done)
+ 1 the run failed or was interrupted
+ 2 the run is paused waiting for human approval / input
+ 3 the outcome could not be confirmed (no or unreadable status, status checks kept failing, or --timeout reached)`,
+ )
+ .action(
+ async (options: {
+ agentId?: string;
+ autoStart?: boolean;
+ device?: string;
+ detach?: boolean;
+ headless?: boolean;
+ json?: boolean;
+ prompt?: string;
+ replay?: string;
+ skill?: string[];
+ slug?: string;
+ sse?: boolean;
+ timeout?: number;
+ tool?: string[];
+ topicId?: string;
+ verbose?: boolean;
+ }) => {
+ if (options.verbose) setVerbose(true);
+
+ // Replay mode: render from saved JSON file, no network needed
+ if (options.replay) {
+ const data = readFileSync(options.replay, 'utf8');
+ const events = JSON.parse(data);
+ const replayed = replayAgentEvents(events, {
+ json: options.json,
+ verbose: options.verbose,
+ });
+ // A recording without a terminal event cannot tell how the run ended.
+ const replayExitCode = AGENT_RUN_EXIT_CODES[(replayed ?? { kind: 'unknown' }).kind];
+ if (replayExitCode !== 0) process.exitCode = replayExitCode;
+ return;
+ }
+
+ if (!options.agentId && !options.slug) {
+ log.error('Either --agent-id or --slug is required.');
+ process.exit(1);
+ return;
+ }
+ if (!options.prompt) {
+ log.error('--prompt is required.');
+ process.exit(1);
+ return;
+ }
+
+ const client = await getTrpcClient();
+
+ let deviceId: string | undefined;
+ if (options.device !== undefined) {
+ if (options.device === 'local') {
+ deviceId = resolveLocalDeviceId();
+ if (!deviceId) {
+ log.error(
+ "No local device found. Run 'lh connect' first, then retry with --device local.",
+ );
+ process.exit(1);
+ return;
+ }
+ } else {
+ deviceId = options.device;
+ }
+
+ const devices = await client.device.listDevices.query();
+ const matchedDevice = devices.find(
+ (device: { deviceId?: string; online?: boolean }) => device.deviceId === deviceId,
+ );
+ if (!matchedDevice) {
+ log.error(`Device "${deviceId}" was not found. Check 'lh device list' and try again.`);
+ process.exit(1);
+ return;
+ }
+ if (!matchedDevice.online) {
+ log.error(
+ options.device === 'local'
+ ? `Local device "${deviceId}" is not online. Reconnect with 'lh connect' and try again.`
+ : `Device "${deviceId}" is not online. Bring it online and try again.`,
+ );
+ process.exit(1);
+ return;
+ }
+ }
+
+ // 1. Exec agent to get operationId
+ const input: Record<string, any> = { prompt: options.prompt, trigger: 'cli' };
+ if (options.agentId) input.agentId = options.agentId;
+ if (deviceId) input.deviceId = deviceId;
+ if (options.slug) input.slug = options.slug;
+ if (options.topicId) input.appContext = { topicId: options.topicId };
+ if (options.autoStart === false) input.autoStart = false;
+ if (options.tool?.length) input.selectedToolIds = options.tool;
+ if (options.skill?.length) input.selectedSkillIds = options.skill;
+ // commander's --no-headless sets `headless` to false. Anything else
+ // (undefined, true) β†’ headless mode is on and tool calls auto-execute.
+ if (options.headless !== false) {
+ input.userInterventionConfig = { approvalMode: 'headless' };
+ }
+
+ const result = await client.aiAgent.execAgent.mutate(input as any);
+ const r = result as any;
+
+ if (!r.success) {
+ log.error(`Failed to start agent: ${r.error || r.message || 'Unknown error'}`);
+ process.exit(1);
+ }
+
+ const operationId = r.operationId;
+ if (options.detach) {
+ const started = {
+ autoStarted: r.autoStarted,
+ operationId,
+ status: r.status,
+ topicId: r.topicId,
+ };
+ if (options.json) outputJson(started);
+ else log.info(`Operation: ${pc.dim(operationId)} Β· Topic: ${pc.dim(r.topicId || 'n/a')}`);
+ return;
+ }
+ if (!options.json) {
+ log.info(`Operation: ${pc.dim(operationId)} Β· Topic: ${pc.dim(r.topicId || 'n/a')}`);
+ }
+
+ // 2. Connect to stream (WebSocket via Gateway, or fallback to SSE)
+ const { serverUrl, headers, token, tokenType } = await getAgentStreamAuthInfo();
+ const agentGatewayUrl = options.sse ? undefined : resolveAgentGatewayUrl();
+
+ const waitForRun = async (): Promise<AgentRunOutcome> => {
+ let streamed: AgentRunOutcome | undefined;
+ try {
+ if (agentGatewayUrl) {
+ streamed = await streamAgentEventsViaWebSocket({
+ gatewayUrl: agentGatewayUrl,
+ json: options.json,
+ // A quiet stream is checked against the run status rather than
+ // treated as finished or failed β€” a long tool call can be silent.
+ onStall: () => probeRunOutcome(client, operationId, { json: options.json }),
+ operationId,
+ serverUrl,
+ token,
+ tokenType,
+ verbose: options.verbose,
+ });
+ } else {
+ const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
+ streamed = await streamAgentEvents(streamUrl, headers, {
+ json: options.json,
+ // SSE heartbeats keep the response open even when the terminal
+ // event was published before this subscription (in-memory event
+ // manager), so a quiet stream is checked against the run status.
+ onStall: () => probeRunOutcome(client, operationId, { json: options.json }),
+ verbose: options.verbose,
+ });
+ }
+ } catch (error) {
+ // The live stream (gateway WS / SSE) dropped before the run finished β€”
+ // the run may still be executing server-side, in --json mode too.
+ // Fall back to polling the run status until it reaches a terminal state.
+ log.warn(
+ `Live stream unavailable (${(error as Error).message}). Polling run status every ${RUN_POLL_INTERVAL_MS / 1000}s…`,
+ );
+ return pollAgentRunStatus(client, operationId, { json: options.json });
+ }
+
+ // The stream closed without a terminal event: that is not a success
+ // signal, so ask the server how the run actually ended.
+ return streamed ?? pollAgentRunStatus(client, operationId, { json: options.json });
+ };
+
+ let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
+ let didTimeOut = false;
+ const timedOut =
+ options.timeout === undefined
+ ? undefined
+ : new Promise<AgentRunOutcome>((resolve) => {
+ timeoutTimer = setTimeout(() => {
+ didTimeOut = true;
+ log.error(
+ `Stopped waiting after ${options.timeout}s (--timeout). The run may still be executing β€” check it with 'lh agent status ${operationId}'.`,
+ );
+ resolve({ kind: 'unknown' });
+ }, options.timeout! * 1000);
+ });
+
+ const outcome = await (timedOut ? Promise.race([waitForRun(), timedOut]) : waitForRun());
+ clearTimeout(timeoutTimer);
+
+ const exitCode = AGENT_RUN_EXIT_CODES[outcome.kind];
+ if (exitCode !== 0) {
+ // A timeout leaves the stream / poll pending, so exit hard; otherwise
+ // set the code and let stdout (possibly a large --json array) drain.
+ if (didTimeOut) process.exit(exitCode);
+ process.exitCode = exitCode;
+ }
+ },
+ );
+}
+
+const collectId = (value: string, previous: string[] = []): string[] => [...previous, value];
+
+function parsePositiveSeconds(value: string): number {
+ const seconds = Number(value);
+ if (!Number.isFinite(seconds) || seconds <= 0) {
+ throw new InvalidArgumentError('Expected a positive number of seconds.');
+ }
+ return seconds;
+}
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.selectedSkills.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.selectedSkills.test.ts
new file mode 100644
index 00000000000..3f3039aca62
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.selectedSkills.test.ts
@@ -0,0 +1,182 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { agents } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import type * as ModelBankModule from 'model-bank';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as InternalJwtModule from '@/libs/trpc/utils/internalJwt';
+import { AiAgentService } from '@/server/services/aiAgent';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+// Mock AgentRuntimeService since we only want to test the router's business logic
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: vi.fn(async (params: any) => {
+ // The real runtime invokes this before the run's first step, with the
+ // operation it is about to start; mirror it so the router's Task-run
+ // reopen path runs when a test seeds a Task run. It is a no-op for the
+ // ordinary conversation, which attaches no hooks.
+ await params?.onOperationCreated?.(params?.operationId);
+ return {
+ success: true,
+ operationId: params?.operationId ?? 'mock-operation-id',
+ autoStarted: true,
+ messageId: 'mock-message-id',
+ };
+ }),
+ };
+ }),
+}));
+
+// Mock serverMessagesEngine
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn(function () {
+ return {
+ generateToolsDetailed: vi.fn(function () {
+ return { tools: [] };
+ }),
+ getEnabledPluginManifests: vi.fn(function () {
+ return new Map();
+ }),
+ };
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue({
+ messages: [
+ { role: 'system', content: 'You are a helpful assistant.' },
+ { role: 'user', content: 'Hello' },
+ ],
+ metadata: {},
+ }),
+}));
+
+// Mock AiChatService to avoid S3 dependency
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(function () {
+ return {
+ getMessagesAndTopics: vi.fn().mockResolvedValue({ messages: [], topics: [] }),
+ };
+ }),
+}));
+
+// Mock FileService to avoid S3 dependency
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ getFullFileUrl: vi.fn(function (path: string | null) {
+ return path;
+ }),
+ };
+ }),
+}));
+
+// Mock the resource-permission guard so workspace-mode tests can assert the
+// router resolves slug β†’ agent id and runs the `use` guard (the guard's own
+// RBAC evaluation is covered by its service tests).
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+
+// The user-hub token is a real RS256 signature in production; the integration
+// DB has no JWKS_KEY, so pin the signer and assert the subject it is asked for.
+const mockSignUserJWT = vi.fn();
+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({
+ ...(await importOriginal<typeof InternalJwtModule>()),
+ signUserJWT: (...args: any[]) => mockSignUserJWT(...args),
+}));
+
+// Mock model-bank with dynamic import to preserve other exports
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ id: 'gpt-4o-mini',
+ providerId: 'openai',
+ abilities: { functionCall: true, vision: true, video: false },
+ },
+ ],
+ };
+});
+
+describe('aiAgent router - selected skills', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let testAgentId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ title: 'Test Agent',
+ userId,
+ })
+ .returning();
+ testAgentId = agent.id;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.restoreAllMocks();
+ });
+
+ const execAgentParams = () => {
+ const spy = vi.spyOn(AiAgentService.prototype, 'execAgent');
+ return () => spy.mock.calls.map(([params]) => params.selectedSkillIds);
+ };
+
+ it('forwards selected skills on the single-run route', async () => {
+ const selectedSkillIdsOf = execAgentParams();
+ const caller = aiAgentRouter.createCaller({ jwtPayload: { userId }, userId });
+
+ await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Audit',
+ selectedSkillIds: ['ux-audit'],
+ });
+
+ expect(selectedSkillIdsOf()).toEqual([['ux-audit']]);
+ });
+
+ // ROOT CAUSE:
+ //
+ // `execAgents` validates each task with `ExecAgentSchema`, so a batch task
+ // accepted `selectedSkillIds`, but the route rebuilt the service params from
+ // a fixed field list that left it out.
+ //
+ // Before the fix, a batch task's selected skills were silently dropped.
+ // The fix forwards them like the single-run route does.
+ it('forwards selected skills on the batch route', async () => {
+ const selectedSkillIdsOf = execAgentParams();
+ const caller = aiAgentRouter.createCaller({ jwtPayload: { userId }, userId });
+
+ await caller.execAgents({
+ tasks: [
+ { agentId: testAgentId, prompt: 'Audit', selectedSkillIds: ['ux-audit'] },
+ { agentId: testAgentId, prompt: 'Plain' },
+ ],
+ });
+
+ expect(selectedSkillIdsOf()).toEqual(expect.arrayContaining([['ux-audit'], undefined]));
+ expect(selectedSkillIdsOf()).toHaveLength(2);
+ });
+});
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 9c7fa54f4a6..284fcfe2bfa 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1315,6 +1315,13 @@ const ExecAgentSchema = z
* by the user-scoped lookups downstream, so it can't enable others' tools.
*/
selectedToolIds: z.array(z.string()).optional(),
+ /**
+ * Skill identifiers the user selected for this message. Their bodies are
+ * injected directly for this turn and every later turn of the topic, the
+ * same way a pinned skill is, instead of waiting for `activateSkill`.
+ * Persisted on the user message as `metadata.selectedSkillIds`.
+ */
+ selectedSkillIds: z.array(z.string()).optional(),
/**
* Agents the user @-mentioned in this message (multi-mention). When present
* (and non-group), the run enables the callAgent tool and injects the
@@ -2520,6 +2527,7 @@ export const aiAgentRouter = router({
resumeApproval,
resumeApprovals,
resumeToolResult,
+ selectedSkillIds,
selectedToolIds,
steer,
trigger,
@@ -2651,6 +2659,7 @@ export const aiAgentRouter = router({
resumeApproval,
resumeApprovals,
resumeToolResult,
+ selectedSkillIds,
selectedToolIds,
slug,
steer,
@@ -2828,6 +2837,10 @@ export const aiAgentRouter = router({
prompt,
// When parentMessageId is provided, this is a regeneration/continue β€” skip user message creation
resume: !!parentMessageId,
+ // NOTICE: the batch route forwards only a subset of `ExecAgentSchema`;
+ // other per-turn picks (`selectedToolIds`, `mentionedAgents`, `fileIds`)
+ // are still dropped here, as before this field was added.
+ selectedSkillIds: task.selectedSkillIds,
slug,
trigger: trigger ?? RequestTrigger.Chat,
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
index eee18d2540b..245557e0289 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
@@ -21,6 +21,7 @@ const {
mockListUserSkillCatalog,
mockLoadUserSkills,
mockMessageCreate,
+ mockMessageQuery,
mockPluginQuery,
mockSkillFindAll,
mockSkillFindByIds,
@@ -40,6 +41,7 @@ const {
mockListUserSkillCatalog: vi.fn().mockResolvedValue([]),
mockLoadUserSkills: vi.fn().mockResolvedValue([]),
mockMessageCreate: vi.fn(),
+ mockMessageQuery: vi.fn().mockResolvedValue([]),
mockPluginQuery: vi.fn().mockResolvedValue([]),
mockSkillFindAll: vi.fn().mockResolvedValue({ data: [], total: 0 }),
mockSkillFindByIds: vi.fn().mockResolvedValue([]),
@@ -63,7 +65,7 @@ vi.mock('@/database/models/message', () => ({
create: mockMessageCreate,
getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
- query: vi.fn().mockResolvedValue([]),
+ query: mockMessageQuery,
update: vi.fn().mockResolvedValue({}),
};
}),
@@ -139,6 +141,8 @@ vi.mock('@/database/models/topic', () => ({
releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ // A follow-up turn reuses its topic; only the selected-skill history case sends one.
+ findById: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: {} }),
};
}),
}));
@@ -502,3 +506,109 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {
expect(injected).toContain('guide.md');
});
});
+
+describe('AiAgentService.execAgent - selected skill content injection', () => {
+ let service: AiAgentService;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockMessageQuery.mockResolvedValue([]);
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ mockSkillFindAll.mockResolvedValue({
+ data: DB_SKILL_ROWS.map(({ id, identifier }) => ({
+ description: 'd',
+ id,
+ identifier,
+ name: identifier,
+ })),
+ total: DB_SKILL_ROWS.length,
+ });
+ mockSkillFindByIds.mockImplementation(async (ids: string[]) =>
+ DB_SKILL_ROWS.filter((r) => ids.includes(r.id)),
+ );
+ mockGetAgentSkills.mockResolvedValue([]);
+ mockListUserSkillCatalog.mockResolvedValue([]);
+ mockLoadUserSkills.mockResolvedValue([]);
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ // Nothing pinned β€” db-skill-auto is an auto-mode skill.
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ });
+ service = new AiAgentService({} as any, 'test-user-id');
+ });
+
+ // ROOT CAUSE:
+ //
+ // A skill picked in the chat composer reached a gateway-mode run only as the
+ // `<skill name="…" />` text in the prompt, because `execAgent` had no field
+ // for it. The client runtime injects the body; the server run left it to the
+ // model to call `activateSkill`.
+ //
+ // The fix injects the body of every selected skill like a pinned skill.
+ it('injects the body of a skill this turn selected and persists the selection', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Audit this page',
+ selectedSkillIds: ['db-skill-auto'],
+ } as any);
+
+ expect(operationSkillSetArg()?.enabledPluginIds).toContain('db-skill-auto');
+ expect(skillById('db-skill-auto')?.content).toBe('AUTO SKILL BODY');
+ expect(mockSkillFindByIds).toHaveBeenCalledWith(['sk-2']);
+ const userRow = mockMessageCreate.mock.calls.find(([row]) => row.role === 'user')?.[0];
+ expect(userRow?.metadata).toEqual(
+ expect.objectContaining({ selectedSkillIds: ['db-skill-auto'] }),
+ );
+ });
+
+ it('keeps injecting a skill an earlier turn of the topic selected', async () => {
+ mockMessageQuery.mockResolvedValue([
+ {
+ content: 'Audit this page',
+ id: 'msg-earlier',
+ metadata: { selectedSkillIds: ['db-skill-auto'] },
+ role: 'user',
+ },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Now the settings page',
+ } as any);
+
+ expect(operationSkillSetArg()?.enabledPluginIds).toContain('db-skill-auto');
+ expect(skillById('db-skill-auto')?.content).toBe('AUTO SKILL BODY');
+ });
+
+ it('keeps a selected skill available when the agent only allows picked skills', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: { skillActivateMode: 'manual' },
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Audit this page',
+ selectedSkillIds: ['db-skill-auto'],
+ } as any);
+
+ expect(skillById('db-skill-auto')?.content).toBe('AUTO SKILL BODY');
+ // Manual mode still hides the skills nobody picked.
+ expect(skillById('db-skill-pinned')).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 2716ca2dfb4..dab89ad780e 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -958,6 +958,7 @@ export class AiAgentService {
resumeToolResult,
approvalResolutionRequestId: providedApprovalResolutionRequestId,
approvalSourceOperationId: providedApprovalSourceOperationId,
+ selectedSkillIds,
selectedToolIds,
shareGate,
mentionedAgents,
@@ -1251,6 +1252,7 @@ export class AiAgentService {
resolvedAgentId,
resume,
runFromHistory,
+ selectedSkillIds,
shareGate,
steer,
throwIfExecutionAborted,
@@ -1464,6 +1466,7 @@ export class AiAgentService {
resumeFromHistory: runFromHistory,
resumeToolResult: resolvedToolResult,
runAttachments,
+ selectedSkillIds,
selectedToolIds,
topicBoundDeviceId: turn.topicBoundDeviceId,
});
diff --git a/apps/server/src/services/aiAgent/pipeline/operationInit.ts b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
index c9e4b3dba65..4bf7fa686ac 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationInit.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
@@ -70,6 +70,7 @@ export interface OperationInitRequest {
resumeFromHistory: boolean;
resumeToolResult?: InternalExecAgentParams['resumeToolResult'];
runAttachments: RunAttachments;
+ selectedSkillIds?: string[];
selectedToolIds?: string[];
/** The Task this run executes, when it runs inside the Task system. */
taskId?: string;
@@ -215,6 +216,7 @@ export const runOperationInit = async (
operationId: request.operationId,
runAttachments: request.runAttachments,
runFromHistory: request.resumeFromHistory,
+ selectedSkillIds: request.selectedSkillIds,
taskId: request.taskId,
throwIfExecutionAborted: deps.throwIfExecutionAborted,
},
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index 654c49a4a47..4e02bab0bdf 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -1,41 +1,31 @@
import type { AgentRuntimeContext } from '@lobechat/agent-runtime';
import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';
-import { builtinSkills, LobeHubIdentifier } from '@lobechat/builtin-skills';
import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';
import type { OperationSkillSet, ProjectInstructionFile } from '@lobechat/context-engine';
-import { buildExpertiseContextSnapshot, mentionsTopic } from '@lobechat/context-engine';
+import { buildExpertiseContextSnapshot } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
-import { assembleSkillPool } from '@lobechat/mecha';
-import { buildTaskManagerDefaultsPrompt, resourcesTreePrompt } from '@lobechat/prompts';
+import { buildTaskManagerDefaultsPrompt } from '@lobechat/prompts';
import type { LobeAgentAgencyConfig, WorkspaceInitResult } from '@lobechat/types';
-import {
- buildGoalOverviewContext,
- getActivePluginIds,
- getWorkingDirEffectivePath,
-} from '@lobechat/types';
+import { buildGoalOverviewContext, getWorkingDirEffectivePath } from '@lobechat/types';
import debug from 'debug';
import type { AgentModel } from '@/database/models/agent';
-import { AgentSkillModel } from '@/database/models/agentSkill';
import { DeviceModel } from '@/database/models/device';
import { ExpertiseModel } from '@/database/models/expertise';
import { GoalGraphModel } from '@/database/models/goalGraph';
import type { MessageModel } from '@/database/models/message';
-import { TaskModel } from '@/database/models/task';
import type { TopicModel } from '@/database/models/topic';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
-import { isDeviceCapablePlan } from '@/helpers/executionTarget';
import type { ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';
import type { AgentDocumentsService } from '@/server/services/agentDocuments';
import { deviceGateway } from '@/server/services/deviceGateway';
import { FileService } from '@/server/services/file';
import { redisService } from '@/server/services/redis';
-import { readTaskSkillIds, UserSkillService } from '@/server/services/userSkill';
import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
import { pruneRegeneratedBranch } from '../pruneRegeneratedBranch';
import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';
-import { applyShareGateToToolSet, filterSkillsByShareGate } from '../shareGate';
+import { applyShareGateToToolSet } from '../shareGate';
import type {
BindTopicWorkingDirectoryParams,
ExecRunContext,
@@ -43,6 +33,7 @@ import type {
ResolvedWorkspaceInit,
} from '../types';
import { isWorkspaceCacheFresh, upsertWorkspaceScan } from '../workspaceInitCache';
+import { buildOperationSkillSet, collectSelectedSkillIds } from './operationSkillSet';
import type { ToolDiscoveryResult } from './toolDiscovery';
import type { RunAttachments } from './turnSetup';
@@ -198,6 +189,8 @@ export interface OperationPrepInput {
operationId: string;
runAttachments: RunAttachments;
runFromHistory: boolean;
+ /** Skills this turn's request selected; earlier turns' come from history. */
+ selectedSkillIds?: string[];
/** The Task this run executes; the skills it names are trusted for this run. */
taskId?: string;
throwIfExecutionAborted: (stage: string) => Promise<void>;
@@ -778,215 +771,37 @@ export const prepareOperation = async (
topicId,
});
- // 18. Build OperationSkillSet via SkillEngine
- // Combines builtin skills + user DB skills + agent-document skill bundles,
- // filters by platform via enableChecker, and pairs with agent's enabled
- // plugin IDs for downstream SkillResolver consumption.
- let operationSkillSet;
- try {
- const builtinMetas = builtinSkills.map((s) => ({
- content: s.content,
- description: s.description,
- identifier: s.identifier,
- name: s.name,
- }));
- const skillModel = new AgentSkillModel(deps.db, deps.userId, deps.workspaceId);
- const { data: dbSkills } = await skillModel.findAll();
-
- // Pinned skills need their SKILL.md body injected into context directly,
- // not lazily via the `activateSkill` tool. Gate on the agent's genuinely
- // pinned entries (`getActivePluginIds(agentConfig.plugins)`), NOT the
- // fully-expanded `agentPlugins`: the latter also carries turn-scoped tool
- // ids (mentions, selected tools, `lobe-message`, …), which would
- // eager-activate an auto-mode skill whose identifier merely collides with
- // one of them. `findAll` uses `skillListColumns` (no `content`), so fetch
- // bodies only for the pinned subset to keep the op-param payload bounded.
- // Non-pinned skills stay content-less here and remain lazily activatable.
- // Content lives in the DB `content` column already (SKILL.md body), so no
- // zip unpack is needed; mirror `activateSkill` by appending the resource
- // tree so pinned ZIP/GitHub skills keep their `readReference` paths.
- const pinnedSkillIds = new Set(getActivePluginIds(agentConfig.plugins));
- const pinnedDbSkillIds = dbSkills
- .filter((s) => pinnedSkillIds.has(s.identifier))
- .map((s) => s.id);
- const pinnedDbContent = new Map(
- (await skillModel.findByIds(pinnedDbSkillIds)).map((s) => {
- const hasResources = !!(s.resources && Object.keys(s.resources).length > 0);
- const content =
- hasResources && s.resources
- ? `${s.content ?? ''}\n\n${resourcesTreePrompt(s.name, s.resources)}`
- : (s.content ?? undefined);
- return [s.identifier, content] as const;
- }),
- );
- const dbMetas = dbSkills.map((s) => ({
- content: pinnedDbContent.get(s.identifier),
- description: s.description ?? '',
- identifier: s.identifier,
- name: s.name,
- }));
-
- // Agent-document skill bundles surfaced as runtime skills via the shared
- // `getAgentSkills` source of truth (prefix + index-child resolution lives
- // there; see `AgentDocumentsService.getAgentSkills`). Identifier is
- // prefixed (`agent-skills:<filename>`) so it can't collide with builtin
- // / DB skill names, and we re-use it as `name` so the prompt's
- // `<skill name="...">` line and the model's `activateSkill(name)` call
- // carry the same value.
- const agentSkills = await deps.agentDocumentsService.getAgentSkills(resolvedAgentId);
- const agentSkillMetas = agentSkills.map((skill) => ({
- // `getAgentSkills` already resolves the bundle body, so pinned
- // agent-document skills inject directly without an extra fetch; only
- // attach it for the pinned subset to keep the payload lean.
- content: pinnedSkillIds.has(skill.identifier) ? skill.content : undefined,
- description: skill.description,
- identifier: skill.identifier,
- name: skill.name,
+ // Collected for the context engine, which assembles the system message and
+ // injects these directly after the persona β€” where this code used to
+ // concatenate them. Returning them rather than stamping `agentConfig` keeps
+ // run context off the agent's configuration.
+ if (workspaceInit.workspace.instructions.length) {
+ projectInstructions = workspaceInit.workspace.instructions.map(({ content, source }) => ({
+ content,
+ source,
}));
-
- // The user's own skill library: listed to every run, and injected up front
- // when the agent pins one or the run names it in its plugins β€” a goal
- // batch's unit runs name the batch's plan skill that way.
- // The catalog carries no bodies; only the pinned / run-named skills read
- // theirs, so a library that grows with every batch stays cheap to list.
- // A workspace-public agent never reads its caller's private skills β€” every
- // user skill is private β€” so its runs see none of them.
- const userSkills = new UserSkillService(
- deps.db,
- deps.userId,
- deps.workspaceId,
- deps.workspaceId ? await deps.agentModel.getAgentVisibility(resolvedAgentId) : undefined,
- );
- // The skills the run's own Task names (a goal batch's plan) load even
- // through a public agent β€” and only those; nothing the model or a picker
- // supplies widens that.
- const taskSkillIds = input.taskId
- ? readTaskSkillIds(
- (await new TaskModel(deps.db, deps.userId, deps.workspaceId).findById(input.taskId))
- ?.config,
- )
- : [];
- const namedUserSkills = await userSkills.loadRuntimeSkills(
- [...pinnedSkillIds, ...(agentPlugins ?? []), ...taskSkillIds],
- { trustedGenerated: taskSkillIds },
- );
- // Skills the system generated for one job (a goal batch's plan) are not
- // listed to every run β€” one accumulates per batch, so the query leaves them
- // out β€” only joined where the run pins or names them, as that batch's units
- // do. Those come in with their bodies.
- const listed = await userSkills.listCatalog({ includeGenerated: false });
- const listedIds = new Set(listed.map((skill) => skill.identifier));
- const namedContent = new Map(
- namedUserSkills.map((skill) => [skill.identifier, skill.content] as const),
- );
- const userSkillMetas = [
- ...listed.map((skill) => ({
- content: namedContent.get(skill.identifier),
- description: skill.description,
- identifier: skill.identifier,
- name: skill.name,
- })),
- ...namedUserSkills
- .filter((skill) => !listedIds.has(skill.identifier))
- .map((skill) => ({
- content: skill.content,
- description: skill.description,
- identifier: skill.identifier,
- name: skill.name,
- })),
- ];
-
- const projectMetas = workspaceInit.workspace.skills.map((s) => ({
- description: s.description ?? '',
- identifier: `${s.scope === 'device' ? 'device' : 'project'}:${s.name}`,
- location: s.path,
- name: s.name,
- source: s.scope === 'device' ? ('device' as const) : ('project' as const),
- }));
-
- if (projectMetas.length) {
- log(
- 'execAgent: workspace skills merged: %d (activeDeviceId=%s)',
- projectMetas.length,
- activeDeviceId ?? 'none',
- );
- }
-
- // Collected for the context engine, which assembles the system message and
- // injects these directly after the persona β€” where this code used to
- // concatenate them. Returning them rather than stamping `agentConfig` keeps
- // run context off the agent's configuration.
- if (workspaceInit.workspace.instructions.length) {
- projectInstructions = workspaceInit.workspace.instructions.map(({ content, source }) => ({
- content,
- source,
- }));
- log(
- 'execAgent: injected %d project instruction file(s): %s',
- workspaceInit.workspace.instructions.length,
- workspaceInit.workspace.instructions.map((i) => i.source).join(', '),
- );
- }
-
- // Precedence, name dedupe, the disabled drop, the share allowlist and the
- // device-only builtin gate are the shared rules in `@lobechat/mecha`; this
- // pipeline supplies the four sources and the run's facts.
- //
- // A shared run only sees skills its share configuration allows β€”
- // `shareConfig.skillGrants`, the creator's explicit per-skill list, NOT the
- // tool picker (`filterSkillsByShareGate`). The pool is the FIRST
- // enforcement point, not the only one: `activateSkill` takes a
- // model-supplied name, so the skill runtime re-checks the same grant at
- // load time.
- const shareAllowedSkillIds = shareGate
- ? filterSkillsByShareGate(
- [...projectMetas, ...dbMetas, ...agentSkillMetas, ...userSkillMetas, ...builtinMetas].map(
- (skill) => skill.identifier,
- ),
- shareGate,
- )
- : undefined;
-
- // Whether a skill is PINNED is the agent's own configuration; the share
- // only decides whether the visitor may reach it. `agentPlugins` has already
- // been narrowed by the TOOL grants (`filterPluginsByShareGate` in
- // `toolDiscovery`), which drops a skill the creator granted as a skill
- // rather than as a tool β€” leaving it un-pinned for the visitor (no content
- // injection) and, under `manual` mode, dropped from the pool entirely. Add
- // back exactly the ids that are both genuinely pinned on the agent AND
- // allowed by this share's skill grants; nothing else widens.
- const shareEnabledSkillIds = shareAllowedSkillIds?.filter((id) => pinnedSkillIds.has(id)) ?? [];
-
- // Device-only builtin skills are gated on the run's execution plan, not
- // the compile-time `isDesktop` constant (always false on the server). Use
- // the device-CAPABLE plan rather than `activeDeviceId`: a
- // `device-unrouted` run lets the model pick a device mid-run, and this
- // skill set is built once per operation, so gating on the routed device
- // would hide the skill forever in those runs. Activation and loading
- // apply the same plan gate via `ToolExecutionContext.deviceCapable`; only
- // command execution is gated at the device tool layer.
- operationSkillSet = assembleSkillPool(
- {
- agentSkills: [...agentSkillMetas, ...userSkillMetas],
- builtin: builtinMetas,
- db: dbMetas,
- project: projectMetas,
- },
- {
- canExecuteOnDevice: executionPlan ? isDeviceCapablePlan(executionPlan) : false,
- disabledIds: disabledPluginIds,
- enabledPluginIds: [...new Set([...(agentPlugins ?? []), ...shareEnabledSkillIds])],
- shareAllowedIds: shareAllowedSkillIds,
- skillActivateMode: agentConfig.chatConfig?.skillActivateMode,
- // Reading another topic (`<refer_topic>` or a raw `tpc_` id) goes through `lh topic view`,
- // which the lobehub skill teaches.
- turnSkillIds: mentionsTopic([{ content: prompt ?? '' }]) ? [LobeHubIdentifier] : [],
- },
+ log(
+ 'execAgent: injected %d project instruction file(s): %s',
+ workspaceInit.workspace.instructions.length,
+ workspaceInit.workspace.instructions.map((i) => i.source).join(', '),
);
- } catch (error) {
- log('execAgent: failed to build operationSkillSet: %O', error);
}
+ // 18. Build OperationSkillSet via SkillEngine (see `buildOperationSkillSet`).
+ const operationSkillSet = await buildOperationSkillSet(deps, {
+ activeDeviceId,
+ agentConfig,
+ agentPlugins,
+ disabledPluginIds,
+ executionPlan,
+ prompt,
+ resolvedAgentId,
+ selectedSkillIds: collectSelectedSkillIds(historyMessages, input.selectedSkillIds),
+ shareGate,
+ taskId: input.taskId,
+ workspaceInit,
+ });
+
// Resolve learned expertise once so every step in this operation uses the exact same snapshot.
// ContextEngine owns the Lab-controlled injection decision via enableExpertise.
const expertiseAgentId = appContext?.agentSignal?.agentId ?? resolvedAgentId;
diff --git a/apps/server/src/services/aiAgent/pipeline/operationSkillSet.test.ts b/apps/server/src/services/aiAgent/pipeline/operationSkillSet.test.ts
new file mode 100644
index 00000000000..a82d2649614
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/operationSkillSet.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { collectSelectedSkillIds } from './operationSkillSet';
+
+describe('collectSelectedSkillIds', () => {
+ it('keeps the skills earlier user turns selected and adds this turn’s', () => {
+ const history = [
+ { metadata: { selectedSkillIds: ['ux-audit'] }, role: 'user' },
+ { metadata: null, role: 'assistant' },
+ { metadata: { selectedSkillIds: ['agent-skills:review', 'ux-audit'] }, role: 'user' },
+ ];
+
+ expect(collectSelectedSkillIds(history, ['db-skill', 'ux-audit'])).toEqual([
+ 'ux-audit',
+ 'agent-skills:review',
+ 'db-skill',
+ ]);
+ });
+
+ it('ignores selections on non-user rows and malformed metadata', () => {
+ const history = [
+ { metadata: { selectedSkillIds: ['from-assistant'] }, role: 'assistant' },
+ { metadata: { selectedSkillIds: 'not-an-array' }, role: 'user' },
+ { metadata: { selectedSkillIds: [42, 'kept'] }, role: 'user' },
+ { role: 'user' },
+ ];
+
+ expect(collectSelectedSkillIds(history)).toEqual(['kept']);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts b/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts
new file mode 100644
index 00000000000..2def1dbe740
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/operationSkillSet.ts
@@ -0,0 +1,300 @@
+import { builtinSkills, LobeHubIdentifier } from '@lobechat/builtin-skills';
+import type { OperationSkillSet } from '@lobechat/context-engine';
+import { mentionsTopic } from '@lobechat/context-engine';
+import type { LobeChatDatabase } from '@lobechat/database';
+import { assembleSkillPool } from '@lobechat/mecha';
+import { resourcesTreePrompt } from '@lobechat/prompts';
+import { getActivePluginIds } from '@lobechat/types';
+import debug from 'debug';
+
+import type { AgentModel } from '@/database/models/agent';
+import { AgentSkillModel } from '@/database/models/agentSkill';
+import { TaskModel } from '@/database/models/task';
+import { isDeviceCapablePlan } from '@/helpers/executionTarget';
+import type { AgentDocumentsService } from '@/server/services/agentDocuments';
+import { readTaskSkillIds, UserSkillService } from '@/server/services/userSkill';
+
+import { filterSkillsByShareGate } from '../shareGate';
+import type { ExecRunContext, ResolvedWorkspaceInit } from '../types';
+import type { ToolDiscoveryResult } from './toolDiscovery';
+
+const log = debug('lobe-server:ai-agent-service');
+
+export interface OperationSkillSetDeps {
+ agentDocumentsService: AgentDocumentsService;
+ agentModel: AgentModel;
+ db: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}
+
+export interface OperationSkillSetInput {
+ activeDeviceId: ToolDiscoveryResult['activeDeviceId'];
+ agentConfig: ExecRunContext['agentConfig'];
+ agentPlugins: ToolDiscoveryResult['agentPlugins'];
+ /** Tri-state disabled plugin identifiers β€” excluded from the skill pool. */
+ disabledPluginIds: string[];
+ executionPlan: ToolDiscoveryResult['executionPlan'];
+ prompt: ExecRunContext['prompt'];
+ resolvedAgentId: ExecRunContext['resolvedAgentId'];
+ /**
+ * Skills the user selected in this topic, from this turn's request and the
+ * `metadata.selectedSkillIds` of earlier user turns (see
+ * {@link collectSelectedSkillIds}). Injected with their bodies like pinned skills.
+ */
+ selectedSkillIds: string[];
+ shareGate: ExecRunContext['shareGate'];
+ /** The Task this run executes; the skills it names are trusted for this run. */
+ taskId?: string;
+ workspaceInit: ResolvedWorkspaceInit;
+}
+
+/**
+ * The skills the user selected anywhere in this topic so far: the current
+ * request's selection plus every earlier user turn's persisted
+ * `metadata.selectedSkillIds`. Deduplicated, in first-selected order.
+ *
+ * Reading the history keeps a selected skill injected on later turns, which
+ * the client runtime achieves by persisting the skill body into the message.
+ */
+export const collectSelectedSkillIds = (
+ historyMessages: ReadonlyArray<{
+ metadata?: { selectedSkillIds?: unknown } | null;
+ role: string;
+ }>,
+ current: readonly string[] = [],
+): string[] => {
+ const ids: string[] = [];
+ for (const message of historyMessages) {
+ if (message.role !== 'user') continue;
+ const persisted = message.metadata?.selectedSkillIds;
+ if (!Array.isArray(persisted)) continue;
+ for (const id of persisted) if (typeof id === 'string') ids.push(id);
+ }
+ return [...new Set([...ids, ...current])];
+};
+
+/**
+ * Stage 18 of {@link AiAgentService.execAgent}: build the OperationSkillSet via SkillEngine.
+ *
+ * Combines builtin skills + user DB skills + agent-document skill bundles,
+ * filters by platform via enableChecker, and pairs with agent's enabled
+ * plugin IDs for downstream SkillResolver consumption.
+ *
+ * Returns `undefined` when any source fails to load; the run then proceeds
+ * without a skill set, as it did before this stage was extracted.
+ */
+export const buildOperationSkillSet = async (
+ deps: OperationSkillSetDeps,
+ input: OperationSkillSetInput,
+): Promise<OperationSkillSet | undefined> => {
+ const {
+ activeDeviceId,
+ agentConfig,
+ agentPlugins,
+ disabledPluginIds,
+ executionPlan,
+ prompt,
+ resolvedAgentId,
+ selectedSkillIds,
+ shareGate,
+ taskId,
+ workspaceInit,
+ } = input;
+
+ try {
+ const builtinMetas = builtinSkills.map((s) => ({
+ content: s.content,
+ description: s.description,
+ identifier: s.identifier,
+ name: s.name,
+ }));
+ const skillModel = new AgentSkillModel(deps.db, deps.userId, deps.workspaceId);
+ const { data: dbSkills } = await skillModel.findAll();
+
+ // Pinned skills need their SKILL.md body injected into context directly,
+ // not lazily via the `activateSkill` tool. Gate on the agent's genuinely
+ // pinned entries (`getActivePluginIds(agentConfig.plugins)`), NOT the
+ // fully-expanded `agentPlugins`: the latter also carries turn-scoped tool
+ // ids (mentions, selected tools, `lobe-message`, …), which would
+ // eager-activate an auto-mode skill whose identifier merely collides with
+ // one of them. `findAll` uses `skillListColumns` (no `content`), so fetch
+ // bodies only for the pinned subset to keep the op-param payload bounded.
+ // Non-pinned skills stay content-less here and remain lazily activatable.
+ // Content lives in the DB `content` column already (SKILL.md body), so no
+ // zip unpack is needed; mirror `activateSkill` by appending the resource
+ // tree so pinned ZIP/GitHub skills keep their `readReference` paths.
+ //
+ // Skills the user explicitly selected in this topic are injected the same
+ // way: the selection names them directly, so no tool id can collide into it.
+ const pinnedSkillIds = new Set(getActivePluginIds(agentConfig.plugins));
+ const injectedSkillIds = new Set([...pinnedSkillIds, ...selectedSkillIds]);
+ const pinnedDbSkillIds = dbSkills
+ .filter((s) => injectedSkillIds.has(s.identifier))
+ .map((s) => s.id);
+ const pinnedDbContent = new Map(
+ (await skillModel.findByIds(pinnedDbSkillIds)).map((s) => {
+ const hasResources = !!(s.resources && Object.keys(s.resources).length > 0);
+ const content =
+ hasResources && s.resources
+ ? `${s.content ?? ''}\n\n${resourcesTreePrompt(s.name, s.resources)}`
+ : (s.content ?? undefined);
+ return [s.identifier, content] as const;
+ }),
+ );
+ const dbMetas = dbSkills.map((s) => ({
+ content: pinnedDbContent.get(s.identifier),
+ description: s.description ?? '',
+ identifier: s.identifier,
+ name: s.name,
+ }));
+
+ // Agent-document skill bundles surfaced as runtime skills via the shared
+ // `getAgentSkills` source of truth (prefix + index-child resolution lives
+ // there; see `AgentDocumentsService.getAgentSkills`). Identifier is
+ // prefixed (`agent-skills:<filename>`) so it can't collide with builtin
+ // / DB skill names, and we re-use it as `name` so the prompt's
+ // `<skill name="...">` line and the model's `activateSkill(name)` call
+ // carry the same value.
+ const agentSkills = await deps.agentDocumentsService.getAgentSkills(resolvedAgentId);
+ const agentSkillMetas = agentSkills.map((skill) => ({
+ // `getAgentSkills` already resolves the bundle body, so pinned
+ // agent-document skills inject directly without an extra fetch; only
+ // attach it for the pinned subset to keep the payload lean.
+ content: injectedSkillIds.has(skill.identifier) ? skill.content : undefined,
+ description: skill.description,
+ identifier: skill.identifier,
+ name: skill.name,
+ }));
+
+ // The user's own skill library: listed to every run, and injected up front
+ // when the agent pins one or the run names it in its plugins β€” a goal
+ // batch's unit runs name the batch's plan skill that way.
+ // The catalog carries no bodies; only the pinned / run-named skills read
+ // theirs, so a library that grows with every batch stays cheap to list.
+ // A workspace-public agent never reads its caller's private skills β€” every
+ // user skill is private β€” so its runs see none of them.
+ const userSkills = new UserSkillService(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ deps.workspaceId ? await deps.agentModel.getAgentVisibility(resolvedAgentId) : undefined,
+ );
+ // The skills the run's own Task names (a goal batch's plan) load even
+ // through a public agent β€” and only those; nothing the model or a picker
+ // supplies widens that.
+ const taskSkillIds = taskId
+ ? readTaskSkillIds(
+ (await new TaskModel(deps.db, deps.userId, deps.workspaceId).findById(taskId))?.config,
+ )
+ : [];
+ const namedUserSkills = await userSkills.loadRuntimeSkills(
+ [...injectedSkillIds, ...(agentPlugins ?? []), ...taskSkillIds],
+ { trustedGenerated: taskSkillIds },
+ );
+ // Skills the system generated for one job (a goal batch's plan) are not
+ // listed to every run β€” one accumulates per batch, so the query leaves them
+ // out β€” only joined where the run pins or names them, as that batch's units
+ // do. Those come in with their bodies.
+ const listed = await userSkills.listCatalog({ includeGenerated: false });
+ const listedIds = new Set(listed.map((skill) => skill.identifier));
+ const namedContent = new Map(
+ namedUserSkills.map((skill) => [skill.identifier, skill.content] as const),
+ );
+ const userSkillMetas = [
+ ...listed.map((skill) => ({
+ content: namedContent.get(skill.identifier),
+ description: skill.description,
+ identifier: skill.identifier,
+ name: skill.name,
+ })),
+ ...namedUserSkills
+ .filter((skill) => !listedIds.has(skill.identifier))
+ .map((skill) => ({
+ content: skill.content,
+ description: skill.description,
+ identifier: skill.identifier,
+ name: skill.name,
+ })),
+ ];
+
+ const projectMetas = workspaceInit.workspace.skills.map((s) => ({
+ description: s.description ?? '',
+ identifier: `${s.scope === 'device' ? 'device' : 'project'}:${s.name}`,
+ location: s.path,
+ name: s.name,
+ source: s.scope === 'device' ? ('device' as const) : ('project' as const),
+ }));
+
+ if (projectMetas.length) {
+ log(
+ 'execAgent: workspace skills merged: %d (activeDeviceId=%s)',
+ projectMetas.length,
+ activeDeviceId ?? 'none',
+ );
+ }
+
+ // Precedence, name dedupe, the disabled drop, the share allowlist and the
+ // device-only builtin gate are the shared rules in `@lobechat/mecha`; this
+ // pipeline supplies the four sources and the run's facts.
+ //
+ // A shared run only sees skills its share configuration allows β€”
+ // `shareConfig.skillGrants`, the creator's explicit per-skill list, NOT the
+ // tool picker (`filterSkillsByShareGate`). The pool is the FIRST
+ // enforcement point, not the only one: `activateSkill` takes a
+ // model-supplied name, so the skill runtime re-checks the same grant at
+ // load time.
+ const shareAllowedSkillIds = shareGate
+ ? filterSkillsByShareGate(
+ [...projectMetas, ...dbMetas, ...agentSkillMetas, ...userSkillMetas, ...builtinMetas].map(
+ (skill) => skill.identifier,
+ ),
+ shareGate,
+ )
+ : undefined;
+
+ // Whether a skill is PINNED is the agent's own configuration; the share
+ // only decides whether the visitor may reach it. `agentPlugins` has already
+ // been narrowed by the TOOL grants (`filterPluginsByShareGate` in
+ // `toolDiscovery`), which drops a skill the creator granted as a skill
+ // rather than as a tool β€” leaving it un-pinned for the visitor (no content
+ // injection) and, under `manual` mode, dropped from the pool entirely. Add
+ // back exactly the ids that are both genuinely pinned on the agent AND
+ // allowed by this share's skill grants; nothing else widens.
+ const shareEnabledSkillIds = shareAllowedSkillIds?.filter((id) => pinnedSkillIds.has(id)) ?? [];
+
+ // Device-only builtin skills are gated on the run's execution plan, not
+ // the compile-time `isDesktop` constant (always false on the server). Use
+ // the device-CAPABLE plan rather than `activeDeviceId`: a
+ // `device-unrouted` run lets the model pick a device mid-run, and this
+ // skill set is built once per operation, so gating on the routed device
+ // would hide the skill forever in those runs. Activation and loading
+ // apply the same plan gate via `ToolExecutionContext.deviceCapable`; only
+ // command execution is gated at the device tool layer.
+ return assembleSkillPool(
+ {
+ agentSkills: [...agentSkillMetas, ...userSkillMetas],
+ builtin: builtinMetas,
+ db: dbMetas,
+ project: projectMetas,
+ },
+ {
+ canExecuteOnDevice: executionPlan ? isDeviceCapablePlan(executionPlan) : false,
+ disabledIds: disabledPluginIds,
+ // Selected skills join the enabled set so the resolver auto-activates
+ // them; a share allowlist or a disabled entry still drops them above.
+ enabledPluginIds: [
+ ...new Set([...(agentPlugins ?? []), ...shareEnabledSkillIds, ...selectedSkillIds]),
+ ],
+ shareAllowedIds: shareAllowedSkillIds,
+ skillActivateMode: agentConfig.chatConfig?.skillActivateMode,
+ // Reading another topic (`<refer_topic>` or a raw `tpc_` id) goes through `lh topic view`,
+ // which the lobehub skill teaches.
+ turnSkillIds: mentionsTopic([{ content: prompt ?? '' }]) ? [LobeHubIdentifier] : [],
+ },
+ );
+ } catch (error) {
+ log('execAgent: failed to build operationSkillSet: %O', error);
+ return undefined;
+ }
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 036d4a1dd01..208f27dfa90 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -9,12 +9,12 @@ import type {
FileAccessScope,
HeterogeneousProviderConfig,
HeterogeneousTopicPin,
+ RequestTrigger,
} from '@lobechat/types';
import {
agentShareFileAccessScope,
ChatErrorType,
ordinaryFileAccessScope,
- RequestTrigger,
resolveHeterogeneousProviderTopicModel,
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
@@ -42,6 +42,7 @@ import { reserveShareVisitorTopic, reserveShareVisitorTurn } from '../shareVisit
import type { InternalExecAgentParams } from '../types';
import { createUserTurnAnchor } from './resolveUserMessageParentId';
import { createStageTracer, openStageMark } from './sendTracing';
+import { buildUserTurnMetadata } from './userTurnMetadata';
const log = debug('lobe-server:ai-agent-service');
@@ -350,6 +351,8 @@ export interface TurnSetupInput {
/** Raw resume flag β€” a resume run must land on an existing topic. */
resume?: boolean;
runFromHistory: boolean;
+ /** Skills the user selected for this turn; see `ExecAgentParams.selectedSkillIds`. */
+ selectedSkillIds?: string[];
/** Shared-agent visitor gate β€” set only by the shareChat router. */
shareGate?: AgentShareGate;
/** The prompt was queued behind a running turn; see `ExecAgentParams.steer`. */
@@ -438,6 +441,7 @@ export const setupTurn = async (
resolvedAgentId,
resume,
runFromHistory,
+ selectedSkillIds,
shareGate,
steer,
throwIfExecutionAborted,
@@ -799,22 +803,14 @@ export const setupTurn = async (
const heteroType = (heteroProviderType ?? model) as HeterogeneousAgentType;
// ── Shared turn setup (runs for BOTH hetero and normal agents) ──────────
- const requestTriggerMetadata = {
- ...(trigger && Object.values(RequestTrigger).includes(trigger as RequestTrigger)
- ? { trigger: trigger as RequestTrigger }
- : undefined),
- ...(appContext?.conversationAgentId && appContext.scope === 'sub_agent'
- ? { agentDispatch: { kind: 'callAgent' as const, visibility: 'internal' as const } }
- : undefined),
- // Bot-channel turns are inserted under the OWNER's userId; keep the real
- // platform author alongside so the UI can attribute the bubble correctly.
- ...(botSender ? { botSender } : undefined),
- // A provider event that injected this turn keeps its source on the row.
- ...(externalOrigin ? { externalOrigin } : undefined),
- // A follow-up queued behind a running turn renders as that turn's
- // continuation; the client's optimistic row is replaced by this one.
- ...(steer ? { steer: true as const } : undefined),
- };
+ const requestTriggerMetadata = buildUserTurnMetadata({
+ appContext,
+ botSender,
+ externalOrigin,
+ selectedSkillIds,
+ steer,
+ trigger,
+ });
// Attachment ingestion: raw bot/IM `files` β†’ S3, pre-uploaded
// `attachedFileIds` β†’ signed URLs + classification.
diff --git a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.test.ts b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.test.ts
new file mode 100644
index 00000000000..d4a5b7dbdf7
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.test.ts
@@ -0,0 +1,32 @@
+import { RequestTrigger } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { buildUserTurnMetadata } from './userTurnMetadata';
+
+describe('buildUserTurnMetadata', () => {
+ it('stores only the trigger for an ordinary chat turn', () => {
+ expect(buildUserTurnMetadata({ trigger: RequestTrigger.Chat })).toEqual({
+ trigger: RequestTrigger.Chat,
+ });
+ });
+
+ it('drops a trigger outside RequestTrigger', () => {
+ expect(buildUserTurnMetadata({ trigger: 'not-a-trigger' })).toEqual({});
+ });
+
+ it('persists the selected skills once each, so later turns can read them back', () => {
+ expect(
+ buildUserTurnMetadata({
+ selectedSkillIds: ['ux-audit', 'agent-skills:review', 'ux-audit'],
+ trigger: RequestTrigger.Chat,
+ }),
+ ).toEqual({
+ selectedSkillIds: ['ux-audit', 'agent-skills:review'],
+ trigger: RequestTrigger.Chat,
+ });
+ });
+
+ it('omits an empty skill selection', () => {
+ expect(buildUserTurnMetadata({ selectedSkillIds: [] })).not.toHaveProperty('selectedSkillIds');
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts
new file mode 100644
index 00000000000..e7f324c7b3b
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts
@@ -0,0 +1,44 @@
+import { RequestTrigger } from '@lobechat/types';
+
+import type { InternalExecAgentParams } from '../types';
+
+export interface UserTurnMetadataInput {
+ appContext?: InternalExecAgentParams['appContext'];
+ botSender?: InternalExecAgentParams['botSender'];
+ externalOrigin?: InternalExecAgentParams['externalOrigin'];
+ selectedSkillIds?: string[];
+ steer?: boolean;
+ trigger?: string;
+}
+
+/**
+ * Metadata persisted on the user message a send creates, derived from the
+ * request. Each field is present only when the request carries it, so an
+ * ordinary chat turn stores no more than `trigger`.
+ */
+export const buildUserTurnMetadata = ({
+ appContext,
+ botSender,
+ externalOrigin,
+ selectedSkillIds,
+ steer,
+ trigger,
+}: UserTurnMetadataInput) => ({
+ ...(trigger && Object.values(RequestTrigger).includes(trigger as RequestTrigger)
+ ? { trigger: trigger as RequestTrigger }
+ : undefined),
+ ...(appContext?.conversationAgentId && appContext.scope === 'sub_agent'
+ ? { agentDispatch: { kind: 'callAgent' as const, visibility: 'internal' as const } }
+ : undefined),
+ // Bot-channel turns are inserted under the OWNER's userId; keep the real
+ // platform author alongside so the UI can attribute the bubble correctly.
+ ...(botSender ? { botSender } : undefined),
+ // A provider event that injected this turn keeps its source on the row.
+ ...(externalOrigin ? { externalOrigin } : undefined),
+ // A follow-up queued behind a running turn renders as that turn's
+ // continuation; the client's optimistic row is replaced by this one.
+ ...(steer ? { steer: true as const } : undefined),
+ // Later turns read the selection back from history, so the skills stay
+ // injected for the rest of the topic (see `collectSelectedSkillIds`).
+ ...(selectedSkillIds?.length ? { selectedSkillIds: [...new Set(selectedSkillIds)] } : undefined),
+});
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index a503b2101a2..c30c2ad5070 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -258,6 +258,13 @@ export interface InternalExecAgentParams extends ExecAgentParams {
rejectionReason?: string;
toolCallId: string;
};
+ /**
+ * Skill identifiers the user selected for this message. Persisted on the
+ * user message (`metadata.selectedSkillIds`) and, together with the ones
+ * earlier turns of the topic selected, injected with their bodies like a
+ * pinned skill. Never widens what the skill pool already allows.
+ */
+ selectedSkillIds?: string[];
/**
* Tool identifiers the user @-mentioned in this message. Merged into the
* agent's plugin set for this run (alongside `additionalPluginIds`) so a
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index d7450ea1d85..80d2a7b4eac 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -287,6 +287,7 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche
performance: ModelPerformanceSchema.optional(),
reactions: z.array(EmojiReactionSchema).optional(),
scope: z.string().optional(),
+ selectedSkillIds: z.array(z.string()).optional(),
// External-signal lineage for Monitor-style callback turns ().
signal: MessageSignalSchema.optional(),
steer: z.boolean().optional(),
@@ -523,6 +524,11 @@ export interface MessageMetadata {
* See MessageMapScope for available values
*/
scope?: string;
+ /**
+ * Skills the user selected for this user turn, injected with their bodies
+ * on this and every later turn of the topic by the server runtime.
+ */
+ selectedSkillIds?: string[];
/**
* External-signal lineage for messages produced as reactive replies
* to an out-of-band trigger (Monitor stdout push, webhook callback,
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index b7976d42d56..d1be78c0d25 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -172,6 +172,8 @@ export interface ExecAgentTaskParams {
resumeApprovals?: ResumeApprovalParam[];
/** Resume a previous op paused on a human-intervention tool by carrying the human answer as the tool result. */
resumeToolResult?: ResumeToolResultParam;
+ /** Skill identifiers the user selected in this message; the server injects their bodies. */
+ selectedSkillIds?: string[];
/** Tool identifiers the user @-mentioned in this message; the server enables them for this run. */
selectedToolIds?: string[];
slug?: string;
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewaySkills.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewaySkills.test.ts
new file mode 100644
index 00000000000..2cf8dbeae37
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewaySkills.test.ts
@@ -0,0 +1,153 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { getSessionStoreState } from '@/store/session';
+import * as toolStoreModule from '@/store/tool';
+import { useUserStore } from '@/store/user';
+
+import { useChatStore } from '../../../../store';
+import { createMockAgentConfig, TEST_IDS } from './fixtures';
+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
+
+vi.mock('../transports/hetero/heterogeneousAgentExecutor', () => ({
+ executeHeterogeneousAgent: vi.fn(),
+}));
+
+vi.mock('@/store/tool/slices/builtin/loadBuiltinSkills', () => ({
+ loadBuiltinSkill: async (identifier: string) =>
+ toolStoreModule
+ .getToolStoreState()
+ .builtinSkills.find((skill: any) => skill.identifier === identifier),
+ loadBuiltinSkills: async () => toolStoreModule.getToolStoreState().builtinSkills,
+}));
+
+// Mock lambdaClient to prevent network requests
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ session: {
+ updateSession: {
+ mutate: vi.fn().mockResolvedValue(undefined),
+ },
+ },
+ },
+}));
+
+beforeEach(() => {
+ resetTestEnvironment();
+ setupMockSelectors();
+ spyOnMessageService();
+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);
+ useUserStore.setState({ workspaceUserPreference: {} });
+
+ act(() => {
+ useChatStore.setState({
+ executeClientAgent: vi.fn(),
+ mainInputEditor: null,
+ refreshMessages: vi.fn(),
+ refreshTopic: vi.fn(),
+ });
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+const skillTag = (actionType: string, actionLabel: string) => ({
+ actionCategory: 'skill',
+ actionLabel,
+ actionType,
+ type: 'action-tag',
+});
+
+describe('sendMessage in gateway mode', () => {
+ // ROOT CAUSE:
+ //
+ // In gateway mode, a skill picked in the composer reached the server only as
+ // `<skill name="…" />` text in the prompt, because the gateway request carried
+ // tool and agent mentions but no skill field.
+ //
+ // Before the fix, the server run never injected the skill body.
+ // The fix forwards the picks as `selectedSkillIds`.
+ it('forwards the selected skills so the server injects their bodies', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ operationId: 'op-skill',
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ });
+
+ vi.spyOn(toolStoreModule, 'getToolStoreState').mockReturnValue({
+ agentSkillDetailMap: {},
+ agentSkills: [],
+ builtinSkills: [
+ {
+ content: 'Audit the page for UX issues.',
+ description: 'UX audit',
+ identifier: 'ux-audit',
+ name: 'UX Audit',
+ source: 'builtin',
+ },
+ ],
+ } as any);
+ act(() => {
+ useChatStore.setState({
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId: TEST_IDS.SESSION_ID, threadId: null, topicId: null },
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ skillTag('ux-audit', 'UX Audit'),
+ { text: ' review the page', type: 'text' },
+ skillTag('ux-audit', 'UX Audit'),
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ },
+ message: '<skill name="ux-audit" label="UX Audit" /> review the page',
+ });
+ });
+
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ selectedSkillIds: ['ux-audit'] }),
+ );
+ });
+
+ it('sends no skill field when nothing was selected', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ operationId: 'op-plain',
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ });
+
+ act(() => {
+ useChatStore.setState({
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId: TEST_IDS.SESSION_ID, threadId: null, topicId: null },
+ message: 'review the page',
+ });
+ });
+
+ expect(executeGatewayAgentSpy.mock.calls[0][0].selectedSkillIds).toBeUndefined();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 2b04e42ce91..980d965e929 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -1921,6 +1921,10 @@ export class ConversationLifecycleActionImpl {
// selection (only the client runtime did). Omit when empty.
selectedToolIds:
selectedTools.length > 0 ? selectedTools.map((tool) => tool.identifier) : undefined,
+ // Forward selected skills so the server injects their bodies, as the
+ // client runtime does by persisting them into the message content.
+ selectedSkillIds:
+ selectedSkills.length > 0 ? selectedSkills.map((skill) => skill.identifier) : undefined,
// Forward @-mentioned agents so the server supervisor can delegate to
// them (multi-mention). Mirrors the client runtime's `initialContext`
// injection: the server enables the callAgent tool and injects the
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 74f29706a85..abfc9a853d3 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -1105,6 +1105,8 @@ export class GatewayActionImpl {
* `phase: 'tool_result'` WITHOUT re-executing the tool.
*/
resumeToolResult?: ResumeToolResultParam;
+ /** Skills the user selected in this message; forwarded as `selectedSkillIds`. */
+ selectedSkillIds?: string[];
/**
* Tool identifiers the user @-mentioned in this message. Forwarded to the
* server as `selectedToolIds` so the server runtime enables them for this
@@ -1150,6 +1152,7 @@ export class GatewayActionImpl {
resumeApproval,
resumeApprovals,
resumeToolResult,
+ selectedSkillIds,
selectedToolIds,
mentionedAgents,
tempMessageIds,
@@ -1343,6 +1346,7 @@ export class GatewayActionImpl {
resumeApproval,
resumeApprovals,
resumeToolResult,
+ selectedSkillIds,
selectedToolIds,
// A queued follow-up keeps its continuation mark on the row the
// server persists, which replaces the optimistic one.