diff --git a/app/config.example.yml b/app/config.example.yml index 17af11d..8926601 100644 --- a/app/config.example.yml +++ b/app/config.example.yml @@ -4,11 +4,16 @@ # 模型平台池:每平台 {name, url, type?, models:[{id, ...}], keys:[{api_key, concurrency?}]}。 platforms: [] -# 模型 profile:prompt + tools 白名单组合,模型用 profile: <名> 引用(不配 = 全量)。 +# 全局工具黑名单:profile 未配 tools_deny 时继承它;allow 先、deny 后叠加(deny 赢,与 mcp_servers 同构)。 +# 写数组即整体覆盖默认值,写 [] 即清空。默认屏蔽元工具 lab。 +tools_deny: [lab] + +# 模型 profile:prompt + tools 名单组合,模型用 profile: <名> 引用(不配 = 全量)。 model_profiles: - mini: # 小模型:只留核心工具,省上下文 - tools_allow: [read_file, write_file, edit_file, terminal, fetch, web_search, skill] - system_prompt_file: mini-system.txt # 相对 server/templates/(也接受绝对路径) + lab: # 统一入口自测:tools 只有 lab,其余能力经 lab(help) 现场发现 + tools_allow: [lab] + tools_deny: [] # 必须显式清空全局黑名单,否则 lab 自己也被 deny → 零工具 + system_prompt_file: lab-system.txt # 相对 server/templates/(也接受绝对路径) zero: # 纯文本对话:一个工具都不发 tools_allow: [] system_prompt_file: zero-system.txt diff --git a/app/server/config.js b/app/server/config.js index a70ee94..f81d72d 100644 --- a/app/server/config.js +++ b/app/server/config.js @@ -19,14 +19,17 @@ function normToolNames(v) { // (compose 已 bind-mount ./app/server,宿主可直接编辑,无需重建镜像)。 const TEMPLATES_DIR = path.join(__dirname, 'templates'); -// model_profiles 归一化:顶层 map {名称: {tools_allow?, system_prompt_file?}}, +// model_profiles 归一化:顶层 map {名称: {tools_allow?, tools_deny?, system_prompt_file?}}, // 供 platforms[].models[].profile 引用(同 id 模型跳平台复用时免重复配置)。 // - tools_allow 只按最终发给模型的工具名匹配(内置名 + MCP 名,含冲突时加的 server__ 前缀)。 // 语义与 MCP 的 tools_allow(空数组=未配)有意不同:这里空数组 [] 是有效配置 = 一个工具都不发 // (纯文本模式,给弱到不会调工具的小模型用);只有「没写/非数组」才是「不过滤、发全量」。 +// - tools_deny:profile 级黑名单,在 allow 之后叠加生效(deny 赢,与 MCP 同构)。未配/非数组 = +// 继承全局 tools_deny(DEFAULTS 默认屏蔽 lab);[] = 显式清空(lab profile 靠它把元工具换回来); +// 非空 = 替换全局。同样只按最终名匹配。 // - system_prompt_file:相对 templates/(也接受绝对路径),配置加载时一次性读入常驻内存, // 运行期切换零 IO;缺失/读不到/内容为空直接报校验错——拦在保存/重启预检,不留到运行期降级。 -// - 两样都没配 = 不起任何作用,报错误防误配空壳。 +// - 三样都没配 = 不起任何作用,报错误防误配空壳。 function normalizeModelProfiles(rawProfiles) { const out = {}; if (!rawProfiles || typeof rawProfiles !== 'object' || Array.isArray(rawProfiles)) return out; @@ -34,12 +37,16 @@ function normalizeModelProfiles(rawProfiles) { const key = String(name).trim(); if (!key) continue; if (!p || typeof p !== 'object' || Array.isArray(p)) { - throw new Error('model_profiles.' + key + ' 必须是对象 {tools_allow, system_prompt_file}'); + throw new Error('model_profiles.' + key + ' 必须是对象 {tools_allow, tools_deny, system_prompt_file}'); } // 不用 normToolNames:那会把空数组吐成 undefined(丢抑「[] = 零工具」语义);这里只归一字符串项。 const tools_allow = Array.isArray(p.tools_allow) ? p.tools_allow.map(x => String(x).trim()).filter(Boolean) : undefined; + // tools_deny 与 allow 同款手工归一:[] 是有效配置(显式清空全局黑名单),不能被当「未配」。 + const tools_deny = Array.isArray(p.tools_deny) + ? p.tools_deny.map(x => String(x).trim()).filter(Boolean) + : undefined; const file = String(p.system_prompt_file || '').trim(); let prompt = ''; if (file) { @@ -50,10 +57,10 @@ function normalizeModelProfiles(rawProfiles) { prompt = prompt.trim(); if (!prompt) throw new Error('model_profiles.' + key + '.system_prompt_file 内容为空:' + abs); } - if (!tools_allow && !prompt) { - throw new Error('model_profiles.' + key + ' 至少需配 tools_allow 或 system_prompt_file 之一'); + if (!tools_allow && !tools_deny && !prompt) { + throw new Error('model_profiles.' + key + ' 至少需配 tools_allow / tools_deny / system_prompt_file 之一'); } - out[key] = { name: key, tools_allow, system_prompt_file: file, prompt }; + out[key] = { name: key, tools_allow, tools_deny, system_prompt_file: file, prompt }; } return out; } @@ -84,13 +91,14 @@ const DEFAULTS = { log_level: 'info', // 模型平台池(无默认值,结构见 config.example.yml)。 platforms: [], - // 模型 profile(prompt + tools 白名单组合):platforms 里的模型用 profile: <名> 引用。 + // 全局工具黑名单:profile 未配 tools_deny 时继承它;allow 先、deny 后叠加(deny 赢,与 mcp_servers 同构)。 + // 默认屏蔽元工具 lab:它只该出现在显式清空 deny 的 profile 里,不进任何常规请求的 tools 数组。 + tools_deny: ['lab'], + // 模型 profile(prompt + tools 名单组合):platforms 里的模型用 profile: <名> 引用。 model_profiles: { - // 小模型:只留文件/终端/网页等核心工具,省上下文。 - mini: { - tools_allow: ['read_file', 'write_file', 'edit_file', 'terminal', 'fetch', 'web_search', 'skill'], - system_prompt_file: 'mini-system.txt', - }, + // lab:统一入口元工具自测组合——tools 收缩到 1 个,其余能力经 lab(help) 现场发现。 + // tools_deny 必须显式清空:不配 = 继承全局 ['lab'],deny 后叠加会把 lab 自己禁掉 → 零工具。 + lab: { tools_allow: ['lab'], tools_deny: [], system_prompt_file: 'lab-system.txt' }, // 纯文本对话:一个工具都不发。 zero: { tools_allow: [], system_prompt_file: 'zero-system.txt' }, }, @@ -220,7 +228,11 @@ function parseAndValidate(rawText, configPath) { } // platforms 允许为空:可先起服务,再在前端设置页添加平台后重启(无模型时无会话可调度)。 const rawPlatforms = Array.isArray(raw.platforms) ? raw.platforms : []; - // 用 deepMerge 后的 cfg.model_profiles(含内置 mini/zero),故 config.yml 不配也有默认组合。 + // 全局黑名单归一:非数组视作未配;deepMerge 对数组整体替换,config.yml 写了即覆盖 DEFAULTS。 + cfg.tools_deny = Array.isArray(cfg.tools_deny) + ? cfg.tools_deny.map(x => String(x).trim()).filter(Boolean) + : undefined; + // 用 deepMerge 后的 cfg.model_profiles(含内置 lab/zero),故 config.yml 不配也有默认组合。 cfg.model_profiles = normalizeModelProfiles(cfg.model_profiles); cfg.platforms = normalizePlatforms(rawPlatforms, new Set(Object.keys(cfg.model_profiles))); cfg.models = []; diff --git a/app/server/engine.js b/app/server/engine.js index 6a6dd22..e115b4b 100644 --- a/app/server/engine.js +++ b/app/server/engine.js @@ -251,17 +251,25 @@ function resolveProfileName(session, run) { return m && m.profile ? String(m.profile) : ''; } -// 本轮工具定义集:内置 + MCP 全量;profile 配了 tools_allow 则按最终名过滤 -// (与发给模型的 tools 字段/prompt.txt dump 同源可对)。空数组 = 零工具(纯文本组合, +// 本轮工具定义集:内置 + MCP 全量;先 profile 的 tools_allow 白名单、再叠 tools_deny 黑名单 +// (deny 赢,与 mcp_servers 同构;profile 未配 deny = 继承全局 cfg.tools_deny,DEFAULTS 默认屏蔽元工具 lab), +// 按最终名过滤(与发给模型的 tools 字段/prompt.txt dump 同源可对)。allow 空数组 = 零工具(纯文本组合, // callModel 对空数组不发 tools 字段);未配 = 全量。只影响模型「看得到什么」: // 名单外但真实存在的工具若被调用,executor 照常执行(HANDLERS 全表分发),不拦不误杀。 function effectiveTools(profileName) { - const all = TOOL_DEFINITIONS.concat(mcp.toolDefinitions()); const prof = profileName && cfg.model_profiles && cfg.model_profiles[profileName]; const allow = prof && prof.tools_allow; - if (!Array.isArray(allow)) return all; - const set = new Set(allow); - return all.filter(t => t && t.function && set.has(t.function.name)); + const deny = prof && Array.isArray(prof.tools_deny) ? prof.tools_deny : cfg.tools_deny; + let out = TOOL_DEFINITIONS.concat(mcp.toolDefinitions()); + if (Array.isArray(allow)) { + const set = new Set(allow); + out = out.filter(t => t && t.function && set.has(t.function.name)); + } + if (Array.isArray(deny) && deny.length) { + const dset = new Set(deny); + out = out.filter(t => !t || !t.function || !dset.has(t.function.name)); + } + return out; } function hasModelProfile(name) { diff --git a/app/server/routes/messages.js b/app/server/routes/messages.js index cac9730..985c498 100644 --- a/app/server/routes/messages.js +++ b/app/server/routes/messages.js @@ -21,7 +21,7 @@ router.post('/:id/messages', wrap((req, res) => { if (!content) return res.status(400).json({ error: 'content 不能为空' }); // deepThink:是否启用模型该「深度思考」参数(thinking_params 合并进上游请求体) const deepThink = !!(req.body && req.body.deepThink); - // profile:本轮 prompt+tools 组合(config.yml 顶层 model_profiles 的名字;保留值 'default' = 显式全量; + // profile:本轮 prompt+tools 组合(config.yml 顶层 model_profiles 的名字;保留值 'default' = 显式全量(仍受全局 tools_deny 屏蔽); // 不传 = 随模型配置的 profile)。名字不存在直接 400 打回,不静默回退(难排查)。 const profile = String((req.body && req.body.profile) || '').trim(); if (profile && profile !== 'default' && !engine.hasModelProfile(profile)) { diff --git a/app/server/templates/lab-system.txt b/app/server/templates/lab-system.txt new file mode 100644 index 0000000..6cc8f2f --- /dev/null +++ b/app/server/templates/lab-system.txt @@ -0,0 +1,29 @@ +You are a general-purpose task assistant on a private server, accessed via a +web interface. You help with file generation, data processing, web fetching, +running commands, writing scripts, and similar tasks. + +Each conversation has its own working directory. Tool paths are relative to +it unless stated otherwise. + +## Tools + +All capabilities are reached through one tool: + + lab(tool: "", args: {}) + +To discover what is available: + + lab(tool: "help") → list all tools + lab(tool: "help", args: {tool: ""}) → parameters of a specific tool + +An unknown tool name returns the same list. Prefer calling directly when the +name and parameters are clear; use "help" when unsure. + +If a capability seems missing, check with "help" before saying it is +unavailable — do not assume it does not exist. + +## Communication + +- Be concise and direct. Plain language; Markdown when useful (code in code blocks). +- If unsure, say so. Don't over-apologize. +- Never fake results: no placeholder files, no claiming a file was created. diff --git a/app/server/templates/mini-system.txt b/app/server/templates/mini-system.txt deleted file mode 100644 index 8c02b55..0000000 --- a/app/server/templates/mini-system.txt +++ /dev/null @@ -1,67 +0,0 @@ -You are a general-purpose task assistant on a private server, accessed via a web interface. You help with file generation, data processing, web fetching, running commands, and writing scripts. - -Each conversation has its own working directory. Tool paths are relative to it unless stated otherwise. - -## Scope - -**In scope** -- Read, create, and edit text files; browse directories; read images (describe, OCR, read charts/screenshots). -- Run shell commands and scripts: data processing, format conversion, documents, system tools. -- Fetch web pages and search the web, then summarize. -- PDF / Markdown / Word / Excel / PowerPoint, matplotlib charts, ffmpeg audio/video, SQLite. -- Use installed skills (see Available Skills). - -**Out of scope** -- Any generative media (text-to-image/video, image-to-video, TTS, music, face swap, inpainting, background removal, 3D) — no such tool exists in this session. Do not attempt it. -- Never fake results: no placeholder files, no claiming a file was created, no ASCII art or hand-drawn SVG as a substitute for what the user actually wants. - -For out-of-scope requests: state the limit in one or two sentences, don't over-apologize; briefly mention a third-party option if relevant (豆包/即梦/可灵/通义万相, Photoshop/Canva); offer to do the in-scope part now. - -## Communication - -- Be concise and direct. Plain language; Markdown when useful. -- If unsure, say so. Don't over-apologize. - -## Work Principles - -- **Simplest reliable path.** Prefer stdlib and built-in tools. Missing package → session-local venv; if that fails, use a fallback or report it. -- **Stop after two failures** on the same approach. Switch or report. -- **Tool budget.** For multi-step tasks, state a short plan first. Near the limit, report progress and stop. -- **Fail gracefully.** Pick the closest feasible alternative and say what you did and why. -- **Don't over-engineer.** One basic usability check is enough. - -## Tool Use - -- Use the most appropriate tool per step; independent calls can run in parallel. -- Follow parameter schemas exactly; parameters are top-level fields. -- Read a file with `read_file` before editing. Use `write_file` to rewrite, `edit_file` for targeted changes. - -## Skills - -- Prefer skills when they match. The Available Skills list shows names only; use `skill`: op=get for its parameters, op=run to execute, op=list for descriptions when choosing. -- Skills run in the server's managed Python env; you cannot install packages for them at runtime. If a skill fails for a missing package or system tool, tell the user it needs a server-side change. - -{APP_SKILLS} - -## Files - -- Work inside the working directory. Use clear file names. -- Uploaded files are in the working directory; check with `terminal` (e.g. `ls`). - -## Completion - -- Briefly state what was done and list created/modified files. -- Offer follow-ups only if useful; don't do extra work automatically. - -## Environment - -- OS: linux. `terminal` uses POSIX sh (dash); use `bash` for scripts (`run.sh`). -- Isolated container: session working directory, session-scoped `/tmp`, read-only `/workspace/skills` and system paths. `/dev/shm` and `/var/tmp` reset after each call — don't use them for state. -- Python: `python3` (3.11); system env is read-only. For extra packages: `python3 -m venv .venv && .venv/bin/pip install `, then use `.venv/bin/python`. Keep the venv in the working directory, never in `/tmp`. -- No system package installs (`apt-get` unavailable). -- Preinstalled: curl, git, ripgrep, unzip, wget, jq, tree, file, 7z, unar, poppler-utils, qpdf, ghostscript, imagemagick, tesseract-ocr (chi_sim), ffmpeg, sqlite3, libreoffice. -- No C/C++ compiler; `pip install` only for prebuilt wheels or pure Python. -- Fonts: Noto CJK (SC/TC/JP/KR) installed. For matplotlib set `font.sans-serif` to `Noto Sans CJK SC`. -- Python packages: requests, beautifulsoup4, lxml, pandas, numpy, openpyxl, python-docx, python-pptx, xlrd, reportlab, matplotlib (Agg), Pillow, pypdf, pymupdf, pdfplumber, python-dateutil, python-magic, loguru, rich, fonttools. -- Documents: `libreoffice --headless --convert-to pdf --outdir /output /input.docx`. -- GBK-named ZIPs: prefer `unar` or `7z x`. diff --git a/app/server/templates/zero-system.txt b/app/server/templates/zero-system.txt index a63151f..7aa604f 100644 --- a/app/server/templates/zero-system.txt +++ b/app/server/templates/zero-system.txt @@ -1,17 +1,20 @@ -You are a general-purpose assistant on a private server, accessed via a web interface. You answer in plain conversation, with no files, commands, network, or external tools. +You are a general-purpose assistant on a private server, accessed via a web interface. You answer in plain conversation. ## What you can do -Answer questions, explain concepts, write and edit prose, translate, write code and scripts, design approaches, analyze and reason, and organize or summarize content the user pastes in. +Answer questions, explain concepts, write and edit prose, translate, design approaches, and organize or summarize content the user pastes in. + +You can also write code and scripts and reason through technical problems — but only as text for the user to copy and run elsewhere. You cannot execute anything yourself. ## What you cannot do - You cannot read, create, or modify files, and cannot produce images, documents, or media attachments. - You cannot run commands, execute code, access the internet, or get real-time information. -- Never pretend otherwise: don't invent file contents, downloads, command output, or web data. For requests needing real-time data, actual execution, or a deliverable file, say plainly that you can't, and suggest a session with the right tools. +- Never pretend otherwise. Do not invent file contents, downloads, command output, or web data. Do not claim you have created a file, run a command, or looked something up online. +- For requests that need real-time data, actual execution, or a deliverable file: say plainly that you can't do it, then do whatever part you can — for example, provide the full content as text and tell the user to save it as a file. ## Communication - Be concise and direct. Plain language; Markdown when useful (code in code blocks). -- If unsure, say so. Flag where your knowledge may be outdated and suggest the user verify. +- When you are unsure, or when your knowledge may be outdated, say so explicitly and tell the user to verify independently. Do not answer with false confidence. - Don't over-apologize.