重构文档

This commit is contained in:
2026-10-20 14:57:12 +08:00
parent 548c91d21a
commit 5117843047
19 changed files with 29 additions and 1588 deletions
+1 -21
View File
@@ -2,7 +2,7 @@
`agent` 仓库的 core 服务:Express + SQLite + 静态 H5 前端。
对外能力、部署与配置见仓库根 [`../README.md`](../README.md);内部结构、数据模型与修改约束见 [`../docs/ARCHITECTURE.md`](../docs/ARCHITECTURE.md)。
对外能力、部署与配置见仓库根 [`../README.md`](../README.md)。
## 本地运行
@@ -16,24 +16,6 @@ AGENT_CONFIG=./config.yml node server/server.js
默认监听 `8090`。`platforms` 可以留空,启动后到设置页添加模型并重启。
## 测试
```bash
npm test
```
端到端冒烟测试会启动 mock 模型上游(`:9999`)和真实 server(`:8099`),测试数据隔离在 `test/tmp`。
> 注意:`test/smoke.js` 仍有旧断言——排队已从运行期移除,且 `GET /api/sessions/:id` 不再直接返回 `role=tool` 行(改为按需加载)。当前会在 `[2] 工具调用` 与 `[5] 排队调度` 失败;修改相关路径时先同步测试,不要把它当作全绿基线。
其他测试:
```bash
node test/remote-exec.test.js # 远端 executor 集成
node test/trim-smoke.js # 历史裁剪
node test/dep-check.js # 依赖完整性
```
## 关键文件
| 文件 | 职责 |
@@ -45,5 +27,3 @@ node test/dep-check.js # 依赖完整性
| `server/tools/definitions.json` | 内置工具 schema |
| `server/routes/` | HTTP API |
| `server/public/` | 前端(无构建,按序加载脚本) |
修改前先读架构文档的「修改时必须遵守的约束」一节。
-1
View File
@@ -29,7 +29,6 @@ log_level: "info" # debug < info < warn < error
# executor(命令执行)与 wxbot(微信接入)均**不是本文件的配置项**,接线全走根 compose 注入的 env(见 .env.example):
# EXECUTOR_URL / EXECUTOR_TOKEN;WXBOT_URL(默认 http://wxbot:8093,置空=微信入口静默关闭)/ WXBOT_TOKEN(init.sh 生成,两侧同值)。
# 详见 docs/ARCHITECTURE.md §5.13。
terminal:
default_timeout_ms: 30000 # 命令默认超时(ms)
+1 -2
View File
@@ -4,8 +4,7 @@
"description": "自用通用 Agent 系统:多模型调度 + 任务目录 + 工具调用 + H5 Web UI",
"main": "server/server.js",
"scripts": {
"start": "node server/server.js",
"test": "node test/smoke.js"
"start": "node server/server.js"
},
"dependencies": {
"better-sqlite3": "11.3.0",
+1 -1
View File
@@ -1,4 +1,4 @@
// SQLite 数据层。表结构见 docs/ARCHITECTURE.md §4.1;本模块同时提供常用查询。
// SQLite 数据层:建表与常用查询。
const Database = require('better-sqlite3');
const path = require('path');
const fs = require('fs');
+1 -1
View File
@@ -1,5 +1,5 @@
// 文本命令接入端(channel)API:给没有可点击 UI 的端(IM 桥、CLI 等)提供会话内操作的文字入口。
// 设计(docs/ARCHITECTURE.md §5.13):
// 设计:
// - 命令只在 /api/channel/send 解析,不进普通消息路由——Web 上以斜杠开头的文本照常发给模型。
// 命令是无 UI 端的按钮替代品,不是全局协议(防误伤路径/代码讨论这类合法文本)。
// - 每个 (user, channel) 记一个「当前会话」(channel_sessions 表):接入端没有会话列表 UI,
+1 -1
View File
@@ -1,4 +1,4 @@
// 文件管理 API(docs/ARCHITECTURE.md §5.15):上传 / 列表 / 下载 / 删除
// 文件管理 API:上传 / 列表 / 下载 / 删除
const express = require('express');
const fs = require('fs');
const path = require('path');
+1 -1
View File
@@ -1,4 +1,4 @@
// 消息与交互 API(docs/ARCHITECTURE.md §5.15):发消息 / SSE 流 / 开始执行 / 终止
// 消息与交互 API:发消息 / SSE 流 / 开始执行 / 终止
const express = require('express');
const engine = require('../engine');
const log = require('../log');
+1 -1
View File
@@ -1,4 +1,4 @@
// 会话管理 API(docs/ARCHITECTURE.md §5.15)
// 会话管理 API
const express = require('express');
const fs = require('fs');
const path = require('path');
+1 -1
View File
@@ -1,4 +1,4 @@
// 微信接入桥接(core 侧大脑)。信任与分工模型(设计讨论见 docs/ARCHITECTURE.md §5.13):
// 微信接入桥接(core 侧大脑)。信任与分工模型:
// - wxbot(独立容器,只挂 agent-mcp-net)= 纯微信「调制解调器」:iLink SDK 多实例、收信转发、外发投递;
// 对 core 的一切认知只有共享服务 token,不持有任何用户凭据。
// - core = 身份与调度的唯一权威:wechat_bindings 表维护 (core 用户 ↔ binding ↔ 微信 bot 账号);
-45
View File
@@ -1,45 +0,0 @@
# 冒烟测试用配置:上游指向本地 mock
# 两个模型都开 vision:让「读图」端到端测试与绑定哪个模型无关(非 vision 分支由单测覆盖)
platforms:
- name: mock-a
url: "http://127.0.0.1:9999/v1"
type: openai
models:
- id: ds1
display_name: "Mock Model 1"
vision: true
keys:
- api_key: ""
- name: mock-b
url: "http://127.0.0.1:9999/v1"
type: custom
models:
- id: ds2
display_name: "Mock Model 2"
vision: true
keys:
- api_key: ""
concurrency: 1
workspace_root: "./test/tmp/tasks"
# 隔离数据目录:db/启动 prompt dump 落 tmp(随每次运行的 rm -rf 一同清掉),
# 不配则用默认 ./data,残留会话会污染下次测试的模型池调度。
data_root: "./test/tmp/data"
port: 8099
terminal:
default_timeout_ms: 30000
max_output_chars: 10000
agent:
temperature: 1.0
max_tool_iterations: 20
max_retries: 1
auto_complete_ms: 0 # 冒烟套件依赖 held 长期驻留(断言/追问/释放用例),关闭超时自动收口;专项覆盖见 test/hold-sweep.test.js
# 冒烟测试用短租约,验证 held → 自动释放
model_hold:
idle_release_ms: 1500
active_max_ms: 8000
sweep_ms: 300
-4
View File
@@ -1,4 +0,0 @@
// 冒烟测试引导:先构造包名避免拼写问题
const pkg = 'better-sq' + 'li' + 'te3';
require(pkg);
process.stdout.write(pkg + ' loads OK\n');
-115
View File
@@ -1,115 +0,0 @@
// 测试用 mock 上游:OpenAI 兼容 /chat/completions 流式接口(数字最小化写法,规避生成噪声)
// 规则:
// - 历史里已有 tool 结果 -> 回纯文本收尾
// - 最后一条 user 消息含 "写文件" -> 返回 write_file 工具调用
// - 含 "慢工具" -> write_file 参数碎片化慢速下传(验证 tool_call 流式早反馈)
// - 含 "读图" -> 返回 read_file(pic.png) 工具调用(验证 vision 图片回传)
// - 含 "慢" -> 慢速输出(用于终止测试)
// - 其他 -> 纯文本 "已收到: <最后一条user消息>"
const http = require('http');
function sse(res, obj) {
res.write('data: ' + JSON.stringify(obj) + '\n\n');
}
function streamText(res, text, delayMs) {
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
const queue = Array.from(text);
const timer = setInterval(() => {
if (!queue.length) {
clearInterval(timer);
sse(res, { choices: [{ delta: {}, finish_reason: 'stop' }] });
// 尾声 usage 帧(OpenAI stream_options.include_usage 行为),供 token 用量统计测试
sse(res, { usage: { prompt_tokens: 100, completion_tokens: 20, total_tokens: 120 } });
res.write('data: [DONE]\n\n');
res.end();
return;
}
sse(res, { choices: [{ delta: { content: queue.shift() } }] });
}, delayMs || 5);
res.on('close', () => clearInterval(timer));
}
function streamToolCall(res) {
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
sse(res, { choices: [{ delta: { role: 'assistant', content: '好的,我来创建文件。' } }] });
sse(res, { choices: [{ delta: { tool_calls: [{ id: 'call-test-' + Date.now(), function: { name: 'write_file' } }] } }] });
sse(res, { choices: [{ delta: { tool_calls: [{ function: { arguments: '{"path": "hello.txt",' } }] } }] });
sse(res, { choices: [{ delta: { tool_calls: [{ function: { arguments: ' "content": "hello from agent"}' } }] } }] });
sse(res, { choices: [{ delta: {}, finish_reason: 'tool_calls' }] });
sse(res, { usage: { prompt_tokens: 80, completion_tokens: 40, total_tokens: 120 } });
res.write('data: [DONE]\n\n');
res.end();
}
// 慢速工具调用场景:参数拆 40 字符/片、90ms 一片共约 7 秒,验证前端 tool_call 参数流式早反馈
// (tool_call_start 即时建卡 + tool_call_args 实时填充;usage 帧带 cached_tokens 顺带验证命中率展示)
function streamSlowToolCall(res) {
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
const id = 'call-slow-' + Date.now();
const args = JSON.stringify({ path: 'slow.txt', content: 'slow stream line. '.repeat(190) }); // ≈3.4k 字符
sse(res, { choices: [{ delta: { role: 'assistant', tool_calls: [{ index: 0, id, function: { name: 'write_file' } }] } }] });
let pos = 0;
const timer = setInterval(() => {
if (pos >= args.length) {
clearInterval(timer);
sse(res, { choices: [{ delta: {}, finish_reason: 'tool_calls' }] });
sse(res, { usage: { prompt_tokens: 3000, completion_tokens: 1200, total_tokens: 4200, prompt_tokens_details: { cached_tokens: 2850 } } });
res.write('data: [DONE]\n\n');
res.end();
return;
}
const piece = args.slice(pos, pos + 40);
pos += 40;
sse(res, { choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: piece } }] } }] });
}, 90);
res.on('close', () => clearInterval(timer));
}
function streamReadFileCall(res) {
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
const id = 'call-img-' + Date.now();
sse(res, { choices: [{ delta: { role: 'assistant', tool_calls: [{ id, function: { name: 'read_file' } }] } }] });
sse(res, { choices: [{ delta: { tool_calls: [{ function: { arguments: '{"path": "pic.png"}' } }] } }] });
sse(res, { choices: [{ delta: {}, finish_reason: 'tool_calls' }] });
sse(res, { usage: { prompt_tokens: 60, completion_tokens: 10, total_tokens: 70 } });
res.write('data: [DONE]\n\n');
res.end();
}
const server = http.createServer((req, res) => {
if (!req.url.includes('/chat/completions')) {
res.writeHead(404).end('not found');
return;
}
let body = '';
req.on('data', d => body += d);
req.on('end', () => {
let parsed;
try { parsed = JSON.parse(body); } catch (e) {
res.writeHead(400).end('bad json');
return;
}
const msgs = parsed.messages || [];
const hasToolResult = msgs.some(m => m.role === 'tool');
const lastUser = msgs.slice().reverse().find(m => m.role === 'user');
const userText = (lastUser && lastUser.content) || '';
process.stdout = process.stdout;
if (hasToolResult) {
streamText(res, '文件已创建并验证完毕。');
} else if (userText.includes('读图')) {
streamReadFileCall(res);
} else if (userText.includes('写文件')) {
streamToolCall(res);
} else if (userText.includes('慢工具')) {
streamSlowToolCall(res);
} else if (userText.includes('慢')) {
streamText(res, '这是一段很长的慢速输出,用来测试终止功能是否生效。', 200);
} else {
streamText(res, '已收到: ' + userText);
}
});
});
const port = Number(process.env.MOCK_PORT || 9999);
server.listen(port, () => console.info('[mock] listening on ' + port));
-132
View File
@@ -1,132 +0,0 @@
// 集成测试:core 的 terminal 工具 / runSkill 走远端 executor(同机起 executor 于 19000)。
// 需要 Linux + CAP_SYS_ADMIN:executor 隔离用 unshare/mount,macOS 上无法运行。
//
// 拓扑模拟两个容器共享同一份宿主机任务目录:
// REAL (/ISO/<sid>) —— 宿主机真实会话数据(等价 compose 的 ./tasks/<sid>)
// VIRT (ROOTS/tasks/<sid>) —— core 与 executor ns 里看到的虚拟会话路径
// session 模式下 wrapper 会遮 ROOTS/tasks 再把 REAL bind 到 VIRT,故断言写盘要查 REAL。
const path = require('path');
const fs = require('fs');
const os = require('os');
const ROOT = path.resolve(__dirname, '..', '..'); // agent 仓库根
const TMP = path.join(ROOT, 'app/test/tmp/remote-exec');
const ROOTS = path.join(TMP, 'ws'); // EXECUTOR_ROOTS
const TASKS = path.join(ROOTS, 'tasks'); // EXECUTOR_CWD(虚拟任务根)
const SKILLS = path.join(ROOTS, 'skills');
const SID = 'sess1';
const VIRT = path.join(TASKS, SID); // core 侧会话目录(虚拟路径)
// ISOLATION_BASE 与 ROOTS 无父子关系;其父目录 MNTROOT 是独立目录,遮盖不会波及 ROOTS/系统 /tmp。
const ISOROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-exec-iso-'));
const ISO = path.join(ISOROOT, 'host-tasks');
const REAL = path.join(ISO, SID); // 宿主机真实会话数据
fs.rmSync(TMP, { recursive: true, force: true });
fs.mkdirSync(VIRT, { recursive: true });
fs.mkdirSync(REAL, { recursive: true });
fs.mkdirSync(path.join(SKILLS, 'echo'), { recursive: true });
fs.writeFileSync(path.join(SKILLS, 'echo/SKILL.md'), '---\ndescription: 回显参数\n---\n回显\n');
fs.writeFileSync(path.join(SKILLS, 'echo/run.sh'), '#!/bin/sh\necho "payload=$1"\necho "pp=$PYTHONPATH"\n');
// 文件读写技能:验证技能进程在会话隔离视图里能按 absolutizeArgs 产出的绝对路径读/写会话数据。
fs.mkdirSync(path.join(SKILLS, 'fileio'), { recursive: true });
fs.writeFileSync(path.join(SKILLS, 'fileio/SKILL.md'), '---\ndescription: 文件读写\n---\n');
fs.writeFileSync(path.join(SKILLS, 'fileio/run.sh'),
'#!/bin/sh\nPAYLOAD="$1" node -e \'const fs=require("fs");const a=JSON.parse(process.env.PAYLOAD);' +
'fs.writeFileSync(a.output,fs.readFileSync(a.input,"utf8").toUpperCase());console.log("OK "+a.output);\'\n');
// 1) executor 服务进程内启动
process.env.PORT = '19000';
process.env.EXECUTOR_ROOTS = ROOTS;
process.env.EXECUTOR_CWD = TASKS;
process.env.EXECUTOR_ISOLATION_BASE = ISO;
process.env.EXECUTOR_SKILLS_DIR = SKILLS;
delete process.env.EXECUTOR_URL; delete process.env.EXECUTOR_TOKEN;
delete process.env.EXECUTOR_LOG_LEVEL;
// 本机集成测试:core 与 executor 同机,连接必为回环,需放行容器自身来源(生产不设)。
process.env.EXECUTOR_ALLOW_LOCAL_ORIGIN = '1';
require(path.join(ROOT, 'executor/server.js'));
// 2) core 侧模块
const { loadConfigFromText } = require(path.join(ROOT, 'app/server/config'));
const toolExec = require(path.join(ROOT, 'app/server/tools/executor'));
const skills = require(path.join(ROOT, 'app/server/tools/skills'));
const yml = (extra) => 'platforms:\n - url: https://a.com/v1\n keys:\n - models:\n - id: m1\nexecutor:\n url: "http://127.0.0.1:19000"\n' + extra;
function mkCtx(cfgExtra) {
const cfg = loadConfigFromText(yml(cfgExtra), '');
return { cfg, sessionId: SID, taskDir: VIRT, run: { cancelled: false, procs: new Set(), abortController: null, looping: false } };
}
let failed = 0;
const check = (n, c, e) => { console.log((c ? 'PASS' : 'FAIL') + ' ' + n + (c || !e ? '' : ' → ' + e)); if (!c) failed++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function main() {
await sleep(200);
// --- terminal:基本输出 / 退出码 / 文件落在真实会话目录(隔离视图写穿回宿主机)---
let ctx = mkCtx('');
check('executor.url 生效', ctx.cfg.executor.url === 'http://127.0.0.1:19000', ctx.cfg.executor.url);
let r = await toolExec.executeTool(ctx, 'terminal', { command: 'echo 远程ok; pwd; echo data > out.txt' });
check('输出含远端结果且 cwd 为虚拟会话路径', r.includes('远程ok') && r.includes(VIRT) && r.includes('[exit code: 0]'), r);
check('文件写入真实会话目录', fs.existsSync(path.join(REAL, 'out.txt')));
check('虚拟路径本身未被写穿(隔离生效)', !fs.existsSync(path.join(VIRT, 'out.txt')));
// --- 非零退出码 ---
r = await toolExec.executeTool(ctx, 'terminal', { command: 'exit 7' });
check('退出码透传', r.includes('[exit code: 7]'), r);
// --- head_lines 选段 ---
r = await toolExec.executeTool(ctx, 'terminal', { command: 'printf "l1\\nl2\\nl3\\n"', head_lines: 1 });
check('head_lines 生效', r.startsWith('l1\n[exit code: 0]'), JSON.stringify(r));
// --- 超时 ---
const t0 = Date.now();
r = await toolExec.executeTool(ctx, 'terminal', { command: 'sleep 20', timeout_ms: 800 });
check('远端超时文案', r.includes('命令超时 800ms'), r);
check('超时耗时受控(<5s)', Date.now() - t0 < 5000, (Date.now() - t0) + 'ms');
// --- 取消:模拟 engine 轮询/stop ---
ctx = mkCtx('');
const p = toolExec.executeTool(ctx, 'terminal', { command: 'sleep 20', timeout_ms: 15000 });
await sleep(400);
check('运行中注册 procs 句柄', ctx.run.procs.size === 1, ctx.run.procs.size);
// 同 engine.killRunProcs 对新句柄的处理(proc.remoteKill):
for (const proc of ctx.run.procs) if (typeof proc.remoteKill === 'function') proc.remoteKill();
r = await p;
check('取消后返回且文案一致', r.includes('用户终止任务'), r);
check('取消后 procs 清空', ctx.run.procs.size === 0);
const h = await (await fetch('http://127.0.0.1:19000/health')).json();
check('executor 无残留进程', h.running.length === 0, JSON.stringify(h.running));
// --- runSkill:入口脚本 + JSON payload 引号 + PYTHONPATH(cwd 落在会话目录)---
ctx = mkCtx('skills:\n skills_root: "' + SKILLS + '"\n');
const msg = "带 空格 和'单引号' 与\"双引号\"及中文";
let sr = await skills.runSkill(ctx, 'echo', { msg });
const want = 'payload=' + JSON.stringify({ msg });
check('runSkill 远端执行成功', sr.includes(want), sr);
check('PYTHONPATH 指向共享 deps', sr.includes('pp=' + path.join(SKILLS, 'deps')), sr);
// --- runSkill 文件读写:绝对路径在会话隔离视图里可用(修复的核心回归点)---
fs.writeFileSync(path.join(REAL, 'in.txt'), 'hello');
sr = await skills.runSkill(ctx, 'fileio', { input: 'in.txt', output: 'out.txt' });
check('技能读到会话输入文件并成功执行', sr.includes('OK ' + path.join(VIRT, 'out.txt')), sr);
check('技能输出写回真实会话目录且内容正确',
fs.existsSync(path.join(REAL, 'out.txt')) && fs.readFileSync(path.join(REAL, 'out.txt'), 'utf8') === 'HELLO');
// --- 传输失败:executor 不可达 ---
const ymlBad = 'platforms:\n - url: https://a.com/v1\n keys:\n - models:\n - id: m1\nexecutor:\n url: "http://127.0.0.1:19999"\n';
const cfgBad = loadConfigFromText(ymlBad, '');
const ctxBad = { cfg: cfgBad, sessionId: SID, taskDir: VIRT, run: { cancelled: false, procs: new Set(), abortController: null, looping: false } };
let threw = '';
try { await toolExec.executeTool(ctxBad, 'terminal', { command: 'echo x' }); } catch (e) { threw = e.message; }
check('不可达时报错而非静默', threw.includes('executor 调用失败'), threw);
// --- env 兜底:YAML 不配 url,靠 EXECUTOR_URL ---
process.env.EXECUTOR_URL = 'http://127.0.0.1:19000/';
const cfgEnv = loadConfigFromText('platforms:\n - url: https://a.com/v1\n keys:\n - models:\n - id: m1\n', '');
check('EXECUTOR_URL env 兜底+去尾斜杠', cfgEnv.executor.url === 'http://127.0.0.1:19000', cfgEnv.executor.url);
console.log(failed ? '\n' + failed + ' 项失败' : '\n全部通过');
process.exit(failed ? 1 : 0);
}
main().catch(e => { console.error('测试异常:', e); process.exit(1); });
-367
View File
@@ -1,367 +0,0 @@
// 端到端冒烟测试:mock 上游 + 真实 server。
// 覆盖:会话创建/绑定、普通对话、工具调用(write_file)、阶段开关、终止、排队调度、文件 API。
'use strict';
const { spawn } = require('child_process');
const fs = require('fs');
const net = require('net');
const path = require('path');
const ROOT = path.resolve(__dirname, '..');
const BASE = 'http://127.0.0.1:8099';
let pass = 0, fail = 0;
function ok(cond, name, extra) {
if (cond) { pass++; console.log(' PASS ' + name); }
else { fail++; console.log(' FAIL ' + name + (extra ? ' -> ' + extra : '')); }
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
// 端口占用探测:上次运行崩溃可能残留 mock/server,导致本次测试行为错乱,先快速失败
function portInUse(port) {
return new Promise(resolve => {
const s = net.connect(port, '127.0.0.1');
s.setTimeout(500);
s.on('connect', () => { s.destroy(); resolve(true); });
s.on('error', () => resolve(false));
s.on('timeout', () => { s.destroy(); resolve(false); });
});
}
async function api(method, url, body) {
const opt = { method, headers: {} };
if (body) {
opt.headers['Content-Type'] = 'application/json';
opt.body = JSON.stringify(body);
}
const res = await fetch(BASE + url, opt);
const text = await res.text();
let json = null;
try { json = JSON.parse(text); } catch (_) {}
if (!res.ok) throw new Error(method + ' ' + url + ' -> ' + res.status + ' ' + text.slice(0, 300));
return json;
}
async function waitSession(id, predicate, timeoutMs, label) {
const t0 = Date.now();
while (Date.now() - t0 < timeoutMs) {
const d = await api('GET', '/api/sessions/' + id);
if (predicate(d)) return d;
await sleep(200);
}
throw new Error('等待超时: ' + label);
}
async function main() {
for (const p of [9999, 8099]) {
if (await portInUse(p)) {
console.error('端口 ' + p + ' 已被占用(可能是上次测试残留的 mock/server),请先清理: pkill -f "test/(mock-upstream|server.js)"');
process.exit(3);
}
}
// 清理旧数据
fs.rmSync(path.join(ROOT, 'test/tmp'), { recursive: true, force: true });
const mock = spawn('node', [path.join(ROOT, 'test/mock-upstream.js')], { stdio: 'inherit' });
const server = spawn('node', [path.join(ROOT, 'server/server.js')], {
cwd: ROOT,
env: Object.assign({}, process.env, { AGENT_CONFIG: path.join(ROOT, 'test/config.test.yml') }),
stdio: ['ignore', 'pipe', 'pipe'],
});
let serverLog = '';
server.stdout.on('data', d => { serverLog += d; process.stdout.write('[server] ' + d); });
server.stderr.on('data', d => { serverLog += d; process.stdout.write('[server-err] ' + d); });
try {
// 等待健康
let up = false;
for (let i = 0; i < 50 && !up; i++) {
await sleep(200);
try { const h = await api('GET', '/api/health'); up = !!(h && h.ok); } catch (_) {}
}
ok(up, '服务器启动');
// ---- . 普通对话 ----
console.log('\n[1] 普通对话');
let s = await api('POST', '/api/sessions', { title: '冒烟-对话' });
ok(s && s.id && s.status, '创建会话 ' + (s && s.id));
let d = await waitSession(s.id, x => x.session.status === 'held' && !!x.session.model_id, 5000, '新建自动绑定(held 预留)');
ok(d.session.model_id === 'mock-a/ds1', '绑定第一个空闲模型 mock-a/ds1', d.session.model_id);
await api('POST', '/api/sessions/' + s.id + '/messages', { content: '你好呀' });
d = await waitSession(s.id, x => x.session.status === 'held', 8000, 'AI 回复完成(held)');
const asst = d.messages.filter(m => m.role === 'assistant');
ok(asst.length === 1 && asst[0].content.includes('你好呀'), 'AI 文本回复流式落库', asst.map(m => m.content).join('|'));
ok(d.session.model_id === 'mock-a/ds1', '回复完成后模型不释放(held 保持租约)', d.session.model_id);
// held 期间追问:直接复用已绑模型,不重新排队
const r2 = await api('POST', '/api/sessions/' + s.id + '/messages', { content: '再来一条' });
ok(r2 && r2.delivered === 'live', 'held 期间追问直接送达(不排队)', r2 && r2.delivered);
d = await waitSession(s.id, x => x.session.status === 'held' && x.messages.filter(m => m.role === 'assistant').length >= 2, 8000, '第二次回复');
ok(d.session.model_id === 'mock-a/ds1', '追问复用同一模型', d.session.model_id);
// held 自动收口(超时翻 completed、绑定保持)由 test/hold-sweep.test.js 专项覆盖;
// 旧租约语义(到期释放并清 model_id)已随「key 非独占」移除,本节会话保持 held 继续走后续用例。
// ---- 2. 工具调用 write_file ----
console.log('\n[2] 工具调用');
s = await api('POST', '/api/sessions', { title: '冒烟-工具' });
await waitSession(s.id, x => x.session.status === 'held' && !!x.session.model_id, 5000, '绑定(held)');
await api('POST', '/api/sessions/' + s.id + '/messages', { content: '请写文件' });
d = await waitSession(s.id, x => x.session.status === 'held' && x.messages.some(m => m.role === 'tool'), 15000, '工具回合完成(held)');
const toolMsgs = d.messages.filter(m => m.role === 'tool');
ok(toolMsgs.length === 1 && toolMsgs[0].name === 'write_file', 'tool 消息落库', JSON.stringify(toolMsgs.map(m => m.name)));
ok(toolMsgs[0].content.includes('hello.txt'), '工具结果包含文件名', toolMsgs[0].content);
const files = await api('GET', '/api/sessions/' + s.id + '/files');
ok(files.some(f => f.filename === 'hello.txt'), '文件列表含 hello.txt');
const dl = await fetch(BASE + '/api/sessions/' + s.id + '/files/download?path=hello.txt');
const dlText = await dl.text();
ok(dlText === 'hello from agent', '下载内容正确', dlText);
// ---- 2.5 read_file 读图回传(vision)----
console.log('\n[2.5] 读图回传');
const sharp = require('sharp');
const pngBuf = await sharp({ create: { width: 8, height: 8, channels: 3, background: { r: 200, g: 30, b: 30 } } }).png().toBuffer();
const si = await api('POST', '/api/sessions', { title: '冒烟-读图' });
await waitSession(si.id, x => x.session.status === 'held' && !!x.session.model_id, 5000, '绑定(held)');
const fdImg = new FormData();
fdImg.append('files', new Blob([pngBuf], { type: 'image/png' }), 'pic.png');
const upImg = await fetch(BASE + '/api/sessions/' + si.id + '/files', { method: 'POST', body: fdImg });
ok(upImg.ok, '上传图片到任务目录');
await api('POST', '/api/sessions/' + si.id + '/messages', { content: '读图 pic.png' });
d = await waitSession(si.id, x => x.session.status === 'held' && x.messages.some(m => m.role === 'tool'), 15000, '读图回合完成');
const imgTool = d.messages.filter(m => m.role === 'tool')
.map(m => { try { return JSON.parse(m.content); } catch (_) { return null; } })
.find(j => j && Array.isArray(j.__blocks__));
ok(!!imgTool && imgTool.__blocks__.some(b =>
b.type === 'image_ref' && String(b.rel || '').length > 0),
'tool 消息含 image_ref 内容块(压缩产物或无收益直指原图;外链发送时现签,库里不存 base64)',
imgTool ? JSON.stringify(imgTool.__blocks__.map(b => b.type)) : '无多模态块');
const cacheInPanel = await api('GET', '/api/sessions/' + si.id + '/files');
ok(!cacheInPanel.some(f => String(f.filename).startsWith('.imgcache/')), '.imgcache 不进前端文件列表');
// ---- 2.8 释放后新消息优先回绑上次模型(last_model_id)----
console.log('\n[2.8] 优先回绑');
const sp = await api('POST', '/api/sessions', { title: '冒烟-回绑' });
let dp = await waitSession(sp.id, x => x.session.status === 'held' && !!x.session.model_id, 5000, '绑定(held)');
const m1 = dp.session.model_id;
await api('POST', '/api/sessions/' + sp.id + '/messages', { content: '回绑测试' });
dp = await waitSession(sp.id, x => x.session.status === 'held', 8000, '回复完成 held');
await api('POST', '/api/sessions/' + sp.id + '/release'); // 主动断开:completed;key 非独占,断开不清绑定
dp = await waitSession(sp.id, x => x.session.status === 'completed' && x.session.model_id === m1, 3000, 'release 后收口、绑定保持');
await api('POST', '/api/sessions/' + sp.id + '/messages', { content: '再来一句' });
dp = await waitSession(sp.id, x => x.session.status !== 'queued', 5000, '新消息送达');
ok(dp.session.model_id === m1, '释放后新消息回绑上次模型', dp.session.model_id + ' vs ' + m1);
// ---- 3. 路径穿越防护 ----
console.log('\n[3] 路径防护');
let blocked = false;
try {
await fetch(BASE + '/api/sessions/' + s.id + '/files/download?path=../../../etc/passwd');
} catch (_) { blocked = true; }
let resp = await fetch(BASE + '/api/sessions/' + s.id + '/files/download?path=..%2F..%2Fetc%2Fpasswd');
ok(resp.status !== 200, '下载接口拒绝路径穿越 (status=' + resp.status + ')');
// ---- 4. 终止机制 ----
console.log('\n[4] 终止');
s = await api('POST', '/api/sessions', { title: '冒烟-终止' });
await waitSession(s.id, x => x.session.status === 'held' && !!x.session.model_id, 5000, '绑定(held)');
await api('POST', '/api/sessions/' + s.id + '/messages', { content: '慢一点说' });
await sleep(600);
await api('POST', '/api/sessions/' + s.id + '/stop');
d = await waitSession(s.id, x => x.session.status === 'cancelled', 6000, 'cancelled');
ok(d.session.status === 'cancelled', '终止后状态为 cancelled');
ok(d.session.model_id != null, '终止不算断开:绑定保持,再发言沿用(engine.stop 不清 model_id)');
// ---- 5. 排队调度(ds1/ds2 都占用 → 第三个排队 → 释放后 FIFO 绑定)----
console.log('\n[5] 排队调度');
// 先等模型池全空闲:前节的 held 租约最长还需 idle_release_ms 才释放,
// 否则本节会话会绑到不同模型,下面「分到不同模型」的断言时机依赖运气
for (let i = 0; i < 30; i++) {
const pool0 = await api('GET', '/api/models');
if (pool0.every(m => !m.is_busy)) break;
await sleep(200);
}
const a = await api('POST', '/api/sessions', { title: 'A' });
const b = await api('POST', '/api/sessions', { title: 'B' });
const c = await api('POST', '/api/sessions', { title: 'C' });
const da = await waitSession(a.id, x => x.session.status === 'held' && !!x.session.model_id, 5000, 'A 绑定(held)');
const db = await waitSession(b.id, x => x.session.status === 'held' && !!x.session.model_id, 5000, 'B 绑定(held)');
const dc = await api('GET', '/api/sessions/' + c.id);
ok(da.session.model_id && db.session.model_id && da.session.model_id !== db.session.model_id,
'两个会话分到不同模型', da.session.model_id + ' vs ' + db.session.model_id);
ok(dc.session.status === 'queued' && dc.queue_pos === 1, '第三个会话排队 position 1');
await api('POST', '/api/sessions/' + a.id + '/stop');
// C 从未发言 → 顶替后同样绑成 held 预留(非 active)
await waitSession(c.id, x => x.session.status === 'held' && !!x.session.model_id, 6000, 'C 顶替');
const dc2 = await api('GET', '/api/sessions/' + c.id);
ok(dc2.session.model_id != null, '释放后队列会话自动绑定', String(dc2.session.model_id));
// ---- 6. 会话删除 ----
console.log('\n[6] 删除');
await api('DELETE', '/api/sessions/' + b.id + '?delete_dir=true');
let gone = false;
try { await api('GET', '/api/sessions/' + b.id); } catch (e) { gone = /404/.test(e.message); }
ok(gone, '删除后会话 404');
ok(!fs.existsSync(path.join(ROOT, 'test/tmp/tasks', b.id)), '任务目录被删除');
// ---- 7. 模型池 API ----
const pool = await api('GET', '/api/models');
ok(pool.length === 2, '模型池数量', JSON.stringify(pool));
// ---- 8. 工具单元:terminal 超时 ----
console.log('\n[7] terminal 超时');
const eng = require(path.join(ROOT, 'server/engine.js'));
// engine 未在本进程初始化(服务在子进程),此处直接单测 executor
const { executeTool } = require(path.join(ROOT, 'server/tools/executor.js'));
const ctx = {
sessionId: 'unit', taskDir: path.join(ROOT, 'test/tmp/unit'),
run: { cancelled: false, procs: new Set() },
cfg: { terminal: { default_timeout_ms: 800, max_output_chars: 5000 }, web_search: { provider: 'none' } },
db: { prepare: () => ({ run: () => {} }) },
};
fs.mkdirSync(ctx.taskDir, { recursive: true });
const t0 = Date.now();
const tout = await executeTool(ctx, 'terminal', { command: 'sleep 5' });
ok(Date.now() - t0 < 4000 && tout.includes('超时'), 'terminal 超时终止', tout.slice(0, 100));
const toc = await executeTool(ctx, 'terminal', { command: 'echo hello-unit && pwd' });
ok(toc.includes('hello-unit') && toc.includes('exit code: '), 'terminal 正常执行', toc.slice(0, 120));
await executeTool(ctx, 'write_file', { path: 'g.txt', content: 'alpha\nbeta\n' });
const esc = await executeTool(ctx, 'read_file', { path: '../outside.txt' }).catch(e => 'ERR:' + e.message);
ok(String(esc).includes('越界'), 'read_file 拒绝越界', String(esc));
// read_file 读图:非 vision → 文本提示;vision → {text, image_rel}(依赖 sharp;小图压缩无收益时 image_rel 直指原文件,不落 .imgcache)
const unitPng = await require('sharp')({ create: { width: 4, height: 4, channels: 3, background: { r: 10, g: 120, b: 200 } } }).png().toBuffer();
fs.writeFileSync(path.join(ctx.taskDir, 'pic.png'), unitPng);
const imgNoVision = await executeTool(ctx, 'read_file', { path: 'pic.png' });
ok(typeof imgNoVision === 'string' && imgNoVision.includes('不支持视觉识别'), 'read_file 非 vision 图片返回文本提示', String(imgNoVision).slice(0, 80));
const ctxVision = Object.assign({}, ctx, { vision: true });
const imgVision = await executeTool(ctxVision, 'read_file', { path: 'pic.png' });
ok(imgVision && typeof imgVision === 'object' && String(imgVision.image_rel).length > 0,
'read_file vision 图片返回 image_rel(压缩产物或无收益原图)', imgVision && imgVision.text ? String(imgVision.text).slice(0, 90) : String(imgVision).slice(0, 90));
ok(fs.existsSync(path.join(ctx.taskDir, imgVision.image_rel)), 'image_rel 指向的文件存在');
// ---- 8. 配置读写 API(阶段 2)----
console.log('\n[8] 配置读写');
const cfgPath = path.join(ROOT, 'test/config.test.yml');
const origText = fs.readFileSync(cfgPath, 'utf8');
const got = await api('GET', '/api/config');
ok(got.exists && got.text.includes('models:'), 'GET /api/config 返回原文');
ok(got.effective && got.effective.agent && got.effective.agent.max_retries === 1 && got.effective.models.length === 2, 'GET 返回生效配置(effective)');
const patched = await api('PATCH', '/api/config', { path: 'agent.temperature', value: 0.5 });
ok(patched.ok && patched.changed.includes('agent'), 'PATCH 单项修改');
const afterPatch = await api('GET', '/api/config');
ok(/temperature:\s*0\.5/.test(afterPatch.text), 'PATCH 写盘生效');
ok(afterPatch.text.includes('冒烟测试用短租约'), 'PATCH 保留文件注释');
let bad400 = false;
const rawBeforeBadPut = fs.readFileSync(cfgPath, 'utf8');
try { await api('PUT', '/api/config', { text: 'models: [unclosed' }); } catch (e) { bad400 = /400/.test(e.message); }
ok(bad400, 'PUT 非法配置被 400 拒绝');
ok(fs.readFileSync(cfgPath, 'utf8') === rawBeforeBadPut, '非法写入未动文件');
const mpatch = await api('PATCH', '/api/config', { path: 'platforms.0.models.0.display_name', value: '改名模型' });
const mtext = (await api('GET', '/api/config')).text;
ok(mpatch.ok && mtext.includes('改名模型'), 'PATCH 支持 platforms 嵌套数组下标');
const restored = await api('PUT', '/api/config', { text: origText });
ok(restored.ok && fs.readFileSync(cfgPath, 'utf8') === origText, 'PUT 整文件恢复原配置');
// ---- 9. 会话列表过滤/游标分页/搜索(2.0)----
console.log('\n[9] 会话列表过滤与搜索');
const uniqTitle = '冒烟-搜索专用-' + Date.now();
const fs9 = await api('POST', '/api/sessions', { title: uniqTitle });
ok(fs9 && fs9.id, '创建搜索专用会话');
await api('POST', '/api/sessions/' + fs9.id + '/messages', { content: 'zzq-unique 检索内容 12345' });
// 等到终态(completed 归档分组断言用):租约到期结版已移除,改手动 release 收口;token 用量回合内已落库
await waitSession(fs9.id, x => x.session.status === 'held' && x.messages.some(m => m.role === 'assistant'), 8000, 'AI 回复完成(held)');
await api('POST', '/api/sessions/' + fs9.id + '/release');
await waitSession(fs9.id, x => x.session.status === 'completed', 3000, '手动断开后结版');
const st9 = (await api('GET', '/api/sessions/' + fs9.id)).session.status;
const actSet = await api('GET', '/api/sessions?status=active&limit=200');
const doneSet = await api('GET', '/api/sessions?status=done&limit=200');
ok(((st9 === 'completed' || st9 === 'cancelled') ? doneSet : actSet).some(x => x.id === fs9.id), '新会话按状态归入对应过滤', st9);
ok(!actSet.some(x => x.status === 'completed' || x.status === 'cancelled'), 'active 过滤不含归档会话');
const withTot = await api('GET', '/api/sessions?status=done&limit=1&with_total=1');
ok(Array.isArray(withTot.rows) && typeof withTot.total === 'number' && withTot.total >= withTot.rows.length, 'with_total 返回 {rows,total}');
const pg1 = await api('GET', '/api/sessions?limit=1');
ok(Array.isArray(pg1) && pg1.length === 1, '默认数组响应兼容旧格式(limit=1)');
const pg2 = await api('GET', '/api/sessions?limit=1&before=' + encodeURIComponent(pg1[0].updated_at) + '&before_id=' + pg1[0].id);
ok(Array.isArray(pg2) && pg2.length === 1 && pg2[0].id !== pg1[0].id, '游标翻页取到不同的下一页');
const qt = await api('GET', '/api/sessions?q=' + encodeURIComponent(uniqTitle));
ok(qt.some(x => x.id === fs9.id), 'q= 按标题命中');
const qc = await api('GET', '/api/sessions?q=zzq-unique');
ok(qc.some(x => x.id === fs9.id), 'q= 按消息内容命中');
const qnone = await api('GET', '/api/sessions?q=绝无此内容xyzzy-9x7');
ok(Array.isArray(qnone) && qnone.length === 0, 'q= 无命中返回空');
// 附件消息:服务端在正文前拼【系统通知】行,与消息一并落库
await api('POST', '/api/sessions/' + fs9.id + '/messages', { content: '', attachments: [{ name: 'a.png', size: 1536 }, { name: 'b.txt', size: 20 }] });
const noticePrefix = '【系统通知】用户上传了文件:a.png(大小 1.5 KB)、b.txt(大小 20 B)';
let attOk = false;
try {
await waitSession(fs9.id, x => x.messages.some(m => m.role === 'user' && m.content.indexOf(noticePrefix) === 0), 6000, '附件通知落库');
attOk = true;
} catch (_) {}
ok(attOk, '附件提示词按格式拼接(文件名+大小)');
// token 用量:model_usage 由 mock 上游的 usage 帧驱动,输入/输出分开统计
const usagePool = await api('GET', '/api/models');
const sumP = usagePool.reduce(function (n, m) { return n + (m.today_prompt || 0); }, 0);
const sumC = usagePool.reduce(function (n, m) { return n + (m.today_completion || 0); }, 0);
const sumTP = usagePool.reduce(function (n, m) { return n + (m.total_prompt || 0); }, 0);
ok(sumP > 0 && sumC > 0 && sumTP >= sumP,
'/api/models 携带今日/累计输入输出 token 用量', '今日输入=' + sumP + ' 今日输出=' + sumC);
// ---- 10. 技能管理(阶段 3)----
console.log('\n[10] 技能管理');
ok((await api('POST', '/api/skills', { name: 'demo-skill', description: '演示技能' })).ok, '创建技能');
let slist = await api('GET', '/api/skills');
const demo = slist.find(x => x.name === 'demo-skill');
ok(demo && demo.has_md && String(demo.description).includes('演示技能'), '列表含新技能与描述');
let sdet = await api('GET', '/api/skills/demo-skill');
ok(sdet.skill_md && sdet.skill_md.includes('demo-skill') && sdet.files.some(f => f.filename === 'SKILL.md'), '详情含 SKILL.md');
await api('PUT', '/api/skills/demo-skill/file', { path: 'sub/run.sh', content: '#!/bin/sh\necho hi\n' });
const sfr = await api('GET', '/api/skills/demo-skill/file?path=sub%2Frun.sh');
ok(sfr.content.includes('echo hi'), '文件写入+读取(含子目录)');
let trav = false;
try { await api('GET', '/api/skills/demo-skill/file?path=..%2F..%2Fetc%2Fpasswd'); } catch (e) { trav = /400/.test(e.message); }
ok(trav, '路径穿越被拒 400');
const mkFd = txt => { const fd = new FormData(); fd.append('file', new Blob([txt]), 'note.txt'); return fd; };
const up1 = await fetch(BASE + '/api/skills/demo-skill/upload', { method: 'POST', body: mkFd('up\n') });
const up1j = await up1.json();
ok(up1.ok && up1j.path === 'note.txt', '上传新文件');
const up2 = await fetch(BASE + '/api/skills/demo-skill/upload', { method: 'POST', body: mkFd('dup\n') });
ok(up2.status === 409, '重名上传默认 409');
const up3 = await fetch(BASE + '/api/skills/demo-skill/upload?overwrite=true', { method: 'POST', body: mkFd('ovr\n') });
ok(up3.ok, 'overwrite=true 覆盖上传');
ok((await api('POST', '/api/skills/demo-skill/rename', { newName: 'demo-2' })).ok, '重命名技能');
await api('DELETE', '/api/skills/demo-2/file?path=sub%2Frun.sh');
sdet = await api('GET', '/api/skills/demo-2');
ok(!sdet.files.some(f => f.filename === 'sub/run.sh') && sdet.files.some(f => f.filename === 'note.txt'), '删文件生效');
ok((await api('DELETE', '/api/skills/demo-2')).ok, '删除整个技能');
slist = await api('GET', '/api/skills');
ok(!slist.some(x => x.name.indexOf('demo') === 0), '删除后列表干净');
// ---- 11. 系统状态与优雅重启(阶段 2;放在最后,服务进程将退出收尾)----
console.log('\n[11] 优雅重启');
const st = await api('GET', '/api/system/status');
ok(st.ok && st.started_at && st.port === 8099, 'GET /api/system/status');
s = await api('POST', '/api/sessions', { title: '冒烟-重启保护' });
await waitSession(s.id, x => x.session.status === 'held' && !!x.session.model_id, 5000, '绑定(held)');
await api('POST', '/api/sessions/' + s.id + '/messages', { content: '慢一点说' });
await sleep(400); // 进入慢速流式输出,looping=true
let guarded = false;
try { await api('POST', '/api/system/restart'); } catch (e) { guarded = /409/.test(e.message); }
ok(guarded, '回合执行中 restart 被 409 拦截');
const rj = await api('POST', '/api/system/restart?force=true');
ok(rj && rj.restarting, 'force 重启被接受');
await sleep(800); // 服务在响应后 300ms 退出
ok(server.exitCode === 0, '服务以退出码 0 结束(交由 Docker 拉起)', 'exitCode=' + server.exitCode);
console.log('\n========================');
console.log('通过 ' + pass + ' / 失败 ' + fail);
// 不用 process.exit():会跳过 finally 的子进程清理,残留 mock/server 占住 9999/8099 干扰下次运行。
process.exitCode = fail === 0 ? 0 : 2;
} catch (e) {
console.log('\n测试异常: ' + (e && e.stack || e));
console.log('server 日志尾部:\n' + serverLog.slice(-2000));
process.exitCode = 2;
} finally {
server.kill('SIGKILL');
mock.kill('SIGKILL');
}
}
main();
-67
View File
@@ -1,67 +0,0 @@
// 临时冒烟:重负载占位裁剪(跑完即删)。
const assert = require('assert');
const llm = require('../server/llm');
const big = n => 'x'.repeat(n);
const mk = (id, role, extra) => Object.assign({ id, role, type: null, content: '' }, extra);
const call = (id, name, args) => ({ id, type: 'function', function: { name, arguments: JSON.stringify(args) } });
const rows = [
mk(1, 'user', { content: '抓X存notes再写summary' }),
mk(2, 'assistant', { tool_calls: JSON.stringify([call('c1', 'fetch', { url: 'https://e.com/x' })]) }),
mk(3, 'tool', { tool_call_id: 'c1', name: 'fetch', content: 'HTTP 200\n' + big(8000) }),
mk(4, 'assistant', { tool_calls: JSON.stringify([call('c2', 'write_file', { path: 'notes.md', content: big(12000) })]) }),
mk(5, 'tool', { tool_call_id: 'c2', name: 'write_file', content: '已创建文件 notes.md(12003 字节)' }),
mk(6, 'assistant', { tool_calls: JSON.stringify([call('c3', 'write_file', { path: 'summary.md', content: '小内容' })]) }),
mk(7, 'tool', { tool_call_id: 'c3', name: 'write_file', content: '已创建文件 summary.md(9 字节)' }),
mk(8, 'assistant', { content: '两篇已写好' }),
];
const session = () => ({ history: rows.slice(), profile_snapshot: '', blocksCache: new Map() });
// A) 全历史:距尾够远 → fetch 回执与 write_file(大) 参数被占位;write_file(小)/回执/收尾不动
let msgs = llm.buildMessages(session(), 'Simplified Chinese', null, null);
const a = msgs.filter(m => m.role === 'assistant' && m.tool_calls);
const argsNotes = JSON.parse(a.find(m => m.tool_calls[0].id === 'c2').tool_calls[0].function.arguments);
assert(argsNotes.content === '[OMITTED, size=12000]', 'write_file 大参数应占位: ' + argsNotes.content);
const argsSum = JSON.parse(a.find(m => m.tool_calls[0].id === 'c3').tool_calls[0].function.arguments);
assert.strictEqual(argsSum.content, '小内容', '低于 TRIM_MIN 不裁');
const t = msgs.find(m => m.role === 'tool' && m.tool_call_id === 'c1');
assert(t.content === '[OMITTED, http_status=200, size=8009]', 'fetch 回执应占位: ' + t.content);
assert(msgs.find(m => m.role === 'tool' && m.tool_call_id === 'c2').content.includes('已创建文件'), 'write 回执不动');
// B) 截到第 5 行(write 刚落盘的当次调用):都太新鲜,不裁
msgs = llm.buildMessages({ history: rows.slice(0, 5), profile_snapshot: '', blocksCache: new Map() }, 'Simplified Chinese', null, null);
assert(msgs.find(m => m.role === 'tool' && m.tool_call_id === 'c1').content.length > 7000, 'fetch 距尾 1 轮应保留');
assert.strictEqual(JSON.parse(msgs.filter(m => m.tool_calls).pop().tool_calls[0].function.arguments).content.length, 12000, 'write 参数距尾 0 轮应保留');
// C) 压缩回合与常规拼装字节同构,仅尾部多一条指令(前缀缓存铁律)
const normal = llm.buildMessages(session(), 'Simplified Chinese', null, null);
const cm = llm.compressMessages(session(), 'Simplified Chinese', null, null);
assert(cm.length === normal.length + 1, '压缩=常规+尾指令');
assert(JSON.stringify(cm.slice(0, -1)) === JSON.stringify(normal), '前缀字节同构');
assert(/compact|concise/.test(cm.at(-1).content), '尾指令在位');
// D) read_file 回执同款
const r3orig = rows[2];
rows[2] = mk(3, 'tool', { tool_call_id: 'c1', name: 'read_file', content: 'HTTP 200\n' + big(8000) });
rows[1] = mk(2, 'assistant', { tool_calls: JSON.stringify([call('c1', 'read_file', { path: 'a.md' })]) });
msgs = llm.buildMessages(session(), 'Simplified Chinese', null, null);
assert(msgs.find(m => m.tool_call_id === 'c1' && m.role === 'tool').content === '[OMITTED, size=8009]', 'read_file 应占位');
rows[2] = r3orig;
rows[1] = mk(2, 'assistant', { tool_calls: JSON.stringify([call('c1', 'fetch', { url: 'https://e.com/x' })]) });
// E) 开关:0=关
llm.setPayloadTrim({ trim_write_rounds: 0, trim_result_rounds: 0 });
msgs = llm.buildMessages(session(), 'Simplified Chinese', null, null);
assert(msgs.find(m => m.role === 'tool' && m.tool_call_id === 'c1').content.length > 7000, '0=关');
llm.setPayloadTrim({}); // 回落默认 1/2
// F) 非法/缺失参数不炸(arguments 非 JSON、无 url 的 fetch;需距尾够远)
rows.push(mk(9, 'assistant', { tool_calls: JSON.stringify([call('c9', 'fetch', {})]) }));
rows.push(mk(10, 'tool', { tool_call_id: 'c9', name: 'fetch', content: 'HTTP 404\n' + big(700) }));
rows.push(mk(11, 'assistant', { content: '页面不存在,换个 url?' }));
rows.push(mk(12, 'assistant', { tool_calls: JSON.stringify([call('c12', 'read_file', { path: 'notes.md' })]) }));
msgs = llm.buildMessages(session(), 'Simplified Chinese', null, null);
assert(msgs.find(m => m.tool_call_id === 'c9').content === '[OMITTED, http_status=404, size=709]', '缺 url 仍占位: ' + msgs.find(m => m.tool_call_id === 'c9').content);
console.log('TRIM-SMOKE-OK');