868 lines
36 KiB
TypeScript
868 lines
36 KiB
TypeScript
import { validationError } from "../../../core/errors.js";
|
||
import { z } from "zod";
|
||
import type { KyInstance } from "ky";
|
||
import * as api from "../api.js";
|
||
import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js";
|
||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
|
||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs/export.js";
|
||
import {
|
||
alignApprovalRunsWithHoseFlow,
|
||
createHoseOpenClient,
|
||
getHoseOpenFlow
|
||
} from "../../hose/index.js";
|
||
import {
|
||
type ApprovalRun
|
||
} from "../types.js";
|
||
import type {
|
||
CapabilityContext
|
||
} from "./helpers.js";
|
||
import * as helpers from "./helpers.js";
|
||
|
||
const {
|
||
summarizeApprovalRun,
|
||
summarizeApprovalRuns,
|
||
parseFieldPaths,
|
||
pickRunFields,
|
||
summarizeApprovalRunDetail,
|
||
summarizeApprovalRunResult,
|
||
summarizeApprovalRunDocument,
|
||
extractCitedRules,
|
||
summarizeRunBridge,
|
||
pickApprovalRunCandidate,
|
||
resolveApprovalRunForUrl,
|
||
resolveSealBaseUrl,
|
||
normalizeUrl,
|
||
stringFromUnknown,
|
||
pickApprovalRuns,
|
||
withApprovalRunFilters,
|
||
resolveManualApprovalStatus,
|
||
prepareApprovalRuns,
|
||
approvalRunAliases,
|
||
extractHumanResult,
|
||
matchesRunLookup,
|
||
localDateKey,
|
||
resolveRuleVersion,
|
||
summarizeRuleVersion
|
||
} = helpers;
|
||
|
||
export const approvalRunsCapabilities = [
|
||
{
|
||
name: "sealApprovalRunsSearch",
|
||
description: "查询 Seal 审批/审核运行记录总表,并整理合思单据到 Langfuse trace/session 的桥接字段",
|
||
parameters: z.object({
|
||
offset: z.number().int().nonnegative().optional(),
|
||
limit: z.number().int().positive().max(100).optional(),
|
||
fromTimestamp: z.string().optional(),
|
||
toTimestamp: z.string().optional(),
|
||
startDate: z.string().optional().describe("运行记录创建开始时间戳(毫秒),对应前端 startDate"),
|
||
endDate: z.string().optional().describe("运行记录创建结束时间戳(毫秒),对应前端 endDate"),
|
||
status: z.string().optional(),
|
||
taskMode: z.string().optional(),
|
||
manualApprovalStatus: z.union([z.string(), z.array(z.string())]).optional().describe("人工审核状态,如 TERMINATED 对应已驳回"),
|
||
sourceDocumentSN: z.string().optional(),
|
||
sourceDocumentId: z.string().optional(),
|
||
humanResult: z.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),
|
||
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配"),
|
||
includeBridge: z.boolean().optional().describe("是否返回完整 bridge 数组;默认 false,避免长输出")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
offset?: number;
|
||
limit?: number;
|
||
fromTimestamp?: string;
|
||
toTimestamp?: string;
|
||
startDate?: string;
|
||
endDate?: string;
|
||
status?: string;
|
||
taskMode?: string;
|
||
manualApprovalStatus?: string | string[];
|
||
sourceDocumentSN?: string;
|
||
sourceDocumentId?: string;
|
||
humanResult?: string;
|
||
query?: string;
|
||
includeBridge?: boolean;
|
||
}
|
||
) => {
|
||
const query = params.query?.trim();
|
||
const data = await api.listApprovalRuns(client, withApprovalRunFilters({
|
||
...params,
|
||
startDate: normalizeTimestamp(params.startDate, false),
|
||
endDate: normalizeTimestamp(params.endDate, true),
|
||
search: query
|
||
}));
|
||
const records = await prepareApprovalRuns(client, data.records, {
|
||
humanResult: params.humanResult
|
||
});
|
||
|
||
return {
|
||
...data,
|
||
records: records.map(summarizeApprovalRun),
|
||
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunsSummary",
|
||
description: "按本地日期/时区汇总 Seal 审批运行记录,返回状态、模式统计和精简记录,避免长 JSON 输出",
|
||
parameters: z.object({
|
||
date: z.string().optional().describe("本地日期,格式 YYYY-MM-DD;默认使用 timezone 下的今天"),
|
||
timezone: z.string().optional().describe("IANA 时区,默认 Asia/Shanghai"),
|
||
offset: z.number().int().nonnegative().optional(),
|
||
limit: z.number().int().positive().max(100).optional(),
|
||
startDate: z.string().optional().describe("运行记录创建开始时间戳(毫秒)或日期/ISO 字符串,对应前端 startDate"),
|
||
endDate: z.string().optional().describe("运行记录创建结束时间戳(毫秒)或日期/ISO 字符串,对应前端 endDate"),
|
||
status: z.string().optional(),
|
||
taskMode: z.string().optional(),
|
||
manualApprovalStatus: z.union([z.string(), z.array(z.string())]).optional().describe("人工审核状态,如 TERMINATED 对应已驳回"),
|
||
sourceDocumentSN: z.string().optional(),
|
||
sourceDocumentId: z.string().optional(),
|
||
humanResult: z.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),
|
||
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
date?: string;
|
||
timezone?: string;
|
||
offset?: number;
|
||
limit?: number;
|
||
startDate?: string;
|
||
endDate?: string;
|
||
status?: string;
|
||
taskMode?: string;
|
||
manualApprovalStatus?: string | string[];
|
||
sourceDocumentSN?: string;
|
||
sourceDocumentId?: string;
|
||
humanResult?: string;
|
||
query?: string;
|
||
}
|
||
) => {
|
||
const timezone = params.timezone ?? "Asia/Shanghai";
|
||
const date = params.date ?? localDateKey(Date.now(), timezone) ?? "";
|
||
const data = await api.listApprovalRuns(client, {
|
||
offset: params.offset,
|
||
limit: params.limit ?? 100,
|
||
startDate: normalizeTimestamp(params.startDate, false),
|
||
endDate: normalizeTimestamp(params.endDate, true),
|
||
status: params.status,
|
||
taskMode: params.taskMode,
|
||
manualApprovalStatus: resolveManualApprovalStatus(
|
||
params.manualApprovalStatus,
|
||
params.humanResult
|
||
),
|
||
sourceDocumentSN: params.sourceDocumentSN,
|
||
sourceDocumentId: params.sourceDocumentId
|
||
});
|
||
const records = (
|
||
await prepareApprovalRuns(client, data.records, {
|
||
query: params.query,
|
||
humanResult: params.humanResult
|
||
})
|
||
).filter((record) => localDateKey(record.createdAt, timezone) === date);
|
||
|
||
return summarizeApprovalRuns(records, {
|
||
date,
|
||
timezone,
|
||
fetched: data.records.length,
|
||
total: data.total
|
||
});
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunsExport",
|
||
description: "将企业的审批审核记录导出为高保真 Excel 报表(包含单据模板、AI决策、人工审核结论、驳回原因及企业规则列细分结果)",
|
||
parameters: z.object({
|
||
startDate: z.string().optional().describe("起始时间,支持 YYYY-MM-DD 或毫秒时间戳"),
|
||
endDate: z.string().optional().describe("截止时间,支持 YYYY-MM-DD 或毫秒时间戳"),
|
||
limit: z.number().int().positive().optional().describe("最大拉取记录条数"),
|
||
status: z.string().optional().describe("单据状态过滤,如 completed, processing, failed"),
|
||
manualApprovalStatus: z.union([z.string(), z.array(z.string())]).optional().describe("人工审核状态过滤,如 APPROVED, TERMINATED, PROCESSING"),
|
||
includeCompletedOnly: z.boolean().optional().describe("是否仅导出已完成单据"),
|
||
outputFile: z.string().optional().describe("输出 Excel 文件的自定义绝对或相对路径"),
|
||
toDownloads: z.boolean().optional().describe("是否直接保存到用户的系统下载目录")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
startDate?: string;
|
||
endDate?: string;
|
||
limit?: number;
|
||
status?: string;
|
||
manualApprovalStatus?: string | string[];
|
||
includeCompletedOnly?: boolean;
|
||
outputFile?: string;
|
||
toDownloads?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => exportApprovalRunsToExcel(client, context.corp, params)
|
||
},
|
||
{
|
||
name: "sealApprovalRunGet",
|
||
description: "获取 Seal 单条审批/审核运行记录详情;可用 fields 只取 metadata、document.fields、result.summary 等局部字段",
|
||
parameters: z.object({
|
||
recordId: z.string().describe("Seal approval run record ID"),
|
||
fields: z.union([z.string(), z.array(z.string())]).optional().describe("逗号分隔或数组形式的字段路径,如 metadata、document.fields、result.summary"),
|
||
summary: z.boolean().optional().describe("返回单据摘要、AI 结果、人工结果和版本号")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { recordId: string; fields?: string | string[]; summary?: boolean }
|
||
) => {
|
||
const record = await api.getApprovalRun(client, params.recordId);
|
||
if (params.summary) return summarizeApprovalRunDetail(record);
|
||
const full = {
|
||
...record,
|
||
aliases: approvalRunAliases(record),
|
||
humanResult: extractHumanResult(record)
|
||
};
|
||
const fields = parseFieldPaths(params.fields);
|
||
return fields.length > 0 ? pickRunFields(full, fields) : full;
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunFlowGet",
|
||
description: "获取合思原生审批流流转时间线、待办节点、员工意见、驳回原因及版本变更指标,并对齐 AI 运行记录与人工行为",
|
||
parameters: z.object({
|
||
target: z.string().optional().describe("合思单号 (sourceDocumentSN) 或 Seal 运行记录 ID (recordId)"),
|
||
recordId: z.string().optional().describe("Seal 运行记录 ID"),
|
||
sourceDocumentSN: z.string().optional().describe("合思单号 (sourceDocumentSN)")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { target?: string; recordId?: string; sourceDocumentSN?: string },
|
||
context: CapabilityContext
|
||
) => {
|
||
const corp = context.corp;
|
||
if (corp.source.type !== "hose") {
|
||
throw new Error(
|
||
`企业「${corp.name || corp.id}」非合思(hose)租户(来源类型: ${corp.source.type}),暂不支持合思原生审批流分析。`
|
||
);
|
||
}
|
||
|
||
const input = (params.target || params.sourceDocumentSN || params.recordId)?.trim();
|
||
if (!input) {
|
||
throw validationError("必须提供 target、recordId 或 sourceDocumentSN 参数。");
|
||
}
|
||
|
||
let sn = input;
|
||
let targetRecord: ApprovalRun | undefined;
|
||
|
||
try {
|
||
targetRecord = await api.getApprovalRun(client, input);
|
||
if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) {
|
||
sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!;
|
||
}
|
||
} catch {
|
||
// Continue as SN
|
||
}
|
||
|
||
let runs: ApprovalRun[] = [];
|
||
try {
|
||
const runsData = await api.listApprovalRuns(client, {
|
||
search: sn,
|
||
sourceDocumentSN: sn,
|
||
limit: 100
|
||
});
|
||
runs = (runsData.records || []).filter(
|
||
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input
|
||
);
|
||
} catch {
|
||
// ignore
|
||
}
|
||
|
||
if (runs.length === 0 && targetRecord) {
|
||
runs = [targetRecord];
|
||
}
|
||
|
||
const flowId = targetRecord?.sourceDocumentId || runs[0]?.sourceDocumentId || sn;
|
||
const hoseClient = await createHoseOpenClient(corp);
|
||
const flow = await getHoseOpenFlow(hoseClient, flowId);
|
||
if (!flow) {
|
||
console.error(`⚠️ 单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`);
|
||
const fallbackAlignments = alignApprovalRunsWithHoseFlow(runs, undefined);
|
||
const fallbackRuns = runs.map((run) => {
|
||
const align = fallbackAlignments.get(run.id);
|
||
return {
|
||
recordId: run.id,
|
||
createdAt: run.createdAt,
|
||
createdAtFormatted: run.createdAt
|
||
? formatBeijingIso(Number(run.createdAt))
|
||
: undefined,
|
||
taskMode: run.taskMode,
|
||
status: run.status,
|
||
aiDecision: align?.aiDecision || "-",
|
||
aiAction: align?.aiAction || "-",
|
||
eHumanAction: "单据已删除",
|
||
eHumanComment: "合思系统中未找到该单据流转记录(已在合思端删除或作废)",
|
||
auditDrift: false,
|
||
auditDriftReason: undefined,
|
||
operator: undefined
|
||
};
|
||
});
|
||
|
||
return {
|
||
sourceDocumentSN: sn,
|
||
corpId: corp.id,
|
||
corpName: corp.name,
|
||
sourceSystem: corp.source.type,
|
||
found: false,
|
||
deleted: true,
|
||
message: `单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`,
|
||
flow: undefined,
|
||
runsCount: runs.length,
|
||
runs: fallbackRuns,
|
||
auditDrift: false
|
||
};
|
||
}
|
||
|
||
const alignments = alignApprovalRunsWithHoseFlow(runs, flow);
|
||
const alignedRuns = runs.map((run) => {
|
||
const align = alignments.get(run.id);
|
||
return {
|
||
recordId: run.id,
|
||
createdAt: run.createdAt,
|
||
createdAtFormatted: run.createdAt
|
||
? formatBeijingIso(Number(run.createdAt))
|
||
: undefined,
|
||
taskMode: run.taskMode,
|
||
status: run.status,
|
||
aiDecision: align?.aiDecision || "-",
|
||
aiAction: align?.aiAction || "-",
|
||
eHumanAction: align?.eHumanAction || "-",
|
||
eHumanComment: align?.eHumanComment || "-",
|
||
auditDrift: align?.auditDrift ?? false,
|
||
auditDriftReason: align?.auditDriftReason,
|
||
operator: align?.operator
|
||
};
|
||
});
|
||
|
||
const hasAuditDrift = alignedRuns.some((r) => r.auditDrift);
|
||
|
||
return {
|
||
sourceDocumentSN: sn,
|
||
corpId: corp.id,
|
||
corpName: corp.name,
|
||
sourceSystem: corp.source.type,
|
||
flow: {
|
||
backlogId: flow.backlogId,
|
||
flowId: flow.flowId,
|
||
billCode: flow.billCode,
|
||
title: flow.title,
|
||
state: flow.state,
|
||
rawState: flow.rawState,
|
||
currentNode: flow.currentNode,
|
||
specification: flow.specification,
|
||
submitter: flow.submitter,
|
||
owner: flow.owner,
|
||
metrics: flow.metrics,
|
||
rejections: flow.rejections,
|
||
staffOpinions: flow.staffOpinions,
|
||
timelineCount: flow.history.length,
|
||
pendingCount: flow.pending.length,
|
||
timeline: flow.history,
|
||
pending: flow.pending
|
||
},
|
||
runsCount: runs.length,
|
||
runs: alignedRuns,
|
||
auditDrift: hasAuditDrift
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunCitedRulesGet",
|
||
description: "从审批运行结果中抽取 AI 引用或命中的规则及应用分析",
|
||
parameters: z.object({
|
||
recordId: z.string().describe("Seal approval run record ID")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { recordId: string },
|
||
context: CapabilityContext
|
||
) => {
|
||
const record = await api.getApprovalRun(client, params.recordId);
|
||
return extractCitedRules(record, context.corp);
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunDocumentSummaryGet",
|
||
description: "返回单据关键字段、附件摘要、AI/人工结果,避免拉取完整原始单据",
|
||
parameters: z.object({
|
||
recordId: z.string().describe("Seal approval run record ID")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { recordId: string }
|
||
) => {
|
||
const record = await api.getApprovalRun(client, params.recordId);
|
||
return summarizeApprovalRunDocument(record);
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunAttachmentsGet",
|
||
description: "从审批运行记录中抽取附件、发票附件和字段位置,不返回完整单据正文和规则结果",
|
||
parameters: z.object({
|
||
recordId: z.string().describe("Seal approval run record ID"),
|
||
summary: z.boolean().optional().describe("只返回附件列表摘要")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { recordId: string; summary?: boolean }
|
||
) => {
|
||
const record = await api.getApprovalRun(client, params.recordId);
|
||
return extractApprovalRunAttachments(record, { summary: params.summary });
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunResultGet",
|
||
description: "返回审批运行结果摘要;summary=true 时只返回 decision、summary、风险点数量、命中规则数量、traceId 等",
|
||
parameters: z.object({
|
||
recordId: z.string().describe("Seal approval run record ID"),
|
||
summary: z.boolean().optional()
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { recordId: string; summary?: boolean }
|
||
) => {
|
||
const record = await api.getApprovalRun(client, params.recordId);
|
||
if (params.summary) return summarizeApprovalRunResult(record);
|
||
return {
|
||
recordId: record.id,
|
||
result: record.result
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunUrlGet",
|
||
description: "获取审批单的 Web 链接(支持 seal-result 审核页与 hose-document 原单据页,支持 --auto-login 免密直达)",
|
||
parameters: z.object({
|
||
recordId: z.string().optional().describe("Seal approval run record ID"),
|
||
sourceDocumentSN: z.string().optional().describe("合思/易快报单号"),
|
||
sourceDocumentId: z.string().optional().describe("合思/易快报源单据 ID"),
|
||
type: z.string().optional().describe("链接类型:'seal-result' (Seal AI 审核页,默认) 或 'hose-document' (合思原单据页)"),
|
||
autoLogin: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接"),
|
||
sso: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接 (兼容别名)"),
|
||
hoseSso: z.boolean().optional().describe("通过合思 OEM 换票生成直达该单据审核详情的免密直达链接 (兼容别名)"),
|
||
expiresIn: z.number().optional().describe("免密凭证有效秒数,默认 7200 (2小时)")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
recordId?: string;
|
||
sourceDocumentSN?: string;
|
||
sourceDocumentId?: string;
|
||
type?: string;
|
||
autoLogin?: boolean;
|
||
sso?: boolean;
|
||
hoseSso?: boolean;
|
||
expiresIn?: number;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
const hasDocumentLookup = Boolean(params.recordId || params.sourceDocumentSN || params.sourceDocumentId);
|
||
if (!hasDocumentLookup) {
|
||
throw new Error("recordId, sourceDocumentSN, or sourceDocumentId is required to generate approval run link");
|
||
}
|
||
const record = await resolveApprovalRunForUrl(client, params);
|
||
const source = context.corp.source;
|
||
let hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
|
||
const flowId = record?.sourceDocumentId;
|
||
if (hoseDocumentUrl) {
|
||
if (flowId && hoseDocumentUrl.includes("backlogId=") && !hoseDocumentUrl.includes("#/")) {
|
||
hoseDocumentUrl = `${hoseDocumentUrl}#/backlogDetail/false/${encodeURIComponent(flowId)}`;
|
||
}
|
||
} else if (source.type === "hose" && flowId) {
|
||
const hoseDomain = normalizeUrl(source.domain);
|
||
const encodedFlowId = encodeURIComponent(flowId);
|
||
const corpId = encodeURIComponent(source.corpId);
|
||
hoseDocumentUrl = `${hoseDomain}/web/thirdparty.html?ekbCorpId=${corpId}&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=${encodedFlowId}&backlogId=#/backlogDetail/false/${encodedFlowId}`;
|
||
}
|
||
|
||
const sealBaseUrl = resolveSealBaseUrl(context.corp);
|
||
const sealResultUrl = `${sealBaseUrl}/approval-result/${record.id}`;
|
||
|
||
const rawType = (params.type ?? "seal-result").toLowerCase().replace(/_/g, "-");
|
||
const isHoseDoc = rawType === "hose-document" || rawType === "source-document" || rawType === "hose";
|
||
const linkType = isHoseDoc ? "hose_document" : "seal_result";
|
||
|
||
const useAutoLogin = Boolean(params.autoLogin ?? params.hoseSso ?? params.sso);
|
||
const expiresIn = params.expiresIn ?? 7200;
|
||
|
||
let ssoUrl: string | undefined;
|
||
let sealSsoUrl: string | undefined;
|
||
let hoseSsoUrl: string | undefined;
|
||
let identity: { name?: string; staffId?: string; isAdmin?: boolean; providerUserId?: string } | undefined;
|
||
let warning: string | undefined;
|
||
|
||
if (useAutoLogin) {
|
||
if (source.type !== "hose") {
|
||
throw new Error(
|
||
`Auto-login direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use auth link' for authorized access.`
|
||
);
|
||
}
|
||
|
||
const hoseAccess = await ensureHoseCloseApiToken(context.corp);
|
||
const provisionalToken = hoseAccess.token;
|
||
if (!provisionalToken) {
|
||
throw new Error("Failed to obtain Hose provisional authentication token");
|
||
}
|
||
|
||
const targetPath = `/approval-result/${record.id}`;
|
||
sealSsoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
|
||
|
||
if (record?.sourceDocumentId) {
|
||
const hoseDomain = normalizeUrl(source.domain);
|
||
const flowId = encodeURIComponent(record.sourceDocumentId);
|
||
const corpId = encodeURIComponent(source.corpId);
|
||
const token = encodeURIComponent(provisionalToken);
|
||
hoseSsoUrl = `${hoseDomain}/web/thirdparty.html?accessToken=${token}&ekbCorpId=${corpId}&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=${flowId}&backlogId=#/backlogDetail/false/${flowId}`;
|
||
}
|
||
|
||
ssoUrl = isHoseDoc ? (hoseSsoUrl ?? sealSsoUrl) : sealSsoUrl;
|
||
|
||
try {
|
||
const me = await api.getMe(client);
|
||
identity = {
|
||
name: me.user.name,
|
||
staffId: source.staffId,
|
||
isAdmin: me.user.isAdmin,
|
||
providerUserId: me.user.providerUserId
|
||
};
|
||
} catch {
|
||
identity = {
|
||
staffId: source.staffId
|
||
};
|
||
}
|
||
|
||
const userName = identity.name ?? "企业成员";
|
||
const roleLabel = identity.isAdmin ? " (管理员)" : "";
|
||
const targetSystem = isHoseDoc ? "合思 (Hose)" : "Seal AI";
|
||
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 ${targetSystem} 拥有对应操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
|
||
|
||
console.error(
|
||
`⚠️ 安全警示 (免密直达链接):\n` +
|
||
`• 身份主体:${userName}${roleLabel}\n` +
|
||
`• 目标系统:${targetSystem}\n` +
|
||
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留会话\n` +
|
||
`• 安全边界:仅限内部排查,严禁在外部公开分享!`
|
||
);
|
||
}
|
||
|
||
const activeUrl = isHoseDoc
|
||
? (useAutoLogin ? (hoseSsoUrl ?? hoseDocumentUrl) : hoseDocumentUrl)
|
||
: (useAutoLogin ? sealSsoUrl : sealResultUrl);
|
||
const activeMode = useAutoLogin ? "auto_login" : "direct";
|
||
|
||
return {
|
||
url: activeUrl,
|
||
type: linkType,
|
||
mode: activeMode,
|
||
sealResultUrl,
|
||
hoseDocumentUrl,
|
||
sealSsoUrl,
|
||
hoseSsoUrl,
|
||
// Legacy compatibility fields
|
||
documentUrl: hoseDocumentUrl,
|
||
ssoUrl,
|
||
expiresIn: useAutoLogin ? expiresIn : undefined,
|
||
identity,
|
||
warning,
|
||
hoseDomain: source.type === "hose" ? normalizeUrl(source.domain) : undefined,
|
||
recordId: record.id,
|
||
sourceDocumentSN: record.sourceDocumentSN,
|
||
sourceDocumentId: record.sourceDocumentId,
|
||
sourceSystem: record.sourceSystem,
|
||
missing: {
|
||
hoseDocumentUrl: !hoseDocumentUrl
|
||
? `该审批运行未回写 hosecloudViewUrl 且缺少 sourceDocumentId,无法生成合思原单据直达链接;请到合思主系统以单据编号 ${record.sourceDocumentSN ?? record.sourceDocumentId ?? record.id} 检索原件,或检查该企业的 hosecloud 集成回写配置。`
|
||
: undefined
|
||
}
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunPick",
|
||
description: "按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",
|
||
parameters: z.object({
|
||
query: z.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),
|
||
sn: z.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),
|
||
batchId: z.string().optional().describe("模拟批次 ID"),
|
||
latest: z.boolean().optional().describe("只返回最新一条匹配记录"),
|
||
fields: z.union([z.string(), z.array(z.string())]).optional().describe("限制返回字段"),
|
||
limit: z.number().int().positive().max(100).optional(),
|
||
maxScan: z.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),
|
||
includeBridge: z.boolean().optional()
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
query?: string;
|
||
sn?: string;
|
||
batchId?: string;
|
||
latest?: boolean;
|
||
fields?: string | string[];
|
||
limit?: number;
|
||
maxScan?: number;
|
||
includeBridge?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
const query = params.sn ?? params.query;
|
||
if (!query) throw new Error("query or sn is required");
|
||
const picked = await pickApprovalRuns(client, {
|
||
query,
|
||
sn: params.sn,
|
||
batchId: params.batchId,
|
||
latest: params.latest,
|
||
limit: params.latest ? 1 : params.limit ?? 20,
|
||
maxScan: params.maxScan ?? 1000
|
||
});
|
||
const records = await Promise.all(
|
||
picked.records.map((record) => api.getApprovalRun(client, record.id))
|
||
);
|
||
const fields = parseFieldPaths(params.fields);
|
||
const projected = records.map((record) => pickApprovalRunCandidate(record, fields));
|
||
const nextRuleVersionNumber = records.find((record) => record.ruleSetVersionNumber !== undefined)?.ruleSetVersionNumber;
|
||
const nextRuleVersionSelector = nextRuleVersionNumber === undefined ? "latest" : String(nextRuleVersionNumber);
|
||
|
||
return {
|
||
query,
|
||
sourceDocumentSN: params.sn,
|
||
simulationBatchId: params.batchId,
|
||
latest: params.latest ?? false,
|
||
total: picked.total,
|
||
scanned: picked.scanned,
|
||
matched: projected.length,
|
||
records: projected,
|
||
next: {
|
||
getSummary: `seal-use approval-runs get <recordId> --summary --corp ${context.corp.id}`,
|
||
getRuleVersion: `seal-use rules version ${nextRuleVersionSelector} --corp ${context.corp.id}`,
|
||
searchRuleVersion: `seal-use rules search <keyword> --version ${nextRuleVersionSelector} --corp ${context.corp.id}`,
|
||
getVersionContext: `seal-use context --ruleVersion ${nextRuleVersionSelector} --corp ${context.corp.id}`
|
||
},
|
||
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunDiagnose",
|
||
description: "一键客诉/单据诊断:按单号 SN 或 recordId 一次聚合单据摘要、AI 判定结果、引用规则、当时的规则版本快照与 Langfuse trace 指针,替代串行调用 pick/get/cited-rules/rules version",
|
||
parameters: z.object({
|
||
sn: z.string().optional().describe("合思/易快报单号 (sourceDocumentSN);与 recordId 二选一"),
|
||
recordId: z.string().optional().describe("Seal approval run record ID;与 sn 二选一"),
|
||
full: z.boolean().optional().describe("为 true 时附带完整 AI result 原文(默认只带摘要)")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { sn?: string; recordId?: string; full?: boolean },
|
||
context: CapabilityContext
|
||
) => {
|
||
if (!params.sn && !params.recordId) {
|
||
throw new Error("sn or recordId is required for approval run diagnosis");
|
||
}
|
||
let detail: ApprovalRun;
|
||
if (params.recordId) {
|
||
detail = await api.getApprovalRun(client, params.recordId);
|
||
} else {
|
||
const { records } = await api.listApprovalRuns(client, {
|
||
limit: 50,
|
||
search: params.sn,
|
||
sourceDocumentSN: params.sn
|
||
});
|
||
const matched = records.find((record) =>
|
||
matchesRunLookup(record, { sourceDocumentSN: params.sn })
|
||
);
|
||
if (!matched) {
|
||
throw new Error(`未找到单号为 ${params.sn} 的审批运行记录;可先用 seal-use approval-runs pick --sn ${params.sn} 确认单号`);
|
||
}
|
||
detail = await api.getApprovalRun(client, matched.id);
|
||
}
|
||
|
||
const documentSummary = summarizeApprovalRunDocument(detail);
|
||
const resultSummary = summarizeApprovalRunResult(detail);
|
||
const citedRules = extractCitedRules(detail, context.corp);
|
||
|
||
let ruleVersion: {
|
||
version: ReturnType<typeof summarizeRuleVersion>;
|
||
citedSnapshots: Array<Record<string, unknown>>;
|
||
} | undefined;
|
||
if (detail.ruleSetVersionNumber !== undefined) {
|
||
try {
|
||
const version = await resolveRuleVersion(client, { versionNumber: detail.ruleSetVersionNumber });
|
||
const citedCodes = new Set(
|
||
(Array.isArray(citedRules?.rules) ? citedRules.rules : [])
|
||
.map((item) => item && typeof item === "object" ? item as Record<string, unknown> : undefined)
|
||
.map((item) => item && helpers.parseRuleCodeNumber(item.ruleCode ?? item.code ?? item.runtimeRuleId))
|
||
.filter((code): code is number => code !== undefined)
|
||
);
|
||
const citedSnapshots = (version.rules ?? [])
|
||
.filter((snapshotRule) => {
|
||
const object = snapshotRule as Record<string, unknown>;
|
||
const codeNum = helpers.parseRuleCodeNumber(object.code ?? object.ruleCode ?? object.runtimeRuleId);
|
||
return codeNum !== undefined && citedCodes.has(codeNum);
|
||
})
|
||
.map((snapshotRule) => {
|
||
const object = snapshotRule as Record<string, unknown>;
|
||
return {
|
||
code: object.code ?? object.ruleCode,
|
||
description: object.description,
|
||
scope: object.scope,
|
||
strictness: object.strictness
|
||
};
|
||
});
|
||
ruleVersion = { version: summarizeRuleVersion(version), citedSnapshots };
|
||
} catch {
|
||
// 版本快照拉取失败不阻断诊断主流程
|
||
}
|
||
}
|
||
|
||
return {
|
||
recordId: detail.id,
|
||
sourceDocumentSN: detail.sourceDocumentSN,
|
||
sourceDocumentId: detail.sourceDocumentId,
|
||
status: detail.status,
|
||
ruleSetVersionNumber: detail.ruleSetVersionNumber,
|
||
documentSummary,
|
||
result: params.full === true ? detail.result : resultSummary,
|
||
citedRules,
|
||
ruleVersion,
|
||
bridge: summarizeRunBridge([detail]),
|
||
next: {
|
||
url: `seal-use approval-runs url ${detail.id} --corp ${context.corp.id}`,
|
||
hoseDocument: `seal-use approval-runs url ${detail.id} --type hose-document --corp ${context.corp.id}`,
|
||
replay: `seal-use approval-runs replay ${detail.id} --dry-run --corp ${context.corp.id}`
|
||
}
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunLangfuseBridgeGet",
|
||
description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",
|
||
parameters: z.object({
|
||
recordId: z.string().optional(),
|
||
sourceDocumentSN: z.string().optional(),
|
||
sourceDocumentId: z.string().optional(),
|
||
simulationBatchId: z.string().optional(),
|
||
limit: z.number().int().positive().max(100).optional()
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
recordId?: string;
|
||
sourceDocumentSN?: string;
|
||
sourceDocumentId?: string;
|
||
simulationBatchId?: string;
|
||
limit?: number;
|
||
}
|
||
) => {
|
||
const records = params.simulationBatchId
|
||
? await api.listSimulationBatchRecords(client, params.simulationBatchId)
|
||
: (await api.listApprovalRuns(client, {
|
||
limit: params.limit ?? 50,
|
||
search: params.sourceDocumentSN ?? params.sourceDocumentId,
|
||
sourceDocumentSN: params.sourceDocumentSN,
|
||
sourceDocumentId: params.sourceDocumentId
|
||
})).records;
|
||
|
||
const filtered = records.filter((record) =>
|
||
matchesRunLookup(record, {
|
||
recordId: params.recordId,
|
||
sourceDocumentSN: params.sourceDocumentSN,
|
||
sourceDocumentId: params.sourceDocumentId
|
||
})
|
||
);
|
||
|
||
return {
|
||
count: filtered.length,
|
||
records: filtered.map(summarizeApprovalRun),
|
||
bridge: summarizeRunBridge(filtered)
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunsStats",
|
||
description: "统计审核记录状态分布、来源系统分布及按单号/ID去重统计",
|
||
parameters: z.object({
|
||
since: z.string().optional().describe("时间范围,如 3months, 7days, 24hours"),
|
||
dedupeBy: z.enum(["sourceDocumentSN", "sourceDocumentId", "id"]).default("sourceDocumentSN").describe("去重字段"),
|
||
status: z.string().optional(),
|
||
sourceSystem: z.string().optional(),
|
||
taskMode: z.string().optional()
|
||
}),
|
||
handler: async (client: KyInstance, params: { since?: string; dedupeBy?: "sourceDocumentSN" | "sourceDocumentId" | "id"; status?: string; sourceSystem?: string; taskMode?: string }) => {
|
||
const runs = await api.listApprovalRuns(client, {
|
||
limit: 1000,
|
||
status: params.status,
|
||
sourceSystem: params.sourceSystem,
|
||
taskMode: params.taskMode
|
||
});
|
||
const dedupeBy = params.dedupeBy ?? "sourceDocumentSN";
|
||
const records = runs.records;
|
||
const byStatus: Record<string, number> = {};
|
||
const bySourceSystem: Record<string, number> = {};
|
||
const uniqueKeys = new Set<string>();
|
||
|
||
for (const r of records) {
|
||
const s = r.status ?? "unknown";
|
||
byStatus[s] = (byStatus[s] ?? 0) + 1;
|
||
const src = r.sourceSystem ?? "unknown";
|
||
bySourceSystem[src] = (bySourceSystem[src] ?? 0) + 1;
|
||
const key = (r as any)[dedupeBy];
|
||
if (key) uniqueKeys.add(String(key));
|
||
}
|
||
|
||
const duplicateRuns = Math.max(0, records.length - uniqueKeys.size);
|
||
|
||
return {
|
||
total: records.length,
|
||
dedupeBy,
|
||
unique: uniqueKeys.size,
|
||
duplicateRuns,
|
||
dedupeNote:
|
||
duplicateRuns > 0
|
||
? `存在 ${duplicateRuns} 笔重复运行记录 (同一单据重跑或修改重推)`
|
||
: "全部单据唯一,无重复记录",
|
||
byStatus,
|
||
bySourceSystem
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealApprovalRunsCount",
|
||
description: "统计符合条件的审核记录总数",
|
||
parameters: z.object({
|
||
status: z.string().optional(),
|
||
sourceSystem: z.string().optional(),
|
||
taskMode: z.string().optional(),
|
||
search: z.string().optional(),
|
||
startDate: z.string().optional().describe("起始时间戳(毫秒)或日期字符串"),
|
||
endDate: z.string().optional().describe("结束时间戳(毫秒)或日期字符串")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
status?: string;
|
||
sourceSystem?: string;
|
||
taskMode?: string;
|
||
search?: string;
|
||
startDate?: string;
|
||
endDate?: string;
|
||
}
|
||
) => {
|
||
const runs = await api.listApprovalRuns(client, {
|
||
limit: 1,
|
||
status: params.status,
|
||
sourceSystem: params.sourceSystem,
|
||
taskMode: params.taskMode,
|
||
search: params.search,
|
||
startDate: normalizeTimestamp(params.startDate, false),
|
||
endDate: normalizeTimestamp(params.endDate, true)
|
||
});
|
||
return {
|
||
total: runs.total ?? runs.records.length
|
||
};
|
||
}
|
||
}
|
||
];
|