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: add lobehub skill (#12922)

Arvin Xu2399f672e213
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 47de3d38985..8abc4645d6d 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -192,12 +192,12 @@
"builtins.lobe-skill-store.render.repository": "Repository",
"builtins.lobe-skill-store.render.version": "Version",
"builtins.lobe-skill-store.title": "Skill Store",
+ "builtins.lobe-skills.apiName.activateSkill": "Activate Skill",
"builtins.lobe-skills.apiName.execScript": "Run Script",
"builtins.lobe-skills.apiName.exportFile": "Export File",
"builtins.lobe-skills.apiName.importFromMarket": "Import from Market",
"builtins.lobe-skills.apiName.importSkill": "Import Skill",
"builtins.lobe-skills.apiName.readReference": "Read Reference",
- "builtins.lobe-skills.apiName.runSkill": "Activate Skill",
"builtins.lobe-skills.apiName.searchSkill": "Search Skills",
"builtins.lobe-skills.title": "Skills",
"builtins.lobe-tools.apiName.activateTools": "Activate Tools",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 6dfa3149bb2..c2b1b20e402 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -188,12 +188,12 @@
"builtins.lobe-skill-store.apiName.importSkill": "导入技能",
"builtins.lobe-skill-store.apiName.searchSkill": "搜索技能",
"builtins.lobe-skill-store.title": "技能商店",
+ "builtins.lobe-skills.apiName.activateSkill": "激活技能",
"builtins.lobe-skills.apiName.execScript": "执行脚本",
"builtins.lobe-skills.apiName.exportFile": "导出文件",
"builtins.lobe-skills.apiName.importFromMarket": "从市场导入",
"builtins.lobe-skills.apiName.importSkill": "导入技能",
"builtins.lobe-skills.apiName.readReference": "读取参考资料",
- "builtins.lobe-skills.apiName.runSkill": "激活技能",
"builtins.lobe-skills.apiName.searchSkill": "搜索技能",
"builtins.lobe-skills.title": "技能",
"builtins.lobe-tools.apiName.activateTools": "激活工具",
diff --git a/packages/builtin-skills/src/index.ts b/packages/builtin-skills/src/index.ts
index c754db05157..6f2975aea1b 100644
--- a/packages/builtin-skills/src/index.ts
+++ b/packages/builtin-skills/src/index.ts
@@ -2,12 +2,15 @@ import type { BuiltinSkill } from '@lobechat/types';
import { AgentBrowserSkill } from './agent-browser';
import { ArtifactsSkill } from './artifacts';
+import { LobeHubSkill } from './lobehub';
export { AgentBrowserIdentifier } from './agent-browser';
export { ArtifactsIdentifier } from './artifacts';
+export { LobeHubIdentifier } from './lobehub';
export const builtinSkills: BuiltinSkill[] = [
AgentBrowserSkill,
ArtifactsSkill,
+ LobeHubSkill,
// FindSkillsSkill
];
diff --git a/packages/builtin-skills/src/lobehub/content.ts b/packages/builtin-skills/src/lobehub/content.ts
new file mode 100644
index 00000000000..4015f79994b
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/content.ts
@@ -0,0 +1,57 @@
+export const systemPrompt = `<lobehub_platform_guides>
+You can manage the LobeHub platform via the \`lh\` CLI. Use the \`runCommand\` tool to run commands.
+
+# Available Modules
+
+| Module | Description |
+|--------|-------------|
+| \`lh kb\` | Knowledge base management (create, upload, organize) |
+| \`lh memory\` | User memory management (identity, activity, preference) |
+| \`lh topic\` | Conversation topic management |
+| \`lh file\` | File management |
+| \`lh doc\` | Document management (create, parse, organize) |
+| \`lh agent\` | Agent management (create, configure, run) |
+| \`lh search\` | Search local resources or the web |
+| \`lh gen\` | Content generation (text, image, video, TTS, ASR) |
+| \`lh message\` | Message management and search |
+| \`lh skill\` | Skill management (install, create, manage) |
+| \`lh model\` | AI model management |
+| \`lh provider\` | AI provider management |
+| \`lh plugin\` | Plugin management |
+| \`lh bot\` | Bot integration management (Discord, Slack, Telegram, etc.) |
+| \`lh eval\` | Evaluation workflow management |
+| \`lh config\` | User info and usage statistics |
+
+# Usage Pattern
+
+1. Read the reference file for the relevant module to learn detailed commands
+2. Run commands via \`runCommand\` — the \`lh\` prefix is automatically handled
+3. Use \`--json\` flag on any command for structured output
+4. Use \`lh <module> --help\` for full command-line help
+
+# Examples
+
+\`\`\`bash
+# List knowledge bases
+lh kb list
+
+# Create a document in a knowledge base
+lh kb create-doc <kbId> -t "Meeting Notes" -c "..."
+
+# Search messages
+lh message search "deployment issue"
+
+# Generate an image
+lh gen image "a sunset over mountains" -m dall-e-3
+
+# Run an agent
+lh agent run -a <agentId> -p "Summarize today's tasks"
+\`\`\`
+
+# Important Notes
+
+- All commands support \`--json\` for machine-readable output
+- Use \`--yes\` to skip confirmation prompts on destructive operations
+- IDs can be found via \`list\` commands
+- For detailed usage of any module, read its reference file using \`readReference\`
+</lobehub_platform_guides>`;
diff --git a/packages/builtin-skills/src/lobehub/helpers.ts b/packages/builtin-skills/src/lobehub/helpers.ts
new file mode 100644
index 00000000000..ad6865ee722
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/helpers.ts
@@ -0,0 +1,19 @@
+import type { SkillResourceMeta } from '@lobechat/types';
+
+/**
+ * Convert a simple path→content map to Record<string, SkillResourceMeta>.
+ */
+export const toResourceMeta = (
+ resources: Record<string, string>,
+): Record<string, SkillResourceMeta> => {
+ return Object.fromEntries(
+ Object.entries(resources).map(([path, content]) => [
+ path,
+ {
+ content,
+ fileHash: '',
+ size: new TextEncoder().encode(content).length,
+ },
+ ]),
+ );
+};
diff --git a/packages/builtin-skills/src/lobehub/index.ts b/packages/builtin-skills/src/lobehub/index.ts
new file mode 100644
index 00000000000..f26832b04f5
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/index.ts
@@ -0,0 +1,49 @@
+import { type BuiltinSkill } from '@lobechat/types';
+
+import { systemPrompt } from './content';
+import { toResourceMeta } from './helpers';
+import agent from './references/agent';
+import bot from './references/bot';
+import config from './references/config';
+import doc from './references/doc';
+import eval_ from './references/eval';
+import file from './references/file';
+import generate from './references/generate';
+import kb from './references/kb';
+import memory from './references/memory';
+import message from './references/message';
+import model from './references/model';
+import plugin from './references/plugin';
+import provider from './references/provider';
+import search from './references/search';
+import skill from './references/skill';
+import topic from './references/topic';
+
+export const LobeHubIdentifier = 'lobehub';
+
+export const LobeHubSkill: BuiltinSkill = {
+ content: systemPrompt,
+ description:
+ 'Manage the LobeHub platform via CLI — knowledge bases, memory, agents, files, search, generation, and more.',
+ identifier: LobeHubIdentifier,
+ name: 'LobeHub',
+ resources: toResourceMeta({
+ 'references/agent': agent,
+ 'references/bot': bot,
+ 'references/config': config,
+ 'references/doc': doc,
+ 'references/eval': eval_,
+ 'references/file': file,
+ 'references/generate': generate,
+ 'references/kb': kb,
+ 'references/memory': memory,
+ 'references/message': message,
+ 'references/model': model,
+ 'references/plugin': plugin,
+ 'references/provider': provider,
+ 'references/search': search,
+ 'references/skill': skill,
+ 'references/topic': topic,
+ }),
+ source: 'builtin',
+};
diff --git a/packages/builtin-skills/src/lobehub/references/agent.ts b/packages/builtin-skills/src/lobehub/references/agent.ts
new file mode 100644
index 00000000000..6b4d91132f9
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/agent.ts
@@ -0,0 +1,23 @@
+const content = `# lh agent - Agent Management
+
+Manage agents (AI assistants with custom configurations).
+
+## Subcommands
+
+- \`lh agent list [-L <limit>] [-k <keyword>]\` - List agents
+- \`lh agent view [agentId] [-s <slug>]\` - View agent configuration
+- \`lh agent create -t <title> [-d <description>] [-m <model>] [-p <provider>] [-s <systemRole>]\` - Create agent
+- \`lh agent edit [agentId] [-t <title>] [-d <description>] [-m <model>] [-s <systemRole>]\` - Update agent
+- \`lh agent delete <agentId> [--yes]\` - Delete agent
+- \`lh agent duplicate <agentId> [-t <title>]\` - Duplicate agent
+- \`lh agent run -a <agentId> -p <prompt> [-t <topicId>] [--replay]\` - Run agent with a prompt
+- \`lh agent status <operationId> [--history]\` - Check agent operation status
+
+## Tips
+
+- Use \`--slug\` to reference agents by slug instead of ID
+- \`lh agent run --replay\` replays the full conversation output
+- \`lh agent status --history\` shows operation execution history
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/bot.ts b/packages/builtin-skills/src/lobehub/references/bot.ts
new file mode 100644
index 00000000000..be98c945b36
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/bot.ts
@@ -0,0 +1,26 @@
+const content = `# lh bot - Bot Integration Management
+
+Manage bot integrations that connect agents to messaging platforms.
+
+## Supported Platforms
+
+Discord, Slack, Telegram, Lark, Feishu
+
+## Subcommands
+
+- \`lh bot list [-a <agentId>] [--platform <p>]\` - List bot integrations
+- \`lh bot view <botId> [-a <agentId>]\` - View bot details
+- \`lh bot add -a <agentId> --platform <p> [--bot-token <t>] [--app-id <id>]\` - Add bot to agent
+- \`lh bot update <botId> [--bot-token <t>] [--platform <p>]\` - Update bot credentials
+- \`lh bot remove <botId> [--yes]\` - Remove bot integration
+- \`lh bot enable <botId>\` - Enable bot
+- \`lh bot disable <botId>\` - Disable bot
+- \`lh bot connect <botId> [-a <agentId>]\` - Connect and start bot
+
+## Tips
+
+- Each platform requires specific credentials (token, app ID, secrets)
+- Use \`lh bot connect\` to start a long-running bot connection
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/config.ts b/packages/builtin-skills/src/lobehub/references/config.ts
new file mode 100644
index 00000000000..3eae85fd26c
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/config.ts
@@ -0,0 +1,16 @@
+const content = `# lh config - User Info and Usage
+
+View account information and usage statistics.
+
+## Subcommands
+
+- \`lh config whoami\` - Display current user information
+- \`lh config usage [--month <YYYY-MM>] [--daily]\` - View token usage statistics
+
+## Tips
+
+- \`whoami\` shows user ID, email, and account details
+- \`usage --daily\` shows a daily breakdown with heatmap
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/doc.ts b/packages/builtin-skills/src/lobehub/references/doc.ts
new file mode 100644
index 00000000000..c9bf93ed6fb
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/doc.ts
@@ -0,0 +1,23 @@
+const content = `# lh doc - Document Management
+
+Manage documents (text content that can be standalone or in knowledge bases).
+
+## Subcommands
+
+- \`lh doc list [-L <limit>] [--file-type <type>] [--source-type <type>]\` - List documents
+- \`lh doc view <id>\` - View document content
+- \`lh doc create -t <title> -b <body> [--kb <kbId>] [--parent <folderId>]\` - Create document
+- \`lh doc batch-create <jsonFile>\` - Batch create documents from JSON file
+- \`lh doc edit <id> [-t <title>] [-b <body>]\` - Edit document
+- \`lh doc delete <ids...> [--yes]\` - Delete documents
+- \`lh doc parse <fileId> [--with-pages]\` - Parse uploaded file into document
+- \`lh doc link-topic <docId> <topicId>\` - Associate document with topic
+- \`lh doc topic-docs <topicId> [--type <type>]\` - List documents for a topic
+
+## Tips
+
+- Use \`-F <filePath>\` instead of \`-b\` to read body content from a file
+- \`lh doc parse\` extracts text from uploaded files (PDF, DOCX, etc.)
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/eval.ts b/packages/builtin-skills/src/lobehub/references/eval.ts
new file mode 100644
index 00000000000..19213d76e70
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/eval.ts
@@ -0,0 +1,22 @@
+const content = `# lh eval - Evaluation Workflow Management
+
+Manage external evaluation workflows for testing agent quality.
+
+## Subcommands
+
+- \`lh eval run get --run-id <id>\` - Get run information
+- \`lh eval run set-status --run-id <id> --status <completed|external>\` - Set run status
+- \`lh eval dataset get --dataset-id <id>\` - Get dataset information
+- \`lh eval run-topics list --run-id <id> [--only-external]\` - List topics in a run
+- \`lh eval threads list --topic-id <id>\` - List threads by topic
+- \`lh eval messages list --topic-id <id> [--thread-id <id>]\` - List messages
+- \`lh eval test-cases count --dataset-id <id>\` - Count test cases
+- \`lh eval run-topic report-result --run-id <id> --topic-id <id> --score <n>\` - Report result
+
+## Tips
+
+- Evaluation runs test agent responses against datasets
+- Use \`report-result\` to submit scores for individual topics
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/file.ts b/packages/builtin-skills/src/lobehub/references/file.ts
new file mode 100644
index 00000000000..3fab63924f8
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/file.ts
@@ -0,0 +1,18 @@
+const content = `# lh file - File Management
+
+Manage uploaded files.
+
+## Subcommands
+
+- \`lh file list [--kb-id <id>] [-L <limit>]\` - List files (optionally filter by knowledge base)
+- \`lh file view <id>\` - View file details
+- \`lh file delete <ids...> [--yes]\` - Delete one or more files
+- \`lh file recent [-L <limit>]\` - List recently accessed files
+
+## Tips
+
+- Files can be associated with knowledge bases
+- Use \`lh kb upload\` to upload new files to a knowledge base
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/generate.ts b/packages/builtin-skills/src/lobehub/references/generate.ts
new file mode 100644
index 00000000000..85c4da514ed
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/generate.ts
@@ -0,0 +1,23 @@
+const content = `# lh gen - Content Generation
+
+Generate text, images, videos, and audio. Alias: \`lh generate\`.
+
+## Subcommands
+
+- \`lh gen text <prompt> [-m <model>] [-p <provider>] [--stream] [--temperature <t>]\` - Generate text
+- \`lh gen image <prompt> [-m <model>] [-n <count>] [--width <w>] [--height <h>]\` - Generate image
+- \`lh gen video <prompt> [-m <model>] [--aspect-ratio <r>] [--duration <d>]\` - Generate video
+- \`lh gen tts <text> [-o <output>] [--voice <v>] [--speed <s>]\` - Text-to-speech
+- \`lh gen asr <audioFile> [--model <m>] [--language <l>]\` - Speech-to-text
+- \`lh gen status <generationId> <taskId>\` - Check generation task status
+- \`lh gen download <generationId> <taskId> [-o <output>]\` - Wait and download result
+- \`lh gen list\` - List generation topics
+
+## Tips
+
+- Image/video generation is async; use \`status\` or \`download\` to get results
+- \`--stream\` for text generation outputs tokens as they arrive
+- \`--pipe\` for text generation outputs only the raw text (no formatting)
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/kb.ts b/packages/builtin-skills/src/lobehub/references/kb.ts
new file mode 100644
index 00000000000..3971ac646f1
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/kb.ts
@@ -0,0 +1,26 @@
+const content = `# lh kb - Knowledge Base Management
+
+Manage knowledge bases, folders, documents, and files.
+
+## Subcommands
+
+- \`lh kb list\` - List all knowledge bases
+- \`lh kb view <id>\` - View KB with all items in tree structure
+- \`lh kb create -n <name> [-d <description>]\` - Create a knowledge base
+- \`lh kb edit <id> [-n <name>] [-d <description>]\` - Update KB metadata
+- \`lh kb delete <id> [--remove-files] [--yes]\` - Delete a knowledge base
+- \`lh kb add-files <kbId> --ids <fileId1,fileId2>\` - Add files to KB
+- \`lh kb remove-files <kbId> --ids <fileId1,fileId2>\` - Remove files from KB
+- \`lh kb mkdir <kbId> -n <name> [--parent <folderId>]\` - Create a folder
+- \`lh kb create-doc <kbId> -t <title> -c <content> [--parent <folderId>]\` - Create a document in KB
+- \`lh kb move <id> --parent <folderId> --type <file|doc>\` - Move file/document to folder
+- \`lh kb upload <kbId> <filePath> [--parent <folderId>]\` - Upload file to KB
+
+## Tips
+
+- Use \`--json\` on any subcommand for structured output
+- \`lh kb view\` shows a full tree of folders, files, and documents
+- After uploading a file, use \`lh doc parse <fileId>\` to extract text content
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/memory.ts b/packages/builtin-skills/src/lobehub/references/memory.ts
new file mode 100644
index 00000000000..d5962dd2188
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/memory.ts
@@ -0,0 +1,29 @@
+const content = `# lh memory - User Memory Management
+
+Manage user memories across five categories: identity, activity, context, experience, preference.
+
+## Subcommands
+
+- \`lh memory list [category]\` - List memories by category
+- \`lh memory create --type <type> --role <role> -d <description>\` - Create identity memory
+- \`lh memory edit <category> <id> [options]\` - Update memory entry
+- \`lh memory delete <category> <id> [--yes]\` - Delete memory entry
+- \`lh memory persona\` - View memory persona summary
+- \`lh memory extract [--from <date>] [--to <date>]\` - Extract memories from chat history
+- \`lh memory extract-status --task-id <id>\` - Check extraction task status
+
+## Memory Categories
+
+- **identity** - Who the user is (role, relationships, descriptions)
+- **activity** - What the user does (events, actions, habits)
+- **context** - Situational context (environment, constraints)
+- **experience** - Past experiences and learnings
+- **preference** - User preferences and settings
+
+## Tips
+
+- Use \`lh memory persona\` to get a comprehensive view of the user
+- Memory extraction analyzes chat history to automatically create entries
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/message.ts b/packages/builtin-skills/src/lobehub/references/message.ts
new file mode 100644
index 00000000000..6a2f3c46443
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/message.ts
@@ -0,0 +1,19 @@
+const content = `# lh message - Message Management
+
+Manage chat messages.
+
+## Subcommands
+
+- \`lh message list [--topic-id <id>] [--agent-id <id>] [-L <limit>] [--page <n>]\` - List messages
+- \`lh message search <keywords>\` - Search messages by keywords
+- \`lh message delete <ids...> [--yes]\` - Delete messages
+- \`lh message count [--start <date>] [--end <date>]\` - Count messages
+- \`lh message heatmap\` - Get message activity heatmap
+
+## Tips
+
+- Filter by \`--topic-id\` to get messages from a specific conversation
+- Use \`--user\` flag to filter by message role (user/assistant)
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/model.ts b/packages/builtin-skills/src/lobehub/references/model.ts
new file mode 100644
index 00000000000..e48ea8f95dd
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/model.ts
@@ -0,0 +1,22 @@
+const content = `# lh model - AI Model Management
+
+Manage AI models for providers.
+
+## Subcommands
+
+- \`lh model list <providerId> [--enabled] [--type <type>] [-L <limit>]\` - List models
+- \`lh model view <id>\` - View model details
+- \`lh model create --id <id> --provider <p> --display-name <name> [--type <type>]\` - Create model
+- \`lh model edit <id> [--provider <p>] [--display-name <name>]\` - Update model
+- \`lh model toggle <id> --provider <p> [--enable|--disable]\` - Enable/disable model
+- \`lh model delete <id> --provider <p> [--yes]\` - Delete model
+- \`lh model batch-toggle <ids...> --provider <p> [--enable|--disable]\` - Batch toggle
+- \`lh model clear --provider <p> [--remote] [--yes]\` - Clear all models for provider
+
+## Tips
+
+- Models belong to providers; always specify \`--provider\` when needed
+- Use \`--type\` to filter by model type (chat, embedding, etc.)
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/plugin.ts b/packages/builtin-skills/src/lobehub/references/plugin.ts
new file mode 100644
index 00000000000..e1d5462e5ef
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/plugin.ts
@@ -0,0 +1,18 @@
+const content = `# lh plugin - Plugin Management
+
+Manage installed plugins (external tool integrations).
+
+## Subcommands
+
+- \`lh plugin list\` - List installed plugins
+- \`lh plugin install -i <identifier> [--manifest <url>] [--type <type>] [--settings <json>]\` - Install plugin
+- \`lh plugin uninstall <id> [--yes]\` - Uninstall plugin
+- \`lh plugin update <id> [--manifest <url>] [--settings <json>]\` - Update plugin
+
+## Tips
+
+- Plugins extend agent capabilities with external tools
+- Use \`--settings\` to pass JSON configuration during install/update
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/provider.ts b/packages/builtin-skills/src/lobehub/references/provider.ts
new file mode 100644
index 00000000000..b72fc8e3231
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/provider.ts
@@ -0,0 +1,22 @@
+const content = `# lh provider - AI Provider Management
+
+Manage AI providers and their configurations.
+
+## Subcommands
+
+- \`lh provider list\` - List all providers
+- \`lh provider view <id>\` - View provider details
+- \`lh provider create --id <id> -n <name> [-s <source>] [--sdk-type <type>]\` - Create provider
+- \`lh provider edit <id> [-n <name>] [-d <description>]\` - Update provider
+- \`lh provider config <id> [--api-key <key>] [--base-url <url>] [--show]\` - Configure settings
+- \`lh provider test <id> [-m <model>]\` - Test provider connectivity
+- \`lh provider toggle <id> [--enable|--disable]\` - Enable/disable provider
+- \`lh provider delete <id> [--yes]\` - Delete provider
+
+## Tips
+
+- Use \`lh provider config <id> --show\` to view current configuration
+- \`lh provider test\` verifies API key and connectivity
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/search.ts b/packages/builtin-skills/src/lobehub/references/search.ts
new file mode 100644
index 00000000000..a96c9de7768
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/search.ts
@@ -0,0 +1,22 @@
+const content = `# lh search - Search Resources
+
+Search local resources or the web.
+
+## Subcommands
+
+- \`lh search -q <query> [-t <type>] [-L <limit>]\` - Search local resources
+- \`lh search -q <query> -w [-e <engines>] [-c <categories>]\` - Search the web
+- \`lh search view <target>\` - View search result details or crawl a URL
+
+## Search Types (local)
+
+agent, topic, file, folder, message, page, memory, mcp, plugin, communityAgent, knowledgeBase
+
+## Tips
+
+- Use \`-w\` flag to perform web search instead of local search
+- \`lh search view <url>\` can crawl and extract content from web pages
+- Web search supports engine and category filters
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/skill.ts b/packages/builtin-skills/src/lobehub/references/skill.ts
new file mode 100644
index 00000000000..7e9537e8c3c
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/skill.ts
@@ -0,0 +1,23 @@
+const content = `# lh skill - Skill Management
+
+Manage agent skills (reusable prompt+resource bundles).
+
+## Subcommands
+
+- \`lh skill list [--source <builtin|market|user>]\` - List skills
+- \`lh skill view <id>\` - View skill details
+- \`lh skill create -n <name> -d <description> -c <content>\` - Create user skill
+- \`lh skill edit <id> [-c <content>] [-n <name>] [-d <description>]\` - Update skill
+- \`lh skill delete <id> [--yes]\` - Delete skill
+- \`lh skill search <query>\` - Search skills
+- \`lh skill install <source> [--branch <b>]\` - Install from GitHub/URL/marketplace
+- \`lh skill resources <id>\` - List skill resource files
+- \`lh skill read-resource <id> <path>\` - Read a skill resource file
+
+## Tips
+
+- Skills can be installed from GitHub repos, URLs, or the marketplace
+- Use \`resources\` and \`read-resource\` to inspect skill reference files
+`;
+
+export default content;
diff --git a/packages/builtin-skills/src/lobehub/references/topic.ts b/packages/builtin-skills/src/lobehub/references/topic.ts
new file mode 100644
index 00000000000..20517f7d0d1
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/topic.ts
@@ -0,0 +1,20 @@
+const content = `# lh topic - Conversation Topic Management
+
+Manage conversation topics (chat sessions).
+
+## Subcommands
+
+- \`lh topic list [--agent-id <id>] [-L <limit>] [--page <n>]\` - List topics with pagination
+- \`lh topic search <keywords> [--agent-id <id>]\` - Search topics by keywords
+- \`lh topic create -t <title> [--agent-id <id>] [--favorite]\` - Create a topic
+- \`lh topic edit <id> [-t <title>] [--favorite] [--no-favorite]\` - Update topic
+- \`lh topic delete <ids...> [--yes]\` - Delete one or more topics
+- \`lh topic recent [-L <limit>]\` - List recently accessed topics
+
+## Tips
+
+- Topics are associated with agents; use \`--agent-id\` to filter
+- Use \`--json\` for structured output suitable for piping
+`;
+
+export default content;
diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
index acd8acb68d1..ac66a3f0afa 100644
--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
@@ -8,12 +8,13 @@ import {
} from '@lobechat/types';
import {
+ type ActivateSkillParams,
type CommandResult,
type ExecScriptParams,
type ExportFileParams,
type ReadReferenceParams,
type RunCommandOptions,
- type RunSkillParams,
+ type RunCommandParams,
} from '../types';
/**
@@ -125,6 +126,37 @@ export class SkillsExecutionRuntime {
}
}
+ async runCommand(args: RunCommandParams): Promise<BuiltinServerRuntimeOutput> {
+ const { command } = args;
+
+ if (!this.service.runCommand) {
+ return {
+ content: 'Command execution is not available in this environment.',
+ success: false,
+ };
+ }
+
+ try {
+ const result = await this.service.runCommand({ command });
+ const output = [result.output, result.stderr].filter(Boolean).join('\n');
+
+ return {
+ content: output || '(no output)',
+ state: {
+ command,
+ exitCode: result.exitCode,
+ success: result.success,
+ },
+ success: result.success,
+ };
+ } catch (e) {
+ return {
+ content: `Failed to execute command: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
async exportFile(args: ExportFileParams): Promise<BuiltinServerRuntimeOutput> {
const { path, filename } = args;
@@ -176,7 +208,29 @@ export class SkillsExecutionRuntime {
}
try {
- // Resolve id: try findById first, fallback to findByName
+ // Check builtin skills first
+ const builtinSkill = this.builtinSkills.find((s) => s.name === id);
+ if (builtinSkill?.resources) {
+ const meta = builtinSkill.resources[path];
+ if (meta?.content !== undefined) {
+ return {
+ content: meta.content,
+ state: {
+ encoding: 'utf8',
+ fileType: 'text/plain',
+ path,
+ size: meta.size,
+ },
+ success: true,
+ };
+ }
+ return {
+ content: `Resource not found: "${path}" in builtin skill "${id}"`,
+ success: false,
+ };
+ }
+
+ // Resolve id: try findByName for DB skills
const skill = await this.service.findByName(id);
if (!skill) {
return {
@@ -205,17 +259,26 @@ export class SkillsExecutionRuntime {
}
}
- async runSkill(args: RunSkillParams): Promise<BuiltinServerRuntimeOutput> {
+ async activateSkill(args: ActivateSkillParams): Promise<BuiltinServerRuntimeOutput> {
const { name } = args;
// Check builtin skills first — no DB query needed
const builtinSkill = this.builtinSkills.find((s) => s.name === name);
if (builtinSkill) {
+ let content = builtinSkill.content;
+ const hasResources = !!(
+ builtinSkill.resources && Object.keys(builtinSkill.resources).length > 0
+ );
+
+ if (hasResources && builtinSkill.resources) {
+ content += '\n\n' + resourcesTreePrompt(builtinSkill.name, builtinSkill.resources);
+ }
+
return {
- content: builtinSkill.content,
+ content,
state: {
description: builtinSkill.description,
- hasResources: false,
+ hasResources,
identifier: builtinSkill.identifier,
name: builtinSkill.name,
},
diff --git a/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx b/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx
index 722871b0a9e..a74c6fb3a11 100644
--- a/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx
+++ b/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx
@@ -7,40 +7,40 @@ import { useTranslation } from 'react-i18next';
import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
-import type { RunSkillParams, RunSkillState } from '../../../types';
+import type { ActivateSkillParams, ActivateSkillState } from '../../../types';
-export const RunSkillInspector = memo<BuiltinInspectorProps<RunSkillParams, RunSkillState>>(
- ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
- const { t } = useTranslation('plugin');
+export const RunSkillInspector = memo<
+ BuiltinInspectorProps<ActivateSkillParams, ActivateSkillState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
- const name = args?.name || partialArgs?.name || '';
- const activatedName = pluginState?.name;
-
- if (isArgumentsStreaming) {
- if (!name)
- return (
- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
- <span>{t('builtins.lobe-skills.apiName.runSkill')}</span>
- </div>
- );
+ const name = args?.name || partialArgs?.name || '';
+ const activatedName = pluginState?.name;
+ if (isArgumentsStreaming) {
+ if (!name)
return (
<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
- <span>{t('builtins.lobe-skills.apiName.runSkill')}:</span>
- <span>{name}</span>
+ <span>{t('builtins.lobe-skills.apiName.activateSkill')}</span>
</div>
);
- }
return (
- <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
- <span>
- <span>{t('builtins.lobe-skills.apiName.runSkill')}:</span>
- <span className={highlightTextStyles.primary}>{activatedName || name}</span>
- </span>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-skills.apiName.activateSkill')}:</span>
+ <span>{name}</span>
</div>
);
- },
-);
+ }
+
+ return (
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
+ <span>
+ <span>{t('builtins.lobe-skills.apiName.activateSkill')}:</span>
+ <span className={highlightTextStyles.primary}>{activatedName || name}</span>
+ </span>
+ </div>
+ );
+});
RunSkillInspector.displayName = 'RunSkillInspector';
diff --git a/packages/builtin-tool-skills/src/client/Inspector/index.ts b/packages/builtin-tool-skills/src/client/Inspector/index.ts
index ed07757644e..da16da2a86c 100644
--- a/packages/builtin-tool-skills/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-skills/src/client/Inspector/index.ts
@@ -6,5 +6,7 @@ import { RunSkillInspector } from './RunSkill';
export const SkillsInspectors = {
[SkillsApiName.execScript]: ExecScriptInspector,
[SkillsApiName.readReference]: ReadReferenceInspector,
- [SkillsApiName.runSkill]: RunSkillInspector,
+ [SkillsApiName.activateSkill]: RunSkillInspector,
+ // @deprecated skill id
+ runSkill: RunSkillInspector,
};
diff --git a/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx b/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx
index ba0b0789277..3aea3b80b3e 100644
--- a/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx
+++ b/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx
@@ -5,7 +5,7 @@ import { Flexbox, Markdown, ScrollShadow } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
-import type { RunSkillParams, RunSkillState } from '../../../types';
+import type { ActivateSkillParams, ActivateSkillState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -36,7 +36,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const RunSkill = memo<BuiltinRenderProps<RunSkillParams, RunSkillState>>(
+const RunSkill = memo<BuiltinRenderProps<ActivateSkillParams, ActivateSkillState>>(
({ content, pluginState }) => {
const { description, name } = pluginState || {};
diff --git a/packages/builtin-tool-skills/src/client/Render/index.ts b/packages/builtin-tool-skills/src/client/Render/index.ts
index 9265d8d9781..f067d821624 100644
--- a/packages/builtin-tool-skills/src/client/Render/index.ts
+++ b/packages/builtin-tool-skills/src/client/Render/index.ts
@@ -6,5 +6,5 @@ import RunSkill from './RunSkill';
export const SkillsRenders = {
[SkillsApiName.execScript]: ExecScript,
[SkillsApiName.readReference]: ReadReference,
- [SkillsApiName.runSkill]: RunSkill,
+ [SkillsApiName.activateSkill]: RunSkill,
};
diff --git a/packages/builtin-tool-skills/src/const.ts b/packages/builtin-tool-skills/src/const.ts
deleted file mode 100644
index c1ed33ef1fc..00000000000
--- a/packages/builtin-tool-skills/src/const.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { isDesktop } from '@lobechat/const';
diff --git a/packages/builtin-tool-skills/src/executor/index.ts b/packages/builtin-tool-skills/src/executor/index.ts
index 4c20f0a871f..d9ee80565ca 100644
--- a/packages/builtin-tool-skills/src/executor/index.ts
+++ b/packages/builtin-tool-skills/src/executor/index.ts
@@ -2,10 +2,11 @@ import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@
import type { SkillsExecutionRuntime } from '../ExecutionRuntime';
import {
+ type ActivateSkillParams,
type ExecScriptParams,
type ExportFileParams,
type ReadReferenceParams,
- type RunSkillParams,
+ type RunCommandParams,
SkillsApiName,
SkillsIdentifier,
} from '../types';
@@ -50,8 +51,8 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
}
};
- runSkill = async (
- params: RunSkillParams,
+ activateSkill = async (
+ params: ActivateSkillParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
try {
@@ -59,7 +60,7 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
return { stop: true, success: false };
}
- const result = await this.runtime.runSkill(params);
+ const result = await this.runtime.activateSkill(params);
if (result.success) {
return { content: result.content, state: result.state, success: true };
@@ -108,6 +109,35 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
}
};
+ runCommand = async (
+ params: RunCommandParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ if (ctx.signal?.aborted) {
+ return { stop: true, success: false };
+ }
+
+ const result = await this.runtime.runCommand(params);
+
+ if (result.success) {
+ return { content: result.content, state: result.state, success: true };
+ }
+
+ return {
+ content: result.content,
+ error: { message: result.content, type: 'PluginServerError' },
+ success: false,
+ };
+ } catch (e) {
+ const err = e as Error;
+ return {
+ error: { body: e, message: err.message, type: 'PluginServerError' },
+ success: false,
+ };
+ }
+ };
+
exportFile = async (
params: ExportFileParams,
ctx: BuiltinToolContext,
diff --git a/packages/builtin-tool-skills/src/index.ts b/packages/builtin-tool-skills/src/index.ts
index b66a2a5dc8d..e99035f0a8f 100644
--- a/packages/builtin-tool-skills/src/index.ts
+++ b/packages/builtin-tool-skills/src/index.ts
@@ -1,10 +1,10 @@
export { SkillsManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
+ type ActivateSkillParams,
type CommandResult,
type ExecScriptParams,
type ReadReferenceParams,
- type RunSkillParams,
SkillsApiName,
SkillsIdentifier,
} from './types';
diff --git a/packages/builtin-tool-skills/src/manifest.base.ts b/packages/builtin-tool-skills/src/manifest.base.ts
index 82cdb34b204..5198dbe62a6 100644
--- a/packages/builtin-tool-skills/src/manifest.base.ts
+++ b/packages/builtin-tool-skills/src/manifest.base.ts
@@ -2,10 +2,10 @@ import type { LobeChatPluginApi } from '@lobechat/types';
import { SkillsApiName } from './types';
-export const runSkillApi: LobeChatPluginApi = {
+export const activateSkillApi: LobeChatPluginApi = {
description:
'Activate a skill by name to load its instructions. Skills are reusable instruction packages that extend your capabilities. Returns the skill content that you should follow to complete the task. If the skill is not found, returns a list of available skills.',
- name: SkillsApiName.runSkill,
+ name: SkillsApiName.activateSkill,
parameters: {
properties: {
name: {
@@ -20,12 +20,12 @@ export const runSkillApi: LobeChatPluginApi = {
export const readReferenceApi: LobeChatPluginApi = {
description:
- "Read a reference file attached to a skill. Use this to load additional context files mentioned in a skill's content. Requires the id returned by runSkill and the file path.",
+ "Read a reference file attached to a skill. Use this to load additional context files mentioned in a skill's content. Requires the id returned by activateSkill and the file path.",
name: SkillsApiName.readReference,
parameters: {
properties: {
id: {
- description: 'The skill ID or name returned by runSkill.',
+ description: 'The skill ID or name returned by activateSkill.',
type: 'string',
},
path: {
@@ -60,6 +60,27 @@ export const exportFileApi: LobeChatPluginApi = {
},
};
+export const runCommandApi: LobeChatPluginApi = {
+ description: 'Execute a shell command. Returns the command output, stderr, and exit code.',
+ humanIntervention: 'required',
+ name: SkillsApiName.runCommand,
+ parameters: {
+ properties: {
+ command: {
+ description: 'The shell command to execute.',
+ type: 'string',
+ },
+ description: {
+ description:
+ 'Clear description of what this command does (5-10 words, in active voice). Use the same language as the user input.',
+ type: 'string',
+ },
+ },
+ required: ['command'],
+ type: 'object',
+ },
+};
+
export const execScriptBaseParams = {
command: {
description: 'The shell command to execute.',
@@ -67,18 +88,18 @@ export const execScriptBaseParams = {
},
config: {
description:
- 'REQUIRED: Current skill context. Must include the id and name from the most recent runSkill call. The server uses this to locate skill resources (e.g., ZIP package for skill files). Example: { "id": "skill_xxx", "name": "skill-name", "description": "..." }',
+ 'REQUIRED: Current skill context. Must include the id and name from the most recent activateSkill call. The server uses this to locate skill resources (e.g., ZIP package for skill files). Example: { "id": "skill_xxx", "name": "skill-name", "description": "..." }',
properties: {
description: {
description: "Current skill's description (optional)",
type: 'string',
},
id: {
- description: "Current skill's ID from runSkill state (required for resource lookup)",
+ description: "Current skill's ID from activateSkill state (required for resource lookup)",
type: 'string',
},
name: {
- description: "Current skill's name from runSkill state (required for resource lookup)",
+ description: "Current skill's name from activateSkill state (required for resource lookup)",
type: 'string',
},
},
diff --git a/packages/builtin-tool-skills/src/manifest.desktop.ts b/packages/builtin-tool-skills/src/manifest.desktop.ts
index edb350a4028..fadde81ef76 100644
--- a/packages/builtin-tool-skills/src/manifest.desktop.ts
+++ b/packages/builtin-tool-skills/src/manifest.desktop.ts
@@ -1,16 +1,21 @@
import type { BuiltinToolManifest } from '@lobechat/types';
-import { execScriptBaseParams, manifestMeta, readReferenceApi, runSkillApi } from './manifest.base';
+import {
+ activateSkillApi,
+ execScriptBaseParams,
+ manifestMeta,
+ readReferenceApi,
+} from './manifest.base';
import { systemPrompt } from './systemRole';
import { SkillsApiName, SkillsIdentifier } from './types';
export const SkillsManifest: BuiltinToolManifest = {
api: [
- runSkillApi,
+ activateSkillApi,
readReferenceApi,
{
description:
- "Execute a shell command or script specified in a skill's instructions. Use this when a skill's content instructs you to run CLI commands (e.g., npx, npm, pip). Commands run directly on the local system. IMPORTANT: Always include the 'config' parameter with the current skill's id and name (obtained from runSkill's state) so the system can locate skill resources. Returns the command output.",
+ "Execute a shell command or script specified in a skill's instructions. Use this when a skill's content instructs you to run CLI commands (e.g., npx, npm, pip). Commands run directly on the local system. IMPORTANT: Always include the 'config' parameter with the current skill's id and name (obtained from activateSkill's state) so the system can locate skill resources. Returns the command output.",
humanIntervention: 'required',
name: SkillsApiName.execScript,
parameters: {
diff --git a/packages/builtin-tool-skills/src/manifest.ts b/packages/builtin-tool-skills/src/manifest.ts
index 8431b2d7e97..25536c9ddaa 100644
--- a/packages/builtin-tool-skills/src/manifest.ts
+++ b/packages/builtin-tool-skills/src/manifest.ts
@@ -1,22 +1,24 @@
import type { BuiltinToolManifest } from '@lobechat/types';
import {
+ activateSkillApi,
execScriptBaseParams,
exportFileApi,
manifestMeta,
readReferenceApi,
- runSkillApi,
+ runCommandApi,
} from './manifest.base';
import { systemPrompt } from './systemRole';
import { SkillsApiName, SkillsIdentifier } from './types';
export const SkillsManifest: BuiltinToolManifest = {
api: [
- runSkillApi,
+ activateSkillApi,
readReferenceApi,
+ runCommandApi,
{
description:
- "Execute a shell command or script specified in a skill's instructions. Use this when a skill's content instructs you to run CLI commands (e.g., npx, npm, pip). IMPORTANT: Always include the 'config' parameter with the current skill's id and name (obtained from runSkill's state) so the system can locate skill resources. Returns the command output.",
+ "Execute a shell command or script specified in a skill's instructions. Use this when a skill's content instructs you to run CLI commands (e.g., npx, npm, pip). IMPORTANT: Always include the 'config' parameter with the current skill's id and name (obtained from activateSkill's state) so the system can locate skill resources. Returns the command output.",
humanIntervention: 'required',
name: SkillsApiName.execScript,
parameters: {
diff --git a/packages/builtin-tool-skills/src/systemRole.desktop.ts b/packages/builtin-tool-skills/src/systemRole.desktop.ts
index 2a3e05d1334..0f2fbf52ff2 100644
--- a/packages/builtin-tool-skills/src/systemRole.desktop.ts
+++ b/packages/builtin-tool-skills/src/systemRole.desktop.ts
@@ -1,13 +1,13 @@
export const systemPrompt = `You have access to a Skills tool that allows you to activate reusable instruction packages (skills) that extend your capabilities. Skills are pre-defined workflows, guidelines, or specialized knowledge that help you handle specific types of tasks.
<core_capabilities>
-1. Activate a skill by name to load its instructions (runSkill)
+1. Activate a skill by name to load its instructions (activateSkill)
2. Read reference files attached to a skill (readReference)
3. Execute shell commands specified in a skill's instructions (execScript)
</core_capabilities>
<workflow>
-1. When the user's request matches an available skill, call runSkill with the skill name
+1. When the user's request matches an available skill, call activateSkill with the skill name
2. The skill content will be returned - follow those instructions to complete the task
3. If the skill content references additional files, use readReference to load them
4. If the skill content instructs you to run CLI commands, use execScript to execute them
@@ -15,18 +15,18 @@ export const systemPrompt = `You have access to a Skills tool that allows you to
</workflow>
<tool_selection_guidelines>
-- **runSkill**: Call this when the user's task matches one of the available skills
+- **activateSkill**: Call this when the user's task matches one of the available skills
- Provide the exact skill name
- Returns the skill content (instructions, templates, guidelines) that you should follow
- If the skill is not found, you'll receive a list of available skills
- **readReference**: Call this to read reference files mentioned in a skill's content
- - Requires the id (returned by runSkill) and the file path
+ - Requires the id (returned by activateSkill) and the file path
- Returns the file content for you to use as context
- Only use paths that are referenced in the skill content
- **execScript**: Call this to execute shell commands mentioned in a skill's content
- - **IMPORTANT**: Always provide the \`config\` parameter with the current skill's id and name (from runSkill's state)
+ - **IMPORTANT**: Always provide the \`config\` parameter with the current skill's id and name (from activateSkill's state)
- Commands run directly on the local system (OS: {{platform}})
- Provide the command to execute and a clear description of what it does
- Returns the command output (stdout/stderr)
@@ -39,6 +39,6 @@ export const systemPrompt = `You have access to a Skills tool that allows you to
- Follow the skill's instructions carefully once loaded
- Use readReference only for files explicitly mentioned in the skill content
- Use execScript only for commands specified in the skill content, always including config parameter
-- If runSkill returns an error with available skills, inform the user what skills are available
+- If activateSkill returns an error with available skills, inform the user what skills are available
</best_practices>
`;
diff --git a/packages/builtin-tool-skills/src/systemRole.ts b/packages/builtin-tool-skills/src/systemRole.ts
index 909ed81382b..0fb09db7566 100644
--- a/packages/builtin-tool-skills/src/systemRole.ts
+++ b/packages/builtin-tool-skills/src/systemRole.ts
@@ -1,41 +1,46 @@
export const systemPrompt = `You have access to a Skills tool that allows you to activate reusable instruction packages (skills) that extend your capabilities. Skills are pre-defined workflows, guidelines, or specialized knowledge that help you handle specific types of tasks.
<core_capabilities>
-1. Activate a skill by name to load its instructions (runSkill)
+1. Activate a skill by name to load its instructions (activateSkill)
2. Read reference files attached to a skill (readReference)
-3. Execute shell commands specified in a skill's instructions (execScript)
-4. Export files generated during skill execution to cloud storage (exportFile)
+3. Execute shell commands in the cloud sandbox (runCommand)
+4. Execute skill-specific scripts with resource context (execScript)
+5. Export files generated during skill execution to cloud storage (exportFile)
</core_capabilities>
<workflow>
-1. When the user's request matches an available skill, call runSkill with the skill name
+1. When the user's request matches an available skill, call activateSkill with the skill name
2. The skill content will be returned - follow those instructions to complete the task
3. If the skill content references additional files, use readReference to load them
-4. If the skill content instructs you to run CLI commands, use execScript to execute them
-5. If the skill execution generates output files, use exportFile to save them for the user
-6. Apply the skill's instructions to fulfill the user's request
+4. If the skill content instructs you to run CLI commands, use runCommand to execute them
+5. If the command requires skill-bundled resources, use execScript instead (with config parameter)
+6. If the skill execution generates output files, use exportFile to save them for the user
+7. Apply the skill's instructions to fulfill the user's request
</workflow>
<tool_selection_guidelines>
-- **runSkill**: Call this when the user's task matches one of the available skills
+- **activateSkill**: Call this when the user's task matches one of the available skills
- Provide the exact skill name
- Returns the skill content (instructions, templates, guidelines) that you should follow
- If the skill is not found, you'll receive a list of available skills
- **readReference**: Call this to read reference files mentioned in a skill's content
- - Requires the id (returned by runSkill) and the file path
+ - Requires the id (returned by activateSkill) and the file path
- Returns the file content for you to use as context
- Only use paths that are referenced in the skill content
-- **execScript**: Call this to execute shell commands mentioned in a skill's content
- - **IMPORTANT**: Always provide the \`config\` parameter with the current skill's id and name (from runSkill's state)
- - **USE CASE**: This is the preferred tool for executing commands from skill scripts
- - Automatically locates and provides skill resources (files, dependencies) to the execution environment
+- **runCommand**: Call this to execute shell commands in the cloud sandbox
+ - Use for general CLI commands, platform tools (e.g., \`lh\` CLI), and ad-hoc operations
- Provide the command to execute and a clear description of what it does
+ - Returns the command output (stdout/stderr) and exit code
+ - Requires user confirmation before execution
+
+- **execScript**: Call this to execute skill-specific scripts that need resource context
+ - **IMPORTANT**: Always provide the \`config\` parameter with the current skill's id and name (from activateSkill's state)
+ - Automatically locates and provides skill resources (ZIP package with scripts, config files, dependencies)
+ - Best for: commands that require skill-bundled files or dependencies
- Returns the command output (stdout/stderr)
- - Only execute commands that are specified or suggested in the skill content
- Requires user confirmation before execution
- - **If execScript fails or encounters issues, fall back to using the Cloud Sandbox's runCommand tool**
- **exportFile**: Call this to export files generated during skill execution
- Use this when a skill generates output files that the user needs to download
@@ -44,35 +49,33 @@ export const systemPrompt = `You have access to a Skills tool that allows you to
- Best for: skill outputs, generated reports, processed data files, result artifacts
</tool_selection_guidelines>
-<execscript_vs_runcommand>
-**When to use execScript vs Cloud Sandbox runCommand:**
+<runcommand_vs_execscript>
+**When to use runCommand vs execScript:**
-- **execScript (Preferred for skill scripts)**:
- - Use when executing commands that are part of a skill's workflow
- - Automatically provides skill resources (ZIP package with scripts, config files, dependencies)
- - Server locates the skill package and makes it available in the execution environment
- - Best for: skill-specific scripts, tool initialization, workflows defined in skills
+- **runCommand (Default for most commands)**:
+ - Use for general shell commands and CLI tools (e.g., \`lh kb list\`, \`npm install\`)
+ - Use for platform tool commands (LobeHub CLI, etc.)
+ - No skill context needed — just provide the command
+ - Best for: CLI operations, system commands, tool invocations
-- **Cloud Sandbox runCommand (Fallback or general commands)**:
- - Use for general shell commands that don't require skill resources
- - Use as fallback when execScript encounters errors or limitations
- - Use for ad-hoc commands not related to any specific skill
- - Best for: system commands, package installations, file operations
+- **execScript (For skill-bundled scripts)**:
+ - Use only when a command needs access to skill-bundled resources (ZIP packages, config files)
+ - Must include \`config\` parameter with skill id and name from activateSkill's state
+ - Best for: running scripts bundled within a skill package
**Example workflow:**
-1. User activates a skill with runSkill
-2. Skill content instructs to run a script (e.g., "python scripts/init.py")
-3. Use execScript with the skill's config to execute the script (skill resources automatically available)
-4. If execScript fails, inform user and optionally try runCommand as fallback
-</execscript_vs_runcommand>
+1. User activates a skill with activateSkill
+2. Skill content instructs to run a CLI command (e.g., \`lh kb list\`) → use runCommand
+3. Skill content instructs to run a bundled script (e.g., \`python scripts/init.py\`) → use execScript with config
+</runcommand_vs_execscript>
<best_practices>
- Only activate skills when the user's task clearly matches the skill's purpose
- Follow the skill's instructions carefully once loaded
- Use readReference only for files explicitly mentioned in the skill content
-- Use execScript only for commands specified in the skill content, always including config parameter
+- Use runCommand for CLI commands and general operations
+- Use execScript only when the command needs skill-bundled resources, always including config parameter
- Use exportFile when the skill generates output files that need to be saved
-- If runSkill returns an error with available skills, inform the user what skills are available
-- If execScript fails, consider using Cloud Sandbox's runCommand as a fallback
+- If activateSkill returns an error with available skills, inform the user what skills are available
</best_practices>
`;
diff --git a/packages/builtin-tool-skills/src/types.ts b/packages/builtin-tool-skills/src/types.ts
index 53236a8b94d..544e1d41ed0 100644
--- a/packages/builtin-tool-skills/src/types.ts
+++ b/packages/builtin-tool-skills/src/types.ts
@@ -4,14 +4,15 @@ export const SkillsApiName = {
execScript: 'execScript',
exportFile: 'exportFile',
readReference: 'readReference',
- runSkill: 'runSkill',
+ runCommand: 'runCommand',
+ activateSkill: 'activateSkill',
};
-export interface RunSkillParams {
+export interface ActivateSkillParams {
name: string;
}
-export interface RunSkillState {
+export interface ActivateSkillState {
description?: string;
hasResources: boolean;
id: string;
@@ -59,6 +60,11 @@ export interface CommandResult {
success: boolean;
}
+export interface RunCommandParams {
+ command: string;
+ description?: string;
+}
+
export interface ReadReferenceParams {
id: string;
path: string;
diff --git a/packages/types/src/skill/index.ts b/packages/types/src/skill/index.ts
index 98abcaf7a70..167b670cd4f 100644
--- a/packages/types/src/skill/index.ts
+++ b/packages/types/src/skill/index.ts
@@ -46,6 +46,12 @@ export interface BuiltinSkill {
description: string;
identifier: string;
name: string;
+ /**
+ * Inline resources for builtin skills.
+ * Key is the file path (e.g. "kb/README.md").
+ * Use `content` field in SkillResourceMeta to inline text content.
+ */
+ resources?: Record<string, SkillResourceMeta>;
source: 'builtin';
}
@@ -76,6 +82,11 @@ export interface ParsedZipSkill {
// ===== Resource Types =====
export interface SkillResourceMeta {
+ /**
+ * Inline text content for builtin skill resources.
+ * When set, the resource is served directly from memory instead of S3.
+ */
+ content?: string;
documentId?: string;
fileHash: string;
size: number;
diff --git a/src/envs/app.ts b/src/envs/app.ts
index b34c0cc5c5e..670bed4f276 100644
--- a/src/envs/app.ts
+++ b/src/envs/app.ts
@@ -59,8 +59,8 @@ export const getAppConfig = () => {
SSRF_ALLOW_PRIVATE_IP_ADDRESS: z.boolean().optional(),
SSRF_ALLOW_IP_ADDRESS_LIST: z.string().optional(),
- MARKET_BASE_URL: z.string().optional(),
+ MARKET_BASE_URL: z.string().optional(),
/**
* Trusted Client Secret for Market API authentication
* 64-character hex string (32 bytes) shared with Market server
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index a1be36286ea..42b372d8f75 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -105,7 +105,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
<Flexbox
className={cx(styles.container, expand && styles.fullscreen)}
gap={8}
- paddingBlock={expand ? 0 : showFootnote ? '0 12px' : '0 16px'}
+ paddingBlock={expand ? 0 : showFootnote ? '0 12px' : '0 8px'}
>
<ChatInput
data-testid="chat-input"
diff --git a/src/libs/trpc/utils/internalJwt.ts b/src/libs/trpc/utils/internalJwt.ts
index c540d0624bc..7a7eb42a249 100644
--- a/src/libs/trpc/utils/internalJwt.ts
+++ b/src/libs/trpc/utils/internalJwt.ts
@@ -1,5 +1,5 @@
import debug from 'debug';
-import { importJWK, jwtVerify,SignJWT } from 'jose';
+import { importJWK, jwtVerify, SignJWT } from 'jose';
import { authEnv } from '@/envs/auth';
@@ -79,6 +79,22 @@ export const signInternalJWT = async (): Promise<string> => {
.sign(key);
};
+/**
+ * Sign a short-lived OIDC-compatible JWT for a given user.
+ * Used by server-side sandbox execution to authenticate CLI commands.
+ * The token contains `sub: userId` and passes standard OIDC JWT validation.
+ */
+export const signUserJWT = async (userId: string): Promise<string> => {
+ const { key, kid } = await getSigningKey();
+
+ return new SignJWT({ purpose: 'cli-sandbox' })
+ .setProtectedHeader({ alg: 'RS256', kid })
+ .setSubject(userId)
+ .setIssuedAt()
+ .setExpirationTime('5m')
+ .sign(key);
+};
+
/**
* Validate internal JWT from lambda → async calls
* Returns true if valid, false otherwise
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index 0143bfe0131..c7205bb0223 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -199,7 +199,7 @@ export default {
'builtins.lobe-skills.apiName.importFromMarket': 'Import from Market',
'builtins.lobe-skills.apiName.importSkill': 'Import Skill',
'builtins.lobe-skills.apiName.readReference': 'Read Reference',
- 'builtins.lobe-skills.apiName.runSkill': 'Activate Skill',
+ 'builtins.lobe-skills.apiName.activateSkill': 'Activate Skill',
'builtins.lobe-skills.apiName.searchSkill': 'Search Skills',
'builtins.lobe-skills.title': 'Skills',
'builtins.lobe-user-memory.apiName.addContextMemory': 'Add context memory',
diff --git a/src/server/routers/tools/market.ts b/src/server/routers/tools/market.ts
index d9fb0e36069..f29ad3b4259 100644
--- a/src/server/routers/tools/market.ts
+++ b/src/server/routers/tools/market.ts
@@ -84,8 +84,8 @@ const metaSchema = z
})
.optional();
-// Schema for code interpreter tool call request
-const callCodeInterpreterToolSchema = z.object({
+// Schema for sandbox tool execution request
+const execInSandboxSchema = z.object({
params: z.record(z.any()),
toolName: z.string(),
topicId: z.string(),
@@ -108,7 +108,9 @@ const callCloudMcpEndpointSchema = z.object({
});
// ============================== Type Exports ==============================
-export type CallCodeInterpreterToolInput = z.infer<typeof callCodeInterpreterToolSchema>;
+export type ExecInSandboxInput = z.infer<typeof execInSandboxSchema>;
+/** @deprecated Use ExecInSandboxInput */
+export type CallCodeInterpreterToolInput = ExecInSandboxInput;
export type ExportAndUploadFileInput = z.infer<typeof exportAndUploadFileSchema>;
export interface CallToolResult {
@@ -133,6 +135,129 @@ export interface ExportAndUploadFileResult {
url?: string;
}
+// ============================== Sandbox Handler ==============================
+const execInSandboxHandler = async ({
+ input,
+ ctx,
+}: {
+ ctx: { fileService: FileService; marketService: MarketService; serverDB: any; userId: string };
+ input: ExecInSandboxInput;
+}): Promise<CallToolResult> => {
+ const { toolName, params, topicId } = input;
+ const userId = input?.userId || ctx.userId;
+
+ log('execInSandbox: tool=%s, topicId=%s', toolName, topicId);
+
+ try {
+ let enhancedParams = params;
+
+ // Preprocess lh commands: rewrite to npx @lobehub/cli + inject auth env vars
+ if ((toolName === 'execScript' || toolName === 'runCommand') && params.command) {
+ const { preprocessLhCommand } =
+ await import('@/server/services/toolExecution/preprocessLhCommand');
+ const lhResult = await preprocessLhCommand(params.command, userId);
+
+ if (lhResult.error) {
+ return {
+ error: { message: lhResult.error, name: 'AuthError' },
+ result: null,
+ sessionExpiredAndRecreated: false,
+ success: false,
+ };
+ }
+
+ if (lhResult.skipSkillLookup) {
+ enhancedParams = { ...params, command: lhResult.command, config: undefined };
+ }
+ }
+
+ // For execScript tool, look up skill zipUrl if config is provided
+ if (toolName === 'execScript' && enhancedParams.config) {
+ const agentSkillModel = new AgentSkillModel(ctx.serverDB, userId);
+
+ let skill;
+ if (enhancedParams.config.name) {
+ skill = await agentSkillModel.findByName(enhancedParams.config.name);
+
+ if (!skill) {
+ const allSkills = await agentSkillModel.findAll();
+ const availableSkills = allSkills.data.map((s) => s.name).join(', ');
+
+ const errorMessage = availableSkills
+ ? `Skill "${enhancedParams.config.name}" not found. Available skills: ${availableSkills}`
+ : `Skill "${enhancedParams.config.name}" not found. No skills available. Please import a skill first.`;
+
+ log(
+ 'Skill not found: %s. Available skills: %s',
+ enhancedParams.config.name,
+ availableSkills,
+ );
+
+ return {
+ error: { message: errorMessage, name: 'SkillNotFound' },
+ result: null,
+ sessionExpiredAndRecreated: false,
+ success: false,
+ };
+ }
+ }
+
+ if (skill?.zipFileHash) {
+ const fileModel = new FileModel(ctx.serverDB, userId);
+ const fileInfo = await fileModel.checkHash(skill.zipFileHash);
+
+ if (fileInfo.isExist && fileInfo.url) {
+ const fullUrl = await ctx.fileService.getFullFileUrl(fileInfo.url);
+ if (fullUrl) {
+ enhancedParams = { ...params, zipUrl: fullUrl };
+ log('Added zipUrl to execScript params for skill %s: %s', skill.name, fullUrl);
+ }
+ }
+ }
+ }
+
+ const market = ctx.marketService.market;
+
+ const response = await market.plugins.runBuildInTool(
+ toolName as CodeInterpreterToolName,
+ enhancedParams as any,
+ { topicId, userId },
+ );
+
+ log('execInSandbox response for %s: %O', toolName, response);
+
+ if (!response.success) {
+ return {
+ error: {
+ message: response.error?.message || 'Unknown error',
+ name: response.error?.code,
+ },
+ result: null,
+ sessionExpiredAndRecreated: false,
+ success: false,
+ };
+ }
+
+ return {
+ result: response.data?.result,
+ sessionExpiredAndRecreated: response.data?.sessionExpiredAndRecreated || false,
+ success: true,
+ };
+ } catch (error) {
+ log('execInSandbox error for %s: %O', toolName, error);
+
+ return {
+ error: {
+ message: (error as Error).message,
+ name: (error as Error).name,
+ },
+ result: null,
+ sessionExpiredAndRecreated: false,
+ success: false,
+ };
+ }
+};
+
// ============================== Router ==============================
export const marketRouter = router({
// ============================== Cloud MCP Gateway ==============================
@@ -226,119 +351,15 @@ export const marketRouter = router({
}
}),
- // ============================== Code Interpreter ==============================
+ /** @deprecated Use execInSandbox instead. Will be removed in a future version. */
callCodeInterpreterTool: marketToolProcedure
- .input(callCodeInterpreterToolSchema)
- .mutation(async ({ input, ctx }) => {
- const { toolName, params, topicId } = input;
- // Use client-provided userId if available, otherwise fallback to authenticated userId
- const userId = input?.userId || ctx.userId;
-
- log('Calling cloud code interpreter tool: %s with params: %O', toolName, {
- params,
- topicId,
- userId,
- });
-
- try {
- // For execScript tool, look up skill zipUrl if config is provided
- let enhancedParams = params;
- if (toolName === 'execScript' && params.config) {
- const agentSkillModel = new AgentSkillModel(ctx.serverDB, userId);
-
- // Look up skill by name
- let skill;
- if (params.config.name) {
- skill = await agentSkillModel.findByName(params.config.name);
-
- // If skill not found, return error with available skills
- if (!skill) {
- const allSkills = await agentSkillModel.findAll();
- const availableSkills = allSkills.data.map((s) => s.name).join(', ');
-
- const errorMessage = availableSkills
- ? `Skill "${params.config.name}" not found. Available skills: ${availableSkills}`
- : `Skill "${params.config.name}" not found. No skills available. Please import a skill first.`;
-
- log('Skill not found: %s. Available skills: %s', params.config.name, availableSkills);
-
- return {
- error: {
- message: errorMessage,
- name: 'SkillNotFound',
- },
- result: null,
- sessionExpiredAndRecreated: false,
- success: false,
- } as CallToolResult;
- }
- }
-
- // If skill exists and has zipFileHash, get the full URL
- if (skill?.zipFileHash) {
- const fileService = ctx.fileService;
- // Get S3 key from globalFiles
- const fileModel = new FileModel(ctx.serverDB, userId);
- const fileInfo = await fileModel.checkHash(skill.zipFileHash);
-
- if (fileInfo.isExist && fileInfo.url) {
- // Convert S3 key to full URL
- const fullUrl = await fileService.getFullFileUrl(fileInfo.url);
- if (fullUrl) {
- // Add zipUrl to params
- enhancedParams = {
- ...params,
- zipUrl: fullUrl,
- };
- log('Added zipUrl to execScript params for skill %s: %s', skill.name, fullUrl);
- }
- }
- }
- }
-
- // Use marketService from ctx
- const market = ctx.marketService.market;
-
- // Call market-sdk's runBuildInTool
- const response = await market.plugins.runBuildInTool(
- toolName as CodeInterpreterToolName,
- enhancedParams as any,
- { topicId, userId },
- );
-
- log('Cloud code interpreter tool %s response: %O', toolName, response);
+ .input(execInSandboxSchema)
+ .mutation(({ input, ctx }) => execInSandboxHandler({ ctx, input })),
- if (!response.success) {
- return {
- error: {
- message: response.error?.message || 'Unknown error',
- name: response.error?.code,
- },
- result: null,
- sessionExpiredAndRecreated: false,
- success: false,
- } as CallToolResult;
- }
-
- return {
- result: response.data?.result,
- sessionExpiredAndRecreated: response.data?.sessionExpiredAndRecreated || false,
- success: true,
- } as CallToolResult;
- } catch (error) {
- log('Error calling cloud code interpreter tool %s: %O', toolName, error);
-
- return {
- error: {
- message: (error as Error).message,
- name: (error as Error).name,
- },
- result: null,
- sessionExpiredAndRecreated: false,
- success: false,
- } as CallToolResult;
- }
- }),
+ // ============================== Sandbox Execution ==============================
+ execInSandbox: marketToolProcedure
+ .input(execInSandboxSchema)
+ .mutation(({ input, ctx }) => execInSandboxHandler({ ctx, input })),
// ============================== LobeHub Skill ==============================
/**
@@ -585,7 +606,7 @@ export const marketRouter = router({
/**
* Export a file from sandbox and upload to S3, then create a persistent file record
- * This combines the previous getExportFileUploadUrl + callCodeInterpreterTool + createFileRecord flow
+ * This combines the previous getExportFileUploadUrl + execInSandbox + createFileRecord flow
* Returns a permanent /f/:id URL instead of a temporary pre-signed URL
*/
exportAndUploadFile: marketToolProcedure
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.test.ts b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
index ddb029c4925..5d048c2f4cc 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
@@ -689,7 +689,7 @@ describe('AgentRuntimeService', () => {
data: { items: [1, 2, 3] },
executionTime: 200,
isSuccess: true,
- toolCall: { identifier: 'lobe-skills', apiName: 'runSkill', id: 'tc-2' },
+ toolCall: { identifier: 'lobe-skills', apiName: 'activateSkill', id: 'tc-2' },
toolCallId: 'tc-2',
},
],
@@ -718,7 +718,7 @@ describe('AgentRuntimeService', () => {
output: 'Result from tool A',
}),
expect.objectContaining({
- apiName: 'runSkill',
+ apiName: 'activateSkill',
identifier: 'lobe-skills',
output: JSON.stringify({ items: [1, 2, 3] }),
}),
diff --git a/src/server/services/toolExecution/preprocessLhCommand.ts b/src/server/services/toolExecution/preprocessLhCommand.ts
new file mode 100644
index 00000000000..feaf90ef391
--- /dev/null
+++ b/src/server/services/toolExecution/preprocessLhCommand.ts
@@ -0,0 +1,56 @@
+import debug from 'debug';
+
+import { appEnv } from '@/envs/app';
+import { signUserJWT } from '@/libs/trpc/utils/internalJwt';
+import { isDev } from '@/utils/env';
+
+const log = debug('lobe-server:lh-command');
+
+export interface PreprocessResult {
+ command: string;
+ error?: string;
+ isLhCommand: boolean;
+ skipSkillLookup: boolean;
+}
+
+/**
+ * Detect and preprocess `lh` CLI commands.
+ * - Replaces `lh` with `npx -y @lobehub/cli`
+ * - Injects LOBEHUB_JWT and LOBEHUB_SERVER env vars
+ * - Signals caller to skip skill DB lookup
+ */
+export const preprocessLhCommand = async (
+ command: string,
+ userId: string,
+): Promise<PreprocessResult> => {
+ const isLhCommand = /^lh\s/.test(command) || command === 'lh';
+
+ if (!isLhCommand) {
+ return { command, isLhCommand: false, skipSkillLookup: false };
+ }
+
+ try {
+ const jwt = await signUserJWT(userId);
+
+ const serverUrl = isDev ? 'https://app.lobehub.com' : appEnv.APP_URL;
+
+ const rewritten = command.replace(/^lh/, 'npx -y @lobehub/cli');
+ const finalCommand = `LOBEHUB_JWT=${jwt} LOBEHUB_SERVER=${serverUrl} ${rewritten}`;
+
+ log(
+ 'Intercepted lh command for user %s, rewritten to: %s',
+ userId,
+ finalCommand.replace(jwt, '<redacted>'),
+ );
+
+ return { command: finalCommand, isLhCommand: true, skipSkillLookup: true };
+ } catch (error) {
+ log('Failed to sign user JWT for lh command: %O', error);
+ return {
+ command,
+ error: 'Failed to authenticate for CLI execution',
+ isLhCommand: true,
+ skipSkillLookup: true,
+ };
+ }
+};
diff --git a/src/server/services/toolExecution/serverRuntimes/skills.ts b/src/server/services/toolExecution/serverRuntimes/skills.ts
index d698766f0b6..6aa4896884b 100644
--- a/src/server/services/toolExecution/serverRuntimes/skills.ts
+++ b/src/server/services/toolExecution/serverRuntimes/skills.ts
@@ -18,6 +18,7 @@ import { FileS3 } from '@/server/modules/S3';
import { FileService } from '@/server/services/file';
import { MarketService } from '@/server/services/market';
import { SkillResourceService } from '@/server/services/skill/resource';
+import { preprocessLhCommand } from '@/server/services/toolExecution/preprocessLhCommand';
import { type ServerRuntimeRegistration } from './types';
@@ -69,6 +70,55 @@ class SkillServerRuntimeService implements SkillRuntimeService {
return this.resourceService.readResource(skill.resources, path);
};
+ runCommand = async (options: { command: string }): Promise<CommandResult> => {
+ if (!this.topicId) {
+ throw new Error('topicId is required for runCommand');
+ }
+
+ // Preprocess lh commands: rewrite to npx @lobehub/cli + inject auth env vars
+ const lhResult = await preprocessLhCommand(options.command, this.userId);
+ if (lhResult.error) {
+ return { exitCode: 1, output: '', stderr: lhResult.error, success: false };
+ }
+
+ try {
+ const market = this.marketService.market;
+ const response = await market.plugins.runBuildInTool(
+ 'runCommand' as any,
+ { command: lhResult.command },
+ { topicId: this.topicId, userId: this.userId },
+ );
+
+ log('runCommand response: %O', response);
+
+ if (!response.success) {
+ return {
+ exitCode: 1,
+ output: '',
+ stderr: response.error?.message || 'Command execution failed',
+ success: false,
+ };
+ }
+
+ const result = response.data?.result || {};
+
+ return {
+ exitCode: result.exitCode ?? (response.success ? 0 : 1),
+ output: result.stdout || result.output || '',
+ stderr: result.stderr || '',
+ success: response.success && (result.exitCode === 0 || result.exitCode === undefined),
+ };
+ } catch (error) {
+ log('Error running command: %O', error);
+ return {
+ exitCode: 1,
+ output: '',
+ stderr: (error as Error).message || 'Command execution failed',
+ success: false,
+ };
+ }
+ };
+
execScript = async (
command: string,
options: {
diff --git a/src/services/cloudSandbox.ts b/src/services/cloudSandbox.ts
index 7a6bbecbd8e..3099763ffff 100644
--- a/src/services/cloudSandbox.ts
+++ b/src/services/cloudSandbox.ts
@@ -1,7 +1,7 @@
import { toolsClient } from '@/libs/trpc/client';
import {
- type CallCodeInterpreterToolInput,
type CallToolResult,
+ type ExecInSandboxInput,
type ExportAndUploadFileInput,
type ExportAndUploadFileResult,
} from '@/server/routers/tools/market';
@@ -18,14 +18,14 @@ class CloudSandboxService {
params: Record<string, any>,
context: { topicId: string; userId?: string },
): Promise<CallToolResult> {
- const input: CallCodeInterpreterToolInput = {
+ const input: ExecInSandboxInput = {
params,
toolName,
topicId: context.topicId,
userId: context.userId,
};
- return toolsClient.market.callCodeInterpreterTool.mutate(input);
+ return toolsClient.market.execInSandbox.mutate(input);
}
/**