新增 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:
@@ -833,6 +833,16 @@ platforms:
|
|||||||
models:
|
models:
|
||||||
- id: ds3
|
- id: ds3
|
||||||
display_name: "AMD DeepSeek 3"
|
display_name: "AMD DeepSeek 3"
|
||||||
|
# profile: mini # 选填,引用顶层 model_profiles 的 prompt+tools 组合(小模型省上下文用)
|
||||||
|
|
||||||
|
# 模型 profile(可选):预定义多套「system prompt 文件 + tools 白名单」组合,模型用 profile: <名>
|
||||||
|
# 引用(同 id 模型跳平台复用时免重复配置)。不配 profile 的模型照旧全量。动机:默认发给模型的
|
||||||
|
# 内置工具 schema + system prompt 约 6K token,特别小的模型会被撑爆上下文。
|
||||||
|
# 改后重启生效;运行期前端可在已定义组合间手动切换(发消息带 profile 参数,纯内存选择、不碰配置)。
|
||||||
|
# model_profiles:
|
||||||
|
# mini:
|
||||||
|
# tools_allow: [read_file, write_file, edit_file, list_directory, find_path, grep, terminal] # 白名单(内置名 + MCP 最终名)
|
||||||
|
# system_prompt_file: mini-system.txt # 相对 server/templates/ 的自定义 prompt
|
||||||
|
|
||||||
workspace_root: "/workspace/tasks"
|
workspace_root: "/workspace/tasks"
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ platforms:
|
|||||||
models: # 该平台下所有模型(与 url/type 同级);多 key 共用
|
models: # 该平台下所有模型(与 url/type 同级);多 key 共用
|
||||||
- id: ds1 # 上游模型名;只需同平台内唯一(不同平台可同名),内部唯一键 = 平台名/模型id,历史会话按它绑定,页面不可改
|
- id: ds1 # 上游模型名;只需同平台内唯一(不同平台可同名),内部唯一键 = 平台名/模型id,历史会话按它绑定,页面不可改
|
||||||
display_name: "AMD DeepSeek 1" # 显示名,缺省同 id
|
display_name: "AMD DeepSeek 1" # 显示名,缺省同 id
|
||||||
|
# profile: mini # 选填:引用顶层 model_profiles 的 prompt+tools 组合(小模型省上下文),见下方示例;不配 = 默认全量
|
||||||
# vision: true # 选填,默认 false;支持时 read_file 读图会压缩回传(长边≤2000px JPEG),会话上下文会告知 AI
|
# vision: true # 选填,默认 false;支持时 read_file 读图会压缩回传(长边≤2000px JPEG),会话上下文会告知 AI
|
||||||
# enable: false # 选填,默认 true;禁用后不进模型池,不参与分配/绑定(重启生效)
|
# enable: false # 选填,默认 true;禁用后不进模型池,不参与分配/绑定(重启生效)
|
||||||
# extra_params: # 选填:每次发往上游都会合并进 body 顶层的对象;同 key 覆盖默认(model/messages/stream/temperature/tools)
|
# extra_params: # 选填:每次发往上游都会合并进 body 顶层的对象;同 key 覆盖默认(model/messages/stream/temperature/tools)
|
||||||
@@ -42,6 +43,24 @@ platforms:
|
|||||||
keys:
|
keys:
|
||||||
- api_key: "your-key"
|
- 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"
|
workspace_root: "./data/tasks"
|
||||||
# 数据根目录:db(默认 .agent.db)与启动 prompt dump(prompt.txt)放这里;相对路径按启动目录展开。
|
# 数据根目录:db(默认 .agent.db)与启动 prompt dump(prompt.txt)放这里;相对路径按启动目录展开。
|
||||||
# 容器部署建议指到挂载卷内(如 /workspace/data),否则重建容器会丢数据。
|
# 容器部署建议指到挂载卷内(如 /workspace/data),否则重建容器会丢数据。
|
||||||
|
|||||||
+54
-2
@@ -15,6 +15,45 @@ function normToolNames(v) {
|
|||||||
return out.length ? out : undefined;
|
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 = {
|
const DEFAULTS = {
|
||||||
port: 8090,
|
port: 8090,
|
||||||
// 数据根目录:db、prompt dump 等运行时产物默认放这里(容器内挂 ./data → /workspace/data)。
|
// 数据根目录:db、prompt dump 等运行时产物默认放这里(容器内挂 ./data → /workspace/data)。
|
||||||
@@ -50,6 +89,10 @@ const DEFAULTS = {
|
|||||||
// 上下文压缩提示词不再走配置:压缩回合沿用默认 system prompt + 正常历史,
|
// 上下文压缩提示词不再走配置:压缩回合沿用默认 system prompt + 正常历史,
|
||||||
// 末尾追加一条 user(提示词原文),不传 tools;模板在 server/templates/compress-prompt.txt。
|
// 末尾追加一条 user(提示词原文),不传 tools;模板在 server/templates/compress-prompt.txt。
|
||||||
platforms: [],
|
platforms: [],
|
||||||
|
// 模型 profile(prompt+tools 组合):顶层定义、platforms 里的模型用 profile: 名称引用(可复用)。
|
||||||
|
// 每项 {tools_allow?, system_prompt_file?},详见 normalizeModelProfiles;改配置需重启生效。
|
||||||
|
// 运行期前端可在已定义的 profile 间手动切换(纯内存选择),不碰本配置。
|
||||||
|
model_profiles: {},
|
||||||
// 登录认证:{ users: [{user, password}], secret?, ttl_ms? },密码明文存配置(自用场景)。
|
// 登录认证:{ users: [{user, password}], secret?, ttl_ms? },密码明文存配置(自用场景)。
|
||||||
// users 为空则不启用认证(可交给前置 nginx-proxy,但手机浏览器原生下载不带 Basic 头,不推荐)。
|
// users 为空则不启用认证(可交给前置 nginx-proxy,但手机浏览器原生下载不带 Basic 头,不推荐)。
|
||||||
auth: null,
|
auth: null,
|
||||||
@@ -107,7 +150,7 @@ function migrateLegacyModels(models) {
|
|||||||
// 新版结构:models 提到平台层(与 url/type 同级),所有 key 共用同一份 models;key 数组里只放
|
// 新版结构:models 提到平台层(与 url/type 同级),所有 key 共用同一份 models;key 数组里只放
|
||||||
// {api_key, concurrency},不再挂 models。旧版 keys[j].models 写法直接报错,让用户改 YAML。
|
// {api_key, concurrency},不再挂 models。旧版 keys[j].models 写法直接报错,让用户改 YAML。
|
||||||
// 内部唯一键 = 平台名/模型id:不同平台允许同模型 id,同平台内必须唯一(会话/模型池/用量均按该键认模型)。
|
// 内部唯一键 = 平台名/模型id:不同平台允许同模型 id,同平台内必须唯一(会话/模型池/用量均按该键认模型)。
|
||||||
function normalizePlatforms(rawPlatforms) {
|
function normalizePlatforms(rawPlatforms, profileNames) {
|
||||||
const seen = new Set(); // 已用唯一键(平台名/模型id)
|
const seen = new Set(); // 已用唯一键(平台名/模型id)
|
||||||
const out = [];
|
const out = [];
|
||||||
for (let pi = 0; pi < rawPlatforms.length; pi++) {
|
for (let pi = 0; pi < rawPlatforms.length; pi++) {
|
||||||
@@ -135,6 +178,12 @@ function normalizePlatforms(rawPlatforms) {
|
|||||||
const uid = name + '/' + String(m.id);
|
const uid = name + '/' + String(m.id);
|
||||||
if (seen.has(uid)) throw new Error('模型重复:平台「' + name + '」下已有模型 id:' + m.id + '(不同平台可同名,同平台内必须唯一)');
|
if (seen.has(uid)) throw new Error('模型重复:平台「' + name + '」下已有模型 id:' + m.id + '(不同平台可同名,同平台内必须唯一)');
|
||||||
seen.add(uid);
|
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({
|
models.push({
|
||||||
id: String(m.id),
|
id: String(m.id),
|
||||||
display_name: m.display_name ? String(m.display_name) : String(m.id), // 缺省 = 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 : {},
|
extra_params: (m.extra_params && typeof m.extra_params === 'object' && !Array.isArray(m.extra_params)) ? m.extra_params : {},
|
||||||
// 选填:前端启用「深度思考」时合并进 body。可覆盖 extra_params 的同名键。
|
// 选填:前端启用「深度思考」时合并进 body。可覆盖 extra_params 的同名键。
|
||||||
thinking_params: (m.thinking_params && typeof m.thinking_params === 'object' && !Array.isArray(m.thinking_params)) ? m.thinking_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)
|
// keys 仅含 api_key/concurrency(不再挂 models)
|
||||||
@@ -175,7 +225,8 @@ function parseAndValidate(rawText, configPath) {
|
|||||||
if (!Array.isArray(raw.platforms) || !raw.platforms.length) {
|
if (!Array.isArray(raw.platforms) || !raw.platforms.length) {
|
||||||
throw new Error('配置缺少 platforms:至少需要一个平台 {name, url, keys:[{api_key}], models:[{id}]}')
|
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.models = [];
|
||||||
cfg.platforms.forEach((p, pi) => p.keys.forEach((k, ki) => p.models.forEach((m, mi) => {
|
cfg.platforms.forEach((p, pi) => p.keys.forEach((k, ki) => p.models.forEach((m, mi) => {
|
||||||
cfg.models.push({
|
cfg.models.push({
|
||||||
@@ -185,6 +236,7 @@ function parseAndValidate(rawText, configPath) {
|
|||||||
id: p.name + '/' + m.id, mid: m.id,
|
id: p.name + '/' + m.id, mid: m.id,
|
||||||
display_name: m.display_name, vision: m.vision, enable: m.enable,
|
display_name: m.display_name, vision: m.vision, enable: m.enable,
|
||||||
extra_params: m.extra_params, thinking_params: m.thinking_params,
|
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,
|
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,
|
platform_index: pi, key_index: ki, model_index: mi,
|
||||||
});
|
});
|
||||||
|
|||||||
+52
-7
@@ -2,7 +2,7 @@
|
|||||||
// 单进程内存模型:JS 单线程 + better-sqlite3 同步 API,不存在跨进程竞争。
|
// 单进程内存模型:JS 单线程 + better-sqlite3 同步 API,不存在跨进程竞争。
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
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 { executeTool, resolveInTask } = require('./tools/executor');
|
||||||
const publicFiles = require('./public-files');
|
const publicFiles = require('./public-files');
|
||||||
const mcp = require('./mcp');
|
const mcp = require('./mcp');
|
||||||
@@ -155,6 +155,7 @@ function queuePosition(sessionId) {
|
|||||||
|
|
||||||
// ---------- 模型池调度 ----------
|
// ---------- 模型池调度 ----------
|
||||||
function syncModelPool() {
|
function syncModelPool() {
|
||||||
|
registerProfilePrompts(); // profile 自定义 prompt 注册进 llm(文本已随配置加载读入)
|
||||||
const stmt = db.prepare(
|
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'
|
'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);
|
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) {
|
function enqueue(sessionId) {
|
||||||
const exists = db.prepare('SELECT id FROM wait_queue WHERE session_id = ?').get(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());
|
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; }
|
} catch (_) { return null; }
|
||||||
};
|
};
|
||||||
const compressing = !!run.summarizing;
|
const compressing = !!run.summarizing;
|
||||||
|
// profile(prompt+tools 组合):每迭代现解,前端切模式后下一个请求即生效;
|
||||||
|
// 压缩回合同样跟随(小模型会话点「压缩」若回退默认大模板,当场撑爆)。
|
||||||
|
const profileName = resolveProfileName(session, run);
|
||||||
const messages = compressing
|
const messages = compressing
|
||||||
? compressMessages(session, (cfg.agent || {}).language, mintImageUrl)
|
? compressMessages(session, (cfg.agent || {}).language, mintImageUrl, profileName)
|
||||||
: buildMessages(session, (cfg.agent || {}).language, mintImageUrl);
|
: buildMessages(session, (cfg.agent || {}).language, mintImageUrl, profileName);
|
||||||
// 内置工具 + 启动时发现的 MCP 工具,一起随 system prompt 发给模型(压缩回合不发)
|
// 内置工具 + 启动时发现的 MCP 工具(按 profile 白名单过滤),一起随 system prompt 发给模型(压缩回合不发)
|
||||||
const tools = compressing ? [] : TOOL_DEFINITIONS.concat(mcp.toolDefinitions());
|
const tools = compressing ? [] : effectiveTools(profileName);
|
||||||
|
|
||||||
let result = null;
|
let result = null;
|
||||||
let lastErr = 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 以携带该值。
|
// 正在跑的回合下一轮迭代会取到最新值。新建会话需在 runLoop 之前先预建 run 以携带该值。
|
||||||
function postUserMessage(sessionId, content, opts) {
|
function postUserMessage(sessionId, content, opts) {
|
||||||
const session = getSession(sessionId);
|
const session = getSession(sessionId);
|
||||||
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
|
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
|
||||||
const messageId = saveMessage(sessionId, { role: 'user', content });
|
const messageId = saveMessage(sessionId, { role: 'user', content });
|
||||||
// 预建/更新 run 记录,记下本轮的 deepThink(被 runLoop / callModel 读取)
|
// 预建/更新 run 记录,记下本轮的 deepThink/profile(被 runLoop / callModel 读取)
|
||||||
const run = getRun(sessionId, true);
|
const run = getRun(sessionId, true);
|
||||||
run.deepThink = !!(opts && opts.deepThink);
|
run.deepThink = !!(opts && opts.deepThink);
|
||||||
|
run.profile = String((opts && opts.profile) || '').trim();
|
||||||
// 真实用户消息到达:若还有个「已排队但尚未开跑」的压缩回合(见 summarizeContext),
|
// 真实用户消息到达:若还有个「已排队但尚未开跑」的压缩回合(见 summarizeContext),
|
||||||
// 让它作废,避免新消息被误当成压缩回合处理;已在跑(looping)的不动,
|
// 让它作废,避免新消息被误当成压缩回合处理;已在跑(looping)的不动,
|
||||||
// 由其收尾时自行清空 summarizing。
|
// 由其收尾时自行清空 summarizing。
|
||||||
@@ -1180,4 +1223,6 @@ module.exports = {
|
|||||||
dispatchQueued,
|
dispatchQueued,
|
||||||
bindToSession,
|
bindToSession,
|
||||||
TOOL_DEFINITIONS,
|
TOOL_DEFINITIONS,
|
||||||
|
effectiveTools,
|
||||||
|
hasModelProfile,
|
||||||
};
|
};
|
||||||
|
|||||||
+33
-15
@@ -35,35 +35,51 @@ function titleMessages(history, language) {
|
|||||||
return messages;
|
return messages;
|
||||||
}
|
}
|
||||||
|
|
||||||
// system prompt 完全静态:所有会话共用同一份内容,利于上游前缀缓存。
|
// system prompt 进程内恒定(利于上游前缀缓存)。多套并存:默认模板 + 每套 model_profiles
|
||||||
|
// 的自定义 prompt(文本随配置加载时读入,见 config.js normalizeModelProfiles,经
|
||||||
|
// setProfilePrompts 注册)。请求时按 profile 名选取——纯内存指针选择,零 IO。
|
||||||
function buildSystemPrompt() {
|
function buildSystemPrompt() {
|
||||||
return SYSTEM_PROMPT_TEMPLATE;
|
return SYSTEM_PROMPT_TEMPLATE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let PROFILE_PROMPTS = {}; // profile 名 -> 自定义 prompt 全文(不含技能段/语言后缀)
|
||||||
|
function setProfilePrompts(map) {
|
||||||
|
PROFILE_PROMPTS = map || {};
|
||||||
|
_promptTextCache = new Map(); // 注册表变化后拼接结果需重建
|
||||||
|
}
|
||||||
|
|
||||||
// 部署级回复语言指令:拼在 system prompt 末尾(尾部对弱模型约束力最强)。
|
// 部署级回复语言指令:拼在 system prompt 末尾(尾部对弱模型约束力最强)。
|
||||||
// 同一进程内恒定,不破坏前缀缓存;改配置需重启生效。
|
// 同一进程内恒定,不破坏前缀缓存;改配置需重启生效。
|
||||||
// system prompt 每次请求都随 messages 发出,拼接结果按语言缓存,不重复分配大字符串。
|
// system prompt 每次请求都随 messages 发出,拼接结果按 (profile, 语言) 缓存,不重复分配大字符串。
|
||||||
let _promptTextCache = null; // { lang, text }
|
let _promptTextCache = new Map(); // 'profile\u0000lang' -> text
|
||||||
|
|
||||||
// “可用技能”段落(skills.formatSkillListForPrompt):启动时快照(server.js)与技能变更后
|
// “可用技能”段落(skills.formatSkillListForPrompt):启动时快照(server.js)与技能变更后
|
||||||
// (routes/skills.js)经 setSkillListText 更新,拼在模板之后、语言指令之前。
|
// (routes/skills.js)经 setSkillListText 更新,拼在默认模板之后、语言指令之前。
|
||||||
// 与语言指令同一约定:仅技能增删/描述变化时更新,否则进程内恒定,不破坏前缀缓存。
|
// 与语言指令同一约定:仅技能增删/描述变化时更新,否则进程内恒定,不破坏前缀缓存。
|
||||||
|
// 只拼默认模板:profile 自定义 prompt 完全接管(技能工具若在其白名单内,模型用 list_skills 自取)。
|
||||||
let SKILL_LIST_TEXT = '';
|
let SKILL_LIST_TEXT = '';
|
||||||
function setSkillListText(text) {
|
function setSkillListText(text) {
|
||||||
SKILL_LIST_TEXT = text || '';
|
SKILL_LIST_TEXT = text || '';
|
||||||
_promptTextCache = null; // 列表变化后拼接结果需重建
|
_promptTextCache = new Map(); // 列表变化后拼接结果需重建
|
||||||
}
|
}
|
||||||
|
|
||||||
function systemPromptText(language) {
|
function systemPromptText(language, profile) {
|
||||||
const t = String(language || '').trim();
|
const t = String(language || '').trim();
|
||||||
if (_promptTextCache && _promptTextCache.lang === t) return _promptTextCache.text;
|
const key = (profile || 'default') + '\u0000' + t;
|
||||||
let text = SYSTEM_PROMPT_TEMPLATE;
|
const hit = _promptTextCache.get(key);
|
||||||
if (SKILL_LIST_TEXT) text += '\n\n' + SKILL_LIST_TEXT;
|
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' +
|
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 — ' +
|
'- 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; ' +
|
'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 + '.';
|
'every sentence addressed to the user MUST be in ' + t + '.';
|
||||||
_promptTextCache = { lang: t, text };
|
_promptTextCache.set(key, text);
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,8 +129,10 @@ function cachedDecodeBlocks(session, row) {
|
|||||||
// 关联 tool 回执按 id 一并跳过(否则会留下无 tool_call 配对的孤儿 tool 消息,上游拒收);
|
// 关联 tool 回执按 id 一并跳过(否则会留下无 tool_call 配对的孤儿 tool 消息,上游拒收);
|
||||||
// 改以一条 user 错误提示替代,让模型看到原因后重新生成工具调用 ——
|
// 改以一条 user 错误提示替代,让模型看到原因后重新生成工具调用 ——
|
||||||
// 坏样本留在上下文里只会被模型继续模仿,反复报同一个错。
|
// 坏样本留在上下文里只会被模型继续模仿,反复报同一个错。
|
||||||
function buildMessages(session, language, mintUrl) {
|
// profile:本轮生效的 prompt+tools 组合名(model_profiles,见 engine.resolveProfileName),
|
||||||
const messages = [{ role: 'system', content: systemPromptText(language) }];
|
// 空 = 默认全量组合。
|
||||||
|
function buildMessages(session, language, mintUrl, profile) {
|
||||||
|
const messages = [{ role: 'system', content: systemPromptText(language, profile) }];
|
||||||
const history = session.history;
|
const history = session.history;
|
||||||
// 行被删除后清理残留的图片解析缓存条目(只增不清会缓慢泄漏;条数不会超过现存行数)
|
// 行被删除后清理残留的图片解析缓存条目(只增不清会缓慢泄漏;条数不会超过现存行数)
|
||||||
if (session.blocksCache && session.blocksCache.size > history.length) {
|
if (session.blocksCache && session.blocksCache.size > history.length) {
|
||||||
@@ -204,8 +222,8 @@ function buildMessages(session, language, mintUrl) {
|
|||||||
//(与 buildMessages 同取舍:archived 不发、旧摘要/工具轮照常),末尾追加一条 user
|
//(与 buildMessages 同取舍:archived 不发、旧摘要/工具轮照常),末尾追加一条 user
|
||||||
//(compress-prompt.txt 原文,历史就在它前面的 messages 里,不再填占位符)。
|
//(compress-prompt.txt 原文,历史就在它前面的 messages 里,不再填占位符)。
|
||||||
// 调用方(engine.runLoopInner 的 compressing 分支)需同时不传 tools。
|
// 调用方(engine.runLoopInner 的 compressing 分支)需同时不传 tools。
|
||||||
function compressMessages(session, language, mintUrl) {
|
function compressMessages(session, language, mintUrl, profile) {
|
||||||
const messages = buildMessages(session, language, mintUrl);
|
const messages = buildMessages(session, language, mintUrl, profile);
|
||||||
messages.push({ role: 'user', content: COMPRESS_PROMPT_TEMPLATE });
|
messages.push({ role: 'user', content: COMPRESS_PROMPT_TEMPLATE });
|
||||||
return messages;
|
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 };
|
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 };
|
||||||
|
|||||||
@@ -21,7 +21,13 @@ router.post('/:id/messages', wrap((req, res) => {
|
|||||||
if (!content) return res.status(400).json({ error: 'content 不能为空' });
|
if (!content) return res.status(400).json({ error: 'content 不能为空' });
|
||||||
// deepThink:是否启用模型该「深度思考」参数(thinking_params 合并进上游请求体)
|
// deepThink:是否启用模型该「深度思考」参数(thinking_params 合并进上游请求体)
|
||||||
const deepThink = !!(req.body && req.body.deepThink);
|
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 || '?') + '):' +
|
log.info('msg', (req.user || '-') + ' ' + req.params.id + ' 用户消息(' + (r && r.delivered || '?') + '):' +
|
||||||
content.slice(0, 60).replace(/\s+/g, ' '));
|
content.slice(0, 60).replace(/\s+/g, ' '));
|
||||||
res.json(r);
|
res.json(r);
|
||||||
|
|||||||
@@ -47,6 +47,9 @@ router.get('/status', wrap((req, res) => {
|
|||||||
port: cfg.port,
|
port: cfg.port,
|
||||||
auth_enabled: !!(cfg.auth && cfg.auth.users && cfg.auth.users.length),
|
auth_enabled: !!(cfg.auth && cfg.auth.users && cfg.auth.users.length),
|
||||||
running_sessions: engine.activeRuns(),
|
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 || {},
|
upload: cfg.upload || {},
|
||||||
});
|
});
|
||||||
|
|||||||
+17
-6
@@ -83,6 +83,7 @@ app.get('/api/models', (req, res) => {
|
|||||||
rows.push({
|
rows.push({
|
||||||
id: m.id, display_name: m.display_name, platform: m.platform, mid: m.mid,
|
id: m.id, display_name: m.display_name, platform: m.platform, mid: m.mid,
|
||||||
vision: !!m.vision, type: m.type, key_count: total,
|
vision: !!m.vision, type: m.type, key_count: total,
|
||||||
|
profile: m.profile || '', // 模型默认 prompt+tools 组合(model_profiles 名,空 = 全量)
|
||||||
slots_total: total, slots_busy: busy,
|
slots_total: total, slots_busy: busy,
|
||||||
is_busy: total > 0 && busy >= total ? 1 : 0,
|
is_busy: total > 0 && busy >= total ? 1 : 0,
|
||||||
current_session_id: (sessByPlat[m.platform] || []).join(','),
|
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;
|
const PORT = process.env.PORT || cfg.port;
|
||||||
|
|
||||||
// 启动成功后把模型实际收到的各部分 dump 到文件方便人工核对(data_root 默认 ./data,
|
// 启动成功后把模型实际收到的各部分 dump 到文件方便人工核对(data_root 默认 ./data,
|
||||||
// 宿主机对应 <repo>/data/prompt.txt,已被 gitignore)。包含两部分:
|
// 宿主机对应 <repo>/data/prompt.txt,已被 gitignore)。包含:
|
||||||
// 1) system 消息:模板 + 可用技能段落 + 语言指令(进程内恒定,仅技能增删时变);
|
// 1) 默认组合:system 消息(模板 + 可用技能段落 + 语言指令)+ tools 数组(内置 + MCP);
|
||||||
// 2) tools 数组:内置 definitions.json + 启动时发现的 MCP 工具,与每次请求的 tools 字段一致。
|
// 2) 每套 model_profiles 一段:按其白名单过滤后的 tools + 自定义 prompt(未配则回落默认模板)。
|
||||||
function dumpPromptBundle() {
|
function dumpPromptBundle() {
|
||||||
const file = path.join(cfg.data_root, 'prompt.txt');
|
const file = path.join(cfg.data_root, 'prompt.txt');
|
||||||
|
const lang = (cfg.agent || {}).language;
|
||||||
const tools = engine.TOOL_DEFINITIONS.concat(mcp.toolDefinitions());
|
const tools = engine.TOOL_DEFINITIONS.concat(mcp.toolDefinitions());
|
||||||
const parts = [
|
const parts = [
|
||||||
'# ===== 1. System Prompt(system 消息,进程内恒定)=====\n\n' + llm.systemPromptText((cfg.agent || {}).language),
|
'# ===== 1. System Prompt(默认组合,system 消息,进程内恒定)=====\n\n' + llm.systemPromptText(lang),
|
||||||
'\n\n# ===== 2. Tools(' + tools.length + ' 个:内置 + MCP,随每次请求的 tools 字段发送)=====\n\n' + JSON.stringify(tools, null, 2),
|
'\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.mkdirSync(path.dirname(file), { recursive: true });
|
||||||
fs.writeFileSync(file, parts.join(''), 'utf8');
|
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 服务的工具(单个服务失败只警告,不阻止启动),
|
// 启动时先发现各 MCP 服务的工具(单个服务失败只警告,不阻止启动),
|
||||||
|
|||||||
+11
-7
@@ -234,7 +234,7 @@ stateDiagram-v2
|
|||||||
| `bindModel` / `releaseModel` | 标记 `model_pool.is_busy` + 改 `sessions.model_id`/`status` |
|
| `bindModel` / `releaseModel` | 标记 `model_pool.is_busy` + 改 `sessions.model_id`/`status` |
|
||||||
| `enqueue` / `dequeue` / `dispatchQueued` | FIFO 调度,空闲模型分配给队首会话(`pickModelFor` 优先回绑 `last_model_id`) |
|
| `enqueue` / `dequeue` / `dispatchQueued` | FIFO 调度,空闲模型分配给队首会话(`pickModelFor` 优先回绑 `last_model_id`) |
|
||||||
| `getRun` / `killRunProcs` | 每会话的运行控制(`cancelled` / `procs` / `abortController` / `looping`) |
|
| `getRun` / `killRunProcs` | 每会话的运行控制(`cancelled` / `procs` / `abortController` / `looping`) |
|
||||||
| `runLoop` / `runLoopInner` | Agent 主循环:buildMessages → callModel → 解包 tool args → 校验 → saveMessage → executeTool → saveMessage(tool) → SSE 广播 |
|
| `runLoop` / `runLoopInner` | Agent 主循环:解析 profile → buildMessages → callModel → 解包 tool args → 校验 → saveMessage → executeTool → saveMessage(tool) → SSE 广播。每迭代现解 profile(`resolveProfileName`:`run.profile` > 模型配置 > 默认全量),prompt 与 tools 集(`effectiveTools` 按 `tools_allow` 过滤)跟着组合切换 |
|
||||||
| `streamAssistant` | 单次上游调用:拿 abortSignal / shouldCancel / 各类回调,把流式 chunk 转 SSE 事件(`assistant_delta` / `reasoning_delta`) |
|
| `streamAssistant` | 单次上游调用:拿 abortSignal / shouldCancel / 各类回调,把流式 chunk 转 SSE 事件(`assistant_delta` / `reasoning_delta`) |
|
||||||
| `createSession` | 生成 id(`task-YYYYMMDD-NNN`,序号从历史 + `meta.task_seq` 取大)→ mkdir 任务目录 → 决定立即绑/入队 |
|
| `createSession` | 生成 id(`task-YYYYMMDD-NNN`,序号从历史 + `meta.task_seq` 取大)→ mkdir 任务目录 → 决定立即绑/入队 |
|
||||||
| `postUserMessage` | 用户消息入口;识别 active/held/queued 路径并决定是 `delivered:'live'` 还是 `'queued'` |
|
| `postUserMessage` | 用户消息入口;识别 active/held/queued 路径并决定是 `delivered:'live'` 还是 `'queued'` |
|
||||||
@@ -250,13 +250,15 @@ stateDiagram-v2
|
|||||||
- **archived/summary 机制**(上下文压缩):`type='archived'` 的消息 UI 照常展示但不再发模型;`type='summary'` 是压缩后的"上下文起点"。压缩回合**不插入任何指令消息**:由 `engine.summarizeContext` 在内存 run 上标 `summarizing`,`runLoopInner` 据此走 `llm.compressMessages`:沿用默认 system prompt + 正常历史 messages,末尾追加一条 user(`server/templates/compress-prompt.txt` 原文,参考标题回合的拼法),且不传 tools;回合内首条无 tool_calls 的收尾回复即摘要。(`llm.buildMessages` 仍保留旧库 `summarize_request` 行的处理,仅为历史数据兼容。)
|
- **archived/summary 机制**(上下文压缩):`type='archived'` 的消息 UI 照常展示但不再发模型;`type='summary'` 是压缩后的"上下文起点"。压缩回合**不插入任何指令消息**:由 `engine.summarizeContext` 在内存 run 上标 `summarizing`,`runLoopInner` 据此走 `llm.compressMessages`:沿用默认 system prompt + 正常历史 messages,末尾追加一条 user(`server/templates/compress-prompt.txt` 原文,参考标题回合的拼法),且不传 tools;回合内首条无 tool_calls 的收尾回复即摘要。(`llm.buildMessages` 仍保留旧库 `summarize_request` 行的处理,仅为历史数据兼容。)
|
||||||
- **图片(多模态)**:`messages.content` 列是 TEXT,含图时存 `{"__blocks__":[content...]}` 哨兵 JSON。新版 `read_file` 读图:sharp 压缩产物落任务目录 `.imgcache/`(前端文件列表隐带点的项),库里只存 `image_ref` 轻量块;`buildMessages` 发送前经调用方传入的 `mintUrl` 回调现签成公网外链(同 `mint_public_link` 那套 `GET /p/<id>`)填入 `image_url` 块,base64 不进 DB 也不进请求体;签不到降级为文字占位。旧库/用户粘贴附件的 `data:` URL 块原样透传。图块**只保留最后一条 assistant 之后的**(`lastAssistant` 判定),之前的换成"已省略"文字描述;UI 渲染走带 cookie 的会话内下载路由,历史永不裂图。
|
- **图片(多模态)**:`messages.content` 列是 TEXT,含图时存 `{"__blocks__":[content...]}` 哨兵 JSON。新版 `read_file` 读图:sharp 压缩产物落任务目录 `.imgcache/`(前端文件列表隐带点的项),库里只存 `image_ref` 轻量块;`buildMessages` 发送前经调用方传入的 `mintUrl` 回调现签成公网外链(同 `mint_public_link` 那套 `GET /p/<id>`)填入 `image_url` 块,base64 不进 DB 也不进请求体;签不到降级为文字占位。旧库/用户粘贴附件的 `data:` URL 块原样透传。图块**只保留最后一条 assistant 之后的**(`lastAssistant` 判定),之前的换成"已省略"文字描述;UI 渲染走带 cookie 的会话内下载路由,历史永不裂图。
|
||||||
- **保持租约**(`holdSweeper`):sweeper_ms 巡检(默认 10s);held 会话无观看者 idle_release_ms 释放(默认 3 分钟),有观看者 active_max_ms 强制释放(默认 30 分钟)。active 闲置(绑了模型但无 run 在跑、无未回应消息)按相同租约处理。
|
- **保持租约**(`holdSweeper`):sweeper_ms 巡检(默认 10s);held 会话无观看者 idle_release_ms 释放(默认 3 分钟),有观看者 active_max_ms 强制释放(默认 30 分钟)。active 闲置(绑了模型但无 run 在跑、无未回应消息)按相同租约处理。
|
||||||
|
- **profile(prompt+tools 组合)**:顶层 `model_profiles` 定义多套组合,`platforms[].models[].profile` 引用(见 §5.8);运行期前端发消息带 `profile` 参数覆写(写进 `run.profile`,与 `deepThink` 同约定:回合中途切换、下一迭代即生效;保留值 `default` = 显式全量)。名单外工具被调用不拦(`checkToolArgs` 查不到 def 不报错,`executeTool` 全表照跑);tools schema 只活在请求体不进历史,所以切换不脏化旧消息。压缩回合同跟随(小模型会话点压缩不会回退到默认大模板)。
|
||||||
|
|
||||||
### 5.2 `llm.js` —— 上游调用
|
### 5.2 `llm.js` —— 上游调用
|
||||||
|
|
||||||
| 函数 | 角色 |
|
| 函数 | 角色 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `systemPromptText(language)` | 拼模板 + 技能列表 + 语言指令;进程内缓存(`_promptTextCache`) |
|
| `systemPromptText(language, profile?)` | 按 profile 名选 prompt 源(自定义文件完全接管、不拼技能段;缺省 = 默认模板 + 技能列表段),末尾统一拼语言指令;拼接结果按 (profile, 语言) 缓存(`_promptTextCache` Map) |
|
||||||
| `setSkillListText(text)` | 技能列表变更后清缓存,强制重拼 |
|
| `setSkillListText(text)` | 技能列表变更后清缓存,强制重拼 |
|
||||||
|
| `setProfilePrompts(map)` | profile 自定义 prompt 注册表(name→全文,文本已随配置加载读入);engine.init 调一次,运行期选取零 IO |
|
||||||
| `buildMessages(session, lang, mintUrl?)` | DB 行 → OpenAI messages 数组;处理 summary/archived/errAck/图片消费;`image_ref` 块用 `mintUrl` 现签成公网 `image_url` 外链 |
|
| `buildMessages(session, lang, mintUrl?)` | DB 行 → OpenAI messages 数组;处理 summary/archived/errAck/图片消费;`image_ref` 块用 `mintUrl` 现签成公网 `image_url` 外链 |
|
||||||
| `forEachSSEData(res, onEvent, onMeta, onBadData)` | 通用 SSE 帧解析(空行分隔,data: 行 JSON.parse,注释行走 onMeta) |
|
| `forEachSSEData(res, onEvent, onMeta, onBadData)` | 通用 SSE 帧解析(空行分隔,data: 行 JSON.parse,注释行走 onMeta) |
|
||||||
| `callModel(cfg, modelId, messages, tools, opts)` | 一次模型调用;`opts.deepThink` 启用时合并 `thinking_params`;返回 `{content, reasoning, tool_calls, finish_reason, usage, aborted, sseFrames}` |
|
| `callModel(cfg, modelId, messages, tools, opts)` | 一次模型调用;`opts.deepThink` 启用时合并 `thinking_params`;返回 `{content, reasoning, tool_calls, finish_reason, usage, aborted, sseFrames}` |
|
||||||
@@ -332,7 +334,8 @@ stateDiagram-v2
|
|||||||
|
|
||||||
- 加载:`loadConfig(AGENT_CONFIG)` 读文件 → `parseAndValidate`。
|
- 加载:`loadConfig(AGENT_CONFIG)` 读文件 → `parseAndValidate`。
|
||||||
- 兼容:旧版 `models[]`(扁平)自动迁移到 `platforms[]` 层级;旧版 `web_search.*` 迁移到 `mcp_servers[]`(log.info 提示)。
|
- 兼容:旧版 `models[]`(扁平)自动迁移到 `platforms[]` 层级;旧版 `web_search.*` 迁移到 `mcp_servers[]`(log.info 提示)。
|
||||||
- 规范化:`normalizePlatforms` 校验 `name/url/type`,key 层 `concurrency`,model 层 `{id, display_name, vision, enable, extra_params, thinking_params}`;同平台内 model id 必须唯一(内部唯一键 = 平台名/模型id)。
|
- 规范化:`normalizePlatforms` 校验 `name/url/type`,key 层 `concurrency`,model 层 `{id, display_name, vision, enable, extra_params, thinking_params, profile}`;同平台内 model id 必须唯一(内部唯一键 = 平台名/模型id);`profile` 引用不存在的名字直接报错。
|
||||||
|
- `model_profiles`(顶层,`normalizeModelProfiles`):多套可复用的 prompt+tools 组合,每项 `{tools_allow?, system_prompt_file?}`,两者至少配一个。`tools_allow` 复用 `normToolNames` 约定(非数组/空数组 = 未配),按**最终发给模型的工具名**匹配(含 MCP 的 `服务名__` 前缀,与 prompt.txt dump 同源可对);`system_prompt_file` 相对 `server/templates/`(compose 已 bind-mount ./app/server,宿主直接可改),**配置加载时一次性读入常驻内存**,缺失/为空报错拦在保存/重启预检。运行期切换(前端传参)零 IO、不碰本配置。
|
||||||
- 默认值(`DEFAULTS`):port=8090、log_level=info、terminal default 30s/10K、agent temperature=1.0、max_tool_iterations=20、max_retries=2、model_hold 3min/30min/10s、上传 1.5MB 阈值/2000px/0.85。
|
- 默认值(`DEFAULTS`):port=8090、log_level=info、terminal default 30s/10K、agent temperature=1.0、max_tool_iterations=20、max_retries=2、model_hold 3min/30min/10s、上传 1.5MB 阈值/2000px/0.85。
|
||||||
- 读写:`readConfigText` / `writeConfigText`(先校验后写,无原子 rename,因 bind mount 上 rename 会 EBUSY);`applyEditsToText` 用 `YAML.Document` 保留注释。
|
- 读写:`readConfigText` / `writeConfigText`(先校验后写,无原子 rename,因 bind mount 上 rename 会 EBUSY);`applyEditsToText` 用 `YAML.Document` 保留注释。
|
||||||
- `getConfig` 是浅引用,路由层拿到的就是运行中实例,**改完 in-memory 不影响**(要重启)。
|
- `getConfig` 是浅引用,路由层拿到的就是运行中实例,**改完 in-memory 不影响**(要重启)。
|
||||||
@@ -417,12 +420,12 @@ AI 通过 `schedule_task` 工具为所在会话建周期性任务(`scheduled_t
|
|||||||
| 路径前缀 | 文件 | 主要端点 |
|
| 路径前缀 | 文件 | 主要端点 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `/api/sessions` | `routes/sessions.js` | `POST /` 创建、`GET /` 列表(分页 + 搜索 + user 隔离)、`GET /:id` 详情(含 `schedule` 字段,列表接口不带以免 N+1)、`PATCH /:id` 改名、`DELETE /:id?delete_dir=...`、`POST /:id/bind`、`DELETE /:id/schedule`(删定时任务,只落 `scheduler_note` 通知消息不触发 AI)、`PATCH /:id/schedule`(改提示词/频次,cron 经 validateCron 重校验并重算 next_run_at) |
|
| `/api/sessions` | `routes/sessions.js` | `POST /` 创建、`GET /` 列表(分页 + 搜索 + user 隔离)、`GET /:id` 详情(含 `schedule` 字段,列表接口不带以免 N+1)、`PATCH /:id` 改名、`DELETE /:id?delete_dir=...`、`POST /:id/bind`、`DELETE /:id/schedule`(删定时任务,只落 `scheduler_note` 通知消息不触发 AI)、`PATCH /:id/schedule`(改提示词/频次,cron 经 validateCron 重校验并重算 next_run_at) |
|
||||||
| `/api/sessions/:id/messages` | `routes/messages.js` | `POST /` 发消息(`delivered:'live'\|'queued'`)、`POST /start` "开始执行" 模板消息、`POST /stop`、`POST /release`(held→completed)、`DELETE /messages`(清空 + ?keep=summary)、`POST /summarize`(压缩)、`DELETE /messages/:mid`、`GET /stream` SSE 事件流 |
|
| `/api/sessions/:id/messages` | `routes/messages.js` | `POST /` 发消息(body 可选 `deepThink` / `profile`(model_profiles 名,未知 400;`default`=显式全量;不传=随模型配置);响应 `delivered:'live'\|'queued'`)、`POST /start` "开始执行" 模板消息、`POST /stop`、`POST /release`(held→completed)、`DELETE /messages`(清空 + ?keep=summary)、`POST /summarize`(压缩)、`DELETE /messages/:mid`、`GET /stream` SSE 事件流 |
|
||||||
| `/api/sessions/:id/files` | `routes/files.js` | `POST /` 上传(multer,50MB/文件,文件名清洗 sanitizeName)、`GET /` 列表(递归)、`GET /download[-name/...]` 签名下载(5 分钟 TTL)、`GET /zip-token` + `GET /zip[-name/...]` 选中项(含文件夹)打包 zip 流式下载(纯 Node STORE,两遍读:先 CRC 后磁盘流发送)、`DELETE /` 删文件(目录递归删) |
|
| `/api/sessions/:id/files` | `routes/files.js` | `POST /` 上传(multer,50MB/文件,文件名清洗 sanitizeName)、`GET /` 列表(递归)、`GET /download[-name/...]` 签名下载(5 分钟 TTL)、`GET /zip-token` + `GET /zip[-name/...]` 选中项(含文件夹)打包 zip 流式下载(纯 Node STORE,两遍读:先 CRC 后磁盘流发送)、`DELETE /` 删文件(目录递归删) |
|
||||||
| `/api/skills` | `routes/skills.js` | 技能列表/创建/重命名/删除 + 技能内文件 CRUD + 上传(`?overwrite=true` 覆盖) |
|
| `/api/skills` | `routes/skills.js` | 技能列表/创建/重命名/删除 + 技能内文件 CRUD + 上传(`?overwrite=true` 覆盖) |
|
||||||
| `/api/config` | `routes/config.js` | `GET /` 原文+生效(脱敏)、`POST /validate`、`PUT /` 整文件保存、`PATCH /` 单项修改(path/value/op[delete\|append]) |
|
| `/api/config` | `routes/config.js` | `GET /` 原文+生效(脱敏)、`POST /validate`、`PUT /` 整文件保存、`PATCH /` 单项修改(path/value/op[delete\|append]) |
|
||||||
| `/api/platforms` | `routes/platforms.js` | `GET /balance?pi=&ki=` 余额 |
|
| `/api/platforms` | `routes/platforms.js` | `GET /balance?pi=&ki=` 余额 |
|
||||||
| `/api/system` | `routes/system.js` | `GET /status`、`POST /restart?force=...` |
|
| `/api/system` | `routes/system.js` | `GET /status`(含 `model_profiles` 可用组合名列表,前端模式选择器据渲染)、`POST /restart?force=...` |
|
||||||
| `/api/models` | `server.js` | 空闲/占用模型池 + token 用量 |
|
| `/api/models` | `server.js` | 空闲/占用模型池 + token 用量 |
|
||||||
| `/api/health` | `server.js` | 健康检查 |
|
| `/api/health` | `server.js` | 健康检查 |
|
||||||
| `/api/login` `/api/login_restore` `/api/logout` `/api/password` `/api/me` | `auth.js` | 认证路由(认证前) |
|
| `/api/login` `/api/login_restore` `/api/logout` `/api/password` `/api/me` | `auth.js` | 认证路由(认证前) |
|
||||||
@@ -469,11 +472,12 @@ AI 通过 `schedule_task` 工具为所在会话建周期性任务(`scheduled_t
|
|||||||
详见 `app/config.example.yml`(被 `cp` 为顶层 `config.yml` 部署,**已 gitignore**)。要点:
|
详见 `app/config.example.yml`(被 `cp` 为顶层 `config.yml` 部署,**已 gitignore**)。要点:
|
||||||
|
|
||||||
- `platforms[].keys[].models[]` —— 三层层级。内部唯一键 = `平台名/模型id`(用于历史会话回绑、用量统计),**改名等于重建其下所有模型**。
|
- `platforms[].keys[].models[]` —— 三层层级。内部唯一键 = `平台名/模型id`(用于历史会话回绑、用量统计),**改名等于重建其下所有模型**。
|
||||||
|
- `model_profiles`(顶层)—— 多套可复用的 prompt+tools 组合(`{tools_allow?, system_prompt_file?}`);模型层用 `profile: <名>` 引用,不配 = 默认全量。小模型省上下文用,详见 §5.8;运行期可前端切换(见 §5.1)。
|
||||||
- `agent.max_tool_iterations`(默认 20)—— 单轮迭代上限(含工具调用),到顶自动停止并提示用户继续输入。
|
- `agent.max_tool_iterations`(默认 20)—— 单轮迭代上限(含工具调用),到顶自动停止并提示用户继续输入。
|
||||||
- `terminal.max_output_chars`(默认 10000)—— AI 看到的命令输出上限;executor 侧另有 `EXECUTOR_MAX_OUTPUT_CHARS=200000` 兜底。
|
- `terminal.max_output_chars`(默认 10000)—— AI 看到的命令输出上限;executor 侧另有 `EXECUTOR_MAX_OUTPUT_CHARS=200000` 兜底。
|
||||||
- `skills.skills_root` —— 缺省取 `workspace_root` 的同级 `skills/`。
|
- `skills.skills_root` —— 缺省取 `workspace_root` 的同级 `skills/`。
|
||||||
- `model_hold` —— 保持租约;详情见 §5.1。
|
- `model_hold` —— 保持租约;详情见 §5.1。
|
||||||
- 上下文压缩 —— 无配置项:压缩回合的 system prompt 整体替换为固定模板 `server/templates/compress-prompt.txt`,该回合不传 tools;调整压缩策略直接改该文件。
|
- 上下文压缩 —— 无配置项:压缩回合沿用当前 profile 的 system prompt(无 profile = 默认模板)+ 正常历史,末尾追加一条 user(固定模板 `server/templates/compress-prompt.txt` 原文),该回合不传 tools;调整压缩策略直接改该文件。
|
||||||
- 会话标题自动生成 —— 无配置项:首次交互回合结束(`finalize` 成功分支)后触发,用会话当前 model_id 发一次**不带 system、不传 tools** 的标题请求(历史 user/assistant 原文 + 模板 `server/templates/title-prompt.txt` 作末条 user,`{{language}}` 填 `agent.language`);结果清洗后写入 `sessions.title` 并 SSE 推 `title` 事件。失败静默(title 仍空,下个回合结束自动重试);已有标题(建会话时填写或手动重命名)不覆盖。
|
- 会话标题自动生成 —— 无配置项:首次交互回合结束(`finalize` 成功分支)后触发,用会话当前 model_id 发一次**不带 system、不传 tools** 的标题请求(历史 user/assistant 原文 + 模板 `server/templates/title-prompt.txt` 作末条 user,`{{language}}` 填 `agent.language`);结果清洗后写入 `sessions.title` 并 SSE 推 `title` 事件。失败静默(title 仍空,下个回合结束自动重试);已有标题(建会话时填写或手动重命名)不覆盖。
|
||||||
- `auth.users` —— 明文密码配在配置里(自用场景);`secret` 留空则随机生成(重启掉登录态,建议固定随机串)。
|
- `auth.users` —— 明文密码配在配置里(自用场景);`secret` 留空则随机生成(重启掉登录态,建议固定随机串)。
|
||||||
- `mcp_servers[].enable: false` —— 启动不加载该服务(配置保留),其余工具不受影响。
|
- `mcp_servers[].enable: false` —— 启动不加载该服务(配置保留),其余工具不受影响。
|
||||||
@@ -599,7 +603,7 @@ sequenceDiagram
|
|||||||
|
|
||||||
### 11.4 加一个模型 / 平台
|
### 11.4 加一个模型 / 平台
|
||||||
|
|
||||||
改 `config.yml` 的 `platforms`:加新平台 `{name, url, type, keys:[{api_key, models:[{id, display_name, vision?, enable?, extra_params?, thinking_params?}]}]}`,**或**在已有平台加新 key/新 model。重启生效。`enable: false` 的模型不进模型池。
|
改 `config.yml` 的 `platforms`:加新平台 `{name, url, type, keys:[{api_key, models:[{id, display_name, vision?, enable?, extra_params?, thinking_params?}]}]}`,**或**在已有平台加新 key/新 model。重启生效。`enable: false` 的模型不进模型池。小模型可加 `profile: <名>` 引用顶层 `model_profiles` 的 prompt+tools 组合(见 §5.8)。
|
||||||
|
|
||||||
模型内部唯一键 = `平台名/模型id`(用于历史回绑、token 用量统计)—— **重命名平台等于重建其下所有模型**。
|
模型内部唯一键 = `平台名/模型id`(用于历史回绑、token 用量统计)—— **重命名平台等于重建其下所有模型**。
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user