新增 model_profiles:小模型的 prompt+tools 组合白名单

- 顶层 model_profiles 定义多套组合 {tools_allow?, system_prompt_file?},platforms 里的模型用 profile: <名> 引用(同 id 跨平台复用);引用不存在/文件缺失/空壳组合直接校验报错
- tools_allow 按最终工具名(内置 + MCP,含 server__ 前缀)过滤发给模型的 tools;名单外工具被调用不拦,executor 全表照跑
- system_prompt_file 相对 server/templates/,配置加载时一次读入常驻内存;设了即完全接管(不拼技能段),语言后缀照拼
- 运行期动态切换:发消息带 profile 参数(同 deepThink 约定,每迭代取 run 最新值),纯内存选择、不碰 config.yml;'default'=显式全量,未知名 400
- 压缩回合跟随当前组合;prompt 缓存改 (profile,语言) 键;prompt.txt dump 每套组合各一段;/api/models 带 profile、/api/system/status 下发组合名供前端选择器
This commit is contained in:
2026-09-22 10:38:04 +08:00
parent af7bd69ed2
commit a9ec8f2741
9 changed files with 206 additions and 38 deletions
+19
View File
@@ -12,6 +12,7 @@ platforms:
models: # 该平台下所有模型(与 url/type 同级);多 key 共用
- id: ds1 # 上游模型名;只需同平台内唯一(不同平台可同名),内部唯一键 = 平台名/模型id,历史会话按它绑定,页面不可改
display_name: "AMD DeepSeek 1" # 显示名,缺省同 id
# profile: mini # 选填:引用顶层 model_profiles 的 prompt+tools 组合(小模型省上下文),见下方示例;不配 = 默认全量
# vision: true # 选填,默认 false;支持时 read_file 读图会压缩回传(长边≤2000px JPEG),会话上下文会告知 AI
# enable: false # 选填,默认 true;禁用后不进模型池,不参与分配/绑定(重启生效)
# extra_params: # 选填:每次发往上游都会合并进 body 顶层的对象;同 key 覆盖默认(model/messages/stream/temperature/tools)
@@ -42,6 +43,24 @@ platforms:
keys:
- api_key: "your-key"
# 模型 profile(可选):预定义多套「prompt + tools 白名单」组合,platforms 里的模型用
# profile: <名字> 引用,同 id 模型跨平台复用时免重复配置。动机:默认发给模型的
# 内置工具 schema + system prompt 合计 ~20KB 字符(约 6K token),对特别小的模型会撑爆上下文。
# - tools_allow:白名单(字符串数组),只保留名单内的工具发给模型;内置名 + MCP 最终名
# (含冲突时加的 服务名__ 前缀,与 data/prompt.txt dump 一致可对)。不配 = 全量发。
# 只影响模型「看得到什么」:名单外但真实存在的工具若被调用,后端照常执行,不拦不误杀。
# - system_prompt_file:自定义 system prompt 文件,相对 server/templates/(也接受绝对路径),
# 配置加载时一次性读入常驻内存;设了就完全接管(不拼技能列表段,只保留末尾语言指令)。
# 文件缺失/为空直接校验报错。两者至少配一个;引用不存在的 profile 名同样直接报错。
# 改本段需重启;运行期前端可在已定义的 profile 间手动切换(发消息带 profile 参数,
# 纯内存选择、下一请求即生效,不碰配置文件);列表随 /api/system/status 的 model_profiles 下发。
# model_profiles:
# mini: # 2B 级小模型:只留文件读写 + 终端
# tools_allow: [read_file, write_file, edit_file, list_directory, find_path, grep, terminal]
# system_prompt_file: mini-system.txt # 配套的精简提示词(别留着默认模板里「用 XX 工具…」的段落)
# web-only: # 只配白名单也行,prompt 沿用默认模板
# tools_allow: [read_file, grep, fetch, web-search__search]
workspace_root: "./data/tasks"
# 数据根目录:db(默认 .agent.db)与启动 prompt dump(prompt.txt)放这里;相对路径按启动目录展开。
# 容器部署建议指到挂载卷内(如 /workspace/data),否则重建容器会丢数据。
+54 -2
View File
@@ -15,6 +15,45 @@ function normToolNames(v) {
return out.length ? out : undefined;
}
// profile 的 prompt 文件查找基准目录:与内置模板同处 server/templates/
// (compose 已 bind-mount ./app/server,宿主可直接编辑,无需重建镜像)。
const TEMPLATES_DIR = path.join(__dirname, 'templates');
// model_profiles 归一化:顶层 map {名称: {tools_allow?, system_prompt_file?}},
// 供 platforms[].models[].profile 引用(同 id 模型跨平台复用时免重复配置)。
// - tools_allow 复用 MCP 名单约定(normToolNames):只按最终发给模型的工具名匹配
// (内置名 + MCP 名,含冲突时加的 server__ 前缀);非数组/空数组 = 未配置不过滤。
// - system_prompt_file:相对 templates/(也接受绝对路径),配置加载时一次性读入常驻内存,
// 运行期切换零 IO;缺失/读不到/内容为空直接报校验错——拦在保存/重启预检,不留到运行期降级。
// - 两样都没配 = 不起任何作用,报错误防误配空壳。
function normalizeModelProfiles(rawProfiles) {
const out = {};
if (!rawProfiles || typeof rawProfiles !== 'object' || Array.isArray(rawProfiles)) return out;
for (const [name, p] of Object.entries(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}');
}
const tools_allow = normToolNames(p.tools_allow);
const file = String(p.system_prompt_file || '').trim();
let prompt = '';
if (file) {
const abs = path.isAbsolute(file) ? file : path.join(TEMPLATES_DIR, file);
try { prompt = fs.readFileSync(abs, 'utf8'); } catch (_) {
throw new Error('model_profiles.' + key + '.system_prompt_file 读取失败:' + abs);
}
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 之一');
}
out[key] = { name: key, tools_allow, system_prompt_file: file, prompt };
}
return out;
}
const DEFAULTS = {
port: 8090,
// 数据根目录:db、prompt dump 等运行时产物默认放这里(容器内挂 ./data → /workspace/data)。
@@ -50,6 +89,10 @@ const DEFAULTS = {
// 上下文压缩提示词不再走配置:压缩回合沿用默认 system prompt + 正常历史,
// 末尾追加一条 user(提示词原文),不传 tools;模板在 server/templates/compress-prompt.txt。
platforms: [],
// 模型 profile(prompt+tools 组合):顶层定义、platforms 里的模型用 profile: 名称引用(可复用)。
// 每项 {tools_allow?, system_prompt_file?},详见 normalizeModelProfiles;改配置需重启生效。
// 运行期前端可在已定义的 profile 间手动切换(纯内存选择),不碰本配置。
model_profiles: {},
// 登录认证:{ users: [{user, password}], secret?, ttl_ms? },密码明文存配置(自用场景)。
// users 为空则不启用认证(可交给前置 nginx-proxy,但手机浏览器原生下载不带 Basic 头,不推荐)。
auth: null,
@@ -107,7 +150,7 @@ function migrateLegacyModels(models) {
// 新版结构:models 提到平台层(与 url/type 同级),所有 key 共用同一份 models;key 数组里只放
// {api_key, concurrency},不再挂 models。旧版 keys[j].models 写法直接报错,让用户改 YAML。
// 内部唯一键 = 平台名/模型id:不同平台允许同模型 id,同平台内必须唯一(会话/模型池/用量均按该键认模型)。
function normalizePlatforms(rawPlatforms) {
function normalizePlatforms(rawPlatforms, profileNames) {
const seen = new Set(); // 已用唯一键(平台名/模型id)
const out = [];
for (let pi = 0; pi < rawPlatforms.length; pi++) {
@@ -135,6 +178,12 @@ function normalizePlatforms(rawPlatforms) {
const uid = name + '/' + String(m.id);
if (seen.has(uid)) throw new Error('模型重复:平台「' + name + '」下已有模型 id:' + m.id + '(不同平台可同名,同平台内必须唯一)');
seen.add(uid);
// 选填:引用顶层 model_profiles 的组合名(tools 白名单 + 自定义 system prompt);
// 不配 = 默认全量。引用了不存在的名字直接报错,不静默回退。
const profile = m.profile ? String(m.profile).trim() : '';
if (profile && !profileNames.has(profile)) {
throw new Error('平台「' + name + '」的模型「' + m.id + '」引用了不存在的 profile:' + profile + '(请核对顶层 model_profiles)');
}
models.push({
id: String(m.id),
display_name: m.display_name ? String(m.display_name) : String(m.id), // 缺省 = id
@@ -144,6 +193,7 @@ function normalizePlatforms(rawPlatforms) {
extra_params: (m.extra_params && typeof m.extra_params === 'object' && !Array.isArray(m.extra_params)) ? m.extra_params : {},
// 选填:前端启用「深度思考」时合并进 body。可覆盖 extra_params 的同名键。
thinking_params: (m.thinking_params && typeof m.thinking_params === 'object' && !Array.isArray(m.thinking_params)) ? m.thinking_params : {},
profile,
});
}
// keys 仅含 api_key/concurrency(不再挂 models)
@@ -175,7 +225,8 @@ function parseAndValidate(rawText, configPath) {
if (!Array.isArray(raw.platforms) || !raw.platforms.length) {
throw new Error('配置缺少 platforms:至少需要一个平台 {name, url, keys:[{api_key}], models:[{id}]}')
}
cfg.platforms = normalizePlatforms(raw.platforms);
cfg.model_profiles = normalizeModelProfiles(raw.model_profiles);
cfg.platforms = normalizePlatforms(raw.platforms, new Set(Object.keys(cfg.model_profiles)));
cfg.models = [];
cfg.platforms.forEach((p, pi) => p.keys.forEach((k, ki) => p.models.forEach((m, mi) => {
cfg.models.push({
@@ -185,6 +236,7 @@ function parseAndValidate(rawText, configPath) {
id: p.name + '/' + m.id, mid: m.id,
display_name: m.display_name, vision: m.vision, enable: m.enable,
extra_params: m.extra_params, thinking_params: m.thinking_params,
profile: m.profile,
url: p.url, api_key: k.api_key, platform: p.name, type: p.type, concurrency: k.concurrency,
platform_index: pi, key_index: ki, model_index: mi,
});
+52 -7
View File
@@ -2,7 +2,7 @@
// 单进程内存模型:JS 单线程 + better-sqlite3 同步 API,不存在跨进程竞争。
const fs = require('fs');
const path = require('path');
const { buildMessages, callModel, encodeBlocks, compressMessages, titleMessages } = require('./llm');
const { buildMessages, callModel, encodeBlocks, compressMessages, titleMessages, setProfilePrompts } = require('./llm');
const { executeTool, resolveInTask } = require('./tools/executor');
const publicFiles = require('./public-files');
const mcp = require('./mcp');
@@ -155,6 +155,7 @@ function queuePosition(sessionId) {
// ---------- 模型池调度 ----------
function syncModelPool() {
registerProfilePrompts(); // profile 自定义 prompt 注册进 llm(文本已随配置加载读入)
const stmt = db.prepare(
'INSERT INTO model_pool (id, display_name, is_busy, current_session_id) VALUES (?,?,0,NULL) ON CONFLICT(id) DO UPDATE SET display_name=excluded.display_name'
);
@@ -229,6 +230,43 @@ function modelVision(session) {
return !!(m && m.vision);
}
// ---------- 模型 profile(prompt+tools 组合) ----------
// 把 cfg 里预加载的自定义 prompt 文本注册给 llm(配置加载时已读入,见 config.js);
// engine.init 调一次,运行期只按名选取,零 IO。
function registerProfilePrompts() {
const map = {};
for (const [name, p] of Object.entries((cfg && cfg.model_profiles) || {})) {
if (p && p.prompt) map[name] = p.prompt;
}
setProfilePrompts(map);
}
// 本轮生效的 profile 名:前端显式选择(run.profile,与 deepThink 同约定:
// 每轮迭代取最新值,回合中途切换下一个请求即生效)> 模型配置默认(cfg.models[].profile)> ''(默认全量)。
// 保留值 'default' = 前端显式切回全量(覆盖配了 profile 的模型的默认组合)。
function resolveProfileName(session, run) {
const manual = run && String(run.profile || '').trim();
if (manual) return manual === 'default' ? '' : manual;
const m = session.model_id && (cfg.models || []).find(x => x.id === session.model_id);
return m && m.profile ? String(m.profile) : '';
}
// 本轮工具定义集:内置 + MCP 全量;profile 配了 tools_allow 则按最终名过滤
// (与发给模型的 tools 字段/prompt.txt dump 同源可对)。只影响模型「看得到什么」:
// 名单外但真实存在的工具若被调用,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 (!allow) return all;
const set = new Set(allow);
return all.filter(t => t && t.function && set.has(t.function.name));
}
function hasModelProfile(name) {
return !!(name && cfg.model_profiles && cfg.model_profiles[String(name)]);
}
function enqueue(sessionId) {
const exists = db.prepare('SELECT id FROM wait_queue WHERE session_id = ?').get(sessionId);
if (!exists) db.prepare('INSERT INTO wait_queue (session_id, queued_at) VALUES (?,?)').run(sessionId, now());
@@ -530,11 +568,14 @@ async function runLoopInner(sessionId, run) {
} catch (_) { return null; }
};
const compressing = !!run.summarizing;
// profile(prompt+tools 组合):每迭代现解,前端切模式后下一个请求即生效;
// 压缩回合同样跟随(小模型会话点「压缩」若回退默认大模板,当场撑爆)。
const profileName = resolveProfileName(session, run);
const messages = compressing
? compressMessages(session, (cfg.agent || {}).language, mintImageUrl)
: buildMessages(session, (cfg.agent || {}).language, mintImageUrl);
// 内置工具 + 启动时发现的 MCP 工具,一起随 system prompt 发给模型(压缩回合不发)
const tools = compressing ? [] : TOOL_DEFINITIONS.concat(mcp.toolDefinitions());
? compressMessages(session, (cfg.agent || {}).language, mintImageUrl, profileName)
: buildMessages(session, (cfg.agent || {}).language, mintImageUrl, profileName);
// 内置工具 + 启动时发现的 MCP 工具(按 profile 白名单过滤),一起随 system prompt 发给模型(压缩回合不发)
const tools = compressing ? [] : effectiveTools(profileName);
let result = null;
let lastErr = null;
@@ -880,15 +921,17 @@ function createSession(title, preferModelId, assistantType, user) {
}
// 用户消息(或“开始执行”的模板消息)入口。
// opts.deepThink: true 时启用深度思考;参数会记在会话 run 上,
// opts.deepThink: true 时启用深度思考;opts.profile: 本轮 prompt+tools 组合名(model_profiles,
// 空 = 随模型配置,'default' = 显式全量);参数都记在会话 run 上,
// 正在跑的回合下一轮迭代会取到最新值。新建会话需在 runLoop 之前先预建 run 以携带该值。
function postUserMessage(sessionId, content, opts) {
const session = getSession(sessionId);
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
const messageId = saveMessage(sessionId, { role: 'user', content });
// 预建/更新 run 记录,记下本轮的 deepThink(被 runLoop / callModel 读取)
// 预建/更新 run 记录,记下本轮的 deepThink/profile(被 runLoop / callModel 读取)
const run = getRun(sessionId, true);
run.deepThink = !!(opts && opts.deepThink);
run.profile = String((opts && opts.profile) || '').trim();
// 真实用户消息到达:若还有个「已排队但尚未开跑」的压缩回合(见 summarizeContext),
// 让它作废,避免新消息被误当成压缩回合处理;已在跑(looping)的不动,
// 由其收尾时自行清空 summarizing。
@@ -1180,4 +1223,6 @@ module.exports = {
dispatchQueued,
bindToSession,
TOOL_DEFINITIONS,
effectiveTools,
hasModelProfile,
};
+33 -15
View File
@@ -35,35 +35,51 @@ function titleMessages(history, language) {
return messages;
}
// system prompt 完全静态:所有会话共用同一份内容,利于上游前缀缓存。
// system prompt 进程内恒定(利于上游前缀缓存)。多套并存:默认模板 + 每套 model_profiles
// 的自定义 prompt(文本随配置加载时读入,见 config.js normalizeModelProfiles,经
// setProfilePrompts 注册)。请求时按 profile 名选取——纯内存指针选择,零 IO。
function buildSystemPrompt() {
return SYSTEM_PROMPT_TEMPLATE;
}
let PROFILE_PROMPTS = {}; // profile 名 -> 自定义 prompt 全文(不含技能段/语言后缀)
function setProfilePrompts(map) {
PROFILE_PROMPTS = map || {};
_promptTextCache = new Map(); // 注册表变化后拼接结果需重建
}
// 部署级回复语言指令:拼在 system prompt 末尾(尾部对弱模型约束力最强)。
// 同一进程内恒定,不破坏前缀缓存;改配置需重启生效。
// system prompt 每次请求都随 messages 发出,拼接结果按语言缓存,不重复分配大字符串。
let _promptTextCache = null; // { lang, text }
// system prompt 每次请求都随 messages 发出,拼接结果按 (profile, 语言) 缓存,不重复分配大字符串。
let _promptTextCache = new Map(); // 'profile\u0000lang' -> text
// “可用技能”段落(skills.formatSkillListForPrompt):启动时快照(server.js)与技能变更后
// (routes/skills.js)经 setSkillListText 更新,拼在模板之后、语言指令之前。
// (routes/skills.js)经 setSkillListText 更新,拼在默认模板之后、语言指令之前。
// 与语言指令同一约定:仅技能增删/描述变化时更新,否则进程内恒定,不破坏前缀缓存。
// 只拼默认模板:profile 自定义 prompt 完全接管(技能工具若在其白名单内,模型用 list_skills 自取)。
let SKILL_LIST_TEXT = '';
function setSkillListText(text) {
SKILL_LIST_TEXT = text || '';
_promptTextCache = null; // 列表变化后拼接结果需重建
_promptTextCache = new Map(); // 列表变化后拼接结果需重建
}
function systemPromptText(language) {
function systemPromptText(language, profile) {
const t = String(language || '').trim();
if (_promptTextCache && _promptTextCache.lang === t) return _promptTextCache.text;
let text = SYSTEM_PROMPT_TEMPLATE;
if (SKILL_LIST_TEXT) text += '\n\n' + SKILL_LIST_TEXT;
const key = (profile || 'default') + '\u0000' + t;
const hit = _promptTextCache.get(key);
if (hit) return hit;
let text;
if (profile && PROFILE_PROMPTS[profile]) {
text = PROFILE_PROMPTS[profile];
} else {
text = SYSTEM_PROMPT_TEMPLATE;
if (SKILL_LIST_TEXT) text += '\n\n' + SKILL_LIST_TEXT;
}
if (t) text += '\n\n## Reply Language\n' +
'- ALWAYS respond to the user in ' + t + '. Tool descriptions, tool outputs and errors are usually in English — ' +
'never let them switch your reply language. Tool names, parameters, code, file paths and shell commands stay as-is; ' +
'every sentence addressed to the user MUST be in ' + t + '.';
_promptTextCache = { lang: t, text };
_promptTextCache.set(key, text);
return text;
}
@@ -113,8 +129,10 @@ function cachedDecodeBlocks(session, row) {
// 关联 tool 回执按 id 一并跳过(否则会留下无 tool_call 配对的孤儿 tool 消息,上游拒收);
// 改以一条 user 错误提示替代,让模型看到原因后重新生成工具调用 ——
// 坏样本留在上下文里只会被模型继续模仿,反复报同一个错。
function buildMessages(session, language, mintUrl) {
const messages = [{ role: 'system', content: systemPromptText(language) }];
// profile:本轮生效的 prompt+tools 组合名(model_profiles,见 engine.resolveProfileName),
// 空 = 默认全量组合。
function buildMessages(session, language, mintUrl, profile) {
const messages = [{ role: 'system', content: systemPromptText(language, profile) }];
const history = session.history;
// 行被删除后清理残留的图片解析缓存条目(只增不清会缓慢泄漏;条数不会超过现存行数)
if (session.blocksCache && session.blocksCache.size > history.length) {
@@ -204,8 +222,8 @@ function buildMessages(session, language, mintUrl) {
//(与 buildMessages 同取舍:archived 不发、旧摘要/工具轮照常),末尾追加一条 user
//(compress-prompt.txt 原文,历史就在它前面的 messages 里,不再填占位符)。
// 调用方(engine.runLoopInner 的 compressing 分支)需同时不传 tools。
function compressMessages(session, language, mintUrl) {
const messages = buildMessages(session, language, mintUrl);
function compressMessages(session, language, mintUrl, profile) {
const messages = buildMessages(session, language, mintUrl, profile);
messages.push({ role: 'user', content: COMPRESS_PROMPT_TEMPLATE });
return messages;
}
@@ -461,4 +479,4 @@ async function callModel(cfg, modelId, messages, tools, options) {
return { content, reasoning, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted, sseFrames };
}
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, encodeBlocks, decodeBlocks, compressMessages, titleMessages };
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages };
+7 -1
View File
@@ -21,7 +21,13 @@ 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);
const r = engine.postUserMessage(req.params.id, content, { deepThink });
// profile:本轮 prompt+tools 组合(config.yml 顶层 model_profiles 的名字;保留值 'default' = 显式全量;
// 不传 = 随模型配置的 profile)。名字不存在直接 400 打回,不静默回退(难排查)。
const profile = String((req.body && req.body.profile) || '').trim();
if (profile && profile !== 'default' && !engine.hasModelProfile(profile)) {
return res.status(400).json({ error: 'profile 不存在:' + profile + '(可选:' + Object.keys(engine.getConfig().model_profiles || {}).join(', ') + ')' });
}
const r = engine.postUserMessage(req.params.id, content, { deepThink, profile });
log.info('msg', (req.user || '-') + ' ' + req.params.id + ' 用户消息(' + (r && r.delivered || '?') + '):' +
content.slice(0, 60).replace(/\s+/g, ' '));
res.json(r);
+3
View File
@@ -47,6 +47,9 @@ router.get('/status', wrap((req, res) => {
port: cfg.port,
auth_enabled: !!(cfg.auth && cfg.auth.users && cfg.auth.users.length),
running_sessions: engine.activeRuns(),
// 可用的 prompt+tools 组合名(config.yml 顶层 model_profiles):前端模式选择器据此渲染;
// 切换 = 发消息时带 profile 参数(见 routes/messages.js),纯内存选择,不碰配置不重启。
model_profiles: Object.keys((engine.getConfig() || {}).model_profiles || {}),
// 前端上传预处理参数(大图压缩阈值/尺寸/质量、大文件确认阈值),避免前端写死
upload: cfg.upload || {},
});
+17 -6
View File
@@ -83,6 +83,7 @@ app.get('/api/models', (req, res) => {
rows.push({
id: m.id, display_name: m.display_name, platform: m.platform, mid: m.mid,
vision: !!m.vision, type: m.type, key_count: total,
profile: m.profile || '', // 模型默认 prompt+tools 组合(model_profiles 名,空 = 全量)
slots_total: total, slots_busy: busy,
is_busy: total > 0 && busy >= total ? 1 : 0,
current_session_id: (sessByPlat[m.platform] || []).join(','),
@@ -106,19 +107,29 @@ app.get('/api/health', (req, res) => res.json({ ok: true, time: Date.now() }));
const PORT = process.env.PORT || cfg.port;
// 启动成功后把模型实际收到的各部分 dump 到文件方便人工核对(data_root 默认 ./data,
// 宿主机对应 <repo>/data/prompt.txt,已被 gitignore)。包含两部分:
// 1) system 消息:模板 + 可用技能段落 + 语言指令(进程内恒定,仅技能增删时变);
// 2) tools 数组:内置 definitions.json + 启动时发现的 MCP 工具,与每次请求的 tools 字段一致。
// 宿主机对应 <repo>/data/prompt.txt,已被 gitignore)。包含:
// 1) 默认组合:system 消息(模板 + 可用技能段落 + 语言指令)+ tools 数组(内置 + MCP);
// 2) 每套 model_profiles 一段:按其白名单过滤后的 tools + 自定义 prompt(未配则回落默认模板)。
function dumpPromptBundle() {
const file = path.join(cfg.data_root, 'prompt.txt');
const lang = (cfg.agent || {}).language;
const tools = engine.TOOL_DEFINITIONS.concat(mcp.toolDefinitions());
const parts = [
'# ===== 1. System Prompt(system 消息,进程内恒定)=====\n\n' + llm.systemPromptText((cfg.agent || {}).language),
'\n\n# ===== 2. Tools(' + tools.length + ' 个:内置 + MCP,随每次请求的 tools 字段发送)=====\n\n' + JSON.stringify(tools, null, 2),
'# ===== 1. System Prompt(默认组合,system 消息,进程内恒定)=====\n\n' + llm.systemPromptText(lang),
'\n\n# ===== 2. Tools(默认组合 ' + tools.length + ' 个:内置 + MCP,随每次请求的 tools 字段发送)=====\n\n' + JSON.stringify(tools, null, 2),
];
for (const name of Object.keys(cfg.model_profiles || {})) {
const pTools = engine.effectiveTools(name);
parts.push(
'\n\n# ===== profile "' + name + '" =====\n\n' +
'# --- system prompt ---\n\n' + llm.systemPromptText(lang, name) +
'\n\n# --- tools(白名单过滤后 ' + pTools.length + ' / 全量 ' + tools.length + ' 个)---\n\n' + JSON.stringify(pTools, null, 2)
);
}
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, parts.join(''), 'utf8');
log.info('startup', ' prompt_dump=' + file + ' (tools=' + tools.length + ')');
log.info('startup', ' prompt_dump=' + file + ' (tools=' + tools.length +
', profiles=' + (Object.keys(cfg.model_profiles || {}).join(',') || '-') + ')');
}
// 启动时先发现各 MCP 服务的工具(单个服务失败只警告,不阻止启动),