feat(agent): 管理端 agent 支持陪诊员并按角色收敛工具
陪诊员身份以 Employee 在职档案为准,显式管理员优先;管理端小程序首次登录会写入 role:['user'],不能据此判断。管理员保留跨用户查询与医院资料写入,陪诊员只开放本人订单查询/改单(归属校验、状态与字段白名单、并发保护)与本人档案,患者档案与财务操作不可用。
This commit is contained in:
@@ -18,8 +18,11 @@ import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
|
||||
import {
|
||||
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
|
||||
httpGetTool, escortRecordQueryTool, escortRecordSetTool,
|
||||
employeeQueryTool, employeeReviewQueryTool
|
||||
employeeQueryTool, employeeReviewQueryTool,
|
||||
createAttendantEscortRecordQueryTool, buildAttendantEscortRecordSetTool,
|
||||
createAttendantEmployeeQueryTool
|
||||
} from "../../infra/tools/index.js";
|
||||
import { resolveEscortAdminRole } from "../../../utils/permissions.js";
|
||||
|
||||
export default class EscortAdminAgent {
|
||||
constructor(options = {}) {
|
||||
@@ -39,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:按用户取会话,并更新使用顺序
|
||||
@@ -78,21 +88,23 @@ export default class EscortAdminAgent {
|
||||
// 长会话下工具结果会挤占上下文,按完整轮次裁剪,避免上下文溢出与"忘记"前文
|
||||
session.messages = trimHistory(session.messages, this.maxHistoryChars);
|
||||
|
||||
// 用户资料变更后需重建 agent,否则 systemPrompt 仍是旧资料
|
||||
const fingerprint = this._userFingerprint(userInfo);
|
||||
if (session.agent && session.fingerprint !== fingerprint) {
|
||||
// 用户资料或角色变更后需重建 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);
|
||||
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: "admin", maxChars: this.maxOutputChars }),
|
||||
subagent: new OutputGuard({ label: "admin:subagent", maxChars: Infinity }),
|
||||
main: new OutputGuard({ label: guardLabel, maxChars: this.maxOutputChars }),
|
||||
subagent: new OutputGuard({ label: `${guardLabel}:subagent`, maxChars: Infinity }),
|
||||
};
|
||||
const lastAiId = { main: "", subagent: "" };
|
||||
|
||||
@@ -167,13 +179,43 @@ export default class EscortAdminAgent {
|
||||
}
|
||||
|
||||
// 用户资料指纹:姓名/手机号/角色变化时需重建 agent,否则 systemPrompt 仍是旧资料
|
||||
_userFingerprint(userInfo) {
|
||||
_userFingerprint(userInfo, role = "admin") {
|
||||
if (!userInfo) return "anonymous";
|
||||
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();
|
||||
// 受限后端:锁定沙箱根并禁止读取 conf.json/.env/logs 及用户数据目录
|
||||
const backend = createRestrictedBackend({ rootDir, dataDir: config.agent.dataDir });
|
||||
@@ -184,17 +226,23 @@ export default class EscortAdminAgent {
|
||||
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,
|
||||
employeeQueryTool, employeeReviewQueryTool],
|
||||
subagents: [createPatientRecordSubagent(this.flashModel), createHospitalInfoSubagent(this.flashModel, { allowWrite: true })],
|
||||
tools: isAdminRole ? this._adminTools() : this._attendantTools(userInfo),
|
||||
subagents,
|
||||
skills: ["./agent/infra/skills/"],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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,强制按当前登录用户隔离;
|
||||
* - 管理端包装传 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 = {
|
||||
patientName: z.string().optional().describe("Patient name for fuzzy search"),
|
||||
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
|
||||
@@ -52,6 +57,9 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Attendant (escort staff) user ID (_id) for exact match");
|
||||
}
|
||||
|
||||
if (allowDateRange) {
|
||||
shape.dateFrom = z
|
||||
.string()
|
||||
.optional()
|
||||
@@ -65,7 +73,7 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
|
||||
return tool(
|
||||
async ({ patientName, mobile, attendantId, dateFrom, dateTo, status, page = 1, pageSize = 20 }) => {
|
||||
try {
|
||||
if (!userId && !allowMobile) {
|
||||
if (!userId && !allowMobile && !attendantScope) {
|
||||
return { success: false, error: "用户未登录,无法查询陪诊记录" };
|
||||
}
|
||||
|
||||
@@ -79,16 +87,21 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
|
||||
filter["patient.mobile"] = mobile;
|
||||
}
|
||||
|
||||
if (allowMobile && attendantId) {
|
||||
const attendantObjectId = parseObjectId(attendantId);
|
||||
if (!attendantObjectId) {
|
||||
return { success: false, error: `Invalid attendant ID: ${attendantId}` };
|
||||
}
|
||||
// 陪诊员只能看到分配给自己的订单:模型侧不暴露该筛选,条件在服务端强制绑定
|
||||
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 (allowMobile && (dateFrom || dateTo)) {
|
||||
if (allowDateRange && (dateFrom || dateTo)) {
|
||||
const range = {};
|
||||
if (dateFrom) {
|
||||
const from = parseDay(dateFrom);
|
||||
@@ -145,7 +158,9 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
|
||||
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."
|
||||
: "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),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -15,6 +15,11 @@ 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';
|
||||
|
||||
Reference in New Issue
Block a user