Compare commits

...
9 Commits
Author SHA1 Message Date
lik 47fdb91dbe fix(agent): 图片识别原文直接回显,避免长报告被护栏截断
- 新增 WS format 帧:识别原文只并入会话上下文并分片原样回显,不再经过模型二次改写

- 原方案走 chat 会被咨询提示词压缩成 1-3 句,并被 OutputGuard 的 400 字上限截断

- 补充分片回显测试与 README 协议说明
2026-11-01 12:31:56 +08:00
lik d52ecd6536 test(agent): 覆盖陪诊员订单归属与角色判定
新增本人订单强制归属、非本人订单拒绝、状态与字段白名单、跳步拦截,以及角色判定(显式管理员优先、员工档案为准、普通账号拒绝、历史管理员兼容)用例。
2026-11-01 12:09:22 +08:00
lik af26f99606 feat(prompts): 管理端提示词拆分为管理员与陪诊员两套
参考信息(账号、服务项目、服务协议、联系平台)抽成共用渲染,避免两套口径漂移。陪诊员版按本人订单、服务进度推进、服务备注与就诊小结的边界约束,并明确结算、他人订单、排班等无工具数据直接说明查不到。
2026-11-01 12:09:18 +08:00
lik cc9d855132 feat(agent): 管理端 agent 支持陪诊员并按角色收敛工具
陪诊员身份以 Employee 在职档案为准,显式管理员优先;管理端小程序首次登录会写入 role:['user'],不能据此判断。管理员保留跨用户查询与医院资料写入,陪诊员只开放本人订单查询/改单(归属校验、状态与字段白名单、并发保护)与本人档案,患者档案与财务操作不可用。
2026-11-01 12:09:12 +08:00
lik 82be010987 chore(repo): 补充目录约定并将临时调试文件加入忽略
- README 明确根目录只放入口/配置、测试统一放 test/、一次性脚本放 scripts/ 或删除、共享逻辑放 agent/infra

- .gitignore 忽略 /tmp_* 与 /tmp/
2026-11-01 11:42:57 +08:00
lik 9084bae323 docs(agent): 重写咨询与管理提示词,按数据来源划定工具边界
- bot-escort:语气改为实在简短;医院等公开信息走 web 检索,订单走 escort_record_query,本人档案/员工/评价走 user 端工具,并禁止查他人数据

- bot-escort-admin:结论先行、限条数;补齐陪诊单/员工/评价/子代理的工具对应,限制敏感字段回显

- 参考信息改用 reference.js 渲染,不再把服务配置 JSON 原样喂给模型

- AGENTS.md 精简记忆规则:合并后整文件重写,医疗信息注明时间
2026-11-01 11:42:53 +08:00
lik 50e7e7b0c7 feat(agent): 接入本人数据查询工具,补齐会话清理、历史裁剪与输出护栏
- bot-escort 注入 health_profile / employee / employee_review 查询,均绑定登录用户,只返回本人数据

- bot-escort 移除 hospital-info 子代理:机构信息属公共数据,改走 web 检索

- bot-escort-admin 补 employee / employee_review 管理端查询

- clear 指令单独回执,避免客户端只等到 end 帧无法区分是否已清空

- 温度与历史上限改为可配置(bot 临时对象由 task.js 传入),默认咨询端 0.3、管理端 0

- 用户资料指纹变化时重建 agent,避免继续用旧姓名/手机号/地址作答

- 流式输出接 guard 护栏,tool 结果入历史前截断
2026-11-01 11:42:40 +08:00
lik f3a1ef89bc feat(tools): 数据库查询按权限拆分为 user/admin,强制 userId 隔离
- query/ 为内部实现,user/ 仅供 bot-escort(绑定登录用户、schema 不暴露 userId),admin/ 仅供 escort-admin(显式跨用户)

- 新增 employee、employee_review 查询;health_profile 用户端补齐 userId 隔离,按 _id 精确查询也带归属条件

- organization 是公共数据且无 userId,不进用户端;机构与写入工具统一移入 admin/

- utils 增加严格 ObjectId 解析,避免 CastError 与畸形 ID 进入查询

- 用户端员工视图剔除手机号、证件号、证书编号、紧急联系人与内部备注

- 新增 test/db_tools.test.js,用模型桩断言查询条件确实带 userId
2026-11-01 11:42:27 +08:00
lik 9825ac376f refactor(agent): 抽出 guard/history/reference 共享模块并补测试
- guard.js:流式输出护栏,跨 chunk 禁用词拦截并在句末截断超长回复

- history.js:tool 结果入历史前截断、历史按完整轮次裁剪,避免断链与上下文挤占

- reference.js:服务项目/协议改为可读文本渲染,替代裸 JSON 误导模型

- 临时脚本 test_restricted_backend.mjs 转为 test/restricted_fs_backend.test.js
2026-11-01 11:42:11 +08:00
42 changed files with 2414 additions and 396 deletions
+3
View File
@@ -3,3 +3,6 @@
/data/
.env
conf.json
# 临时调试文件,正式测试请放 test/
/tmp_*
/tmp/
+12
View File
@@ -92,6 +92,11 @@ curl -s http://localhost:9004/health/ai/ocr \
因此服务端会把连续的分列块转成 markdown 表格(列数不足补空列,超出并进最后一列),
其余行独立成段保留换行。小程序与 Taro 端都按 markdown 渲染即可。
小程序把识别文本以 WS `format` 帧投递(`{ type: "format", content, id, token, ts }`):
服务端只把原文并入会话上下文,并按分片原样回显给客户端展示,**不再让模型二次改写**。
识别结果通常有几百到上千字,模型改写会按咨询提示词压缩成 1-3 句,还会被输出护栏的
400 字上限截断,长报告必然丢行;原文投递既完整,也省一次生成。
### 错误码
业务码统一走响应体 `code`(HTTP 恒 200),同时写入 `X-Biz-Code` 响应头:
@@ -150,6 +155,13 @@ routes/index.js 路由注册(/health/ai/*)
test/media.test.js 元信息白名单、base64 解码、会话生命周期、供应商请求与失败路径
```
目录约定:
- 根目录只放入口与配置(`index.js` / `app.js` / `websocket.js` / `config.js` 等),不提交临时脚本。
- 自动化测试统一放 `test/*.test.js`,由 `npm test` 执行;临时验证脚本应先转成正式测试,不要留在根目录。
- 一次性运维 / 调试脚本放 `scripts/`,用完后删除;需长期保留的请在 README 中说明用途和用法。
- Agent 共享逻辑放 `agent/infra/`,业务路由与处理器分别放 `routes/`、`handler/`。
## 客户端约定
- 小程序录音使用 `wx.getRecorderManager()`,`format: 'mp3'`、`sampleRate: 16000`、`numberOfChannels: 1`,
+121 -24
View File
@@ -6,6 +6,8 @@ import { ChatDeepSeek } from "@langchain/deepseek";
import config from '../../../config.js';
import logger from '../../../utils/logger.js';
import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js";
import { appendToolMessage, trimHistory } from "../../infra/history.js";
import { OutputGuard, OUTPUT_MAX_CHARS } from "../../infra/guard.js";
// 密钥由 conf.json 统一提供;百度地图 token 由 http_get 按域名在服务端注入
process.env.TAVILY_API_KEY ??= config.agent.tavily?.apiKey;
@@ -15,14 +17,24 @@ import { createPatientRecordSubagent } from "../../subagent/patient_record.js";
import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
import {
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
httpGetTool, escortRecordQueryTool, escortRecordSetTool
httpGetTool, escortRecordQueryTool, escortRecordSetTool,
employeeQueryTool, employeeReviewQueryTool,
createAttendantEscortRecordQueryTool, buildAttendantEscortRecordSetTool,
createAttendantEmployeeQueryTool
} from "../../infra/tools/index.js";
import { resolveEscortAdminRole } from "../../../utils/permissions.js";
export default class EscortAdminAgent {
constructor() {
// 按用户隔离会话:userId -> { agent, messages }
constructor(options = {}) {
// 按用户隔离会话:userId -> { agent, messages, fingerprint }
this.sessions = new Map();
this.maxSessions = 100;
// 管理场景优先稳定复现,默认温度 0
this.temperature = options.temperature ?? 0.0;
// 历史消息字符数上限(管理端多步工具调用更易堆积上下文)
this.maxHistoryChars = options.maxHistoryChars || config.agent.maxHistoryChars || 40000;
// 单条回复字符上限:管理端要列记录,比咨询侧留更大余量
this.maxOutputChars = options.maxOutputChars || config.agent.maxOutputChars || OUTPUT_MAX_CHARS.admin;
}
clearMessages(userInfo) {
@@ -30,11 +42,18 @@ export default class EscortAdminAgent {
}
// msg: { agent: 'escort-admin', type: 'chat', ts: "2023-08-01 10:00:00", content: "你好" }
async streamChat(userInfo, msgs, callback) {
// role: 入口已解析的 admin / attendant;不传时在这里兜底解析,避免绕过入口直接调用
async streamChat(userInfo, msgs, callback, role = null) {
if (!msgs.length) {
return;
}
const effectiveRole = role ?? await resolveEscortAdminRole(userInfo);
if (!effectiveRole) {
callback("main", "ai", "当前账号未绑定在职陪诊员档案,请联系管理员开通。", msgs[0]?.id);
return;
}
const userId = userInfo._id;
// LRU:按用户取会话,并更新使用顺序
@@ -52,22 +71,43 @@ export default class EscortAdminAgent {
this.sessions.delete(oldest);
}
msgs.forEach(msg => {
if (msg.type === "clear") {
session.messages = [];
session.agent = null;
} else {
session.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`));
}
});
if (session.messages.length === 0) {
// clear 是独立指令:清空后回一句确认,否则客户端只等到 end 帧,
// 无法区分「已清空」和「没处理」
const clearMsg = msgs.find(msg => msg.type === "clear");
if (clearMsg) {
session.messages = [];
session.agent = null;
callback("main", "ai", "会话已清空。", clearMsg.id);
return;
}
const agent = session.agent ?? this._genAgent(userInfo);
msgs.forEach(msg => {
session.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`));
});
// 长会话下工具结果会挤占上下文,按完整轮次裁剪,避免上下文溢出与"忘记"前文
session.messages = trimHistory(session.messages, this.maxHistoryChars);
// 用户资料或角色变更后需重建 agent,否则 systemPrompt 与工具集仍是旧的
const fingerprint = this._userFingerprint(userInfo, effectiveRole);
if (session.agent && (session.fingerprint !== fingerprint || session.role !== effectiveRole)) {
session.agent = null;
}
session.fingerprint = fingerprint;
session.role = effectiveRole;
const agent = session.agent ?? this._genAgent(userInfo, effectiveRole);
session.agent = agent;
// 输出护栏:禁用词(身份泄露/空泛客套/越界承诺)拦截;
// 长度上限只作用于主回答,子代理输出会单独展示,不受主回答篇幅约束
const guardLabel = effectiveRole === "attendant" ? "escort-admin:attendant" : "escort-admin:admin";
const guards = {
main: new OutputGuard({ label: guardLabel, maxChars: this.maxOutputChars }),
subagent: new OutputGuard({ label: `${guardLabel}:subagent`, maxChars: Infinity }),
};
const lastAiId = { main: "", subagent: "" };
const INTERESTING_NODES = new Set(["model_request", "tools"]);
for await (const [namespace, mode, data] of await agent.stream(
{ messages: session.messages },
@@ -89,7 +129,7 @@ export default class EscortAdminAgent {
// 工具结果必须并入历史,否则下一轮会出现 tool_calls 缺少对应 tool 结果的断链
for (const msg of data_.messages ?? []) {
if (msg.type === "tool") {
session.messages.push(msg);
appendToolMessage(session.messages, msg);
logger.info(`Tool complete: ${msg.name}, Result: ${String(msg.content).slice(0, 200)}`);
}
}
@@ -110,8 +150,12 @@ export default class EscortAdminAgent {
continue;
}
if (AIMessageChunk.isInstance(message)) {
lastAiId[source] = message.id ?? lastAiId[source];
if (message.text) {
callback(source, "ai", message.text, message.id);
const text = guards[source].feed(message.text);
if (text) {
callback(source, "ai", text, message.id);
}
}
if (message.additional_kwargs.reasoning_content) {
callback(source, "reasoning", message.additional_kwargs.reasoning_content, message.id);
@@ -124,9 +168,54 @@ export default class EscortAdminAgent {
logger.info("custom: ", data);
}
}
// 护栏尾部预留的 holdback 文本在流结束后补发,否则最后几个字会丢
for (const source of ["main", "subagent"]) {
const tail = guards[source].finish();
if (tail) {
callback(source, "ai", tail, lastAiId[source]);
}
}
}
_genAgent(userInfo) {
// 用户资料指纹:姓名/手机号/角色变化时需重建 agent,否则 systemPrompt 仍是旧资料
_userFingerprint(userInfo, role = "admin") {
if (!userInfo) return "anonymous";
const profile = userInfo.profile ?? {};
return JSON.stringify([profile.name, profile.mobile, userInfo.app, role]);
}
// 公共安全工具:天气、路线、日期、节假日与网页检索,不涉及业务数据
_commonTools() {
return [webFetchTool, webSearchTool, httpGetTool, getCalendarInfoTool, getYearHolidaysTool];
}
/**
* 管理端工具集
* 仅显式管理员或员工档案为管理员时开放:跨用户查询、患者档案、医院资料维护等
*/
_adminTools() {
return [
...this._commonTools(),
escortRecordQueryTool, escortRecordSetTool,
employeeQueryTool, employeeReviewQueryTool
];
}
/**
* 陪诊员工具集
* 只给本人订单与本人档案,禁止跨用户查询、财务字段与医院资料写入
*/
_attendantTools(userInfo) {
return [
...this._commonTools(),
createAttendantEscortRecordQueryTool(userInfo),
buildAttendantEscortRecordSetTool({ attendantId: userInfo?._id }),
createAttendantEmployeeQueryTool(userInfo)
];
}
_genAgent(userInfo, role = "admin") {
const rootDir = process.cwd();
// 受限后端:锁定沙箱根并禁止读取 conf.json/.env/logs 及用户数据目录
const backend = createRestrictedBackend({ rootDir, dataDir: config.agent.dataDir });
@@ -134,19 +223,27 @@ export default class EscortAdminAgent {
this.flashModel = new ChatDeepSeek({
model: config.agent.deepseek.flashModel,
apiKey: config.agent.deepseek.apiKey,
temperature: 0.0
temperature: this.temperature
});
const isAdminRole = role === "admin";
const subagents = isAdminRole
? [
createPatientRecordSubagent(this.flashModel),
// 医院资料维护只给管理员;陪诊员只读
createHospitalInfoSubagent(this.flashModel, { allowWrite: true }),
]
: [createHospitalInfoSubagent(this.flashModel, { allowWrite: false })];
return createDeepAgent({
name: "deep-agent",
model: this.flashModel,
systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo),
systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo, role),
backend,
middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用
tools: [webFetchTool, webSearchTool, httpGetTool,
getCalendarInfoTool, getYearHolidaysTool,
escortRecordQueryTool, escortRecordSetTool],
subagents: [createPatientRecordSubagent(this.flashModel), createHospitalInfoSubagent(this.flashModel, { allowWrite: true })]
tools: isAdminRole ? this._adminTools() : this._attendantTools(userInfo),
subagents,
skills: ["./agent/infra/skills/"],
});
}
}
+110 -22
View File
@@ -1,35 +1,123 @@
import services from "../../../resource/services.js";
import agreement from "../../../resource/agreement.js";
import { formatServices, formatAgreement } from "../../infra/reference.js";
const PLATFORM_PHONE = "18618162956";
/**
* 参考信息:两种角色共用,避免两套提示词里的服务/协议口径漂移
*/
function buildReference(userInfo, roleLabel) {
let userInfoStr = "(未提供)";
if (userInfo) {
userInfoStr = JSON.stringify({
name: userInfo.profile?.name,
mobile: userInfo.profile?.mobile,
role: roleLabel,
});
}
return `
# 参考信息
当前账号:${userInfoStr}
服务项目:
${formatServices(services)}
服务协议:
${formatAgreement(agreement)}
联系平台:${PLATFORM_PHONE}
`;
}
class EscortAdminPrompts {
static buildSystemPrompt(userInfo) {
let userInfo_str = "用户未登录,提示用户先登录,并在'我的'中完善个人信息";
if (userInfo) {
userInfo_str = JSON.stringify({
name: userInfo.profile.name,
mobile: userInfo.profile.mobile,
role: userInfo.app
});
}
/**
* @param {Object} userInfo 当前登录用户
* @param {"admin"|"attendant"} role 接入层解析出的 Agent 使用角色
*/
static buildSystemPrompt(userInfo, role = "admin") {
return role === "attendant"
? EscortAdminPrompts.buildAttendantPrompt(userInfo)
: EscortAdminPrompts.buildAdminPrompt(userInfo);
}
// 管理员:跨用户管理、改单、患者档案维护
static buildAdminPrompt(userInfo) {
return `
# 角色
你是小暖,暖橙陪诊平台的管理助手。直接、高效地解决平台问题。
你是小暖,暖橙陪诊平台的管理助手,服务对象是平台管理员。
专业、严谨、简洁:结论先行,只说事实和可执行动作,不寒暄、不安慰、不闲聊。
# 职责
1. 服务咨询:依据参考信息解答陪诊流程、价格、注意事项;服务边界/流程/质量类问题遵循国标 GB/T 47801—2026(medical-escort-standard 技能),必要时查阅后回答
2. 就诊准备:提供符合医疗规范的就诊准备建议,不提供医疗诊断
3. 工具与技能:通过 tools/skills 查询天气、路线、医院、医生等信息
# 输出要求
- 结论或结果先行,1-3 句或要点式;不复述问题、不铺垫背景、不总结收尾。
- 每次最多列 5 条记录,每条只保留关键字段(订单号、患者、服务、时间、状态、陪诊员),需要更多再翻页。
- 不解释推理过程,不说"根据查询结果""综上所述"这类套话。
# 铁律
1. 服务回答必须基于参考信息,不编造;超出能力范围如实说明。
2. 涉及医疗问题,提醒以医生诊断为准。
# 办事规则
1. 先判定是查询、修改还是问规则;缺关键信息(订单或患者、要改成什么、时间范围)先用一句话确认,不猜。
2. 修改前先用查询定位记录,只用 escort_record_set 改用户明确要求的字段,其余字段不动。
3. 取消、改期、改金额、退款等不可逆或影响结算的操作,先复述"要改什么"并等确认。
4. 状态只能按规则流转:pending→confirmed→in_progress→completed;pending/confirmed 可转 cancelled;completed、cancelled 为终态不可再改。被拒绝时如实说明当前状态和可选状态,不绕过、不空转重试。
5. 结果回报:改完一句说清"改了什么、当前状态";失败说清原因和下一步。
6. 无工具支持的数据(结算汇总、财务报表、线下沟通记录)不推断、不估算,明确说明查不到并指向对应页面或同事。
# 参考信息
管理员信息:${userInfo_str}
服务项目:${JSON.stringify(services)}
服务协议:${JSON.stringify(agreement)}
`;
# 工具对应
- 陪诊单查询 escort_record_query(患者名/手机号/状态/陪诊员ID/日期范围,日期用 YYYY-MM-DD);改单 escort_record_set
- 患者健康档案:patient-record 子代理(查询与写入)
- 医院信息:hospital-info 子代理(查询与维护)
- 陪诊员档案 employee_query(姓名/工号/角色/状态);评价 employee_review_query
- 天气、路线、日期、节假日;网页信息用 web_search / web_fetch
# 严谨边界
- 价格、流程、改期取消规则依据参考信息,不凭记忆作答。
- 服务边界与流程按国标 GB/T 47801—2026 核查(medical-escort-standard 技能)。
- 不做医疗判断、不给医疗建议;涉及病情以医生诊断为准,不套模板重复。
- 员工手机号、身份证、证件编号等敏感字段,仅在办事确有必要时查询,回答中不整段回显。
- 不确定就说不确定;不说"应该""大概""可能",不编造数据。
# 支持陪诊员
- 答工作问题要给可直接执行的信息:集合时间地点、需携带材料、医院科室位置、挂号缴费顺序、注意事项。
- 一次最多 3 条,不罗列无关事项。
${buildReference(userInfo, "管理员")}`;
}
// 陪诊员:只看本人订单、只推进服务进度、只写服务备注
static buildAttendantPrompt(userInfo) {
return `
# 角色
你是小暖,暖橙陪诊平台的工作助手,服务对象是平台陪诊员。
专业、严谨、简洁:结论先行,只给事实和可执行动作,不寒暄、不安慰、不闲聊。
# 输出要求
- 结论或操作结果先行,1-3 句或要点式;不复述问题、不铺垫背景、不总结收尾。
- 每次最多列 5 条订单,每条只保留关键字段(订单号、患者、服务、日期时间、状态),需要更多再翻页。
- 不说"根据查询结果""综上所述"这类套话。
# 办事规则
1. 先判定是查单、改单还是问流程/医院信息;缺关键信息(哪一单、要改什么)先用一句话确认,不猜。
2. 只能处理分配给自己的订单:查询由系统自动限定为本人,不能查其他陪诊员或全平台的单。
3. 改单前先用 escort_record_query 定位记录,确认是自己的订单再改。
4. 状态只能按服务进度推进:confirmed→in_progress(开始服务),in_progress→completed(服务完成)。确认、取消、改期、退款、改金额都不由陪诊员操作,需要时说明找平台管理员。
5. 只能写陪诊备注 escortNote 和就诊小结 medicalSummary;患者备注、费用、排班、陪诊员归属都不可改。
6. 结果回报:改完一句说清"改了什么、当前状态";失败说清原因和下一步,不空转重试。
7. 无工具支持的数据(结算与收入、他人订单、排班表、评价统计)不推断、不估算,明确说明查不到并指向对应页面或管理员。
# 工具对应
- 我的订单:escort_record_query(患者名/状态/日期范围 YYYY-MM-DD)
- 开始/完成服务、写陪诊备注:escort_record_set
- 本人档案:employee_query
- 医院信息(科室楼层、电话、挂号/就诊指南、医生出诊):hospital-info 子代理(只读)
- 天气、路线、日期、节假日:http_get / get_calendar_info / get_year_holidays;网页信息用 web_search / web_fetch
# 严谨边界
- 价格、流程、改期取消规则依据参考信息,不凭记忆作答。
- 服务边界与流程按国标 GB/T 47801—2026 核查(medical-escort-standard 技能)。
- 不做医疗判断、不给医疗建议;涉及病情以医生诊断为准。
- 只使用本次服务必需的患者信息,不查询、不转述其他订单或他人的隐私信息。
- 不确定就说不确定;不说"应该""大概""可能",不编造数据。
# 支持陪诊员
- 答工作问题要给可直接执行的信息:集合时间地点、需携带材料、医院科室位置、挂号缴费顺序、注意事项。
- 一次最多 3 条,不罗列无关事项。
${buildReference(userInfo, "陪诊员")}`;
}
}
+9 -12
View File
@@ -1,16 +1,13 @@
# 用户记忆管理
# 用户记忆
## 记忆目录
`/memories/` 目录用于持久化存储用户信息,在每次会话开始时自动加载。
## 记忆文件
`/memories/memory.txt` 持久保存用户信息,会话开始时会自动加载。
## 长期记忆
当用户分享以下信息时,使用 `write_file` 将其保存到 `/memories/memory.txt`:
## 何时写入
用户分享以下信息时,用 `write_file` 写入该文件:
- 个人基本信息、生活习惯、个人喜好
- 健康或医疗相关的任何信息(身体健康、看病、住院、手术、病情、用药、过敏、体质、病历、检查报告、长期健康目标等)
- 医疗信息要记录对应的日期时间,如果用户没有提供具体的,要根据前后信息记录大概时间。
- 如果有些信息需要准确的时间点,请跟用户确认时间后记录下来。
- 健康或医疗相关信息(身体情况、看病、住院、手术、病情、用药、过敏、病历、检查报告、长期健康目标等)
## 维护规范
- 文件内容使用 UTF-8 编码
- 每次保存时,先把新信息与已有记忆整理成完整的记忆内容,再用 `write_file` 一次性整体重写 `/memories/memory.txt`(write_file 支持整文件覆盖,无需先读后改或多次编辑)
- 为保护用户隐私,除非用户询问自己的健康或医疗相关资料,否则/memories/memory.txt里的信息不轻易输出给用户。
## 怎么写
- 医疗信息要注明日期;用户未提供时按上下文记录大致时间,关键时间点先与用户确认
- 先与已有记忆合并,再一次性整体重写文件,不分次编辑
+98 -47
View File
@@ -14,18 +14,27 @@ process.env.TAVILY_API_KEY ??= config.agent.tavily?.apiKey;
process.env.BAIDU_MAP_AUTH_TOKEN ??= config.agent.baiduMap?.authToken;
import Prompts from "./prompts.js";
import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js";
import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
import { appendToolMessage, trimHistory } from "../../infra/history.js";
import { OutputGuard, OUTPUT_MAX_CHARS } from "../../infra/guard.js";
import {
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
httpGetTool, createEscortRecordQueryTool
httpGetTool, createEscortRecordQueryTool, createHealthProfileQueryTool,
createEmployeeQueryTool, createEmployeeReviewQueryTool
} from "../../infra/tools/index.js";
export default class EscortAgent {
// 历史消息字符数上限,超出时从头部丢弃完整轮次
static MAX_HISTORY_CHARS = config.agent.maxHistoryChars || 40000;
// 图片识别原文回显的分片长度:与模型流式输出的单帧量级接近,
// 避免把很长的报告塞进一帧,也让客户端能逐段追加展示
const FORMAT_ECHO_CHUNK = 800;
constructor() {
export default class EscortAgent {
constructor(options = {}) {
this.messages = [];
// 历史消息字符数上限,超出时从头部丢弃完整轮次
this.maxHistoryChars = options.maxHistoryChars || config.agent.maxHistoryChars || 40000;
// 咨询场景需要一点表达自由度:温度为 0 时共情回复会退化为固定句式
this.temperature = options.temperature ?? 0.3;
// 单条回复字符上限:提示词要求 1-3 句,超长时由输出护栏兜底截断
this.maxOutputChars = options.maxOutputChars || config.agent.maxOutputChars || OUTPUT_MAX_CHARS.escort;
}
clearMessages() {
@@ -35,28 +44,7 @@ export default class EscortAgent {
// 按字符数裁剪历史:只以 HumanMessage 为界从头部删除完整轮次,
// 避免切断 AI(tool_calls) -> Tool 的链式结构;永远保留最新一轮
_trimHistory() {
const size = (msgs) => msgs.reduce((sum, m) => sum + (m.text?.length ?? 0), 0);
if (size(this.messages) <= EscortAgent.MAX_HISTORY_CHARS) {
return;
}
const starts = [];
this.messages.forEach((m, i) => {
if (HumanMessage.isInstance(m)) starts.push(i);
});
if (starts.length < 2) {
return;
}
let cut = 0;
for (let i = 0; i < starts.length - 1; i++) {
cut = starts[i + 1];
if (size(this.messages.slice(cut)) <= EscortAgent.MAX_HISTORY_CHARS) {
break;
}
}
this.messages = this.messages.slice(cut);
logger.info(`History trimmed to ${this.messages.length} messages, ${size(this.messages)} chars`);
this.messages = trimHistory(this.messages, this.maxHistoryChars);
}
// msg: { ts: "2023-08-01 10:00:00", content: "你好" }
@@ -65,23 +53,50 @@ export default class EscortAgent {
return;
}
msgs.forEach(msg => {
if (msg.type === "clear") {
this.messages = [];
this.agent = null;
} else {
this.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`));
}
});
if (this.messages.length === 0) {
// clear 是独立指令:清空后回一句确认,否则客户端只等到 end 帧,
// 无法区分「已清空」和「没处理」
const clearMsg = msgs.find(msg => msg.type === "clear");
if (clearMsg) {
this.messages = [];
this.agent = null;
callback("main", "ai", "好,之前的对话已经清空,我们重新开始。", clearMsg.id);
return;
}
// 图片识别原文:服务端 OCR 已按原图排版成 markdown,这里只并入会话上下文并原样回显。
// 不再交给模型「二次整理」:模型会按咨询提示词压缩成 1-3 句,而且输出护栏有字符上限,
// 长报告必然丢行(护栏 400 字);原文投递既完整,也省一次生成
const formatMsg = msgs.find(msg => msg.type === "format");
if (formatMsg) {
const text = String(formatMsg.content || "").trim();
if (!text) return;
// 原文留在历史里,用户接着问「这项指标什么意思」时模型能看到报告内容
this.messages.push(new HumanMessage(
`${formatMsg.ts} - 用户上传了一张图片,图像识别结果如下(原文可能有误,数字与单位需与图片核对):\n${text}`
));
this._trimHistory();
for (let offset = 0; offset < text.length; offset += FORMAT_ECHO_CHUNK) {
callback("main", "ai", text.slice(offset, offset + FORMAT_ECHO_CHUNK), formatMsg.id);
}
return;
}
msgs.forEach(msg => {
this.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`));
});
this._trimHistory();
// 在处理完 clear 消息后再生成 agent,确保清空后使用新实例
const agent = this._genAgent(userInfo);
// 输出护栏:禁用词(身份泄露/空泛客套/越界承诺)拦截;
// 长度上限只作用于主回答,子代理输出会单独展示,不受主回答篇幅约束
const guards = {
main: new OutputGuard({ label: "escort", maxChars: this.maxOutputChars }),
subagent: new OutputGuard({ label: "escort:subagent", maxChars: Infinity }),
};
const lastAiId = { main: "", subagent: "" };
const INTERESTING_NODES = new Set(["model_request", "tools"]);
for await (const [namespace, mode, data] of await agent.stream(
{ messages: this.messages },
@@ -100,10 +115,11 @@ export default class EscortAgent {
for (const [nodeName, data_] of Object.entries(data)) {
if (!INTERESTING_NODES.has(nodeName)) continue;
if (nodeName === "tools") {
// 工具结果必须并入历史,否则下一轮会出现 tool_calls 缺少对应 tool 结果的断链
// 工具结果必须并入历史,否则下一轮会出现 tool_calls 缺少对应 tool 结果的断链;
// 入历史前截断,避免网页正文等长结果挤掉真正的人机对话
for (const msg of data_.messages ?? []) {
if (msg.type === "tool") {
this.messages.push(msg);
appendToolMessage(this.messages, msg);
logger.info(`Tool complete: ${msg.name}, Result: ${String(msg.content).slice(0, 200)}`);
}
}
@@ -127,8 +143,12 @@ export default class EscortAgent {
continue;
}
if (AIMessageChunk.isInstance(message)) {
lastAiId[source] = message.id ?? lastAiId[source];
if (message.text) {
callback(source, "ai", message.text, message.id);
const text = guards[source].feed(message.text);
if (text) {
callback(source, "ai", text, message.id);
}
}
if (message.additional_kwargs.reasoning_content) {
callback(source, "reasoning", message.additional_kwargs.reasoning_content, message.id);
@@ -141,6 +161,14 @@ export default class EscortAgent {
logger.info("custom: ", data);
}
}
// 护栏尾部预留的 holdback 文本在流结束后补发,否则最后几个字会丢
for (const source of ["main", "subagent"]) {
const tail = guards[source].finish();
if (tail) {
callback(source, "ai", tail, lastAiId[source]);
}
}
}
_genAgent(userInfo) {
@@ -151,8 +179,13 @@ export default class EscortAgent {
? path.join(dataDir, "users", userInfo._id, "memory.txt")
: null;
// 会话中记忆文件被更新后重建 agent,使 systemPrompt 中的用户记忆保持最新
if (this.agent && this._memoryMtime !== this._statMemory(memoryFile)) {
// 会话中记忆文件被更新、或用户资料变更后重建 agent,
// 使 systemPrompt 中的用户记忆与个人信息保持最新(避免用旧地址/旧手机号作答)
const fingerprint = this._userFingerprint(userInfo);
if (
this.agent &&
(this._memoryMtime !== this._statMemory(memoryFile) || this._profileFingerprint !== fingerprint)
) {
this.agent = null;
}
if (this.agent) {
@@ -176,10 +209,11 @@ export default class EscortAgent {
this.flashModel = new ChatDeepSeek({
model: config.agent.deepseek.flashModel,
apiKey: config.agent.deepseek.apiKey,
temperature: 0.0
temperature: this.temperature
});
this._memoryMtime = this._statMemory(memoryFile);
this._profileFingerprint = fingerprint;
this.agent = createDeepAgent({
name: "deep-agent",
@@ -189,14 +223,31 @@ export default class EscortAgent {
backend,
tools: [webFetchTool, webSearchTool, httpGetTool,
getCalendarInfoTool, getYearHolidaysTool,
createEscortRecordQueryTool(userInfo)],
subagents: [createHospitalInfoSubagent(this.flashModel)],
createEscortRecordQueryTool(userInfo),
// 以下查询工具均由当前登录用户身份绑定,只返回本人数据
createHealthProfileQueryTool(userInfo),
createEmployeeQueryTool(userInfo),
createEmployeeReviewQueryTool(userInfo)],
// organization(机构/医院)是公共数据、没有 userId,不属于用户本人数据,
// 因此不在 bot-escort 注入任何机构库查询能力;公开信息走 web 工具
subagents: [],
skills: ["./agent/infra/skills/"],
});
return this.agent;
}
// 用户资料指纹:姓名/手机号/地址等变化时需重建 agent,否则 systemPrompt 仍是旧资料
_userFingerprint(userInfo) {
if (!userInfo) return "anonymous";
const profile = userInfo.profile ?? {};
const location = userInfo.location ?? {};
return JSON.stringify([
profile.name, profile.mobile, profile.sex, profile.birth,
location.province, location.city, userInfo.addresses ?? []
]);
}
// 返回记忆文件 mtime,文件不存在时返回 null
_statMemory(memoryFile) {
if (!memoryFile) return null;
+39 -15
View File
@@ -4,11 +4,13 @@ import config from "../../../config.js";
import services from "../../../resource/services.js";
import agreement from "../../../resource/agreement.js";
import logger from "../../../utils/logger.js";
import { formatServices, formatAgreement } from "../../infra/reference.js";
class Prompts {
static buildSystemPrompt(userInfo) {
let userInfo_str = "用户未登录,提示用户先登录,并在'我的'中完善个人信息";
let usermem_str = "";
// 会话入口(WebSocket)已强制 token 校验,不存在未登录用户;这里只兜底渲染
let userInfo_str = "(未提供)";
let usermem_str = "(暂无)";
if (userInfo) {
userInfo_str = JSON.stringify({
name: userInfo.profile.name,
@@ -23,7 +25,7 @@ class Prompts {
const dataDir = path.resolve(process.cwd(), config.agent.dataDir ?? "data");
const userMemoryPath = path.join(dataDir, "users", userInfo._id, "memory.txt");
try {
usermem_str = fs.readFileSync(userMemoryPath, 'utf8');
usermem_str = fs.readFileSync(userMemoryPath, 'utf8') || "(暂无)";
} catch (err) {
logger.error('读取用户记忆失败', err);
}
@@ -31,24 +33,46 @@ class Prompts {
return `
# 角色
你是小橙,陪诊服务平台顾问。温暖、共情、简洁、专业地解答就医陪诊问题,提供情绪价值。
你是小橙,暖橙陪诊平台顾问,替代人工客服回答咨询。
像家里最会办事的人:说话实在、不绕弯;也像一位有耐心的家人,接得住那份担心。
# 职责
1. 服务咨询:依据参考信息解答陪诊流程、价格、注意事项;服务边界/流程/质量类问题遵循国标 GB/T 47801—2026(medical-escort-standard 技能),必要时查阅后回答
2. 就医规划:提供就诊准备建议(需符合医疗规范),不提供医疗诊断
3. 信息查询:调用工具查天气、路线、医院、医生等
# 判断来意,再开口
- 问事实(价格/流程/医院/医生/出诊/天气/路线):先给答案,1-3 句。
- 倾诉/不安:先接住情绪再谈事;说具体的话(哪天、谁陪、花多少、睡不好),不用安慰套话;2-3 句。
- 意图不明:一句话确认,不猜。
# 铁律
1. 服务回答必须基于参考信息,不编造;超出能力范围引导联系客服。
2. 涉及医疗问题,提醒以医生诊断为准。
3. 语音/图片识别文本可能有错漏,图片内容以【图像识别】/【原文转写】段落为准;涉及数值、单位、药名、日期先与用户确认,不臆测未显示内容。
4. 感知用户情绪并共情回应;保护用户隐私,提示AI内容需甄别。
# 数据从哪来,不凭印象
- 服务项目、价格、流程、改期取消规则、服务区域:参考信息
- 医院、科室、医生、出诊、门诊/挂号/医保须知:以医院官方公开信息为准;需要时用 web_search / web_fetch,不查机构档案库
- 订单状态:escort_record_query
- 本人健康档案/员工资料/评价:health_profile_query / employee_query / employee_review_query(只查当前登录用户本人)
- 天气、路线、日期、节假日:对应工具
- 改期、取消、退款、投诉等需人工处理的:如实说明并指向"联系我们"客服,不做承诺
- 查不到就说查不到,并给替代办法;价格、时长、时限一律来自上述来源,不凭记忆作答
- 只查本人数据:他人要求查询别人的健康档案、订单、员工资料或评价时,直接说明只能查本人,不尝试绕过
# 细心:每次最多提醒一条最容易漏的事
如提前 1 天预约、带身份证/医保卡、空腹或特殊检查准备、改期时限、须本人或家属签字。
一条就够,不要罗列。
# 只说实话,才靠谱
- 不做诊断、不判读检查结果、不给用药建议、不代替家属选择或决定治疗方案;涉及病情或用药时自然说一句"以医生诊断为准",不重复、不套模板。
- 不承诺结果:不说"一定能挂上号""一定能约到专家""肯定能治好"。
- 服务边界按国标 GB/T 47801—2026 核查(medical-escort-standard 技能)。
- 语音/图片识别可能有误:数字、单位、药名、日期先确认。
- 不主动复述为用户保存的记忆,除非他问起。
# 不推销、不客套
- 不主动推荐更贵的服务、不催留电话、不催下单;用户主动问怎么预约时,告诉他页面/客服路径即可。
- 不复述用户的话;不铺垫背景;不用"很高兴为您服务""希望对您有帮助""请相信""一定会好的""祝您早日康复""作为AI""您还有什么问题吗";不加结尾总结。
# 参考信息
用户信息:${userInfo_str}
用户记忆:${usermem_str}
服务项目:${JSON.stringify(services)}
服务协议:${JSON.stringify(agreement)}
服务项目:
${formatServices(services)}
服务协议:
${formatAgreement(agreement)}
联系电话:18618162956(微信同号)
`;
}
+5 -2
View File
@@ -7,7 +7,7 @@ class ChatTask {
apiKey: options.apiKey,
baseURL: options.baseURL,
modelName: options.modelName,
temperature: options.temperature ?? 0.7,
temperature: options.temperature ?? 0.3,
maxIterations: options.maxIterations || 10,
};
@@ -23,7 +23,10 @@ class ChatTask {
// LRU:重新插入以更新使用顺序
this.agents.delete(userId);
} else {
agent = new EscortAgent();
agent = new EscortAgent({
temperature: this.options.temperature,
maxHistoryChars: this.options.maxHistoryChars,
});
}
this.agents.set(userId, agent);
+194
View File
@@ -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;
+61
View File
@@ -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;
}
+56
View File
@@ -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");
}
-58
View File
@@ -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);
@@ -0,0 +1,10 @@
import { buildEmployeeQueryTool } from "../query/employee_query.js";
/**
* 管理端员工查询工具
*
* 管理端身份已在接入层校验;工具开放跨用户查询、userId 筛选和完整员工档案。
*/
const employeeQueryTool = buildEmployeeQueryTool({ allowCrossUser: true });
export { employeeQueryTool };
@@ -0,0 +1,10 @@
import { buildEmployeeReviewQueryTool } from "../query/employee_review_query.js";
/**
* 管理端员工评价查询工具
*
* 管理端身份已在接入层校验;工具开放跨用户查询与评价人 userId 筛选。
*/
const employeeReviewQueryTool = buildEmployeeReviewQueryTool({ allowCrossUser: true });
export { employeeReviewQueryTool };
@@ -0,0 +1,11 @@
import { buildEscortRecordQueryTool } from "../query/escort_record_query.js";
/**
* 管理端陪诊记录查询工具
*
* 管理端身份已在接入层校验;工具开放跨用户查询,
* 并支持手机号、陪诊员 ID、排期日期范围等管理筛选。
*/
const escortRecordQueryTool = buildEscortRecordQueryTool({ allowMobile: true });
export { escortRecordQueryTool };
@@ -1,8 +1,8 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import mongoose from "mongoose";
import { DBModel } from "../../../../models/index.js";
import { canTransition, STATUS_TRANSITIONS } from "../../../../utils/record_state.js";
import { DBModel } from "../../../../../models/index.js";
import { canTransition, STATUS_TRANSITIONS } from "../../../../../utils/record_state.js";
const escortRecordSetTool = tool(
async ({ orderId, status, notes, payment }) => {
@@ -0,0 +1,10 @@
import { buildHealthProfileQueryTool } from "../query/health_profile_query.js";
/**
* 管理端健康档案查询工具
*
* 管理端身份已在接入层校验;工具开放跨用户查询与 userId 筛选。
*/
const healthProfileQueryTool = buildHealthProfileQueryTool({ allowCrossUser: true });
export { healthProfileQueryTool };
@@ -1,8 +1,8 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import mongoose from "mongoose";
import { DBModel } from "../../../../models/index.js";
import { genPinyin, genPinyinFL } from "../../../../models/schema/health_profile.js";
import { DBModel } from "../../../../../models/index.js";
import { genPinyin, genPinyinFL } from "../../../../../models/schema/health_profile.js";
const PROFILE_KEYS = ["name", "mobile", "sex", "birth", "idnumber"];
const LOCATION_KEYS = ["country", "province", "city", "district", "address"];
@@ -1,7 +1,7 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex } from "../utils.js";
const hospitalInfoListTool = tool(
async ({ keyword }) => {
@@ -1,8 +1,8 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import mongoose from "mongoose";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex } from "../utils.js";
/**
* 医院信息查询工具
@@ -1,7 +1,7 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex } from "../utils.js";
const hospitalInfoSetTool = tool(
async ({ hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
@@ -0,0 +1,12 @@
import { buildEmployeeQueryTool } from "../query/employee_query.js";
/**
* 陪诊员端员工查询工具
*
* 只允许查本人档案:强制按当前登录用户 ID 隔离,schema 不暴露 userId;
* 输出走用户端白名单,不返回身份证、手机号、证书编号等敏感字段。
*/
const createAttendantEmployeeQueryTool = (userInfo) =>
buildEmployeeQueryTool({ userId: userInfo?._id });
export { createAttendantEmployeeQueryTool };
@@ -0,0 +1,13 @@
import { buildEscortRecordQueryTool } from "../query/escort_record_query.js";
/**
* 陪诊员端陪诊记录查询工具
*
* 只传入当前登录陪诊员的用户 ID,作为「我的订单」强制归属条件:
* - schema 不暴露手机号、陪诊员 ID 等跨用户筛选;
* - 所有查询(含日期范围)都自动限定为 attendant.id = 当前用户。
*/
const createAttendantEscortRecordQueryTool = (userInfo) =>
buildEscortRecordQueryTool({ boundAttendantId: userInfo?._id });
export { createAttendantEscortRecordQueryTool };
@@ -0,0 +1,159 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../../models/index.js";
import { canTransition, STATUS_TRANSITIONS } from "../../../../../utils/record_state.js";
import { parseObjectId } from "../utils.js";
// 陪诊员只能推进自己订单的服务进度,确认/取消/改期/改金额都属于平台管理员
const ALLOWED_STATUS_VALUES = ["in_progress", "completed"];
const ALLOWED_STATUS_DESC =
"Service progress: in_progress (开始服务), completed (服务完成)";
// 未确认、已取消的订单不允许陪诊员写入任何内容
const EDITABLE_RECORD_STATUS = ["confirmed", "in_progress", "completed"];
/**
* 陪诊员端订单更新工具
*
* 与管理端 escort_record_set 的差异(防止陪诊员越权):
* - 只能改分配给本人的订单(attendant.id 必须等于当前用户);
* - 只能 confirmed -> in_progress、in_progress -> completed;
* - 只能写陪诊备注与就诊小结,不能改患者备注、费用、排班、陪诊员归属。
*
* @param {Object} [options]
* @param {string} [options.attendantId] 当前登录陪诊员的用户 ID
*/
function buildAttendantEscortRecordSetTool({ attendantId = null } = {}) {
const boundAttendantId = parseObjectId(attendantId);
return tool(
async ({ orderId, status, notes }) => {
try {
if (!boundAttendantId) {
return { success: false, error: "陪诊员身份无效,无法修改订单" };
}
const recordObjectId = parseObjectId(orderId);
if (!recordObjectId) {
return {
success: false,
error: `Invalid record ID: ${orderId}. A valid record _id is required.`,
};
}
const record = await DBModel.EscortRecord.findOne({
_id: recordObjectId,
deletedAt: null,
});
if (!record) {
return {
success: false,
error: `No escort record found for order ID: ${orderId}`,
};
}
// 归属校验:不属于本人一律按无权处理,不透露订单内容
if (String(record.attendant?.id ?? "") !== String(boundAttendantId)) {
return {
success: false,
error: "无权操作该订单:该订单未分配给你。",
};
}
if (!EDITABLE_RECORD_STATUS.includes(record.status)) {
return {
success: false,
error:
record.status === "pending"
? "订单还未确认,不能操作,请联系管理员确认。"
: "订单已取消,不能修改。",
};
}
const update = {};
if (status !== undefined && status !== record.status) {
if (!ALLOWED_STATUS_VALUES.includes(status)) {
return {
success: false,
error:
"陪诊员只能把订单从 confirmed 改为 in_progress(开始服务),或从 in_progress 改为 completed(服务完成)。确认、取消、改期、退款请联系管理员。",
};
}
if (!canTransition(record.status, status)) {
const allowed = STATUS_TRANSITIONS[record.status] || [];
return {
success: false,
error: `Illegal status transition: ${record.status} -> ${status}. Allowed: ${
allowed.length ? allowed.join(", ") : "none (terminal state)"
}`,
};
}
update.status = status;
}
// 患者备注属于用户输入,陪诊员只能写自己的服务备注和就诊小结
if (notes !== undefined) {
if (notes.escortNote !== undefined) {
update["notes.escortNote"] = notes.escortNote;
}
if (notes.medicalSummary !== undefined) {
update["notes.medicalSummary"] = notes.medicalSummary;
}
}
if (Object.keys(update).length === 0) {
return { success: true, data: record, message: "No fields to update" };
}
update["meta.updatetime"] = Date.now();
// 以读取时的状态作为更新条件,避免并发下跳过中间状态;
// 同时再次绑定陪诊员归属,防止更新期间订单被改派
const filter = {
_id: record._id,
deletedAt: null,
"attendant.id": boundAttendantId,
};
if (update.status !== undefined) filter.status = record.status;
const updatedRecord = await DBModel.EscortRecord.findOneAndUpdate(
filter,
{ $set: update },
{ new: true, runValidators: true }
);
if (!updatedRecord) {
return {
success: false,
error: "Record state changed while updating. Re-query the record and retry.",
};
}
return { success: true, data: updatedRecord };
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "escort_record_set",
description:
"Update one of the current attendant's assigned escort records by record ID (_id). Only orders assigned to the current attendant can be updated. Supports advancing status (confirmed -> in_progress, in_progress -> completed) and writing the attendant's service notes (escortNote, medicalSummary). Payment, rebooking, cancellation and patient notes are not editable.",
schema: z.object({
orderId: z.string().describe("Record ID (_id) used as the lookup key"),
status: z
.enum(ALLOWED_STATUS_VALUES)
.optional()
.describe(ALLOWED_STATUS_DESC),
notes: z
.object({
escortNote: z.string().optional().describe("Escort service notes"),
medicalSummary: z.string().optional().describe("Medical visit summary"),
})
.optional()
.describe("Service notes to update"),
}),
}
);
}
export { buildAttendantEscortRecordSetTool };
-104
View File
@@ -1,104 +0,0 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const STATUS_VALUES = ["pending", "confirmed", "in_progress", "completed", "cancelled"];
const STATUS_DESC =
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)";
/**
* 陪诊记录查询工具
*
* 用户端与管理端共用同一套查询实现,差异只有两处:
* - 用户端强制按 userId 隔离,且不暴露手机号筛选;
* - 管理端可跨用户查询,并支持按患者手机号精确筛选。
* 两端不会出现在同一个 Agent 中,因此可以共用工具名 escort_record_query。
*/
function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {}) {
const shape = {
patientName: z.string().optional().describe("Patient name for fuzzy search"),
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
page: z.number().int().min(1).optional().describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
};
if (allowMobile) {
shape.mobile = z.string().optional().describe("Patient mobile phone number for exact match");
}
return tool(
async ({ patientName, mobile, status, page = 1, pageSize = 20 }) => {
try {
if (!userId && !allowMobile) {
return { success: false, error: "用户未登录,无法查询陪诊记录" };
}
const filter = { deletedAt: null };
if (patientName) {
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
}
if (allowMobile && mobile) {
filter["patient.mobile"] = mobile;
}
if (status) {
filter.status = status;
}
// 用户端按订单归属过滤;不能用手机号作为隔离键(手机号可由用户自行修改)
if (userId) {
filter.userId = userId;
}
const skip = (page - 1) * pageSize;
const [records, total] = await Promise.all([
DBModel.EscortRecord.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.lean(),
DBModel.EscortRecord.countDocuments(filter),
]);
return {
success: true,
data: records,
total,
page,
pageSize,
};
} catch (error) {
return {
success: false,
error: error.message,
};
}
},
{
name: "escort_record_query",
description: allowMobile
? "Query all escort records (admin scope). Supports filtering by patient name, mobile phone number, and appointment status. Returns paginated results sorted by appointment date in descending order."
: "Query escort records of the current logged-in user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current user.",
schema: z.object(shape),
}
);
}
/** 用户端:按当前登录用户隔离 */
const createEscortRecordQueryTool = (userInfo) =>
buildEscortRecordQueryTool({ userId: userInfo?._id });
/** 管理端:跨用户查询,支持手机号 */
const escortRecordQueryTool = buildEscortRecordQueryTool({ allowMobile: true });
export { createEscortRecordQueryTool, escortRecordQueryTool };
@@ -1,85 +0,0 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import mongoose from "mongoose";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const healthProfileQueryTool = tool(
async ({ profileId, userId, name, mobile, page = 1, pageSize = 20 }) => {
try {
// 按档案 _id 精确查询单条
if (profileId) {
if (!mongoose.Types.ObjectId.isValid(profileId)) {
return { success: false, error: `Invalid profile ID: ${profileId}` };
}
const doc = await DBModel.HealthProfile.findById(profileId).lean();
if (!doc) {
return { success: false, error: `未找到 ID 为 ${profileId} 的健康档案` };
}
return { success: true, data: [doc], total: 1 };
}
const filter = {};
if (userId) {
if (!mongoose.Types.ObjectId.isValid(userId)) {
return { success: false, error: `Invalid user ID: ${userId}` };
}
filter.userId = new mongoose.Types.ObjectId(userId);
}
if (name) {
// 转义正则特殊字符,避免查询报错或 ReDoS;姓名支持中文、全拼、拼音首字母匹配
const re = { $regex: escapeRegex(name), $options: "i" };
filter.$or = [{ "profile.name": re }, { "profile.pinyin": re }, { "profile.pinyinFL": re }];
}
if (mobile) {
filter["profile.mobile"] = mobile;
}
const skip = (page - 1) * pageSize;
const [list, total] = await Promise.all([
DBModel.HealthProfile.find(filter)
.sort({ "meta.createtime": -1 })
.skip(skip)
.limit(pageSize)
.lean(),
DBModel.HealthProfile.countDocuments(filter),
]);
return {
success: true,
data: list,
total,
page,
pageSize,
};
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "health_profile_query",
description:
"查询患者健康档案。支持按档案 ID 精确查询,或按用户 ID、患者姓名(模糊)、患者电话筛选,返回分页结果。",
schema: z.object({
profileId: z
.string()
.optional()
.describe("健康档案 ID(_id),提供时精确查询单条,忽略其他筛选条件"),
userId: z.string().optional().describe("所属用户ID(精确匹配)"),
name: z.string().optional().describe("患者姓名(支持中文模糊、全拼、拼音首字母匹配,如 张三/zhangsan/zs)"),
mobile: z.string().optional().describe("患者电话(精确匹配)"),
page: z.number().int().min(1).optional().describe("页码,从 1 开始"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("每页数量(1-50),默认 20"),
}),
}
);
export { healthProfileQueryTool };
@@ -0,0 +1,243 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex, parseObjectId } from "../utils.js";
const ROLE_VALUES = ["attendant", "nurse", "doctor", "admin", "operator", "other"];
const ROLE_DESC =
"Employee role: attendant (陪诊员), nurse (护士), doctor (医生), admin (管理员), operator (运营), other (其他)";
const STATUS_VALUES = ["active", "inactive", "resigned", "suspended"];
const STATUS_DESC = "Employee status: active (在职), inactive (停用), resigned (离职), suspended (暂停)";
// 管理端白名单:只取 schema 已定义字段,避免未来新增/遗留字段被整文档带出
const ADMIN_EMPLOYEE_FIELDS = [
"employeeNo", "userId", "orgId", "role",
"profile", "work", "attendantInfo", "emergencyContact",
"status", "introduction", "remark", "meta",
].join(" ");
// 用户端本人白名单:不返回身份证、手机号、邮箱、紧急联系人、证书编号等敏感信息
const SELF_EMPLOYEE_FIELDS = [
"employeeNo", "role", "orgId", "status",
"profile.name", "profile.sex", "profile.birthday", "profile.avatar",
"work.department", "work.title", "work.entryDate", "work.workYears",
"work.qualification",
"work.healthCertificate.issueDate", "work.healthCertificate.expireDate",
"work.trainings.title", "work.trainings.org", "work.trainings.date",
"attendantInfo.serviceAreas", "attendantInfo.specialties", "attendantInfo.languages",
"attendantInfo.orderCount", "attendantInfo.isOnline",
"introduction", "meta.createtime", "meta.updatetime",
].join(" ");
/**
* 用户端本人视图:显式字段挑选,避免 employee 文档内的敏感字段随查询泄漏
*/
function toSelfEmployee(employee) {
const profile = employee.profile ?? {};
const work = employee.work ?? {};
const info = employee.attendantInfo ?? {};
const healthCertificate = work.healthCertificate ?? {};
return {
_id: employee._id,
employeeNo: employee.employeeNo ?? "",
role: employee.role ?? "",
status: employee.status ?? "",
orgId: employee.orgId ?? null,
profile: {
name: profile.name ?? "",
sex: profile.sex ?? "",
birthday: profile.birthday ?? null,
avatar: profile.avatar ?? "",
},
work: {
department: work.department ?? "",
title: work.title ?? "",
entryDate: work.entryDate ?? null,
workYears: work.workYears ?? 0,
// 证书编号不外泄,只告诉是否已核验
qualificationVerified: Boolean(work.qualification),
healthCertificate: {
issueDate: healthCertificate.issueDate ?? null,
expireDate: healthCertificate.expireDate ?? null,
},
trainings: Array.isArray(work.trainings)
? work.trainings.map((item) => ({
title: item.title ?? "",
org: item.org ?? "",
date: item.date ?? null,
}))
: [],
},
attendantInfo: {
serviceAreas: info.serviceAreas ?? [],
specialties: info.specialties ?? [],
languages: info.languages ?? [],
orderCount: info.orderCount ?? 0,
isOnline: Boolean(info.isOnline),
},
introduction: employee.introduction ?? "",
meta: {
createtime: employee.meta?.createtime ?? null,
updatetime: employee.meta?.updatetime ?? null,
},
};
}
/**
* 员工信息查询内部实现
*
* 仅供 db/user 与 db/admin 下的工具包装使用,不直接暴露给 Agent:
* - 用户端包装只传 userId,强制按当前登录用户隔离,并只输出非敏感字段;
* - 管理端包装传 allowCrossUser,才允许跨用户查询完整员工档案。
*/
function buildEmployeeQueryTool({ userId = null, allowCrossUser = false } = {}) {
const boundUserId = allowCrossUser ? null : parseObjectId(userId);
const shape = {
page: z.number().int().min(1).optional().describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
};
if (allowCrossUser) {
shape.employeeId = z
.string()
.optional()
.describe("Employee ID (_id) for exact lookup; when provided, other filters are ignored");
shape.keyword = z
.string()
.optional()
.describe("Fuzzy keyword matching name, pinyin, employee number or phone (e.g. 张三/zhangsan/zs/E001)");
shape.name = z
.string()
.optional()
.describe("Employee name for fuzzy match (supports Chinese, full pinyin and pinyin initials)");
shape.employeeNo = z.string().optional().describe("Employee number for exact match");
shape.role = z.enum(ROLE_VALUES).optional().describe(ROLE_DESC);
shape.status = z.enum(STATUS_VALUES).optional().describe(STATUS_DESC);
shape.orgId = z.string().optional().describe("Organization ID (_id) for exact match");
shape.userId = z.string().optional().describe("Linked login user ID for exact match");
}
return tool(
async ({ employeeId, keyword, name, employeeNo, role, status, orgId, userId: queryUserId, page = 1, pageSize = 20 }) => {
try {
if (!allowCrossUser && !boundUserId) {
return { success: false, error: "用户未登录,无法查询员工信息" };
}
// 用户端强制归属过滤,所有分支(含按 ID 精确查询)都带 userId
const scope = boundUserId ? { userId: boundUserId } : {};
const projection = allowCrossUser ? ADMIN_EMPLOYEE_FIELDS : SELF_EMPLOYEE_FIELDS;
if (allowCrossUser && employeeId) {
const employeeObjectId = parseObjectId(employeeId);
if (!employeeObjectId) {
return { success: false, error: `Invalid employee ID: ${employeeId}` };
}
const doc = await DBModel.Employee.findOne({ _id: employeeObjectId })
.select(projection)
.lean();
if (!doc) {
return { success: false, error: `No employee found for ID: ${employeeId}` };
}
return { success: true, data: [doc], total: 1, page: 1, pageSize: 1 };
}
const filter = { ...scope };
if (allowCrossUser && queryUserId) {
const ownerId = parseObjectId(queryUserId);
if (!ownerId) {
return { success: false, error: `Invalid user ID: ${queryUserId}` };
}
filter.userId = ownerId;
}
if (allowCrossUser && orgId) {
const organizationId = parseObjectId(orgId);
if (!organizationId) {
return { success: false, error: `Invalid organization ID: ${orgId}` };
}
filter.orgId = organizationId;
}
if (allowCrossUser && employeeNo) {
filter.employeeNo = employeeNo;
}
// 姓名/工号/手机号既可用 keyword 一起搜,也可用 name 单独模糊匹配
const orGroups = [];
if (allowCrossUser && keyword) {
// 转义正则特殊字符,避免查询报错或 ReDoS
const re = { $regex: escapeRegex(keyword), $options: "i" };
orGroups.push({
$or: [
{ "profile.name": re },
{ "profile.pinyin": re },
{ "profile.pinyinFL": re },
{ employeeNo: re },
{ "profile.phone": re },
],
});
}
if (allowCrossUser && name) {
const re = { $regex: escapeRegex(name), $options: "i" };
orGroups.push({
$or: [
{ "profile.name": re },
{ "profile.pinyin": re },
{ "profile.pinyinFL": re },
],
});
}
if (orGroups.length === 1) {
Object.assign(filter, orGroups[0]);
} else if (orGroups.length > 1) {
filter.$and = orGroups;
}
if (allowCrossUser && role) {
filter.role = role;
}
if (allowCrossUser && status) {
filter.status = status;
}
const skip = (page - 1) * pageSize;
const [docs, total] = await Promise.all([
DBModel.Employee.find(filter)
.select(projection)
.sort({ "meta.createtime": -1 })
.skip(skip)
.limit(pageSize)
.lean(),
DBModel.Employee.countDocuments(filter),
]);
return {
success: true,
data: allowCrossUser ? docs : docs.map(toSelfEmployee),
total,
page,
pageSize,
};
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "employee_query",
description: allowCrossUser
? "Query employee records across all users (admin scope). Supports exact employee ID lookup, or filters by keyword (name/pinyin/employee number/phone), name, employee number, role, status, organization ID and linked user ID. Returns paginated full employee profiles, including sensitive fields such as phone and ID number; use only when necessary."
: "Query the current logged-in user's own employee record. The query is automatically scoped to the current user ID and only returns the user's own non-sensitive profile fields (contact details, ID number, emergency contact and certificate numbers are excluded).",
schema: z.object(shape),
}
);
}
/** 内部实现:由 db/user 与 db/admin 包装后暴露给对应 Agent */
export { buildEmployeeQueryTool, toSelfEmployee };
@@ -0,0 +1,137 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../../models/index.js";
import { parseObjectId } from "../utils.js";
const STATUS_VALUES = ["published", "hidden"];
const STATUS_DESC = "Review status: published (已发布,计入评分), hidden (已隐藏,不计入评分)";
// 白名单投影:只返回 schema 已定义字段,避免未来新增字段被整文档带出
const REVIEW_FIELDS = "recordId employeeId userId score content status meta";
/**
* 员工评价查询内部实现
*
* 仅供 db/user 与 db/admin 下的工具包装使用,不直接暴露给 Agent:
* - 用户端包装只传 userId,强制按评价人隔离,只返回当前登录用户自己提交的评价;
* - 管理端包装传 allowCrossUser,才允许跨用户查询。
*/
function buildEmployeeReviewQueryTool({ userId = null, allowCrossUser = false } = {}) {
const boundUserId = allowCrossUser ? null : parseObjectId(userId);
const shape = {
reviewId: z
.string()
.optional()
.describe("Review ID (_id) for exact lookup; when provided, other filters are ignored"),
employeeId: z.string().optional().describe("Reviewed employee ID (_id) for exact match"),
recordId: z.string().optional().describe("Related escort record ID (_id) for exact match"),
score: z.number().int().min(1).max(5).optional().describe("Rating score (1-5)"),
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
page: z.number().int().min(1).optional().describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
};
if (allowCrossUser) {
shape.userId = z.string().optional().describe("Reviewer user ID (_id) for exact match");
}
return tool(
async ({ reviewId, employeeId, recordId, userId: queryUserId, score, status, page = 1, pageSize = 20 }) => {
try {
if (!allowCrossUser && !boundUserId) {
return { success: false, error: "用户未登录,无法查询员工评价" };
}
// 用户端强制评价人归属;按评价 ID 精确查询时同样并入该条件
const scope = boundUserId ? { userId: boundUserId } : {};
if (reviewId) {
const reviewObjectId = parseObjectId(reviewId);
if (!reviewObjectId) {
return { success: false, error: `Invalid review ID: ${reviewId}` };
}
const doc = await DBModel.EmployeeReview.findOne({ _id: reviewObjectId, ...scope })
.select(REVIEW_FIELDS)
.lean();
if (!doc) {
// 用户端不区分「不存在」与「不属于本人」,避免凭 ID 探测他人评价
return {
success: false,
error: allowCrossUser ? `No review found for ID: ${reviewId}` : "未找到对应的员工评价",
};
}
return { success: true, data: [doc], total: 1, page: 1, pageSize: 1 };
}
const filter = { ...scope };
if (allowCrossUser && queryUserId) {
const reviewerId = parseObjectId(queryUserId);
if (!reviewerId) {
return { success: false, error: `Invalid user ID: ${queryUserId}` };
}
filter.userId = reviewerId;
}
if (employeeId) {
const employeeObjectId = parseObjectId(employeeId);
if (!employeeObjectId) {
return { success: false, error: `Invalid employee ID: ${employeeId}` };
}
filter.employeeId = employeeObjectId;
}
if (recordId) {
const recordObjectId = parseObjectId(recordId);
if (!recordObjectId) {
return { success: false, error: `Invalid record ID: ${recordId}` };
}
filter.recordId = recordObjectId;
}
if (score !== undefined) {
filter.score = score;
}
if (status) {
filter.status = status;
}
const skip = (page - 1) * pageSize;
const [list, total] = await Promise.all([
DBModel.EmployeeReview.find(filter)
.select(REVIEW_FIELDS)
.sort({ "meta.createtime": -1 })
.skip(skip)
.limit(pageSize)
.lean(),
DBModel.EmployeeReview.countDocuments(filter),
]);
return {
success: true,
data: list,
total,
page,
pageSize,
};
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "employee_review_query",
description: allowCrossUser
? "Query employee reviews across all users (admin scope). Supports exact review ID lookup, or filters by employee ID, escort record ID, reviewer user ID, score and status. Returns paginated results sorted by creation time in descending order."
: "Query employee reviews submitted by the current logged-in user. The query is automatically scoped to the current user ID and never returns reviews submitted by other users. Supports filtering by employee ID, escort record ID, score and status.",
schema: z.object(shape),
}
);
}
/** 内部实现:由 db/user 与 db/admin 包装后暴露给对应 Agent */
export { buildEmployeeReviewQueryTool };
@@ -0,0 +1,170 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex, parseObjectId } from "../utils.js";
const STATUS_VALUES = ["pending", "confirmed", "in_progress", "completed", "cancelled"];
const STATUS_DESC =
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)";
/**
* 严格解析 YYYY-MM-DD(东八区零点)
* Date 会把 2026-02-30 静默进位成 3 月 2 日,这里回算一次日期,拒绝非法日期
*/
function parseDay(value) {
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const [year, month, day] = value.split("-").map(Number);
const check = new Date(Date.UTC(year, month - 1, day));
if (
check.getUTCFullYear() !== year ||
check.getUTCMonth() !== month - 1 ||
check.getUTCDate() !== day
) {
return null;
}
return new Date(`${value}T00:00:00+08:00`);
}
/**
* 陪诊记录查询内部实现
*
* 仅供 db/user、db/attendant 与 db/admin 下的工具包装使用,不直接暴露给 Agent:
* - 用户端包装只传 userId,强制按当前登录用户隔离;
* - 陪诊员端包装传 boundAttendantId,强制按陪诊员归属隔离;
* - 管理端包装传 allowMobile,才开放跨用户查询与手机号/陪诊员筛选。
*/
function buildEscortRecordQueryTool({ userId = null, allowMobile = false, boundAttendantId = null } = {}) {
const attendantObjectId = boundAttendantId ? parseObjectId(boundAttendantId) : null;
const attendantScope = Boolean(attendantObjectId);
const allowDateRange = allowMobile || attendantScope;
const shape = {
patientName: z.string().optional().describe("Patient name for fuzzy search"),
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
page: z.number().int().min(1).optional().describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
};
if (allowMobile) {
shape.mobile = z.string().optional().describe("Patient mobile phone number for exact match");
shape.attendantId = z
.string()
.optional()
.describe("Attendant (escort staff) user ID (_id) for exact match");
}
if (allowDateRange) {
shape.dateFrom = z
.string()
.optional()
.describe("Schedule date range start, inclusive, format YYYY-MM-DD");
shape.dateTo = z
.string()
.optional()
.describe("Schedule date range end, inclusive, format YYYY-MM-DD");
}
return tool(
async ({ patientName, mobile, attendantId, dateFrom, dateTo, status, page = 1, pageSize = 20 }) => {
try {
if (!userId && !allowMobile && !attendantScope) {
return { success: false, error: "用户未登录,无法查询陪诊记录" };
}
const filter = { deletedAt: null };
if (patientName) {
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
}
if (allowMobile && mobile) {
filter["patient.mobile"] = mobile;
}
// 陪诊员只能看到分配给自己的订单:模型侧不暴露该筛选,条件在服务端强制绑定
if (attendantScope) {
filter["attendant.id"] = attendantObjectId;
}
if (allowMobile && attendantId) {
const queryAttendantId = parseObjectId(attendantId);
if (!queryAttendantId) {
return { success: false, error: `Invalid attendant ID: ${attendantId}` };
}
filter["attendant.id"] = queryAttendantId;
}
// 日期按东八区自然日解释,dateTo 含当天
if (allowDateRange && (dateFrom || dateTo)) {
const range = {};
if (dateFrom) {
const from = parseDay(dateFrom);
if (!from) {
return { success: false, error: `Invalid dateFrom: ${dateFrom}, expected YYYY-MM-DD` };
}
range.$gte = from;
}
if (dateTo) {
const to = parseDay(dateTo);
if (!to) {
return { success: false, error: `Invalid dateTo: ${dateTo}, expected YYYY-MM-DD` };
}
range.$lt = new Date(to.getTime() + 24 * 60 * 60 * 1000);
}
filter["schedule.date"] = range;
}
if (status) {
filter.status = status;
}
// 用户端按订单归属过滤;不能用手机号作为隔离键(手机号可由用户自行修改)
if (userId) {
filter.userId = userId;
}
const skip = (page - 1) * pageSize;
const [records, total] = await Promise.all([
DBModel.EscortRecord.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.lean(),
DBModel.EscortRecord.countDocuments(filter),
]);
return {
success: true,
data: records,
total,
page,
pageSize,
};
} catch (error) {
return {
success: false,
error: error.message,
};
}
},
{
name: "escort_record_query",
description: allowMobile
? "Query all escort records (admin scope). Supports filtering by patient name, mobile phone number, attendant ID, schedule date range (YYYY-MM-DD, inclusive), and appointment status. Returns paginated results sorted by appointment date in descending order."
: attendantScope
? "Query escort records assigned to the current attendant. Supports filtering by patient name, appointment status and schedule date range (YYYY-MM-DD, inclusive). Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current attendant."
: "Query escort records of the current logged-in user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current user.",
schema: z.object(shape),
}
);
}
/** 内部实现:由 db/user 与 db/admin 包装后暴露给对应 Agent */
export { buildEscortRecordQueryTool };
@@ -0,0 +1,117 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex, parseObjectId } from "../utils.js";
/**
* 健康档案查询内部实现
*
* 仅供 db/user 与 db/admin 下的工具包装使用,不直接暴露给 Agent:
* - 用户端包装只传 userId,强制按当前登录用户隔离,且不暴露 userId 筛选;
* - 管理端包装传 allowCrossUser,才允许跨用户查询。
*/
function buildHealthProfileQueryTool({ userId = null, allowCrossUser = false } = {}) {
// 用户端只认调用方绑定的登录用户,管理端不绑定归属
const boundUserId = allowCrossUser ? null : parseObjectId(userId);
const shape = {
profileId: z
.string()
.optional()
.describe("健康档案 ID(_id),提供时精确查询单条,忽略其他筛选条件"),
name: z.string().optional().describe("患者姓名(支持中文模糊、全拼、拼音首字母匹配,如 张三/zhangsan/zs)"),
mobile: z.string().optional().describe("患者电话(精确匹配)"),
page: z.number().int().min(1).optional().describe("页码,从 1 开始"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("每页数量(1-50),默认 20"),
};
if (allowCrossUser) {
shape.userId = z.string().optional().describe("所属用户ID(精确匹配,仅管理端可用)");
}
return tool(
async ({ profileId, userId: queryUserId, name, mobile, page = 1, pageSize = 20 }) => {
try {
// 用户端未登录/身份异常时直接拒绝,绝不回落到跨用户查询
if (!allowCrossUser && !boundUserId) {
return { success: false, error: "用户未登录,无法查询健康档案" };
}
// 用户端把归属条件强制并入所有查询(包括按档案 ID 精确查询)
const scope = boundUserId ? { userId: boundUserId } : {};
// 按档案 _id 精确查询单条
if (profileId) {
const profileObjectId = parseObjectId(profileId);
if (!profileObjectId) {
return { success: false, error: `Invalid profile ID: ${profileId}` };
}
const doc = await DBModel.HealthProfile.findOne({ _id: profileObjectId, ...scope }).lean();
if (!doc) {
// 用户端不区分「不存在」与「不属于本人」,避免凭 ID 探测他人档案
return {
success: false,
error: allowCrossUser ? `未找到 ID 为 ${profileId} 的健康档案` : "未找到对应的健康档案",
};
}
return { success: true, data: [doc], total: 1, page: 1, pageSize: 1 };
}
const filter = { ...scope };
if (allowCrossUser && queryUserId) {
const ownerId = parseObjectId(queryUserId);
if (!ownerId) {
return { success: false, error: `Invalid user ID: ${queryUserId}` };
}
filter.userId = ownerId;
}
if (name) {
// 转义正则特殊字符,避免查询报错或 ReDoS;姓名支持中文、全拼、拼音首字母匹配
const re = { $regex: escapeRegex(name), $options: "i" };
filter.$or = [{ "profile.name": re }, { "profile.pinyin": re }, { "profile.pinyinFL": re }];
}
if (mobile) {
filter["profile.mobile"] = mobile;
}
const skip = (page - 1) * pageSize;
const [list, total] = await Promise.all([
DBModel.HealthProfile.find(filter)
.sort({ "meta.createtime": -1 })
.skip(skip)
.limit(pageSize)
.lean(),
DBModel.HealthProfile.countDocuments(filter),
]);
return {
success: true,
data: list,
total,
page,
pageSize,
};
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "health_profile_query",
description: allowCrossUser
? "查询患者健康档案(管理端)。支持按档案 ID 精确查询,或按用户 ID、患者姓名(模糊)、患者电话筛选,返回分页结果。"
: "查询当前登录用户本人的健康档案。支持按档案 ID 精确查询,或按患者姓名(模糊)、患者电话筛选,返回分页结果。查询自动限定为当前登录用户,不会返回他人档案。",
schema: z.object(shape),
}
);
}
/** 内部实现:由 db/user 与 db/admin 包装后暴露给对应 Agent */
export { buildHealthProfileQueryTool };
@@ -0,0 +1,12 @@
import { buildEmployeeQueryTool } from "../query/employee_query.js";
/**
* 用户端员工查询工具
*
* 只传入当前登录用户的 userId,schema 不暴露 userId 参数;
* 查询强制按 userId 隔离,并只输出本人员工档案的非敏感字段。
*/
const createEmployeeQueryTool = (userInfo) =>
buildEmployeeQueryTool({ userId: userInfo?._id });
export { createEmployeeQueryTool };
@@ -0,0 +1,12 @@
import { buildEmployeeReviewQueryTool } from "../query/employee_review_query.js";
/**
* 用户端员工评价查询工具
*
* 只传入当前登录用户的 userId,schema 不暴露 userId 参数;
* 查询强制按评价人 userId 隔离,只返回本人提交的评价。
*/
const createEmployeeReviewQueryTool = (userInfo) =>
buildEmployeeReviewQueryTool({ userId: userInfo?._id });
export { createEmployeeReviewQueryTool };
@@ -0,0 +1,12 @@
import { buildEscortRecordQueryTool } from "../query/escort_record_query.js";
/**
* 用户端陪诊记录查询工具
*
* 只传入当前登录用户的 userId,不开放管理端的手机号/陪诊员/日期筛选。
* 未登录或身份非法时,工具执行会直接拒绝,不会回落到跨用户查询。
*/
const createEscortRecordQueryTool = (userInfo) =>
buildEscortRecordQueryTool({ userId: userInfo?._id });
export { createEscortRecordQueryTool };
@@ -0,0 +1,12 @@
import { buildHealthProfileQueryTool } from "../query/health_profile_query.js";
/**
* 用户端健康档案查询工具
*
* 只传入当前登录用户的 userId,schema 不暴露 userId 参数;
* 未登录或身份非法时直接拒绝,不会回落到跨用户查询。
*/
const createHealthProfileQueryTool = (userInfo) =>
buildHealthProfileQueryTool({ userId: userInfo?._id });
export { createHealthProfileQueryTool };
+19 -1
View File
@@ -2,6 +2,8 @@
* 数据库工具的公共小工具
*/
import mongoose from "mongoose";
/**
* 转义正则元字符,用于把用户/模型输入当作字面量做模糊匹配
*
@@ -19,4 +21,20 @@ function escapeRegex(input, maxLength = 64) {
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
export { escapeRegex };
/**
* 严格解析 ObjectId
*
* 用固定 24 位十六进制格式校验,而不是 isValid(后者对部分非标准字符串也返回 true)。
* 非法值返回 null,供工具提前返回错误,避免 Mongoose CastError 或把字符串直接带进查询。
*
* @param {*} value 待解析的 ID
* @returns {mongoose.Types.ObjectId|null}
*/
function parseObjectId(value) {
if (value === null || value === undefined) return null;
const raw = typeof value === "string" ? value.trim() : String(value);
if (!/^[0-9a-fA-F]{24}$/.test(raw)) return null;
return new mongoose.Types.ObjectId(raw);
}
export { escapeRegex, parseObjectId };
+23 -7
View File
@@ -9,10 +9,26 @@ export { getCalendarInfoTool } from './calendar/calendar_info.js';
export { getYearHolidaysTool } from './calendar/year_holidays.js';
// 数据库工具
export { createEscortRecordQueryTool, escortRecordQueryTool } from './db/escort_record_query.js';
export { escortRecordSetTool } from './db/escort_record_set.js';
export { healthProfileQueryTool } from './db/health_profile_query.js';
export { healthProfileSetTool } from './db/health_profile_set.js';
export { hospitalInfoListTool } from './db/hospital_info_list.js';
export { hospitalInfoQueryTool } from './db/hospital_info_query.js';
export { hospitalInfoSetTool } from './db/hospital_info_set.js';
// 用户端查询:只允许当前登录用户本人的数据(强制 userId 隔离)
export { createEscortRecordQueryTool } from './db/user/escort_record_query.js';
export { createHealthProfileQueryTool } from './db/user/health_profile_query.js';
export { createEmployeeQueryTool } from './db/user/employee_query.js';
export { createEmployeeReviewQueryTool } from './db/user/employee_review_query.js';
// 陪诊员端:只允许查/改分配给本人的订单与本人档案
export { createAttendantEscortRecordQueryTool } from './db/attendant/escort_record_query.js';
export { buildAttendantEscortRecordSetTool } from './db/attendant/escort_record_set.js';
export { createAttendantEmployeeQueryTool } from './db/attendant/employee_query.js';
// 管理端查询:仅注入 escort-admin,可跨用户查询
export { escortRecordQueryTool } from './db/admin/escort_record_query.js';
export { healthProfileQueryTool } from './db/admin/health_profile_query.js';
export { employeeQueryTool } from './db/admin/employee_query.js';
export { employeeReviewQueryTool } from './db/admin/employee_review_query.js';
// 管理端写入工具与机构(公共服务)工具
export { escortRecordSetTool } from './db/admin/escort_record_set.js';
export { healthProfileSetTool } from './db/admin/health_profile_set.js';
export { hospitalInfoListTool } from './db/admin/hospital_info_list.js';
export { hospitalInfoQueryTool } from './db/admin/hospital_info_query.js';
export { hospitalInfoSetTool } from './db/admin/hospital_info_set.js';
+60
View File
@@ -0,0 +1,60 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import EscortAgent from "../agent/bots/bot-escort/agent.js";
// 一份超过护栏 400 字上限的识别原文:用来确认回显分支不再截断长报告
const IMAGE_TEXT = [
"【图像识别】检验报告|血常规",
"",
"【原文转写】",
"",
"白细胞计数 WBC 6.2 10^9/L 3.5-9.5".repeat(30),
"",
"【说明】本内容为图像文字识别结果,不构成诊断意见。",
].join("\n");
test("图片识别原文完整回显,不经过模型与输出护栏", async () => {
const agent = new EscortAgent();
const chunks = [];
await agent.streamChat(
{ _id: "test-user", profile: {}, location: {} },
[{
type: "format",
ts: "2026-11-01 10:00:00",
content: IMAGE_TEXT,
id: "req_format",
}],
(source, type, content, id) => {
chunks.push({ source, type, content, id });
}
);
// 分片回显,拼接后必须与原文完全一致:长报告不能被字符上限截断
assert.ok(chunks.length > 1);
assert.equal(chunks.map(item => item.content).join(""), IMAGE_TEXT);
assert.deepEqual(new Set(chunks.map(item => item.id)), new Set(["req_format"]));
assert.deepEqual(new Set(chunks.map(item => item.source)), new Set(["main"]));
assert.deepEqual(new Set(chunks.map(item => item.type)), new Set(["ai"]));
// 原文进历史:用户接着问「这项指标什么意思」时模型能看到报告内容
assert.equal(agent.messages.length, 1);
assert.match(agent.messages[0].text, /白细胞计数 WBC 6\.2/);
// 走回显分支时不构建 agent,也就不会产生模型调用
assert.equal(agent.agent, undefined);
});
test("空白识别原文不投递", async () => {
const agent = new EscortAgent();
const chunks = [];
await agent.streamChat(
{ _id: "test-user", profile: {}, location: {} },
[{ type: "format", ts: "2026-11-01 10:00:00", content: " ", id: "req_empty" }],
(source, type, content, id) => {
chunks.push({ source, type, content, id });
}
);
assert.equal(chunks.length, 0);
assert.equal(agent.messages.length, 0);
});
+411
View File
@@ -0,0 +1,411 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DBModel } from "../models/index.js";
import { parseObjectId } from "../agent/infra/tools/db/utils.js";
import { createHealthProfileQueryTool } from "../agent/infra/tools/db/user/health_profile_query.js";
import { healthProfileQueryTool } from "../agent/infra/tools/db/admin/health_profile_query.js";
import { createEmployeeQueryTool } from "../agent/infra/tools/db/user/employee_query.js";
import { employeeQueryTool } from "../agent/infra/tools/db/admin/employee_query.js";
import { toSelfEmployee } from "../agent/infra/tools/db/query/employee_query.js";
import { createEmployeeReviewQueryTool } from "../agent/infra/tools/db/user/employee_review_query.js";
import { employeeReviewQueryTool } from "../agent/infra/tools/db/admin/employee_review_query.js";
import { createEscortRecordQueryTool } from "../agent/infra/tools/db/user/escort_record_query.js";
import { escortRecordQueryTool } from "../agent/infra/tools/db/admin/escort_record_query.js";
import { createAttendantEscortRecordQueryTool } from "../agent/infra/tools/db/attendant/escort_record_query.js";
import { buildAttendantEscortRecordSetTool } from "../agent/infra/tools/db/attendant/escort_record_set.js";
import { resolveEscortAdminRole } from "../utils/permissions.js";
const OWNER_ID = "64b000000000000000000001";
const OTHER_ID = "64b000000000000000000002";
// LangChain 不同版本可能返回对象或 JSON 字符串,统一按对象消费
function parseResult(result) {
return typeof result === "string" ? JSON.parse(result) : result;
}
/**
* 只记录查询条件的 Mongoose 模型桩:验证工具把归属条件真正带进了查询
*/
function createModelStub(docs = []) {
const calls = [];
const chain = {
sort() { return this; },
skip() { return this; },
limit() { return this; },
select() { return this; },
lean() { return Promise.resolve(docs); },
};
return {
calls,
find(filter) {
calls.push({ method: "find", filter });
return chain;
},
countDocuments(filter) {
calls.push({ method: "countDocuments", filter });
return Promise.resolve(docs.length);
},
findOne(filter) {
calls.push({ method: "findOne", filter });
return {
select() { return this; },
lean() { return Promise.resolve(docs[0] ?? null); },
};
},
};
}
function withModel(modelName, stub, fn) {
const previous = DBModel[modelName];
DBModel[modelName] = stub;
return Promise.resolve(fn()).finally(() => {
DBModel[modelName] = previous;
});
}
/**
* 陪诊员改单模型桩:findOne 返回固定记录,findOneAndUpdate 返回合并后的记录
*/
function createRecordModelStub(record) {
const calls = [];
return {
calls,
findOne(filter) {
calls.push({ method: "findOne", filter });
return Promise.resolve(record);
},
findOneAndUpdate(filter, update, options) {
calls.push({ method: "findOneAndUpdate", filter, update, options });
return Promise.resolve(record ? { ...record, ...update.$set } : null);
},
};
}
test("ObjectId 严格解析拒绝非法输入", () => {
assert.equal(parseObjectId(OWNER_ID).toHexString(), OWNER_ID);
assert.equal(parseObjectId(null), null);
assert.equal(parseObjectId(""), null);
assert.equal(parseObjectId("123"), null);
assert.equal(parseObjectId("z".repeat(24)), null);
});
test("用户端健康档案查询强制按登录用户隔离", async () => {
const stub = createModelStub([]);
await withModel("HealthProfile", stub, async () => {
const tool = createHealthProfileQueryTool({ _id: OWNER_ID });
assert.equal("userId" in tool.schema.shape, false);
const byId = parseResult(await tool.invoke({ profileId: OTHER_ID }));
assert.equal(byId.success, false);
assert.equal(stub.calls[0].filter.userId.toHexString(), OWNER_ID);
assert.equal(stub.calls[0].filter._id.toHexString(), OTHER_ID);
const list = parseResult(await tool.invoke({ name: "张三" }));
assert.equal(list.success, true);
for (const call of stub.calls) {
assert.equal(call.filter.userId.toHexString(), OWNER_ID);
}
});
});
test("管理端健康档案查询允许按用户筛选", async () => {
const stub = createModelStub([]);
await withModel("HealthProfile", stub, async () => {
assert.equal("userId" in healthProfileQueryTool.schema.shape, true);
const result = parseResult(await healthProfileQueryTool.invoke({ userId: OTHER_ID }));
assert.equal(result.success, true);
assert.equal(stub.calls[0].filter.userId.toHexString(), OTHER_ID);
});
});
test("用户端员工查询只取本人数据且不返回敏感字段", async () => {
const stub = createModelStub([]);
await withModel("Employee", stub, async () => {
const tool = createEmployeeQueryTool({ _id: OWNER_ID });
assert.equal("userId" in tool.schema.shape, false);
const result = parseResult(await tool.invoke({}));
assert.equal(result.success, true);
for (const call of stub.calls) {
assert.equal(call.filter.userId.toHexString(), OWNER_ID);
}
});
});
test("管理端员工查询允许按用户筛选", async () => {
const stub = createModelStub([]);
await withModel("Employee", stub, async () => {
assert.equal("userId" in employeeQueryTool.schema.shape, true);
const result = parseResult(await employeeQueryTool.invoke({ userId: OTHER_ID }));
assert.equal(result.success, true);
assert.equal(stub.calls[0].filter.userId.toHexString(), OTHER_ID);
});
});
test("用户端本人员工视图剔除联系方式、证件号与证书编号", () => {
const raw = {
employeeNo: "E001",
userId: OWNER_ID,
orgId: OTHER_ID,
role: "attendant",
profile: {
name: "张三",
mobile: "13800000000",
email: "zhangsan@example.com",
idNumber: "110101199001011234",
birthday: new Date("1990-01-01"),
avatar: "https://example.com/a.png",
},
work: {
department: "陪诊部",
title: "陪诊员",
qualification: "CERT-001",
healthCertificate: {
number: "HC-001",
issueDate: new Date("2025-01-01"),
expireDate: new Date("2026-01-01"),
},
trainings: [{ title: "陪诊培训", org: "培训机构", date: new Date("2025-01-01") }],
},
attendantInfo: {
serviceAreas: ["北京"],
specialties: ["陪诊"],
languages: ["普通话"],
rating: 5,
orderCount: 10,
isOnline: true,
},
emergencyContact: { name: "李四", phone: "13900000000", relation: "朋友" },
remark: "内部备注",
introduction: "简介",
meta: { createtime: new Date("2025-01-01"), updatetime: new Date("2025-06-01") },
};
const safe = toSelfEmployee(raw);
assert.equal(safe.profile.name, "张三");
assert.equal(safe.profile.mobile, undefined);
assert.equal(safe.profile.email, undefined);
assert.equal(safe.profile.idNumber, undefined);
assert.equal(safe.work.qualification, undefined);
assert.equal(safe.work.qualificationVerified, true);
assert.equal(safe.work.healthCertificate.number, undefined);
assert.equal(safe.emergencyContact, undefined);
assert.equal(safe.remark, undefined);
assert.equal(safe.attendantInfo.rating, undefined);
assert.equal(safe.attendantInfo.orderCount, 10);
});
test("用户端陪诊记录查询强制按登录用户隔离且不开放管理端筛选", async () => {
const stub = createModelStub([]);
await withModel("EscortRecord", stub, async () => {
const tool = createEscortRecordQueryTool({ _id: OWNER_ID });
assert.equal("mobile" in tool.schema.shape, false);
assert.equal("attendantId" in tool.schema.shape, false);
assert.equal("dateFrom" in tool.schema.shape, false);
const result = parseResult(await tool.invoke({ status: "completed", mobile: "13800000000" }));
assert.equal(result.success, true);
for (const call of stub.calls) {
assert.equal(String(call.filter.userId), OWNER_ID);
assert.equal(call.filter.deletedAt, null);
// 管理端筛选参数即使被传入,也会被 schema 剥离
assert.equal(call.filter["patient.mobile"], undefined);
}
});
});
test("管理端陪诊记录查询开放跨用户与管理端筛选", async () => {
const stub = createModelStub([]);
await withModel("EscortRecord", stub, async () => {
assert.equal("mobile" in escortRecordQueryTool.schema.shape, true);
assert.equal("attendantId" in escortRecordQueryTool.schema.shape, true);
assert.equal("dateFrom" in escortRecordQueryTool.schema.shape, true);
const result = parseResult(await escortRecordQueryTool.invoke({ mobile: "13800000000" }));
assert.equal(result.success, true);
for (const call of stub.calls) {
assert.equal(call.filter.userId, undefined);
assert.equal(call.filter["patient.mobile"], "13800000000");
}
});
});
test("用户端员工评价查询强制按评价人隔离", async () => {
const stub = createModelStub([]);
await withModel("EmployeeReview", stub, async () => {
const tool = createEmployeeReviewQueryTool({ _id: OWNER_ID });
assert.equal("userId" in tool.schema.shape, false);
const result = parseResult(await tool.invoke({ employeeId: OTHER_ID }));
assert.equal(result.success, true);
for (const call of stub.calls) {
assert.equal(call.filter.userId.toHexString(), OWNER_ID);
assert.equal(call.filter.employeeId.toHexString(), OTHER_ID);
}
});
});
test("管理端员工评价查询允许按评价人筛选", async () => {
const stub = createModelStub([]);
await withModel("EmployeeReview", stub, async () => {
assert.equal("userId" in employeeReviewQueryTool.schema.shape, true);
const result = parseResult(await employeeReviewQueryTool.invoke({ userId: OTHER_ID }));
assert.equal(result.success, true);
assert.equal(stub.calls[0].filter.userId.toHexString(), OTHER_ID);
});
});
test("陪诊员端陪诊记录查询强制按本人归属", async () => {
const stub = createModelStub([]);
await withModel("EscortRecord", stub, async () => {
const tool = createAttendantEscortRecordQueryTool({ _id: OWNER_ID });
// 手机号与陪诊员 ID 属管理端筛选,陪诊员侧不暴露
assert.equal("mobile" in tool.schema.shape, false);
assert.equal("attendantId" in tool.schema.shape, false);
// 日期范围用于查自己的排期,保留
assert.equal("dateFrom" in tool.schema.shape, true);
const result = parseResult(
await tool.invoke({ status: "confirmed", attendantId: OTHER_ID, mobile: "13800000000" })
);
assert.equal(result.success, true);
for (const call of stub.calls) {
assert.equal(call.filter["attendant.id"].toHexString(), OWNER_ID);
assert.equal(call.filter.userId, undefined);
// 越权参数即使被传入,也会被 schema 剥离
assert.equal(call.filter["patient.mobile"], undefined);
}
});
});
test("陪诊员端改单拒绝非本人订单", async () => {
const record = {
_id: OTHER_ID,
status: "confirmed",
attendant: { id: OTHER_ID },
notes: {},
};
const stub = createRecordModelStub(record);
await withModel("EscortRecord", stub, async () => {
const tool = buildAttendantEscortRecordSetTool({ attendantId: OWNER_ID });
const result = parseResult(await tool.invoke({ orderId: OTHER_ID, status: "in_progress" }));
assert.equal(result.success, false);
assert.match(result.error, /未分配给你/);
// 越权时不应进入更新阶段
assert.equal(stub.calls.filter((call) => call.method === "findOneAndUpdate").length, 0);
});
});
test("陪诊员端改单只允许服务进度与本人备注", async () => {
const record = {
_id: OWNER_ID,
status: "confirmed",
attendant: { id: OWNER_ID },
notes: {},
};
const stub = createRecordModelStub(record);
await withModel("EscortRecord", stub, async () => {
const tool = buildAttendantEscortRecordSetTool({ attendantId: OWNER_ID });
// 费用字段不暴露、也不允许写入
assert.equal("payment" in tool.schema.shape, false);
const result = parseResult(
await tool.invoke({
orderId: OWNER_ID,
status: "in_progress",
notes: { escortNote: "已到达医院", medicalSummary: "完成检查" },
})
);
assert.equal(result.success, true);
const updateCall = stub.calls.find((call) => call.method === "findOneAndUpdate");
assert.ok(updateCall);
assert.equal(updateCall.filter["attendant.id"].toHexString(), OWNER_ID);
// 并发保护:以读取时的旧状态作为条件
assert.equal(updateCall.filter.status, "confirmed");
assert.equal(updateCall.update.$set.status, "in_progress");
assert.equal(updateCall.update.$set["notes.escortNote"], "已到达医院");
assert.equal(updateCall.update.$set["notes.medicalSummary"], "完成检查");
assert.equal(updateCall.update.$set.payment, undefined);
});
});
test("陪诊员端改单拒绝跳步", async () => {
const record = {
_id: OWNER_ID,
status: "confirmed",
attendant: { id: OWNER_ID },
notes: {},
};
const stub = createRecordModelStub(record);
await withModel("EscortRecord", stub, async () => {
const tool = buildAttendantEscortRecordSetTool({ attendantId: OWNER_ID });
// confirmed 不能直接跳 completed;cancelled 也不在 schema 枚举内,模型无法提交
const skip = parseResult(await tool.invoke({ orderId: OWNER_ID, status: "completed" }));
assert.equal(skip.success, false);
assert.match(skip.error, /Illegal status transition/);
assert.equal(stub.calls.filter((call) => call.method === "findOneAndUpdate").length, 0);
});
});
test("管理端 Agent 角色以员工档案为准", async () => {
const stub = createModelStub([{ role: "attendant" }]);
await withModel("Employee", stub, async () => {
const role = await resolveEscortAdminRole({
_id: OWNER_ID,
app: { "wxapp-escort-admin": { role: ["user"] } },
});
assert.equal(role, "attendant");
const filter = stub.calls[0].filter;
assert.equal(filter.userId.toHexString(), OWNER_ID);
assert.equal(filter.status, "active");
});
});
test("显式管理员不依赖员工档案", async () => {
const stub = createModelStub([{ role: "attendant" }]);
await withModel("Employee", stub, async () => {
const admin = await resolveEscortAdminRole({
_id: OWNER_ID,
app: { "wxapp-escort-admin": { role: ["admin"] } },
});
assert.equal(admin, "admin");
assert.equal(stub.calls.length, 0);
});
});
test("普通管理端账号无员工档案时拒绝", async () => {
const stub = createModelStub([]);
await withModel("Employee", stub, async () => {
const outsider = await resolveEscortAdminRole({
_id: OWNER_ID,
app: { "wxapp-escort-admin": { role: ["user"] } },
});
assert.equal(outsider, null);
});
});
test("历史管理员 role 缺失仍按管理员放行", async () => {
const stub = createModelStub([]);
await withModel("Employee", stub, async () => {
const legacy = await resolveEscortAdminRole({
_id: OWNER_ID,
app: { "wxapp-escort-admin": { wxopenid: "o123" } },
});
assert.equal(legacy, "admin");
});
});
+63
View File
@@ -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);
});
+94
View File
@@ -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 });
}
});
+77 -3
View File
@@ -1,3 +1,24 @@
import mongoose from "mongoose";
import { DBModel } from "../models/index.js";
const ADMIN_APP = "wxapp-escort-admin";
/**
* 管理端 app 条目里的角色数组
*
* 注意:普通账号首次登录管理端小程序时,user 服务会写入 role: ["user"],
* 所以「有 wxapp-escort-admin 条目」不等于陪诊员,陪诊员身份必须以 Employee 记录为准。
*
* @param {Object} user 登录用户
* @returns {string[]}
*/
function appRoles(user) {
const entry = user?.app?.[ADMIN_APP];
if (!entry) return [];
if (Array.isArray(entry.role)) return entry.role;
return entry.role ? [entry.role] : [];
}
/**
* 管理端身份判定:路由中间件、订单 handler、WebSocket 入口共用同一口径。
*
@@ -8,10 +29,10 @@
* 待库中补齐 app.wxapp-escort-admin.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。
*/
function isAdmin(user) {
const entry = user?.app?.["wxapp-escort-admin"];
const entry = user?.app?.[ADMIN_APP];
if (!entry) return false;
const roles = Array.isArray(entry.role) ? entry.role : [entry.role].filter(Boolean);
const roles = appRoles(user);
if (roles.includes("admin")) return true;
if (entry.role === undefined) {
@@ -23,4 +44,57 @@ function isAdmin(user) {
return false;
}
export { isAdmin };
/**
* 陪诊员身份判定:以 Employee 记录为唯一可信来源
*
* @param {ObjectId|string} userId 登录用户 ID
* @returns {Promise<Object|null>} 在职员工档案(只含 role/employeeNo)
*/
async function findActiveEmployee(userId) {
const raw = typeof userId === "string" ? userId.trim() : String(userId ?? "");
if (!/^[0-9a-fA-F]{24}$/.test(raw)) return null;
try {
return await DBModel.Employee.findOne({
userId: new mongoose.Types.ObjectId(raw),
status: "active",
})
.select("role employeeNo")
.lean();
} catch (err) {
// 员工库查询失败不能把管理员一起拒之门外:返回 null 后仍走 app role 判定
console.warn("[permissions] 查询员工档案失败:", err.message);
return null;
}
}
/**
* 管理端 Agent 的使用角色
*
* - admin:显式管理员,或员工档案为管理员;
* - attendant:员工档案为在职陪诊员(app role 一般为 ["user"],不能据此判断);
* - null:无权使用。
*
* 先查员工档案再看 app role:历史账号 role 缺失时 isAdmin 会兼容放行,
* 若该账号同时也是在职陪诊员,必须收敛为陪诊员权限,不能拿到管理员级工具。
*
* @param {Object} user 登录用户
* @returns {Promise<"admin"|"attendant"|null>}
*/
async function resolveEscortAdminRole(user) {
if (!user) return null;
const roles = appRoles(user);
// 显式管理员优先,避免为管理员多查一次员工库
if (roles.includes("admin")) return "admin";
const employee = await findActiveEmployee(user._id);
if (employee?.role === "admin") return "admin";
if (employee?.role === "attendant") return "attendant";
// 兼容历史管理员(role 缺失);普通管理端账号 role 为 ["user"],不会走到这里
if (isAdmin(user)) return "admin";
if (roles.includes("attendant")) return "attendant";
return null;
}
export { isAdmin, resolveEscortAdminRole };
+9 -6
View File
@@ -4,7 +4,7 @@ import { DBModel } from "./models/index.js";
import { chatTask } from "./agent/bots/bot-escort/task.js";
import { adminAgent } from "./agent/bots/bot-escort-admin/agent.js"
import { getUserByToken } from "./utils/user_service.js";
import { isAdmin } from "./utils/permissions.js";
import { resolveEscortAdminRole } from "./utils/permissions.js";
import logger from "./utils/logger.js";
import { createUserLimiter } from "./middleware/ratelimit.js";
import {
@@ -171,7 +171,8 @@ export default class WebSocketServerManager {
return;
}
if (msg.type === 'chat' || msg.type === 'clear') {
// format 是图片识别原文的投递帧:只并入会话上下文并回显原文,不触发模型生成
if (msg.type === 'chat' || msg.type === 'clear' || msg.type === 'format') {
// 客户端断开后不再处理消息
if (ws.readyState !== WebSocket.OPEN) return;
@@ -201,14 +202,16 @@ export default class WebSocketServerManager {
}
if (msg.agent === 'escort-admin') {
// 管理端 agent 含写库/环境变量等高危工具,必须校验管理员角色,防止普通用户越权
if (!isAdmin(userInfo)) {
send('system', 'error', '无管理员权限', msg.id);
// 管理端 agent 按角色收敛工具:管理员可跨用户/写库,陪诊员只能看本人订单。
// 身份以 Employee 记录为准,普通 C 端账号不能借 agent 升级权限。
const role = await resolveEscortAdminRole(userInfo);
if (!role) {
send('system', 'error', '当前账号未绑定在职陪诊员档案,请联系管理员开通', msg.id);
return;
}
await adminAgent.streamChat(userInfo, [msg], (source, type, content, id) => {
send(source, type, content, id);
});
}, role);
} else {
await chatTask.streamChat(userInfo, msg, (source, type, content, id) => {
send(source, type, content, id);