Compare commits

...
4 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
13 changed files with 702 additions and 55 deletions
+5
View File
@@ -92,6 +92,11 @@ curl -s http://localhost:9004/health/ai/ocr \
因此服务端会把连续的分列块转成 markdown 表格(列数不足补空列,超出并进最后一列), 因此服务端会把连续的分列块转成 markdown 表格(列数不足补空列,超出并进最后一列),
其余行独立成段保留换行。小程序与 Taro 端都按 markdown 渲染即可。 其余行独立成段保留换行。小程序与 Taro 端都按 markdown 渲染即可。
小程序把识别文本以 WS `format` 帧投递(`{ type: "format", content, id, token, ts }`):
服务端只把原文并入会话上下文,并按分片原样回显给客户端展示,**不再让模型二次改写**。
识别结果通常有几百到上千字,模型改写会按咨询提示词压缩成 1-3 句,还会被输出护栏的
400 字上限截断,长报告必然丢行;原文投递既完整,也省一次生成。
### 错误码 ### 错误码
业务码统一走响应体 `code`(HTTP 恒 200),同时写入 `X-Biz-Code` 响应头: 业务码统一走响应体 `code`(HTTP 恒 200),同时写入 `X-Biz-Code` 响应头:
+65 -17
View File
@@ -18,8 +18,11 @@ import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
import { import {
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool, webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
httpGetTool, escortRecordQueryTool, escortRecordSetTool, httpGetTool, escortRecordQueryTool, escortRecordSetTool,
employeeQueryTool, employeeReviewQueryTool employeeQueryTool, employeeReviewQueryTool,
createAttendantEscortRecordQueryTool, buildAttendantEscortRecordSetTool,
createAttendantEmployeeQueryTool
} from "../../infra/tools/index.js"; } from "../../infra/tools/index.js";
import { resolveEscortAdminRole } from "../../../utils/permissions.js";
export default class EscortAdminAgent { export default class EscortAdminAgent {
constructor(options = {}) { constructor(options = {}) {
@@ -39,11 +42,18 @@ export default class EscortAdminAgent {
} }
// msg: { agent: 'escort-admin', type: 'chat', ts: "2023-08-01 10:00:00", content: "你好" } // 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) { if (!msgs.length) {
return; return;
} }
const effectiveRole = role ?? await resolveEscortAdminRole(userInfo);
if (!effectiveRole) {
callback("main", "ai", "当前账号未绑定在职陪诊员档案,请联系管理员开通。", msgs[0]?.id);
return;
}
const userId = userInfo._id; const userId = userInfo._id;
// LRU:按用户取会话,并更新使用顺序 // LRU:按用户取会话,并更新使用顺序
@@ -78,21 +88,23 @@ export default class EscortAdminAgent {
// 长会话下工具结果会挤占上下文,按完整轮次裁剪,避免上下文溢出与"忘记"前文 // 长会话下工具结果会挤占上下文,按完整轮次裁剪,避免上下文溢出与"忘记"前文
session.messages = trimHistory(session.messages, this.maxHistoryChars); session.messages = trimHistory(session.messages, this.maxHistoryChars);
// 用户资料变更后需重建 agent,否则 systemPrompt 仍是旧资料 // 用户资料或角色变更后需重建 agent,否则 systemPrompt 与工具集仍是旧的
const fingerprint = this._userFingerprint(userInfo); const fingerprint = this._userFingerprint(userInfo, effectiveRole);
if (session.agent && session.fingerprint !== fingerprint) { if (session.agent && (session.fingerprint !== fingerprint || session.role !== effectiveRole)) {
session.agent = null; session.agent = null;
} }
session.fingerprint = fingerprint; session.fingerprint = fingerprint;
session.role = effectiveRole;
const agent = session.agent ?? this._genAgent(userInfo); const agent = session.agent ?? this._genAgent(userInfo, effectiveRole);
session.agent = agent; session.agent = agent;
// 输出护栏:禁用词(身份泄露/空泛客套/越界承诺)拦截; // 输出护栏:禁用词(身份泄露/空泛客套/越界承诺)拦截;
// 长度上限只作用于主回答,子代理输出会单独展示,不受主回答篇幅约束 // 长度上限只作用于主回答,子代理输出会单独展示,不受主回答篇幅约束
const guardLabel = effectiveRole === "attendant" ? "escort-admin:attendant" : "escort-admin:admin";
const guards = { const guards = {
main: new OutputGuard({ label: "admin", maxChars: this.maxOutputChars }), main: new OutputGuard({ label: guardLabel, maxChars: this.maxOutputChars }),
subagent: new OutputGuard({ label: "admin:subagent", maxChars: Infinity }), subagent: new OutputGuard({ label: `${guardLabel}:subagent`, maxChars: Infinity }),
}; };
const lastAiId = { main: "", subagent: "" }; const lastAiId = { main: "", subagent: "" };
@@ -167,13 +179,43 @@ export default class EscortAdminAgent {
} }
// 用户资料指纹:姓名/手机号/角色变化时需重建 agent,否则 systemPrompt 仍是旧资料 // 用户资料指纹:姓名/手机号/角色变化时需重建 agent,否则 systemPrompt 仍是旧资料
_userFingerprint(userInfo) { _userFingerprint(userInfo, role = "admin") {
if (!userInfo) return "anonymous"; if (!userInfo) return "anonymous";
const profile = userInfo.profile ?? {}; const profile = userInfo.profile ?? {};
return JSON.stringify([profile.name, profile.mobile, userInfo.app]); return JSON.stringify([profile.name, profile.mobile, userInfo.app, role]);
} }
_genAgent(userInfo) { // 公共安全工具:天气、路线、日期、节假日与网页检索,不涉及业务数据
_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(); const rootDir = process.cwd();
// 受限后端:锁定沙箱根并禁止读取 conf.json/.env/logs 及用户数据目录 // 受限后端:锁定沙箱根并禁止读取 conf.json/.env/logs 及用户数据目录
const backend = createRestrictedBackend({ rootDir, dataDir: config.agent.dataDir }); const backend = createRestrictedBackend({ rootDir, dataDir: config.agent.dataDir });
@@ -184,17 +226,23 @@ export default class EscortAdminAgent {
temperature: this.temperature 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({ return createDeepAgent({
name: "deep-agent", name: "deep-agent",
model: this.flashModel, model: this.flashModel,
systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo), systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo, role),
backend, backend,
middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用 middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用
tools: [webFetchTool, webSearchTool, httpGetTool, tools: isAdminRole ? this._adminTools() : this._attendantTools(userInfo),
getCalendarInfoTool, getYearHolidaysTool, subagents,
escortRecordQueryTool, escortRecordSetTool,
employeeQueryTool, employeeReviewQueryTool],
subagents: [createPatientRecordSubagent(this.flashModel), createHospitalInfoSubagent(this.flashModel, { allowWrite: true })],
skills: ["./agent/infra/skills/"], skills: ["./agent/infra/skills/"],
}); });
} }
+79 -18
View File
@@ -2,18 +2,45 @@ import services from "../../../resource/services.js";
import agreement from "../../../resource/agreement.js"; import agreement from "../../../resource/agreement.js";
import { formatServices, formatAgreement } from "../../infra/reference.js"; import { formatServices, formatAgreement } from "../../infra/reference.js";
class EscortAdminPrompts { const PLATFORM_PHONE = "18618162956";
static buildSystemPrompt(userInfo) {
// 会话入口(WebSocket)已强制 token 校验并通过管理员角色校验,这里只兜底渲染
let userInfo_str = "(未提供)";
if (userInfo) {
userInfo_str = JSON.stringify({
name: userInfo.profile.name,
mobile: userInfo.profile.mobile,
role: userInfo.app
});
}
/**
* 参考信息:两种角色共用,避免两套提示词里的服务/协议口径漂移
*/
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 {
/**
* @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 ` return `
# 角色 # 角色
你是小暖,暖橙陪诊平台的管理助手,服务对象是平台管理员。 你是小暖,暖橙陪诊平台的管理助手,服务对象是平台管理员。
@@ -49,14 +76,48 @@ class EscortAdminPrompts {
# 支持陪诊员 # 支持陪诊员
- 答工作问题要给可直接执行的信息:集合时间地点、需携带材料、医院科室位置、挂号缴费顺序、注意事项。 - 答工作问题要给可直接执行的信息:集合时间地点、需携带材料、医院科室位置、挂号缴费顺序、注意事项。
- 一次最多 3 条,不罗列无关事项。 - 一次最多 3 条,不罗列无关事项。
${buildReference(userInfo, "管理员")}`;
}
# 参考信息 // 陪诊员:只看本人订单、只推进服务进度、只写服务备注
管理员信息:${userInfo_str} static buildAttendantPrompt(userInfo) {
服务项目: return `
${formatServices(services)} # 角色
服务协议: 你是小暖,暖橙陪诊平台的工作助手,服务对象是平台陪诊员。
${formatAgreement(agreement)} 专业、严谨、简洁:结论先行,只给事实和可执行动作,不寒暄、不安慰、不闲聊。
`;
# 输出要求
- 结论或操作结果先行,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, "陪诊员")}`;
} }
} }
+24
View File
@@ -22,6 +22,10 @@ import {
createEmployeeQueryTool, createEmployeeReviewQueryTool createEmployeeQueryTool, createEmployeeReviewQueryTool
} from "../../infra/tools/index.js"; } from "../../infra/tools/index.js";
// 图片识别原文回显的分片长度:与模型流式输出的单帧量级接近,
// 避免把很长的报告塞进一帧,也让客户端能逐段追加展示
const FORMAT_ECHO_CHUNK = 800;
export default class EscortAgent { export default class EscortAgent {
constructor(options = {}) { constructor(options = {}) {
this.messages = []; this.messages = [];
@@ -59,6 +63,26 @@ export default class EscortAgent {
return; 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 => { msgs.forEach(msg => {
this.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`)); this.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`));
}); });
@@ -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 };
@@ -28,11 +28,16 @@ function parseDay(value) {
/** /**
* 陪诊记录查询内部实现 * 陪诊记录查询内部实现
* *
* 仅供 db/user 与 db/admin 下的工具包装使用,不直接暴露给 Agent: * 仅供 db/user、db/attendant 与 db/admin 下的工具包装使用,不直接暴露给 Agent:
* - 用户端包装只传 userId,强制按当前登录用户隔离; * - 用户端包装只传 userId,强制按当前登录用户隔离;
* - 管理端包装传 allowMobile,才开放跨用户查询与手机号/陪诊员/日期筛选。 * - 陪诊员端包装传 boundAttendantId,强制按陪诊员归属隔离;
* - 管理端包装传 allowMobile,才开放跨用户查询与手机号/陪诊员筛选。
*/ */
function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {}) { function buildEscortRecordQueryTool({ userId = null, allowMobile = false, boundAttendantId = null } = {}) {
const attendantObjectId = boundAttendantId ? parseObjectId(boundAttendantId) : null;
const attendantScope = Boolean(attendantObjectId);
const allowDateRange = allowMobile || attendantScope;
const shape = { const shape = {
patientName: z.string().optional().describe("Patient name for fuzzy search"), patientName: z.string().optional().describe("Patient name for fuzzy search"),
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC), status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
@@ -52,6 +57,9 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
.string() .string()
.optional() .optional()
.describe("Attendant (escort staff) user ID (_id) for exact match"); .describe("Attendant (escort staff) user ID (_id) for exact match");
}
if (allowDateRange) {
shape.dateFrom = z shape.dateFrom = z
.string() .string()
.optional() .optional()
@@ -65,7 +73,7 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
return tool( return tool(
async ({ patientName, mobile, attendantId, dateFrom, dateTo, status, page = 1, pageSize = 20 }) => { async ({ patientName, mobile, attendantId, dateFrom, dateTo, status, page = 1, pageSize = 20 }) => {
try { try {
if (!userId && !allowMobile) { if (!userId && !allowMobile && !attendantScope) {
return { success: false, error: "用户未登录,无法查询陪诊记录" }; return { success: false, error: "用户未登录,无法查询陪诊记录" };
} }
@@ -79,16 +87,21 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
filter["patient.mobile"] = mobile; filter["patient.mobile"] = mobile;
} }
if (allowMobile && attendantId) { // 陪诊员只能看到分配给自己的订单:模型侧不暴露该筛选,条件在服务端强制绑定
const attendantObjectId = parseObjectId(attendantId); if (attendantScope) {
if (!attendantObjectId) {
return { success: false, error: `Invalid attendant ID: ${attendantId}` };
}
filter["attendant.id"] = attendantObjectId; 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 含当天 // 日期按东八区自然日解释,dateTo 含当天
if (allowMobile && (dateFrom || dateTo)) { if (allowDateRange && (dateFrom || dateTo)) {
const range = {}; const range = {};
if (dateFrom) { if (dateFrom) {
const from = parseDay(dateFrom); const from = parseDay(dateFrom);
@@ -145,7 +158,9 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
name: "escort_record_query", name: "escort_record_query",
description: allowMobile 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." ? "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."
: "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.", : 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), schema: z.object(shape),
} }
); );
+5
View File
@@ -15,6 +15,11 @@ export { createHealthProfileQueryTool } from './db/user/health_profile_query.js'
export { createEmployeeQueryTool } from './db/user/employee_query.js'; export { createEmployeeQueryTool } from './db/user/employee_query.js';
export { createEmployeeReviewQueryTool } from './db/user/employee_review_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,可跨用户查询 // 管理端查询:仅注入 escort-admin,可跨用户查询
export { escortRecordQueryTool } from './db/admin/escort_record_query.js'; export { escortRecordQueryTool } from './db/admin/escort_record_query.js';
export { healthProfileQueryTool } from './db/admin/health_profile_query.js'; export { healthProfileQueryTool } from './db/admin/health_profile_query.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);
});
+168
View File
@@ -12,6 +12,9 @@ import { createEmployeeReviewQueryTool } from "../agent/infra/tools/db/user/empl
import { employeeReviewQueryTool } from "../agent/infra/tools/db/admin/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 { createEscortRecordQueryTool } from "../agent/infra/tools/db/user/escort_record_query.js";
import { escortRecordQueryTool } from "../agent/infra/tools/db/admin/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 OWNER_ID = "64b000000000000000000001";
const OTHER_ID = "64b000000000000000000002"; const OTHER_ID = "64b000000000000000000002";
@@ -62,6 +65,24 @@ function withModel(modelName, stub, fn) {
}); });
} }
/**
* 陪诊员改单模型桩: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 严格解析拒绝非法输入", () => { test("ObjectId 严格解析拒绝非法输入", () => {
assert.equal(parseObjectId(OWNER_ID).toHexString(), OWNER_ID); assert.equal(parseObjectId(OWNER_ID).toHexString(), OWNER_ID);
assert.equal(parseObjectId(null), null); assert.equal(parseObjectId(null), null);
@@ -241,3 +262,150 @@ test("管理端员工评价查询允许按评价人筛选", async () => {
assert.equal(stub.calls[0].filter.userId.toHexString(), OTHER_ID); 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");
});
});
+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 入口共用同一口径。 * 管理端身份判定:路由中间件、订单 handler、WebSocket 入口共用同一口径。
* *
@@ -8,10 +29,10 @@
* 待库中补齐 app.wxapp-escort-admin.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。 * 待库中补齐 app.wxapp-escort-admin.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。
*/ */
function isAdmin(user) { function isAdmin(user) {
const entry = user?.app?.["wxapp-escort-admin"]; const entry = user?.app?.[ADMIN_APP];
if (!entry) return false; 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 (roles.includes("admin")) return true;
if (entry.role === undefined) { if (entry.role === undefined) {
@@ -23,4 +44,57 @@ function isAdmin(user) {
return false; 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 { chatTask } from "./agent/bots/bot-escort/task.js";
import { adminAgent } from "./agent/bots/bot-escort-admin/agent.js" import { adminAgent } from "./agent/bots/bot-escort-admin/agent.js"
import { getUserByToken } from "./utils/user_service.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 logger from "./utils/logger.js";
import { createUserLimiter } from "./middleware/ratelimit.js"; import { createUserLimiter } from "./middleware/ratelimit.js";
import { import {
@@ -171,7 +171,8 @@ export default class WebSocketServerManager {
return; 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; if (ws.readyState !== WebSocket.OPEN) return;
@@ -201,14 +202,16 @@ export default class WebSocketServerManager {
} }
if (msg.agent === 'escort-admin') { if (msg.agent === 'escort-admin') {
// 管理端 agent 含写库/环境变量等高危工具,必须校验管理员角色,防止普通用户越权 // 管理端 agent 按角色收敛工具:管理员可跨用户/写库,陪诊员只能看本人订单。
if (!isAdmin(userInfo)) { // 身份以 Employee 记录为准,普通 C 端账号不能借 agent 升级权限。
send('system', 'error', '无管理员权限', msg.id); const role = await resolveEscortAdminRole(userInfo);
if (!role) {
send('system', 'error', '当前账号未绑定在职陪诊员档案,请联系管理员开通', msg.id);
return; return;
} }
await adminAgent.streamChat(userInfo, [msg], (source, type, content, id) => { await adminAgent.streamChat(userInfo, [msg], (source, type, content, id) => {
send(source, type, content, id); send(source, type, content, id);
}); }, role);
} else { } else {
await chatTask.streamChat(userInfo, msg, (source, type, content, id) => { await chatTask.streamChat(userInfo, msg, (source, type, content, id) => {
send(source, type, content, id); send(source, type, content, id);