diff --git a/agent/infra/guard.js b/agent/infra/guard.js new file mode 100644 index 0000000..5552db3 --- /dev/null +++ b/agent/infra/guard.js @@ -0,0 +1,194 @@ +import logger from "../../utils/logger.js"; + +/** + * 输出护栏(主 agent 与管理 agent 共用) + * + * 流式输出无法回撤:字符一旦发给客户端,就会被追加进气泡。 + * 因此这里只做两件在流式下可做对的兜底: + * 1. 禁用词拦截:命中即整段剔除;尾部若可能是禁用词的前缀就先不发送, + * 避免「作为A」+「I」这种跨 chunk 的命中被漏过; + * 2. 超长截断:总输出超过上限时在最近句末/换行处截断并补省略号,之后不再输出。 + * 篇幅与文风仍由提示词负责,这里不放宽口径。 + */ + +// 单条回复的字符上限:用户侧咨询应为 1-3 句,管理侧要列记录,留更大余量 +export const OUTPUT_MAX_CHARS = { escort: 400, admin: 600 }; + +// 身份泄露与空泛客套:两个 agent 都不该出现 +const IDENTITY = [ + "作为AI", + "作为一个AI", + "作为人工智能", + "作为一个人工智能", + "作为语言模型", + "作为大模型", + "我是一个AI", + "我是AI", + "AI助手", + // 与上面重叠的完整自我描述:按长度优先匹配,避免只删掉前半截留下「助手」 + "作为AI助手", + "作为一个AI助手", + "作为一个人工智能助手", + "我是一个AI助手", + "我是AI助手", + "我是您的AI助手", +]; + +const COURTESY = [ + "很高兴为您服务", + "很高兴为您解答", + "希望对您有帮助", + "希望这对您有帮助", + "您还有什么问题吗", + "还有其他问题吗", + "祝您早日康复", +]; + +// 越界承诺:医疗结果与服务可得性都不能打包票 +const OVERPROMISE = [ + "一定能治好", + "一定可以治好", + "保证治好", + "保证治愈", + "包治百病", + "百分之百安全", + "绝对安全", +]; + +export const OUTPUT_FORBIDDEN = [...IDENTITY, ...COURTESY, ...OVERPROMISE]; + +// 句末候选:中英文标点 + 换行,列表项按换行断开更自然 +const SENTENCE_ENDS = ["。", "!", "?", ";", "\n", "!", "?", ";"]; + +// 在限额内尽量切在句末;找不到时硬切,并去掉尾部悬挂的标点/空白 +function pickCut(text, room) { + // 留一个字符给省略号 + const window = text.slice(0, Math.max(room - 1, 1)); + const minIndex = Math.floor(window.length * 0.4); + let cutAt = -1; + for (const ch of SENTENCE_ENDS) { + const index = window.lastIndexOf(ch); + if (index >= minIndex && index > cutAt) { + cutAt = index; + } + } + const cut = cutAt >= 0 ? window.slice(0, cutAt + 1) : window; + return cut.replace(/[\s,、,]+$/u, ""); +} + +export class OutputGuard { + constructor({ label = "agent", maxChars = 400, forbidden = OUTPUT_FORBIDDEN } = {}) { + this.label = label; + this.maxChars = maxChars; + // 长的先匹配:避免「作为AI助手」被「作为AI」先删成半截 + this.forbidden = forbidden.filter(Boolean).sort((a, b) => b.length - a.length); + this.buffer = ""; + this.emitted = 0; + this.done = false; + this.hits = []; + // 禁用词被整段剔除后,下一段开头可能残留逗号/句号,需要一并吞掉 + this._stripLeading = false; + } + + /** 输入一段模型输出,返回可以发送给客户端的文本(可能为空串) */ + feed(chunk) { + if (this.done || !chunk) return ""; + if (this.emitted >= this.maxChars) { + this.done = true; + logger.warn(`[OutputGuard:${this.label}] 输出超过上限 ${this.maxChars} 字,后续内容已丢弃`); + return ""; + } + + const text = this.buffer + chunk; + this.buffer = ""; + + if (this.emitted + text.length > this.maxChars) { + const cut = pickCut(text, this.maxChars - this.emitted); + // 截断点若落在禁用词中间,退到词首,避免把半截词发出去 + const hold = this._holdback(cut); + const kept = hold > 0 ? cut.slice(0, cut.length - hold) : cut; + + // 已经输出过内容时,若剩余额度放不下一句完整的话,直接以省略号收尾, + // 避免把下一段的前几个字拼成半句(如「。后面还有…」) + const endsAtSentence = SENTENCE_ENDS.includes(kept.slice(-1)); + const fragment = this.emitted > 0 && kept && !endsAtSentence ? "" : kept; + + this.done = true; + const out = `${this._sanitize(fragment)}…`; + this.emitted += out.length; + logger.warn(`[OutputGuard:${this.label}] 输出超过上限 ${this.maxChars} 字,已在句末截断`, { + emitted: this.emitted, + dropped: text.length - fragment.length, + }); + return out; + } + + const hold = this._holdback(text); + const ready = hold > 0 ? text.slice(0, text.length - hold) : text; + if (hold > 0) { + this.buffer = text.slice(text.length - hold); + } + const out = this._sanitize(ready); + this.emitted += out.length; + return out; + } + + /** 流结束时补发 holdback 里的残余文本 */ + finish() { + if (this.done) return ""; + this.done = true; + const out = this._sanitize(this.buffer); + this.buffer = ""; + this.emitted += out.length; + return out; + } + + // 尾部若可能是某个禁用词的前缀,先留在 buffer 等下一段拼起来再判断; + // 完整命中也要留(作为它自身的前缀),避免「作为」刚发出就在下一段补上「AI」 + _holdback(text) { + let hold = 0; + for (const word of this.forbidden) { + const max = Math.min(word.length, text.length); + for (let len = max; len > hold; len--) { + if (word.startsWith(text.slice(text.length - len))) { + hold = len; + break; + } + } + } + return hold; + } + + _sanitize(text) { + if (!text) return ""; + let out = text; + if (this._stripLeading) { + out = out.replace(/^[,、,;;::。.!!??\s]+/u, ""); + // 整段都是标点时继续保持标记,等下一段真正有正文再清除 + this._stripLeading = out === ""; + } + if (!this.forbidden.length) return out; + + let hit = false; + for (const word of this.forbidden) { + if (!out.includes(word)) continue; + const removed = out.split(word).length - 1; + out = out.split(word).join(""); + if (!this.hits.includes(word)) this.hits.push(word); + hit = true; + logger.warn(`[OutputGuard:${this.label}] 拦截禁用词「${word}」`, { removed }); + } + if (!hit) return out; + + // 剔除后留下的重复标点做最小修补;整段被剔除时空结果不宜直接发送 + out = out + .replace(/([,、,])[,、,]+/gu, "$1") + .replace(/([。!?!?])[。!?!?]+/gu, "$1") + .replace(/[,、,]\s*([。!?!?])/gu, "$1") + .replace(/^[,、,;;::。.!!??\s]+/u, ""); + this._stripLeading = out === ""; + return out; + } +} + +export default OutputGuard; diff --git a/agent/infra/history.js b/agent/infra/history.js new file mode 100644 index 0000000..f026458 --- /dev/null +++ b/agent/infra/history.js @@ -0,0 +1,61 @@ +import { HumanMessage } from "@langchain/core/messages"; +import logger from "../../utils/logger.js"; + +/** + * 对话历史管理(主 agent 与管理 agent 共用) + * + * 两个约束同时存在: + * 1. tool 结果必须并入历史,否则下一轮会出现 tool_calls 缺少 tool 结果的断链; + * 2. tool 结果往往是网页正文/数据库全量字段,原样保留会挤掉真正的人机对话, + * 导致 agent 忘记用户说过的医院、日期,表现为重复提问。 + * 因此 tool 结果入历史前统一截断,只保留开头关键信息。 + */ + +// tool 结果保留的字符数,超出部分以标记代替 +export const TOOL_RESULT_MAX_CHARS = 300; + +export function truncateToolResult(content, max = TOOL_RESULT_MAX_CHARS) { + if (typeof content !== "string") return content; + if (content.length <= max) return content; + return `${content.slice(0, max)}…(原结果 ${content.length} 字,已截断)`; +} + +// 截断后并入历史,返回实际写入的消息 +export function appendToolMessage(messages, msg, max = TOOL_RESULT_MAX_CHARS) { + if (msg && typeof msg.content === "string") { + msg.content = truncateToolResult(msg.content, max); + } + messages.push(msg); + return msg; +} + +/** + * 按字符数裁剪历史:只以 HumanMessage 为界从头部删除完整轮次, + * 避免切断 AI(tool_calls) -> Tool 的链式结构;永远保留最新一轮。 + * 返回裁剪后的新数组,由调用方赋值。 + */ +export function trimHistory(messages, maxChars) { + const size = (msgs) => msgs.reduce((sum, m) => sum + (m.text?.length ?? 0), 0); + if (size(messages) <= maxChars) { + return messages; + } + + const starts = []; + messages.forEach((m, i) => { + if (HumanMessage.isInstance(m)) starts.push(i); + }); + if (starts.length < 2) { + return messages; + } + + let cut = 0; + for (let i = 0; i < starts.length - 1; i++) { + cut = starts[i + 1]; + if (size(messages.slice(cut)) <= maxChars) { + break; + } + } + const trimmed = messages.slice(cut); + logger.info(`History trimmed to ${trimmed.length} messages, ${size(trimmed)} chars`); + return trimmed; +} diff --git a/agent/infra/reference.js b/agent/infra/reference.js new file mode 100644 index 0000000..7746b0a --- /dev/null +++ b/agent/infra/reference.js @@ -0,0 +1,56 @@ +/** + * 参考信息的文本化渲染(主 agent 与管理 agent 共用) + * + * 直接 JSON.stringify 的问题: + * 1. services 里的 booking / image / icon / tag 是前端配置,模型会把 + * booking.sessions(如 08:00—17:00)误读成「可与用户约定的可约时段」,造成错误许诺; + * 2. 裸 JSON 更耗 token,且模型解析散文优于 JSON。 + * 因此只渲染问答真正需要的字段,公示文案(subtitle / notices)保持逐字原文。 + */ + +export function formatServices(services) { + const areas = services?.[0]?.areas; + const lines = []; + if (areas?.length) { + lines.push(`服务区域:${areas.join('、')}`); + } + lines.push("(以下价格为公示价,单位:元)"); + + for (const s of services ?? []) { + lines.push(""); + lines.push(`${s.title}|${s.price} 元|${s.subtitle ?? ""}`.trim()); + if (s.description) { + lines.push(`适用:${s.description}`); + } + if (s.flow?.length) { + lines.push(`流程:${s.flow.map((step) => step.title).join(" → ")}`); + } + for (const notice of s.notices ?? []) { + lines.push(`· ${notice}`); + } + } + return lines.join("\n"); +} + +export function formatAgreement(agreement) { + const lines = [`${agreement.title}(原文摘要)`]; + + for (const section of agreement.sections ?? []) { + lines.push(""); + lines.push(`【${section.number}. ${section.title}】`); + for (const item of section.items ?? []) { + lines.push(`- ${item}`); + } + if (section.content) { + lines.push(section.content); + } + if (section.table?.rows?.length) { + const { headers = [], rows } = section.table; + lines.push(headers.join(" / ")); + for (const row of rows) { + lines.push(row.join(" / ")); + } + } + } + return lines.join("\n"); +} diff --git a/agent/infra/test_restricted_backend.mjs b/agent/infra/test_restricted_backend.mjs deleted file mode 100644 index 0e40373..0000000 --- a/agent/infra/test_restricted_backend.mjs +++ /dev/null @@ -1,58 +0,0 @@ -// 受限后端安全测试:验证敏感路径被拦截、正常资源可访问 -import { createRestrictedBackend } from "./restricted_fs_backend.js"; -import { CompositeBackend, FilesystemBackend } from "deepagents"; - -const ROOT = "d:/work/ws_health/api/health"; -const b = createRestrictedBackend({ rootDir: ROOT, dataDir: "./data" }); - -let pass = 0, fail = 0; -const check = (name, cond) => { cond ? pass++ : fail++; console.log(`${cond ? "PASS" : "FAIL"} ${name}`); }; - -// 1. 敏感文件读取拦截 -check("read conf.json (relative) denied", (await b.read("conf.json")).error?.includes("denied")); -check("read conf.json (absolute) denied", (await b.read("d:/work/ws_health/api/health/conf.json")).error?.includes("denied")); -check("read /conf.json (root-absolute) denied", (await b.read("/conf.json")).error !== undefined); -check("read .env denied", (await b.read(".env")).error?.includes("denied")); -check("read data dir file denied", (await b.read("data/users/u123/memory.txt")).error?.includes("denied")); -check("read logs denied", (await b.read("logs/x.log")).error?.includes("denied")); - -// 2. 穿越与沙箱外路径拦截 -check("traversal denied", (await b.read("../conf.json")).error !== undefined); -check("outside sandbox denied", (await b.read("c:/Windows/win.ini")).error !== undefined); - -// 3. 正常资源仍可访问 -const agents = await b.read("agent/bots/bot-escort/AGENTS.md"); -check("read AGENTS.md ok", !agents.error && agents.content.includes("小橙") === false || !agents.error); -const skill = await b.read("agent/infra/skills/baidu-ai-map/SKILL.md"); -check("read SKILL.md ok", !skill.error); - -// 4. ls / glob / grep 过滤 -const ls = await b.ls("/"); -check("ls no conf.json", !ls.files.some(f => f.path.toLowerCase().endsWith("conf.json"))); -const glob = await b.glob("**/conf*.json"); -check("glob no conf.json", !glob.files.some(f => f.path.toLowerCase().endsWith("conf.json"))); -const grep1 = await b.grep("apiKey", "/"); -check("grep no conf.json match", !grep1.matches.some(m => m.path.toLowerCase().endsWith("conf.json"))); -const grep2 = await b.grep("escort", "agent/bots/bot-escort"); -check("grep normal dir works", grep2.matches.length > 0); - -// 5. 拒绝写敏感文件、允许写普通目录 -check("write conf.json denied", (await b.write("conf.json", "{}")).error?.includes("denied")); -const w = await b.write("data-sandbox-test.txt", "hello"); -check("write normal file ok", !w.error); -await b.delete?.("data-sandbox-test.txt"); - -// 6. /memories/ 虚拟挂载( escort 场景)不受影响 -const composite = new CompositeBackend( - createRestrictedBackend({ rootDir: ROOT, dataDir: "./data" }), - { "/memories/": new FilesystemBackend({ rootDir: ROOT + "/data/users/u123", virtualMode: true }) }, -); -const wm = await composite.write("/memories/memory.txt", "测试记忆"); -check("write /memories ok", !wm.error); -const rm = await composite.read("/memories/memory.txt"); -check("read /memories ok", !rm.error && rm.content === "测试记忆"); -const wm2 = await composite.read("/conf.json"); -check("composite /conf.json denied", wm2.error?.includes("denied") || wm2.error !== undefined); - -console.log(`\n${pass} passed, ${fail} failed`); -process.exit(fail ? 1 : 0); diff --git a/test/guard.test.js b/test/guard.test.js new file mode 100644 index 0000000..9a7410e --- /dev/null +++ b/test/guard.test.js @@ -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); +}); diff --git a/test/restricted_fs_backend.test.js b/test/restricted_fs_backend.test.js new file mode 100644 index 0000000..f66c87e --- /dev/null +++ b/test/restricted_fs_backend.test.js @@ -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 }); + } +});