以工具的形式提供技能
This commit is contained in:
@@ -6,5 +6,7 @@ app/config.yml
|
||||
/config.yml
|
||||
app/data/
|
||||
data/
|
||||
skills/deps/
|
||||
skills/*/.deps_installed
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
@@ -25,6 +25,12 @@ terminal:
|
||||
default_timeout_ms: 30000
|
||||
max_output_chars: 10000
|
||||
|
||||
# Skill Manager:技能根目录,所有任务/会话共享(容器内挂 ./skills → /workspace/skills)。
|
||||
# skills_root 缺省取 workspace_root 的同级 skills 目录(如 /workspace/tasks → /workspace/skills);可显式覆盖。
|
||||
skills:
|
||||
skills_root: "/workspace/skills"
|
||||
timeout_ms: 120000 # 单个技能执行超时,默认 120 秒
|
||||
|
||||
agent:
|
||||
temperature: 1.0
|
||||
max_tool_iterations: 50
|
||||
|
||||
@@ -9,6 +9,9 @@ const DEFAULTS = {
|
||||
db_path: '', // 默认为 workspace_root/.agent.db
|
||||
terminal: { default_timeout_ms: 30000, max_output_chars: 10000 },
|
||||
agent: { temperature: 1.0, max_tool_iterations: 50, max_retries: 2 },
|
||||
// 技能(Skill Manager):skills_root 为技能根目录,所有任务/会话共享(容器内挂我 ./skills → /workspace/skills);
|
||||
// 缺省取 workspace_root 的同级目录 skills(如 /workspace/tasks → /workspace/skills)。timeout_ms 为单个技能执行超时,默认 120000。
|
||||
skills: { skills_root: '', timeout_ms: 120000 },
|
||||
// 回合结束后模型保持占用(held)的租约:页内无人观看超过 idle_release_ms 则释放;
|
||||
// 即便一直有人观看,最长也只保持 active_max_ms;sweep_ms 为巡检间隔。
|
||||
// 「绑定模型但闲置」的会话(从未发言、无未回应消息)同样按此租约释放,防建而不用霸占模型。
|
||||
@@ -59,6 +62,16 @@ function loadConfig(configPath) {
|
||||
cfg.workspace_root = path.resolve(cfg.workspace_root);
|
||||
if (!cfg.db_path) cfg.db_path = path.join(cfg.workspace_root, '.agent.db');
|
||||
|
||||
// 技能根目录:显式配置优先;缺省取 workspace_root 的同级 skills 目录(容器内 /workspace/tasks → /workspace/skills)。
|
||||
if (!cfg.skills || !cfg.skills.skills_root) {
|
||||
cfg.skills_root = path.resolve(cfg.workspace_root, '..', 'skills');
|
||||
} else {
|
||||
cfg.skills_root = path.resolve(cfg.skills.skills_root);
|
||||
}
|
||||
if (cfg.skills) {
|
||||
cfg.skills.timeout_ms = (cfg.skills.timeout_ms == null) ? 120000 : cfg.skills.timeout_ms;
|
||||
}
|
||||
|
||||
// auth 规范化:多用户 auth.users: [{user, password}];兼容旧的单用户 auth.{user,password}
|
||||
if (cfg.auth && !Array.isArray(cfg.auth.users)) {
|
||||
cfg.auth.users = cfg.auth.user ? [{ user: cfg.auth.user, password: cfg.auth.password }] : [];
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "copy_path",
|
||||
"description": "Copies a file or directory in the project, and returns confirmation that the copy succeeded.\nDirectory contents will be copied recursively.\n\nThis tool should be used when it's desirable to create a copy of a file or directory without modifying the original.\nIt's much more efficient than doing this by separately reading and then writing the file or directory's contents, so this tool should be preferred over that approach whenever copying is the goal.\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.",
|
||||
"description": "Copies a file or directory in the project, and returns confirmation that the copy succeeded.\nDirectory contents will be copied recursively.\n\nThis tool should be used when it's desirable to create a copy of a file or directory without modifying the original.\nIt's much more efficient than doing this by separately reading and then writing the file or directory's contents, so this tool should be preferred over that approach whenever copying is the goal.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"source_path",
|
||||
@@ -27,14 +27,14 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "create_directory",
|
||||
"description": "Creates a new directory at the specified path within the project. Returns confirmation that the directory was created.\n\nThis tool creates a directory and all necessary parent directories. It should be used whenever you need to create new directories within the project.\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
|
||||
"description": "Creates a new directory at the specified path within the project. Returns confirmation that the directory was created.\n\nThis tool creates a directory and all necessary parent directories. It should be used whenever you need to create new directories within the project.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path"
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The path of the new directory.\n\n<example>\nIf the project has the following structure:\n\n- directory1/\n- directory2/\n\nYou can create a new directory by providing a path of \"directory1/new_directory\"\n</example>\n\n<example>\nTo create a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.\n</example>",
|
||||
"description": "The path of the new directory.\n\n<example>\nIf the project has the following structure:\n\n- directory1/\n- directory2/\n\nYou can create a new directory by providing a path of \"directory1/new_directory\"\n</example>",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
@@ -46,7 +46,7 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "delete_path",
|
||||
"description": "Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.\n\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.",
|
||||
"description": "Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path"
|
||||
@@ -65,7 +65,7 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "edit_file",
|
||||
"description": "This is a tool for applying edits to an existing file.\n\nBefore using this tool, use the `read_file` tool to understand the file's contents and context.\nTo create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.\n\n`read_file` prefixes each line of its output with a line number right-aligned in a\n6-character field followed by a single tab, then the line's actual content. When you\nderive `old_text` or `new_text` from that output, strip this prefix and keep only what\ncomes after the tab, preserving the original indentation (tabs and spaces) exactly.\nNever include any part of the line number prefix in `old_text` or `new_text`.",
|
||||
"description": "This is a tool for applying edits to an existing file.\n\nBefore using this tool, use the `read_file` tool to understand the file's contents and context.\nTo create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.\n\n`read_file` prefixes each line of its output with a line number right-aligned in a\n6-character field followed by a single tab, then the line's actual content. When you\nderive `old_text` or `new_text` from that output, strip this prefix and keep only what\ncomes after the tab, preserving the original indentation (tabs and spaces) exactly.\nNever include any part of the line number prefix in `old_text` or `new_text`.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path",
|
||||
@@ -73,7 +73,7 @@
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The full path of the file to edit in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n<example>\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n</example>\n\n<example>\n`frontend/db.js`\n</example>\n\n<example>\nTo edit a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n</example>",
|
||||
"description": "The full path of the file to edit in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories,\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n<example>\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n</example>\n\n<example>\n`frontend/db.js`\n</example>",
|
||||
"type": "string"
|
||||
},
|
||||
"edits": {
|
||||
@@ -107,7 +107,7 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "fetch",
|
||||
"description": "Fetches a URL and returns the content as Markdown.\n\nThis tool is not run inside the terminal OS sandbox, but it still refuses to\nreach any host that hasn't been granted network access. It shares the same\nper-host grants as the `terminal` tool: approving a host for one authorizes\nit for the other, whether the grant is for this thread or saved permanently.\nWhen unsandboxed access has been granted, these restrictions are lifted\nentirely, matching the terminal, which is also how loopback and IP-literal\nhosts (which can't be granted individually) become reachable.",
|
||||
"description": "Fetches a URL and returns the content as Markdown.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"url"
|
||||
@@ -186,14 +186,14 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "list_directory",
|
||||
"description": "Lists files and directories in a given path. Prefer the `grep` or `find_path` tools when searching the codebase.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
|
||||
"description": "Lists files and directories in a given path. Prefer the `grep` or `find_path` tools when searching the codebase.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path"
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The fully-qualified path of the directory to list in the project.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill directory under `~/.agents/skills`.\n\n<example>\nIf the project has the following root directories:\n\n- directory1\n- directory2\n\nYou can list the contents of `directory1` by using the path `directory1`.\n</example>\n\n<example>\nIf the project has the following root directories:\n\n- foo\n- bar\n\nIf you wanna list contents in the directory `foo/baz`, you should use the path `foo/baz`.\n</example>\n\n<example>\nTo list a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.\n</example>",
|
||||
"description": "The fully-qualified path of the directory to list in the project.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project,\n\n<example>\nIf the project has the following root directories:\n\n- directory1\n- directory2\n\nYou can list the contents of `directory1` by using the path `directory1`.\n</example>\n\n<example>\nIf the project has the following root directories:\n\n- foo\n- bar\n\nIf you wanna list contents in the directory `foo/baz`, you should use the path `foo/baz`.\n</example>",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
@@ -205,7 +205,7 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "move_path",
|
||||
"description": "Moves or rename a file or directory in the project, and returns confirmation that the move succeeded.\n\nIf the source and destination directories are the same, but the filename is different, this performs a rename. Otherwise, it performs a move.\n\nThis tool should be used when it's desirable to move or rename a file or directory without changing its contents at all.\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.",
|
||||
"description": "Moves or rename a file or directory in the project, and returns confirmation that the move succeeded.\n\nIf the source and destination directories are the same, but the filename is different, this performs a rename. Otherwise, it performs a move.\n\nThis tool should be used when it's desirable to move or rename a file or directory without changing its contents at all.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"source_path",
|
||||
@@ -229,14 +229,14 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "read_file",
|
||||
"description": "Reads the content of the given file in the project.\n\n- Never attempt to read a path that hasn't been previously mentioned.\n- For large files, this tool returns a file outline with symbol names and line numbers instead of the full content.\n This outline IS a successful response - use the line numbers to read specific sections with start_line/end_line.\n Do NOT retry reading the same file without line numbers if you receive an outline.\n- This tool supports reading image files. Supported formats: PNG, JPEG, WebP, GIF, BMP, TIFF.\n Image files are returned as visual content that you can analyze directly.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
|
||||
"description": "Reads the content of the given file in the project.\n\n- Never attempt to read a path that hasn't been previously mentioned.\n- For large files, this tool returns a file outline with symbol names and line numbers instead of the full content.\n This outline IS a successful response - use the line numbers to read specific sections with start_line/end_line.\n Do NOT retry reading the same file without line numbers if you receive an outline.\n- This tool supports reading image files. Supported formats: PNG, JPEG, WebP, GIF, BMP, TIFF.\n Image files are returned as visual content that you can analyze directly.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path"
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The relative path of the file to read.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill under `~/.agents/skills`.\n\n<example>\nIf the project has the following root directories:\n\n- /a/b/directory1\n- /c/d/directory2\n\nIf you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.\nIf you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.\n</example>\n\n<example>\nTo read a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n</example>",
|
||||
"description": "The relative path of the file to read.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project,\n\n<example>\nIf the project has the following root directories:\n\n- /a/b/directory1\n- /c/d/directory2\n\nIf you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.\nIf you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.\n</example>",
|
||||
"type": "string"
|
||||
},
|
||||
"start_line": {
|
||||
@@ -306,7 +306,7 @@
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "write_file",
|
||||
"description": "This is a tool for creating a new file or overwriting an existing file with completely new contents.\n\nTo make granular edits to an existing file, prefer the `edit_file` tool instead.\n\nBefore using this tool, verify the directory path is correct (only applicable when creating new files). Use the `list_directory` tool to verify the parent directory exists and is the correct location\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
|
||||
"description": "This is a tool for creating a new file or overwriting an existing file with completely new contents.\n\nTo make granular edits to an existing file, prefer the `edit_file` tool instead.\n\nBefore using this tool, verify the directory path is correct (only applicable when creating new files). Use the `list_directory` tool to verify the parent directory exists and is the correct location",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path",
|
||||
@@ -314,7 +314,7 @@
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The full path of the file to create or overwrite in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n<example>\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n</example>\n\n<example>\n`frontend/db.js`\n</example>\n\n<example>\nTo create or overwrite a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n</example>",
|
||||
"description": "The full path of the file to create or overwrite in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories,\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n<example>\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n</example>\n\n<example>\n`frontend/db.js`\n</example>",
|
||||
"type": "string"
|
||||
},
|
||||
"content": {
|
||||
@@ -325,5 +325,60 @@
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "list_skills",
|
||||
"description": "列出技能根目录下的所有可用技能,返回每个技能的名称与简要描述。\n\n技能是自包含的目录(含 SKILL.md 描述与 run.py/run.sh 可执行入口),用于复用已有能力。先调用本工具了解有哪些技能,再决定是否用 get_skill_info 查看详情或用 run_skill 执行。\n\n- 无需参数。\n- 若技能目录不存在,返回空列表。",
|
||||
"parameters": {
|
||||
"required": [],
|
||||
"properties": {},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_skill_info",
|
||||
"description": "查看指定技能的完整说明(返回该技能目录下 SKILL.md 的全文),便于了解其用途、参数(input_schema)与调用方式。",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"skill_name"
|
||||
],
|
||||
"properties": {
|
||||
"skill_name": {
|
||||
"description": "技能名称(即技能根目录下的子目录名,如 md2pdf)",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "run_skill",
|
||||
"description": "执行指定技能,传入所需参数,自动检查与安装依赖(pip install --target 装入共享 deps 目录并以 PYTHONPATH 注入,或执行 install.sh),返回技能运行的标准输出或错误信息。\n\n技能入口脚本约定接收一个 JSON 字符串作为唯一命令行参数,其中包含全部输入参数键值对。\n\n- 执行前会根据 SKILL.md 的 input_schema.required 校验必填参数。\n- 依赖安装有缓存标记 .deps_installed,仅当 requirements.txt / install.sh 变化时重装。\n- 默认超时 120 秒。\n- input_args 中的相对路径会按会话工作目录自动解析并转为绝对路径(技能进程的工作目录是技能目录,不是会话目录),直接传相对路径即可。",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"skill_name",
|
||||
"input_args"
|
||||
],
|
||||
"properties": {
|
||||
"skill_name": {
|
||||
"description": "技能名称(技能根目录下的子目录名,如 md2pdf)",
|
||||
"type": "string"
|
||||
},
|
||||
"input_args": {
|
||||
"description": "技能所需的输入参数字典(对象),键值对形式。例如 {\"input\": \"file.md\", \"output\": \"out.pdf\"}。具体字段以 get_skill_info 查看的 SKILL.md 为准。路径参数可传相对会话工作目录的路径,也可传绝对路径,后者原样使用。",
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -6,6 +6,7 @@ const fsp = require('fs').promises;
|
||||
const { spawn } = require('child_process');
|
||||
const { Minimatch } = require('minimatch');
|
||||
const mcp = require('../mcp');
|
||||
const skills = require('./skills');
|
||||
|
||||
function makeMatcher(pattern, opts) {
|
||||
const mm = new Minimatch(pattern, opts || {});
|
||||
@@ -640,6 +641,9 @@ const HANDLERS = {
|
||||
grep: toolGrep,
|
||||
terminal: toolTerminal,
|
||||
fetch: toolFetch,
|
||||
list_skills: async (ctx, args) => JSON.stringify(await skills.listSkills(ctx), null, 2),
|
||||
get_skill_info: (ctx, args) => skills.getSkillInfo(ctx, args.skill_name),
|
||||
run_skill: (ctx, args) => skills.runSkill(ctx, args.skill_name, args.input_args),
|
||||
};
|
||||
|
||||
// ctx: {sessionId, taskDir, run, cfg, db}
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
// Skill Manager:发现、查看与执行技能,并在执行前自动检查与安装依赖。
|
||||
// 技能统一存放于技能根目录(cfg.skills_root,所有任务/会话共享;容器内挂 ./skills → /workspace/skills),每个技能一个子目录:
|
||||
// <skill>/SKILL.md(必须)、run.py | run.sh(入口)、requirements.txt、install.sh(可选)。
|
||||
// 入口脚本约定接收一个 JSON 字符串作为唯一命令行参数(含全部 input_args)。
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const { spawn } = require('child_process');
|
||||
const YAML = require('yaml');
|
||||
|
||||
class SkillNotFoundError extends Error {
|
||||
constructor(msg) { super(msg); this.name = 'SkillNotFoundError'; }
|
||||
}
|
||||
class SkillExecutionError extends Error {
|
||||
constructor(msg, code) { super(msg); this.name = 'SkillExecutionError'; this.code = code; }
|
||||
}
|
||||
class DependencyInstallError extends Error {
|
||||
constructor(msg, code) { super(msg); this.name = 'DependencyInstallError'; this.code = code; }
|
||||
}
|
||||
|
||||
// 技能根目录:优先 cfg.skills_root(config.yml 配置,所有任务共享);缺省取 workspace_root 的同级 skills 目录。
|
||||
function skillsRoot(ctx) {
|
||||
if (ctx.cfg && ctx.cfg.skills_root) return ctx.cfg.skills_root;
|
||||
if (ctx.cfg && ctx.cfg.skills && ctx.cfg.skills.skills_root) return path.resolve(ctx.cfg.skills.skills_root);
|
||||
return path.resolve(ctx.cfg.workspace_root, '..', 'skills');
|
||||
}
|
||||
|
||||
function skillDir(ctx, skillName) {
|
||||
const name = String(skillName || '').trim();
|
||||
if (!name) throw new SkillNotFoundError('技能名为空');
|
||||
if (name.includes('/') || name.includes('..')) throw new SkillNotFoundError('非法技能名:' + name);
|
||||
return path.join(skillsRoot(ctx), name);
|
||||
}
|
||||
|
||||
// 解析 SKILL.md 的 YAML Front Matter;无 Front Matter 返回 {}。
|
||||
function parseFrontMatter(content) {
|
||||
const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(content);
|
||||
if (!m) return {};
|
||||
try { return YAML.parse(m[1]) || {}; } catch (_) { return {}; }
|
||||
}
|
||||
|
||||
// 提取描述:优先 Front Matter 的 description,回退为第一个非标题文本行。
|
||||
function extractDescription(content) {
|
||||
const fm = parseFrontMatter(content);
|
||||
if (fm.description && String(fm.description).trim()) return String(fm.description).trim();
|
||||
const line = content.split(/\r?\n/).map(l => l.trim()).find(l => l && !/^#/.test(l));
|
||||
return line || '(无描述)';
|
||||
}
|
||||
|
||||
// ---------- 3.1 list_skills ----------
|
||||
async function listSkills(ctx) {
|
||||
const root = skillsRoot(ctx);
|
||||
if (!fs.existsSync(root)) {
|
||||
console.log('[skills] 技能根目录不存在:' + root);
|
||||
return [];
|
||||
}
|
||||
const out = [];
|
||||
const entries = await fsp.readdir(root, { withFileTypes: true });
|
||||
for (const e of entries) {
|
||||
if (!e.isDirectory()) continue;
|
||||
const mdPath = path.join(root, e.name, 'SKILL.md');
|
||||
if (!fs.existsSync(mdPath)) continue;
|
||||
let content;
|
||||
try { content = await fsp.readFile(mdPath, 'utf8'); } catch (_) { continue; }
|
||||
out.push({ name: e.name, description: extractDescription(content) });
|
||||
}
|
||||
out.sort((a, b) => a.name.localeCompare(b.name));
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------- 3.2 get_skill_info ----------
|
||||
async function getSkillInfo(ctx, skillName) {
|
||||
const dir = skillDir(ctx, skillName);
|
||||
const mdPath = path.join(dir, 'SKILL.md');
|
||||
if (!fs.existsSync(mdPath)) {
|
||||
throw new SkillNotFoundError('技能不存在或缺少 SKILL.md:' + skillName);
|
||||
}
|
||||
return fsp.readFile(mdPath, 'utf8');
|
||||
}
|
||||
|
||||
// ---------- 依赖安装 ----------
|
||||
// 不用虚拟环境(每个技能一份 .venv 太占空间,且容器重建后全丢):
|
||||
// pip install --target 装到技能根目录下的共享 deps 目录(容器内 /workspace/skills/deps,
|
||||
// 随挂载卷持久化,重建镜像不丢);运行时通过 PYTHONPATH 让 Python 找到它们。
|
||||
function depsRoot(ctx) {
|
||||
return path.join(skillsRoot(ctx), 'deps');
|
||||
}
|
||||
|
||||
// 技能子进程环境:PYTHONPATH 追加共享依赖目录(sys.path 的搜索路径,非标准库覆盖)。
|
||||
function skillEnv(ctx) {
|
||||
const deps = depsRoot(ctx);
|
||||
const existing = process.env.PYTHONPATH;
|
||||
return Object.assign({}, process.env, { PYTHONPATH: existing ? deps + ':' + existing : deps });
|
||||
}
|
||||
|
||||
function hashFile(p) {
|
||||
try { return crypto.createHash('sha1').update(fs.readFileSync(p)).digest('hex'); } catch (_) { return ''; }
|
||||
}
|
||||
|
||||
// 在技能目录下执行一个前台命令,返回 stdout+stderr;非零退出抛 DependencyInstallError。
|
||||
// 安装命令兼有硬超时(默认 10 分钟),防 pip/apt 挂死阻塞会话。
|
||||
function execSyncCapture(cmd, args, cwd, timeoutMs) {
|
||||
const limit = timeoutMs || 600000;
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(cmd, args, { cwd, env: process.env, detached: true });
|
||||
let out = '';
|
||||
let settled = false;
|
||||
const onData = d => { out += d.toString(); };
|
||||
child.stdout.on('data', onData);
|
||||
child.stderr.on('data', onData);
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
|
||||
reject(new DependencyInstallError('依赖安装超时(' + limit + 'ms)已终止:\n' + out.trim(), -1));
|
||||
}, limit);
|
||||
child.on('error', err => {
|
||||
if (settled) return;
|
||||
settled = true; clearTimeout(timer);
|
||||
reject(new DependencyInstallError('依赖命令启动失败:' + err.message, -1));
|
||||
});
|
||||
child.on('close', code => {
|
||||
if (settled) return;
|
||||
settled = true; clearTimeout(timer);
|
||||
if (code === 0) resolve(out.trim());
|
||||
else reject(new DependencyInstallError((out.trim() || ('依赖命令退出码 ' + code)) + ' [exit: ' + code + ']', code));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 安装依赖并写缓存标记 .deps_installed(内容为依赖文件 hash,变化则重装)。
|
||||
// Python 依赖装进共享 deps 目录;install.sh 用于系统级依赖,直接执行。
|
||||
async function ensureDeps(ctx, dir, skillName) {
|
||||
const reqPath = path.join(dir, 'requirements.txt');
|
||||
const installPath = path.join(dir, 'install.sh');
|
||||
const hasReq = fs.existsSync(reqPath);
|
||||
const hasInstall = fs.existsSync(installPath);
|
||||
if (!hasReq && !hasInstall) return;
|
||||
|
||||
const need = 'req:' + hashFile(reqPath) + '|install:' + hashFile(installPath);
|
||||
const markerPath = path.join(dir, '.deps_installed');
|
||||
if (fs.existsSync(markerPath) && fs.readFileSync(markerPath, 'utf8') === need) {
|
||||
console.log('[skills] ' + skillName + ' 依赖已安装(命中缓存)');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (hasReq) {
|
||||
const target = depsRoot(ctx);
|
||||
fs.mkdirSync(target, { recursive: true });
|
||||
console.log('[skills] ' + skillName + ':pip install --target ' + target);
|
||||
await execSyncCapture('python3', ['-m', 'pip', 'install', '--target', target, '-r', reqPath], dir);
|
||||
}
|
||||
if (hasInstall) {
|
||||
console.log('[skills] ' + skillName + ':执行 install.sh');
|
||||
await execSyncCapture('bash', ['install.sh'], dir);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof DependencyInstallError) throw e;
|
||||
throw new DependencyInstallError('依赖安装失败:' + e.message, -1);
|
||||
}
|
||||
fs.writeFileSync(markerPath, need, 'utf8');
|
||||
console.log('[skills] ' + skillName + ':依赖安装完成');
|
||||
}
|
||||
|
||||
// ---------- 参数路径预处理 ----------
|
||||
// 技能进程的工作目录是技能目录,而 Agent 习惯传相对会话任务目录的路径;
|
||||
// 执行前统一把路径样式的相对参数转成绝对路径,技能脚本无感知。
|
||||
// 含路径分隔符,或以字母开头的扩展名结尾(排除 "1.5" 这类数字串误判)。
|
||||
function looksLikePath(v) {
|
||||
return /[\\/]/.test(v) || /\.\D\w{0,5}$/.test(v);
|
||||
}
|
||||
|
||||
function absolutizeValue(key, v, baseDir) {
|
||||
if (typeof v !== 'string' || !v.trim()) return v;
|
||||
const looksAbs = v.startsWith('/') || v.startsWith('\\') || /^[a-zA-Z]:[\\/]/.test(v);
|
||||
if (looksAbs) return v;
|
||||
const outputish = /out|dest|target|save/i.test(key);
|
||||
const exists = fs.existsSync(path.resolve(baseDir, v));
|
||||
if (outputish || exists || looksLikePath(v)) return path.resolve(baseDir, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
function absolutizeArgs(inputArgs, baseDir) {
|
||||
const out = {};
|
||||
for (const [k, v] of Object.entries(inputArgs || {})) out[k] = absolutizeValue(k, v, baseDir);
|
||||
return out;
|
||||
}
|
||||
|
||||
// 按 input_schema 校验 input_args(仅校验 required 字段存在且非空)。
|
||||
function validateArgs(fm, inputArgs, skillName) {
|
||||
const schema = fm && fm.input_schema;
|
||||
if (!schema || !Array.isArray(schema.required)) return;
|
||||
const missing = schema.required.filter(k => inputArgs[k] === undefined || inputArgs[k] === null || inputArgs[k] === '');
|
||||
if (missing.length) {
|
||||
throw new SkillExecutionError('技能 ' + skillName + ' 缺少必填参数:' + missing.join(', '), 1);
|
||||
}
|
||||
}
|
||||
|
||||
// 前台执行技能入口,带超时与取消支持;成功 resolve stdout,失败 reject SkillExecutionError。
|
||||
function runEntry(ctx, entry, args, cwd, timeoutMs) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(entry, args, { cwd, env: skillEnv(ctx), detached: true });
|
||||
if (ctx.run && ctx.run.procs) ctx.run.procs.add(child);
|
||||
let out = '';
|
||||
let settled = false;
|
||||
const onData = d => { out += d.toString(); };
|
||||
child.stdout.on('data', onData);
|
||||
child.stderr.on('data', onData);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearInterval(cancelCheck);
|
||||
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
|
||||
reject(new SkillExecutionError('技能执行超时(' + timeoutMs + 'ms)已终止:\n' + out.trim(), -1));
|
||||
}, timeoutMs);
|
||||
|
||||
const cancelCheck = setInterval(() => {
|
||||
if (ctx.run && ctx.run.cancelled && !settled) {
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { try { child.kill('SIGKILL'); } catch (__) {} }
|
||||
reject(new SkillExecutionError('技能执行被用户终止', -1));
|
||||
}
|
||||
}, 200);
|
||||
|
||||
child.on('error', err => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
clearInterval(cancelCheck);
|
||||
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
||||
reject(new SkillExecutionError('技能入口启动失败:' + err.message, -1));
|
||||
});
|
||||
child.on('close', code => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
clearInterval(cancelCheck);
|
||||
if (ctx.run && ctx.run.procs) ctx.run.procs.delete(child);
|
||||
const trimmed = out.replace(/\n+$/, '').trim();
|
||||
if (code === 0) resolve(trimmed || '(无输出)');
|
||||
else reject(new SkillExecutionError((trimmed || ('技能执行失败,退出码 ' + code)) + '\n[exit code: ' + code + ']', code));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 3.3 run_skill ----------
|
||||
async function runSkill(ctx, skillName, inputArgs) {
|
||||
const dir = skillDir(ctx, skillName);
|
||||
if (!fs.existsSync(dir)) throw new SkillNotFoundError('技能不存在:' + skillName);
|
||||
|
||||
const mdPath = path.join(dir, 'SKILL.md');
|
||||
if (!fs.existsSync(mdPath)) throw new SkillNotFoundError('技能缺少 SKILL.md:' + skillName);
|
||||
|
||||
// 先把相对路径参数按会话任务目录转成绝对路径(缺任务目录时退回进程当前目录)。
|
||||
const args = absolutizeArgs(inputArgs || {}, ctx.taskDir || process.cwd());
|
||||
const payload = JSON.stringify(args);
|
||||
|
||||
let fm = {};
|
||||
try { fm = parseFrontMatter(await fsp.readFile(mdPath, 'utf8')); } catch (_) {}
|
||||
validateArgs(fm, args, skillName);
|
||||
|
||||
await ensureDeps(ctx, dir, skillName);
|
||||
|
||||
let entry, cmdArgs;
|
||||
const runPy = path.join(dir, 'run.py');
|
||||
const runSh = path.join(dir, 'run.sh');
|
||||
if (fs.existsSync(runPy)) {
|
||||
// PYTHONPATH 已指向共享 deps,直接走系统 python3。
|
||||
entry = 'python3';
|
||||
cmdArgs = ['run.py', payload];
|
||||
} else if (fs.existsSync(runSh)) {
|
||||
entry = 'bash';
|
||||
cmdArgs = ['run.sh', payload];
|
||||
} else {
|
||||
throw new SkillExecutionError('技能 ' + skillName + ' 缺少入口 run.py 或 run.sh', 1);
|
||||
}
|
||||
|
||||
const timeoutMs = (ctx.cfg && ctx.cfg.skills && ctx.cfg.skills.timeout_ms) || 120000;
|
||||
console.log('[skills] 执行 ' + skillName + ':' + entry + ' ' + cmdArgs.join(' '));
|
||||
return runEntry(ctx, entry, cmdArgs, dir, timeoutMs);
|
||||
}
|
||||
|
||||
module.exports = { listSkills, getSkillInfo, runSkill, skillsRoot };
|
||||
@@ -7,6 +7,7 @@ services:
|
||||
- "8080" # 仅内网暴露,由 nginx-proxy 对外
|
||||
volumes:
|
||||
- ./data:/workspace/tasks # 持久化:任务目录 + SQLite(.agent.db 在此目录内)
|
||||
- ./skills:/workspace/skills # 技能目录:所有任务/会话共享同一份技能
|
||||
- ./config.yml:/app/config.yml:ro
|
||||
- ./app/server:/app/server
|
||||
environment:
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
name: md2pdf
|
||||
description: 将 Markdown 文件转换为 PDF(仅英文,简单排版)
|
||||
input_schema:
|
||||
type: object
|
||||
properties:
|
||||
input:
|
||||
type: string
|
||||
description: 输入 Markdown 文件路径
|
||||
output:
|
||||
type: string
|
||||
description: 输出 PDF 文件路径(可选,默认与输入同名)
|
||||
required: [input]
|
||||
output_schema:
|
||||
type: string
|
||||
description: 生成的 PDF 文件路径
|
||||
---
|
||||
|
||||
## 使用说明
|
||||
该技能使用 `reportlab` 将 Markdown 转换为 PDF。
|
||||
|
||||
本技能由 `run_skill` 调用,参数:
|
||||
- `input`(必填):Markdown 文件路径,支持相对路径(自动转为绝对路径)。
|
||||
- `output`(可选):PDF 输出路径,默认与输入文件同名。
|
||||
@@ -0,0 +1 @@
|
||||
reportlab==3.6.12
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
||||
from reportlab.lib.units import inch
|
||||
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, ListFlowable, ListItem
|
||||
from reportlab.lib.enums import TA_LEFT
|
||||
|
||||
def markdown_to_pdf(md_path: str, pdf_path: str):
|
||||
"""简化版 Markdown 转 PDF,支持标题、段落、无序列表"""
|
||||
md_text = Path(md_path).read_text(encoding="utf-8")
|
||||
lines = md_text.split("\n")
|
||||
|
||||
doc = SimpleDocTemplate(pdf_path, pagesize=A4,
|
||||
right_margin=72, left_margin=72,
|
||||
top_margin=72, bottom_margin=72)
|
||||
styles = getSampleStyleSheet()
|
||||
# 自定义样式
|
||||
h1_style = ParagraphStyle('H1Custom', parent=styles['Heading1'], fontSize=20, spaceAfter=12)
|
||||
h2_style = ParagraphStyle('H2Custom', parent=styles['Heading2'], fontSize=16, spaceAfter=10)
|
||||
body_style = ParagraphStyle('BodyCustom', parent=styles['BodyText'], fontSize=12, leading=16)
|
||||
list_style = ParagraphStyle('ListCustom', parent=styles['BodyText'], fontSize=12, leading=16)
|
||||
|
||||
story = []
|
||||
current_list = []
|
||||
in_list = False
|
||||
|
||||
def flush_list():
|
||||
nonlocal in_list, current_list
|
||||
if in_list and current_list:
|
||||
story.append(ListFlowable(
|
||||
[ListItem(Paragraph(item, list_style), leftIndent=20) for item in current_list],
|
||||
bulletType='bullet',
|
||||
start='circle',
|
||||
leftIndent=20
|
||||
))
|
||||
current_list = []
|
||||
in_list = False
|
||||
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
flush_list()
|
||||
continue
|
||||
|
||||
if line.startswith('# '):
|
||||
flush_list()
|
||||
story.append(Paragraph(line[2:], h1_style))
|
||||
elif line.startswith('## '):
|
||||
flush_list()
|
||||
story.append(Paragraph(line[3:], h2_style))
|
||||
elif line.startswith('- ') or line.startswith('* '):
|
||||
in_list = True
|
||||
current_list.append(line[2:])
|
||||
else:
|
||||
flush_list()
|
||||
story.append(Paragraph(line, body_style))
|
||||
|
||||
flush_list()
|
||||
|
||||
doc.build(story)
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: python run.py '<json_string>'")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
args = json.loads(sys.argv[1])
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Invalid JSON argument: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
input_path = args.get("input")
|
||||
if not input_path:
|
||||
print("Error: 'input' field is required")
|
||||
sys.exit(1)
|
||||
|
||||
output_path = args.get("output")
|
||||
if not output_path:
|
||||
output_path = str(Path(input_path).with_suffix(".pdf"))
|
||||
|
||||
try:
|
||||
markdown_to_pdf(input_path, output_path)
|
||||
print(f"PDF generated: {output_path}")
|
||||
except Exception as e:
|
||||
print(f"Error during conversion: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user