refactor(agent): 抽出 guard/history/reference 共享模块并补测试
- guard.js:流式输出护栏,跨 chunk 禁用词拦截并在句末截断超长回复 - history.js:tool 结果入历史前截断、历史按完整轮次裁剪,避免断链与上下文挤占 - reference.js:服务项目/协议改为可读文本渲染,替代裸 JSON 误导模型 - 临时脚本 test_restricted_backend.mjs 转为 test/restricted_fs_backend.test.js
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { OutputGuard, OUTPUT_MAX_CHARS } from "../agent/infra/guard.js";
|
||||
|
||||
// 按服务端聚合方式跑完一整条流,返回最终下发给客户端的文本
|
||||
function runStream(chunks, options) {
|
||||
const guard = new OutputGuard(options);
|
||||
const parts = [];
|
||||
for (const chunk of chunks) {
|
||||
const text = guard.feed(chunk);
|
||||
if (text) parts.push(text);
|
||||
}
|
||||
const tail = guard.finish();
|
||||
if (tail) parts.push(tail);
|
||||
return { text: parts.join(""), guard };
|
||||
}
|
||||
|
||||
test("跨 chunk 的禁用词不会漏过,也不留下孤立标点", () => {
|
||||
const { text, guard } = runStream(["作为", "AI", ",我不能给出诊断。"]);
|
||||
assert.equal(text, "我不能给出诊断。");
|
||||
assert.deepEqual(guard.hits, ["作为AI"]);
|
||||
});
|
||||
|
||||
test("禁用词在句中时修补重复标点", () => {
|
||||
const { text } = runStream(["嗯,作为AI。我认为你说得对。"]);
|
||||
assert.equal(text, "嗯。我认为你说得对。");
|
||||
});
|
||||
|
||||
test("整条回复只有禁用词时输出为空", () => {
|
||||
const { text } = runStream(["作为", "AI", "助手"]);
|
||||
assert.equal(text, "");
|
||||
});
|
||||
|
||||
test("禁用词落在流末尾时在 finish 阶段拦截", () => {
|
||||
const { text } = runStream(["回答仅供参考,", "希望对您有帮助"]);
|
||||
assert.equal(text, "回答仅供参考,");
|
||||
});
|
||||
|
||||
test("普通文本不吞字,尾部 holdback 在 finish 阶段补发", () => {
|
||||
const { text } = runStream(["您好", ",陪诊流程是:先预约,再确认。"]);
|
||||
assert.equal(text, "您好,陪诊流程是:先预约,再确认。");
|
||||
});
|
||||
|
||||
test("超长回复在句末截断并补省略号,之后不再输出", () => {
|
||||
const sentence = "陪诊服务分为预约、确认、陪同就诊三步。";
|
||||
const { text, guard } = runStream([sentence.repeat(10), "后面还有很长的内容。"], { maxChars: 120 });
|
||||
|
||||
assert.ok(text.length <= 120);
|
||||
assert.ok(text.endsWith("。…"));
|
||||
assert.equal(guard.done, true);
|
||||
});
|
||||
|
||||
test("没有句末可切时按上限硬切", () => {
|
||||
const { text } = runStream(["这是一段没有句号的很长文本".repeat(20)], { maxChars: 50 });
|
||||
assert.ok(text.length <= 50);
|
||||
assert.ok(text.endsWith("…"));
|
||||
});
|
||||
|
||||
test("两类 agent 的默认上限符合预期", () => {
|
||||
assert.equal(OUTPUT_MAX_CHARS.escort, 400);
|
||||
assert.equal(OUTPUT_MAX_CHARS.admin, 600);
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { CompositeBackend, FilesystemBackend } from "deepagents";
|
||||
|
||||
import { createRestrictedBackend } from "../agent/infra/restricted_fs_backend.js";
|
||||
|
||||
// 以 api/health 为沙箱根,避免写死本机绝对路径
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const DATA_DIR = path.join(ROOT, "data");
|
||||
const backend = createRestrictedBackend({ rootDir: ROOT, dataDir: DATA_DIR });
|
||||
|
||||
const isDenied = result => typeof result.error === "string" && result.error.includes("denied");
|
||||
|
||||
test("敏感文件读取被拒绝", async () => {
|
||||
assert.ok(isDenied(await backend.read("conf.json")), "相对路径 conf.json 应被拒绝");
|
||||
assert.ok(isDenied(await backend.read(path.join(ROOT, "conf.json"))), "沙箱内绝对路径 conf.json 应被拒绝");
|
||||
assert.ok((await backend.read("/conf.json")).error, "根绝对路径 /conf.json 应被拒绝");
|
||||
assert.ok(isDenied(await backend.read(".env")), ".env 应被拒绝");
|
||||
assert.ok(isDenied(await backend.read(".env.local")), ".env.* 应被拒绝");
|
||||
assert.ok(isDenied(await backend.read("data/users/u123/memory.txt")), "用户数据目录应被拒绝");
|
||||
assert.ok(isDenied(await backend.read("logs/x.log")), "logs 目录应被拒绝");
|
||||
});
|
||||
|
||||
test("路径穿越与沙箱外路径被拒绝", async () => {
|
||||
assert.ok((await backend.read("../conf.json")).error, ".. 穿越应报错");
|
||||
assert.ok((await backend.read(path.join(os.tmpdir(), "outside-sandbox.txt"))).error, "沙箱外绝对路径应报错");
|
||||
});
|
||||
|
||||
test("正常资源仍可访问", async () => {
|
||||
const agents = await backend.read("agent/bots/bot-escort/AGENTS.md");
|
||||
assert.equal(agents.error, undefined, `AGENTS.md 应可读:${agents.error}`);
|
||||
assert.match(agents.content, /用户记忆/);
|
||||
|
||||
const skill = await backend.read("agent/infra/skills/baidu-ai-map/SKILL.md");
|
||||
assert.equal(skill.error, undefined, `SKILL.md 应可读:${skill.error}`);
|
||||
assert.match(skill.content, /百度地图|Baidu|baidu/i);
|
||||
});
|
||||
|
||||
test("ls / glob / grep 不泄露敏感文件", async () => {
|
||||
const isConf = file => path.basename(file.replace(/[\\/]+$/, "")).toLowerCase() === "conf.json";
|
||||
|
||||
const ls = await backend.ls("/");
|
||||
assert.ok(!ls.files.some(f => isConf(f.path)), "ls 不应列出 conf.json");
|
||||
|
||||
const glob = await backend.glob("**/conf*.json");
|
||||
assert.ok(!glob.files.some(f => isConf(f.path)), "glob 不应返回 conf.json");
|
||||
|
||||
// conf.json 内存在 apiKey,若过滤失效此处会命中
|
||||
const grep = await backend.grep("apiKey", "/", "conf.json");
|
||||
assert.equal(grep.matches.filter(m => isConf(m.path)).length, 0, "grep 不应返回 conf.json 内容");
|
||||
|
||||
const normal = await backend.grep("escort", "agent/bots/bot-escort");
|
||||
assert.ok(normal.matches.length > 0, "普通目录 grep 应正常工作");
|
||||
});
|
||||
|
||||
test("拒绝写敏感文件,允许写普通文件", async () => {
|
||||
assert.ok(isDenied(await backend.write("conf.json", "{}")), "写 conf.json 应被拒绝");
|
||||
assert.ok(isDenied(await backend.write("data/users/u123/memory.txt", "x")), "写用户记忆应被拒绝");
|
||||
assert.ok((await backend.write("../escape.txt", "x")).error, "写沙箱外路径应报错");
|
||||
|
||||
const name = `.restricted-backend-${process.pid}.txt`;
|
||||
try {
|
||||
const written = await backend.write(name, "hello");
|
||||
assert.equal(written.error, undefined, `普通文件应可写:${written.error}`);
|
||||
const read = await backend.read(name);
|
||||
assert.equal(read.error, undefined, `普通文件应可读:${read.error}`);
|
||||
assert.match(read.content, /hello/);
|
||||
} finally {
|
||||
await backend.delete(name);
|
||||
}
|
||||
});
|
||||
|
||||
test("CompositeBackend 的 /memories/ 挂载仍可用,默认路径仍受限", async () => {
|
||||
const memoryRoot = fs.mkdtempSync(path.join(os.tmpdir(), "restricted-backend-memories-"));
|
||||
const composite = new CompositeBackend(backend, {
|
||||
"/memories/": new FilesystemBackend({ rootDir: memoryRoot, virtualMode: true }),
|
||||
});
|
||||
|
||||
try {
|
||||
const written = await composite.write("/memories/memory.txt", "测试记忆");
|
||||
assert.equal(written.error, undefined, `/memories 应可写:${written.error}`);
|
||||
const read = await composite.read("/memories/memory.txt");
|
||||
assert.equal(read.error, undefined, `/memories 应可读:${read.error}`);
|
||||
assert.equal(read.content, "测试记忆");
|
||||
|
||||
assert.ok((await composite.read("/conf.json")).error, "composite 默认路径仍应受限");
|
||||
} finally {
|
||||
fs.rmSync(memoryRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user